backtrader.brokers.bbroker module

Back Broker Module - Backtesting broker simulation.

This module provides the BackBroker for simulating broker behavior during backtesting.

Classes:

BackBroker: Broker simulator for backtesting (alias: BrokerBack).

Example

>>> cerebro = bt.Cerebro()
>>> # Uses BackBroker by default
class backtrader.brokers.bbroker.BackBroker[source]

Bases: BrokerBase

Broker Simulator

The simulation supports different order types, checking a submitted order cash requirements against current cash, keeping track of cash and value for each iteration of cerebro and keeping the current position on different datas.

cash is adjusted on each iteration for instruments like futures for

which a price change implies in real brokers the addition/subtraction of cash.

# This backtesting simulation class supports different order types, checks if current cash meets the cash requirements for submitted orders, # checks cash and value at each bar, and positions on different data feeds

Supported order types:

  • Market: to be executed with the 1st tick of the next bar (namely the open price)

  • Close: meant for intraday in which the order is executed with the closing price of the last bar of the session

  • Limit: executes if the given limit price is seen during the session

  • Stop: executes a Market order if the given stop price is seen

  • StopLimit: sets a Limit order in motion if the given stop price is seen

# Supported order types include the five basic types above. In fact, there are other order types supported. Refer to previous tutorials # https://blog.csdn.net/qq_26948675/article/details/122868368

