This commit is contained in:
Ichinga Samuel
2024-10-29 13:04:45 +01:00
parent 9eb0baa85c
commit 4f0150a552
45 changed files with 9896 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
# Account
## Table of Contents
- [Account](#account.Account)
- [\_\_init\_\_](#account.__init__)
- [\_\_aenter\_\_](#account.__aenter__)
- [\_\_aexit\_\_](#account.__aexit__)
- [sign_in](#account.sign_in)
- [refresh](#account.refresh)
- [has_symbol](#account.has_symbol)
- [symbols_get](#account.symbols_get)
<a id="Account"></a>
### Account
```python
class Account(AccountInfo)
```
Singleton class for managing a trading account. A subclass of AccountInfo.
All AccountInfo attributes are available in this class.
#### Attributes
| Name | Type | Description | Default |
|-------------|-------------------|------------------------------------------------------|---------|
| `connected` | `bool` | Status of connection to MetaTrader 5 Terminal | False |
| `symbols` | `set[SymbolInfo]` | A set of available symbols for the financial market. | set() |
<a id="account.__init__"></a>
#### \_\_init\_\_
```python
def __init__(self, *args, **kwargs)
```
Initializes the Account class. Inherits all attributes from the AccountInfo class.
<a id="account.__aenter__"></a>
### __aenter__
```python
async def __aenter__() -> 'Account'
```
Async context manager for the Account class. Connects to a trading account and returns the account instance.
#### Returns:
| Type | Description |
|-----------|----------------------------------|
| `Account` | An instance of the Account class |
#### Raises:
| Exception | Description |
|--------------|----------------|
| `LoginError` | If login fails |
<a id="account.__aexit__"></a>
### __aexit__
```python
async def __aexit__(exc_type, exc_value, traceback)
```
Async context manager for the Account class. Disconnects from the trading account.
<a id="account.sign_in"></a>
### sign_in
```python
async def sign_in() -> bool
```
Connect to a trading account.
#### Returns:
| Type | Description |
|--------|-----------------------------------------|
| `bool` | True if login was successful else False |
<a id="account.refresh"></a>
### refresh
```python
async def refresh()
```
Refreshes the account instance with the latest data from the MetaTrader 5 terminal
<a id="account.has_symbol"></a>
### has_symbol
```python
def has_symbol(symbol: str | Type[SymbolInfo])
```
Checks to see if a symbol is available for a trading account
#### Parameters:
| Name | Type | Description |
|----------|---------------------|--------------------------------------|
| `symbol` | `str`\|`SymbolInfo` | A symbol name or SymbolInfo instance |
#### Returns:
| Type | Description |
|--------|----------------------------------------|
| `bool` | True if symbol is available else False |
<a id="account.symbols_get"></a>
### symbols_get
```python
async def symbols_get() -> set[SymbolInfo]
```
Get all financial instruments from the MetaTrader 5 terminal available for the current account.
#### Returns:
| Type | Description |
|-------------------|-------------------------------|
| `set[SymbolInfo]` | A set of SymbolInfo instances |
+162
View File
@@ -0,0 +1,162 @@
# Bot
## Table of Contents
- [Bot](#bb.Bot)
- [\_\_init\_\_](#bb.__init__)
- [initialize](#bb.initialize)
- [execute](#bb.execute)
- [start](#bb.start)
- [add_coroutine](#bb.add_coroutine)
- [add_function](#bb.add_function)
- [add_strategy](#bb.add_strategy)
- [add_strategies](#bb.add_strategies)
- [add_strategy_all](#bb.add_strategy_all)
- [init_symbols](#bb.init_symbols)
- [init_symbol](#bb.init_symbol]())
- [run_bots](#bb.run_bots)
<a id='bb.Bot'></a>
### Bot
```python
class Bot
```
The bot class. Create a bot instance to run your strategies.
#### Attributes:
| Name | Type | Description | Default |
|------------|----------------------|------------------------------------------|----------|
| `account` | `Account` | Account Object. | None |
| `executor` | `ThreadPoolExecutor` | The default thread executor. | None |
| `symbols` | `set[Symbols]` | A set of symbols for the trading session | set() |
| `config` | `Config` | A Config instance | Config() |
<a id='bb.__init__'></a>
### \_\_init\_\_
```python
def __init__()
```
Initializes the Bot class.
<a id='bb.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.
#### Raises:
| Exception | Description |
|--------------|-------------------------------|
| `SystemExit` | If sign in was not successful |
<a id='bb.execute'></a>
### execute
```python
def execute()
```
Execute the bot. Use this method to run the bot.
<a id='bb.start'></a>
### start
```python
async def start()
```
Initialize the bot and execute it. Similar to calling **execute** method but is asynchronous.
<a id='bb.add_coroutine'></a>
### add_coroutine
```python
def add_coroutine(coro: Coroutine, **kwargs)
```
Add a coroutine to the executor.
#### Parameters:
| Name | Type | Description |
|----------|-------------|--------------------------------------------|
| `coro` | `Coroutine` | A coroutine to run in the executor |
| `kwargs` | `Any` | Keyword arguments to pass to the coroutine |
<a id='bb.add_function'></a>
### add_function
```python
def add_function(func: Callable, **kwargs)
```
Add a function to the executor.
#### Parameters:
| Name | Type | Description |
|----------|------------|-------------------------------------------|
| `func` | `Callable` | A function to run in the executor |
| `kwargs` | `Any` | Keyword arguments to pass to the function |
<a id='bb.add_strategy'></a>
### add_strategy
```python
def add_strategy(strategy: Strategy)
```
Add a strategy to the executor. An added strategy will only run if it's symbol was successfully initialized.
#### Parameters:
| Name | Type | Description |
|------------|------------|-----------------------------------|
| `strategy` | `Strategy` | A Strategy instance to run on bot |
<a id='bb.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='bb.add_strategy_all'></a>
### add_strategy_all
```python
def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None)
```
Use this to run a single strategy on all available instruments in the market using the default parameters
i.e. one set of parameters for all trading symbols
#### Parameters:
| Name | Type | Description |
|------------|------------------|---------------------------------------------|
| `strategy` | `Type[Strategy]` | A Strategy class |
| `params` | `dict` or `None` | A dictionary of parameters for the strategy |
<a id='bb.init_symbols'></a>
### init_symbols
```python
async def init_symbols()
```
Initialize the symbols for the current trading session. This method is called internally by the bot.
<a id='bb.init_symbol'></a>
### init_symbol
```python
async def init_symbol(symbol: Symbol) -> Symbol
```
Initialize a symbol before the beginning of a trading session.
Removes it from the list of symbols if it was not successfully initialized or not available for the account.
#### Parameters:
| Name | Type | Description |
|----------|----------|-------------------|
| `symbol` | `Symbol` | A Symbol instance |
#### Returns:
| Type | Description |
|----------|-------------------|
| `Symbol` | A Symbol instance |
<a id='bb.run_bots'></a>
```python
@classmethod
def run_bots(cls, funcs: dict[Callable: dict] = None, num_workers: int = None):
```
Run multiple functions (scripts, bots) at the same time in parallel with different accounts.
Running multiple functions is useful when you want to run different strategies on different accounts.
The callable can for example be a bot instance that defines its own Config instance within the function scope.
The dictionary should contain the callable as the key and the dictionary of keyword arguments to pass to the callable as
the value. Use the path attribute of the config instance to specify the terminal path of each account.
The num_workers parameter specifies the number of workers to use. If not specified, the number of workers will be the
number of bots.
#### Parameters
| Name | Type | Description |
|---------------|------------------------|---------------------------------------------------------------------------------|
| `funcs` | `dict[Callable: dict]` | A dictionary of callables and their keyword arguments to run as bots |
| `num_workers` | `int` | The number of workers to use. If not specified, the number of bots will be used |
+242
View File
@@ -0,0 +1,242 @@
# Candle and Candles
Candle and Candles classes for handling bars from the MetaTrader 5 terminal.
## Table of Contents
- [Candle](#candle)
- [\_\_init\_\_](#candle.__init__)
- [set_attributes](#candle.set_attributes)
- [is_bullish](#candle.is_bullish)
- [is_bearish](#candle.is_bearish)
- [Candles](#candles)
- [\_\_init\_\_](#candles.__init__)
- [ta](#candles.ta)
- [ta_lib](#candles.ta_lib)
- [data](#candles.data)
- [rename](#candles.rename)
<a id="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.
### Attributes
| Name | Type | Description |
|---------------|---------|-------------------------------------------------------------------------|
| `time` | `int` | Period start time |
| `open` | `int` | Open price |
| `high` | `float` | The highest price of the period |
| `low` | `float` | The lowest price of the period |
| `close` | `float` | Close price |
| `tick_volume` | `float` | Tick volume |
| `real_volume` | `float` | Trade volume |
| `spread` | `float` | Spread |
| `Index` | `int` | Custom attribute representing the position of the candle in a sequence. |
<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. |
#### Raises:
| Exception | Description |
|--------------|-----------------------------------------------|
| `ValueError` | If open, high, low, or close is not provided. |
<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. |
<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 |
<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 |
<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.|
### <a id="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. Add operations between two candles objects or between a
candles object and a candle object are also supported.
### Attributes
The attributes of this class vary depending on the columns of underlying **data** attribute. i.e. each column of the **data**
attribute is an attribute of the class.
| Name | Type | Description |
|---------------|-----------------|-------------------------------------------------------------------|
| `data` | `DataFrame` | The pandas DataFrame containing the data. |
| `Index` | `Series['int']` | A pandas Series of the indexes of all candles in the object |
| `time` | `Series['int']` | A pandas Series of the time of all candles in the object |
| `open` | `Series[float]` | A pandas Series of the opening price of all candles in the object |
| `high` | `Series[float]` | A pandas Series of the high price of all candles in the object |
| `low` | `Series[float]` | A pandas Series of the low price of all candles in the object |
| `close` | `Series[float]` | A pandas Series of the closing price of all candles in the object |
| `tick_volume` | `Series[float]` | A pandas Series of the tick volume of all candles in the object |
| `real_volume` | `Series[float]` | A pandas Series of the real volume of all candles in the object |
| `spread` | `Series[float]` | A pandas Series of the spread of all candles in the object |
| `timeframe` | `TimeFrame` | The timeframe of the candles in the object |
| `Candle` | `Type[Candle]` | The Candle class for representing the candles in the object. |
| `data` | `DataFrame` | A pandas DataFrame of all candles in the object. |
#### Notes
When subclassing this class make sure the Candle attribute is set to your desired candle class.
<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. |
<id="candles.visualize"></a>
### visualize
```python
async def visualize(self, *, count: int = 50, type='candle', savefig: str | dict = None, addplot: dict = None,
style: str = 'charles', ylabel: str = 'Price', title: str = 'Chart', **kwargs)
```
Visualize the candles using the mplfinance library.
#### Parameters:
| Name | Type | Description | Default |
|----------|------------------|-----------------------------------------------------------------------------------------------|---------|
| `count` | `int` | The number of candles to visualize. | 50 |
| `type` | `str` | The type of chart to plot. | 'candle'|
| `savefig`| `str` or `dict` | The path to save the figure or a dictionary of keyword arguments to pass to the savefig method.| None |
| `addplot`| `dict` | A dictionary of keyword arguments to pass to the addplot method. | None |
| `style` | `str` | The style of the chart. | 'charles'|
| `ylabel` | `str` | The label of the y-axis. | 'Price' |
| `title` | `str` | The title of the chart. | 'Chart' |
| `kwargs` | `Any` | Additional keyword arguments to pass to the plot method. | |
<id="candles.make_addplot"></a>
```python
def make_addplot(self, *, count: int = 50, columns: list = None, **kwargs) -> dict
```
Make subplots for adding to the main plot.
#### Parameters:
| Name | Type | Description | Default |
|-----------|--------|-----------------------------------------------------------------------------------------------|---------|
| `count` | `int` | The number of candles to visualize. | 50 |
| `columns` | `list` | The columns to plot. | None |
| `kwargs` | `Any` | Additional keyword arguments to pass to the addplot method. | |
#### Returns:
| Type | Description |
|------|-----------------|
| dict | A makeplot dict |
+102
View File
@@ -0,0 +1,102 @@
# Executor
## Table of Contents
- [Executor](#executor.Executor)
- [__init__](#executor.__init__)
- [add_workers](#executor.add_workers)
- [remove_workers](#executor.remove_workers)
- [add_worker](#executor.add_worker)
- [run](#executor.run)
- [trade](#executor.trade)
- [execute](#executor.execute)
<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 |
| `workers` | `list` | List of strategies. | [] |
| `coroutines` | `dict` | Dictionary of coroutines and keyword arguments | {} |
| `functions` | `dict` | Dictionary of functions and keyword arguments | {} |
<a id="executor.__init__"></a>
#### \_\_init\_\_
```python
def __init__(self):
```
Initialize the executor class.
<a id="executor.add_workers"></a>
### add\_workers
```python
def add_workers(strategies: Sequence[type(Strategy)])
```
Add multiple strategies at once
#### Arguments:
| Name | Type | Description |
|--------------|----------------------------|---------------------------|
| `strategies` | `Sequence[type(Strategy)]` | A sequence of strategies. |
<a id="executor.remove_workers"></a>
### remove\_workers
```python
def remove_workers(*symbols: Sequence[Symbol])
```
Removes any worker running on a symbol not successfully initialized.
#### Arguments:
| Name | Type | Description |
|-----------|--------------------|------------------------|
| `symbols` | `Sequence[Symbol]` | A sequence of symbols. |
<a id="executor.add_worker"></a>
### add\_worker
```python
def add_worker(strategy: type(Strategy))
```
Add a strategy instance to the list of workers
#### Arguments:
| Name | Type | Description |
|------------|------------------|----------------------|
| `strategy` | `type(Strategy)` | A strategy instance. |
<a id="executor.run"></a>
### run
```python
@staticmethod
def run(func: Callable|Coroutine, kwargs: dict)
```
Wrap the input coroutine function with 'asyncio.run' so that it can be executed in a threadpool executor.
#### Arguments:
| Name | Type | Description |
|----------|-----------|--------------------------------------------|
| `func` | `Callable | Coroutine` |A coroutine function.|
| `kwargs` | `Dict` | Keyword arguments to pass to the function. |
<a id="executor.trade"></a>
### trade
```python
def trade(strategy: Strategy)
```
Wrap coroutine trade method of each strategy with 'asyncio.run'.
#### Arguments:
| Name | Type | Description |
|------------|------------|----------------------|
| `strategy` | `Strategy` | A strategy instance. |
<a id="executor.execute"></a>
### execute
```python
async def execute(workers: int = 5)
```
Run the strategies with a threadpool executor.
#### Arguments:
| Name | Type | Description |
|-----------|-------|-----------------------------------------------------------|
| `workers` | `int` | Number of workers to use in executor pool. Defaults to 5. |
#### Notes:
No matter the number specified, the executor will always use a minimum of 5 workers.
+196
View File
@@ -0,0 +1,196 @@
# History
## Table of contents
- [History](#history)
- [\_\_init\_\_](#__init__)
- [init](#init)
- [get_deals](#get_deals)
- [get_deals_ticket](#get_deals_ticket)
- [get_deals_position](#get_deals_position)
- [deals_total](#deals_total)
- [get_orders](#get_orders)
- [get_orders_position](#get_orders_position)
- [get_order_ticket](#get_order_ticket)
- [orders_total](#orders_total)
<a id='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. | "" |
| `ticket` | `int` | Filter for selecting history by ticket number | 0 |
| `position` | `int` | Filter for selecting history deals by position | 0 |
| `initialized` | `bool` | check if initial request has been sent to the terminal to get history. | False |
| `mt5` | `MetaTrader` | MetaTrader instance | None |
| `config` | `Config` | Config instance | None |
<a id='__init__'></a>
### \_\_init\_\_
```python
def __init__(*,
date_from: datetime | float = 0,
date_to: datetime | float = 0,
group: str = "",
ticket: int = 0,
position: int = 0)
```
#### Parameters
| Name | Type | Description | Default |
|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | 0 |
| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | 0 |
| `group` | `str` | Filter for selecting history by symbols. | "" |
| `ticket` | `int` | Filter for selecting history by ticket number | 0 |
| `position` | `int` | Filter for selecting history deals by position | 0 |
<a id='init'></a>
### init
```python
async def init(deals=True, orders=True) -> bool
```
Get history deals and orders
#### Parameters
| Name | Type | Description | Default |
|----------|--------|---------------------------------------------------------------|---------|
| `deals` | `bool` | If true get history deals during initial request to terminal | True |
| `orders` | `bool` | If true get history orders during initial request to terminal | True |
#### Returns
| Name | Type | Description | Default |
|--------|--------|-------------------------------------------------|---------|
| `bool` | `bool` | True if all requests were successful else False | False |
<a id='get_deals'></a>
### get_deals
```python
async def get_deals(self, *, date_from: datetime | int = None, date_to: datetime | int = None, group: str = '',
retries=3) -> list[TradeDeal]
```
#### Parameters:
| Name | Type | Description | Default |
|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | None |
| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | None |
| `group` | `str` | Filter for selecting history by symbols. | "" |
| `retries` | `int` | Number of retries if the request fails. | 3 |
#### Returns:
| Name | Type | Description | Default |
|---------|--------------------|-----------------------|---------|
| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] |
<a id='get_deals_ticket'></a>
### get_deals_ticket
```python
async def get_deals_ticket(self, *, ticket: int) -> tuple[TradeDeal]
```
Get deals by ticket number
#### Parameters:
| Name | Type | Description | Default |
|----------|------|-----------------------|---------|
| `ticket` | `int`| Ticket number to get | 0 |
#### Returns:
| Name | Type | Description | Default |
|---------|--------------------|-----------------------|---------|
| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] |
<a id='get_deals_position'></a>
### get_deals_position
```python
async def get_deals_position(self, *, position: int) -> list[TradeDeal]
```
Get deals by position
#### Parameters:
| Name | Type | Description | Default |
|------------|------|-----------------------|---------|
| `position` | `int`| Position number to get | 0 |
#### Returns:
| Name | Type | Description | Default |
|---------|--------------------|-----------------------|---------|
| `deals` | `tuple[TradeDeal]` | A list of trade deals | [] |
<a id='deals_total'></a>
### deals_total
```python
async def deals_total() -> int
```
Get total number of deals within the specified period in the constructor.
#### Returns
| Name | Type | Description | Default |
|---------------|-------|-----------------------|---------|
| `total_deals` | `int` | Total number of deals | 0 |
<a id='get_orders'></a>
### get_orders
```python
async def get_orders(self, *, date_from: datetime | int = None, date_to: datetime | int = None, group: str = '',
retries=3) -> tuple[TradeOrder]
```
Get orders from trading history using the parameters set in the constructor.
#### Parameters
| Name | Type | Description | Default |
|-------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `date_from` | `datetime\|float` | Date the deals are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to twenty-four hours from the current time in 'utc' | None |
| `date_to` | `datetime\|float` | Date up to which the deals are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" | None |
| `group` | `str` | Filter for selecting history by symbols. | "" |
#### Returns
| Name | Type | Description | Default |
|----------|---------------------|------------------------|---------|
| `orders` | `tuple[TradeOrder]` | A list of trade orders | [] |
<a id='get_orders_position'></a>
### get_orders_position
```python
async def get_orders_position(self, *, position: int) -> tuple[TradeOrder]
```
Get orders by position.
#### Parameters
| Name | Type | Description | Default |
|------------|------|-----------------------|---------|
| `position` | `int`| Position number to get | 0 |
#### Returns
| Name | Type | Description | Default |
|----------|---------------------|------------------------|---------|
| `orders` | `tuple[TradeOrder]` | A list of trade orders | [] |
<a id='get_order_ticket'></a>
### get_order_ticket
```python
async def get_order_ticket(self, ticket: int | None = None) -> TradeOrder
```
Get a single order by ticket number.
#### Parameters
| Name | Type | Description | Default |
|----------|-------|----------------------|---------|
| `ticket` | `int` | Ticket number to get | 0 |
#### Returns
| Name | Type | Description | Default |
|----------|---------------------|------------------------|---------|
| `order` | `TradeOrder` | A single trade order | None |
<a id='orders_total'></a>
### orders_total
```python
async def orders_total() -> int
```
Get total number of orders within the specified period in the constructor.
#### Returns
| Name | Type | Description | Default |
|----------------|-------|---------------------|---------|
| `total_orders` | `int` | Total number orders | 0 |
+133
View File
@@ -0,0 +1,133 @@
# Order
## Table of contents
- [Order](#Order)
- [\_\_init\_\_](#__init__)
- [orders_total](#orders_total)
- [get_order](#get_order)
- [get_orders](#get_orders)
- [check](#check)
- [send](#send)
- [calc_margin](#calc_margin)
- [calc_profit](#calc_profit)
<a id="Order"></a>
### Order
```python
class Order(TradeRequest)
```
Trade order related functions and attributes. Subclass of TradeRequest.
<a id="__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 |
<a id="orders_total"></a>
### <a id=order.Order.orders_total> orders_total
```python
async def orders_total()
```
Get the total number of active orders.
#### Returns
| Type | Description |
|-------|-------------------------------|
| `int` | total number of active orders |
<a id="get_order"></a>
### get_order
```python
async def get_order(self, ticket: int) -> TradeOrder
```
Get an active trade order by ticket.
<a id="get_orders"></a>
### get_orders
```python
async def get_orders(self, *, ticket: int = 0, symbol: str = '', group: str = '', retries=3) -> tuple[TradeOrder]:
```
Get active trade orders. If ticket is provided, it will return the order with the specified ticket.
If symbol is provided, it will return all orders for the specified symbol.
If group is provided, it will return all orders for the specified group.
#### Parameters
| Name | Type | Description | Default |
|----------|--------|--------------------------------------|---------|
| `ticket` | `int` | Order ticket | 0 |
| `symbol` | `str` | Symbol name | '' |
| `group` | `str` | Group name | '' |
#### Returns
| Type | Description |
|---------------------|------------------------------------------------------|
| `tuple[TradeOrder]` | A Tuple of active trade orders as TradeOrder objects |
#### Raises
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
<a id="check"></a>
### check
```python
async def check() -> OrderCheckResult
```
Check funds sufficiency for performing a required trading operation and the possibility of executing it at the current market price.
#### Returns
| Type | Description |
|--------------------|----------------------------|
| `OrderCheckResult` | An OrderCheckResult object |
#### Raises:
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
<a id="send"></a>
### send
```python
async def send() -> OrderSendResult
```
Send a request to perform a trading operation from the terminal to the trade server.
#### Returns
| Type | Description |
|-------------------|---------------------------|
| `OrderSendResult` | An OrderSendResult object |
#### Raises:
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
<a id="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.
#### Returns
| Type | Description |
|---------|-----------------------------------|
| `float` | Returns float value if successful |
#### Raises
| Exception | Description |
|--------------|-------------------|
| `OrderError` | If not successful |
<a id="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 |
+135
View File
@@ -0,0 +1,135 @@
# Positions
## Table of contents
- [Positions](#positions)
- [Attributes](#attributes)
- [\_\_init\_\_](#__init__)
- [positions_total](#positions_total)
- [position_get](#position_get)
- [positions_get](#positions_get)
- [close](#close)
- [close_by](#close_by)
- [close_position](#close_position)
- [close_all](#close_all)
<a id="positions"></a>
### Positions
```python
class Positions
```
Get and handle Open positions.
#### Attributes
| Name | Type | Description | Default |
|----------|--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `symbol` | `str` | Financial instrument name. | "" |
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" |
| `ticket` | `int` | Position ticket. | 0 |
| `mt5` | `MetaTrader` | MetaTrader instance. | None |
<a id="__init__"></a>
### \_\_init\_\_
```python
def __init__(*, symbol: str = "", group: str = "", ticket: int = 0)
```
Get Open Positions.
#### Arguments
| Name | Type | Description | Default |
|----------|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `symbol` | `str` | Financial instrument name. | "" |
| `group` | `str` | The filter for arranging a group of symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" |
| `ticket` | `int` | Position ticket. | 0 |
<a id="positions_total"></a>
### positions_total
```python
async def positions_total() -> int
```
Get the number of open positions.
#### Returns
| Type | Description |
|-------|---------------------------------------|
| `int` | Return total number of open positions |
<a id="positions_get"></a>
### positions_get
```python
async def positions_get(self, symbol: str = '', group: str = '', ticket: int = 0, retries=3) -> list[TradePosition]:
```
Get open positions with the ability to filter by symbol or ticket.
#### Arguments
| Name | Type | Description | Default |
|----------|--------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `symbol` | `str` | Financial instrument name. | "" |
| `group` | `str` | The filter for arranging a group of symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name. | "" |
| `ticket` | `int` | Position ticket. | 0 |
#### Returns
| Type | Description |
|-----------------------|--------------------------------|
| `list[TradePosition]` | A list of open trade positions |
<a id="position_get"></a>
### position_get
```python
async def position_get(self, *, ticket: int) -> TradePosition
```
Get a position by ticket number.
#### Arguments
| Name | Type | Description |
|----------|-------|-----------------|
| `ticket` | `int` | Position ticket |
#### Returns
| Type | Description |
|-----------------|----------------|
| `TradePosition` | Trade position |
<a id="close"></a>
### close
```python
async def close(self, *, ticket: int, symbol: str, price: float, volume: float, order_type: OrderType):
```
Close a position by ticket number.
#### Arguments
| Name | Type | Description | Default |
|--------------|-------------|----------------------------|---------|
| `ticket` | `int` | Position ticket. | |
| `symbol` | `str` | Financial instrument name. | |
| `price` | `float` | Closing price. | |
| `volume` | `float` | Volume to close. | |
| `order_type` | `OrderType` | Order type. | |
<a id="close_by"></a>
### close_by
```python
async def close_by(self, pos: TradePosition):
```
Close a position by position object.
#### Arguments
| Name | Type | Description |
|-------|-----------------|-----------------|
| `pos` | `TradePosition` | Position object |
<a id='close_position'></a>
### close_position
```python
async def close_position(self, *, position: TradePosition):
```
Close a position by position object.
#### Arguments
| Name | Type | Description |
|------------|-----------------|-----------------|
| `position` | `TradePosition` | Position object |
<a id="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 |
+74
View File
@@ -0,0 +1,74 @@
# Risk Assessment and Management
## Table of Contents
- [RAM](#RAM)
- [\_\_init\_\_](#__init__)
- [get\_amount](#get_amount)
- [check_losing_positions](#check_losing_positions)
- [check_risk_level](#check_balance_level)
<a id="RAM"></a>
### RAM
```python
class RAM
```
Risk Assessment and Management. You can customize this class based on how you want to manage risk.
#### Attributes
| Name | Type | Description | Default |
|------------------|---------|--------------------------------------------------------|---------|
| `risk_to_reward` | `float` | Risk to reward ratio | 1 |
| `risk` | `float` | Percentage of account balance to risk per trade | |
| `points` | `float` | A fixed number of points per trade can be fixed here | |
| `pips` | `float` | A fixed number of pips per trade can be fixed here | |
| `min_amount` | `float` | Minimum amount to risk per trade | |
| `max_amount` | `float` | Maximum amount to risk per trade | |
| `risk_level` | `float` | Ratio of free margin to current equity as a percentage | 50 |
| `loss_limit` | `int` | Number of open losing trades to allow at any time | 3 |
<a id="__init__"></a>
### \_\_init\_\_
```python
def __init__(self, *, risk_to_reward: float = 1, risk: float = 0.01, **kwargs):
```
Risk Assessment and Management. All provided keyword arguments are set as attributes.
#### Parameters
| Name | Type | Description | Default |
|------------------|---------|----------------------------------------------------|-----------|
| `risk_to_reward` | `float` | Risk to reward ratio | 1 |
| `risk` | `float` | Percentage of account balance to risk per trade | 0.01 # 1% |
| `kwargs` | `Dict` | Keyword arguments to be set as instance attributes | {} |
<a id="get_amount"></a>
### get\_amount
```python
async def get_amount() -> float
```
Calculate the amount to risk per trade as a percentage of balance.
#### Returns
| Type | Description |
|--------|-------------------------------------------------------|
| float | Amount to risk per trade in terms of account currency |
<a id="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.
#### Returns
| Type | Description |
|------|---------------------------------------------------------------------------------------|
| bool | True if the number of open losing trades is more than the loss limit, False otherwise |
<a id="check_balance_level"></a>
### check\_balance\_level
```python
async def check_balance_level(self) -> bool:
```
Check if the balance level is greater than or equal to the fixed balance level.
#### Returns
| Type | Description |
|------|---------------------------------------------------------------------------------|
| bool | True if the balance level is more than the fixed balance level, False otherwise |
+96
View File
@@ -0,0 +1,96 @@
# Records
## Table of contents
- [Records](#records)
- [\_\_init\_\_](#__init__)
- [get\_records](#get_records)
- [read\_update](#read_update)
- [update\_rows](#update_rows)
- [update\_records](#update_records)
- [update\_record](#update_record)
<a id="records"></a>
### Records
```python
class Records()
```
This utility class read trade records from csv files, and update them based on their closing positions. To use this default
implementation the csv files should at least have the following columns `['order', 'symbol', 'actual_profit', 'win', 'closed']`
Once a trade have been closed, the actual profit and win status will be updated in the csv file.
#### Default Headers
| column | type | description |
|---------------|-------|-------------------------------------------------------|
| order | int | Order id of the trade |
| symbol | str | the name of the Symbol |
| actual_profit | float | The actual profit of the trade, this zero by default |
| win | bool | The win status of the trade, this is False by default |
| closed | bool | The status of the trade, this is False by default |
#### Attributes
| name | type | description |
|-------------|--------|--------------------------------------------------------------|
| records_dir | Path | Absolut path to directory containing record of placed trades |
| config | Config | Config object |
<a id="__init__"></a>
### \_\_init\_\_
```python
def __init__(records_dir: Path | str = '')
```
Initialize an instance of the class
#### Parameters
| name | type | description |
|--------------|------|----------------------------------------------------------------|
| records_dir | Path | Absolute path to directory containing record of placed trades. |
<a id="get_records"></a>
### get\_records
```python
async def get_records()
```
Get trade records from records_dir folder
#### Yields
| type | description |
|------|--------------------|
| Path | Trade record files |
<a id="read_update"></a>
### read\_update
```python
async def read_update(file: Path)
```
Read and update trade records
#### Parameters
| name | type | description |
|------|------|-------------------|
| file | Path | Trade record file |
<a id="update_rows"></a>
### update\_rows
```python
async def update_rows(rows: list[dict]) -> list[dict]
```
Update the rows of entered trades in the csv file with the actual profit.
#### Parameters
| name | type | description |
|------|------------|---------------------------------------------------------------------------|
| rows | list[dict] | A list of dictionaries from the dictionary writer object of the csv file. |
#### Returns
| type | description |
|------------|---------------------------------------------------------------|
| list[dict] | A list of dictionaries with the actual profit and win status. |
<a id="update_records"></a>
### update\_records
```python
async def update_records()
```
Update trade records in the records_dir folder.
<a id="update_record"></a>
### update\_record
```python
async def update_record(file: Path | str)
```
Update a single trade record file.
+60
View File
@@ -0,0 +1,60 @@
# Result
## Table of Contents
- [Result](#result)
- [__init__](#__init__)
- [get_data](#get_data)
- [to_csv](#to_csv)
- [to_json](#to_json)
<a id="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 |
<a id="__init__"></a>
### \_\_init\_\_
```python
def __init__(result: OrderSendResult, parameters: dict = None, name: str = '')
```
Prepare result data for record keeping and analysis.
#### Parameters
| Name | Type | Description |
|--------------|-------------------|-----------------------------------|
| `result` | `OrderSendResult` | The result of the trade |
| `parameters` | `dict` | The parameters used for the trade |
| `name` | `str` | The name of the result object |
<a id="get_data"></a>
### get\_data
```python
def get_data(self) -> dict:
```
Get the result data as a dictionary
#### Returns
| Type | Description |
|--------|-----------------|
| `dict` | The result data |
<a id="to_csv"></a>
### to\_csv
```python
async def to_csv()
```
Record trade results and associated parameters as a csv file
<a id="to_json"></a>
### to\_json
```python
async def to_json()
```
Record trade results and associated parameters as a json file
```
+177
View File
@@ -0,0 +1,177 @@
# Session and Sessions
Sessions allow you to run a strategy at specific times of the day.
## Table of Contents
- [Session](#session)
- [\_\_init\_\_](#session.__init__)
- [begin](#session.begin)
- [close](#session.close)
- [action](#session.action)
- [Sessions](#sessions)
- [\_\_init\_\_](#sessions.__init__)
- [find](#sessions.find)
- [find_next](#sessions.find_next)
- [check](#sessions.check)
- [delta](#delta)
- [until](#until)
<a id="session"></a>
## Session
```python
class Session
```
A session is a time period between two `datetime.time` objects specified in utc.
#### Attributes
| Name | Type | Description | Default |
|----------------|-------------------------------------------------------------------|------------------------------------------------------------------------|---------|
| `start` | `datetime.time` | The start time of the session. | None |
| `end` | `datetime.time` | The end time of the session. | None |
| `on_start` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start']` | The action to take when the session starts. Default is None. | None |
| `on_end` | `Literal['close_all', 'close_win', 'close_loss', 'custom_end']` | The action to take when the session ends. Default is None. | None |
| `custom_start` | `Callable` | A custom function to call when the session starts. Default is None. | None |
| `custom_end` | `Callable` | A custom function to call when the session ends. Default is None. | None |
| `name` | `str` | The name of the session. Default is a combination of start and finish. | |
#### Notes:
The `[close_all, close_win, close_loss]` will affect or open positions in the account irrespective of whether they were
opened during the session or not or even by a strategy using the session. This is because the session is not aware of the
positions opened by the strategy. This will be handled in a future release.
<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.
#### Arguments
| Name | Type | Description | Default |
|----------------|-------------------------------------------------------------------|---------------------------------------------------------------------|---------|
| `start` | `int` \| `datetime.time` | The start time of the session in UTC. | None |
| `end` | `int` \| `datetime.time` | The end time of the session in UTC. | None |
| `on_start` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start']` | The action to take when the session starts. Default is None. | None |
| `on_end` | `Literal['close_all', 'close_win', 'close_loss', 'custom_end']` | The action to take when the session ends. Default is None. | None |
| `custom_start` | `Callable` | A custom function to call when the session starts. Default is None. | None |
| `custom_end` | `Callable` | A custom function to call when the session ends. Default is None. | None |
| `name` | `str` | The name of the session. Default is None. | None |
<a id="session.begin"></a>
### begin
```python
async def begin()
```
Call the action specified in on_start or custom_start.
<a id="session.close"></a>
### close
```python
async def close()
```
Call the action specified in on_end or custom_end.
### action
```python
async def action(action): pass
```
Used by begin and close to call the action specified.
#### Arguments
| Name | Type | Description | Default |
|----------|---------------------------------------------------------------------------------|---------------------|---------|
| `action` | `Literal['close_all', 'close_win', 'close_loss', 'custom_start', 'custom_end']` | The action to take. | None |
<a id="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)
```
Create a Sessions object.
#### Arguments
| Name | Type | Description | Default |
|------------|------------------|-----------------------------|---------|
| `sessions` | `tuple[Session]` | A tuple of Session objects. | None |
<a id="sessions.find"></a>
### find
```python
def find(obj: time) -> Session | None
```
Find a session that contains a datetime.time object.
#### Arguments
| Name | Type | Description | Default |
|-------|-----------------|-------------------------|---------|
| `obj` | `datetime.time` | A datetime.time object. | None |
#### Returns
| Type | Description |
|-----------|----------------------------------------|
| `Session` | A Session object or None if not found. |
<a id="sessions.find_next"></a>
### find\_next
```python
def find_next(obj: time) -> Session
```
Find the next session that contains a datetime.time object.
#### Arguments
| Name | Type | Description | Default |
|-------|-----------------|-------------------------|---------|
| `obj` | `datetime.time` | A datetime.time object. | |
#### Returns
| Type | Description |
|-----------|-------------------|
| `Session` | A Session object. |
<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="delta"></a>
### delta
```python
def delta(obj: time) -> timedelta: pass
```
Get the timedelta of a datetime.time object.
#### Arguments:
| Name | Type | Description | Default |
|-------|-----------------|-------------------------|---------|
| `obj` | `datetime.time` | A datetime.time object. | None |
#### Returns
| Type | Description |
|-------------|---------------------|
| `timedelta` | A timedelta object. |
<a id="until"></a>
### until
```python
def until()
```
Get the seconds until the session starts from the current time.
#### Returns:
| Type | Description |
|-------|---------------------------------------|
| `int` | The seconds until the session starts. |
+65
View File
@@ -0,0 +1,65 @@
# Strategy
The base class for creating strategies.
## Table of Contents
- [Strategy](#strategy)
- [\_\_init\_\_](#init)
- [sleep](#sleep)
- [trade](#trade)
<a id="strategy"></a>
### Strategy
```python
class Strategy(ABC)
```
The base class for creating strategies.
#### Attributes
| Name | Type | Description | Default |
|--------------|--------------|----------------------------------------------|---------|
| `name` | `str` | A name for the strategy. | None |
| `account` | `Account` | Account instance. | None |
| `mt5` | `MetaTrader` | MetaTrader instance. | None |
| `config` | `Config` | Config instance. | None |
| `symbol` | `Symbol` | The Financial Instrument as a Symbol Object | None |
| `parameters` | `Dict` | A dictionary of parameters for the strategy. | None |
| `sessions` | `Sessions` | Trading sessions. | None |
### Notes
Define the name of a strategy as a class attribute. If not provided, the class name will be used as the name.
<a id="init"></a>
### \_\_init\_\_
```python
def __init__(*, symbol: Symbol, params: dict = None, sessions: Sessions)
```
Initiate the parameters dict and add name and symbol fields. Use class name as strategy name if name is not provided.
#### Parameters
| Name | Type | Description | Default |
|------------|------------|-----------------------------|---------|
| `symbol` | `Symbol` | The Financial instrument | None |
| `params` | `Dict` | Trading strategy parameters | None |
| `sessions` | `Sessions` | Trading sessions | None |
<a id="sleep"></a>
### sleep
```python
@staticmethod
async def sleep(secs: float)
```
Sleep for the needed amount of seconds in between requests to the terminal.
computes the accurate amount of time needed to sleep ensuring that the next request is made at the start of
a new bar and making cooperative multitasking possible.
#### Parameters
| Name | Type | Description | Default |
|--------|---------|----------------------------------------------------------------|---------|
| `secs` | `float` | The time in seconds. Usually the timeframe you are trading on. | None |
<a id="trade"></a>
### trade
```python
@abstractmethod
async def trade()
```
Place trades using this method. This is the main method of the strategy.
It will be called by the strategy runner.
+337
View File
@@ -0,0 +1,337 @@
# Symbol
Symbol class for handling a financial instrument.
## Table of Contents
- [Symbol](#Symbol)
- [info_tick](#info_tick)
- [symbol_select](#symbol_select)
- [info](#info)
- [init](#init)
- [book_add](#book_add)
- [book_get](#book_get)
- [book_release](#book_release)
- [compute_volume](#compute_volume)
- [currency_conversion](#currency_conversion)
- [convert_currency](#convert_currency)
- [copy_rates_from](#copy_rates_from)
- [copy_rates_from_pos](#copy_rates_from_pos)
- [copy_rates_range](#copy_rates_range)
- [copy_ticks_from](#copy_ticks_from)
- [copy_ticks_range](#copy_ticks_range)
- [check_volume](#check_volume)
- [round_off_volume](#round_off_volume)
<a id="Symbol"></a>
### Symbol
```python
class Symbol(SymbolInfo)
```
Main class for handling a financial instrument. A subclass of `SymbolInfo` where most of the attributes are defined.
for working with a financial instrument.
#### Attributes
| Name | Type | Description | Default |
|-----------|--------------|---------------------------------------|---------|
| `name` | `str` | The name of the symbol. | None |
| `mt5` | `MetaTrader` | MetaTrader instance. | None |
| `config` | `Config` | Config instance. | None |
| `account` | `Account` | Account instance. | None |
| `tick` | `Tick` | The current price tick of the symbol. | None |
#### Notes
Full properties are on the SymbolInfo Object.
Make sure Symbol is always initialized with a name argument
<a id="info_tick"></a>
### info\_tick
```python
async def info_tick(*, name: str = "") -> Tick
```
Get the current price tick of a financial instrument.
#### Parameters
| Name | Type | Description | Default |
|--------|-------|-------------------------|---------|
| `name` | `str` | The name of the symbol. | '' |
#### Returns
| Type | Description |
|--------|----------------------|
| `Tick` | Return a Tick Object |
#### Raises
| Exception | Description |
|--------------|---------------------------------------------------|
| `ValueError` | If request was unsuccessful and None was returned |
<a id="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
#### Parameters
| Name | Type | Description | Default |
|----------|--------|---------------------------------------------------------------------------------------------------------|---------|
| `enable` | `bool` | Switch. Optional unnamed parameter. If 'false', a symbol should be removed from the MarketWatch window. | None |
#### Returns
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, otherwise False. |
<a id="info"></a>
### info
```python
async def info() -> SymbolInfo
```
Get data on the specified financial instrument and update the symbol object properties
#### Returns
| Type | Description |
|--------------|--------------------------|
| `SymbolInfo` | SymbolInfo if successful |
#### Raises
| Exception | Description |
|--------------|---------------------------------------------------|
| `ValueError` | If request was unsuccessful and None was returned |
<a id="init"></a>
### init
```python
async def init() -> bool
```
Initialized the symbol by pulling properties from the terminal
#### Returns
| Type | Description |
|--------|--------------------------------------------------------|
| `bool` | Returns True if symbol info was successful initialized |
<a id="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="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 |
#### Raises
| Exception | Description |
|--------------|---------------------------------------------------|
| `ValueError` | If request was unsuccessful and None was returned |
<a id="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="compute_volume"></a>
### compute_volume
```python
async def compute_volume(*args, **kwargs) -> float
```
Computes the volume of a trade based on the amount or any other parameter.
This is a dummy method that returns the minimum volume of the symbol. It is meant to be overridden by a subclass.
#### Parameters
| Name | Type | Description | Default |
|--------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| `amount` | `float` | Amount to risk in the trade | None |
| `points` | `float` | Number of pips to target | None |
| `use_limits` | `bool` | If True, the minimum volume is returned if the computed volume is less than the minimum volume and the maximum volume is returned if the computed volume is greater than the maximum volume for the symbol | False |
#### Returns
| Type | Description |
|---------|---------------------------------|
| `float` | Returns the volume of the trade |
<a id="currency_conversion"></a>
### currency\_conversion
```python
async def currency_conversion(*, amount: float, base: str,
quote: str) -> float
```
Convert from one currency to the other. Returns the amount in terms of the base currency.
#### Parameters
| Name | Type | Description | Default |
|----------|---------|--------------------------------------------------------|---------|
| `amount` | `float` | Amount to convert given in terms of the quote currency | None |
| `base` | `str` | The base currency of the pair | None |
| `quote` | `str` | The quote currency of the pair | None |
#### Returns
| Type | Description |
|---------|--------------------------------------|
| `float` | Amount in terms of the base currency |
#### Raises
| Exception | Description |
|--------------|----------------------|
| `ValueError` | If conversion failed |
<a id="convert_currency"></a>
```python
async def convert_currency(self, *, amount: float, base: str, quote: str) -> float:
```
Alias for currency_conversion
<a id="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="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="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="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="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 |
<a id="check_volume"></a>
### check_volume
```python
async def check_volume(*, volume: float) -> tuple[bool, float]
```
Checks if the volume is within the minimum and maximum volume for the symbol. If not, return the nearest limit.
#### Parameters
| Name | Type | Description | Default |
|--------|---------|---------------------|---------|
| volume | `float` | The volume to check | None |
#### Returns
| Type | Description |
|----------------------|-----------------------------------------------------|
| `tuple[bool, float]` | The boolean is True if the volume is within limits. |
<a id="round_off_volume"></a>
### round_off_volume
```python
async def round_off_volume(*, volume: float, round_down: bool = True) -> float
```
Rounds off the volume to the nearest minimum or maximum volume for the symbol.
#### Parameters
| Name | Type | Description | Default |
|--------------|---------|---------------------------|---------|
| `volume` | `float` | The volume to round off | None |
| `round_down` | `bool` | To round_up or round_down | True |
#### Returns
| Type | Description |
|---------|---------------------|
| `float` | The rounded volume. |
+77
View File
@@ -0,0 +1,77 @@
# Terminal
## Table of Contents
- [Terminal](#terminal)
- [initialize](#initialize)
- [version](#version)
- [info](#info)
- [symbols_total](#symbols_total)
<a id="terminal"></a>
### Terminal
```python
class Terminal(TerminalInfo)
```
Terminal Class. Get information about the MetaTrader 5 terminal. The class is a subclass of the TerminalInfo
class. It inherits all the attributes and methods of the TerminalInfo class and adds some useful methods.
#### Attributes
| Name | Type | Description | Default |
|---------------|--------------|------------------------------------------------------------------------------|---------|
| `initialized` | `bool` | check if initial request has been sent to the terminal to get terminal info. | False |
| `mt5` | `MetaTrader` | MetaTrader instance | None |
| `config` | `Config` | Config instance | None |
<a id="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.
#### Returns
| Type | Description |
|--------|-------------------------------|
| `bool` | True if successful else False |
<a id="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
#### Returns
| Type | Description |
|-----------|------------------------------------|
| `Version` | version of tuple as Version object |
#### Raises
| Exception | Description |
|--------------|--------------------------------------------|
| `ValueError` | If the terminal version cannot be obtained |
<a id="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="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 |
+125
View File
@@ -0,0 +1,125 @@
# Tick and Ticks
Module for working with price ticks.
## Table of Contents
- [Tick](#tick)
- [\_\_init\_\_](#tick.__init__)
- [set\_attributes](#tick.set_attributes)
- [Ticks](#ticks)
- [\_\_init\_\_](#ticks.__init__)
- [ta](#ticks.ta)
- [ta\_lib](#ticks.ta_lib)
- [data](#ticks.data)
- [rename](#ticks.rename)
<a id='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 |
<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 id="tick.set_attributes"></a>
### set\_attributes
```python
def set_attributes(**kwargs)
```
Set attributes from keyword arguments
<a id="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 |
<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 |
<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 |
+127
View File
@@ -0,0 +1,127 @@
# Trade Records
## Table of contents
- [Trade Records](#trade_records)
- [\_\_init\_\_](#__init__)
- [get_csv_records](#get_csv_records)
- [get_json_records](#get_json_records)
- [read_update_csv](#read_update_csv)
- [read_update_json](#read_update_json)
- [update_rows](#update_rows)
- [update_row](#update_row)
- [update_csv_records](#update_csv_records)
- [update_json_records](#update_json_records)
- [update_csv_record](#update_csv_record)
- [update_json_record](#update_json_record)
<a id="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.
To use this default implementation the csv or json file should be able to provide the following data.
`['order', 'symbol', 'actual_profit', 'win', 'closed']`
Once a trade have been closed, the actual profit and win status will be updated in the csv file.
#### Default Headers
| column | type | description |
|---------------|-------|-------------------------------------------------------|
| order | int | Order id of the trade |
| symbol | str | the name of the Symbol |
| actual_profit | float | The actual profit of the trade, this zero by default |
| win | bool | The win status of the trade, this is False by default |
| closed | bool | The status of the trade, this is False by default |
#### Attributes
| name | type | description |
|-------------|--------|--------------------------------------------------------------|
| records_dir | Path | Absolut path to directory containing record of placed trades |
| config | Config | Config object |
<a id="__init__"></a>
### \_\_init\_\_
```python
def __init__(records_dir: Path | str = '')
```
Initialize an instance of the class.
#### Parameters
| name | type | description |
|--------------|------|----------------------------------------------------------------|
| records_dir | Path | Absolute path to directory containing record of placed trades. |
<a id="get_csv_records"></a>
### get_csv_records
```python
async def get_csv_records()
```
Get trade records from records_dir folder.
#### Yields
| type | description |
|------|--------------------|
| Path | Trade record files |
<a id="get_json_records"></a>
### get_json_records
```python
async def get_json_records()
```
Get trade records from records_dir folder.
#### Yields
| type | description |
|------|--------------------|
| Path | Trade record files |
<a id="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="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="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="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 |
+113
View File
@@ -0,0 +1,113 @@
# Trader
Trader class module. Handles the creation of an order and the placing of trades
## Table of Contents
- [Trader](#trader)
- [\_\_init\_\_](#__init__)
- [create\_order](#create_order)
- [set\_order\_limits](#set_order_limits)
- [set\_trade\_stop_levels](#set_trade_stop_levels)
- [send\_order](#send_order)
- [check_order](#check_order)
- [record_trade](#record_trade)
- [place\_trade](#place_trade)
<a name="trader"></a>
### Trader
```python
class Trader()
```
Base class for creating a Trader object. Handles the creation of an order and the placing of trades
#### Attributes
| Name | Type | Description | Default |
|----------|----------|-------------------------------------------------------|---------|
| `ram` | `RAM` | Risk Assessment Management System. | None |
| `config` | `Config` | Config instance. | None |
| `order` | `Order` | Order instance. | None |
| `symbol` | `Symbol` | The Financial Instrument | None |
| `params` | `Dict` | A dictionary of parameters associated with the trade. | None |
<a name="init"></a>
### \_\_init\_\_
```python
def __init__(*, symbol: Symbol, ram: RAM = None)
```
#### Parameters
| Name | Type | Description | Default |
|----------|----------|-----------------------------------------|---------|
| `symbol` | `Symbol` | The Financial instrument | None |
| `ram` | `RAM` | Risk Assessment and Management instance | None |
<a name="create_order"></a>
### create\_order
```python
async def create_order(*, order_type: OrderType, `kwargs)
```
Complete the order object with the required values. Creates a simple order.
#### Parameters
| Name | Type | Description | Default |
|--------------|-------------|-------------------------------------------------------|---------|
| `order_type` | `OrderType` | Type of order | None |
| `kwargs` | | keyword arguments as required for the specific trader | |
<a name="set_order_limits"></a>
### set\_order\_limits
```python
async def set_order_limits(pips: float):
```
Sets the stop loss and take profit for the order. This method uses pips as defined for forex instruments.
#### Parameters
| Name | Type | Description | Default |
|--------|---------|-------------|---------|
| `pips` | `float` | Target pips | None |
<a name="set_trade_stop_levels"></a>
### set\_trade\_stop\_levels
```python
async def set_trade_stop_levels(*, points)
```
sets the stop loss and take profit for the order. This method uses points as defined by MetaTrader5 for all symbols.
#### Parameters
| Name | Type | Description | Default |
|----------|---------|---------------|---------|
| `points` | `float` | Target points | None |
<a name="send_order"></a>
### send\_order
```python
async def send_order()
```
Sends the order to the broker for execution. Record the trade.
<a name="check_order"></a>
### check_order
```python
async def check_order()
```
Checks the status of the order before placing the trade.
#### Returns
| Type | Description |
|--------|-----------------------------------|
| `bool` | True if order is valid else False |
<a name="record_trade"></a>
### record_trade
```python
async def record_trade(result: OrderSendResult, parameters: dict = None, name: str = '', exclude: set = None)
```
Records the trade and the order details if `Config.record_trades` is true. Trades are recorded as either json or csv.
#### Parameters
| Name | Type | Description | Default |
|--------------|-------------------|--------------------------------------------------------------|---------|
| `result` | `OrderSendResult` | The result of the placed order | None |
| `parameters` | `dict` | parameters to saved instead of the ones in `self.parameters` | None |
| `name` | `str` | Name for the csv or json file | '' |
| `exclude` | `set` | Set of keys to exclude from the saved parameters | None |
<a name="place_trade"></a>
### place\_trade
```python
@abstractmethod
async def place_trade(self, *args, **kwargs):
```
Places a trade. All traders must implement this method.
+66
View File
@@ -0,0 +1,66 @@
# Utils
Utils is a collection of utility functions that are used throughout the codebase. It is a collection of functions.
## Table of Contents
- [round_off](#round_off)
- [find_bearish_fractal](#find_bearish_fractal)
- [find_bullish_fractal](#find_bullish_fractal)
- [dict_to_string](#dict_to_string)
<a id="round_off"></a>
```python
def round_off(value: float, step: float, round_down: bool = True) -> float:
```
Rounds off a value to the nearest step. If round_down is True, it will round down, otherwise it will round up.
#### Parameters
| Name | Type | Description | Default |
|------------|-------|--------------------------------------------|---------|
| value | float | The value to round off. | |
| step | float | The step to round off to. | |
| round_down | bool | Whether to round down. If False, round up. | True |
#### Returns
| Type | Description |
|-------|------------------------|
| float | The rounded off value. |
```python
def find_bearish_fractal(candles: Candles) -> Candle | None:
```
Finds the most recent bearish fractal in the candles.
#### Parameters
| Name | Type | Description | Default |
|---------|---------|----------------------------------|---------|
| candles | Candles | The candles to search for. | |
#### Returns
| Type | Description |
|--------|----------------------------------|
| Candle | The most recent bearish fractal. |
```python
def find_bullish_fractal(candles: Candles) -> Candle | None:
```
Finds the most recent bullish fractal in the candles.
#### Parameters
| Name | Type | Description | Default |
|---------|---------|----------------------------------|---------|
| candles | Candles | The candles to search for. | |
#### Returns
| Type | Description |
|--------|----------------------------------|
| Candle | The most recent bullish fractal. |
<a id="dict_to_string"></a>
```python
def dict_to_string(data: dict, multi=True) -> str:
```
Converts a dictionary to a string. If multi is True, it will return a multi-line string.
#### Parameters
| Name | Type | Description | Default |
|-------|------|----------------------------------------|---------|
| data | dict | The dictionary to convert to a string. | |
| multi | bool | Whether to return a multi-line string. | True |
#### Returns
| Type | Description |
|------|-----------------------------|
| str | The dictionary as a string. |