From 4f0150a552b6c31681281ee24e16e4b8bc1bf3a3 Mon Sep 17 00:00:00 2001 From: Ichinga Samuel Date: Tue, 29 Oct 2024 13:04:45 +0100 Subject: [PATCH] v3.23 --- docs/TOC.md | 30 + docs/account.md | 85 + docs/bot_builder.md | 105 + docs/candle.md | 154 ++ docs/core/base.md | 109 ++ docs/core/config.md | 72 + docs/core/constants.md | 579 ++++++ docs/core/errors.md | 30 + docs/core/exceptions.md | 37 + docs/core/meta_trader.md | 624 ++++++ docs/core/model.md | 0 docs/core/models.md | 374 ++++ docs/core/task_queue.md | 91 + docs/executor.md | 77 + docs/history.md | 110 ++ docs/lib/account.md | 97 + docs/lib/bot_builder.md | 162 ++ docs/lib/candle.md | 242 +++ docs/lib/executor.md | 102 + docs/lib/history.md | 196 ++ docs/lib/order.md | 133 ++ docs/lib/positions.md | 135 ++ docs/lib/ram.md | 74 + docs/lib/records.md | 96 + docs/lib/result.md | 60 + docs/lib/sessions.md | 177 ++ docs/lib/strategy.md | 65 + docs/lib/symbol.md | 337 ++++ docs/lib/terminal.md | 77 + docs/lib/ticks.md | 125 ++ docs/lib/trade_records.md | 127 ++ docs/lib/trader.md | 113 ++ docs/lib/utils.md | 66 + docs/main.md | 3842 +++++++++++++++++++++++++++++++++++++ docs/order.md | 115 ++ docs/positions.md | 72 + docs/ram.md | 83 + docs/records.md | 103 + docs/result.md | 56 + docs/sessions.md | 169 ++ docs/strategy.md | 52 + docs/symbol.md | 310 +++ docs/terminal.md | 71 + docs/ticks.md | 97 + docs/trader.md | 65 + 45 files changed, 9896 insertions(+) create mode 100644 docs/TOC.md create mode 100644 docs/account.md create mode 100644 docs/bot_builder.md create mode 100644 docs/candle.md create mode 100644 docs/core/base.md create mode 100644 docs/core/config.md create mode 100644 docs/core/constants.md create mode 100644 docs/core/errors.md create mode 100644 docs/core/exceptions.md create mode 100644 docs/core/meta_trader.md create mode 100644 docs/core/model.md create mode 100644 docs/core/models.md create mode 100644 docs/core/task_queue.md create mode 100644 docs/executor.md create mode 100644 docs/history.md create mode 100644 docs/lib/account.md create mode 100644 docs/lib/bot_builder.md create mode 100644 docs/lib/candle.md create mode 100644 docs/lib/executor.md create mode 100644 docs/lib/history.md create mode 100644 docs/lib/order.md create mode 100644 docs/lib/positions.md create mode 100644 docs/lib/ram.md create mode 100644 docs/lib/records.md create mode 100644 docs/lib/result.md create mode 100644 docs/lib/sessions.md create mode 100644 docs/lib/strategy.md create mode 100644 docs/lib/symbol.md create mode 100644 docs/lib/terminal.md create mode 100644 docs/lib/ticks.md create mode 100644 docs/lib/trade_records.md create mode 100644 docs/lib/trader.md create mode 100644 docs/lib/utils.md create mode 100644 docs/main.md create mode 100644 docs/order.md create mode 100644 docs/positions.md create mode 100644 docs/ram.md create mode 100644 docs/records.md create mode 100644 docs/result.md create mode 100644 docs/sessions.md create mode 100644 docs/strategy.md create mode 100644 docs/symbol.md create mode 100644 docs/terminal.md create mode 100644 docs/ticks.md create mode 100644 docs/trader.md diff --git a/docs/TOC.md b/docs/TOC.md new file mode 100644 index 0000000..2d7503b --- /dev/null +++ b/docs/TOC.md @@ -0,0 +1,30 @@ +# Table of Contents +- [MetaTrader](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/meta_trader.md) +- [Config](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/config.md) +- [Base](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/base.md) +- [Constants](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/constants.md) +- [TaskQueue](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/task_queue.md) +- [Models](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/models.md) +- [Bot_Builder](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/bot_builder.md) +- [Account](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/account.md) +- [Candle](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/candle.md) +- [Candles](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/candle.md) +- [Executor](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/executor.md) +- [History](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/history.md) +- [Order](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/order.md) +- [Positions](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/postions.md) +- [RAM](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/ram.md) +- [Records](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/records.md) +- [TradeRecords](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/trade_records.md) +- [Result](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/result.md) +- [Session](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/sessions.md) +- [Sessions](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/sessions.md) +- [Symbol](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/symbol.md) +- [Strategy](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/stategy.md) +- [Terminal](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/terminal.md) +- [Tick](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/ticks.md) +- [Ticks](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/ticks.md) +- [Trader](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/trader.md) +- [utils](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/utils.md) +- [Errors](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/errors.md) +- [Exceptions](https://github.com/Ichinga-Samuel/aiomql/blob/master/docs/core/exceptions.md) diff --git a/docs/account.md b/docs/account.md new file mode 100644 index 0000000..68067e9 --- /dev/null +++ b/docs/account.md @@ -0,0 +1,85 @@ +## Account + +```python +class Account(AccountInfo) +``` +Singleton class for managing a trading account. A subclass of [AccountInfo](#accountinfo). All AccountInfo attributes are available in this class. + +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**connected**|**bool**|Status of connection to MetaTrader 5 Terminal|False| +|symbols|set[SymbolInfo]|A set of available symbols for the financial market.|set()| + +### Notes +Other Account properties are defined in the AccountInfo class. + +### refresh +```python +async def refresh() +``` +Refreshes the account instance with the latest data from the MetaTrader 5 terminal + +### account_info +```python +@property +def account_info() -> dict +``` +Get account login, server and password details. If the login attribute of the account instance returns +a falsy value, the config instance is used to get the account details. +#### Returns: +|Type|Description| +|---|---| +|**dict**|A dict of login, server and password details| +#### Note: +This method will only look for config details in the config instance if the login attribute of the account Instance returns a falsy value + +### __aenter__ +```python +async def __aenter__() -> 'Account' +``` +Connect to a trading account and return the account instance. +Async context manager for the Account class. +#### Returns: +|Type|Description| +|---|---| +|**Account**|An instance of the Account class| +#### Raises: +|Exception|Description| +|---|---| +|**LoginError**|If login fails| + +### sign_in +```python +async def sign_in() -> bool +``` +Connect to a trading account. +#### Returns: +|Type|Description| +|---|---| +|**bool**|True if login was successful else False| + +### has_symbol +```python +def has_symbol(symbol: str | Type[SymbolInfo]) +``` +Checks to see if a symbol is available for a trading account\ +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**symbol**|**str** or **SymbolInfo**|A symbol name or SymbolInfo instance| +#### Returns: +|Type|Description| +|---|---| +|**bool**|True if symbol is available else False| + +### symbols_get +```python +async def symbols_get() -> set[SymbolInfo] +``` +Get all financial instruments from the MetaTrader 5 terminal available for the current account. +#### Returns: +|Type|Description| +|---|---| +|**set[SymbolInfo]**|A set of SymbolInfo instances| + diff --git a/docs/bot_builder.md b/docs/bot_builder.md new file mode 100644 index 0000000..3be23c1 --- /dev/null +++ b/docs/bot_builder.md @@ -0,0 +1,105 @@ +## Bot Builder + +```python +class Bot() +``` +The bot class. Create a bot instance to run your strategies. +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**account**|**Account**|Account Object.|None| +|**executor**|**ThreadPoolExecutor**|The default thread executor.|None| +|**symbols**|**set[Symbols]**|A set of symbols for the trading session|set()| + +### initialize +```python +async def initialize() +``` +Prepares the bot by signing in to the trading account and initializing the symbols for the trading session. +#### Raises: +|Exception|Description| +|---|---| +|**SystemExit**|If sign in was not successful| + +### execute +```python +def execute() +``` +Execute the bot. This method calls start internally. To enable you run your bot outside of an async function. +### start +```python +async def start() +``` +Starts the bot by calling the initialize method and running the strategies in the executor. + +### add_coroutine +```python +def add_coroutine(coro: Coroutine, **kwargs) +``` +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**coro**|**Coroutine**|A coroutine to run in the executor| + +### add_function +```python +def add_coroutine(func: Callable, **kwargs) +``` +#### Arguments: +| Name | Type | Description | +|----------|--------------|-----------------------------------| +| **func** | **Callable** | A function to run in the executor | + +### add_strategy +```python +def add_strategy(strategy: Strategy) +``` +Add a strategy to the executor. An added strategy will only run if it's symbol was successfully initialized. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**strategy**|**Strategy**|A Strategy instance to run on bot| + +### add_strategies +```python +def add_strategies(strategies: Iterable[Strategy]) +``` +Add multiple strategies at the same time +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**strategies**|**Iterable[Strategy]**|An iterable of Strategy instances| + +### add_strategy_all +```python +def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None) +``` +Use this to run a single strategy on all available instruments in the market using the default parameters +i.e one set of parameters for all trading symbols +#### Arguments +|Name|Type|Description| +|---|---|---| +|**strategy**|**Type[Strategy]**|A Strategy class| +|**params**|**dict** or **None**|A dictionary of parameters for the strategy| + +### init_symbols +```python +async def init_symbols() +``` +Initialize the symbols for the current trading session. This method is called internally by the bot. + +### init_symbol +```python +async def init_symbol(symbol: Symbol) -> Symbol +``` +Initialize a symbol before the beginning of a trading session. +Removes it from the list of symbols if it was not successfully initialized or not available +for the account. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**symbol**|**Symbol**|A Symbol instance| +#### Returns: +|Type|Description| +|---|---| +|**Symbol**|A Symbol instance| diff --git a/docs/candle.md b/docs/candle.md new file mode 100644 index 0000000..cb56114 --- /dev/null +++ b/docs/candle.md @@ -0,0 +1,154 @@ +## Candle +Candle and Candles classes for handling bars from the MetaTrader 5 terminal. +```python +class Candle +``` +A class representing bars from the MetaTrader 5 terminal as a customized class analogous to Japanese Candlesticks. +You can subclass this class for added customization. + +### Attributes +|Name|Type|Description| +|---|---|---| +|**time**|**int**|Period start time| +|**open**|**int**|Open price| +|**high**|**float**|The highest price of the period| +|**low**|**float**|The lowest price of the period| +|**close**|**float**|Close price| +|**tick_volume**|**float**|Tick volume| +|**real_volume**|**float**|Trade volume| +|**spread**|**float**|Spread| +|**Index**|**int**|Custom attribute representing the position of the candle in a sequence.| + +### \_\_init\_\_ +```python +def __init__(**kwargs) +``` +Create a Candle object from keyword arguments. Kwargs are set as instance attributes. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**kwargs**|**Any**|Candle attributes and values as keyword arguments.| + +### set\_attributes +```python +def set_attributes(**kwargs) +``` +Set keyword arguments as instance attributes + +### mid +```python +@property +def mid() -> float +``` +The median of open and close +#### Returns: +|Type|Description| +|---|---| +|**float**|The median of open and close| + +### is_bullish +```python +def is_bullish() -> bool +``` +A simple check to see if the candle is bullish. +#### Returns: +|Type|Description| +|---|---| +|**bool**|True or False| + +### is_bearish +```python +def is_bearish() -> bool +``` +A simple check to see if the candle is bearish. +#### Returns: +|Type|Description| +|---|---| +|bool|True or False| + +## Candles +```python +class Candles(Generic[_Candle]) +``` +An iterable container class of Candle objects in chronological order. A wrapper around Pandas DataFrame object. +### Attributes: +|Name|Type|Description| +|---|---|---| +|**data**|**DataFrame**|A pandas DataFrame of all candles in the object.| +|**Index**|**Series['int']**|A pandas Series of the indexes of all candles in the object| +|**time**|**Series['int']**|A pandas Series of the time of all candles in the object| +|**open**|**Series[float]**|A pandas Series of the opening price of all candles in the object| +|**high**|**Series[float]**|A pandas Series of the high price of all candles in the object| +|**low**|**Series[float]**|A pandas Series of the low price of all candles in the object| +|**close**|**Series[float]**|A pandas Series of the closing price of all candles in the object| +|**tick_volume**|**Series[float]**|A pandas Series of the tick volume of all candles in the object| +|**real_volume**|**Series[float]**|A pandas Series of the real volume of all candles in the object| +|**spread**|**Series[float]**|A pandas Series of the spread of all candles in the object| +|**timeframe**|**TimeFrame**|The timeframe of the candles in the object| +|**Candle**|**Type[Candle]**|The Candle class for representing the candles in the object.| +|**data**|**DataFrame**|A pandas DataFrame of all candles in the object.| + +**Notes**: When subclassing this class make sure to Candle attribute is set to your desired candle class. + +#### \_\_init\_\_ +```python +def __init__(*, + data: DataFrame | _Candles | Iterable, + flip=False, + candle_class: Type[_Candle] = None) +``` +A container class of Candle objects in chronological order. +#### Arguments: +|Name|Type|Description|Default| +|---|---|---|---| +|**data**|**DataFrame** or **Candles** or **Iterable**|A pandas dataframe, a Candles object or any suitable iterable| +|**flip**|**bool**|Reverse the chronological order of the candles to the oldest first.|False| +|**candle_class**|**Type[Candle]**|A subclass of Candle to use as the candle class.|Candle| + +#### ta +```python +@property +def ta() +``` +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. Use this as you would use the pandas_ta library. + +#### Returns: +|Type|Description| +|---|---| +|**pandas_ta**|The pandas_ta library| + +#### ta\_lib +```python +@property +def ta_lib() +``` +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. Use this for +functions that require pandas Series as input. + +#### Returns: +|Type|Description| +|---|---| +|ta|The ta library| + +#### data +```python +@property +def data() -> DataFrame +``` +A pandas DataFrame of all candles in the object. + +#### rename +```python +def rename(inplace=True, **kwargs) -> _Candles | None +``` +Rename columns of the candles class. +#### Arguments: +| Name | Type |Description|Default| +|---------|----------|---|---| +| inplace | **bool** |Rename the columns inplace or return a new instance of the class with the renamed columns|True| +| **kwargs** | **str** |The new names of the columns|| + +#### Returns: +|Type|Description| +|---|---| +|**Candles**|A new instance of the class with the renamed columns if inplace is False.| diff --git a/docs/core/base.md b/docs/core/base.md new file mode 100644 index 0000000..7f6e34c --- /dev/null +++ b/docs/core/base.md @@ -0,0 +1,109 @@ +# Base Class + +## Table of Contents +- [Base](#base) +- [set\_attributes](#base.set_attributes) +- [annotations](#base.annotations) +- [get\_dict](#base.get_dict) +- [class\_vars](#base.class_vars) +- [dict](#base.dict) + + +### 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. + +#### Class Attributes +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------|---------| +| `mt5` | `MetaTrader` | An instance of the MetaTrader class | | +| `config` | `Config` | An instance of the Config class | | + + +### __init__ +```python +def __init__(**kwargs) +``` +#### Parameters: +| Name | Type | Description | +|----------|-------|---------------------------------------------------| +| `kwargs` | `Any` | Object attributes and values as keyword arguments | + + +### 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 | + +#### Raises +| Exception | Description | +|------------------|-----------------------------------------------------------------------------------| +| `AttributeError` | When assigning an attribute that does not belong to the class or any parent class | + +#### Notes +Only sets attributes that have been annotated on the class body. + + +### annotations +```python +@property +@cache +def annotations() -> dict +``` +Class annotations from all ancestor classes and the current class. +#### Returns +| Type | Description | +|--------|-----------------------------------| +| `dict` | A dictionary of class annotations | + + +#### get\_dict +```python +def get_dict(exclude: set = None, include: set = None) -> dict +``` +Returns class attributes as a dict, with the ability to filter +#### Parameters +| Name | Type | Description | +|-----------|-------|------------------------------------| +| `exclude` | `set` | A set of attributes to be excluded | +| `include` | `set` | Specific attributes to be returned | +#### Returns +| Type | Description | +|--------|--------------------------------------------| +| `dict` | A dictionary of specified class attributes | + +#### Notes +You can only set either of include or exclude. If you set both, include will take precedence + + +### class\_vars +```python +@property +@cache +def class_vars() +``` +Annotated class attributes +#### Returns +| Type | Description | +|--------|-------------------------------------------------------------------------------------------| +| `dict` | A dictionary of available class attributes in all ancestor classes and the current class. | + + +### dict +```python +@property +def dict() -> dict +``` +All instance and class attributes as a dictionary, except those excluded in the Meta class. +#### Returns +| Type | Description | +|--------|-----------------------------------------------| +| `dict` | A dictionary of instance and class attributes | diff --git a/docs/core/config.md b/docs/core/config.md new file mode 100644 index 0000000..6b40cc3 --- /dev/null +++ b/docs/core/config.md @@ -0,0 +1,72 @@ +# Config + +## Table of Contents +- [Config](#config.Config) +- [account\_info](#config.account_info) +- [load\_config](#config.load_config) +- [create\_records\_dir](#config.create_records_dir) + + + +```python +class Config +``` +A class for handling configuration settings for the aiomql package. A single instance of this class is created and used +per bot instance. +### Class Attributes +| Name | Type | Description | Default | +|------------------|--------------|-----------------------------------------------------|-----------------------------------------------------| +| `record\_trades` | `bool` | Whether to keep record of trades or not. | True | +| `filename` | `str` | Name of the config file | aiomql.json | +| `records\_dir` | `str\| Path` | Path to the directory where trade records are saved | Should be relative to the project root | +| `login` | `str` | Trading account number | | +| `password` | `str` | Trading account password | | +| `server` | `str` | Broker server | | +| `path` | `str\|Path` | Path to terminal file | Absolute | +| `timeout` | `int` | Timeout for terminal connection | | +| `config_dir` | `str` | Directory where the config file is located | Optional. Should be relative to the root directory | +| `state` | `dict` | A global state object | | +| `task_queue` | `Queue` | A global queue for handling tasks | | +| `bot` | `Bot` | The bot instance | Added to the config object after bot initialization | +| `root_dir` | `str` | Root directory of the project | | + +#### Notes +By default, the config class looks for a file named aiomql.json. +You can change this by passing the filename keyword argument to the constructor. +By passing reload=True to the load_config method, you can reload and search again for the config file. + + +### account\_info +```python +def account_info() -> dict['login', 'password', 'server'] +``` +Returns Account login details as found in the config object if available +#### Returns +| Type | Description | +|--------|-------------------------------------------------------| +| `dict` | A dictionary with login, password, and server details | + + +### load\_config +```python +def load_config(self, *, file: str = None, reload: bool = True, filename: str = None, config_dir: str = '') +``` +Load configuration settings from a file. +#### Parameters +| Name | Type | Description | +|--------------|--------|-------------------------------------------------------------------------------------------------------------| +| `file` | `str` | The file to load the configuration settings from. If not provided, the default file is used. | +| `reload` | `bool` | Whether to reload the configuration settings or not. | +| `filename` | `str` | The name of the file to load the configuration settings from. If not provided, the default filename is used | +| `config_dir` | `str` | The directory where the configuration file is located. Default is the root directory | + + +### create_records_dir +```python +def create_records_dir(self, *, records_dir: str | Path = 'records'): +``` +Create a directory for saving trade records. +#### Parameters +| Name | Type | Description | +|----------------|-------------|-------------------------------------------------------------------| +| `records\_dir` | `str\|Path` | The directory where trade records are saved. Default is 'records' | diff --git a/docs/core/constants.md b/docs/core/constants.md new file mode 100644 index 0000000..98e516a --- /dev/null +++ b/docs/core/constants.md @@ -0,0 +1,579 @@ +# Constants +MetaTrader 5 constants defined as Enums. + +## Table of Contents +- [TradeAction](#TradeAction) +- [OrderFilling](#OrderFilling) +- [OrderTime](#OrderTime) +- [OrderType](#OrderType) + - [opposite](#ordertype.opposite) +- [BookType](#BookType) +- [TimeFrame](#TimeFrame) + - [time](#timeframe.time) + - [get](#timeframe.get) +- [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) + + +## 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. | + + +## 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. | + + +## 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. | + + +## 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 | + +### Properties +| Name | Description | +|------------|------------------------------------| +| `opposite` | Gets the opposite of an order type | + + +#### 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 | + + +## 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 | + + +## 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 | + + +### get +```python +@classmethod + def get(cls, time: int) -> 'TimeFrame': +``` +Gets the TIMEFRAME enum value from a time in seconds +#### Parameters +| Name | Type | Description | +|-------|------|----------------------| +| time | int | The time in seconds | +#### Returns +| Type | Description | +|------------|--------------------------------------| +| TimeFrame | The TIMEFRAME enum value | + + +### time +```python +@property +def time() +``` +The number of seconds in a TIMEFRAME +#### Returns +| Type | Description | +|------|--------------------------------------| +| int | The number of seconds in a TIMEFRAME | + + +### Example + +```python +t = TimeFrame.H1 +print(t.seconds) # 3600 +``` + + +## 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 | + + +## 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 | + + +## 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 | + + +## 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. | + + +## 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 | + + +## 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 | + + +## 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 | + + +## 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 + +### Members +| Name | Value | Description | +|--------|-------|-------------------------------| +| `BID` | 0 | Bars are based on Bid prices | +| `LAST` | 1 | Bars are based on last prices | + + +## 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 | + + + +## 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 | + + +## 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 | + + +## 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) | + + +## 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 | + + + +## 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 | + + +## 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. | + + +## 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. | + + +## 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 | + + +## 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 | + + +## 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) | + + +## 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 | + + +## 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). | diff --git a/docs/core/errors.md b/docs/core/errors.md new file mode 100644 index 0000000..0c8872b --- /dev/null +++ b/docs/core/errors.md @@ -0,0 +1,30 @@ +# Errors + +## Tabel of contents +- [Error](#errors.Error) +- [is_connection_error](#errors.is_connection_error) + + +## Error +```python +class Error() +``` +Error class for handling errors from MetaTrader 5. +#### Attributes +| Name | Type | Description | +|----------------|--------|----------------------------------------------| +| `code` | `int` | Error code | +| `description` | `str` | Error description | +| `descriptions` | `dict` | A dictionary of error codes and descriptions | + + + +## is_connection_error +```python +def is_connection_error(self) -> bool +``` +Check if error is a connection error. +#### Returns +| Type | Description | +|--------|------------------------------------------------------| +| `bool` | True if error is a connection error, False otherwise | \ No newline at end of file diff --git a/docs/core/exceptions.md b/docs/core/exceptions.md new file mode 100644 index 0000000..f62e14a --- /dev/null +++ b/docs/core/exceptions.md @@ -0,0 +1,37 @@ +# Exceptions +Exceptions for the aiomql package. + +## Table of Contents +- [LoginError](#exceptions.LoginError) +- [VolumeError](#exceptions.VolumeError) +- [SymbolError](#exceptions.SymbolError) +- [OrderError](#exceptions.OrderError) + + + +### LoginError +```python +class LoginError(Exception) +``` +Raised when an error occurs when logging in. + + +### VolumeError +```python +class VolumeError(Exception) +``` +Raised when a volume is not valid or out of range for a symbol. + + +### SymbolError +```python +class SymbolError(Exception) +``` +Raised when a symbol is not provided where required or not available in the Market Watch. + + +### OrderError +```python +class OrderError(Exception) +``` +Raised when an error occurs when working with the order class. \ No newline at end of file diff --git a/docs/core/meta_trader.md b/docs/core/meta_trader.md new file mode 100644 index 0000000..12eef11 --- /dev/null +++ b/docs/core/meta_trader.md @@ -0,0 +1,624 @@ +# MetaTrader +The MetaTrader Class provides an asynchronous wrapper around the MetaTrader5 API. + +## Table of Contents +- [MetaTrader](#MetaTrader) +- [\_\_aenter\_\_](#__aenter__) +- [\_\_aexit\_\_](#__aexit__) +- [login](#login) +- [initialize](#initialize) +- [shutdown](#shutdown) +- [version](#version) +- [account\_info](#account_info) +- [terminal\_info](#terminal_info) +- [last\_error](#last_error) +- [symbols\_total](#symbols_total) +- [symbols\_get](#symbols_get) +- [symbol\_info](#symbol_info) +- [symbol\_info\_tick](#symbol_info_tick) +- [symbol\_select](#symbol_select) +- [market\_book\_add](#market_book_add) +- [market\_book\_get](#market_book_get) +- [market\_book\_release](#market_book_release) +- [copy\_rates\_from](#copy_rates_from) +- [copy\_rates\_from\_pos](#copy_rates_from_pos) +- [copy\_rates\_range](#copy_rates_range) +- [copy\_ticks\_from](#copy_ticks_from) +- [copy\_ticks\_range](#copy_ticks_range) +- [orders\_total](#orders_total) +- [orders\_get](#orders_get) +- [order\_calc\_margin](#order_calc_margin) +- [order\_calc\_profit](#order_calc_profit) +- [order\_check](#order_check) +- [order\_send](#order_send) +- [positions\_total](#positions_total) +- [positions\_get](#positions_get) +- [history\_orders\_total](#history_orders_total) +- [history\_orders\_get](#history_orders_get) +- [history\_deals\_total](#history_deals_total) +- [history\_deals\_get](#history_deals_get) + + +### MetaTrader +```python +class MetaTrader(metaclass=BaseMeta) +``` +The MetaTrader class is a wrapper around the MetaTrader terminal. +It provides methods for connecting to the MetaTrader terminal and retrieving data from it. +#### Attributes +| Name | Type | Description | Default | +|-------|-------|--------------------------------------------------------|------------------------| +| error | Error | The last error encountered by the MetaTrader terminal. | Error(1, 'Successful') | + +#### 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. + + +#### \_\_aenter\_\_ +```python +async def __aenter__() -> 'MetaTrader' +``` +Async context manager entry point. +Initializes the connection to the MetaTrader terminal. + +#### Returns +| Type | Description | +|--------------|-------------------------------------| +| `MetaTrader` | An instance of the MetaTrader class | + + +#### \_\_aexit\_\_ +```python +async def __aexit__(exc_type, exc_val, exc_tb) +``` +Async context manager exit point. Closes the connection to the MetaTrader terminal. + + +#### 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. +#### 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. | +#### Returns: +| Type | Description | +|--------|--------------------------------------| +| `bool` | True if successful, False otherwise. | + + +#### 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. +#### 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` or `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. | + + +#### shutdown +```python +async def shutdown() -> None +``` +Closes the connection to the MetaTrader terminal. + + +#### 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` | + + +#### 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 | + + +#### 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 | + + +#### 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. | + + +#### symbols\_total +```python +async def symbols_total() -> int +``` +Returns the total number of symbols. +#### Returns +| Type | Description | +|-------|------------------------------| +| `int` | The total number of symbols. | + + +#### 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. | + + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + + +#### 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. | + + +#### 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. | + + +#### copy\_rates\_from + +```python +import numpy + + +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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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 | +#### Returns +| Type | Description | +|---------------------|------------------------------------------------------| +| `tuple[TradeOrder]` | A tuple of active trade orders as TradeOrder objects | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + +#### 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. | + + + +#### 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 | + + +#### 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. | + + + +#### 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 | + + +#### 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. | + + +#### 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 | \ No newline at end of file diff --git a/docs/core/model.md b/docs/core/model.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/core/models.md b/docs/core/models.md new file mode 100644 index 0000000..bf14070 --- /dev/null +++ b/docs/core/models.md @@ -0,0 +1,374 @@ +# 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. + +## Table of Contents +- [AccountInfo](#AccountInfo) +- [TerminalInfo](#TerminalInfo) +- [SymbolInfo](#SymbolInfo) +- [BookInfo](#BookInfo) +- [TradeOrder](#TradeOrder) +- [TradeRequest](#TradeRequest) +- [OrderCheckResult](#OrderCheckResult) +- [OrderSendResult](#OrderSendResult) +- [TradePosition](#TradePosition) +- [TradeDeal](#TradeDeal) + + +## 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 | | + + +## TerminalInfo +```python +class TerminalInfo(Base) +``` +Terminal information class. Holds information about the terminal. + +#### 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 | | + + +## 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 | | + + +## 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 | | + + +## TradeOrder +```python +class TradeOrder(Base) +``` +Trade Order Class. +#### 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 | | + + +## 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 | | + + +## 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 | | + + +## OrderSendResult +```python +class OrderSendResult(Base) +``` +Order Send Result + +#### 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 | | + + +## 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 | | + + +## 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 | | diff --git a/docs/core/task_queue.md b/docs/core/task_queue.md new file mode 100644 index 0000000..91e8323 --- /dev/null +++ b/docs/core/task_queue.md @@ -0,0 +1,91 @@ +# TaskQueue and QueueItem + +## Table of Contents +- [QueueItem](#queue_item) + - [run](#run) + +- [TaskQueue](#task_queue) + - [TaskQueue.add](#task_queue.add) + - [TaskQueue.add_task](#task_queue.add_task) + - [TaskQueue.worker](#task_queue.worker) + - [TaskQueue.start](#task_queue.start) + + + +### QueueItem +```python +class QueueItem: + def __init__(self, task: Callable | Awaitable, *args, **kwargs): +``` +A task to be executed by the `TaskQueue`. The task can be a callable or an awaitable. 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. All parameters are created as attributes of the `QueueItem` object. + +#### 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 | + + +### run +```python +def run(self) -> Any +``` +Run the task. If the task is a coroutine, it is awaited. If the task is a callable, it is called. + + +### TaskQueue +```python +class TaskQueue: + def __init__(self): +``` +#### Attributes: +| Name | Type | Description | +|---------------|-----------------|---------------------------------------------------------------------------------| +| `queue` | `asyncio.Queue` | An asyncio.Queue queue of `QueueItem` objects to be executed by the `TaskQueue` | + + + +### add +```python +def add(self, item: QueueItem, *args, **kwargs) -> None +``` +Add a `QueueItem` to the `TaskQueue` queue. + +#### Parameters: +| Name | Type | Description | +|--------|-------------|----------------------------------------| +| `item` | `QueueItem` | A `QueueItem` to be added to the queue | + + + +### add_task +```python +def add_task(self, task: Callable | Awaitable, *args, **kwargs) -> None +``` +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 | + + +### worker +```python +async def worker(self) -> None +``` +A worker that processes the `QueueItem` objects in the `TaskQueue` queue. The worker runs indefinitely, processing +`QueueItem` objects as they are added to the queue. + + +### start +```python +def start(self) -> None +``` +Start the worker that processes the `QueueItem` objects in the `TaskQueue` queue. diff --git a/docs/executor.md b/docs/executor.md new file mode 100644 index 0000000..1f54fff --- /dev/null +++ b/docs/executor.md @@ -0,0 +1,77 @@ +## Executor + +```python +class Executor +``` +Executor class for running multiple strategies on multiple symbols concurrently. +### Attributes: +| Name | Type | Description | Default | +|----------------|---------------------|------------------------------------------------|----| +| **executor** |**ThreadPoolExecutor** | The default thread executor. |None| +| **workers** |**list** | List of strategies. |[]| +| **coroutines** |**dict** | Dictionary of coroutines and keyword arguments | {} | +| **functions** |**dict** | Dictionary of functions and keyword arguments | {} | + +### add\_workers +```python +def add_workers(strategies: Sequence[type(Strategy)]) +``` +Add multiple strategies at once +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**strategies**|**Sequence[type(Strategy)]**|A sequence of strategies.| + +### remove\_workers +```python +def remove_workers(*symbols: Sequence[Symbol]) +``` +Removes any worker running on a symbol not successfully initialized. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**symbols**|**Sequence[Symbol]**|A sequence of symbols.| + +### add\_worker +```python +def add_worker(strategy: type(Strategy)) +``` +Add a strategy instance to the list of workers +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**strategy**|**type(Strategy)**|A strategy instance.| + +### run +```python +@staticmethod +def run(func: Callable|Coroutine, kwargs: dict) +``` +Wrap the input coroutine function with 'asyncio.run' so that it can be executed in a threadpool executor. +#### Arguments: +| Name | Type |Description| +|------------|------------|---| +| **func** | **Callable |Coroutine**|A coroutine function.| +| **kwargs** | **Dict** |Keyword arguments to pass to the function.| + +### trade +```python +def trade(strategy: Strategy) +``` +Wrap the input coroutine function trade method of each strategy with 'asyncio.run'. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**strategy**|**Strategy**|A strategy instance.| + +### execute +```python +async def execute(workers: int = 0) +``` +Run the strategies with a threadpool executor. +#### Arguments: +|Name|Type|Description| +|---|---|---| +|**workers**|**int**|Number of workers to use in executor pool. Defaults to zero which uses all workers.| +#### Notes: +No matter the number specified, the executor will always use a minimum of 5 workers. diff --git a/docs/history.md b/docs/history.md new file mode 100644 index 0000000..12cbb82 --- /dev/null +++ b/docs/history.md @@ -0,0 +1,110 @@ +## History + + +```python +class History +``` +The history class handles completed trade deals and trade orders in the trading history of an account. + +**Attributes**: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**deals**|**list[TradeDeal]** | Iterable of trade deals | [] | +|**orders**|**list[TradeOrder]** | Iterable of trade orders | [] | +|**total_deals**|**int** | Total number of deals | 0 | +|**total_orders**|**int** | Total number orders | 0 | +|**group**|**str** | Filter for selecting history by symbols. | "" | +|**ticket**|**int** | Filter for selecting history by ticket number | 0 | +|**position**|**int** | Filter for selecting history deals by position | 0 | +|**initialized**|**bool** | check if initial request has been sent to the terminal to get history. | False | +|**mt5**|**MetaTrader** | MetaTrader instance | None | +|**config**|**Config** | Config instance | None | + + +#### \_\_init\_\_ +```python +def __init__(*, + date_from: datetime | float = 0, + date_to: datetime | float = 0, + group: str = "", + ticket: int = 0, + position: int = 0) +``` +*Arguments*: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**date_from**|**datetime, float** | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | 0 | +|**date_to**|**datetime, float** | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | 0 | +|**group**|**str** | Filter for selecting history by symbols. | "" | +|**ticket**|**int** | Filter for selecting history by ticket number | 0 | +|**position**|**int** | Filter for selecting history deals by position | 0 | + +#### init +```python +async def init(deals=True, orders=True) -> bool +``` +Get history deals and orders + +*Arguments*: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**deals**|**bool** | If true get history deals during initial request to terminal | True | +|**orders**|**bool** | If true get history orders during initial request to terminal | True | + +*returns*: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**bool**|**bool** | True if all requests were successful else False | False | +- `bool` - True if all requests were successful else False + +#### get_deals +```python +async def get_deals() -> list[TradeDeal] +``` +Get deals from trading history using the parameters set in the constructor. + +*returns*: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**deals**|**list[TradeDeal]** | A list of trade deals | [] | + +#### deals_total +```python +async def deals_total() -> int +``` +Get total number of deals within the specified period in the constructor. + +*returns*: + +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**total_deals**|**int** | Total number of deals | 0 | + +#### get_orders +```python +async def get_orders() -> list[TradeOrder] +``` +Get orders from trading history using the parameters set in the constructor. +*returns*: + +|Name|Type|Description|Default| +|---|---|---|---| +|**orders**|**list[TradeOrder]**|A list of trade orders|[]| + +#### orders_total +```python +async def orders_total() -> int +``` +Get total number of orders within the specified period in the constructor. + +*returns*: + +|Name| Type | Description | Default | +|---|---------------------|--------------------|----| +|**total_orders**|**int** | Total number orders| 0 | + diff --git a/docs/lib/account.md b/docs/lib/account.md new file mode 100644 index 0000000..8fc81df --- /dev/null +++ b/docs/lib/account.md @@ -0,0 +1,97 @@ +# Account + +## Table of Contents +- [Account](#account.Account) +- [\_\_init\_\_](#account.__init__) +- [\_\_aenter\_\_](#account.__aenter__) +- [\_\_aexit\_\_](#account.__aexit__) +- [sign_in](#account.sign_in) +- [refresh](#account.refresh) +- [has_symbol](#account.has_symbol) +- [symbols_get](#account.symbols_get) + + +### Account +```python +class Account(AccountInfo) +``` +Singleton class for managing a trading account. A subclass of AccountInfo. +All AccountInfo attributes are available in this class. +#### Attributes +| Name | Type | Description | Default | +|-------------|-------------------|------------------------------------------------------|---------| +| `connected` | `bool` | Status of connection to MetaTrader 5 Terminal | False | +| `symbols` | `set[SymbolInfo]` | A set of available symbols for the financial market. | set() | + + +#### \_\_init\_\_ +```python +def __init__(self, *args, **kwargs) +``` +Initializes the Account class. Inherits all attributes from the AccountInfo class. + + +### __aenter__ +```python +async def __aenter__() -> 'Account' +``` +Async context manager for the Account class. Connects to a trading account and returns the account instance. +#### Returns: +| Type | Description | +|-----------|----------------------------------| +| `Account` | An instance of the Account class | +#### Raises: +| Exception | Description | +|--------------|----------------| +| `LoginError` | If login fails | + + +### __aexit__ +```python +async def __aexit__(exc_type, exc_value, traceback) +``` +Async context manager for the Account class. Disconnects from the trading account. + + +### sign_in +```python +async def sign_in() -> bool +``` +Connect to a trading account. +#### Returns: +| Type | Description | +|--------|-----------------------------------------| +| `bool` | True if login was successful else False | + + +### refresh +```python +async def refresh() +``` +Refreshes the account instance with the latest data from the MetaTrader 5 terminal + + +### has_symbol +```python +def has_symbol(symbol: str | Type[SymbolInfo]) +``` +Checks to see if a symbol is available for a trading account +#### Parameters: +| Name | Type | Description | +|----------|---------------------|--------------------------------------| +| `symbol` | `str`\|`SymbolInfo` | A symbol name or SymbolInfo instance | +#### Returns: +| Type | Description | +|--------|----------------------------------------| +| `bool` | True if symbol is available else False | + + +### symbols_get +```python +async def symbols_get() -> set[SymbolInfo] +``` +Get all financial instruments from the MetaTrader 5 terminal available for the current account. +#### Returns: +| Type | Description | +|-------------------|-------------------------------| +| `set[SymbolInfo]` | A set of SymbolInfo instances | diff --git a/docs/lib/bot_builder.md b/docs/lib/bot_builder.md new file mode 100644 index 0000000..e7bdfed --- /dev/null +++ b/docs/lib/bot_builder.md @@ -0,0 +1,162 @@ +# Bot + +## Table of Contents +- [Bot](#bb.Bot) +- [\_\_init\_\_](#bb.__init__) +- [initialize](#bb.initialize) +- [execute](#bb.execute) +- [start](#bb.start) +- [add_coroutine](#bb.add_coroutine) +- [add_function](#bb.add_function) +- [add_strategy](#bb.add_strategy) +- [add_strategies](#bb.add_strategies) +- [add_strategy_all](#bb.add_strategy_all) +- [init_symbols](#bb.init_symbols) +- [init_symbol](#bb.init_symbol]()) +- [run_bots](#bb.run_bots) + + +### Bot +```python +class Bot +``` +The bot class. Create a bot instance to run your strategies. +#### Attributes: +| Name | Type | Description | Default | +|------------|----------------------|------------------------------------------|----------| +| `account` | `Account` | Account Object. | None | +| `executor` | `ThreadPoolExecutor` | The default thread executor. | None | +| `symbols` | `set[Symbols]` | A set of symbols for the trading session | set() | +| `config` | `Config` | A Config instance | Config() | + + +### \_\_init\_\_ +```python +def __init__() +``` +Initializes the Bot class. + + +### initialize +```python +async def initialize() +``` +Prepares the bot by signing in to the trading account and initializing the symbols for the trading session. +#### Raises: +| Exception | Description | +|--------------|-------------------------------| +| `SystemExit` | If sign in was not successful | + + +### execute +```python +def execute() +``` +Execute the bot. Use this method to run the bot. + + +### start +```python +async def start() +``` +Initialize the bot and execute it. Similar to calling **execute** method but is asynchronous. + + +### add_coroutine +```python +def add_coroutine(coro: Coroutine, **kwargs) +``` +Add a coroutine to the executor. +#### Parameters: +| Name | Type | Description | +|----------|-------------|--------------------------------------------| +| `coro` | `Coroutine` | A coroutine to run in the executor | +| `kwargs` | `Any` | Keyword arguments to pass to the coroutine | + + +### add_function +```python +def add_function(func: Callable, **kwargs) +``` +Add a function to the executor. +#### Parameters: +| Name | Type | Description | +|----------|------------|-------------------------------------------| +| `func` | `Callable` | A function to run in the executor | +| `kwargs` | `Any` | Keyword arguments to pass to the function | + + +### add_strategy +```python +def add_strategy(strategy: Strategy) +``` +Add a strategy to the executor. An added strategy will only run if it's symbol was successfully initialized. +#### Parameters: +| Name | Type | Description | +|------------|------------|-----------------------------------| +| `strategy` | `Strategy` | A Strategy instance to run on bot | + + +### add_strategies +```python +def add_strategies(strategies: Iterable[Strategy]) +``` +Add multiple strategies at the same time +#### Parameters: +| Name | Type | Description | +|--------------|----------------------|-----------------------------------| +| `strategies` | `Iterable[Strategy]` | An iterable of Strategy instances | + + +### add_strategy_all +```python +def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None) +``` +Use this to run a single strategy on all available instruments in the market using the default parameters +i.e. one set of parameters for all trading symbols +#### Parameters: +| Name | Type | Description | +|------------|------------------|---------------------------------------------| +| `strategy` | `Type[Strategy]` | A Strategy class | +| `params` | `dict` or `None` | A dictionary of parameters for the strategy | + + +### init_symbols +```python +async def init_symbols() +``` +Initialize the symbols for the current trading session. This method is called internally by the bot. + + +### init_symbol +```python +async def init_symbol(symbol: Symbol) -> Symbol +``` +Initialize a symbol before the beginning of a trading session. +Removes it from the list of symbols if it was not successfully initialized or not available for the account. +#### Parameters: +| Name | Type | Description | +|----------|----------|-------------------| +| `symbol` | `Symbol` | A Symbol instance | +#### Returns: +| Type | Description | +|----------|-------------------| +| `Symbol` | A Symbol instance | + + +```python +@classmethod +def run_bots(cls, funcs: dict[Callable: dict] = None, num_workers: int = None): +``` +Run multiple functions (scripts, bots) at the same time in parallel with different accounts. +Running multiple functions is useful when you want to run different strategies on different accounts. +The callable can for example be a bot instance that defines its own Config instance within the function scope. +The dictionary should contain the callable as the key and the dictionary of keyword arguments to pass to the callable as +the value. Use the path attribute of the config instance to specify the terminal path of each account. +The num_workers parameter specifies the number of workers to use. If not specified, the number of workers will be the +number of bots. +#### Parameters +| Name | Type | Description | +|---------------|------------------------|---------------------------------------------------------------------------------| +| `funcs` | `dict[Callable: dict]` | A dictionary of callables and their keyword arguments to run as bots | +| `num_workers` | `int` | The number of workers to use. If not specified, the number of bots will be used | diff --git a/docs/lib/candle.md b/docs/lib/candle.md new file mode 100644 index 0000000..ec2fb88 --- /dev/null +++ b/docs/lib/candle.md @@ -0,0 +1,242 @@ +# Candle and Candles +Candle and Candles classes for handling bars from the MetaTrader 5 terminal. + +## Table of Contents +- [Candle](#candle) + - [\_\_init\_\_](#candle.__init__) + - [set_attributes](#candle.set_attributes) + - [is_bullish](#candle.is_bullish) + - [is_bearish](#candle.is_bearish) +- [Candles](#candles) + - [\_\_init\_\_](#candles.__init__) + - [ta](#candles.ta) + - [ta_lib](#candles.ta_lib) + - [data](#candles.data) + - [rename](#candles.rename) + + +### Candle +```python +class Candle +``` +A class representing bars from the MetaTrader 5 terminal as a customized class analogous to Japanese Candlesticks. +You can subclass this class for added customization. +### Attributes +| Name | Type | Description | +|---------------|---------|-------------------------------------------------------------------------| +| `time` | `int` | Period start time | +| `open` | `int` | Open price | +| `high` | `float` | The highest price of the period | +| `low` | `float` | The lowest price of the period | +| `close` | `float` | Close price | +| `tick_volume` | `float` | Tick volume | +| `real_volume` | `float` | Trade volume | +| `spread` | `float` | Spread | +| `Index` | `int` | Custom attribute representing the position of the candle in a sequence. | + + +### \_\_init\_\_ +```python +def __init__(**kwargs) +``` +Create a Candle object from keyword arguments. Kwargs are set as instance attributes. Open, high, low, close must be +provided during each instantiation. +#### Parameters: +| Name | Type | Description | +|----------|-------|----------------------------------------------------| +| `kwargs` | `Any` | Candle attributes and values as keyword arguments. | + +#### Raises: +| Exception | Description | +|--------------|-----------------------------------------------| +| `ValueError` | If open, high, low, or close is not provided. | + + +### set\_attributes +```python +def set_attributes(**kwargs) +``` +Set keyword arguments as instance attributes +#### Parameters: +| Name | Type | Description | +|----------|-------|----------------------------------------------------| +| `kwargs` | `Any` | Candle attributes and values as keyword arguments. | + + +### is_bullish +```python +def is_bullish() -> bool +``` +A simple check to see if the candle is bullish. +#### Returns: +| Type | Description | +|--------|---------------| +| `bool` | True or False | + + +### is_bearish +```python +def is_bearish() -> bool +``` +A simple check to see if the candle is bearish. +#### Returns: +| Type | Description | +|------|---------------| +| bool | True or False | + + +### dict +```python +def dict(self, exclude: set = None, include: set = None) -> Dict[str, Any] +``` +Return a dictionary representation of the Candle object. +#### Parameters: +| Name | Type | Description | +|-----------|------------|-----------------------------------------------------------------------------| +| `exclude` | `set[str]` | A set of attributes to exclude from the dictionary. | +| `include` | `set[str]` | A set of attributes to include in the dictionary. | + +#### Returns: +| Type | Description | +|---------------|--------------------------------------------------| +| `Dict[str, Any]` | A dictionary representation of the Candle object.| + + +### Candles +```python +class Candles(Generic[_Candle]) +``` +An iterable container class of Candle objects in chronological order. It is in a way a wrapper around a Pandas DataFrame +object. All the data pulled from the chart is stored as a pandas DataFrame object. In an attribute called **data**. +This class can be sliced, iterated over, and indexed like a sequence. It also has access to the pandas_ta library. +Indexing it returns a Candle object. It can be sliced to return a new instance of the class with the sliced candles. +This slices and resets the index of the underlying dataframe object. Key based indexing is also supported on the candles +object for accessing the columns of the underlying data attribute. Add operations between two candles objects or between a +candles object and a candle object are also supported. + +### Attributes +The attributes of this class vary depending on the columns of underlying **data** attribute. i.e. each column of the **data** +attribute is an attribute of the class. + +| Name | Type | Description | +|---------------|-----------------|-------------------------------------------------------------------| +| `data` | `DataFrame` | The pandas DataFrame containing the data. | +| `Index` | `Series['int']` | A pandas Series of the indexes of all candles in the object | +| `time` | `Series['int']` | A pandas Series of the time of all candles in the object | +| `open` | `Series[float]` | A pandas Series of the opening price of all candles in the object | +| `high` | `Series[float]` | A pandas Series of the high price of all candles in the object | +| `low` | `Series[float]` | A pandas Series of the low price of all candles in the object | +| `close` | `Series[float]` | A pandas Series of the closing price of all candles in the object | +| `tick_volume` | `Series[float]` | A pandas Series of the tick volume of all candles in the object | +| `real_volume` | `Series[float]` | A pandas Series of the real volume of all candles in the object | +| `spread` | `Series[float]` | A pandas Series of the spread of all candles in the object | +| `timeframe` | `TimeFrame` | The timeframe of the candles in the object | +| `Candle` | `Type[Candle]` | The Candle class for representing the candles in the object. | +| `data` | `DataFrame` | A pandas DataFrame of all candles in the object. | + +#### Notes +When subclassing this class make sure the Candle attribute is set to your desired candle class. + + +### \_\_init\_\_ +```python +def __init__(*, + data: DataFrame | _Candles | Iterable, + flip=False, + candle_class: Type[_Candle] = None) +``` +A container class of Candle objects in chronological order. +#### Parameters: +| Name | Type | Description | Default | +|----------------|----------------------------------------|---------------------------------------------------------------------|---------| +| `data` | `DataFrame` or `Candles` or `Iterable` | A pandas dataframe, a Candles object or any suitable iterable | +| `flip` | `bool` | Reverse the chronological order of the candles to the oldest first. | False | +| `candle_class` | `Type[Candle]` | A subclass of Candle to use as the candle class. | Candle | + + +### ta +```python +@property +def ta() +``` +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. Use this as you +would use the pandas_ta library on a pandas DataFrame. For inplace operations. The underlying data attribute is modified. +#### Returns: +| Type | Description | +|-------------|-----------------------| +| `pandas_ta` | The pandas_ta library | + + +### ta\_lib +```python +@property +def ta_lib() +``` +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. Use this for +functions that require pandas Series as input. +#### Returns: +| Type | Description | +|------|----------------| +| ta | The ta library | + + +### data +```python +@property +def data() -> DataFrame +``` +A pandas DataFrame of all candles in the object. + + +### rename +```python +def rename(inplace=True, **kwargs) -> _Candles | None +``` +Rename columns of the data object. +#### Parameters: +| Name | Type | Description | Default | +|-----------|--------|-------------------------------------------------------------------------------------------|---------| +| `inplace` | `bool` | Rename the columns inplace or return a new instance of the class with the renamed columns | True | +| `kwargs` | `str` | The new names of the columns | | + +#### Returns: +| Type | Description | +|-----------|---------------------------------------------------------------------------| +| `Candles` | A new instance of the class with the renamed columns if inplace is False. | + + + +### visualize +```python +async def visualize(self, *, count: int = 50, type='candle', savefig: str | dict = None, addplot: dict = None, + style: str = 'charles', ylabel: str = 'Price', title: str = 'Chart', **kwargs) +``` +Visualize the candles using the mplfinance library. +#### Parameters: +| Name | Type | Description | Default | +|----------|------------------|-----------------------------------------------------------------------------------------------|---------| +| `count` | `int` | The number of candles to visualize. | 50 | +| `type` | `str` | The type of chart to plot. | 'candle'| +| `savefig`| `str` or `dict` | The path to save the figure or a dictionary of keyword arguments to pass to the savefig method.| None | +| `addplot`| `dict` | A dictionary of keyword arguments to pass to the addplot method. | None | +| `style` | `str` | The style of the chart. | 'charles'| +| `ylabel` | `str` | The label of the y-axis. | 'Price' | +| `title` | `str` | The title of the chart. | 'Chart' | +| `kwargs` | `Any` | Additional keyword arguments to pass to the plot method. | | + + +```python +def make_addplot(self, *, count: int = 50, columns: list = None, **kwargs) -> dict +``` +Make subplots for adding to the main plot. +#### Parameters: +| Name | Type | Description | Default | +|-----------|--------|-----------------------------------------------------------------------------------------------|---------| +| `count` | `int` | The number of candles to visualize. | 50 | +| `columns` | `list` | The columns to plot. | None | +| `kwargs` | `Any` | Additional keyword arguments to pass to the addplot method. | | + +#### Returns: +| Type | Description | +|------|-----------------| +| dict | A makeplot dict | diff --git a/docs/lib/executor.md b/docs/lib/executor.md new file mode 100644 index 0000000..0c4d153 --- /dev/null +++ b/docs/lib/executor.md @@ -0,0 +1,102 @@ +# Executor + +## Table of Contents +- [Executor](#executor.Executor) +- [__init__](#executor.__init__) +- [add_workers](#executor.add_workers) +- [remove_workers](#executor.remove_workers) +- [add_worker](#executor.add_worker) +- [run](#executor.run) +- [trade](#executor.trade) +- [execute](#executor.execute) + + +### Executor +```python +class Executor +``` +Executor class for running multiple strategies on multiple symbols concurrently. +#### Attributes: +| Name | Type | Description | Default | +|--------------|----------------------|------------------------------------------------|---------| +| `executor` | `ThreadPoolExecutor` | The default thread executor. | None | +| `workers` | `list` | List of strategies. | [] | +| `coroutines` | `dict` | Dictionary of coroutines and keyword arguments | {} | +| `functions` | `dict` | Dictionary of functions and keyword arguments | {} | + + +#### \_\_init\_\_ +```python +def __init__(self): +``` +Initialize the executor class. + + +### add\_workers +```python +def add_workers(strategies: Sequence[type(Strategy)]) +``` +Add multiple strategies at once +#### Arguments: +| Name | Type | Description | +|--------------|----------------------------|---------------------------| +| `strategies` | `Sequence[type(Strategy)]` | A sequence of strategies. | + + +### remove\_workers +```python +def remove_workers(*symbols: Sequence[Symbol]) +``` +Removes any worker running on a symbol not successfully initialized. +#### Arguments: +| Name | Type | Description | +|-----------|--------------------|------------------------| +| `symbols` | `Sequence[Symbol]` | A sequence of symbols. | + + +### add\_worker +```python +def add_worker(strategy: type(Strategy)) +``` +Add a strategy instance to the list of workers +#### Arguments: +| Name | Type | Description | +|------------|------------------|----------------------| +| `strategy` | `type(Strategy)` | A strategy instance. | + + +### run +```python +@staticmethod +def run(func: Callable|Coroutine, kwargs: dict) +``` +Wrap the input coroutine function with 'asyncio.run' so that it can be executed in a threadpool executor. +#### Arguments: +| Name | Type | Description | +|----------|-----------|--------------------------------------------| +| `func` | `Callable | Coroutine` |A coroutine function.| +| `kwargs` | `Dict` | Keyword arguments to pass to the function. | + + +### trade +```python +def trade(strategy: Strategy) +``` +Wrap coroutine trade method of each strategy with 'asyncio.run'. +#### Arguments: +| Name | Type | Description | +|------------|------------|----------------------| +| `strategy` | `Strategy` | A strategy instance. | + + +### execute +```python +async def execute(workers: int = 5) +``` +Run the strategies with a threadpool executor. +#### Arguments: +| Name | Type | Description | +|-----------|-------|-----------------------------------------------------------| +| `workers` | `int` | Number of workers to use in executor pool. Defaults to 5. | +#### Notes: +No matter the number specified, the executor will always use a minimum of 5 workers. diff --git a/docs/lib/history.md b/docs/lib/history.md new file mode 100644 index 0000000..d554be3 --- /dev/null +++ b/docs/lib/history.md @@ -0,0 +1,196 @@ +# History + +## Table of contents +- [History](#history) +- [\_\_init\_\_](#__init__) +- [init](#init) +- [get_deals](#get_deals) +- [get_deals_ticket](#get_deals_ticket) +- [get_deals_position](#get_deals_position) +- [deals_total](#deals_total) +- [get_orders](#get_orders) +- [get_orders_position](#get_orders_position) +- [get_order_ticket](#get_order_ticket) +- [orders_total](#orders_total) + + +### History +```python +class History +``` +The history class handles completed trade deals and trade orders in the trading history of an account. +#### Attributes +| Name | Type | Description | Default | +|----------------|--------------------|------------------------------------------------------------------------|---------| +| `deals` | `list[TradeDeal]` | Iterable of trade deals | [] | +| `orders` | `list[TradeOrder]` | Iterable of trade orders | [] | +| `total_deals` | `int` | Total number of deals | 0 | +| `total_orders` | `int` | Total number orders | 0 | +| `group` | `str` | Filter for selecting history by symbols. | "" | +| `ticket` | `int` | Filter for selecting history by ticket number | 0 | +| `position` | `int` | Filter for selecting history deals by position | 0 | +| `initialized` | `bool` | check if initial request has been sent to the terminal to get history. | False | +| `mt5` | `MetaTrader` | MetaTrader instance | None | +| `config` | `Config` | Config instance | None | + + + +### \_\_init\_\_ +```python +def __init__(*, + date_from: datetime | float = 0, + date_to: datetime | float = 0, + group: str = "", + ticket: int = 0, + position: int = 0) +``` +#### Parameters +| Name | Type | Description | Default | +|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | 0 | +| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | 0 | +| `group` | `str` | Filter for selecting history by symbols. | "" | +| `ticket` | `int` | Filter for selecting history by ticket number | 0 | +| `position` | `int` | Filter for selecting history deals by position | 0 | + + +### init +```python +async def init(deals=True, orders=True) -> bool +``` +Get history deals and orders +#### Parameters +| Name | Type | Description | Default | +|----------|--------|---------------------------------------------------------------|---------| +| `deals` | `bool` | If true get history deals during initial request to terminal | True | +| `orders` | `bool` | If true get history orders during initial request to terminal | True | +#### Returns +| Name | Type | Description | Default | +|--------|--------|-------------------------------------------------|---------| +| `bool` | `bool` | True if all requests were successful else False | False | + + +### get_deals +```python +async def get_deals(self, *, date_from: datetime | int = None, date_to: datetime | int = None, group: str = '', + retries=3) -> list[TradeDeal] +``` +#### Parameters: +| Name | Type | Description | Default | +|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | None | +| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | None | +| `group` | `str` | Filter for selecting history by symbols. | "" | +| `retries` | `int` | Number of retries if the request fails. | 3 | + +#### Returns: +| Name | Type | Description | Default | +|---------|--------------------|-----------------------|---------| +| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] | + + +### get_deals_ticket +```python +async def get_deals_ticket(self, *, ticket: int) -> tuple[TradeDeal] +``` +Get deals by ticket number +#### Parameters: +| Name | Type | Description | Default | +|----------|------|-----------------------|---------| +| `ticket` | `int`| Ticket number to get | 0 | + +#### Returns: +| Name | Type | Description | Default | +|---------|--------------------|-----------------------|---------| +| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] | + + +### get_deals_position +```python +async def get_deals_position(self, *, position: int) -> list[TradeDeal] +``` +Get deals by position +#### Parameters: +| Name | Type | Description | Default | +|------------|------|-----------------------|---------| +| `position` | `int`| Position number to get | 0 | + +#### Returns: +| Name | Type | Description | Default | +|---------|--------------------|-----------------------|---------| +| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] | + + + +### deals_total +```python +async def deals_total() -> int +``` +Get total number of deals within the specified period in the constructor. +#### Returns +| Name | Type | Description | Default | +|---------------|-------|-----------------------|---------| +| `total_deals` | `int` | Total number of deals | 0 | + + +### get_orders +```python +async def get_orders(self, *, date_from: datetime | int = None, date_to: datetime | int = None, group: str = '', + retries=3) -> tuple[TradeOrder] +``` +Get orders from trading history using the parameters set in the constructor. + +#### Parameters +| Name | Type | Description | Default | +|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | None | +| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | None | +| `group` | `str` | Filter for selecting history by symbols. | "" | + +#### Returns +| Name | Type | Description | Default | +|----------|---------------------|------------------------|---------| +| `orders` | `tuple[TradeOrder]` | A list of trade orders | [] | + + +### get_orders_position +```python +async def get_orders_position(self, *, position: int) -> tuple[TradeOrder] +``` +Get orders by position. +#### Parameters +| Name | Type | Description | Default | +|------------|------|-----------------------|---------| +| `position` | `int`| Position number to get | 0 | + +#### Returns +| Name | Type | Description | Default | +|----------|---------------------|------------------------|---------| +| `orders` | `tuple[TradeOrder]` | A list of trade orders | [] | + + +### get_order_ticket +```python +async def get_order_ticket(self, ticket: int | None = None) -> TradeOrder +``` +Get a single order by ticket number. +#### Parameters +| Name | Type | Description | Default | +|----------|-------|----------------------|---------| +| `ticket` | `int` | Ticket number to get | 0 | + +#### Returns +| Name | Type | Description | Default | +|----------|---------------------|------------------------|---------| +| `order` | `TradeOrder` | A single trade order | None | + + +### orders_total +```python +async def orders_total() -> int +``` +Get total number of orders within the specified period in the constructor. +#### Returns +| Name | Type | Description | Default | +|----------------|-------|---------------------|---------| +| `total_orders` | `int` | Total number orders | 0 | diff --git a/docs/lib/order.md b/docs/lib/order.md new file mode 100644 index 0000000..5091081 --- /dev/null +++ b/docs/lib/order.md @@ -0,0 +1,133 @@ +# Order + +## Table of contents +- [Order](#Order) +- [\_\_init\_\_](#__init__) +- [orders_total](#orders_total) +- [get_order](#get_order) +- [get_orders](#get_orders) +- [check](#check) +- [send](#send) +- [calc_margin](#calc_margin) +- [calc_profit](#calc_profit) + + +### Order +```python +class Order(TradeRequest) +``` +Trade order related functions and attributes. Subclass of TradeRequest. + + +### \_\_init\_\_ +```python +def __init__(**kwargs) +``` +Initialize the order object with keyword arguments, symbol must be provided. +Provides default values for action, type_time and type_filling if not provided. +#### Arguments +| Name | Type | Description | Default | +|----------------|---------------------|----------------------------------------|------------------| +| `action` | `TradeAction` | Trade action | TradeAction.DEAL | +| `type_time` | `OrderTime` | Order time | OrderTime.DAY | +| `type_filling` | `OrderFilling` | Order filling | OrderFilling.FOK | + + +### orders_total +```python +async def orders_total() +``` +Get the total number of active orders. +#### Returns +| Type | Description | +|-------|-------------------------------| +| `int` | total number of active orders | + + +### get_order +```python +async def get_order(self, ticket: int) -> TradeOrder +``` +Get an active trade order by ticket. + + +### get_orders +```python +async def get_orders(self, *, ticket: int = 0, symbol: str = '', group: str = '', retries=3) -> tuple[TradeOrder]: +``` +Get active trade orders. If ticket is provided, it will return the order with the specified ticket. +If symbol is provided, it will return all orders for the specified symbol. +If group is provided, it will return all orders for the specified group. +#### Parameters +| Name | Type | Description | Default | +|----------|--------|--------------------------------------|---------| +| `ticket` | `int` | Order ticket | 0 | +| `symbol` | `str` | Symbol name | '' | +| `group` | `str` | Group name | '' | +#### Returns +| Type | Description | +|---------------------|------------------------------------------------------| +| `tuple[TradeOrder]` | A Tuple of active trade orders as TradeOrder objects | + +#### Raises +| Exception | Description | +|--------------|-------------------| +| `OrderError` | If not successful | + + +### check +```python +async def check() -> OrderCheckResult +``` +Check funds sufficiency for performing a required trading operation and the possibility of executing it at the current market price. +#### Returns +| Type | Description | +|--------------------|----------------------------| +| `OrderCheckResult` | An OrderCheckResult object | +#### Raises: +| Exception | Description | +|--------------|-------------------| +| `OrderError` | If not successful | + + + +### send +```python +async def send() -> OrderSendResult +``` +Send a request to perform a trading operation from the terminal to the trade server. +#### Returns +| Type | Description | +|-------------------|---------------------------| +| `OrderSendResult` | An OrderSendResult object | +#### Raises: +| Exception | Description | +|--------------|-------------------| +| `OrderError` | If not successful | + + +### calc_margin +```python +async def calc_margin() -> float +``` +Return the required margin in the account currency to perform a specified trading operation. +#### Returns +| Type | Description | +|---------|-----------------------------------| +| `float` | Returns float value if successful | +#### Raises +| Exception | Description | +|--------------|-------------------| +| `OrderError` | If not successful | + + +### calc_profit +```python +async def calc_profit() -> float +``` +Return profit in the account currency for a specified trading operation. +#### Returns +| Type | Description | +|---------|-----------------------------------| +| `float` | Returns float value if successful | +| `None` | If not successful | diff --git a/docs/lib/positions.md b/docs/lib/positions.md new file mode 100644 index 0000000..b98b8b9 --- /dev/null +++ b/docs/lib/positions.md @@ -0,0 +1,135 @@ +# Positions + +## Table of contents +- [Positions](#positions) +- [Attributes](#attributes) +- [\_\_init\_\_](#__init__) +- [positions_total](#positions_total) +- [position_get](#position_get) +- [positions_get](#positions_get) +- [close](#close) +- [close_by](#close_by) +- [close_position](#close_position) +- [close_all](#close_all) + + +### Positions +```python +class Positions +``` +Get and handle Open positions. + +#### Attributes +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `symbol` | `str` | Financial instrument name. | "" | +| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" | +| `ticket` | `int` | Position ticket. | 0 | +| `mt5` | `MetaTrader` | MetaTrader instance. | None | + + +### \_\_init\_\_ +```python +def __init__(*, symbol: str = "", group: str = "", ticket: int = 0) +``` +Get Open Positions. +#### Arguments +| Name | Type | Description | Default | +|----------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `symbol` | `str` | Financial instrument name. | "" | +| `group` | `str` | The filter for arranging a group of symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" | +| `ticket` | `int` | Position ticket. | 0 | + + +### positions_total +```python +async def positions_total() -> int +``` +Get the number of open positions. +#### Returns +| Type | Description | +|-------|---------------------------------------| +| `int` | Return total number of open positions | + + +### positions_get +```python +async def positions_get(self, symbol: str = '', group: str = '', ticket: int = 0, retries=3) -> list[TradePosition]: +``` +Get open positions with the ability to filter by symbol or ticket. +#### Arguments +| Name | Type | Description | Default | +|----------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `symbol` | `str` | Financial instrument name. | "" | +| `group` | `str` | The filter for arranging a group of symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" | +| `ticket` | `int` | Position ticket. | 0 | + +#### Returns +| Type | Description | +|-----------------------|--------------------------------| +| `list[TradePosition]` | A list of open trade positions | + + +### position_get +```python +async def position_get(self, *, ticket: int) -> TradePosition +``` +Get a position by ticket number. +#### Arguments +| Name | Type | Description | +|----------|-------|-----------------| +| `ticket` | `int` | Position ticket | + +#### Returns +| Type | Description | +|-----------------|----------------| +| `TradePosition` | Trade position | + + +### close +```python +async def close(self, *, ticket: int, symbol: str, price: float, volume: float, order_type: OrderType): +``` +Close a position by ticket number. +#### Arguments +| Name | Type | Description | Default | +|--------------|-------------|----------------------------|---------| +| `ticket` | `int` | Position ticket. | | +| `symbol` | `str` | Financial instrument name. | | +| `price` | `float` | Closing price. | | +| `volume` | `float` | Volume to close. | | +| `order_type` | `OrderType` | Order type. | | + + +### close_by +```python +async def close_by(self, pos: TradePosition): +``` + +Close a position by position object. +#### Arguments +| Name | Type | Description | +|-------|-----------------|-----------------| +| `pos` | `TradePosition` | Position object | + + +### close_position +```python +async def close_position(self, *, position: TradePosition): +``` +Close a position by position object. +#### Arguments +| Name | Type | Description | +|------------|-----------------|-----------------| +| `position` | `TradePosition` | Position object | + + +### close_all +```python +async def close_all() -> int +``` +Close all open positions for the trading account. +#### Returns +| Type | Description | +|-------|--------------------------------------| +| `int` | Return total number of closed trades | diff --git a/docs/lib/ram.md b/docs/lib/ram.md new file mode 100644 index 0000000..c32e0ca --- /dev/null +++ b/docs/lib/ram.md @@ -0,0 +1,74 @@ +# Risk Assessment and Management + +## Table of Contents +- [RAM](#RAM) +- [\_\_init\_\_](#__init__) +- [get\_amount](#get_amount) +- [check_losing_positions](#check_losing_positions) +- [check_risk_level](#check_balance_level) + + +### RAM +```python +class RAM +``` +Risk Assessment and Management. You can customize this class based on how you want to manage risk. +#### Attributes +| Name | Type | Description | Default | +|------------------|---------|--------------------------------------------------------|---------| +| `risk_to_reward` | `float` | Risk to reward ratio | 1 | +| `risk` | `float` | Percentage of account balance to risk per trade | | +| `points` | `float` | A fixed number of points per trade can be fixed here | | +| `pips` | `float` | A fixed number of pips per trade can be fixed here | | +| `min_amount` | `float` | Minimum amount to risk per trade | | +| `max_amount` | `float` | Maximum amount to risk per trade | | +| `risk_level` | `float` | Ratio of free margin to current equity as a percentage | 50 | +| `loss_limit` | `int` | Number of open losing trades to allow at any time | 3 | + + + +### \_\_init\_\_ +```python +def __init__(self, *, risk_to_reward: float = 1, risk: float = 0.01, **kwargs): +``` +Risk Assessment and Management. All provided keyword arguments are set as attributes. +#### Parameters +| Name | Type | Description | Default | +|------------------|---------|----------------------------------------------------|-----------| +| `risk_to_reward` | `float` | Risk to reward ratio | 1 | +| `risk` | `float` | Percentage of account balance to risk per trade | 0.01 # 1% | +| `kwargs` | `Dict` | Keyword arguments to be set as instance attributes | {} | + + + +### get\_amount +```python +async def get_amount() -> float +``` +Calculate the amount to risk per trade as a percentage of balance. +#### Returns +| Type | Description | +|--------|-------------------------------------------------------| +| float | Amount to risk per trade in terms of account currency | + + +### check_losing_positions +```python +async def check_losing_positions(self) -> bool: +``` +Check if the number of open losing trades is greater than or equal to the loss limit. +#### Returns +| Type | Description | +|------|---------------------------------------------------------------------------------------| +| bool | True if the number of open losing trades is more than the loss limit, False otherwise | + + +### check\_balance\_level +```python +async def check_balance_level(self) -> bool: +``` +Check if the balance level is greater than or equal to the fixed balance level. +#### Returns +| Type | Description | +|------|---------------------------------------------------------------------------------| +| bool | True if the balance level is more than the fixed balance level, False otherwise | diff --git a/docs/lib/records.md b/docs/lib/records.md new file mode 100644 index 0000000..75a10cb --- /dev/null +++ b/docs/lib/records.md @@ -0,0 +1,96 @@ +# Records + +## Table of contents +- [Records](#records) +- [\_\_init\_\_](#__init__) +- [get\_records](#get_records) +- [read\_update](#read_update) +- [update\_rows](#update_rows) +- [update\_records](#update_records) +- [update\_record](#update_record) + + +### Records +```python +class Records() +``` +This utility class read trade records from csv files, and update them based on their closing positions. To use this default +implementation the csv files should at least have the following columns `['order', 'symbol', 'actual_profit', 'win', 'closed']` +Once a trade have been closed, the actual profit and win status will be updated in the csv file. +#### Default Headers +| column | type | description | +|---------------|-------|-------------------------------------------------------| +| order | int | Order id of the trade | +| symbol | str | the name of the Symbol | +| actual_profit | float | The actual profit of the trade, this zero by default | +| win | bool | The win status of the trade, this is False by default | +| closed | bool | The status of the trade, this is False by default | +#### Attributes +| name | type | description | +|-------------|--------|--------------------------------------------------------------| +| records_dir | Path | Absolut path to directory containing record of placed trades | +| config | Config | Config object | + + +### \_\_init\_\_ +```python +def __init__(records_dir: Path | str = '') +``` +Initialize an instance of the class +#### Parameters +| name | type | description | +|--------------|------|----------------------------------------------------------------| +| records_dir | Path | Absolute path to directory containing record of placed trades. | + + +### get\_records +```python +async def get_records() +``` +Get trade records from records_dir folder +#### Yields +| type | description | +|------|--------------------| +| Path | Trade record files | + + +### read\_update +```python +async def read_update(file: Path) +``` +Read and update trade records +#### Parameters +| name | type | description | +|------|------|-------------------| +| file | Path | Trade record file | + + +### update\_rows +```python +async def update_rows(rows: list[dict]) -> list[dict] +``` +Update the rows of entered trades in the csv file with the actual profit. +#### Parameters +| name | type | description | +|------|------------|---------------------------------------------------------------------------| +| rows | list[dict] | A list of dictionaries from the dictionary writer object of the csv file. | + +#### Returns +| type | description | +|------------|---------------------------------------------------------------| +| list[dict] | A list of dictionaries with the actual profit and win status. | + + + +### update\_records +```python +async def update_records() +``` +Update trade records in the records_dir folder. + + +### update\_record +```python +async def update_record(file: Path | str) +``` +Update a single trade record file. diff --git a/docs/lib/result.md b/docs/lib/result.md new file mode 100644 index 0000000..fec7685 --- /dev/null +++ b/docs/lib/result.md @@ -0,0 +1,60 @@ +# Result + +## Table of Contents +- [Result](#result) +- [__init__](#__init__) +- [get_data](#get_data) +- [to_csv](#to_csv) +- [to_json](#to_json) + + +```python +class Result() +``` +A base class for handling trade results and strategy parameters for record keeping and analysis. +#### Attributes +| Name | Type | Description | +|--------------|-------------------|-----------------------------------| +| `result` | `OrderSendResult` | The result of the trade | +| `parameters` | `dict` | The parameters used for the trade | +| `name` | `str` | The name of the result object | + + + +### \_\_init\_\_ +```python +def __init__(result: OrderSendResult, parameters: dict = None, name: str = '') +``` +Prepare result data for record keeping and analysis. +#### Parameters +| Name | Type | Description | +|--------------|-------------------|-----------------------------------| +| `result` | `OrderSendResult` | The result of the trade | +| `parameters` | `dict` | The parameters used for the trade | +| `name` | `str` | The name of the result object | + + +### get\_data +```python +def get_data(self) -> dict: +``` +Get the result data as a dictionary +#### Returns +| Type | Description | +|--------|-----------------| +| `dict` | The result data | + + +### to\_csv +```python +async def to_csv() +``` +Record trade results and associated parameters as a csv file + + +### to\_json +```python +async def to_json() +``` +Record trade results and associated parameters as a json file +``` diff --git a/docs/lib/sessions.md b/docs/lib/sessions.md new file mode 100644 index 0000000..a93c1aa --- /dev/null +++ b/docs/lib/sessions.md @@ -0,0 +1,177 @@ +# Session and Sessions +Sessions allow you to run a strategy at specific times of the day. + +## Table of Contents +- [Session](#session) + - [\_\_init\_\_](#session.__init__) + - [begin](#session.begin) + - [close](#session.close) + - [action](#session.action) +- [Sessions](#sessions) + - [\_\_init\_\_](#sessions.__init__) + - [find](#sessions.find) + - [find_next](#sessions.find_next) + - [check](#sessions.check) +- [delta](#delta) +- [until](#until) + + + +## Session +```python +class Session +``` +A session is a time period between two `datetime.time` objects specified in utc. +#### Attributes +| Name | Type | Description | Default | +|----------------|-------------------------------------------------------------------|------------------------------------------------------------------------|---------| +| `start` | `datetime.time` | The start time of the session. | None | +| `end` | `datetime.time` | The end time of the session. | None | +| `on_start` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start']` | The action to take when the session starts. Default is None. | None | +| `on_end` | `Literal['close_all', 'close_win', 'close_loss', 'custom_end']` | The action to take when the session ends. Default is None. | None | +| `custom_start` | `Callable` | A custom function to call when the session starts. Default is None. | None | +| `custom_end` | `Callable` | A custom function to call when the session ends. Default is None. | None | +| `name` | `str` | The name of the session. Default is a combination of start and finish. | | + +#### Notes: +The `[close_all, close_win, close_loss]` will affect or open positions in the account irrespective of whether they were +opened during the session or not or even by a strategy using the session. This is because the session is not aware of the +positions opened by the strategy. This will be handled in a future release. + + +### \_\_init\_\_ +```python +def __init__(*, + start: int | time, + end: int | time, + on_start: Literal['close_all', 'close_win', 'close_loss', + 'custom_start'] = None, + on_end: Literal['close_all', 'close_win', 'close_loss', + 'custom_end'] = None, + custom_start: Callable = None, + custom_end: Callable = None) +``` +Create a session. +#### Arguments +| Name | Type | Description | Default | +|----------------|-------------------------------------------------------------------|---------------------------------------------------------------------|---------| +| `start` | `int` \| `datetime.time` | The start time of the session in UTC. | None | +| `end` | `int` \| `datetime.time` | The end time of the session in UTC. | None | +| `on_start` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start']` | The action to take when the session starts. Default is None. | None | +| `on_end` | `Literal['close_all', 'close_win', 'close_loss', 'custom_end']` | The action to take when the session ends. Default is None. | None | +| `custom_start` | `Callable` | A custom function to call when the session starts. Default is None. | None | +| `custom_end` | `Callable` | A custom function to call when the session ends. Default is None. | None | +| `name` | `str` | The name of the session. Default is None. | None | + + +### begin +```python +async def begin() +``` +Call the action specified in on_start or custom_start. + + +### close +```python +async def close() +``` +Call the action specified in on_end or custom_end. + +### action +```python +async def action(action): pass +``` +Used by begin and close to call the action specified. + +#### Arguments +| Name | Type | Description | Default | +|----------|---------------------------------------------------------------------------------|---------------------|---------| +| `action` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start', 'custom_end']` | The action to take. | None | + + + +## Sessions +```python +class Sessions() +``` +Sessions allow you to run code at specific times of the day. It is a collection of Session objects. +Sessions are sorted by start time. The sessions object is an asynchronous context manager. +### Attributes: +| Name | Type | Description | Default | +|-------------------|-----------------|----------------------------|---------| +| `sessions` | `list[Session]` | A list of Session objects. | [] | +| `current_session` | `Session` | The current session. | None | + + +#### \_\_init\_\_ +```python +def __init__(*sessions) +``` +Create a Sessions object. +#### Arguments +| Name | Type | Description | Default | +|------------|------------------|-----------------------------|---------| +| `sessions` | `tuple[Session]` | A tuple of Session objects. | None | + + +### find +```python +def find(obj: time) -> Session | None +``` +Find a session that contains a datetime.time object. +#### Arguments +| Name | Type | Description | Default | +|-------|-----------------|-------------------------|---------| +| `obj` | `datetime.time` | A datetime.time object. | None | + +#### Returns +| Type | Description | +|-----------|----------------------------------------| +| `Session` | A Session object or None if not found. | + + +### find\_next +```python +def find_next(obj: time) -> Session +``` +Find the next session that contains a datetime.time object. +#### Arguments +| Name | Type | Description | Default | +|-------|-----------------|-------------------------|---------| +| `obj` | `datetime.time` | A datetime.time object. | | +#### Returns +| Type | Description | +|-----------|-------------------| +| `Session` | A Session object. | + +### check +```python +async def check(): pass +``` +Check if the current session has started and if not, wait until it starts. + + +### delta +```python +def delta(obj: time) -> timedelta: pass +``` +Get the timedelta of a datetime.time object. +#### Arguments: +| Name | Type | Description | Default | +|-------|-----------------|-------------------------|---------| +| `obj` | `datetime.time` | A datetime.time object. | None | +#### Returns +| Type | Description | +|-------------|---------------------| +| `timedelta` | A timedelta object. | + + +### until +```python +def until() +``` +Get the seconds until the session starts from the current time. +#### Returns: +| Type | Description | +|-------|---------------------------------------| +| `int` | The seconds until the session starts. | diff --git a/docs/lib/strategy.md b/docs/lib/strategy.md new file mode 100644 index 0000000..ad20454 --- /dev/null +++ b/docs/lib/strategy.md @@ -0,0 +1,65 @@ +# Strategy +The base class for creating strategies. + +## Table of Contents +- [Strategy](#strategy) +- [\_\_init\_\_](#init) +- [sleep](#sleep) +- [trade](#trade) + + + +### Strategy +```python +class Strategy(ABC) +``` +The base class for creating strategies. +#### Attributes +| Name | Type | Description | Default | +|--------------|--------------|----------------------------------------------|---------| +| `name` | `str` | A name for the strategy. | None | +| `account` | `Account` | Account instance. | None | +| `mt5` | `MetaTrader` | MetaTrader instance. | None | +| `config` | `Config` | Config instance. | None | +| `symbol` | `Symbol` | The Financial Instrument as a Symbol Object | None | +| `parameters` | `Dict` | A dictionary of parameters for the strategy. | None | +| `sessions` | `Sessions` | Trading sessions. | None | + +### Notes +Define the name of a strategy as a class attribute. If not provided, the class name will be used as the name. + + +### \_\_init\_\_ +```python +def __init__(*, symbol: Symbol, params: dict = None, sessions: Sessions) +``` +Initiate the parameters dict and add name and symbol fields. Use class name as strategy name if name is not provided. +#### Parameters +| Name | Type | Description | Default | +|------------|------------|-----------------------------|---------| +| `symbol` | `Symbol` | The Financial instrument | None | +| `params` | `Dict` | Trading strategy parameters | None | +| `sessions` | `Sessions` | Trading sessions | None | + + +### sleep +```python +@staticmethod +async def sleep(secs: float) +``` +Sleep for the needed amount of seconds in between requests to the terminal. +computes the accurate amount of time needed to sleep ensuring that the next request is made at the start of +a new bar and making cooperative multitasking possible. +#### Parameters +| Name | Type | Description | Default | +|--------|---------|----------------------------------------------------------------|---------| +| `secs` | `float` | The time in seconds. Usually the timeframe you are trading on. | None | + + +### trade +```python +@abstractmethod +async def trade() +``` +Place trades using this method. This is the main method of the strategy. +It will be called by the strategy runner. diff --git a/docs/lib/symbol.md b/docs/lib/symbol.md new file mode 100644 index 0000000..426029d --- /dev/null +++ b/docs/lib/symbol.md @@ -0,0 +1,337 @@ +# Symbol +Symbol class for handling a financial instrument. + +## Table of Contents +- [Symbol](#Symbol) + - [info_tick](#info_tick) + - [symbol_select](#symbol_select) + - [info](#info) + - [init](#init) + - [book_add](#book_add) + - [book_get](#book_get) + - [book_release](#book_release) + - [compute_volume](#compute_volume) + - [currency_conversion](#currency_conversion) + - [convert_currency](#convert_currency) + - [copy_rates_from](#copy_rates_from) + - [copy_rates_from_pos](#copy_rates_from_pos) + - [copy_rates_range](#copy_rates_range) + - [copy_ticks_from](#copy_ticks_from) + - [copy_ticks_range](#copy_ticks_range) + - [check_volume](#check_volume) + - [round_off_volume](#round_off_volume) + + +### Symbol +```python +class Symbol(SymbolInfo) +``` +Main class for handling a financial instrument. A subclass of `SymbolInfo` where most of the attributes are defined. +for working with a financial instrument. +#### Attributes +| Name | Type | Description | Default | +|-----------|--------------|---------------------------------------|---------| +| `name` | `str` | The name of the symbol. | None | +| `mt5` | `MetaTrader` | MetaTrader instance. | None | +| `config` | `Config` | Config instance. | None | +| `account` | `Account` | Account instance. | None | +| `tick` | `Tick` | The current price tick of the symbol. | None | + +#### Notes +Full properties are on the SymbolInfo Object. +Make sure Symbol is always initialized with a name argument + + +### info\_tick +```python +async def info_tick(*, name: str = "") -> Tick +``` +Get the current price tick of a financial instrument. +#### Parameters +| Name | Type | Description | Default | +|--------|-------|-------------------------|---------| +| `name` | `str` | The name of the symbol. | '' | +#### Returns +| Type | Description | +|--------|----------------------| +| `Tick` | Return a Tick Object | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### symbol\_select +```python +async def symbol_select(*, enable: bool = True) -> bool +``` +Select a symbol in the MarketWatch window or remove a symbol from the window. +Update the select property +#### Parameters +| Name | Type | Description | Default | +|----------|--------|---------------------------------------------------------------------------------------------------------|---------| +| `enable` | `bool` | Switch. Optional unnamed parameter. If 'false', a symbol should be removed from the MarketWatch window. | None | +#### Returns +| Type | Description | +|--------|--------------------------------------| +| `bool` | True if successful, otherwise False. | + + +### info +```python +async def info() -> SymbolInfo +``` +Get data on the specified financial instrument and update the symbol object properties +#### Returns +| Type | Description | +|--------------|--------------------------| +| `SymbolInfo` | SymbolInfo if successful | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### init +```python +async def init() -> bool +``` +Initialized the symbol by pulling properties from the terminal +#### Returns +| Type | Description | +|--------|--------------------------------------------------------| +| `bool` | Returns True if symbol info was successful initialized | + + +### book\_add +```python +async def book_add() -> bool +``` +Subscribes the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. +If the symbol is not in the list of instruments for the market, This method will return False +#### Returns +| Type | Description | +|--------|--------------------------------------| +| `bool` | True if successful, otherwise False. | + + +### book\_get +```python +async def book_get() -> tuple[BookInfo] +``` +Returns a tuple of BookInfo featuring Market Depth entries for the specified symbol. +#### Returns +| Type | Description | +|-------------------|-------------------------------------------------------------------| +| `tuple[BookInfo]` | Returns the Market Depth contents as a tuples of BookInfo Objects | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### book\_release +```python +async def book_release() -> bool +``` +Cancels subscription of the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. +#### Returns +| Type | Description | +|--------|--------------------------------------| +| `bool` | True if successful, otherwise False. | + + +### compute_volume +```python +async def compute_volume(*args, **kwargs) -> float +``` +Computes the volume of a trade based on the amount or any other parameter. +This is a dummy method that returns the minimum volume of the symbol. It is meant to be overridden by a subclass. + +#### Parameters +| Name | Type | Description | Default | +|--------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| `amount` | `float` | Amount to risk in the trade | None | +| `points` | `float` | Number of pips to target | None | +| `use_limits` | `bool` | If True, the minimum volume is returned if the computed volume is less than the minimum volume and the maximum volume is returned if the computed volume is greater than the maximum volume for the symbol | False | +#### Returns +| Type | Description | +|---------|---------------------------------| +| `float` | Returns the volume of the trade | + + +### currency\_conversion +```python +async def currency_conversion(*, amount: float, base: str, + quote: str) -> float +``` +Convert from one currency to the other. Returns the amount in terms of the base currency. +#### Parameters +| Name | Type | Description | Default | +|----------|---------|--------------------------------------------------------|---------| +| `amount` | `float` | Amount to convert given in terms of the quote currency | None | +| `base` | `str` | The base currency of the pair | None | +| `quote` | `str` | The quote currency of the pair | None | +#### Returns +| Type | Description | +|---------|--------------------------------------| +| `float` | Amount in terms of the base currency | +#### Raises +| Exception | Description | +|--------------|----------------------| +| `ValueError` | If conversion failed | + + +```python +async def convert_currency(self, *, amount: float, base: str, quote: str) -> float: +``` +Alias for currency_conversion + + +### copy\_rates\_from +```python +async def copy_rates_from(*, + timeframe: TimeFrame, + date_from: datetime | int, + count: int = 500) -> Candles +``` +Get bars from the MetaTrader 5 terminal starting from the specified date. +#### Parameters +| Name | Type | Description | Default | +|-------------|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------|----------------------------| +| `timeframe` | `TimeFrame` | Timeframe the bars are requested for. Set by a value from the TimeFrame enumeration. | Required unnamed parameter | +| `date_from` | `datetime, int` | Date of opening of the first bar from the requested sample. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +| `count` | `int` | Number of bars to receive. | Required unnamed parameter | +#### Returns +| Type | Description | +|-----------|---------------------------------------------------------------------------| +| `Candles` | Returns a Candles object as a collection of rates ordered chronologically | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### copy\_rates\_from\_pos +```python +async def copy_rates_from_pos(*, + timeframe: TimeFrame, + count: int = 500, + start_position: int = 0) -> Candles +``` +Get bars from the MetaTrader 5 terminal starting from the specified index. +#### Parameters +| Name | Type | Description | Default | +|------------------|-------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------| +| `timeframe` | `TimeFrame` | TimeFrame value from TimeFrame Enum. Required keyword only parameter | Required keyword only parameter | +| `count` | `int` | Number of bars to return. Keyword argument defaults to 500 | 500 | +| `start_position` | `int` | Initial index of the bar the data are requested from. The numbering of bars goes from present to past. Thus, the zero bar means the current one. Keyword argument defaults to 0. | 0 | +#### Returns +| Type | Description | +|-----------|----------------------------------------------------------------------------| +| `Candles` | Returns a Candles object as a collection of rates ordered chronologically. | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### copy\_rates\_range +```python +async def copy_rates_range(*, timeframe: TimeFrame, date_from: datetime | int, + date_to: datetime | int) -> Candles +``` +Get bars in the specified date range from the MetaTrader 5 terminal. +#### Parameters +| Name | Type | Description | Default | +|-------------|---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------| +| `timeframe` | `TimeFrame` | Timeframe for the bars using the TimeFrame enumeration. Required unnamed parameter. | Required unnamed parameter | +| date_from | datetime, int | Date the bars are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time >= date_from are returned. Required unnamed parameter. | Required unnamed parameter | +| date_to | datetime, int | Date, up to which the bars are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time <= date_to are returned. Required unnamed parameter. | Required unnamed parameter | +#### Returns +| Type | Description | +|-----------|----------------------------------------------------------------------------| +| `Candles` | Returns a Candles object as a collection of rates ordered chronologically. | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### copy\_ticks\_from +```python +async def copy_ticks_from(*, + date_from: datetime | int, + count: int = 100, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` +Get ticks from the MetaTrader 5 terminal starting from the specified date. +#### Parameters +| Name | Type | Description | Default | +|-------------|-----------------|---------------------------------------------------------------------------------------------------------------------|----------------------------| +| `date_from` | `datetime, int` | Date the ticks are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +| `count` | `int` | Number of requested ticks. Defaults to 100 | Required unnamed parameter | +| `flags` | `CopyTicks` | A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default | Required unnamed parameter | +#### Returns +| Type | Description | +|---------|--------------------------------------------------------------------------| +| `Ticks` | Returns a Ticks object as a collection of ticks ordered chronologically. | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### copy\_ticks\_range +```python +async def copy_ticks_range(*, + date_from: datetime | int, + date_to: datetime | int, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` +Get ticks for the specified date range from the MetaTrader 5 terminal. +#### Parameters +| Name | Type | Description | Default | +|-------------|-----------------|-----------------------------------------------------------------------------------------------------------------------------|----------------------------| +| `date_from` | `datetime, int` | Date the ticks are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +| `date_to` | `datetime, int` | Date, up to which the ticks are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +| `flags` | `CopyTicks` | A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default | Required unnamed parameter | +#### Returns +| Type | Description | +|---------|--------------------------------------------------------------------------| +| `Ticks` | Returns a Ticks object as a collection of ticks ordered chronologically. | +#### Raises +| Exception | Description | +|--------------|---------------------------------------------------| +| `ValueError` | If request was unsuccessful and None was returned | + + +### check_volume +```python +async def check_volume(*, volume: float) -> tuple[bool, float] +``` +Checks if the volume is within the minimum and maximum volume for the symbol. If not, return the nearest limit. +#### Parameters +| Name | Type | Description | Default | +|--------|---------|---------------------|---------| +| volume | `float` | The volume to check | None | +#### Returns +| Type | Description | +|----------------------|-----------------------------------------------------| +| `tuple[bool, float]` | The boolean is True if the volume is within limits. | + + +### round_off_volume +```python +async def round_off_volume(*, volume: float, round_down: bool = True) -> float +``` +Rounds off the volume to the nearest minimum or maximum volume for the symbol. +#### Parameters +| Name | Type | Description | Default | +|--------------|---------|---------------------------|---------| +| `volume` | `float` | The volume to round off | None | +| `round_down` | `bool` | To round_up or round_down | True | +#### Returns +| Type | Description | +|---------|---------------------| +| `float` | The rounded volume. | diff --git a/docs/lib/terminal.md b/docs/lib/terminal.md new file mode 100644 index 0000000..e36b212 --- /dev/null +++ b/docs/lib/terminal.md @@ -0,0 +1,77 @@ +# Terminal + +## Table of Contents +- [Terminal](#terminal) +- [initialize](#initialize) +- [version](#version) +- [info](#info) +- [symbols_total](#symbols_total) + + +### Terminal +```python +class Terminal(TerminalInfo) +``` +Terminal Class. Get information about the MetaTrader 5 terminal. The class is a subclass of the TerminalInfo +class. It inherits all the attributes and methods of the TerminalInfo class and adds some useful methods. +#### Attributes +| Name | Type | Description | Default | +|---------------|--------------|------------------------------------------------------------------------------|---------| +| `initialized` | `bool` | check if initial request has been sent to the terminal to get terminal info. | False | +| `mt5` | `MetaTrader` | MetaTrader instance | None | +| `config` | `Config` | Config instance | None | + + +### initialize +```python +async def initialize() -> bool +``` +Establish a connection with the MetaTrader 5 terminal. There are three call options. Call without parameters. +The terminal for connection is found automatically. Call specifying the path to the MetaTrader 5 terminal we +want to connect to. word path as a keyword argument Call specifying the trading account path and parameters +i.e. login, password, server, as keyword arguments, path can be omitted. +#### Returns +| Type | Description | +|--------|-------------------------------| +| `bool` | True if successful else False | + + +### version +```python +async def version() +``` +Get the MetaTrader 5 terminal version. This method returns the terminal version, build and release date as +a tuple of three values +#### Returns +| Type | Description | +|-----------|------------------------------------| +| `Version` | version of tuple as Version object | +#### Raises +| Exception | Description | +|--------------|--------------------------------------------| +| `ValueError` | If the terminal version cannot be obtained | + + +### info +```python +async def info() +``` +Get the connected MetaTrader 5 client terminal status and settings. gets terminal info in the form of a +named tuple structure (namedtuple). Return None in case of an error. The info on the error can be +obtained using last_error(). +#### Returns +| Type | Description | +|----------------|----------------------------------------------------| +| `TerminalInfo` | Terminal status and settings as a terminal object. | + + + +### symbols\_total +```python +async def symbols_total() -> int +``` +Get the number of all financial instruments in the MetaTrader 5 terminal. +#### Returns +| Type | Description | +|-------|-----------------------------------| +| `int` | Total number of available symbols | diff --git a/docs/lib/ticks.md b/docs/lib/ticks.md new file mode 100644 index 0000000..666aa23 --- /dev/null +++ b/docs/lib/ticks.md @@ -0,0 +1,125 @@ +# Tick and Ticks +Module for working with price ticks. + +## Table of Contents +- [Tick](#tick) + - [\_\_init\_\_](#tick.__init__) + - [set\_attributes](#tick.set_attributes) +- [Ticks](#ticks) + - [\_\_init\_\_](#ticks.__init__) + - [ta](#ticks.ta) + - [ta\_lib](#ticks.ta_lib) + - [data](#ticks.data) + - [rename](#ticks.rename) + + +## Tick +```python +class Tick() +``` +Price Tick of a Financial Instrument. +#### Attributes +| Name | Type | Description | Default | +|---------------|------------|-----------------------------------------------------------------------|---------| +| `symbol` | `Symbol` | The Financial Instrument as a Symbol Object | None | +| `time` | `datetime` | Time of the last prices update for the symbol | None | +| `bid` | `float` | Current Bid price | None | +| `ask` | `float` | Current Ask price | None | +| `last` | `float` | Price of the last deal (Last) | None | +| `volume` | `float` | Volume for the current Last price | None | +| `time_msc` | `int` | Time of the last prices update for the symbol in milliseconds | None | +| `flags` | `TickFlag` | Tick flags | None | +| `volume_real` | `float` | Volume for the current Last price | None | +| `Index` | `int` | Custom attribute representing the position of the tick in a sequence. | None | + + +### \_\_init\_\_ +```python +def __init__(self, **kwargs): +``` +Initialize the Tick class. Set attributes from keyword arguments.The `bid`, `ask`, `last`, `time` and `volume` must be present + + +### set\_attributes +```python +def set_attributes(**kwargs) +``` +Set attributes from keyword arguments + + +## Ticks +```python +class Ticks() +``` +Container data class for price ticks. Arrange in chronological order. Saves data with a pandas DataFrame. +Supports iteration, slicing and assignment. Similar to `Candles` class but for price ticks. + +#### Attributes +| Name | Type | Description | Default | +|--------|-------------|-----------------------------------------------------------|---------| +| `data` | `DataFrame` | DataFrame of price ticks arranged in chronological order. | None | + + +### \_\_init\_\_ +```python +def __init__(*, data: DataFrame | Iterable, flip=False) +``` +Initialize the Ticks class. Creates a DataFrame of price ticks from the data argument. +#### Arguments: +| Name | Type | Description | Default | +|--------|---------------------------|---------------------------------------------------------------------------------------------|---------| +| `data` | `DataFrame` \| `Iterable` | Dataframe of price ticks or any iterable object that can be converted to a pandas DataFrame | None | +| `flip` | `bool` | If flip is True reverse data chronological order. | False | + + +### ta +```python +@property +def ta() +``` +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. +#### Returns +| Name | Type | Description | +|-------------|-------------|-----------------------| +| `pandas_ta` | `pandas_ta` | The pandas_ta library | + + +### ta\_lib +```python +@property +def ta_lib() +``` +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. +#### Returns +| Name | Type | Description | +|------|------|----------------| +| `ta` | `ta` | The ta library | + + +### data +```python +@property +def data() -> DataFrame +``` +DataFrame of price ticks arranged in chronological order. +#### Returns +| Name | Type | Description | +|--------|-------------|-----------------------------------------------------------| +| `data` | `DataFrame` | DataFrame of price ticks arranged in chronological order. | + + +### rename +```python +def rename(inplace=True, **kwargs) -> _Ticks | None +``` +Rename columns of the candle class. +#### Arguments +| Name | Type | Description | Default | +|-----------|--------|-------------------------------------------------------------------------------------------|---------| +| `inplace` | `bool` | Rename the columns inplace or return a new instance of the class with the renamed columns | True | +| `kwargs` | | The new names of the columns | | +#### Returns +| Type | Description | +|---------|---------------------------------------------------------------------------| +| `Ticks` | A new instance of the class with the renamed columns if inplace is False. | +| `None` | If inplace is True | diff --git a/docs/lib/trade_records.md b/docs/lib/trade_records.md new file mode 100644 index 0000000..31680d8 --- /dev/null +++ b/docs/lib/trade_records.md @@ -0,0 +1,127 @@ +# Trade Records + +## Table of contents +- [Trade Records](#trade_records) +- [\_\_init\_\_](#__init__) +- [get_csv_records](#get_csv_records) +- [get_json_records](#get_json_records) +- [read_update_csv](#read_update_csv) +- [read_update_json](#read_update_json) +- [update_rows](#update_rows) +- [update_row](#update_row) +- [update_csv_records](#update_csv_records) +- [update_json_records](#update_json_records) +- [update_csv_record](#update_csv_record) +- [update_json_record](#update_json_record) + + +### Trade Records +```python +class TradeRecords() +``` +This utility class read trade records from csv and json files, and update them based on their closing positions. +To use this default implementation the csv or json file should be able to provide the following data. +`['order', 'symbol', 'actual_profit', 'win', 'closed']` +Once a trade have been closed, the actual profit and win status will be updated in the csv file. + +#### Default Headers +| column | type | description | +|---------------|-------|-------------------------------------------------------| +| order | int | Order id of the trade | +| symbol | str | the name of the Symbol | +| actual_profit | float | The actual profit of the trade, this zero by default | +| win | bool | The win status of the trade, this is False by default | +| closed | bool | The status of the trade, this is False by default | + +#### Attributes +| name | type | description | +|-------------|--------|--------------------------------------------------------------| +| records_dir | Path | Absolut path to directory containing record of placed trades | +| config | Config | Config object | + + +### \_\_init\_\_ +```python +def __init__(records_dir: Path | str = '') +``` +Initialize an instance of the class. +#### Parameters +| name | type | description | +|--------------|------|----------------------------------------------------------------| +| records_dir | Path | Absolute path to directory containing record of placed trades. | + + +### get_csv_records +```python +async def get_csv_records() +``` +Get trade records from records_dir folder. +#### Yields +| type | description | +|------|--------------------| +| Path | Trade record files | + + +### get_json_records +```python +async def get_json_records() +``` +Get trade records from records_dir folder. +#### Yields +| type | description | +|------|--------------------| +| Path | Trade record files | + + +### read_update_csv +```python +async def read_update_csv(file: Path) +``` +Read and update trade records from a csv file. +#### Parameters +| name | type | description | +|------|------|-------------------| +| file | Path | Trade record file | + + +### read_update_json +```python +async def read_update_json(file: Path) +``` +Read and update trade records from a json file. +#### Parameters +| name | type | description | +|------|------|-------------------| +| file | Path | Trade record file | + + +### update_rows +```python +async def update_rows(rows: list[dict]) -> list[dict] +``` +Update the rows of entered trades with the actual profit. +#### Parameters +| name | type | description | +|------|------------|---------------------------------------------------------------------------| +| rows | list[dict] | A list of dictionaries from the dictionary writer object of the csv file. | + +#### Returns +| type | description | +|------------|---------------------------------------------------------------| +| list[dict] | A list of dictionaries with the actual profit and win status. | + + +### update_row +```python +async def update_row(row: dict) -> dict +``` +Update the row of an entered trade with the actual profit. +#### Parameters +| name | type | description | +|------|------|-------------------------------------------| +| row | dict | A dictionary from the csv file row object | + +#### Returns +| type | description | +|------|------------------------------------| +| dict | A dictionary with the actual profit | diff --git a/docs/lib/trader.md b/docs/lib/trader.md new file mode 100644 index 0000000..4b7f5d8 --- /dev/null +++ b/docs/lib/trader.md @@ -0,0 +1,113 @@ +# Trader +Trader class module. Handles the creation of an order and the placing of trades + +## Table of Contents +- [Trader](#trader) +- [\_\_init\_\_](#__init__) +- [create\_order](#create_order) +- [set\_order\_limits](#set_order_limits) +- [set\_trade\_stop_levels](#set_trade_stop_levels) +- [send\_order](#send_order) +- [check_order](#check_order) +- [record_trade](#record_trade) +- [place\_trade](#place_trade) + + +### Trader +```python +class Trader() +``` +Base class for creating a Trader object. Handles the creation of an order and the placing of trades +#### Attributes +| Name | Type | Description | Default | +|----------|----------|-------------------------------------------------------|---------| +| `ram` | `RAM` | Risk Assessment Management System. | None | +| `config` | `Config` | Config instance. | None | +| `order` | `Order` | Order instance. | None | +| `symbol` | `Symbol` | The Financial Instrument | None | +| `params` | `Dict` | A dictionary of parameters associated with the trade. | None | + + +### \_\_init\_\_ +```python +def __init__(*, symbol: Symbol, ram: RAM = None) +``` +#### Parameters +| Name | Type | Description | Default | +|----------|----------|-----------------------------------------|---------| +| `symbol` | `Symbol` | The Financial instrument | None | +| `ram` | `RAM` | Risk Assessment and Management instance | None | + + +### create\_order +```python +async def create_order(*, order_type: OrderType, `kwargs) +``` +Complete the order object with the required values. Creates a simple order. +#### Parameters +| Name | Type | Description | Default | +|--------------|-------------|-------------------------------------------------------|---------| +| `order_type` | `OrderType` | Type of order | None | +| `kwargs` | | keyword arguments as required for the specific trader | | + + +### set\_order\_limits +```python +async def set_order_limits(pips: float): +``` +Sets the stop loss and take profit for the order. This method uses pips as defined for forex instruments. +#### Parameters +| Name | Type | Description | Default | +|--------|---------|-------------|---------| +| `pips` | `float` | Target pips | None | + + +### set\_trade\_stop\_levels +```python +async def set_trade_stop_levels(*, points) +``` +sets the stop loss and take profit for the order. This method uses points as defined by MetaTrader5 for all symbols. +#### Parameters +| Name | Type | Description | Default | +|----------|---------|---------------|---------| +| `points` | `float` | Target points | None | + + +### send\_order +```python +async def send_order() +``` +Sends the order to the broker for execution. Record the trade. + + +### check_order +```python +async def check_order() +``` +Checks the status of the order before placing the trade. +#### Returns +| Type | Description | +|--------|-----------------------------------| +| `bool` | True if order is valid else False | + + +### record_trade +```python +async def record_trade(result: OrderSendResult, parameters: dict = None, name: str = '', exclude: set = None) +``` +Records the trade and the order details if `Config.record_trades` is true. Trades are recorded as either json or csv. +#### Parameters +| Name | Type | Description | Default | +|--------------|-------------------|--------------------------------------------------------------|---------| +| `result` | `OrderSendResult` | The result of the placed order | None | +| `parameters` | `dict` | parameters to saved instead of the ones in `self.parameters` | None | +| `name` | `str` | Name for the csv or json file | '' | +| `exclude` | `set` | Set of keys to exclude from the saved parameters | None | + + +### place\_trade +```python +@abstractmethod + async def place_trade(self, *args, **kwargs): +``` +Places a trade. All traders must implement this method. diff --git a/docs/lib/utils.md b/docs/lib/utils.md new file mode 100644 index 0000000..af921db --- /dev/null +++ b/docs/lib/utils.md @@ -0,0 +1,66 @@ +# Utils +Utils is a collection of utility functions that are used throughout the codebase. It is a collection of functions. + +## Table of Contents +- [round_off](#round_off) +- [find_bearish_fractal](#find_bearish_fractal) +- [find_bullish_fractal](#find_bullish_fractal) +- [dict_to_string](#dict_to_string) + + +```python +def round_off(value: float, step: float, round_down: bool = True) -> float: +``` +Rounds off a value to the nearest step. If round_down is True, it will round down, otherwise it will round up. +#### Parameters +| Name | Type | Description | Default | +|------------|-------|--------------------------------------------|---------| +| value | float | The value to round off. | | +| step | float | The step to round off to. | | +| round_down | bool | Whether to round down. If False, round up. | True | +#### Returns +| Type | Description | +|-------|------------------------| +| float | The rounded off value. | + +```python +def find_bearish_fractal(candles: Candles) -> Candle | None: +``` +Finds the most recent bearish fractal in the candles. +#### Parameters +| Name | Type | Description | Default | +|---------|---------|----------------------------------|---------| +| candles | Candles | The candles to search for. | | +#### Returns +| Type | Description | +|--------|----------------------------------| +| Candle | The most recent bearish fractal. | + +```python +def find_bullish_fractal(candles: Candles) -> Candle | None: +``` +Finds the most recent bullish fractal in the candles. +#### Parameters +| Name | Type | Description | Default | +|---------|---------|----------------------------------|---------| +| candles | Candles | The candles to search for. | | +#### Returns +| Type | Description | +|--------|----------------------------------| +| Candle | The most recent bullish fractal. | + + +```python +def dict_to_string(data: dict, multi=True) -> str: +``` +Converts a dictionary to a string. If multi is True, it will return a multi-line string. +#### Parameters +| Name | Type | Description | Default | +|-------|------|----------------------------------------|---------| +| data | dict | The dictionary to convert to a string. | | +| multi | bool | Whether to return a multi-line string. | True | + +#### Returns +| Type | Description | +|------|-----------------------------| +| str | The dictionary as a string. | diff --git a/docs/main.md b/docs/main.md new file mode 100644 index 0000000..be020eb --- /dev/null +++ b/docs/main.md @@ -0,0 +1,3842 @@ +# Table of Contents + +* [aiomql](#aiomql) +* [aiomql.account](#aiomql.account) + * [Account](#aiomql.account.Account) + * [refresh](#aiomql.account.Account.refresh) + * [account\_info](#aiomql.account.Account.account_info) + * [\_\_aenter\_\_](#aiomql.account.Account.__aenter__) + * [sign\_in](#aiomql.account.Account.sign_in) + * [has\_symbol](#aiomql.account.Account.has_symbol) + * [symbols\_get](#aiomql.account.Account.symbols_get) +* [aiomql.bot\_builder](#aiomql.bot_builder) + * [Bot](#aiomql.bot_builder.Bot) + * [initialize](#aiomql.bot_builder.Bot.initialize) + * [execute](#aiomql.bot_builder.Bot.execute) + * [start](#aiomql.bot_builder.Bot.start) + * [add\_strategy](#aiomql.bot_builder.Bot.add_strategy) + * [add\_strategies](#aiomql.bot_builder.Bot.add_strategies) + * [add\_strategy\_all](#aiomql.bot_builder.Bot.add_strategy_all) + * [init\_symbols](#aiomql.bot_builder.Bot.init_symbols) + * [init\_symbol](#aiomql.bot_builder.Bot.init_symbol) +* [aiomql.candle](#aiomql.candle) + * [Candle](#aiomql.candle.Candle) + * [\_\_init\_\_](#aiomql.candle.Candle.__init__) + * [set\_attributes](#aiomql.candle.Candle.set_attributes) + * [mid](#aiomql.candle.Candle.mid) + * [is\_bullish](#aiomql.candle.Candle.is_bullish) + * [is\_bearish](#aiomql.candle.Candle.is_bearish) + * [Candles](#aiomql.candle.Candles) + * [\_\_init\_\_](#aiomql.candle.Candles.__init__) + * [ta](#aiomql.candle.Candles.ta) + * [ta\_lib](#aiomql.candle.Candles.ta_lib) + * [data](#aiomql.candle.Candles.data) + * [rename](#aiomql.candle.Candles.rename) +* [aiomql.core.base](#aiomql.core.base) + * [Base](#aiomql.core.base.Base) + * [set\_attributes](#aiomql.core.base.Base.set_attributes) + * [annotations](#aiomql.core.base.Base.annotations) + * [get\_dict](#aiomql.core.base.Base.get_dict) + * [class\_vars](#aiomql.core.base.Base.class_vars) + * [dict](#aiomql.core.base.Base.dict) + * [Meta](#aiomql.core.base.Base.Meta) +* [aiomql.core.config](#aiomql.core.config) + * [Config](#aiomql.core.config.Config) + * [account\_info](#aiomql.core.config.Config.account_info) +* [aiomql.core.constants](#aiomql.core.constants) + * [TradeAction](#aiomql.core.constants.TradeAction) + * [OrderFilling](#aiomql.core.constants.OrderFilling) + * [OrderTime](#aiomql.core.constants.OrderTime) + * [OrderType](#aiomql.core.constants.OrderType) + * [opposite](#aiomql.core.constants.OrderType.opposite) + * [BookType](#aiomql.core.constants.BookType) + * [TimeFrame](#aiomql.core.constants.TimeFrame) + * [time](#aiomql.core.constants.TimeFrame.time) + * [CopyTicks](#aiomql.core.constants.CopyTicks) + * [PositionType](#aiomql.core.constants.PositionType) + * [PositionReason](#aiomql.core.constants.PositionReason) + * [DealType](#aiomql.core.constants.DealType) + * [DealEntry](#aiomql.core.constants.DealEntry) + * [DealReason](#aiomql.core.constants.DealReason) + * [OrderReason](#aiomql.core.constants.OrderReason) + * [SymbolChartMode](#aiomql.core.constants.SymbolChartMode) + * [SymbolCalcMode](#aiomql.core.constants.SymbolCalcMode) + * [SymbolTradeMode](#aiomql.core.constants.SymbolTradeMode) + * [SymbolTradeExecution](#aiomql.core.constants.SymbolTradeExecution) + * [SymbolSwapMode](#aiomql.core.constants.SymbolSwapMode) + * [DayOfWeek](#aiomql.core.constants.DayOfWeek) + * [SymbolOrderGTCMode](#aiomql.core.constants.SymbolOrderGTCMode) + * [SymbolOptionRight](#aiomql.core.constants.SymbolOptionRight) + * [SymbolOptionMode](#aiomql.core.constants.SymbolOptionMode) + * [AccountTradeMode](#aiomql.core.constants.AccountTradeMode) + * [TickFlag](#aiomql.core.constants.TickFlag) + * [TradeRetcode](#aiomql.core.constants.TradeRetcode) + * [AccountStopOutMode](#aiomql.core.constants.AccountStopOutMode) + * [AccountMarginMode](#aiomql.core.constants.AccountMarginMode) +* [aiomql.core.errors](#aiomql.core.errors) + * [Error](#aiomql.core.errors.Error) +* [aiomql.core.exceptions](#aiomql.core.exceptions) + * [LoginError](#aiomql.core.exceptions.LoginError) + * [VolumeError](#aiomql.core.exceptions.VolumeError) + * [SymbolError](#aiomql.core.exceptions.SymbolError) + * [OrderError](#aiomql.core.exceptions.OrderError) +* [aiomql.core.meta\_trader](#aiomql.core.meta_trader) + * [MetaTrader](#aiomql.core.meta_trader.MetaTrader) + * [\_\_aenter\_\_](#aiomql.core.meta_trader.MetaTrader.__aenter__) + * [\_\_aexit\_\_](#aiomql.core.meta_trader.MetaTrader.__aexit__) + * [login](#aiomql.core.meta_trader.MetaTrader.login) + * [initialize](#aiomql.core.meta_trader.MetaTrader.initialize) + * [shutdown](#aiomql.core.meta_trader.MetaTrader.shutdown) + * [version](#aiomql.core.meta_trader.MetaTrader.version) + * [account\_info](#aiomql.core.meta_trader.MetaTrader.account_info) + * [orders\_get](#aiomql.core.meta_trader.MetaTrader.orders_get) +* [aiomql.core.models](#aiomql.core.models) + * [AccountInfo](#aiomql.core.models.AccountInfo) + * [TerminalInfo](#aiomql.core.models.TerminalInfo) + * [SymbolInfo](#aiomql.core.models.SymbolInfo) + * [BookInfo](#aiomql.core.models.BookInfo) + * [TradeOrder](#aiomql.core.models.TradeOrder) + * [TradeRequest](#aiomql.core.models.TradeRequest) + * [OrderCheckResult](#aiomql.core.models.OrderCheckResult) + * [OrderSendResult](#aiomql.core.models.OrderSendResult) + * [TradePosition](#aiomql.core.models.TradePosition) + * [TradeDeal](#aiomql.core.models.TradeDeal) +* [aiomql.core](#aiomql.core) +* [aiomql.executor](#aiomql.executor) + * [Executor](#aiomql.executor.Executor) + * [add\_workers](#aiomql.executor.Executor.add_workers) + * [remove\_workers](#aiomql.executor.Executor.remove_workers) + * [add\_worker](#aiomql.executor.Executor.add_worker) + * [run](#aiomql.executor.Executor.run) + * [execute](#aiomql.executor.Executor.execute) +* [aiomql.history](#aiomql.history) + * [History](#aiomql.history.History) + * [\_\_init\_\_](#aiomql.history.History.__init__) + * [init](#aiomql.history.History.init) + * [get\_deals](#aiomql.history.History.get_deals) + * [deals\_total](#aiomql.history.History.deals_total) + * [get\_orders](#aiomql.history.History.get_orders) + * [orders\_total](#aiomql.history.History.orders_total) +* [aiomql.lib.strategies.finger\_trap](#aiomql.lib.strategies.finger_trap) + * [Entry](#aiomql.lib.strategies.finger_trap.Entry) +* [aiomql.lib.strategies](#aiomql.lib.strategies) +* [aiomql.lib.symbols.forex\_symbol](#aiomql.lib.symbols.forex_symbol) + * [ForexSymbol](#aiomql.lib.symbols.forex_symbol.ForexSymbol) + * [pip](#aiomql.lib.symbols.forex_symbol.ForexSymbol.pip) + * [compute\_volume](#aiomql.lib.symbols.forex_symbol.ForexSymbol.compute_volume) +* [aiomql.lib.symbols](#aiomql.lib.symbols) +* [aiomql.lib.traders.simple\_deal\_trader](#aiomql.lib.traders.simple_deal_trader) + * [DealTrader](#aiomql.lib.traders.simple_deal_trader.DealTrader) + * [create\_order](#aiomql.lib.traders.simple_deal_trader.DealTrader.create_order) +* [aiomql.lib.traders](#aiomql.lib.traders) +* [aiomql.lib](#aiomql.lib) +* [aiomql.order](#aiomql.order) + * [Order](#aiomql.order.Order) + * [\_\_init\_\_](#aiomql.order.Order.__init__) + * [orders\_total](#aiomql.order.Order.orders_total) + * [orders](#aiomql.order.Order.orders) + * [check](#aiomql.order.Order.check) + * [send](#aiomql.order.Order.send) + * [calc\_margin](#aiomql.order.Order.calc_margin) + * [calc\_profit](#aiomql.order.Order.calc_profit) +* [aiomql.positions](#aiomql.positions) + * [Positions](#aiomql.positions.Positions) + * [\_\_init\_\_](#aiomql.positions.Positions.__init__) + * [positions\_total](#aiomql.positions.Positions.positions_total) + * [positions\_get](#aiomql.positions.Positions.positions_get) + * [close\_all](#aiomql.positions.Positions.close_all) +* [aiomql.ram](#aiomql.ram) + * [RAM](#aiomql.ram.RAM) + * [\_\_init\_\_](#aiomql.ram.RAM.__init__) + * [get\_amount](#aiomql.ram.RAM.get_amount) + * [get\_volume](#aiomql.ram.RAM.get_volume) +* [aiomql.records](#aiomql.records) + * [Records](#aiomql.records.Records) + * [\_\_init\_\_](#aiomql.records.Records.__init__) + * [get\_records](#aiomql.records.Records.get_records) + * [read\_update](#aiomql.records.Records.read_update) + * [update\_rows](#aiomql.records.Records.update_rows) + * [update\_records](#aiomql.records.Records.update_records) + * [update\_record](#aiomql.records.Records.update_record) +* [aiomql.result](#aiomql.result) + * [Result](#aiomql.result.Result) + * [\_\_init\_\_](#aiomql.result.Result.__init__) + * [to\_csv](#aiomql.result.Result.to_csv) + * [save\_csv](#aiomql.result.Result.save_csv) +* [aiomql.strategy](#aiomql.strategy) + * [Strategy](#aiomql.strategy.Strategy) + * [\_\_init\_\_](#aiomql.strategy.Strategy.__init__) + * [sleep](#aiomql.strategy.Strategy.sleep) + * [trade](#aiomql.strategy.Strategy.trade) +* [aiomql.symbol](#aiomql.symbol) + * [Symbol](#aiomql.symbol.Symbol) + * [pip](#aiomql.symbol.Symbol.pip) + * [info\_tick](#aiomql.symbol.Symbol.info_tick) + * [symbol\_select](#aiomql.symbol.Symbol.symbol_select) + * [info](#aiomql.symbol.Symbol.info) + * [init](#aiomql.symbol.Symbol.init) + * [book\_add](#aiomql.symbol.Symbol.book_add) + * [book\_get](#aiomql.symbol.Symbol.book_get) + * [book\_release](#aiomql.symbol.Symbol.book_release) + * [compute\_volume](#aiomql.symbol.Symbol.compute_volume) + * [currency\_conversion](#aiomql.symbol.Symbol.currency_conversion) + * [copy\_rates\_from](#aiomql.symbol.Symbol.copy_rates_from) + * [copy\_rates\_from\_pos](#aiomql.symbol.Symbol.copy_rates_from_pos) + * [copy\_rates\_range](#aiomql.symbol.Symbol.copy_rates_range) + * [copy\_ticks\_from](#aiomql.symbol.Symbol.copy_ticks_from) + * [copy\_ticks\_range](#aiomql.symbol.Symbol.copy_ticks_range) +* [aiomql.terminal](#aiomql.terminal) + * [Terminal](#aiomql.terminal.Terminal) + * [initialize](#aiomql.terminal.Terminal.initialize) + * [version](#aiomql.terminal.Terminal.version) + * [info](#aiomql.terminal.Terminal.info) + * [symbols\_total](#aiomql.terminal.Terminal.symbols_total) +* [aiomql.ticks](#aiomql.ticks) + * [Tick](#aiomql.ticks.Tick) + * [set\_attributes](#aiomql.ticks.Tick.set_attributes) + * [Ticks](#aiomql.ticks.Ticks) + * [\_\_init\_\_](#aiomql.ticks.Ticks.__init__) + * [ta](#aiomql.ticks.Ticks.ta) + * [ta\_lib](#aiomql.ticks.Ticks.ta_lib) + * [data](#aiomql.ticks.Ticks.data) + * [rename](#aiomql.ticks.Ticks.rename) +* [aiomql.trader](#aiomql.trader) + * [Trader](#aiomql.trader.Trader) + * [\_\_init\_\_](#aiomql.trader.Trader.__init__) + * [create\_order](#aiomql.trader.Trader.create_order) + * [set\_order\_limits](#aiomql.trader.Trader.set_order_limits) + * [place\_trade](#aiomql.trader.Trader.place_trade) +* [aiomql.utils](#aiomql.utils) + * [dict\_to\_string](#aiomql.utils.dict_to_string) + + + +# aiomql + + + +# aiomql.account + + + +## Account Objects + +```python +class Account(AccountInfo) +``` + +A class for managing a trading account. A singleton class. +A subclass of AccountInfo. All AccountInfo attributes are available in this class. + +**Attributes**: + +- `connected` _bool_ - Status of connection to MetaTrader 5 Terminal +- `symbols` _set[SymbolInfo]_ - A set of available symbols for the financial market. + + +**Notes**: + + Other Account properties are defined in the AccountInfo class. + + + +#### refresh + +```python +async def refresh() +``` + +Refreshes the account instance with the latest account details from the MetaTrader 5 terminal + + + +#### account\_info + +```python +@property +def account_info() -> dict +``` + +Get account login, server and password details. If the login attribute of the account instance returns +a falsy value, the config instance is used to get the account details. + +**Returns**: + +- `dict` - A dict of login, server and password details + + +**Notes**: + + This method will only look for config details in the config instance if the login attribute of the + account Instance returns a falsy value + + + +#### \_\_aenter\_\_ + +```python +async def __aenter__() -> 'Account' +``` + +Connect to a trading account and return the account instance. +Async context manager for the Account class. + +**Returns**: + +- `Account` - An instance of the Account class + + +**Raises**: + +- `LoginError` - If login fails + + + +#### sign\_in + +```python +async def sign_in() -> bool +``` + +Connect to a trading account. + +**Returns**: + +- `bool` - True if login was successful else False + + + +#### has\_symbol + +```python +def has_symbol(symbol: str | Type[SymbolInfo]) +``` + +Checks to see if a symbol is available for a trading account + +**Arguments**: + + symbol (str | SymbolInfo): + + +**Returns**: + +- `bool` - True if symbol is present otherwise False + + + +#### symbols\_get + +```python +async def symbols_get() -> set[SymbolInfo] +``` + +Get all financial instruments from the MetaTrader 5 terminal available for the current account. + +**Returns**: + +- `set[Symbol]` - A set of available symbols. + + + +# aiomql.bot\_builder + + + +## Bot Objects + +```python +class Bot() +``` + +The bot class. Create a bot instance to run your strategies. + +**Attributes**: + +- `account` _Account_ - Account Object. +- `executor` - The default thread executor. +- `symbols` _set[Symbols]_ - A set of symbols for the trading session + + + +#### initialize + +```python +async def initialize() +``` + +Prepares the bot by signing in to the trading account and initializing the symbols for the trading session. + +**Raises**: + + SystemExit if sign in was not successful + + + +#### execute + +```python +def execute() +``` + +Execute the bot. + + + +#### start + +```python +async def start() +``` + +Starts the bot by calling the initialize method and running the strategies in the executor. + + + +#### add\_strategy + +```python +def add_strategy(strategy: Strategy) +``` + +Add a strategy to the executor. An added strategy will only run if it's symbol was successfully initialized. + +**Arguments**: + +- `strategy` _Strategy_ - A Strategy instance to run on bot + + +**Notes**: + + Make sure the symbol has been added to the market + + + +#### add\_strategies + +```python +def add_strategies(strategies: Iterable[Strategy]) +``` + +Add multiple strategies at the same time + +**Arguments**: + +- `strategies` - A list of strategies + + + +#### add\_strategy\_all + +```python +def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None) +``` + +Use this to run a single strategy on all available instruments in the market using the default parameters +i.e one set of parameters for all trading symbols + +**Arguments**: + +- `strategy` _Strategy_ - Strategy class +- `params` _dict_ - A dictionary of parameters for the strategy + + + +#### init\_symbols + +```python +async def init_symbols() +``` + +Initialize the symbols for the current trading session. This method is called internally by the bot. + + + +#### init\_symbol + +```python +async def init_symbol(symbol: Symbol) -> Symbol +``` + +Initialize a symbol before the beginning of a trading sessions. +Removes it from the list of symbols if it was not successfully initialized or not available +for the current market. + +**Arguments**: + +- `symbol` _Symbol_ - Symbol object to be initialized + + +**Returns**: + +- `Symbol` - if successfully initialized + + + +# aiomql.candle + +Candle and Candles classes for handling bars from the MetaTrader 5 terminal. + + + +## Candle Objects + +```python +class Candle() +``` + +A class representing bars from the MetaTrader 5 terminal as a customized class analogous to Japanese Candlesticks. +You can subclass this class for added customization. + +**Attributes**: + +- `time` _int_ - Period start time. +- `open` _int_ - Open price +- `high` _float_ - The highest price of the period +- `low` _float_ - The lowest price of the period +- `close` _float_ - Close price +- `tick_volume` _float_ - Tick volume +- `real_volume` _float_ - Trade volume +- `spread` _float_ - Spread +- `Index` _int_ - Custom attribute representing the position of the candle in a sequence. + + + +#### \_\_init\_\_ + +```python +def __init__(**kwargs) +``` + +Create a Candle object from keyword arguments. + +**Arguments**: + +- `**kwargs` - Candle attributes and values as keyword arguments. + + + +#### set\_attributes + +```python +def set_attributes(**kwargs) +``` + +Set keyword arguments as instance attributes + +**Arguments**: + +- `**kwargs` - Instance attributes and values as keyword arguments + + + +#### mid + +```python +@property +def mid() -> float +``` + +The median of open and close + +**Returns**: + +- `float` - The median of open and close + + + +#### is\_bullish + +```python +def is_bullish() -> bool +``` + +A simple check to see if the candle is bullish. + +**Returns**: + +- `bool` - True or False + + + +#### is\_bearish + +```python +def is_bearish() -> bool +``` + +A simple check to see if the candle is bearish. + +**Returns**: + +- `bool` - True or False + + + +## Candles Objects + +```python +class Candles(Generic[_Candle]) +``` + +An iterable container class of Candle objects in chronological order. + +**Attributes**: + +- `Index` _Series['int']_ - A pandas Series of the indexes of all candles in the object. +- `time` _Series['int']_ - A pandas Series of the time of all candles in the object. +- `open` _Series[float]_ - A pandas Series of the opening price of all candles in the object. +- `high` _Series[float]_ - A pandas Series of the high price of all candles in the object. +- `low` _Series[float]_ - A pandas Series of the low price of all candles in the object. +- `close` _Series[float]_ - A pandas Series of the closing price of all candles in the object. +- `tick_volume` _Series[float]_ - A pandas Series of the tick volume of all candles in the object. +- `real_volume` _Series[float]_ - A pandas Series of the real volume of all candles in the object. +- `spread` _Series[float]_ - A pandas Series of the spread of all candles in the object. +- `timeframe` _TimeFrame_ - The timeframe of the candles in the object. +- `Candle` _Type[Candle]_ - The Candle class for representing the candles in the object. + + properties: +- `data` _DataFrame_ - A pandas DataFrame of all candles in the object. + + +**Notes**: + + The candle class can be customized by subclassing the Candle class and passing the subclass as the candle keyword argument. + Or defining it on the class body as a class attribute. + + + +#### \_\_init\_\_ + +```python +def __init__(*, + data: DataFrame | _Candles | Iterable, + flip=False, + candle_class: Type[_Candle] = None) +``` + +A container class of Candle objects in chronological order. + +**Arguments**: + +- `data` _DataFrame|Candles|Iterable_ - A pandas dataframe, a Candles object or any suitable iterable + + +**Arguments**: + +- `flip` _bool_ - Reverse the chronological order of the candles to the oldest first. Defaults to False. +- `candle_class` - A subclass of Candle to use as the candle class. Defaults to Candle. + + + +#### ta + +```python +@property +def ta() +``` + +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. + +**Returns**: + +- `pandas_ta` - The pandas_ta library + + + +#### ta\_lib + +```python +@property +def ta_lib() +``` + +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. + +**Returns**: + +- `ta` - The ta library + + + +#### data + +```python +@property +def data() -> DataFrame +``` + +The original data passed to the class as a pandas DataFrame + + + +#### rename + +```python +def rename(inplace=True, **kwargs) -> _Candles | None +``` + +Rename columns of the candles class. + +**Arguments**: + +- `inplace` _bool_ - Rename the columns inplace or return a new instance of the class with the renamed columns +- `**kwargs` - The new names of the columns + + +**Returns**: + +- `Candles` - A new instance of the class with the renamed columns if inplace is False. +- `None` - If inplace is True + + + +# aiomql.core.base + + + +## Base Objects + +```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. +For the data model classes attributes are annotated on the class body and are set as object attributes when the +class is instantiated. + +**Arguments**: + +- `**kwargs` - Object attributes and values as keyword arguments. Only added if they are annotated on the class body. + + Class Attributes: +- `mt5` _MetaTrader_ - An instance of the MetaTrader class +- `config` _Config_ - An instance of the Config class +- `Meta` _Type[Meta]_ - The Meta class for configuration of the data model class + + + +#### set\_attributes + +```python +def set_attributes(**kwargs) +``` + +Set keyword arguments as object attributes + +**Arguments**: + +- `**kwargs` - Object attributes and values as keyword arguments + + +**Raises**: + +- `AttributeError` - When assigning an attribute that does not belong to the class or any parent class + + +**Notes**: + + Only sets attributes that have been annotated on the class body. + + + +#### annotations + +```python +@property +@cache +def annotations() -> dict +``` + +Class annotations from all ancestor classes and the current class. + +**Returns**: + +- `dict` - A dictionary of class annotations + + + +#### get\_dict + +```python +def get_dict(exclude: set = None, include: set = None) -> dict +``` + +Returns class attributes as a dict, with the ability to filter + +**Arguments**: + +- `exclude` - A set of attributes to be excluded +- `include` - Specific attributes to be returned + + +**Returns**: + +- `dict` - A dictionary of specified class attributes + + +**Notes**: + + You can only set either of include or exclude. If you set both, include will take precedence + + + +#### class\_vars + +```python +@property +@cache +def class_vars() +``` + +Annotated class attributes + +**Returns**: + +- `dict` - A dictionary of available class attributes in all ancestor classes and the current class. + + + +#### dict + +```python +@property +def dict() -> dict +``` + +All instance and class attributes as a dictionary, except those excluded in the Meta class. + +**Returns**: + +- `dict` - A dictionary of instance and class attributes + + + +## Meta Objects + +```python +class Meta() +``` + +A class for defining class attributes to be excluded or included in the dict property + +**Attributes**: + +- `exclude` _set_ - A set of attributes to be excluded +- `include` _set_ - Specific attributes to be returned. Include supercedes exclude. + + + +#### filter + +```python +@classmethod +@property +def filter(cls) -> set +``` + +Combine the exclude and include attributes to return a set of attributes to be excluded. + +**Returns**: + +- `set` - A set of attributes to be excluded + + + +# aiomql.core.config + + + +## Config Objects + +```python +class Config() +``` + +A class for handling configuration settings for the aiomql package. + +**Arguments**: + +- `**kwargs` - Configuration settings as keyword arguments. + Variables set this way supersede those set in the config file. + + +**Attributes**: + +- `record_trades` _bool_ - Whether to keep record of trades or not. +- `filename` _str_ - Name of the config file +- `records_dir` _str_ - Path to the directory where trade records are saved +- `win_percentage` _float_ - Percentage of achieved target profit in a trade to be considered a win +- `login` _int_ - Trading account number +- `password` _str_ - Trading account password +- `server` _str_ - Broker server +- `path` _str_ - Path to terminal file +- `timeout` _int_ - Timeout for terminal connection + + +**Notes**: + + By default, the config class looks for a file named aiomql.json. + You can change this by passing the filename keyword argument to the constructor. + By passing reload=True to the load_config method, you can reload and search again for the config file. + + + +#### account\_info + +```python +def account_info() -> dict['login', 'password', 'server'] +``` + +Returns Account login details as found in the config object if available + +**Returns**: + +- `dict` - A dictionary of login details + + + +# aiomql.core.constants + + + +## TradeAction Objects + +```python +class TradeAction(Repr, IntEnum) +``` + +TRADE_REQUEST_ACTION Enum. + +**Attributes**: + +- `DEAL` _int_ - Delete the pending order placed previously Place a trade order for an immediate execution with the + specified parameters (market order). +- `PENDING` _int_ - Delete the pending order placed previously +- `SLTP` _int_ - Modify Stop Loss and Take Profit values of an opened position +- `MODIFY` _int_ - Modify the parameters of the order placed previously +- `REMOVE` _int_ - Delete the pending order placed previously +- `CLOSE_BY` _int_ - Close a position by an opposite one + + + +## OrderFilling Objects + +```python +class OrderFilling(Repr, IntEnum) +``` + +ORDER_TYPE_FILLING Enum. + +**Attributes**: + +- `FOK` _int_ - 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` _int_ - 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` _int_ - 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. + + + +## OrderTime Objects + +```python +class OrderTime(Repr, IntEnum) +``` + +ORDER_TIME Enum. + +**Attributes**: + +- `GTC` _int_ - Good till cancel order +- `DAY` _int_ - Good till current trade day order +- `SPECIFIED` _int_ - The order is active until the specified date +- `SPECIFIED_DAY` _int_ - 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. + + + +## OrderType Objects + +```python +class OrderType(Repr, IntEnum) +``` + +ORDER_TYPE Enum. + +**Attributes**: + +- `BUY` _int_ - Market buy order +- `SELL` _int_ - Market sell order +- `BUY_LIMIT` _int_ - Buy Limit pending order +- `SELL_LIMIT` _int_ - Sell Limit pending order +- `BUY_STOP` _int_ - Buy Stop pending order +- `SELL_STOP` _int_ - Sell Stop pending order +- `BUY_STOP_LIMIT` _int_ - Upon reaching the order price, Buy Limit pending order is placed at StopLimit price +- `SELL_STOP_LIMIT` _int_ - Upon reaching the order price, Sell Limit pending order is placed at StopLimit price +- `CLOSE_BY` _int_ - Order for closing a position by an opposite one + + Properties: +- `opposite` _int_ - Gets the opposite of an order type + + + +#### opposite + +```python +@property +def opposite() +``` + +Gets the opposite of an order type for closing an open position + +**Returns**: + +- `int` - integer value of opposite order type + + + +## BookType Objects + +```python +class BookType(Repr, IntEnum) +``` + +BOOK_TYPE Enum. + +**Attributes**: + +- `SELL` _int_ - Sell order (Offer) +- `BUY` _int_ - Buy order (Bid) +- `SELL_MARKET` _int_ - Sell order by Market +- `BUY_MARKET` _int_ - Buy order by Market + + + +## TimeFrame Objects + +```python +class TimeFrame(Repr, IntEnum) +``` + +TIMEFRAME Enum. + +**Attributes**: + +- `M1` _int_ - One Minute +- `M2` _int_ - Two Minutes +- `M3` _int_ - Three Minutes +- `M4` _int_ - Four Minutes +- `M5` _int_ - Five Minutes +- `M6` _int_ - Six Minutes +- `M10` _int_ - Ten Minutes +- `M15` _int_ - Fifteen Minutes +- `M20` _int_ - Twenty Minutes +- `M30` _int_ - Thirty Minutes +- `H1` _int_ - One Hour +- `H2` _int_ - Two Hours +- `H3` _int_ - Three Hours +- `H4` _int_ - Four Hours +- `H6` _int_ - Six Hours +- `H8` _int_ - Eight Hours +- `D1` _int_ - One Day +- `W1` _int_ - One Week +- `MN1` _int_ - One Month + + Properties: +- `time` - return the value of the timeframe object in seconds. Used as a property + + +**Methods**: + +- `get` - get a timeframe object from a time value in seconds + + + +#### time + +```python +@property +def time() +``` + +The number of seconds in a TIMEFRAME + +**Returns**: + +- `int` - The number of seconds in a TIMEFRAME + + +**Examples**: + + >>> t = TimeFrame.H1 + >>> print(t.time) + 3600 + + + +## CopyTicks Objects + +```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. + +**Attributes**: + +- `ALL` _int_ - All ticks +- `INFO` _int_ - Ticks containing Bid and/or Ask price changes +- `TRADE` _int_ - Ticks containing Last and/or Volume price changes + + + +## PositionType Objects + +```python +class PositionType(Repr, IntEnum) +``` + +POSITION_TYPE Enum. Direction of an open position (buy or sell) + +**Attributes**: + +- `BUY` _int_ - Buy +- `SELL` _int_ - Sell + + + +## PositionReason Objects + +```python +class PositionReason(Repr, IntEnum) +``` + +POSITION_REASON Enum. The reason for opening a position is contained in the POSITION_REASON Enum + +**Attributes**: + +- `CLIENT` _int_ - The position was opened as a result of activation of an order placed from a desktop terminal +- `MOBILE` _int_ - The position was opened as a result of activation of an order placed from a mobile application +- `WEB` _int_ - The position was opened as a result of activation of an order placed from the web platform +- `EXPERT` _int_ - The position was opened as a result of activation of an order placed from an MQL5 program, + i.e. an Expert Advisor or a script + + + +## DealType Objects + +```python +class DealType(Repr, IntEnum) +``` + +DEAL_TYPE enum. Each deal is characterized by a type, allowed values are enumerated in this enum + +**Attributes**: + +- `BUY` _int_ - Buy +- `SELL` _int_ - Sell +- `BALANCE` _int_ - Balance +- `CREDIT` _int_ - Credit +- `CHARGE` _int_ - Additional Charge +- `CORRECTION` _int_ - Correction +- `BONUS` _int_ - Bonus +- `COMMISSION` _int_ - Additional Commission +- `COMMISSION_DAILY` _int_ - Daily Commission +- `COMMISSION_MONTHLY` _int_ - Monthly Commission +- `COMMISSION_AGENT_DAILY` _int_ - Daily Agent Commission +- `COMMISSION_AGENT_MONTHLY` _int_ - Monthly Agent Commission +- `INTEREST` _int_ - Interest Rate +- `DEAL_DIVIDEND` _int_ - Dividend Operations +- `DEAL_DIVIDEND_FRANKED` _int_ - Franked (non-taxable) dividend operations +- `DEAL_TAX` _int_ - Tax Charges + +- `BUY_CANCELED` _int_ - 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` _int_ - 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. + + + +## DealEntry Objects + +```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. + +**Attributes**: + +- `IN` _int_ - Entry In +- `OUT` _int_ - Entry Out +- `INOUT` _int_ - Reverse +- `OUT_BY` _int_ - Close a position by an opposite one + + + +## DealReason Objects + +```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. + +**Attributes**: + +- `CLIENT` _int_ - The deal was executed as a result of activation of an order placed from a desktop terminal +- `MOBILE` _int_ - The deal was executed as a result of activation of an order placed from a desktop terminal +- `WEB` _int_ - The deal was executed as a result of activation of an order placed from the web platform +- `EXPERT` _int_ - 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` _int_ - The deal was executed as a result of Stop Loss activation +- `TP` _int_ - The deal was executed as a result of Take Profit activation +- `SO` _int_ - The deal was executed as a result of the Stop Out event +- `ROLLOVER` _int_ - The deal was executed due to a rollover +- `VMARGIN` _int_ - The deal was executed after charging the variation margin +- `SPLIT` _int_ - The deal was executed after the split (price reduction) of an instrument, which had an open + position during split announcement + + + +## OrderReason Objects + +```python +class OrderReason(Repr, IntEnum) +``` + +ORDER_REASON Enum. + +**Attributes**: + +- `CLIENT` _int_ - The order was placed from a desktop terminal +- `MOBILE` _int_ - The order was placed from a mobile application +- `WEB` _int_ - The order was placed from a web platform +- `EXPERT` _int_ - The order was placed from an MQL5-program, i.e. by an Expert Advisor or a script +- `SL` _int_ - The order was placed as a result of Stop Loss activation +- `TP` _int_ - The order was placed as a result of Take Profit activation +- `SO` _int_ - The order was placed as a result of the Stop Out event + + + +## SymbolChartMode Objects + +```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 + +**Attributes**: + +- `BID` _int_ - Bars are based on Bid prices +- `LAST` _int_ - Bars are based on last prices + + + +## SymbolCalcMode Objects + +```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. + +**Attributes**: + +- `FOREX` _int_ - Forex mode - calculation of profit and margin for Forex +- `FOREX_NO_LEVERAGE` _int_ - Forex No Leverage mode – calculation of profit and margin for Forex symbols without + taking into account the leverage +- `FUTURES` _int_ - Futures mode - calculation of margin and profit for futures +- `CFD` _int_ - CFD mode - calculation of margin and profit for CFD +- `CFDINDEX` _int_ - CFD index mode - calculation of margin and profit for CFD by indexes +- `CFDLEVERAGE` _int_ - CFD Leverage mode - calculation of margin and profit for CFD at leverage trading +- `EXCH_STOCKS` _int_ - Calculation of margin and profit for trading securities on a stock exchange +- `EXCH_FUTURES` _int_ - Calculation of margin and profit for trading futures contracts on a stock exchange +- `EXCH_OPTIONS` _int_ - value is 34 +- `EXCH_OPTIONS_MARGIN` _int_ - value is 36 +- `EXCH_BONDS` _int_ - Exchange Bonds mode – calculation of margin and profit for trading bonds on a stock exchange +- `STOCKS_MOEX` _int_ - Exchange MOEX Stocks mode –calculation of margin and profit for trading securities on MOEX +- `EXCH_BONDS_MOEX` _int_ - Exchange MOEX Bonds mode – calculation of margin and profit for trading bonds on MOEX + +- `SERV_COLLATERAL` _int_ - 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 + + + +## SymbolTradeMode Objects + +```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 + +**Attributes**: + +- `DISABLED` _int_ - Trade is disabled for the symbol +- `LONGONLY` _int_ - Allowed only long positions +- `SHORTONLY` _int_ - Allowed only short positions +- `CLOSEONLY` _int_ - Allowed only position close operations +- `FULL` _int_ - No trade restrictions + + + +## SymbolTradeExecution Objects + +```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. + +**Attributes**: + +- `REQUEST` _int_ - Executing a market order at the price previously received from the broker. Prices for a certain + market order are requested from the broker before the order is sent. Upon receiving the prices, order + execution at the given price can be either confirmed or rejected. + +- `INSTANT` _int_ - Executing a market order at the specified price immediately. When sending a trade request to be + executed, the platform automatically adds the current prices to the order. + - If the broker accepts the price, the order is executed. + - If the broker does not accept the requested price, a "Requote" is sent — the broker returns prices, + at which this order can be executed. + +- `MARKET` _int_ - A broker makes a decision about the order execution price without any additional discussion with the trader. + Sending the order in such a mode means advance consent to its execution at this price. + +- `EXCHANGE` _int_ - Trade operations are executed at the prices of the current market offers. + + + +## SymbolSwapMode Objects + +```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. + +**Attributes**: + +- `DISABLED` _int_ - Swaps disabled (no swaps) +- `POINTS` _int_ - Swaps are charged in points +- `CURRENCY_SYMBOL` _int_ - Swaps are charged in money in base currency of the symbol +- `CURRENCY_MARGIN` _int_ - Swaps are charged in money in margin currency of the symbol +- `CURRENCY_DEPOSIT` _int_ - Swaps are charged in money, in client deposit currency + +- `INTEREST_CURRENT` _int_ - Swaps are charged as the specified annual interest from the instrument price at + calculation of swap (standard bank year is 360 days) + +- `INTEREST_OPEN` _int_ - Swaps are charged as the specified annual interest from the open price of position + (standard bank year is 360 days) + +- `REOPEN_CURRENT` _int_ - 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` _int_ - 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) + + + +## DayOfWeek Objects + +```python +class DayOfWeek(Repr, IntEnum) +``` + +DAY_OF_WEEK Enum. + +**Attributes**: + +- `SUNDAY` _int_ - Sunday +- `MONDAY` _int_ - Monday +- `TUESDAY` _int_ - Tuesday +- `WEDNESDAY` _int_ - Wednesday +- `THURSDAY` _int_ - Thursday +- `FRIDAY` _int_ - Friday +- `SATURDAY` _int_ - Saturday + + + +## SymbolOrderGTCMode Objects + +```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. + +**Attributes**: + +- `GTC` _int_ - Pending orders and Stop Loss/Take Profit levels are valid for an unlimited period + until theirConstants, Enumerations and explicit cancellation + +- `DAILY` _int_ - 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` _int_ - When a trade day changes, only pending orders are deleted, + while Stop Loss and Take Profit levels are preserved + + + +## SymbolOptionRight Objects + +```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. + +**Attributes**: + +- `CALL` _int_ - A call option gives you the right to buy an asset at a specified price. +- `PUT` _int_ - A put option gives you the right to sell an asset at a specified price. + + + +## SymbolOptionMode Objects + +```python +class SymbolOptionMode(Repr, IntEnum) +``` + +SYMBOL_OPTION_MODE Enum. + +**Attributes**: + +- `EUROPEAN` _int_ - European option may only be exercised on a specified date (expiration, execution date, delivery date) +- `AMERICAN` _int_ - 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. + + + +## AccountTradeMode Objects + +```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. + +**Attributes**: + +- `DEMO` - Demo account +- `CONTEST` - Contest account +- `REAL` - Real Account + + + +## TickFlag Objects + +```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. + +**Attributes**: + +- `BID` _int_ - Bid price changed +- `ASK` _int_ - Ask price changed +- `LAST` _int_ - Last price changed +- `VOLUME` _int_ - Volume changed +- `BUY` _int_ - last Buy price changed +- `SELL` _int_ - last Sell price changed + + + +## TradeRetcode Objects + +```python +class TradeRetcode(Repr, IntEnum) +``` + +TRADE_RETCODE Enum. Return codes for order send/check operations + +**Attributes**: + +- `REQUOTE` _int_ - Requote +- `REJECT` _int_ - Request rejected +- `CANCEL` _int_ - Request canceled by trader +- `PLACED` _int_ - Order placed +- `DONE` _int_ - Request completed +- `DONE_PARTIAL` _int_ - Only part of the request was completed +- `ERROR` _int_ - Request processing error +- `TIMEOUT` _int_ - Request canceled by timeout +- `INVALID` _int_ - Invalid request +- `INVALID_VOLUME` _int_ - Invalid volume in the request +- `INVALID_PRICE` _int_ - Invalid price in the request +- `INVALID_STOPS` _int_ - Invalid stops in the request +- `TRADE_DISABLED` _int_ - Trade is disabled +- `MARKET_CLOSED` _int_ - Market is closed +- `NO_MONEY` _int_ - There is not enough money to complete the request +- `PRICE_CHANGED` _int_ - Prices changed +- `PRICE_OFF` _int_ - There are no quotes to process the request +- `INVALID_EXPIRATION` _int_ - Invalid order expiration date in the request +- `ORDER_CHANGED` _int_ - Order state changed +- `TOO_MANY_REQUESTS` _int_ - Too frequent requests +- `NO_CHANGES` _int_ - No changes in request +- `SERVER_DISABLES_AT` _int_ - Autotrading disabled by server +- `CLIENT_DISABLES_AT` _int_ - Autotrading disabled by client terminal +- `LOCKED` _int_ - Request locked for processing +- `FROZEN` _int_ - Order or position frozen +- `INVALID_FILL` _int_ - Invalid order filling type +- `CONNECTION` _int_ - No connection with the trade server +- `ONLY_REAL` _int_ - Operation is allowed only for live accounts +- `LIMIT_ORDERS` _int_ - The number of pending orders has reached the limit +- `LIMIT_VOLUME` _int_ - The volume of orders and positions for the symbol has reached the limit +- `INVALID_ORDER` _int_ - Incorrect or prohibited order type +- `POSITION_CLOSED` _int_ - Position with the specified POSITION_IDENTIFIER has already been closed +- `INVALID_CLOSE_VOLUME` _int_ - A close volume exceeds the current position volume + +- `CLOSE_ORDER_EXIST` _int_ - A close order already exists for a specified position. This may happen when working in + the hedging system: + · when attempting to close a position with an opposite one, while close orders for the position already exist + · when attempting to fully or partially close a position if the total volume of the already present close + orders and the newly placed one exceeds the current position volume + +- `LIMIT_POSITIONS` _int_ - The number of open positions simultaneously present on an account can be limited by the + server settings.After a limit is reached, the server returns the TRADE_RETCODE_LIMIT_POSITIONS error when + attempting to place an order. The limitation operates differently depending on the position accounting type: + · Netting — number of open positions is considered. When a limit is reached, the platform does not let + placing new orders whose execution may increase the number of open positions. In fact, the platform + allows placing orders only for the symbols that already have open positions. + The current pending orders are not considered since their execution may lead to changes in the current + positions but it cannot increase their number. + + · Hedging — pending orders are considered together with open positions, since a pending order activation + always leads to opening a new position. When a limit is reached, the platform does not allow placing + both new market orders for opening positions and pending orders. + +- `REJECT_CANCEL` _int_ - The pending order activation request is rejected, the order is canceled. +- `LONG_ONLY` _int_ - The request is rejected, because the "Only long positions are allowed" rule is set for the + symbol (POSITION_TYPE_BUY) +- `SHORT_ONLY` _int_ - The request is rejected, because the "Only short positions are allowed" rule is set for the + symbol (POSITION_TYPE_SELL) +- `CLOSE_ONLY` _int_ - The request is rejected, because the "Only position closing is allowed" rule is set for the + symbol +- `FIFO_CLOSE` _int_ - The request is rejected, because "Position closing is allowed only by FIFO rule" flag is set + for the trading account (ACCOUNT_FIFO_CLOSE=true) + + + +## AccountStopOutMode Objects + +```python +class AccountStopOutMode(Repr, IntEnum) +``` + +ACCOUNT_STOPOUT_MODE Enum. + +**Attributes**: + +- `PERCENT` _int_ - Account stop out mode in percents +- `MONEY` _int_ - Account stop out mode in money + + + +## AccountMarginMode Objects + +```python +class AccountMarginMode(Repr, IntEnum) +``` + +ACCOUNT_MARGIN_MODE Enum. + +**Attributes**: + +- `RETAIL_NETTING` _int_ - 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` _int_ - 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. + +- `HEDGING` _int_ - 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). + + + +# aiomql.core.errors + + + +## Error Objects + +```python +class Error() +``` + +Error class for handling errors from MetaTrader 5. + + + +# aiomql.core.exceptions + +Exceptions for the aiomql package. + + + +## LoginError Objects + +```python +class LoginError(Exception) +``` + +Raised when an error occurs when logging in. + + + +## VolumeError Objects + +```python +class VolumeError(Exception) +``` + +Raised when a volume is not valid or out of range for a symbol. + + + +## SymbolError Objects + +```python +class SymbolError(Exception) +``` + +Raised when a symbol is not provided where required or not available in the Market Watch. + + + +## OrderError Objects + +```python +class OrderError(Exception) +``` + +Raised when an error occurs when working with the order class. + + + +# aiomql.core.meta\_trader + + + +## MetaTrader Objects + +```python +class MetaTrader(metaclass=BaseMeta) +``` + + + +#### \_\_aenter\_\_ + +```python +async def __aenter__() -> 'MetaTrader' +``` + +Async context manager entry point. +Initializes the connection to the MetaTrader terminal. + +**Returns**: + +- `MetaTrader` - An instance of the MetaTrader class. + + + +#### \_\_aexit\_\_ + +```python +async def __aexit__(exc_type, exc_val, exc_tb) +``` + +Async context manager exit point. Closes the connection to the MetaTrader terminal. + + + +#### 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. + +**Arguments**: + +- `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. + + +**Returns**: + +- `bool` - True if successful, False otherwise. + + + +#### 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. + +**Arguments**: + +- `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_ - The timeout for the connection in seconds. +- `portable` _bool_ - If True, the terminal will be launched in portable mode. + + +**Returns**: + +- `bool` - True if successful, False otherwise. + + + +#### shutdown + +```python +async def shutdown() -> None +``` + +Closes the connection to the MetaTrader terminal. + +**Returns**: + +- `None` - None + + + +#### version + +```python +async def version() -> tuple[int, int, str] | None +``` + + + + + +#### account\_info + +```python +async def account_info() -> AccountInfo | None +``` + + + + + +#### 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 + +**Arguments**: + +- `symbol` _str_ - Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. + +- `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. + + +**Returns**: + +- `list[TradeOrder]` - A list of active trade orders as TradeOrder objects + + + +# aiomql.core.models + + + +## AccountInfo Objects + +```python +class AccountInfo(Base) +``` + +Account Information Class. + +**Attributes**: + +- `login` - int +- `password` - str +- `server` - str +- `trade_mode` - AccountTradeMode +- `balance` - float +- `leverage` - float +- `profit` - float +- `point` - float +- `amount` - float = 0 +- `equity` - float +- `credit` - float +- `margin` - float +- `margin_level` - float +- `margin_free` - float +- `margin_mode` - AccountMarginMode +- `margin_so_mode` - AccountStopoutMode +- `margin_so_call` - float +- `margin_so_so` - float +- `margin_initial` - float +- `margin_maintenance` - float +- `fifo_close` - bool +- `limit_orders` - float +- `currency` - str = "USD" +- `trade_allowed` - bool = True +- `trade_expert` - bool = True +- `currency_digits` - int +- `assets` - float +- `liabilities` - float +- `commission_blocked` - float +- `name` - str +- `company` - str + + + +## TerminalInfo Objects + +```python +class TerminalInfo(Base) +``` + +Terminal information class. Holds information about the terminal. + +**Attributes**: + +- `community_account` - bool +- `community_connection` - bool +- `connected` - bool +- `dlls_allowed` - bool +- `trade_allowed` - bool +- `tradeapi_disabled` - bool +- `email_enabled` - bool +- `ftp_enabled` - bool +- `notifications_enabled` - bool +- `mqid` - bool +- `build` - int +- `maxbars` - int +- `codepage` - int +- `ping_last` - int +- `community_balance` - float +- `retransmission` - float +- `company` - str +- `name` - str +- `language` - str +- `path` - str +- `data_path` - str +- `commondata_path` - str + + + +## SymbolInfo Objects + +```python +class SymbolInfo(Base) +``` + +Symbol Information Class. Symbols are financial instruments available for trading in the MetaTrader 5 terminal. + +**Attributes**: + +- `name` - str +- `custom` - bool +- `chart_mode` - SymbolChartMode +- `select` - bool +- `visible` - bool +- `session_deals` - int +- `session_buy_orders` - int +- `session_sell_orders` - int +- `volume` - float +- `volumehigh` - float +- `volumelow` - float +- `time` - int +- `digits` - int +- `spread` - float +- `spread_float` - bool +- `ticks_bookdepth` - int +- `trade_calc_mode` - SymbolCalcMode +- `trade_mode` - SymbolTradeMode +- `start_time` - int +- `expiration_time` - int +- `trade_stops_level` - int +- `trade_freeze_level` - int +- `trade_exemode` - SymbolTradeExecution +- `swap_mode` - SymbolSwapMode +- `swap_rollover3days` - DayOfWeek +- `margin_hedged_use_leg` - bool +- `expiration_mode` - int +- `filling_mode` - int +- `order_mode` - int +- `order_gtc_mode` - SymbolOrderGTCMode +- `option_mode` - SymbolOptionMode +- `option_right` - SymbolOptionRight +- `bid` - float +- `bidhigh` - float +- `bidlow` - float +- `ask` - float +- `askhigh` - float +- `asklow` - float +- `last` - float +- `lasthigh` - float +- `lastlow` - float +- `volume_real` - float +- `volumehigh_real` - float +- `volumelow_real` - float +- `option_strike` - float +- `point` - float +- `trade_tick_value` - float +- `trade_tick_value_profit` - float +- `trade_tick_value_loss` - float +- `trade_tick_size` - float +- `trade_contract_size` - float +- `trade_accrued_interest` - float +- `trade_face_value` - float +- `trade_liquidity_rate` - float +- `volume_min` - float +- `volume_max` - float +- `volume_step` - float +- `volume_limit` - float +- `swap_long` - float +- `swap_short` - float +- `margin_initial` - float +- `margin_maintenance` - float +- `session_volume` - float +- `session_turnover` - float +- `session_interest` - float +- `session_buy_orders_volume` - float +- `session_sell_orders_volume` - float +- `session_open` - float +- `session_close` - float +- `session_aw` - float +- `session_price_settlement` - float +- `session_price_limit_min` - float +- `session_price_limit_max` - float +- `margin_hedged` - float +- `price_change` - float +- `price_volatility` - float +- `price_theoretical` - float +- `price_greeks_delta` - float +- `price_greeks_theta` - float +- `price_greeks_gamma` - float +- `price_greeks_vega` - float +- `price_greeks_rho` - float +- `price_greeks_omega` - float +- `price_sensitivity` - float +- `basis` - str +- `category` - str +- `currency_base` - str +- `currency_profit` - str +- `currency_margin` - Any +- `bank` - str +- `description` - str +- `exchange` - str +- `formula` - Any +- `isin` - Any +- `name` - str +- `page` - str +- `path` - str + + + +## BookInfo Objects + +```python +class BookInfo(Base) +``` + +Book Information Class. + +**Attributes**: + +- `type` - BookType +- `price` - float +- `volume` - float +- `volume_dbl` - float + + + +## TradeOrder Objects + +```python +class TradeOrder(Base) +``` + +Trade Order Class. + +**Attributes**: + +- `ticket` - int +- `time_setup` - int +- `time_setup_msc` - int +- `time_expiration` - int +- `time_done` - int +- `time_done_msc` - int +- `type` - OrderType +- `type_time` - OrderTime +- `type_filling` - OrderFilling +- `state` - int +- `magic` - int +- `position_id` - int +- `position_by_id` - int +- `reason` - OrderReason +- `volume_current` - float +- `volume_initial` - float +- `price_open` - float +- `sl` - float +- `tp` - float +- `price_current` - float +- `price_stoplimit` - float +- `symbol` - str +- `comment` - str +- `external_id` - str + + + +## TradeRequest Objects + +```python +class TradeRequest(Base) +``` + +Trade Request Class. + +**Attributes**: + +- `action` - TradeAction +- `type` - OrderType +- `order` - int +- `symbol` - str +- `volume` - float +- `sl` - float +- `tp` - float +- `price` - float +- `deviation` - float +- `stop_limit` - float +- `type_time` - OrderTime +- `type_filling` - OrderFilling +- `expiration` - int +- `position` - int +- `position_by` - int +- `comment` - str +- `magic` - int +- `deviation` - int +- `comment` - str + + + +## OrderCheckResult Objects + +```python +class OrderCheckResult(Base) +``` + +Order Check Result + +**Attributes**: + +- `retcode` - int +- `balance` - float +- `equity` - float +- `profit` - float +- `margin` - float +- `margin_free` - float +- `margin_level` - float +- `comment` - str +- `request` - TradeRequest + + + +## OrderSendResult Objects + +```python +class OrderSendResult(Base) +``` + +Order Send Result + +**Attributes**: + +- `retcode` - int +- `deal` - int +- `order` - int +- `volume` - float +- `price` - float +- `bid` - float +- `ask` - float +- `comment` - str +- `request` - TradeRequest +- `request_id` - int +- `retcode_external` - int +- `profit` - float + + + +## TradePosition Objects + +```python +class TradePosition(Base) +``` + +Trade Position + +**Attributes**: + +- `ticket` - int +- `time` - int +- `time_msc` - int +- `time_update` - int +- `time_update_msc` - int +- `type` - OrderType +- `magic` - float +- `identifier` - int +- `reason` - PositionReason +- `volume` - float +- `price_open` - float +- `sl` - float +- `tp` - float +- `price_current` - float +- `swap` - float +- `profit` - float +- `symbol` - str +- `comment` - str +- `external_id` - str + + + +## TradeDeal Objects + +```python +class TradeDeal(Base) +``` + +Trade Deal + +**Attributes**: + +- `ticket` - int +- `order` - int +- `time` - int +- `time_msc` - int +- `type` - DealType +- `entry` - DealEntry +- `magic` - int +- `position_id` - int +- `reason` - DealReason +- `volume` - float +- `price` - float +- `commission` - float +- `swap` - float +- `profit` - float +- `fee` - float +- `sl` - float +- `tp` - float +- `symbol` - str +- `comment` - str +- `external_id` - str + + + +# aiomql.core + + + +# aiomql.executor + + + +## Executor Objects + +```python +class Executor() +``` + +Executor class for running multiple strategies on multiple symbols concurrently. + +**Attributes**: + +- `executor` _ThreadPoolExecutor_ - The executor object. +- `workers` _list_ - List of strategies. + + + +#### add\_workers + +```python +def add_workers(strategies: Sequence[type(Strategy)]) +``` + +Add multiple strategies at once + +**Arguments**: + +- `strategies` _Sequence[Strategy]_ - A sequence of strategies. + + + +#### remove\_workers + +```python +def remove_workers(*symbols: Sequence[Symbol]) +``` + +Removes any worker running on a symbol not successfully initialized. + +**Arguments**: + +- `*symbols` - Successfully initialized symbols. + + + +#### add\_worker + +```python +def add_worker(strategy: type(Strategy)) +``` + +Add a strategy instance to the list of workers + +**Arguments**: + +- `strategy` _Strategy_ - A strategy object + + + +#### run + +```python +@staticmethod +def run(strategy: type(Strategy)) +``` + +Wraps the coroutine trade method of each strategy with 'asyncio.run'. + +**Arguments**: + +- `strategy` _Strategy_ - A strategy object + + + +#### execute + +```python +async def execute(workers: int = 0) +``` + +Run the strategies with a threadpool executor. + +**Arguments**: + +- `workers` - Number of workers to use in executor pool. Defaults to zero which uses all workers. + + +**Notes**: + + No matter the number specified, the executor will always use a minimum of 5 workers. + + + +# aiomql.history + + + +## History Objects + +```python +class History() +``` + +The history class handles completed trade deals and trade orders in the trading history of an account. + +**Attributes**: + +- `deals` _list[TradeDeal]_ - Iterable of trade deals +- `orders` _list[TradeOrder]_ - Iterable of trade orders +- `total_deals` - Total number of deals +- `total_orders` _int_ - Total number orders +- `group` _str_ - Filter for selecting history by symbols. +- `ticket` _int_ - Filter for selecting history by ticket number +- `position` _int_ - Filter for selecting history deals by position +- `initialized` _bool_ - check if initial request has been sent to the terminal to get history. +- `mt5` _MetaTrader_ - MetaTrader instance +- `config` _Config_ - Config instance + + + +#### \_\_init\_\_ + +```python +def __init__(*, + date_from: datetime | float = 0, + date_to: datetime | float = 0, + group: str = "", + ticket: int = 0, + position: int = 0) +``` + +**Arguments**: + +- `date_from` _datetime, float_ - Date the orders are requested from. Set by the 'datetime' object or as a + number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' + +- `date_to` _datetime, float_ - Date up to which the orders are requested. Set by the 'datetime' object or as a + number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" + +- `group` _str_ - Filter for selecting history by symbols. +- `ticket` _int_ - Filter for selecting history by ticket number +- `position` _int_ - Filter for selecting history deals by position + + + +#### init + +```python +async def init(deals=True, orders=True) -> bool +``` + +Get history deals and orders + +**Arguments**: + +- `deals` _bool_ - If true get history deals during initial request to terminal +- `orders` _bool_ - If true get history orders during initial request to terminal + + +**Returns**: + +- `bool` - True if all requests were successful else False + + + +#### get\_deals + +```python +async def get_deals() -> list[TradeDeal] +``` + +Get deals from trading history using the parameters set in the constructor. + +**Returns**: + +- `list[TradeDeal]` - A list of trade deals + + + +#### deals\_total + +```python +async def deals_total() -> int +``` + +Get total number of deals within the specified period in the constructor. + +**Returns**: + +- `int` - Total number of Deals + + + +#### get\_orders + +```python +async def get_orders() -> list[TradeOrder] +``` + +Get orders from trading history using the parameters set in the constructor. + +**Returns**: + +- `list[TradeOrder]` - A list of trade orders + + + +#### orders\_total + +```python +async def orders_total() -> int +``` + +Get total number of orders within the specified period in the constructor. + +**Returns**: + +- `int` - Total number of orders + + + +# aiomql.lib.strategies.finger\_trap + + + +## Entry Objects + +```python +@dataclass +class Entry() +``` + +Entry class for FingerTrap strategy.Will be used to store entry conditions and other entry related data. + +**Attributes**: + +- `bearish` _bool_ - True if the market is bearish +- `bullish` _bool_ - True if the market is bullish +- `ranging` _bool_ - True if the market is ranging +- `snooze` _float_ - Time to wait before checking for entry conditions +- `trend` _str_ - The current trend of the market +- `last_candle` _Candle_ - The last candle of the market +- `new` _bool_ - True if the last candle is new +- `order_type` _OrderType_ - The type of order to place +- `pips` _int_ - The number of pips to place the order from the current price + + + +# aiomql.lib.strategies + + + +# aiomql.lib.symbols.forex\_symbol + + + +## ForexSymbol Objects + +```python +class ForexSymbol(Symbol) +``` + +Subclass of Symbol for Forex Symbols. Handles the conversion of currency and the computation of stop loss, +take profit and volume. + + + +#### pip + +```python +@property +def pip() +``` + +Returns the pip value of the symbol. This is ten times the point value for forex symbols. + +**Returns**: + +- `float` - The pip value of the symbol. + + + +#### compute\_volume + +```python +async def compute_volume(*, + amount: float, + pips: float, + use_minimum: bool = True) -> float +``` + +Compute volume given an amount to risk and target pips. Round the computed volume to the nearest step. + +**Arguments**: + +- `amount` _float_ - Amount to risk. Given in terms of the account currency. +- `pips` _float_ - Target pips. + + +**Arguments**: + +- `use_minimum` _bool_ - If True, the minimum volume is returned if the computed volume is less than the minimum volume. + + +**Returns**: + +- `float` - volume + + +**Raises**: + +- `VolumeError` - If the computed volume is less than the minimum volume or greater than the maximum volume. + + + +# aiomql.lib.symbols + + + +# aiomql.lib.traders.simple\_deal\_trader + + + +## DealTrader Objects + +```python +class DealTrader(Trader) +``` + +A base class for placing trades based on the number of pips to target + + + +#### create\_order + +```python +async def create_order(*, order_type: OrderType, pips: float = 0) +``` + +Using the number of target pips it determines the lot size, stop loss and take profit for the order, +and updates the order object with the values. + +**Arguments**: + +- `order_type` _OrderType_ - Type of order +- `pips` _float_ - Target pips + + + +# aiomql.lib.traders + + + +# aiomql.lib + + + +# aiomql.order + +Order Class + + + +## Order Objects + +```python +class Order(TradeRequest) +``` + +Trade order related functions and properties. Subclass of TradeRequest. + + + +#### \_\_init\_\_ + +```python +def __init__(**kwargs) +``` + +Initialize the order object with keyword arguments, symbol must be provided. +Provide default values for action, type_time and type_filling if not provided. + +**Arguments**: + +- `**kwargs` - Keyword arguments must match the attributes of TradeRequest as well as the attributes of + Order class as specified in the annotations in the class definition. + + Default Values: +- `action` _TradeAction.DEAL_ - Trade action +- `type_time` _OrderTime.DAY_ - Order time +- `type_filling` _OrderFilling.FOK_ - Order filling + + +**Raises**: + +- `SymbolError` - If symbol is not provided + + + +#### orders\_total + +```python +async def orders_total() +``` + +Get the number of active orders. + +**Returns**: + +- `(int)` - total number of active orders + + + +#### orders + +```python +async def orders() -> tuple[TradeOrder] +``` + +Get the list of active orders for the current symbol. + +**Returns**: + +- `tuple[TradeOrder]` - A Tuple of active trade orders as TradeOrder objects + + + +#### check + +```python +async def check() -> OrderCheckResult +``` + +Check funds sufficiency for performing a required trading operation and the possibility to execute it at + +**Returns**: + +- `OrderCheckResult` - An OrderCheckResult object + + +**Raises**: + +- `OrderError` - If not successful + + + +#### send + +```python +async def send() -> OrderSendResult +``` + +Send a request to perform a trading operation from the terminal to the trade server. + +**Returns**: + +- `OrderSendResult` - An OrderSendResult object + + +**Raises**: + +- `OrderError` - If not successful + + + +#### calc\_margin + +```python +async def calc_margin() -> float +``` + +Return the required margin in the account currency to perform a specified trading operation. + +**Returns**: + +- `float` - Returns float value if successful + + +**Raises**: + +- `OrderError` - If not successful + + + +#### calc\_profit + +```python +async def calc_profit() -> float +``` + +Return profit in the account currency for a specified trading operation. + +**Returns**: + +- `float` - Returns float value if successful + + +**Raises**: + +- `OrderError` - If not successful + + + +# aiomql.positions + +Handle Open positions. + + + +## Positions Objects + +```python +class Positions() +``` + +Get Open Positions. + +**Attributes**: + +- `symbol` _str_ - Financial instrument name. +- `group` _str_ - The filter for arranging a group of necessary symbols. Optional named parameter. + If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. +- `ticket` _int_ - Position ticket. +- `mt5` _MetaTrader_ - MetaTrader instance. + + + +#### \_\_init\_\_ + +```python +def __init__(*, symbol: str = "", group: str = "", ticket: int = 0) +``` + +Get Open Positions. + +**Arguments**: + +- `symbol` _str_ - Financial instrument name. +- `group` _str_ - The filter for arranging a group of necessary symbols. Optional named parameter. If the group + is specified, the function returns only positions meeting a specified criteria for a symbol name. +- `ticket` _int_ - Position ticket + + + +#### positions\_total + +```python +async def positions_total() -> int +``` + +Get the number of open positions. + +**Returns**: + +- `int` - Return total number of open positions + + + +#### positions\_get + +```python +async def positions_get() +``` + +Get open positions with the ability to filter by symbol or ticket. + +**Returns**: + +- `list[TradePosition]` - A list of open trade positions + + + +#### close\_all + +```python +async def close_all() -> int +``` + +Close all open positions for the trading account. + +**Returns**: + +- `int` - Return number of positions closed. + + + +# aiomql.ram + +Risk Assessment and Management + + + +## RAM Objects + +```python +class RAM() +``` + + + +#### \_\_init\_\_ + +```python +def __init__(**kwargs) +``` + +Risk Assessment and Management. All provided keyword arguments are set as attributes. + +**Arguments**: + +- `kwargs` _Dict_ - Keyword arguments. + + Defaults: +- `risk_to_reward` _float_ - Risk to reward ratio 1 +- `risk` _float_ - Percentage of account balance to risk per trade 0.01 # 1% +- `amount` _float_ - Amount to risk per trade in terms of account currency 0 +- `pips` _float_ - Target pips 0 +- `volume` _float_ - Volume to trade 0 + + + +#### get\_amount + +```python +async def get_amount(risk: float = 0) -> float +``` + +Calculate the amount to risk per trade as a percentage of free margin. + +**Arguments**: + +- `risk` _float_ - Percentage of account balance to risk per trade. Defaults to zero. + + +**Returns**: + +- `float` - Amount to risk per trade + + + +#### get\_volume + +```python +async def get_volume(*, + symbol: Symbol, + pips: float = 0, + amount: float = 0) -> float +``` + +Calculate the volume to trade. if pips is not provided, the pips attribute is used. +If the amount attribute or amount argument is zero, the amount is calculated using the get_amount method based on the risk. + +**Arguments**: + +- `symbol` _Symbol_ - Financial instrument + + +**Arguments**: + +- `pips` _float_ - Target pips. Defaults to zero. +- `amount` _float_ - Amount to risk per trade. Defaults to zero. + + +**Returns**: + +- `float` - Volume to trade + + + +# aiomql.records + +This module contains the Records class, which is used to read and update trade records from csv files. + + + +## Records Objects + +```python +class Records() +``` + +This utility class read trade records from csv files, and update them based on their closing positions. + +**Attributes**: + +- `config` - Config object +- `records_dir(Path)` - Path to directory containing record of placed trades, If not given takes the default + from the config + + + +#### \_\_init\_\_ + +```python +def __init__(records_dir: Path = '') +``` + +Initialize the Records class. + +**Arguments**: + +- `records_dir` _Path_ - Path to directory containing record of placed trades. + + + +#### get\_records + +```python +async def get_records() +``` + +Get trade records from records_dir folder + +**Yields**: + +- `files` - Trade record files + + + +#### read\_update + +```python +async def read_update(file: Path) +``` + +Read and update trade records + +**Arguments**: + +- `file` - Trade record file + + + +#### update\_rows + +```python +async def update_rows(rows: list[dict]) -> list[dict] +``` + +Update the rows of entered trades in the csv file with the actual profit. + +**Arguments**: + +- `rows` - A list of dictionaries from the dictionary writer object of the csv file. + + +**Returns**: + +- `list[dict]` - A list of dictionaries with the actual profit and win status. + + + +#### update\_records + +```python +async def update_records() +``` + +Update trade records in the records_dir folder. + + + +#### update\_record + +```python +async def update_record(file: Path | str) +``` + +Update a single trade record file. + + + +# aiomql.result + + + +## Result Objects + +```python +class Result() +``` + +A base class for handling trade results and strategy parameters for record keeping and reference purpose. +The data property must be implemented in the subclass + +**Attributes**: + +- `config` _Config_ - The configuration object +- `name` - Any desired name for the result file object + + + +#### \_\_init\_\_ + +```python +def __init__(result: OrderSendResult, parameters: dict = None, name: str = '') +``` + +Prepare result data + +**Arguments**: + + result: + parameters: + name: + + + +#### to\_csv + +```python +async def to_csv() +``` + +Record trade results and associated parameters as a csv file + + + +#### save\_csv + +```python +async def save_csv() +``` + +Save trade results and associated parameters as a csv file in a separate thread + + + +# aiomql.strategy + +The base class for creating strategies. + + + +## Strategy Objects + +```python +class Strategy(ABC) +``` + +The base class for creating strategies. + +**Attributes**: + +- `symbol` _Symbol_ - The Financial Instrument as a Symbol Object +- `parameters` _Dict_ - A dictionary of parameters for the strategy. + + Class Attributes: +- `name` _str_ - A name for the strategy. +- `account` _Account_ - Account instance. +- `mt5` _MetaTrader_ - MetaTrader instance. +- `config` _Config_ - Config instance. + + +**Notes**: + + Define the name of a strategy as a class attribute. If not provided, the class name will be used as the name. + + + +#### \_\_init\_\_ + +```python +def __init__(*, symbol: Symbol, params: dict = None) +``` + +Initiate the parameters dict and add name and symbol fields. +Use class name as strategy name if name is not provided + +**Arguments**: + +- `symbol` _Symbol_ - The Financial instrument +- `params` _Dict_ - Trading strategy parameters + + + +#### sleep + +```python +@staticmethod +async def sleep(secs: float) +``` + +Sleep for the needed amount of seconds in between requests to the terminal. +computes the accurate amount of time needed to sleep ensuring that the next request is made at the start of +a new bar and making cooperative multitasking possible. + +**Arguments**: + +- `secs` _float_ - The time in seconds. Usually the timeframe you are trading on. + + + +#### trade + +```python +@abstractmethod +async def trade() +``` + +Place trades using this method. This is the main method of the strategy. +It will be called by the strategy runner. + + + +# aiomql.symbol + +Symbol class for handling a financial instrument. + + + +## Symbol Objects + +```python +class Symbol(SymbolInfo) +``` + +Main class for handling a financial instrument. A subclass of SymbolInfo and Base it has attributes and methods +for working with a financial instrument. + +**Attributes**: + +- `tick` _Tick_ - Price tick object for instrument +- `account` - An instance of the current trading account + + +**Notes**: + + Full properties are on the SymbolInfo Object. + Make sure Symbol is always initialized with a name argument + + + +#### pip + +```python +@property +def pip() +``` + +Returns the pip value of the symbol. This is ten times the point value for forex symbols. + +**Returns**: + +- `float` - The pip value of the symbol. + + + +#### info\_tick + +```python +async def info_tick(*, name: str = "") -> Tick +``` + +Get the current price tick of a financial instrument. + +**Arguments**: + +- `name` - if name is supplied get price tick of that financial instrument + + +**Returns**: + +- `Tick` - Return a Tick Object + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### symbol\_select + +```python +async def symbol_select(*, enable: bool = True) -> bool +``` + +Select a symbol in the MarketWatch window or remove a symbol from the window. +Update the select property + +**Arguments**: + +- `enable` _bool_ - Switch. Optional unnamed parameter. If 'false', a symbol should be removed from + the MarketWatch window. + + +**Returns**: + +- `bool` - True if successful, otherwise – False. + + + +#### info + +```python +async def info() -> SymbolInfo +``` + +Get data on the specified financial instrument and update the symbol object properties + +**Returns**: + +- `(SymbolInfo)` - SymbolInfo if successful + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### init + +```python +async def init() -> bool +``` + +Initialized the symbol by pulling properties from the terminal + +**Returns**: + +- `bool` - Returns True if symbol info was successful initialized + + + +#### book\_add + +```python +async def book_add() -> bool +``` + +Subscribes the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. +If the symbol is not in the list of instruments for the market, This method will return False + +**Returns**: + +- `bool` - True if successful, otherwise – False. + + + +#### book\_get + +```python +async def book_get() -> tuple[BookInfo] +``` + +Returns a tuple of BookInfo featuring Market Depth entries for the specified symbol. + +**Returns**: + +- `tuple[BookInfo]` - Returns the Market Depth contents as a tuples of BookInfo Objects + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### book\_release + +```python +async def book_release() -> bool +``` + +Cancels subscription of the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. + +**Returns**: + +- `bool` - True if successful, otherwise – False. + + + +#### compute\_volume + +```python +async def compute_volume(*, + amount: float, + pips: float, + use_minimum: bool = True) -> float +``` + +Computes the volume of a trade based on the amount and the number of pips to target. +This is a dummy method that returns the minimum volume of the symbol. It is meant to be overridden by a subclass +Checkout Forex Symbol implementation in srciomql\lib\ForexSymbol.py + +**Arguments**: + +- `amount` _float_ - Amount to risk in the trade +- `pips` _float_ - Number of pips to target + + +**Arguments**: + +- `use_minimum` _bool_ - If True, the minimum volume is returned if the computed volume is less than the minimum volume. + + +**Returns**: + +- `float` - Returns the volume of the trade + + + +#### currency\_conversion + +```python +async def currency_conversion(*, amount: float, base: str, + quote: str) -> float +``` + +Convert from one currency to the other. + +**Arguments**: + +- `amount` - amount to convert given in terms of the quote currency +- `base` - The base currency of the pair +- `quote` - The quote currency of the pair + + +**Returns**: + +- `float` - Amount in terms of the base currency or None if it failed to convert + + +**Raises**: + +- `ValueError` - If conversion is impossible + + + +#### copy\_rates\_from + +```python +async def copy_rates_from(*, + timeframe: TimeFrame, + date_from: datetime | int, + count: int = 500) -> Candles +``` + +Get bars from the MetaTrader 5 terminal starting from the specified date. + +**Arguments**: + +- `timeframe` _TimeFrame_ - Timeframe the bars are requested for. Set by a value from the TimeFrame enumeration. Required unnamed parameter. + +- `date_from` _datetime | int_ - Date of opening of the first bar from the requested sample. Set by the 'datetime' object or as a number + of seconds elapsed since 1970.01.01. Required unnamed parameter. + +- `count` _int_ - Number of bars to receive. Required unnamed parameter. + + +**Returns**: + +- `Candles` - Returns a Candles object as a collection of rates ordered chronologically + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### copy\_rates\_from\_pos + +```python +async def copy_rates_from_pos(*, + timeframe: TimeFrame, + count: int = 500, + start_position: int = 0) -> Candles +``` + +Get bars from the MetaTrader 5 terminal starting from the specified index. + +**Arguments**: + +- `timeframe` _TimeFrame_ - TimeFrame value from TimeFrame Enum. Required keyword only parameter + +- `count` _int_ - Number of bars to return. Keyword argument defaults to 500 + +- `start_position` _int_ - Initial index of the bar the data are requested from. The numbering of bars goes from + present to past. Thus, the zero bar means the current one. Keyword argument defaults to 0. + + +**Returns**: + +- `Candles` - Returns a Candles object as a collection of rates ordered chronologically. + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### copy\_rates\_range + +```python +async def copy_rates_range(*, timeframe: TimeFrame, date_from: datetime | int, + date_to: datetime | int) -> Candles +``` + +Get bars in the specified date range from the MetaTrader 5 terminal. + +**Arguments**: + +- `timeframe` _TimeFrame_ - Timeframe for the bars using the TimeFrame enumeration. Required unnamed parameter. + +- `date_from` _datetime | int_ - Date the bars are requested from. Set by the 'datetime' object or as a number of seconds + elapsed since 1970.01.01. Bars with the open time >= date_from are returned. Required unnamed parameter. + +- `date_to` _datetime | int_ - Date, up to which the bars are requested. Set by the 'datetime' object or as a number of + seconds elapsed since 1970.01.01. Bars with the open time <= date_to are returned. Required unnamed parameter. + + +**Returns**: + +- `Candles` - Returns a Candles object as a collection of rates ordered chronologically. + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### copy\_ticks\_from + +```python +async def copy_ticks_from(*, + date_from: datetime | int, + count: int = 100, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` + +Get ticks from the MetaTrader 5 terminal starting from the specified date. + +Args: date_from (datetime | int): Date the ticks are requested from. Set by the 'datetime' object or as a +number of seconds elapsed since 1970.01.01. + +count (int): Number of requested ticks. Defaults to 100 + +flags (CopyTicks): A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default + +**Returns**: + +- `Candles` - Returns a Candles object as a collection of ticks ordered chronologically. + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned + + + +#### copy\_ticks\_range + +```python +async def copy_ticks_range(*, + date_from: datetime | int, + date_to: datetime | int, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` + +Get ticks for the specified date range from the MetaTrader 5 terminal. + +**Arguments**: + +- `date_from` - Date the bars are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with + the open time >= date_from are returned. Required unnamed parameter. + +- `date_to` - Date, up to which the bars are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars + with the open time <= date_to are returned. Required unnamed parameter. + + flags (CopyTicks): + + +**Returns**: + +- `Candles` - Returns a Candles object as a collection of ticks ordered chronologically. + + +**Raises**: + +- `ValueError` - If request was unsuccessful and None was returned. + + + +# aiomql.terminal + +Terminal related functions and properties + + + +## Terminal Objects + +```python +class Terminal(TerminalInfo) +``` + +Terminal Class. Get information about the MetaTrader 5 terminal. The class is a subclass of the TerminalInfo +class. It inherits all the attributes and methods of the TerminalInfo class and adds some useful methods. + +**Notes**: + + Other attributes are defined in the TerminalInfo Class + + + +#### initialize + +```python +async def initialize() -> bool +``` + +Establish a connection with the MetaTrader 5 terminal. There are three call options. Call without parameters. +The terminal for connection is found automatically. Call specifying the path to the MetaTrader 5 terminal we +want to connect to. word path as a keyword argument Call specifying the trading account path and parameters +i.e login, password, server, as keyword arguments, path can be omitted. + +**Returns**: + +- `bool` - True if successful else False + + + +#### version + +```python +async def version() +``` + +Get the MetaTrader 5 terminal version. This method returns the terminal version, build and release date as +a tuple of three values + +**Returns**: + +- `Version` - version of tuple as Version object + + +**Raises**: + +- `ValueError` - If the terminal version cannot be obtained + + + +#### info + +```python +async def info() +``` + +Get the connected MetaTrader 5 client terminal status and settings. gets terminal info in the form of a +named tuple structure (namedtuple). Return None in case of an error. The info on the error can be +obtained using last_error(). + +**Returns**: + +- `Terminal` - Terminal status and settings as a terminal object. + + + +#### symbols\_total + +```python +async def symbols_total() -> int +``` + +Get the number of all financial instruments in the MetaTrader 5 terminal. + +**Returns**: + +- `int` - Total number of available symbols + + + +# aiomql.ticks + +Module for working with price ticks. + + + +## Tick Objects + +```python +class Tick() +``` + +Price Tick of a Financial Instrument. + +**Attributes**: + +- `time` _int_ - Time of the last prices update for the symbol +- `bid` _float_ - Current Bid price +- `ask` _float_ - Current Ask price +- `last` _float_ - Price of the last deal (Last) +- `volume` _float_ - Volume for the current Last price +- `time_msc` _int_ - Time of the last prices update for the symbol in milliseconds +- `flags` _TickFlag_ - Tick flags +- `volume_real` _float_ - Volume for the current Last price +- `Index` _int_ - Custom attribute representing the position of the tick in a sequence. + + + +#### set\_attributes + +```python +def set_attributes(**kwargs) +``` + +Set attributes from keyword arguments + + + +## Ticks Objects + +```python +class Ticks() +``` + +Container data class for price ticks. Arrange in chronological order. +Supports iteration, slicing and assignment + +**Arguments**: + +- `data` _DataFrame | tuple[tuple]_ - Dataframe of price ticks or a tuple of tuples + + +**Arguments**: + +- `flip` _bool_ - If flip is True reverse data chronological order. + + +**Attributes**: + +- `data` - Dataframe Object holding the ticks + + + +#### \_\_init\_\_ + +```python +def __init__(*, data: DataFrame | Iterable, flip=False) +``` + +Initialize the Ticks class. Creates a DataFrame of price ticks from the data argument. + +**Arguments**: + +- `data` _DataFrame | Iterable_ - Dataframe of price ticks or any iterable object that can be converted to a + pandas DataFrame +- `flip` _bool_ - If flip is True reverse data chronological order. + + + +#### ta + +```python +@property +def ta() +``` + +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. + +**Returns**: + +- `pandas_ta` - The pandas_ta library + + + +#### ta\_lib + +```python +@property +def ta_lib() +``` + +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. + +**Returns**: + +- `ta` - The ta library + + + +#### data + +```python +@property +def data() -> DataFrame +``` + +DataFrame of price ticks arranged in chronological order. + + + +#### rename + +```python +def rename(inplace=True, **kwargs) -> _Ticks | None +``` + +Rename columns of the candle class. + +**Arguments**: + +- `inplace` _bool_ - Rename the columns inplace or return a new instance of the class with the renamed columns +- `**kwargs` - The new names of the columns + + +**Returns**: + +- `Ticks` - A new instance of the class with the renamed columns if inplace is False. +- `None` - If inplace is True + + + +# aiomql.trader + +Trader class module. Handles the creation of an order and the placing of trades + + + +## Trader Objects + +```python +class Trader() +``` + +Base class for creating a Trader object. Handles the creation of an order and the placing of trades + +**Attributes**: + +- `symbol` _Symbol_ - Financial instrument class Symbol class or any subclass of it. +- `ram` _RAM_ - RAM instance +- `order` _Order_ - Trade order + + Class Attributes: +- `name` _str_ - A name for the strategy. +- `account` _Account_ - Account instance. +- `mt5` _MetaTrader_ - MetaTrader instance. +- `config` _Config_ - Config instance. + + + +#### \_\_init\_\_ + +```python +def __init__(*, symbol: Symbol, ram: RAM = None) +``` + +Initializes the order object and RAM instance + +**Arguments**: + +- `symbol` _Symbol_ - Financial instrument +- `ram` _RAM_ - Risk Assessment and Management instance + + + +#### create\_order + +```python +async def create_order(*, order_type: OrderType, **kwargs) +``` + +Complete the order object with the required values. Creates a simple order. +Uses the ram instance to set the volume. + +**Arguments**: + +- `order_type` _OrderType_ - Type of order +- `kwargs` - keyword arguments as required for the specific trader + + + +#### set\_order\_limits + +```python +async def set_order_limits(pips: float) +``` + +Sets the stop loss and take profit for the order. +This method uses pips as defined for forex instruments. + +**Arguments**: + +- `pips` - Target pips + + + +#### place\_trade + +```python +async def place_trade(order_type: OrderType, params: dict = None, **kwargs) +``` + +Places a trade based on the order_type. + +**Arguments**: + +- `order_type` _OrderType_ - Type of order +- `params` - parameters to be saved with the trade +- `kwargs` - keyword arguments as required for the specific trader + + + +# aiomql.utils + +Utility functions for aiomql. + + + +#### dict\_to\_string + +```python +def dict_to_string(data: dict, multi=False) -> str +``` + +Convert a dict to a string. Use for logging. + +**Arguments**: + +- `data` _dict_ - The dict to convert. +- `multi` _bool, optional_ - If True, each key-value pair will be on a new line. Defaults to False. + + +**Returns**: + +- `str` - The string representation of the dict. + diff --git a/docs/order.md b/docs/order.md new file mode 100644 index 0000000..0453d78 --- /dev/null +++ b/docs/order.md @@ -0,0 +1,115 @@ +## Order + + +```python +class Order(TradeRequest) +``` +Trade order related functions and properties. Subclass of [TradeRequest](#traderequest). + +### \_\_init\_\_ +```python +def __init__(**kwargs) +``` +Initialize the order object with keyword arguments, symbol must be provided. +Provides default values for action, type_time and type_filling if not provided. +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**symbol**| **str** \| **Symbol** | Symbol name. Required keyword argument | | +|**action**| **TradeAction** | Trade action | TradeAction.DEAL | +|**type_time**| **OrderTime** | Order time | OrderTime.DAY | +|**type_filling**| **OrderFilling** | Order filling | OrderFilling.FOK | +#### Raises: + +|Exception|Description| +|---|---| +|**SymbolError**|If symbol is not provided| + +### orders_total +```python +async def orders_total() +``` +Get the number of active orders. + +#### Returns: +|Type|Description| +|---|---| +|**int**|total number of active orders| + +### orders +```python +async def orders() -> tuple[TradeOrder] +``` +Get the list of active orders for the current symbol. + +#### Returns: +|Type|Description| +|---|---| +|**tuple[TradeOrder]**|A Tuple of active trade orders as TradeOrder objects| + +### check +```python +async def check() -> OrderCheckResult +``` +Check funds sufficiency for performing a required trading operation and the possibility to execute it at + +#### Returns:: + +|Type|Description| +|---|---| +|**OrderCheckResult**|An OrderCheckResult object| + +#### Raises: + +|Exception|Description| +|---|---| +|**OrderError**|If not successful| +- `OrderError` - If not successful + +#### send + +```python +async def send() -> OrderSendResult +``` +Send a request to perform a trading operation from the terminal to the trade server. + +#### Returns: +|Type|Description| +|---|---| +|**OrderSendResult**|An OrderSendResult object| + +#### Raises: +|Exception|Description| +|---|---| +|**OrderError**|If not successful| + +### calc_margin +```python +async def calc_margin() -> float +``` +Return the required margin in the account currency to perform a specified trading operation. +#### Returns: +|Type|Description| +|---|---| +|**float**|Returns float value if successful| + +#### Raises: +|Exception|Description| +|---|---| +|**OrderError**|If not successful| + + +### calc_profit +```python +async def calc_profit() -> float +``` +Return profit in the account currency for a specified trading operation. +#### Returns: +|Type|Description| +|---|---| +|**float**|Returns float value if successful| +#### Raises: +|Exception|Description| +|---|---| +|**OrderError**|If not successful| + diff --git a/docs/positions.md b/docs/positions.md new file mode 100644 index 0000000..dcbd868 --- /dev/null +++ b/docs/positions.md @@ -0,0 +1,72 @@ +## Positions + +```python +class Positions +``` +Get and handle Open positions. + +**Attributes**: + +|Name|Type|Description|Default| +|---|---|---|---| +|**symbol**|**str**|Financial instrument name.|""| +|**group**|**str**|The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name.|""| +|**ticket**|**int**|Position ticket.|0| +|**mt5**|**MetaTrader**|MetaTrader instance.|None| + +- `symbol` _str_ - Financial instrument name. +- `group` _str_ - The filter for arranging a group of necessary symbols. Optional named parameter. + If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. +- `ticket` _int_ - Position ticket. +- `mt5` _MetaTrader_ - MetaTrader instance. + + #### \_\_init\_\_ + +```python +def __init__(*, symbol: str = "", group: str = "", ticket: int = 0) +``` +Get Open Positions. + +|Name|Type|Description|Default| +|---|---|---|---| +|**symbol**|**str**|Financial instrument name.|""| +|**group**|**str**|The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name.|""| +|**ticket**|**int**|Position ticket.|0| + +#### positions_total +```python +async def positions_total() -> int +``` +Get the number of open positions. + +**Returns**: + +|Type|Description| +|---|---| +|**int**|Return total number of open positions| + +#### positions_get + +```python +async def positions_get() +``` +Get open positions with the ability to filter by symbol or ticket. + +**Returns**: + +|Type|Description| +|---|---| +|**list[TradePosition]**|A list of open trade positions| + + + + +#### close_all +```python +async def close_all() -> int +``` +Close all open positions for the trading account. + +**Returns**: +- `int` - Return number of positions closed. + diff --git a/docs/ram.md b/docs/ram.md new file mode 100644 index 0000000..682feaf --- /dev/null +++ b/docs/ram.md @@ -0,0 +1,83 @@ + + +# aiomql.ram + +Risk Assessment and Management + + + +## RAM Objects + +```python +class RAM() +``` + + + +#### \_\_init\_\_ + +```python +def __init__(**kwargs) +``` + +Risk Assessment and Management. All provided keyword arguments are set as attributes. + +**Arguments**: + +- `kwargs` _Dict_ - Keyword arguments. + + Defaults: +- `risk_to_reward` _float_ - Risk to reward ratio 1 +- `risk` _float_ - Percentage of account balance to risk per trade 0.01 # 1% +- `amount` _float_ - Amount to risk per trade in terms of account currency 0 +- `pips` _float_ - Target pips 0 +- `volume` _float_ - Volume to trade 0 + + + +#### get\_amount + +```python +async def get_amount(risk: float = 0) -> float +``` + +Calculate the amount to risk per trade as a percentage of free margin. + +**Arguments**: + +- `risk` _float_ - Percentage of account balance to risk per trade. Defaults to zero. + + +**Returns**: + +- `float` - Amount to risk per trade + + + +#### get\_volume + +```python +async def get_volume(*, + symbol: Symbol, + pips: float = 0, + amount: float = 0) -> float +``` + +Calculate the volume to trade. if pips is not provided, the pips attribute is used. +If the amount attribute or amount argument is zero, the amount is calculated using the get_amount method based on the risk. + +**Arguments**: + +- `symbol` _Symbol_ - Financial instrument + + +**Arguments**: + +- `pips` _float_ - Target pips. Defaults to zero. +- `amount` _float_ - Amount to risk per trade. Defaults to zero. + + +**Returns**: + +- `float` - Volume to trade + diff --git a/docs/records.md b/docs/records.md new file mode 100644 index 0000000..3ac429b --- /dev/null +++ b/docs/records.md @@ -0,0 +1,103 @@ + + +# aiomql.records + +This module contains the Records class, which is used to read and update trade records from csv files. + + + +## Records Objects + +```python +class Records() +``` + +This utility class read trade records from csv files, and update them based on their closing positions. + +**Attributes**: + +- `config` - Config object +- `records_dir(Path)` - Path to directory containing record of placed trades, If not given takes the default + from the config + + + +#### \_\_init\_\_ + +```python +def __init__(records_dir: Path = '') +``` + +Initialize the Records class. + +**Arguments**: + +- `records_dir` _Path_ - Path to directory containing record of placed trades. + + + +#### get\_records + +```python +async def get_records() +``` + +Get trade records from records_dir folder + +**Yields**: + +- `files` - Trade record files + + + +#### read\_update + +```python +async def read_update(file: Path) +``` + +Read and update trade records + +**Arguments**: + +- `file` - Trade record file + + + +#### update\_rows + +```python +async def update_rows(rows: list[dict]) -> list[dict] +``` + +Update the rows of entered trades in the csv file with the actual profit. + +**Arguments**: + +- `rows` - A list of dictionaries from the dictionary writer object of the csv file. + + +**Returns**: + +- `list[dict]` - A list of dictionaries with the actual profit and win status. + + + +#### update\_records + +```python +async def update_records() +``` + +Update trade records in the records_dir folder. + + + +#### update\_record + +```python +async def update_record(file: Path | str) +``` + +Update a single trade record file. + diff --git a/docs/result.md b/docs/result.md new file mode 100644 index 0000000..700ffb7 --- /dev/null +++ b/docs/result.md @@ -0,0 +1,56 @@ + + +# aiomql.result + + + +## Result Objects + +```python +class Result() +``` + +A base class for handling trade results and strategy parameters for record keeping and reference purpose. +The data property must be implemented in the subclass + +**Attributes**: + +- `config` _Config_ - The configuration object +- `name` - Any desired name for the result file object + + + +#### \_\_init\_\_ + +```python +def __init__(result: OrderSendResult, parameters: dict = None, name: str = '') +``` + +Prepare result data + +**Arguments**: + + result: + parameters: + name: + + + +#### to\_csv + +```python +async def to_csv() +``` + +Record trade results and associated parameters as a csv file + + + +#### save\_csv + +```python +async def save_csv() +``` + +Save trade results and associated parameters as a csv file in a separate thread + diff --git a/docs/sessions.md b/docs/sessions.md new file mode 100644 index 0000000..08f597b --- /dev/null +++ b/docs/sessions.md @@ -0,0 +1,169 @@ +## Sessions and Session + +Sessions allow you to run code at specific times of the day. + +```python +class Session() +``` +A session is a time period between two datetime.time objects specified in utc. + +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**start**|**datetime.time**|The start time of the session.|None| +|**end**|**datetime.time**|The end time of the session.|None| +|**on_start**|**str**|The action to take when the session starts. Default is None.|None| +|**on_end**|**str**|The action to take when the session ends. Default is None.|None| +|**custom_start**|**Callable**|A custom function to call when the session starts. Default is None.|None| +|**custom_end**|**Callable**|A custom function to call when the session ends. Default is None.|None| + +### Methods: +|Name|Description| +|---|---| +|**begin**|Call the action specified in on_start or custom_start.| +|**close**|Call the action specified in on_end or custom_end.| +|**action**|Used by begin and close to call the action specified.| +|**delta**|Get the timedelta of a datetime.time object.| +|**until**|Get the seconds until the session starts from the current time.| + +### \_\_init\_\_ + +```python +def __init__(*, + start: int | time, + end: int | time, + on_start: Literal['close_all', 'close_win', 'close_loss', + 'custom_start'] = None, + on_end: Literal['close_all', 'close_win', 'close_loss', + 'custom_end'] = None, + custom_start: Callable = None, + custom_end: Callable = None) +``` +Create a session. +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**start**| **int** \| **datetime.time** | The start time of the session in UTC. | None | +|**end**| **int** \| **datetime.time** | The end time of the session in UTC. | None | +|**on_start**| **Literal['close_all', 'close_win', 'close_loss', 'custom_start']** | The action to take when the session starts. Default is None. | None | +|**on_end**| **Literal['close_all', 'close_win', 'close_loss', 'custom_end']** | The action to take when the session ends. Default is None. | None | +|**custom_start**| **Callable** | A custom function to call when the session starts. Default is None. | None | +|**custom_end**| **Callable** | A custom function to call when the session ends. Default is None. | None | + +### begin +```python +async def begin() +``` +Call the action specified in on_start or custom_start. + +### close +```python +async def close() +``` +Call the action specified in on_end or custom_end. +### action +```python +async def action(action) +``` +Used by begin and close to call the action specified. + +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**action**| **Literal['close_all', 'close_win', 'close_loss', 'custom_start', 'custom_end']** | The action to take. | None | + +### delta +```python +@staticmethod +def delta(obj: time) +``` +Get the timedelta of a datetime.time object. + +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**obj**| **datetime.time** | A datetime.time object. | None | + +#### Returns: +|Type|Description| +|---|---| +|**timedelta**|A timedelta object.| + +### until +```python +def until() +``` +Get the seconds until the session starts from the current time. +#### Returns: +|Type|Description| +|---|---| +|**int**|The seconds until the session starts.| + + +## Sessions + +```python +class Sessions() +``` +Sessions allow you to run code at specific times of the day. It is a collection of Session objects. +Sessions are sorted by start time. The sessions object is an asynchronous context manager. +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**sessions**|**list[Session]**|A list of Session objects.|[]| +|**current_session**|**Session**|The current session.|None| + +### Methods: +|Name|Description| +|---|---| +|**add**|Add a Session object to the sessions list.| +|**remove**|Remove a Session object from the sessions list.| +|**find**|Find a session that contains a datetime.time object.| +|**find_next**|Find the next session that contains a datetime.time object.| +|**check**|Check if the current session has started and if not, wait until it starts.| + +#### \_\_init\_\_ +```python +def __init__(*sessions) +``` +Create a Sessions object. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**sessions**| **tuple[Session]** | A tuple of Session objects. | None | + +### find +```python +def find(obj: time) -> Session | None +``` +Find a session that contains a datetime.time object. +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**obj**| **datetime.time** | A datetime.time object. | None | + +#### Returns: +|Type|Description| +|---|---| +|**Session**|A Session object or None if not found.| + +### find\_next +```python +def find_next(obj: time) -> Session +``` +Find the next session that contains a datetime.time object. +#### Arguments: +|Name| Type | Description | Default | +|---|-------------------------|--------------|-------------------| +|**obj**| **datetime.time** | A datetime.time object. | None | +#### Returns: +|Type|Description| +|---|---| +|**Session**|A Session object.| + + +### check +```python +async def check() +``` +Check if the current session has started and if not, wait until it starts. diff --git a/docs/strategy.md b/docs/strategy.md new file mode 100644 index 0000000..a96423b --- /dev/null +++ b/docs/strategy.md @@ -0,0 +1,52 @@ +## Strategy +The base class for creating strategies. +```python +class Strategy(ABC) +``` +The base class for creating strategies. +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**name**|**str**|A name for the strategy.|None| +|**account**|**Account**|Account instance.|None| +|**mt5**|**MetaTrader**|MetaTrader instance.|None| +|**config**|**Config**|Config instance.|None| +|**symbol**|**Symbol**|The Financial Instrument as a Symbol Object|None| +|**parameters**|**Dict**|A dictionary of parameters for the strategy.|None| + +### Notes: +Define the name of a strategy as a class attribute. If not provided, the class name will be used as the name. + +### \_\_init\_\_ +```python +def __init__(*, symbol: Symbol, params: dict = None, sessions: Sessions) +``` +Initiate the parameters dict and add name and symbol fields. Use class name as strategy name if name is not provided. +### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**symbol**| **Symbol** | The Financial instrument | None | +|**params**| **Dict** | Trading strategy parameters | None | +|**sessions**| **Sessions** | Trading sessions | None | + +### sleep +```python +@staticmethod +async def sleep(secs: float) +``` +Sleep for the needed amount of seconds in between requests to the terminal. +computes the accurate amount of time needed to sleep ensuring that the next request is made at the start of +a new bar and making cooperative multitasking possible. + +### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**secs**| **float** | The time in seconds. Usually the timeframe you are trading on. | None | + +### trade +```python +@abstractmethod +async def trade() +``` +Place trades using this method. This is the main method of the strategy. +It will be called by the strategy runner. diff --git a/docs/symbol.md b/docs/symbol.md new file mode 100644 index 0000000..9c7c555 --- /dev/null +++ b/docs/symbol.md @@ -0,0 +1,310 @@ +## Symbol + +Symbol class for handling a financial instrument. + +```python +class Symbol(SymbolInfo) +``` +Main class for handling a financial instrument. A subclass of SymbolInfo and Base it has attributes and methods +for working with a financial instrument. + +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**name**|**str**|The name of the symbol.|None| +|**mt5**|**MetaTrader**|MetaTrader instance.|None| +|**config**|**Config**|Config instance.|None| +|**account**|**Account**|Account instance.|None| +|**tick**|**Tick**|The current price tick of the symbol.|None| + +### Methods: +|Name|Description| +|---|---| +|**pip**|Returns the pip value of the symbol. This is ten times the point value for forex symbols.| +|**info_tick**|Get the current price tick of a financial instrument.| +|**symbol_select**|Select a symbol in the MarketWatch window or remove a symbol from the window.| +|**info**|Get data on the specified financial instrument and update the symbol object properties.| +|**init**|Initialized the symbol by pulling properties from the terminal.| +|**book_add**|Subscribes the MetaTrader 5 terminal to the Market Depth change events for a specified symbol.| +|**book_get**|Returns a tuple of BookInfo featuring Market Depth entries for the specified symbol.| +|**book_release**|Cancels subscription of the MetaTrader 5 terminal to the Market Depth change events for a specified symbol.| +|**compute_volume**|Computes the volume of a trade based on the amount and the number of pips to target.| +|**currency_conversion**|Convert from one currency to the other.| +|**copy_rates_from**|Get bars from the MetaTrader 5 terminal starting from the specified date.| +|**copy_rates_from_pos**|Get bars from the MetaTrader 5 terminal starting from the specified index.| +|**copy_rates_range**|Get bars in the specified date range from the MetaTrader 5 terminal.| +|**copy_ticks_from**|Get ticks from the MetaTrader 5 terminal starting from the specified date.| +|**copy_ticks_range**|Get ticks for the specified date range from the MetaTrader 5 terminal.| + +### Notes: +Full properties are on the SymbolInfo Object. +Make sure Symbol is always initialized with a name argument + + + +### pip +```python +@property +def pip() +``` +Returns the pip value of the symbol. This is ten times the point value for forex symbols. + +## Returns: +|Type|Description| +|---|---| +|**float**|The pip value of the symbol.| + +### info\_tick +```python +async def info_tick(*, name: str = "") -> Tick +``` +Get the current price tick of a financial instrument. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**name**| **str** | The name of the symbol. | None | + + +#### Returns: +|Type|Description| +|---|---| +|**Tick**|Return a Tick Object| + +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### symbol\_select +```python +async def symbol_select(*, enable: bool = True) -> bool +``` +Select a symbol in the MarketWatch window or remove a symbol from the window. +Update the select property +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**enable**| **bool** | Switch. Optional unnamed parameter. If 'false', a symbol should be removed from the MarketWatch window. | None | + +#### Returns: +|Type|Description| +|---|---| +|**bool**|True if successful, otherwise False.| + +### info +```python +async def info() -> SymbolInfo +``` +Get data on the specified financial instrument and update the symbol object properties + +#### Returns: +|Type|Description| +|---|---| +|**SymbolInfo**|SymbolInfo if successful| + +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### init +```python +async def init() -> bool +``` +Initialized the symbol by pulling properties from the terminal +#### Returns: +|Type|Description| +|---|---| +|**bool**|Returns True if symbol info was successful initialized| + +### book\_add +```python +async def book_add() -> bool +``` +Subscribes the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. +If the symbol is not in the list of instruments for the market, This method will return False +#### Returns: +|Type|Description| +|---|---| + +### book\_get +```python +async def book_get() -> tuple[BookInfo] +``` +Returns a tuple of BookInfo featuring Market Depth entries for the specified symbol. +#### Returns: +|Type|Description| +|---|---| +|**tuple[BookInfo]**|Returns the Market Depth contents as a tuples of BookInfo Objects| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### book\_release +```python +async def book_release() -> bool +``` +Cancels subscription of the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. +#### Returns: +|Type|Description| +|---|---| +|**bool**|True if successful, otherwise � False.| +#### compute\_volume +```python +async def compute_volume(*, + amount: float, + pips: float, + use_minimum: bool = True) -> float +``` +Computes the volume of a trade based on the amount and the number of pips to target. +This is a dummy method that returns the minimum volume of the symbol. It is meant to be overridden by a subclass +Checkout Forex Symbol implementation in [ForexSymbol](#forexsymbol) + +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**amount**| **float** | Amount to risk in the trade | None | +|**pips**| **float** | Number of pips to target | None | +|**use_minimum**| **bool** | If True, the minimum volume is returned if the computed volume is less than the minimum volume. | True | +#### Returns: +|Type|Description| +|---|---| +|**float**|Returns the volume of the trade| + +### currency\_conversion +```python +async def currency_conversion(*, amount: float, base: str, + quote: str) -> float +``` +Convert from one currency to the other. +#### Arguments: + +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**amount**| **float** | Amount to convert given in terms of the quote currency | None | +|**base**| **str** | The base currency of the pair | None | +|**quote**| **str** | The quote currency of the pair | None | + +#### Returns: +|Type|Description| +|---|---| +|**float**|Amount in terms of the base currency or None if it failed to convert| + +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If conversion is impossible| + +### copy\_rates\_from +```python +async def copy_rates_from(*, + timeframe: TimeFrame, + date_from: datetime | int, + count: int = 500) -> Candles +``` +Get bars from the MetaTrader 5 terminal starting from the specified date. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**timeframe**| **TimeFrame** | Timeframe the bars are requested for. Set by a value from the TimeFrame enumeration. | Required unnamed parameter | +|**date_from**| **datetime, int** | Date of opening of the first bar from the requested sample. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +|**count**| **int** | Number of bars to receive. | Required unnamed parameter | +#### Returns: +|Type|Description| +|---|---| +|**Candles**|Returns a Candles object as a collection of rates ordered chronologically| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### copy\_rates\_from\_pos +```python +async def copy_rates_from_pos(*, + timeframe: TimeFrame, + count: int = 500, + start_position: int = 0) -> Candles +``` +Get bars from the MetaTrader 5 terminal starting from the specified index. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**timeframe**| **TimeFrame** | TimeFrame value from TimeFrame Enum. Required keyword only parameter | Required keyword only parameter | +|**count**| **int** | Number of bars to return. Keyword argument defaults to 500 | 500 | +|**start_position**| **int** | Initial index of the bar the data are requested from. The numbering of bars goes from present to past. Thus, the zero bar means the current one. Keyword argument defaults to 0. | 0 | +#### Returns: +|Type|Description| +|---|---| +|**Candles**|Returns a Candles object as a collection of rates ordered chronologically.| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### copy\_rates\_range +```python +async def copy_rates_range(*, timeframe: TimeFrame, date_from: datetime | int, + date_to: datetime | int) -> Candles +``` +Get bars in the specified date range from the MetaTrader 5 terminal. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**timeframe**| **TimeFrame** | Timeframe for the bars using the TimeFrame enumeration. Required unnamed parameter. | Required unnamed parameter | +|date_from|datetime, int|Date the bars are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time >= date_from are returned. Required unnamed parameter.|Required unnamed parameter| +|date_to|datetime, int|Date, up to which the bars are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time <= date_to are returned. Required unnamed parameter.|Required unnamed parameter| +#### Returns: +|Type|Description| +|---|---| +|**Candles**|Returns a Candles object as a collection of rates ordered chronologically.| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### copy\_ticks\_from +```python +async def copy_ticks_from(*, + date_from: datetime | int, + count: int = 100, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` +Get ticks from the MetaTrader 5 terminal starting from the specified date. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**date_from**| **datetime, int** | Date the ticks are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +|**count**| **int** | Number of requested ticks. Defaults to 100 | Required unnamed parameter | +|**flags**| **CopyTicks** | A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default | Required unnamed parameter | +#### Returns: +|Type|Description| +|---|---| +|**Ticks**|Returns a Ticks object as a collection of ticks ordered chronologically.| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| + +### copy\_ticks\_range +```python +async def copy_ticks_range(*, + date_from: datetime | int, + date_to: datetime | int, + flags: CopyTicks = CopyTicks.ALL) -> Ticks +``` +Get ticks for the specified date range from the MetaTrader 5 terminal. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**date_from**| **datetime, int** | Date the ticks are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +|**date_to**| **datetime, int** | Date, up to which the ticks are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. | Required unnamed parameter | +|**flags**| **CopyTicks** | A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default | Required unnamed parameter | +#### Returns: +|Type|Description| +|---|---| +|**Ticks**|Returns a Ticks object as a collection of ticks ordered chronologically.| +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If request was unsuccessful and None was returned| diff --git a/docs/terminal.md b/docs/terminal.md new file mode 100644 index 0000000..44c2a39 --- /dev/null +++ b/docs/terminal.md @@ -0,0 +1,71 @@ +## Terminal +Terminal related functions and properties + +```python +class Terminal(TerminalInfo) +``` +Terminal Class. Get information about the MetaTrader 5 terminal. The class is a subclass of the TerminalInfo +class. It inherits all the attributes and methods of the TerminalInfo class and adds some useful methods. +### Attributes: +|Name| Type | Description | Default | +|---|---------------------|------------------------------------------------|----| +|**initialized**|**bool** | check if initial request has been sent to the terminal to get terminal info. | False | +|**mt5**|**MetaTrader** | MetaTrader instance | None | +|**config**|**Config** | Config instance | None | + +### Notes: +Other attributes are defined in the TerminalInfo Class + +### initialize +```python +async def initialize() -> bool +``` +Establish a connection with the MetaTrader 5 terminal. There are three call options. Call without parameters. +The terminal for connection is found automatically. Call specifying the path to the MetaTrader 5 terminal we +want to connect to. word path as a keyword argument Call specifying the trading account path and parameters +i.e login, password, server, as keyword arguments, path can be omitted. +#### Returns: +|Type|Description| +|---|---| +|**bool**|True if successful else False| + +### version +```python +async def version() +``` +Get the MetaTrader 5 terminal version. This method returns the terminal version, build and release date as +a tuple of three values + +#### Returns: +|Type|Description| +|---|---| +|**Version**|version of tuple as Version object| + +#### Raises: +|Exception|Description| +|---|---| +|**ValueError**|If the terminal version cannot be obtained| + +### info +```python +async def info() +``` +Get the connected MetaTrader 5 client terminal status and settings. gets terminal info in the form of a +named tuple structure (namedtuple). Return None in case of an error. The info on the error can be +obtained using last_error(). + +#### Returns: +|Type|Description| +|---|---| +|**TerminalInfo**|Terminal status and settings as a terminal object.| + +### symbols\_total +```python +async def symbols_total() -> int +``` +Get the number of all financial instruments in the MetaTrader 5 terminal. + +#### Returns: +|Type|Description| +|---|---| +|**int**|Total number of available symbols| diff --git a/docs/ticks.md b/docs/ticks.md new file mode 100644 index 0000000..190eab5 --- /dev/null +++ b/docs/ticks.md @@ -0,0 +1,97 @@ +## ticks +Module for working with price ticks. + +```python +class Tick() +``` +Price Tick of a Financial Instrument. +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**symbol**|**Symbol**|The Financial Instrument as a Symbol Object|None| +|**time**|**datetime**|Time of the last prices update for the symbol|None| +|**bid**|**float**|Current Bid price|None| +|**ask**|**float**|Current Ask price|None| +|**last**|**float**|Price of the last deal (Last)|None| +|**volume**|**float**|Volume for the current Last price|None| +|**time_msc**|**int**|Time of the last prices update for the symbol in milliseconds|None| +|**flags**|**TickFlag**|Tick flags|None| +|**volume_real**|**float**|Volume for the current Last price|None| +|**Index**|**int**|Custom attribute representing the position of the tick in a sequence.|None| + +### set\_attributes +```python +def set_attributes(**kwargs) +``` +Set attributes from keyword arguments + +## Ticks +```python +class Ticks() +``` +Container data class for price ticks. Arrange in chronological order. +Supports iteration, slicing and assignment +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**data**|**DataFrame**|DataFrame of price ticks arranged in chronological order.|None| + +### \_\_init\_\_ +```python +def __init__(*, data: DataFrame | Iterable, flip=False) +``` +Initialize the Ticks class. Creates a DataFrame of price ticks from the data argument. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**data**| **DataFrame** \| **Iterable** | Dataframe of price ticks or any iterable object that can be converted to a pandas DataFrame | None | +|**flip**| **bool** | If flip is True reverse data chronological order. | False | + +### ta +```python +@property +def ta() +``` +Access to the pandas_ta library for performing technical analysis on the underlying data attribute. +#### Returns: +|Name|Type|Description| +|---|---|---| +|**pandas_ta**|**pandas_ta**|The pandas_ta library| + +### ta\_lib +```python +@property +def ta_lib() +``` +Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute. +#### Returns: +|Name|Type|Description| +|---|---|---| +|**ta**|**ta**|The ta library| + +### data +```python +@property +def data() -> DataFrame +``` +DataFrame of price ticks arranged in chronological order. +#### Returns: +|Name|Type|Description| +|---|---|---| +|**data**|**DataFrame**|DataFrame of price ticks arranged in chronological order.| + +### rename +```python +def rename(inplace=True, **kwargs) -> _Ticks | None +``` +Rename columns of the candle class. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**inplace**| **bool** | Rename the columns inplace or return a new instance of the class with the renamed columns | True | +|**kwargs**| | The new names of the columns | | +#### Returns: +|Type|Description| +|---|---| +|**Ticks**|A new instance of the class with the renamed columns if inplace is False.| +|**None**|If inplace is True| diff --git a/docs/trader.md b/docs/trader.md new file mode 100644 index 0000000..35c342e --- /dev/null +++ b/docs/trader.md @@ -0,0 +1,65 @@ +## Trader +Trader class module. Handles the creation of an order and the placing of trades + +```python +class Trader() +``` +Base class for creating a Trader object. Handles the creation of an order and the placing of trades +### Attributes: +|Name|Type|Description|Default| +|---|---|---|---| +|**name**|**str**|A name for the strategy.|None| +|**account**|**Account**|Account instance.|None| +|**mt5**|**MetaTrader**|MetaTrader instance.|None| +|**config**|**Config**|Config instance.|None| +|**symbol**|**Symbol**|The Financial Instrument as a Symbol Object|None| +|**parameters**|**Dict**|A dictionary of parameters for the strategy.|None| + +### \_\_init\_\_ +```python +def __init__(*, symbol: Symbol, ram: RAM = None) +``` +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**symbol**| **Symbol** | The Financial instrument | None | +|**ram**| **RAM** | Risk Assessment and Management instance | None | +Initializes the order object and RAM instance +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**symbol**| **Symbol** | The Financial instrument | None | +|**ram**| **RAM** | Risk Assessment and Management instance | None | +### create\_order +```python +async def create_order(*, order_type: OrderType, **kwargs) +``` +Complete the order object with the required values. Creates a simple order. +Uses the ram instance to set the volume. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**order_type**| **OrderType** | Type of order | None | +|**kwargs**| | keyword arguments as required for the specific trader | | + +### set\_order\_limits +```python +async def set_order_limits(pips: float) +``` +Sets the stop loss and take profit for the order. +This method uses pips as defined for forex instruments. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**pips**| **float** | Target pips | None | + +### place\_trade +```python +async def place_trade(order_type: OrderType, params: dict = None, **kwargs) +``` +Places a trade based on the order_type. +#### Arguments: +|Name| Type | Description | Default | +|---|--------------------|-----------------------------|-------------------| +|**order_type**| **OrderType** | Type of order | None | +|**params**| **dict** | parameters to be saved with the trade | None | +|**kwargs**| | keyword arguments as required for the specific trader | |