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
+109
View File
@@ -0,0 +1,109 @@
# Base Class
## Table of Contents
- [Base](#base)
- [set\_attributes](#base.set_attributes)
- [annotations](#base.annotations)
- [get\_dict](#base.get_dict)
- [class\_vars](#base.class_vars)
- [dict](#base.dict)
<a id="base"></a>
### Base
```python
class Base
```
A base class for all data model classes in the aiomql package. This class provides a set of common methods
and attributes for all data model classes.
#### Class Attributes
| Name | Type | Description | Default |
|----------|--------------|-------------------------------------|---------|
| `mt5` | `MetaTrader` | An instance of the MetaTrader class | |
| `config` | `Config` | An instance of the Config class | |
<a id="base.__init__"></a>
### __init__
```python
def __init__(**kwargs)
```
#### Parameters:
| Name | Type | Description |
|----------|-------|---------------------------------------------------|
| `kwargs` | `Any` | Object attributes and values as keyword arguments |
<a id="base.set_attributes"></a>
### set_attributes
```python
def set_attributes(**kwargs)
```
Set keyword arguments as object attributes. Only sets attributes that have been annotated on the class body.
#### Parameters
| Name | Type | Description |
|----------|-------|---------------------------------------------------|
| `kwargs` | `Any` | Object attributes and values as keyword arguments |
#### Raises
| Exception | Description |
|------------------|-----------------------------------------------------------------------------------|
| `AttributeError` | When assigning an attribute that does not belong to the class or any parent class |
#### Notes
Only sets attributes that have been annotated on the class body.
<a id="base.annotations"></a>
### annotations
```python
@property
@cache
def annotations() -> dict
```
Class annotations from all ancestor classes and the current class.
#### Returns
| Type | Description |
|--------|-----------------------------------|
| `dict` | A dictionary of class annotations |
<a id="base.get_dict"></a>
#### get\_dict
```python
def get_dict(exclude: set = None, include: set = None) -> dict
```
Returns class attributes as a dict, with the ability to filter
#### Parameters
| Name | Type | Description |
|-----------|-------|------------------------------------|
| `exclude` | `set` | A set of attributes to be excluded |
| `include` | `set` | Specific attributes to be returned |
#### Returns
| Type | Description |
|--------|--------------------------------------------|
| `dict` | A dictionary of specified class attributes |
#### Notes
You can only set either of include or exclude. If you set both, include will take precedence
<a id="base.class_vars"></a>
### class\_vars
```python
@property
@cache
def class_vars()
```
Annotated class attributes
#### Returns
| Type | Description |
|--------|-------------------------------------------------------------------------------------------|
| `dict` | A dictionary of available class attributes in all ancestor classes and the current class. |
<a id="base.dict"></a>
### dict
```python
@property
def dict() -> dict
```
All instance and class attributes as a dictionary, except those excluded in the Meta class.
#### Returns
| Type | Description |
|--------|-----------------------------------------------|
| `dict` | A dictionary of instance and class attributes |
+72
View File
@@ -0,0 +1,72 @@
# Config
## Table of Contents
- [Config](#config.Config)
- [account\_info](#config.account_info)
- [load\_config](#config.load_config)
- [create\_records\_dir](#config.create_records_dir)
<a id="config.Config"></a>
```python
class Config
```
A class for handling configuration settings for the aiomql package. A single instance of this class is created and used
per bot instance.
### Class Attributes
| Name | Type | Description | Default |
|------------------|--------------|-----------------------------------------------------|-----------------------------------------------------|
| `record\_trades` | `bool` | Whether to keep record of trades or not. | True |
| `filename` | `str` | Name of the config file | aiomql.json |
| `records\_dir` | `str\| Path` | Path to the directory where trade records are saved | Should be relative to the project root |
| `login` | `str` | Trading account number | |
| `password` | `str` | Trading account password | |
| `server` | `str` | Broker server | |
| `path` | `str\|Path` | Path to terminal file | Absolute |
| `timeout` | `int` | Timeout for terminal connection | |
| `config_dir` | `str` | Directory where the config file is located | Optional. Should be relative to the root directory |
| `state` | `dict` | A global state object | |
| `task_queue` | `Queue` | A global queue for handling tasks | |
| `bot` | `Bot` | The bot instance | Added to the config object after bot initialization |
| `root_dir` | `str` | Root directory of the project | |
#### Notes
By default, the config class looks for a file named aiomql.json.
You can change this by passing the filename keyword argument to the constructor.
By passing reload=True to the load_config method, you can reload and search again for the config file.
<a id="config.account_info"></a>
### account\_info
```python
def account_info() -> dict['login', 'password', 'server']
```
Returns Account login details as found in the config object if available
#### Returns
| Type | Description |
|--------|-------------------------------------------------------|
| `dict` | A dictionary with login, password, and server details |
<a id="config.load_config"></a>
### load\_config
```python
def load_config(self, *, file: str = None, reload: bool = True, filename: str = None, config_dir: str = '')
```
Load configuration settings from a file.
#### Parameters
| Name | Type | Description |
|--------------|--------|-------------------------------------------------------------------------------------------------------------|
| `file` | `str` | The file to load the configuration settings from. If not provided, the default file is used. |
| `reload` | `bool` | Whether to reload the configuration settings or not. |
| `filename` | `str` | The name of the file to load the configuration settings from. If not provided, the default filename is used |
| `config_dir` | `str` | The directory where the configuration file is located. Default is the root directory |
<a id="config.create_records_dir"></a>
### create_records_dir
```python
def create_records_dir(self, *, records_dir: str | Path = 'records'):
```
Create a directory for saving trade records.
#### Parameters
| Name | Type | Description |
|----------------|-------------|-------------------------------------------------------------------|
| `records\_dir` | `str\|Path` | The directory where trade records are saved. Default is 'records' |
+579
View File
@@ -0,0 +1,579 @@
# Constants
MetaTrader 5 constants defined as Enums.
## Table of Contents
- [TradeAction](#TradeAction)
- [OrderFilling](#OrderFilling)
- [OrderTime](#OrderTime)
- [OrderType](#OrderType)
- [opposite](#ordertype.opposite)
- [BookType](#BookType)
- [TimeFrame](#TimeFrame)
- [time](#timeframe.time)
- [get](#timeframe.get)
- [CopyTicks](#CopyTicks)
- [PositionType](#PositionType)
- [PositionReason](#PositionReason)
- [DealType](#DealType)
- [DealEntry](#DealEntry)
- [DealReason](#DealReason)
- [OrderReason](#OrderReason)
- [SymbolChartMode](#SymbolChartMode)
- [SymbolCalcMode](#SymbolCalcMode)
- [SymbolTradeMode](#SymbolTradeMode)
- [SymbolTradeExecution](#SymbolTradeExecution)
- [SymbolSwapMode](#SymbolSwapMode)
- [DayOfWeek](#DayOfWeek)
- [SymbolOrderGTCMode](#SymbolOrderGTCMode)
- [SymbolOptionRight](#SymbolOptionRight)
- [SymbolOptionMode](#SymbolOptionMode)
- [AccountTradeMode](#AccountTradeMode)
- [TickFlag](#TickFlag)
- [TradeRetcode](#TradeRetcode)
- [AccountStopOutMode](#AccountStopOutMode)
- [AccountMarginMode](#AccountMarginMode)
<a id="TradeAction"></a>
## TradeAction
```python
class TradeAction(Repr, IntEnum)
```
The TRADE_REQUEST_ACTION Enum.
### Members
| Name | Value | Description |
|------------|-------|----------------------------------------------------------------------------------------------|
| `DEAL` | 0 | Place a trade order for an immediate execution with the specified parameters (market order). |
| `PENDING` | 1 | Place a pending order with the specified parameters. |
| `SLTP` | 2 | Modify Stop Loss and Take Profit values of an opened position. |
| `MODIFY` | 3 | Modify the parameters of the order placed previously. |
| `REMOVE` | 4 | Delete the pending order placed previously. |
| `CLOSE_BY` | 5 | Close a position by an opposite one. |
<a id="OrderFilling"></a>
## OrderFilling
```python
class OrderFilling(Repr, IntEnum)
```
ORDER_TYPE_FILLING Enum.
### Members
| Name | Value | Description |
|----------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `FILL` | 0 | This execution policy means that an order can be executed only in the specified volume. If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be executed. The desired volume can be made up of several available offers. |
| `FOK` | 1 | This execution policy means that an order can be executed only in the specified volume. If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be executed. The desired volume can be made up of several available offers. |
| `IOC` | 2 | An agreement to execute a deal at the maximum volume available in the market within the volume specified in the order. If the request cannot be filled completely, an order with the available volume will be executed, and the remaining volume will be canceled. |
| `RETURN` | 3 | This policy is used only for market (ORDER_TYPE_BUY and ORDER_TYPE_SELL), limit and stop limit orders (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT,ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT) and only for the symbols with Market or Exchange execution modes. If filled partially, a market or limit order with the remaining volume is not canceled, and is processed further. During activation of the ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT orders, an appropriate limit order ORDER_TYPE_BUY_LIMIT/ORDER_TYPE_SELL_LIMIT with the ORDER_FILLING_RETURN type is created. |
<a id="OrderTime"></a>
## OrderTime
```python
class OrderTime(Repr, IntEnum)
```
ORDER_TIME Enum.
### Members
| Name | Value | Description |
|-----------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `GTC` | 0 | Good till cancel order |
| `DAY` | 1 | Good till current trade day order |
| `SPECIFIED` | 2 | The order is active until the specified date |
| `SPECIFIED_DAY` | 3 | The order is active until 23:59:59 of the specified day. If this time appears to be out of a trading session, the expiration is processed at the nearest trading time. |
<a id="OrderType"></a>
## OrderType
```python
class OrderType(Repr, IntEnum)
```
ORDER_TYPE Enum.
### Members
| Name | Value | Description |
|-------------------|-------|--------------------------------------------------------------------------------------|
| `BUY` | 0 | Market buy order |
| `SELL` | 1 | Market sell order |
| `BUY_LIMIT` | 2 | Buy Limit pending order |
| `SELL_LIMIT` | 3 | Sell Limit pending order |
| `BUY_STOP` | 4 | Buy Stop pending order |
| `SELL_STOP` | 5 | Sell Stop pending order |
| `BUY_STOP_LIMIT` | 6 | Upon reaching the order price, Buy Limit pending order is placed at StopLimit price |
| `SELL_STOP_LIMIT` | 7 | Upon reaching the order price, Sell Limit pending order is placed at StopLimit price |
| `CLOSE_BY` | 8 | Order for closing a position by an opposite one |
### Properties
| Name | Description |
|------------|------------------------------------|
| `opposite` | Gets the opposite of an order type |
<a id="ordertype.opposite"></a>
#### opposite
```python
@property
def opposite()
```
Gets the opposite of an order type for closing an open position
#### Returns
| Type | Description |
|------|--------------------------------------|
| int | integer value of opposite order type |
<a id="BookType"></a>
## BookType
```python
class BookType(Repr, IntEnum)
```
BOOK_TYPE Enum.
### Members
| Name | Value | Description |
|---------------|-------|----------------------|
| `SELL` | 0 | Sell order (Offer) |
| `BUY` | 1 | Buy order (Bid) |
| `SELL_MARKET` | 2 | Sell order by Market |
| `BUY_MARKET` | 3 | Buy order by Market |
<a id="TimeFrame"></a>
## TimeFrame
```python
class TimeFrame(Repr, IntEnum)
```
TIMEFRAME Enum.
### Members
| Name | Value | Description |
|-------|---------|-----------------|
| `M1` | 60 | One Minute |
| `M2` | 120 | Two Minutes |
| `M3` | 180 | Three Minutes |
| `M4` | 240 | Four Minutes |
| `M5` | 300 | Five Minutes |
| `M6` | 360 | Six Minutes |
| `M10` | 600 | Ten Minutes |
| `M15` | 900 | Fifteen Minutes |
| `M20` | 1200 | Twenty Minutes |
| `M30` | 1800 | Thirty Minutes |
| `H1` | 3600 | One Hour |
| `H2` | 7200 | Two Hours |
| `H3` | 10800 | Three Hours |
| `H4` | 14400 | Four Hours |
| `H6` | 21600 | Six Hours |
| `H8` | 28800 | Eight Hours |
| `D1` | 86400 | One Day |
| `W1` | 604800 | One Week |
| `MN1` | 2592000 | One Month |
<a id="timeframe.get"></a>
### get
```python
@classmethod
def get(cls, time: int) -> 'TimeFrame':
```
Gets the TIMEFRAME enum value from a time in seconds
#### Parameters
| Name | Type | Description |
|-------|------|----------------------|
| time | int | The time in seconds |
#### Returns
| Type | Description |
|------------|--------------------------------------|
| TimeFrame | The TIMEFRAME enum value |
<a id="timeframe.time"></a>
### time
```python
@property
def time()
```
The number of seconds in a TIMEFRAME
#### Returns
| Type | Description |
|------|--------------------------------------|
| int | The number of seconds in a TIMEFRAME |
<a id="TimeFrame.example"></a>
### Example
```python
t = TimeFrame.H1
print(t.seconds) # 3600
```
<a id="CopyTicks"></a>
## CopyTicks
```python
class CopyTicks(Repr, IntEnum)
```
COPY_TICKS Enum. This defines the types of ticks that can be requested using the copy_ticks_from() and
copy_ticks_range() functions.
### Members
| Name | Value | Description |
|---------|-------|---------------------------------------------------|
| `ALL` | 0 | All ticks |
| `INFO` | 1 | Ticks containing Bid and/or Ask price changes |
| `TRADE` | 2 | Ticks containing Last and/or Volume price changes |
<a id="PositionType"></a>
## PositionType
```python
class PositionType(Repr, IntEnum)
```
POSITION_TYPE Enum. Direction of an open position (buy or sell)
### Members
| Name | Value | Description |
|--------|-------|-------------|
| `BUY` | 0 | Buy |
| `SELL` | 1 | Sell |
<a id="PositionReason"></a>
## PositionReason
```python
class PositionReason(Repr, IntEnum)
```
POSITION_REASON Enum. The reason for opening a position is contained in the POSITION_REASON Enum
### Members
| Name | Value | Description |
|----------|-------|------------------------------------------------------------------------------------------------|
| `CLIENT` | 0 | The position was opened as a result of activation of an order placed from a desktop terminal |
| `MOBILE` | 1 | The position was opened as a result of activation of an order placed from a mobile application |
| `WEB` | 2 | The position was opened as a result of activation of an order placed from the web platform |
| `EXPERT` | 3 | The position was opened as a result of activation of an order placed from an MQL5 program |
<a id="DealType"></a>
## DealType
```python
class DealType(Repr, IntEnum)
```
DEAL_TYPE enum. Each deal is characterized by a type, allowed values are enumerated in this enum
### Members
| Name | Value | Description |
|----------------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `BUY` | 0 | Buy |
| `SELL` | 1 | Sell |
| `BALANCE` | 2 | Balance |
| `CREDIT` | 3 | Credit |
| `CHARGE` | 4 | Additional Charge |
| `CORRECTION` | 5 | Correction |
| `BONUS` | 6 | Bonus |
| `COMMISSION` | 7 | Additional Commission |
| `COMMISSION_DAILY` | 8 | Daily Commission |
| `COMMISSION_MONTHLY` | 9 | Monthly Commission |
| `COMMISSION_AGENT_DAILY` | 10 | Daily Agent Commission |
| `COMMISSION_AGENT_MONTHLY` | 11 | Monthly Agent Commission |
| `INTEREST` | 12 | Interest Rate |
| `DEAL_DIVIDEND` | 13 | Dividend Operations |
| `DEAL_DIVIDEND_FRANKED` | 14 | Franked (non-taxable) dividend operations |
| `DEAL_TAX` | 15 | Tax Charges |
| `BUY_CANCELED` | 16 | Canceled buy deal. There can be a situation when a previously executed buy deal is canceled. In this case, the type of the previously executed deal (DEAL_TYPE_BUY) is changed to DEAL_TYPE_BUY_CANCELED, and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation |
| `SELL_CANCELED` | 17 | Canceled sell deal. There can be a situation when a previously executed sell deal is canceled. In this case, the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation. |
<a id="DealEntry"></a>
## DealEntry
```python
class DealEntry(Repr, IntEnum)
```
DEAL_ENTRY Enum. Deals differ not only in their types set in DEAL_TYPE enum, but also in the way they change
positions. This can be a simple position opening, or accumulation of a previously opened position (market entering),
position closing by an opposite deal of a corresponding volume (market exiting), or position reversing, if the
opposite-direction deal covers the volume of the previously opened position.
### Members
| Name | Value | Description |
|----------|-------|-------------------------------------|
| `IN` | 0 | Entry In |
| `OUT` | 1 | Entry Out |
| `INOUT` | 2 | Reverse |
| `OUT_BY` | 3 | Close a position by an opposite one |
<a id="DealReason"></a>
## DealReason
```python
class DealReason(Repr, IntEnum)
```
DEAL_REASON Enum. The reason for deal execution is contained in the DEAL_REASON property. A deal can be executed
as a result of triggering of an order placed from a mobile application or an MQL5 program, as well as as a result
of the StopOut event, variation margin calculation, etc.
### Members
| Name | Value | Description |
|------------|-------|--------------------------------------------------------------------------------------------------------------------------------|
| `CLIENT` | 0 | The deal was executed as a result of activation of an order placed from a desktop terminal |
| `MOBILE` | 1 | The deal was executed as a result of activation of an order placed from a desktop terminal |
| `WEB` | 2 | The deal was executed as a result of activation of an order placed from the web platform |
| `EXPERT` | 3 | The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script |
| `SL` | 4 | The deal was executed as a result of Stop Loss activation |
| `TP` | 5 | The deal was executed as a result of Take Profit activation |
| `SO` | 6 | The deal was executed as a result of the Stop Out event |
| `ROLLOVER` | 7 | The deal was executed due to a rollover |
| `VMARGIN` | 8 | The deal was executed after charging the variation margin |
| `SPLIT` | 9 | The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement |
<a id="OrderReason"></a>
## OrderReason
```python
class OrderReason(Repr, IntEnum)
```
ORDER_REASON Enum.
### Members
| Name | Value | Description |
|----------|-------|----------------------------------------------------------------------------------|
| `CLIENT` | 0 | The order was placed from a desktop terminal |
| `MOBILE` | 1 | The order was placed from a mobile application |
| `WEB` | 2 | The order was placed from a web platform |
| `EXPERT` | 3 | The order was placed from an MQL5-program, i.e. by an Expert Advisor or a script |
| `SL` | 4 | The order was placed as a result of Stop Loss activation |
| `TP` | 5 | The order was placed as a result of Take Profit activation |
| `SO` | 6 | The order was placed as a result of the Stop Out event |
<a id="SymbolChartMode"></a>
## SymbolChartMode
```python
class SymbolChartMode(Repr, IntEnum)
```
SYMBOL_CHART_MODE Enum. A symbol price chart can be based on Bid or Last prices. The price selected for symbol
charts also affects the generation and display of bars in the terminal.
Possible values of the SYMBOL_CHART_MODE property are described in this enum
### Members
| Name | Value | Description |
|--------|-------|-------------------------------|
| `BID` | 0 | Bars are based on Bid prices |
| `LAST` | 1 | Bars are based on last prices |
<a id="SymbolCalcMode"></a>
## SymbolCalcMode
```python
class SymbolCalcMode(Repr, IntEnum)
```
SYMBOL_CALC_MODE Enum. The SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin
requirements for a symbol are calculated.
### Members
| Name | Value | Description |
|-----------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `FOREX` | 0 | Forex mode - calculation of profit and margin for Forex |
| `FOREX_NO_LEVERAGE` | 1 | Forex No Leverage mode calculation of profit and margin for Forex symbols without taking into account the leverage |
| `FUTURES` | 2 | Futures mode - calculation of margin and profit for futures |
| `CFD` | 3 | CFD mode - calculation of margin and profit for CFD |
| `CFDINDEX` | 4 | CFD index mode - calculation of margin and profit for CFD by indexes |
| `CFDLEVERAGE` | 5 | CFD Leverage mode - calculation of margin and profit for CFD at leverage trading |
| `EXCH_STOCKS` | 6 | Calculation of margin and profit for trading securities on a stock exchange |
| `EXCH_FUTURES` | 7 | Calculation of margin and profit for trading futures contracts on a stock exchange |
| `EXCH_OPTIONS` | 8 | value is 34 |
| `EXCH_OPTIONS_MARGIN` | 9 | value is 36 |
| `EXCH_BONDS` | 10 | Exchange Bonds mode calculation of margin and profit for trading bonds on a stock exchange |
| `EXCH_STOCKS_MOEX` | 11 | Exchange MOEX Stocks mode calculation of margin and profit for trading securities on MOEX |
| `EXCH_BONDS_MOEX` | 12 | Exchange MOEX Bonds mode calculation of margin and profit for trading bonds on MOEX |
| `SERV_COLLATERAL` | 13 | Collateral mode - a symbol is used as a non-tradable asset on a trading account. The market value of an open position is calculated based on the volume, current market price, contract size and liquidity ratio. The value is included into Assets, which are added to Equity. Open positions of such symbols increase the Free Margin amount and are used as additional margin (collateral) for open positions |
<a id="SymbolTradeMode"></a>
## SymbolTradeMode
```python
class SymbolTradeMode(Repr, IntEnum)
```
SYMBOL_TRADE_MODE Enum. There are several symbol trading modes. Information about trading modes of a certain
symbol is reflected in the values this enumeration
### Members
| Name | Value | Description |
|-------------|-------|----------------------------------------|
| `DISABLED` | 0 | Trade is disabled for the symbol |
| `LONGONLY` | 1 | Allowed only long positions |
| `SHORTONLY` | 2 | Allowed only short positions |
| `CLOSEONLY` | 3 | Allowed only position close operations |
| `FULL` | 4 | No trade restrictions |
<a id="SymbolTradeExecution"></a>
## SymbolTradeExecution
```python
class SymbolTradeExecution(Repr, IntEnum)
```
SYMBOL_TRADE_EXECUTION Enum. The modes, or execution policies, define the rules for cases when the price has
changed or the requested volume cannot be completely fulfilled at the moment.
### Members
| Name | Value | Description |
|------------|-------|---------------------------------------------------------------------------------------------|
| `REQUEST` | 0 | Executing a market order at the price previously received from the broker |
| `INSTANT` | 1 | Executing a market order at the specified price immediately |
| `MARKET` | 2 | A broker makes a decision about the order execution price without any additional discussion |
| `EXCHANGE` | 3 | Trade operations are executed at the prices of the current market offers |
<a id="SymbolSwapMode"></a>
## SymbolSwapMode
```python
class SymbolSwapMode(Repr, IntEnum)
```
SYMBOL_SWAP_MODE Enum. Methods of swap calculation at position transfer are specified in enumeration
ENUM_SYMBOL_SWAP_MODE. The method of swap calculation determines the units of measure of the SYMBOL_SWAP_LONG and
SYMBOL_SWAP_SHORT parameters. For example, if swaps are charged in the client deposit currency, then the values of
those parameters are specified as an amount of money in the client deposit currency.
### Members
| Name | Value | Description |
|--------------------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `DISABLED` | 0 | Swaps disabled (no swaps) |
| `POINTS` | 1 | Swaps are charged in points |
| `CURRENCY_SYMBOL` | 2 | Swaps are charged in money in base currency of the symbol |
| `CURRENCY_MARGIN` | 3 | Swaps are charged in money in margin currency of the symbol |
| `CURRENCY_DEPOSIT` | 4 | Swaps are charged in money, in client deposit currency |
| `INTEREST_CURRENT` | 5 | Swaps are charged as the specified annual interest from the instrument price at calculation of swap (standard bank year is 360 days) |
| `INTEREST_OPEN` | 6 | Swaps are charged as the specified annual interest from the open price of position (standard bank year is 360 days) |
| `REOPEN_CURRENT` | 7 | Swaps are charged by reopening positions. At the end of a trading day the position is closed. Next day it is reopened by the close price +/- specified number of points (parameters SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT) |
| `REOPEN_BID` | 8 | Swaps are charged by reopening positions. At the end of a trading day the position is closed. Next day it is reopened by the current Bid price +/- specified number of points (parameters SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT) |
<a id="DayOfWeek"></a>
## DayOfWeek
```python
class DayOfWeek(Repr, IntEnum)
```
DAY_OF_WEEK Enum.
### Members
| Name | Value | Description |
|-------------|-------|-------------|
| `SUNDAY` | 0 | Sunday |
| `MONDAY` | 1 | Monday |
| `TUESDAY` | 2 | Tuesday |
| `WEDNESDAY` | 3 | Wednesday |
| `THURSDAY` | 4 | Thursday |
| `FRIDAY` | 5 | Friday |
| `SATURDAY` | 6 | Saturday |
<a id="SymbolOrderGTCMode"></a>
## SymbolOrderGTCMode
```python
class SymbolOrderGTCMode(Repr, IntEnum)
```
SYMBOL_ORDER_GTC_MODE Enum. If the SYMBOL_EXPIRATION_MODE property is set to SYMBOL_EXPIRATION_GTC
(good till canceled), the expiration of pending orders, as well as of
Stop Loss/Take Profit orders should be additionally set using the ENUM_SYMBOL_ORDER_GTC_MODE enumeration.
### Members
| Name | Value | Description |
|------------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------|
| `GTC` | 0 | Pending orders and Stop Loss/Take Profit levels are valid for an unlimited period |
| `DAILY` | 1 | Orders are valid during one trading day. At the end of the day, all Stop Loss and Take Profit levels, as well as pending orders are deleted. |
| `DAILY_NO_STOPS` | 2 | When a trade day changes, only pending orders are deleted, while Stop Loss and Take Profit levels are preserved |
<a id="SymbolOptionRight"></a>
## SymbolOptionRight
```python
class SymbolOptionRight(Repr, IntEnum)
```
SYMBOL_OPTION_RIGHT Enum. An option is a contract, which gives the right, but not the obligation,
to buy or sell an underlying asset (goods, stocks, futures, etc.) at a specified price on or before a specific date.
The following enumerations describe option properties, including the option type and the right arising from it.
### Members
| Name | Value | Description |
|--------|-------|-----------------------------------------------------------------------------------------------|
| `CALL` | 0 | A call option gives you the right to buy an asset at a specified price. |
| `PUT` | 1 | A put option gives you the right to sell an asset at a specified price. |
<a id="SymbolOptionMode"></a>
## SymbolOptionMode
```python
class SymbolOptionMode(Repr, IntEnum)
```
SYMBOL_OPTION_MODE Enum.
### Members
| Name | Value | Description |
|------------|-------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| `EUROPEAN` | 0 | European option may only be exercised on a specified date (expiration, execution date, delivery date) |
| `AMERICAN` | 1 | American option may be exercised on any trading day or before expiry. The period within which a buyer can exercise the option is specified for it. |
<a id="AccountTradeMode"></a>
## AccountTradeMode
```python
class AccountTradeMode(Repr, IntEnum)
```
ACCOUNT_TRADE_MODE Enum. There are several types of accounts that can be opened on a trade server.
The type of account on which an MQL5 program is running can be found out using
the ENUM_ACCOUNT_TRADE_MODE enumeration.
### Members
| Name | Value | Description |
|-----------|-------|-----------------|
| `DEMO` | 0 | Demo account |
| `CONTEST` | 1 | Contest account |
| `REAL` | 2 | Real Account |
<a id="TickFlag"></a>
## TickFlag
```python
class TickFlag(Repr, IntFlag)
```
TICK_FLAG Enum. TICK_FLAG defines possible flags for ticks. These flags are used to describe ticks obtained by the
copy_ticks_from() and copy_ticks_range() functions.
### Members
| Name | Value | Description |
|----------|-------|-------------------------|
| `BID` | 2 | Bid price changed |
| `ASK` | 4 | Ask price changed |
| `LAST` | 8 | Last price changed |
| `VOLUME` | 16 | Volume changed |
| `BUY` | 32 | last Buy price changed |
| `SELL` | 64 | last Sell price changed |
<a id="TradeRetcode"></a>
## TradeRetcode
```python
class TradeRetcode(Repr, IntEnum)
```
TRADE_RETCODE Enum. Return codes for order send/check operations
### Members
| Name | Value | Description |
|------------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------|
| `OK` | 10009 | OK |
| `REQUOTE` | 10004 | Requote |
| `REJECT` | 10006 | Reject |
| `CANCEL` | 10007 | Cancel |
| `PLACED` | 10008 | Placed |
| `DONE` | 10009 | Done |
| `DONE_PARTIAL` | 10010 | Done Partial |
| `ERROR` | 10011 | Error |
| `TIMEOUT` | 10012 | Timeout |
| `INVALID` | 10013 | Invalid |
| `INVALID_VOLUME` | 10014 | Invalid Volume |
| `INVALID_PRICE` | 10015 | Invalid Price |
| `INVALID_STOPS` | 10016 | Invalid Stops |
| `TRADE_DISABLED` | 10017 | Trade is disabled |
| `MARKET_CLOSED` | 10018 | Market is closed |
| `NO_MONEY` | 10019 | No money |
| `PRICE_CHANGED` | 10020 | Price changed |
| `PRICE_OFF` | 10021 | Price off |
| `INVALID_EXPIRATION` | 10022 | Invalid expiration |
| `ORDER_CHANGED` | 10023 | Order state changed |
| `TOO_MANY_REQUESTS` | 10024 | Too frequent requests |
| `NO_CHANGES` | 10025 | No changes in request |
| `SERVER_DISABLES_AT` | 10026 | Autotrading disabled by server |
| `CLIENT_DISABLES_AT` | 10027 | Autotrading disabled by client terminal |
| `LOCKED` | 10028 | Request locked for processing |
| `FROZEN` | 10029 | Order or position frozen |
| `INVALID_FILL` | 10030 | Invalid order filling type |
| `CONNECTION` | 10031 | No connection with the trade server |
| `ONLY_REAL` | 10032 | Operation is allowed only for live accounts |
| `LIMIT_ORDERS` | 10033 | The number of pending orders has reached the limit |
| `LIMIT_VOLUME` | 10034 | The volume of orders and positions for the symbol has reached the limit |
| `INVALID_ORDER` | 10035 | Incorrect or prohibited order type |
| `POSITION_CLOSED` | 10036 | Position with the specified POSITION_IDENTIFIER has already been closed |
| `INVALID_CLOSE_VOLUME` | 10037 | A close volume exceeds the current position volume |
| `CLOSE_ORDER_EXIST` | 10038 | A close order already exists for a specified position. This may happen when working in the hedging system |
| `LIMIT_POSITIONS` | 10039 | The number of open positions simultaneously present on an account can be limited by the server settings |
| `REJECT_CANCEL` | 10040 | The pending order activation request is rejected, the order is canceled |
| `LONG_ONLY` | 10041 | The request is rejected, because the "Only long positions are allowed" rule is set for the symbol (POSITION_TYPE_BUY) |
| `SHORT_ONLY` | 10042 | The request is rejected, because the "Only short positions are allowed" rule is set for the symbol (POSITION_TYPE_SELL) |
| `CLOSE_ONLY` | 10043 | The request is rejected, because the "Only position closing is allowed" rule is set for the symbol |
| `FIFO_CLOSE` | 10044 | The request is rejected, because "Position closing is allowed only by FIFO rule" flag is set for the trading account (ACCOUNT_FIFO_CLOSE=true) |
<a id="AccountStopOutMode"></a>
## AccountStopOutMode
```python
class AccountStopOutMode(Repr, IntEnum)
```
ACCOUNT_STOPOUT_MODE Enum.
### Members
| Name | Value | Description |
|-----------|-------|-----------------------------------|
| `PERCENT` | 0 | Account stop out mode in percents |
| `MONEY` | 1 | Account stop out mode in money |
<a id="AccountMarginMode"></a>
## AccountMarginMode
```python
class AccountMarginMode(Repr, IntEnum)
```
ACCOUNT_MARGIN_MODE Enum.
### Members
| Name | Value | Description |
|------------------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `RETAIL_NETTING` | 0 | Used for the OTC markets to interpret positions in the "netting" mode (only one position can exist for one symbol). The margin is calculated based on the symbol type (SYMBOL_TRADE_CALC_MODE). |
| `EXCHANGE` | 1 | Used for the exchange markets. Margin is calculated based on the discounts specified in symbol settings. Discounts are set by the broker, but not less than the values set by the exchange. |
| `RETAIL_HEDGING` | 2 | Used for the exchange markets where individual positions are possible (hedging, multiple positions can exist for one symbol). The margin is calculated based on the symbol type (SYMBOL_TRADE_CALC_MODE) taking into account the hedged margin (SYMBOL_MARGIN_HEDGED). |
+30
View File
@@ -0,0 +1,30 @@
# Errors
## Tabel of contents
- [Error](#errors.Error)
- [is_connection_error](#errors.is_connection_error)
<a id="errors.Error"></a>
## Error
```python
class Error()
```
Error class for handling errors from MetaTrader 5.
#### Attributes
| Name | Type | Description |
|----------------|--------|----------------------------------------------|
| `code` | `int` | Error code |
| `description` | `str` | Error description |
| `descriptions` | `dict` | A dictionary of error codes and descriptions |
<a id="errors.is_connection_error"></a>
## is_connection_error
```python
def is_connection_error(self) -> bool
```
Check if error is a connection error.
#### Returns
| Type | Description |
|--------|------------------------------------------------------|
| `bool` | True if error is a connection error, False otherwise |
+37
View File
@@ -0,0 +1,37 @@
# Exceptions
Exceptions for the aiomql package.
## Table of Contents
- [LoginError](#exceptions.LoginError)
- [VolumeError](#exceptions.VolumeError)
- [SymbolError](#exceptions.SymbolError)
- [OrderError](#exceptions.OrderError)
<a id="exceptions.LoginError"></a>
### LoginError
```python
class LoginError(Exception)
```
Raised when an error occurs when logging in.
<a id="exceptions.VolumeError"></a>
### VolumeError
```python
class VolumeError(Exception)
```
Raised when a volume is not valid or out of range for a symbol.
<a id="exceptions.SymbolError"></a>
### SymbolError
```python
class SymbolError(Exception)
```
Raised when a symbol is not provided where required or not available in the Market Watch.
<a id="exceptions.OrderError"></a>
### OrderError
```python
class OrderError(Exception)
```
Raised when an error occurs when working with the order class.
+624
View File
@@ -0,0 +1,624 @@
# MetaTrader
The MetaTrader Class provides an asynchronous wrapper around the MetaTrader5 API.
## Table of Contents
- [MetaTrader](#MetaTrader)
- [\_\_aenter\_\_](#__aenter__)
- [\_\_aexit\_\_](#__aexit__)
- [login](#login)
- [initialize](#initialize)
- [shutdown](#shutdown)
- [version](#version)
- [account\_info](#account_info)
- [terminal\_info](#terminal_info)
- [last\_error](#last_error)
- [symbols\_total](#symbols_total)
- [symbols\_get](#symbols_get)
- [symbol\_info](#symbol_info)
- [symbol\_info\_tick](#symbol_info_tick)
- [symbol\_select](#symbol_select)
- [market\_book\_add](#market_book_add)
- [market\_book\_get](#market_book_get)
- [market\_book\_release](#market_book_release)
- [copy\_rates\_from](#copy_rates_from)
- [copy\_rates\_from\_pos](#copy_rates_from_pos)
- [copy\_rates\_range](#copy_rates_range)
- [copy\_ticks\_from](#copy_ticks_from)
- [copy\_ticks\_range](#copy_ticks_range)
- [orders\_total](#orders_total)
- [orders\_get](#orders_get)
- [order\_calc\_margin](#order_calc_margin)
- [order\_calc\_profit](#order_calc_profit)
- [order\_check](#order_check)
- [order\_send](#order_send)
- [positions\_total](#positions_total)
- [positions\_get](#positions_get)
- [history\_orders\_total](#history_orders_total)
- [history\_orders\_get](#history_orders_get)
- [history\_deals\_total](#history_deals_total)
- [history\_deals\_get](#history_deals_get)
<a id="MetaTrader"></a>
### MetaTrader
```python
class MetaTrader(metaclass=BaseMeta)
```
The MetaTrader class is a wrapper around the MetaTrader terminal.
It provides methods for connecting to the MetaTrader terminal and retrieving data from it.
#### Attributes
| Name | Type | Description | Default |
|-------|-------|--------------------------------------------------------|------------------------|
| error | Error | The last error encountered by the MetaTrader terminal. | Error(1, 'Successful') |
#### Notes
All the attributes, enums and constants of the MetaTrader5 class are also available here. Although, they are more easily
accessible and used via the various enums and models defined in the module.
<a id="__aenter__"></a>
#### \_\_aenter\_\_
```python
async def __aenter__() -> 'MetaTrader'
```
Async context manager entry point.
Initializes the connection to the MetaTrader terminal.
#### Returns
| Type | Description |
|--------------|-------------------------------------|
| `MetaTrader` | An instance of the MetaTrader class |
<a id="__aexit__"></a>
#### \_\_aexit\_\_
```python
async def __aexit__(exc_type, exc_val, exc_tb)
```
Async context manager exit point. Closes the connection to the MetaTrader terminal.
<a id="login"></a>
#### login
```python
async def login(login: int,
password: str,
server: str,
timeout: int = 60000) -> bool
```
Connects to the MetaTrader terminal using the specified login, password and server.
#### Parameters
| Name | Type | Description |
|------------|-------|--------------------------------------------|
| `login` | `int` | The trading account number. |
| `password` | `str` | The trading account password. |
| `server` | `str` | The trading server name. |
| `timeout` | `int` | The timeout for the connection in seconds. |
#### Returns:
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, False otherwise. |
<a id="initialize"></a>
#### initialize
```python
async def initialize(path: str = "",
login: int = 0,
password: str = "",
server: str = "",
timeout: int | None = None,
portable=False) -> bool
```
Initializes the connection to the MetaTrader terminal. All parameters are optional.
#### Parameters
| Name | Type | Description |
|------------|-----------------|----------------------------------------------------------|
| `path` | `str` | The path to the MetaTrader terminal executable. |
| `login` | `int` | The trading account number. |
| `password` | `str` | The trading account password. |
| `server` | `str` | The trading server name. |
| `timeout` | `int` or `None` | The timeout for the connection in seconds. |
| `portable` | `bool` | If True, the terminal will be launched in portable mode. |
#### Returns
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, False otherwise. |
<a id="shutdown"></a>
#### shutdown
```python
async def shutdown() -> None
```
Closes the connection to the MetaTrader terminal.
<a id="version"></a>
#### version
```python
async def version() -> tuple[int, int, str] | None
```
Returns the version of the MetaTrader terminal.
#### Returns
| Type | Description |
|------------------------|-----------------------------------------------------------------------------------------------|
| `tuple[int, int, str]` | A tuple of the MetaTrader terminal version. `Terminal Version`, `Build`, `Build Release Date` |
<a id="account_info"></a>
#### account\_info
```python
async def account_info() -> AccountInfo | None
```
Returns the account information for the connected account.
#### Returns
| Type | Description |
|---------------|--------------------------------------|
| `AccountInfo` | An instance of the AccountInfo class |
<a id="terminal_info"></a>
#### terminal\_info
```python
async def terminal_info() -> TerminalInfo | None
```
Returns the terminal information for the connected terminal.
#### Returns
| Type | Description |
|----------------|------------------------------------------------|
| `TerminalInfo` | An instance of the TerminalInfo class. A tuple |
<a id="last_error"></a>
#### last\_error
```python
async def last_error() -> tuple[int, str]
```
Returns the last error code and description.
#### Returns
| Type | Description |
|-------------------|-------------------------------------------------|
| `tuple[int, str]` | A tuple of the last error code and description. |
<a id="symbols_total"></a>
#### symbols\_total
```python
async def symbols_total() -> int
```
Returns the total number of symbols.
#### Returns
| Type | Description |
|-------|------------------------------|
| `int` | The total number of symbols. |
<a id="symbols_get"></a>
#### symbols\_get
```python
async def symbols_get(group: str = "") -> tuple[SymbolInfo] | None
```
Returns the symbol information for all symbols or for a specified group.
#### Parameters
| Name | Type | Description |
|---------|-------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
| `group` | `str` | The group name. Optional named parameter. If the group is specified, the function returns only symbols meeting a specified criteria for a symbol name. |
#### Returns
| Type | Description |
|---------------------|--------------------------------|
| `tuple[SymbolInfo]` | A tuple of SymbolInfo objects. |
<a id="symbol_info"></a>
#### symbol\_info
```python
async def symbol_info(symbol: str) -> SymbolInfo | None
```
Returns the symbol information for the specified symbol.
#### Parameters
| Name | Type | Description |
|----------|-------|------------------|
| `symbol` | `str` | The symbol name. |
#### Returns:
| Type | Description |
|--------------|--------------------------------------|
| `SymbolInfo` | An instance of the SymbolInfo class. |
<a id="symbol_info_tick"></a>
#### symbol\_info\_tick
```python
async def symbol_info_tick(symbol: str) -> Tick | None
```
Returns the latest tick for the specified symbol.
#### Parameters
| Name | Type | Description |
|----------|-------|------------------|
| `symbol` | `str` | The symbol name. |
#### Returns
| Type | Description |
|--------|--------------------------------|
| `Tick` | An instance of the Tick class. |
<a id="symbol_select"></a>
#### symbol\_select
```python
async def symbol_select(symbol: str, enable: bool) -> bool
```
Selects or unselects the specified symbol in the Market Watch window.
#### Parameters
| Name | Type | Description |
|----------|--------|--------------------------------------------------------------------------------|
| `symbol` | `str` | The symbol name. |
| `enable` | `bool` | If True, the symbol will be selected. If False, the symbol will be unselected. |
#### Returns
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, False otherwise. |
<a id="market_book_add"></a>
#### market\_book\_add
```python
async def market_book_add(symbol: str) -> bool
```
Adds the specified symbol to the market book.
#### Parameters
| Name | Type | Description |
|----------|-------|------------------|
| `symbol` | `str` | The symbol name. |
#### Returns
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, False otherwise. |
<a id="market_book_get"></a>
#### market\_book\_get
```python
async def market_book_get(symbol: str) -> tuple[BookInfo] | None
```
Returns the market depth for the specified symbol.
#### Parameters
| Name | Type | Description |
|----------|-------|------------------|
| `symbol` | `str` | The symbol name. |
#### Returns
| Type | Description |
|-------------------|------------------------------|
| `tuple[BookInfo]` | A tuple of BookInfo objects. |
<a id="market_book_release"></a>
#### market\_book\_release
```python
async def market_book_release(symbol: str) -> bool
```
Removes the specified symbol from the market book.
#### Parameters
| Name | Type | Description |
|----------|-------|------------------|
| `symbol` | `str` | The symbol name. |
#### Returns
| Type | Description |
|--------|--------------------------------------|
| `bool` | True if successful, False otherwise. |
<a id="copy_rates_from"></a>
#### copy\_rates\_from
```python
import numpy
async def copy_rates_from(symbol: str,
timeframe: TimeFrame,
date_from: datetime | int,
count: int) -> numpy.ndarray | None
```
Returns the OHLCV rates for the specified symbol and timeframe starting from the specified date.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|--------------------------------|
| `symbol` | `str` | The symbol name. |
| `timeframe` | `TimeFrame` | The timeframe. |
| `date_from` | `datetime` or `int` | The date to start from. |
| `count` | `int` | The number of rates to return. |
#### Returns
| Type | Description |
|-----------------|-------------------------------|
| `numpy.ndarray` | A numpy array of OHLCV rates. |
<a id="copy_rates_from_pos"></a>
#### copy\_rates\_from\_pos
```python
async def copy_rates_from_pos(symbol: str,
timeframe: TimeFrame,
start_pos: int,
count: int) -> numpy.ndarray | None
```
Returns the OHLCV rates for the specified symbol and timeframe starting from the specified position.
#### Parameters
| Name | Type | Description |
|-------------|-------------|--------------------------------|
| `symbol` | `str` | The symbol name. |
| `timeframe` | `TimeFrame` | The timeframe. |
| `start_pos` | `int` | The position to start from. |
| `count` | `int` | The number of rates to return. |
#### Returns
| Type | Description |
|-----------------|-------------------------------|
| `numpy.ndarray` | A numpy array of OHLCV rates. |
<a id="copy_rates_range"></a>
#### copy\_rates\_range
```python
async def copy_rates_range(symbol: str,
timeframe: TimeFrame,
date_from: datetime | int,
date_to: datetime | int) -> numpy.ndarray | None
```
Returns the OHLCV rates for the specified symbol and timeframe between the specified dates.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|------------------|
| `symbol` | `str` | The symbol name. |
| `timeframe` | `TimeFrame` | The timeframe. |
| `date_from` | `datetime` or `int` | The start date. |
| `date_to` | `datetime` or `int` | The end date. |
#### Returns:
| Type | Description |
|-----------------|-------------------------------|
| `numpy.ndarray` | A numpy array of OHLCV rates. |
<a id="copy_ticks_from"></a>
#### copy\_ticks\_from
```python
async def copy_ticks_from(symbol: str,
date_from: datetime | int,
count: int,
flags: CopyTicks) -> tuple[Tick] | None
```
Returns the ticks for the specified symbol starting from the specified date.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|--------------------------------|
| `symbol` | `str` | The symbol name. |
| `date_from` | `datetime` or `int` | The date to start from. |
| `count` | `int` | The number of ticks to return. |
| `flags` | `CopyTicks` | The CopyTicks flags. |
#### Returns
| Type | Description |
|---------------|--------------------------|
| `tuple[Tick]` | A tuple of Tick objects. |
<a id="copy_ticks_range"></a>
#### copy\_ticks\_range
```python
async def copy_ticks_range(symbol: str,
date_from: datetime | int,
date_to: datetime | int,
flags: CopyTicks) -> tuple[Tick] | None
```
Returns the ticks for the specified symbol between the specified dates.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|----------------------|
| `symbol` | `str` | The symbol name. |
| `date_from` | `datetime` or `int` | The start date. |
| `date_to` | `datetime` or `int` | The end date. |
| `flags` | `CopyTicks` | The CopyTicks flags. |
#### Returns
| Type | Description |
|---------------|--------------------------|
| `tuple[Tick]` | A tuple of Tick objects. |
<a id="orders_total"></a>
#### orders\_total
```python
async def orders_total() -> int
```
Returns the total number of active orders.
#### Returns
| Type | Description |
|-------|------------------------------------|
| `int` | The total number of active orders. |
<a id="orders_get"></a>
#### orders\_get
```python
async def orders_get(group: str = "",
ticket: int = 0,
symbol: str = "") -> tuple[TradeOrder] | None
```
Get active orders with the ability to filter by symbol or ticket. There are three call options.
Call without parameters. Return active orders on all symbols
#### Parameters
| Name | Type | Description |
|----------|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only active orders meeting a specified criteria for a symbol name. |
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
| `symbol` | `str` | Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
#### Returns
| Type | Description |
|---------------------|------------------------------------------------------|
| `tuple[TradeOrder]` | A tuple of active trade orders as TradeOrder objects |
#### Returns
| Type | Description |
|---------------------|------------------------------------------------------|
| `tuple[TradeOrder]` | A tuple of active trade orders as TradeOrder objects |
<a id="order_calc_margin"></a>
#### order\_calc\_margin
```python
async def order_calc_margin(action: OrderType,
symbol: str,
volume: float,
price: float) -> float | None
```
Calculates the margin required to open a trade.
#### Parameters
| Name | Type | Description |
|----------|-------------|-------------------|
| `action` | `OrderType` | The order type. |
| `symbol` | `str` | The symbol name. |
| `volume` | `float` | The order volume. |
| `price` | `float` | The order price. |
#### Returns
| Type | Description |
|---------|--------------------------------------|
| `float` | The margin required to open a trade. |
<a id="order_calc_profit"></a>
#### order\_calc\_profit
```python
async def order_calc_profit(action: OrderType,
symbol: str,
volume: float,
price_open: float,
price_close: float) -> float | None
```
Calculates the profit for a closed trade.
#### Parameters
| Name | Type | Description |
|---------------|-------------|------------------------|
| `action` | `OrderType` | The order type. |
| `symbol` | `str` | The symbol name. |
| `volume` | `float` | The order volume. |
| `price_open` | `float` | The order open price. |
| `price_close` | `float` | The order close price. |
#### Returns
| Type | Description |
|---------|--------------------------------|
| `float` | The profit for a closed trade. |
<a id="order_check"></a>
#### order\_check
```python
async def order_check(request: dict) -> OrderCheckResult
```
Checks the specified order for validity.
#### Parameters
| Name | Type | Description |
|-----------|--------|--------------------|
| `request` | `dict` | The order request. |
#### Returns
| Type | Description |
|--------------------|--------------------------------------------|
| `OrderCheckResult` | An instance of the OrderCheckResult class. |
<a id="order_send"></a>
#### order\_send
```python
async def order_send(request: dict) -> OrderSendResult
```
Sends the specified order request to the MetaTrader terminal.
#### Parameters
| Name | Type | Description |
|-----------|--------|--------------------|
| `request` | `dict` | The order request. |
#### Returns
| Type | Description |
|-------------------|-------------------------------------------|
| `OrderSendResult` | An instance of the OrderSendResult class. |
<a id="positions_total"></a>
#### positions\_total
```python
async def positions_total() -> int
```
Returns the total number of open positions.
#### Returns
| Type | Description |
|-------|-------------------------------------|
| `int` | The total number of open positions. |
<a id="positions_get"></a>
#### positions\_get
```python
async def positions_get(group: str = "",
ticket: int = 0,
symbol: str = "") -> tuple[TradePosition] | None
```
Returns the open positions with the ability to filter by symbol or ticket. There are three call options.
Call without parameters. Return open positions on all symbols
#### Parameters
| Name | Type | Description |
|----------|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only open positions meeting a specified criteria for a symbol name. |
| `ticket` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
| `symbol` | `str` | Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
#### Returns
| Type | Description |
|------------------------|----------------------------------------------------------|
| `tuple[TradePosition]` | A tuple of open trade positions as TradePosition objects |
<a id="history_orders_total"></a>
#### history\_orders\_total
```python
async def history_orders_total(date_from: datetime | int,
date_to: datetime | int) -> int
```
Returns the total number of closed orders for the specified period.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|-----------------|
| `date_from` | `datetime` or `int` | The start date. |
| `date_to` | `datetime` or `int` | The end date. |
#### Returns
| Type | Description |
|-------|-------------------------------------------------------------|
| `int` | The total number of closed orders for the specified period. |
<a id="history_orders_get"></a>
#### history\_orders\_get
```python
async def history_orders_get(date_from: datetime | int = None,
date_to: datetime | int = None,
group: str = "",
ticket: int = 0,
position: int = 0) -> tuple[TradeOrder] | None
```
Returns the closed orders for the specified period with the ability to filter by symbol or ticket. There are three call options.
Call without parameters. Return closed orders on all symbols
#### Parameters
| Name | Type | Description |
|-------------|---------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `date_from` | `datetime` or `int` | The start date. Optional named parameter. |
| `date_to` | `datetime` or `int` | The end date. Optional named parameter. |
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only closed orders meeting a specified criteria for a symbol name. |
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
| `position` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
#### Returns
| Type | Description |
|---------------------|------------------------------------------------------|
| `tuple[TradeOrder]` | A tuple of closed trade orders as TradeOrder objects |
<a id="history_deals_total"></a>
#### history\_deals\_total
```python
async def history_deals_total(date_from: datetime | int,
date_to: datetime | int) -> int
```
Returns the total number of closed deals for the specified period.
#### Parameters
| Name | Type | Description |
|-------------|---------------------|-----------------|
| `date_from` | `datetime` or `int` | The start date. |
| `date_to` | `datetime` or `int` | The end date. |
#### Returns
| Type | Description |
|-------|------------------------------------------------------------|
| `int` | The total number of closed deals for the specified period. |
<a id="history_deals_get"></a>
#### history\_deals\_get
```python
async def history_deals_get(date_from: datetime | int = None,
date_to: datetime | int = None,
group: str = "",
ticket: int = 0,
position: int = 0) -> tuple[TradeDeal] | None
```
Returns the closed deals for the specified period with the ability to filter by symbol or ticket. There are three call options.
Call without parameters. Return closed deals on all symbols
#### Parameters
| Name | Type | Description |
|-------------|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `date_from` | `datetime` or `int` | The start date. Optional named parameter. |
| `date_to` | `datetime` or `int` | The end date. Optional named parameter. |
| `group` | `str` | The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only closed deals meeting a specified criteria for a symbol name. |
| `ticket` | `int` | Order ticket (ORDER_TICKET). Optional named parameter. |
| `position` | `int` | Position ticket (POSITION_TICKET). Optional named parameter. |
#### Returns
| Type | Description |
|--------------------|----------------------------------------------------|
| `tuple[TradeDeal]` | A tuple of closed trade deals as TradeDeal objects |
View File
+374
View File
@@ -0,0 +1,374 @@
# Models
This module contains the models used in the aiomql package. These models are used to represent the data returned from the MetaTrader 5 terminal.
They are all subclasses of the `Base` class.
## Table of Contents
- [AccountInfo](#AccountInfo)
- [TerminalInfo](#TerminalInfo)
- [SymbolInfo](#SymbolInfo)
- [BookInfo](#BookInfo)
- [TradeOrder](#TradeOrder)
- [TradeRequest](#TradeRequest)
- [OrderCheckResult](#OrderCheckResult)
- [OrderSendResult](#OrderSendResult)
- [TradePosition](#TradePosition)
- [TradeDeal](#TradeDeal)
<a id="AccountInfo"></a>
## AccountInfo
```python
class AccountInfo(Base)
```
Account Information Class.
#### Attributes
| Name | Type | Description | Default |
|----------------------|--------------------|------------------------------------------|---------|
| `login` | `int` | Account number | |
| `password` | `str` | Account password | |
| `server` | `str` | Trade server name | |
| `trade_mode` | AccountTradeMode | Trade mode | |
| `balance` | `float` | Account balance | |
| `leverage` | `float` | Account leverage | |
| `profit` | `float` | Account profit | |
| `point` | `float` | Point size | |
| `amount` | `float` | Account amount | 0 |
| `equity` | `float` | Account equity | |
| `credit` | `float` | Account credit | |
| `margin` | `float` | Account margin | |
| `margin_level` | `float` | Margin level | |
| `margin_free` | `float` | Free margin | |
| `margin_mode` | AccountMarginMode | Margin calculation mode | |
| `margin_so_mode` | AccountStopoutMode | Stop out mode | |
| `margin_so_call` | `float` | Margin call level | |
| `margin_so_so` | `float` | Stop out level | |
| `margin_initial` | `float` | Initial margin | |
| `margin_maintenance` | `float` | Maintenance margin | |
| `fifo_close` | `bool` | FIFO close flag | |
| `limit_orders` | `float` | Limit orders | |
| `currency` | `str` | Account currency | "USD" |
| `trade_allowed` | `bool` | Trade allowed flag | True |
| `trade_expert` | `bool` | Trade expert flag | True |
| `currency_digits` | `int` | Number of digits after the decimal point | |
| `assets` | `float` | Assets | |
| `liabilities` | `float` | Liabilities | |
| `commission_blocked` | `float` | Blocked commission | |
| `name` | `str` | Account name | |
| `company` | `str` | Company name | |
<a id="TerminalInfo"></a>
## TerminalInfo
```python
class TerminalInfo(Base)
```
Terminal information class. Holds information about the terminal.
#### Attributes
| Name | Type | Description | Default |
|-------------------------|---------|----------------------------|---------|
| `community_account` | `bool` | Community account flag | |
| `community_connection` | `bool` | Community connection flag | |
| `connected` | `bool` | Connection flag | |
| `dlls_allowed` | `bool` | DLLs allowed flag | |
| `trade_allowed` | `bool` | Trade allowed flag | |
| `tradeapi_disabled` | `bool` | Trade API disabled flag | |
| `email_enabled` | `bool` | Email enabled flag | |
| `ftp_enabled` | `bool` | FTP enabled flag | |
| `notifications_enabled` | `bool` | Notifications enabled flag | |
| `mqid` | `bool` | MQID | |
| `build` | `int` | Build number | |
| `maxbars` | `int` | Maximum number of bars | |
| `codepage` | `int` | Code page | |
| `ping_last` | `int` | Last ping | |
| `community_balance` | `float` | Community balance | |
| `retransmission` | `float` | Retransmission | |
| `company` | `str` | Company name | |
| `name` | `str` | Terminal name | |
| `language` | `str` | Language | |
| `path` | `str` | Terminal path | |
| `data_path` | `str` | Data path | |
| `commondata_path` | `str` | Common data path | |
<a id="SymbolInfo"></a>
## SymbolInfo
```python
class SymbolInfo(Base)
```
Symbol Information Class. Symbols are financial instruments available for trading in the MetaTrader 5 terminal.
#### Attributes
| Name | Type | Description | Default |
|------------------------------|------------------------|----------------------------|---------|
| `name` | `str` | Symbol name | |
| `custom` | `bool` | Custom symbol flag | |
| `chart_mode` | `SymbolChartMode` | Chart mode | |
| `select` | `bool` | Symbol selection flag | |
| `visible` | `bool` | Symbol visibility flag | |
| `session_deals` | `int` | Session deals | |
| `session_buy_orders` | `int` | Session buy orders | |
| `session_sell_orders` | `int` | Session sell orders | |
| `volume` | `float` | Volume | |
| `volumehigh` | `float` | Volume high | |
| `volumelow` | `float` | Volume low | |
| `time` | `int` | Time | |
| `digits` | `int` | Digits | |
| `spread` | `float` | Spread | |
| `spread_float` | `bool` | Spread float flag | |
| `ticks_bookdepth` | `int` | Ticks book depth | |
| `trade_calc_mode` | `SymbolCalcMode` | Trade calculation mode | |
| `trade_mode` | `SymbolTradeMode` | Trade mode | |
| `start_time` | `int` | Start time | |
| `expiration_time` | `int` | Expiration time | |
| `trade_stops_level` | `int` | Trade stops level | |
| `trade_freeze_level` | `int` | Trade freeze level | |
| `trade_exemode` | `SymbolTradeExecution` | Trade execution mode | |
| `swap_mode` | `SymbolSwapMode` | Swap mode | |
| `swap_rollover3days` | `DayOfWeek` | Swap rollover 3 days | |
| `margin_hedged_use_leg` | `bool` | Margin hedged use leg flag | |
| `expiration_mode` | `int` | Expiration mode | |
| `filling_mode` | `int` | Filling mode | |
| `order_mode` | `int` | Order mode | |
| `order_gtc_mode` | `SymbolOrderGTCMode` | Order GTC mode | |
| `option_mode` | `SymbolOptionMode` | Option mode | |
| `option_right` | `SymbolOptionRight` | Option right | |
| `bid` | `float` | Bid | |
| `bidhigh` | `float` | Bid high | |
| `bidlow` | `float` | Bid low | |
| `ask` | `float` | Ask | |
| `askhigh` | `float` | Ask high | |
| `asklow` | `float` | Ask low | |
| `last` | `float` | Last | |
| `lasthigh` | `float` | Last high | |
| `lastlow` | `float` | Last low | |
| `volume_real` | `float` | Volume real | |
| `volumehigh_real` | `float` | Volume high real | |
| `volumelow_real` | `float` | Volume low real | |
| `option_strike` | `float` | Option strike | |
| `point` | `float` | Point | |
| `trade_tick_value` | `float` | Trade tick value | |
| `trade_tick_value_profit` | `float` | Trade tick value profit | |
| `trade_tick_value_loss` | `float` | Trade tick value loss | |
| `trade_tick_size` | `float` | Trade tick size | |
| `trade_contract_size` | `float` | Trade contract size | |
| `trade_accrued_interest` | `float` | Trade accrued interest | |
| `trade_face_value` | `float` | Trade face value | |
| `trade_liquidity_rate` | `float` | Trade liquidity rate | |
| `volume_min` | `float` | Volume min | |
| `volume_max` | `float` | Volume max | |
| `volume_step` | `float` | Volume step | |
| `volume_limit` | `float` | Volume limit | |
| `swap_long` | `float` | Swap long | |
| `swap_short` | `float` | Swap short | |
| `margin_initial` | `float` | Initial margin | |
| `margin_maintenance` | `float` | Maintenance margin | |
| `session_volume` | `float` | Session volume | |
| `session_turnover` | `float` | Session turnover | |
| `session_interest` | `float` | Session interest | |
| `session_buy_orders_volume` | `float` | Session buy orders volume | |
| `session_sell_orders_volume` | `float` | Session sell orders volume | |
| `session_open` | `float` | Session open | |
| `session_close` | `float` | Session close | |
| `session_aw` | `float` | Session AW | |
| `session_price_settlement` | `float` | Session price settlement | |
| `session_price_limit_min` | `float` | Session price limit min | |
| `session_price_limit_max` | `float` | Session price limit max | |
| `margin_hedged` | `float` | Margin hedged | |
| `price_change` | `float` | Price change | |
| `price_volatility` | `float` | Price volatility | |
| `price_theoretical` | `float` | Price theoretical | |
| `price_greeks_delta` | `float` | Price greeks delta | |
| `price_greeks_theta` | `float` | Price greeks theta | |
| `price_greeks_gamma` | `float` | Price greeks gamma | |
| `price_greeks_vega` | `float` | Price greeks vega | |
| `price_greeks_rho` | `float` | Price greeks rho | |
| `price_greeks_omega` | `float` | Price greeks omega | |
| `price_sensitivity` | `float` | Price sensitivity | |
| `basis` | `str` | Basis | |
| `category` | `str` | Category | |
| `currency_base` | `str` | Base currency | |
| `currency_profit` | `str` | Profit currency | |
| `currency_margin` | `Any` | Margin currency | |
| `bank` | `str` | Bank | |
| `description` | `str` | Description | |
| `exchange` | `str` | Exchange | |
| `formula` | `Any` | Formula | |
| `isin` | `Any` | ISIN | |
| `name` | `str` | Name | |
| `page` | `str` | Page | |
| `path` | `str` | Path | |
<a id="BookInfo"></a>
## BookInfo
```python
class BookInfo(Base)
```
Book Information Class.
#### Attributes
| Name | Type | Description | Default |
|--------------|------------|-------------|---------|
| `symbol` | `str` | Symbol | |
| `type` | `BookType` | Type | |
| `price` | `float` | Price | |
| `volume` | `float` | Volume | |
| `volume_dbl` | `float` | Volume dbl | |
<a id="TradeOrder"></a>
## TradeOrder
```python
class TradeOrder(Base)
```
Trade Order Class.
#### Attributes
| Name | Type | Description | Default |
|-------------------|----------------|-----------------|---------|
| `ticket` | `int` | Ticket | |
| `time_setup` | `int` | Time setup | |
| `time_setup_msc` | `int` | Time setup msc | |
| `time_expiration` | `int` | Time expiration | |
| `time_done` | `int` | Time done | |
| `time_done_msc` | `int` | Time done msc | |
| `type` | `OrderType` | Type | |
| `type_time` | `OrderTime` | Type time | |
| `type_filling` | `OrderFilling` | Type filling | |
| `state` | `int` | State | |
| `magic` | `int` | Magic | |
| `position_id` | `int` | Position id | |
| `position_by_id` | `int` | Position by id | |
| `reason` | `OrderReason` | Reason | |
| `volume_current` | `float` | Volume current | |
| `volume_initial` | `float` | Volume initial | |
| `price_open` | `float` | Price open | |
| `sl` | `float` | SL | |
| `tp` | `float` | TP | |
| `price_current` | `float` | Price current | |
| `price_stoplimit` | `float` | Price stoplimit | |
| `symbol` | `str` | Symbol | |
| `comment` | `str` | Comment | |
| `external_id` | `str` | External id | |
<a id="TradeRequest"></a>
## TradeRequest
```python
class TradeRequest(Base)
```
Trade Request Class.
#### Attributes
| Name | Type | Description | Default |
|----------------|--------------|--------------|---------|
| `action` | TradeAction | Action | |
| `type` | OrderType | Type | |
| `order` | `int` | Order | |
| `symbol` | `str` | Symbol | |
| `volume` | `float` | Volume | |
| `sl` | `float` | SL | |
| `tp` | `float` | TP | |
| `price` | `float` | Price | |
| `deviation` | `float` | Deviation | |
| `stop_limit` | `float` | Stop limit | |
| `type_time` | OrderTime | Type time | |
| `type_filling` | OrderFilling | Type filling | |
| `expiration` | `int` | Expiration | |
| `position` | `int` | Position | |
| `position_by` | `int` | Position by | |
| `comment` | `str` | Comment | |
| `magic` | `int` | Magic | |
| `deviation` | `int` | Deviation | |
<a id="OrderCheckResult"></a>
## OrderCheckResult
```python
class OrderCheckResult(Base)
```
Order Check Result
#### Attributes
| Name | Type | Description | Default |
|----------------|----------------|--------------|---------|
| `retcode` | `int` | Retcode | |
| `balance` | `float` | Balance | |
| `equity` | `float` | Equity | |
| `profit` | `float` | Profit | |
| `margin` | `float` | Margin | |
| `margin_free` | `float` | Margin free | |
| `margin_level` | `float` | Margin level | |
| `comment` | `str` | Comment | |
| `request` | `TradeRequest` | Request | |
<a id="OrderSendResult"></a>
## OrderSendResult
```python
class OrderSendResult(Base)
```
Order Send Result
#### Attributes
| Name | Type | Description | Default |
|--------------------|----------------|------------------|---------|
| `retcode` | `int` | Retcode | |
| `deal` | `int` | Deal | |
| `order` | `int` | Order | |
| `volume` | `float` | Volume | |
| `price` | `float` | Price | |
| `bid` | `float` | Bid | |
| `ask` | `float` | Ask | |
| `comment` | `str` | Comment | |
| `request` | `TradeRequest` | Request | |
| `request_id` | `int` | Request id | |
| `retcode_external` | `int` | Retcode external | |
| `profit` | `float` | Profit | |
<a id="TradePosition"></a>
## TradePosition
```python
class TradePosition(Base)
```
Trade Position
#### Attributes
| Name | Type | Description | Default |
|-------------------|------------------|-----------------|---------|
| `ticket` | `int` | Ticket | |
| `time` | `int` | Time | |
| `time_msc` | `int` | Time msc | |
| `time_update` | `int` | Time update | |
| `time_update_msc` | `int` | Time update msc | |
| `type` | `OrderType` | Type | |
| `magic` | `float` | Magic | |
| `identifier` | `int` | Identifier | |
| `reason` | `PositionReason` | Reason | |
| `volume` | `float` | Volume | |
| `price_open` | `float` | Price open | |
| `sl` | `float` | SL | |
| `tp` | `float` | TP | |
| `price_current` | `float` | Price current | |
| `swap` | `float` | Swap | |
| `profit` | `float` | Profit | |
| `symbol` | `str` | Symbol | |
| `comment` | `str` | Comment | |
| `external_id` | `str` | External id | |
<a id="TradeDeal"></a>
## TradeDeal
```python
class TradeDeal(Base)
```
Trade Deal
#### Attributes
| Name | Type | Description | Default |
|---------------|--------------|-------------|---------|
| `ticket` | `int` | Ticket | |
| `order` | `int` | Order | |
| `time` | `int` | Time | |
| `time_msc` | `int` | Time msc | |
| `type` | `DealType` | Type | |
| `entry` | `DealEntry` | Entry | |
| `magic` | `int` | Magic | |
| `position_id` | `int` | Position id | |
| `reason` | `DealReason` | Reason | |
| `volume` | `float` | Volume | |
| `price` | `float` | Price | |
| `commission` | `float` | Commission | |
| `swap` | `float` | Swap | |
| `profit` | `float` | Profit | |
| `fee` | `float` | Fee | |
| `sl` | `float` | SL | |
| `tp` | `float` | TP | |
| `symbol` | `str` | Symbol | |
| `comment` | `str` | Comment | |
| `external_id` | `str` | External id | |
+91
View File
@@ -0,0 +1,91 @@
# TaskQueue and QueueItem
## Table of Contents
- [QueueItem](#queue_item)
- [run](#run)
- [TaskQueue](#task_queue)
- [TaskQueue.add](#task_queue.add)
- [TaskQueue.add_task](#task_queue.add_task)
- [TaskQueue.worker](#task_queue.worker)
- [TaskQueue.start](#task_queue.start)
<a id="queue_item"></a>
### QueueItem
```python
class QueueItem:
def __init__(self, task: Callable | Awaitable, *args, **kwargs):
```
A task to be executed by the `TaskQueue`. The task can be a callable or an awaitable. The task is wrapped as a
`QueueItem` object, which is then added to the `TaskQueue` for execution. The arguments and keyword arguments are
passed to the task when it is executed. All parameters are created as attributes of the `QueueItem` object.
#### Parameters:
| Name | Type | Description |
|----------|---------------------------|-------------------------------------------------------------------|
| `task` | `Callable` \| `Awaitable` | A callable or awaitable task to be executed by the `TaskQueue` |
| `args` | `Any` | Positional arguments to be passed to the task when it is executed |
| `kwargs` | `Any` | Keyword arguments to be passed to the task when it is executed |
<a id="run"></a>
### run
```python
def run(self) -> Any
```
Run the task. If the task is a coroutine, it is awaited. If the task is a callable, it is called.
### TaskQueue
```python
class TaskQueue:
def __init__(self):
```
#### Attributes:
| Name | Type | Description |
|---------------|-----------------|---------------------------------------------------------------------------------|
| `queue` | `asyncio.Queue` | An asyncio.Queue queue of `QueueItem` objects to be executed by the `TaskQueue` |
<a id="task_queue.add"></a>
### add
```python
def add(self, item: QueueItem, *args, **kwargs) -> None
```
Add a `QueueItem` to the `TaskQueue` queue.
#### Parameters:
| Name | Type | Description |
|--------|-------------|----------------------------------------|
| `item` | `QueueItem` | A `QueueItem` to be added to the queue |
<a id="task_queue.add_task"></a>
### add_task
```python
def add_task(self, task: Callable | Awaitable, *args, **kwargs) -> None
```
Create a QueueItem from the task and add it to the `TaskQueue` queue. The task can be a callable or an awaitable.
The arguments and keyword arguments are passed to the QueueItem.
#### Parameters:
| Name | Type | Description |
|----------|---------------------------|-------------------------------------------------------------------|
| `task` | `Callable` \| `Awaitable` | A callable or awaitable task to be executed by the `TaskQueue` |
| `args` | `Any` | Positional arguments to be passed to the task when it is executed |
| `kwargs` | `Any` | Keyword arguments to be passed to the task when it is executed |
<a id="task_queue.worker"></a>
### worker
```python
async def worker(self) -> None
```
A worker that processes the `QueueItem` objects in the `TaskQueue` queue. The worker runs indefinitely, processing
`QueueItem` objects as they are added to the queue.
<a id="task_queue.start"></a>
### start
```python
def start(self) -> None
```
Start the worker that processes the `QueueItem` objects in the `TaskQueue` queue.