mirror of
https://github.com/Ichinga-Samuel/aiomql.git
synced 2026-08-17 22:08:06 +00:00
v4.0.17 no-backtest
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
# _core
|
||||
|
||||
`aiomql.core._core` — Low-level interface that dynamically binds MetaTrader 5 constants, functions, and types.
|
||||
|
||||
## Overview
|
||||
|
||||
This module provides the metaclass machinery that introspects the `MetaTrader5` Python package and copies its
|
||||
attributes into the class hierarchy. It is **not** intended for direct use — the higher-level
|
||||
[`MetaTrader`](meta_trader.md) class should be used instead.
|
||||
|
||||
## Module-Level Attributes
|
||||
|
||||
| Name | Type | Description |
|
||||
|------|------|-------------|
|
||||
| `constants` | `tuple[str, ...]` | Names of MT5 integer constants to bind (e.g. `TIMEFRAME_M1`) |
|
||||
| `core_mt5_functions` | `tuple[str, ...]` | Names of MT5 API functions to bind (prefixed with `_` on `MetaCore`) |
|
||||
| `types` | `tuple[str, ...]` | Names of MT5 named-tuple types to bind |
|
||||
|
||||
## Classes
|
||||
|
||||
### `MetaBase`
|
||||
|
||||
> Metaclass that dynamically binds MetaTrader 5 attributes to classes.
|
||||
|
||||
On class creation, `MetaBase.__new__` introspects the `MetaTrader5` module and copies constants,
|
||||
API functions (prefixed with `_`), and named-tuple types into the new class's namespace.
|
||||
|
||||
### `MetaCore`
|
||||
|
||||
> Base class exposing all MetaTrader 5 constants, functions, and types.
|
||||
|
||||
Created by `MetaBase`, this class holds every MT5 constant, every API function, and every
|
||||
named-tuple type as class attributes.
|
||||
|
||||
**Key attribute groups:**
|
||||
|
||||
| Group | Examples |
|
||||
|-------|---------|
|
||||
| Timeframes | `TIMEFRAME_M1`, `TIMEFRAME_H1`, `TIMEFRAME_D1`, … |
|
||||
| Order types | `ORDER_TYPE_BUY`, `ORDER_TYPE_SELL`, `ORDER_FILLING_FOK`, … |
|
||||
| Trade actions | `TRADE_ACTION_DEAL`, `TRADE_ACTION_PENDING`, … |
|
||||
| Return codes | `TRADE_RETCODE_DONE`, `TRADE_RETCODE_ERROR`, … |
|
||||
| API functions | `_initialize`, `_login`, `_order_send`, `_positions_get`, … |
|
||||
| Named-tuple types | `TradePosition`, `TradeOrder`, `TradeDeal`, `SymbolInfo`, … |
|
||||
| Config | `config` — the global `Config` instance |
|
||||
@@ -1,55 +0,0 @@
|
||||
# BackTestAccount
|
||||
|
||||
## Table of Contents
|
||||
- [BackTestAccount](#back_test_account.back_test_account)
|
||||
- [get_dict](#back_test_account.back_test_account.get_dict)
|
||||
- [asdict](#back_test_account.asdict)
|
||||
- [set_attrs](#back_test_account.set_attrs)
|
||||
|
||||
|
||||
### BackTestAccount
|
||||
<a id="back_test_account.back_test_account"></a>
|
||||
```python
|
||||
@dataclass
|
||||
class BackTestAccount:
|
||||
```
|
||||
The `BackTestAccount` class provides data structure for managing account data specifically for backtesting purposes.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------|-----------------------------------------------------------|
|
||||
| `balance` | `float` | The account balance for the backtest |
|
||||
| `equity` | `float` | The equity value of the account during the backtest |
|
||||
| `currency` | `str` | The currency type used in the backtesting account |
|
||||
| `leverage` | `float` | Leverage ratio applied to the backtest account |
|
||||
| `spread` | `int` | Spread value applied to simulated trades |
|
||||
|
||||
|
||||
<a id="back_test_account.get_dict"></a>
|
||||
### get_dict
|
||||
```python
|
||||
def get_dict(exclude: set = None, include: set = None) -> dict
|
||||
```
|
||||
Returns a dictionary representation of the account data. The `exclude` and `include` parameters allow filtering of data keys.
|
||||
|
||||
#### Arguments:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|----------------------------------------------------------|
|
||||
| `exclude` | `set` | A set of attribute names to exclude from the dictionary. |
|
||||
| `include` | `set` | A set of attribute names to include in the dictionary. |
|
||||
|
||||
|
||||
<a id="back_test_account.asdict"></a>
|
||||
### asdict
|
||||
```python
|
||||
def asdict() -> dict
|
||||
```
|
||||
Returns a dictionary of all attributes in the account data without filtering.
|
||||
|
||||
|
||||
### set_attrs
|
||||
<a id="back_test_account.set_attrs"></a>
|
||||
```python
|
||||
def set_attrs(**kwargs)
|
||||
```
|
||||
Sets multiple attributes at once by passing key-value pairs as keyword arguments.
|
||||
@@ -1,104 +0,0 @@
|
||||
# BackTestController
|
||||
|
||||
## Table of Contents
|
||||
- [BackTestController](#backtest_controller.back_test_controller)
|
||||
- [backtest_engine](#backtest_controller.backtest_engine)
|
||||
- [add_tasks](#backtest_controller.add_tasks)
|
||||
- [set_parties](#backtest_controller.set_parties)
|
||||
- [parties](#backtest_controller.parties)
|
||||
- [control](#backtest_controller.control)
|
||||
- [stop_backtesting](#backtest_controller.stop_backtesting)
|
||||
- [wait](#backtest_controller.wait)
|
||||
- [abort](#backtest_controller.abort)
|
||||
|
||||
|
||||
<a id="backtest_controller.back_test_controller"></a>
|
||||
### BackTestController
|
||||
```python
|
||||
class BackTestController
|
||||
```
|
||||
The controller for the backtesting engine.
|
||||
It also acts as a synchronizer for running multiple strategies (tasks) using a threading.Barrier primitive.
|
||||
It handles the updating of open positions and close them when necessary.
|
||||
It handles the iterator for the backtesting engine and handles it movement in time by moving it to the next time step.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|-------------|----------------------|----------------------------------------------|
|
||||
| `_instance` | `BackTestController` | The instance of the controller |
|
||||
| `config` | `Config` | The configuration for the backtesting engine |
|
||||
| `tasks` | `list[Task]` | The tasks that are being run |
|
||||
| `barrier` | `Barrier` | The barrier for synchronizing the tasks |
|
||||
|
||||
|
||||
<a id="backtest_controller.backtest_engine"></a>
|
||||
#### backtest_engine
|
||||
```python
|
||||
@property
|
||||
def backtest_engine()
|
||||
```
|
||||
Returns the backtest engine
|
||||
|
||||
|
||||
<a id="backtest_controller.add_tasks"></a>
|
||||
#### add_tasks
|
||||
```python
|
||||
def add_tasks(*tasks: Task)
|
||||
```
|
||||
Adds a task to the tasks list
|
||||
|
||||
|
||||
<a id="backtest_controller.set_parties"></a>
|
||||
#### set_parties
|
||||
```python
|
||||
def set_parties(*, parties: int)
|
||||
```
|
||||
Sets the number of parties for the barrier. The barrier will wait for the number of parties to reach the barrier.
|
||||
This has to be done here as it can be impossible to know the eventual number of parties to set the barrier to during initialization.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|---------------------------------------------|
|
||||
| `parties` | `int` | The number of parties to set the barrier to |
|
||||
|
||||
|
||||
<a id="backtest_controller.parties"></a>
|
||||
#### parties
|
||||
```python
|
||||
@property
|
||||
def parties()
|
||||
```
|
||||
Returns the number of parties for the barrier
|
||||
|
||||
|
||||
<a id="backtest_controller.control"></a>
|
||||
#### control
|
||||
```python
|
||||
async def control()
|
||||
```
|
||||
The backtest controller. It controls the backtesting engine and the tasks that are being run.
|
||||
It acts as a synchronizer for the tasks and the backtesting engine.
|
||||
|
||||
|
||||
<a id="backtest_controller.stop_backtesting"></a>
|
||||
#### stop_backtesting
|
||||
```python
|
||||
def stop_backtesting()
|
||||
```
|
||||
Stop the backtester, and shutdown the executor
|
||||
|
||||
|
||||
<a id="backtest_controller.wait"></a>
|
||||
#### wait
|
||||
```python
|
||||
def wait()
|
||||
```
|
||||
Called by individual tasks to indicate completion of their cycle
|
||||
|
||||
|
||||
<a id="backtest_controller.abort"></a>
|
||||
#### abort
|
||||
```python
|
||||
def abort()
|
||||
```
|
||||
Aborts the barrier
|
||||
@@ -1,957 +0,0 @@
|
||||
# BackTestEngine
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [BackTestEngine](#backtest_engine.back_test_engine)
|
||||
- [\__init\__](#backtest_engine.__init__)
|
||||
- [setup_test_range](#backtest_engine.setup_test_range)
|
||||
- [setup_data](#backtest_engine.setup_data)
|
||||
- [next](#backtest_engine.next)
|
||||
- [data](#backtest_engine.data)
|
||||
- [reset](#backtest_engine.reset)
|
||||
- [go_to](#backtest_engine.go_to)
|
||||
- [fast_forward](#backtest_engine.fast_forward)
|
||||
- [tracker](#backtest_engine.tracker)
|
||||
- [save_result_to_json](#backtest_engine.save_result_to_json)
|
||||
- [close_all_open](#backtest_engine.close_all_open)
|
||||
- [wrap_up](#backtest_engine.wrap_up)
|
||||
- [preload_ticks](#backtest_engine.preload_ticks)
|
||||
- [get_price_tick](#backtest_engine.get_price_tick)
|
||||
- [check_order](#backtest_engine.check_order)
|
||||
- [check_account](#backtest_engine.check_account)
|
||||
- [check_position](#backtest_engine.check_position)
|
||||
- [close_position_manually](#backtest_engine.close_position_manually)
|
||||
- [close_position](#backtest_engine.close_position)
|
||||
- [modify_stops](#backtest_engine.modify_stops)
|
||||
- [update_account](#backtest_engine.update_account)
|
||||
- [deposit](#backtest_engine.deposit)
|
||||
- [withdraw](#backtest_engine.withdraw)
|
||||
- [setup_account](#backtest_engine.setup_account)
|
||||
- [setup_account_sync](#backtest_engine.setup_account_sync)
|
||||
- [prices](#backtest_engine.prices)
|
||||
- [ticks](#backtest_engine.ticks)
|
||||
- [rates](#backtest_engine.rates)
|
||||
- [symbols](#backtest_engine.symbols)
|
||||
- [order_send](#backtest_engine.order_send)
|
||||
- [order_check](#backtest_engine.order_check)
|
||||
- [get_terminal_info](#backtest_engine.get_terminal_info)
|
||||
- [get_version](#backtest_engine.get_version)
|
||||
- [get_symbols_total](#backtest_engine.get_symbols_total)
|
||||
- [get_symbols](#backtest_engine.get_symbols)
|
||||
- [get_account_info](#backtest_engine.get_account_info)
|
||||
- [get_symbol_info_tick](#backtest_engine.get_symbol_info_tick)
|
||||
- [get_symbol_info](#backtest_engine.get_symbol_info)
|
||||
- [get_rates_from](#backtest_engine.get_rates_from)
|
||||
- [get_rates_from_pos](#backtest_engine.get_rates_from_pos)
|
||||
- [get_rates_range](#backtest_engine.get_rates_range)
|
||||
- [get_ticks_from](#backtest_engine.get_ticks_from)
|
||||
- [get_ticks_range](#backtest_engine.get_ticks_range)
|
||||
- [order_calc_margin](#backtest_engine.order_calc_margin)
|
||||
- [order_calc_profit](#backtest_engine.order_calc_profit)
|
||||
- [get_orders_total](#backtest_engine.get_orders_total)
|
||||
- [get_orders](#backtest_engine.get_orders)
|
||||
- [get_positions_total](#backtest_engine.get_positions_total)
|
||||
- [get_positions](#backtest_engine.get_positions)
|
||||
- [get_history_orders_total](#backtest_engine.get_history_orders_total)
|
||||
- [get_history_orders](#backtest_engine.get_history_orders)
|
||||
- [get_history_deals_total](#backtest_engine.get_history_deals_total)
|
||||
- [get_history_deals](#backtest_engine.get_history_deals)
|
||||
|
||||
|
||||
<a id="backtest_engine.back_test_engine"></a>
|
||||
#### BackTestEngine
|
||||
```python
|
||||
class BackTestEngine
|
||||
```
|
||||
The BackTestEngine class is used to simulate trading strategies on historical data that is either preloaded or provided
|
||||
at runtime during the test.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|--------------------------------|----------------|-----------------------------------------------------------------------------------------------------|
|
||||
| `_data` | `BackTestData` | The data used for backtesting. This is the data that is saved to disk when the backtest is stopped. |
|
||||
| `mt5` | `MetaTrader` | The MetaTrader instance for the backtest engine. |
|
||||
| `config` | `Config` | The global configuration instance. |
|
||||
| `name` | `str` | The name of the backtest. |
|
||||
| `stop_testing` | `bool` | Whether to stop the backtest. |
|
||||
| `use_terminal` | `bool` | Whether to use the terminal for backtesting. |
|
||||
| `close_open_positions_on_exit` | `bool` | Whether to close all open positions when the backtest is stopped. |
|
||||
| `stop_time` | `int` | The time to stop the backtest. |
|
||||
| `preload` | `bool` | Whether to preload the ticks for the backtest. |
|
||||
| `preloaded_ticks` | `dict` | A dictionary of preloaded ticks for the backtest. |
|
||||
| `account_lock` | `RLock` | A reentrant lock for the account data. |
|
||||
| `account_info` | `dict` | A dictionary of account information for the backtest. |
|
||||
|
||||
|
||||
<a id="backtest_engine.__init__"></a>
|
||||
#### \__init\__
|
||||
```python
|
||||
def __init__(*,
|
||||
data: BackTestData = None,
|
||||
speed: int = 60,
|
||||
start: float | datetime = 0,
|
||||
end: float | datetime = 0,
|
||||
restart: bool = True,
|
||||
use_terminal: bool = None,
|
||||
name: str = "",
|
||||
stop_time: float | datetime = None,
|
||||
close_open_positions_on_exit: bool = True,
|
||||
preload=True,
|
||||
assign_to_config: bool = True,
|
||||
account_info: dict = None)
|
||||
```
|
||||
The BackTestEngine class is used to simulate trading strategies on historical data.
|
||||
It can accept already saved data or create new data for backtesting on the fly. Ideally only one instance of
|
||||
this class should be created per session. By default it is automatically assigned to the global config instance
|
||||
during instantiation, replacing any existing backtest engine instance. But this is a configurable behaviour.
|
||||
The start and end time can still be specified even when test data is provided. In that case it will be used
|
||||
to set the range of the backtest.
|
||||
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|--------------------------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `data` | `BackTestData` | The data to use for backtesting. Defaults to None. |
|
||||
| `speed` | `int` | The speed of the backtest. Defaults to 60 seconds. |
|
||||
| `start` | `float \| datetime` | The start time of the backtest. Defaults to 0. If a float is passed, it is assumed to be a timestamp. |
|
||||
| `end` | `float \| datetime` | The end time of the backtest. Defaults to 0. If a float is passed, it is assumed to be a timestamp. |
|
||||
| `restart` | `bool` | Whether to restart the backtest from the beginning. Defaults to True. This is useful when resuming a backtest using a saved BackTestData instance. |
|
||||
| `use_terminal` | `bool` | Whether to use the terminal for backtesting. Defaults to None. If None, it uses the global config setting. If use terminal is true, the backtest engine will use the terminal to get price data, compute margins, profit and check order viability. If false, it will use the data provided in the BackTestData instance and default algorithm for the calculations |
|
||||
| `name` | `str` | The name of the backtest. Defaults to "". If not provided, it is generated from the start and end times. |
|
||||
| `stop_time` | `float \| datetime` | The time to stop the backtest. Defaults to None. If a float is passed, it is assumed to be a timestamp. If not given it is assumed to be the end of the backtest range. |
|
||||
| `close_open_positions_on_exit` | `bool` | Whether to close all open positions when the backtest is stopped. Defaults to True. |
|
||||
| `preload` | `bool` | Whether to preload the ticks for the backtest. Defaults to True. |
|
||||
| `assign_to_config` | `bool` | Whether to assign the backtest engine to the global config instance. Defaults to True. |
|
||||
| `account_info` | `dict` | A dictionary of account information to use for the backtest. Defaults to None. Use this to set the account information for the backtest. |
|
||||
|
||||
|
||||
<a id="backtest_engine.setup_test_range"></a>
|
||||
#### setup_test_range
|
||||
```python
|
||||
def setup_test_range(*,
|
||||
start: float | datetime = None,
|
||||
end: float | datetime = None,
|
||||
speed: int = 60,
|
||||
restart: bool = True)
|
||||
```
|
||||
Setup the test range for the backtest engine. This is used to set the range of the backtest and the speed
|
||||
at which it runs.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|---------------------|------------------------------------------------------------------------------------------------------------------------|
|
||||
| `start` | `float \| datetime` | The start time of the backtest. Defaults to None. If a float is passed, it is assumed to be a timestamp. |
|
||||
| `end` | `float \| datetime` | The end time of the backtest. Defaults to None. If a float is passed, it is assumed to be a timestamp. |
|
||||
| `speed` | `int` | The speed of the backtest. Defaults to 60 seconds. |
|
||||
| `restart` | `bool` | Whether to restart the backtest. Defaults to True. This is useful when resuming a backtest using a saved BackTestData. |
|
||||
|
||||
|
||||
<a id="backtest_engine.setup_data"></a>
|
||||
#### setup_data
|
||||
```python
|
||||
def setup_data(*, restart: bool = True)
|
||||
```
|
||||
Sets up the data for the backtest engine. This includes the orders, positions, deals and account
|
||||
information. This data is handled by specialized classes such as the BackTestAccount and the TradeManager
|
||||
classes.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|--------|------------------------------------------------|
|
||||
| `restart` | `bool` | Whether to restart the data. Defaults to True. |
|
||||
|
||||
|
||||
<a id="backtest_engine.next"></a>
|
||||
#### next
|
||||
```python
|
||||
def next() -> Cursor
|
||||
```
|
||||
Move the cursor to the next time step in the backtest range.
|
||||
|
||||
|
||||
<a id="backtest_engine.data"></a>
|
||||
#### data
|
||||
```python
|
||||
@property
|
||||
def data()
|
||||
```
|
||||
The BackTestData instance used for the backtest. If not provided, a new instance is created,
|
||||
and the data is made persistent when the backtest is stopped.
|
||||
|
||||
|
||||
<a id="backtest_engine.reset"></a>
|
||||
#### reset
|
||||
```python
|
||||
def reset(clear_data: bool = False)
|
||||
```
|
||||
Reset the backtest engine. This is useful when restarting the backtest from the beginning. Clear trade data if any
|
||||
when the `clear_data` parameter is true
|
||||
|
||||
|
||||
<a id="backtest_engine.go_to"></a>
|
||||
#### go_to
|
||||
```python
|
||||
def go_to(*, time: datetime | float)
|
||||
```
|
||||
Move the cursor to a specific time in the backtest range. You can pass a datetime object or a timestamp.
|
||||
You can't go back in time or beyond the limits of the range.
|
||||
|
||||
|
||||
<a id="backtest_engine.fast_forward"></a>
|
||||
#### fast_forward
|
||||
```python
|
||||
def fast_forward(*, steps: int)
|
||||
```
|
||||
Fast-forward the backtester by the given steps.
|
||||
|
||||
|
||||
<a id="backtest_engine.tracker"></a>
|
||||
#### tracker
|
||||
```python
|
||||
async def tracker()
|
||||
```
|
||||
The tracker monitors and updates open positions on every iteration. It is called by the controller.
|
||||
|
||||
|
||||
<a id="backtest_engine.save_result_to_json"></a>
|
||||
#### save_result_to_json
|
||||
```python
|
||||
@error_handler_sync
|
||||
def save_result_to_json()
|
||||
```
|
||||
Saves the result to a json file at the end of testing.
|
||||
|
||||
|
||||
<a id="backtest_engine.close_all_open"></a>
|
||||
#### close_all_open
|
||||
```python
|
||||
async def close_all_open()
|
||||
```
|
||||
Closes all open position at the end of testing
|
||||
|
||||
<a id="backtest_engine.wrap_up"></a>
|
||||
#### wrap_up
|
||||
```python
|
||||
@error_handler
|
||||
async def wrap_up()
|
||||
```
|
||||
Wraps up the backtest. This is called at the end of testing to save the results and close all open positions.
|
||||
|
||||
|
||||
<a id="backtest_engine.preload_ticks"></a>
|
||||
#### preload_ticks
|
||||
```python
|
||||
async def preload_ticks(*, symbol: str)
|
||||
```
|
||||
Pull a month data on ticks from the terminal. Starting from the current time.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|----------------------------------|
|
||||
| `symbol` | `str` | The symbol to preload ticks for. |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_price_tick"></a>
|
||||
#### get_price_tick
|
||||
```python
|
||||
@async_cache
|
||||
async def get_price_tick(*, symbol: str, time: int) -> Tick | None
|
||||
```
|
||||
Get the price tick for a symbol at a given time. If the preload option is set to True,
|
||||
it will use the preloaded ticks when available.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|---------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get the price tick for. |
|
||||
| `time` | `int` | The time to get the price tick. |
|
||||
|
||||
|
||||
<a id="backtest_engine.check_order"></a>
|
||||
#### check_order
|
||||
```python
|
||||
@error_handler
|
||||
async def check_order(*, ticket: int)
|
||||
```
|
||||
Check if the order has reached its take profit or stop loss levels and close the order if it has.
|
||||
Checks only `OrderType.BUY` and `OrderType.SELL` orders that have reached their take profit or stop loss levels.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|--------------|
|
||||
| `ticket` | `int` | Order ticket |
|
||||
|
||||
|
||||
<a id="backtest_engine.check_account"></a>
|
||||
#### check_account
|
||||
```python
|
||||
def check_account()
|
||||
```
|
||||
Checks an account status. This method is called at each iteration to check if the account has burned out.
|
||||
|
||||
|
||||
<a id="backtest_engine.check_position"></a>
|
||||
#### check_position
|
||||
```python
|
||||
async def check_position(*, ticket: int)
|
||||
```
|
||||
Update the profit of an open position based on the current price of the symbol. It is called by the
|
||||
tracker to update the profit of open positions.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `ticket` | `int` | Position ticket |
|
||||
|
||||
|
||||
<a id="backtest_engine.close_position_manually"></a>
|
||||
#### close_position_manually
|
||||
```python
|
||||
@error_handler_sync
|
||||
async def close_position_manually(*, ticket: int)
|
||||
```
|
||||
Close a position manually without. Usually at the end of testing.
|
||||
|
||||
|
||||
<a id="backtest_engine.close_position"></a>
|
||||
#### close_position
|
||||
```python
|
||||
async def close_position(*, ticket: int) -> bool
|
||||
```
|
||||
Close an open position for the trading account using the position ticket.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `ticket` | `int` | Position ticket |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------------------------------|
|
||||
| `bool` | True if the position is closed successfully, False otherwise |
|
||||
|
||||
|
||||
<a id="backtest_engine.modify_stops"></a>
|
||||
#### modify_stops
|
||||
```python
|
||||
@error_handler(response=False)
|
||||
def modify_stops(*, ticket: int, sl: int, tp: int) -> bool
|
||||
```
|
||||
Modify the stop loss and take profit levels of an open position.
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `ticket` | `int` | Position ticket |
|
||||
| `sl` | `int` | stop loss level |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------------------------------|
|
||||
| `bool` | True if the stops are modified successfully, False otherwise |
|
||||
|
||||
|
||||
<a id="backtest_engine.update_account"></a>
|
||||
#### update_account
|
||||
```python
|
||||
def update_account(*,
|
||||
profit: float = None,
|
||||
margin: float = 0,
|
||||
gain: float = 0)
|
||||
```
|
||||
Update the account. This method is protected by thread lock.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|---------|--------------------------------------------------------------------------------|
|
||||
| `profit` | `float` | The current profit of one or more open positions. Can be positive or negative. |
|
||||
| `margin` | `float` | The margin set aside for a trade. It is released when the trade is closed. |
|
||||
| `gain` | `gain` | The gain realized when the trade is closed. |
|
||||
|
||||
|
||||
<a id="backtest_engine.deposit"></a>
|
||||
#### deposit
|
||||
```python
|
||||
def deposit(*, amount: float)
|
||||
```
|
||||
Make deposit to the trading account
|
||||
|
||||
|
||||
<a id="backtest_engine.withdraw"></a>
|
||||
#### withdraw
|
||||
```python
|
||||
def withdraw(*, amount: float)
|
||||
```
|
||||
Make a withdrawal from the trading account. You can not withdraw more than what you have
|
||||
|
||||
|
||||
<a id="backtest_engine.setup_account"></a>
|
||||
#### setup_account
|
||||
```python
|
||||
@error_handler
|
||||
async def setup_account(**kwargs)
|
||||
```
|
||||
Set up the trading account before the beginning of a backtesting session.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|------|-------------------------------------------------------------|
|
||||
| `kwargs` | dict | Attributes for the backtest account object can be set here. |
|
||||
|
||||
|
||||
<a id="backtest_engine.setup_account_sync"></a>
|
||||
#### setup_account_sync
|
||||
```python
|
||||
@error_handler_sync
|
||||
def setup_account_sync(**kwargs)
|
||||
```
|
||||
Set up the backtesting account in sync mode
|
||||
|
||||
|
||||
<a id="backtest_engine.prices"></a>
|
||||
#### prices
|
||||
```python
|
||||
@cached_property
|
||||
def prices() -> dict[str, DataFrame]
|
||||
```
|
||||
Get the prices for instruments used in the backtesting. This class is called when the use_terminal option
|
||||
is set to False and trading data is provided in the data attribute. It makes sure that there is a price for each
|
||||
symbol for every second covered in the backtesting range, by reindexing the price ticks using the backtesting
|
||||
time span and filling up missing data using the nearest method.
|
||||
This method returns a dictionaries of dataframe containing the prices for each symbol.
|
||||
It's cached and there computed only once per backtesting session.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------------------------------|
|
||||
| `dict` | A dictionary mapping dataframe of prices to symbols. |
|
||||
|
||||
|
||||
<a id="backtest_engine.ticks"></a>
|
||||
#### ticks
|
||||
```python
|
||||
@cached_property
|
||||
def ticks() -> dict[str, DataFrame]
|
||||
```
|
||||
Similar to prices above, but returns prices exactly as they are without reindexing and filling up.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------------------------------|
|
||||
| `dict` | A dictionary mapping dataframe of prices to symbols. |
|
||||
|
||||
|
||||
<a id="backtest_engine.rates"></a>
|
||||
#### rates
|
||||
```python
|
||||
@cached_property
|
||||
def rates() -> dict[str, dict[int, DataFrame]]
|
||||
```
|
||||
This property is useful when backtesting with the use_terminal option set to false. It returns a nested dict
|
||||
that maps symbols to a dict mapping timeframes to rates. The timeframes are mapped using their integer values.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------------------------|-------------------------------------------|
|
||||
| `dict[str, dict[int, DataFrame]]` | A dictionary containing the symbol rates. |
|
||||
|
||||
|
||||
<a id="backtest_engine.symbols"></a>
|
||||
#### symbols
|
||||
```python
|
||||
@cached_property
|
||||
def symbols() -> dict[str, SymbolInfo]
|
||||
```
|
||||
A dictionary of symbols and SymbolInfo object. Used when use_terminal is set to false.
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------------|------------------------------------------------|
|
||||
| `dict[str, SymbolInfo]` | A dictionary of symbols and SymbolInfo object. |
|
||||
|
||||
|
||||
<a id="backtest_engine.order_send"></a>
|
||||
#### order_send
|
||||
```python
|
||||
@error_handler
|
||||
async def order_send(*, request: dict, use_terminal=False) -> OrderSendResult
|
||||
```
|
||||
Simulates the sending of an order to the broker. An OrderSendResult is object is created at the end of this
|
||||
operation as would be created if it was done in live trading. When an order is successful a positions object is
|
||||
created, an order and deal object is created as well. The margin and profit are calculated by sending to the broker
|
||||
if `use_terminal` is true. This increases accuracy but slows down the backtester. The `check_order` method is
|
||||
called to make sure the order is valid and would go through if it was a live trade.
|
||||
|
||||
#### Parameters:
|
||||
|
||||
| Name | Type | Description |
|
||||
|----------------|------|-------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `request` | dict | The order request as a dict. |
|
||||
| `use_terminal` | bool | A flag to override the use_terminal attribute. If true, the terminal will be used even if the use_terminal attribute is True. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------|--------------------------------------------------------------|
|
||||
| `OrderSendResult` | An object containing the result of the order send operation. |
|
||||
|
||||
|
||||
<a id="backtest_engine.order_check"></a>
|
||||
#### order_check
|
||||
```python
|
||||
@error_handler
|
||||
async def order_check(*, request: dict, use_terminal: bool = False) -> OrderCheckResult
|
||||
```
|
||||
Checks the order before placing it. If `use_terminal` is true, the order is checked with the broker,
|
||||
but the entire result is not used. Details such as balance, profit, equity, margin, and margin level are calculated
|
||||
by the backtester.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------------|------|---------------------------------------------------------------------------------|
|
||||
| `request` | dict | The order request as a dict. |
|
||||
| `use_terminal` | bool | A flag to override the use_terminal attribute. If true, the terminal will used. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------|--------------------------------|
|
||||
| `OrderCheckResult` | The result of the order check. |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_terminal_info"></a>
|
||||
#### get_terminal_info
|
||||
```python
|
||||
@error_handler
|
||||
async def get_terminal_info() -> TerminalInfo
|
||||
```
|
||||
Get the terminal information
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|----------------|--------------------------|
|
||||
| `TerminalInfo` | The terminal information |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_version"></a>
|
||||
#### get_version
|
||||
```python
|
||||
@error_handler
|
||||
async def get_version() -> tuple[int, int, str]
|
||||
```
|
||||
Get the version of the terminal.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------------------------|-----------------------------|
|
||||
| `tuple[int, int, str]` | The version of the terminal |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_symbols_total"></a>
|
||||
#### get_symbols_total
|
||||
```python
|
||||
@error_handler
|
||||
async def get_symbols_total() -> int
|
||||
```
|
||||
Get the total number of symbols available in the terminal.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------|------------------------------------------------|
|
||||
| `int` | The total number of symbols available. |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_symbols"></a>
|
||||
#### get_symbols
|
||||
```python
|
||||
@error_handler
|
||||
async def get_symbols(*, group: str = "") -> tuple[SymbolInfo, ...]
|
||||
```
|
||||
Get the symbols available in the terminal. Filter by group if provided.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|------|------------------------------------------------|
|
||||
| `group` | str | The group to filter by (default is "") |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|-------------------------------|
|
||||
| `tuple[SymbolInfo, ...]` | A tuple of symbol information |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_account_info"></a>
|
||||
#### get_account_info
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_account_info() -> AccountInfo
|
||||
```
|
||||
Get the account information
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------|-------------------------|
|
||||
| `AccountInfo` | The account information |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_symbol_info_tick"></a>
|
||||
#### get_symbol_info_tick
|
||||
```python
|
||||
@error_handler
|
||||
async def get_symbol_info_tick(*, symbol: str) -> Tick
|
||||
```
|
||||
Get the price tick for a symbol at the current time
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|------|---------------------------------------|
|
||||
| `symbol` | str | The symbol to get the price tick for. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|----------------|
|
||||
| `Tick` | The price tick |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_symbol_info"></a>
|
||||
#### get_symbol_info
|
||||
```python
|
||||
@error_handler
|
||||
async def get_symbol_info(*, symbol: str) -> SymbolInfo
|
||||
```
|
||||
Get the symbol information
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|------|---------------------------------------|
|
||||
| `symbol` | str | The symbol to get information for |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `SymbolInfo` | The symbol information |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_rates_from"></a>
|
||||
#### get_rates_from
|
||||
```python
|
||||
@error_handler
|
||||
async def get_rates_from(*, symbol: str, timeframe: TimeFrame, date_from: datetime | float, count: int) -> np.ndarray
|
||||
```
|
||||
Get rates from a specific date to the current date. Used by the backtester to get rates for a symbol
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get rates for |
|
||||
| `timeframe` | `TimeFrame` | The timeframe of the rates |
|
||||
| `date_from` | `datetime \| float` | The date from which to get the rates |
|
||||
| `count` | `int` | The number of rates to get |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `np.ndarray` | An array of rates |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_rates_from_pos"></a>
|
||||
#### get_rates_from_pos
|
||||
```python
|
||||
@error_handler
|
||||
async def get_rates_from_pos(*, symbol: str, timeframe: TimeFrame, start_pos: int, count: int) -> np.ndarray
|
||||
```
|
||||
Get a number of rates counting from a specific position. With position zero being the current time.
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get rates for |
|
||||
| `timeframe` | `TimeFrame` | The timeframe of the rates |
|
||||
| `start_pos` | `int` | The position to start from |
|
||||
| `count` | `int` | The number of rates to get |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `np.ndarray` | An array of rates |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_rates_range"></a>
|
||||
#### get_rates_range
|
||||
```python
|
||||
@error_handler
|
||||
async def get_rates_range(*, symbol: str, timeframe: TimeFrame, date_from: datetime | float,
|
||||
date_to: datetime | float) -> np.ndarray
|
||||
```
|
||||
Get rates within a specific date range. Used by the backtester to get rates for a symbol
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get rates for |
|
||||
| `timeframe` | `TimeFrame` | The timeframe of the rates |
|
||||
| `date_from` | `datetime \| float` | The date from which to get the rates |
|
||||
| `date_to` | `datetime \| float` | The date to which to get the rates |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `np.ndarray` | An array of rates |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_ticks_from"></a>
|
||||
#### get_ticks_from
|
||||
```python
|
||||
@error_handler
|
||||
async def get_ticks_from(*, symbol: str, date_from: datetime | float, count: int,
|
||||
flags: CopyTicks = CopyTicks.ALL) -> np.ndarray
|
||||
```
|
||||
Get a specified number of ticks counting from a specific date.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get ticks for |
|
||||
| `date_from` | `datetime \| float` | The date from which to get the ticks |
|
||||
| `count` | `int` | The number of ticks to get |
|
||||
| `flags` | `CopyTicks` | The flags to use when getting ticks |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `np.ndarray` | An array of ticks |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_ticks_range"></a>
|
||||
#### get_ticks_range
|
||||
```python
|
||||
@error_handler
|
||||
async def get_ticks_range(*, symbol: str, date_from: datetime | float, date_to: datetime | float,
|
||||
flags: CopyTicks = CopyTicks.ALL) -> np.ndarray
|
||||
```
|
||||
Get ticks within a specific date range.
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `symbol` | `str` | The symbol to get ticks for |
|
||||
| `date_from` | `datetime \| float` | The date from which to get the ticks |
|
||||
| `date_to` | `datetime \| float` | The date to which to get the ticks |
|
||||
| `flags` | `CopyTicks` | The flags to use when getting ticks |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|------------------------|
|
||||
| `np.ndarray` | An array of ticks |
|
||||
|
||||
|
||||
<a id="backtest_engine.order_calc_margin"></a>
|
||||
#### order_calc_margin
|
||||
```python
|
||||
@error_handler
|
||||
async def order_calc_margin(*, action: Literal[OrderType.BUY, OrderType.SELL], symbol: str, volume: float,
|
||||
price: float, use_terminal: bool = None)
|
||||
```
|
||||
Calculate the margin required for a trade.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------------|------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `action` | `Literal[OrderType.BUY, OrderType.SELL]` | Type of order |
|
||||
| `symbol` | `str` | Symbol name |
|
||||
| `volume` | `float` | Volume of the trade |
|
||||
| `price` | `float` | The price at which the trade is opened |
|
||||
| `use_terminal` | `bool` | A flag to override the use_terminal attribute. If true, the terminal will be used even if the use_terminal attribute is True. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|------------------------------------|
|
||||
| `float` | The margin required for the trade |
|
||||
|
||||
|
||||
<a id="backtest_engine.order_calc_profit"></a>
|
||||
#### order_calc_profit
|
||||
```python
|
||||
@error_handler
|
||||
async def order_calc_profit(*, action: Literal[OrderType.BUY, OrderType.SELL], symbol: str, volume: float,
|
||||
price_open: float, price_close: float, use_terminal=None)
|
||||
```
|
||||
Calculate the profit for a trade.
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------------|------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `action` | `Literal[OrderType.BUY, OrderType.SELL]` | Type of order |
|
||||
| `symbol` | `str` | Symbol name |
|
||||
| `volume` | `float` | Volume of the trade |
|
||||
| `price_open` | `float` | The price at which the trade is opened |
|
||||
| `price_close` | `float` | The price at which the trade is closed |
|
||||
| `use_terminal` | `bool` | A flag to override the use_terminal attribute. If true, the terminal will be used even if the `use_terminal` attribute is True. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------|-------------------------|
|
||||
| `float` | The profit of the trade |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_orders_total"></a>
|
||||
#### get_orders_total
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_orders_total() -> int
|
||||
```
|
||||
Get the total number of pending orders.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|--------------------------------|
|
||||
| `int` | Total number of pending orders |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_orders"></a>
|
||||
#### get_orders
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_orders(*, symbol: str = "", group: str = "", ticket: int = None) -> tuple[TradeOrder, ...]
|
||||
```
|
||||
Get pending orders from the terminal history. This has to do with pending orders, which this backtester
|
||||
doesn't support yet.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|--------------|
|
||||
| `symbol` | `str` | Symbol name |
|
||||
| `group` | `str` | Group name |
|
||||
| `ticket` | `int` | Order ticket |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|----------------|
|
||||
| `tuple[TradeOrder, ...]` | Pending orders |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_positions_total"></a>
|
||||
#### get_positions_total
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_positions_total() -> int
|
||||
```
|
||||
Get the total number of open positions.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|--------------------------------|
|
||||
| `int` | Total number of open positions |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_positions"></a>
|
||||
#### get_positions
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_positions(*, symbol: str = None, group: str = None, ticket: int = None) -> tuple[TradePosition, ...]
|
||||
```
|
||||
Get open positions from the terminal history.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------|
|
||||
| `symbol` | `str` | Symbol name |
|
||||
| `group` | `str` | Group name |
|
||||
| `ticket` | `int` | Position ticket |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|----------------|
|
||||
| `tuple[TradePosition, ...]` | Open positions |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_history_orders_total"></a>
|
||||
#### get_history_orders_total
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_history_orders_total(*, date_from: datetime | float, date_to: datetime | float) -> int
|
||||
```
|
||||
Get the total number of orders in the terminal history.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|---------------------------------------|
|
||||
| `date_from` | `datetime \| float` | The start date of the history |
|
||||
| `date_to` | `datetime \| float` | The end date of the history |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|--------------------------------|
|
||||
| `int` | Total number of orders in the history |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_history_orders"></a>
|
||||
#### get_history_orders
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_history_orders(*, date_from: datetime | float = None, date_to: datetime | float = None, group: str = "",
|
||||
ticket: int = None, position: int = None) -> tuple[TradeOrder, ...]
|
||||
```
|
||||
Get orders from the terminal history.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|---------------------------------------|
|
||||
| `date_from` | `datetime \| float` | Date from which to start the history |
|
||||
| `date_to` | `datetime \| float` | Date to which to end the history |
|
||||
| `group` | `str` | group keyword to filter by |
|
||||
| `ticket` | `int` | ticket id to filter by |
|
||||
| `position` | `int` | position id to filter by |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|-----------------------|
|
||||
| `tuple[TradeOrder, ...]` | Orders in the history |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_history_deals_total"></a>
|
||||
#### get_history_deals_total
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_history_deals_total(*, date_from: datetime | float, date_to: datetime | float) -> int
|
||||
```
|
||||
Get the total number of deals in the terminal history.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------------|
|
||||
| `date_from` | `datetime \| float` | Date from which to start the history |
|
||||
| `date_to` | `datetime \| float` | Date to which to end the history |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|--------------------------------------|
|
||||
| `int` | Total number of deals in the history |
|
||||
|
||||
|
||||
<a id="backtest_engine.get_history_deals"></a>
|
||||
#### get_history_deals
|
||||
```python
|
||||
@error_handler_sync
|
||||
def get_history_deals(*, date_from: datetime | float = None, date_to: datetime | float = None, group: str = None,
|
||||
position: int = None, ticket: int = None) -> tuple[TradeDeal, ...]
|
||||
```
|
||||
Get deals from the terminal history.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|---------------------------------------|
|
||||
| `date_from` | `datetime \| float` | Date from which to start the history |
|
||||
| `date_to` | `datetime \| float` | Date to which to end the history |
|
||||
| `group` | `str` | group keyword to filter by |
|
||||
| `position` | `int` | position id to filter by |
|
||||
| `ticket` | `int` | ticket id to filter by |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------------|----------------------|
|
||||
| `tuple[TradeDeal, ...]` | Deals in the history |
|
||||
@@ -1,162 +0,0 @@
|
||||
# Get Data
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Cursor](#get_data.cursor)
|
||||
- [BackTestData](#get_data.back_test_data)
|
||||
- [set_attrs](#get_data.back_test_data.set_attrs)
|
||||
- [fields](#get_data.back_test_data.fields)
|
||||
- [GetData](#get_data.getdata)
|
||||
- [\__init\__](#get_data.get_data.__init__)
|
||||
- [pickle_data](#get_data.pickle_data)
|
||||
- [load_data](#get_data.load_data)
|
||||
- [save_data](#get_data.save_data)
|
||||
- [get_data](#get_data.get_data)
|
||||
|
||||
|
||||
<a id="get_data.cursor"></a>
|
||||
### Cursor
|
||||
```python
|
||||
class Cursor(NamedTuple)
|
||||
```
|
||||
A cursor to iterate over the data. Marks the current position in time.
|
||||
|
||||
|
||||
<a id="get_data.back_test_data"></a>
|
||||
### BackTestData
|
||||
```python
|
||||
@dataclass
|
||||
class BackTestData
|
||||
```
|
||||
The data class to store the backtesting data.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|------------------|----------|------------------------------------------------|
|
||||
| `name` | `str` | The name of the backtest data |
|
||||
| `terminal` | `dict` | The terminal information |
|
||||
| `version` | `tuple` | The version of the terminal |
|
||||
| `account` | `dict` | The account information |
|
||||
| `symbols` | `dict` | The symbols information |
|
||||
| `ticks` | `dict` | The ticks data |
|
||||
| `rates` | `dict` | The rates data |
|
||||
| `span` | `range` | The range of the data |
|
||||
| `range` | `range` | The range of the data |
|
||||
| `orders` | `dict` | The orders data |
|
||||
| `deals` | `dict` | The deals data |
|
||||
| `positions` | `dict` | The positions data |
|
||||
| `open_positions` | `set` | The open positions |
|
||||
| `cursor` | `Cursor` | The cursor to iterate over the data |
|
||||
| `margins` | `dict` | The margins data |
|
||||
| `fully_loaded` | `bool` | A flag to indicate if the data is fully loaded |
|
||||
|
||||
|
||||
<a id="get_data.set_attrs"></a>
|
||||
#### set_attrs
|
||||
```python
|
||||
def set_attrs(**kwargs)
|
||||
```
|
||||
Set the attributes of the class on the instance.
|
||||
|
||||
|
||||
<a id="get_data.fields"></a>
|
||||
#### fields
|
||||
```python
|
||||
@property
|
||||
def fields()
|
||||
```
|
||||
A list of the fields of the class.
|
||||
|
||||
|
||||
<a id="get_data.getdata"></a>
|
||||
### GetData
|
||||
```python
|
||||
class GetData
|
||||
```
|
||||
A class to get the backtesting data from the MetaTrader5 terminal.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|--------------|-----------------------|---------------------------------------|
|
||||
| `start` | `datetime` | The start date of the data |
|
||||
| `end` | `datetime` | The end date of the data |
|
||||
| `symbols` | `Iterable[str]` | The symbols to get the data for |
|
||||
| `timeframes` | `Iterable[TimeFrame]` | The timeframes to get the data for |
|
||||
| `name` | `str` | The name of the backtest data |
|
||||
| `range` | `range` | The range of the data |
|
||||
| `span` | `range` | The span of the data |
|
||||
| `data` | `BackTestData` | The backtesting data |
|
||||
| `mt5` | `MetaTrader` | The MetaTrader5 instance |
|
||||
| `task_queue` | `TaskQueue` | The task queue to handle the requests |
|
||||
|
||||
|
||||
<a id="get_data.__init__"></a>
|
||||
#### \__init\__
|
||||
```python
|
||||
def __init__(*, start: datetime, end: datetime, symbols: Sequence[str],
|
||||
timeframes: Sequence[TimeFrame], name: str = "")
|
||||
```
|
||||
Get the backtesting data from the MetaTrader5 terminal.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|--------------|-----------------------|------------------------------------------------|
|
||||
| `start` | `datetime` | The start date of the data |
|
||||
| `end` | `datetime` | The end date of the data |
|
||||
| `symbols` | `Sequence[str]` | The symbols to get the data for |
|
||||
| `timeframes` | `Sequence[TimeFrame]` | The timeframes to get the data for |
|
||||
| `name` | `str` | The name of the backtest data |
|
||||
|
||||
|
||||
<a id="get_data.pickle_data"></a>
|
||||
#### pickle_data
|
||||
```python
|
||||
@classmethod
|
||||
def pickle_data(cls, *, data: BackTestData, name: str | Path)
|
||||
```
|
||||
Pickle the data to a file.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|--------|-------------------------|----------------------|
|
||||
| `data` | `BackTestData` | The data to pickle |
|
||||
| `name` | `str \| Path` | The name of the file |
|
||||
|
||||
|
||||
<a id="get_data.load_data"></a>
|
||||
#### load_data
|
||||
```python
|
||||
@classmethod
|
||||
def load_data(cls, *, name: str | Path) -> BackTestData
|
||||
```
|
||||
Load the data from a file.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|--------|-------------------------|----------------------|
|
||||
| `name` | `str \| Path` | The name of the file |
|
||||
|
||||
|
||||
<a id="get_data.save_data"></a>
|
||||
#### save_data
|
||||
```python
|
||||
def save_data(*, name: str | Path = "")
|
||||
```
|
||||
Save the data to a file.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|--------|-------------------------|----------------------|
|
||||
| `name` | `str \| Path` | The name of the file |
|
||||
|
||||
|
||||
<a id="get_data.get_data"></a>
|
||||
#### get_data
|
||||
```python
|
||||
async def get_data(workers: int = None)
|
||||
```
|
||||
Use the task queue to get the data from the MetaTrader5 terminal.
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|------------------------------------------------|
|
||||
| `workers` | `int` | The number of workers to use in the task queue |
|
||||
@@ -1,409 +0,0 @@
|
||||
# TradesManager
|
||||
|
||||
## Table of Contents
|
||||
- [trades_manager](#trades_manager.trades_manager)
|
||||
- [TradesManager](#trades_manager.trades_manager)
|
||||
- [update](#trades_manager.trade_manager.update)
|
||||
- [values](#trades_manager.trade_manager.values)
|
||||
- [keys](#trades_manager.trade_manager.keys)
|
||||
- [items](#trades_manager.trade_manager.items)
|
||||
- [to_dict](#trades_manager.trade_manager.to_dict)
|
||||
- [PositionsManager](#trades_manager.positions_manager)
|
||||
- [\__init\__](#positions_manager.__init__)
|
||||
- [margin](#positions_manager.margin)
|
||||
- [close](#positions_manager.close)
|
||||
- [get_margin](#positions_manager.get_margin)
|
||||
- [delete_margin](#positions_manager.delete_margin)
|
||||
- [set_margin](#positions_manager.set_margin)
|
||||
- [positions_get](#positions_manager.positions_get)
|
||||
- [positions_total](#positions_manager.positions_total)
|
||||
- [open_positions](#positions_manager.open_positions)
|
||||
- [OrdersManager](#trades_manager.orders_manager)
|
||||
- [get_orders_range](#orders_manager.get_orders_range)
|
||||
- [history_orders_get](#orders_manager.history_orders_get)
|
||||
- [history_orders_total](#orders_manager.history_orders_total)
|
||||
- [DealsManager](#trades_manager.deals_manager)
|
||||
- [get_deals_range](#deals_manager.get_deals_range)
|
||||
- [history_deals_get](#deals_manager.history_deals_get)
|
||||
- [history_deals_total](#deals_manager.history_deals_total)
|
||||
|
||||
|
||||
<a id="trades_manager.trades_manager"></a>
|
||||
### TradesManager
|
||||
```python
|
||||
class TradeManager(Generic[TradeData])
|
||||
```
|
||||
A generic class to manage trades data during a backtest. It is the parent class of the
|
||||
PositionsManager, OrdersManager, and DealsManager. It implements some dict-like methods to manage the data.
|
||||
It has a private attribute _data to store the data. It exposes the data through the values, keys, and items methods.
|
||||
It also has a `to_dict` method to convert the data to a dictionary.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|---------|------------------------|------------------------------|
|
||||
| `_data` | `dict[int, TradeData]` | The data to store the trades |
|
||||
|
||||
|
||||
#### Examples:
|
||||
```python
|
||||
>>> manager = TradeManager()
|
||||
>>> manager[123456] = TradePosition(ticket=123456, symbol="EURUSD", volume=0.1)
|
||||
>>> manager.update(ticket=123456, symbol="EURUSD", volume=0.1)
|
||||
>>> manager[123456]
|
||||
TradePosition(ticket=123456, symbol='EURUSD', volume=0.1)
|
||||
>>> manager.values()
|
||||
(TradePosition(ticket=123456, symbol='EURUSD', volume=0.1),)
|
||||
>>> manager.keys()
|
||||
(123456,)
|
||||
>>> manager.items()
|
||||
((123456, TradePosition(ticket=123456, symbol='EURUSD', volume=0.1)),)
|
||||
>>> manager.to_dict()
|
||||
{'123456' - {'ticket': 123456, 'symbol': 'EURUSD', 'volume': 0.1}}
|
||||
>>> pos = manager.get(123456)
|
||||
>>> pos
|
||||
TradePosition(ticket=123456, symbol='EURUSD', volume=0.1)
|
||||
>>> pos in manager
|
||||
True
|
||||
>>> len(manager)
|
||||
1
|
||||
>>> pos in manager
|
||||
False
|
||||
```
|
||||
|
||||
<a id="trades_manager.update"></a>
|
||||
#### update
|
||||
```python
|
||||
def update(*, ticket: int, **kwargs)
|
||||
```
|
||||
Update the data of a trade. Given the ticket of the trade and the new data to update.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------|-------|------------------------------------|
|
||||
| `ticket` | `int` | The ticket of the trade to update. |
|
||||
| `**kwargs` | | The new data to update. |
|
||||
|
||||
|
||||
<a id="trades_manager.values"></a>
|
||||
### values
|
||||
```python
|
||||
def values() -> tuple[TradeData, ...]
|
||||
```
|
||||
Returns the values of the data.
|
||||
|
||||
|
||||
<a id="trades_manager.keys"></a>
|
||||
### keys
|
||||
```python
|
||||
def keys() -> tuple[int, ...]
|
||||
```
|
||||
Returns the keys of the data.
|
||||
|
||||
|
||||
<a id="trades_manager.items"></a>
|
||||
### items
|
||||
```python
|
||||
def items() -> tuple[tuple[int, TradeData], ...]
|
||||
```
|
||||
Returns the items of the data.
|
||||
|
||||
|
||||
<a id="trades_manager.to_dict"></a>
|
||||
### to_dict
|
||||
```python
|
||||
def to_dict()
|
||||
```
|
||||
Convert the data to a dictionary.
|
||||
|
||||
|
||||
<a id="trades_manager.positions_manager"></a>
|
||||
```python
|
||||
class PositionsManager(TradeManager)
|
||||
```
|
||||
A class to manage the open positions during a backtest. It is a subclass of It has an additional
|
||||
attribute _open_positions to store the open positions. It also has a margins attribute to store the margins of the
|
||||
open positions. It overrides some methods of the TradeManager class to manage the open positions.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|------------------|--------------------|--------------------------------------------------------------------------------------------------------------------------|
|
||||
| `data` | `dict` | The data to store the trades. This used for continuation of the backtesting, if it was stopped with some open positions. |
|
||||
| `open_positions` | `set[int]` | The open positions. |
|
||||
| `margins` | `dict[int, float]` | The margins of the open positions. |
|
||||
|
||||
|
||||
<a id="positions_manager.__init__"></a>
|
||||
#### \__init\__
|
||||
```python
|
||||
def __init__(*, data: dict = None, open_positions: set[int] = None, margins: dict = None)
|
||||
```
|
||||
Positions manager manages the open positions during a backtest. It is a subclass of It has an
|
||||
additional attribute _open_positions to store the open positions. It also has a margins attribute to store the
|
||||
margins of the open positions. It overrides some methods of the TradeManager class to manage the open positions.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------------|--------------------|--------------------------------------------------------------------------------------------------------------------------|
|
||||
| `data` | `dict` | The data to store the trades. This used for continuation of the backtesting, if it was stopped with some open positions. |
|
||||
| `open_positions` | `set[int]` | The open positions. |
|
||||
| `margins` | `dict[int, float]` | The margins of the open positions. |
|
||||
|
||||
|
||||
<a id="positions_manager.margin"></a>
|
||||
### margin
|
||||
```python
|
||||
@property
|
||||
def margin()
|
||||
```
|
||||
Returns the total margin of all open positions
|
||||
|
||||
|
||||
<a id="positions_manager.close"></a>
|
||||
### close
|
||||
```python
|
||||
def close(*, ticket: int) -> bool
|
||||
```
|
||||
Close a position. Given the ticket of the position to close.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|--------------------------------------|
|
||||
| `ticket` | `int` | The ticket of the position to close. |
|
||||
|
||||
|
||||
<a id="positions_manager.get_margin"></a>
|
||||
#### get_margin
|
||||
```python
|
||||
def get_margin(*, ticket: int) -> float
|
||||
```
|
||||
Get the margin of a position. Given the ticket of the position.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------------------|
|
||||
| `ticket` | `int` | The ticket of the position. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------|-----------------------------|
|
||||
| `float` | The margin of the position. |
|
||||
|
||||
|
||||
<a id="positions_manager.delete_margin"></a>
|
||||
### delete_margin
|
||||
```python
|
||||
def delete_margin(*, ticket: int)
|
||||
```
|
||||
Delete the margin of a position. Given the ticket of the position.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------------------|
|
||||
| `ticket` | `int` | The ticket of the position. |
|
||||
|
||||
|
||||
<a id="positions_manager.set_margin"></a>
|
||||
### set_margin
|
||||
```python
|
||||
def set_margin(*, ticket: int, margin: float)
|
||||
```
|
||||
Set the margin of a position. Given the ticket of the position and the margin.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|---------|-----------------------------|
|
||||
| `ticket` | `int` | The ticket of the position. |
|
||||
| `margin` | `float` | The margin of the position. |
|
||||
|
||||
|
||||
<a id="positions_manager.positions_get"></a>
|
||||
### positions_get
|
||||
```python
|
||||
def positions_get(*, ticket: int = None, symbol: str = None, group: None = None) -> tuple[TradePosition, ...]
|
||||
```
|
||||
Get positions. Given the ticket, symbol, or group of the positions.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------------------|
|
||||
| `ticket` | `int` | The ticket of the position. |
|
||||
| `symbol` | `str` | The symbol of the position. |
|
||||
| `group` | `str` | The group of the position. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------------------------|-----------------------------|
|
||||
| `tuple[TradePosition]` | The positions. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------------------|-----------------------------|
|
||||
| `tuple[TradePosition, ...]` | The positions. |
|
||||
|
||||
|
||||
<a id="positions_manager.positions_total"></a>
|
||||
### positions_total
|
||||
```python
|
||||
def positions_total() -> int
|
||||
```
|
||||
Get the total number of open positions.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|-------------------------------------|
|
||||
| `int` | The total number of open positions. |
|
||||
|
||||
|
||||
<a id="positions_manager.open_positions"></a>
|
||||
#### open_positions
|
||||
```python
|
||||
@property
|
||||
def open_positions() -> tuple[TradePosition, ...]
|
||||
```
|
||||
Returns the open positions.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------------------|
|
||||
| `ticket` | `int` | The ticket of the position. |
|
||||
|
||||
|
||||
<a id="trades_manager.orders_manager"></a>
|
||||
### OrdersManager
|
||||
```python
|
||||
class OrdersManager(TradeManager)
|
||||
```
|
||||
Managers orders data during a backtest. It is a subclass of It manages access to the historical
|
||||
orders data
|
||||
|
||||
|
||||
<a id="orders_manager.get_orders_range"></a>
|
||||
#### get_orders_range
|
||||
```python
|
||||
def get_orders_range(*, date_from: float, date_to: float) -> tuple[TradeData, ...]
|
||||
```
|
||||
Get orders within a date range. Given the start and end date of the range.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------|-----------------------------------|
|
||||
| `tuple[TradeData]` | The orders within the date range. |
|
||||
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------|-----------------------------------|
|
||||
| `tuple[TradeData]` | The orders within the date range. |
|
||||
|
||||
|
||||
<a id="orders_manager.history_orders_get"></a>
|
||||
#### history_orders_get
|
||||
```python
|
||||
def history_orders_get(*, date_from: float | datetime = None, date_to: float | datetime = None,
|
||||
group: str = "", ticket: int = None, position: int = None) -> tuple[TradeOrder, ...]
|
||||
```
|
||||
Get historical orders. Given the start and end date of the range, the group, ticket, or position of the
|
||||
orders.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
| `group` | `str` | The group of the orders. |
|
||||
| `ticket` | `int` | The ticket of the order. |
|
||||
| `position` | `int` | The position of the order. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------------|------------------------|
|
||||
| `tuple[TradeOrder]` | The historical orders. |
|
||||
|
||||
|
||||
<a id="orders_manager.history_orders_total"></a>
|
||||
### history_orders_total
|
||||
```python
|
||||
def history_orders_total(*, date_from: datetime | float,
|
||||
date_to: datetime | float) -> int
|
||||
```
|
||||
Get the total number of historical orders. Given the start and end date of the range.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
|
||||
|
||||
<a id="trades_manager.deals_manager"></a>
|
||||
### DealsManager
|
||||
```python
|
||||
class DealsManager(TradeManager)
|
||||
```
|
||||
|
||||
<a id="deals_manager.get_deals_range"></a>
|
||||
#### get_deals_range
|
||||
```python
|
||||
def get_deals_range(*, date_from: float, date_to: float) -> tuple[TradeData, ...]
|
||||
```
|
||||
Get deals within a date range. Given the start and end date of the range.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------|-----------------------------------|
|
||||
| `tuple[TradeData]` | The deals within the date range. |
|
||||
|
||||
|
||||
<a id="deals_manager.history_deals_get"></a>
|
||||
### history_deals_get
|
||||
```python
|
||||
def history_deals_get(*,
|
||||
date_from: float | datetime = None,
|
||||
date_to: float | datetime = None,
|
||||
group: str = "",
|
||||
ticket: int = None,
|
||||
position: int = None) -> tuple[TradeDeal, ...]
|
||||
```
|
||||
History deals get. Given the start and end date of the range, the group, ticket, or position of the deals.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
| `group` | `str` | The group of the deals. |
|
||||
| `ticket` | `int` | The ticket of the deal. |
|
||||
| `position` | `int` | The position of the deal. |
|
||||
|
||||
|
||||
<a id="deals_manager.history_deals_total"></a>
|
||||
#### history_deals_total
|
||||
```python
|
||||
def history_deals_total(*, date_from: datetime | float,
|
||||
date_to: datetime | float) -> int
|
||||
```
|
||||
Get the total number of historical deals. Given the start and end date of the range
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------|------------------------------|
|
||||
| `date_from` | `float` | The start date of the range. |
|
||||
| `date_to` | `float` | The end date of the range. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|---------------------------------------|
|
||||
| `int` | The total number of historical deals. |
|
||||
+49
-107
@@ -1,135 +1,77 @@
|
||||
# Base
|
||||
# base
|
||||
|
||||
## Table of Contents
|
||||
- [Base](#base.base)
|
||||
- [set_attributes](#base.set_attributes)
|
||||
- [annotations](#base.annotations)
|
||||
- [get_dict](#base.get_dict)
|
||||
- [class_vars](#base.class_vars)
|
||||
- [dict](#base.dict)
|
||||
`aiomql.core.base` — Foundational base classes for data structure handling.
|
||||
|
||||
- [_Base](#_base._base)
|
||||
## Overview
|
||||
|
||||
Provides the `Base` and `_Base` classes that all data-model and trading classes inherit from.
|
||||
`Base` offers attribute management, dictionary conversion, and filtering.
|
||||
`_Base` extends it with automatic access to the MetaTrader terminal and configuration.
|
||||
|
||||
<a id="base.base"></a>
|
||||
### Base
|
||||
```python
|
||||
class Base
|
||||
```
|
||||
A base class for all data model classes in the aiomql package. This class provides a set of common methods
|
||||
and attributes for all data model classes.
|
||||
## Classes
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|------------------------------------------------------------------------------------------------------|
|
||||
| `exclude` | `set` | A set of attributes to be excluded when retrieving attributes using the *get_dict* and *dict* method |
|
||||
| `include` | `set` | A set of attributes to be included when retrieving attributes using the *get_dict* and *dict* method |
|
||||
### `BaseMeta`
|
||||
|
||||
> Metaclass that lazily initialises `config` and `mt5` on first access.
|
||||
|
||||
<a id="base.__init__"></a>
|
||||
### __init__
|
||||
```python
|
||||
def __init__(**kwargs)
|
||||
```
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|---------------------------------------------------|
|
||||
| `kwargs` | `Any` | Object attributes and values as keyword arguments |
|
||||
#### `_setup()`
|
||||
|
||||
Attaches `Config()` and `MetaTrader()` (or sync variant) to the class if not already present.
|
||||
|
||||
<a id="base.set_attributes"></a>
|
||||
### set_attributes
|
||||
```python
|
||||
def set_attributes(**kwargs)
|
||||
```
|
||||
Set keyword arguments as object attributes. Only sets attributes that have been annotated on the class body.
|
||||
---
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|---------------------------------------------------|
|
||||
| `kwargs` | `Any` | Object attributes and values as keyword arguments |
|
||||
### `Base`
|
||||
|
||||
#### Raises:
|
||||
| Exception | Description |
|
||||
|------------------|-----------------------------------------------------------------------------------|
|
||||
| `AttributeError` | When assigning an attribute that does not belong to the class or any parent class |
|
||||
> Common base class for all data structures in aiomql.
|
||||
|
||||
#### Notes:
|
||||
Only sets attributes that have been annotated on the class body.
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `exclude` | `set[str]` | Attributes excluded from dict conversion (default: `mt5`, `config`, …) |
|
||||
| `include` | `set[str]` | Attributes always included (overrides `exclude`) |
|
||||
|
||||
#### `__init__(**kwargs)`
|
||||
|
||||
<a id="base.annotations"></a>
|
||||
### annotations
|
||||
```python
|
||||
@property
|
||||
@cache
|
||||
def annotations() -> dict
|
||||
```
|
||||
Class annotations from all ancestor classes and the current class.
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------------------|-----------------------------------|
|
||||
| `dict[str, Any]` | A dictionary of class annotations |
|
||||
Sets keyword arguments as instance attributes via `set_attributes`.
|
||||
|
||||
#### `set_attributes(**kwargs)`
|
||||
|
||||
<a id="base.get_dict"></a>
|
||||
#### get_dict
|
||||
```python
|
||||
def get_dict(exclude: set = None, include: set = None) -> dict
|
||||
```
|
||||
Returns class attributes as a dict, with the ability to filter
|
||||
Sets only attributes that are annotated on the class body. Logs a debug message for unknown or
|
||||
non-convertible attributes.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|------------------------------------|
|
||||
| `exclude` | `set` | A set of attributes to be excluded |
|
||||
| `include` | `set` | Specific attributes to be returned |
|
||||
#### `annotations` *(property)*
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------------|
|
||||
| `dict` | A dictionary of specified class attributes |
|
||||
Merged `__annotations__` from all ancestor classes.
|
||||
|
||||
#### Notes:
|
||||
You can only set either of include or exclude. If you set both, include will take precedence
|
||||
#### `class_vars` *(property)*
|
||||
|
||||
Annotated class-level attributes from the full MRO.
|
||||
|
||||
<a id="base.class_vars"></a>
|
||||
### class_vars
|
||||
```python
|
||||
@property
|
||||
@cache
|
||||
def class_vars()
|
||||
```
|
||||
Annotated class attributes
|
||||
#### `dict` *(property)*
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|-------------------------------------------------------------------------------------------|
|
||||
| `dict` | A dictionary of available class attributes in all ancestor classes and the current class. |
|
||||
All instance and class attributes as a dictionary, excluding those in `exclude`.
|
||||
|
||||
#### `get_dict(exclude=None, include=None)`
|
||||
|
||||
<a id="base.dict"></a>
|
||||
### dict
|
||||
```python
|
||||
@property
|
||||
def dict() -> dict
|
||||
```
|
||||
All instance and class attributes as a dictionary, except those excluded in the Meta class.
|
||||
Returns a filtered dictionary. If both `include` and `exclude` are provided, `include` takes precedence.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|-----------------------------------------------|
|
||||
| `dict` | A dictionary of instance and class attributes |
|
||||
#### `__repr__()`
|
||||
|
||||
Shows up to 3 key attributes; appends `...` with the last attribute if there are more.
|
||||
|
||||
<a id="_base._base></a>
|
||||
### _Base(Base)
|
||||
Base class that provides access to the MetaTrader and Config classes as well as the MetaBackTester class for
|
||||
backtesting mode.
|
||||
---
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|----------|--------------|-------------------------------------|---------|
|
||||
| `mt5` | `MetaTrader` | An instance of the MetaTrader class | |
|
||||
| `config` | `Config` | An instance of the Config class | |
|
||||
### `_Base`
|
||||
|
||||
> Extended base class with `MetaTrader` and `Config` integration.
|
||||
|
||||
Inherits from `Base` with `BaseMeta` as its metaclass.
|
||||
|
||||
| Attribute | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `mt5` | `MetaTrader \| MetaTraderSync` | — | The MetaTrader interface (auto-initialised) |
|
||||
| `config` | `Config` | — | The global configuration instance |
|
||||
| `mode` | `Literal["async", "sync"]` | `"async"` | Determines which MetaTrader variant is used |
|
||||
|
||||
#### `__getstate__()`
|
||||
|
||||
Removes the `mt5` attribute before pickling to avoid serialization issues.
|
||||
|
||||
+72
-95
@@ -1,110 +1,87 @@
|
||||
# Config
|
||||
# config
|
||||
|
||||
## Table of Contents
|
||||
- [Config](#config.config)
|
||||
- [account_info](#config.account_info)
|
||||
- [backtest_engine](#config.backtest_engine)
|
||||
- [set_attributes](#config.set_attributes)
|
||||
- [load_config](#config.load_config)
|
||||
|
||||
`aiomql.core.config` — Singleton configuration manager for the aiomql package.
|
||||
|
||||
<a id="config.config"></a>
|
||||
```python
|
||||
class Config
|
||||
```
|
||||
The global config object. It is a singleton class for handling configuration settings for the aiomql package.
|
||||
A single instance of this class is created and used per bot instance.
|
||||
## Overview
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|--------------------------------|-------------------------------|-------------------------------------------------------------------------|
|
||||
| `login` | `int` | The account login number |
|
||||
| `trade_record_mode` | `Literal["csv", "json"]` | The mode for recording trades |
|
||||
| `password` | `str` | The account password |
|
||||
| `server` | `str` | The account server |
|
||||
| `path` | `str \| Path` | The path to the terminal |
|
||||
| `timeout` | `int` | The timeout argument for the terminal |
|
||||
| `filename` | `str` | The filename of the config file |
|
||||
| `state` | `dict` | The state of the configuration |
|
||||
| `root` | `Path` | The root directory of the project |
|
||||
| `record_trades` | `bool` | To record trades or not. Default is True |
|
||||
| `records_dir` | `Path` | The directory to store trade records, relative to the root directory |
|
||||
| `plots_dir` | `Path` | Save chart plots as images |
|
||||
| `backtest_dir` | `Path` | The directory to store backtest results, relative to the root directory |
|
||||
| `task_queue` | `TaskQueue` | The TaskQueue object for handling background tasks |
|
||||
| `_backtest_engine` | `BackTestEngine` | The backtest engine object |
|
||||
| `bot` | `Bot` | The bot object |
|
||||
| `_instance` | `Self` | The instance of the Config class |
|
||||
| `mode` | `Literal["backtest", "live"]` | The trading mode, either backtest or live, default is live |
|
||||
| `use_terminal_for_backtesting` | `bool` | Use the terminal for backtesting, default is True |
|
||||
| `shutdown` | `bool` | A signal to shut down the terminal, default is False |
|
||||
| `force_shutdown` | `bool` | A signal to force shut down the terminal, default is False |
|
||||
The `Config` class manages all runtime settings — login credentials, paths, database names,
|
||||
trade-recording preferences, and shutdown signals. It implements the singleton pattern and can
|
||||
load values from a JSON file (default `aiomql.json`) or be configured programmatically.
|
||||
|
||||
#### Notes:
|
||||
By default, the config class looks for a file named aiomql.json. This can be changed by setting the filename
|
||||
attribute to the desired file name. The root directory of the project can be set by passing the root argument
|
||||
to the load_config method or during object instantiation. If not provided it is assumed to be the current working
|
||||
directory. All directories and files are assumed to be relative to the root directory except when an absolute path
|
||||
is provided, this includes the config file, the records_dir and the backtest_dir attributes.
|
||||
The root directory is used to locate the config file and to set the records_dir and backtest_dir attributes.
|
||||
## Classes
|
||||
|
||||
### `Config`
|
||||
|
||||
<a id="config.account_info"></a>
|
||||
### account_info
|
||||
```python
|
||||
def account_info() -> dict['login', 'password', 'server']
|
||||
```
|
||||
Returns Account login details as found in the config object if available
|
||||
> Singleton configuration class.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------------------------------|-------------------------------------------------------|
|
||||
| `dict['login', 'password', 'server']` | A dictionary with login, password, and server details |
|
||||
#### Key Attributes
|
||||
|
||||
<a id="config.backtest_engine"></a>
|
||||
### backtest_engine
|
||||
```python
|
||||
@property
|
||||
def backtest_engine(self)
|
||||
```
|
||||
Returns the backtest engine object.
|
||||
| Attribute | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `login` | `int` | `None` | MetaTrader account number |
|
||||
| `password` | `str` | `""` | Account password |
|
||||
| `server` | `str` | `""` | Account server name |
|
||||
| `path` | `str \| Path` | `""` | Path to the MT5 terminal executable |
|
||||
| `timeout` | `int` | `60000` | Connection timeout (ms) |
|
||||
| `filename` | `str` | `"aiomql.json"` | Config file name to search for |
|
||||
| `root` | `Path` | CWD | Project root directory |
|
||||
| `trade_record_mode` | `Literal["csv","json","sql"]` | `"sql"` | Trade recording format |
|
||||
| `record_trades` | `bool` | `True` | Enable/disable trade recording |
|
||||
| `records_dir_name` | `str` | `"trade_records"` | Trade records directory name |
|
||||
| `db_dir_name` | `str` | `"db"` | Database directory name |
|
||||
| `db_name` | `str \| Path` | `""` | SQLite database file name |
|
||||
| `shutdown` | `bool` | `False` | Graceful shutdown signal |
|
||||
| `force_shutdown` | `bool` | `False` | Forced shutdown signal |
|
||||
| `stop_trading` | `bool` | `False` | Stop opening new trades |
|
||||
| `db_commit_interval` | `float` | `30` | Database commit interval (seconds) |
|
||||
| `auto_commit` | `bool` | `False` | Auto-commit database changes |
|
||||
| `flush_state` | `bool` | `False` | Flush state on init |
|
||||
| `state` | `State` | — | Persistent key-value store |
|
||||
| `store` | `Store` | — | Key-value database store |
|
||||
| `task_queue` | `TaskQueue` | — | Background task queue |
|
||||
| `bot` | `Bot` | `None` | Associated bot instance |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------------------|----------------------------|
|
||||
| `BackTestEngine` | The backtest engine object |
|
||||
#### `__init__(**kwargs)`
|
||||
|
||||
Loads the config file and sets attributes. If already initialised and no `root` or
|
||||
`config_file` is provided, only the extra `kwargs` are applied.
|
||||
|
||||
<a id="config.backtest_engine.setter"></a>
|
||||
```python
|
||||
@backtest_engine.setter
|
||||
def backtest_engine(self, value: BackTestEngine)
|
||||
```
|
||||
Sets the backtest engine object.
|
||||
#### `load_config(*, config_file=None, filename=None, root=None, **kwargs)`
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|---------|------------------|----------------------------|
|
||||
| `value` | `BackTestEngine` | The backtest engine object |
|
||||
Sets the project root, locates/loads the JSON config file, initialises the database,
|
||||
and applies all settings. Returns `self` for chaining.
|
||||
|
||||
<a id="config.set_attributes"></a>
|
||||
### set_attributes
|
||||
```python
|
||||
def set_attributes(self, **kwargs)
|
||||
```
|
||||
Set attributes on the config object. The root folder attribute can't be set here.
|
||||
#### `set_root(root=None)`
|
||||
|
||||
<a id="config.load_config"></a>
|
||||
### load_config
|
||||
```python
|
||||
def load_config(*, config_file: str | Path = None, filename: str = None, root: str | Path = None, **kwargs) -> Config
|
||||
```
|
||||
Load configuration settings from a file and reset the config object.
|
||||
Resolves and creates the project root directory. Falls back to CWD.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|---------------|---------------|----------------------------------------------------------------------------------------------------|
|
||||
| `config_file` | `str \| Path` | The absolute path to the config file. |
|
||||
| `filename` | `str` | The name of the file to load if file path is not specified. If not provided `aiomql.json` is used. |
|
||||
| `root` | `str` | The root directory of the project. |
|
||||
| `**kwargs` | `dict` | Additional keyword arguments to be set on the config object. |
|
||||
#### `find_config_file()`
|
||||
|
||||
Searches up from CWD through parent directories for the config filename.
|
||||
|
||||
**Returns:** `Path | None`
|
||||
|
||||
#### `set_attributes(**kwargs)`
|
||||
|
||||
Sets attributes, but prevents `root` and `config_file` from being changed here
|
||||
(use `load_config` instead).
|
||||
|
||||
#### `state` *(property)*
|
||||
|
||||
Lazily initialised `State` instance.
|
||||
|
||||
#### `store` *(property)*
|
||||
|
||||
Lazily initialised `Store` instance.
|
||||
|
||||
#### `records_dir` *(cached property)*
|
||||
|
||||
Path to the trade records directory. Created on first access.
|
||||
|
||||
#### `plots_dir` *(cached property)*
|
||||
|
||||
Path to the plots directory. Created on first access.
|
||||
|
||||
#### `account_info` *(property)*
|
||||
|
||||
Returns `{"login": …, "password": …, "server": …}`.
|
||||
|
||||
+111
-539
@@ -1,582 +1,154 @@
|
||||
# Constants
|
||||
MetaTrader 5 constants defined as Enums.
|
||||
# constants
|
||||
|
||||
## Table of Contents
|
||||
- [TradeAction](#TradeAction)
|
||||
- [OrderFilling](#OrderFilling)
|
||||
- [OrderTime](#OrderTime)
|
||||
- [OrderType](#OrderType)
|
||||
- [opposite](#ordertype.opposite)
|
||||
- [BookType](#BookType)
|
||||
- [TimeFrame](#TimeFrame)
|
||||
- [get_timeframe](#timeframe.get_timeframe)
|
||||
- [seconds](#timeframe.seconds)
|
||||
- [all](#timeframe.all)
|
||||
- [CopyTicks](#CopyTicks)
|
||||
- [PositionType](#PositionType)
|
||||
- [PositionReason](#PositionReason)
|
||||
- [DealType](#DealType)
|
||||
- [DealEntry](#DealEntry)
|
||||
- [DealReason](#DealReason)
|
||||
- [OrderReason](#OrderReason)
|
||||
- [SymbolChartMode](#SymbolChartMode)
|
||||
- [SymbolCalcMode](#SymbolCalcMode)
|
||||
- [SymbolTradeMode](#SymbolTradeMode)
|
||||
- [SymbolTradeExecution](#SymbolTradeExecution)
|
||||
- [SymbolSwapMode](#SymbolSwapMode)
|
||||
- [DayOfWeek](#DayOfWeek)
|
||||
- [SymbolOrderGTCMode](#SymbolOrderGTCMode)
|
||||
- [SymbolOptionRight](#SymbolOptionRight)
|
||||
- [SymbolOptionMode](#SymbolOptionMode)
|
||||
- [AccountTradeMode](#AccountTradeMode)
|
||||
- [TickFlag](#TickFlag)
|
||||
- [TradeRetcode](#TradeRetcode)
|
||||
- [AccountStopOutMode](#AccountStopOutMode)
|
||||
- [AccountMarginMode](#AccountMarginMode)
|
||||
`aiomql.core.constants` — MetaTrader 5 constants as Pythonic `IntEnum` types.
|
||||
|
||||
<a id="TradeAction"></a>
|
||||
## TradeAction
|
||||
```python
|
||||
class TradeAction(Repr, IntEnum)
|
||||
```
|
||||
The TRADE_REQUEST_ACTION Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------|-------|----------------------------------------------------------------------------------------------|
|
||||
| `DEAL` | 0 | Place a trade order for an immediate execution with the specified parameters (market order). |
|
||||
| `PENDING` | 1 | Place a pending order with the specified parameters. |
|
||||
| `SLTP` | 2 | Modify Stop Loss and Take Profit values of an opened position. |
|
||||
| `MODIFY` | 3 | Modify the parameters of the order placed previously. |
|
||||
| `REMOVE` | 4 | Delete the pending order placed previously. |
|
||||
| `CLOSE_BY` | 5 | Close a position by an opposite one. |
|
||||
## Overview
|
||||
|
||||
<a id="OrderFilling"></a>
|
||||
## OrderFilling
|
||||
```python
|
||||
class OrderFilling(Repr, IntEnum)
|
||||
```
|
||||
ORDER_TYPE_FILLING Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `FILL` | 0 | This execution policy means that an order can be executed only in the specified volume. If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be executed. The desired volume can be made up of several available offers. |
|
||||
| `FOK` | 1 | This execution policy means that an order can be executed only in the specified volume. If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be executed. The desired volume can be made up of several available offers. |
|
||||
| `IOC` | 2 | An agreement to execute a deal at the maximum volume available in the market within the volume specified in the order. If the request cannot be filled completely, an order with the available volume will be executed, and the remaining volume will be canceled. |
|
||||
| `RETURN` | 3 | This policy is used only for market (ORDER_TYPE_BUY and ORDER_TYPE_SELL), limit and stop limit orders (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT,ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT) and only for the symbols with Market or Exchange execution modes. If filled partially, a market or limit order with the remaining volume is not canceled, and is processed further. During activation of the ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT orders, an appropriate limit order ORDER_TYPE_BUY_LIMIT/ORDER_TYPE_SELL_LIMIT with the ORDER_FILLING_RETURN type is created. |
|
||||
Wraps every MT5 constant group into a typed Python enum. Each enum inherits from `Repr`
|
||||
(which provides MT5-style `__str__`) and `IntEnum`, giving both type safety and integer
|
||||
interoperability with the MT5 API.
|
||||
|
||||
<a id="OrderTime"></a>
|
||||
## OrderTime
|
||||
```python
|
||||
class OrderTime(Repr, IntEnum)
|
||||
```
|
||||
ORDER_TIME Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-----------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GTC` | 0 | Good till cancel order |
|
||||
| `DAY` | 1 | Good till current trade day order |
|
||||
| `SPECIFIED` | 2 | The order is active until the specified date |
|
||||
| `SPECIFIED_DAY` | 3 | The order is active until 23:59:59 of the specified day. If this time appears to be out of a trading session, the expiration is processed at the nearest trading time. |
|
||||
## Classes
|
||||
|
||||
<a id="OrderType"></a>
|
||||
## OrderType
|
||||
```python
|
||||
class OrderType(Repr, IntEnum)
|
||||
```
|
||||
ORDER_TYPE Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-------------------|-------|--------------------------------------------------------------------------------------|
|
||||
| `BUY` | 0 | Market buy order |
|
||||
| `SELL` | 1 | Market sell order |
|
||||
| `BUY_LIMIT` | 2 | Buy Limit pending order |
|
||||
| `SELL_LIMIT` | 3 | Sell Limit pending order |
|
||||
| `BUY_STOP` | 4 | Buy Stop pending order |
|
||||
| `SELL_STOP` | 5 | Sell Stop pending order |
|
||||
| `BUY_STOP_LIMIT` | 6 | Upon reaching the order price, Buy Limit pending order is placed at StopLimit price |
|
||||
| `SELL_STOP_LIMIT` | 7 | Upon reaching the order price, Sell Limit pending order is placed at StopLimit price |
|
||||
| `CLOSE_BY` | 8 | Order for closing a position by an opposite one |
|
||||
### `Repr`
|
||||
|
||||
### Properties
|
||||
| Name | Description |
|
||||
|------------|------------------------------------|
|
||||
| `opposite` | Gets the opposite of an order type |
|
||||
> Mixin that formats enum values as `{__enum_name__}_{name}`.
|
||||
|
||||
<a id="ordertype.opposite"></a>
|
||||
#### opposite
|
||||
```python
|
||||
@property
|
||||
def opposite()
|
||||
```
|
||||
Gets the opposite of an order type for closing an open position
|
||||
#### Returns
|
||||
| Type | Description |
|
||||
|------|--------------------------------------|
|
||||
| int | integer value of opposite order type |
|
||||
---
|
||||
|
||||
<a id="BookType"></a>
|
||||
## BookType
|
||||
```python
|
||||
class BookType(Repr, IntEnum)
|
||||
```
|
||||
BOOK_TYPE Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|---------------|-------|----------------------|
|
||||
| `SELL` | 0 | Sell order (Offer) |
|
||||
| `BUY` | 1 | Buy order (Bid) |
|
||||
| `SELL_MARKET` | 2 | Sell order by Market |
|
||||
| `BUY_MARKET` | 3 | Buy order by Market |
|
||||
### `TradeAction`
|
||||
|
||||
<a id="TimeFrame"></a>
|
||||
## TimeFrame
|
||||
```python
|
||||
class TimeFrame(Repr, IntEnum)
|
||||
```
|
||||
TIMEFRAME Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-------|---------|-----------------|
|
||||
| `M1` | 60 | One Minute |
|
||||
| `M2` | 120 | Two Minutes |
|
||||
| `M3` | 180 | Three Minutes |
|
||||
| `M4` | 240 | Four Minutes |
|
||||
| `M5` | 300 | Five Minutes |
|
||||
| `M6` | 360 | Six Minutes |
|
||||
| `M10` | 600 | Ten Minutes |
|
||||
| `M15` | 900 | Fifteen Minutes |
|
||||
| `M20` | 1200 | Twenty Minutes |
|
||||
| `M30` | 1800 | Thirty Minutes |
|
||||
| `H1` | 3600 | One Hour |
|
||||
| `H2` | 7200 | Two Hours |
|
||||
| `H3` | 10800 | Three Hours |
|
||||
| `H4` | 14400 | Four Hours |
|
||||
| `H6` | 21600 | Six Hours |
|
||||
| `H8` | 28800 | Eight Hours |
|
||||
| `D1` | 86400 | One Day |
|
||||
| `W1` | 604800 | One Week |
|
||||
| `MN1` | 2592000 | One Month |
|
||||
> Trade request actions (`TRADE_ACTION_*`).
|
||||
|
||||
| Member | Description |
|
||||
|--------|-------------|
|
||||
| `DEAL` | Immediate market order |
|
||||
| `PENDING` | Conditional pending order |
|
||||
| `SLTP` | Modify SL/TP of an open position |
|
||||
| `MODIFY` | Modify a pending order |
|
||||
| `REMOVE` | Delete a pending order |
|
||||
| `CLOSE_BY` | Close by an opposite position |
|
||||
|
||||
<a id="timeframe.seconds"></a>
|
||||
### seconds
|
||||
```python
|
||||
@property
|
||||
def seconds() -> int
|
||||
```
|
||||
The number of seconds in a TIMEFRAME
|
||||
---
|
||||
|
||||
### `OrderFilling`
|
||||
|
||||
<a id="timeframe.get_timeframe"></a>
|
||||
#### get_timeframe
|
||||
```python
|
||||
@property
|
||||
def get_timeframe()
|
||||
```
|
||||
Get a timeframe object from a time value in seconds
|
||||
> Order filling policies (`ORDER_FILLING_*`).
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------|-----------------------------|
|
||||
| TimeFrame | The corresponding timeframe |
|
||||
`FOK` · `IOC` · `RETURN`
|
||||
|
||||
---
|
||||
|
||||
<a id="timeframe.all"></a>
|
||||
#### all
|
||||
```python
|
||||
@classmethod
|
||||
def all()
|
||||
```
|
||||
Get all the timeframes
|
||||
### `OrderTime`
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------------|-----------------------------|
|
||||
| tuple[TimeFrame, ...] | All the timeframes |
|
||||
> Time-in-force policies (`ORDER_TIME_*`).
|
||||
|
||||
`GTC` · `DAY` · `SPECIFIED` · `SPECIFIED_DAY`
|
||||
|
||||
<a id="CopyTicks"></a>
|
||||
## CopyTicks
|
||||
```python
|
||||
class CopyTicks(Repr, IntEnum)
|
||||
```
|
||||
COPY_TICKS Enum. This defines the types of ticks that can be requested using the copy_ticks_from() and
|
||||
copy_ticks_range() functions.
|
||||
---
|
||||
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|---------|-------|---------------------------------------------------|
|
||||
| `ALL` | 0 | All ticks |
|
||||
| `INFO` | 1 | Ticks containing Bid and/or Ask price changes |
|
||||
| `TRADE` | 2 | Ticks containing Last and/or Volume price changes |
|
||||
### `OrderType`
|
||||
|
||||
<a id="PositionType"></a>
|
||||
## PositionType
|
||||
```python
|
||||
class PositionType(Repr, IntEnum)
|
||||
```
|
||||
POSITION_TYPE Enum. Direction of an open position (buy or sell)
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|--------|-------|-------------|
|
||||
| `BUY` | 0 | Buy |
|
||||
| `SELL` | 1 | Sell |
|
||||
> Order types (`ORDER_TYPE_*`).
|
||||
|
||||
<a id="PositionReason"></a>
|
||||
## PositionReason
|
||||
```python
|
||||
class PositionReason(Repr, IntEnum)
|
||||
```
|
||||
POSITION_REASON Enum. The reason for opening a position is contained in the POSITION_REASON Enum
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------|-------|------------------------------------------------------------------------------------------------|
|
||||
| `CLIENT` | 0 | The position was opened as a result of activation of an order placed from a desktop terminal |
|
||||
| `MOBILE` | 1 | The position was opened as a result of activation of an order placed from a mobile application |
|
||||
| `WEB` | 2 | The position was opened as a result of activation of an order placed from the web platform |
|
||||
| `EXPERT` | 3 | The position was opened as a result of activation of an order placed from an MQL5 program |
|
||||
`BUY` · `SELL` · `BUY_LIMIT` · `SELL_LIMIT` · `BUY_STOP` · `SELL_STOP` · `BUY_STOP_LIMIT` · `SELL_STOP_LIMIT` · `CLOSE_BY`
|
||||
|
||||
<a id="DealType"></a>
|
||||
## DealType
|
||||
```python
|
||||
class DealType(Repr, IntEnum)
|
||||
```
|
||||
DEAL_TYPE enum. Each deal is characterized by a type, allowed values are enumerated in this enum
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `BUY` | 0 | Buy |
|
||||
| `SELL` | 1 | Sell |
|
||||
| `BALANCE` | 2 | Balance |
|
||||
| `CREDIT` | 3 | Credit |
|
||||
| `CHARGE` | 4 | Additional Charge |
|
||||
| `CORRECTION` | 5 | Correction |
|
||||
| `BONUS` | 6 | Bonus |
|
||||
| `COMMISSION` | 7 | Additional Commission |
|
||||
| `COMMISSION_DAILY` | 8 | Daily Commission |
|
||||
| `COMMISSION_MONTHLY` | 9 | Monthly Commission |
|
||||
| `COMMISSION_AGENT_DAILY` | 10 | Daily Agent Commission |
|
||||
| `COMMISSION_AGENT_MONTHLY` | 11 | Monthly Agent Commission |
|
||||
| `INTEREST` | 12 | Interest Rate |
|
||||
| `DEAL_DIVIDEND` | 13 | Dividend Operations |
|
||||
| `DEAL_DIVIDEND_FRANKED` | 14 | Franked (non-taxable) dividend operations |
|
||||
| `DEAL_TAX` | 15 | Tax Charges |
|
||||
| `BUY_CANCELED` | 16 | Canceled buy deal. There can be a situation when a previously executed buy deal is canceled. In this case, the type of the previously executed deal (DEAL_TYPE_BUY) is changed to DEAL_TYPE_BUY_CANCELED, and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation |
|
||||
| `SELL_CANCELED` | 17 | Canceled sell deal. There can be a situation when a previously executed sell deal is canceled. In this case, the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation. |
|
||||
**Properties:**
|
||||
|
||||
<a id="DealEntry"></a>
|
||||
## DealEntry
|
||||
```python
|
||||
class DealEntry(Repr, IntEnum)
|
||||
```
|
||||
DEAL_ENTRY Enum. Deals differ not only in their types set in DEAL_TYPE enum, but also in the way they change
|
||||
positions. This can be a simple position opening, or accumulation of a previously opened position (market entering),
|
||||
position closing by an opposite deal of a corresponding volume (market exiting), or position reversing, if the
|
||||
opposite-direction deal covers the volume of the previously opened position.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------|-------|-------------------------------------|
|
||||
| `IN` | 0 | Entry In |
|
||||
| `OUT` | 1 | Entry Out |
|
||||
| `INOUT` | 2 | Reverse |
|
||||
| `OUT_BY` | 3 | Close a position by an opposite one |
|
||||
| Property | Returns |
|
||||
|----------|---------|
|
||||
| `opposite` | The opposite order type |
|
||||
| `is_long` | `True` for buy-side types |
|
||||
| `is_short` | `True` for sell-side types |
|
||||
|
||||
<a id="DealReason"></a>
|
||||
## DealReason
|
||||
```python
|
||||
class DealReason(Repr, IntEnum)
|
||||
```
|
||||
DEAL_REASON Enum. The reason for deal execution is contained in the DEAL_REASON property. A deal can be executed
|
||||
as a result of triggering of an order placed from a mobile application or an MQL5 program, as well as as a result
|
||||
of the StopOut event, variation margin calculation, etc.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------|-------|--------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `CLIENT` | 0 | The deal was executed as a result of activation of an order placed from a desktop terminal |
|
||||
| `MOBILE` | 1 | The deal was executed as a result of activation of an order placed from a desktop terminal |
|
||||
| `WEB` | 2 | The deal was executed as a result of activation of an order placed from the web platform |
|
||||
| `EXPERT` | 3 | The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script |
|
||||
| `SL` | 4 | The deal was executed as a result of Stop Loss activation |
|
||||
| `TP` | 5 | The deal was executed as a result of Take Profit activation |
|
||||
| `SO` | 6 | The deal was executed as a result of the Stop Out event |
|
||||
| `ROLLOVER` | 7 | The deal was executed due to a rollover |
|
||||
| `VMARGIN` | 8 | The deal was executed after charging the variation margin |
|
||||
| `SPLIT` | 9 | The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement |
|
||||
---
|
||||
|
||||
<a id="OrderReason"></a>
|
||||
## OrderReason
|
||||
```python
|
||||
class OrderReason(Repr, IntEnum)
|
||||
```
|
||||
ORDER_REASON Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------|-------|----------------------------------------------------------------------------------|
|
||||
| `CLIENT` | 0 | The order was placed from a desktop terminal |
|
||||
| `MOBILE` | 1 | The order was placed from a mobile application |
|
||||
| `WEB` | 2 | The order was placed from a web platform |
|
||||
| `EXPERT` | 3 | The order was placed from an MQL5-program, i.e. by an Expert Advisor or a script |
|
||||
| `SL` | 4 | The order was placed as a result of Stop Loss activation |
|
||||
| `TP` | 5 | The order was placed as a result of Take Profit activation |
|
||||
| `SO` | 6 | The order was placed as a result of the Stop Out event |
|
||||
### `TimeFrame`
|
||||
|
||||
<a id="SymbolChartMode"></a>
|
||||
## SymbolChartMode
|
||||
```python
|
||||
class SymbolChartMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_CHART_MODE Enum. A symbol price chart can be based on Bid or Last prices. The price selected for symbol
|
||||
charts also affects the generation and display of bars in the terminal.
|
||||
Possible values of the SYMBOL_CHART_MODE property are described in this enum
|
||||
> Chart timeframes (`TIMEFRAME_*`).
|
||||
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|--------|-------|-------------------------------|
|
||||
| `BID` | 0 | Bars are based on Bid prices |
|
||||
| `LAST` | 1 | Bars are based on last prices |
|
||||
`M1` · `M2` · `M3` · `M4` · `M5` · `M6` · `M10` · `M15` · `M20` · `M30` · `H1` · `H2` · `H3` · `H4` · `H6` · `H8` · `H12` · `D1` · `W1` · `MN1`
|
||||
|
||||
<a id="SymbolCalcMode"></a>
|
||||
## SymbolCalcMode
|
||||
```python
|
||||
class SymbolCalcMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_CALC_MODE Enum. The SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin
|
||||
requirements for a symbol are calculated.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-----------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `FOREX` | 0 | Forex mode - calculation of profit and margin for Forex |
|
||||
| `FOREX_NO_LEVERAGE` | 1 | Forex No Leverage mode – calculation of profit and margin for Forex symbols without taking into account the leverage |
|
||||
| `FUTURES` | 2 | Futures mode - calculation of margin and profit for futures |
|
||||
| `CFD` | 3 | CFD mode - calculation of margin and profit for CFD |
|
||||
| `CFDINDEX` | 4 | CFD index mode - calculation of margin and profit for CFD by indexes |
|
||||
| `CFDLEVERAGE` | 5 | CFD Leverage mode - calculation of margin and profit for CFD at leverage trading |
|
||||
| `EXCH_STOCKS` | 6 | Calculation of margin and profit for trading securities on a stock exchange |
|
||||
| `EXCH_FUTURES` | 7 | Calculation of margin and profit for trading futures contracts on a stock exchange |
|
||||
| `EXCH_OPTIONS` | 8 | value is 34 |
|
||||
| `EXCH_OPTIONS_MARGIN` | 9 | value is 36 |
|
||||
| `EXCH_BONDS` | 10 | Exchange Bonds mode – calculation of margin and profit for trading bonds on a stock exchange |
|
||||
| `EXCH_STOCKS_MOEX` | 11 | Exchange MOEX Stocks mode –calculation of margin and profit for trading securities on MOEX |
|
||||
| `EXCH_BONDS_MOEX` | 12 | Exchange MOEX Bonds mode – calculation of margin and profit for trading bonds on MOEX |
|
||||
| `SERV_COLLATERAL` | 13 | Collateral mode - a symbol is used as a non-tradable asset on a trading account. The market value of an open position is calculated based on the volume, current market price, contract size and liquidity ratio. The value is included into Assets, which are added to Equity. Open positions of such symbols increase the Free Margin amount and are used as additional margin (collateral) for open positions |
|
||||
| Member / Method | Description |
|
||||
|-----------------|-------------|
|
||||
| `seconds` *(property)* | Duration in seconds (e.g. `H1.seconds` → `3600`) |
|
||||
| `get_timeframe(time)` | Look up a `TimeFrame` from a duration in seconds |
|
||||
| `all` | Tuple of all timeframes |
|
||||
|
||||
---
|
||||
|
||||
<a id="SymbolTradeMode"></a>
|
||||
## SymbolTradeMode
|
||||
```python
|
||||
class SymbolTradeMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_TRADE_MODE Enum. There are several symbol trading modes. Information about trading modes of a certain
|
||||
symbol is reflected in the values this enumeration
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-------------|-------|----------------------------------------|
|
||||
| `DISABLED` | 0 | Trade is disabled for the symbol |
|
||||
| `LONGONLY` | 1 | Allowed only long positions |
|
||||
| `SHORTONLY` | 2 | Allowed only short positions |
|
||||
| `CLOSEONLY` | 3 | Allowed only position close operations |
|
||||
| `FULL` | 4 | No trade restrictions |
|
||||
### `CopyTicks`
|
||||
|
||||
<a id="SymbolTradeExecution"></a>
|
||||
## SymbolTradeExecution
|
||||
```python
|
||||
class SymbolTradeExecution(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_TRADE_EXECUTION Enum. The modes, or execution policies, define the rules for cases when the price has
|
||||
changed or the requested volume cannot be completely fulfilled at the moment.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------|-------|---------------------------------------------------------------------------------------------|
|
||||
| `REQUEST` | 0 | Executing a market order at the price previously received from the broker |
|
||||
| `INSTANT` | 1 | Executing a market order at the specified price immediately |
|
||||
| `MARKET` | 2 | A broker makes a decision about the order execution price without any additional discussion |
|
||||
| `EXCHANGE` | 3 | Trade operations are executed at the prices of the current market offers |
|
||||
> Tick copy modes (`COPY_TICKS_*`).
|
||||
|
||||
<a id="SymbolSwapMode"></a>
|
||||
## SymbolSwapMode
|
||||
```python
|
||||
class SymbolSwapMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_SWAP_MODE Enum. Methods of swap calculation at position transfer are specified in enumeration
|
||||
ENUM_SYMBOL_SWAP_MODE. The method of swap calculation determines the units of measure of the SYMBOL_SWAP_LONG and
|
||||
SYMBOL_SWAP_SHORT parameters. For example, if swaps are charged in the client deposit currency, then the values of
|
||||
those parameters are specified as an amount of money in the client deposit currency.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|--------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `DISABLED` | 0 | Swaps disabled (no swaps) |
|
||||
| `POINTS` | 1 | Swaps are charged in points |
|
||||
| `CURRENCY_SYMBOL` | 2 | Swaps are charged in money in base currency of the symbol |
|
||||
| `CURRENCY_MARGIN` | 3 | Swaps are charged in money in margin currency of the symbol |
|
||||
| `CURRENCY_DEPOSIT` | 4 | Swaps are charged in money, in client deposit currency |
|
||||
| `INTEREST_CURRENT` | 5 | Swaps are charged as the specified annual interest from the instrument price at calculation of swap (standard bank year is 360 days) |
|
||||
| `INTEREST_OPEN` | 6 | Swaps are charged as the specified annual interest from the open price of position (standard bank year is 360 days) |
|
||||
| `REOPEN_CURRENT` | 7 | Swaps are charged by reopening positions. At the end of a trading day the position is closed. Next day it is reopened by the close price +/- specified number of points (parameters SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT) |
|
||||
| `REOPEN_BID` | 8 | Swaps are charged by reopening positions. At the end of a trading day the position is closed. Next day it is reopened by the current Bid price +/- specified number of points (parameters SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT) |
|
||||
`ALL` · `INFO` · `TRADE`
|
||||
|
||||
<a id="DayOfWeek"></a>
|
||||
## DayOfWeek
|
||||
```python
|
||||
class DayOfWeek(Repr, IntEnum)
|
||||
```
|
||||
DAY_OF_WEEK Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-------------|-------|-------------|
|
||||
| `SUNDAY` | 0 | Sunday |
|
||||
| `MONDAY` | 1 | Monday |
|
||||
| `TUESDAY` | 2 | Tuesday |
|
||||
| `WEDNESDAY` | 3 | Wednesday |
|
||||
| `THURSDAY` | 4 | Thursday |
|
||||
| `FRIDAY` | 5 | Friday |
|
||||
| `SATURDAY` | 6 | Saturday |
|
||||
---
|
||||
|
||||
### `PositionType`
|
||||
|
||||
<a id="SymbolOrderGTCMode"></a>
|
||||
## SymbolOrderGTCMode
|
||||
```python
|
||||
class SymbolOrderGTCMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_ORDER_GTC_MODE Enum. If the SYMBOL_EXPIRATION_MODE property is set to SYMBOL_EXPIRATION_GTC
|
||||
(good till canceled), the expiration of pending orders, as well as of
|
||||
Stop Loss/Take Profit orders should be additionally set using the ENUM_SYMBOL_ORDER_GTC_MODE enumeration.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GTC` | 0 | Pending orders and Stop Loss/Take Profit levels are valid for an unlimited period |
|
||||
| `DAILY` | 1 | Orders are valid during one trading day. At the end of the day, all Stop Loss and Take Profit levels, as well as pending orders are deleted. |
|
||||
| `DAILY_NO_STOPS` | 2 | When a trade day changes, only pending orders are deleted, while Stop Loss and Take Profit levels are preserved |
|
||||
> Position direction (`POSITION_TYPE_*`).
|
||||
|
||||
<a id="SymbolOptionRight"></a>
|
||||
## SymbolOptionRight
|
||||
```python
|
||||
class SymbolOptionRight(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_OPTION_RIGHT Enum. An option is a contract, which gives the right, but not the obligation,
|
||||
to buy or sell an underlying asset (goods, stocks, futures, etc.) at a specified price on or before a specific date.
|
||||
The following enumerations describe option properties, including the option type and the right arising from it.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|--------|-------|-----------------------------------------------------------------------------------------------|
|
||||
| `CALL` | 0 | A call option gives you the right to buy an asset at a specified price. |
|
||||
| `PUT` | 1 | A put option gives you the right to sell an asset at a specified price. |
|
||||
`BUY` · `SELL`
|
||||
|
||||
<a id="SymbolOptionMode"></a>
|
||||
## SymbolOptionMode
|
||||
```python
|
||||
class SymbolOptionMode(Repr, IntEnum)
|
||||
```
|
||||
SYMBOL_OPTION_MODE Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `EUROPEAN` | 0 | European option may only be exercised on a specified date (expiration, execution date, delivery date) |
|
||||
| `AMERICAN` | 1 | American option may be exercised on any trading day or before expiry. The period within which a buyer can exercise the option is specified for it. |
|
||||
---
|
||||
|
||||
<a id="AccountTradeMode"></a>
|
||||
## AccountTradeMode
|
||||
```python
|
||||
class AccountTradeMode(Repr, IntEnum)
|
||||
```
|
||||
ACCOUNT_TRADE_MODE Enum. There are several types of accounts that can be opened on a trade server.
|
||||
The type of account on which an MQL5 program is running can be found out using
|
||||
the ENUM_ACCOUNT_TRADE_MODE enumeration.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-----------|-------|-----------------|
|
||||
| `DEMO` | 0 | Demo account |
|
||||
| `CONTEST` | 1 | Contest account |
|
||||
| `REAL` | 2 | Real Account |
|
||||
### `PositionReason`
|
||||
|
||||
<a id="TickFlag"></a>
|
||||
## TickFlag
|
||||
```python
|
||||
class TickFlag(Repr, IntFlag)
|
||||
```
|
||||
TICK_FLAG Enum. TICK_FLAG defines possible flags for ticks. These flags are used to describe ticks obtained by the
|
||||
copy_ticks_from() and copy_ticks_range() functions.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|----------|-------|-------------------------|
|
||||
| `BID` | 2 | Bid price changed |
|
||||
| `ASK` | 4 | Ask price changed |
|
||||
| `LAST` | 8 | Last price changed |
|
||||
| `VOLUME` | 16 | Volume changed |
|
||||
| `BUY` | 32 | last Buy price changed |
|
||||
| `SELL` | 64 | last Sell price changed |
|
||||
> Reason for opening a position (`POSITION_REASON_*`).
|
||||
|
||||
<a id="TradeRetcode"></a>
|
||||
## TradeRetcode
|
||||
```python
|
||||
class TradeRetcode(Repr, IntEnum)
|
||||
```
|
||||
TRADE_RETCODE Enum. Return codes for order send/check operations
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `OK` | 10009 | OK |
|
||||
| `REQUOTE` | 10004 | Requote |
|
||||
| `REJECT` | 10006 | Reject |
|
||||
| `CANCEL` | 10007 | Cancel |
|
||||
| `PLACED` | 10008 | Placed |
|
||||
| `DONE` | 10009 | Done |
|
||||
| `DONE_PARTIAL` | 10010 | Done Partial |
|
||||
| `ERROR` | 10011 | Error |
|
||||
| `TIMEOUT` | 10012 | Timeout |
|
||||
| `INVALID` | 10013 | Invalid |
|
||||
| `INVALID_VOLUME` | 10014 | Invalid Volume |
|
||||
| `INVALID_PRICE` | 10015 | Invalid Price |
|
||||
| `INVALID_STOPS` | 10016 | Invalid Stops |
|
||||
| `TRADE_DISABLED` | 10017 | Trade is disabled |
|
||||
| `MARKET_CLOSED` | 10018 | Market is closed |
|
||||
| `NO_MONEY` | 10019 | No money |
|
||||
| `PRICE_CHANGED` | 10020 | Price changed |
|
||||
| `PRICE_OFF` | 10021 | Price off |
|
||||
| `INVALID_EXPIRATION` | 10022 | Invalid expiration |
|
||||
| `ORDER_CHANGED` | 10023 | Order state changed |
|
||||
| `TOO_MANY_REQUESTS` | 10024 | Too frequent requests |
|
||||
| `NO_CHANGES` | 10025 | No changes in request |
|
||||
| `SERVER_DISABLES_AT` | 10026 | Autotrading disabled by server |
|
||||
| `CLIENT_DISABLES_AT` | 10027 | Autotrading disabled by client terminal |
|
||||
| `LOCKED` | 10028 | Request locked for processing |
|
||||
| `FROZEN` | 10029 | Order or position frozen |
|
||||
| `INVALID_FILL` | 10030 | Invalid order filling type |
|
||||
| `CONNECTION` | 10031 | No connection with the trade server |
|
||||
| `ONLY_REAL` | 10032 | Operation is allowed only for live accounts |
|
||||
| `LIMIT_ORDERS` | 10033 | The number of pending orders has reached the limit |
|
||||
| `LIMIT_VOLUME` | 10034 | The volume of orders and positions for the symbol has reached the limit |
|
||||
| `INVALID_ORDER` | 10035 | Incorrect or prohibited order type |
|
||||
| `POSITION_CLOSED` | 10036 | Position with the specified POSITION_IDENTIFIER has already been closed |
|
||||
| `INVALID_CLOSE_VOLUME` | 10037 | A close volume exceeds the current position volume |
|
||||
| `CLOSE_ORDER_EXIST` | 10038 | A close order already exists for a specified position. This may happen when working in the hedging system |
|
||||
| `LIMIT_POSITIONS` | 10039 | The number of open positions simultaneously present on an account can be limited by the server settings |
|
||||
| `REJECT_CANCEL` | 10040 | The pending order activation request is rejected, the order is canceled |
|
||||
| `LONG_ONLY` | 10041 | The request is rejected, because the "Only long positions are allowed" rule is set for the symbol (POSITION_TYPE_BUY) |
|
||||
| `SHORT_ONLY` | 10042 | The request is rejected, because the "Only short positions are allowed" rule is set for the symbol (POSITION_TYPE_SELL) |
|
||||
| `CLOSE_ONLY` | 10043 | The request is rejected, because the "Only position closing is allowed" rule is set for the symbol |
|
||||
| `FIFO_CLOSE` | 10044 | The request is rejected, because "Position closing is allowed only by FIFO rule" flag is set for the trading account (ACCOUNT_FIFO_CLOSE=true) |
|
||||
`CLIENT` · `MOBILE` · `WEB` · `EXPERT`
|
||||
|
||||
<a id="AccountStopOutMode"></a>
|
||||
## AccountStopOutMode
|
||||
```python
|
||||
class AccountStopOutMode(Repr, IntEnum)
|
||||
```
|
||||
ACCOUNT_STOPOUT_MODE Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|-----------|-------|-----------------------------------|
|
||||
| `PERCENT` | 0 | Account stop out mode in percents |
|
||||
| `MONEY` | 1 | Account stop out mode in money |
|
||||
---
|
||||
|
||||
<a id="AccountMarginMode"></a>
|
||||
## AccountMarginMode
|
||||
```python
|
||||
class AccountMarginMode(Repr, IntEnum)
|
||||
```
|
||||
ACCOUNT_MARGIN_MODE Enum.
|
||||
### Members
|
||||
| Name | Value | Description |
|
||||
|------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `RETAIL_NETTING` | 0 | Used for the OTC markets to interpret positions in the "netting" mode (only one position can exist for one symbol). The margin is calculated based on the symbol type (SYMBOL_TRADE_CALC_MODE). |
|
||||
| `EXCHANGE` | 1 | Used for the exchange markets. Margin is calculated based on the discounts specified in symbol settings. Discounts are set by the broker, but not less than the values set by the exchange. |
|
||||
| `RETAIL_HEDGING` | 2 | Used for the exchange markets where individual positions are possible (hedging, multiple positions can exist for one symbol). The margin is calculated based on the symbol type (SYMBOL_TRADE_CALC_MODE) taking into account the hedged margin (SYMBOL_MARGIN_HEDGED). |
|
||||
### `DealType`
|
||||
|
||||
> Deal types (`DEAL_TYPE_*`).
|
||||
|
||||
`BUY` · `SELL` · `BALANCE` · `CREDIT` · `CHARGE` · `CORRECTION` · `BONUS` · `COMMISSION` · `COMMISSION_DAILY` · `COMMISSION_MONTHLY` · `COMMISSION_AGENT_DAILY` · `COMMISSION_AGENT_MONTHLY` · `INTEREST` · `BUY_CANCELED` · `SELL_CANCELED` · `DEAL_DIVIDEND` · `DEAL_DIVIDEND_FRANKED` · `DEAL_TAX`
|
||||
|
||||
---
|
||||
|
||||
### `DealEntry`
|
||||
|
||||
> Deal entry direction (`DEAL_ENTRY_*`).
|
||||
|
||||
`IN` · `OUT` · `INOUT` · `OUT_BY`
|
||||
|
||||
---
|
||||
|
||||
### `DealReason`
|
||||
|
||||
> Reason for deal execution (`DEAL_REASON_*`).
|
||||
|
||||
`CLIENT` · `MOBILE` · `WEB` · `EXPERT` · `SL` · `TP` · `SO` · `ROLLOVER` · `VMARGIN` · `SPLIT`
|
||||
|
||||
---
|
||||
|
||||
### `OrderReason`
|
||||
|
||||
> Reason for placing an order (`ORDER_REASON_*`).
|
||||
|
||||
`CLIENT` · `MOBILE` · `WEB` · `EXPERT` · `SL` · `TP` · `SO`
|
||||
|
||||
---
|
||||
|
||||
### Other Enums
|
||||
|
||||
| Enum | Members |
|
||||
|------|---------|
|
||||
| `BookType` | `SELL`, `BUY`, `SELL_MARKET`, `BUY_MARKET` |
|
||||
| `SymbolChartMode` | `BID`, `LAST` |
|
||||
| `SymbolCalcMode` | `FOREX`, `FUTURES`, `CFD`, `CFDINDEX`, `CFDLEVERAGE`, … |
|
||||
| `SymbolTradeMode` | `DISABLED`, `LONGONLY`, `SHORTONLY`, `CLOSEONLY`, `FULL` |
|
||||
| `SymbolTradeExecution` | `REQUEST`, `INSTANT`, `MARKET`, `EXCHANGE` |
|
||||
| `SymbolSwapMode` | `DISABLED`, `POINTS`, `CURRENCY_SYMBOL`, … |
|
||||
| `DayOfWeek` | `SUNDAY` through `SATURDAY` |
|
||||
| `SymbolOrderGTCMode` | `GTC`, `DAILY`, `DAILY_NO_STOPS` |
|
||||
| `SymbolOptionRight` | `CALL`, `PUT` |
|
||||
| `SymbolOptionMode` | `EUROPEAN`, `AMERICAN` |
|
||||
| `AccountTradeMode` | `DEMO`, `CONTEST`, `REAL` |
|
||||
| `AccountStopOutMode` | `PERCENT`, `MONEY` |
|
||||
| `AccountMarginMode` | `RETAIL_NETTING`, `EXCHANGE`, `RETAIL_HEDGING` |
|
||||
| `TickFlag` | `BID`, `ASK`, `LAST`, `VOLUME`, `BUY`, `SELL` |
|
||||
| `TradeRetcode` | `REQUOTE`, `DONE`, `ERROR`, `TIMEOUT`, `INVALID`, … |
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# db
|
||||
|
||||
`aiomql.core.db` — SQLite ORM base class with dataclass support.
|
||||
|
||||
## Overview
|
||||
|
||||
The `DB` class provides ORM-style CRUD operations backed by SQLite. Classes that inherit
|
||||
from `DB` and are decorated with `@dataclass` automatically get a database table whose
|
||||
columns mirror the dataclass fields. Column types, defaults, and constraints (e.g.
|
||||
`PRIMARY KEY`) are derived from field metadata.
|
||||
|
||||
## Classes
|
||||
|
||||
### `DB`
|
||||
|
||||
> Base class for ORM-style database operations.
|
||||
|
||||
| Class Attribute | Type | Description |
|
||||
|-----------------|------|-------------|
|
||||
| `table_name` | `ClassVar[str]` | Table name (defaults to class name) |
|
||||
|
||||
#### Schema Helpers
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `pk` *(property)* | Returns `(field_name, value)` for the PRIMARY KEY field |
|
||||
| `init_db()` | Initialises the connection and creates the table |
|
||||
| `get_connection()` | Returns a new `sqlite3.Connection` with a custom row factory |
|
||||
| `create_table(conn)` | Creates the table if it doesn't exist |
|
||||
| `get_columns()` | Generates column definitions from dataclass fields |
|
||||
| `types(key)` | Maps a Python type to its SQLite equivalent |
|
||||
| `get_default(col)` | Returns the `DEFAULT` SQL clause for a field |
|
||||
| `get_metadata(col)` | Extracts SQL constraints (e.g. `PRIMARY KEY`) from field metadata |
|
||||
| `dict_factory()` | Returns a row factory that converts rows into class instances |
|
||||
| `sanitize(identifier)` | Sanitises a SQL identifier to prevent injection |
|
||||
|
||||
#### CRUD Operations
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `save(commit=True, update=False, data=None, conn=None)` | Inserts or updates a record |
|
||||
| `get(**kwargs)` | Returns the first matching record, or `None` |
|
||||
| `filter(**kwargs)` | Returns all matching records (or all if no criteria) |
|
||||
| `clear()` | Deletes all records from the table |
|
||||
|
||||
#### Serialisation
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `asdict()` | Converts the instance to a dictionary |
|
||||
| `get_data()` | Returns instance data for saving |
|
||||
+27
-27
@@ -1,34 +1,34 @@
|
||||
# Errors
|
||||
# errors
|
||||
|
||||
## Tabel of contents
|
||||
- [Error](#errors.error)
|
||||
- [is_connection_error](#errors.is_connection_error)
|
||||
`aiomql.core.errors` — MetaTrader 5 error wrapper.
|
||||
|
||||
## Overview
|
||||
|
||||
<a id="errors.error"></a>
|
||||
## Error
|
||||
```python
|
||||
class Error
|
||||
```
|
||||
Error class for handling errors.
|
||||
Provides the `Error` class for representing and inspecting errors returned by the MetaTrader 5
|
||||
terminal. Wraps numeric error codes with human-readable descriptions.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|----------------|--------------|----------------------------------------------|
|
||||
| `code` | `int` | Error code |
|
||||
| `description` | `str` | Error description |
|
||||
| `descriptions` | `dict` | A dictionary of error codes and descriptions |
|
||||
| `conn_errors` | `tuple[int]` | A tuple of connection errors |
|
||||
## Classes
|
||||
|
||||
### `Error`
|
||||
|
||||
<a id="errors.is_connection_error"></a>
|
||||
## is_connection_error
|
||||
```python
|
||||
def is_connection_error(self) -> bool
|
||||
```
|
||||
Check if an error is a connection error.
|
||||
> Wraps an MT5 error code with a description and category helpers.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|------------------------------------------------------|
|
||||
| `bool` | True if error is a connection error, False otherwise |
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `code` | `int` | Numeric error code |
|
||||
| `description` | `str` | Human-readable description |
|
||||
| `descriptions` | `dict[int, str]` | Class-level mapping of known error codes → descriptions |
|
||||
| `conn_errors` | `tuple[int, ...]` | Codes that indicate connection-level failures |
|
||||
|
||||
#### `__init__(code=1, description="")`
|
||||
|
||||
Creates an `Error`. If `description` is empty, the description is looked up from
|
||||
`descriptions`. Defaults to `"unknown error"` for unrecognised codes.
|
||||
|
||||
#### `is_connection_error()`
|
||||
|
||||
Returns `True` if `code` is in `conn_errors`.
|
||||
|
||||
#### `__repr__()`
|
||||
|
||||
Returns `"code: description"`.
|
||||
|
||||
+14
-44
@@ -1,49 +1,19 @@
|
||||
# Exceptions
|
||||
Exceptions for the aiomql package.
|
||||
# exceptions
|
||||
|
||||
## Table of Contents
|
||||
- [LoginError](#exceptions.login_error)
|
||||
- [VolumeError](#exceptions.volume_error)
|
||||
- [SymbolError](#exceptions.symbol_error)
|
||||
- [OrderError](#exceptions.order_error)
|
||||
- [StopTradingError](#exceptions.stop_trading_error)
|
||||
`aiomql.core.exceptions` — Custom exception hierarchy for the aiomql package.
|
||||
|
||||
|
||||
<a id="exceptions.login_error"></a>
|
||||
### LoginError
|
||||
```python
|
||||
class LoginError(Exception)
|
||||
```
|
||||
Raised when an error occurs when logging in.
|
||||
## Overview
|
||||
|
||||
Defines domain-specific exceptions used throughout the library to signal
|
||||
trading and connection errors.
|
||||
|
||||
<a id="exceptions.volume_error"></a>
|
||||
### VolumeError
|
||||
```python
|
||||
class VolumeError(Exception)
|
||||
```
|
||||
Raised when a volume is not valid or out of range for a symbol.
|
||||
## Exceptions
|
||||
|
||||
|
||||
<a id="exceptions.symbol_error"></a>
|
||||
### SymbolError
|
||||
```python
|
||||
class SymbolError(Exception)
|
||||
```
|
||||
Raised when a symbol is not provided where required or not available in the Market Watch.
|
||||
|
||||
|
||||
<a id="exceptions.order_error"></a>
|
||||
### OrderError
|
||||
```python
|
||||
class OrderError(Exception)
|
||||
```
|
||||
Raised when an error occurs when working with the order class.
|
||||
|
||||
|
||||
<a id="exceptions.Stop_trading_error"></a>
|
||||
### StopTradingError
|
||||
```python
|
||||
class StopTradingError(Exception)
|
||||
```
|
||||
Raised when an error occurs when trying to stop trading.
|
||||
| Exception | Base | Description |
|
||||
|-----------|------|-------------|
|
||||
| `LoginError` | `Exception` | Raised when a login attempt fails |
|
||||
| `VolumeError` | `Exception` | Raised when a volume is invalid or out of range for a symbol |
|
||||
| `SymbolError` | `Exception` | Raised when a required symbol is missing or not in Market Watch |
|
||||
| `OrderError` | `Exception` | Raised when an error occurs while working with the `Order` class |
|
||||
| `StopTrading` | `Exception` | Raised to signal that trading should stop |
|
||||
| `InvalidRequest` | `Exception` | Raised when a market query fails |
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# MetaBackTester
|
||||
|
||||
## Table of Contents
|
||||
- [MetaBackTester](#metabacktester)
|
||||
- [\__init\__](#metabacktester.__init__)
|
||||
- [backtest_engine](#metabacktester.backtest_engine)
|
||||
- [backtest_engine.setter](#metabacktester.backtest_engine.setter)
|
||||
|
||||
|
||||
<a id="metabacktester.meta_back_tester"></a>
|
||||
### MetaBackTester
|
||||
```python
|
||||
class MetaBackTester(MetaTrader)
|
||||
```
|
||||
A class for testing trading strategies in the MetaTrader 5 terminal. A subclass of MetaTrader.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|-------------------|------------------|---------------------------------------------------------------|
|
||||
| `backtest_engine` | `BackTestEngine` | The backtesting engine to use for testing trading strategies. |
|
||||
|
||||
|
||||
<a id="metabacktester.__init__"></a>
|
||||
### \__init\__
|
||||
```python
|
||||
def __init__(self, *, backtest_engine: BackTestEngine = None)
|
||||
```
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------------|------------------|--------------------------------------------------|
|
||||
| `backtest_engine` | `BackTestEngine` | The backtesting engine to use for testing trades |
|
||||
|
||||
<a id="metabacktester.backtest_engine"></a>
|
||||
```python
|
||||
@property
|
||||
def backtest_engine(self) -> BackTestEngine
|
||||
```
|
||||
Returns the backtest engine object.
|
||||
|
||||
|
||||
<a id="metabacktester.backtest_engine.setter"></a>
|
||||
```python
|
||||
@backtest_engine.setter
|
||||
def backtest_engine(self, value: BackTestEngine):
|
||||
```
|
||||
Sets the backtest engine object.
|
||||
+74
-688
@@ -1,712 +1,98 @@
|
||||
# MetaTrader
|
||||
The MetaTrader Class provides an asynchronous wrapper around the MetaTrader5 API.
|
||||
# meta_trader
|
||||
|
||||
## Table of Contents
|
||||
- [MetaTrader](#meta_trader.meta_trader)
|
||||
- [\__aenter\__](#meta_trader.__aenter__)
|
||||
- [\__aexit\__](#meta_trader.__aexit__)
|
||||
- [login](#meta_trader.login)
|
||||
- [initialize](#meta_trader.initialize)
|
||||
- [login_sync](#meta_trader.login_sync)
|
||||
- [initialize_sync](#meta_trader.initialize_sync)
|
||||
- [shutdown](#meta_trader.shutdown)
|
||||
- [version](#meta_trader.version)
|
||||
- [account_info](#meta_trader.account_info)
|
||||
- [terminal_info](#meta_trader.terminal_info)
|
||||
- [last_error](#meta_trader.last_error)
|
||||
- [symbols_total](#meta_trader.symbols_total)
|
||||
- [symbols_get](#meta_trader.symbols_get)
|
||||
- [symbol_info](#meta_trader.symbol_info)
|
||||
- [symbol_info_tick](#meta_trader.symbol_info_tick)
|
||||
- [symbol_select](#meta_trader.symbol_select)
|
||||
- [market_book_add](#meta_trader.market_book_add)
|
||||
- [market_book_get](#meta_trader.market_book_get)
|
||||
- [market_book_release](#meta_trader.market_book_release)
|
||||
- [copy_rates_from](#meta_trader.copy_rates_from)
|
||||
- [copy_rates_from_pos](#meta_trader.copy_rates_from_pos)
|
||||
- [copy_rates_range](#meta_trader.copy_rates_range)
|
||||
- [copy_ticks_from](#meta_trader.copy_ticks_from)
|
||||
- [copy_ticks_range](#meta_trader.copy_ticks_range)
|
||||
- [orders_total](#meta_trader.orders_total)
|
||||
- [orders_get](#meta_trader.orders_get)
|
||||
- [order_calc_margin](#meta_trader.order_calc_margin)
|
||||
- [order_calc_profit](#meta_trader.order_calc_profit)
|
||||
- [order_check](#meta_trader.order_check)
|
||||
- [order_send](#meta_trader.order_send)
|
||||
- [positions_total](#meta_trader.positions_total)
|
||||
- [positions_get](#meta_trader.positions_get)
|
||||
- [history_orders_total](#meta_trader.history_orders_total)
|
||||
- [history_orders_get](#meta_trader.history_orders_get)
|
||||
- [history_deals_total](#meta_trader.history_deals_total)
|
||||
- [history_deals_get](#meta_trader.history_deals_get)
|
||||
`aiomql.core.meta_trader` — Async/sync singleton interface to the MetaTrader 5 terminal.
|
||||
|
||||
<a id="meta_trader.meta_trader"></a>
|
||||
### MetaTrader
|
||||
```python
|
||||
class MetaTrader(MetaCore)
|
||||
```
|
||||
The MetaTrader class is a wrapper around the MetaTrader terminal.
|
||||
It provides methods for connecting to the MetaTrader terminal and retrieving data from it.
|
||||
## Overview
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|-------|-------|--------------------------------------------------------|------------------------|
|
||||
| error | Error | The last error encountered by the MetaTrader terminal. | Error(1, 'Successful') |
|
||||
The `MetaTrader` class wraps every MT5 API call with async execution via
|
||||
`asyncio.to_thread` and automatic retry logic for transient connection errors.
|
||||
It is a **singleton** — only one instance exists per process.
|
||||
|
||||
#### Notes:
|
||||
All the attributes, enums and constants of the MetaTrader5 class are also available here. Although, they are more easily
|
||||
accessible and used via the various enums and models defined in the module.
|
||||
A synchronous counterpart lives in `aiomql.core.sync.meta_trader`.
|
||||
|
||||
## Classes
|
||||
|
||||
<a id="meta_trader.__aenter__"></a>
|
||||
### \__aenter\__
|
||||
```python
|
||||
async def __aenter__() -> 'MetaTrader'
|
||||
```
|
||||
Async context manager entry point.
|
||||
Initializes the connection to the MetaTrader terminal.
|
||||
### `MetaTrader`
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|-------------------------------------|
|
||||
| `MetaTrader` | An instance of the MetaTrader class |
|
||||
> Asynchronous interface to the MetaTrader 5 terminal.
|
||||
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `error` | `Error` | The last error from the terminal |
|
||||
| `config` | `Config` | The global configuration instance |
|
||||
|
||||
<a id="meta_trader.__aexit__"></a>
|
||||
### \__aexit\__
|
||||
```python
|
||||
async def __aexit__(exc_type, exc_val, exc_tb)
|
||||
```
|
||||
Async context manager exit point. Closes the connection to the MetaTrader terminal.
|
||||
#### Connection
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `initialize(path, login, password, server, timeout, portable)` | Initialises the terminal connection |
|
||||
| `initialize_sync(…)` | Synchronous variant of `initialize` |
|
||||
| `login(*, login, password, server, timeout)` | Logs into a trading account |
|
||||
| `login_sync(…)` | Synchronous variant of `login` |
|
||||
| `shutdown()` | Closes the terminal connection |
|
||||
| `__aenter__` / `__aexit__` | Async context manager for connect/disconnect |
|
||||
|
||||
<a id="meta_trader.login"></a>
|
||||
### login
|
||||
```python
|
||||
async def login(*, login: int, password: str, server: str, timeout: int = 60000) -> bool
|
||||
```
|
||||
Connects to the MetaTrader terminal using the specified login, password and server.
|
||||
#### Account & Terminal
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------|-------|--------------------------------------------|
|
||||
| `login` | `int` | The trading account number. |
|
||||
| `password` | `str` | The trading account password. |
|
||||
| `server` | `str` | The trading server name. |
|
||||
| `timeout` | `int` | The timeout for the connection in seconds. |
|
||||
| Method | Returns | Description |
|
||||
|--------|---------|-------------|
|
||||
| `account_info()` | `AccountInfo \| None` | Current account details |
|
||||
| `terminal_info()` | `TerminalInfo \| None` | Terminal information |
|
||||
| `version()` | `tuple[int,int,str] \| None` | Terminal version |
|
||||
| `last_error()` | `tuple[int,str]` | Last error code and description |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
#### Symbols
|
||||
|
||||
| Method | Returns |
|
||||
|--------|---------|
|
||||
| `symbols_total()` | `int` |
|
||||
| `symbols_get(group)` | `tuple[SymbolInfo, …] \| None` |
|
||||
| `symbol_info(symbol)` | `SymbolInfo \| None` |
|
||||
| `symbol_info_tick(symbol)` | `Tick \| None` |
|
||||
| `symbol_select(symbol, enable)` | `bool` |
|
||||
|
||||
<a id="meta_trader.login_sync"></a>
|
||||
#### login_sync
|
||||
```python
|
||||
async def login_sync(*, login: int, password: str, server: str, timeout: int = 60000) -> bool
|
||||
```
|
||||
A synchronous version of the login method.
|
||||
Connects to the MetaTrader terminal using the specified login, password and server.
|
||||
#### Market Data
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------|-------|--------------------------------------------|
|
||||
| `login` | `int` | The trading account number. |
|
||||
| `password` | `str` | The trading account password. |
|
||||
| `server` | `str` | The trading server name. |
|
||||
| `timeout` | `int` | The timeout for the connection in seconds. |
|
||||
| Method | Returns |
|
||||
|--------|---------|
|
||||
| `copy_rates_from(symbol, timeframe, date_from, count)` | `ndarray \| None` |
|
||||
| `copy_rates_from_pos(symbol, timeframe, start_pos, count)` | `ndarray \| None` |
|
||||
| `copy_rates_range(symbol, timeframe, date_from, date_to)` | `ndarray \| None` |
|
||||
| `copy_ticks_from(symbol, date_from, count, flags)` | `ndarray \| None` |
|
||||
| `copy_ticks_range(symbol, date_from, date_to, flags)` | `ndarray \| None` |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
#### Orders & Positions
|
||||
|
||||
| Method | Returns |
|
||||
|--------|---------|
|
||||
| `positions_total()` | `int` |
|
||||
| `positions_get(group, symbol, ticket)` | `tuple[TradePosition, …] \| None` |
|
||||
| `orders_total()` | `int` |
|
||||
| `orders_get(group, symbol, ticket)` | `tuple[TradeOrder, …] \| None` |
|
||||
| `history_orders_total(date_from, date_to)` | `int` |
|
||||
| `history_orders_get(date_from, date_to, group, ticket, position)` | `tuple[TradeOrder, …] \| None` |
|
||||
| `history_deals_total(date_from, date_to)` | `int` |
|
||||
| `history_deals_get(date_from, date_to, group, ticket, position)` | `tuple[TradeDeal, …] \| None` |
|
||||
|
||||
<a id="meta_trader.initialize"></a>
|
||||
### initialize
|
||||
```python
|
||||
async def initialize(path: str = "", login: int = 0, password: str = "", server: str = "",
|
||||
timeout: int | None = None, portable=False) -> bool
|
||||
```
|
||||
Initializes the connection to the MetaTrader terminal. All parameters are optional.
|
||||
#### Trade Execution
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------|---------------|----------------------------------------------------------|
|
||||
| `path` | `str` | The path to the MetaTrader terminal executable. |
|
||||
| `login` | `int` | The trading account number. |
|
||||
| `password` | `str` | The trading account password. |
|
||||
| `server` | `str` | The trading server name. |
|
||||
| `timeout` | `int \| None` | The timeout for the connection in seconds. |
|
||||
| `portable` | `bool` | If True, the terminal will be launched in portable mode. |
|
||||
| Method | Returns | Description |
|
||||
|--------|---------|-------------|
|
||||
| `order_check(request)` | `OrderCheckResult \| None` | Validates a trade request |
|
||||
| `order_send(request)` | `OrderSendResult \| None` | Sends a trade request |
|
||||
| `order_calc_margin(action, symbol, volume, price)` | `float \| None` | Calculates required margin |
|
||||
| `order_calc_profit(action, symbol, volume, price_open, price_close)` | `float \| None` | Calculates expected profit |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
#### Market Book
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `market_book_add(symbol)` | Subscribes to market depth |
|
||||
| `market_book_get(symbol)` | Gets current market depth |
|
||||
| `market_book_release(symbol)` | Unsubscribes from market depth |
|
||||
|
||||
<a id="meta_trader.initialize_sync"></a>
|
||||
### initialize_sync
|
||||
```python
|
||||
async def initialize_sync(path: str = "", login: int = 0, password: str = "", server: str = "",
|
||||
timeout: int | None = None, portable=False) -> bool
|
||||
```
|
||||
Initializes the connection to the MetaTrader terminal. All parameters are optional.
|
||||
#### Internal
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|------------|---------------|----------------------------------------------------------|
|
||||
| `path` | `str` | The path to the MetaTrader terminal executable. |
|
||||
| `login` | `int` | The trading account number. |
|
||||
| `password` | `str` | The trading account password. |
|
||||
| `server` | `str` | The trading server name. |
|
||||
| `timeout` | `int \| None` | The timeout for the connection in seconds. |
|
||||
| `portable` | `bool` | If True, the terminal will be launched in portable mode. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
|
||||
|
||||
<a id="meta_trader.shutdown"></a>
|
||||
### shutdown
|
||||
```python
|
||||
async def shutdown() -> None
|
||||
```
|
||||
Closes the connection to the MetaTrader terminal.
|
||||
|
||||
|
||||
<a id="meta_trader.version"></a>
|
||||
### version
|
||||
```python
|
||||
async def version() -> tuple[int, int, str] | None
|
||||
```
|
||||
Returns the version of the MetaTrader terminal.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|------------------------|-----------------------------------------------------------------------------------------------|
|
||||
| `tuple[int, int, str]` | A tuple of the MetaTrader terminal version. `Terminal Version`, `Build`, `Build Release Date` |
|
||||
|
||||
|
||||
<a id="meta_trader.account_info"></a>
|
||||
### account_info
|
||||
```python
|
||||
async def account_info() -> AccountInfo | None
|
||||
```
|
||||
Returns the account information for the connected account.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------|--------------------------------------|
|
||||
| `AccountInfo` | An instance of the AccountInfo class |
|
||||
|
||||
|
||||
<a id="meta_trader.terminal_info"></a>
|
||||
### terminal_info
|
||||
```python
|
||||
async def terminal_info() -> TerminalInfo | None
|
||||
```
|
||||
|
||||
Returns the terminal information for the connected terminal.
|
||||
### Returns
|
||||
| Type | Description |
|
||||
|----------------|------------------------------------------------|
|
||||
| `TerminalInfo` | An instance of the TerminalInfo class. A tuple |
|
||||
|
||||
|
||||
<a id="meta_trader.last_error"></a>
|
||||
### last_error
|
||||
```python
|
||||
async def last_error() -> tuple[int, str]
|
||||
```
|
||||
Returns the last error code and description.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------|-------------------------------------------------|
|
||||
| `tuple[int, str]` | A tuple of the last error code and description. |
|
||||
|
||||
|
||||
<a id="meta_trader.symbols_total"></a>
|
||||
### symbols_total
|
||||
```python
|
||||
async def symbols_total() -> int
|
||||
```
|
||||
Returns the total number of symbols.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|------------------------------|
|
||||
| `int` | The total number of symbols. |
|
||||
|
||||
|
||||
<a id="meta_trader.symbols_get"></a>
|
||||
### symbols_get
|
||||
```python
|
||||
async def symbols_get(group: str = "") -> tuple[SymbolInfo] | None
|
||||
```
|
||||
Returns the symbol information for all symbols or for a specified group.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|---------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `group` | `str` | The group name. Optional named parameter. If the group is specified, the function returns only symbols meeting a specified criteria for a symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------------|--------------------------------|
|
||||
| `tuple[SymbolInfo]` | A tuple of SymbolInfo objects. |
|
||||
|
||||
|
||||
<a id="meta_trader.symbol_info"></a>
|
||||
### symbol_info
|
||||
```python
|
||||
async def symbol_info(symbol: str) -> SymbolInfo | None
|
||||
```
|
||||
Returns the symbol information for the specified symbol.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------|--------------------------------------|
|
||||
| `SymbolInfo` | An instance of the SymbolInfo class. |
|
||||
|
||||
|
||||
<a id="meta_trader.symbol_info_tick"></a>
|
||||
### symbol_info_tick
|
||||
```python
|
||||
async def symbol_info_tick(symbol: str) -> Tick | None
|
||||
```
|
||||
Returns the latest tick for the specified symbol.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------|
|
||||
| `Tick` | An instance of the Tick class. |
|
||||
|
||||
|
||||
<a id="meta_trader.symbol_select"></a>
|
||||
### symbol_select
|
||||
```python
|
||||
async def symbol_select(symbol: str, enable: bool) -> bool
|
||||
```
|
||||
Selects or unselects the specified symbol in the Market Watch window.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|--------|--------------------------------------------------------------------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `enable` | `bool` | If True, the symbol will be selected. If False, the symbol will be unselected. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
|
||||
|
||||
<a id="meta_trader.market_book_add"></a>
|
||||
### market_book_add
|
||||
```python
|
||||
async def market_book_add(symbol: str) -> bool
|
||||
```
|
||||
Adds the specified symbol to the market book.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
|
||||
|
||||
<a id="meta_trader.market_book_get"></a>
|
||||
### market_book_get
|
||||
```python
|
||||
async def market_book_get(symbol: str) -> tuple[BookInfo] | None
|
||||
```
|
||||
Returns the market depth for the specified symbol.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------|------------------------------|
|
||||
| `tuple[BookInfo]` | A tuple of BookInfo objects. |
|
||||
|
||||
|
||||
<a id="meta_trader.market_book_release"></a>
|
||||
### market_book_release
|
||||
```python
|
||||
async def market_book_release(symbol: str) -> bool
|
||||
```
|
||||
Removes the specified symbol from the market book.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------|--------------------------------------|
|
||||
| `bool` | True if successful, False otherwise. |
|
||||
|
||||
|
||||
<a id="meta_trader.copy_rates_from"></a>
|
||||
### copy_rates_from
|
||||
```python
|
||||
async def copy_rates_from(symbol: str, timeframe: TimeFrame, date_from: datetime | int,
|
||||
count: int) -> numpy.ndarray | None
|
||||
```
|
||||
Returns the OHLCV rates for the specified symbol and timeframe starting from the specified date.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `timeframe` | `TimeFrame` | The timeframe. |
|
||||
| `date_from` | `datetime` or `int` | The date to start from. |
|
||||
| `count` | `int` | The number of rates to return. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------|-------------------------------|
|
||||
| `numpy.ndarray` | A numpy array of OHLCV rates. |
|
||||
|
||||
|
||||
<a id="meta_trader.copy_rates_from_pos"></a>
|
||||
### copy_rates_from_pos
|
||||
```python
|
||||
async def copy_rates_from_pos(symbol: str, timeframe: TimeFrame, start_pos: int, count: int) -> numpy.ndarray | None
|
||||
```
|
||||
Returns the OHLCV rates for the specified symbol and timeframe starting from the specified position.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|-------------|--------------------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `timeframe` | `TimeFrame` | The timeframe. |
|
||||
| `start_pos` | `int` | The position to start from. |
|
||||
| `count` | `int` | The number of rates to return. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------|-------------------------------|
|
||||
| `numpy.ndarray` | A numpy array of OHLCV rates. |
|
||||
|
||||
|
||||
<a id="meta_trader.copy_rates_range"></a>
|
||||
### copy_rates_range
|
||||
```python
|
||||
async def copy_rates_range(symbol: str, timeframe: TimeFrame, date_from: datetime | int,
|
||||
date_to: datetime | int) -> numpy.ndarray | None
|
||||
```
|
||||
Returns the OHLCV rates for the specified symbol and timeframe between the specified dates.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `timeframe` | `TimeFrame` | The timeframe. |
|
||||
| `date_from` | `datetime` or `int` | The start date. |
|
||||
| `date_to` | `datetime` or `int` | The end date. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------|-------------------------------|
|
||||
| `numpy.ndarray` | A numpy array of OHLCV rates. |
|
||||
|
||||
|
||||
<a id="meta_trader.copy_ticks_from"></a>
|
||||
### copy_ticks_from
|
||||
```python
|
||||
async def copy_ticks_from(symbol: str, date_from: datetime | int, count: int, flags: CopyTicks) -> tuple[Tick] | None
|
||||
```
|
||||
Returns the ticks for the specified symbol starting from the specified date.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|--------------------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `date_from` | `datetime` or `int` | The date to start from. |
|
||||
| `count` | `int` | The number of ticks to return. |
|
||||
| `flags` | `CopyTicks` | The CopyTicks flags. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------|--------------------------|
|
||||
| `tuple[Tick]` | A tuple of Tick objects. |
|
||||
|
||||
|
||||
<a id="meta_trader.copy_ticks_range"></a>
|
||||
### copy_ticks_range
|
||||
```python
|
||||
async def copy_ticks_range(symbol: str, date_from: datetime | int, date_to: datetime | int,
|
||||
flags: CopyTicks) -> tuple[Tick] | None
|
||||
```
|
||||
Returns the ticks for the specified symbol between the specified dates.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|----------------------|
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `date_from` | `datetime` or `int` | The start date. |
|
||||
| `date_to` | `datetime` or `int` | The end date. |
|
||||
| `flags` | `CopyTicks` | The CopyTicks flags. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------------|--------------------------|
|
||||
| `tuple[Tick]` | A tuple of Tick objects. |
|
||||
|
||||
|
||||
<a id="meta_trader.orders_total"></a>
|
||||
### orders_total
|
||||
```python
|
||||
async def orders_total() -> int
|
||||
```
|
||||
Returns the total number of active orders.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|------------------------------------|
|
||||
| `int` | The total number of active orders. |
|
||||
|
||||
|
||||
<a id="meta_trader.orders_get"></a>
|
||||
### orders_get
|
||||
```python
|
||||
async def orders_get(group: str = "", ticket: int = 0, symbol: str = "") -> tuple[TradeOrder, ...] | None
|
||||
```
|
||||
Get active orders with the ability to filter by symbol or ticket. There are three call options.
|
||||
Call without parameters. Return active orders on all symbols
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only active orders meeting a specified criteria for a symbol name. |
|
||||
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
|
||||
| `symbol` | `str` | Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|------------------------------------------------------|
|
||||
| `tuple[TradeOrder, ...]` | A tuple of active trade orders as TradeOrder objects |
|
||||
|
||||
|
||||
<a id="meta_trader.order_calc_margin"></a>
|
||||
### order_calc_margin
|
||||
```python
|
||||
async def order_calc_margin(action: OrderType, symbol: str, volume: float, price: float) -> float | None
|
||||
```
|
||||
Calculates the margin required to open a trade.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------------|-------------------|
|
||||
| `action` | `OrderType` | The order type. |
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `volume` | `float` | The order volume. |
|
||||
| `price` | `float` | The order price. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------|--------------------------------------|
|
||||
| `float` | The margin required to open a trade. |
|
||||
|
||||
|
||||
<a id="meta_trader.order_calc_profit"></a>
|
||||
### order_calc_profit
|
||||
```python
|
||||
async def order_calc_profit(action: OrderType, symbol: str, volume: float, price_open: float,
|
||||
price_close: float) -> float | None
|
||||
```
|
||||
Calculates the profit for a closed trade.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|---------------|-------------|------------------------|
|
||||
| `action` | `OrderType` | The order type. |
|
||||
| `symbol` | `str` | The symbol name. |
|
||||
| `volume` | `float` | The order volume. |
|
||||
| `price_open` | `float` | The order open price. |
|
||||
| `price_close` | `float` | The order close price. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|---------|--------------------------------|
|
||||
| `float` | The profit for a closed trade. |
|
||||
|
||||
|
||||
<a id="meta_trader.order_check"></a>
|
||||
### order_check
|
||||
```python
|
||||
async def order_check(request: dict) -> OrderCheckResult
|
||||
```
|
||||
Checks the specified order for validity.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|--------|--------------------|
|
||||
| `request` | `dict` | The order request. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------|--------------------------------------------|
|
||||
| `OrderCheckResult` | An instance of the OrderCheckResult class. |
|
||||
|
||||
|
||||
<a id="meta_trader.order_send"></a>
|
||||
### order_send
|
||||
```python
|
||||
async def order_send(request: dict) -> OrderSendResult
|
||||
```
|
||||
Sends the specified order request to the MetaTrader terminal.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|--------|--------------------|
|
||||
| `request` | `dict` | The order request. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------|-------------------------------------------|
|
||||
| `OrderSendResult` | An instance of the OrderSendResult class. |
|
||||
|
||||
|
||||
<a id="meta_trader.positions_total"></a>
|
||||
### positions_total
|
||||
```python
|
||||
async def positions_total() -> int
|
||||
```
|
||||
Returns the total number of open positions.
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|-------------------------------------|
|
||||
| `int` | The total number of open positions. |
|
||||
|
||||
|
||||
<a id="meta_trader.positions_get"></a>
|
||||
### positions_get
|
||||
```python
|
||||
async def positions_get(group: str = "", ticket: int = 0, symbol: str = "") -> tuple[TradePosition, ...] | None
|
||||
```
|
||||
Returns the open positions with the ability to filter by symbol or ticket. There are three call options.
|
||||
Call without parameters. Return open positions on all symbols
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only open positions meeting a specified criteria for a symbol name. |
|
||||
| `ticket` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
|
||||
| `symbol` | `str` | Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-----------------------------|----------------------------------------------------------|
|
||||
| `tuple[TradePosition, ...]` | A tuple of open trade positions as TradePosition objects |
|
||||
|
||||
|
||||
<a id="meta_trader.history_orders_total"></a>
|
||||
### history_orders_total
|
||||
```python
|
||||
async def history_orders_total(date_from: datetime | int, date_to: datetime | int) -> int
|
||||
```
|
||||
Returns the total number of closed orders for the specified period.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|-----------------|
|
||||
| `date_from` | `datetime` or `int` | The start date. |
|
||||
| `date_to` | `datetime` or `int` | The end date. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|-------------------------------------------------------------|
|
||||
| `int` | The total number of closed orders for the specified period. |
|
||||
|
||||
|
||||
<a id="meta_trader.history_orders_get"></a>
|
||||
### history_orders_get
|
||||
```python
|
||||
async def history_orders_get(date_from: datetime | int = None, date_to: datetime | int = None, group: str = "",
|
||||
ticket: int = 0, position: int = 0) -> tuple[TradeOrder, ...] | None
|
||||
```
|
||||
Returns the closed orders for the specified period with the ability to filter by symbol or ticket. There are three call options.
|
||||
Call without parameters. Return closed orders on all symbols
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `date_from` | `datetime` or `int` | The start date. Optional named parameter. |
|
||||
| `date_to` | `datetime` or `int` | The end date. Optional named parameter. |
|
||||
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only closed orders meeting a specified criteria for a symbol name. |
|
||||
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
|
||||
| `position` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|--------------------------|------------------------------------------------------|
|
||||
| `tuple[TradeOrder, ...]` | A tuple of closed trade orders as TradeOrder objects |
|
||||
|
||||
|
||||
<a id="meta_trader.history_deals_total"></a>
|
||||
### history_deals_total
|
||||
```python
|
||||
async def history_deals_total(date_from: datetime | int, date_to: datetime | int) -> int
|
||||
```
|
||||
Returns the total number of closed deals for the specified period.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|-----------------|
|
||||
| `date_from` | `datetime` or `int` | The start date. |
|
||||
| `date_to` | `datetime` or `int` | The end date. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------|------------------------------------------------------------|
|
||||
| `int` | The total number of closed deals for the specified period. |
|
||||
|
||||
<a id="meta_trader.history_deals_get"></a>
|
||||
### history_deals_get
|
||||
```python
|
||||
async def history_deals_get(date_from: datetime | int = None, date_to: datetime | int = None, group: str = "",
|
||||
ticket: int = 0,position: int = 0) -> tuple[TradeDeal, ...] | None
|
||||
```
|
||||
Returns the closed deals for the specified period with the ability to filter by symbol or ticket. There are three call options.
|
||||
Call without parameters. Return closed deals on all symbols
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-------------|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `date_from` | `datetime` or `int` | The start date. Optional named parameter. |
|
||||
| `date_to` | `datetime` or `int` | The end date. Optional named parameter. |
|
||||
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only closed deals meeting a specified criteria for a symbol name. |
|
||||
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
|
||||
| `position` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
|
||||
|
||||
#### Returns:
|
||||
| Type | Description |
|
||||
|-------------------------|----------------------------------------------------|
|
||||
| `tuple[TradeDeal, ...]` | A tuple of closed trade deals as TradeDeal objects |
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `_handler(api, retries=3)` | Executes API calls with connection-error retry |
|
||||
|
||||
+86
-361
@@ -1,386 +1,111 @@
|
||||
# Models
|
||||
# models
|
||||
|
||||
This module contains the models used in the aiomql package. These models are used to represent the data returned from
|
||||
the MetaTrader 5 terminal. They are all subclasses of the `Base` class.
|
||||
`aiomql.core.models` — Data models mirroring MetaTrader 5 structures.
|
||||
|
||||
## Table of Contents
|
||||
- [AccountInfo](#models.account_info)
|
||||
- [TerminalInfo](#models.terminal_info)
|
||||
- [SymbolInfo](#models.symbol.info)
|
||||
- [BookInfo](#models.book_info)
|
||||
- [TradeOrder](#models.trade_order)
|
||||
- [TradeRequest](#models_trade_request)
|
||||
- [OrderCheckResult](#models.order_check_result)
|
||||
- [OrderSendResult](#models.order_send_result)
|
||||
- [TradePosition](#models.trade_position)
|
||||
- [TradeDeal](#models.trade_deal)
|
||||
## Overview
|
||||
|
||||
Defines data-model classes that correspond to the named-tuple structures returned by the
|
||||
MetaTrader 5 terminal. All models inherit from [`Base`](base.md) and provide typed attributes,
|
||||
dictionary conversion, and string representations.
|
||||
|
||||
<a id="models.account_info"></a>
|
||||
### AccountInfo
|
||||
```python
|
||||
class AccountInfo(Base)
|
||||
```
|
||||
Account Information Class.
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|----------------------|----------------------|------------------------------------------|---------|
|
||||
| `login` | `int` | Account number | |
|
||||
| `password` | `str` | Account password | |
|
||||
| `server` | `str` | Trade server name | |
|
||||
| `trade_mode` | AccountTradeMode | Trade mode | |
|
||||
| `balance` | `float` | Account balance | |
|
||||
| `leverage` | `float` | Account leverage | |
|
||||
| `profit` | `float` | Account profit | |
|
||||
| `point` | `float` | Point size | |
|
||||
| `amount` | `float` | Account amount | 0 |
|
||||
| `equity` | `float` | Account equity | |
|
||||
| `credit` | `float` | Account credit | |
|
||||
| `margin` | `float` | Account margin | |
|
||||
| `margin_level` | `float` | Margin level | |
|
||||
| `margin_free` | `float` | Free margin | |
|
||||
| `margin_mode` | `AccountMarginMode` | Margin calculation mode | |
|
||||
| `margin_so_mode` | `AccountStopoutMode` | Stop out mode | |
|
||||
| `margin_so_call` | `float` | Margin call level | |
|
||||
| `margin_so_so` | `float` | Stop out level | |
|
||||
| `margin_initial` | `float` | Initial margin | |
|
||||
| `margin_maintenance` | `float` | Maintenance margin | |
|
||||
| `fifo_close` | `bool` | FIFO close flag | |
|
||||
| `limit_orders` | `float` | Limit orders | |
|
||||
| `currency` | `str` | Account currency | "USD" |
|
||||
| `trade_allowed` | `bool` | Trade allowed flag | True |
|
||||
| `trade_expert` | `bool` | Trade expert flag | True |
|
||||
| `currency_digits` | `int` | Number of digits after the decimal point | |
|
||||
| `assets` | `float` | Assets | |
|
||||
| `liabilities` | `float` | Liabilities | |
|
||||
| `commission_blocked` | `float` | Blocked commission | |
|
||||
| `name` | `str` | Account name | |
|
||||
| `company` | `str` | Company name | |
|
||||
## Classes
|
||||
|
||||
### `AccountInfo`
|
||||
|
||||
<a id="models.terminal_info"></a>
|
||||
### TerminalInfo
|
||||
```python
|
||||
class TerminalInfo(Base)
|
||||
```
|
||||
Terminal information class. Holds information about the terminal.
|
||||
> Trading account information.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|-------------------------|---------|----------------------------|---------|
|
||||
| `community_account` | `bool` | Community account flag | |
|
||||
| `community_connection` | `bool` | Community connection flag | |
|
||||
| `connected` | `bool` | Connection flag | |
|
||||
| `dlls_allowed` | `bool` | DLLs allowed flag | |
|
||||
| `trade_allowed` | `bool` | Trade allowed flag | |
|
||||
| `tradeapi_disabled` | `bool` | Trade API disabled flag | |
|
||||
| `email_enabled` | `bool` | Email enabled flag | |
|
||||
| `ftp_enabled` | `bool` | FTP enabled flag | |
|
||||
| `notifications_enabled` | `bool` | Notifications enabled flag | |
|
||||
| `mqid` | `bool` | MQID | |
|
||||
| `build` | `int` | Build number | |
|
||||
| `maxbars` | `int` | Maximum number of bars | |
|
||||
| `codepage` | `int` | Code page | |
|
||||
| `ping_last` | `int` | Last ping | |
|
||||
| `community_balance` | `float` | Community balance | |
|
||||
| `retransmission` | `float` | Retransmission | |
|
||||
| `company` | `str` | Company name | |
|
||||
| `name` | `str` | Terminal name | |
|
||||
| `language` | `str` | Language | |
|
||||
| `path` | `str` | Terminal path | |
|
||||
| `data_path` | `str` | Data path | |
|
||||
| `commondata_path` | `str` | Common data path | |
|
||||
Key fields: `login`, `server`, `trade_mode`, `balance`, `leverage`, `profit`, `equity`,
|
||||
`margin`, `margin_free`, `margin_level`, `currency`.
|
||||
|
||||
---
|
||||
|
||||
<a id="models.symbol_info"></a>
|
||||
### SymbolInfo
|
||||
```python
|
||||
class SymbolInfo(Base)
|
||||
```
|
||||
Symbol Information Class. Symbols are financial instruments available for trading in the MetaTrader 5 terminal.
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|------------------------------|------------------------|----------------------------|---------|
|
||||
| `name` | `str` | Symbol name | |
|
||||
| `custom` | `bool` | Custom symbol flag | |
|
||||
| `chart_mode` | `SymbolChartMode` | Chart mode | |
|
||||
| `select` | `bool` | Symbol selection flag | |
|
||||
| `visible` | `bool` | Symbol visibility flag | |
|
||||
| `session_deals` | `int` | Session deals | |
|
||||
| `session_buy_orders` | `int` | Session buy orders | |
|
||||
| `session_sell_orders` | `int` | Session sell orders | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `volumehigh` | `float` | Volume high | |
|
||||
| `volumelow` | `float` | Volume low | |
|
||||
| `time` | `int` | Time | |
|
||||
| `digits` | `int` | Digits | |
|
||||
| `spread` | `float` | Spread | |
|
||||
| `spread_float` | `bool` | Spread float flag | |
|
||||
| `ticks_bookdepth` | `int` | Ticks book depth | |
|
||||
| `trade_calc_mode` | `SymbolCalcMode` | Trade calculation mode | |
|
||||
| `trade_mode` | `SymbolTradeMode` | Trade mode | |
|
||||
| `start_time` | `int` | Start time | |
|
||||
| `expiration_time` | `int` | Expiration time | |
|
||||
| `trade_stops_level` | `int` | Trade stops level | |
|
||||
| `trade_freeze_level` | `int` | Trade freeze level | |
|
||||
| `trade_exemode` | `SymbolTradeExecution` | Trade execution mode | |
|
||||
| `swap_mode` | `SymbolSwapMode` | Swap mode | |
|
||||
| `swap_rollover3days` | `DayOfWeek` | Swap rollover 3 days | |
|
||||
| `margin_hedged_use_leg` | `bool` | Margin hedged use leg flag | |
|
||||
| `expiration_mode` | `int` | Expiration mode | |
|
||||
| `filling_mode` | `int` | Filling mode | |
|
||||
| `order_mode` | `int` | Order mode | |
|
||||
| `order_gtc_mode` | `SymbolOrderGTCMode` | Order GTC mode | |
|
||||
| `option_mode` | `SymbolOptionMode` | Option mode | |
|
||||
| `option_right` | `SymbolOptionRight` | Option right | |
|
||||
| `bid` | `float` | Bid | |
|
||||
| `bidhigh` | `float` | Bid high | |
|
||||
| `bidlow` | `float` | Bid low | |
|
||||
| `ask` | `float` | Ask | |
|
||||
| `askhigh` | `float` | Ask high | |
|
||||
| `asklow` | `float` | Ask low | |
|
||||
| `last` | `float` | Last | |
|
||||
| `lasthigh` | `float` | Last high | |
|
||||
| `lastlow` | `float` | Last low | |
|
||||
| `volume_real` | `float` | Volume real | |
|
||||
| `volumehigh_real` | `float` | Volume high real | |
|
||||
| `volumelow_real` | `float` | Volume low real | |
|
||||
| `option_strike` | `float` | Option strike | |
|
||||
| `point` | `float` | Point | |
|
||||
| `trade_tick_value` | `float` | Trade tick value | |
|
||||
| `trade_tick_value_profit` | `float` | Trade tick value profit | |
|
||||
| `trade_tick_value_loss` | `float` | Trade tick value loss | |
|
||||
| `trade_tick_size` | `float` | Trade tick size | |
|
||||
| `trade_contract_size` | `float` | Trade contract size | |
|
||||
| `trade_accrued_interest` | `float` | Trade accrued interest | |
|
||||
| `trade_face_value` | `float` | Trade face value | |
|
||||
| `trade_liquidity_rate` | `float` | Trade liquidity rate | |
|
||||
| `volume_min` | `float` | Volume min | |
|
||||
| `volume_max` | `float` | Volume max | |
|
||||
| `volume_step` | `float` | Volume step | |
|
||||
| `volume_limit` | `float` | Volume limit | |
|
||||
| `swap_long` | `float` | Swap long | |
|
||||
| `swap_short` | `float` | Swap short | |
|
||||
| `margin_initial` | `float` | Initial margin | |
|
||||
| `margin_maintenance` | `float` | Maintenance margin | |
|
||||
| `session_volume` | `float` | Session volume | |
|
||||
| `session_turnover` | `float` | Session turnover | |
|
||||
| `session_interest` | `float` | Session interest | |
|
||||
| `session_buy_orders_volume` | `float` | Session buy orders volume | |
|
||||
| `session_sell_orders_volume` | `float` | Session sell orders volume | |
|
||||
| `session_open` | `float` | Session open | |
|
||||
| `session_close` | `float` | Session close | |
|
||||
| `session_aw` | `float` | Session AW | |
|
||||
| `session_price_settlement` | `float` | Session price settlement | |
|
||||
| `session_price_limit_min` | `float` | Session price limit min | |
|
||||
| `session_price_limit_max` | `float` | Session price limit max | |
|
||||
| `margin_hedged` | `float` | Margin hedged | |
|
||||
| `price_change` | `float` | Price change | |
|
||||
| `price_volatility` | `float` | Price volatility | |
|
||||
| `price_theoretical` | `float` | Price theoretical | |
|
||||
| `price_greeks_delta` | `float` | Price greeks delta | |
|
||||
| `price_greeks_theta` | `float` | Price greeks theta | |
|
||||
| `price_greeks_gamma` | `float` | Price greeks gamma | |
|
||||
| `price_greeks_vega` | `float` | Price greeks vega | |
|
||||
| `price_greeks_rho` | `float` | Price greeks rho | |
|
||||
| `price_greeks_omega` | `float` | Price greeks omega | |
|
||||
| `price_sensitivity` | `float` | Price sensitivity | |
|
||||
| `basis` | `str` | Basis | |
|
||||
| `category` | `str` | Category | |
|
||||
| `currency_base` | `str` | Base currency | |
|
||||
| `currency_profit` | `str` | Profit currency | |
|
||||
| `currency_margin` | `Any` | Margin currency | |
|
||||
| `bank` | `str` | Bank | |
|
||||
| `description` | `str` | Description | |
|
||||
| `exchange` | `str` | Exchange | |
|
||||
| `formula` | `Any` | Formula | |
|
||||
| `isin` | `Any` | ISIN | |
|
||||
| `name` | `str` | Name | |
|
||||
| `page` | `str` | Page | |
|
||||
| `path` | `str` | Path | |
|
||||
### `TerminalInfo`
|
||||
|
||||
> MetaTrader 5 terminal details.
|
||||
|
||||
<a id="models.book_info"></a>
|
||||
### BookInfo
|
||||
```python
|
||||
class BookInfo(Base)
|
||||
```
|
||||
Book Information Class.
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|--------------|------------|-------------|---------|
|
||||
| `symbol` | `str` | Symbol | |
|
||||
| `type` | `BookType` | Type | |
|
||||
| `price` | `float` | Price | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `volume_dbl` | `float` | Volume dbl | |
|
||||
Key fields: `connected`, `trade_allowed`, `tradeapi_disabled`, `build`, `company`,
|
||||
`name`, `path`, `data_path`.
|
||||
|
||||
---
|
||||
|
||||
<a id="models.trade_order"></a>
|
||||
#### TradeOrder
|
||||
```python
|
||||
class TradeOrder(Base)
|
||||
```
|
||||
Trade Order Class.
|
||||
### `SymbolInfo`
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|-------------------|----------------|-----------------|---------|
|
||||
| `ticket` | `int` | Ticket | |
|
||||
| `time_setup` | `int` | Time setup | |
|
||||
| `time_setup_msc` | `int` | Time setup msc | |
|
||||
| `time_expiration` | `int` | Time expiration | |
|
||||
| `time_done` | `int` | Time done | |
|
||||
| `time_done_msc` | `int` | Time done msc | |
|
||||
| `type` | `OrderType` | Type | |
|
||||
| `type_time` | `OrderTime` | Type time | |
|
||||
| `type_filling` | `OrderFilling` | Type filling | |
|
||||
| `state` | `int` | State | |
|
||||
| `magic` | `int` | Magic | |
|
||||
| `position_id` | `int` | Position id | |
|
||||
| `position_by_id` | `int` | Position by id | |
|
||||
| `reason` | `OrderReason` | Reason | |
|
||||
| `volume_current` | `float` | Volume current | |
|
||||
| `volume_initial` | `float` | Volume initial | |
|
||||
| `price_open` | `float` | Price open | |
|
||||
| `sl` | `float` | SL | |
|
||||
| `tp` | `float` | TP | |
|
||||
| `price_current` | `float` | Price current | |
|
||||
| `price_stoplimit` | `float` | Price stoplimit | |
|
||||
| `symbol` | `str` | Symbol | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `external_id` | `str` | External id | |
|
||||
> Trading instrument (symbol) properties.
|
||||
|
||||
Extensive attributes covering pricing, volume limits, spread, margin parameters, swap
|
||||
settings, option properties, and session schedules.
|
||||
|
||||
<a id="models.trade_request"></a>
|
||||
## TradeRequest
|
||||
```python
|
||||
class TradeRequest(Base)
|
||||
```
|
||||
Trade Request Class.
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|----------------|--------------|--------------|---------|
|
||||
| `action` | TradeAction | Action | |
|
||||
| `type` | OrderType | Type | |
|
||||
| `order` | `int` | Order | |
|
||||
| `symbol` | `str` | Symbol | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `sl` | `float` | SL | |
|
||||
| `tp` | `float` | TP | |
|
||||
| `price` | `float` | Price | |
|
||||
| `deviation` | `float` | Deviation | |
|
||||
| `stop_limit` | `float` | Stop limit | |
|
||||
| `type_time` | OrderTime | Type time | |
|
||||
| `type_filling` | OrderFilling | Type filling | |
|
||||
| `expiration` | `int` | Expiration | |
|
||||
| `position` | `int` | Position | |
|
||||
| `position_by` | `int` | Position by | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `magic` | `int` | Magic | |
|
||||
| `deviation` | `int` | Deviation | |
|
||||
| Method / Property | Description |
|
||||
|-------------------|-------------|
|
||||
| `__repr__()` | `"SymbolInfo(name=<name>)"` |
|
||||
| `__str__()` | The symbol name |
|
||||
| `__eq__(other)` | Equality by symbol name |
|
||||
| `__hash__()` | Hash of the symbol name |
|
||||
|
||||
---
|
||||
|
||||
<a id="models.order_check_result"></a>
|
||||
### OrderCheckResult
|
||||
```python
|
||||
class OrderCheckResult(Base)
|
||||
```
|
||||
Order Check Result
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|----------------|----------------|--------------|---------|
|
||||
| `retcode` | `int` | Retcode | |
|
||||
| `balance` | `float` | Balance | |
|
||||
| `equity` | `float` | Equity | |
|
||||
| `profit` | `float` | Profit | |
|
||||
| `margin` | `float` | Margin | |
|
||||
| `margin_free` | `float` | Margin free | |
|
||||
| `margin_level` | `float` | Margin level | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `request` | `TradeRequest` | Request | |
|
||||
### `BookInfo`
|
||||
|
||||
> Market depth entry.
|
||||
|
||||
<a id="models.order_send_result"></a>
|
||||
### OrderSendResult
|
||||
```python
|
||||
class OrderSendResult(Base)
|
||||
```
|
||||
Order Send Result
|
||||
Fields: `type` (`BookType`), `price`, `volume`, `volume_dbl`.
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|--------------------|----------------|------------------|---------|
|
||||
| `retcode` | `int` | Retcode | |
|
||||
| `deal` | `int` | Deal | |
|
||||
| `order` | `int` | Order | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `price` | `float` | Price | |
|
||||
| `bid` | `float` | Bid | |
|
||||
| `ask` | `float` | Ask | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `request` | `TradeRequest` | Request | |
|
||||
| `request_id` | `int` | Request id | |
|
||||
| `retcode_external` | `int` | Retcode external | |
|
||||
| `profit` | `float` | Profit | |
|
||||
---
|
||||
|
||||
### `TradeOrder`
|
||||
|
||||
<a id="models.trade_position"></a>
|
||||
### TradePosition
|
||||
```python
|
||||
class TradePosition(Base)
|
||||
```
|
||||
Trade Position
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|-------------------|------------------|-----------------|---------|
|
||||
| `ticket` | `int` | Ticket | |
|
||||
| `time` | `int` | Time | |
|
||||
| `time_msc` | `int` | Time msc | |
|
||||
| `time_update` | `int` | Time update | |
|
||||
| `time_update_msc` | `int` | Time update msc | |
|
||||
| `type` | `OrderType` | Type | |
|
||||
| `magic` | `float` | Magic | |
|
||||
| `identifier` | `int` | Identifier | |
|
||||
| `reason` | `PositionReason` | Reason | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `price_open` | `float` | Price open | |
|
||||
| `sl` | `float` | SL | |
|
||||
| `tp` | `float` | TP | |
|
||||
| `price_current` | `float` | Price current | |
|
||||
| `swap` | `float` | Swap | |
|
||||
| `profit` | `float` | Profit | |
|
||||
| `symbol` | `str` | Symbol | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `external_id` | `str` | External id | |
|
||||
> Pending or historical order.
|
||||
|
||||
Key fields: `ticket`, `type` (`OrderType`), `state`, `time_setup`, `volume_current`,
|
||||
`volume_initial`, `price_open`, `sl`, `tp`, `symbol`, `comment`.
|
||||
|
||||
<a id="models.trade_deal"></a>
|
||||
### TradeDeal
|
||||
```python
|
||||
class TradeDeal(Base)
|
||||
```
|
||||
Trade Deal
|
||||
#### Attributes:
|
||||
| Name | Type | Description | Default |
|
||||
|---------------|--------------|-------------|---------|
|
||||
| `ticket` | `int` | Ticket | |
|
||||
| `order` | `int` | Order | |
|
||||
| `time` | `int` | Time | |
|
||||
| `time_msc` | `int` | Time msc | |
|
||||
| `type` | `DealType` | Type | |
|
||||
| `entry` | `DealEntry` | Entry | |
|
||||
| `magic` | `int` | Magic | |
|
||||
| `position_id` | `int` | Position id | |
|
||||
| `reason` | `DealReason` | Reason | |
|
||||
| `volume` | `float` | Volume | |
|
||||
| `price` | `float` | Price | |
|
||||
| `commission` | `float` | Commission | |
|
||||
| `swap` | `float` | Swap | |
|
||||
| `profit` | `float` | Profit | |
|
||||
| `fee` | `float` | Fee | |
|
||||
| `sl` | `float` | SL | |
|
||||
| `tp` | `float` | TP | |
|
||||
| `symbol` | `str` | Symbol | |
|
||||
| `comment` | `str` | Comment | |
|
||||
| `external_id` | `str` | External id | |
|
||||
---
|
||||
|
||||
### `TradeRequest`
|
||||
|
||||
> Trade request structure sent to `order_send` / `order_check`.
|
||||
|
||||
Key fields: `action` (`TradeAction`), `type` (`OrderType`), `symbol`, `volume`,
|
||||
`price`, `sl`, `tp`, `deviation`, `magic`, `comment`, `type_filling`, `type_time`.
|
||||
|
||||
---
|
||||
|
||||
### `OrderCheckResult`
|
||||
|
||||
> Result of `order_check`.
|
||||
|
||||
Key fields: `retcode`, `balance`, `equity`, `profit`, `margin`, `margin_free`,
|
||||
`margin_level`, `request` (`TradeRequest`), `comment`.
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `__init__(**kwargs)` | Converts `request` dict to `TradeRequest` |
|
||||
| `__getstate__()` | Serialises `request` as a plain dict |
|
||||
| `__setstate__(state)` | Restores `request` from dict |
|
||||
|
||||
---
|
||||
|
||||
### `OrderSendResult`
|
||||
|
||||
> Result of `order_send`.
|
||||
|
||||
Key fields: `retcode`, `deal`, `order`, `volume`, `price`, `bid`, `ask`,
|
||||
`request` (`TradeRequest`), `comment`, `request_id`.
|
||||
|
||||
---
|
||||
|
||||
### `TradePosition`
|
||||
|
||||
> Open position information.
|
||||
|
||||
Key fields: `ticket`, `type` (`PositionType`), `symbol`, `volume`, `price_open`,
|
||||
`price_current`, `sl`, `tp`, `profit`, `swap`, `magic`, `comment`.
|
||||
|
||||
---
|
||||
|
||||
### `TradeDeal`
|
||||
|
||||
> Completed deal record.
|
||||
|
||||
Key fields: `ticket`, `type` (`DealType`), `entry` (`DealEntry`), `symbol`, `volume`,
|
||||
`price`, `profit`, `swap`, `commission`, `magic`, `comment`, `position_id`, `order`.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# state
|
||||
|
||||
`aiomql.core.state` — Singleton persistent key-value store backed by SQLite.
|
||||
|
||||
## Overview
|
||||
|
||||
The `State` class implements `MutableMapping`, providing dict-like access to data that is
|
||||
automatically persisted to a SQLite database. The entire state is stored as a single pickled
|
||||
row — ideal for small, frequently-accessed configuration data. It uses the singleton pattern
|
||||
so all parts of the application share the same state.
|
||||
|
||||
## Classes
|
||||
|
||||
### `State`
|
||||
|
||||
> Singleton persistent key-value store.
|
||||
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `db_name` | `str \| Path` | Path to the SQLite database |
|
||||
| `autocommit` | `bool` | If `True`, commits after every modification |
|
||||
|
||||
#### `__init__(db_name="", data=None, flush=False, autocommit=True)`
|
||||
|
||||
Initialises the state. If `flush` is `True`, all existing data is cleared.
|
||||
|
||||
#### Dict-like Interface
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `__getitem__(key)` | Get a value by key |
|
||||
| `__setitem__(key, value)` | Set a value |
|
||||
| `__delitem__(key)` | Delete a key-value pair |
|
||||
| `__contains__(key)` | Check if a key exists |
|
||||
| `__len__()` | Number of items |
|
||||
| `__iter__()` | Iterate over keys |
|
||||
| `get(key, default=None)` | Get with default |
|
||||
| `pop(key, default=SENTINEL)` | Remove and return |
|
||||
| `update(data, **kwargs)` | Bulk update |
|
||||
| `setdefault(key, default=None)` | Get or set default |
|
||||
| `keys()` / `values()` / `items()` | Standard views |
|
||||
|
||||
#### Persistence
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `commit()` | Writes current state to the database |
|
||||
| `load()` | Loads state from the database |
|
||||
| `flush()` | Clears all data (in-memory and on disk) |
|
||||
@@ -0,0 +1,51 @@
|
||||
# store
|
||||
|
||||
`aiomql.core.store` — Per-key persistent key-value store backed by SQLite.
|
||||
|
||||
## Overview
|
||||
|
||||
The `Store` class provides a persistent dict-like interface backed by SQLite. Unlike
|
||||
[`State`](state.md) (which stores all data as a single pickled row), `Store` keeps each
|
||||
key-value pair as a separate database row. This makes it more suitable for large or
|
||||
independently-accessed data sets.
|
||||
|
||||
## Classes
|
||||
|
||||
### `Store`
|
||||
|
||||
> Persistent key-value store with per-row storage.
|
||||
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `db_name` | `str \| Path` | Path to the SQLite database |
|
||||
| `table_name` | `str` | Table name (default: `"store"`) |
|
||||
| `autocommit` | `bool` | If `True`, commits after every modification |
|
||||
|
||||
#### `__init__(db_name="", table_name="store", data=None, flush=False, autocommit=True)`
|
||||
|
||||
Initialises the store, optionally flushing existing data.
|
||||
|
||||
#### Dict-like Interface
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `__getitem__(key)` | Get a value by key |
|
||||
| `__setitem__(key, value)` | Set or replace a value |
|
||||
| `__delitem__(key)` | Delete a key-value pair |
|
||||
| `__contains__(key)` | Check if a key exists |
|
||||
| `__len__()` | Number of items |
|
||||
| `__iter__()` | Iterate over keys |
|
||||
| `get(key, default=None)` | Get with default |
|
||||
| `pop(key, default=SENTINEL)` | Remove and return |
|
||||
| `update(data, **kwargs)` | Bulk update |
|
||||
| `setdefault(key, default=None)` | Get or set default |
|
||||
| `keys()` / `values()` / `items()` | Standard list accessors |
|
||||
| `iterkeys()` / `itervalues()` / `iteritems()` | Generator-based accessors |
|
||||
| `clear()` | Remove all entries |
|
||||
|
||||
#### Persistence
|
||||
|
||||
| Property | Description |
|
||||
|----------|-------------|
|
||||
| `data` | Returns all key-value pairs as a dict |
|
||||
| `commit()` | Commits pending changes |
|
||||
+47
-161
@@ -1,181 +1,67 @@
|
||||
# TaskQueue and QueueItem
|
||||
# task_queue
|
||||
|
||||
## Table of Contents
|
||||
- [QueueItem](#queue_item.queue_item)
|
||||
- [\__init\__](#queue_item.__init__)
|
||||
- [run](#queue_item.run)
|
||||
`aiomql.core.task_queue` — Async priority task queue for managing concurrent execution.
|
||||
|
||||
- [TaskQueue](#task_queue.task_queue)
|
||||
- [\__init\__](#task_queue.__init__)
|
||||
- [add](#task_queue.add)
|
||||
- [add_task](#task_queue.add_task)
|
||||
- [worker](#task_queue.worker)
|
||||
- [run](#task_queue.run)
|
||||
- [stop_queue](#task_queue.stop_queue)
|
||||
- [clean_up](#task_queue.clean_up)
|
||||
- [cancel](#task_queue.cancel)
|
||||
## Overview
|
||||
|
||||
Provides `QueueItem` (a callable wrapper) and `TaskQueue` (an `asyncio.PriorityQueue`-based
|
||||
executor). Supports priority-based scheduling, dynamic worker scaling, timeout handling, and
|
||||
both **finite** (run until empty) and **infinite** (run until stopped) modes.
|
||||
|
||||
<a id="queue_item.queue_item"></a>
|
||||
### QueueItem
|
||||
```python
|
||||
class QueueItem
|
||||
```
|
||||
A task to be executed by the `TaskQueue`. The task can be any coroutine callable. The task is wrapped as a
|
||||
`QueueItem` object, which is then added to the `TaskQueue` for execution. The arguments and keyword arguments are
|
||||
passed to the task when it is executed.
|
||||
## Classes
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|-----------------|---------------------------|-----------------------------------------------------------------------|
|
||||
| `task_item` | `Callable` \| `Coroutine` | A coroutine function to be executed by the `TaskQueue` |
|
||||
| `args` | `tuple[Any, ...]` | Positional arguments to be passed to the task_item |
|
||||
| `kwargs` | `dict[str, Any]` | Keyword arguments to be passed to the task_item |
|
||||
| `must_complete` | `bool` | If True, the item must be completed even if the queue is stopped. |
|
||||
| `time` | `float` | The time the item was added to the queue. For sorting priority queues |
|
||||
### `QueueItem`
|
||||
|
||||
> Wraps a callable or coroutine for deferred, priority-aware execution.
|
||||
|
||||
<a id="queue_item.__init__"></a>
|
||||
### \__init\__
|
||||
```python
|
||||
def __init__(self, task: Callable | Coroutine, *args, **kwargs):
|
||||
```
|
||||
| Attribute | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `task` | `Callable \| Coroutine` | The wrapped callable |
|
||||
| `args` | `tuple` | Positional arguments |
|
||||
| `kwargs` | `dict` | Keyword arguments |
|
||||
| `time` | `float` | Creation timestamp (used for ordering) |
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|---------------------------|-------------------------------------------------------------------|
|
||||
| `task` | `Callable` \| `Coroutine` | A coroutine to be executed by the `TaskQueue` |
|
||||
| `args` | `Any` | Positional arguments to be passed to the task when it is executed |
|
||||
| `kwargs` | `Any` | Keyword arguments to be passed to the task when it is executed |
|
||||
#### `__call__()`
|
||||
|
||||
Executes the task. Coroutine functions are awaited directly; regular callables are run
|
||||
in a thread executor. Handles `asyncio.CancelledError`.
|
||||
|
||||
<a id="queue.run"></a>
|
||||
### run
|
||||
```python
|
||||
def run(self)
|
||||
```
|
||||
Run the task. If the task is a coroutine, it is awaited. If the task is a callable, it is called.
|
||||
Comparison operators (`<`, `<=`, `==`) are based on creation time.
|
||||
|
||||
---
|
||||
|
||||
<a id="task_queue.task_queue"></a>
|
||||
### TaskQueue
|
||||
```python
|
||||
class TaskQueue
|
||||
```
|
||||
A perpetual task queue that processes `QueueItem` objects. The `TaskQueue` runs indefinitely, processing `QueueItem`
|
||||
objects as they are added to the queue. The `TaskQueue` is a wrapper around an `asyncio.Queue` that can be passed in as
|
||||
an argument or defaults to an `asyncio.PriorityQueue`. It is added to the bot executor of the `Bot` class on a
|
||||
separate thread.
|
||||
### `TaskQueue`
|
||||
|
||||
#### Attributes:
|
||||
| Name | Type | Description |
|
||||
|------------------|------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `queue` | `asyncio.Queue` | An `asyncio.Queue` queue of `QueueItem` objects to be executed by the `TaskQueue`. If not provided during instantiation, an `asyncio.PriorityQueue` is used |
|
||||
| `stop` | `bool` | A flag to stop the task_queue instance. |
|
||||
| `workers` | `int` | The number of workers to process the queue items. Defaults to 10. |
|
||||
| `timeout` | `int` | The maximum time to wait for the queue to complete. Default is None. If timeout is provided the queue is joined using `asyncio.wait_for` with the timeout |
|
||||
| `on_exit` | `Literal["cancel", "complete_priority"]` | The action to take when the queue is stopped. If "cancel" the queue is cancelled and the remaining items are not processed. If "complete_priority" the queue is completed with the priority items. Default is "cancel" |
|
||||
| `mode` | `Literal["finite", "infinite"]` | The mode of the queue. If `finite` the queue will stop when all tasks are completed. If `infinite` the queue will continue to run until stopped. |
|
||||
| `worker_timeout` | `int` | The time to wait for a task to be added to the queue before stopping the worker or adding a dummy sleep task to the queue. |
|
||||
| `tasks` | `List[Task]` | A list of the worker tasks running concurrently, including the main task that joins the queue. |
|
||||
| `priority_tasks` | `set[QueueItem]` | A set to store the `QueueItems` that must complete before the queue stops |
|
||||
> Priority-based async task queue with worker management.
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `size` | `int` | `0` | Max queue size (0 = unlimited) |
|
||||
| `max_workers` | `int \| None` | `None` | Max concurrent workers |
|
||||
| `queue_timeout` | `int \| None` | `None` | Overall timeout in seconds |
|
||||
| `on_exit` | `Literal["cancel","complete_priority"]` | `"complete_priority"` | Shutdown behaviour |
|
||||
| `mode` | `Literal["finite","infinite"]` | `"finite"` | Queue mode |
|
||||
|
||||
<a id="task_queue.__init__"></a>
|
||||
### \__init\__
|
||||
```python
|
||||
def __init__(self, queue: asyncio.Queue = None, workers: int = 10, timeout: int = None, size: int = None,
|
||||
on_exit: Literal["cancel", "complete_priority"] = "cancel",
|
||||
mode: Literal["finite", "infinite"] = "infinite", worker_timeout: int = 60)
|
||||
```
|
||||
Create a new `TaskQueue` instance.
|
||||
#### Task Management
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description | Default |
|
||||
|------------------|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------|---------------------|
|
||||
| `queue` | `asyncio.Queue` | An `asyncio.Queue` queue instance | None |
|
||||
| `workers` | `int` | The number of workers to process the queue items. | 10 |
|
||||
| `timeout` | `int` | The maximum time to wait for the queue to complete. | None |
|
||||
| `size` | `int` | The maximum size of the queue. | None |
|
||||
| `on_exit` | `Literal["cancel", "complete_priority"]` | The action to take when the queue is stopped. | "complete_priority" |
|
||||
| `mode` | `Literal["finite", "infinite"]` | The mode of the queue. | "infinite" |
|
||||
| `worker_timeout` | `int` | The time to wait for a task to be added to the queue before stopping the worker or adding a dummy sleep task to the queue. | 60 |
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `add_task(task, *args, must_complete=False, priority=3, **kwargs)` | Wraps and enqueues a task |
|
||||
| `add(*, item, priority=3, must_complete=False, with_new_workers=True)` | Enqueues a `QueueItem` |
|
||||
|
||||
#### Worker Management
|
||||
|
||||
<a id="task_queue.add"></a>
|
||||
### add
|
||||
```python
|
||||
def add(*, item: QueueItem, priority: int = 3, must_complete_false: bool = False) -> None
|
||||
```
|
||||
Add a `QueueItem` to the `TaskQueue` queue.
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `add_workers(no_of_workers=None)` | Creates worker coroutines |
|
||||
| `remove_worker(wid)` | Removes a specific worker |
|
||||
| `cancel_all_workers()` | Cancels all workers |
|
||||
| `cancel()` | Cancels workers and stops the queue |
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------------------|-------------|----------------------------------------------------------------------------------------|
|
||||
| `item` | `QueueItem` | A `QueueItem` to be added to the queue |
|
||||
| `priority` | `int` | The priority of the item. The lower the number, the higher the priority. Default is 3. |
|
||||
| `must_complete_false` | `bool` | If True, the item must be completed even if the queue is stopped. Default is False. |
|
||||
#### Execution
|
||||
|
||||
|
||||
<a id="task_queue.add_task"></a>
|
||||
### add_task
|
||||
```python
|
||||
def add_task(self, task: Callable | Awaitable, *args, **kwargs)
|
||||
```
|
||||
Create a QueueItem from the task and add it to the `TaskQueue` queue. The task can be a callable or an awaitable.
|
||||
The arguments and keyword arguments are passed to the QueueItem.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|----------|---------------------------|-------------------------------------------------------------------|
|
||||
| `task` | `Callable` \| `Awaitable` | A callable or awaitable task to be executed by the `TaskQueue` |
|
||||
| `args` | `Any` | Positional arguments to be passed to the task when it is executed |
|
||||
| `kwargs` | `Any` | Keyword arguments to be passed to the task when it is executed |
|
||||
|
||||
<a id="task_queue.worker"></a>
|
||||
### worker
|
||||
```python
|
||||
async def worker()
|
||||
```
|
||||
A worker that processes the `QueueItem` objects in the `TaskQueue` queue.
|
||||
|
||||
|
||||
<a id="task_queue.run"></a>
|
||||
### run
|
||||
```python
|
||||
async def run(timeout: int = None)
|
||||
```
|
||||
Start the `TaskQueue` instance. If a timeout is provided, the queue is joined using `asyncio.wait_for` with the timeout.
|
||||
This is the main entry point for the `TaskQueue` instance. It is added to the bot executor of the `Bot` class on a
|
||||
separate thread.
|
||||
|
||||
#### Parameters:
|
||||
| Name | Type | Description |
|
||||
|-----------|-------|----------------------------------------------------------------------|
|
||||
| `timeout` | `int` | The maximum time to wait for the queue to complete. Default is None. |
|
||||
|
||||
|
||||
<a id="task_queue.stop_queue"></a>
|
||||
### stop_queue
|
||||
```python
|
||||
def stop_queue()
|
||||
```
|
||||
Stop the `TaskQueue` instance. This sets the `stop` attribute to True, changes the `on_exit` attribute to "cancel",
|
||||
and cancels the queue.
|
||||
|
||||
|
||||
<a id="task_queue.clean_up"></a>
|
||||
### clean_up
|
||||
```python
|
||||
async def clean_up()
|
||||
```
|
||||
Clean up the `TaskQueue` instance. This is called when the queue is stopped. It cancels the queue and processes the
|
||||
remaining priority items based on the `on_exit` attribute.
|
||||
|
||||
|
||||
<a id="task_queue.cancel"></a>
|
||||
### cancel
|
||||
```python
|
||||
def cancel()
|
||||
```
|
||||
Cancel all remaining tasks.
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `run(queue_timeout=None)` | Starts workers and processes the queue |
|
||||
| `worker(wid=None)` | Internal worker coroutine |
|
||||
| `check_timeout()` | Checks and enforces queue timeout |
|
||||
|
||||
Reference in New Issue
Block a user