bbstrader.metatrader¶
The Python side of the C++/Python bridge to MetaTrader 5: account management, order/trade helpers, risk management, symbol rates, and the copy-trading engine (CLI and desktop GUI).
metatrader ¶
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.
Account ¶
The 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)
Initialize the Account class.
See bbstrader.metatrader.broker.check_mt5_connection()
for more details on how to connect to MT5 terminal.
Source code in src/bbstrader/metatrader/account.py
server
property
¶
The name of the trade server to which the client terminal is connected. (e.g., 'AdmiralsGroup-Demo')
shutdown ¶
refresh ¶
clear_symbol_cache ¶
get_account_info ¶
get_account_info(account: int | None = None, password: str | None = None, server: str | None = None, timeout: int | None = _DEFAULT_TIMEOUT, path: str | None = None) -> AccountInfo | None
Get info on the current trading account or a specific account .
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account (int, optinal)
|
MT5 Trading account number. |
required | |
password
|
(str, optinal)
|
MT5 Trading account password. |
None
|
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 |
None
|
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. |
_DEFAULT_TIMEOUT
|
path
|
str
|
The path to the MetaTrader 5 terminal executable file. Defaults to None (e.g., "C:/Program Files/MetaTrader 5/terminal64.exe"). |
None
|
Returns: - AccountInfo - None in case of an error
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_terminal_info ¶
Get the connected MetaTrader 5 client terminal status and settings.
Returns: - TerminalInfo - None in case of an error
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_symbol_info ¶
Get symbol properties
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name |
required |
Returns: - SymbolInfo. - None in case of an error.
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_tick_info ¶
Get symbol tick properties
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name |
required |
Returns: - TickInfo. - None in case of an error.
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_currency_rates ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol for which to get currencies |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
dict[str, str]
|
|
dict[str, str]
|
|
dict[str, str]
|
|
Exemple
account = Account() account.get_currency_rates('EURUSD')
Source code in src/bbstrader/metatrader/account.py
get_symbols ¶
get_symbols(symbol_type: SymbolType | str = 'ALL', check_etf=False, save=False, file_name='symbols', include_desc=False, display_total=False) -> list[str]
Get all specified financial instruments from the MetaTrader 5 terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_type
|
SymbolType | str
|
The type of financial instruments to retrieve. |
'ALL'
|
- `ALL`
|
For all available symbols |
required | |
check_etf
|
bool
|
If True and symbol_type is 'etf', check if the ETF description contains 'ETF'. |
False
|
save
|
bool
|
If True, save the symbols to a file. |
False
|
file_name
|
str
|
The name of the file to save the symbols to (without the extension). |
'symbols'
|
include_desc
|
bool
|
If True, include the symbol's description in the output and saved file. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of symbols. |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error connecting to MT5 or retrieving symbols. |
Source code in src/bbstrader/metatrader/account.py
get_symbol_type ¶
Determines the type of a given financial instrument symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol of the financial instrument (e.g., |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SymbolType |
SymbolType
|
The type of the financial instrument, one of the following: |
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
SymbolType.unknownif the type cannot be determined.
Source code in src/bbstrader/metatrader/account.py
get_stocks_from_country ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
country
|
str
|
The country code of stocks to retrieve. Defaults to 'USA'. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of stock symbol names from the specified country. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/account.py
get_stocks_from_exchange ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
exchange_code
|
str
|
The ISO code of the exchange. |
'XNYS'
|
etf
|
bool
|
If True, include ETFs from the exchange. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of stock symbol names from the specified exchange. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/account.py
get_rate_info ¶
Get the most recent bar for a specified symbol and timeframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol for which to get the rate information. |
required |
timeframe
|
str
|
The timeframe for the rate information. Default is '1m'.
See |
'1m'
|
Returns: RateInfo: The most recent bar as a RateInfo named tuple. None: If no rates are found or an error occurs. Raises: MT5TerminalError: A specific exception based on the error code.
Source code in src/bbstrader/metatrader/account.py
get_positions ¶
get_positions(symbol: str | None = None, group: str | None = None, ticket: int | None = None) -> list[TradePosition] | None
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:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Symbol name. Optional named parameter.
If a symbol is specified, the |
None
|
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. |
None
|
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. |
None
|
Returns:
| Type | Description |
|---|---|
list[TradePosition] | None
|
list[TradePosition] | None: |
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.
Source code in src/bbstrader/metatrader/account.py
get_orders ¶
get_orders(symbol: str | None = None, group: str | None = None, ticket: int | None = None) -> list[TradeOrder] | None
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:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Order ticket. Optional named parameter. Unique number assigned to each order. |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
required |
Returns:
| Type | Description |
|---|---|
list[TradeOrder] | None
|
[List[TradeOrder] | None]: |
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.
Source code in src/bbstrader/metatrader/account.py
get_trades_history ¶
get_trades_history(date_from: datetime = datetime(2000, 1, 1), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) -> pd.DataFrame | list[TradeDeal] | None
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 specifiedorder ticketin theDEAL_ORDERproperty. -
Call specifying the
position ticket. Returns all deals having the specifiedposition ticketin theDEAL_POSITION_IDproperty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime
|
Date the bars are requested from.
Set by the |
datetime(2000, 1, 1)
|
date_to
|
Optional[datetime]
|
Same as |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Ticket of an order (stored in |
None
|
position
|
Optional[int]
|
Ticket of a position (stored in |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame | list[TradeDeal] | None
|
Union[pd.DataFrame, Tuple[TradeDeal], None]: |
DataFrame | list[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)
Source code in src/bbstrader/metatrader/account.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
get_orders_history ¶
get_orders_history(date_from: datetime = datetime(2000, 1, 1), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) -> pd.DataFrame | list[TradeOrder] | None
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 specifiedorder ticketin theDEAL_ORDERproperty. -
Call specifying the
position ticket. Returns all deals having the specifiedposition ticketin theDEAL_POSITION_IDproperty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime
|
Date the bars are requested from.
Set by the |
datetime(2000, 1, 1)
|
date_to
|
Optional[datetime]
|
Same as |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Order ticket to filter results. Optional parameter. If not specified, the filter is not applied. |
None
|
position
|
Optional[int]
|
Ticket of a position (stored in |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
True
|
save
|
bool
|
If True, a CSV file will be created to save the history. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | list[TradeOrder] | None
|
Union[pd.DataFrame, List[TradeOrder], None] |
DataFrame | 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 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)
Source code in src/bbstrader/metatrader/account.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | |
get_today_deals ¶
get_today_deals(strategy_id: int, group: str | None = None, lookback_days: int = 3) -> list[TradeDeal]
Get all today deals for a specific strategy magic number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy_id
|
int
|
Strategy or expert magic number. |
required |
group
|
str | None
|
Symbol or group filter. |
None
|
lookback_days
|
int
|
How many days back to search for open positions. |
3
|
Returns: list[TradeDeal]: Deals closed today belonging to the strategy.
Source code in src/bbstrader/metatrader/account.py
Rates ¶
Rates(symbol: str, timeframe: str = 'D1', start_pos: int = 0, count: int | None = MAX_BARS, **kwargs)
Provides 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
-
Befor using this class, ensure that the
Max bars in chartin 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 toTools->Options->Charts->Max bars in chart. -
The
open, high, low, close, adjclose, returns, volumeproperties 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())
Initializes a new Rates instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Financial instrument symbol (e.g., "EURUSD"). |
required |
timeframe
|
str
|
Timeframe string (e.g., "D1", "1h", "5m"). |
'D1'
|
start_pos
|
int
|
Starting index (int) for data retrieval. |
0
|
count
|
int
|
Number of bars to retrieve default is the maximum bars availble in the MT5 terminal. |
MAX_BARS
|
Raises: ValueError: If the provided timeframe is invalid.
Source code in src/bbstrader/metatrader/rates.py
returns
property
¶
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.
get_rates_from_pos ¶
get_rates_from_pos(filter=False, fill_na=False, lower_colnames=False, utc=False) -> pd.DataFrame | None
Retrieves historical data starting from a specific position.
Uses the start_pos and count attributes specified during
initialization to fetch data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filter
|
See |
required | |
fill_na
|
See |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
utc
|
bool
|
If True, the data will be in UTC timezone. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical |
DataFrame | None
|
data if successful, otherwise None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The Datetime for this method is in Broker's timezone.
Source code in src/bbstrader/metatrader/rates.py
get_rates_from ¶
get_rates_from(date_from: datetime | Timestamp, count: int = MAX_BARS, filter=False, fill_na=False, lower_colnames=False, utc=False) -> pd.DataFrame | None
Retrieves historical data within a specified date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
Starting date for data retrieval. The data will be retrieved from this date going to the past. |
required | |
count
|
Number of bars to retrieve. |
required | |
filter
|
See |
required | |
fill_na
|
See |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
utc
|
bool
|
If True, the data will be in UTC timezone. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical |
DataFrame | None
|
data if successful, otherwise None. |
Source code in src/bbstrader/metatrader/rates.py
get_historical_data ¶
get_historical_data(date_from: datetime | Timestamp, date_to: datetime | Timestamp = pd.Timestamp.now(), utc: bool = False, filter: bool | None = False, fill_na: bool | str | None = False, lower_colnames: bool | None = True, save_csv: bool | None = False) -> pd.DataFrame | None
Retrieves historical data within a specified date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
Starting date for data retrieval. |
required | |
date_to
|
Ending date for data retrieval. Defaults to the current time. |
required | |
utc
|
If True, the data will be in UTC timezone. Defaults to False. |
required | |
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. |
required | |
fill_na
|
If True, the data will be filled with the nearest value.
This is use only when 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. |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
save_csv
|
File path to save the data as a CSV. If None, the data won't be saved. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical data if successful, otherwise None. |
Raises:
| Type | Description |
|---|---|
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_futures calendar.
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.
Source code in src/bbstrader/metatrader/rates.py
RiskManagement ¶
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, account_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)
The 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()
Initialize the RiskManagement class to manage risk in trading activities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol of the financial instrument to trade. |
required |
max_risk
|
float
|
The |
10.0
|
daily_risk
|
float
|
|
None
|
max_trades
|
int
|
Maximum number of trades at any point in time. If set to None it will be determine based on the timeframe of trading. |
None
|
std_stop
|
bool
|
If set to True, the Stop loss is calculated based
On |
False
|
pchange_sl
|
float
|
If set, the Stop loss is calculated based
On |
None
|
act_leverage
|
bool
|
If set to True the account leverage will be used In risk management setting. Defaults to False. |
required |
time_frame
|
str
|
The time frame on which the program is working
|
'D1'
|
start_time
|
str
|
The starting time for the trading session
|
'1:00'
|
finishing_time
|
str
|
The finishing time for the trading strategy
|
'23:00'
|
sl
|
int
|
Stop Loss in points, Must be a positive number. |
None
|
tp
|
int
|
Take Profit in points, Must be a positive number. |
None
|
be
|
int
|
Break Even in points, Must be a positive number. |
None
|
rr
|
float
|
Risk reward ratio, Must be a positive number. Defaults to 1.5. |
3.0
|
Source code in src/bbstrader/metatrader/risk.py
get_minutes ¶
calculates the number of minutes between the starting of the session and the end of the session
Source code in src/bbstrader/metatrader/risk.py
get_hours ¶
Calculates the number of hours between the starting of the session and the end of the session
risk_level ¶
Calculates the risk level of a trade
Returns: - Risk level in the form of a float percentage.
Source code in src/bbstrader/metatrader/risk.py
max_trade ¶
calculates the maximum number of trades allowed
Source code in src/bbstrader/metatrader/risk.py
get_std_stop ¶
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.
Source code in src/bbstrader/metatrader/risk.py
get_pchange_stop ¶
Calculate the percentage change-based stop loss level for a given financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
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. |
required |
Returns: - Percentage change-based stop loss level, rounded to the nearest point. - 0 if the calculated stop loss is <= 0.
Source code in src/bbstrader/metatrader/risk.py
calculate_var ¶
Calculate Value at Risk (VaR) for a given portfolio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tf
|
str
|
Time frame to use to calculate volatility. |
'D1'
|
c
|
float
|
Confidence level for VaR calculation (default is 95%). |
0.95
|
Returns: - VaR value
Source code in src/bbstrader/metatrader/risk.py
get_trade_risk ¶
Calculate risk per trade as percentage
Source code in src/bbstrader/metatrader/risk.py
var_loss_value ¶
Calculate the stop-loss level based on VaR.
Notes
The Var is Estimated using the Variance-Covariance method on the daily returns. If you want to use the VaR for a different time frame .
Source code in src/bbstrader/metatrader/risk.py
get_take_profit ¶
calculates the take profit of a trade in points
get_currency_risk ¶
expected_profit ¶
volume ¶
currency_risk ¶
Calculates the currency risk of a trade.
Returns:
| Type | Description |
|---|---|
dict[str, int | float | Any]
|
Dict[str, Union[int, float, Any]]: A dictionary containing the following keys: |
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
Source code in src/bbstrader/metatrader/risk.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
get_break_even ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
thresholds
|
list[tuple[int, float]]
|
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. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The calculated break-even value in points/pips. |
Note
The function automatically sorts thresholds in descending order to ensure the 'stop' value is matched against the highest possible tier first.
Source code in src/bbstrader/metatrader/risk.py
Trade ¶
Trade(symbol: str = 'EURUSD', expert_name: str = 'bbstrader', expert_id: int = EXPERT_ID, 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)
Extends 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)
Initializes the Trade class with the specified parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The |
'EURUSD'
|
expert_name
|
str
|
The name of the |
'bbstrader'
|
expert_id
|
int
|
The |
EXPERT_ID
|
version
|
str
|
The |
'3.0'
|
target
|
float
|
|
5.0
|
start_time
|
str
|
The |
'1:00'
|
finishing_time
|
str
|
The time after which no new position can be opened. |
'23:00'
|
ending_time
|
str
|
The time after which any open position will be closed. |
'23:30'
|
verbose
|
bool | None
|
If set to None (default), account summary and risk managment parameters are printed in the terminal. |
False
|
console_log
|
bool
|
If set to True, log messages are displayed in the console. |
False
|
logger
|
Logger | str
|
The logger object to use for logging messages could be a string or a logger object. |
'bbstrader.log'
|
**kwargs
|
Params for the RiskManagement and Account
See the |
{}
|
Source code in src/bbstrader/metatrader/trade.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
initialize ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If initialization fails. |
Source code in src/bbstrader/metatrader/trade.py
select_symbol ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If symbole selection fails. |
Source code in src/bbstrader/metatrader/trade.py
prepare_symbol ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If the symbol cannot be made visible for trading operations. |
Source code in src/bbstrader/metatrader/trade.py
summary ¶
Show a brief description about the trading program
Source code in src/bbstrader/metatrader/trade.py
risk_managment ¶
Show the risk management parameters
Source code in src/bbstrader/metatrader/trade.py
statistics ¶
Print some statistics for the trading session and save to CSV if specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save
|
bool
|
Whether to save the statistics to a CSV file. |
True
|
dir
|
str
|
The directory to save the CSV file. |
None
|
Source code in src/bbstrader/metatrader/trade.py
open_position ¶
open_position(action: Buys | Sells, 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
Opens a Buy or Sell position (Market or Pending).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
str
|
( |
required |
price
|
float
|
The price at which to open an order |
None
|
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 |
None
|
id
|
int
|
The strategy id or expert Id |
None
|
mm
|
bool
|
Weither to put stop loss and tp or not |
True
|
trail
|
bool
|
Weither to trail the stop loss or not |
True
|
comment
|
str
|
The comment for the closing position |
None
|
symbol
|
str
|
The symbol to trade |
None
|
volume
|
float
|
The volume (lot) to trade |
None
|
sl
|
float
|
The stop loss price |
None
|
tp
|
float
|
The take profit price |
None
|
Source code in src/bbstrader/metatrader/trade.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
open_buy_position ¶
Open a buy position or order.
See Trade.open_position for the kwargs parameters.
open_sell_position ¶
Open a sell position or order.
See Trade.open_position for the kwargs parameters.
check ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
comment
|
str
|
The comment for the closing position |
required |
Source code in src/bbstrader/metatrader/trade.py
request_result ¶
Check if a trading order has been sent correctly
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
float
|
Price for opening the position |
required |
request
|
Dict[str, Any]
|
A trade request to sent to Mt5.order_sent() |
required |
all detail in request can be found here https
|
//www.mql5.com/en/docs/python_metatrader5/mt5ordersend_py |
required | |
type
|
str
|
The type of the order |
required |
Source code in src/bbstrader/metatrader/trade.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | |
get_filtered_tickets ¶
get_filtered_tickets(id: int | None = None, filter_type: str | None = None, th=None) -> list[int] | None
Get tickets for positions or orders based on filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
The strategy id or expert Id |
None
|
filter_type
|
str
|
Filter type to apply on the tickets,
- |
None
|
th
|
bool
|
the minimum treshold for winning position (only relevant when filter_type is 'profitables') |
None
|
Returns:
| Type | Description |
|---|---|
list[int] | None
|
List[int] | None: A list of filtered tickets or None if no tickets match the criteria. |
Source code in src/bbstrader/metatrader/trade.py
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 | |
positive_profit ¶
Check is the total profit on current open positions Is greater than a minimum profit express as percentage of the profit target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
th
|
float
|
The minimum profit target on current positions |
None
|
id
|
int
|
The strategy id or expert Id |
None
|
account
|
bool
|
Weither to check positions on the account or on the symbol |
True
|
Source code in src/bbstrader/metatrader/trade.py
break_even ¶
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)
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:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
The strategy ID or expert ID. |
None
|
mm
|
bool
|
Whether to manage the position or not. |
True
|
trail
|
bool
|
Whether to trail the stop loss or not. |
True
|
stop_trail
|
int
|
Number of points to trail the stop loss by. It represent the distance from the current price to the stop loss. |
None
|
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. |
None
|
be_plus_points
|
int
|
Number of points to add to the break-even level. Represents the minimum profit to secure. |
None
|
Source code in src/bbstrader/metatrader/trade.py
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
set_break_even ¶
set_break_even(position: TradePosition, be: int, price: float | None = None, level: float | None = None)
Sets the break-even level for a given trading position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position
|
TradePosition
|
The trading position for which the break-even is to be set.
This is the value return by |
required |
be
|
int
|
The break-even level in points. |
required |
level
|
float
|
The break-even level in price, if set to None , it will be calated automaticaly. |
None
|
price
|
float
|
The break-even price, if set to None , it will be calated automaticaly. |
None
|
Source code in src/bbstrader/metatrader/trade.py
break_even_request ¶
Send a request to set the stop loss to break even for a given trading position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiket
|
int
|
The ticket number of the trading position. |
required |
price
|
float
|
The price at which the stop loss is to be set. |
required |
request
|
dict
|
The request to set the stop loss to break even. |
required |
Source code in src/bbstrader/metatrader/trade.py
win_trade ¶
Determines if a position has met the minimum 'win' threshold in points.
Source code in src/bbstrader/metatrader/trade.py
profit_target ¶
Checks if the net profit for today's deals has reached the percentage target.
Source code in src/bbstrader/metatrader/trade.py
close_request ¶
Close a trading order or position
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict
|
The request to close a trading order or position |
required |
type
|
str
|
Type of the request ('order', 'position') |
required |
Source code in src/bbstrader/metatrader/trade.py
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 | |
modify_order ¶
modify_order(ticket: int, price: float | None = None, stoplimit: float | None = None, sl: float | None = None, tp: float | None = None)
Modify an open order by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Order ticket to modify (e.g TradeOrder.ticket) |
required |
price
|
float
|
The price at which to modify the order |
None
|
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 |
None
|
sl
|
float
|
The stop loss in points |
None
|
tp
|
float
|
The take profit in points |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_order ¶
Close an open order by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Order ticket to close (e.g TradeOrder.ticket) |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Returns: - True if order closed, False otherwise
Source code in src/bbstrader/metatrader/trade.py
close_position ¶
close_position(ticket: int, id: int | None = None, pct: float | None = 1.0, comment: str | None = None, symbol: str | None = None) -> bool
Close an open position by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Positon ticket to close (e.g TradePosition.ticket) |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
pct
|
float
|
Percentage of the position to close |
1.0
|
comment
|
str
|
Comment for the closing position |
None
|
Returns: - True if position closed, False otherwise
Source code in src/bbstrader/metatrader/trade.py
bulk_close ¶
bulk_close(tickets: list, tikets_type: Literal['positions', 'orders'], close_func: Callable, order_type: str, id: int | None = None, comment: str | None = None)
Close multiple orders or positions at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickets
|
List
|
List of tickets to close |
required |
tikets_type
|
str
|
Type of tickets to close ('positions', 'orders') |
required |
close_func
|
Callable
|
The function to close the tickets |
required |
order_type
|
str
|
Type of orders or positions to close |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_orders ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_type
|
str
|
Type of orders to close ('all', 'buy_stops', 'sell_stops', 'buy_limits', 'sell_limits', 'buy_stop_limits', 'sell_stop_limits') |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_positions ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position_type
|
str
|
Type of positions to close ('all', 'buy', 'sell', 'profitable', 'losing') |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
is_max_trades_reached ¶
Check if the maximum number of trades for the day has been reached.
:return: bool
Source code in src/bbstrader/metatrader/trade.py
get_stats ¶
Retrieves aggregated session and historical trading performance.
Source code in src/bbstrader/metatrader/trade.py
sharpe ¶
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.
Source code in src/bbstrader/metatrader/trade.py
days_end ¶
Check if it is the end of the trading day.
Source code in src/bbstrader/metatrader/trade.py
trading_time ¶
Check if it is time to trade.
Source code in src/bbstrader/metatrader/trade.py
TimeFrame ¶
Bases: Enum
Rrepresent a time frame object
SymbolType ¶
Bases: Enum
Represents the type of a symbol.
RateInfo ¶
Bases: NamedTuple
Reprents 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
InvalidBroker ¶
GenericFail ¶
Bases: MT5TerminalError
Exception raised for generic failure.
Source code in src/bbstrader/metatrader/utils.py
InvalidParams ¶
Bases: MT5TerminalError
Exception raised for invalid arguments or parameters.
Source code in src/bbstrader/metatrader/utils.py
HistoryNotFound ¶
Bases: MT5TerminalError
Exception raised when no history is found.
Source code in src/bbstrader/metatrader/utils.py
InvalidVersion ¶
Bases: MT5TerminalError
Exception raised for an invalid version.
Source code in src/bbstrader/metatrader/utils.py
AuthFailed ¶
Bases: MT5TerminalError
Exception raised for authorization failure.
Source code in src/bbstrader/metatrader/utils.py
UnsupportedMethod ¶
Bases: MT5TerminalError
Exception raised for an unsupported method.
Source code in src/bbstrader/metatrader/utils.py
AutoTradingDisabled ¶
Bases: MT5TerminalError
Exception raised when auto-trading is disabled.
Source code in src/bbstrader/metatrader/utils.py
InternalFailSend ¶
Bases: InternalFailError
Exception raised for internal IPC send failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailReceive ¶
Bases: InternalFailError
Exception raised for internal IPC receive failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailInit ¶
Bases: InternalFailError
Exception raised for internal IPC initialization failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailConnect ¶
Bases: InternalFailError
Exception raised for no IPC connection.
Source code in src/bbstrader/metatrader/utils.py
InternalFailTimeout ¶
Bases: InternalFailError
Exception raised for an internal timeout.
Source code in src/bbstrader/metatrader/utils.py
TradeCopier ¶
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)
Bases: object
TradeCopier responsible 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.
Initializes the TradeCopier instance, setting up the source and destination trading accounts for trade copying.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
dict
|
A dictionary containing the connection details for the source trading account. This dictionary
must include all parameters required to successfully connect to the source account.
Refer to the |
required |
destinations
|
list[dict]
|
A list of dictionaries, where each dictionary represents a destination trading account to which trades will be copied. Each destination dictionary must contain the following keys |
required |
sleeptime
|
float
|
The time interval in seconds between each iteration of the trade copying process. Defaults to 0.1 seconds. It can be useful if you know the frequency of new trades on the source account. |
0.1
|
start_time
|
str
|
The time (HH:MM) from which the copier start copying from the source. |
None
|
end_time
|
str
|
The time (HH:MM) from which the copier stop copying from the source. |
None
|
custom_logger
|
(Any, Optional)
|
Used to set a cutum logger (default is |
None
|
shutdown_event
|
(Any, Otional)
|
Use to terminate the copy process when runs in a custum environment like web App or GUI. |
None
|
log_queue
|
(Queue, Optional)
|
Use to send log to an external program, usefule in GUI apps |
None
|
Note
The source account and the destination accounts must be connected to different MetaTrader 5 platforms. you can copy the initial installation of MetaTrader 5 to a different directory and rename it to create a new instance Then you can connect destination accounts to the new instance while the source account is connected to the original instance.
Source code in src/bbstrader/metatrader/copier.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
start_copy_process ¶
Worker process: copies orders and positions concurrently for a single destination account.
Source code in src/bbstrader/metatrader/copier.py
run ¶
Entry point: Starts a dedicated worker thread for EACH destination account to run concurrently.
Source code in src/bbstrader/metatrader/copier.py
stop ¶
Stop the Trade Copier gracefully by setting the shutdown event.
Source code in src/bbstrader/metatrader/copier.py
download_historical_data ¶
download_historical_data(symbol, timeframe, date_from, date_to=pd.Timestamp.now(), lower_colnames=True, utc=False, filter=False, fill_na=False, save_csv=False, **kwargs)
Download historical data from MetaTrader 5 terminal.
See Rates.get_historical_data for more details.
Source code in src/bbstrader/metatrader/rates.py
get_data_from_pos ¶
get_data_from_pos(symbol, timeframe, start_pos=0, fill_na=False, count=MAX_BARS, lower_colnames=False, utc=False, filter=False, session_duration=23.0, **kwargs)
Get historical data from a specific position.
See Rates.get_rates_from_pos for more details.
Source code in src/bbstrader/metatrader/rates.py
get_data_from_date ¶
get_data_from_date(symbol, timeframe, date_from, count=MAX_BARS, fill_na=False, lower_colnames=False, utc=False, filter=False, **kwargs)
Get historical data from a specific date.
See Rates.get_rates_from for more details.
Source code in src/bbstrader/metatrader/rates.py
create_trade_instance ¶
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]
Creates Trade instances for each symbol provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
A list of trading symbols (e.g., ['AAPL', 'MSFT']). |
required |
params
|
dict[str, Any]
|
A dictionary containing parameters for the Trade instance. |
required |
daily_risk
|
dict[str, float] | None
|
A dictionary containing daily risk weight for each symbol. |
None
|
max_risk
|
dict[str, float] | None
|
A dictionary containing maximum risk weight for each symbol. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Trade]
|
A dictionary where keys are symbols and values are corresponding Trade instances. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/trade.py
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 | |
raise_mt5_error ¶
Raises an exception based on the given error code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Optional[str]
|
An optional custom error message. |
None
|
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/utils.py
retry_on_disconnect ¶
Decorator that retries a function on MT5 connection errors with exponential back-off.
Catches InternalFailConnect and InternalFailTimeout, waits
delay * 2**attempt seconds between tries, then re-raises on the last attempt.
Source code in src/bbstrader/metatrader/utils.py
trade_retcode_message ¶
Retrieves a user-friendly message corresponding to a given trade return code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
The trade return code to look up. |
required |
display
|
bool
|
Whether to print the message to the console. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
The message associated with the provided trade return code. If the code is not found, it returns "Unknown trade error.". |
Source code in src/bbstrader/metatrader/utils.py
copier_worker_process ¶
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)
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:
| Name | Type | Description | Default |
|---|---|---|---|
source_config
|
dict
|
Configuration dictionary for the source account. Must contain 'login', 'password', 'server', and 'path'. |
required |
destination_config
|
dict
|
Configuration dictionary for a single destination account. |
required |
sleeptime
|
float
|
The time in seconds to wait between copy cycles. |
required |
start_time
|
str
|
The time of day to start copying (e.g., "08:00"). |
required |
end_time
|
str
|
The time of day to stop copying (e.g., "22:00"). |
required |
custom_logger
|
An optional custom logger instance. |
None
|
|
shutdown_event
|
Event
|
An event object that, when set, will signal this process to terminate gracefully. |
None
|
log_queue
|
Queue
|
A queue for sending log messages back to the parent process in a thread-safe manner. |
None
|
Source code in src/bbstrader/metatrader/copier.py
RunCopier ¶
RunCopier(source: dict, destinations: list, sleeptime: float, start_time: str, end_time: str, /, custom_logger=None, shutdown_event=None, log_queue=None)
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.
Parameters¶
source : dict
Configuration dictionary for the source account.
destinations : list
A list of configuration dictionaries, one for each
destination account to be processed sequentially.
sleeptime : float
The time in seconds to wait after completing a full
cycle through all destinations.
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 : logging.Logger, optional
An optional custom logger instance.
shutdown_event : multiprocessing.Event, optional
An event to signal shutdown.
log_queue : multiprocessing.Queue, optional
A queue for log messages.
Returns¶
None
Runs until stopped via shutdown_event or external interruption.
Source code in src/bbstrader/metatrader/copier.py
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 | |
RunMultipleCopier ¶
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)
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 accounts structure:
.. code-block:: python
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 source key and a destinations key.
sleeptime : float, optional
The sleep time passed down to each RunCopier process.
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 RunCopier process.
end_time : str, optional
The end time passed down to each RunCopier process.
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¶
None
Runs until stopped via shutdown_event or external interruption.
Source code in src/bbstrader/metatrader/copier.py
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 | |
config_copier ¶
config_copier(source_section: str = None, dest_sections: str | list[str] = None, inifile: str | Path = None) -> tuple[dict, list[dict]]
Read the configuration file and return the source and destination account details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inifile
|
str | Path
|
The path to the INI configuration file. |
None
|
source_section
|
str
|
The section name of the source account, defaults to "SOURCE". |
None
|
dest_sections
|
str | list[str]
|
The section name(s) of the destination account(s). |
None
|
Returns:
| Type | Description |
|---|---|
tuple[dict, list[dict]]
|
tuple[dict, list[dict]]: A tuple containing the source account and a list of destination accounts. |
Example
Source code in src/bbstrader/metatrader/copier.py
account ¶
Account ¶
The 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)
Initialize the Account class.
See bbstrader.metatrader.broker.check_mt5_connection()
for more details on how to connect to MT5 terminal.
Source code in src/bbstrader/metatrader/account.py
server
property
¶
The name of the trade server to which the client terminal is connected. (e.g., 'AdmiralsGroup-Demo')
shutdown ¶
refresh ¶
clear_symbol_cache ¶
get_account_info ¶
get_account_info(account: int | None = None, password: str | None = None, server: str | None = None, timeout: int | None = _DEFAULT_TIMEOUT, path: str | None = None) -> AccountInfo | None
Get info on the current trading account or a specific account .
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account (int, optinal)
|
MT5 Trading account number. |
required | |
password
|
(str, optinal)
|
MT5 Trading account password. |
None
|
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 |
None
|
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. |
_DEFAULT_TIMEOUT
|
path
|
str
|
The path to the MetaTrader 5 terminal executable file. Defaults to None (e.g., "C:/Program Files/MetaTrader 5/terminal64.exe"). |
None
|
Returns: - AccountInfo - None in case of an error
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_terminal_info ¶
Get the connected MetaTrader 5 client terminal status and settings.
Returns: - TerminalInfo - None in case of an error
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_symbol_info ¶
Get symbol properties
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name |
required |
Returns: - SymbolInfo. - None in case of an error.
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_tick_info ¶
Get symbol tick properties
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Symbol name |
required |
Returns: - TickInfo. - None in case of an error.
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/account.py
get_currency_rates ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol for which to get currencies |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
|
dict[str, str]
|
|
dict[str, str]
|
|
dict[str, str]
|
|
Exemple
account = Account() account.get_currency_rates('EURUSD')
Source code in src/bbstrader/metatrader/account.py
get_symbols ¶
get_symbols(symbol_type: SymbolType | str = 'ALL', check_etf=False, save=False, file_name='symbols', include_desc=False, display_total=False) -> list[str]
Get all specified financial instruments from the MetaTrader 5 terminal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_type
|
SymbolType | str
|
The type of financial instruments to retrieve. |
'ALL'
|
- `ALL`
|
For all available symbols |
required | |
check_etf
|
bool
|
If True and symbol_type is 'etf', check if the ETF description contains 'ETF'. |
False
|
save
|
bool
|
If True, save the symbols to a file. |
False
|
file_name
|
str
|
The name of the file to save the symbols to (without the extension). |
'symbols'
|
include_desc
|
bool
|
If True, include the symbol's description in the output and saved file. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of symbols. |
Raises:
| Type | Description |
|---|---|
Exception
|
If there is an error connecting to MT5 or retrieving symbols. |
Source code in src/bbstrader/metatrader/account.py
get_symbol_type ¶
Determines the type of a given financial instrument symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol of the financial instrument (e.g., |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SymbolType |
SymbolType
|
The type of the financial instrument, one of the following: |
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
|
SymbolType
|
|
SymbolType.unknownif the type cannot be determined.
Source code in src/bbstrader/metatrader/account.py
get_stocks_from_country ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
country
|
str
|
The country code of stocks to retrieve. Defaults to 'USA'. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of stock symbol names from the specified country. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/account.py
get_stocks_from_exchange ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
exchange_code
|
str
|
The ISO code of the exchange. |
'XNYS'
|
etf
|
bool
|
If True, include ETFs from the exchange. Defaults to True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list[str]
|
A list of stock symbol names from the specified exchange. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/account.py
get_rate_info ¶
Get the most recent bar for a specified symbol and timeframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol for which to get the rate information. |
required |
timeframe
|
str
|
The timeframe for the rate information. Default is '1m'.
See |
'1m'
|
Returns: RateInfo: The most recent bar as a RateInfo named tuple. None: If no rates are found or an error occurs. Raises: MT5TerminalError: A specific exception based on the error code.
Source code in src/bbstrader/metatrader/account.py
get_positions ¶
get_positions(symbol: str | None = None, group: str | None = None, ticket: int | None = None) -> list[TradePosition] | None
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:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Symbol name. Optional named parameter.
If a symbol is specified, the |
None
|
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. |
None
|
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. |
None
|
Returns:
| Type | Description |
|---|---|
list[TradePosition] | None
|
list[TradePosition] | None: |
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.
Source code in src/bbstrader/metatrader/account.py
get_orders ¶
get_orders(symbol: str | None = None, group: str | None = None, ticket: int | None = None) -> list[TradeOrder] | None
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:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
Optional[str]
|
Symbol name. Optional named parameter. If a symbol is specified, the ticket parameter is ignored. |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Order ticket. Optional named parameter. Unique number assigned to each order. |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
required |
Returns:
| Type | Description |
|---|---|
list[TradeOrder] | None
|
[List[TradeOrder] | None]: |
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.
Source code in src/bbstrader/metatrader/account.py
get_trades_history ¶
get_trades_history(date_from: datetime = datetime(2000, 1, 1), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) -> pd.DataFrame | list[TradeDeal] | None
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 specifiedorder ticketin theDEAL_ORDERproperty. -
Call specifying the
position ticket. Returns all deals having the specifiedposition ticketin theDEAL_POSITION_IDproperty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime
|
Date the bars are requested from.
Set by the |
datetime(2000, 1, 1)
|
date_to
|
Optional[datetime]
|
Same as |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Ticket of an order (stored in |
None
|
position
|
Optional[int]
|
Ticket of a position (stored in |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame | list[TradeDeal] | None
|
Union[pd.DataFrame, Tuple[TradeDeal], None]: |
DataFrame | list[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)
Source code in src/bbstrader/metatrader/account.py
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
get_orders_history ¶
get_orders_history(date_from: datetime = datetime(2000, 1, 1), date_to: datetime | None = None, group: str | None = None, ticket: int | None = None, position: int | None = None, to_df: bool = True) -> pd.DataFrame | list[TradeOrder] | None
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 specifiedorder ticketin theDEAL_ORDERproperty. -
Call specifying the
position ticket. Returns all deals having the specifiedposition ticketin theDEAL_POSITION_IDproperty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
datetime
|
Date the bars are requested from.
Set by the |
datetime(2000, 1, 1)
|
date_to
|
Optional[datetime]
|
Same as |
None
|
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. |
None
|
ticket
|
Optional[int]
|
Order ticket to filter results. Optional parameter. If not specified, the filter is not applied. |
None
|
position
|
Optional[int]
|
Ticket of a position (stored in |
None
|
to_df
|
bool
|
If True, a DataFrame is returned. |
True
|
save
|
bool
|
If True, a CSV file will be created to save the history. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | list[TradeOrder] | None
|
Union[pd.DataFrame, List[TradeOrder], None] |
DataFrame | 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 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)
Source code in src/bbstrader/metatrader/account.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 | |
get_today_deals ¶
get_today_deals(strategy_id: int, group: str | None = None, lookback_days: int = 3) -> list[TradeDeal]
Get all today deals for a specific strategy magic number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy_id
|
int
|
Strategy or expert magic number. |
required |
group
|
str | None
|
Symbol or group filter. |
None
|
lookback_days
|
int
|
How many days back to search for open positions. |
3
|
Returns: list[TradeDeal]: Deals closed today belonging to the strategy.
Source code in src/bbstrader/metatrader/account.py
broker ¶
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 code in src/bbstrader/metatrader/broker.py
initialize_connection ¶
get_terminal_timezone ¶
Fetch or override terminal timezone.
Source code in src/bbstrader/metatrader/broker.py
check_mt5_connection ¶
check_mt5_connection(*, path=None, login=None, password=None, server=None, timeout=60000, portable=False, **kwargs) -> bool
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 to False.
See: https://www.metatrader5.com/en/terminal/help/start_advanced/start#portable
Returns¶
bool
True if the connection is successfully established, otherwise False.
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
Source code in src/bbstrader/metatrader/broker.py
copier ¶
TradeCopier ¶
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)
Bases: object
TradeCopier responsible 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.
Initializes the TradeCopier instance, setting up the source and destination trading accounts for trade copying.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
dict
|
A dictionary containing the connection details for the source trading account. This dictionary
must include all parameters required to successfully connect to the source account.
Refer to the |
required |
destinations
|
list[dict]
|
A list of dictionaries, where each dictionary represents a destination trading account to which trades will be copied. Each destination dictionary must contain the following keys |
required |
sleeptime
|
float
|
The time interval in seconds between each iteration of the trade copying process. Defaults to 0.1 seconds. It can be useful if you know the frequency of new trades on the source account. |
0.1
|
start_time
|
str
|
The time (HH:MM) from which the copier start copying from the source. |
None
|
end_time
|
str
|
The time (HH:MM) from which the copier stop copying from the source. |
None
|
custom_logger
|
(Any, Optional)
|
Used to set a cutum logger (default is |
None
|
shutdown_event
|
(Any, Otional)
|
Use to terminate the copy process when runs in a custum environment like web App or GUI. |
None
|
log_queue
|
(Queue, Optional)
|
Use to send log to an external program, usefule in GUI apps |
None
|
Note
The source account and the destination accounts must be connected to different MetaTrader 5 platforms. you can copy the initial installation of MetaTrader 5 to a different directory and rename it to create a new instance Then you can connect destination accounts to the new instance while the source account is connected to the original instance.
Source code in src/bbstrader/metatrader/copier.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | |
start_copy_process ¶
Worker process: copies orders and positions concurrently for a single destination account.
Source code in src/bbstrader/metatrader/copier.py
run ¶
Entry point: Starts a dedicated worker thread for EACH destination account to run concurrently.
Source code in src/bbstrader/metatrader/copier.py
stop ¶
Stop the Trade Copier gracefully by setting the shutdown event.
Source code in src/bbstrader/metatrader/copier.py
copier_worker_process ¶
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)
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:
| Name | Type | Description | Default |
|---|---|---|---|
source_config
|
dict
|
Configuration dictionary for the source account. Must contain 'login', 'password', 'server', and 'path'. |
required |
destination_config
|
dict
|
Configuration dictionary for a single destination account. |
required |
sleeptime
|
float
|
The time in seconds to wait between copy cycles. |
required |
start_time
|
str
|
The time of day to start copying (e.g., "08:00"). |
required |
end_time
|
str
|
The time of day to stop copying (e.g., "22:00"). |
required |
custom_logger
|
An optional custom logger instance. |
None
|
|
shutdown_event
|
Event
|
An event object that, when set, will signal this process to terminate gracefully. |
None
|
log_queue
|
Queue
|
A queue for sending log messages back to the parent process in a thread-safe manner. |
None
|
Source code in src/bbstrader/metatrader/copier.py
RunCopier ¶
RunCopier(source: dict, destinations: list, sleeptime: float, start_time: str, end_time: str, /, custom_logger=None, shutdown_event=None, log_queue=None)
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.
Parameters¶
source : dict
Configuration dictionary for the source account.
destinations : list
A list of configuration dictionaries, one for each
destination account to be processed sequentially.
sleeptime : float
The time in seconds to wait after completing a full
cycle through all destinations.
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 : logging.Logger, optional
An optional custom logger instance.
shutdown_event : multiprocessing.Event, optional
An event to signal shutdown.
log_queue : multiprocessing.Queue, optional
A queue for log messages.
Returns¶
None
Runs until stopped via shutdown_event or external interruption.
Source code in src/bbstrader/metatrader/copier.py
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 | |
RunMultipleCopier ¶
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)
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 accounts structure:
.. code-block:: python
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 source key and a destinations key.
sleeptime : float, optional
The sleep time passed down to each RunCopier process.
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 RunCopier process.
end_time : str, optional
The end time passed down to each RunCopier process.
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¶
None
Runs until stopped via shutdown_event or external interruption.
Source code in src/bbstrader/metatrader/copier.py
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 | |
auto_convert ¶
Convert string values to appropriate data types
Source code in src/bbstrader/metatrader/copier.py
dict_from_ini ¶
Reads an INI file and converts it to a dictionary with proper data types. Args: file_path: Path to the INI file to read. sections: Optional list of sections to read from the INI file. Returns: A dictionary containing the INI file contents with proper data types.
Source code in src/bbstrader/metatrader/copier.py
config_copier ¶
config_copier(source_section: str = None, dest_sections: str | list[str] = None, inifile: str | Path = None) -> tuple[dict, list[dict]]
Read the configuration file and return the source and destination account details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inifile
|
str | Path
|
The path to the INI configuration file. |
None
|
source_section
|
str
|
The section name of the source account, defaults to "SOURCE". |
None
|
dest_sections
|
str | list[str]
|
The section name(s) of the destination account(s). |
None
|
Returns:
| Type | Description |
|---|---|
tuple[dict, list[dict]]
|
tuple[dict, list[dict]]: A tuple containing the source account and a list of destination accounts. |
Example
Source code in src/bbstrader/metatrader/copier.py
rates ¶
Rates ¶
Rates(symbol: str, timeframe: str = 'D1', start_pos: int = 0, count: int | None = MAX_BARS, **kwargs)
Provides 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
-
Befor using this class, ensure that the
Max bars in chartin 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 toTools->Options->Charts->Max bars in chart. -
The
open, high, low, close, adjclose, returns, volumeproperties 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())
Initializes a new Rates instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Financial instrument symbol (e.g., "EURUSD"). |
required |
timeframe
|
str
|
Timeframe string (e.g., "D1", "1h", "5m"). |
'D1'
|
start_pos
|
int
|
Starting index (int) for data retrieval. |
0
|
count
|
int
|
Number of bars to retrieve default is the maximum bars availble in the MT5 terminal. |
MAX_BARS
|
Raises: ValueError: If the provided timeframe is invalid.
Source code in src/bbstrader/metatrader/rates.py
returns
property
¶
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.
get_rates_from_pos ¶
get_rates_from_pos(filter=False, fill_na=False, lower_colnames=False, utc=False) -> pd.DataFrame | None
Retrieves historical data starting from a specific position.
Uses the start_pos and count attributes specified during
initialization to fetch data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filter
|
See |
required | |
fill_na
|
See |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
utc
|
bool
|
If True, the data will be in UTC timezone. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical |
DataFrame | None
|
data if successful, otherwise None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The Datetime for this method is in Broker's timezone.
Source code in src/bbstrader/metatrader/rates.py
get_rates_from ¶
get_rates_from(date_from: datetime | Timestamp, count: int = MAX_BARS, filter=False, fill_na=False, lower_colnames=False, utc=False) -> pd.DataFrame | None
Retrieves historical data within a specified date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
Starting date for data retrieval. The data will be retrieved from this date going to the past. |
required | |
count
|
Number of bars to retrieve. |
required | |
filter
|
See |
required | |
fill_na
|
See |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
utc
|
bool
|
If True, the data will be in UTC timezone. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical |
DataFrame | None
|
data if successful, otherwise None. |
Source code in src/bbstrader/metatrader/rates.py
get_historical_data ¶
get_historical_data(date_from: datetime | Timestamp, date_to: datetime | Timestamp = pd.Timestamp.now(), utc: bool = False, filter: bool | None = False, fill_na: bool | str | None = False, lower_colnames: bool | None = True, save_csv: bool | None = False) -> pd.DataFrame | None
Retrieves historical data within a specified date range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date_from
|
Starting date for data retrieval. |
required | |
date_to
|
Ending date for data retrieval. Defaults to the current time. |
required | |
utc
|
If True, the data will be in UTC timezone. Defaults to False. |
required | |
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. |
required | |
fill_na
|
If True, the data will be filled with the nearest value.
This is use only when 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. |
required | |
lower_colnames
|
If True, the column names will be converted to lowercase. |
required | |
save_csv
|
File path to save the data as a CSV. If None, the data won't be saved. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame | None
|
Union[pd.DataFrame, None]: A DataFrame containing historical data if successful, otherwise None. |
Raises:
| Type | Description |
|---|---|
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_futures calendar.
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.
Source code in src/bbstrader/metatrader/rates.py
download_historical_data ¶
download_historical_data(symbol, timeframe, date_from, date_to=pd.Timestamp.now(), lower_colnames=True, utc=False, filter=False, fill_na=False, save_csv=False, **kwargs)
Download historical data from MetaTrader 5 terminal.
See Rates.get_historical_data for more details.
Source code in src/bbstrader/metatrader/rates.py
get_data_from_pos ¶
get_data_from_pos(symbol, timeframe, start_pos=0, fill_na=False, count=MAX_BARS, lower_colnames=False, utc=False, filter=False, session_duration=23.0, **kwargs)
Get historical data from a specific position.
See Rates.get_rates_from_pos for more details.
Source code in src/bbstrader/metatrader/rates.py
get_data_from_date ¶
get_data_from_date(symbol, timeframe, date_from, count=MAX_BARS, fill_na=False, lower_colnames=False, utc=False, filter=False, **kwargs)
Get historical data from a specific date.
See Rates.get_rates_from for more details.
Source code in src/bbstrader/metatrader/rates.py
risk ¶
RiskManagement ¶
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, account_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)
The 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()
Initialize the RiskManagement class to manage risk in trading activities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The symbol of the financial instrument to trade. |
required |
max_risk
|
float
|
The |
10.0
|
daily_risk
|
float
|
|
None
|
max_trades
|
int
|
Maximum number of trades at any point in time. If set to None it will be determine based on the timeframe of trading. |
None
|
std_stop
|
bool
|
If set to True, the Stop loss is calculated based
On |
False
|
pchange_sl
|
float
|
If set, the Stop loss is calculated based
On |
None
|
act_leverage
|
bool
|
If set to True the account leverage will be used In risk management setting. Defaults to False. |
required |
time_frame
|
str
|
The time frame on which the program is working
|
'D1'
|
start_time
|
str
|
The starting time for the trading session
|
'1:00'
|
finishing_time
|
str
|
The finishing time for the trading strategy
|
'23:00'
|
sl
|
int
|
Stop Loss in points, Must be a positive number. |
None
|
tp
|
int
|
Take Profit in points, Must be a positive number. |
None
|
be
|
int
|
Break Even in points, Must be a positive number. |
None
|
rr
|
float
|
Risk reward ratio, Must be a positive number. Defaults to 1.5. |
3.0
|
Source code in src/bbstrader/metatrader/risk.py
get_minutes ¶
calculates the number of minutes between the starting of the session and the end of the session
Source code in src/bbstrader/metatrader/risk.py
get_hours ¶
Calculates the number of hours between the starting of the session and the end of the session
risk_level ¶
Calculates the risk level of a trade
Returns: - Risk level in the form of a float percentage.
Source code in src/bbstrader/metatrader/risk.py
max_trade ¶
calculates the maximum number of trades allowed
Source code in src/bbstrader/metatrader/risk.py
get_std_stop ¶
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.
Source code in src/bbstrader/metatrader/risk.py
get_pchange_stop ¶
Calculate the percentage change-based stop loss level for a given financial instrument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
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. |
required |
Returns: - Percentage change-based stop loss level, rounded to the nearest point. - 0 if the calculated stop loss is <= 0.
Source code in src/bbstrader/metatrader/risk.py
calculate_var ¶
Calculate Value at Risk (VaR) for a given portfolio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tf
|
str
|
Time frame to use to calculate volatility. |
'D1'
|
c
|
float
|
Confidence level for VaR calculation (default is 95%). |
0.95
|
Returns: - VaR value
Source code in src/bbstrader/metatrader/risk.py
get_trade_risk ¶
Calculate risk per trade as percentage
Source code in src/bbstrader/metatrader/risk.py
var_loss_value ¶
Calculate the stop-loss level based on VaR.
Notes
The Var is Estimated using the Variance-Covariance method on the daily returns. If you want to use the VaR for a different time frame .
Source code in src/bbstrader/metatrader/risk.py
get_take_profit ¶
calculates the take profit of a trade in points
get_currency_risk ¶
expected_profit ¶
volume ¶
currency_risk ¶
Calculates the currency risk of a trade.
Returns:
| Type | Description |
|---|---|
dict[str, int | float | Any]
|
Dict[str, Union[int, float, Any]]: A dictionary containing the following keys: |
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
dict[str, int | float | Any]
|
|
Source code in src/bbstrader/metatrader/risk.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
get_break_even ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
thresholds
|
list[tuple[int, float]]
|
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. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The calculated break-even value in points/pips. |
Note
The function automatically sorts thresholds in descending order to ensure the 'stop' value is matched against the highest possible tier first.
Source code in src/bbstrader/metatrader/risk.py
trade ¶
Trade ¶
Trade(symbol: str = 'EURUSD', expert_name: str = 'bbstrader', expert_id: int = EXPERT_ID, 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)
Extends 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)
Initializes the Trade class with the specified parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
The |
'EURUSD'
|
expert_name
|
str
|
The name of the |
'bbstrader'
|
expert_id
|
int
|
The |
EXPERT_ID
|
version
|
str
|
The |
'3.0'
|
target
|
float
|
|
5.0
|
start_time
|
str
|
The |
'1:00'
|
finishing_time
|
str
|
The time after which no new position can be opened. |
'23:00'
|
ending_time
|
str
|
The time after which any open position will be closed. |
'23:30'
|
verbose
|
bool | None
|
If set to None (default), account summary and risk managment parameters are printed in the terminal. |
False
|
console_log
|
bool
|
If set to True, log messages are displayed in the console. |
False
|
logger
|
Logger | str
|
The logger object to use for logging messages could be a string or a logger object. |
'bbstrader.log'
|
**kwargs
|
Params for the RiskManagement and Account
See the |
{}
|
Source code in src/bbstrader/metatrader/trade.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
initialize ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If initialization fails. |
Source code in src/bbstrader/metatrader/trade.py
select_symbol ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If symbole selection fails. |
Source code in src/bbstrader/metatrader/trade.py
prepare_symbol ¶
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:
| Type | Description |
|---|---|
MT5TerminalError
|
If the symbol cannot be made visible for trading operations. |
Source code in src/bbstrader/metatrader/trade.py
summary ¶
Show a brief description about the trading program
Source code in src/bbstrader/metatrader/trade.py
risk_managment ¶
Show the risk management parameters
Source code in src/bbstrader/metatrader/trade.py
statistics ¶
Print some statistics for the trading session and save to CSV if specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save
|
bool
|
Whether to save the statistics to a CSV file. |
True
|
dir
|
str
|
The directory to save the CSV file. |
None
|
Source code in src/bbstrader/metatrader/trade.py
open_position ¶
open_position(action: Buys | Sells, 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
Opens a Buy or Sell position (Market or Pending).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
action
|
str
|
( |
required |
price
|
float
|
The price at which to open an order |
None
|
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 |
None
|
id
|
int
|
The strategy id or expert Id |
None
|
mm
|
bool
|
Weither to put stop loss and tp or not |
True
|
trail
|
bool
|
Weither to trail the stop loss or not |
True
|
comment
|
str
|
The comment for the closing position |
None
|
symbol
|
str
|
The symbol to trade |
None
|
volume
|
float
|
The volume (lot) to trade |
None
|
sl
|
float
|
The stop loss price |
None
|
tp
|
float
|
The take profit price |
None
|
Source code in src/bbstrader/metatrader/trade.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
open_buy_position ¶
Open a buy position or order.
See Trade.open_position for the kwargs parameters.
open_sell_position ¶
Open a sell position or order.
See Trade.open_position for the kwargs parameters.
check ¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
comment
|
str
|
The comment for the closing position |
required |
Source code in src/bbstrader/metatrader/trade.py
request_result ¶
Check if a trading order has been sent correctly
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
price
|
float
|
Price for opening the position |
required |
request
|
Dict[str, Any]
|
A trade request to sent to Mt5.order_sent() |
required |
all detail in request can be found here https
|
//www.mql5.com/en/docs/python_metatrader5/mt5ordersend_py |
required | |
type
|
str
|
The type of the order |
required |
Source code in src/bbstrader/metatrader/trade.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | |
get_filtered_tickets ¶
get_filtered_tickets(id: int | None = None, filter_type: str | None = None, th=None) -> list[int] | None
Get tickets for positions or orders based on filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
The strategy id or expert Id |
None
|
filter_type
|
str
|
Filter type to apply on the tickets,
- |
None
|
th
|
bool
|
the minimum treshold for winning position (only relevant when filter_type is 'profitables') |
None
|
Returns:
| Type | Description |
|---|---|
list[int] | None
|
List[int] | None: A list of filtered tickets or None if no tickets match the criteria. |
Source code in src/bbstrader/metatrader/trade.py
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 | |
positive_profit ¶
Check is the total profit on current open positions Is greater than a minimum profit express as percentage of the profit target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
th
|
float
|
The minimum profit target on current positions |
None
|
id
|
int
|
The strategy id or expert Id |
None
|
account
|
bool
|
Weither to check positions on the account or on the symbol |
True
|
Source code in src/bbstrader/metatrader/trade.py
break_even ¶
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)
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:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int
|
The strategy ID or expert ID. |
None
|
mm
|
bool
|
Whether to manage the position or not. |
True
|
trail
|
bool
|
Whether to trail the stop loss or not. |
True
|
stop_trail
|
int
|
Number of points to trail the stop loss by. It represent the distance from the current price to the stop loss. |
None
|
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. |
None
|
be_plus_points
|
int
|
Number of points to add to the break-even level. Represents the minimum profit to secure. |
None
|
Source code in src/bbstrader/metatrader/trade.py
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 | |
set_break_even ¶
set_break_even(position: TradePosition, be: int, price: float | None = None, level: float | None = None)
Sets the break-even level for a given trading position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position
|
TradePosition
|
The trading position for which the break-even is to be set.
This is the value return by |
required |
be
|
int
|
The break-even level in points. |
required |
level
|
float
|
The break-even level in price, if set to None , it will be calated automaticaly. |
None
|
price
|
float
|
The break-even price, if set to None , it will be calated automaticaly. |
None
|
Source code in src/bbstrader/metatrader/trade.py
break_even_request ¶
Send a request to set the stop loss to break even for a given trading position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiket
|
int
|
The ticket number of the trading position. |
required |
price
|
float
|
The price at which the stop loss is to be set. |
required |
request
|
dict
|
The request to set the stop loss to break even. |
required |
Source code in src/bbstrader/metatrader/trade.py
win_trade ¶
Determines if a position has met the minimum 'win' threshold in points.
Source code in src/bbstrader/metatrader/trade.py
profit_target ¶
Checks if the net profit for today's deals has reached the percentage target.
Source code in src/bbstrader/metatrader/trade.py
close_request ¶
Close a trading order or position
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
dict
|
The request to close a trading order or position |
required |
type
|
str
|
Type of the request ('order', 'position') |
required |
Source code in src/bbstrader/metatrader/trade.py
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 | |
modify_order ¶
modify_order(ticket: int, price: float | None = None, stoplimit: float | None = None, sl: float | None = None, tp: float | None = None)
Modify an open order by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Order ticket to modify (e.g TradeOrder.ticket) |
required |
price
|
float
|
The price at which to modify the order |
None
|
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 |
None
|
sl
|
float
|
The stop loss in points |
None
|
tp
|
float
|
The take profit in points |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_order ¶
Close an open order by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Order ticket to close (e.g TradeOrder.ticket) |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Returns: - True if order closed, False otherwise
Source code in src/bbstrader/metatrader/trade.py
close_position ¶
close_position(ticket: int, id: int | None = None, pct: float | None = 1.0, comment: str | None = None, symbol: str | None = None) -> bool
Close an open position by it ticket
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ticket
|
int
|
Positon ticket to close (e.g TradePosition.ticket) |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
pct
|
float
|
Percentage of the position to close |
1.0
|
comment
|
str
|
Comment for the closing position |
None
|
Returns: - True if position closed, False otherwise
Source code in src/bbstrader/metatrader/trade.py
bulk_close ¶
bulk_close(tickets: list, tikets_type: Literal['positions', 'orders'], close_func: Callable, order_type: str, id: int | None = None, comment: str | None = None)
Close multiple orders or positions at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tickets
|
List
|
List of tickets to close |
required |
tikets_type
|
str
|
Type of tickets to close ('positions', 'orders') |
required |
close_func
|
Callable
|
The function to close the tickets |
required |
order_type
|
str
|
Type of orders or positions to close |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_orders ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order_type
|
str
|
Type of orders to close ('all', 'buy_stops', 'sell_stops', 'buy_limits', 'sell_limits', 'buy_stop_limits', 'sell_stop_limits') |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
close_positions ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
position_type
|
str
|
Type of positions to close ('all', 'buy', 'sell', 'profitable', 'losing') |
required |
id
|
int
|
The unique ID of the Expert or Strategy |
None
|
comment
|
str
|
Comment for the closing position |
None
|
Source code in src/bbstrader/metatrader/trade.py
is_max_trades_reached ¶
Check if the maximum number of trades for the day has been reached.
:return: bool
Source code in src/bbstrader/metatrader/trade.py
get_stats ¶
Retrieves aggregated session and historical trading performance.
Source code in src/bbstrader/metatrader/trade.py
sharpe ¶
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.
Source code in src/bbstrader/metatrader/trade.py
days_end ¶
Check if it is the end of the trading day.
Source code in src/bbstrader/metatrader/trade.py
trading_time ¶
Check if it is time to trade.
Source code in src/bbstrader/metatrader/trade.py
create_trade_instance ¶
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]
Creates Trade instances for each symbol provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
list[str]
|
A list of trading symbols (e.g., ['AAPL', 'MSFT']). |
required |
params
|
dict[str, Any]
|
A dictionary containing parameters for the Trade instance. |
required |
daily_risk
|
dict[str, float] | None
|
A dictionary containing daily risk weight for each symbol. |
None
|
max_risk
|
dict[str, float] | None
|
A dictionary containing maximum risk weight for each symbol. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Trade]
|
A dictionary where keys are symbols and values are corresponding Trade instances. |
Raises:
| Type | Description |
|---|---|
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.
Source code in src/bbstrader/metatrader/trade.py
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 | |
utils ¶
TimeFrame ¶
Bases: Enum
Rrepresent a time frame object
SymbolType ¶
Bases: Enum
Represents the type of a symbol.
RateInfo ¶
Bases: NamedTuple
Reprents 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
InvalidBroker ¶
MT5TerminalError ¶
GenericFail ¶
Bases: MT5TerminalError
Exception raised for generic failure.
Source code in src/bbstrader/metatrader/utils.py
InvalidParams ¶
Bases: MT5TerminalError
Exception raised for invalid arguments or parameters.
Source code in src/bbstrader/metatrader/utils.py
HistoryNotFound ¶
Bases: MT5TerminalError
Exception raised when no history is found.
Source code in src/bbstrader/metatrader/utils.py
InvalidVersion ¶
Bases: MT5TerminalError
Exception raised for an invalid version.
Source code in src/bbstrader/metatrader/utils.py
AuthFailed ¶
Bases: MT5TerminalError
Exception raised for authorization failure.
Source code in src/bbstrader/metatrader/utils.py
UnsupportedMethod ¶
Bases: MT5TerminalError
Exception raised for an unsupported method.
Source code in src/bbstrader/metatrader/utils.py
AutoTradingDisabled ¶
Bases: MT5TerminalError
Exception raised when auto-trading is disabled.
Source code in src/bbstrader/metatrader/utils.py
InternalFailError ¶
Bases: MT5TerminalError
Base exception class for internal IPC errors.
Source code in src/bbstrader/metatrader/utils.py
InternalFailSend ¶
Bases: InternalFailError
Exception raised for internal IPC send failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailReceive ¶
Bases: InternalFailError
Exception raised for internal IPC receive failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailInit ¶
Bases: InternalFailError
Exception raised for internal IPC initialization failure.
Source code in src/bbstrader/metatrader/utils.py
InternalFailConnect ¶
Bases: InternalFailError
Exception raised for no IPC connection.
Source code in src/bbstrader/metatrader/utils.py
InternalFailTimeout ¶
Bases: InternalFailError
Exception raised for an internal timeout.
Source code in src/bbstrader/metatrader/utils.py
raise_mt5_error ¶
Raises an exception based on the given error code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
Optional[str]
|
An optional custom error message. |
None
|
Raises:
| Type | Description |
|---|---|
MT5TerminalError
|
A specific exception based on the error code. |
Source code in src/bbstrader/metatrader/utils.py
retry_on_disconnect ¶
Decorator that retries a function on MT5 connection errors with exponential back-off.
Catches InternalFailConnect and InternalFailTimeout, waits
delay * 2**attempt seconds between tries, then re-raises on the last attempt.
Source code in src/bbstrader/metatrader/utils.py
trade_retcode_message ¶
Retrieves a user-friendly message corresponding to a given trade return code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
The trade return code to look up. |
required |
display
|
bool
|
Whether to print the message to the console. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
The message associated with the provided trade return code. If the code is not found, it returns "Unknown trade error.". |