Because the broker is instantiated by Cerebro and there should be (mostly) no reason to replace the broker, the params are not controlled by the user for the instance. To change this there are two options:

  1. Manually create an instance of this class with the desired params and use cerebro.broker = instance to set the instance as the broker for the run execution

  2. Use the set_xxx to set the value using cerebro.broker.set_xxx where `xxx stands for the name of the parameter to set

Note

cerebro.broker is a property supported by the getbroker and setbroker methods of Cerebro

# Normally there is no need to set broker parameters. If setting is needed, there are usually two methods: first is to create a broker instance, then cerebro.broker = instance # The second method is to use cerebro.broker.set_xxx to set different parameters

Params:

# The meanings of some parameters are below

  • cash (default: 10000): starting cash

    # cash is the starting capital amount, default is 10000

  • commission (default: CommInfoBase(percabs=True)) base commission scheme which applies to all assets

    # Commission class for how to charge commissions, margin, etc. for asset trading. Default is CommInfoBase(percabs=True)

  • checksubmit (default: True) check margin/cash before accepting an order into the system # Whether to check if margin and cash are sufficient when passing an order to the system. Default is to check

  • eosbar (default: False): With intraday bars consider a bar with the same time as the end of session to be the end of the session. This is not usually the case, because some bars (final auction) are produced by many exchanges for many products for a couple of minutes after the end of the session

    # End-of-session bar, default is False. For intraday bars, consider a bar with the same time as the end of session as the end of day’s trading. # However, this is usually not the case, because many assets’ bars are formed through final auctions at many exchanges a few minutes after the end of the day’s trading time

  • filler (default: None)

    A callable with signature: callable(order, price, ago)

    • order: obviously the order in execution. This provides access to the data (and with it the ohlc and volume values), the execution type, remaining size (order.executed.remsize) and others.

      Please check the Order documentation and reference for things available inside an Order instance

    • price the price at which the order is going to be executed in the ago bar

    • ago: index meant to be used with order.data for the extraction of the ohlc and volume prices. In most cases this will be 0 but on a corner case for Close orders, this will be -1.

      In order to get the bar volume (for example) do: volume = order.data.voluume[ago]

    The callable must return the executed size (a value >= 0)

    The callable may of course be an object with __call__ matching the aforementioned signature

    With the default None orders will be completely executed in a single shot

    # filler is a callable object, default is None. In this case, all trading volume can be executed; if filler is not None, # it will calculate the executable order size based on order, price, ago # Reference articles: https://blog.csdn.net/qq_26948675/article/details/124566885?spm=1001.2014.3001.5501 # https://yunjinqi.blog.csdn.net/article/details/113445040

  • slip_perc (default: 0.0) Percentage in absolute terms (and positive) that should be used to slip prices up/down for buy/sell orders

    Note:

    • 0.01 is 1%

    • 0.001 is 0.1%

    # Percentage slippage form

  • slip_fixed (default: 0.0) Percentage in units (and positive) that should be used to slip prices up/down for buy/sell orders

    Note: if slip_perc is non zero, it takes precedence over this.

    # Fixed slippage form. If percentage slippage is not 0, only percentage slippage is considered

  • slip_open (default: False) whether to slip prices for order execution which would specifically used the opening price of the next bar. An example would be Market order which is executed with the next available tick, i.e: the opening price of the bar.

    This also applies to some of the other executions, because the logic tries to detect if the opening price would match the requested price/execution type when moving to a new bar.

    # Whether to use the next bar’s opening price when calculating slippage

  • slip_match (default: True)

    If True the broker will offer a match by capping slippage at high/low prices in case they would be exceeded.

    If False the broker will not match the order with the current prices and will try execution during the next iteration

    # If the price with slippage exceeds the high or low price, and if slip_match is set to True, the execution price will be calculated based on the high or low price # If not set to True, it will wait for the next bar to attempt execution

  • slip_limit (default: True)

    Limit orders, given the exact match price requested, will be matched even if slip_match is False.

    This option controls that behavior.

    If True, then Limit orders will be matched by capping prices to the limit / high/low prices

    If False and slippage exceeds the cap, then there will be no match

    # Limit orders will seek strict matching, even when slip_match is False # If slip_limit is set to True, limit orders will be executed if they are between the high and low prices # If set to False, limit orders with slippage that exceeds high and low prices will not be executed

  • slip_out (default: False)

    Provide slippage even if the price falls outside the high - low range.

    # When slip_out is set to True, slippage will be provided even if the price exceeds the high-low range

  • coc (default: False)

    Cheat-On-Close Setting this to True with set_coc enables

    matching a Market order to the closing price of the bar in which the order was issued. This is actually cheating, because the bar is closed and any order should first be matched against the prices in the next bar

    # When coc is set to True, when placing a market order, it allows execution at the closing price

  • coo (default: False)

    Cheat-On-Open Setting this to True with set_coo enables

    matching a Market order to the opening price, by for example using a timer with cheat set to True, because such a timer gets executed before the broker has evaluated

    # When coo is set to True, market orders are allowed to execute at the opening price, similar to tbquant mode

  • int2pnl (default: True)

    Assign generated interest (if any) to the profit and loss of operation that reduces a position (be it long or short). There may be cases in which this is undesired, because different strategies are competing and the interest would be assigned on a non-deterministic basis to any of them. # int2pnl, default is True. TODO: Understand literally as transferring generated interest costs to pnl

  • shortcash (default: True)

    If True then cash will be increased when a stocklike asset is shorted and the calculated value for the asset will be negative.

    If False then the cash will be deducted as operation cost and the calculated value will be positive to end up with the same amount

    # For stock-like assets, if this parameter is set to True, when short selling, the available cash will increase, but the asset value will be negative # If this parameter is set to False, when short selling, the available cash decreases, and the asset value is positive

  • fundstartval (default: 100.0)

    This parameter controls the start value for measuring the performance in a fund-like way, i.e.: cash can be added and deducted increasing the amount of shares. Performance is not measured using the net asset value of the portfolio but using the value of the fund # fundstartval will calculate performance in fund mode

  • fundmode (default: False)

    If this is set to True analyzers like TimeReturn can automatically calculate returns based on the fund value and not on the total net asset value # If fundmode is set to True, some analyzers like TimeReturn will use fund value to calculate returns

cash
checksubmit

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

eosbar

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

filler

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_perc

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_fixed

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_open

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_match

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_limit

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_out

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

coc

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

coo

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

int2pnl

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

shortcash

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

fundstartval

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

fundmode

Advanced parameter descriptor with type checking and validation.

This descriptor replaces the metaclass-based parameter system with a more modern and maintainable approach. It provides:

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

__init__(**kwargs)[source]

Initialize the BackBroker instance.

Parameters:

**kwargs – Keyword arguments for parameter initialization

init()[source]

Initialize broker state and internal data structures.

This method sets up the initial cash, positions, orders, and other broker-related data structures. Called during cerebro initialization.

get_notification()[source]

Get the next notification from the notification queue.

Returns:

Order notification if available, None otherwise

set_fundmode(fundmode, fundstartval=None)[source]

Set the actual fundmode (True or False)

If the argument fundstartval is not None, it will use

get_fundmode()[source]

Get the current fund mode status.

Returns:

True if fund mode is enabled, False otherwise

Return type:

bool

set_fundstartval(fundstartval)[source]

Set the starting value for fund-like performance tracking.

Parameters:

fundstartval – The starting value for the fund

set_int2pnl(int2pnl)[source]

Configure assignment of interest to profit and loss.

Parameters:

int2pnl – If True, interest is assigned to PnL when positions close

set_coc(coc)[source]

Configure Cheat-On-Close behavior.

When enabled, market orders can execute at the closing price of the bar in which they were issued.

Parameters:

coc – If True, enable cheat-on-close

set_coo(coo)[source]

Configure Cheat-On-Open behavior.

When enabled, market orders can execute at the opening price.

Parameters:

coo – If True, enable cheat-on-open

set_shortcash(shortcash)[source]

Configure short cash behavior for stock-like assets.

Parameters:

shortcash – If True, increase cash when shorting stock-like assets

set_slippage_perc(perc, slip_open=True, slip_limit=True, slip_match=True, slip_out=False)[source]

Configure percentage-based slippage.

Parameters:
  • perc – Slippage percentage (e.g., 0.01 for 1%)

  • slip_open – Apply slippage to opening prices

  • slip_limit – Allow limit order matching with slippage capping

  • slip_match – Cap slippage at high/low prices

  • slip_out – Provide slippage even outside high-low range

set_slippage_fixed(fixed, slip_open=True, slip_limit=True, slip_match=True, slip_out=False)[source]

Configure fixed-point slippage.

Parameters:
  • fixed – Fixed slippage amount in price units

  • slip_open – Apply slippage to opening prices

  • slip_limit – Allow limit order matching with slippage capping

  • slip_match – Cap slippage at high/low prices

  • slip_out – Provide slippage even outside high-low range

set_filler(filler)[source]

Set a volume filler callable for order execution.

Parameters:

filler – Callable with signature (order, price, ago) -> executed_size

set_checksubmit(checksubmit)[source]

Set whether to check margin/cash before accepting orders.

Parameters:

checksubmit – If True, validate margin/cash before order submission

set_eosbar(eosbar)[source]

Set end-of-session bar behavior.

Parameters:

eosbar – If True, consider bar with same time as end of session as EOS

seteosbar(eosbar)

Set end-of-session bar behavior.

Parameters:

eosbar – If True, consider bar with same time as end of session as EOS

get_cash()[source]

Get the current available cash.

Returns:

Current cash amount. Returns parameter value if not yet

initialized, otherwise returns current cash status.

Return type:

float

getcash()

Get the current available cash.

Returns:

Current cash amount. Returns parameter value if not yet

initialized, otherwise returns current cash status.

Return type:

float

set_cash(cash)[source]

Set the broker cash amount.

Parameters:

cash – Cash amount to set

setcash(cash)

Set the broker cash amount.

Parameters:

cash – Cash amount to set

add_cash(cash)[source]

Add or remove cash from the system.

Parameters:

cash – Cash amount to add (use negative value to remove)

get_fundshares()[source]

Get the current number of fund shares.

Returns:

Current number of shares in fund-like mode

Return type:

float

property fundshares

Get the current number of fund shares.

Returns:

Current number of shares in fund-like mode

Return type:

float

get_fundvalue()[source]

Get the fund share value.

Returns:

Current fund-like share value

Return type:

float

property fundvalue

Get the fund share value.

Returns:

Current fund-like share value

Return type:

float

cancel(order, bracket=False)[source]

Cancel an order.

Parameters:
  • order – The order to cancel

  • bracket – If True, cancel as part of bracket order

Returns:

True if order was cancelled, False if not found

Return type:

bool

get_value(datas=None, mkt=False, lever=False)[source]

Returns the portfolio value of the given datas (if datas is None, then the total portfolio value will be returned (alias: getvalue)

getvalue(datas=None, mkt=False, lever=False)

Returns the portfolio value of the given datas (if datas is None, then the total portfolio value will be returned (alias: getvalue)

get_leverage()[source]

Get the current account leverage ratio.

Returns:

Current leverage ratio

Return type:

float

get_orders_open(safe=False)[source]

Returns an iterable with the orders which are still open (either not executed or partially executed)

The orders returned must not be touched.

If order manipulation is needed, set the parameter safe to True

getposition(data)[source]

Get the current position status for a data feed.

Parameters:

data – Data feed to get position for

Returns:

Current position instance for the data feed

Return type:

Position

orderstatus(order)[source]

Get the status of an order.

Parameters:

order – Order object or order reference

Returns:

The current status of the order

Return type:

Order.Status

submit(order, check=True)[source]

Submit an order to the broker.

Parameters:
  • order – Order object to submit

  • check – If True, validate order before submission

Returns:

The submitted order or parent order if part of bracket

Return type:

Order

transmit(order, check=True)[source]

Transmit an order for execution.

Parameters:
  • order – Order to transmit

  • check – If True, check margin/cash before accepting

Returns:

The transmitted order

Return type:

Order

check_submitted()[source]

Check and validate submitted orders against available cash and margin.

Processes all orders in the submitted queue and validates them against current cash and margin requirements.

submit_accept(order)[source]

Accept and activate a submitted order.

Parameters:

order – Order to accept

add_order_history(orders, notify=True)[source]

Add historical orders to the broker.

Parameters:
  • orders – Iterable of historical orders to add

  • notify – If True, send notifications for these orders

set_fund_history(fund)[source]

Set fund history for fund-like performance tracking.

Parameters:

fund – Iterable of [datetime, share_value, net_asset_value] items

buy(owner, data, size, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, histnotify=False, _checksubmit=True, **kwargs)[source]

Create and submit a buy order.

Parameters:
  • owner – Strategy or object creating the order

  • data – Data feed for the order

  • size – Order size (positive for buy)

  • price – Order price (for limit/stop orders)

  • plimit – Limit price for stop-limit orders

  • exectype – Order execution type

  • valid – Order validity

  • tradeid – Trade identifier

  • oco – OCO (One-Cancels-Other) order reference

  • trailamount – Trailing stop amount

  • trailpercent – Trailing stop percentage

  • parent – Parent order (for bracket orders)

  • transmit – If True, transmit order immediately

  • histnotify – If True, notify for historical orders

  • _checksubmit – If True, validate order before submission

  • **kwargs – Additional order parameters

Returns:

The submitted buy order

Return type:

Order

sell(owner, data, size, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, histnotify=False, _checksubmit=True, **kwargs)[source]

Create and submit a sell order.

Parameters:
  • owner – Strategy or object creating the order

  • data – Data feed for the order

  • size – Order size (positive for sell)

  • price – Order price (for limit/stop orders)

  • plimit – Limit price for stop-limit orders

  • exectype – Order execution type

  • valid – Order validity

  • tradeid – Trade identifier

  • oco – OCO (One-Cancels-Other) order reference

  • trailamount – Trailing stop amount

  • trailpercent – Trailing stop percentage

  • parent – Parent order (for bracket orders)

  • transmit – If True, transmit order immediately

  • histnotify – If True, notify for historical orders

  • _checksubmit – If True, validate order before submission

  • **kwargs – Additional order parameters

Returns:

The submitted sell order

Return type:

Order

notify(order)[source]

Add an order notification to the notification queue.

Parameters:

order – Order to create notification for

next()[source]

Process broker operations for the current time step.

This method: - Activates pending orders - Validates submitted orders - Calculates interest charges - Processes order history - Executes pending orders - Adjusts cash for mark-to-market

backtrader.brokers.bbroker.BrokerBack

alias of BackBroker