Broker¶
The Broker class handles order execution and portfolio management.
Backtrader Broker Module.
This module provides the broker system for order execution and portfolio management. It handles order creation, position tracking, cash management, and commission calculation.
- Key Classes:
BrokerBase: Base class for broker implementations. BrokerAliasMixin: Mixin providing method aliases.
- The broker system supports:
Order execution (buy, sell, cancel)
Position management
Cash and value tracking
Commission schemes
Order history
- class backtrader.broker.BrokerAliasMixin[源代码]
基类:
objectMixin to provide method aliases without using metaclasses.
This mixin creates method aliases for compatibility with different naming conventions (e.g., get_cash/getcash, get_value/getvalue).
- __init__(*args, **kwargs)[源代码]
Initialize the broker alias mixin.
- Creates method aliases for compatibility:
get_cash -> getcash
get_value -> getvalue
- 参数:
*args -- Positional arguments passed to parent.
**kwargs -- Keyword arguments passed to parent.
- class backtrader.broker.BrokerBase[源代码]
基类:
BrokerAliasMixin,ParameterizedBaseBase class for broker implementations.
The broker handles order execution, position tracking, and cash management. It supports commission schemes, margin requirements, and order history.
- commission
Default commission scheme for all assets.
- comminfo
Dictionary mapping asset names to commission info objects.
- Params:
commission: Default commission scheme (CommInfoBase instance).
- commission
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 broker instance.
- 参数:
**kwargs -- Keyword arguments passed to parent class.
- init()[源代码]
Initialize the commission info dictionary.
Sets up the default commission scheme if not already present. Called from both __init__ and start methods.
- start()[源代码]
Start the broker. Re-initializes commission info.
- stop()[源代码]
Stop the broker.
Override this method in subclasses for cleanup operations.
- add_order_history(orders, notify=False)[源代码]
Add order history to the broker.
- 参数:
orders -- Orders to add to history.
notify -- Whether to notify about these orders.
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- set_fund_history(fund)[源代码]
Set fund history for the broker.
- 参数:
fund -- Fund history data.
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- getcommissioninfo(data)[源代码]
Get the commission info for a given data.
- 参数:
data -- Data feed to get commission info for.
- 返回:
The commission info for the data, or the default.
- 返回类型:
- setcommission(commission=0.0, margin=None, mult=1.0, commtype=None, percabs=True, stocklike=False, interest=0.0, interest_long=False, leverage=1.0, automargin=False, name=None)[源代码]
This method sets a `` CommissionInfo`` object for assets managed in the broker with the parameters. Consult the reference for
CommInfoBaseIf name is None, this will be the default for assets for which no other
CommissionInfoscheme can be found
- addcommissioninfo(comminfo, name=None)[源代码]
Add a CommissionInfo object for an asset.
- 参数:
comminfo -- The CommissionInfo object to add.
name -- Asset name. If None, sets as default for all assets.
- getcash()[源代码]
Get the current available cash.
- 返回:
Current cash amount.
- 返回类型:
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- getvalue(datas=None)[源代码]
Get the current portfolio value.
- 参数:
datas -- Data feeds to calculate value for (optional).
- 返回:
Current portfolio value.
- 返回类型:
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- get_fundshares()[源代码]
Get the current number of shares in fund-like mode.
- 返回:
Number of shares (1.0 for abstract mode).
- 返回类型:
- property fundshares
Get the current number of shares in fund-like mode.
- 返回:
Number of shares (1.0 for abstract mode).
- 返回类型:
- property fundvalue
Get the current fund value.
- 返回:
Current fund value.
- 返回类型:
- set_fundmode(fundmode, fundstartval=None)[源代码]
Set the fund mode for the broker.
- 参数:
fundmode -- True to enable fund mode, False otherwise.
fundstartval -- Initial fund value (optional).
备注
Not all brokers support fund mode.
- get_fundmode()[源代码]
Get the current fund mode status.
- 返回:
True if fund mode is enabled, False otherwise.
- 返回类型:
- property fundmode
Get the current fund mode status.
- 返回:
True if fund mode is enabled, False otherwise.
- 返回类型:
- getposition(data)[源代码]
Get the current position for a data feed.
- 参数:
data -- Data feed to get position for.
- 返回:
Current position for the data feed.
- 返回类型:
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- submit(order)[源代码]
Submit an order to the broker.
- 参数:
order -- Order object to submit.
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- cancel(order)[源代码]
Cancel a pending order.
- 参数:
order -- Order object to cancel.
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- buy(owner, data, size, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, **kwargs)[源代码]
Create a buy order.
- 参数:
owner -- Strategy/owner creating the order.
data -- Data feed for the order.
size -- Size of the order (positive for buy).
price -- Limit price (optional).
plimit -- Profit limit price (optional).
exectype -- Execution type (Market, Limit, Stop, etc.).
valid -- Validity period for the order.
tradeid -- Trade identifier.
oco -- One-cancels-other order reference.
trailamount -- Trailing amount for stop orders.
trailpercent -- Trailing percent for stop orders.
**kwargs -- Additional keyword arguments.
- 返回:
The created order object.
- 返回类型:
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- sell(owner, data, size, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, **kwargs)[源代码]
Create a sell order.
- 参数:
owner -- Strategy/owner creating the order.
data -- Data feed for the order.
size -- Size of the order (positive for sell).
price -- Limit price (optional).
plimit -- Profit limit price (optional).
exectype -- Execution type (Market, Limit, Stop, etc.).
valid -- Validity period for the order.
tradeid -- Trade identifier.
oco -- One-cancels-other order reference.
trailamount -- Trailing amount for stop orders.
trailpercent -- Trailing percent for stop orders.
**kwargs -- Additional keyword arguments.
- 返回:
The created order object.
- 返回类型:
- 抛出:
NotImplementedError -- Must be implemented by subclasses.
- next()[源代码]
Process the next bar in the backtest.
Called by the cerebro engine for each iteration. Override in subclasses to perform per-bar operations.
Overview¶
The broker simulates or executes orders in live trading. It manages:
Cash and portfolio value
Order execution
Commissions and slippage
Position tracking
Margin requirements
Default Broker¶
The default BackBroker provides:
Simulated order execution
Commission modeling
Slippage simulation
Margin/leverage support
Configuration¶
cerebro = bt.Cerebro()
# Set initial cash
cerebro.broker.setcash(100000)
# Set commission
cerebro.broker.setcommission(
commission=0.001, # 0.1% commission
margin=None, # No margin
mult=1.0, # Multiplier
)
# Set slippage
cerebro.broker.set_slippage_perc(0.001) # 0.1% slippage
Commission Schemes¶
# Percentage commission
cerebro.broker.setcommission(commission=0.001)
# Fixed commission per trade
cerebro.broker.setcommission(
commission=10,
commtype=bt.CommInfoBase.COMM_FIXED
)
# Futures commission
cerebro.broker.addcommissioninfo(
bt.CommissionInfo(
commission=2.0,
margin=2000,
mult=50
),
name='ES'
)
Accessing Broker in Strategy¶
class MyStrategy(bt.Strategy):
def next(self):
# Get current cash
cash = self.broker.getcash()
# Get portfolio value
value = self.broker.getvalue()
# Get position
position = self.broker.getposition(self.data)
# Check if we can buy
if cash > self.data.close[0] * 100:
self.buy(size=100)