v4.0.17 no-backtest

This commit is contained in:
Ichinga Samuel
2026-02-21 07:43:33 +01:00
parent 844e39194b
commit 97aea6952e
124 changed files with 8198 additions and 14349 deletions
+37 -21
View File
@@ -1,27 +1,43 @@
# Account
# account
## Table of Contents
- [Account](#account.account)
- [refresh](#account.refresh)
`aiomql.lib.account` — Trading account connection manager.
## Overview
<a id="account.account"></a>
### Account
```python
class Account(_Base, AccountInfo)
```
A singleton class for managing a trading account. A subclass of _Base and AccountInfo. It supports asynchronous context
management protocol.
The `Account` class is a singleton that manages the connection to a MetaTrader 5 trading
account. It supports both async and sync context managers for connecting and disconnecting,
and provides access to account properties such as balance, equity, and margin.
#### Attributes:
| Name | Type | Description | Default |
|-------------|-------------------|------------------------------------------------------|---------|
| `connected` | `bool` | Status of connection to MetaTrader 5 Terminal | False |
Inherits from [`_Base`](../core/base.md).
## Classes
<a id="account.refresh"></a>
### refresh
```python
async def refresh()
```
Refreshes the account instance with the latest data from the MetaTrader 5 terminal
### `Account`
> Singleton for managing the MT5 account connection.
| Attribute | Type | Description |
|-----------|------|-------------|
| `connected` | `bool` | Whether the account is currently connected |
All `AccountInfo` fields (e.g. `login`, `balance`, `equity`, `margin`, `leverage`, `currency`)
are available as instance attributes after a successful connection.
#### `__aenter__()` / `__aexit__(…)`
Async context manager — initializes the terminal, logs in, and populates account info.
#### `__enter__()` / `__exit__(…)`
Sync context manager — same as above using synchronous calls.
#### `refresh()`
Re-fetches account info from the terminal and updates instance attributes.
**Returns:** `bool``True` if the account info was successfully refreshed.
## Synchronous API
The sync context manager (`with Account() as acc:`) uses `initialize_sync` and `login_sync`
internally. See [`sync/account.py`] for the full synchronous wrapper.
-185
View File
@@ -1,185 +0,0 @@
<a id="backtester"></a>
# backtester
<a id="backtester.BackTester"></a>
## BackTester Objects
```python
class BackTester()
```
The bot class. Create a bot instance to run your strategies.
**Attributes**:
- `executor` - The default thread executor.
- `config` _Config_ - Config instance
- `mt` _MetaBackTester_ - MetaTrader instance
<a id="backtester.BackTester.initialize_sync"></a>
#### initialize\_sync
```python
def initialize_sync()
```
Prepares the bot by signing in to the trading account and initializing the symbols for the trading session.
Starts the global task queue.
**Raises**:
SystemExit if sign in was not successful
<a id="backtester.BackTester.initialize"></a>
#### initialize
```python
async def initialize()
```
Prepares the bot by signing in to the trading account and initializing the symbols for the trading session.
Starts the global task queue.
**Raises**:
SystemExit if sign in was not successful
<a id="backtester.BackTester.add_coroutine"></a>
#### add\_coroutine
```python
def add_coroutine(*,
coroutine: Callable[..., ...] | Coroutine,
on_separate_thread=False,
**kwargs)
```
Add a coroutine to the executor.
**Arguments**:
- `coroutine` _Coroutine_ - A coroutine to be executed
- `on_separate_thread` _bool_ - Run the coroutine
- `**kwargs` _dict_ - keyword arguments for the coroutine
<a id="backtester.BackTester.execute"></a>
#### execute
```python
def execute()
```
Execute the bot.
<a id="backtester.BackTester.start"></a>
#### start
```python
async def start()
```
Initialize the bot and execute it. Similar to calling `execute` method but is a coroutine.
<a id="backtester.BackTester.add_strategy"></a>
#### add\_strategy
```python
def add_strategy(*, strategy: Strategy)
```
Add a strategy to the list of strategies.
An added strategy will only run if it's symbol was successfully initialized and it is added to the executor.
**Arguments**:
- `strategy` _Strategy_ - A Strategy instance to run on bot
**Notes**:
Make sure the symbol has been added to the market
<a id="backtester.BackTester.add_strategies"></a>
#### add\_strategies
```python
def add_strategies(*, strategies: Iterable[Strategy])
```
Add multiple strategies at the same time
**Arguments**:
- `strategies` - A list of strategies
<a id="backtester.BackTester.add_strategy_all"></a>
#### add\_strategy\_all
```python
def add_strategy_all(*,
strategy: Type[Strategy],
params: dict | None = None,
symbols: list[Symbol] = None,
**kwargs)
```
Use this to run a single strategy on multiple symbols with the same parameters and keyword arguments.
**Arguments**:
- `strategy` _Strategy_ - Strategy class
- `params` _dict_ - A dictionary of parameters for the strategy
- `symbols` _list_ - A list of symbols to run the strategy on
- `**kwargs` - Additional keyword arguments for the strategy
<a id="backtester.BackTester.init_strategy"></a>
#### init\_strategy
```python
async def init_strategy(*, strategy: Strategy) -> bool
```
Initialize a single strategy. This method is called internally by the bot.
<a id="backtester.BackTester.init_strategy_sync"></a>
#### init\_strategy\_sync
```python
def init_strategy_sync(*, strategy: Strategy) -> bool
```
Initialize a single strategy. This method is called internally by the bot.
<a id="backtester.BackTester.init_strategies"></a>
#### init\_strategies
```python
async def init_strategies()
```
Initialize the symbols for the current trading session. This method is called internally by the bot.
<a id="backtester.BackTester.init_strategies_sync"></a>
#### init\_strategies\_sync
```python
def init_strategies_sync()
```
Initialize the symbols for the current trading session. This method is called internally by the bot.
+33 -145
View File
@@ -1,161 +1,49 @@
# Bot
# bot
## Table of Contents
- [Bot](#bot.bot)
- [\_\_init\_\_](#bot.init)
- [initialize](#bot.initialize)
- [execute](#bot.execute)
- [start](#bot.start)
- [add_coroutine](#bot.add_coroutine)
- [add_function](#bot.add_function)
- [add_strategy](#bot.add_strategy)
- [add_strategies](#bot.add_strategies)
- [add_strategy_all](#bot.add_strategy_all)
- [process_pool](#bot.run_bots)
`aiomql.lib.bot` — Bot orchestrator for running trading strategies.
<a id='bot.bot'></a>
### Bot
```python
class Bot
```
"""The bot class. Create a bot instance to run strategies.
## Overview
#### Attributes:
| Name | Type | Description | Default |
|--------------|--------------------|--------------------------------------------|--------------|
| `account` | `Account` | Account Object. | None |
| `executor` | `Executor` | The executor. | None |
| `strategies` | `List[Strategies]` | A list of strategies to initialize and run | list() |
| `mt5` | `MetaTrader` | `A MetaTrader Instance` | MetaTrader() |
| `config` | `Config` | A Config instance | Config() |
The `Bot` class is the main entry point for running one or more trading strategies against
the MetaTrader 5 terminal. It manages the account connection lifecycle, strategy
initialisation, task queuing, and graceful shutdown via signal handlers.
<a id='bot.init'></a>
### \__init\__
```python
def __init__()
```
Initializes the Bot class.
Inherits from [`_Base`](../core/base.md).
## Classes
<a id='bot.initialize'></a>
### initialize
```python
async def initialize(self)
```
Prepares the bot by signing in to the trading account and initializing the symbols for each strategy.
Only strategies with successfully initialized symbols will be added to the executor. Starts the global task queue.
### `Bot`
Note: *initialize_sync* is a synchronous version of this method.
> Orchestrates strategy execution and terminal connection.
#### Raises:
| Exception | Description |
|--------------|-------------------------------|
| `SystemExit` | If sign in was not successful |
| Attribute | Type | Description |
|-----------|------|-------------|
| `account` | `Account` | The trading account instance |
| `executor` | `Executor` | Strategy and task executor |
| `mt5` | `MetaTrader` | MetaTrader terminal interface |
#### Lifecycle
<a id='bot.execute'></a>
### execute
```python
def execute()
```
Executes the bot. Use this method to run the bot in a synchronous manner.
This method is blocking and will not return until the bot is done running.
| Method | Description |
|--------|-------------|
| `initialize()` | Connects to MT5 and logs in, sets up the executor |
| `start()` | Starts the bot: initialises, adds strategies, and runs the executor |
| `stop()` | Gracefully stops the bot and shuts down the terminal |
| `execute()` | Main execution loop |
#### Strategy Management
<a id='bot.start'></a>
### start
```python
async def start()
```
Initialize the bot and execute it. Similar to calling **execute** method but is asynchronous.
| Method | Description |
|--------|-------------|
| `add_strategy(strategy)` | Registers a `Strategy` subclass for execution |
| `add_strategies(*strategies)` | Registers multiple strategies at once |
#### Signal Handling
<a id='bot.add_coroutine'></a>
### add_coroutine
```python
def add_coroutine(self, coroutine: Coroutine, on_separate_thread=False, **kwargs)
```
Add a coroutine to the executor. By default, all coroutines added to the executor run on this same thread,
using `asyncio.gather`, but if `on_separate_thread` is true then the coroutine is given it's own thread.
| Method | Description |
|--------|-------------|
| `sigint_handler(sig, frame)` | Handles SIGINT for graceful shutdown |
#### Parameters:
| Name | Type | Description |
|----------------------|-------------|----------------------------------------------------|
| `coroutine` | `Coroutine` | A coroutine to run in the executor |
| `on_separate_thread` | `bool` | Run coroutine on a separate thread in the executor |
| `kwargs` | `Any` | Keyword arguments to pass to the coroutine |
## Synchronous API
<a id='bot.add_function'></a>
### add_function
```python
def add_function(self, function: Callable, **kwargs)
```
Add a function to the executor.
#### Parameters:
| Name | Type | Description |
|------------|------------|-------------------------------------------|
| `function` | `Callable` | A function to run in the executor |
| `kwargs` | `Any` | Keyword arguments to pass to the function |
<a id='bot.add_strategy'></a>
### add_strategy
```python
def add_strategy(self, strategy: Strategy)
```
Add a strategy to the list of strategies.
#### Parameters:
| Name | Type | Description |
|------------|------------|-----------------------------------|
| `strategy` | `Strategy` | A Strategy instance to run on bot |
<a id='bot.add_strategies'></a>
### 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 |
<a id='bot.add_strategy_all'></a>
### add_strategy_all
```python
def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None, symbols: list[Symbol] = None, **kwargs)
```
Use this to run a single strategy on multiple symbols with the same parameters and keyword arguments.
#### Parameters:
| Name | Type | Description |
|------------|------------------|---------------------------------------------|
| `strategy` | `Type[Strategy]` | A Strategy class |
| `params` | `dict` or `None` | A dictionary of parameters for the strategy |
| `symbols` | `list[Symbol]` | A list of symbols to run the strategy on |
| `**kwargs` | `Any` | Keyword arguments |
<a id='bot.process_pool'></a>
```python
@classmethod
def process_pool(cls, processes: dict[Callable: dict] = None, num_workers: int = None):
```
Run multiple processes (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 |
|---------------|------------------------|---------------------------------------------------------------------------------|
| `processes` | `dict[Callable: dict]` | A dictionary of callables and their keyword arguments to run as processes |
| `num_workers` | `int` | The number of workers to use. If not specified, the number of bots will be used |
A synchronous variant is available in `aiomql.lib.sync.bot`.
+48 -225
View File
@@ -1,242 +1,65 @@
# Candle and Candles
Candle and Candles classes for handling bars from the MetaTrader 5 terminal.
# candle
## Table of Contents
- [Candle](#candle.candle)
- [\_\_init\_\_](#candle.__init__)
- [set_attributes](#candle.set_attributes)
- [is_bullish](#candle.is_bullish)
- [is_bearish](#candle.is_bearish)
- [dict](#candle.dict)
- [Candles](#candles.candles)
- [\_\_init\_\_](#candles.__init__)
- [ta](#candles.ta)
- [ta_lib](#candles.ta_lib)
- [data](#candles.data)
- [rename](#candles.rename)
- [plot](#candles.plot)
- [make_subplot](#candles.make_subplot)
`aiomql.lib.candle` — Candlestick / bar data and technical analysis.
<a id="candle.candle"></a>
### 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.
## Overview
### Attributes
Provides `Candle` (a single OHLCV bar) and `Candles` (an ordered collection). The `Candles`
class wraps a `pandas.DataFrame` and integrates with `pandas_ta` for technical analysis.
| 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. |
| `index` | `Timestamp` | Index of the object in the DataFrame, as a timestamp. |
## Classes
<a id='candle.__init__'></a>
### \_\_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. |
### `Candle`
#### Raises:
| Exception | Description |
|--------------|-----------------------------------------------|
| `ValueError` | If open, high, low, or close is not provided. |
> A single candlestick bar.
<a id="candle.set_attributes"></a>
### 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. |
| Attribute | Type | Description |
|-----------|------|-------------|
| `time` | `int` | Bar open time (unix timestamp) |
| `open` | `float` | Open price |
| `high` | `float` | High price |
| `low` | `float` | Low price |
| `close` | `float` | Close price |
| `tick_volume` | `float` | Tick volume |
| `real_volume` | `float` | Real volume |
| `spread` | `float` | Spread |
| `Index` | `int` | Position index within a `Candles` collection |
<a id="candle.is_bullish"></a>
### is_bullish
```python
def is_bullish() -> bool
```
A simple check to see if the candle is bullish.
#### Returns:
| Type | Description |
|--------|---------------|
| `bool` | True or False |
#### Properties
<a id="candle.is_bearish"></a>
### is_bearish
```python
def is_bearish() -> bool
```
A simple check to see if the candle is bearish.
#### Returns:
| Type | Description |
|------|---------------|
| bool | True or False |
| Property | Description |
|----------|-------------|
| `mid` | Midpoint `(high + low) / 2` |
| `is_bullish` | `True` if `close >= open` |
| `is_bearish` | `True` if `close < open` |
| `dict` | Attribute dictionary |
<a id="candle.dict"></a>
### 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`
> Ordered collection of candlestick bars backed by a DataFrame.
### <a id="candles.candles"></a> 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.
| Attribute | Type | Description |
|-----------|------|-------------|
| `data` | `DataFrame` | The underlying OHLCV data |
| `Index` | `Series` | Positional index column |
| `timeframe` | `TimeFrame` | The chart timeframe |
### 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.
#### Data Access
| 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 |
| `index` | `Series['Timestamp']` | DatetimeIndex of the underlying DataFrame 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. |
| Method / Property | Description |
|-------------------|-------------|
| `__getitem__(index)` | Get a `Candle` by position or slice |
| `__len__()` | Number of bars |
| `__iter__()` | Iterate over `Candle` objects |
| `columns` | DataFrame column names |
| `ta` | Access to `pandas_ta` indicators |
| `rename(inplace=True, **kwargs)` | Rename columns |
#### Notes
When subclassing this class, make sure the Candle attribute is set to your desired candle class.
#### Technical Analysis
<a id="candles.__init__"></a>
### \_\_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 |
<a id="candles.ta"></a>
### 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 |
<a id="candles.ta_lib"></a>
### 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 |
<a id="candles.data"></a>
### data
```python
@property
def data() -> DataFrame
```
A pandas DataFrame of all candles in the object.
<a id="candles.rename"></a>
### 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. |
<a id="candles.plot"></a>
### plot
```python
def plot(subplots=None, span: int = None, filename="", **kwargs):
```
Create a plot with mplfinance, can be saved as png.
#### Parameters:
| Name | Type | Description | Default |
|------------|--------|-------------------------|---------|
| `subplots` | `dict` | Add subplots | None |
| `span` | `int` | Take the last n candles | None |
| `filename` | `str` | A name to save plot | "" |
| `**kwargs` | `Any` | Kwargs to plot function | |
<a id="candles.make_subplot"></a>
### make_subplot
```python
def make_subplot(column: str | list[str], span: int = None, **kwargs):
```
Create a plot with mplfinance, can be saved as png.
#### Parameters:
| Name | Type | Description | Default |
|------------|-------------------|--------------------------------------------------|---------|
| `column` | `list[str]\| str` | An iterable of column names as a list or strings | None |
| `span` | `int` | Take the last n candles | None |
| `**kwargs` | `Any` | Kwargs to plot function | |
| Method | Description |
|--------|-------------|
| `ta_lib(func, *args, **kwargs)` | Run any `pandas_ta` indicator |
| `ta.sma(length)`, `ta.ema(length)`, etc. | Standard TA indicators via `pandas_ta` |
+30 -83
View File
@@ -1,94 +1,41 @@
# Executor
# executor
## Table of Contents
- [Executor](#executor.Executor)
- [__init__](#executor.__init__)
- [add_function](#executor.add_function)
- [add_coroutine](#executor.add_coroutine)
- [run_function](#executor.run_function)
- [execute](#executor.execute)
`aiomql.lib.executor` — Strategy and task executor.
<a id='executor.Executor'></a>
### 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 |
| `strategy_runners` | `list[Strategy]` | List of strategies. | [] |
| `coroutines` | `dict` | Dictionary of coroutines and keyword arguments | {} |
| `functions` | `dict` | Dictionary of functions and keyword arguments | {} |
## Overview
<a id="executor.__init__"></a>
#### \_\_init\_\_
```python
def __init__(self):
```
Initialize the executor class.
The `Executor` manages the lifecycle of trading strategies and background tasks. It collects
functions, coroutines, and `Strategy` instances, then runs them via a `TaskQueue`.
<a id="executor.add_coroutine"></a>
### add_coroutine
```python
def add_coroutine(self,*,coroutine: Callable | Coroutine,kwargs: dict = None,on_separate_thread=False):
```
Submit a coroutine to the executor. The coroutines are run in parallel using *asyncio.gather* except when the
on_spate_thread flag is set to True. In that case, the coroutine is run in a separate thread.
## Classes
#### Arguments:
| Name | Type | Description |
|----------------------|------------|-------------------------------------------------|
| `coroutine` | `Callable` | The coroutine |
| `kwargs` | `Dict` | The keyword arguments to pass to the coroutine. |
| `on_separate_thread` | `bool` | If True run the coroutine on a separate thread |
### `Executor`
<a id="executor.add_function"></a>
### add_function
```python
def add_function(self, *, function: Callable, kwargs: dict = None)
```
Submit a function to the executor. Each functions runs on a separate thread.
> Executes strategies and tasks using a `TaskQueue`.
#### Arguments:
| Name | Type | Description |
|------------|------------|--------------------------------------------|
| `function` | `Callable` | The function to run in the executor |
| `kwargs` | `Dict` | Keyword arguments to pass to the function. |
| Attribute | Type | Description |
|-----------|------|-------------|
| `config` | `Config` | Global configuration |
| `task_queue` | `TaskQueue` | The underlying task queue |
<a id="executor.run_function"></a>
### run_function
```python
@staticmethod
def run_function(function: Callable, kwargs: dict)
```
Wrap the input coroutine function with 'asyncio.run' so that it can be executed in a threadpool executor.
#### Arguments:
| Name | Type | Description |
|------------|------------|--------------------------------------------|
| `function` | `Callable` | Run a function in the executor |
| `kwargs` | `Dict` | Keyword arguments to pass to the function. |
#### Adding Tasks
<a id="executor.exit"></a>
### exit
```python
async def exit()
```
Shutdowns the executor. Due to the nature of threadpool executors, shutdown is not usually an immediate process.
This exit function is added as a coroutine function to the bot or backtester during initialization.
| Method | Description |
|--------|-------------|
| `add_function(func, *args, **kwargs)` | Registers a regular callable |
| `add_coroutine(coro, *args, **kwargs)` | Registers an async coroutine |
| `add_strategy(strategy)` | Registers a `Strategy` instance |
<a id="executor.execute"></a>
### execute
```python
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. |
#### Execution
#### Notes:
No matter the number specified, the number of workers will always be greater than equal to the minimum number of
workers required to run all functions, coroutines and strategies added to the executor.
| Method | Description |
|--------|-------------|
| `execute()` | Starts all registered tasks and strategies via the queue |
| `run_coroutine_task(coro, *args, **kwargs)` | Runs a single coroutine task |
#### Shutdown
| Method | Description |
|--------|-------------|
| `sigint_handle(sig, frame)` | Handles SIGINT for graceful shutdown |
| `exit()` | Sets the shutdown flag and stops the queue |
+37 -119
View File
@@ -1,135 +1,53 @@
# History
# history
## Table of contents
- [History](#history.history)
- [\_\_init\_\_](#history.__init__)
- [initialize](#history.initialize)
- [get_deals](#history.get_deals)
- [get_deals_by_ticket](#history.get_deals_by_ticket)
- [get_deals_by_position](#history.get_deals_by_position)
- [get_orders](#history.get_orders)
- [get_orders_by_position](#history.get_orders_by_position)
- [get_orders_by_ticket](#history.get_orders_by_ticket)
`aiomql.lib.history` — Historical deals and orders retrieval.
<a id='history.history'></a>
### 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. | "" |
| `mt5` | `MetaTrader` | MetaTrader instance | None |
| `config` | `Config` | Config instance | None |
## Overview
The `History` class retrieves completed trade deals and orders from the MetaTrader 5 terminal
for a specified date range. Results are cached for efficient filtering and querying.
<a id='history.__init__'></a>
### \_\_init\_\_
```python
def __init__(*, date_from: datetime | float, date_to: datetime | float, group: str = "")
```
Inherits from [`_Base`](../core/base.md).
#### 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. | "" |
## Classes
<a id='history.initialize'></a>
### initialize
```python
async def initialize() -> bool
```
Get deals and orders within the timeframe specified in the constructor.
### `History`
<a id='history.get_deals'></a>
### get_deals
```python
async def get_deals(self) -> tuple[TradeDeal, ...]
```
Get deals from trading history using the parameters set in the constructor.
> Retrieves and caches historical deals and orders.
#### Returns
| Name | Type | Description |
|---------|-------------------------|-----------------------|
| `deals` | `tuple[TradeDeal, ...]` | A list of trade deals |
| Attribute | Type | Description |
|-----------|------|-------------|
| `deals` | `tuple[TradeDeal, ...]` | Cached deals |
| `orders` | `tuple[TradeOrder, ...]` | Cached orders |
| `total_deals` | `int` | Total deal count in range |
| `total_orders` | `int` | Total order count in range |
<a id='history.get_deals_by_ticket'></a>
### get_deals_by_ticket
```python
def get_deals_by_ticket(self, *, ticket: int) -> tuple[TradeDeal, ...]
```
Get deals by ticket number. This filters deals by ticket based on the deals already fetched in initialize.
#### Initialization
#### Parameters
| Name | Type | Description |
|----------|-------|----------------------|
| `ticket` | `int` | Ticket number to get |
| Method | Description |
|--------|-------------|
| `init(date_from, date_to)` | Fetches deals and orders for the date range |
| `get_deals(date_from, date_to)` | Fetches deals only |
| `get_orders(date_from, date_to)` | Fetches orders only |
#### Returns:
| Name | Type | Description |
|---------|-------------------------|------------------------|
| `deals` | `tuple[TradeDeal, ...]` | A tuple of trade deals |
#### Filtering Deals
<a id='history.get_deals_by_position'></a>
### get_deals_by_position
```python
async def get_deals_by_position(self, *, position: int) -> tuple[TradeDeal, ...]
```
Get deals by position
#### Parameters
| Name | Type | Description |
|------------|-------|------------------------|
| `position` | `int` | Position number to get |
| Method | Description |
|--------|-------------|
| `filter_deals_by_symbol(symbol)` | Filter deals by symbol name |
| `filter_deals_by_ticket(ticket)` | Filter deals by ticket number |
| `filter_deals_by_position(position)` | Filter deals by position ID |
| `get_deals_by_position(position)` | Get all deals for a position |
#### Returns
| Name | Type | Description |
|---------|-------------------------|------------------------|
| `deals` | `tuple[TradeDeal, ...]` | A tuple of trade deals |
#### Filtering Orders
<a id='history.get_orders'></a>
### get_orders
```python
async def get_orders(self) -> tuple[TradeOrder, ...]
```
Get orders from trading history using the parameters set in the constructor.
| Method | Description |
|--------|-------------|
| `filter_orders_by_symbol(symbol)` | Filter orders by symbol name |
| `filter_orders_by_ticket(ticket)` | Filter orders by ticket number |
| `filter_orders_by_position(position)` | Filter orders by position ID |
| `get_orders_by_position(position)` | Get all orders for a position |
<a id='history.get_orders_by_position'></a>
### get_orders_by_position
```python
def get_orders_by_position(self, *, position: int) -> tuple[TradeOrder, ...]
```
Get orders by position.
#### Parameters
| Name | Type | Description |
|------------|-------|------------------------|
| `position` | `int` | Position number to get |
## Synchronous API
#### Returns
| Name | Type | Description |
|----------|--------------------------|-------------------------|
| `orders` | `tuple[TradeOrder, ...]` | A tuple of trade orders |
<a id='history.get_orders_by_ticket'></a>
### get_orders_by_ticket
```python
def get_orders_by_ticket(self, *, position: int) -> tuple[TradeOrder, ...]
```
Get orders by ticket number. This filters orders by ticket based on the orders already fetched in initialize.
#### Parameters
| Name | Type | Description |
|----------|-------|----------------------|
| `ticket` | `int` | ticket number to get |
#### Returns
| Name | Type | Description |
|----------|--------------------------|-------------------------|
| `orders` | `tuple[TradeOrder, ...]` | A tuple of trade orders |
A synchronous variant is available in `aiomql.lib.sync.history`.
+43 -153
View File
@@ -1,171 +1,61 @@
# Order
# order
## Table of contents
- [Order](#order.order)
- [\_\_init\_\_](#order.__init__)
- [orders_total](#order.orders_total)
- [get_order](#order.get_pending_order)
- [get_orders](#order.get_pending_orders)
- [check](#order.check)
- [send](#order.send)
- [calc_margin](#order.calc_margin)
- [calc_profit](#order.calc_profit)
- [calc_loss](#order.calc_loss)
- [request](#order.request)
- [modify](#order.modify)
`aiomql.lib.order` — Trade order creation, checking, and sending.
<a id="order.order"></a>
### Order
```python
class Order(_Base, TradeRequest)
```
Trade order related functions and attributes. Subclass of TradeRequest.
## Overview
<a id="order.__init__"></a>
### \_\_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 |
The `Order` class creates and manages trade orders for the MetaTrader 5 terminal. It handles
margin calculations, profit projections, order validation, modification, and cancellation.
<a id="order.orders_total"></a>
```python
async def orders_total()
```
Get the total number of active pending orders.
#### Returns
| Type | Description |
|-------|-------------------------------|
| `int` | total number of active orders |
Inherits from [`_Base`](../core/base.md).
<a id="order.get_pending_order"></a>
### get_pending order
```python
async def get_pending_order(self, ticket: int) -> TradeOrder
```
Get an active pending trade order by ticket.
## Classes
<a id="order.get_pending_orders"></a>
### get_pending_orders
```python
async def get_pending_orders(self, *, ticket: int = 0, symbol: str = '', group: str = '') -> 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.
### `Order`
#### Parameters:
| Name | Type | Description | Default |
|----------|--------|--------------------------------------|---------|
| `ticket` | `int` | Order ticket | 0 |
| `symbol` | `str` | Symbol name | '' |
| `group` | `str` | Group name | '' |
> Creates, validates, and sends trade orders.
#### Returns:
| Type | Description |
|--------------------------|------------------------------------------------------|
| `tuple[TradeOrder, ...]` | A Tuple of active trade orders as TradeOrder objects |
| Attribute | Type | Description |
|-----------|------|-------------|
| `action` | `TradeAction` | Trade action type |
| `type` | `OrderType` | Order type (BUY, SELL, etc.) |
| `symbol` | `str` | Trading instrument |
| `volume` | `float` | Trade volume in lots |
| `price` | `float` | Order price |
| `sl` | `float` | Stop loss level |
| `tp` | `float` | Take profit level |
| `deviation` | `int` | Maximum price deviation |
| `magic` | `int` | Expert Advisor magic number |
| `comment` | `str` | Order comment |
| `type_filling` | `OrderFilling` | Filling policy |
| `type_time` | `OrderTime` | Time-in-force policy |
<a id="order.check"></a>
### check
```python
async def check(**kwargs) -> OrderCheckResult
```
#### Parameters:
| Type | Description |
|--------|----------------------------------------------|
| kwargs | Update the request dict with extra arguments |
#### `request` *(property)*
Check if an order is okay.
Returns the trade request as a dict, filtering out `None` values.
#### Returns:
| Type | Description |
|--------------------|----------------------------|
| `OrderCheckResult` | An OrderCheckResult object |
#### Validation
#### Raises:
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
| Method | Returns | Description |
|--------|---------|-------------|
| `check()` | `OrderCheckResult` | Validates the order, raises `OrderError` on failure |
<a id="order.send"></a>
### send
```python
async def send() -> OrderSendResult
```
Send a request to perform a trading operation from the terminal to the trade server.
#### Execution
#### Returns:
| Type | Description |
|-------------------|---------------------------|
| `OrderSendResult` | An OrderSendResult object |
| Method | Returns | Description |
|--------|---------|-------------|
| `send()` | `OrderSendResult` | Sends the order; retries on requote/timeout |
#### Raises:
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
#### Calculations
<a id="order.calc_margin"></a>
### calc_margin:
```python
async def calc_margin() -> float
```
Return the required margin in the account currency to perform a specified trading operation.
| Method | Returns | Description |
|--------|---------|-------------|
| `calc_margin()` | `float \| None` | Required margin for the order |
| `calc_profit(close_price)` | `float \| None` | Projected profit at a given close price |
#### Returns:
| Type | Description |
|---------|-----------------------------------|
| `float` | Returns float value if successful |
#### Modification
<a id="order.calc_profit"></a>
### 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 |
<a id="order.calc_loss"></a>
### calc_profit
```python
async def calc_loss() -> float
```
Return loss in the account currency for a specified trading operation.
#### Returns
| Type | Description |
|---------|-----------------------------------|
| `float` | Returns float value if successful |
| `None` | If not successful |
<a id="order.request"></a>
### request
```python
@property
async def request() -> dict
```
Return the trade request object as a dict
#### Returns
| Type | Description |
|--------|----------------------------------|
| `dict` | Returns the trade request object |
<a id="order.modify"></a>
### modify
```python
def modify(**kwargs)
```
Modify the order object with keyword arguments.
| Method | Description |
|--------|-------------|
| `modify(**kwargs)` | Modifies a pending order's parameters |
| `cancel()` | Cancels a pending order |
+25 -162
View File
@@ -1,175 +1,38 @@
# Positions
# positions
## Table of contents
- [Positions](#positions.positions)
- [\_\_init\_\_](#positions.__init__)
- [get_positions](#positions.get_positions)
- [get_position_by_ticket](#positions.get_position_by_ticket)
- [get_positions_by_symbol](#positions.get_positions_by_symbol)
- [close](#positions.close)
- [close_position_by_ticket](#positions.close_position_by_ticket)
- [close_position](#positions.close_position)
- [close_all](#positions.close_all)
- [get_total_positions](#positions.get_total_positions)
`aiomql.lib.positions` — Open position management.
<a id="positions.positions"></a>
### Positions
```python
class Positions
```
Get and handle Open positions.
## Overview
#### Attributes
| Name | Type | Description |
|-------------|-----------------------------|-------------------------------------------------------------------------------------|
| `positions` | `tuple[TradePosition, ...]` | Financial instrument name. |
| `mt5` | `MetaTrader` | MetaTrader instance. |
|`total_positions`| `int` | Total number of open positions. Can be set in `get_positions` or `get_total_positions`. |
The `Positions` class provides methods for retrieving, counting, and closing open positions
in the MetaTrader 5 terminal.
<a id="positions.__init__"></a>
### \_\_init\_\_
```python
def __init__()
```
Initialize a position instance
Inherits from [`_Base`](../core/base.md).
## Classes
<a id="positions.get_position"></a>
### get_positions
```python
async def get_positions(*, symbol: str = None, ticket: int = None, group: str = None) -> tuple[TradePosition, ...]:
```
Get open positions, with the ability to filter by symbol, ticket, or group.
### `Positions`
#### Parameters:
| Name | Type | Description |
|----------|-------|-----------------|
| `symbol` | `str` | Symbol |
| `ticket` | `int` | Position ticket |
| `group` | `str` | Group name |
> Manages open positions in MetaTrader 5.
#### Retrieval
#### Returns:
| Type | Description |
|-----------------------------|--------------------------------|
| `tuple[TradePosition, ...]` | A list of open trade positions |
| Method | Returns | Description |
|--------|---------|-------------|
| `positions_get(symbol, group, ticket)` | `tuple[TradePosition, …] \| None` | Get positions matching criteria |
| `positions_total()` | `int` | Total number of open positions |
| `get_by_ticket(ticket)` | `TradePosition \| None` | Get a position by ticket |
| `get_by_symbol(symbol)` | `tuple[TradePosition, …] \| None` | Get positions for a symbol |
#### Closing
<a id="positions.get_position_by_ticket"></a>
### get_position_by_ticket
```python
async def get_position_by_ticket(self, *, ticket: int) -> TradePosition
```
Get a position by ticket id.
| Method | Returns | Description |
|--------|---------|-------------|
| `close(*, ticket, symbol, volume, price, order_type)` | `OrderSendResult` | Close a position |
| `close_all()` | `None` | Close all open positions |
#### Parameters:
| Name | Type | Description |
|----------|-------|-----------------|
| `ticket` | `int` | Position ticket |
#### Counting
#### Returns:
| Type | Description |
|-----------------|----------------|
| `TradePosition` | Trade position |
<a id="positions.get_positions_by_symbol"></a>
### get_positions_by_symbol
```python
async def get_positions_by_symbol(self, *, symbol: str) -> tuple[TradePosition, ...]
```
Filter positions by symbols
#### Parameters:
| Name | Type | Description |
|----------|-------|-------------|
| `symbol` | `str` | Symbol |
#### Returns:
| Type | Description |
|-----------------------------|----------------|
| `tuple[TradePosition, ...]` | Trade position |
<a id="positions.close"></a>
### close
```python
async def close(self, *, ticket: int, symbol: str, price: float, volume: float, order_type: OrderType) -> OrderSendResult:
```
Close a position using its details.
#### Parameters:
| Name | Type | Description |
|--------------|-------------|----------------------------|
| `ticket` | `int` | Position ticket. |
| `symbol` | `str` | Financial instrument name. |
| `price` | `float` | Closing price. |
| `volume` | `float` | Volume to close. |
| `order_type` | `OrderType` | Order type. |
#### Returns:
| Type | Description |
|--------------------|----------------------------------------------------|
| `OrderSendResult ` | The result of the order sent to close the position |
<a id="positions.close_position"></a>
### close_position
```python
async def close_position(self, *, position: TradePosition) -> OrderSendResult:
```
Close a position by position object.
#### Parameters:
| Name | Type | Description |
|------------|-----------------|-----------------|
| `position` | `TradePosition` | Position object |
#### Returns:
| Type | Description |
|-------------------|----------------------------------------------------|
| `OrderSendResult` | The result of the order sent to close the position |
<a id='positions.close_position_by_ticket'></a>
### close_position_by_ticket
```python
async def close_position_by_ticket(self, *, position: TradePosition) -> OrderSendResult:
```
Close a position by position object.
#### Parameters:
| Name | Type | Description |
|------------|-----------------|-----------------|
| `position` | `TradePosition` | Position object |
#### Returns:
| Type | Description |
|-------------------|----------------------------------------------------|
| `OrderSendResult` | The result of the order sent to close the position |
<a id="positions.close_all"></a>
### 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 |
<a id="positions.get_total_positions"></a>
### get_total_positions
```python
async def get_total_positions() -> int
```
Get the total number of open positions and set the `total_positions` attribute.
#### Returns:
| Type | Description |
|-------|--------------------------------------|
| `int` | Return total number of open trades |
| Method | Returns | Description |
|--------|---------|-------------|
| `get_total_positions()` | `int` | Number of open positions |
+25 -74
View File
@@ -1,86 +1,37 @@
# Risk Assessment and Management
# ram
## Table of Contents
- [RAM](#ram.ram)
- [\__init\__](#ram.__init__)
- [get_amount](#ram.get_amount)
- [check_losing_positions](#ram.check_losing_positions)
- [check_open_positions](#ram.check_open_positions)
- [modify_ram](#ram.modify_ram)
`aiomql.lib.ram` — Risk Assessment and Money management.
<a id="ram.ram"></a>
### RAM
```python
class RAM
```
Risk Assessment and Management. You can customize this class based on how you want to manage risk.
## Overview
#### Attributes:
| Name | Type | Description | Default |
|------------------|-----------|---------------------------------------------------|-----------|
| `account` | `Account` | The account object | Account() |
| `risk_to_reward` | `float` | Risk to reward ratio | 2 |
| `risk` | `float` | Percentage of account balance to risk per trade | 1% |
| `fixed_amount` | `float` | A fixed amount to risk per trade | |
| `min_amount` | `float` | Minimum amount to risk per trade | |
| `max_amount` | `float` | Maximum amount to risk per trade | |
| `loss_limit` | `int` | Number of open losing trades to allow at any time | 3 |
| `open_limit` | `int` | Number of open trades to allow at any time | 3 |
The `RAM` class calculates position sizes based on risk parameters and account balance.
It checks open positions against configured limits and determines the volume for new trades.
Inherits from [`_Base`](../core/base.md).
<a id="ram.__init__"></a>
### \_\_init\_\_
```python
def __init__(self, **kwargs):
```
Risk Assessment and Management. All provided keyword arguments are set as attributes.
#### Parameters
| Name | Type | Description | Default |
|------------------|--------|----------------------------------------------------|-----------|
| `kwargs` | `dict` | Keyword arguments to be set as instance attributes | {} |
## Classes
### `RAM`
<a id="ram.get_amount"></a>
### ram.get_amount
```python
async def get_amount() -> float
```
Calculate the amount to risk per trade as a percentage of balance.
> Calculates trade volumes using risk-based sizing.
#### Returns:
| Type | Description |
|---------|-------------------------------------------------------|
| `float` | Amount to risk per trade in terms of account currency |
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| `risk_to_reward` | `float` | `2` | Risk-to-reward ratio |
| `risk` | `float` | `0.01` | Risk per trade as a fraction of balance |
| `min_amount` | `float` | `0` | Minimum trade amount in account currency |
| `max_amount` | `float` | `0` | Maximum trade amount (0 = unlimited) |
| `max_open_positions` | `int` | `0` | Maximum concurrent positions (0 = unlimited) |
| `fixed_amount` | `float` | `0` | Fixed trade amount (overrides risk calculation) |
<a id="ram.check_losing_positions"></a>
### 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.
#### Methods
#### Returns:
| Type | Description |
|--------|---------------------------------------------------------------------------------------|
| `bool` | True if the number of open losing trades is more than the loss limit, False otherwise |
| Method | Returns | Description |
|--------|---------|-------------|
| `check_open_positions()` | `bool` | `True` if under the open-position limit |
| `get_amount()` | `float` | Calculates the trade amount based on risk parameters |
| `calc_volume(symbol, amount, pips, …)` | `float` | Calculates lot size from amount and stop distance |
## Synchronous API
<a id="ram.check_open_positions"></a>
### check_open_positions
```python
async def check_open_positions(self) -> bool:
```
Check if the number of open positions is less than or equal the loss limit.
#### Returns:
| Type | Description |
|--------|---------------------------------------------------------------------------------------|
| `bool` | True if the number of open losing trades is more than the loss limit, False otherwise |
<a id="ram.modify_ram"></a>
### modify_ram
```python
def modify_ram(**kwargs):
```
Modify the RAM attributes. All provided keyword arguments are set as attributes.
Available in `aiomql.lib.sync.ram`.
+23 -68
View File
@@ -1,80 +1,35 @@
# Result
# result
## Table of Contents
- [Result](#result.result)
- [__init__](#result.__init__)
- [save](#result.save)
- [get_data](#result.get_data)
- [to_csv](#result.to_csv)
- [to_json](#result.to_json)
`aiomql.lib.result` — Trade result recording (CSV / JSON / SQL).
## Overview
<a id="result.result"></a>
```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 |
The `Result` class records trade outcomes and strategy parameters to files in CSV, JSON,
or SQL format. It integrates with the `Config` to determine the recording directory and
format.
Inherits from [`_Base`](../core/base.md).
<a id="result.__init__"></a>
### \__init\__
```python
def __init__(*, result: OrderSendResult, parameters: dict = None, name: str = '')
```
Prepare result data for record keeping and analysis.
## Classes
#### 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 |
### `Result`
> Saves trade results to persistent storage.
<a id="result.get_data"></a>
### get_data
```python
def get_data(self) -> dict
```
Get the result data as a dictionary
| Attribute | Type | Description |
|-----------|------|-------------|
| `config` | `Config` | Global configuration |
#### Returns:
| Type | Description |
|--------|-----------------|
| `dict` | The result data |
#### Methods
| Method | Description |
|--------|-------------|
| `save(result, parameters, name)` | Dispatches to the configured format (CSV/JSON/SQL) |
| `save_csv(result, parameters, name)` | Appends a result row to a CSV file |
| `save_json(result, parameters, name)` | Appends a result object to a JSON file |
| `save_sql(result, parameters, name)` | Saves the result to the SQLite database |
| `get_data(result, parameters)` | Prepares a unified dict from result and parameters |
<a id="result.to_save"></a>
### to_save
```python
async def to_save(*, trade_record_mode: Literal["csv", "json"] = None)
```
Save to json or csv depending on the trade record mode.
## Synchronous API
#### Returns:
| Name | Type | Description | Default |
|---------------------|--------------------------|-----------------------|---------|
| `trade_record_mode` | `Literal["csv", "json"]` | The trade record mode | None |
<a id="result.to_csv"></a>
### to_csv
```python
async def to_csv()
```
Record trade results and associated parameters as a csv file
<a id="result.to_json"></a>
### to_json
```python
async def to_json()
```
Record trade results and associated parameters as a json file
```
Available in `aiomql.lib.sync.result`.
+37
View File
@@ -0,0 +1,37 @@
# result_db
`aiomql.lib.result_db` — SQLite-backed trade result storage.
## Overview
The `ResultDB` dataclass stores trade results in a SQLite database via the [`DB`](../core/db.md)
ORM base class. Each instance represents a single trade record with fields for order details,
strategy parameters, and profit/loss.
## Classes
### `ResultDB`
> Dataclass for persisting trade results to SQLite.
Inherits from `DB`. Decorated with `@dataclass`.
| Field | Type | Description |
|-------|------|-------------|
| `id` | `int` | Primary key (auto-incremented) |
| `symbol` | `str` | Trading instrument |
| `order_type` | `str` | Order type string |
| `strategy` | `str` | Strategy name |
| `volume` | `float` | Trade volume |
| `points` | `float` | Profit in points |
| `profit` | `float` | Profit in account currency |
| `actual_profit` | `float` | Actual profit after close |
| `*` | … | Additional strategy-specific fields |
#### Methods
| Method | Description |
|--------|-------------|
| `save(commit, update, data, conn)` | Inserts or updates the record |
| `get(**kwargs)` | Retrieves a single matching record |
| `filter(**kwargs)` | Retrieves all matching records |
+36 -242
View File
@@ -1,259 +1,53 @@
from aiomql import TradePositionfrom aiomql.lib.sessions import Duration
# sessions
# Session and Sessions
Sessions allow you to run a strategy at specific times of the day.
`aiomql.lib.sessions` — Trading session time windows.
## Table of Contents
- [Session](#session)
- [\__init\__](#session.__init__)
- [begin](#session.begin)
- [close](#session.close)
- [action](#session.action)
- [in_session](#session.in_session)
- [duration](#session.duration)
- [close_positions](#session.close_positions)
- [close_all](#session.close_all)
- [close_win](#session.close_win)
- [close_loss](#session.close_loss)
- [close_until](#session.until)
- [Sessions](#sessions.sessions)
- [\__init\__](#sessions.__init__)
- [find](#sessions.find)
- [find_next](#sessions.find_next)
- [check](#sessions.check)
- [delta](#sessions_mod.delta)
- [backtest_sleep](#sessions_mod.backtest_sleep)
## Overview
<a id="session.session"></a>
## Session
```python
class Session
```
A session is a time period between two `datetime.time` objects specified in utc.
Provides `Session` (a single trading window) and `Sessions` (a collection of windows)
for restricting trading to specific hours of the day. Sessions can automatically trigger
actions at their boundaries — e.g. closing all positions when a session ends.
#### 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. | |
## Classes
#### 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.
### `Session`
<a id="session.__init__"></a>
### \__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
#### Parameters:
| 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 |
> Defines a single trading time window.
| Attribute | Type | Description |
|-----------|------|-------------|
| `name` | `str` | Session name |
| `start` | `time` | Session start time |
| `end` | `time` | Session end time |
| `on_start` | `Callable \| None` | Hook called when the session opens |
| `on_end` | `Callable \| None` | Hook called when the session closes |
| `close_all` | `bool` | If `True`, close all positions on session end |
<a id="session.begin"></a>
### begin
```python
async def begin()
```
Call the action specified in on_start or custom_start.
#### Properties
| Property | Returns | Description |
|----------|---------|-------------|
| `duration` | `timedelta` | Length of the session |
| `in_session` | `bool` | `True` if current time is within the window |
<a id="session.close"></a>
### close
```python
async def close()
```
Call the action specified in on_end or custom_end.
---
### `Sessions`
<a id="session.in_session"></a>
### in_session
```python
def in_session() -> bool
```
Check if the current time is within the current session.
> Manages multiple `Session` objects.
| Attribute | Type | Description |
|-----------|------|-------------|
| `sessions` | `list[Session]` | Registered sessions |
<a id="session.duration"></a>
### duration
```python
def duration() -> Duration
```
Get the duration of the session in hours, minutes, and seconds.
#### Methods
| Method | Description |
|--------|-------------|
| `add(session)` | Adds a session |
| `find(name)` | Finds a session by name |
| `check()` | Checks which sessions are active and triggers hooks |
<a id="session.close_positions"></a>
### close_positions
```python
async def close_positions(*, positions: tuple[TradePosition, ...])
```
Close positions in the sessions. This is used by the `close_all` action.
## Synchronous API
#### Parameters:
| Name | Type | Description |
|-------------|-----------------------------|---------------------------------------|
| `positions` | `tuple[TradePosition, ...]` | A tuple of TradePosition objects. |
<a id="session.close_all"></a>
### close_all
```python
async def close_all()
```
Close all open positions
<a id="session.close_win"></a>
### close_win
```python
async def close_win()
```
Close only winning positions
<a id="session.close_loss"></a>
### close_loss
```python
async def close_loss()
```
Close only losing positions
<a id="session.action"></a>
### action
```python
async def action(*, action: Literal["close_all", "close_win", "close_loss", "custom_start", "custom_end"]): pass
```
Used by begin and close to call the action specified.
#### Parameters:
| Name | Type | Description |
|----------|---------------------------------------------------------------------------------|---------------------|
| `action` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start', 'custom_end']` | The action to take. |
<a id="session.until"></a>
### until
```python
def until() -> int
```
Get the seconds until the session starts from the current time.
<a id="sessions.sessions"></a>
## 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 |
<a id="sessions.__init__"></a>
#### \__init\__
```python
def __init__(*sessions: Iterable[Session])
```
Create a Sessions object.
#### Parameters:
| Name | Type | Description |
|------------|---------------------|--------------------------------|
| `sessions` | `Iterable[Session]` | A iterable of Session objects. |
<a id="sessions.find"></a>
### find
```python
def find(*, moment: time = None) -> Session | None
```
Find a session that contains a datetime.time object.
#### Parameters:
| Name | Type | Description | Default |
|----------|--------|-------------------------|---------|
| `moment` | `time` | A datetime.time object. | None |
#### Returns:
| Type | Description |
|-----------|----------------------------------------|
| `Session` | A Session object or None if not found. |
<a id="sessions.find_next"></a>
### find_next
```python
def find_next(*, moment: time = None) -> Session
```
Find the next session that contains a datetime.time object.
#### Parameters:
| Name | Type | Description | Default |
|----------|--------|-------------------------|---------|
| `moment` | `time` | A datetime.time object. | |
#### Returns:
| Type | Description |
|-----------|-------------------|
| `Session` | A Session object. |
<a id="sessions.check"></a>
### check
```python
async def check(): pass
```
Check if the current session has started and if not, wait until it starts.
<a id="sessions_mod.delta"></a>
### delta
```python
def delta(obj: time) -> timedelta: pass
```
Get the timedelta of a datetime.time object.
#### Parameters:
| Name | Type | Description | Default |
|-------|-----------------|-------------------------|---------|
| `obj` | `datetime.time` | A datetime.time object. | None |
#### Returns
| Type | Description |
|-------------|---------------------|
| `timedelta` | A timedelta object. |
<a id="sessions_mod.backtest_sleep"></a>
### backtest_sleep
```python
async def backtest_sleep(secs)
```
Sleep method for backtesting.
Available in `aiomql.lib.sync.sessions`.
+27 -132
View File
@@ -1,144 +1,39 @@
# Strategy
The base class for creating strategies.
# strategy
## Table of Contents
- [Strategy](#strategy.strategy)
- [\__init\__](#strategy.__init__)
- [sleep](#strategy.sleep)
- [delay](#strategy.delay)
- [live_sleep](#strategy.live_sleep)
- [backtest_sleep](#strategy.backtest_sleep)
- [run_strategy](#strategy.run_strategy)
- [live_strategy](#strategy.live_strategy)
- [backtest_strategy](#strategy.backtest_strategy)
- [trade](#strategy.trade)
- [test](#strategy.test)
- [initialize](#strategy.initialize)
`aiomql.lib.strategy` — Strategy base class.
## Overview
<a id="strategy.strategy"></a>
### Strategy
```python
class Strategy(ABC)
```
The base class for creating strategies.
The `Strategy` class is the abstract base for all trading strategies. Subclasses implement
`trade()` to define entry/exit logic. The strategy lifecycle is managed by the
[`Bot`](bot.md) / [`Executor`](executor.md).
#### Attributes:
| Name | Type | Description | Default |
|-----------------------|--------------------------------|------------------------------------------------|---------|
| `name` | `str` | A name for the strategy. | None |
| `symbol` | `Symbol` | The Financial Instrument as a Symbol Object | None |
| `sessions` | `Sessions` | Trading sessions. | None |
| `mt5` | `MetaTrader \| MetaBackTester` | MetaTrader instance. | None |
| `config` | `Config` | Config instance. | None |
| `parameters` | `dict` | A dictionary of parameters for the strategy. | None |
| `backtest_controller` | `BackTesterController` | A controller for the backtester. |
| `current_session` | `Session` | The current trading session |
| `running` | `bool` | A flag to indicate if the strategy is running. | True |
Inherits from [`_Base`](../core/base.md).
## Classes
<a id="strategy.__init__"></a>
### \__init\__
```python
def __init__(*, symbol: Symbol, params: dict = None, sessions: Sessions, name: str = "")
```
Initiate the parameters dict and add name and symbol fields. Use class name as strategy name if name is not provided.
### `Strategy`
#### Parameters:
| Name | Type | Description | Default |
|------------|------------|-----------------------------|---------|
| `symbol` | `Symbol` | The Financial instrument | |
| `params` | `Dict` | Trading strategy parameters | None |
| `sessions` | `Sessions` | Trading sessions | None |
| `name` | `str` | The name of the strategy | "" |
> Abstract base class for trading strategies.
| Attribute | Type | Description |
|-----------|------|-------------|
| `name` | `str` | Strategy name (defaults to class name) |
| `symbol` | `Symbol` | The trading instrument |
| `sessions` | `Sessions \| None` | Optional session restrictions |
| `params` | `dict` | Strategy parameters |
<a id="strategy.sleep"></a>
### sleep
```python
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.
This method calls the `live_sleep` method during live trading or `backtest_sleep`.
#### Lifecycle
#### Parameters:
| Name | Type | Description | Default |
|--------|---------|----------------------------------------------------------------|---------|
| `secs` | `float` | The time in seconds. Usually the timeframe you are trading on. | None |
| Method | Description |
|--------|-------------|
| `__init__(symbol, params, sessions, …)` | Initialises the strategy with a symbol and parameters |
| `init()` | Async setup hook (called once before trading begins) |
| `run()` | Main loop — calls `trade()` repeatedly |
| `sleep(secs)` | Suspends the strategy for a duration |
#### Trading Logic
<a id="strategy.delay"></a>
### delay
```python
async def delay(*, secs: float)
```
Sleep for the needed amount of seconds specified in the parameter.
<a id="strategy.live_sleep"></a>
### live_sleep
```python
async def live_sleep(*, secs: float)
```
Sleep method for live trading
<a id="strategy.backtest_sleep"></a>
### backtest_sleep
```python
async def backtest_sleep(*, secs: float)
```
Sleep method for backtesting
<a id="strategy.trade"></a>
### trade
```python
@abstractmethod
async def trade()
```
Place trades using this method.
Implement this method in your own strategy as you wish.
<a id="strategy.test"></a>
### test
```python
@abstractmethod
async def test()
```
Use for backtesting. If not implemented use the trade method.
<a id="strategy.run_strategy"></a>
### run_strategy
```python
async def run_strategy()
```
Run the strategy by calling the trade or test method repeatedly in a while loop.
This method actually calls the `live_strategy` or `backtest_strategy` depending on the mode.
<a id="strategy.live_strategy"></a>
### live_strategy
```python
async def live_strategy()
```
Runs the strategy in live mode.
<a id="strategy.backtest_strategy"></a>
### backtest_strategy
```python
async def live_strategy()
```
Runs the strategy in backtest mode.
<a id="strategy.initialize"></a>
### initialize
```python
async def initialize()
```
Initialize a strategy
| Method | Description |
|--------|-------------|
| `trade()` | **Abstract** — implement entry/exit logic here |
+34 -346
View File
@@ -1,363 +1,51 @@
# Symbol
Symbol class for handling a financial instrument.
# symbol
## Table of Contents
- [Symbol](#symbol.symbol)
- [info_tick](#symbol.info_tick)
- [symbol_select](#symbol.symbol_select)
- [info](#symbol.info)
- [initialize](#symbol.initialize)
- [initialize_sync](#symbol.initialize_sync)
- [book_add](#symbol.book_add)
- [book_get](#symbol.book_get)
- [book_release](#symbol.book_release)
- [compute_volume](#symbol.compute_volume)
- [convert_currency](#symbol.convert_currency)
- [copy_rates_from](#symbol.copy_rates_from)
- [copy_rates_from_pos](#symbol.copy_rates_from_pos)
- [copy_rates_range](#symbol.copy_rates_range)
- [copy_ticks_from](#symbol.copy_ticks_from)
- [copy_ticks_range](#symbol.copy_ticks_range)
- [check_volume](#symbol.check_volume)
- [round_off_volume](#symbol.round_off_volume)
`aiomql.lib.symbol` — Trading instrument interface.
## Overview
<a id="symbol.symbol"></a>
### Symbol
```python
class Symbol(_Base, 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.
The `Symbol` class represents a financial instrument (forex pair, stock, etc.) and provides
methods for querying market data, selecting symbols, and retrieving rates and ticks.
#### Attributes:
| Name | Type | Description | Default |
|-----------|--------------|---------------------------------------|---------|
| `account` | `Account` | Account instance. | None |
| `tick` | `Tick` | The current price tick of the symbol. | None |
Inherits from [`_Base`](../core/base.md).
#### Notes:
Make sure Symbol is always initialized with a name argument.
## Classes
<a id="symbol.info_tick"></a>
### info_tick
```python
async def info_tick(*, name: str = "") -> Tick
```
Get the current price tick of a financial instrument.
### `Symbol`
#### Parameters:
| Name | Type | Description | Default |
|--------|-------|-------------------------|---------|
| `name` | `str` | The name of the symbol. | '' |
> Interface for a MetaTrader 5 trading instrument.
#### Returns:
| Type | Description |
|--------|----------------------|
| `Tick` | Return a Tick Object |
| Attribute | Type | Description |
|-----------|------|-------------|
| `name` | `str` | Symbol name (e.g. `"EURUSD"`) |
| `select` | `bool` | Whether the symbol is selected in Market Watch |
All `SymbolInfo` fields are available as instance attributes after initialisation.
<a id="symbol.symbol_select"></a>
### 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
#### Initialisation
#### Parameters:
| Name | Type | Description | Default |
|----------|--------|---------------------------------------------------------------------------------------------------------|---------|
| `enable` | `bool` | Switch. Optional unnamed parameter. If 'false', a symbol should be removed from the MarketWatch window. | None |
| Method | Description |
|--------|-------------|
| `init()` | Fetches symbol info from the terminal and sets all attributes |
#### Returns:
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, otherwise False. |
#### Market Data
| Method | Returns | Description |
|--------|---------|-------------|
| `info_tick()` | `Tick` | Current tick for the symbol |
| `copy_rates_from(timeframe, date_from, count)` | `Candles` | Historical bars from a date |
| `copy_rates_from_pos(timeframe, start_pos, count)` | `Candles` | Historical bars from a position |
| `copy_rates_range(timeframe, date_from, date_to)` | `Candles` | Historical bars in a range |
| `copy_ticks_from(date_from, count, flags)` | `Ticks` | Historical ticks from a date |
| `copy_ticks_range(date_from, date_to, flags)` | `Ticks` | Historical ticks in a range |
<a id="symbol.info"></a>
### info
```python
async def info() -> SymbolInfo
```
Get data on the specified financial instrument and update the symbol object properties
#### Helpers
#### Returns:
| Type | Description |
|--------------|--------------------------|
| `SymbolInfo` | SymbolInfo if successful |
| Property | Returns | Description |
|----------|---------|-------------|
| `pip` | `float` | The pip size for the symbol |
| `spread` | `float` | Current bid-ask spread |
#### Raises:
| Exception | Description |
|--------------|---------------------------------------------------|
| `ValueError` | If request was unsuccessful and None was returned |
## Synchronous API
<a id="symbol.initialize"></a>
### initialize
```python
async def initialize() -> bool
```
Initialized the symbol by pulling properties from the terminal
#### Returns:
| Type | Description |
|--------|--------------------------------------------------------|
| `bool` | Returns True if symbol info was successful initialized |
<a id="symbol.initialize_sync"></a>
### initialize_sync
```python
def initialize_sync() -> bool
```
Initialized the symbol by pulling properties from the terminal
#### Returns:
| Type | Description |
|--------|--------------------------------------------------------|
| `bool` | Returns True if symbol info was successful initialized |
<a id="symbol.book_add"></a>
### 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. |
<a id="symbol.book_get"></a>
### 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 |
<a id="symbol.book_release"></a>
### 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. |
<a id="symbol.compute_volume"></a>
### compute_volume
```python
async def compute_volume(self) -> float
```
Computes the volume of a trade based on the amount or any other parameter.
This default implementation returns the minimum volume of the symbol. It is meant to be overridden by a subclass.
#### Returns
| Type | Description |
|---------|---------------------------------|
| `float` | Returns the volume of the trade |
<a id="symbol.check_volume"></a>
### check_volume
```python
async def check_volume(*, volume: float) -> tuple[bool, float]
```
Check if the volume is within the limits of permitted volume for
the symbol. If not, return the nearest limit.
#### Returns:
| Type | Description |
|----------------------|-------------------------------------------------------------------------------|
| `tuple[bool, float]` | True and the input volume if within bounds, else False and the nearest limit. |
<a id="symbol.round_off_volume"></a>
### round_off_volume
```python
async def round_off_volume(*, volume: float, round_down: bool = False) -> float
```
Round off the volume to the nearest volume step.
#### Parameters:
| Name | Type | Description | Default |
|--------------|---------|---------------------------------------------------|---------|
| `volume` | `float` | The volume | |
| `round_down` | `float` | Round up or round down to the nearest volume step | False |
#### Returns:
| Type | Description |
|---------|---------------------------------|
| `float` | Returns the volume of the trade |
<a id="symbol.amount_in_quote_currency"></a>
### amount_in_quote_currency
```python
async def amount_quote_currency(*, amount: float) -> float
```
Convert an amount in the account_currency to the quote currency of the symbol.
#### Parameters:
| Name | Type | Description |
|----------|---------|-----------------------|
| `amount` | `float` | The amount to convert |
<a id="symbol.convert_currency"></a>
### convert_currency
```python
async def convert_currency(*, amount: float, from_currency: str, to_currency: str) -> float
```
Convert from one currency to the other.
#### Parameters:
| Name | Type | Description |
|-----------------|---------|--------------------------------------------------------|
| `amount` | `float` | Amount to convert given in terms of the quote currency |
| `from_currency` | `str` | The currency to convert from |
| `to_currency` | `str` | The currency to convert to |
#### Returns:
| Type | Description |
|---------|--------------------------------------|
| `float` | Amount in terms of the base currency |
<a id="symbol.copy_rates_from"></a>
### 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 |
<a id="symbol.copy_rates_from_pos"></a>
### 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 |
<a id="symbol.copy_rates_range"></a>
### 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 |
<a id="symbol.copy_ticks_from"></a>
### 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 |
<a id="symbol.copy_ticks_range"></a>
### 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 |
Available in `aiomql.lib.sync.symbol`.
+18 -72
View File
@@ -1,84 +1,30 @@
# Terminal
# terminal
## Table of Contents
- [Terminal](#terminal.terminal)
- [initialize](#terminal.initialize)
- [version](#terminal.version)
- [info](#terminal.info)
- [symbols_total](#terminal.symbols_total)
`aiomql.lib.terminal` — Terminal information retrieval.
<a id="terminal.terminal"></a>
### Terminal
```python
class Terminal(_Base, 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.
## Overview
#### Attributes:
| Name | Type | Description | Default |
|-----------|--------------|-------------------------------|---------|
| `version` | `Version` | MetaTrader5 Terminal Version. | None |
The `Terminal` class retrieves information about the MetaTrader 5 terminal, such as its
version, connection status, and data paths.
Inherits from [`_Base`](../core/base.md).
<a id="terminal.initialize"></a>
### 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.
## Classes
#### Returns:
| Type | Description |
|--------|-------------------------------|
| `bool` | True if successful else False |
### `Terminal`
> Retrieves MetaTrader 5 terminal details.
<a id="terminal.version"></a>
### 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
All `TerminalInfo` fields (e.g. `connected`, `trade_allowed`, `name`, `path`, `build`)
are available as instance attributes after initialisation.
#### Returns:
| Type | Description |
|-----------|------------------------------------|
| `Version` | version of tuple as Version object |
#### Methods
#### Raises:
| Exception | Description |
|--------------|--------------------------------------------|
| `ValueError` | If the terminal version cannot be obtained |
| Method | Returns | Description |
|--------|---------|-------------|
| `info()` | `TerminalInfo \| None` | Fetches and caches terminal info |
| `version()` | `tuple[int, int, str] \| None` | Terminal version |
## Synchronous API
<a id="terminal.info"></a>
### 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. |
<a id="terminal.symbols_total"></a>
### 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 |
Available in `aiomql.lib.sync.terminal`.
+43 -144
View File
@@ -1,161 +1,60 @@
# Tick and Ticks
Module for working with price ticks.
# ticks
## Table of Contents
- [Tick](#tick.tick)
- [\_\_init\_\_](#tick.__init__)
- [set_attributes](#tick.set_attributes)
`aiomql.lib.ticks` — Tick-level price data and technical analysis.
- [Ticks](#ticks.ticks)
- [\__init\__](#ticks.__init__)
- [ta](#ticks.ta)
- [ta_lib](#ticks.ta_lib)
- [data](#ticks.data)
- [rename](#ticks.rename)
## Overview
Provides `Tick` (a single tick) and `Ticks` (an ordered collection). Like `Candles`, the
`Ticks` class wraps a `pandas.DataFrame` and integrates with `pandas_ta`.
<a id='tick.tick'></a>
## 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 |
| `index` | `int` | Index of the tick in the input dataframe object. | None |
## Classes
### `Tick`
<a id="tick.__init__"></a>
### \__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
> A single tick (price update).
| Attribute | Type | Description |
|-----------|------|-------------|
| `time` | `int` | Tick time (unix timestamp) |
| `bid` | `float` | Bid price |
| `ask` | `float` | Ask price |
| `last` | `float` | Last price |
| `volume` | `float` | Volume |
| `flags` | `int` | Tick flags |
| `volume_real` | `float` | Real volume |
| `time_msc` | `int` | Tick time in milliseconds |
| `Index` | `int` | Position index within a `Ticks` collection |
<a id="tick.set_attributes"></a>
### set_attributes
```python
def set_attributes(**kwargs)
```
Set attributes from keyword arguments
#### Properties
| Property | Description |
|----------|-------------|
| `dict` | Attribute dictionary |
<a id="tick.dict"></a>
### dict
```python
def dict(exclude: set = None, include: set = None) -> dict
```
Return a dictionary of the tick attributes.
---
#### Parameters:
| Name | Type | Description | Default |
|-----------|-------|-----------------------------------------------------|---------|
| `exclude` | `set` | A set of attributes to exclude from the dictionary. | None |
| `include` | `set` | A set of attributes to include in the dictionary. | None |
### `Ticks`
> Ordered collection of ticks backed by a DataFrame.
<a id="ticks.ticks"></a>
## 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 |
| `time` | `Series` | Time of the last prices update for the symbol | None |
| `bid` | `Series` | Current Bid price | None |
| `ask` | `Series` | Current Ask price | None |
| `last` | `Series` | Price of the last deal (Last) | None |
| `volume` | `Series` | Volume for the current Last price | None |
| `time_msc` | `Series` | Time of the last prices update for the symbol in milliseconds | None |
| `flags` | `Series` | Tick flags | None |
| `volume_real` | `Series` | Volume for the current Last price | None |
| `Index` | `Series` | Custom attribute representing the position of the tick in a sequence | None |
| `index` | `Series` | Custom attribute representing the index of the tick in the DataFrame | None |
| Attribute | Type | Description |
|-----------|------|-------------|
| `data` | `DataFrame` | The underlying tick data |
| `Index` | `Series` | Positional index column |
#### Data Access
<a id="ticks.__init__"></a>
### \__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 |
| Method / Property | Description |
|-------------------|-------------|
| `__getitem__(index)` | Get a `Tick` by position or slice |
| `__len__()` | Number of ticks |
| `__iter__()` | Iterate over `Tick` objects |
| `columns` | DataFrame column names |
| `ta` | Access to `pandas_ta` indicators |
| `rename(inplace=True, **kwargs)` | Rename columns |
#### Technical Analysis
<a id="ticks.ta"></a>
### 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 |
<a id="ticks.ta_lib"></a>
### 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 |
<a id="ticks.data"></a>
### 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. |
<a id="ticks.rename"></a>
### 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 |
| Method | Description |
|--------|-------------|
| `ta_lib(func, *args, **kwargs)` | Run any `pandas_ta` indicator |
+26 -159
View File
@@ -1,171 +1,38 @@
# Trade Records
# trade_records
## Table of contents
- [Trade Records](#trade_records)
- [\_\_init\_\_](#trade_records.__init__)
- [get_csv_records](#trade_records.get_csv_records)
- [get_json_records](#trade_records.get_json_records)
- [read_update_csv](#trade_records.read_update_csv)
- [read_update_json](#trade_records.read_update_json)
- [update_rows](#trade_records.update_rows)
- [update_row](#trade_records.update_row)
- [update_csv_records](#trade_records.update_csv_records)
- [update_json_records](#trade_records.update_json_records)
- [update_csv_record](#trade_records.update_csv_record)
- [update_json_record](#trade_records.update_json_record)
`aiomql.lib.trade_records` — Trade record file management.
<a id="trade_records.trade_records"></a>
### Trade Records
```python
class TradeRecords()
```
This utility class read trade records from csv and json files, and update them based on their closing positions.
Once a trade have been closed, the actual profit and win status will be updated in the file.
## Overview
#### Attributes:
| name | type | description |
|---------------|----------|-------------------------------------------|
| `config` | `Config` | Config object |
| `records_dir` | `Path` | A directory for finding the trade records |
The `TradeRecords` class manages trade record files in CSV, JSON, and SQL formats. It
provides methods for updating stored records with actual profit/loss data from completed
trades.
<a id="trade_records.__init__"></a>
### \__init\__
```python
def __init__(*, records_dir: Path | str = '')
```
Initialize an instance of the class.
Inherits from [`_Base`](../core/base.md).
#### Parameters:
| name | type | description |
|---------------|--------|----------------------------------------------------------------|
| `records_dir` | `Path` | Absolute path to directory containing record of placed trades. |
## Classes
### `TradeRecords`
<a id="trade_records.get_csv_records"></a>
### get_csv_records
```python
async def get_csv_records()
```
Get trade records from records_dir folder.
> Updates and manages trade record files.
#### Yields:
| type | description |
|------|--------------------|
| Path | Trade record files |
| Attribute | Type | Description |
|-----------|------|-------------|
| `config` | `Config` | Global configuration |
#### Methods
<a id="trade_records.get_json_records"></a>
### get_json_records
```python
async def get_json_records()
```
Get trade records from records_dir folder.
| Method | Description |
|--------|-------------|
| `update_rows(records_dir)` | Updates all record files in a directory |
| `update_row(file, row)` | Updates a single record row with actual P/L |
| `update_csv(file)` | Updates records in a CSV file |
| `update_json(file)` | Updates records in a JSON file |
| `update_sql()` | Updates records in the SQLite database |
| `get_actual_profit(order, symbol)` | Calculates actual P/L for a trade |
#### Yields
| type | description |
|------|--------------------|
| Path | Trade record files |
#### Static Methods
<a id="trade_records.read_update_csv"></a>
### 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 |
<a id="trade_records.read_update_json"></a>
### 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 |
<a id="trade_records.update_rows"></a>
### 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. |
<a id="trade_records.update_row"></a>
### 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 |
<a id="trade_records.update_csv_record"></a>
### update_csv_record
```python
async def update_csv_record(*, file: Path | str)
```
Update a single trade record csv file
#### Parameters:
| Name | Type | Description |
|--------|--------|-------------------------|
| `file` | `Path` | A trade record csv file |
<a id="trade_records.update_csv_records"></a>
### update_csv_records
```python
def update_csv_records()
```
Update csv trade records in the records_dir folder.
<a id="trade_records.update_json_record"></a>
### update_csv_record
```python
async def update_json_record(*, file: Path | str)
```
Update a single trade record json file
#### Parameters:
| Name | Type | Description |
|--------|--------|--------------------------|
| `file` | `Path` | A trade record json file |
<a id="trade_records.update_json_records"></a>
### update_json_records
```python
def update_json_records()
```
Update json trade records in the records_dir folder.
| Method | Description |
|--------|-------------|
| `str_to_bool(val)` | Converts `"true"` / `"false"` strings to `bool` |
+29 -168
View File
@@ -1,182 +1,43 @@
# Trader
Trader class module. Handles the creation of an order and the placing of trades
# trader
## Table of Contents
- [Trader](#trader)
- [\_\_init\_\_](#trader.__init__)
- [set_trade_stop_levels_points](#trader.set_trade_stop_levels_points)
- [set_trade_stop_levels_pips](#trader.set_trade_stop_levels_pips)
- [create_order_with_points](#trade.create_order_with_points)
- [create_order_with_sl](#trade.create_order_with_sl)
- [create_order_with_stops](#trade.create_order_with_stops)
- [create_order_no_stops](#trade.create_order_no_stops)
- [send_order](#trader.send_order)
- [check_order](#trader.check_order)
- [record_trade](#trader.record_trade)
- [place_trade](#trader.place_trade)
`aiomql.lib.trader` — Trader base class for order management.
<a name="trader.trader"></a>
### Trader
```python
class Trader()
```
Base class for creating a Trader object. Handles the creation of an order and the placing of trades
## Overview
#### 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 |
| `parameters` | `dict` | A dictionary of parameters associated with the trade. | None |
The `Trader` class is the base for creating and managing trade orders. It brings together
`Symbol`, `RAM`, `Order`, and `Result` to provide a complete workflow for placing trades
with risk management and result recording.
<a name="trader.__init__"></a>
### \_\_init\_\_
```python
def __init__(*, symbol: Symbol, ram: RAM = None)
```
#### Parameters:
| Name | Type | Description | Default |
|----------|----------|-----------------------------------------|---------|
| `symbol` | `Symbol` | The Financial instrument | |
| `ram` | `RAM` | Risk Assessment and Management instance | None |
Inherits from [`_Base`](../core/base.md).
## Classes
<a name="trader.set_trade_stop_levels_pips"></a>
### set_trade_stop_levels_pips
```python
async def set_trade_stop_levels_pips(*, pips: float, risk_to_reward: float = None):
```
Sets the stop loss and take profit for the order. This method uses pips as defined for forex instruments.
### `Trader`
#### Parameters:
| Name | Type | Description | Default |
|------------------|---------|-------------------------------|---------|
| `pips` | `float` | Target pips | |
| `risk_to_reward` | `float` | Optional risk to reward ratio | None |
> Base class for placing risk-managed trades.
| Attribute | Type | Description |
|-----------|------|-------------|
| `symbol` | `Symbol` | The trading instrument |
| `ram` | `RAM` | Risk Assessment and Money manager |
| `order` | `Order` | The current trade order |
| `result` | `Result` | Trade result recorder |
| `parameters` | `dict` | Strategy parameters to record |
<a name="trader.set_trade_stop_levels_points"></a>
### set_trade_stop_levels_points
```python
async def set_trade_stop_levels_points(*, points: float, risk_to_reward: float = None):
```
Sets the stop loss and take profit for the order. This method uses points as defined for forex instruments.
#### Lifecycle
#### Parameters:
| Name | Type | Description | Default |
|------------------|---------|-------------------------------|---------|
| `points` | `float` | Target points | |
| `risk_to_reward` | `float` | Optional risk to reward ratio | None |
| Method | Description |
|--------|-------------|
| `__init__(symbol, ram, params, …)` | Initialises with a symbol and risk parameters |
| `create_order(order_type, …)` | Creates an `Order` with calculated volume and stops |
| `set_stop_levels(order_type, sl, tp)` | Sets stop loss and take profit prices |
#### Trade Placement
<a name="trader.create_order_no_stops"></a>
### create_order_no_stops
```python
async def create_order_no_stops(*, order_type: OrderType, volume: float = None)
```
Create an order without setting stop loss and take profit. Using minimum lot size.
| Method | Description |
|--------|-------------|
| `place_trade(*, order_type, sl, tp, …)` | **Abstract** — subclasses implement to place trades |
#### Parameters:
| Name | Type | Description | Default |
|--------------|-------------|---------------------|---------|
| `order_type` | `OrderType` | The order type | |
| `volume` | `float` | The volume to trade | None |
## Synchronous API
<a name="trader.create_order_with_stops"></a>
### create_order_with_stops
```python
async def create_order_with_stops(*, order_type: OrderType, sl: float, tp: float, amount_to_risk: float = None)
```
Create an order with stop loss and take profit levels. Use the amount to risk per trade to
calculate the volume.
#### Parameters:
| Name | Type | Description | Default |
|------------------|-------------|--------------------|---------|
| `order_type` | `OrderType` | The order type | |
| `sl` | `float` | The stop loss` | |
| `tp` | `float` | The take profit` | |
| `amount_to_risk` | `float` | The amount to risk | None |
<a name="trader.create_order_with_sl"></a>
### create_order_with_sl
```python
async def create_order_with_sl(*, order_type: OrderType, sl: float, amount_to_risk: float = None, risk_to_reward: float = None)
```
Create an order with a given stop_loss level. Use the amount to risk per trade to calculate the volume.
#### Parameters:
| Name | Type | Description | Default |
|------------------|-------------|------------------------------------------|---------|
| `order_type` | `OrderType` | The order type | |
| `sl` | `float` | The stop loss` | |
| `risk_to_reward` | `float` | Risk to reward ratio. Optional parameter | None |
| `amount_to_risk` | `float` | The amount to risk | None |
<a name="trader.create_order_with_points"></a>
### create_order_with_points
```python
async def create_order_with_points(*, order_type: OrderType, points: float, amount_to_risk: float = None, risk_to_reward: float = None)
```
Create an order with specific points to risk. Use the amount to risk per trade to calculate the volume.
#### Parameters:
| Name | Type | Description | Default |
|------------------|-------------|------------------------------------------|---------|
| `order_type` | `OrderType` | The order type | |
| `points` | `float` | Points to risk | |
| `risk_to_reward` | `float` | Risk to reward ratio. Optional parameter | None |
| `amount_to_risk` | `float` | The amount to risk | None |
<a name="trader.send_order"></a>
### send_order
```python
async def send_order() -> OrderSendResult
```
Sends the order to the broker for execution.
#### Returns:
| Type | Description |
|-------------------|----------------------------|
| `OrderSendResult` | The OrderSendResult object |
<a name="trader.check_order"></a>
### check_order
```python
async def check_order() -> OrderCheckResult
```
Checks the status of the order before placing the trade.
#### Returns:
| Type | Description |
|--------------------|-----------------------------|
| `OrderCheckResult` | The OrderCheckResult object |
<a name="trader.record_trade"></a>
### record_trade
```python
async def record_trade(*, result: OrderSendResult, parameters: dict = None, name: str = '')
```
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 | |
| `parameters` | `dict` | parameters to saved instead of the ones in `self.parameters` | None |
| `name` | `str` | Name for the csv or json file | '' |
<a name="trader.place_trade"></a>
### place_trade
```python
@abstractmethod
async def place_trade(self, *args, **kwargs)
```
Places a trade. All traders must implement this method.
Available in `aiomql.lib.sync.trader`.