bbstrader.trading package

Module contents

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.

Submodules

bbstrader.trading.execution module

class bbstrader.trading.execution.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: int | None = None, trail_after_points: int | str = None, be_plus_points: int | None = 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: float | None = None, trading_days: List[str] | None = None, comment: str | None = None, **kwargs)[source]

Bases: object

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 Mt5ExecutionEngine is 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 Mt5ExecutionEngine is 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()
run()[source]
stop()[source]

Stops the execution engine.

bbstrader.trading.execution.RunMt5Engine(account_id: str, **kwargs)[source]

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_listlist

      List of symbols to trade.

    • trades_instancesdict

      Dictionary of Trade instances.

    • strategy_clsclass

      Strategy class to use for trading.

Returns:

Initializes and runs the MT5 execution engine.

Return type:

None

bbstrader.trading.execution.RunMt5Engines(accounts: Dict[str, Dict], start_delay: float = 1.0)[source]

Runs multiple MT5 execution engines in parallel using multiprocessing.

Parameters:
  • accounts – 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 Mt5ExecutionEngine class.

  • start_delay – Delay in seconds between starting the processes. Defaults to 1.0.

bbstrader.trading.strategy module

class bbstrader.trading.strategy.LiveStrategy(symbol_list: List[str], **kwargs: Any)[source]

Bases: BaseStrategy

Strategy implementation for Live Trading. Relies on the Account class for state (orders, positions, cash) and Rates for data.

property account: Account

Create or access the MT5 Account.

property cash: float

Returns the available cash (virtual or real).

events: Queue[SignalEvent | FillEvent]
exit_positions(position: int, prices: ndarray, asset: str, th: float = 0.01) bool[source]

Logic to determine if positions should be exited based on threshold.

get_active_orders(symbol: str, strategy_id: int, order_type: int | None = None) List[TradeOrder][source]

Get the active orders for a given symbol and strategy.

Parameters:
  • symbol – The symbol for the trade.

  • strategy_id – The unique identifier for the strategy.

  • 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

Returns:

A list of active orders for the given symbol and strategy.

Return type:

List[TradeOrder]

get_asset_values(symbol_list: List[str], window: int, value_type: str = 'returns', array: bool = True, **kwargs) Dict[str, ndarray | Series] | None[source]

Get the historical OHLCV value or returns or custum value based on the DataHandker of the assets in the symbol list.

Parameters:
  • bars – DataHandler for market data handling, required for backtest mode.

  • symbol_list – List of ticker symbols for the pairs trading strategy.

  • value_type – The type of value to get (e.g., returns, open, high, low, close, adjclose, volume).

  • array – If True, return the values as numpy arrays, otherwise as pandas Series.

  • mode – Mode of operation for the strategy.

  • window – The lookback period for resquesting the data.

  • tf – The time frame for the strategy.

  • error – The error handling method for the function.

Returns:

Historical values of the assets in the symbol list.

Return type:

asset_values

Note

In Live mode, the bbstrader.metatrader.rates.Rates class is used to get the historical data so the value_type must be ‘returns’, ‘open’, ‘high’, ‘low’, ‘close’, ‘adjclose’, ‘volume’.

get_positions_prices(symbol: str, strategy_id: int, position: int) ndarray[source]

Get the buy or sell prices for open positions of a given symbol and strategy.

Parameters:
  • symbol – The symbol for the trade.

  • strategy_id – The unique identifier for the strategy.

  • position – The position type (1: short, 0: long).

  • account – The bbstrader.metatrader.Account object for the strategy.

Returns:

numpy array of buy or sell prices for open positions if any or an empty array.

Return type:

prices

ispositions(symbol: str, strategy_id: int, position: int, max_trades: int, one_true: bool = False) bool[source]

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:
  • symbol – The symbol for the trade.

  • strategy_id – The unique identifier for the strategy.

  • position – The position type (1: short, 0: long).

  • max_trades – The maximum number of trades allowed per symbol.

  • one_true – If True, return True if there is at least one open position.

  • account – The bbstrader.metatrader.Account object for the strategy.

Returns:

True if there are open positions, False otherwise

Return type:

bool

property orders: List[TradeOrder]

Returns active orders from the Broker.

property positions: List[Any]

Returns open positions from the Broker.

send_trade_report(perf_analyzer: Callable, **kwargs: Any) None[source]

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:
  • 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.

  • **kwargs – Additional keyword arguments, which may include - Any other param requires by perf_analyzer

signal(signal: int, symbol: str, sl: float = None, tp: float = None) TradeSignal[source]

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:

A TradeSignal object representing the trade signal.

Return type:

TradeSignal

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.

bbstrader.trading.utils module

bbstrader.trading.utils.send_message(title='SIGNAL', message='New signal', notify_me=False, telegram=False, token=None, chat_id=None)[source]

Send a message to the user

Parameters:
  • title – str: Title of the message

  • message – str: Message of the message

  • notify_me – bool: Send a desktop notification

  • telegram – bool: Send a telegram message

  • token – str: Telegram bot token

  • chat_id – int or str or list: Chat id or list of chat ids

bbstrader.trading.utils.send_notification(title, message='')[source]

Send a desktop notification

Parameters:
  • title – str: Title of the notification

  • message – str: Message of the notification

async bbstrader.trading.utils.send_telegram_message(token, chat_id, text='')[source]

Send a message to a telegram chat

Parameters:
  • token – str: Telegram bot token

  • chat_id – int or str or list: Chat id or list of chat ids

  • text – str: Message to send