bbstrader.trading¶
Live execution and strategy orchestration: manages live sessions, coordinates signals from
strategies and risk from models, and dispatches execution via bbstrader.metatrader.
trading ¶
Overview¶
The Trading Module is responsible for the execution of trading strategies. It provides a structured framework for implementing and managing trading strategies, from signal generation to order execution. This module is designed to be flexible and extensible, allowing for the customization of trading logic and integration with various execution handlers.
Features¶
- Strategy Execution Framework: Defines a clear structure for creating and executing trading strategies.
- Signal Generation: Supports the generation of trading signals based on market data and strategy logic.
- Order Management: Manages the creation and execution of orders based on generated signals.
- Extensibility: Allows for the implementation of custom strategies and execution handlers.
Components¶
- Execution: Handles the execution of trades, with a base class for creating custom execution handlers.
- Strategy: Defines the core logic of the trading strategy, including signal generation and order creation.
- Utils: Provides utility functions to support the trading process.
Notes¶
This module can be used in both backtesting and live trading environments by swapping out the execution handler.
Mt5ExecutionEngine ¶
Mt5ExecutionEngine(symbol_list: List[str], trades_instances: Dict[str, Trade], strategy_cls: Strategy | LiveStrategy, /, mm: bool = True, auto_trade: bool = True, prompt_callback: Callable = None, multithread: bool = False, shutdown_event: Event = None, optimizer: str = 'equal', trail: bool = True, stop_trail: Optional[int] = None, trail_after_points: int | str = None, be_plus_points: Optional[int] = None, show_positions_orders: bool = False, iter_time: int | float = 5, use_trade_time: bool = True, period: Literal['24/7', 'day', 'week', 'month'] = 'month', period_end_action: Literal['break', 'sleep'] = 'sleep', closing_pnl: Optional[float] = None, trading_days: Optional[List[str]] = None, comment: Optional[str] = None, **kwargs)
The Mt5ExecutionEngine class serves as the central hub for executing your trading strategies within the bbstrader framework.
It orchestrates the entire trading process, ensuring seamless interaction between your strategies, market data, and your chosen
trading platform.
Key Features¶
- Strategy Execution: The
Mt5ExecutionEngineis responsible for running your strategy, retrieving signals, and executing trades based on those signals. - Time Management: You can define a specific time frame for your trades and set the frequency with which the engine checks for signals and manages trades.
- Trade Period Control: Define whether your strategy runs for a day, a week, or a month, allowing for flexible trading durations.
- Money Management: The engine supports optional money management features, allowing you to control risk and optimize your trading performance.
- Trading Day Configuration: You can customize the days of the week your strategy will execute, providing granular control over your trading schedule.
- Platform Integration: The
Mt5ExecutionEngineis currently designed to work with MT5.
Examples¶
from bbstrader.metatrader import create_trade_instance from bbstrader.trading.execution import Mt5ExecutionEngine from examples.strategies import StockIndexSTBOTrading from bbstrader.config import config_logger
if name == 'main': logger = config_logger(index_trade.log, console_log=True) # Define symbols ndx = '[NQ100]' spx = '[SP500]' dji = '[DJI30]' dax = 'GERMANY40'
symbol_list = [spx, dax, dji, ndx] trade_kwargs = {... 'expert_id': 5134, ... 'version': 2.0, ... 'time_frame': '15m', ... 'var_level': 0.99, ... 'start_time': '8:30', ... 'finishing_time': '19:30', ... 'ending_time': '21:30', ... 'max_risk': 5.0, ... 'daily_risk': 0.10, ... 'pchange_sl': 1.5, ... 'rr': 3.0, ... 'logger': logger ... } strategy_kwargs = { ... 'max_trades': {ndx: 3, spx: 3, dji: 3, dax: 3}, ... 'expected_returns': {ndx: 1.5, spx: 1.5, dji: 1.0, dax: 1.0}, ... 'strategy_name': 'SISTBO', ... 'logger': logger, ... 'expert_id': 5134 ... } trades_instances = create_trade_instance( ... symbol_list, trade_kwargs, ... logger=logger, ... )
engine = Mt5ExecutionEngine(... symbol_list, ... trades_instances, ... StockIndexCFDTrading, ... time_frame='15m', ... iter_time=5, ... mm=True, ... period='week', ... comment='bbs_SISTBO_@2.0', ... **strategy_kwargs ... ) engine.run()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
List of symbols to trade |
required | |
trades_instances
|
Dictionary of Trade instances |
required | |
strategy_cls
|
Strategy class to use for trading |
required | |
mm
|
Enable Money Management. Defaults to True. |
required | |
optimizer
|
Risk management optimizer. Defaults to 'equal'.
See |
required | |
auto_trade
|
If set to true, when signal are generated by the strategy class, the Execution engine will automaticaly open position in other whise it will prompt the user for confimation. |
required | |
prompt_callback
|
Callback function to prompt the user for confirmation. This is useful when integrating with GUI applications. multithread : If True, use a thread pool to process signals in parallel. If False, process them sequentially. Set this to True only if the engine is running in a separate process. Default to False. |
required | |
shutdown_event
|
Use to terminate the copy process when runs in a custum environment like web App or GUI. |
required | |
show_positions_orders
|
Print open positions and orders. Defaults to False. |
required | |
iter_time
|
Interval to check for signals and |
required | |
use_trade_time
|
Open trades after the time is completed. Defaults to True. |
required | |
period
|
Period to trade ("24/7", "day", "week", "month"). Defaults to 'week'. |
required | |
period_end_action
|
Action to take at the end of the period ("break", "sleep"). Defaults to 'break', this only applies when period is 'day', 'week'. |
required | |
closing_pnl
|
Minimum profit in percentage of target profit to close positions. Defaults to -0.001. |
required | |
trading_days
|
Trading days in a week. Defaults to monday to friday. |
required | |
comment
|
Optional[str]
|
Comment for trades. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments _ time_frame : Time frame to trade. Defaults to '15m'. - strategy_name (Optional[str]): Strategy name. Defaults to None. - max_trades (Dict[str, int]): Maximum trades per symbol. Defaults to None. - notify (bool): Enable notifications. Defaults to False. - telegram (bool): Enable telegram notifications. Defaults to False. - bot_token (str): Telegram bot token. Defaults to None. - chat_id (Union[int, str, List] ): Telegram chat id. Defaults to None. - MT5 connection arguments. |
{}
|
Note
- For
trail,stop_trail,trail_after_points,be_plus_pointsseebbstrader.metatrader.trade.Trade.break_even(). -
All Strategies must inherit from
bbstrader.btengine.strategy.MT5Strategyclass and have acalculate_signalsmethod that returns a List ofbbstrader.metatrader.trade.TradingSignal. -
All strategies must have the following arguments in their
__init__method:- bars (DataHandler): DataHandler instance default to None
- events (Queue): Queue instance default to None
- symbol_list (List[str]): List of symbols to trade can be none for backtesting
- mode (str): Mode of the strategy. Must be either 'live' or 'backtest'
- **kwargs: Additional keyword arguments
The keyword arguments are all the additional arguments passed to the
Mt5ExecutionEngineclass, theStrategyclass, theDataHandlerclass, thePortfolioclass and theExecutionHandlerclass. - The
barsandeventsarguments are used for backtesting only.
-
All strategies must generate signals for backtesting and live trading. See the
bbstrader.trading.strategiesmodule for more information on how to create custom strategies. Seebbstrader.metatrader.account.check_mt5_connection()for more details on how to connect to MT5 terminal.
Source code in src/bbstrader/trading/execution.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
stop ¶
Stops the execution engine.
Source code in src/bbstrader/trading/execution.py
LiveStrategy ¶
Bases: BaseStrategy
Strategy implementation for Live Trading.
Relies on the Account class for state (orders, positions, cash)
and Rates for data.
Initialize the LiveStrategy object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
The list of symbols for the strategy. |
required | |
**kwargs
|
Additional keyword arguments for other classes (e.g, Portfolio, ExecutionHandler). - max_trades : The maximum number of trades allowed per symbol. - time_frame : The time frame for the strategy. - logger : The logger object for the strategy. |
required |
Source code in src/bbstrader/trading/strategy.py
signal ¶
Generate a TradeSignal object based on the signal value.
Parameters¶
signal : int An integer value representing the signal type: * 0: BUY * 1: SELL * 2: EXIT_LONG * 3: EXIT_SHORT * 4: EXIT_ALL_POSITIONS * 5: EXIT_ALL_ORDERS * 6: EXIT_STOP * 7: EXIT_LIMIT symbol : str The symbol for the trade.
Returns¶
TradeSignal
A TradeSignal object representing the trade signal.
Raises¶
ValueError If the signal value is not between 0 and 7.
Notes¶
This generates only common signals. For more complex signals, use
generate_signal directly.
Source code in src/bbstrader/trading/strategy.py
ispositions ¶
ispositions(symbol: str, strategy_id: int, position: int, max_trades: int, one_true: bool = False) -> bool
This function is use for live trading to check if there are open positions for a given symbol and strategy. It is used to prevent opening more trades than the maximum allowed trades per symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
position
|
The position type (1: short, 0: long). |
required | |
max_trades
|
The maximum number of trades allowed per symbol. |
required | |
one_true
|
If True, return True if there is at least one open position. |
required | |
account
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if there are open positions, False otherwise |
Source code in src/bbstrader/trading/strategy.py
get_positions_prices ¶
Get the buy or sell prices for open positions of a given symbol and strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
position
|
The position type (1: short, 0: long). |
required | |
account
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
prices |
ndarray
|
numpy array of buy or sell prices for open positions if any or an empty array. |
Source code in src/bbstrader/trading/strategy.py
get_active_orders ¶
get_active_orders(symbol: str, strategy_id: int, order_type: Optional[int] = None) -> List[TradeOrder]
Get the active orders for a given symbol and strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
order_type
|
The type of order to filter by (optional): "BUY_LIMIT": 2 "SELL_LIMIT": 3 "BUY_STOP": 4 "SELL_STOP": 5 "BUY_STOP_LIMIT": 6 "SELL_STOP_LIMIT": 7 |
required |
Returns:
| Type | Description |
|---|---|
List[TradeOrder]
|
List[TradeOrder] : A list of active orders for the given symbol and strategy. |
Source code in src/bbstrader/trading/strategy.py
exit_positions ¶
Logic to determine if positions should be exited based on threshold.
Source code in src/bbstrader/trading/strategy.py
send_trade_report ¶
Generates and sends a trade report message containing performance metrics for the current strategy.
This method retrieves the trade history for the current account, filters it by the strategy's ID,
computes performance metrics using the provided perf_analyzer callable, and formats the results
into a message. The message includes account information, strategy details, a timestamp, and
performance metrics. The message is then sent via Telegram using the specified bot token and chat ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
perf_analyzer
|
Callable
|
A function or callable object that takes the filtered trade history (as a DataFrame) and additional keyword arguments, and returns a DataFrame of performance metrics. |
required |
**kwargs
|
Any
|
Additional keyword arguments, which may include
- Any other param requires by |
{}
|
Source code in src/bbstrader/trading/strategy.py
RunMt5Engine ¶
Start an MT5 execution engine for a given account.
Parameters¶
account_id : str Account ID to run the execution engine on.
**kwargs : dict Additional keyword arguments. Possible keys include:
* symbol_list : list
List of symbols to trade.
* trades_instances : dict
Dictionary of Trade instances.
* strategy_cls : class
Strategy class to use for trading.
Returns¶
None Initializes and runs the MT5 execution engine.
Source code in src/bbstrader/trading/execution.py
RunMt5Engines ¶
Runs multiple MT5 execution engines in parallel using multiprocessing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Dict[str, Dict]
|
Dictionary of accounts to run the execution engines on.
Keys are the account names or IDs and values are the parameters for the execution engine.
The parameters are the same as the ones passed to the |
required |
start_delay
|
float
|
Delay in seconds between starting the processes. Defaults to 1.0. |
1.0
|
Source code in src/bbstrader/trading/execution.py
execution ¶
Mt5ExecutionEngine ¶
Mt5ExecutionEngine(symbol_list: List[str], trades_instances: Dict[str, Trade], strategy_cls: Strategy | LiveStrategy, /, mm: bool = True, auto_trade: bool = True, prompt_callback: Callable = None, multithread: bool = False, shutdown_event: Event = None, optimizer: str = 'equal', trail: bool = True, stop_trail: Optional[int] = None, trail_after_points: int | str = None, be_plus_points: Optional[int] = None, show_positions_orders: bool = False, iter_time: int | float = 5, use_trade_time: bool = True, period: Literal['24/7', 'day', 'week', 'month'] = 'month', period_end_action: Literal['break', 'sleep'] = 'sleep', closing_pnl: Optional[float] = None, trading_days: Optional[List[str]] = None, comment: Optional[str] = None, **kwargs)
The Mt5ExecutionEngine class serves as the central hub for executing your trading strategies within the bbstrader framework.
It orchestrates the entire trading process, ensuring seamless interaction between your strategies, market data, and your chosen
trading platform.
Key Features¶
- Strategy Execution: The
Mt5ExecutionEngineis responsible for running your strategy, retrieving signals, and executing trades based on those signals. - Time Management: You can define a specific time frame for your trades and set the frequency with which the engine checks for signals and manages trades.
- Trade Period Control: Define whether your strategy runs for a day, a week, or a month, allowing for flexible trading durations.
- Money Management: The engine supports optional money management features, allowing you to control risk and optimize your trading performance.
- Trading Day Configuration: You can customize the days of the week your strategy will execute, providing granular control over your trading schedule.
- Platform Integration: The
Mt5ExecutionEngineis currently designed to work with MT5.
Examples¶
from bbstrader.metatrader import create_trade_instance from bbstrader.trading.execution import Mt5ExecutionEngine from examples.strategies import StockIndexSTBOTrading from bbstrader.config import config_logger
if name == 'main': logger = config_logger(index_trade.log, console_log=True) # Define symbols ndx = '[NQ100]' spx = '[SP500]' dji = '[DJI30]' dax = 'GERMANY40'
symbol_list = [spx, dax, dji, ndx] trade_kwargs = {... 'expert_id': 5134, ... 'version': 2.0, ... 'time_frame': '15m', ... 'var_level': 0.99, ... 'start_time': '8:30', ... 'finishing_time': '19:30', ... 'ending_time': '21:30', ... 'max_risk': 5.0, ... 'daily_risk': 0.10, ... 'pchange_sl': 1.5, ... 'rr': 3.0, ... 'logger': logger ... } strategy_kwargs = { ... 'max_trades': {ndx: 3, spx: 3, dji: 3, dax: 3}, ... 'expected_returns': {ndx: 1.5, spx: 1.5, dji: 1.0, dax: 1.0}, ... 'strategy_name': 'SISTBO', ... 'logger': logger, ... 'expert_id': 5134 ... } trades_instances = create_trade_instance( ... symbol_list, trade_kwargs, ... logger=logger, ... )
engine = Mt5ExecutionEngine(... symbol_list, ... trades_instances, ... StockIndexCFDTrading, ... time_frame='15m', ... iter_time=5, ... mm=True, ... period='week', ... comment='bbs_SISTBO_@2.0', ... **strategy_kwargs ... ) engine.run()
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
List of symbols to trade |
required | |
trades_instances
|
Dictionary of Trade instances |
required | |
strategy_cls
|
Strategy class to use for trading |
required | |
mm
|
Enable Money Management. Defaults to True. |
required | |
optimizer
|
Risk management optimizer. Defaults to 'equal'.
See |
required | |
auto_trade
|
If set to true, when signal are generated by the strategy class, the Execution engine will automaticaly open position in other whise it will prompt the user for confimation. |
required | |
prompt_callback
|
Callback function to prompt the user for confirmation. This is useful when integrating with GUI applications. multithread : If True, use a thread pool to process signals in parallel. If False, process them sequentially. Set this to True only if the engine is running in a separate process. Default to False. |
required | |
shutdown_event
|
Use to terminate the copy process when runs in a custum environment like web App or GUI. |
required | |
show_positions_orders
|
Print open positions and orders. Defaults to False. |
required | |
iter_time
|
Interval to check for signals and |
required | |
use_trade_time
|
Open trades after the time is completed. Defaults to True. |
required | |
period
|
Period to trade ("24/7", "day", "week", "month"). Defaults to 'week'. |
required | |
period_end_action
|
Action to take at the end of the period ("break", "sleep"). Defaults to 'break', this only applies when period is 'day', 'week'. |
required | |
closing_pnl
|
Minimum profit in percentage of target profit to close positions. Defaults to -0.001. |
required | |
trading_days
|
Trading days in a week. Defaults to monday to friday. |
required | |
comment
|
Optional[str]
|
Comment for trades. Defaults to None. |
None
|
**kwargs
|
Additional keyword arguments _ time_frame : Time frame to trade. Defaults to '15m'. - strategy_name (Optional[str]): Strategy name. Defaults to None. - max_trades (Dict[str, int]): Maximum trades per symbol. Defaults to None. - notify (bool): Enable notifications. Defaults to False. - telegram (bool): Enable telegram notifications. Defaults to False. - bot_token (str): Telegram bot token. Defaults to None. - chat_id (Union[int, str, List] ): Telegram chat id. Defaults to None. - MT5 connection arguments. |
{}
|
Note
- For
trail,stop_trail,trail_after_points,be_plus_pointsseebbstrader.metatrader.trade.Trade.break_even(). -
All Strategies must inherit from
bbstrader.btengine.strategy.MT5Strategyclass and have acalculate_signalsmethod that returns a List ofbbstrader.metatrader.trade.TradingSignal. -
All strategies must have the following arguments in their
__init__method:- bars (DataHandler): DataHandler instance default to None
- events (Queue): Queue instance default to None
- symbol_list (List[str]): List of symbols to trade can be none for backtesting
- mode (str): Mode of the strategy. Must be either 'live' or 'backtest'
- **kwargs: Additional keyword arguments
The keyword arguments are all the additional arguments passed to the
Mt5ExecutionEngineclass, theStrategyclass, theDataHandlerclass, thePortfolioclass and theExecutionHandlerclass. - The
barsandeventsarguments are used for backtesting only.
-
All strategies must generate signals for backtesting and live trading. See the
bbstrader.trading.strategiesmodule for more information on how to create custom strategies. Seebbstrader.metatrader.account.check_mt5_connection()for more details on how to connect to MT5 terminal.
Source code in src/bbstrader/trading/execution.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
stop ¶
Stops the execution engine.
Source code in src/bbstrader/trading/execution.py
RunMt5Engine ¶
Start an MT5 execution engine for a given account.
Parameters¶
account_id : str Account ID to run the execution engine on.
**kwargs : dict Additional keyword arguments. Possible keys include:
* symbol_list : list
List of symbols to trade.
* trades_instances : dict
Dictionary of Trade instances.
* strategy_cls : class
Strategy class to use for trading.
Returns¶
None Initializes and runs the MT5 execution engine.
Source code in src/bbstrader/trading/execution.py
RunMt5Engines ¶
Runs multiple MT5 execution engines in parallel using multiprocessing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
accounts
|
Dict[str, Dict]
|
Dictionary of accounts to run the execution engines on.
Keys are the account names or IDs and values are the parameters for the execution engine.
The parameters are the same as the ones passed to the |
required |
start_delay
|
float
|
Delay in seconds between starting the processes. Defaults to 1.0. |
1.0
|
Source code in src/bbstrader/trading/execution.py
strategy ¶
LiveStrategy ¶
Bases: BaseStrategy
Strategy implementation for Live Trading.
Relies on the Account class for state (orders, positions, cash)
and Rates for data.
Initialize the LiveStrategy object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol_list
|
The list of symbols for the strategy. |
required | |
**kwargs
|
Additional keyword arguments for other classes (e.g, Portfolio, ExecutionHandler). - max_trades : The maximum number of trades allowed per symbol. - time_frame : The time frame for the strategy. - logger : The logger object for the strategy. |
required |
Source code in src/bbstrader/trading/strategy.py
signal ¶
Generate a TradeSignal object based on the signal value.
Parameters¶
signal : int An integer value representing the signal type: * 0: BUY * 1: SELL * 2: EXIT_LONG * 3: EXIT_SHORT * 4: EXIT_ALL_POSITIONS * 5: EXIT_ALL_ORDERS * 6: EXIT_STOP * 7: EXIT_LIMIT symbol : str The symbol for the trade.
Returns¶
TradeSignal
A TradeSignal object representing the trade signal.
Raises¶
ValueError If the signal value is not between 0 and 7.
Notes¶
This generates only common signals. For more complex signals, use
generate_signal directly.
Source code in src/bbstrader/trading/strategy.py
ispositions ¶
ispositions(symbol: str, strategy_id: int, position: int, max_trades: int, one_true: bool = False) -> bool
This function is use for live trading to check if there are open positions for a given symbol and strategy. It is used to prevent opening more trades than the maximum allowed trades per symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
position
|
The position type (1: short, 0: long). |
required | |
max_trades
|
The maximum number of trades allowed per symbol. |
required | |
one_true
|
If True, return True if there is at least one open position. |
required | |
account
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if there are open positions, False otherwise |
Source code in src/bbstrader/trading/strategy.py
get_positions_prices ¶
Get the buy or sell prices for open positions of a given symbol and strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
position
|
The position type (1: short, 0: long). |
required | |
account
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
prices |
ndarray
|
numpy array of buy or sell prices for open positions if any or an empty array. |
Source code in src/bbstrader/trading/strategy.py
get_active_orders ¶
get_active_orders(symbol: str, strategy_id: int, order_type: Optional[int] = None) -> List[TradeOrder]
Get the active orders for a given symbol and strategy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
The symbol for the trade. |
required | |
strategy_id
|
The unique identifier for the strategy. |
required | |
order_type
|
The type of order to filter by (optional): "BUY_LIMIT": 2 "SELL_LIMIT": 3 "BUY_STOP": 4 "SELL_STOP": 5 "BUY_STOP_LIMIT": 6 "SELL_STOP_LIMIT": 7 |
required |
Returns:
| Type | Description |
|---|---|
List[TradeOrder]
|
List[TradeOrder] : A list of active orders for the given symbol and strategy. |
Source code in src/bbstrader/trading/strategy.py
exit_positions ¶
Logic to determine if positions should be exited based on threshold.
Source code in src/bbstrader/trading/strategy.py
send_trade_report ¶
Generates and sends a trade report message containing performance metrics for the current strategy.
This method retrieves the trade history for the current account, filters it by the strategy's ID,
computes performance metrics using the provided perf_analyzer callable, and formats the results
into a message. The message includes account information, strategy details, a timestamp, and
performance metrics. The message is then sent via Telegram using the specified bot token and chat ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
perf_analyzer
|
Callable
|
A function or callable object that takes the filtered trade history (as a DataFrame) and additional keyword arguments, and returns a DataFrame of performance metrics. |
required |
**kwargs
|
Any
|
Additional keyword arguments, which may include
- Any other param requires by |
{}
|
Source code in src/bbstrader/trading/strategy.py
utils ¶
send_telegram_message
async
¶
Send a message to a telegram chat
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str: Telegram bot token |
required | |
chat_id
|
int or str or list: Chat id or list of chat ids |
required | |
text
|
str: Message to send |
''
|
Source code in src/bbstrader/trading/utils.py
send_notification ¶
Send a desktop notification
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str: Title of the notification |
required | |
message
|
str: Message of the notification |
''
|
Source code in src/bbstrader/trading/utils.py
send_message ¶
send_message(title='SIGNAL', message='New signal', notify_me=False, telegram=False, token=None, chat_id=None)
Send a message to the user
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str: Title of the message |
'SIGNAL'
|
|
message
|
str: Message of the message |
'New signal'
|
|
notify_me
|
bool: Send a desktop notification |
False
|
|
telegram
|
bool: Send a telegram message |
False
|
|
token
|
str: Telegram bot token |
None
|
|
chat_id
|
int or str or list: Chat id or list of chat ids |
None
|