bbstrader.metatrader package
Module contents
Overview
This MetaTrader Module provides a direct interface to the MetaTrader 5 trading platform, enabling seamless integration of Python-based trading strategies with a live trading environment. It offers a comprehensive set of tools for account management, trade execution, market data retrieval, and risk management, all tailored for the MetaTrader 5 platform.
Features
Direct MetaTrader 5 Integration: Connects to the MetaTrader 5 terminal to access its full range of trading functionalities.
Account and Trade Management: Provides tools for querying account information, managing open positions, and executing trades.
Market Data Retrieval: Fetches historical and real-time market data, including rates and ticks, directly from MetaTrader 5.
Risk Management: Includes utilities for managing risk, such as setting stop-loss and take-profit levels.
Trade Copying: Functionality to copy trades between different MetaTrader 5 accounts.
Components
Account: Manages account information, including balance, equity, and margin.
Broker: Handles the connection to the MetaTrader 5 terminal.
Copier: Copies trades between accounts.
Rates: Retrieves historical and current market rates.
Risk: Provides risk management functionalities.
Trade: Manages trade execution and position management.
Utils: Contains utility functions for the MetaTrader module.
Examples
>>> from bbstrader.metatrader import Account
>>> account = Account()
>>> print(account.get_account_info())
Notes
This module requires the MetaTrader 5 terminal to be installed and running.
Submodules
bbstrader.metatrader.account module
- class bbstrader.metatrader.account.Account(broker: Broker | None = None, **kwargs)[source]
Bases:
objectThe Account class is utilized to retrieve information about the current trading account or a specific account. It enables interaction with the MT5 terminal to manage account details, including account informations, terminal status, financial instrument details, active orders, open positions, and trading history.
Example
>>> # Instantiating the Account class >>> account = Account()
>>> # Getting account information >>> account_info = account.get_account_info()
>>> # Getting terminal information >>> terminal_info = account.get_terminal_info()
>>> # Getting active orders >>> orders = account.get_orders()
>>> # Fetching open positions >>> positions = account.get_positions()
>>> # Accessing trade history >>> from_date = datetime(2020, 1, 1) >>> to_date = datetime.now() >>> trade_history = account.get_trade_history(from_date, to_date)
- property balance: float
- property currency: str
- property equity: float
- get_account_info(account: int | None = None, password: str | None = None, server: str | None = None, timeout: int | None = 60000, path: str | None = None) AccountInfo | None[source]
Get info on the current trading account or a specific account .
- Parameters:
account (int, optinal) – MT5 Trading account number.
password (str, optinal) – MT5 Trading account password.
server (str, optinal) – MT5 Trading account server [Brokers or terminal server [“demo”, “real”]] If no server is set, the last used server is applied automaticall
timeout (int, optinal) – Connection timeout in milliseconds. Optional named parameter. If not specified, the value of 60 000 (60 seconds) is applied. If the connection is not established within the specified time, the call is forcibly terminated and the exception is generated.
path (str, optional) – The path to the MetaTrader 5 terminal executable file. Defaults to None (e.g., “C:/Program Files/MetaTrader 5/terminal64.exe”).
Returns: - AccountInfo - None in case of an error
- Raises:
MT5TerminalError – A specific exception based on the error code.
- get_currency_rates(symbol: str) Dict[str, str][source]
- Parameters:
symbol (str) – The symbol for which to get currencies
- Returns:
base currency (bc)
margin currency (mc)
profit currency (pc)
account currency (ac)
- Exemple:
>>> account = Account() >>> account.get_currency_rates('EURUSD') {'bc': 'EUR', 'mc': 'EUR', 'pc': 'USD', 'ac': 'USD'}
- get_orders(symbol: str | None = None, group: str | None = None, ticket: int | None = None) List[TradeOrder] | None[source]
Get active orders with the ability to filter by symbol or ticket. There are four call options:
Call without parameters. Returns open positions for all symbols.
Call specifying a symbol, open positions should be received for.
Call specifying a group of symbols, open positions should be received for.
Call specifying a position ticket.
- Parameters:
symbol (Optional[str]) – Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored.
group (Optional[str]) – The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting a specified criteria for a symbol name.
ticket (Optional[int]) – Order ticket. Optional named parameter. Unique number assigned to each order.
to_df (bool) – If True, a DataFrame is returned.
- Returns:
List of TradeOrder .
- Return type:
[List[TradeOrder] | None]
Notes
The method allows receiving all history orders within a specified period. The group parameter may contain several comma-separated conditions. A condition can be set as a mask using ‘*’.
The logical negation symbol ‘!’ can be used for exclusion. All conditions are applied sequentially, which means conditions for inclusion in a group should be specified first, followed by an exclusion condition.
For example, group=”*, !EUR” means that deals for all symbols should be selected first and the ones containing “EUR” in symbol names should be excluded afterward.
- get_orders_history(date_from: datetime = datetime.datetime(2000, 1, 1, 0, 0), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) DataFrame | List[TradeOrder] | None[source]
Get orders from trading history within the specified interval with the ability to filter by ticket or position.
You can call this method in the following ways:
Call with a time interval. Returns all deals falling within the specified interval.
Call specifying the order ticket. Returns all deals having the specified order ticket in the DEAL_ORDER property.
Call specifying the position ticket. Returns all deals having the specified position ticket in the DEAL_POSITION_ID property.
- Parameters:
date_from (datetime) – 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 (Optional[datetime]) – Same as date_from.
group (Optional[str]) – The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting specified criteria for a symbol name.
ticket (Optional[int]) – Order ticket to filter results. Optional parameter. If not specified, the filter is not applied.
position (Optional[int]) – Ticket of a position (stored in DEAL_POSITION_ID) to filter results. Optional parameter. If not specified, the filter is not applied.
to_df (bool) – If True, a DataFrame is returned.
save (bool) – If True, a CSV file will be created to save the history.
- Returns:
Union[pd.DataFrame, List[TradeOrder], None] - List of TradeOrder .
Notes
The method allows receiving all history orders within a specified period.
The group parameter may contain several comma-separated conditions.
A condition can be set as a mask using ‘*’.
The logical negation symbol ‘!’ can be used for exclusion.
All conditions are applied sequentially, which means conditions for inclusion in a group should be specified first, followed by an exclusion condition.
For example, group=”*, !EUR” means that deals for all symbols should be selected first and those containing “EUR” in symbol names should be excluded afterward.
Example
>>> # Get the number of deals in history >>> from datetime import datetime >>> from_date = datetime(2020, 1, 1) >>> to_date = datetime.now() >>> account = Account() >>> history = account.get_orders_history(from_date, to_date)
- get_positions(symbol: str | None = None, group: str | None = None, ticket: int | None = None) List[TradePosition] | None[source]
Get open positions with the ability to filter by symbol or ticket. There are four call options:
Call without parameters. Returns open positions for all symbols.
Call specifying a symbol. Returns open positions for the specified symbol.
Call specifying a group of symbols. Returns open positions for the specified group of symbols.
Call specifying a position ticket. Returns the position corresponding to the specified ticket.
- Parameters:
symbol (Optional[str]) – Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored.
group (Optional[str]) – The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting specified criteria for a symbol name.
ticket (Optional[int]) – Position ticket. Optional named parameter. A unique number assigned to each newly opened position. It usually matches the ticket of the order used to open the position, except when the ticket is changed as a result of service operations on the server, for example, when charging swaps with position re-opening.
- Returns:
List of TradePosition.
- Return type:
[List[TradePosition] | None]
Notes
The method allows receiving all open positions within a specified period.
The group parameter may contain several comma-separated conditions.
A condition can be set as a mask using ‘*’.
The logical negation symbol ‘!’ can be used for exclusion.
All conditions are applied sequentially, which means conditions for inclusion in a group should be specified first, followed by an exclusion condition.
For example, group=”*, !EUR” means that deals for all symbols should be selected first, and those containing “EUR” in symbol names should be excluded afterward.
- get_rate_info(symbol: str, timeframe: str = '1m') RateInfo | None[source]
Get the most recent bar for a specified symbol and timeframe.
- Parameters:
symbol (str) – The symbol for which to get the rate information.
timeframe (str) – The timeframe for the rate information. Default is ‘1m’. See
bbstrader.metatrader.utils.TIMEFRAMESfor supported timeframes.
- Returns:
The most recent bar as a RateInfo named tuple. None: If no rates are found or an error occurs.
- Return type:
- Raises:
MT5TerminalError – A specific exception based on the error code.
- get_stocks_from_country(country_code: str = 'USA', etf=False) List[str][source]
Retrieves a list of stock symbols from a specific country.
- Supported countries are:
Australia: AUS
Belgium: BEL
Denmark: DNK
Finland: FIN
France: FRA
Germany: DEU
Netherlands: NLD
Norway: NOR
Portugal: PRT
Spain: ESP
Sweden: SWE
United Kingdom: GBR
United States: USA
Switzerland: CHE
Hong Kong: HKG
Ireland: IRL
Austria: AUT
- Parameters:
country (str, optional) – The country code of stocks to retrieve. Defaults to ‘USA’.
- Returns:
A list of stock symbol names from the specified country.
- Return type:
list
- Raises:
ValueError – If an unsupported country is provided.
Notes
This mthods works primarly with brokers who specify the stock symbols type and exchanges, For other brokers use get_symbols() or this method will use it by default.
- get_stocks_from_exchange(exchange_code: str = 'XNYS', etf=True) List[str][source]
Get stock symbols from a specific exchange using the ISO Code for the exchange.
Supported exchanges are from Admirals Group AS products: * XASX: Australian Securities Exchange * XBRU: Euronext Brussels Exchange * XCSE: Copenhagen Stock Exchange * XHEL: NASDAQ OMX Helsinki * XPAR: Euronext Paris * XETR: Xetra Frankfurt * XOSL: Oslo Stock Exchange * XLIS: Euronext Lisbon * XMAD: Bolsa de Madrid * XSTO: NASDAQ OMX Stockholm * XLON: London Stock Exchange * NYSE: New York Stock Exchange * ARCA: NYSE ARCA * AMEX: NYSE AMEX * XNYS: New York Stock Exchange (AMEX, ARCA, NYSE) * NASDAQ: NASDAQ * BATS: BATS Exchange * XSWX: SWX Swiss Exchange * XAMS: Euronext Amsterdam
- Parameters:
exchange_code (str, optional) – The ISO code of the exchange.
etf (bool, optional) – If True, include ETFs from the exchange. Defaults to True.
- Returns:
A list of stock symbol names from the specified exchange.
- Return type:
list
- Raises:
ValueError – If an unsupported exchange is provided.
Notes
This mthods works primarly with brokers who specify the stock symbols type and exchanges, For other brokers use get_symbols() or this method will use it by default.
- get_symbol_info(symbol: str) SymbolInfo | None[source]
Get symbol properties
- Parameters:
symbol (str) – Symbol name
Returns: - SymbolInfo. - None in case of an error.
- Raises:
MT5TerminalError – A specific exception based on the error code.
- get_symbol_type(symbol: str) SymbolType[source]
Determines the type of a given financial instrument symbol.
- Parameters:
symbol (str) – The symbol of the financial instrument (e.g., GOOGL, EURUSD).
- Returns:
The type of the financial instrument, one of the following: - SymbolType.ETFs - SymbolType.BONDS - SymbolType.FOREX - SymbolType.FUTURES - SymbolType.STOCKS - SymbolType.INDICES - SymbolType.COMMODITIES - SymbolType.CRYPTO
- Return type:
SymbolType.unknown if the type cannot be determined.
- get_symbols(symbol_type: SymbolType | str = 'ALL', check_etf=False, save=False, file_name='symbols', include_desc=False, display_total=False) List[str][source]
Get all specified financial instruments from the MetaTrader 5 terminal.
- Parameters:
symbol_type (SymbolType | str) – The type of financial instruments to retrieve.
ALL (-) – For all available symbols
details. (- See bbstrader.metatrader.utils.SymbolType for more)
check_etf (bool) – If True and symbol_type is ‘etf’, check if the ETF description contains ‘ETF’.
save (bool) – If True, save the symbols to a file.
file_name (str) – The name of the file to save the symbols to (without the extension).
include_desc (bool) – If True, include the symbol’s description in the output and saved file.
- Returns:
A list of symbols.
- Return type:
list
- Raises:
Exception – If there is an error connecting to MT5 or retrieving symbols.
- get_terminal_info() TerminalInfo | None[source]
Get the connected MetaTrader 5 client terminal status and settings.
Returns: - TerminalInfo - None in case of an error
- Raises:
MT5TerminalError – A specific exception based on the error code.
- get_tick_info(symbol: str) TickInfo | None[source]
Get symbol tick properties
- Parameters:
symbol (str) – Symbol name
Returns: - TickInfo. - None in case of an error.
- Raises:
MT5TerminalError – A specific exception based on the error code.
- get_today_deals(id, group=None) List[TradeDeal][source]
Get all today deals for a specific symbol or group of symbols
- Parameters:
id (int) – strategy or expert id
group (str) – Symbol or group or symbol
- Returns:
List of today deals
- Return type:
List[TradeDeal]
- get_trades_history(date_from: datetime = datetime.datetime(2000, 1, 1, 0, 0), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) DataFrame | List[TradeDeal] | None[source]
Get deals from trading history within the specified interval with the ability to filter by ticket or position.
This method is useful if you need panda dataframe.
You can call this method in the following ways:
Call with a time interval. Returns all deals falling within the specified interval.
Call specifying the order ticket. Returns all deals having the specified order ticket in the DEAL_ORDER property.
Call specifying the position ticket. Returns all deals having the specified position ticket in the DEAL_POSITION_ID property.
- Parameters:
date_from (datetime) – 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 (Optional[datetime]) – Same as date_from.
group (Optional[str]) – The filter for arranging a group of necessary symbols. Optional named parameter. If the group is specified, the function returns only positions meeting specified criteria for a symbol name.
ticket (Optional[int]) – Ticket of an order (stored in DEAL_ORDER) for which all deals should be received. Optional parameter. If not specified, the filter is not applied.
position (Optional[int]) – Ticket of a position (stored in DEAL_POSITION_ID) for which all deals should be received. Optional parameter. If not specified, the filter is not applied.
to_df (bool) – If True, a DataFrame is returned.
- Returns:
TradeDeal in the form of a named tuple structure (namedtuple) or pd.DataFrame().
- Return type:
Union[pd.DataFrame, Tuple[TradeDeal], None]
Notes
The method allows receiving all history orders within a specified period.
The group parameter may contain several comma-separated conditions.
A condition can be set as a mask using ‘*’.
The logical negation symbol ‘!’ can be used for exclusion.
All conditions are applied sequentially, which means conditions for inclusion in a group should be specified first, followed by an exclusion condition.
For example, group=”*, !EUR” means that deals for all symbols should be selected first and those containing “EUR” in symbol names should be excluded afterward.
Example
>>> # Get the number of deals in history >>> from datetime import datetime >>> from_date = datetime(2020, 1, 1) >>> to_date = datetime.now() >>> account = Account() >>> history = account.get_trades_history(from_date, to_date)
- property info: AccountInfo
- property leverage: int
- property name: str
- property number: int
- property server: str
The name of the trade server to which the client terminal is connected. (e.g., ‘AdmiralsGroup-Demo’)
- property timezone: str | None
bbstrader.metatrader.broker module
- class bbstrader.metatrader.broker.Broker(name: str, timezone: str | None = None, custom_patterns: Dict[SymbolType, str] | None = None, custom_countries_stocks: Dict[str, str] | None = None, custom_exchanges: Dict[str, str] | None = None)[source]
Bases:
object- adjust_tick_values(symbol: str, tick_value_loss: float, tick_value_profit: float, contract_size: float) Tuple[float, float][source]
- property countries_stocks
- property exchanges
- get_currency_conversion_factor(symbol: str, base_currency: str, account_currency: str) float[source]
- get_symbol_type(symbol: str) SymbolType[source]
- get_symbols(symbol_type: SymbolType | str = 'ALL', check_etf: bool = False, save: bool = False, file_name: str = 'symbols', include_desc: bool = False, display_total: bool = False) List[str][source]
- get_symbols_by_category(symbol_type: SymbolType | str, category: str, category_map: Dict[str, str]) List[str][source]
- property name
- property timezone
- bbstrader.metatrader.broker.check_mt5_connection(*, path=None, login=None, password=None, server=None, timeout=60000, portable=False, **kwargs) bool[source]
Initialize the connection to the MetaTrader 5 terminal.
- Parameters:
path (str, optional) – Path to the MetaTrader 5 terminal executable file. Defaults to
None(e.g.,"C:/Program Files/MetaTrader 5/terminal64.exe").login (int, optional) – The login ID of the trading account. Defaults to
None.password (str, optional) – The password of the trading account. Defaults to
None.server (str, optional) – The name of the trade server to which the client terminal is connected. Defaults to
None.timeout (int, optional) – Connection timeout in milliseconds. Defaults to
60_000.portable (bool, optional) – If
True, the portable mode of the terminal is used. Defaults toFalse. See: https://www.metatrader5.com/en/terminal/help/start_advanced/start#portable
- Returns:
Trueif the connection is successfully established, otherwiseFalse.- Return type:
bool
Notes
If you want to launch multiple terminal instances:
First, launch each terminal in portable mode.
See instructions: https://www.metatrader5.com/en/terminal/help/start_advanced/start#configuration_file
bbstrader.metatrader.copier module
- bbstrader.metatrader.copier.RunCopier(source: dict, destinations: list, sleeptime: float, start_time: str, end_time: str, /, custom_logger=None, shutdown_event=None, log_queue=None)[source]
Initialize and run a TradeCopier instance in a single process.
This function serves as a straightforward wrapper to start a copying session that handles one source account and one or more destination accounts sequentially within the same thread. It does not create any new processes itself.
Use Cases
Simpler, command-line based use cases.
Scenarios where parallelism is not required.
As the target for
RunMultipleCopier, where each process handles a full source-to-destinations session.
- param source:
Configuration dictionary for the source account.
- type source:
dict
- param destinations:
A list of configuration dictionaries, one for each destination account to be processed sequentially.
- type destinations:
list
- param sleeptime:
The time in seconds to wait after completing a full cycle through all destinations.
- type sleeptime:
float
- param start_time:
The time of day to start copying (e.g.,
"08:00").- type start_time:
str
- param end_time:
The time of day to stop copying (e.g.,
"22:00").- type end_time:
str
- param custom_logger:
An optional custom logger instance.
- type custom_logger:
logging.Logger, optional
- param shutdown_event:
An event to signal shutdown.
- type shutdown_event:
multiprocessing.Event, optional
- param log_queue:
A queue for log messages.
- type log_queue:
multiprocessing.Queue, optional
- returns:
Runs until stopped via
shutdown_eventor external interruption.- rtype:
None
- bbstrader.metatrader.copier.RunMultipleCopier(accounts: List[dict], sleeptime: float = 0.01, start_delay: float = 1.0, start_time: str = None, end_time: str = None, shutdown_event=None, custom_logger=None, log_queue=None)[source]
Manage multiple, independent trade copying sessions in parallel.
This function acts as a high-level manager that takes a list of account setups and creates a separate, dedicated process for each one. Each process is responsible for copying from one source account to its associated list of destination accounts.
The parallelism occurs at the source account level. Within each spawned process, the destinations for that source are handled sequentially by
RunCopier.Example
An example
accountsstructure:accounts = [ {"source": {...}, "destinations": [{...}, {...}]}, # -> Process 1 {"source": {...}, "destinations": [{...}]} # -> Process 2 ]
- Parameters:
accounts (list of dict) – A list of account configurations. Each item must be a dictionary with a
sourcekey and adestinationskey.sleeptime (float, optional) – The sleep time passed down to each
RunCopierprocess.start_delay (float, optional) – A delay in seconds between starting each new process. Helps prevent resource contention by staggering the initialization of multiple MetaTrader 5 terminals.
start_time (str, optional) – The start time passed down to each
RunCopierprocess.end_time (str, optional) – The end time passed down to each
RunCopierprocess.shutdown_event (multiprocessing.Event, optional) – An event to signal shutdown to all child processes.
custom_logger (logging.Logger, optional) – An optional custom logger instance.
log_queue (multiprocessing.Queue, optional) – A queue for aggregating log messages from all child processes.
- Returns:
Runs until stopped via
shutdown_eventor external interruption.- Return type:
None
- class bbstrader.metatrader.copier.TradeCopier(source: Dict, destinations: List[dict], /, sleeptime: float = 0.1, start_time: str = None, end_time: str = None, *, custom_logger=None, shutdown_event=None, log_queue=None)[source]
Bases:
objectTradeCopierresponsible for copying trading orders and positions from a source account to multiple destination accounts.This class facilitates the synchronization of trades between a source account and multiple destination accounts. It handles copying new orders, modifying existing orders, updating and closing positions based on updates from the source account.
- custom_logger
- destinations: List[dict]
- end_time
- errors
- log_queue: Queue
- run()[source]
Entry point: Starts a dedicated worker thread for EACH destination account to run concurrently.
- property running
Check if the Trade Copier is running.
- shutdown_event: Event
- sleeptime
- source: Dict
- source_id: int
- source_isunique: bool
- start_copy_process(destination: dict)[source]
Worker process: copies orders and positions concurrently for a single destination account.
- start_time
- bbstrader.metatrader.copier.config_copier(source_section: str = None, dest_sections: str | List[str] = None, inifile: str | Path = None) Tuple[dict, List[dict]][source]
Read the configuration file and return the source and destination account details.
- Parameters:
inifile (str | Path) – The path to the INI configuration file.
source_section (str) – The section name of the source account, defaults to “SOURCE”.
dest_sections (str | List[str]) – The section name(s) of the destination account(s).
- Returns:
A tuple containing the source account and a list of destination accounts.
- Return type:
Tuple[dict, List[dict]]
Example
`python from pathlib import Path config_file = ~/.bbstrader/copier/copier.ini source, destinations = config_copier(config_file, "SOURCE", ["DEST1", "DEST2"]) `
- bbstrader.metatrader.copier.copier_worker_process(source_config: dict, destination_config: dict, sleeptime: float, start_time: str, end_time: str, /, custom_logger=None, shutdown_event=None, log_queue=None)[source]
A top-level worker function for handling a single source-to-destination copy task.
This function is the cornerstone of the robust, multi-process architecture. It is designed to be the target of a multiprocessing.Process. By being a top-level function, it avoids pickling issues on Windows and ensures that each copy task runs in a completely isolated process.
A controller (like a GUI or a master script) should spawn one process with this target for each destination account it needs to manage.
- Parameters:
source_config (dict) – Configuration dictionary for the source account. Must contain ‘login’, ‘password’, ‘server’, and ‘path’.
destination_config (dict) – Configuration dictionary for a single destination account.
sleeptime (float) – The time in seconds to wait between copy cycles.
start_time (str) – The time of day to start copying (e.g., “08:00”).
end_time (str) – The time of day to stop copying (e.g., “22:00”).
custom_logger – An optional custom logger instance.
shutdown_event (multiprocessing.Event) – An event object that, when set, will signal this process to terminate gracefully.
log_queue (multiprocessing.Queue) – A queue for sending log messages back to the parent process in a thread-safe manner.
bbstrader.metatrader.rates module
- class bbstrader.metatrader.rates.Rates(symbol: str, timeframe: str = 'D1', start_pos: int = 0, count: int | None = 10000000, **kwargs)[source]
Bases:
objectProvides methods to retrieve historical financial data from MetaTrader 5.
This class encapsulates interactions with the MetaTrader 5 (MT5) terminal to fetch historical price data for a given symbol and timeframe. It offers flexibility in retrieving data either by specifying a starting position and count of bars or by providing a specific date range .
Notes
All data is rerturn as pandas.DataFrame
1. Befor using this class, ensure that the Max bars in chart in your terminal is set to a value that is greater than the number of bars you want to retrieve or just set it to Unlimited. In your MT5 terminal, go to Tools -> Options -> Charts -> Max bars in chart.
2. The open, high, low, close, adjclose, returns, volume properties returns data in Broker’s timezone by default.
See bbstrader.metatrader.broker.check_mt5_connection() for more details on how to connect to MT5 terminal.
Example
>>> rates = Rates("EURUSD", "1h") >>> df = rates.get_historical_data( ... date_from=datetime(2023, 1, 1), ... date_to=datetime(2023, 1, 10), ... ) >>> print(df.head())
- property adjclose
- property close
- get_historical_data(date_from: datetime | Timestamp, date_to: datetime | Timestamp = Timestamp('2026-01-15 14:27:37.151623'), utc: bool = False, filter: bool | None = False, fill_na: bool | str | None = False, lower_colnames: bool | None = True, save_csv: bool | None = False) DataFrame | None[source]
Retrieves historical data within a specified date range.
- Parameters:
date_from – Starting date for data retrieval.
date_to – Ending date for data retrieval. Defaults to the current time.
utc – If True, the data will be in UTC timezone. Defaults to False.
filter – If True, the data will be filtered based on the trading sessions for the symbol. This is use when we want to use the data for backtesting using Zipline.
fill_na –
If True, the data will be filled with the nearest value. This is use only when filter is True and time frame is “1m” or “D1”, this is because we use
calendar.minutes_in_rangeorcalendar.sessions_in_rangewhere calendar is theExchangeCalendarfrom exchange_calendars package. So, for “1m” or “D1” time frame, the data will be filled with the nearest value because the data from MT5 will have approximately the same number of rows as the number of trading days or minute in the exchange calendar, so we can fill the missing data with the nearest value.But for other time frames, the data will be reindexed with the exchange calendar because the data from MT5 will have more rows than the number of trading days or minute in the exchange calendar. So we only take the data that is in the range of the exchange calendar sessions or minutes.
lower_colnames – If True, the column names will be converted to lowercase.
save_csv – File path to save the data as a CSV. If None, the data won’t be saved.
- Returns:
- A DataFrame containing historical data
if successful, otherwise None.
- Return type:
Union[pd.DataFrame, None]
- Raises:
ValueError – If the starting date is greater than the ending date.
Notes
The filter for this method can be use only for Admira Markets Group (AMG) symbols. The Datetime for this method is in Local timezone by default. All STK symbols are filtered based on the the exchange calendar. All FX symbols are filtered based on the
us_futurescalendar. All IDX symbols are filtered based on the exchange calendar of margin currency. All COMD symbols are filtered based on the exchange calendar of the commodity.
- get_rates_from(date_from: datetime | Timestamp, count: int = 10000000, filter=False, fill_na=False, lower_colnames=False, utc=False) DataFrame | None[source]
Retrieves historical data within a specified date range.
- Parameters:
date_from – Starting date for data retrieval. The data will be retrieved from this date going to the past.
count – Number of bars to retrieve.
filter – See Rates.get_historical_data for more details.
fill_na – See Rates.get_historical_data for more details.
lower_colnames – If True, the column names will be converted to lowercase.
utc (bool, optional) – If True, the data will be in UTC timezone. Defaults to False.
- Returns:
A DataFrame containing historical data if successful, otherwise None.
- Return type:
Union[pd.DataFrame, None]
- get_rates_from_pos(filter=False, fill_na=False, lower_colnames=False, utc=False) DataFrame | None[source]
Retrieves historical data starting from a specific position.
Uses the start_pos and count attributes specified during initialization to fetch data.
- Parameters:
filter – See Rates.get_historical_data for more details.
fill_na – See Rates.get_historical_data for more details.
lower_colnames – If True, the column names will be converted to lowercase.
utc (bool, optional) – If True, the data will be in UTC timezone. Defaults to False.
- Returns:
A DataFrame containing historical data if successful, otherwise None.
- Return type:
Union[pd.DataFrame, None]
- Raises:
ValueError – If start_pos or count is not provided during initialization.
Notes
The Datetime for this method is in Broker’s timezone.
- property high
- property low
- property open
- property returns
Fractional change between the current and a prior element.
Computes the fractional change from the immediately previous row by default. This is useful in comparing the fraction of change in a time series of elements.
Note
It calculates fractional change (also known as per unit change or relative change) and not percentage change. If you need the percentage change, multiply these values by 100.
- property volume
- bbstrader.metatrader.rates.download_historical_data(symbol, timeframe, date_from, date_to=Timestamp('2026-01-15 14:27:37.151668'), lower_colnames=True, utc=False, filter=False, fill_na=False, save_csv=False, **kwargs)[source]
Download historical data from MetaTrader 5 terminal. See Rates.get_historical_data for more details.
bbstrader.metatrader.risk module
- class bbstrader.metatrader.risk.RiskManagement(symbol: str, max_risk: float = 10.0, daily_risk: float | None = None, max_trades: int | None = None, std_stop: bool = False, pchange_sl: float | None = None, accountt_leverage: bool = True, time_frame: TimeFrame = 'D1', start_time: str = '1:00', finishing_time: str = '23:00', broker_tz: bool = False, sl: int | None = None, tp: int | None = None, be: int | None = None, rr: float = 3.0, **kwargs)[source]
Bases:
objectThe RiskManagement class provides foundational risk management functionalities for trading activities. It calculates risk levels, determines stop loss and take profit levels, and ensures trading activities align with predefined risk parameters.
- Exemple:
>>> risk_manager = RiskManagement( ... symbol="EURUSD", ... max_risk=5.0, ... daily_risk=2.0, ... max_trades=10, ... std_stop=True, ... act_leverage=True, ... start_time="09:00", ... finishing_time="17:00", ... time_frame="1h" ... ) >>> # Calculate risk level >>> risk_level = risk_manager.risk_level()
>>> # Get appropriate lot size for a trade >>> lot_size = risk_manager.get_lot()
>>> # Determine stop loss and take profit levels >>> stop_loss = risk_manager.get_stop_loss() >>> take_profit = risk_manager.get_take_profit()
>>> # Check if current risk is acceptable >>> is_risk_acceptable = risk_manager.is_risk_ok()
- calculate_var(tf: TimeFrame = 'D1', c=0.95) float[source]
Calculate Value at Risk (VaR) for a given portfolio.
- Parameters:
tf (str) – Time frame to use to calculate volatility.
c (float) – Confidence level for VaR calculation (default is 95%).
Returns: - VaR value
- currency_risk() Dict[str, int | float | Any][source]
Calculates the currency risk of a trade.
- Returns:
A dictionary containing the following keys:
’currency_risk’: Dollar amount risk on a single trade.
’trade_loss’: Loss value per tick in dollars.
’trade_profit’: Profit value per tick in dollars.
’volume’: Contract size multiplied by the average price.
’lot’: Lot size per trade.
- Return type:
Dict[str, Union[int, float, Any]]
- property dailydd: float
- get_break_even(thresholds: list[tuple[int, float]] = None) int[source]
Calculates the break-even price level based on stop-loss tiers.
The function determines the break-even point by applying a multiplier to the sum of the current stop-loss and market spread. If an explicit break-even value (self.be) is already set, it returns that value (converting percentage-based floats to absolute points if necessary).
- Parameters:
thresholds (list[tuple[int, float]], optional) – A list of tiers defined as (threshold_limit, multiplier). Example: [(150, 0.25), (100, 0.35), (0, 0.5)]. If None, defaults to standard conservative tiers.
- Returns:
The calculated break-even value in points/pips.
- Return type:
int
Note
The function automatically sorts thresholds in descending order to ensure the ‘stop’ value is matched against the highest possible tier first.
- get_hours() int[source]
Calculates the number of hours between the starting of the session and the end of the session
- get_minutes() int[source]
calculates the number of minutes between the starting of the session and the end of the session
- get_pchange_stop(pchange: float | None) int[source]
Calculate the percentage change-based stop loss level for a given financial instrument.
- Parameters:
pchange (float) – Percentage change in price to use for calculating stop loss level. If pchange is set to None, the stop loss is calculate using std.
Returns: - Percentage change-based stop loss level, rounded to the nearest point. - 0 if the calculated stop loss is <= 0.
- get_std_stop() int[source]
Calculate the standard deviation-based stop loss level for a given financial instrument.
Returns: - Standard deviation-based stop loss level, rounded to the nearest point. - 0 if the calculated stop loss is less than or equal to 0.
- property maxrisk: float
- risk_level(balance_value=False) float | Tuple[float, float][source]
Calculates the risk level of a trade
Returns: - Risk level in the form of a float percentage.
bbstrader.metatrader.trade module
- class bbstrader.metatrader.trade.Trade(symbol: str = 'EURUSD', expert_name: str = 'bbstrader', expert_id: int = 181051, version: str = '3.0', target: float = 5.0, start_time: str = '1:00', finishing_time: str = '23:00', ending_time: str = '23:30', time_frame: str = 'D1', broker_tz=False, verbose: bool = False, console_log: bool = False, logger: Logger | str = 'bbstrader.log', **kwargs)[source]
Bases:
objectExtends the RiskManagement class to include specific trading operations, incorporating risk management strategies directly into trade executions. It offers functionalities to execute trades while managing risks.
- Exemple:
>>> import time >>> # Initialize the Trade class with parameters >>> trade = Trade( ... symbol="EURUSD", # Symbol to trade ... expert_name="bbstrader", # Name of the expert advisor ... expert_id=12345, # Unique ID for the expert advisor ... version="1.0", # Version of the expert advisor ... target=5.0, # Daily profit target in percentage ... start_time="09:00", # Start time for trading ... finishing_time="17:00", # Time to stop opening new positions ... ending_time="17:30", # Time to close any open positions ... max_risk=2.0, # Maximum risk allowed on the account in percentage ... daily_risk=1.0, # Daily risk allowed in percentage ... max_trades=5, # Maximum number of trades per session ... rr=2.0, # Risk-reward ratio ... account_leverage=True, # Use account leverage in calculations ... std_stop=True, # Use standard deviation for stop loss calculation ... sl=20, # Stop loss in points (optional) ... tp=30, # Take profit in points (optional) ... be=10 # Break-even in points (optional) ... )
>>> # Example to open a buy position >>> trade.open_buy_position(mm=True, comment="Opening Buy Position")
>>> # Example to open a sell position >>> trade.open_sell_position(mm=True, comment="Opening Sell Position")
>>> # Check current open positions >>> opened_positions = trade.get_opened_positions >>> if opened_positions is not None: ... print(f"Current open positions: {opened_positions}")
>>> # Close all open positions at the end of the trading session >>> if trade.days_end(): ... trade.close_all_positions(comment="Closing all positions at day's end")
>>> # Print trading session statistics >>> trade.statistics(save=True, dir="my_trading_stats")
>>> # Sleep until the next trading session if needed (example usage) >>> sleep_time = trade.sleep_time() >>> print(f"Sleeping for {sleep_time} minutes until the next trading session.") >>> time.sleep(sleep_time * 60)
- property bepos
Return All positon’s tickets for which a break even has been set
- break_even(mm=True, id: int | None = None, trail: bool | None = True, stop_trail: int | str = None, trail_after_points: int | str = None, be_plus_points: int | None = None)[source]
Manages the break-even level of a trading position.
This function checks whether it is time to set a break-even stop loss for an open position. If the break-even level is already set, it monitors price movement and updates the stop loss accordingly if the trail parameter is enabled.
When trail is enabled, the function dynamically adjusts the break-even level based on the trail_after_points and stop_trail parameters.
- Parameters:
id (int) – The strategy ID or expert ID.
mm (bool) – Whether to manage the position or not.
trail (bool) – Whether to trail the stop loss or not.
stop_trail (int) – Number of points to trail the stop loss by. It represent the distance from the current price to the stop loss.
trail_after_points (int, str) – Number of points in profit from where the strategy will start to trail the stop loss. If set to str, it must be one of the following values: - ‘SL’ to trail the stop loss after the profit reaches the stop loss level in points. - ‘TP’ to trail the stop loss after the profit reaches the take profit level in points. - ‘BE’ to trail the stop loss after the profit reaches the break-even level in points.
be_plus_points (int) – Number of points to add to the break-even level. Represents the minimum profit to secure.
- break_even_request(tiket, price, request)[source]
Send a request to set the stop loss to break even for a given trading position.
- Parameters:
tiket (int) – The ticket number of the trading position.
price (float) – The price at which the stop loss is to be set.
request (dict) – The request to set the stop loss to break even.
- bulk_close(tickets: List, tikets_type: Literal['positions', 'orders'], close_func: Callable, order_type: str, id: int | None = None, comment: str | None = None)[source]
Close multiple orders or positions at once.
- Parameters:
tickets (List) – List of tickets to close
tikets_type (str) – Type of tickets to close (‘positions’, ‘orders’)
close_func (Callable) – The function to close the tickets
order_type (str) – Type of orders or positions to close
id (int) – The unique ID of the Expert or Strategy
comment (str) – Comment for the closing position
- property buypos
Return all buy opened position’s tickets
- check(comment)[source]
Verify if all conditions for taking a position are valide, These conditions are based on the Maximum risk ,daily risk, the starting, the finishing, and ending trading time.
- Parameters:
comment (str) – The comment for the closing position
- close_order(ticket: int, id: int | None = None, comment: str | None = None)[source]
Close an open order by it ticket
- Parameters:
ticket (int) – Order ticket to close (e.g TradeOrder.ticket)
id (int) – The unique ID of the Expert or Strategy
comment (str) – Comment for the closing position
Returns: - True if order closed, False otherwise
- close_orders(order_type: Literal['all', 'buy_stops', 'sell_stops', 'buy_limits', 'sell_limits', 'buy_stop_limits', 'sell_stop_limits'], id: int | None = None, comment: str | None = None)[source]
- Parameters:
order_type (str) – Type of orders to close (‘all’, ‘buy_stops’, ‘sell_stops’, ‘buy_limits’, ‘sell_limits’, ‘buy_stop_limits’, ‘sell_stop_limits’)
id (int) – The unique ID of the Expert or Strategy
comment (str) – Comment for the closing position
- close_position(ticket: int, id: int | None = None, pct: float | None = 1.0, comment: str | None = None, symbol: str | None = None) bool[source]
Close an open position by it ticket
- Parameters:
ticket (int) – Positon ticket to close (e.g TradePosition.ticket)
id (int) – The unique ID of the Expert or Strategy
pct (float) – Percentage of the position to close
comment (str) – Comment for the closing position
Returns: - True if position closed, False otherwise
- close_positions(position_type: Literal['all', 'buy', 'sell', 'profitable', 'losing'], id: int | None = None, comment: str | None = None)[source]
- Parameters:
position_type (str) – Type of positions to close (‘all’, ‘buy’, ‘sell’, ‘profitable’, ‘losing’)
id (int) – The unique ID of the Expert or Strategy
comment (str) – Comment for the closing position
- close_request(request: dict, type: str)[source]
Close a trading order or position
- Parameters:
request (dict) – The request to close a trading order or position
type (str) – Type of the request (‘order’, ‘position’)
- get_filtered_tickets(id: int | None = None, filter_type: str | None = None, th=None) List[int] | None[source]
Get tickets for positions or orders based on filters.
- Parameters:
id (int) – The strategy id or expert Id
filter_type (str) – Filter type to apply on the tickets, - orders are current open orders - buy_stops are current buy stop orders - sell_stops are current sell stop orders - buy_limits are current buy limit orders - sell_limits are current sell limit orders - buy_stop_limits are current buy stop limit orders - sell_stop_limits are current sell stop limit orders - positions are all current open positions - buys and sells are current buy or sell open positions - profitables are current open position that have a profit greater than a threshold - losings are current open position that have a negative profit
th (bool) – the minimum treshold for winning position (only relevant when filter_type is ‘profitables’)
- Returns:
- A list of filtered tickets
or None if no tickets match the criteria.
- Return type:
List[int] | None
- get_stats() Tuple[Dict[str, Any], Dict[str, Any]][source]
Retrieves aggregated session and historical trading performance.
- initialize(**kwargs)[source]
Initializes the MetaTrader 5 (MT5) terminal for trading operations. This method attempts to establish a connection with the MT5 terminal. If the initial connection attempt fails due to a timeout, it retries after a specified delay. Successful initialization is crucial for the execution of trading operations.
- Raises:
MT5TerminalError – If initialization fails.
- is_max_trades_reached() bool[source]
Check if the maximum number of trades for the day has been reached.
- Returns:
bool
- property logger
- modify_order(ticket: int, price: float | None = None, stoplimit: float | None = None, sl: float | None = None, tp: float | None = None)[source]
Modify an open order by it ticket
- Parameters:
ticket (int) – Order ticket to modify (e.g TradeOrder.ticket)
price (float) – The price at which to modify the order
stoplimit (float) – A price a pending Limit order is set at when the price reaches the ‘price’ value (this condition is mandatory). The pending order is not passed to the trading system until that moment
sl (float) – The stop loss in points
tp (float) – The take profit in points
- open_buy_position(**kwargs)[source]
Open a buy position or order.
See Trade.open_position for the
kwargsparameters.
- open_position(action: Literal['BMKT', 'BLMT', 'BSTP', 'BSTPLMT', 'SMKT', 'SLMT', 'SSTP', 'SSTPLMT'], price: float | None = None, stoplimit: float | None = None, id: int | None = None, mm: bool = True, trail: bool = True, comment: str | None = None, symbol: str | None = None, volume: float | None = None, sl: float | None = None, tp: float | None = None) bool[source]
Opens a Buy or Sell position (Market or Pending).
- Parameters:
action (str) – (‘BMKT’, ‘SMKT’) for Market orders or (‘BLMT’, ‘SLMT’, ‘BSTP’, ‘SSTP’, ‘BSTPLMT’, ‘SSTPLMT’) for pending orders
price (float) – The price at which to open an order
stoplimit (float) – A price a pending Limit order is set at when the price reaches the ‘price’ value (this condition is mandatory). The pending order is not passed to the trading system until that moment
id (int) – The strategy id or expert Id
mm (bool) – Weither to put stop loss and tp or not
trail (bool) – Weither to trail the stop loss or not
comment (str) – The comment for the closing position
symbol (str) – The symbol to trade
volume (float) – The volume (lot) to trade
sl (float) – The stop loss price
tp (float) – The take profit price
- open_sell_position(**kwargs)[source]
Open a sell position or order.
See Trade.open_position for the
kwargsparameters.
- property orders
Return all opened order’s tickets
- property positions
Return all opened position’s tickets
- positive_profit(th: float | None = None, id: int | None = None, account: bool = True) bool[source]
Check is the total profit on current open positions Is greater than a minimum profit express as percentage of the profit target.
- Parameters:
th (float) – The minimum profit target on current positions
id (int) – The strategy id or expert Id
account (bool) – Weither to check positions on the account or on the symbol
- prepare_symbol()[source]
Prepares the selected symbol for trading. This method checks if the symbol is available and visible in the MT5 terminal. If the symbol is not visible, it attempts to select the symbol again. This step ensures that trading operations can be performed on the selected symbol without issues.
- Raises:
MT5TerminalError – If the symbol cannot be made visible for trading operations.
- profit_target() bool[source]
Checks if the net profit for today’s deals has reached the percentage target.
- request_result(price: float, request: Dict[str, Any], type: Literal['BMKT', 'BLMT', 'BSTP', 'BSTPLMT', 'SMKT', 'SLMT', 'SSTP', 'SSTPLMT'])[source]
Check if a trading order has been sent correctly
- Parameters:
price (float) – Price for opening the position
request (Dict[str, Any]) – A trade request to sent to Mt5.order_sent()
https (all detail in request can be found here) – //www.mql5.com/en/docs/python_metatrader5/mt5ordersend_py
type (str) – The type of the order (BMKT, SMKT, BLMT, SLMT, BSTP, SSTP, BSTPLMT, SSTPLMT)
- property retcodes: List[int]
Return all the retcodes
- select_symbol(**kwargs)[source]
Selects the trading symbol in the MetaTrader 5 (MT5) terminal. This method ensures that the specified trading symbol is selected and visible in the MT5 terminal, allowing subsequent trading operations such as opening and closing positions on this symbol.
- Raises:
MT5TerminalError – If symbole selection fails.
- property sellpos
Return all sell opened position’s tickets
- set_break_even(position: TradePosition, be: int, price: float | None = None, level: float | None = None)[source]
Sets the break-even level for a given trading position.
- Parameters:
position (TradePosition) – The trading position for which the break-even is to be set. This is the value return by mt5.positions_get().
be (int) – The break-even level in points.
level (float) – The break-even level in price, if set to None , it will be calated automaticaly.
price (float) – The break-even price, if set to None , it will be calated automaticaly.
- sharpe()[source]
Calculate the Sharpe ratio of a returns stream based on a number of trading periods. The function assumes that the returns are the excess of those compared to a benchmark.
- bbstrader.metatrader.trade.create_trade_instance(symbols: List[str], params: Dict[str, Any], daily_risk: Dict[str, float] | None = None, max_risk: Dict[str, float] | None = None, pchange_sl: Dict[str, float] | float | None = None, **kwargs) Dict[str, Trade][source]
Creates Trade instances for each symbol provided.
- Parameters:
symbols – A list of trading symbols (e.g., [‘AAPL’, ‘MSFT’]).
params – A dictionary containing parameters for the Trade instance.
daily_risk – A dictionary containing daily risk weight for each symbol.
max_risk – A dictionary containing maximum risk weight for each symbol.
- Returns:
A dictionary where keys are symbols and values are corresponding Trade instances.
- Raises:
ValueError – If the ‘symbols’ list is empty or the ‘params’ dictionary is missing required keys.
Note
daily_risk and max_risk can be used to manage the risk of each symbol based on the importance of the symbol in the portfolio or strategy. See bbstrader.metatrader.risk.RiskManagement for more details.
bbstrader.metatrader.utils module
- exception bbstrader.metatrader.utils.AuthFailed(message='Authorization failed.')[source]
Bases:
MT5TerminalErrorException raised for authorization failure.
- exception bbstrader.metatrader.utils.AutoTradingDisabled(message='Auto-trading is disabled.')[source]
Bases:
MT5TerminalErrorException raised when auto-trading is disabled.
- exception bbstrader.metatrader.utils.GenericFail(message='Generic fail')[source]
Bases:
MT5TerminalErrorException raised for generic failure.
- exception bbstrader.metatrader.utils.HistoryNotFound(message='No history found.')[source]
Bases:
MT5TerminalErrorException raised when no history is found.
- exception bbstrader.metatrader.utils.InternalFailConnect(message='No IPC connection.')[source]
Bases:
InternalFailErrorException raised for no IPC connection.
- exception bbstrader.metatrader.utils.InternalFailInit(message='Internal IPC initialization failed.')[source]
Bases:
InternalFailErrorException raised for internal IPC initialization failure.
- exception bbstrader.metatrader.utils.InternalFailReceive(message='Internal IPC receive failed.')[source]
Bases:
InternalFailErrorException raised for internal IPC receive failure.
- exception bbstrader.metatrader.utils.InternalFailSend(message='Internal IPC send failed.')[source]
Bases:
InternalFailErrorException raised for internal IPC send failure.
- exception bbstrader.metatrader.utils.InternalFailTimeout(message='Internal timeout.')[source]
Bases:
InternalFailErrorException raised for an internal timeout.
- exception bbstrader.metatrader.utils.InvalidBroker(message='Invalid broker.')[source]
Bases:
ExceptionException raised for invalid broker errors.
- exception bbstrader.metatrader.utils.InvalidParams(message='Invalid arguments or parameters.')[source]
Bases:
MT5TerminalErrorException raised for invalid arguments or parameters.
- exception bbstrader.metatrader.utils.InvalidVersion(message='Invalid version.')[source]
Bases:
MT5TerminalErrorException raised for an invalid version.
- class bbstrader.metatrader.utils.RateInfo(time: int, open: float, high: float, low: float, close: float, tick_volume: float, spread: int, real_volume: float)[source]
Bases:
NamedTupleReprents a candle (bar) for a specified period. * time: Time in seconds since 1970.01.01 00:00 * open: Open price * high: High price * low: Low price * close: Close price * tick_volume: Tick volume * spread: Spread value * real_volume: Real volume
- close: float
Alias for field number 4
- high: float
Alias for field number 2
- low: float
Alias for field number 3
- open: float
Alias for field number 1
- real_volume: float
Alias for field number 7
- spread: int
Alias for field number 6
- tick_volume: float
Alias for field number 5
- time: int
Alias for field number 0
- class bbstrader.metatrader.utils.SymbolType(*values)[source]
Bases:
EnumRepresents the type of a symbol.
- BONDS = 'BONDS'
- COMMODITIES = 'COMMODITIES'
- CRYPTO = 'CRYPTO'
- ETFs = 'ETFs'
- FOREX = 'FOREX'
- FUTURES = 'FUTURES'
- INDICES = 'INDICES'
- OPTIONS = 'OPTIONS'
- STOCKS = 'STOCKS'
- unknown = 'UNKNOWN'
- class bbstrader.metatrader.utils.TimeFrame(*values)[source]
Bases:
EnumRrepresent a time frame object
- D1 = <MagicMock id='125943294139264'>
- H1 = <MagicMock id='125943294079824'>
- H12 = <MagicMock id='125943294135472'>
- H2 = <MagicMock id='125943294100064'>
- H3 = <MagicMock id='125943294103856'>
- H4 = <MagicMock id='125943294107648'>
- H6 = <MagicMock id='125943294111440'>
- H8 = <MagicMock id='125943294115232'>
- M1 = <MagicMock id='125943293984112'>
- M10 = <MagicMock id='125943294044512'>
- M12 = <MagicMock id='125943294048304'>
- M15 = <MagicMock id='125943294068544'>
- M2 = <MagicMock id='125943294036976'>
- M20 = <MagicMock id='125943294072288'>
- M3 = <MagicMock id='125943294040672'>
- M30 = <MagicMock id='125943294076128'>
- M4 = <MagicMock id='125943293982144'>
- M5 = <MagicMock id='125943293978304'>
- M6 = <MagicMock id='125943293974416'>
- MN1 = <MagicMock id='125943294146848'>
- W1 = <MagicMock id='125943294143056'>
- exception bbstrader.metatrader.utils.UnsupportedMethod(message='Unsupported method.')[source]
Bases:
MT5TerminalErrorException raised for an unsupported method.
- bbstrader.metatrader.utils.raise_mt5_error(message: str | None = None)[source]
Raises an exception based on the given error code.
- Parameters:
message – An optional custom error message.
- Raises:
MT5TerminalError – A specific exception based on the error code.
- bbstrader.metatrader.utils.trade_retcode_message(code, display=False, add_msg='')[source]
Retrieves a user-friendly message corresponding to a given trade return code.
- Parameters:
code (int) – The trade return code to look up.
display (bool, optional) – Whether to print the message to the console. Defaults to False.
- Returns:
- The message associated with the provided trade return code. If the code is not found,
it returns “Unknown trade error.”.
- Return type:
str