Asynchronous MetaTrader5 library and Bot Building Framework
Project description
aiomql
Installation
pip install aiomql
Key Features
- Asynchronous Python Library For MetaTrader 5
- Build bots for trading in different financial markets using a bot factory
- Use threadpool executors to run multiple strategies on multiple instruments concurrently
- Record and keep track of trades and strategies in csv files.
- Utility classes for using the MetaTrader 5 Library
- Sample Pre-Built strategies
Simple Usage as an asynchronous MetaTrader5 Libray
import asyncio
# import the class
from aiomql import MetaTrader, Account, TimeFrame, OrderType
async def main():
# Assuming your login details are already defined in the aiomql.json somewhere in your project directory.
acc = Account()
# if this is unsuccessful the program exits
await acc.sign_in()
# print all available symbols
print(acc.symbols)
asyncio.run(main())
As a Bot Building FrameWork using a Sample Strategy
from aiomql import Bot
from aiomql import ForexSymbol
from aiomql import FingerTrap
# Create a bot instance
bot = Bot()
# Choose a Symbol to trade
symbol = ForexSymbol(name='EURUSD')
# Create a strategy
ft_eur_usd = FingerTrap(symbol=symbol)
# Add strategy to Bot
bot.add_strategy(ft_eur_usd)
# run the bot
bot.execute()
Api Documentation
aiomql
aiomql.account
Account Objects
class Account(AccountInfo)
A class for managing a trading account. A singleton class. A subclass of AccountInfo. All AccountInfo attributes are available in this class.
Attributes:
connectedbool - Status of connection to MetaTrader 5 Terminalsymbolsset[SymbolInfo] - A set of available symbols for the financial market.
Notes:
Other Account properties are defined in the AccountInfo class.
refresh
async def refresh()
Refreshes the account instance with the latest account details from the MetaTrader 5 terminal
account_info
@property
def account_info() -> dict
Get account login, server and password details. If the login attribute of the account instance returns a falsy value, the config instance is used to get the account details.
Returns:
dict- A dict of login, server and password details
Notes:
This method will only look for config details in the config instance if the login attribute of the account Instance returns a falsy value
sign_in
async def sign_in() -> bool
Connect to a trading account.
Returns:
bool- True if login was successful else False
has_symbol
def has_symbol(symbol: str | Type[SymbolInfo])
Checks to see if a symbol is available for a trading account
Arguments:
symbol (str | SymbolInfo):
Returns:
bool- True if symbol is present otherwise False
symbols_get
async def symbols_get() -> set[SymbolInfo]
Get all financial instruments from the MetaTrader 5 terminal available for the current account.
Returns:
set[Symbol]- A set of available symbols.
aiomql.bot_builder
Bot Objects
class Bot()
The bot builder class. This class is used to build a bot by adding strategies and running them in the executor.
Attributes:
accountAccount - Account Object.executor- The default thread executor.symbolsset[Symbols] - A set of symbols for the trading session
initialize
async def initialize()
Prepares the bot by signing in to the trading account and initializing the symbols for the trading session.
Raises:
SystemExit if sign in was not successful
execute
def execute()
Execute the bot.
start
async def start()
Starts the bot by calling the initialize method and running the strategies in the executor.
add_strategy
def add_strategy(strategy: Strategy)
Add a strategy to the executor. An added strategy will only run if it's symbol was successfully initialized.
Arguments:
strategyStrategy - A Strategy instance to run on bot
Notes:
Make sure the symbol has been added to the market
add_strategies
def add_strategies(strategies: Iterable[Strategy])
Add multiple strategies at the same time
Arguments:
strategies- A list of strategies
add_strategy_all
def add_strategy_all(*, strategy: Type[Strategy], params: dict | None = None)
Use this to run a single strategy on all available instruments in the market using the default parameters i.e one set of parameters for all trading symbols
Arguments:
strategyStrategy - Strategy classparamsdict - A dictionary of parameters for the strategy
init_symbols
async def init_symbols()
Initialize the symbols for the current trading session. This method is called internally by the bot.
init_symbol
async def init_symbol(symbol: Symbol) -> Symbol
Initialize a symbol before the beginning of a trading sessions. Removes it from the list of symbols if it was not successfully initialized or not available for the current market.
Arguments:
symbolSymbol - Symbol object to be initialized
Returns:
symbolSymbol - if successfully initialized
aiomql.candle
Candle and Candles classes for handling bars from the MetaTrader 5 terminal.
Candle Objects
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:
timeint - Period start time.openint - Open pricehighfloat - The highest price of the periodlowfloat - The lowest price of the periodclosefloat - Close pricetick_volumefloat - Tick volumereal_volumefloat - Trade volumespreadfloat - SpreadIndexint - Custom attribute representing the position of the candle in a sequence.
__init__
def __init__(**kwargs)
Create a Candle object from keyword arguments.
Arguments:
**kwargs- Candle attributes and values as keyword arguments.
set_attributes
def set_attributes(**kwargs)
Set keyword arguments as instance attributes
Arguments:
**kwargs- Instance attributes and values as keyword arguments
mid
@property
def mid() -> float
The median of open and close
Returns:
float- The median of open and close
is_bullish
def is_bullish() -> bool
A simple check to see if the candle is bullish.
Returns:
bool- True or False
is_bearish
def is_bearish() -> bool
A simple check to see if the candle is bearish.
Returns:
bool- True or False
Candles Objects
class Candles(Generic[_Candle])
An iterable container class of Candle objects in chronological order.
Attributes:
-
IndexSeries['int'] - A pandas Series of the indexes of all candles in the object. -
timeSeries['int'] - A pandas Series of the time of all candles in the object. -
openSeries[float] - A pandas Series of the opening price of all candles in the object. -
highSeries[float] - A pandas Series of the high price of all candles in the object. -
lowSeries[float] - A pandas Series of the low price of all candles in the object. -
closeSeries[float] - A pandas Series of the closing price of all candles in the object. -
tick_volumeSeries[float] - A pandas Series of the tick volume of all candles in the object. -
real_volumeSeries[float] - A pandas Series of the real volume of all candles in the object. -
spreadSeries[float] - A pandas Series of the spread of all candles in the object. -
timeframeTimeFrame - The timeframe of the candles in the object. -
CandleType[Candle] - The Candle class for representing the candles in the object.properties:
-
dataDataFrame - A pandas DataFrame of all candles in the object.
Notes:
The candle class can be customized by subclassing the Candle class and passing the subclass as the candle keyword argument. Or defining it on the class body as a class attribute.
__init__
def __init__(*,
data: DataFrame | _Candles | Iterable,
flip=False,
candle_class: Type[_Candle] = None)
A container class of Candle objects in chronological order.
Arguments:
dataDataFrame|Candles|Iterable - A pandas dataframe, a Candles object or any suitable iterable
Arguments:
flipbool - Reverse the chronological order of the candles to the oldest first. Defaults to False.candle_class- A subclass of Candle to use as the candle class. Defaults to Candle.
ta
@property
def ta()
Access to the pandas_ta library for performing technical analysis on the underlying data attribute.
Returns:
pandas_ta- The pandas_ta library
ta_lib
@property
def ta_lib()
Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute.
Returns:
ta- The ta library
data
@property
def data() -> DataFrame
The original data passed to the class as a pandas DataFrame
rename
def rename(inplace=True, **kwargs) -> _Candles | None
Rename columns of the candles class.
Arguments:
inplacebool - Rename the columns inplace or return a new instance of the class with the renamed columns**kwargs- The new names of the columns
Returns:
Candles- A new instance of the class with the renamed columns if inplace is False.None- If inplace is True
aiomql.core.base
Base Objects
class Base()
A base class for all data model classes in the aiomql package. This class provides a set of common methods and attributes for all data model classes. For the data model classes attributes are annotated on the class body and are set as object attributes when the class is instantiated.
Arguments:
-
**kwargs- Object attributes and values as keyword arguments. Only added if they are annotated on the class body.Class Attributes:
-
mt5MetaTrader - An instance of the MetaTrader class -
configConfig - An instance of the Config class -
MetaType[Meta] - The Meta class for configuration of the data model class
set_attributes
def set_attributes(**kwargs)
Set keyword arguments as object attributes
Arguments:
**kwargs- Object attributes and values as keyword arguments
Raises:
AttributeError- When assigning an attribute that does not belong to the class or any parent class
Notes:
Only sets attributes that have been annotated on the class body.
annotations
@property
@cache
def annotations() -> dict
Class annotations from all ancestor classes and the current class.
Returns:
dict- A dictionary of class annotations
get_dict
def get_dict(exclude: set = None, include: set = None) -> dict
Returns class attributes as a dict, with the ability to filter
Arguments:
exclude- A set of attributes to be excludedinclude- Specific attributes to be returned
Returns:
dict- A dictionary of specified class attributes
Notes:
You can only set either of include or exclude. If you set both, include will take precedence
class_vars
@property
@cache
def class_vars()
Annotated class attributes
Returns:
dict- A dictionary of available class attributes in all ancestor classes and the current class.
dict
@property
def dict() -> dict
All instance and class attributes as a dictionary, except those excluded in the Meta class.
Returns:
dict- A dictionary of instance and class attributes
Meta Objects
class Meta()
A class for defining class attributes to be excluded or included in the dict property
Attributes:
excludeset - A set of attributes to be excludedincludeset - Specific attributes to be returned. Include supercedes exclude.
filter
@classmethod
@property
def filter(cls) -> set
Combine the exclude and include attributes to return a set of attributes to be excluded.
Returns:
set- A set of attributes to be excluded
aiomql.core.config
Config Objects
class Config()
A class for handling configuration settings for the aiomql package.
Arguments:
**kwargs- Configuration settings as keyword arguments. Variables set this way supersede those set in the config file.
Attributes:
record_tradesbool - Whether to keep record of trades or not.filenamestr - Name of the config filerecords_dirstr - Path to the directory where trade records are savedwin_percentagefloat - Percentage of achieved target profit in a trade to be considered a winloginint - Trading account numberpasswordstr - Trading account passwordserverstr - Broker serverpathstr - Path to terminal filetimeoutint - Timeout for terminal connection
Notes:
By default, the config class looks for a file named aiomql.json. You can change this by passing the filename keyword argument to the constructor. By passing reload=True to the load_config method, you can reload and search again for the config file.
account_info
def account_info() -> dict['login', 'password', 'server']
Returns Account login details as found in the config object if available
Returns:
dict- A dictionary of login details
aiomql.core.constants
TradeAction Objects
class TradeAction(Repr, IntEnum)
TRADE_REQUEST_ACTION Enum.
Attributes:
DEALint - Delete the pending order placed previously Place a trade order for an immediate execution with the specified parameters (market order).PENDINGint - Delete the pending order placed previouslySLTPint - Modify Stop Loss and Take Profit values of an opened positionMODIFYint - Modify the parameters of the order placed previouslyREMOVEint - Delete the pending order placed previouslyCLOSE_BYint - Close a position by an opposite one
OrderFilling Objects
class OrderFilling(Repr, IntEnum)
ORDER_TYPE_FILLING Enum.
Attributes:
-
FOKint - 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. -
IOCint - 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. -
RETURNint - This policy is used only for market (ORDER_TYPE_BUY and ORDER_TYPE_SELL), limit and stop limit orders (ORDER_TYPE_BUY_LIMIT, ORDER_TYPE_SELL_LIMIT,ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT) and only for the symbols with Market or Exchange execution modes. If filled partially, a market or limit order with the remaining volume is not canceled, and is processed further. During activation of the ORDER_TYPE_BUY_STOP_LIMIT and ORDER_TYPE_SELL_STOP_LIMIT orders, an appropriate limit order ORDER_TYPE_BUY_LIMIT/ORDER_TYPE_SELL_LIMIT with the ORDER_FILLING_RETURN type is created.
OrderTime Objects
class OrderTime(Repr, IntEnum)
ORDER_TIME Enum.
Attributes:
GTCint - Good till cancel orderDAYint - Good till current trade day orderSPECIFIEDint - The order is active until the specified dateSPECIFIED_DAYint - The order is active until 23:59:59 of the specified day. If this time appears to be out of a trading session, the expiration is processed at the nearest trading time.
OrderType Objects
class OrderType(Repr, IntEnum)
ORDER_TYPE Enum.
Attributes:
-
BUYint - Market buy order -
SELLint - Market sell order -
BUY_LIMITint - Buy Limit pending order -
SELL_LIMITint - Sell Limit pending order -
BUY_STOPint - Buy Stop pending order -
SELL_STOPint - Sell Stop pending order -
BUY_STOP_LIMITint - Upon reaching the order price, Buy Limit pending order is placed at StopLimit price -
SELL_STOP_LIMITint - Upon reaching the order price, Sell Limit pending order is placed at StopLimit price -
CLOSE_BYint - Order for closing a position by an opposite oneProperties:
-
oppositeint - Gets the opposite of an order type
opposite
@property
def opposite()
Gets the opposite of an order type for closing an open position
Returns:
int- integer value of opposite order type
BookType Objects
class BookType(Repr, IntEnum)
BOOK_TYPE Enum.
Attributes:
SELLint - Sell order (Offer)BUYint - Buy order (Bid)SELL_MARKETint - Sell order by MarketBUY_MARKETint - Buy order by Market
TimeFrame Objects
class TimeFrame(Repr, IntEnum)
TIMEFRAME Enum.
Attributes:
-
M1int - One Minute -
M2int - Two Minutes -
M3int - Three Minutes -
M4int - Four Minutes -
M5int - Five Minutes -
M6int - Six Minutes -
M10int - Ten Minutes -
M15int - Fifteen Minutes -
M20int - Twenty Minutes -
M30int - Thirty Minutes -
H1int - One Hour -
H2int - Two Hours -
H3int - Three Hours -
H4int - Four Hours -
H6int - Six Hours -
H8int - Eight Hours -
D1int - One Day -
W1int - One Week -
MN1int - One MonthProperties:
-
time- return the value of the timeframe object in seconds. Used as a property
Methods:
get- get a timeframe object from a time value in seconds
time
@property
def time()
The number of seconds in a TIMEFRAME
Returns:
int- The number of seconds in a TIMEFRAME
Examples:
t = TimeFrame.H1 print(t.time) 3600
CopyTicks Objects
class CopyTicks(Repr, IntEnum)
COPY_TICKS Enum. This defines the types of ticks that can be requested using the copy_ticks_from() and copy_ticks_range() functions.
Attributes:
ALLint - All ticksINFOint - Ticks containing Bid and/or Ask price changesTRADEint - Ticks containing Last and/or Volume price changes
PositionType Objects
class PositionType(Repr, IntEnum)
POSITION_TYPE Enum. Direction of an open position (buy or sell)
Attributes:
BUYint - BuySELLint - Sell
PositionReason Objects
class PositionReason(Repr, IntEnum)
POSITION_REASON Enum. The reason for opening a position is contained in the POSITION_REASON Enum
Attributes:
CLIENTint - The position was opened as a result of activation of an order placed from a desktop terminalMOBILEint - The position was opened as a result of activation of an order placed from a mobile applicationWEBint - The position was opened as a result of activation of an order placed from the web platformEXPERTint - The position was opened as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a script
DealType Objects
class DealType(Repr, IntEnum)
DEAL_TYPE enum. Each deal is characterized by a type, allowed values are enumerated in this enum
Attributes:
-
BUYint - Buy -
SELLint - Sell -
BALANCEint - Balance -
CREDITint - Credit -
CHARGEint - Additional Charge -
CORRECTIONint - Correction -
BONUSint - Bonus -
COMMISSIONint - Additional Commission -
COMMISSION_DAILYint - Daily Commission -
COMMISSION_MONTHLYint - Monthly Commission -
COMMISSION_AGENT_DAILYint - Daily Agent Commission -
COMMISSION_AGENT_MONTHLYint - Monthly Agent Commission -
INTERESTint - Interest Rate -
DEAL_DIVIDENDint - Dividend Operations -
DEAL_DIVIDEND_FRANKEDint - Franked (non-taxable) dividend operations -
DEAL_TAXint - Tax Charges -
BUY_CANCELEDint - 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_CANCELEDint - Canceled sell deal. There can be a situation when a previously executed sell deal is canceled. In this case, the type of the previously executed deal (DEAL_TYPE_SELL) is changed to DEAL_TYPE_SELL_CANCELED, and its profit/loss is zeroized. Previously obtained profit/loss is charged/withdrawn using a separated balance operation.
DealEntry Objects
class DealEntry(Repr, IntEnum)
DEAL_ENTRY Enum. Deals differ not only in their types set in DEAL_TYPE enum, but also in the way they change positions. This can be a simple position opening, or accumulation of a previously opened position (market entering), position closing by an opposite deal of a corresponding volume (market exiting), or position reversing, if the opposite-direction deal covers the volume of the previously opened position.
Attributes:
INint - Entry InOUTint - Entry OutINOUTint - ReverseOUT_BYint - Close a position by an opposite one
DealReason Objects
class DealReason(Repr, IntEnum)
DEAL_REASON Enum. The reason for deal execution is contained in the DEAL_REASON property. A deal can be executed as a result of triggering of an order placed from a mobile application or an MQL5 program, as well as as a result of the StopOut event, variation margin calculation, etc.
Attributes:
CLIENTint - The deal was executed as a result of activation of an order placed from a desktop terminalMOBILEint - The deal was executed as a result of activation of an order placed from a desktop terminalWEBint - The deal was executed as a result of activation of an order placed from the web platformEXPERTint - The deal was executed as a result of activation of an order placed from an MQL5 program, i.e. an Expert Advisor or a scriptSLint - The deal was executed as a result of Stop Loss activationTPint - The deal was executed as a result of Take Profit activationSOint - The deal was executed as a result of the Stop Out eventROLLOVERint - The deal was executed due to a rolloverVMARGINint - The deal was executed after charging the variation marginSPLITint - The deal was executed after the split (price reduction) of an instrument, which had an open position during split announcement
OrderReason Objects
class OrderReason(Repr, IntEnum)
ORDER_REASON Enum.
Attributes:
CLIENTint - The order was placed from a desktop terminalMOBILEint - The order was placed from a mobile applicationWEBint - The order was placed from a web platformEXPERTint - The order was placed from an MQL5-program, i.e. by an Expert Advisor or a scriptSLint - The order was placed as a result of Stop Loss activationTPint - The order was placed as a result of Take Profit activationSOint - The order was placed as a result of the Stop Out event
SymbolChartMode Objects
class SymbolChartMode(Repr, IntEnum)
SYMBOL_CHART_MODE Enum. A symbol price chart can be based on Bid or Last prices. The price selected for symbol charts also affects the generation and display of bars in the terminal. Possible values of the SYMBOL_CHART_MODE property are described in this enum
Attributes:
BIDint - Bars are based on Bid pricesLASTint - Bars are based on last prices
SymbolCalcMode Objects
class SymbolCalcMode(Repr, IntEnum)
SYMBOL_CALC_MODE Enum. The SYMBOL_CALC_MODE enumeration is used for obtaining information about how the margin requirements for a symbol are calculated.
Attributes:
-
FOREXint - Forex mode - calculation of profit and margin for Forex -
FOREX_NO_LEVERAGEint - Forex No Leverage mode � calculation of profit and margin for Forex symbols without taking into account the leverage -
FUTURESint - Futures mode - calculation of margin and profit for futures -
CFDint - CFD mode - calculation of margin and profit for CFD -
CFDINDEXint - CFD index mode - calculation of margin and profit for CFD by indexes -
CFDLEVERAGEint - CFD Leverage mode - calculation of margin and profit for CFD at leverage trading -
EXCH_STOCKSint - Calculation of margin and profit for trading securities on a stock exchange -
EXCH_FUTURESint - Calculation of margin and profit for trading futures contracts on a stock exchange -
EXCH_OPTIONSint - value is 34 -
EXCH_OPTIONS_MARGINint - value is 36 -
EXCH_BONDSint - Exchange Bonds mode � calculation of margin and profit for trading bonds on a stock exchange -
STOCKS_MOEXint - Exchange MOEX Stocks mode �calculation of margin and profit for trading securities on MOEX -
EXCH_BONDS_MOEXint - Exchange MOEX Bonds mode � calculation of margin and profit for trading bonds on MOEX -
SERV_COLLATERALint - Collateral mode - a symbol is used as a non-tradable asset on a trading account. The market value of an open position is calculated based on the volume, current market price, contract size and liquidity ratio. The value is included into Assets, which are added to Equity. Open positions of such symbols increase the Free Margin amount and are used as additional margin (collateral) for open positions
SymbolTradeMode Objects
class SymbolTradeMode(Repr, IntEnum)
SYMBOL_TRADE_MODE Enum. There are several symbol trading modes. Information about trading modes of a certain symbol is reflected in the values this enumeration
Attributes:
DISABLEDint - Trade is disabled for the symbolLONGONLYint - Allowed only long positionsSHORTONLYint - Allowed only short positionsCLOSEONLYint - Allowed only position close operationsFULLint - No trade restrictions
SymbolTradeExecution Objects
class SymbolTradeExecution(Repr, IntEnum)
SYMBOL_TRADE_EXECUTION Enum. The modes, or execution policies, define the rules for cases when the price has changed or the requested volume cannot be completely fulfilled at the moment.
Attributes:
-
REQUESTint - Executing a market order at the price previously received from the broker. Prices for a certain market order are requested from the broker before the order is sent. Upon receiving the prices, order execution at the given price can be either confirmed or rejected. -
INSTANTint - Executing a market order at the specified price immediately. When sending a trade request to be executed, the platform automatically adds the current prices to the order.- If the broker accepts the price, the order is executed.
- If the broker does not accept the requested price, a "Requote" is sent � the broker returns prices, at which this order can be executed.
-
MARKETint - A broker makes a decision about the order execution price without any additional discussion with the trader. Sending the order in such a mode means advance consent to its execution at this price. -
EXCHANGEint - Trade operations are executed at the prices of the current market offers.
SymbolSwapMode Objects
class SymbolSwapMode(Repr, IntEnum)
SYMBOL_SWAP_MODE Enum. Methods of swap calculation at position transfer are specified in enumeration ENUM_SYMBOL_SWAP_MODE. The method of swap calculation determines the units of measure of the SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT parameters. For example, if swaps are charged in the client deposit currency, then the values of those parameters are specified as an amount of money in the client deposit currency.
Attributes:
-
DISABLEDint - Swaps disabled (no swaps) -
POINTSint - Swaps are charged in points -
CURRENCY_SYMBOLint - Swaps are charged in money in base currency of the symbol -
CURRENCY_MARGINint - Swaps are charged in money in margin currency of the symbol -
CURRENCY_DEPOSITint - Swaps are charged in money, in client deposit currency -
INTEREST_CURRENTint - Swaps are charged as the specified annual interest from the instrument price at calculation of swap (standard bank year is 360 days) -
INTEREST_OPENint - Swaps are charged as the specified annual interest from the open price of position (standard bank year is 360 days) -
REOPEN_CURRENTint - 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_BIDint - Swaps are charged by reopening positions. At the end of a trading day the position is closed. Next day it is reopened by the current Bid price +/- specified number of points (parameters SYMBOL_SWAP_LONG and SYMBOL_SWAP_SHORT)
DayOfWeek Objects
class DayOfWeek(Repr, IntEnum)
DAY_OF_WEEK Enum.
Attributes:
SUNDAYint - SundayMONDAYint - MondayTUESDAYint - TuesdayWEDNESDAYint - WednesdayTHURSDAYint - ThursdayFRIDAYint - FridaySATURDAYint - Saturday
SymbolOrderGTCMode Objects
class SymbolOrderGTCMode(Repr, IntEnum)
SYMBOL_ORDER_GTC_MODE Enum. If the SYMBOL_EXPIRATION_MODE property is set to SYMBOL_EXPIRATION_GTC (good till canceled), the expiration of pending orders, as well as of Stop Loss/Take Profit orders should be additionally set using the ENUM_SYMBOL_ORDER_GTC_MODE enumeration.
Attributes:
-
GTCint - Pending orders and Stop Loss/Take Profit levels are valid for an unlimited period until theirConstants, Enumerations and explicit cancellation -
DAILYint - 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_STOPSint - When a trade day changes, only pending orders are deleted, while Stop Loss and Take Profit levels are preserved
SymbolOptionRight Objects
class SymbolOptionRight(Repr, IntEnum)
SYMBOL_OPTION_RIGHT Enum. An option is a contract, which gives the right, but not the obligation, to buy or sell an underlying asset (goods, stocks, futures, etc.) at a specified price on or before a specific date. The following enumerations describe option properties, including the option type and the right arising from it.
Attributes:
CALLint - A call option gives you the right to buy an asset at a specified price.PUTint - A put option gives you the right to sell an asset at a specified price.
SymbolOptionMode Objects
class SymbolOptionMode(Repr, IntEnum)
SYMBOL_OPTION_MODE Enum.
Attributes:
EUROPEANint - European option may only be exercised on a specified date (expiration, execution date, delivery date)AMERICANint - American option may be exercised on any trading day or before expiry. The period within which a buyer can exercise the option is specified for it.
AccountTradeMode Objects
class AccountTradeMode(Repr, IntEnum)
ACCOUNT_TRADE_MODE Enum. There are several types of accounts that can be opened on a trade server. The type of account on which an MQL5 program is running can be found out using the ENUM_ACCOUNT_TRADE_MODE enumeration.
Attributes:
DEMO- Demo accountCONTEST- Contest accountREAL- Real Account
TickFlag Objects
class TickFlag(Repr, IntFlag)
TICK_FLAG Enum. TICK_FLAG defines possible flags for ticks. These flags are used to describe ticks obtained by the copy_ticks_from() and copy_ticks_range() functions.
Attributes:
BIDint - Bid price changedASKint - Ask price changedLASTint - Last price changedVOLUMEint - Volume changedBUYint - last Buy price changedSELLint - last Sell price changed
TradeRetcode Objects
class TradeRetcode(Repr, IntEnum)
TRADE_RETCODE Enum. Return codes for order send/check operations
Attributes:
-
REQUOTEint - Requote -
REJECTint - Request rejected -
CANCELint - Request canceled by trader -
PLACEDint - Order placed -
DONEint - Request completed -
DONE_PARTIALint - Only part of the request was completed -
ERRORint - Request processing error -
TIMEOUTint - Request canceled by timeout -
INVALIDint - Invalid request -
INVALID_VOLUMEint - Invalid volume in the request -
INVALID_PRICEint - Invalid price in the request -
INVALID_STOPSint - Invalid stops in the request -
TRADE_DISABLEDint - Trade is disabled -
MARKET_CLOSEDint - Market is closed -
NO_MONEYint - There is not enough money to complete the request -
PRICE_CHANGEDint - Prices changed -
PRICE_OFFint - There are no quotes to process the request -
INVALID_EXPIRATIONint - Invalid order expiration date in the request -
ORDER_CHANGEDint - Order state changed -
TOO_MANY_REQUESTSint - Too frequent requests -
NO_CHANGESint - No changes in request -
SERVER_DISABLES_ATint - Autotrading disabled by server -
CLIENT_DISABLES_ATint - Autotrading disabled by client terminal -
LOCKEDint - Request locked for processing -
FROZENint - Order or position frozen -
INVALID_FILLint - Invalid order filling type -
CONNECTIONint - No connection with the trade server -
ONLY_REALint - Operation is allowed only for live accounts -
LIMIT_ORDERSint - The number of pending orders has reached the limit -
LIMIT_VOLUMEint - The volume of orders and positions for the symbol has reached the limit -
INVALID_ORDERint - Incorrect or prohibited order type -
POSITION_CLOSEDint - Position with the specified POSITION_IDENTIFIER has already been closed -
INVALID_CLOSE_VOLUMEint - A close volume exceeds the current position volume -
CLOSE_ORDER_EXISTint - A close order already exists for a specified position. This may happen when working in the hedging system: � when attempting to close a position with an opposite one, while close orders for the position already exist � when attempting to fully or partially close a position if the total volume of the already present close orders and the newly placed one exceeds the current position volume -
LIMIT_POSITIONSint - The number of open positions simultaneously present on an account can be limited by the server settings.After a limit is reached, the server returns the TRADE_RETCODE_LIMIT_POSITIONS error when attempting to place an order. The limitation operates differently depending on the position accounting type: � Netting � number of open positions is considered. When a limit is reached, the platform does not let placing new orders whose execution may increase the number of open positions. In fact, the platform allows placing orders only for the symbols that already have open positions. The current pending orders are not considered since their execution may lead to changes in the current positions but it cannot increase their number.� Hedging � pending orders are considered together with open positions, since a pending order activation always leads to opening a new position. When a limit is reached, the platform does not allow placing both new market orders for opening positions and pending orders.
-
REJECT_CANCELint - The pending order activation request is rejected, the order is canceled. -
LONG_ONLYint - The request is rejected, because the "Only long positions are allowed" rule is set for the symbol (POSITION_TYPE_BUY) -
SHORT_ONLYint - The request is rejected, because the "Only short positions are allowed" rule is set for the symbol (POSITION_TYPE_SELL) -
CLOSE_ONLYint - The request is rejected, because the "Only position closing is allowed" rule is set for the symbol -
FIFO_CLOSEint - The request is rejected, because "Position closing is allowed only by FIFO rule" flag is set for the trading account (ACCOUNT_FIFO_CLOSE=true)
AccountStopOutMode Objects
class AccountStopOutMode(Repr, IntEnum)
ACCOUNT_STOPOUT_MODE Enum.
Attributes:
PERCENTint - Account stop out mode in percentsMONEYint - Account stop out mode in money
AccountMarginMode Objects
class AccountMarginMode(Repr, IntEnum)
ACCOUNT_MARGIN_MODE Enum.
Attributes:
-
RETAIL_NETTINGint - 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). -
EXCHANGEint - 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. -
HEDGINGint - Used for the exchange markets where individual positions are possible (hedging, multiple positions can exist for one symbol). The margin is calculated based on the symbol type (SYMBOL_TRADE_CALC_MODE) taking into account the hedged margin (SYMBOL_MARGIN_HEDGED).
aiomql.core.errors
Error Objects
class Error()
Error class for handling errors from MetaTrader 5.
aiomql.core.exceptions
Exceptions for the aiomql package.
LoginError Objects
class LoginError(Exception)
Raised when an error occurs when logging in.
VolumeError Objects
class VolumeError(Exception)
Raised when a volume is not valid or out of range for a symbol.
SymbolError Objects
class SymbolError(Exception)
Raised when a symbol is not provided where required or not available in the Market Watch.
OrderError Objects
class OrderError(Exception)
Raised when an error occurs when working with the order class.
aiomql.core.meta_trader
MetaTrader Objects
class MetaTrader(metaclass=BaseMeta)
__aenter__
async def __aenter__() -> 'MetaTrader'
Async context manager entry point. Initializes the connection to the MetaTrader terminal.
Returns:
MetaTrader- An instance of the MetaTrader class.
__aexit__
async def __aexit__(exc_type, exc_val, exc_tb)
Async context manager exit point. Closes the connection to the MetaTrader terminal.
login
async def login(login: int,
password: str,
server: str,
timeout: int = 60000) -> bool
Connects to the MetaTrader terminal using the specified login, password and server.
Arguments:
loginint - The trading account number.passwordstr - The trading account password.serverstr - The trading server name.timeoutint - The timeout for the connection in seconds.
Returns:
bool- True if successful, False otherwise.
initialize
async def initialize(path: str = "",
login: int = 0,
password: str = "",
server: str = "",
timeout: int | None = None,
portable=False) -> bool
Initializes the connection to the MetaTrader terminal. All parameters are optional.
Arguments:
pathstr - The path to the MetaTrader terminal executable.loginint - The trading account number.passwordstr - The trading account password.serverstr - The trading server name.timeoutint - The timeout for the connection in seconds.portablebool - If True, the terminal will be launched in portable mode.
Returns:
bool- True if successful, False otherwise.
shutdown
async def shutdown() -> None
Closes the connection to the MetaTrader terminal.
Returns:
None- None
version
async def version() -> tuple[int, int, str] | None
account_info
async def account_info() -> AccountInfo | None
orders_get
async def orders_get(group: str = "",
ticket: int = 0,
symbol: str = "") -> tuple[TradeOrder] | None
Get active orders with the ability to filter by symbol or ticket. There are three call options. Call without parameters. Return active orders on all symbols
Arguments:
-
symbolstr - Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. -
groupstr - 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. -
ticketint - Order ticket (ORDER_TICKET). Optional named parameter.
Returns:
list[TradeOrder]- A list of active trade orders as TradeOrder objects
aiomql.core.models
AccountInfo Objects
class AccountInfo(Base)
Account Information Class.
Attributes:
login- intpassword- strserver- strtrade_mode- AccountTradeModebalance- floatleverage- floatprofit- floatpoint- floatamount- float = 0equity- floatcredit- floatmargin- floatmargin_level- floatmargin_free- floatmargin_mode- AccountMarginModemargin_so_mode- AccountStopoutModemargin_so_call- floatmargin_so_so- floatmargin_initial- floatmargin_maintenance- floatfifo_close- boollimit_orders- floatcurrency- str = "USD"trade_allowed- bool = Truetrade_expert- bool = Truecurrency_digits- intassets- floatliabilities- floatcommission_blocked- floatname- strcompany- str
TerminalInfo Objects
class TerminalInfo(Base)
Terminal information class. Holds information about the terminal.
Attributes:
community_account- boolcommunity_connection- boolconnected- booldlls_allowed- booltrade_allowed- booltradeapi_disabled- boolemail_enabled- boolftp_enabled- boolnotifications_enabled- boolmqid- boolbuild- intmaxbars- intcodepage- intping_last- intcommunity_balance- floatretransmission- floatcompany- strname- strlanguage- strpath- strdata_path- strcommondata_path- str
SymbolInfo Objects
class SymbolInfo(Base)
Symbol Information Class. Symbols are financial instruments available for trading in the MetaTrader 5 terminal.
Attributes:
name- strcustom- boolchart_mode- SymbolChartModeselect- boolvisible- boolsession_deals- intsession_buy_orders- intsession_sell_orders- intvolume- floatvolumehigh- floatvolumelow- floattime- intdigits- intspread- floatspread_float- boolticks_bookdepth- inttrade_calc_mode- SymbolCalcModetrade_mode- SymbolTradeModestart_time- intexpiration_time- inttrade_stops_level- inttrade_freeze_level- inttrade_exemode- SymbolTradeExecutionswap_mode- SymbolSwapModeswap_rollover3days- DayOfWeekmargin_hedged_use_leg- boolexpiration_mode- intfilling_mode- intorder_mode- intorder_gtc_mode- SymbolOrderGTCModeoption_mode- SymbolOptionModeoption_right- SymbolOptionRightbid- floatbidhigh- floatbidlow- floatask- floataskhigh- floatasklow- floatlast- floatlasthigh- floatlastlow- floatvolume_real- floatvolumehigh_real- floatvolumelow_real- floatoption_strike- floatpoint- floattrade_tick_value- floattrade_tick_value_profit- floattrade_tick_value_loss- floattrade_tick_size- floattrade_contract_size- floattrade_accrued_interest- floattrade_face_value- floattrade_liquidity_rate- floatvolume_min- floatvolume_max- floatvolume_step- floatvolume_limit- floatswap_long- floatswap_short- floatmargin_initial- floatmargin_maintenance- floatsession_volume- floatsession_turnover- floatsession_interest- floatsession_buy_orders_volume- floatsession_sell_orders_volume- floatsession_open- floatsession_close- floatsession_aw- floatsession_price_settlement- floatsession_price_limit_min- floatsession_price_limit_max- floatmargin_hedged- floatprice_change- floatprice_volatility- floatprice_theoretical- floatprice_greeks_delta- floatprice_greeks_theta- floatprice_greeks_gamma- floatprice_greeks_vega- floatprice_greeks_rho- floatprice_greeks_omega- floatprice_sensitivity- floatbasis- strcategory- strcurrency_base- strcurrency_profit- strcurrency_margin- Anybank- strdescription- strexchange- strformula- Anyisin- Anyname- strpage- strpath- str
BookInfo Objects
class BookInfo(Base)
Book Information Class.
Attributes:
type- BookTypeprice- floatvolume- floatvolume_dbl- float
TradeOrder Objects
class TradeOrder(Base)
Trade Order Class.
Attributes:
ticket- inttime_setup- inttime_setup_msc- inttime_expiration- inttime_done- inttime_done_msc- inttype- OrderTypetype_time- OrderTimetype_filling- OrderFillingstate- intmagic- intposition_id- intposition_by_id- intreason- OrderReasonvolume_current- floatvolume_initial- floatprice_open- floatsl- floattp- floatprice_current- floatprice_stoplimit- floatsymbol- strcomment- strexternal_id- str
TradeRequest Objects
class TradeRequest(Base)
Trade Request Class.
Attributes:
action- TradeActiontype- OrderTypeorder- intsymbol- strvolume- floatsl- floattp- floatprice- floatdeviation- floatstop_limit- floattype_time- OrderTimetype_filling- OrderFillingexpiration- intposition- intposition_by- intcomment- strmagic- intdeviation- intcomment- str
OrderCheckResult Objects
class OrderCheckResult(Base)
Order Check Result
Attributes:
retcode- intbalance- floatequity- floatprofit- floatmargin- floatmargin_free- floatmargin_level- floatcomment- strrequest- TradeRequest
OrderSendResult Objects
class OrderSendResult(Base)
Order Send Result
Attributes:
retcode- intdeal- intorder- intvolume- floatprice- floatbid- floatask- floatcomment- strrequest- TradeRequestrequest_id- intretcode_external- intprofit- float
TradePosition Objects
class TradePosition(Base)
Trade Position
Attributes:
ticket- inttime- inttime_msc- inttime_update- inttime_update_msc- inttype- OrderTypemagic- floatidentifier- intreason- PositionReasonvolume- floatprice_open- floatsl- floattp- floatprice_current- floatswap- floatprofit- floatsymbol- strcomment- strexternal_id- str
TradeDeal Objects
class TradeDeal(Base)
Trade Deal
Attributes:
ticket- intorder- inttime- inttime_msc- inttype- DealTypeentry- DealEntrymagic- intposition_id- intreason- DealReasonvolume- floatprice- floatcommission- floatswap- floatprofit- floatfee- floatsl- floattp- floatsymbol- strcomment- strexternal_id- str
aiomql.core
aiomql.executor
Executor Objects
class Executor()
Executor class for running multiple strategies on multiple symbols concurrently.
Attributes:
executorThreadPoolExecutor - The executor object.workerslist - List of strategies.
add_workers
def add_workers(strategies: Sequence[type(Strategy)])
Add multiple strategies at once
Arguments:
strategiesSequence[Strategy] - A sequence of strategies.
remove_workers
def remove_workers(*symbols: Sequence[Symbol])
Removes any worker running on a symbol not successfully initialized.
Arguments:
*symbols- Successfully initialized symbols.
add_worker
def add_worker(strategy: type(Strategy))
Add a strategy instance to the list of workers
Arguments:
strategyStrategy - A strategy object
run
@staticmethod
def run(strategy: type(Strategy))
Wraps the coroutine trade method of each strategy with 'asyncio.run'.
Arguments:
strategyStrategy - A strategy object
execute
async def execute(workers: int = 0)
Run the strategies with a threadpool executor.
Arguments:
workers- Number of workers to use in executor pool. Defaults to zero which uses all workers.
Notes:
No matter the number specified, the executor will always use a minimum of 5 workers.
aiomql.history
History Objects
class History()
The history class handles completed trade deals and trade orders in the trading history of an account.
Attributes:
dealslist[TradeDeal] - Iterable of trade dealsorderslist[TradeOrder] - Iterable of trade orderstotal_deals- Total number of dealstotal_ordersint - Total number ordersgroupstr - Filter for selecting history by symbols.ticketint - Filter for selecting history by ticket numberpositionint - Filter for selecting history deals by positioninitializedbool - check if initial request has been sent to the terminal to get history.mt5MetaTrader - MetaTrader instanceconfigConfig - Config instance
__init__
def __init__(*,
date_from: datetime | float = 0,
date_to: datetime | float = 0,
group: str = "",
ticket: int = 0,
position: int = 0)
Arguments:
-
date_fromdatetime, float - Date the orders are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" -
date_todatetime, float - Date up to which the orders are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Defaults to the current time in "utc" -
groupstr - Filter for selecting history by symbols. -
ticketint - Filter for selecting history by ticket number -
positionint - Filter for selecting history deals by position
init
async def init(deals=True, orders=True) -> bool
Get history deals and orders
Arguments:
dealsbool - If true get history deals during initial request to terminalordersbool - If true get history orders during initial request to terminal
Returns:
bool- True if all requests were successful else False
get_deals
async def get_deals() -> list[TradeDeal]
Get deals from trading history using the parameters set in the constructor.
Returns:
list[TradeDeal]- A list of trade deals
deals_total
async def deals_total() -> int
Get total number of deals within the specified period in the constructor.
Returns:
int- Total number of Deals
get_orders
async def get_orders() -> list[TradeOrder]
Get orders from trading history using the parameters set in the constructor.
Returns:
list[TradeOrder]- A list of trade orders
orders_total
async def orders_total() -> int
Get total number of orders within the specified period in the constructor.
Returns:
int- Total number of orders
aiomql.lib.strategies.finger_trap
Entry Objects
@dataclass
class Entry()
Entry class for FingerTrap strategy.Will be used to store entry conditions and other entry related data.
Attributes:
bearishbool - True if the market is bearishbullishbool - True if the market is bullishrangingbool - True if the market is rangingsnoozefloat - Time to wait before checking for entry conditionstrendstr - The current trend of the marketlast_candleCandle - The last candle of the marketnewbool - True if the last candle is neworder_typeOrderType - The type of order to placepipsint - The number of pips to place the order from the current price
aiomql.lib.strategies
aiomql.lib.symbols.forex_symbol
ForexSymbol Objects
class ForexSymbol(Symbol)
Subclass of Symbol for Forex Symbols. Handles the conversion of currency and the computation of stop loss, take profit and volume.
pip
@property
def pip()
Returns the pip value of the symbol. This is ten times the point value for forex symbols.
Returns:
float- The pip value of the symbol.
compute_volume
async def compute_volume(*, amount: float, pips: float) -> float
Compute volume given an amount to risk and target pips. Round the computed volume to the nearest step.
Arguments:
amountfloat - Amount to risk. Given in terms of the account currency.pipsfloat - Target pips.
Returns:
float- volume
Raises:
VolumeError- If the computed volume is less than the minimum volume or greater than the maximum volume.
aiomql.lib.symbols
aiomql.lib.traders.simple_deal_trader
DealTrader Objects
class DealTrader(Trader)
A base class for placing trades based on the number of pips to target
create_order
async def create_order(*, order_type: OrderType, pips: float)
Using the number of target pips it determines the lot size, stop loss and take profit for the order, and updates the order object with the values.
Arguments:
order_typeOrderType - Type of orderpipsfloat - Target pips
aiomql.lib.traders
aiomql.lib
aiomql.order
Order Class
Order Objects
class Order(TradeRequest)
Trade order related functions and properties. Subclass of TradeRequest.
__init__
def __init__(**kwargs)
Initialize the order object with keyword arguments, symbol must be provided. Provide default values for action, type_time and type_filling if not provided.
Arguments:
-
**kwargs- Keyword arguments must match the attributes of TradeRequest as well as the attributes of Order class as specified in the annotations in the class definition.Default Values:
-
actionTradeAction.DEAL - Trade action -
type_timeOrderTime.DAY - Order time -
type_fillingOrderFilling.FOK - Order filling
Raises:
SymbolError- If symbol is not provided
orders_total
async def orders_total()
Get the number of active orders.
Returns:
(int)- total number of active orders
orders
async def orders() -> tuple[TradeOrder]
Get the list of active orders for the current symbol.
Returns:
tuple[TradeOrder]- A Tuple of active trade orders as TradeOrder objects
check
async def check() -> OrderCheckResult
Check funds sufficiency for performing a required trading operation and the possibility to execute it at
Returns:
OrderCheckResult- An OrderCheckResult object
Raises:
OrderError- If not successful
send
async def send() -> OrderSendResult
Send a request to perform a trading operation from the terminal to the trade server.
Returns:
OrderSendResult- An OrderSendResult object
Raises:
OrderError- If not successful
calc_margin
async def calc_margin() -> float
Return the required margin in the account currency to perform a specified trading operation.
Returns:
float- Returns float value if successful
Raises:
OrderError- If not successful
calc_profit
async def calc_profit() -> float
Return profit in the account currency for a specified trading operation.
Returns:
float- Returns float value if successful
Raises:
OrderError- If not successful
aiomql.positions
Handle Open positions.
Positions Objects
class Positions()
Get Open Positions.
Attributes:
symbolstr - Financial instrument name.groupstr - 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.ticketint - Position ticket.mt5MetaTrader - MetaTrader instance.
__init__
def __init__(*, symbol: str = "", group: str = "", ticket: int = 0)
Get Open Positions.
Arguments:
symbolstr - Financial instrument name.groupstr - 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.ticketint - Position ticket
positions_total
async def positions_total() -> int
Get the number of open positions.
Returns:
int- Return total number of open positions
positions_get
async def positions_get()
Get open positions with the ability to filter by symbol or ticket.
Returns:
list[TradePosition]- A list of open trade positions
close_all
async def close_all() -> int
Close all open positions for the trading account.
Returns:
int- Return number of positions closed.
aiomql.ram
Risk Assessment and Management
RAM Objects
class RAM()
__init__
def __init__(**kwargs)
Risk Assessment and Management. All provided keyword arguments are set as attributes.
Arguments:
-
kwargsDict - Keyword arguments.Defaults:
-
risk_to_rewardfloat - Risk to reward ratio 1 -
riskfloat - Percentage of account balance to risk per trade 0.01 # 1% -
amountfloat - Amount to risk per trade in terms of base currency 10 -
pipsfloat - Target pips 10 -
volumefloat - Volume to trade 0.05
get_amount
async def get_amount() -> float
Calculate the amount to risk per trade.
Returns:
float- Amount to risk per trade
aiomql.records
This module contains the Records class, which is used to read and update trade records from csv files.
Records Objects
class Records()
This utility class read trade records from csv files, and update them based on their closing positions.
Attributes:
config- Config objectrecords_dir(Path)- Path to directory containing record of placed trades, If not given takes the default from the config
__init__
def __init__(records_dir: Path = '')
Initialize the Records class.
Arguments:
records_dirPath - Path to directory containing record of placed trades.
get_records
async def get_records()
Get trade records from records_dir folder
Yields:
files- Trade record files
read_update
async def read_update(file: Path)
Read and update trade records
Arguments:
file- Trade record file
update_rows
async def update_rows(rows: list[dict]) -> list[dict]
Update the rows of entered trades in the csv file with the actual profit.
Arguments:
rows- A list of dictionaries from the dictionary writer object of the csv file.
Returns:
list[dict]- A list of dictionaries with the actual profit and win status.
update_records
async def update_records()
Update trade records in the records_dir folder.
update_record
async def update_record(file: Path | str)
Update a single trade record file.
aiomql.result
Result Objects
class Result()
A base class for handling trade results and strategy parameters for record keeping and reference purpose. The data property must be implemented in the subclass
Attributes:
configConfig - The configuration objectname- Any desired name for the result file object
__init__
def __init__(result: OrderSendResult, parameters: dict = None, name: str = '')
Prepare result data
Arguments:
result: parameters: name:
to_csv
async def to_csv()
Record trade results and associated parameters as a csv file
save_csv
async def save_csv()
Save trade results and associated parameters as a csv file in a separate thread
aiomql.strategy
The base class for creating strategies.
Strategy Objects
class Strategy(ABC)
The base class for creating strategies.
Attributes:
-
symbolSymbol - The Financial Instrument as a Symbol Object -
parametersDict - A dictionary of parameters for the strategy.Class Attributes:
-
namestr - A name for the strategy. -
accountAccount - Account instance. -
mt5MetaTrader - MetaTrader instance. -
configConfig - Config instance.
Notes:
Define the name of a strategy as a class attribute. If not provided, the class name will be used as the name.
__init__
def __init__(*, symbol: Symbol, params: dict = None)
Initiate the parameters dict and add name and symbol fields. Use class name as strategy name if name is not provided
Arguments:
symbolSymbol - The Financial instrumentparamsDict - Trading strategy parameters
sleep
@staticmethod
async def sleep(secs: float)
Sleep for the needed amount of seconds in between requests to the terminal. computes the accurate amount of time needed to sleep ensuring that the next request is made at the start of a new bar and making cooperative multitasking possible.
Arguments:
secsfloat - The time in seconds. Usually the timeframe you are trading on.
trade
@abstractmethod
async def trade()
Place trades using this method. This is the main method of the strategy. It will be called by the strategy runner.
aiomql.symbol
Symbol class for handling a financial instrument.
Symbol Objects
class Symbol(SymbolInfo)
Main class for handling a financial instrument. A subclass of SymbolInfo and Base it has attributes and methods for working with a financial instrument.
Attributes:
tickTick - Price tick object for instrumentaccount- An instance of the current trading account
Notes:
Full properties are on the SymbolInfo Object. Make sure Symbol is always initialized with a name argument
info_tick
async def info_tick(*, name: str = "") -> Tick
Get the current price tick of a financial instrument.
Arguments:
name- if name is supplied get price tick of that financial instrument
Returns:
Tick- Return a Tick Object
Raises:
ValueError- If request was unsuccessful and None was returned
symbol_select
async def symbol_select(*, enable: bool = True) -> bool
Select a symbol in the MarketWatch window or remove a symbol from the window. Update the select property
Arguments:
enablebool - Switch. Optional unnamed parameter. If 'false', a symbol should be removed from the MarketWatch window.
Returns:
bool- True if successful, otherwise � False.
info
async def info() -> SymbolInfo
Get data on the specified financial instrument and update the symbol object properties
Returns:
(SymbolInfo)- SymbolInfo if successful
Raises:
ValueError- If request was unsuccessful and None was returned
init
async def init() -> bool
Initialized the symbol by pulling properties from the terminal
Returns:
bool- Returns True if symbol info was successful initialized
book_add
async def book_add() -> bool
Subscribes the MetaTrader 5 terminal to the Market Depth change events for a specified symbol. If the symbol is not in the list of instruments for the market, This method will return False
Returns:
bool- True if successful, otherwise � False.
book_get
async def book_get() -> tuple[BookInfo]
Returns a tuple of BookInfo featuring Market Depth entries for the specified symbol.
Returns:
tuple[BookInfo]- Returns the Market Depth contents as a tuples of BookInfo Objects
Raises:
ValueError- If request was unsuccessful and None was returned
book_release
async def book_release() -> bool
Cancels subscription of the MetaTrader 5 terminal to the Market Depth change events for a specified symbol.
Returns:
bool- True if successful, otherwise � False.
compute_volume
async def compute_volume(*, amount: float, pips: float) -> float
Computes the volume of a trade based on the amount and the number of pips to target
Arguments:
amountfloat - Amount to risk in the tradepipsfloat - Number of pips to target
Returns:
float- Returns the volume of the trade
currency_conversion
async def currency_conversion(*, amount: float, base: str,
quote: str) -> float
Convert from one currency to the other.
Arguments:
amount- amount to convert given in terms of the quote currencybase- The base currency of the pairquote- The quote currency of the pair
Returns:
float- Amount in terms of the base currency or None if it failed to convert
Raises:
ValueError- If conversion is impossible
copy_rates_from
async def copy_rates_from(*, timeframe: TimeFrame, date_from: datetime | int,
count: int) -> Candles
Get bars from the MetaTrader 5 terminal starting from the specified date.
Arguments:
-
timeframeTimeFrame - Timeframe the bars are requested for. Set by a value from the TimeFrame enumeration. Required unnamed parameter. -
date_fromdatetime | 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. -
countint - Number of bars to receive. Required unnamed parameter.
Returns:
Candles- Returns a Candles object as a collection of rates ordered chronologically
Raises:
ValueError- If request was unsuccessful and None was returned
copy_rates_from_pos
async def copy_rates_from_pos(*,
timeframe: TimeFrame,
count: int = 500,
start_position: int = 0) -> Candles
Get bars from the MetaTrader 5 terminal starting from the specified index.
Arguments:
-
timeframeTimeFrame - TimeFrame value from TimeFrame Enum. Required keyword only parameter -
countint - Number of bars to return. Keyword argument defaults to 500 -
start_positionint - Initial index of the bar the data are requested from. The numbering of bars goes from present to past. Thus, the zero bar means the current one. Keyword argument defaults to 0.
Returns:
Candles- Returns a Candles object as a collection of rates ordered chronologically.
Raises:
ValueError- If request was unsuccessful and None was returned
copy_rates_range
async def copy_rates_range(*, timeframe: TimeFrame, date_from: datetime | int,
date_to: datetime | int) -> Candles
Get bars in the specified date range from the MetaTrader 5 terminal.
Arguments:
-
timeframeTimeFrame - Timeframe for the bars using the TimeFrame enumeration. Required unnamed parameter. -
date_fromdatetime | int - Date the bars are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time >= date_from are returned. Required unnamed parameter. -
date_todatetime | int - Date, up to which the bars are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time <= date_to are returned. Required unnamed parameter.
Returns:
Candles- Returns a Candles object as a collection of rates ordered chronologically.
Raises:
ValueError- If request was unsuccessful and None was returned
copy_ticks_from
async def copy_ticks_from(*,
date_from: datetime | int,
count: int = 100,
flags: CopyTicks = CopyTicks.ALL) -> Ticks
Get ticks from the MetaTrader 5 terminal starting from the specified date.
Args: date_from (datetime | int): Date the ticks are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01.
count (int): Number of requested ticks. Defaults to 100
flags (CopyTicks): A flag to define the type of the requested ticks from CopyTicks enum. INFO is the default
Returns:
Candles- Returns a Candles object as a collection of ticks ordered chronologically.
Raises:
ValueError- If request was unsuccessful and None was returned
copy_ticks_range
async def copy_ticks_range(*,
date_from: datetime | int,
date_to: datetime | int,
flags: CopyTicks = CopyTicks.ALL) -> Ticks
Get ticks for the specified date range from the MetaTrader 5 terminal.
Arguments:
-
date_from- Date the bars are requested from. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time >= date_from are returned. Required unnamed parameter. -
date_to- Date, up to which the bars are requested. Set by the 'datetime' object or as a number of seconds elapsed since 1970.01.01. Bars with the open time <= date_to are returned. Required unnamed parameter.flags (CopyTicks):
Returns:
Candles- Returns a Candles object as a collection of ticks ordered chronologically.
Raises:
ValueError- If request was unsuccessful and None was returned.
aiomql.terminal
Terminal related functions and properties
Terminal Objects
class Terminal(TerminalInfo)
Terminal Class. Get information about the MetaTrader 5 terminal. The class is a subclass of the TerminalInfo class. It inherits all the attributes and methods of the TerminalInfo class and adds some useful methods.
Notes:
Other attributes are defined in the TerminalInfo Class
initialize
async def initialize() -> bool
Establish a connection with the MetaTrader 5 terminal. There are three call options. Call without parameters. The terminal for connection is found automatically. Call specifying the path to the MetaTrader 5 terminal we want to connect to. word path as a keyword argument Call specifying the trading account path and parameters i.e login, password, server, as keyword arguments, path can be omitted.
Returns:
bool- True if successful else False
version
async def version()
Get the MetaTrader 5 terminal version. This method returns the terminal version, build and release date as a tuple of three values
Returns:
Version- version of tuple as Version object
Raises:
ValueError- If the terminal version cannot be obtained
info
async def info()
Get the connected MetaTrader 5 client terminal status and settings. gets terminal info in the form of a named tuple structure (namedtuple). Return None in case of an error. The info on the error can be obtained using last_error().
Returns:
Terminal- Terminal status and settings as a terminal object.
symbols_total
async def symbols_total() -> int
Get the number of all financial instruments in the MetaTrader 5 terminal.
Returns:
int- Total number of available symbols
aiomql.ticks
Module for working with price ticks.
Tick Objects
class Tick()
Price Tick of a Financial Instrument.
Attributes:
timeint - Time of the last prices update for the symbolbidfloat - Current Bid priceaskfloat - Current Ask pricelastfloat - Price of the last deal (Last)volumefloat - Volume for the current Last pricetime_mscint - Time of the last prices update for the symbol in millisecondsflagsTickFlag - Tick flagsvolume_realfloat - Volume for the current Last priceIndexint - Custom attribute representing the position of the tick in a sequence.
set_attributes
def set_attributes(**kwargs)
Set attributes from keyword arguments
Ticks Objects
class Ticks()
Container data class for price ticks. Arrange in chronological order. Supports iteration, slicing and assignment
Arguments:
dataDataFrame | tuple[tuple] - Dataframe of price ticks or a tuple of tuples
Arguments:
flipbool - If flip is True reverse data chronological order.
Attributes:
data- Dataframe Object holding the ticks
__init__
def __init__(*, data: DataFrame | Iterable, flip=False)
Initialize the Ticks class. Creates a DataFrame of price ticks from the data argument.
Arguments:
dataDataFrame | Iterable - Dataframe of price ticks or any iterable object that can be converted to a pandas DataFrameflipbool - If flip is True reverse data chronological order.
ta
@property
def ta()
Access to the pandas_ta library for performing technical analysis on the underlying data attribute.
Returns:
pandas_ta- The pandas_ta library
ta_lib
@property
def ta_lib()
Access to the ta library for performing technical analysis. Not dependent on the underlying data attribute.
Returns:
ta- The ta library
data
@property
def data() -> DataFrame
DataFrame of price ticks arranged in chronological order.
rename
def rename(inplace=True, **kwargs) -> _Ticks | None
Rename columns of the candle class.
Arguments:
inplacebool - Rename the columns inplace or return a new instance of the class with the renamed columns**kwargs- The new names of the columns
Returns:
Ticks- A new instance of the class with the renamed columns if inplace is False.None- If inplace is True
aiomql.trader
Trader class module. Handles the creation of an order and the placing of trades
Trader Objects
class Trader()
Base class for creating a Trader object. Handles the creation of an order and the placing of trades
Attributes:
-
symbolSymbol - Financial instrument class Symbol class or any subclass of it. -
ramRAM - RAM instance -
orderOrder - Trade orderClass Attributes:
-
namestr - A name for the strategy. -
accountAccount - Account instance. -
mt5MetaTrader - MetaTrader instance. -
configConfig - Config instance.
__init__
def __init__(*, symbol: Symbol, ram: RAM = None)
Initializes the order object and RAM instance
Arguments:
symbolSymbol - Financial instrumentramRAM - Risk Assessment and Management instance
create_order
async def create_order(*, order_type: OrderType, **kwargs)
Complete the order object with the required values. The default trader object uses the values specified in the default RAM instance to determine the take profit, stop loss, volume, and number of pips to target.
Arguments:
order_typeOrderType - Type of orderkwargs- keyword arguments as required for the specific trader
set_order_limits
async def set_order_limits(pips: float)
Sets the stop loss and take profit for the order. This method uses pips as defined for forex instruments.
Arguments:
pips- Target pips
place_trade
async def place_trade(order_type: OrderType, params: dict = None, **kwargs)
Places a trade based on the order_type.
Arguments:
order_typeOrderType - Type of orderparams- parameters to be saved with the tradekwargs- keyword arguments as required for the specific trader
aiomql.utils
Utility functions for aiomql.
dict_to_string
def dict_to_string(data: dict, multi=False) -> str
Convert a dict to a string. Use for logging.
Arguments:
datadict - The dict to convert.multibool, optional - If True, each key-value pair will be on a new line. Defaults to False.
Returns:
str- The string representation of the dict.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aiomql-3.0.2.tar.gz.
File metadata
- Download URL: aiomql-3.0.2.tar.gz
- Upload date:
- Size: 102.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f2cc9a7e8e62609a6a1a3586fead4e91530744d33ca7a72a797e251feb52ed34
|
|
| MD5 |
82da01c695aaf7adae4580502c148423
|
|
| BLAKE2b-256 |
9ed0751ed3d5c0ba4733cb4a4f9630c40c8b6435a342cdcec057ee34e0161ef8
|
File details
Details for the file aiomql-3.0.2-py3-none-any.whl.
File metadata
- Download URL: aiomql-3.0.2-py3-none-any.whl
- Upload date:
- Size: 69.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d56ecd541666023e32e57fa96c38a2f6abf65bebe3a1417563700f92d3eca089
|
|
| MD5 |
e0e0e9f98a7d0a33fe943d589ac57df7
|
|
| BLAKE2b-256 |
2ee369e549fd26e63f983f9ae1e9d4f2a00bd8d3d5a988bf5ea372418ea91b7d
|