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).
示例
>>> cerebro = bt.Cerebro()
>>> # Uses BackBroker by default
- class backtrader.brokers.bbroker.BackBroker[源代码]¶
基类:
BrokerBaseBroker 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
cerebroand keeping the current position on different datas.- cash is adjusted on each iteration for instruments like
futuresfor 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 theopenprice)Close: meant for intraday in which the order is executed with the closing price of the last bar of the sessionLimit: executes if the given limit price is seen during the sessionStop: executes aMarketorder if the given stop price is seenStopLimit: sets aLimitorder 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
Cerebroand 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:Manually create an instance of this class with the desired params and use
cerebro.broker = instanceto set the instance as the broker for therunexecutionUse the
set_xxxto set the value usingcerebro.broker.set_xxxwhere`xxxstands for the name of the parameter to set
备注
cerebro.brokeris a property supported by thegetbrokerandsetbrokermethods ofCerebro# 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 checkeosbar(default:False): With intraday bars consider a bar with the sametimeas 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
Orderdocumentation and reference for things available inside anOrderinstancepricethe price at which the order is going to be executed in theagobarago: index meant to be used withorder.datafor the extraction of the ohlc and volume prices. In most cases this will be0but on a corner case forCloseorders, 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 signatureWith the default
Noneorders 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 ordersNote:
0.01is1%0.001is0.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 ordersNote: if
slip_percis 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 beMarketorder 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
Truethe broker will offer a match by capping slippage athigh/lowprices in case they would be exceeded.If
Falsethe 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)Limitorders, given the exact match price requested, will be matched even ifslip_matchisFalse.This option controls that behavior.
If
True, thenLimitorders will be matched by capping prices to thelimit/high/lowpricesIf
Falseand 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-lowrange.# 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
Truewithset_cocenables matching a
Marketorder 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
- Cheat-On-Close Setting this to
coo(default:False)- Cheat-On-Open Setting this to
Truewithset_cooenables matching a
Marketorder to the opening price, by for example using a timer withcheatset toTrue, 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
- Cheat-On-Open Setting this to
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
Falsethen 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
Trueanalyzers likeTimeReturncan 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)[源代码]¶
Initialize the BackBroker instance.
- 参数:
**kwargs -- Keyword arguments for parameter initialization
- init()[源代码]¶
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()[源代码]¶
Get the next notification from the notification queue.
- 返回:
Order notification if available, None otherwise
- set_fundmode(fundmode, fundstartval=None)[源代码]¶
Set the actual fundmode (True or False)
If the argument fundstartval is not
None, it will use
- get_fundmode()[源代码]¶
Get the current fund mode status.
- 返回:
True if fund mode is enabled, False otherwise
- 返回类型:
- set_fundstartval(fundstartval)[源代码]¶
Set the starting value for fund-like performance tracking.
- 参数:
fundstartval -- The starting value for the fund
- set_int2pnl(int2pnl)[源代码]¶
Configure assignment of interest to profit and loss.
- 参数:
int2pnl -- If True, interest is assigned to PnL when positions close
- set_coc(coc)[源代码]¶
Configure Cheat-On-Close behavior.
When enabled, market orders can execute at the closing price of the bar in which they were issued.
- 参数:
coc -- If True, enable cheat-on-close
- set_coo(coo)[源代码]¶
Configure Cheat-On-Open behavior.
When enabled, market orders can execute at the opening price.
- 参数:
coo -- If True, enable cheat-on-open
- set_shortcash(shortcash)[源代码]¶
Configure short cash behavior for stock-like assets.
- 参数:
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)[源代码]¶
Configure percentage-based slippage.
- 参数:
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)[源代码]¶
Configure fixed-point slippage.
- 参数:
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)[源代码]¶
Set a volume filler callable for order execution.
- 参数:
filler -- Callable with signature (order, price, ago) -> executed_size
- set_checksubmit(checksubmit)[源代码]¶
Set whether to check margin/cash before accepting orders.
- 参数:
checksubmit -- If True, validate margin/cash before order submission
- set_eosbar(eosbar)[源代码]¶
Set end-of-session bar behavior.
- 参数:
eosbar -- If True, consider bar with same time as end of session as EOS
- seteosbar(eosbar)¶
Set end-of-session bar behavior.
- 参数:
eosbar -- If True, consider bar with same time as end of session as EOS
- get_cash()[源代码]¶
Get the current available cash.
- 返回:
- Current cash amount. Returns parameter value if not yet
initialized, otherwise returns current cash status.
- 返回类型:
- getcash()¶
Get the current available cash.
- 返回:
- Current cash amount. Returns parameter value if not yet
initialized, otherwise returns current cash status.
- 返回类型:
- setcash(cash)¶
Set the broker cash amount.
- 参数:
cash -- Cash amount to set
- add_cash(cash)[源代码]¶
Add or remove cash from the system.
- 参数:
cash -- Cash amount to add (use negative value to remove)
Get the current number of fund shares.
- 返回:
Current number of shares in fund-like mode
- 返回类型:
Get the current number of fund shares.
- 返回:
Current number of shares in fund-like mode
- 返回类型:
- cancel(order, bracket=False)[源代码]¶
Cancel an order.
- 参数:
order -- The order to cancel
bracket -- If True, cancel as part of bracket order
- 返回:
True if order was cancelled, False if not found
- 返回类型:
- get_value(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)
- 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_orders_open(safe=False)[源代码]¶
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
safeto True
- getposition(data)[源代码]¶
Get the current position status for a data feed.
- 参数:
data -- Data feed to get position for
- 返回:
Current position instance for the data feed
- 返回类型:
- orderstatus(order)[源代码]¶
Get the status of an order.
- 参数:
order -- Order object or order reference
- 返回:
The current status of the order
- 返回类型:
Order.Status
- submit(order, check=True)[源代码]¶
Submit an order to the broker.
- 参数:
order -- Order object to submit
check -- If True, validate order before submission
- 返回:
The submitted order or parent order if part of bracket
- 返回类型:
- transmit(order, check=True)[源代码]¶
Transmit an order for execution.
- 参数:
order -- Order to transmit
check -- If True, check margin/cash before accepting
- 返回:
The transmitted order
- 返回类型:
- check_submitted()[源代码]¶
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.
- add_order_history(orders, notify=True)[源代码]¶
Add historical orders to the broker.
- 参数:
orders -- Iterable of historical orders to add
notify -- If True, send notifications for these orders
- set_fund_history(fund)[源代码]¶
Set fund history for fund-like performance tracking.
- 参数:
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)[源代码]¶
Create and submit a buy order.
- 参数:
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
- 返回:
The submitted buy 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)[源代码]¶
Create and submit a sell order.
- 参数:
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
- 返回:
The submitted sell order
- 返回类型:
- cash is adjusted on each iteration for instruments like
- backtrader.brokers.bbroker.BrokerBack¶
BackBroker的别名