backtrader package¶
Backtrader - Python Trading Framework.
A feature-rich Python framework for backtesting and trading with support for multiple data feeds, brokers, and analysis tools.
This module serves as the main entry point for the backtrader package, exposing all public APIs through a unified namespace.
Example
Basic usage:
import backtrader as bt
cerebro = bt.Cerebro()
data = bt.feeds.GenericCSVData(dataname='data.csv')
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)
results = cerebro.run()
cerebro.plot()
- Core Components:
Cerebro: Main engine that orchestrates backtesting
Strategy: Base class for trading strategies
Indicator: Base class for technical indicators
Analyzer: Base class for performance analyzers
Broker: Simulated broker for order execution
Feed: Data feed classes for market data input
- Subpackages:
analyzers: Performance analysis tools (Sharpe, Drawdown, etc.)
brokers: Broker implementations (backtesting + unified bt_api_py live broker)
feeds: Data feed implementations (CSV, Pandas, Yahoo, bt_api_py live feed)
indicators: Technical indicators (SMA, RSI, MACD, etc.)
observers: Chart observers for visualization
sizers: Position sizing algorithms
stores: Data store implementations
filters: Data filtering utilities
See also
Documentation: https://www.backtrader.com/docu/
- class backtrader.OrderedDict[source]¶
Bases:
dictDictionary that remembers insertion order
- __init__(*args, **kwargs)¶
- clear() None. Remove all items from od.¶
- popitem(last=True)¶
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- move_to_end(key, last=True)¶
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- update([E, ]**F) None. Update D from dict/iterable E and F.¶
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- keys() a set-like object providing a view on D's keys¶
- items() a set-like object providing a view on D's items¶
- values() an object providing a view on D's values¶
- pop(key[, default]) v, remove specified key and return the corresponding value.¶
If the key is not found, return the default if given; otherwise, raise a KeyError.
- setdefault(key, default=None)¶
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- copy() a shallow copy of od¶
- classmethod fromkeys(iterable, value=None)¶
Create a new ordered dictionary with keys from iterable and values set to value.
- class backtrader.TimeFrame[source]¶
Bases:
objectEnumeration of time periods for financial data.
Defines constants for different time periods used in financial data: Ticks, MicroSeconds, Seconds, Minutes, Days, Weeks, Months, Years, and NoTimeFrame.
- Class Methods:
getname(tframe, compression): Get name for timeframe. TFrame(name): Get timeframe constant from name. TName(tframe): Get name string from timeframe constant.
- Ticks, MicroSeconds, Seconds, Minutes, Days, Weeks, Months, Years, NoTimeFrame
Timeframe constants.
- Ticks = 1¶
- MicroSeconds = 2¶
- Seconds = 3¶
- Minutes = 4¶
- Days = 5¶
- Weeks = 6¶
- Months = 7¶
- Years = 8¶
- NoTimeFrame = 9¶
- Names = ['', 'Ticks', 'MicroSeconds', 'Seconds', 'Minutes', 'Days', 'Weeks', 'Months', 'Years', 'NoTimeFrame']¶
- names = ['', 'Ticks', 'MicroSeconds', 'Seconds', 'Minutes', 'Days', 'Weeks', 'Months', 'Years', 'NoTimeFrame']¶
- classmethod getname(tframe, compression=None)[source]¶
Get the name for a timeframe.
- Parameters:
tframe – TimeFrame constant (e.g., TimeFrame.Days).
compression – Compression factor. If None, uses 1.
- Returns:
Name of the timeframe (singular or plural).
- Return type:
- backtrader.findowner(owned, cls, startlevel=2, skip=None)[source]¶
Find the owner object in the call stack or context.
This function first checks the OwnerContext for an explicitly set owner, then falls back to traversing the call stack to find an object that: 1. Is an instance of the specified class (cls) 2. Is not the owned object itself 3. Is not the skip object (if provided)
This is commonly used to find parent containers (e.g., Strategy finding its Cerebro, or Indicator finding its Strategy).
- Parameters:
owned – The object looking for its owner.
cls – The class type the owner must be an instance of.
startlevel – Stack frame level to start searching from (default: 2, skips this function and the caller).
skip – Optional object to skip during the search.
- Returns:
The owner object if found, None otherwise.
Note
Uses OwnerContext for explicit owner management. The legacy sys._getframe() based lookup has been removed for better portability and performance.
- class backtrader.Observer[source]¶
Bases:
ObserverBaseBase class for monitoring strategy execution.
Observers track and record strategy state during backtesting. They can track metrics like cash, value, drawdown, positions, etc.
- csv¶
Whether to save observer data to CSV (default: True).
- plotinfo¶
Plotting configuration dictionary.
Example
>>> observer = MyObserver() >>> cerebro.addobserver(observer)
- csv = True¶
- plotinfo = <backtrader.metabase.plotinfo_obj object>¶
- __init__(*args, **kwargs)¶
Wrapped __init__ that properly handles observer initialization
- prenext()[source]¶
Process bars before minimum period is reached.
By default, observers always process every bar by calling next() even during the prenext phase. Subclasses can override this behavior.
Note
This default implementation calls next() to ensure observers track all bars from the beginning.
- start()[source]¶
Called at the start of the backtesting run.
This method can be overridden by subclasses to perform initialization at the start of strategy execution.
- frompackages = ()¶
- packages = ()¶
- class backtrader.ParameterizedBase[source]¶
Bases:
objectEnhanced base class for objects with parameters - without metaclass.
This class provides the modern parameter system interface while maintaining backward compatibility with the old MetaParams-based system. It uses regular class mechanisms instead of metaclass.
- classmethod __init_subclass__(**kwargs)[source]¶
Called when a class is subclassed. Replaces metaclass functionality.
This method sets up the class for lazy parameter descriptor resolution to avoid inheritance contamination issues.
- set_param(name, value, validate=True)[source]¶
Set parameter value with optional validation.
- Parameters:
- Raises:
AttributeError – If parameter manager not initialized
ValueError – If validation fails
- Return type:
None
- reset_param(name)[source]¶
Reset parameter to its default value.
- Parameters:
name (str) – Parameter name
- Raises:
AttributeError – If parameter manager not initialized
ValueError – If parameter doesn’t exist or is locked
- Return type:
None
- copy_params_from(other, param_names=None, exclude=None)[source]¶
Copy parameters from another ParameterizedBase instance.
- Parameters:
other (ParameterizedBase) – Source object to copy parameters from
param_names (List[str] | None) – Specific parameter names to copy (None for all)
exclude (List[str] | None) – Parameter names to exclude from copying
- Return type:
None
- class backtrader.Strategy[source]¶
Bases:
StrategyBaseBase class for user-defined trading strategies.
This class provides the core functionality for implementing trading strategies including order management, position tracking, and event handling. Users should subclass this to create custom strategies.
- env¶
Reference to the Cerebro environment.
- cerebro¶
Alias for env.
- broker¶
Reference to the broker for order execution.
- datas¶
List of data feeds available to the strategy.
- data¶
Shortcut to the first data feed (datas[0]).
- position¶
Current position for the main data feed.
- stats¶
Collection of observer instances.
- analyzers¶
Collection of analyzer instances.
- Methods to Override:
__init__: Initialize indicators and strategy state. start: Called when the strategy starts running. prenext: Called before minimum period is reached. nextstart: Called once when minimum period is first reached. next: Main strategy logic, called on each bar. stop: Called when the strategy stops running. notify_order: Receive order status notifications. notify_trade: Receive trade notifications. notify_data: Receive data feed notifications. notify_timer: Receive timer notifications.
Example
- class MyStrategy(bt.Strategy):
params = ((‘period’, 20),)
- def __init__(self):
self.sma = bt.indicators.SMA(period=self.p.period)
- def next(self):
- if not self.position:
- if self.data.close[0] > self.sma[0]:
self.buy()
- else:
- if self.data.close[0] < self.sma[0]:
self.close()
- static __new__(cls, *args, **kwargs)[source]¶
Override __new__ to handle method renaming that was done in MetaStrategy
- __reduce_ex__(protocol)[source]¶
Restore saved state without re-entering the run-time owner setup.
Optimization results are unpickled outside an active OwnerContext. Calling Strategy.__new__ there would request a new strategy ID from a nonexistent Cerebro and kill the multiprocessing result thread. Keep the default state/slot handling and any user-defined reducer, changing only the allocation of an otherwise ordinary instance.
object.__new__also resolves in older framework installations.
- __init__(*args, **kwargs)¶
- csv = True¶
- log(txt, dt=None, level='info')[source]¶
Log a message with optional datetime.
This method provides basic logging functionality. For comprehensive logging including orders, trades, positions, indicators, and signals, use the TradeLogger observer.
- Parameters:
txt – The message text to log.
dt – Optional datetime. If None, uses current bar datetime.
level – Log level (‘info’, ‘warning’, ‘error’, ‘debug’).
Example
>>> self.log(f'Close price: {self.data.close[0]:.2f}') >>> self.log('Warning message', level='warning')
- send_message(text, *, title=None, level='info', channels=None, wait=None, timeout=None, dedup_key=None)[source]¶
Send a notification (iteration 32); asynchronous unless
wait=True.Channels are configured once with
bt.configure_notifications(...). The call injects strategy context (class name, data name and the backtest timestamp) and never raises for delivery problems: results come back as aSendResultwhoseoutcomesclassify each channel.- Parameters:
text – Message body; must be a non-empty string.
title – Optional title; defaults to the strategy class name.
level – ‘info’, ‘warning’, ‘error’ or ‘critical’ (case-insensitive).
channels – Optional subset of configured channel ids.
wait – True sends synchronously and returns delivery results; None uses the configured default. Prefer the default (False) inside
next()- a synchronous send blocks on network I/O.timeout – Per-request timeout in seconds; only used when
wait.dedup_key – Optional deduplication key.
- Returns:
Per-channel outcomes.
acceptedis False andreasonexplains why when nothing was sent (not configured, no channels, queue full, or a child process suppressing sends).- Return type:
SendResult
- Raises:
ValueError – On empty
text, an invalidlevelor an unknown channel id - programming errors surface immediately.
Example
>>> self.send_message("entry filled", level="warning")
- qbuffer(savemem=0, replaying=False)[source]¶
Enable the memory saving schemes. Possible values for
savemem:0: No savings. Each line object keeps in memory all values
1: All lines objects save memory, using the strict minimum needed
Negative values are meant to be used when plotting is required:
- -1: Indicators at Strategy Level and Observers do not enable memory
savings (but anything declared below it does)
- -2: Same as -1 plus activation of memory saving for any indicators
which has declared plotinfo.plot as False (will not be plotted)
- prenext_open()[source]¶
Called before next() during prenext phase.
This is a hook for strategies to take action at the open of each bar before minimum period is reached.
- nextstart_open()[source]¶
Called at the open of the first bar where minimum period is satisfied.
This is called only once, transitioning from prenext to next phase.
- next_open()[source]¶
Called at the open of each bar during normal execution.
This is a hook for strategies to take action at the open of each bar.
- start()[source]¶
Called right before the backtesting is about to be started.
This is a hook for strategies to perform initialization before the backtesting loop begins.
- getwriterheaders()[source]¶
Get the CSV headers for writer output.
- Returns:
Headers including indicator/observer names and line aliases
- Return type:
- getwritervalues()[source]¶
Get current values for writer output.
- Returns:
Current values from indicators and observers
- Return type:
- getwriterinfo()[source]¶
Get comprehensive writer information including params and analysis.
- Returns:
- Nested structure containing params, indicators,
observers, and analyzer results
- Return type:
- nextstart()[source]¶
Handle the first bar at which the strategy minperiod is satisfied.
Logs one lifecycle INFO line, then delegates to the engine implementation so user
next/nextstartoverrides keep their usual behaviour. Called exactly once per run.
- stop()[source]¶
Called right before the backtesting is about to be stopped.
This is a hook for strategies to perform cleanup or final logging.
- set_tradehistory(onoff=True)[source]¶
Enable or disable trade history tracking.
- Parameters:
onoff – If True, keep full trade history; if False, only track current trade
- clear()[source]¶
Clear pending orders and trades.
Moves pending orders to _orders list and clears pending trades.
- notify_fee_correction(order, trade, delta, currency)[source]¶
A late provider fee changed
order’s commission bydelta.trade(orNone) already includes the change. Default: no-op.
Copy of per-field reason codes for the most recent notification.
An empty mapping means no unavailable strategy fields were recorded; it does not establish account permissions or a valuation guarantee.
- add_timer(when, offset=datetime.timedelta(0), repeat=datetime.timedelta(0), weekdays=None, weekcarry=False, monthdays=None, monthcarry=True, allow=None, tzdata=None, cheat=False, *args, **kwargs)[source]¶
Schedule a timer to invoke notify_timer or a callback.
Note: Can be called during __init__ or start
Schedules a timer to invoke either a specified callback or the notify_timer of one or more strategies.
- Parameters:
when – Can be: - datetime.time instance (see tzdata below) - bt.timer.SESSION_START to reference session start - bt.timer.SESSION_END to reference session end
offset (datetime.timedelta) – Offset the when value. Used with SESSION_START/SESSION_END to trigger after session start/end.
repeat (datetime.timedelta) – If set, timer repeats at this interval within the same session. Resets to original when after session end.
weekdays (list) – Sorted iterable with integers (Monday=1, Sunday=7) indicating which days the timer can be invoked. Empty = all days.
weekcarry (bool) – If True and weekday not seen (e.g., holiday), execute on next day (even if in new week).
monthdays (list) – Sorted iterable with integers (1-31) indicating which days of month to execute. Empty = all days.
monthcarry (bool) – If True and day not seen (weekend, holiday), execute on next available day.
allow (callable) – Callback receiving datetime.date, returns True if date is allowed for timer execution.
tzdata – Timezone data - None, pytz instance, or data feed instance. If None and when is SESSION_START/END, uses first data feed.
cheat (bool) – If True, timer called before broker evaluates orders, allowing orders based on opening price.
*args – Additional args passed to notify_timer
**kwargs – Additional kwargs passed to notify_timer
- Returns:
The created timer instance
- notify_timer(timer, when, *args, **kwargs)[source]¶
Receive timer notifications.
Receives a timer notification where
timeris the timer instance returned byadd_timer, andwhenis the calling time.argsandkwargsare any additional arguments passed toadd_timer.The actual
whentime can be later than expected, as the system may not have been able to call the timer before. This value is the timer’s scheduled time, not the actual system time.- Parameters:
timer – The timer instance created by add_timer
when – The scheduled time when the timer was triggered
*args – Additional positional arguments passed to add_timer
**kwargs – Additional keyword arguments passed to add_timer
- notify_idle()[source]¶
Receive a live-engine poll when no data bar or tick was produced.
Live brokers may still need strategies to advance execution deadlines, reconciliation and risk controls while market data is silent. The default hook is intentionally empty and is only dispatched for strategy classes that override it.
- notify_cashvalue(cash, value)[source]¶
Notify the current cash and value of the strategy’s broker.
- Parameters:
cash – Current cash amount
value – Current portfolio value
- notify_fund(cash, value, fundvalue, shares)[source]¶
Notify the current cash, value, fund value, and fund shares.
- Parameters:
cash – Current cash amount
value – Current portfolio value
fundvalue – Current fund value
shares – Current fund shares
- notify_order(order)[source]¶
Receive notification when an order status changes.
- Parameters:
order – The order with changed status
- notify_trade(trade)[source]¶
Receive notification when a trade status changes.
- Parameters:
trade – The trade with changed status
- notify_store(msg, *args, **kwargs)[source]¶
Receive notification from a store provider.
- Parameters:
msg – Message from the store
*args – Additional positional arguments
**kwargs – Additional keyword arguments
- notify_data(data, status, *args, **kwargs)[source]¶
Receive notification from a data feed.
- Parameters:
data – The data feed sending the notification
status – Status code
*args – Additional positional arguments
**kwargs – Additional keyword arguments
- notify_tick(tick)[source]¶
Called when a new tick event arrives.
Override this method to implement tick-level trading logic.
- Parameters:
tick – TickEvent instance with price, volume, direction, etc.
- notify_orderbook(orderbook)[source]¶
Called when a new order book snapshot arrives.
Override this method to implement orderbook-based trading logic.
- Parameters:
orderbook – OrderBookSnapshot instance with bids, asks, spread, etc.
- notify_funding(funding)[source]¶
Called when a new funding rate event arrives.
Override this method to implement funding rate arbitrage or position management.
- Parameters:
funding – FundingEvent instance with rate, mark_price, etc.
- notify_bar(bar)[source]¶
Called when a bar event arrives from the channel system.
This is different from the standard next() method which processes bars from LineSeries data feeds. This callback handles BarEvents from the channel/queue system.
- Parameters:
bar – BarEvent instance with open, high, low, close, volume.
- get_last_tick(symbol=None)[source]¶
Get the last tick for a symbol.
- Parameters:
symbol – Symbol name. If None, returns first available.
- Returns:
TickEvent or None.
- get_last_orderbook(symbol=None)[source]¶
Get the last order book for a symbol.
- Parameters:
symbol – Symbol name. If None, returns first available.
- Returns:
OrderBookSnapshot or None.
- get_last_funding(symbol=None)[source]¶
Get the last funding rate for a symbol.
- Parameters:
symbol – Symbol name. If None, returns first available.
- Returns:
FundingEvent or None.
- get_hft_data(symbol=None)[source]¶
Return a data reference suitable for channel-mode HFT orders.
In channel-only runs there may be no LineSeries data feed attached to the strategy, but standard order APIs still need a data identity. Cerebro registers lightweight per-symbol references before invoking
notify_tick/notify_orderbook/notify_barcallbacks.- Parameters:
symbol – Optional symbol to look up. If omitted and exactly one HFT data reference exists, that reference is returned.
- Returns:
A LineSeries data feed or a channel-mode data reference.
- Raises:
KeyError – If the requested symbol is unknown or no reference has been registered yet.
ValueError – If
symbolis omitted but more than one HFT data reference is available.
- getdatanames()[source]¶
Get a list of all data names in the system.
- Returns:
Names of all data feeds
- Return type:
- getdatabyname(name)[source]¶
Get a data feed by its name.
- Parameters:
name – Name of the data feed
- Returns:
The data feed with the given name
- bind_service_execution_group()[source]¶
Bind this Strategy to its explicit managed group-order route.
- submit_group_roll_exit(group_id, source_leg_id, limit_price)[source]¶
Close an accepted source leg through the coordinator’s roll-exit path.
Risk reconstructs the accepted OPEN source and derives its instrument, side, and closable quantity. This Strategy API accepts no quantity or ordinary order fields.
- query_group_roll_exit(action_id)[source]¶
Read the coordinator’s durable roll-exit projection without dispatch.
- recover_group_order(group_id, cursor=None, *, limit=32)[source]¶
Query the original group ID and resume its durable residual cursor.
- read_group_residuals(cursor=None, *, limit=32)[source]¶
Read one durable residual page and return its caller-owned cursor.
- buy(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)[source]¶
Create a buy (long) order and send it to the broker.
- Parameters:
data – The data feed for the order. If None, uses the first data feed (self.data).
size – Size to use (positive) for the order. If None, the sizer instance retrieved via getsizer will determine the size.
price – Price to use. None is valid for Market and Close orders. For Limit, Stop and StopLimit orders this determines the trigger point.
plimit – Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered.
trailamount – For StopTrail/StopTrailLimit orders, an absolute amount which determines the distance to the price to keep the trailing stop.
trailpercent – For StopTrail/StopTrailLimit orders, a percentage amount which determines the distance to the price to keep the trailing stop.
exectype – Execution type. Possible values: - Order.Market or None: Market order - Order.Limit: Limit order - Order.Stop: Stop order - Order.StopLimit: Stop-limit order - Order.Close: Close order - Order.StopTrail: Stop-trail order - Order.StopTrailLimit: Stop-trail-limit order
valid – Order validity. Possible values: - None: Good till cancel - datetime.datetime/date: Good till date - Order.DAY: Day order
tradeid – Internal value to track overlapping trades.
oco – Another order instance for OCO (Order Cancel Others) group.
parent – Controls the relationship of a group of orders (e.g., bracket orders).
transmit – If True, transmit the order to the broker. Used for controlling bracket orders.
**kwargs – Additional broker-specific parameters.
- Returns:
The submitted order, or None if size is 0.
- Return type:
Order | None
Example
Create a market buy order: >>> order = self.buy()
Create a limit buy order: >>> order = self.buy(price=100.0, exectype=Order.Limit)
- sell(data=None, size=None, price=None, plimit=None, exectype=None, valid=None, tradeid=0, oco=None, trailamount=None, trailpercent=None, parent=None, transmit=True, **kwargs)[source]¶
Create a sell (short) order and send it to the broker.
See the documentation for
buyfor an explanation of the parameters.- Returns:
The submitted order, or None if no order was created
- Return type:
Order | None
- close(data=None, size=None, **kwargs)[source]¶
Close a long or short position.
Creates an order that counters the existing position to close it.
- Parameters:
data – The data feed for which to close the position. If None, uses the default data feed.
size – The size to close. If None, closes the entire position.
**kwargs – Additional keyword arguments passed to the order.
- Return type:
Order | None
Note
If size is not provided, it is automatically calculated from the existing position to fully close it.
- Returns:
The submitted order, or None if no position exists
- Return type:
Order | None
- buy_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs=None, stopprice=None, stopexec=3, stopargs=None, limitprice=None, limitexec=2, limitargs=None, **kwargs)[source]¶
Create a bracket order group (buy order with stop-loss and take-profit).
- Creates a bracket order group consisting of:
A main buy order with the specified execution type (default: Limit)
A low side bracket sell stop-loss order
A high side bracket sell take-profit order
- Parameters:
(default (- limitargs) –
None): The data feed for the order. If None, uses the first data feed (self.data).(default –
None): Size for the order. If None, the sizer determines the size. The same size is applied to all three orders.(default –
None): Price for the main buy order. None is valid for Market and Close orders.(default –
None): Price limit for StopLimit orders.(default –
None): Absolute trailing amount for StopTrail/StopTrailLimit orders.(default –
None): Percentage trailing amount for StopTrail/StopTrailLimit orders.(default –
bt.Order.Limit): Execution type for the main order. See buy() documentation for possible values.(default –
None): Order validity period. See buy() documentation for possible values.(default –
0): Trade ID for tracking overlapping trades.(default –
{}): Specific keyword arguments (dict) for the main side order. Applied before **kwargs.**kwargs (-) – Additional keyword arguments applied to all three orders. See buy() documentation for possible values.
(default –
None): Specific price for the stop-loss order.(default –
bt.Order.Stop): Execution type for the stop-loss order.(default –
{}): Specific keyword arguments (dict) for the stop-loss order.(default –
None): Specific price for the take-profit order.(default –
bt.Order.Limit): Execution type for the take-profit order.(default –
{}): Specific keyword arguments (dict) for the take-profit order.
- Returns:
A list containing the three orders [main_order, stop_order, limit_order]. Suppressed orders are represented as None.
Note
High/Low side orders can be suppressed by setting limitexec=None or stopexec=None.
- sell_bracket(data=None, size=None, price=None, plimit=None, exectype=2, valid=None, tradeid=0, trailamount=None, trailpercent=None, oargs=None, stopprice=None, stopexec=3, stopargs=None, limitprice=None, limitexec=2, limitargs=None, **kwargs)[source]¶
Create a sell bracket order group (sell order with stop-loss and take-profit).
- Creates a bracket order group consisting of:
A main sell order with the specified execution type (default: Limit)
A high side bracket buy stop-loss order
A low side bracket buy take-profit order
- Parameters:
documentation. (See buy_bracket() for parameter)
- Returns:
A list containing the three orders [main_order, stop_order, limit_order]. Suppressed orders are represented as None.
Note
High/Low side orders can be suppressed by setting limitexec=None or stopexec=None.
- order_target_size(data=None, target=0, **kwargs)[source]¶
Place an order to achieve a target position size.
Rebalances the current position to reach the specified target size.
- Parameters:
data – The data feed for the order. If None, uses the default data feed.
target – Target position size. - If target > pos.size: buy (target - pos.size) - If target < pos.size: sell (pos.size - target) - If target == 0: close the entire position
**kwargs – Additional keyword arguments passed to buy/sell.
- Returns:
The generated order, or None if target == current position size.
- Return type:
Order | None
- order_target_value(data=None, target=0.0, price=None, **kwargs)[source]¶
Place an order to achieve a target position value.
Rebalances the position to reach the specified target value.
- Parameters:
data – The data feed for the order. If None, uses the default data feed.
target – Target position value in currency units. - If target is 0: close position - If target > value: buy to increase value - If target < value: sell to decrease value
price – Price for size calculation. If None, uses data.close[0].
**kwargs – Additional keyword arguments passed to buy/sell.
- Returns:
The generated order, or None if no order was issued.
- Return type:
Order | None
- strategy_mark_max_age = 0.0¶
Seconds a historical valuation mark may lag the newest mark used with it;
0means every mark must be on the same bar time (60.11-A5).
- strategy_mark_max_age_seconds = 5.0¶
Absolute freshness bound, in seconds, for a live valuation mark (iteration 60, F6):
now - event timeof each mark must not exceed it, wherenowis the feed’s injected clock (wall clock in live runs) and the event time is the provider/exchange time of the bar close or tick. The default is deliberately tight; a strategy that values on slower data must raise it explicitly. It only tightens each feed’s ownvaluation_mark_max_ageand never loosens it.
- order_target_percent(data=None, target=0.0, **kwargs)[source]¶
Place an order to achieve a target percentage of portfolio value.
Rebalances the position so its value equals the target percentage of the total portfolio value.
- Parameters:
data – The data feed for the order. If None, uses the default data feed.
target – Target percentage as a decimal (e.g., 0.05 for 5%).
**kwargs – Additional keyword arguments passed to order_target_value.
- Returns:
The generated order, or None if no order was issued.
- Return type:
Order | None
Example
With target=0.05 and portfolio value of 100: - Target value = 0.05 * 100 = 5 - Orders are placed through order_target_value
Note
Position direction (long/short) is considered: - If target > value: buy if pos.size >= 0, sell if pos.size < 0 - If target < value: sell if pos.size >= 0, buy if pos.size < 0
- notify_ledger_event(event)[source]¶
Receive one event of this strategy’s SDK ledger book (iteration 60, G5).
Called only for a strategy bound with
BtApiBroker.bind_direct_strategy_ledger(..., event_cursor_path=...).eventis abt_api_py.strategy_ledger.LedgerEventwith a stableevent_id. Delivery is at least once: after a crash, or if this method raises, the same event is delivered again, so side effects here must be idempotent or keyed byevent_id. Default: no-op.
- getposition(data=None, broker=None, side=None, **kwargs)[source]¶
Get the current position for a data feed.
- Parameters:
data – The data feed to get position for. If None, uses the first data feed.
broker – The broker to query. If None, uses the default broker.
- Returns:
The Broker’s account-scope Position, when available.
Note
A property
positionis also available as a shortcut.
- get_strategy_position(data=None, broker=None, side=None)[source]¶
Return this strategy’s position, never an account-total fallback.
- property position¶
Get the current position for a data feed.
- Parameters:
data – The data feed to get position for. If None, uses the first data feed.
broker – The broker to query. If None, uses the default broker.
- Returns:
The Broker’s account-scope Position, when available.
Note
A property
positionis also available as a shortcut.
- getpositionbyname(name=None, broker=None, side=None, **kwargs)[source]¶
Get the current position for a data feed by name.
- Parameters:
name – Name of the data feed. If None, uses the first data feed.
broker – The broker to query. If None, uses the default broker.
- Returns:
The account-scope Position, like
getposition().
Note
A property
positionbynameis also available as a shortcut.
- property positionbyname¶
Get the current position for a data feed by name.
- Parameters:
name – Name of the data feed. If None, uses the first data feed.
broker – The broker to query. If None, uses the default broker.
- Returns:
The account-scope Position, like
getposition().
Note
A property
positionbynameis also available as a shortcut.
- getpositions(broker=None)[source]¶
Get all positions.
- Parameters:
broker – The broker to query. If None, uses the default broker.
- Returns:
Mapping of data feeds to account-scope Position objects.
Note
A property
positionsis also available as a shortcut.
- property positions¶
Get all positions.
- Parameters:
broker – The broker to query. If None, uses the default broker.
- Returns:
Mapping of data feeds to account-scope Position objects.
Note
A property
positionsis also available as a shortcut.
- getpositionsbyname(broker=None)[source]¶
Get all positions indexed by data name.
- Parameters:
broker – The broker to query. If None, uses the default broker.
- Returns:
OrderedDict mapping data names to account-scope Position objects, like
getpositions().
Note
A property
positionsbynameis also available as a shortcut.
- property positionsbyname¶
Get all positions indexed by data name.
- Parameters:
broker – The broker to query. If None, uses the default broker.
- Returns:
OrderedDict mapping data names to account-scope Position objects, like
getpositions().
Note
A property
positionsbynameis also available as a shortcut.
- getaccountposition(data=None, broker=None, side=None, **kwargs)[source]¶
Account-wide position from the Broker, ignoring any strategy book.
This is the explicit entry for account-level reads on a shared account; orders sized from it can affect other strategies’ positions.
- getaccountpositions(broker=None)[source]¶
Account-wide positions from the Broker, ignoring any strategy book.
- setsizer(sizer)[source]¶
Set the sizer for automatic stake calculation.
- Parameters:
sizer – The sizer instance to use
- Returns:
The sizer instance
- getsizer()[source]¶
Get the current sizer for automatic stake calculation.
- Returns:
The current sizer instance
Note
Also available as the
sizerproperty.
- property sizer¶
Get the current sizer for automatic stake calculation.
- Returns:
The current sizer instance
Note
Also available as the
sizerproperty.
- getsizing(data=None, isbuy=True)[source]¶
Get the order size from the sizer.
Uses the configured sizer to calculate the appropriate stake size for the next order.
- Parameters:
data – The data feed for the order. If None, uses the default data.
isbuy – True for buy orders, False for sell orders.
- Returns:
The calculated stake size.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Analyzer[source]¶
Bases:
ParameterizedBaseAnalyzer base class. All analyzers are subclass of this one
An Analyzer instance operates in the frame of a strategy and provides an analysis for that strategy.
# Analyzer class, all analyzers are base classes of this class. An analyzer operates within the strategy framework and provides analysis of strategy execution
Automagically set member attributes:
self.strategy(giving access to the strategy and anything accessible from it)# Access to strategy instance
self.datas[x]giving access to the array of data feeds present in the the system, which could also be accessed via the strategy referenceself.data, giving access toself.datas[0]self.dataX->self.datas[X]self.dataX_Y->self.datas[X].lines[Y]self.dataX_name->self.datas[X].nameself.data_name->self.datas[0].nameself.data_Y->self.datas[0].lines[Y]
# Methods to access data
This is not a Lines object, but the methods and operation follow the same design
__init__during instantiation and initial setupstart/stopto signal the begin and end of operationsprenext/nextstart/nextfamily of methods that follow the calls made to the same methods in the strategynotify_trade/notify_order/notify_cashvalue/notify_fundwhich receive the same notifications as the equivalent methods of the strategy
The mode of operation is open and no pattern is preferred. As such the analysis can be generated with the
nextcalls, at the end of operations duringstopand even with a single method likenotify_tradeThe important thing is to override
get_analysisto return a dict-like object containing the results of the analysis (the actual format is implementation dependent)# Below are not line objects, but methods and operation design are similar to strategy. The most important thing is to override get_analysis, # to return a dict-like object to store analysis results
- csv = True¶
- __init__(*args, **kwargs)[source]¶
Initialize Analyzer with basic functionality.
Note: __new__ removed - _children initialization moved here.
- __len__()[source]¶
Support for invoking
lenon analyzers by actually returning the current length of the strategy the analyzer operates on
- notify_cashvalue(cash, value)[source]¶
Notify the analyzer of cash and value changes.
- Parameters:
cash – Current available cash.
value – Current portfolio value.
Note
Override this method to react to cash/value changes.
- notify_fund(cash, value, fundvalue, shares)[source]¶
Notify the analyzer of fund-related changes.
- Parameters:
cash – Current available cash.
value – Current portfolio value.
fundvalue – Current fund value.
shares – Number of fund shares.
Note
Override this method to react to fund changes.
- notify_order(order)[source]¶
Notify the analyzer of an order status change.
- Parameters:
order – The order that was updated.
Note
Override this method to track order status.
- notify_trade(trade)[source]¶
Notify the analyzer of a trade status change.
- Parameters:
trade – The trade that was updated.
Note
Override this method to track trade status.
- next()[source]¶
Called on each bar after minimum period is reached.
Note
Override this method to implement per-bar analysis logic.
- prenext()[source]¶
Called on each bar before minimum period is reached.
By default calls next(). Override if different behavior is needed.
- nextstart()[source]¶
Called once when minimum period is first reached.
By default calls next(). Override if different behavior is needed.
- start()[source]¶
Called at the start of the backtest.
Note
Override this method to initialize analyzer state.
- stop()[source]¶
Called at the end of the backtest.
Note
Override this method to perform final calculations.
- create_analysis()[source]¶
Create the analysis results container.
Creates the rets OrderedDict that will hold analysis results. Override this method to customize the results structure.
- get_analysis()[source]¶
Returns a dict-like object with the results of the analysis
The keys and format of analysis results in the dictionary is implementation dependent.
It is not even enforced that the result is a dict-like object, just the convention
The default implementation returns the default OrderedDict
retscreated by the defaultcreate_analysismethod# Return dict-like result analysis, specific format depends on implementation
- class backtrader.TimeFrameAnalyzerBase[source]¶
Bases:
AnalyzerBase class for time-frame aware analyzers.
This analyzer base operates on a specific timeframe (daily, weekly, monthly, etc.) and calls on_dt_over() when the timeframe changes.
- Params:
timeframe: TimeFrame to use (None = use data’s timeframe). compression: Compression factor (None = use data’s compression). _doprenext: Whether to call prenext (default: True).
- params = (('timeframe', None), ('compression', None), ('_doprenext', True))¶
- class backtrader.CommInfoBase[source]¶
Bases:
ParameterizedBaseBase Class for the Commission Schemes.
Migrated from MetaParams to ParameterizedBase system for better parameter management and validation.
- Params:
commission (def: 0.0): base commission value in percentage or monetary units
mult (def 1.0): multiplier applied to the asset for value/profit
margin (def: None): amount of monetary units needed to open/hold an operation
automargin (def: False): Used by get_margin to automatically calculate margin
commtype (def: None): Commission type (COMM_PERC/COMM_FIXED)
stocklike (def: False): Indicates if the instrument is Stock-like or Futures-like
percabs (def: False): whether commission is XX% or 0.XX when commtype is COMM_PERC
interest (def: 0.0): yearly interest charged for holding short selling position
interest_long (def: False): whether to charge interest on long positions
leverage (def: 1.0): amount of leverage for the asset
- COMM_PERC = 0¶
- COMM_FIXED = 1¶
- 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
- maker_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
- taker_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
- open_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
- close_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
- close_today_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
- close_yesterday_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
- mult¶
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
- margin¶
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
- commtype¶
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
- stocklike¶
- percabs¶
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
- interest¶
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
- interest_long¶
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
- leverage¶
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
- automargin¶
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
- set_param(name, value, validate=True)[source]¶
Set a parameter and refresh the cached commission attributes.
Keeps the fast-path caches (
_margin,_automargin,_leverage_param,_interest_long) in step with the parameter store so hot-path lookups can bypassget_param.- Parameters:
name – Parameter name.
value – New value.
validate – Whether the descriptor should validate
value.
- get_margin(price)[source]¶
Returns the actual margin/guarantees needed for a single item of the asset at the given price. The default implementation has this policy:
Use param
marginif paramautomarginevaluates toFalseUse param
mult*priceifautomargin < 0Use param
automargin*priceifautomargin > 0
- getvaluesize(size, price)[source]¶
Returns the value of size for given a price. For future-like objects it is fixed at size * margin
- getvalue(position, price)[source]¶
Returns the value of a position given a price. For future-like objects it is fixed at size * margin
- class backtrader.ParameterDescriptor[source]¶
Bases:
objectAdvanced 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__(default=None, type_=None, validator=None, doc=None, name=None, required=False)[source]¶
Initialize parameter descriptor.
- Parameters:
default (Any) – Default value for the parameter
type – Expected type for the parameter (enables type checking)
validator (Callable[[Any], bool] | None) – Function to validate parameter values
doc (str | None) – Documentation string for the parameter
name (str | None) – Parameter name (usually set by __set_name__)
required (bool) – Whether this parameter is required (no default allowed)
- __set_name__(owner, name)[source]¶
Called when the descriptor is assigned to a class attribute. This is a Python 3.6+ feature that automatically sets the parameter name.
- backtrader.get_logger(name=None)[source]¶
Return a logger under the
backtradernamespace.- Parameters:
name – Usually
__name__of the calling module. If it already starts with"backtrader"it is used as-is; otherwise it is nested under thebacktraderroot (e.g."mystuff"->"backtrader.mystuff").Nonereturns the root logger.- Returns:
A logger in the backtrader hierarchy.
- Return type:
- class backtrader.BrokerAliasMixin[source]¶
Bases:
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).
- class backtrader.BrokerBase[source]¶
Bases:
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)[source]¶
Initialize the broker instance.
- Parameters:
**kwargs – Keyword arguments passed to parent class.
- init()[source]¶
Initialize the commission info dictionary.
Sets up the default commission scheme if not already present. Called from both __init__ and start methods.
- add_order_history(orders, notify=False)[source]¶
Add order history to the broker.
- Parameters:
orders – Orders to add to history.
notify – Whether to notify about these orders.
- Raises:
NotImplementedError – Must be implemented by subclasses.
- set_fund_history(fund)[source]¶
Set fund history for the broker.
- Parameters:
fund – Fund history data.
- Raises:
NotImplementedError – Must be implemented by subclasses.
- getcommissioninfo(data)[source]¶
Get the commission info for a given data.
- Parameters:
data – Data feed to get commission info for.
- Returns:
The commission info for the data, or the default.
- Return type:
- setcommission(commission=0.0, maker_commission=None, taker_commission=None, open_commission=None, close_commission=None, close_today_commission=None, close_yesterday_commission=None, margin=None, mult=1.0, commtype=None, percabs=True, stocklike=False, interest=0.0, interest_long=False, leverage=1.0, automargin=False, name=None)[source]¶
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)[source]¶
Add a CommissionInfo object for an asset.
- Parameters:
comminfo – The CommissionInfo object to add.
name – Asset name. If None, sets as default for all assets.
- getcash()[source]¶
Get the current available cash.
- Returns:
Current cash amount.
- Return type:
- Raises:
NotImplementedError – Must be implemented by subclasses.
- getvalue(datas=None)[source]¶
Get the current portfolio value.
- Parameters:
datas – Data feeds to calculate value for (optional).
- Returns:
Current portfolio value.
- Return type:
- Raises:
NotImplementedError – Must be implemented by subclasses.
- get_strategy_position(strategy, data, side=None)[source]¶
Return an explicitly bound strategy position, when supported.
- get_strategy_cash(strategy, *, currency=None)[source]¶
Return explicitly bound strategy cash, when supported.
- get_strategy_value(strategy, *, datas=None, currency=None)[source]¶
Return explicitly bound strategy equity, when supported.
- get_cached_report_state()[source]¶
Return a local-only state view for runtime observers.
Implementations must not perform network, disk, or provider queries in this method. It is deliberately separate from
getcash(),getvalue(), andgetposition(), because live brokers may refresh those values synchronously. A caller may receiveNonewhen a broker does not expose a local report cache.- Returns:
A mapping with optional
cash,value, andpositionsentries, plus an optionalposition_legsmapping for dual-side brokers, orNoneif no read-only cache exists.- Return type:
dict | None
- get_cached_mark_price(data)[source]¶
Return a local-only mark for
datawhen the broker has one.Runtime reports may use this optional hook only when the data object has no current close line, such as channel-only strategies. An implementation must read an already-held tick/order-book/cache value; it must not make a network, disk, or provider request.
Nonemeans that no cached mark is available.
Get the current number of shares in fund-like mode.
- Returns:
Number of shares (1.0 for abstract mode).
- Return type:
Get the current number of shares in fund-like mode.
- Returns:
Number of shares (1.0 for abstract mode).
- Return type:
- set_fundmode(fundmode, fundstartval=None)[source]¶
Set the fund mode for the broker.
- Parameters:
fundmode – True to enable fund mode, False otherwise.
fundstartval – Initial fund value (optional).
Note
Not all brokers support fund mode.
- get_fundmode()[source]¶
Get the current fund mode status.
- Returns:
True if fund mode is enabled, False otherwise.
- Return type:
- property fundmode¶
Get the current fund mode status.
- Returns:
True if fund mode is enabled, False otherwise.
- Return type:
- getposition(data, side=None)[source]¶
Get the current position for a data feed.
- Parameters:
data – Data feed to get position for.
side – Optional side selector used by brokers that support dual-side position books.
- Returns:
Current position for the data feed.
- Return type:
- Raises:
NotImplementedError – Must be implemented by subclasses.
- submit(order)[source]¶
Submit an order to the broker.
- Parameters:
order – Order object to submit.
- Raises:
NotImplementedError – Must be implemented by subclasses.
- cancel(order)[source]¶
Cancel a pending order.
- Parameters:
order – Order object to cancel.
- Raises:
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)[source]¶
Create a buy order.
- Parameters:
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.
- Returns:
The created order object.
- Return type:
- Raises:
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)[source]¶
Create a sell order.
- Parameters:
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.
- Returns:
The created order object.
- Return type:
- Raises:
NotImplementedError – Must be implemented by subclasses.
- class backtrader.timezone[source]¶
Bases:
tzinfoFixed offset from UTC implementation of tzinfo.
- utcoffset()¶
Return fixed offset.
- tzname()¶
If name is specified when timezone is created, returns the name. Otherwise returns offset as ‘UTC(+|-)HH:MM’.
- dst()¶
Return None.
- fromutc()¶
datetime in UTC -> datetime in local time.
- max = datetime.timezone(datetime.timedelta(seconds=86340))¶
- min = datetime.timezone(datetime.timedelta(days=-1, seconds=60))¶
- utc = datetime.timezone.utc¶
- class backtrader.BackBroker[source]¶
Bases:
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
Note
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.
int2pnldefaults to True, meaning generated interest cost is transferred to the PnL of the position-reducing operation.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
- position_mode¶
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
- strategy_dir¶
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.
- start()[source]¶
Start the broker and lock the
position_modeparameter.After the broker has been started the
position_modeparameter is frozen (see_freeze_position_mode()). This mirrors the behaviour ofBtApiBrokerand prevents strategies from silently switching between net and dual-side accounting part-way through a run.- Returns:
The return value of the parent
BrokerBase.start()is forwarded unchanged.- Return type:
None
- set_param(name, value, validate=True)[source]¶
Override
BrokerBase.set_param()to guardposition_modechanges.The
position_modeparameter is treated specially: it is immutable oncestart()has run (frozen via_freeze_position_mode()), and its raw value is normalized throughnormalize_position_mode()so that the broker always stores one of the canonical"net"/"dual_side"strings.- Parameters:
name – Name of the parameter to set.
value – New value for the parameter. For
position_modethe value is normalized before being applied.validate – When
True(default), delegate to the base class so that the registered validator runs. Set toFalseto bypass validation (used internally when applying normalized values).
- Returns:
The return value of
BrokerBase.set_param()after the value has been applied.- Raises:
ValueError – If
name == "position_mode"and the parameter has already been frozen bystart().
- 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:
- 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:
- getcash()¶
Get the current available cash.
- Returns:
- Current cash amount. Returns parameter value if not yet
initialized, otherwise returns current cash status.
- Return type:
- 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 the current number of fund shares.
- Returns:
Current number of shares in fund-like mode
- Return type:
Get the current number of fund shares.
- Returns:
Current number of shares in fund-like mode
- Return type:
- get_fundvalue()[source]¶
Get the fund share value.
- Returns:
Current fund-like share value
- Return type:
- property fundvalue¶
Get the fund share value.
- Returns:
Current fund-like share value
- Return type:
- 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:
- 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:
- 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
safeto True
- getposition(data, side=None)[source]¶
Get the current position status for a data feed.
- Parameters:
data – Data feed to get position for
side – Optional leg selector in dual_side mode
- Returns:
Current position instance for the data feed
- Return type:
- get_cached_report_state()[source]¶
Return the broker’s already-computed state without recalculation.
- 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:
- 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:
- 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:
- 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:
- cash is adjusted on each iteration for instruments like
- class backtrader.ChannelDataRef[source]¶
Bases:
objectLightweight data reference for channel-only strategies.
Channel-mode HFT strategies submit orders through the standard
Strategy.buy/Strategy.sellAPIs but may not have LineSeries data feeds. This object provides the minimal data identity expected by brokers and order objects:_name,nameandsymbol.
- class backtrader.AbstractDataBase[source]¶
Bases:
OHLCDateTimeBase class for all data feed implementations.
Provides the core functionality for data feeds including: - Data loading and preprocessing - Timeline management - Session handling - Live data support - Notification system for data status changes
- States:
CONNECTED, DISCONNECTED, CONNBROKEN, DELAYED, LIVE, NOTSUBSCRIBED, NOTSUPPORTED_TF, UNKNOWN
- Params:
dataname: Data source identifier (filename, URL, etc.). name: Display name for the data feed. compression: Timeframe compression factor. timeframe: TimeFrame period (Days, Minutes, etc.). fromdate: Start date for data filtering. todate: End date for data filtering. sessionstart: Session start time. sessionend: Session end time. filters: List of data filters to apply. tz: Output timezone. tzinput: Input timezone. qcheck: Timeout in seconds for live event checking. calendar: Trading calendar to use.
Example
>>> data = AbstractDataBase(dataname='data.csv') >>> cerebro.adddata(data)
- CONNECTED = 0¶
- DISCONNECTED = 1¶
- CONNBROKEN = 2¶
- DELAYED = 3¶
- LIVE = 4¶
- NOTSUBSCRIBED = 5¶
- NOTSUPPORTED_TF = 6¶
- UNKNOWN = 7¶
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- resampling = 0¶
- replaying = 0¶
- date2num(dt)[source]¶
Convert datetime to internal numeric format.
- Parameters:
dt – datetime object to convert.
- Returns:
Internal numeric representation of the datetime.
- Return type:
- num2date(dt=None, tz=None, naive=True)[source]¶
Convert internal numeric format to datetime.
- Parameters:
dt – Numeric datetime value (uses current if None).
tz – Timezone to use (uses feed tz if None).
naive – Return naive datetime if True.
- Returns:
Converted datetime object.
- Return type:
- haslivedata()[source]¶
Check if this data feed has live data.
- Returns:
False for base class, override for live data feeds.
- Return type:
- do_qcheck(onoff, qlapse)[source]¶
Calculate wait interval for queue checking.
- Parameters:
onoff – Whether queue checking is enabled.
qlapse – Time elapsed since last check.
- islive()[source]¶
If this returns True,
Cerebrowill deactivatepreloadandrunoncebecause a live data source must be fetched tick by tick (or bar by bar)
- getfeed()[source]¶
Get the parent feed object.
- Returns:
The parent feed instance.
- Return type:
FeedBase or None
- qbuffer(savemem=0, replaying=False)[source]¶
Apply queued buffering to all lines.
- Parameters:
savemem – Memory saving mode.
replaying – Whether replaying is active.
- clone(**kwargs)[source]¶
Create a clone of this data feed.
- Parameters:
**kwargs – Additional keyword arguments for the clone.
- Returns:
A cloned data feed.
- Return type:
- copyas(_dataname, **kwargs)[source]¶
Copy the data feed with a different name.
- Parameters:
_dataname – New name for the data feed.
**kwargs – Additional keyword arguments.
- Returns:
A cloned data feed with the new name.
- Return type:
- getenvironment()[source]¶
Get the cerebro environment reference.
- Returns:
The cerebro environment instance.
- addfilter_simple(f, *args, **kwargs)[source]¶
Add a simple filter wrapper to this data feed.
- Parameters:
f – Filter function to apply.
*args – Positional arguments for the filter.
**kwargs – Keyword arguments for the filter.
- addfilter(p, *args, **kwargs)[source]¶
Add a filter to this data feed.
- Parameters:
p – Filter class or instance.
*args – Positional arguments for filter creation.
**kwargs – Keyword arguments for filter creation.
- compensate(other)[source]¶
Call it to let the broker know that actions on this asset will compensate open positions in another
- advance_peek()[source]¶
Peek at the datetime of the next bar.
- Returns:
Numeric datetime of next bar, or inf if unavailable.
- Return type:
- advance(size=1, datamaster=None, ticks=True)[source]¶
Advance the data feed by the specified size.
- Parameters:
size – Number of bars to advance (default: 1).
datamaster – Master data feed for synchronization.
ticks – Whether to process tick data.
- next(datamaster=None, ticks=True)[source]¶
Move to the next bar.
- Parameters:
datamaster – Master data feed for synchronization.
ticks – Whether to process tick data.
- Returns:
True if a bar is available, False otherwise.
- Return type:
- preload()[source]¶
Preload all available data from the data feed.
Loads all bars and resets position to the beginning.
- load()[source]¶
Load the next bar from the data feed.
- Returns:
True if a bar was loaded, False if no more data.
- Return type:
- This method handles:
Forwarding the data pointer
Processing filters
Checking date boundaries
- resample(**kwargs)[source]¶
Add a resampling filter to this data feed.
Resampling converts data to a different timeframe (e.g., minutes to days).
- Parameters:
**kwargs – Arguments for the Resampler filter.
- replay(**kwargs)[source]¶
Add a replay filter to this data feed.
Replay filters process tick data into bars with precise control.
- Parameters:
**kwargs – Arguments for the Replayer filter.
- frompackages = ()¶
- packages = ()¶
- class backtrader.OwnerContext[source]¶
Bases:
objectContext manager for tracking owner objects during indicator creation.
This class provides an alternative to sys._getframe() based owner lookup by maintaining an explicit owner stack in thread-local storage.
- Usage:
- with OwnerContext.set_owner(strategy):
# All indicators created here will have strategy as their owner sma = SMA(data, period=20)
The owner stack allows nested contexts, so indicators creating sub-indicators will correctly assign ownership.
- static get_current_owner(cls_filter=None)[source]¶
Get the current owner from the context stack.
- Parameters:
cls_filter – Optional class type to filter owners. If provided, only returns an owner that is an instance of this class.
- Returns:
The current owner object, or None if no owner is set or no owner matches the filter.
- static set_owner(owner)[source]¶
Set the current owner for indicator creation.
- Parameters:
owner – The owner object (typically a Strategy or Indicator).
- Yields:
None. The owner is available via get_current_owner() within the context.
- static push_owner(owner)[source]¶
Push an owner onto the stack (non-context-manager version).
- Parameters:
owner – The owner object to push.
- class backtrader.SignalStrategy[source]¶
Bases:
StrategyA strategy subclass that automatically operates using signals.
This strategy subclass responds to signal indicators to automatically enter and exit positions based on signal values.
- Signal values:
> 0indicates a long (buy) signal< 0indicates a short (sell) signal
There are five types of signals, broken into two groups:
Main Group:
LONGSHORT: Both long and short indications from this signal are taken. The strategy will go long or short based on the sign.LONG: - Positive (long) indications: Go long - Negative (short) indications: Close long positionIf
LONGEXITexists, it is used to exit longsIf
SHORTsignal exists and noLONGEXIT, it will close longs before opening a short
SHORT: - Negative (short) indications: Go short - Positive (long) indications: Close short positionIf
SHORTEXITexists, it is used to exit shortsIf
LONGsignal exists and noSHORTEXIT, it will close shorts before opening a long
- Exit Group:
These signals override others to provide explicit exit criteria:
LONGEXIT: Negative indications are taken to exit long positionsSHORTEXIT: Positive indications are taken to exit short positions
Order Issuing
Orders are placed with Market execution type and Good-Until-Canceled validity.
Params:
signals(default:[]): A list/tuple of lists/tuples for signal instantiation and type allocation. This parameter is typically managed throughcerebro.add_signal._accumulate(default:False): Allow entering the market even if already in a position (accumulate positions)._concurrent(default:False): Allow issuing orders even when orders are already pending execution._data(default:None): If multiple datas are present in the system which is the target for orders. This can beNone: The first data in the system will be usedAn
int: indicating the data that was inserted at that positionAn
str: name given to the data when creating it (parametername) or when adding it cerebro withcerebro.adddata(..., name=)A
datainstance
- static __new__(cls, *args, **kwargs)[source]¶
Override __new__ to handle next method remapping that was done in MetaSigStrategy
- __init__(*args, **kwargs)¶
- signal_add(sigtype, signal)[source]¶
Add a signal indicator to the strategy.
- Parameters:
sigtype – Type of signal (e.g., SIGNAL_LONG, SIGNAL_SHORT)
signal – The signal indicator instance
- frompackages = ()¶
- packages = ()¶
- class backtrader.Timer[source]¶
Bases:
ParameterizedBaseTimer class for scheduling time-based notifications in backtrader.
Timers can trigger at specific times of day, session boundaries, or at repeating intervals. They can filter by weekdays and monthdays.
- Params:
tid: Timer ID for identification. owner: Owner object of the timer. strats: Whether to notify strategies (default: False). when: When to trigger (time, SESSION_START, or SESSION_END). offset: Time offset for the trigger. repeat: Repeat interval for recurring timers. weekdays: List of weekdays when timer is active (0=Monday, 6=Sunday). weekcarry: Whether to carry over to next weekday if missed. monthdays: List of month days when timer is active. monthcarry: Whether to carry over to next month day if missed. allow: Callback function to allow/disallow timer on specific dates. tzdata: Timezone data for the timer. cheat: Whether timer can execute before broker.
Example
>>> timer = bt.Timer(when=datetime.time(9, 30), weekdays=[0, 1, 2, 3, 4]) >>> cerebro.add_timer(timer)
- tid¶
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
- owner¶
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
- strats¶
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
- when¶
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
- offset¶
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
- repeat¶
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
- weekdays¶
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
- weekcarry¶
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
- monthdays¶
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
- monthcarry¶
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
- allow¶
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
- tzdata¶
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
- cheat¶
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
- SESSION_TIME = 0¶
- SESSION_START = 1¶
- SESSION_END = 2¶
- __init__(*args, **kwargs)[source]¶
Initialize the Timer instance.
- Parameters:
*args – Positional arguments.
**kwargs – Keyword arguments for timer parameters.
- class backtrader.PandasMarketCalendar[source]¶
Bases:
TradingCalendarBaseWrapper of
pandas_market_calendarsfor a trading calendar. The packagepandas_market_calendarmust be installed # pandas_market_calendar must be installed Params:calendar(defaultNone)The param
calendaraccepts the following:string: the name of one of the calendars supported, for example, NYSE. The wrapper will attempt to get a calendar instance
Calendar instance: as returned by
get_calendar('NYSE')
# calendar information, can be string or calendar instance
cachesize(default365)Number of days to cache in advance for lookup
# How many dates to cache in advance for convenient lookup
See also
- params = (('calendar', None), ('cachesize', 365))¶
- class backtrader.TradingCalendarBase[source]¶
Bases:
ParameterizedBaseBase class for trading calendars.
Provides methods for calculating trading days, session times, and determining if a day is the last trading day of a week or month.
- schedule(day)[source]¶
Returns a tuple with the opening and closing times (
datetime.time) for the givendate(datetime/dateinstance)
- nextday(day)[source]¶
Returns the next trading day (datetime/date instance) after
day(datetime/date instance)
- nextday_week(day)[source]¶
Returns the iso week number of the next trading day, given a
day(datetime/date) instance
- last_weekday(day)[source]¶
Returns
Trueif the givenday(datetime/date) instance is the last trading day of this week
- backtrader.date2num(dt, tz=None)[source]¶
Convert: mod:datetime to the Gregorian date as UTC float days, preserving hours, minutes, seconds and microseconds. Return value is a: func:float.
- backtrader.tzparse(tz)[source]¶
Parse a timezone specification into a tzinfo object.
- Parameters:
tz – Timezone specification (string, tzinfo object, or None).
- Returns:
A tzinfo object. If pytz is available and tz is a string, returns the corresponding pytz timezone. Otherwise returns a Localizer-wrapped tz object.
- class backtrader.map¶
Bases:
objectmap(func, *iterables) –> map object
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
- class backtrader.range¶
Bases:
objectrange(stop) -> range object range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).
- count(value) integer -- return number of occurrences of value¶
- index(value) integer -- return index of value.¶
Raise ValueError if the value is not present.
- start¶
- step¶
- stop¶
- class backtrader.zip¶
Bases:
objectzip(*iterables, strict=False) –> Yield tuples until an input is exhausted.
>>> list(zip('abcdefg', range(3), range(4))) [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted.
If strict is true and one of the arguments is exhausted before the others, raise a ValueError.
- class backtrader.WriterFile[source]¶
Bases:
WriterBaseThe system-wide writer class.
Writes strategy execution results to a file or stdout.
- Params:
- out: Output stream (default: sys.stdout). If a string is passed,
it’s treated as a filename. Use None for multiprocess optimization.
close_out: If True, explicitly close the output stream (default: False). csv: If True, write CSV data during execution (default: False). csv_filternan: If True, replace NaN values with empty fields (default: True). csvsep: CSV separator character (default: ‘,’). indent: Indentation for formatted output (default: 2).
Example
>>> cerebro.addwriter(bt.WriterFile, out='results.csv', csv=True)
- params = (('out', None), ('close_out', False), ('csv', False), ('csvsep', ','), ('csv_filternan', True), ('csv_counter', True), ('indent', 2), ('separators', ['=', '-', '+', '*', '.', '~', '"', '^', '#']), ('seplen', 79), ('rounding', None))¶
- __init__(**kwargs)[source]¶
Initialize the WriterFile instance.
Sets up the counter, headers list, and values list for tracking data during execution.
- Parameters:
**kwargs – Keyword arguments for writer parameters.
- start()[source]¶
Initialize the writer at the start of execution.
Opens the output file/stream and writes CSV headers if CSV mode is enabled.
- stop()[source]¶
Close the output stream when execution ends.
Closes the output file if close_out parameter is True.
- next()[source]¶
Write accumulated values to output.
Called during execution to write the current set of values to the CSV output and reset the values list.
- addheaders(headers)[source]¶
Add column headers for CSV output.
- Parameters:
headers – List of header names to add.
- addvalues(values)[source]¶
Add values to be written to CSV output.
- Parameters:
values – Iterable of values to add.
- writeiterable(iterable, func=None, counter='')[source]¶
Write an iterable to the output as a CSV line.
- Parameters:
iterable – The data to write.
func – Optional function to apply to each element.
counter – Optional counter value to prepend.
- writeline(line)[source]¶
Write a single line to the output.
- Parameters:
line – The line content to write.
- writelines(lines)[source]¶
Write multiple lines to the output.
- Parameters:
lines – Iterable of line contents to write.
- class backtrader.OptReturn[source]¶
Bases:
objectLightweight result container for optimization runs.
This class is defined at module level to make it picklable for multiprocessing. It stores only essential information from strategy runs during optimization to reduce memory usage.
- p¶
Alias for params.
- params¶
Strategy parameters used in this optimization run.
- analyzers¶
Analyzer results (if returned during optimization).
Note
Additional attributes may be set dynamically via kwargs.
- class backtrader.Cerebro[source]¶
Bases:
RegistryMixin,NotificationMixin,RunLifecycleMixin,ChannelMixin,ExecutionMixin,RunNextMixin,RunOnceMixin,PresentationMixin,ParameterizedBaseParams:
preload(default:True)Whether to preload the different
data feedspassed to cerebro for the StrategiesNote: When True (default), data is loaded into memory before backtesting, which uses more memory but significantly improves execution speed.
runonce(default:True)Run Indicators in vectorized mode to speed up the entire system. Strategies and Observers will always be run on an event-based basis
Note: When True, indicators are calculated using vectorized operations for better performance. Strategies and observers still run event-by-event.
live(default:False)If no data has reported itself as live (via the data’s
islivemethod but the end user still wants to run inlivemode, this parameter can be set to trueThis will simultaneously deactivate
preloadandrunonce. It will have no effect on memory saving schemes.Note: Setting to True forces live mode behavior, disabling preload and runonce optimizations, which slows down backtesting.
maxcpus(default: None -> all available cores)How many cores to use simultaneously for optimization
Note: Set to number of CPU cores minus 1 to avoid system overload. Use None (default) to use all available cores.
stdstats(default:True)If True, default Observers will be added: Broker (Cash and Value), Trades and BuySell
Note: These observers are used for plotting. Set to False if not needed.
oldbuysell(default:False)If
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theBuySellobserverFalse: use the modern behavior in which the buy / sell signals are plotted below / above the low / high prices respectively to avoid cluttering the plotTrue: use the deprecated behavior in which the buy / sell signals are plotted where the average price of the order executions for the given moment in time is. This will, of course, be on top of an OHLC bar or on a Line on Cloe bar, difficult the recognition of the plot.
Note: False (modern) plots signals outside the price bars for clarity. True (old) plots signals at execution price, overlapping with bars.
oldtrades(default:False)If
stdstatsisTrueand observers are getting automatically added, this switch controls the main behavior of theTradesobserverFalse: use the modern behavior in which trades for all datas are plotted with different markersTrue: use the old Trades observer which plots the trades with the same markers, differentiating only if they are positive or negative
Note: False uses different markers for different trades. True uses same markers, only distinguishing positive/negative.
exactbars(default:False)With the default value, each and every value stored in a line is kept in memory
- Possible values:
Trueor1: all “lines” objects reduce memory usage to the automatically calculated minimum period.If a Simple Moving Average has a period of 30, the underlying data will have always a running buffer of 30 bars to allow the calculation of the Simple Moving Average
This setting will deactivate
preloadandrunonceUsing this setting also deactivates plotting
-1: datafeeds and indicators/operations at strategy level will keep all data in memory.For example: a
RSIinternally uses the indicatorUpDayto make calculations. This subindicator will not keep all data in memoryThis allows keeping
plottingandpreloadingactive.runoncewill be deactivated
-2: data feeds and indicators kept as attributes of the strategy will keep all points in memory.For example: a
RSIinternally uses the indicatorUpDayto make calculations. This subindicator will not keep all data in memoryIf in the
__init__something likea = self.data.close - self.data.highis defined, thenawill not keep all data in memoryThis allows keeping
plottingandpreloadingactive.runoncewill be deactivated
- Note on exactbars values:
True/1: Minimum memory, disables preload/runonce/plotting
-1: Keeps data/indicators but not sub-indicator internals, disables runonce
-2: Keeps strategy-level data/indicators, sub-indicators not using self are discarded
objcache(default:False)Experimental option to implement a cache of lines objects and reduce the amount of them. Example from UltimateOscillator:
bp = self.data.close - TrueLow(self.data) tr = TrueRange(self.data) # -> creates another TrueLow(self.data)
If this is True, the second
TrueLow(self.data)insideTrueRangematches the signature of the one in thebpcalculation. It will be reused.Corner cases may happen in which this drives a line object off its minimum period and breaks things, and it is therefore disabled.
Note: When True, identical indicator calculations are cached and reused to reduce computation. Disabled by default due to edge cases.
writer(default:False)If set to
Truea default WriterFile will be created which will print to stdout. It will be added to the strategy (in addition to any other writers added by the user code)Note: Outputs trading information to stdout. Custom logging in strategy is usually preferred for more control.
tradehistory(default:False)If set to
True, it will activate update event logging in each trade for all strategies. This can also be achieved on a per-strategy basis with the strategy methodset_tradehistoryNote: Enables trade update logging for all strategies. Can also be enabled per-strategy using set_tradehistory method.
optdatas(default:True)If
Trueand optimizing (and the system canpreloadand userunonce, data preloading will be done only once in the main process to save time and resources.The tests show an approximate
20%speed-up moving from a sample execution in83seconds to66Note: When True with preload/runonce, data is preloaded once in the main process and shared across optimization workers (~20% speedup).
optreturn(default:True)If True, the optimization results will not be full
Strategyobjects (and all datas, indicators, observers …) but object with the following attributes (same as inStrategy):params(orp) the strategy had for the executionanalyzersthe strategy has executed
On most occasions, only the analyzers and with which params are the things needed to evaluate the performance of a strategy. If detailed analysis of the generated values for (for example) indicators is needed, turn this off
The tests show a 13% - 15% improvement in execution time. Combined with optdatas the total gain increases to a total speed-up of 32% in an optimization run.
Note: Returns only params and analyzers during optimization, discarding data/indicators/observers for ~15% speedup (32% combined with optdatas).
oldsync(default:False)Starting with release 1.9.0.99, the synchronization of multiple datas (same or different timeframes) has been changed to allow datas of different lengths.
If the old behavior with data0 as the master of the system is wished, set this parameter to true
Note: False allows data feeds of different lengths. True uses data0 as master (legacy behavior).
tz(default:None)Adds a global timezone for strategies. The argument
tzcan beNone: in this case the datetime displayed by strategies will be in UTC, which has always been the standard behaviorpytzinstance. It will be used as such to convert UTC times to the chosen timezonestring. Instantiating apytzinstance will be attempted.integer. Use, for the strategy, the same timezone as the correspondingdatain theself.datasiterable (0would use the timezone fromdata0)
Note: None=UTC, pytz instance converts from UTC, string creates pytz, integer uses timezone from corresponding data feed index.
cheat_on_open(default:False)The
next_openmethod of strategies will be called. This happens beforenextand before the broker has had a chance to evaluate orders. The indicators have not yet been recalculated. This allows issuing an order which takes into account the indicators of the previous day but uses theopenprice for stake calculationsFor cheat_on_open order execution, it is also necessary to make the call
cerebro.broker.set_coo(True)or instantiate a broker withBackBroker(coo=True)(where coo stands for cheat-on-open) or set thebroker_cooparameter toTrue. Cerebro will do it automatically unless disabled below.Note: Enables using next bar’s open price for position sizing. Useful for precise capital allocation. Requires broker_coo=True.
broker_coo(default:True)This will automatically invoke the
set_coomethod of the broker withTrueto activatecheat_on_openexecution. Will only do it ifcheat_on_openis alsoTrueNote: Works together with cheat_on_open parameter.
quicknotify(default:False)Broker notifications are delivered right before the delivery of the next prices. For backtesting, this has no implications, but with live
brokers, a notification can take place long before the bar is
delivered. When set to
Truenotifications will be delivered as soon as possible (seeqcheckin live feeds)Set to
Falsefor compatibility. May be changed toTrueNote: False delays notifications until next bar. True sends immediately. Mainly relevant for live trading.
- preload¶
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
- runonce¶
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
- maxcpus¶
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
- stdstats¶
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
- oldbuysell¶
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
- oldtrades¶
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
- lookahead¶
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
- exactbars¶
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
- optdatas¶
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
- optreturn¶
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
- objcache¶
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
- live¶
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
- writer¶
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
- tradehistory¶
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
- oldsync¶
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
- tz¶
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
- cheat_on_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
- broker_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
- quicknotify¶
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 Cerebro with optional parameter overrides.
- Parameters:
**kwargs – Parameter overrides (preload, runonce, maxcpus, etc.)
- setbroker(broker)[source]¶
Sets a specific
brokerinstance for this strategy, replacing the one inherited from cerebro.
- add_live_bar_cohort(cohort, *, clock, winddown_timeout_seconds=0)[source]¶
Opt into one validated, batch-delivered live-bar cohort.
clockmust provideutc_now(),monotonic_ns(), and a singlewait(timeout_seconds)operation. A clock that needs provider-event interruption may additionally providewait_interruptibly(timeout_seconds, wait_for_event). Cerebro uses that optional method only when a Store has registered an event waker; otherwise it always calls the injectedwaitmethod. The callback waits on the engine’s generation-checked event condition and returns a boolean. A legacy clock’swaitcannot be interrupted externally;runstop()is observed after that wait returns. Cerebro never substitutes its process wall clock for this source-time mapping.winddown_timeout_secondsis a finite, nonnegative bound for the maintenance period after the final complete calendar batch. Zero keeps the normal finite-source EOF behavior.
- property live_bar_cohort¶
The configured cohort, or None for ordinary Cerebro runs.
- property live_bar_cohort_clock¶
The exact caller-injected source/UTC clock for cohort strategies.
- property live_bar_cohort_winddown_status¶
The persisted result of the configured live-cohort terminal window.
- property live_bar_cohort_winddown_reason¶
The bounded reason associated with the persisted winddown status.
- getbroker()[source]¶
Returns the broker instance.
This is also available as a
propertyby the namebroker
- __call__(iterstrat)[source]¶
Used during optimization to pass the cerebro over the multiprocessing module without complaints
- __getstate__()[source]¶
Used during optimization to prevent optimization result runstrats from being pickled to subprocesses
- run(**kwargs)[source]¶
The core method to perform backtesting. Any
kwargspassed to it will affect the value of the standard parametersCerebrowas instantiated with.If cerebro has no data and no
channelis given, the method will immediately bail out.Extra keyword arguments¶
- channeliterable or True, optional
When provided the engine runs in channel mode instead of the traditional bar-based mode.
iterable – an
Eventstream (StreamingEventQueue,LiveEventQueue, or any iterable yieldingEventobjects). Events are dispatched to the broker and then to every strategy via theirnotify_*callbacks.True– strategies are instantiated and returned immediately without entering an event loop. This is useful when an external async loop drives the data (e.g. external market-data watchers callingstrategy.notify_tick()directly). Callcerebro.close_channel()from the same thread when that external loop is done to tear down brokers and strategies.
It has different return values:
For No Optimization: a list contanining instances of the Strategy classes added with
addstrategyFor Optimization: a list of lists which contain instances of the Strategy classes added with
addstrategy
- Return type:
- property broker¶
Returns the broker instance.
This is also available as a
propertyby the namebroker
- backtrader.BoolParam(default=None, doc=None)[source]¶
Create a boolean parameter descriptor.
- Parameters:
doc (str)
- Return type:
- class backtrader.CommissionInfo[source]¶
Bases:
CommInfoBaseBase Class for the actual Commission Schemes.
CommInfoBase was created to keep support for the original, incomplete, support provided by backtrader. New commission schemes derive from this class which subclasses
CommInfoBase.The default value of
percabsis also changed toTrue- percabs¶
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
- class backtrader.ComminfoDC[source]¶
Bases:
CommInfoBaseDigital currency commission class
- stocklike¶
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
- commtype¶
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
- percabs¶
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
- interest¶
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
- class backtrader.ComminfoFuturesPercent[source]¶
Bases:
CommInfoBaseFutures percentage commission class
- 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
- mult¶
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
- margin¶
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
- margin_amount¶
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
- stocklike¶
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
- commtype¶
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
- percabs¶
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
- class backtrader.ComminfoFuturesMixed[source]¶
Bases:
ComminfoFuturesPercentFutures commission with both percentage and fixed per-lot components.
- commission_amount¶
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
- open_commission_amount¶
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
- close_commission_amount¶
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
- close_today_commission_amount¶
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
- close_yesterday_commission_amount¶
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
- class backtrader.ComminfoFuturesInverse[source]¶
Bases:
ComminfoFuturesMixedInverse futures commission and PnL using fixed contract notional.
Crypto inverse contracts quote PnL and fees from a fixed contract value, for example BTC-USD-SWAP with a 100 USD contract value. Their quote-value PnL changes with the price ratio rather than a linear
price * multnotional.
- class backtrader.ComminfoFuturesFixed[source]¶
Bases:
CommInfoBaseFutures fixed commission class
- 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
- mult¶
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
- margin¶
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
- margin_amount¶
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
- stocklike¶
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
- commtype¶
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
- percabs¶
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
- class backtrader.ComminfoFundingRate[source]¶
Bases:
CommInfoBaseFunding rate class
- 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
- mult¶
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
- margin¶
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
- stocklike¶
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
- commtype¶
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
- percabs¶
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
- class backtrader.LineSeries[source]¶
Bases:
LineMultiple,LineSeriesMixin,ParamsMixinBase class for objects with multiple time-series lines.
LineSeries provides the foundation for classes that manage multiple line objects, such as indicators with multiple output lines. It handles line creation, access, and management.
- lines¶
Container object holding all line instances.
- plotinfo¶
Plotting configuration object.
Example
Accessing lines by name or index: >>> obj = LineSeries() >>> obj.lines.close # Named access >>> obj.lines[0] # Index access
- static __new__(cls, *args, **kwargs)[source]¶
Instantiate lines class when creating LineSeries instances.
CRITICAL FIX: The lines attribute is set as a class by __init_subclass__, but it needs to be instantiated for each object instance.
- class PlotInfoObj[source]¶
Bases:
objectPlot information object for LineSeries.
Stores plotting configuration attributes that control how the LineSeries is displayed in plots.
- __init__()[source]¶
Initialize plotinfo with default values.
Sets up default plotting attributes including plot status, plot master, and legend location.
- get(key, default=None)[source]¶
Standard get method for compatibility
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotinfo = <backtrader.lineseries.LineSeries.PlotInfoObj object>¶
- class PlotLinesObj[source]¶
Bases:
objectPlot lines configuration object for LineSeries.
Stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.
- get(key, default=None)[source]¶
Standard get method for compatibility
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotlines = <backtrader.lineseries.LineSeries.PlotLinesObj object>¶
- csv = True¶
- property array¶
Get the array of the first line.
- Returns:
The underlying array of the first line.
- Return type:
- property line¶
Return the first line (lines[0]) for single-line indicators.
- Returns:
The first line in the lines collection.
- Return type:
- property l¶
Alias for lines - used in indicator next() methods like self.l.sma[0].
- Returns:
The lines container object.
- Return type:
- __getattr__(name)[source]¶
High-frequency attribute resolution optimized for performance.
OPTIMIZATION NOTES: - Results are cached in __dict__ to avoid repeated lookups - Removed recursion guard overhead (rely on Python’s natural recursion limit) - Use direct __dict__ access instead of getattr() to avoid triggering __getattr__ - Use index check (name[0]) instead of startswith() for speed
- __setattr__(name, value)[source]¶
Optimized attribute setter with minimal type checking.
OPTIMIZATION NOTES: - Use type() instead of isinstance() - faster for simple types - Use EAFP (try/except) instead of hasattr() to avoid double lookups - Minimize attribute access on value object
- __len__()[source]¶
Return length of LineSeries (number of data points)
OPTIMIZATION NOTES: - Cache lines[0] reference to avoid repeated indexing - Called 11M+ times, so optimization is critical
- __getitem__(key)[source]¶
Get value at index from primary line.
OPTIMIZATION NOTES: - Cache reference to lines[0] to avoid repeated indexing - Use fast NaN detection without isinstance/math.isnan - Minimal exception handling
- __setitem__(key, value)[source]¶
Set a line value by index.
Delegates to the Lines.__setitem__ method which handles line assignments properly including binding for indicators.
- Parameters:
key – Line index or name.
value – Value to set.
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- plotlabel()[source]¶
Get the plot label for this LineSeries.
- Returns:
The plot label string.
- Return type:
- __call__(ago=None, line=-1)[source]¶
Return either a delayed line or the data for a given index/name
- Possible calls:
self() -> current line
self(ago) -> delayed line by “ago” periods
self(-1) -> current line
self(line=-1) -> current line
self(line=’close’) -> current line by name
- forward(value=nan, size=1)[source]¶
Forward all lines by the specified size.
- Parameters:
value – Value to use for forwarding (default: NAN).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move all lines backward by the specified size.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind all lines by decreasing idx and lencount.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend all lines with additional positions.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- reset(value=0.0)[source]¶
Reset all lines to their initial state.
- Parameters:
value – Value to use for reset (default: 0.0).
- advance(size=1)[source]¶
Advance all lines by increasing idx.
- Parameters:
size – Number of positions to advance (default: 1).
- size()[source]¶
Return the number of lines in this LineSeries.
- Returns:
Number of main lines (excluding extra lines).
- Return type:
- property chkmin¶
Property to ensure chkmin is never None for TestStrategy.
This property provides a safe default value for chkmin, which is used in testing to validate minimum period requirements.
- Returns:
The chkmin value, or 30 as a safe default.
- Return type:
- frompackages = ()¶
- packages = ()¶
- class backtrader.AutoOrderedDict[source]¶
Bases:
OrderedDictOrderedDict with automatic nested dict creation and closeable state.
Combines OrderedDict’s insertion ordering with AutoDict’s automatic nested dict creation and closeable state.
- _closed¶
If True, __missing__ raises KeyError instead of creating nested dicts.
Example
>>> d = AutoOrderedDict() >>> d['a']['b'] = 1 # Automatically creates nested dicts >>> d._close() # Prevent further auto-creation
- class backtrader.DataSeries[source]¶
Bases:
LineSeriesBase class for financial time-series data feeds.
DataSeries extends LineSeries to provide the standard OHLCV (Open, High, Low, Close, Volume, OpenInterest) data lines plus DateTime.
- _name¶
Name identifier for the data series.
- _compression¶
Compression factor for the timeframe.
- _timeframe¶
TimeFrame period (Days, Minutes, etc.).
- Lines:
DateTime: Timestamp of the bar. Open: Opening price. High: Highest price. Low: Lowest price. Close: Closing price. Volume: Trading volume. OpenInterest: Open interest (for derivatives).
Example
>>> data = DataSeries() >>> print(data.close[0]) # Current close price
- plotinfo = <backtrader.metabase.plotinfo_obj object>¶
- name = ''¶
- Close = 0¶
- Low = 1¶
- High = 2¶
- Open = 3¶
- Volume = 4¶
- OpenInterest = 5¶
- DateTime = 6¶
- LineOrder = [6, 3, 2, 1, 0, 4, 5]¶
- getwriterheaders()[source]¶
Get header names for writing data.
- Returns:
List of header names including data name and line names.
- Return type:
- getwritervalues()[source]¶
Get current values for writing.
- Returns:
List of current values including data name, length, and line values.
- Return type:
- getwriterinfo()[source]¶
Get information about the data series.
- Returns:
Dictionary with name, timeframe, and compression info.
- Return type:
- frompackages = ()¶
- packages = ()¶
- class backtrader.OHLC[source]¶
Bases:
DataSeriesDataSeries with OHLCV lines but no datetime line.
- Lines:
close, low, high, open, volume, openinterest
- frompackages = ()¶
- packages = ()¶
- class backtrader.OHLCDateTime[source]¶
Bases:
OHLCDataSeries with datetime line plus OHLCV lines.
This is the full-featured data series for financial data.
- frompackages = ()¶
- packages = ()¶
- class backtrader.SimpleFilterWrapper[source]¶
Bases:
objectWrapper for filters added via .addfilter to turn them into processors.
Filters are callables which
Take data as an argument
Return False if the current bar has not triggered the filter
Return True if the current bar must be filtered
The wrapper takes the return value and executes the bar removal if needed to be
- exception backtrader.BacktraderError[source]¶
Bases:
ExceptionBase exception for all backtrader exceptions.
- exception backtrader.StrategySkipError[source]¶
Bases:
BacktraderErrorRequests the platform to skip this strategy for backtesting. To be raised during the initialization (
__init__) phase of the instance
- exception backtrader.DataError[source]¶
Bases:
BacktraderErrorRaised for data-feed problems: loading, parsing, or alignment failures.
- exception backtrader.BrokerError[source]¶
Bases:
BacktraderErrorRaised for broker/execution problems: cash, margin, or matching failures.
- exception backtrader.OrderError[source]¶
Bases:
BrokerErrorRaised for order-related problems: invalid size/price or rejected orders.
- exception backtrader.ConfigError[source]¶
Bases:
BacktraderErrorRaised for invalid configuration or parameter values.
- exception backtrader.ResearchError[source]¶
Bases:
BacktraderErrorBase class for stable, machine-readable research failures.
- default_code = 'RESEARCH_ERROR'¶
- exception backtrader.ResearchConfigError[source]¶
Bases:
ResearchError,ValueErrorInvalid or unsupported research configuration.
- default_code = 'INVALID_CONFIG'¶
- exception backtrader.DatasetError[source]¶
Bases:
ResearchError,ValueErrorInvalid, incomplete, or unsupported research input data.
- default_code = 'INVALID_DATASET'¶
- exception backtrader.DependencyError[source]¶
Bases:
ResearchError,ImportErrorA required runtime or public dependency is unavailable.
- default_code = 'DEPENDENCY_UNAVAILABLE'¶
- exception backtrader.DataQualityError[source]¶
Bases:
ResearchError,ValueErrorA requested quality bound is exceeded by the collected dataset.
- default_code = 'LOSS_LIMIT_EXCEEDED'¶
- exception backtrader.FactorComputationError[source]¶
Bases:
ResearchError,RuntimeErrorAn unexpected native factor or line calculation failure.
__cause__is kept by normal Python exception chaining. Callers should raise the result ofFactorComputationContext.wrap()withfromthe original exception so its type and traceback remain available.- default_code = 'FACTOR_COMPUTATION_FAILED'¶
- class backtrader.FactorComputationContext[source]¶
Bases:
objectDuck-typed strict policy context propagated through one native factor.
The core only needs the public
phase,asset_forandwrapprotocol. Feed and output-line references are retained by identity so an error is attributed only when one asset can be identified unambiguously.- factor¶
- phase¶
- failed¶
- error¶
- asset_for(operation=None)[source]¶
Resolve an asset from an operation or its direct data operands.
Cross-sectional operations touching multiple assets intentionally return
None; callers must not guess one member of the panel.
- wrap(exc, *, phase=None, asset=None)[source]¶
Build a safe structured error; preserve
excviaraise from.- Parameters:
exc (BaseException)
phase (str | None)
asset (str | None)
- Return type:
- class backtrader.Replayer[source]¶
Bases:
_BaseResamplerThis class replays data of a given timeframe to a larger timeframe.
It simulates the action of the market by slowly building up (for ex.) a daily bar from tick/seconds/minutes data
Only when the bar is complete will the “length” of the data be changed effectively delivering a closed bar
Params
Bar2edge (default: True)
Replays using time boundaries as the target of the closed bar.For example, with a “ticks -> 5 seconds” the resulting 5-second bars will be aligned to xx:00, xx:05, xx:10 …
Adjbartime (default: False)
Use the time at the boundary to adjust the time of the delivered resampled bar instead of the last seen timestamp. If resampling to “5 seconds” the time of the bar will be adjusted, for example, to hh:mm:05 even if the last seen timestamp was hh:mm:04.33
Note
Time will only be adjusted if “bar2edge” is True. It wouldn’t make sense to adjust the time if the bar has not been aligned to a boundary
- Note if this parameter is True, an extra tick with the adjusted
time will be introduced at the end of the replayed bar
Rightedge (default: True)
Use the right edge of the time boundaries to set the time.
If False and compressing to 5 seconds, the time of a resampled bar for seconds between hh:mm:00 and hh:mm:04 will be hh:mm:00 (the starting boundary
If True, the used boundary for the time will be hh:mm:05 (the ending boundary)
- params = (('bar2edge', True), ('adjbartime', False), ('rightedge', True))¶
- replaying = True¶
- __call__(data, fromcheck=False, forcedata=None)[source]¶
Process the data for replaying.
Manages bar replaying with session information and time alignment.
- Parameters:
data – The data source to replay.
fromcheck – Whether this is being called from a periodic check.
forcedata – Optional data source to force timing from.
- Returns:
True if a new bar was generated, False otherwise.
- Return type:
- class backtrader.Resampler[source]¶
Bases:
_BaseResamplerThis class resamples data of a given timeframe to a larger timeframe.
Params
Bar2edge (default: True)
Resamples using time boundaries as the target.For example, with a “ticks -> 5 seconds” the resulting 5-seconds bars will be aligned to xx:00, xx:05, xx:10 …
# When resampling, use time boundary as target, for example if ticks data wants to resample to 5 seconds, bars will be formed at xx:00, xx:05, xx:10
Adjbartime (default: True)
Use the time at the boundary to adjust the time of the delivered resampled bar instead of the last seen timestamp. If resampling to “5 seconds” the time of the bar will be adjusted, for example, to hh:mm:05 even if the last seen timestamp was hh:mm:04.33
- note::
Time will only be adjusted if “bar2edge” is True. It wouldn’t make sense to adjust the time if the bar has not been aligned to a boundary
# Adjust the last bar’s final time, when bar2edge is True, use the final boundary as the last bar’s time
Rightedge (default: True)
Use the right edge of the time boundaries to set the time.
If False and compressing to 5 seconds, the time of a resampled bar for seconds between hh:mm:00 and hh:mm:04 will be hh:mm:00 (the starting boundary
If True, the used boundary for the time will be hh:mm:05 (the ending boundary) # Whether to use the right time boundary, for example if time boundary is hh:mm:00:hh:mm:05, if set to True, will use hh:mm:05 # Set to False, will use hh:mm:00
- params = (('bar2edge', True), ('adjbartime', True), ('rightedge', True))¶
- replaying = False¶
- backtrader.num2date(x, tz=None, naive=True)[source]¶
x is a float value that gives the number of days (fraction part represents hours, minutes, seconds) since 0001-01-01 00:00:00 UTC plus one. The addition of one here is a historical artifact. Also, note that the Gregorian calendar is assumed; this is not universal practice. For details, see the module docstring. Return value is a: class:datetime instance in timezone tz (default to rcparams TZ value). If x is a sequence, a sequence of: class:datetime objects will be returned.
- backtrader.time2num(tm)[source]¶
Converts the hour/minute/second/microsecond part of tm (datetime.datetime or time) to a num
- backtrader.Localizer(tz)[source]¶
Add a localize method to a timezone object.
This function adds a localize method to tz objects that don’t have one, allowing consistent timezone localization across different timezone implementations.
- Parameters:
tz – Timezone object to add localize method to.
- Returns:
The same timezone object with a localize method added.
- class backtrader.DataBase[source]¶
Bases:
AbstractDataBaseFull-featured data feed class.
Inherits all functionality from AbstractDataBase. This is the standard data feed class for most use cases.
- frompackages = ()¶
- packages = ()¶
- class backtrader.FeedBase[source]¶
Bases:
objectBase class for feed containers.
Manages multiple data feeds and provides parameter processing without using metaclasses.
- __init__(**kwargs)[source]¶
Initialize the feed base.
- Parameters:
**kwargs – Keyword arguments for parameters.
- getdata(dataname, name=None, **kwargs)[source]¶
Get or create a data feed and add it to the managed datas.
- Parameters:
dataname – Data source identifier (filename, URL, etc.).
name – Display name for the data feed.
**kwargs – Additional parameters for the data feed.
- Returns:
The created or retrieved data feed instance.
- Return type:
- class backtrader.CSVDataBase[source]¶
Bases:
DataBaseBase class for classes implementing CSV DataFeeds
The class takes care of opening the file, reading the lines and tokenizing them.
Subclasses do only need to override:
_loadline(tokens)
The return value of
_loadline(True/False) will be the return value of_loadwhich has been overriden by this base class- f = None¶
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- preload()[source]¶
Preload all data from the CSV file.
Loads all available data and closes the file handle.
- frompackages = ()¶
- packages = ()¶
- class backtrader.CSVFeedBase[source]¶
Bases:
FeedBaseBase class for CSV feed containers.
Manages CSV data feeds with support for base path prefixing.
- class backtrader.DataClone[source]¶
Bases:
AbstractDataBaseClones an existing data feed.
Creates a new data feed that references an existing data feed. Useful for creating multiple views of the same data with different parameters or filters.
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- preload()[source]¶
Preload data from the source data feed.
After preloading, resets the source data’s position.
- advance(size=1, datamaster=None, ticks=True)[source]¶
Advance the data clone by the specified size.
- Parameters:
size – Number of bars to advance.
datamaster – Master data feed for synchronization (unused).
ticks – Whether to process tick data.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Filter[source]¶
Bases:
ParameterizedBaseBase class for data filters in backtrader.
Filters process data bars and can modify or reject them. Subclasses should override the next() method to implement custom filtering logic.
- _firsttime¶
Tracks if this is the first call.
This class has been refactored from MetaParams to the new ParameterizedBase system for Day 36-38 of the metaprogramming removal project.
- __init__(data_, **kwargs)[source]¶
Initialize the Filter.
- Parameters:
data – The data feed to filter.
**kwargs – Additional keyword arguments for parameters.
- __call__(data)[source]¶
Process a data bar through the filter.
- Parameters:
data – The data feed being filtered.
- class backtrader.LineActions[source]¶
Bases:
LineBuffer,LineActionsMixin,ParamsMixinBase class for Line Clases with different lines, derived from a LineBuffer
- plotlines = <object object>¶
- static __new__(cls, *args, **kwargs)[source]¶
Handle data processing for indicators and other LineActions objects
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- getindicators()[source]¶
Get list of indicators using this line actions object.
- Returns:
Empty list for base LineActions (override in subclasses).
- Return type:
- qbuffer(savemem=0)[source]¶
Enable queued buffer mode for memory-efficient storage.
- Parameters:
savemem – Memory saving mode (0=normal, >0=enable cache mode).
- static arrayize(obj)[source]¶
Convert an object to an array-compatible object.
- Parameters:
obj – Object to convert. Can be a value, iterable, or array-like.
- Returns:
The original object if it has an array attribute, otherwise a LineNum or PseudoArray wrapper.
- frompackages = ()¶
- packages = ()¶
- backtrader.throttled_warning(logger, key, msg, *args, every=100, window=60.0, exc_info=True)[source]¶
logger.warning with storm suppression (same contract as error).
- backtrader.cmp(a, b)[source]¶
Compare two values.
- Parameters:
a – First value to compare.
b – Second value to compare.
- Returns:
1 if a > b, 0 if a == b, -1 if a < b.
- Return type:
- class backtrader.Logic[source]¶
Bases:
LineActionsBase class for logical operations on line objects.
Handles argument conversion to arrays and manages minperiod propagation from operands.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- frompackages = ()¶
- packages = ()¶
- class backtrader.DivByZero[source]¶
Bases:
LogicThis operation is a Lines object and fills it values by executing a division on the numerator / denominator arguments and avoiding a division by zero exception by checking the denominator
- Params:
a: numerator (numeric or iterable object … mostly a Lines object)
b: denominator (numeric or iterable object … mostly a Lines object)
zero (def: 0.0): value to apply if division by zero is raised
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- once(start, end)[source]¶
Calculate all values at once with zero-division protection.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.DivZeroByZero[source]¶
Bases:
LogicThis operation is a Lines object and fills it values by executing a division on the numerator / denominator arguments and avoiding a division by zero exception or an indetermination by checking the denominator/numerator pair
- Params:
a: numerator (numeric or iterable object … mostly a Lines object)
b: denominator (numeric or iterable object … mostly a Lines object)
single (def: +inf): value to apply if division is x / 0
dual (def: 0.0): value to apply if division is 0 / 0
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- once(start, end)[source]¶
Calculate all values at once with zero/zero indetermination protection.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Cmp[source]¶
Bases:
LogicComparison operation that returns comparison results.
Compares two line objects and returns standard comparison values: -1 if a < b, 0 if a == b, 1 if a > b.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- once(start, end)[source]¶
Calculate all comparison values at once.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.CmpEx[source]¶
Bases:
LogicExtended comparison operation with three possible return values.
Compares two line objects and returns one of three values based on the comparison result: - r1 if a < b - r2 if a == b - r3 if a > b
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- once(start, end)[source]¶
Calculate all extended comparison values at once.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.If[source]¶
Bases:
LogicConditional selection operation.
Returns a value from a or b based on a condition: - Returns a if condition is True - Returns b if condition is False
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- once(start, end)[source]¶
Calculate all conditional values at once.
- Supports self-referencing patterns like:
self.lines.direction = bt.If(cond, 1, bt.If(cond2, -1, self.lines.direction(-1)))
For self-referencing patterns, processes bar-by-bar using next() semantics to ensure previously computed values are available for the next bar.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.MultiLogic[source]¶
Bases:
LogicBase class for operations that apply a function to multiple arguments.
The flogic attribute should be set to a callable that takes an iterable of values and returns a single result.
- once(start, end)[source]¶
Apply the logic function to all values across the specified range.
- Parameters:
start – Starting index for calculation.
end – Ending index for calculation.
- frompackages = ()¶
- packages = ()¶
- class backtrader.MultiLogicReduce[source]¶
Bases:
MultiLogicMultiLogic that uses functools.reduce for cumulative operations.
This class applies a reduction function cumulatively to all arguments, combining them into a single result.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Reduce[source]¶
Bases:
MultiLogicReduceGeneric reduction operation with a custom function.
Allows any reduction function to be applied to the arguments.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- frompackages = ()¶
- packages = ()¶
- class backtrader.And[source]¶
Bases:
MultiLogicReduceLogical AND operation across all arguments.
Returns True only if all input values are truthy.
- static flogic(x, y)¶
Logical AND operation for reduction.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Or[source]¶
Bases:
MultiLogicReduceLogical OR operation across all arguments.
Returns True if any input value is truthy.
- static flogic(x, y)¶
Logical OR operation for reduction.
- frompackages = ()¶
- packages = ()¶
- class backtrader.Max[source]¶
Bases:
MultiLogicMaximum operation across all arguments.
Returns the maximum value from all input lines.
- static flogic(values)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.Min[source]¶
Bases:
MultiLogicMinimum operation across all arguments.
Returns the minimum value from all input lines.
- static flogic(values)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.Sum[source]¶
Bases:
MultiLogicSum operation across all arguments.
Returns the sum of all input values using math.fsum for better floating point precision.
- static flogic(values)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.Any[source]¶
Bases:
MultiLogicAny operation across all arguments.
Returns True if any input value is truthy.
- flogic(iterable, /)¶
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
- frompackages = ()¶
- packages = ()¶
- class backtrader.All[source]¶
Bases:
MultiLogicAll operation across all arguments.
Returns True only if all input values are truthy.
- flogic(iterable, /)¶
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
- frompackages = ()¶
- packages = ()¶
- class backtrader.IndicatorBase[source]¶
Bases:
DataAccessorBase class for all indicators.
This class provides the foundation for creating custom indicators. It handles plot initialization and indicator type registration.
- _ltype¶
Set to IndType (0) to indicate this is an indicator.
- __init__(*args, **kwargs)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.LineIterator[source]¶
Bases:
LineIteratorMixin,LineSeriesBase class for all objects that iterate over time-series data.
LineIterator is the foundation for Indicators, Strategies, Observers, and other objects that process data bar-by-bar. It manages:
Multiple data feeds with automatic clock synchronization
Minimum period calculations before full processing begins
Execution phases: prenext -> nextstart -> next
Child lineiterator registration (indicators within strategies)
Plotting configuration via plotinfo and plotlines
- _nextforce¶
Force cerebro to run in next mode instead of runonce
- _mindatas¶
Minimum number of data feeds required (default: 1)
- _ltype¶
Line type (IndType=0, StratType=1, ObsType=2)
- plotinfo¶
Plotting configuration object
- plotlines¶
Line-specific plotting configuration
- Class Attributes:
IndType: Constant for indicator type (0) StratType: Constant for strategy type (1) ObsType: Constant for observer type (2)
- class PlotInfoObj[source]¶
Bases:
objectPlot information container for LineIterator objects.
This class stores plotting configuration attributes that control how the LineIterator is displayed in plots.
- __init__()[source]¶
Initialize plotinfo with default values.
Sets up default plotting attributes including subplot position, plot name, and various display options.
- get(key, default=None)[source]¶
Standard get method for compatibility.
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotinfo = <backtrader.lineiterator.LineIterator.PlotInfoObj object>¶
- class PlotLinesObj[source]¶
Bases:
objectPlot lines configuration container for LineIterator objects.
This class stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.
- get(key, default=None)[source]¶
Get plotlines attribute value.
- Parameters:
key – Attribute name.
default – Default value if attribute not found.
- Returns:
The attribute value or default.
- plotlines = <backtrader.lineiterator.LineIterator.PlotLinesObj object>¶
- IndType = 0¶
- StratType = 1¶
- ObsType = 2¶
- static __new__(cls, *args, **kwargs)[source]¶
Create a new LineIterator instance.
This method replaces the metaclass functionality for creating LineIterator instances. It initializes basic attributes, sets up the lines collection, and assigns owner references.
- Parameters:
*args – Positional arguments including data feeds.
**kwargs – Keyword arguments for parameter initialization.
- Returns:
The newly created instance.
- Return type:
- __init__(*args, **kwargs)¶
- stop()[source]¶
Called when backtesting stops.
This method ensures TestStrategy chkmin is handled properly. Can be overridden in subclasses for cleanup operations.
- getindicators()[source]¶
Get all indicators registered with this lineiterator.
- Returns:
List of all registered indicators.
- Return type:
- getobservers()[source]¶
Get all observers registered with this lineiterator.
- Returns:
List of all registered observers.
- Return type:
- addindicator(indicator)[source]¶
Add an indicator to this lineiterator.
- Parameters:
indicator – The indicator instance to add.
- bindlines(owner=None, own=None)[source]¶
Bind lines from owner to lines from own.
This creates line bindings that automatically update when the source line changes.
- Parameters:
owner – Index or name of the owner’s line(s).
own – Index or name of this object’s line(s).
- Returns:
Returns self for method chaining.
- Return type:
self
- bind2lines(owner=None, own=None)¶
Bind lines from owner to lines from own.
This creates line bindings that automatically update when the source line changes.
- Parameters:
owner – Index or name of the owner’s line(s).
own – Index or name of this object’s line(s).
- Returns:
Returns self for method chaining.
- Return type:
self
- bind2line(owner=None, own=None)¶
Bind lines from owner to lines from own.
This creates line bindings that automatically update when the source line changes.
- Parameters:
owner – Index or name of the owner’s line(s).
own – Index or name of this object’s line(s).
- Returns:
Returns self for method chaining.
- Return type:
self
- preonce(start, end)[source]¶
Process bars before minimum period is reached in runonce mode.
- Parameters:
start – Starting index.
end – Ending index.
- oncestart(start, end)[source]¶
Called once when minimum period is first reached in runonce mode.
This method is the runonce equivalent of nextstart(). It handles the transition between preonce() and once() phases.
- Parameters:
start – Starting index for processing.
end – Ending index for processing.
- once(start, end)[source]¶
Process bars in runonce mode.
- Parameters:
start – Starting index.
end – Ending index.
- prenext()[source]¶
Called before minimum period is reached.
This method is called for each bar until the minimum period required for all indicators is satisfied. Override this method to implement custom logic during this phase.
- nextstart()[source]¶
Called once when minimum period is first reached.
This method is called exactly once when the minimum period required for all data feeds and indicators has been satisfied. The default implementation calls next().
This is the transition point between prenext() and next() phases.
- qbuffer(savemem=0)[source]¶
Enable memory saving mode for lines and indicators.
- Parameters:
savemem – Memory saving level. 0: No memory saving 1: Save memory for all lines and indicators -1: Don’t save for indicators at strategy level -2: Also don’t save for indicators with plot=False
- home()[source]¶
Reset lines and all sub-indicator lines to home position.
Extends LineSeries.home() to recursively reset sub-indicators so that after _once() computes all arrays, every indicator in the tree is back at position -1 and ready for _oncepost() replay.
- advance(size=1)[source]¶
Advance the line position by the specified size.
- Parameters:
size – Number of steps to advance (default: 1).
- size()[source]¶
Return the number of lines in this LineIterator.
- Returns:
Number of lines.
- Return type:
- frompackages = ()¶
- packages = ()¶
- class backtrader.Lines[source]¶
Bases:
objectDefines an “array” of lines which also has most of the interface of a LineBuffer class (forward, rewind, advance…).
This interface operations are passed to the lines held by self
The class can autosubclass itself (_derive) to hold new lines keeping them in the defined order.
- classmethod getlinealiases()[source]¶
Get all line aliases for this class.
- Returns:
Tuple of line alias names.
- Return type:
- itersize()[source]¶
Return an iterator over the lines.
- Returns:
Iterator over lines from index 0 to size().
- Return type:
iterator
- __init__(initlines=None)[source]¶
Create the lines recording during “_derive” or else use the provided “initlines”
- __iter__()[source]¶
Allow proper iteration over lines without calling __getitem__ for each index.
- Returns:
Iterator over the lines list.
- Return type:
iterator
- __len__()[source]¶
Return the number of lines.
- Returns:
Number of lines in the lines list.
- Return type:
- size()[source]¶
Return the number of lines excluding extra lines.
- Returns:
Number of main lines.
- Return type:
- fullsize()[source]¶
Return the total number of lines including extra lines.
- Returns:
Total number of lines.
- Return type:
- __getitem__(line)[source]¶
Get a line by index.
This method implements dynamic line creation - accessing an index beyond the current number of lines will create new lines up to a reasonable limit.
- Parameters:
line – Index of the line to retrieve.
- Returns:
- The line at the specified index, or None if
the index exceeds the maximum reasonable limit.
- Return type:
- __setitem__(line, value)[source]¶
Set a line by index with proper binding support.
This method handles different types of values: - Scalar values: Creates a LineNum (constant line) - Indicators: Binds the indicator’s output line to the parent’s line - LineBuffers: Adds binding for value propagation - Iterables: Creates a new line from the iterable values
- Parameters:
line – Line index or name to set.
value – Value to assign (scalar, indicator, or iterable).
- forward(value=nan, size=1)[source]¶
Forward all lines by the specified size.
- Parameters:
value – Value to use for forwarding (default: NAN).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move all lines backward by the specified size.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind all lines by decreasing idx and lencount.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend all lines with additional positions.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- advance(size=1)[source]¶
Advance all lines by increasing idx.
- Parameters:
size – Number of positions to advance (default: 1).
- buflen(line=0)[source]¶
Get the buffer length of a specific line.
- Parameters:
line – Index of the line (default: 0).
- Returns:
Buffer length of the specified line.
- Return type:
- __getattr__(name)[source]¶
Handle missing attributes, especially _owner for observers.
PERF OPTIMIZATIONS: - Class-level frozenset for critical attrs (was recreated every call) - name[0] == ‘_’ instead of startswith (2-3x faster) - Removed inspect.currentframe() stack walk (extremely expensive) - Reduced hasattr chains with try/except EAFP
- class backtrader.AutoInfoClass[source]¶
Bases:
objectDynamic class for storing parameter and info key-value pairs.
This class provides a flexible mechanism for storing and retrieving configuration data (parameters, plot info, etc.) with support for inheritance and derivation.
- Class Methods:
_getpairsbase: Get base class pairs as OrderedDict. _getpairs: Get all pairs (including inherited) as OrderedDict. _getrecurse: Check if recursive derivation is enabled. _derive: Create a derived class with additional parameters. _getkeys: Get all parameter keys. _getdefaults: Get all default values. _getitems: Get all key-value pairs. _gettuple: Get pairs as tuple of tuples.
- Instance Methods:
isdefault: Check if a parameter has its default value. notdefault: Check if a parameter differs from default. get/_get: Get a parameter value with optional default.
- class backtrader.IndicatorRegistry[source]¶
Bases:
objectRegistry to manage indicator classes and provide caching functionality.
This class replaces the metaclass-based indicator registration and caching mechanism from the original backtrader implementation.
- classmethod register(name, indicator_cls)[source]¶
Register an indicator class in the registry.
- Parameters:
name – Name of the indicator class
indicator_cls – The indicator class to register
- classmethod usecache(onoff)[source]¶
Enable or disable indicator caching.
- Parameters:
onoff – If True, enable caching; if False, disable it
- classmethod get_cached_or_create(indicator_cls, *args, **kwargs)[source]¶
Get cached indicator instance or create new one.
- Parameters:
indicator_cls – The indicator class to instantiate
*args – Positional arguments for the indicator
**kwargs – Keyword arguments for the indicator
- Returns:
Cached indicator instance if available and caching enabled, otherwise a new indicator instance
- class backtrader.Indicator[source]¶
Bases:
IndicatorBaseBase class for all technical indicators in Backtrader.
This class provides the foundation for creating custom indicators. It manages line data, minimum periods, and calculation logic. Indicators inherit from IndicatorBase and integrate with the LineIterator system for data flow.
- _ltype¶
Line type set to IndType (0) for indicators
- csv¶
Whether to output this indicator to CSV (default: False)
- aliased¶
Whether this indicator has an alias name
- csv = False¶
- __getitem__(ago)[source]¶
CRITICAL FIX: Forward item access to the first line (e.g., sma line)
For indicators with named lines like SMA (which has lines.sma), accessing indicator[0] should return the value from the first line, not the indicator’s own array.
- aliased = False¶
- classmethod __init_subclass__(**kwargs)[source]¶
Handle subclass registration and initialization.
This method is called when a subclass of Indicator is created. It performs: 1. Lines creation using Lines infrastructure 2. Automatic registration in IndicatorRegistry 3. Alias handling for module-level access 4. next/once method setup for calculation modes
- Parameters:
**kwargs – Additional keyword arguments
- advance(size=1)[source]¶
Advance indicator lines when data length is less than clock length.
Also advances sub-indicators so that during _oncepost() replay every level of the indicator tree stays in sync (fixes runonce ATR/SMMA index mismatch when an indicator uses sub_ind[0] in next()).
- Parameters:
size – Number of steps to advance (default: 1)
- preonce_via_prenext(start, end)[source]¶
Implement preonce using prenext for batch calculation.
This is a generic implementation if prenext is overridden but preonce is not. It loops through the range and calls prenext for each step.
- Parameters:
start – Starting index
end – Ending index
- oncestart_via_nextstart(start, end)[source]¶
Implement oncestart using nextstart for batch calculation.
This is used when nextstart is overridden but oncestart is not.
- Parameters:
start – Starting index
end – Ending index
- once_via_next(start, end)[source]¶
Implement once using next for batch calculation.
This is used when next is overridden but once is not. It loops through the range and calls next for each step.
- Parameters:
start – Starting index
end – Ending index
- frompackages = ()¶
- packages = ()¶
- class backtrader.LinePlotterIndicatorBase[source]¶
Bases:
typeBase class for indicators that plot multiple lines.
Note: These classes are not currently used in the project. They are kept for compatibility with the original backtrader.
- class backtrader.LinePlotterIndicator[source]¶
Bases:
Indicator,LinePlotterIndicatorBaseIndicator that plots multiple lines.
Note: This class is not currently used in the project.
- frompackages = ()¶
- packages = ()¶
- class backtrader.ContextVar¶
Bases:
object- get()¶
Return a value for the context variable for the current context.
- If there is no value for the variable in the current context, the method will:
return the value of the default argument of the method, if provided; or
return the default value for the context variable, if it was created with one; or
raise a LookupError.
- name¶
- reset(token, /)¶
Reset the context variable.
The variable is reset to the value it had before the ContextVar.set() that created the token was used.
- set(value, /)¶
Call to set a new value for the context variable in the current context.
The required value argument is the new value for the context variable.
Returns a Token object that can be used to restore the variable to its previous value via the ContextVar.reset() method.
- class backtrader.islice¶
Bases:
objectislice(iterable, stop) –> islice object islice(iterable, start, stop[, step]) –> islice object
Return an iterator whose next() method returns selected values from an iterable. If start is specified, will skip all preceding elements; otherwise, start defaults to zero. Step defaults to one. If specified as another value, step determines how many values are skipped between successive calls. Works like a slice() on a list but returns an iterator.
- class backtrader.repeat¶
Bases:
objectrepeat(object [,times]) -> create an iterator which returns the object for the specified number of times. If not specified, returns the object endlessly.
- class backtrader.LineRoot[source]¶
Bases:
LineRootMixin,BaseMixinDefines a common base and interfaces for Single and Multiple LineXXX instances
Period management Iteration management Operation (dual/single operand) Management Rich Comparison operator definition
- IndType = 0¶
- StratType = 1¶
- ObsType = 2¶
- setminperiod(minperiod)[source]¶
Direct minperiod manipulation.It could be used, for example, by a strategy to not wait for all indicators to produce a value
- updateminperiod(minperiod)[source]¶
Update the minperiod if needed. The minperiod will have been calculated elsewhere and has to take over if greater that self’s
- nextstart()[source]¶
It will be called when the minperiod phase is over for the 1st post-minperiod value. Only called once and defaults to automatically calling next
- class backtrader.LineRootMixin[source]¶
Bases:
objectMixin to provide LineRoot functionality without metaclass
- class backtrader.LineSingle[source]¶
Bases:
LineRootBase class for single-line objects.
LineSingle is the base class for objects that represent a single line of time-series data. It provides the foundational interface for period management and operations on individual lines.
Example
>>> line = LineSingle() >>> line.addminperiod(5) # Require 5 periods before valid
- backtrader.throttled_error(logger, key, msg, *args, every=100, window=60.0, exc_info=True)[source]¶
logger.error with storm suppression: first full, repeats summarized.
- class backtrader.LineBuffer[source]¶
Bases:
LineSingle,LineRootMixinLineBuffer defines an interface to an “array.array” (or list) in which index 0 points to the item which is active for input and output.
Positive indices fetch values from the past (left-hand side) Negative indices fetch values from the future (if the array has been extended on the right-hand side)
With this behavior, no index has to be passed around to entities which have to work with the current value produced by other entities: the value is always reachable at “0”.
Likewise, storing the current value produced by “self” is done at 0.
Additional operations to move the pointer (home, forward, extend, rewind, advance getzero) are provided
The class can also hold “bindings” to other LineBuffers. When a value is set in this class, it will also be set in the binding.
- UnBounded = 0¶
- QBuffer = 1¶
- __init__()[source]¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- get_idx()[source]¶
Get the current index position.
- Returns:
The current index in the buffer.
- Return type:
- set_idx(idx, force=False)[source]¶
Set the index position.
- Parameters:
idx – The new index value.
force – If True, force set even in QBuffer mode at lenmark.
Note
In QBuffer mode, when at lenmark, the index stays at 0 unless force is True. This allows resampling operations.
- property idx¶
Get the current index position.
- Returns:
The current index in the buffer.
- Return type:
- qbuffer(savemem=0, extrasize=0)[source]¶
Enable queued buffer mode for memory-efficient storage.
- Parameters:
savemem – Memory saving mode (0=normal, >0=enable cache mode).
extrasize – Extra buffer size for resampling/replay operations.
Note
In QBuffer mode, only the last maxlen values are kept, reducing memory usage for long backtests.
- getindicators()[source]¶
Get list of indicators using this line buffer.
- Returns:
Empty list for base LineBuffer (override in subclasses).
- Return type:
- minbuffer(size)[source]¶
The linebuffer must guarantee the minimum requested size to be available.
In non-dqbuffer mode, this is always true (of course, until data is filled at the beginning, there are fewer values, but minperiod in the framework should account for this.
In dqbuffer mode, the buffer has to be adjusted for this if currently less than requested
- __len__()[source]¶
Return the linebuffer’s length counter.
Performance optimization: Restore master branch’s simple implementation - Directly return self.lencount (pre-calculated length value) - Remove all recursion checks, hasattr calls and complex logic - Performance improvement: from 0.611s to ~0.05s (92% improvement)
- buflen()[source]¶
Real data that can be currently held in the internal buffer
The internal buffer can be longer than the actual stored data to allow for “lookahead” operations. The real amount of data that is held/can be held in the buffer is returned
- __getitem__(ago)[source]¶
Get the value at a specified offset - optimized for hot path.
- Parameters:
ago (int) – Relative offset from current index (0=current, -1=previous, 1=next)
- Returns:
Value at the specified position
- get(ago=0, size=1)[source]¶
Returns a slice of the array relative to ago
- Keyword Arguments:
ago (int) – Point of the array to which size will be added
size (to return the slice) – size of the slice to return,
negative (can be positive or)
If size is positive ago will mark the end of the iterable and vice versa if size is negative
- Returns:
A slice of the underlying buffer
- getzeroval(idx=0)[source]¶
Returns a single value of the array relative to the real zero of the buffer
- getzero(idx=0, size=1)[source]¶
Returns a slice of the array relative to the real zero of the buffer
- __setitem__(ago, value)[source]¶
Sets a value at position “ago” and executes any associated bindings
- Keyword Arguments:
ago (int) – Point of the array to which size will be added to return
slice (the)
value (variable) – value to be set
Performance optimization: Use pre-calculated flags to avoid repeated hasattr and string operations
- set(value, ago=0)[source]¶
Sets a value at position “ago” and executes any associated bindings
- Keyword Arguments:
value (variable) – value to be set
ago (int) – Point of the array to which size will be added to return
slice (the)
PERF: Uses pre-calculated _is_datetime_line and _default_value flags instead of hasattr/isinstance checks on every call.
- home()[source]¶
Rewinds the logical index to the beginning
The underlying buffer remains untouched and the actual len can be found out with buflen
- forward(value=nan, size=1)[source]¶
Moves the logical index forward and enlarges the buffer as much as needed
- Keyword Arguments:
value (variable) – value to be set in new positions
size (int) – How many extra positions to enlarge the buffer
- backwards(size=1, force=False)[source]¶
Moves the logical index backwards and reduces the buffer as much as needed
- safe_backwards(size=1)[source]¶
Safely move the index backwards without raising errors.
- Parameters:
size – Number of positions to move backwards.
- Returns:
True if index is still >= 0 after moving, False otherwise.
- Return type:
- rewind(size=1)[source]¶
Rewind the buffer by decreasing idx and lencount.
- Parameters:
size – Number of positions to rewind.
- extend(value=nan, size=0)[source]¶
Extends the underlying array with positions that the index will not reach
- Keyword Arguments:
value (variable) – value to be set in new positins
size (int) – How many extra positions to enlarge the buffer
The purpose is to allow for lookahead operations or to be able to set values in the buffer “future”
- addbinding(binding)[source]¶
Adds another line binding
- Keyword Arguments:
binding (LineBuffer) – another line that must be set when this line
value (becomes a)
- plot(idx=0, size=None)[source]¶
Returns a slice of the array relative to the real zero of the buffer
- Keyword Arguments:
This is a variant of getzero that unless told otherwise returns the entire buffer, which is usually the idea behind plottint (all must be plotted)
- Returns:
A slice of the underlying buffer
- bind2lines(binding=0)[source]¶
Stores a binding to another line. “Binding” can be an index or a name
- bind2line(binding=0)¶
Stores a binding to another line. “Binding” can be an index or a name
- __call__(ago=None)[source]¶
Returns either the current value (ago=None) or a delayed LineBuffer that fetches the value which is “ago” periods before. Useful to have the closing price 5 bars before: close(-5)
- datetime(ago=0, tz=None, naive=True)[source]¶
Get the datetime value at the specified offset.
- Parameters:
ago – Number of periods to look back (0=current, -1=previous).
tz – Timezone to apply. If None, uses self._tz.
naive – If True, return naive datetime without timezone info.
- Returns:
Datetime object representing the timestamp.
- Return type:
- Raises:
IndexError – If the requested position is out of bounds for data feeds.
- date(ago=0, tz=None, naive=True)[source]¶
Get the date component of the datetime value at the specified offset.
- Parameters:
ago – Number of periods to look back (0=current, -1=previous).
tz – Timezone to apply. If None, uses self._tz.
naive – If True, return naive date without timezone info.
- Returns:
Date object representing the date portion of the timestamp.
- Return type:
- Raises:
IndexError – If the requested position is out of bounds for data feeds.
- time(ago=0, tz=None, naive=True)[source]¶
Get the time component of the datetime value at the specified offset.
- Parameters:
ago – Number of periods to look back (0=current, -1=previous).
tz – Timezone to apply. If None, uses self._tz.
naive – If True, return naive time without timezone info.
- Returns:
Time object representing the time portion of the timestamp.
- Return type:
time
- tm_raw(ago=0)[source]¶
Returns a localtime/gmtime like time.struct_time object which is compatible with strftime formatting.
The time zone of the struct_time is naive
- tm(ago=0)[source]¶
Returns a localtime/gmtime like time.struct_time object which is compatible with strftime formatting.
The time zone of the struct_time is naive
- tm_lt(other, ago=0)[source]¶
Returns True if the time carried by this line’s index “ago” is lower than the time carried by the “other” line
- tm_le(other, ago=0)[source]¶
Returns True if the time carried by this line’s index “ago” is lower than or equal to the time carried by the “other” line
- tm_eq(other, ago=0)[source]¶
Returns True if the time carried by this line’s index “ago” is equal to the time carried by the “other” line
- tm_gt(other, ago=0)[source]¶
Returns True if the time carried by this line’s index “ago” is greater than the time carried by the “other” line
- tm_ge(other, ago=0)[source]¶
Returns True if the time carried by this line’s index “ago” is greater than or equal to the time carried by the “other” line
- class backtrader.LineActionsCache[source]¶
Bases:
objectCache system for LineActions to avoid repetitive calculations
- class backtrader.LineActionsMixin[source]¶
Bases:
objectMixin to provide LineActions functionality without metaclass
- class backtrader.PseudoArray[source]¶
Bases:
objectWrapper for non-array iterables to provide array-like access.
This class wraps iterables (including itertools.repeat) and provides array-like indexing access. It handles cases where the wrapped object doesn’t support direct indexing.
- wrapped¶
The wrapped iterable object.
- _minperiod¶
Minimum period inherited from the wrapped object.
Example
>>> from itertools import repeat >>> pseudo = PseudoArray(repeat(1.0)) >>> print(pseudo[0]) 1.0
- backtrader.LineDelay(a, ago=0, **kwargs)[source]¶
Create a delayed line object.
- Parameters:
a – Source line object.
ago – Number of periods to delay. Negative for lookback.
**kwargs – Additional keyword arguments.
- Returns:
A delayed line object.
- Return type:
_LineDelay or _LineForward
- backtrader.LineNum(num)[source]¶
Create a constant line from a number.
- Parameters:
num – The constant value.
- Returns:
A line object that always returns the constant value.
- Return type:
_LineDelay
- class backtrader.LinesOperation[source]¶
Bases:
LineActionsOperation between two line objects (binary operations).
This class represents binary operations (addition, subtraction, etc.) between two line objects. The result is a new line that contains the element-wise operation result.
- operation¶
The binary function to apply (e.g., operator.add).
- a¶
First operand (left-hand side).
- b¶
Second operand (right-hand side).
- r¶
If True, reverse operation order.
- _parent_a¶
Parent indicator for operand a.
- _parent_b¶
Parent indicator for operand b.
Example
>>> result = LinesOperation(indicator1, indicator2, operator.sub) >>> # result[0] = indicator1[0] - indicator2[0]
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- __getitem__(ago)[source]¶
Get value at the specified offset.
In runonce mode, the array is pre-computed by once(), so use it directly. Falls back to dynamic computation only if the array is not populated.
- next()[source]¶
Calculate and set the operation result for the current bar.
Performs the binary operation on the current values of both operands and stores the result at position 0.
- once(start, end)[source]¶
Calculate operation results in batch mode (runonce).
- Parameters:
start – Starting index.
end – Ending index.
- frompackages = ()¶
- packages = ()¶
- class backtrader.LineOwnOperation[source]¶
Bases:
LineActionsOperation on a single line object (unary operations).
This class represents unary operations (negation, absolute value, etc.) on a single line object. The result is a new line that contains the element-wise operation result.
- operation¶
The unary function to apply (e.g., operator.neg).
- a¶
The operand (line object).
- _parent_a¶
Parent indicator for the operand.
Example
>>> result = LineOwnOperation(indicator, operator.neg) >>> # result[0] = -indicator[0]
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- frompackages = ()¶
- packages = ()¶
- __getitem__(ago)[source]¶
CRITICAL FIX: Override __getitem__ to compute value dynamically from source operand.
- next()[source]¶
Calculate and set the unary operation result for the current bar.
Performs the unary operation on the current value of the operand and stores the result at position 0.
- backtrader.LineSeriesMaker(arg, slave=False)[source]¶
Create a LineSeries from a single line or return existing LineSeries.
- Parameters:
arg – A single line or LineSeries object.
slave – If True, mark the created stub as a slave.
- Returns:
The original LineSeries if arg is already a LineSeries, otherwise a LineSeriesStub wrapping the line.
- class backtrader.DotDict[source]¶
Bases:
dictDictionary with attribute-style access.
Allows accessing dictionary values as attributes using dot notation. If an attribute is not found in the usual places, the dict itself is checked.
Example
>>> d = DotDict() >>> d['key'] = 'value' >>> print(d.key) 'value'
- class backtrader.LineIteratorMixin[source]¶
Bases:
objectMixin for LineIterator that handles data argument processing.
This mixin provides the donew() method which processes constructor arguments to extract and properly configure data feeds before instance creation.
- classmethod __init_subclass__(**kwargs)[source]¶
Handle subclass initialization.
- Parameters:
**kwargs – Additional keyword arguments
- classmethod donew(*args, **kwargs)[source]¶
Process data arguments and filter them before instance creation.
This method scans the positional arguments to identify data feeds (LineRoot, LineSeries, LineBuffer objects) and separates them from regular parameters. Data feeds are converted to LineSeriesMaker objects and stored in the datas attribute.
- Parameters:
*args – Positional arguments that may include data feeds
**kwargs – Keyword arguments for instance creation
- Returns:
(created_object, remaining_args, kwargs)
- Return type:
- classmethod dopreinit(_obj, *args, **kwargs)[source]¶
Handle pre-initialization setup.
This method performs setup after instance creation but before __init__: 1. Sets up datas if not already set 2. Configures clock from first data feed or owner 3. Calculates minimum period from data sources
- Parameters:
_obj – The instance being initialized
*args – Remaining positional arguments
**kwargs – Remaining keyword arguments
- Returns:
(_obj, args, kwargs)
- Return type:
- classmethod dopostinit(_obj, *args, **kwargs)[source]¶
Handle post-initialization setup.
This method performs final setup after __init__ completes: 1. Recalculates minimum period from lines 2. Propagates minperiod to all lines 3. Registers indicator with owner
- Parameters:
_obj – The instance being finalized
*args – Remaining positional arguments
**kwargs – Remaining keyword arguments
- Returns:
(_obj, args, kwargs)
- Return type:
- class backtrader.DataAccessor[source]¶
Bases:
LineIteratorBase class for accessing data feed price series.
This class provides convenient aliases for accessing different price series from data feeds (open, high, low, close, volume, etc.).
- PriceClose¶
Alias for DataSeries.Close
- PriceLow¶
Alias for DataSeries.Low
- PriceHigh¶
Alias for DataSeries.High
- PriceOpen¶
Alias for DataSeries.Open
- PriceVolume¶
Alias for DataSeries.Volume
- PriceOpenInteres¶
Alias for DataSeries.OpenInterest
- PriceDateTime¶
Alias for DataSeries.DateTime
- PriceClose = 0¶
- PriceLow = 1¶
- PriceHigh = 2¶
- PriceOpen = 3¶
- PriceVolume = 4¶
- PriceOpenInteres = 5¶
- PriceDateTime = 6¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.ObserverBase[source]¶
Bases:
DataAccessorBase class for all observers.
Observers are similar to indicators but are used primarily for monitoring and recording strategy state rather than generating trading signals.
- _ltype¶
Set to ObsType (2) to indicate this is an observer.
- _mindatas¶
Set to 0 because observers don’t consume data arguments.
- classmethod __init_subclass__(**kwargs)[source]¶
Automatically wrap __init__ methods of observer subclasses to handle extra arguments
- frompackages = ()¶
- packages = ()¶
- class backtrader.StrategyBase[source]¶
Bases:
DataAccessorBase class for all trading strategies.
This class provides the foundation for creating custom trading strategies. It handles indicator registration, data management, and the once() method override for proper backtesting behavior.
- _ltype¶
Set to StratType (1) to indicate this is a strategy.
- static __new__(cls, *args, **kwargs)[source]¶
Ensure strategies get proper data setup by directly calling LineIterator.__new__.
- once(start, end)[source]¶
CRITICAL FIX: Override once() for strategies to do nothing.
For strategies, once() should NOT call next() because next() is called by _oncepost() in the cerebro event loop. If we call next() here, it will be called twice (once in _once and once in _oncepost).
- oncestart(start, end)[source]¶
CRITICAL FIX: Override oncestart() for strategies to do nothing.
For strategies, oncestart() should NOT call nextstart()/next() because next() is called by _oncepost() in the cerebro event loop. If we call nextstart()->next() here, it will be called twice (once in _once and once in _oncepost).
- __init__(*args, **kwargs)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.SingleCoupler[source]¶
Bases:
LineActionsCoupler for single line operations.
This class couples a single line source with a clock, allowing synchronization of data from different sources.
- cdata¶
The data source being coupled.
- dlen¶
Current data length.
- val¶
Current value.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- next()[source]¶
Advance the coupler to the next bar.
Updates the current value if new data is available.
- frompackages = ()¶
- packages = ()¶
- class backtrader.MultiCoupler[source]¶
Bases:
LineIteratorCoupler for multiple line operations.
This class couples multiple line sources with a clock, allowing synchronization of data from different sources.
- dlen¶
Current data length.
- dsize¶
Number of lines being coupled.
- dvals¶
Current values for all lines.
- frompackages = ()¶
- packages = ()¶
- __init__(*args, **kwargs)¶
- backtrader.LinesCoupler(cdata, clock=None, **kwargs)[source]¶
Create a coupler for line(s) to synchronize data from different sources.
This function creates either a SingleCoupler or MultiCoupler depending on whether the input is a single line or multiple lines.
- Parameters:
cdata – The data source to couple. Can be a single line or multi-line object.
clock – Optional clock for synchronization. If None, tries to find clock from cdata.
**kwargs – Additional keyword arguments passed to the coupler.
- Returns:
A coupler instance for the data source.
- Return type:
- backtrader.LineCoupler(cdata, clock=None, **kwargs)¶
Create a coupler for line(s) to synchronize data from different sources.
This function creates either a SingleCoupler or MultiCoupler depending on whether the input is a single line or multiple lines.
- Parameters:
cdata – The data source to couple. Can be a single line or multi-line object.
clock – Optional clock for synchronization. If None, tries to find clock from cdata.
**kwargs – Additional keyword arguments passed to the coupler.
- Returns:
A coupler instance for the data source.
- Return type:
- class backtrader.LineMultiple[source]¶
Bases:
LineRootBase class for objects containing multiple lines.
LineMultiple is the base class for objects that manage multiple line instances, such as indicators with multiple outputs. It provides common functionality for period management, staging, and operations across all contained lines.
- lines¶
Collection of line objects managed by this instance.
- _ltype¶
Line type indicator (None for base LineMultiple).
- _clock¶
Clock reference for synchronization.
- _lineiterators¶
Dictionary tracking registered lineiterators.
Example
>>> class MyIndicator(LineMultiple): ... lines = ('output1', 'output2')
- __init__()[source]¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- reset()[source]¶
Reset the line multiple to initial state.
Resets the operation stage to stage 1 and resets all managed lines to their initial state. This is typically called before starting a new backtest run.
- class backtrader.MinimalData[source]¶
Bases:
objectMinimal data replacement for missing data0, data1, etc. attributes.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- __init__()[source]¶
Initialize minimal data with pre-filled array.
Creates a pre-filled array to prevent index errors when accessing missing data attributes.
- __getitem__(key)[source]¶
Get item from the array at the specified index offset.
- Parameters:
key – Index offset from the current position (_idx).
- Returns:
Value at the computed index, or 0.0 if index is invalid.
- Return type:
- class backtrader.MinimalOwner[source]¶
Bases:
objectMinimal owner implementation for observers and analyzers.
Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.
- class backtrader.MinimalClock[source]¶
Bases:
objectMinimal clock implementation used as a fallback when _clock is not set.
CRITICAL FIX: Defined at module level to support pickling for multiprocessing. Previously this was defined as a local class inside __getattribute__, which caused pickle failures during strategy optimization.
- __init__()[source]¶
Initialize minimal clock with default attributes.
Sets up basic attributes needed for clock functionality when the actual clock is not available.
- __len__()[source]¶
Return the length of the minimal clock.
- Returns:
Always returns 0 for minimal clock.
- Return type:
- class backtrader.LineAlias[source]¶
Bases:
objectDescriptor class that store a line reference and returns that line from the owner
- Keyword Arguments:
line (int) – reference to the line that will be returned from
buffer (owner's lines)
As a convenience, the __set__ method of the descriptor is used not set the line reference because this is a constant along the live of the descriptor instance, but rather to set the value of the line at the instant ‘0’ (the current one)
- __init__(line)[source]¶
Initialize the line alias descriptor.
- Parameters:
line – Index of the line in the owner’s lines buffer.
- class backtrader.LineSeriesMixin[source]¶
Bases:
objectMixin to provide LineSeries functionality without metaclass
- class backtrader.LineSeriesStub[source]¶
Bases:
LineSeriesSimulates a LineMultiple object based on LineSeries from a single line
The index management operations are overriden to take into account if the line is a slave, i.e.:
The line reference is a line from many in a LineMultiple object
Both the LineMultiple object and the Line are managed by the same object
Were slave not to be taken into account, the individual line would, for example, be advanced twice:
Once under when the LineMultiple object is advanced (because it advances all lines it is holding
Again as part of the regular management of the object holding it
- extralines = 1¶
- __init__(*args, **kwargs)¶
Initialize a LineMultiple instance.
Sets up the internal state for managing multiple lines, including line type indicator, lines collection, clock reference, and line iterator tracking.
- Initializes:
_ltype: Line type indicator (None for base LineMultiple). lines: Collection of line objects (creates if not exists). _clock: Clock reference for synchronization. _lineiterators: Dictionary tracking registered lineiterators. _minperiod: Minimum period requirement (defaults to 1).
- forward(value=nan, size=1)[source]¶
Forward the line if not a slave.
- Parameters:
value – Value to use for forwarding (default: NAN).
size – Number of positions to forward (default: 1).
- backwards(size=1, force=False)[source]¶
Move the line backward if not a slave.
- Parameters:
size – Number of positions to move backward (default: 1).
force – If True, force the backward movement.
- rewind(size=1)[source]¶
Rewind the line if not a slave.
- Parameters:
size – Number of positions to rewind (default: 1).
- extend(value=0.0, size=0)[source]¶
Extend the line if not a slave.
- Parameters:
value – Value to use for extension (default: 0.0).
size – Number of positions to add (default: 0).
- advance(size=1)[source]¶
Advance the line if not a slave.
- Parameters:
size – Number of positions to advance (default: 1).
- qbuffer()[source]¶
Queue buffer operation (no-op for stub).
This method is a no-op in the stub implementation since the underlying line manages its own buffering.
- minbuffer(size)[source]¶
Set minimum buffer size (no-op for stub).
This method is a no-op in the stub implementation since the underlying line manages its own buffering.
- Parameters:
size – Minimum buffer size (ignored in stub).
- frompackages = ()¶
- packages = ()¶
- backtrader.iteritems(d)[source]¶
Return an iterator over the dictionary’s items.
- Parameters:
d – Dictionary to iterate over.
- Returns:
An iterator over (key, value) tuples.
- class backtrader.OrderExecutionBit[source]¶
Bases:
objectIntended to hold information about order execution. A “bit” does not determine if the order has been fully/partially executed, it just holds information.
Member Attributes:
dt: datetime (float) execution time
# Execution time, float - size: how much was executed # How much was executed - price: execution price # Execution price - closed: how much of the execution closed an existing position # How much of existing position was closed - opened: how much of the execution opened a new position # How much new position was opened - openedvalue: market value of the “opened” part # Market value of opened position - closedvalue: market value of the “closed” part # Market value of closed position part - closedcomm: commission for the “closed” part # Commission for closed position part - openedcomm: commission for the “opened” part # Commission for opened position part - value: market value for the entire bit size # Market value of entire position - comm: commission for the entire bit execution # Commission for entire position - pnl: pnl generated by this bit (if something was closed) # PnL from closing part of position - psize: current open position size # Size of already opened position - pprice: current open position price # Price of already opened position
- __init__(dt=None, size=0, price=0.0, closed=0, closedvalue=0.0, closedcomm=0.0, opened=0, openedvalue=0.0, openedcomm=0.0, pnl=0.0, psize=0, pprice=0.0)[source]¶
Initialize order execution bit information.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- class backtrader.OrderData[source]¶
Bases:
objectHolds actual order data for Creation and Execution.
In the case of Creation the request made and in the case of Execution the actual outcome.
Member Attributes:
exbits : iterable of OrderExecutionBits for this OrderData # Serialized order execution information for this order
dt: datetime (float) creation/execution time # Order creation or execution time, string format
size: requested/executed size # Creation or execution size
price: execution price # Execution price. If no price or limit price is given, the order creation # or current closing price will be used as reference Note: if no price is given and no pricelimite is given, the closing price at the time or order creation will be used as reference
pricelimit: holds pricelimit for StopLimit (which has trigger first) # Limit price for stop limit (triggered first)
trailamount: absolute price distance in trailing stops # Absolute price distance in trailing stop
trailpercent: percentage price distance in trailing stops # Percentage distance in trailing stop
value: market value for the entire bit size # Market value of entire position
comm: commission for the entire bit execution # Commission for entire position execution
pnl: pnl generated by this bit (if something was closed) # PnL after closing position
margin: margin incurred by the Order (if any) # Margin required for order
psize: current open position size # Current position size
pprice: current open position price # Current position price
- __init__(dt=None, size=0, price=0.0, pricelimit=0.0, remsize=0, pclose=0.0, trailamount=0.0, trailpercent=0.0)[source]¶
Initialize order data.
- Parameters:
dt – Order datetime.
size – Order size.
price – Order price.
pricelimit – Limit price for stop orders.
remsize – Remaining size to execute.
pclose – Previous close price.
trailamount – Trailing amount for stop orders.
trailpercent – Trailing percent for stop orders.
- property plimit¶
- add(dt, size, price, closed=0, closedvalue=0.0, closedcomm=0.0, opened=0, openedvalue=0.0, openedcomm=0.0, pnl=0.0, psize=0, pprice=0.0)[source]¶
Add execution information to this order.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- addbit(exbit)[source]¶
Store an execution bit and recalculate order values.
- Parameters:
exbit – OrderExecutionBit to add.
- getpending()[source]¶
Get list of pending execution bits.
- Returns:
List of pending OrderExecutionBit objects.
- Return type:
- iterpending()[source]¶
Iterate over pending execution bits.
- Returns:
Iterator over pending OrderExecutionBit objects.
- Return type:
iterator
- class backtrader.OrderParams[source]¶
Bases:
objectSimple parameter container for Order classes.
Stores order parameters like owner, data, size, price, execution type, etc.
- __init__(**kwargs)[source]¶
Initialize order parameters with defaults.
- Parameters:
**kwargs – Keyword arguments to override default parameters.
- Raises:
AttributeError – If an invalid parameter is provided.
- class backtrader.OrderBase[source]¶
Bases:
objectBase class for order objects.
Provides the foundation for all order types with common attributes and methods for order tracking, status management, and execution.
- Class Attributes:
DAY: Constant for day order identification. Market, Close, Limit, Stop, StopLimit, StopTrail, StopTrailLimit: Order execution types. Buy, Sell: Order direction types. Created, Submitted, Accepted, Partial, Completed, Canceled, Expired, Margin, Rejected: Order status codes.
- ref¶
Unique order reference number.
- broker¶
Broker instance handling this order.
- p¶
OrderParams instance containing order parameters.
- DAY = datetime.timedelta(0)¶
- T_Close = 0¶
- T_Day = 1¶
- T_Date = 2¶
- T_None = 3¶
- V_None = range(0, 1)¶
- Market = 0¶
- Close = 1¶
- Limit = 2¶
- Stop = 3¶
- StopLimit = 4¶
- StopTrail = 5¶
- StopTrailLimit = 6¶
- Historical = 7¶
- ExecTypes = ['Market', 'Close', 'Limit', 'Stop', 'StopLimit', 'StopTrail', 'StopTrailLimit', 'Historical']¶
- OrdTypes = ['Buy', 'Sell']¶
- Buy = 0¶
- Sell = 1¶
- Created = 0¶
- Submitted = 1¶
- Accepted = 2¶
- Partial = 3¶
- Completed = 4¶
- Canceled = 5¶
- Expired = 6¶
- Margin = 7¶
- Rejected = 8¶
- Cancelled = 5¶
- Status = ['Created', 'Submitted', 'Accepted', 'Partial', 'Completed', 'Canceled', 'Expired', 'Margin', 'Rejected']¶
- refbasis = count(1)¶
- notification_id = None¶
- replayed = False¶
- __init__(**kwargs)[source]¶
Initialize the order base instance.
- Parameters:
**kwargs – Order parameters (owner, data, size, price, etc.).
- property plimit¶
- clone()[source]¶
Clone the order.
- Returns:
A cloned copy with cloned executed OrderData.
- Return type:
- property position_side¶
Read-only alias for order.info.position_side.
- property offset¶
Read-only alias for order.info.offset.
- classmethod ExecType(exectype)[source]¶
Get the execution type constant from the class.
- Parameters:
exectype – String name of the execution type.
- Returns:
The execution type constant.
- Return type:
- active()[source]¶
Check if the order is active.
- Returns:
True if order is active, False otherwise.
- Return type:
- addinfo(**kwargs)[source]¶
Add the keys, values of kwargs to the internal info dictionary to hold custom information in the order
- submit(broker=None)[source]¶
Marks an order as submitted and stores the broker to which it was submitted
- brokerstatus()[source]¶
Tries to retrieve the status from the broker in which the order is.
Defaults to last known status if no broker is associated
- class backtrader.Order[source]¶
Bases:
OrderBaseOrder class for buy/sell orders.
Extends OrderBase with order type (buy/sell) and session end time handling. This is the main order class used for creating and managing trading orders.
- dteos¶
Date/time of end of session for order validity.
- __init__(**kwargs)[source]¶
Initialize the order instance.
- Parameters:
**kwargs – Order parameters (owner, data, size, price, etc.).
- execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, margin, pnl, psize, pprice)[source]¶
Execute the order with given parameters.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
margin – Margin required for the order.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- class backtrader.BuyOrder[source]¶
Bases:
OrderBuy order class.
Represents a buy order with ordtype set to Order.Buy.
- class backtrader.StopBuyOrder[source]¶
Bases:
BuyOrderStop buy order class.
Used for buy orders that trigger when price crosses a threshold.
- class backtrader.StopLimitBuyOrder[source]¶
Bases:
BuyOrderStop limit buy order class.
Used for buy orders that become limit orders after stop price is triggered.
- class backtrader.SellOrder[source]¶
Bases:
OrderSell order class.
Represents a sell order with ordtype set to Order.Sell.
- class backtrader.StopSellOrder[source]¶
Bases:
SellOrderStop sell order class.
Used for sell orders that trigger when price crosses a threshold.
- class backtrader.StopLimitSellOrder[source]¶
Bases:
SellOrderStop limit sell order class.
Used for sell orders that become limit orders after stop price is triggered.
- class backtrader.Position[source]¶
Bases:
objectKeeps and updates the size and price of a position.
The Position object has no relationship to any specific asset. It only keeps size and price information.
- size¶
Current position size (positive for long, negative for short).
- price¶
Current price of the position.
- price_orig¶
Original price when position was opened.
- upopened¶
Amount of position opened in last update.
- upclosed¶
Amount of position closed in last update.
- adjbase¶
Adjustment base for position calculations.
Example
>>> position = Position(size=100, price=50.0) >>> print(len(position)) # Returns True if size != 0
- __init__(size=0, price=0.0)[source]¶
Initialize a Position instance.
- Parameters:
size – Initial position size (default: 0).
price – Initial price for the position (default: 0.0).
- fix(size, price)[source]¶
Fix the position to a specific size and price.
- Parameters:
size – The new position size.
price – The new position price.
- Returns:
True if size equals oldsize, False otherwise.
- Return type:
- set(size, price)[source]¶
Set position’s size and price, calculating opening and closing amounts.
- Parameters:
size – The new position size.
price – The new position price.
- Returns:
(size, price, upopened, upclosed) calculated values.
- Return type:
- clone()[source]¶
Create a copy of the current position.
- Returns:
- A new Position instance with the same size and price,
including all internal state fields.
- Return type:
- pseudoupdate(size, price)[source]¶
Create a pseudo-update by cloning and updating.
- Parameters:
size – The size to add to the position.
price – The price for the update.
- Returns:
A new Position instance after update.
- Return type:
- update(size, price, dt=None)[source]¶
Updates the current position and returns the updated size, price and units used to open/close a position # Update current position and return updated size, price and position size needed to open/close
- Parameters:
size (# Amount to update position) – amount to update the position’s size if size < 0: A sell operation has taken place if size > 0: A buy operation has taken place
size
0 (if size >)
executed (a buy operation will be)
0
executed
price (float) – Must always be positive to ensure consistency
Price (#)
consistency (must always be positive to maintain)
dt (datetime.datetime) – record datetime update (datetime.datetime)
- Returns:
- A tuple (non-named) contaning
- size - new position size
Simply the sum of the existing size plus the “size” argument
- price - new position price
If a position is increased, the new average price will be returned If a position is reduced, the price of the remaining size does not change If a position is closed, the price is nullified If a position is reversed, the price is the price given as argument
- opened - amount of contracts from argument “size” that were used
to open/increase a position. A position can be opened from 0 or can be a reversal. If a reversal is performed, then opened is less than “size”, because part of “size” will have been used to close the existing position
- closed - the amount of units from arguments “size” that were used to
close/reduce a position
Both opened and closed carry the same sign as the “size” argument because they refer to a part of the “size” argument # Result will return a tuple containing the following data: # size represents new position size, simply existing position size plus new position increment # price represents new position price, returns different price based on different position # opened represents position size to be newly opened # closed represents position size to be closed
- class backtrader.timedelta[source]¶
Bases:
objectDifference between two datetime values.
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.
- total_seconds()¶
Total seconds in the duration.
- days¶
Number of days.
- seconds¶
Number of seconds (>= 0 and less than 1 day).
- microseconds¶
Number of microseconds (>= 0 and less than 1 second).
- max = datetime.timedelta(days=999999999, seconds=86399, microseconds=999999)¶
- min = datetime.timedelta(days=-999999999)¶
- resolution = datetime.timedelta(microseconds=1)¶
- class backtrader.DTFaker[source]¶
Bases:
objectProvides fake datetime for data sources that need periodic checks.
This class is used for real-time data feeds that return None from _load to indicate that a check of the resampler and/or notification queue is needed. It provides the current time in both UTC and localized formats.
- data¶
The underlying data source.
- _dt¶
UTC-like time as numeric value.
- _dtime¶
Localized datetime.
- sessionend¶
Trading day end time.
Example
>>> faker = DTFaker(data) >>> print(faker.datetime()) # Current localized time
- __init__(data, forcedata=None)[source]¶
Initialize the DTFaker with current time.
- Parameters:
data – The underlying data source.
forcedata – Optional data source to force time from.
- __call__(idx=0)[source]¶
Return the localized datetime.
- Parameters:
idx – Index (ignored, for compatibility).
- Returns:
Localized datetime object.
- datetime(idx=0)[source]¶
Return the localized datetime.
- Parameters:
idx – Index (ignored, for compatibility).
- Returns:
Localized datetime object.
- date(idx=0)[source]¶
Return the localized date.
- Parameters:
idx – Index (ignored, for compatibility).
- Returns:
Date object.
- time(idx=0)[source]¶
Return the localized time.
- Parameters:
idx – Index (ignored, for compatibility).
- Returns:
Time object.
- class backtrader.ResamplerTicks[source]¶
Bases:
ResamplerResampler for tick-level data.
- params = (('timeframe', 1),)¶
- class backtrader.ResamplerSeconds[source]¶
Bases:
ResamplerResampler for seconds-level data.
- params = (('timeframe', 3),)¶
- class backtrader.ResamplerMinutes[source]¶
Bases:
ResamplerResampler for minute-level data.
- params = (('timeframe', 4),)¶
- class backtrader.ResamplerDaily[source]¶
Bases:
ResamplerResampler for daily data.
- params = (('timeframe', 5),)¶
- class backtrader.ResamplerWeekly[source]¶
Bases:
ResamplerResampler for weekly data.
- params = (('timeframe', 6),)¶
- class backtrader.ResamplerMonthly[source]¶
Bases:
ResamplerResampler for monthly data.
- params = (('timeframe', 7),)¶
- class backtrader.ResamplerYearly[source]¶
Bases:
ResamplerResampler for yearly data.
- params = (('timeframe', 8),)¶
- class backtrader.ReplayerTicks[source]¶
Bases:
ReplayerReplayer for tick-level data.
- params = (('timeframe', 1),)¶
- class backtrader.ReplayerSeconds[source]¶
Bases:
ReplayerReplayer for seconds-level data.
- params = (('timeframe', 3),)¶
- class backtrader.ReplayerMinutes[source]¶
Bases:
ReplayerReplayer for minute-level data.
- params = (('timeframe', 4),)¶
- class backtrader.ReplayerDaily[source]¶
Bases:
ReplayerReplayer for daily data.
- params = (('timeframe', 5),)¶
- class backtrader.ReplayerWeekly[source]¶
Bases:
ReplayerReplayer for weekly data.
- params = (('timeframe', 6),)¶
- class backtrader.ReplayerMonthly[source]¶
Bases:
ReplayerReplayer for monthly data.
- params = (('timeframe', 7),)¶
- class backtrader.Signal[source]¶
Bases:
IndicatorSignal indicator for trading strategies.
The Signal class wraps a data line to provide trading signal values for strategy execution. It inherits from Indicator and exposes a single signal line that can be used to generate long/short signals.
- SignalTypes¶
List of available signal type constants.
- lines¶
Tuple containing the signal line name.
Example
>>> class MyStrategy(bt.Strategy): ... def __init__(self): ... # Create a signal indicator from a data line ... self.signal = bt.Signal(self.data.close) ... self.sma = bt.indicators.SMA(self.data.close, period=20) ... ... def next(self): ... if self.signal[0] > 0: ... self.buy() ... elif self.signal[0] < 0: ... self.sell()
- SignalTypes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]¶
- __init__(*args, **kwargs)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.Sizer[source]¶
Bases:
ParameterizedBaseBase class for position sizers.
This is the base class for sizers. Any sizer should subclass this and override the
_getsizingmethod to provide custom position sizing logic.- strategy¶
The strategy using this sizer.
- broker¶
The broker instance for portfolio information.
Example
>>> cerebro.addsizer(bt.sizers.FixedSize, stake=100)
- uses_account_cash = True¶
Whether
_getsizinguses thecashargument (Broker account cash).
- strategy = None¶
- broker = None¶
- class backtrader.Store[source]¶
Bases:
StoreParamsPer-instance base class for store implementations.
Stores manage connections to external data sources and brokers. They provide data feeds and broker instances, and handle notifications from the external service.
- _started¶
Whether the store has been started.
- params¶
Tuple of parameter definitions.
- broker¶
The broker instance associated with this store.
- params = ()¶
- getbroker(*args, **kwargs)[source]¶
Construct the configured broker and bind it to this Store instance.
- start(data=None, broker=None)[source]¶
Register Store participants and initialize common lifecycle state.
- Parameters:
data – Data feed to register with the store (optional).
broker – Broker instance to register with the store (optional).
Note
On first call, initializes the notification queue and data list. Subsequent calls can add data feeds or set the broker.
- stop()[source]¶
Stop the Store.
Concrete stores with resources to release should override this hook.
- class backtrader.Mapping¶
Bases:
CollectionA Mapping is a generic container for associating key/value pairs.
This class provides concrete generic implementations of all methods except for __getitem__, __iter__, and __len__.
- get(k[, d]) D[k] if k in D, else d. d defaults to None.¶
- items() a set-like object providing a view on D's items¶
- keys() a set-like object providing a view on D's keys¶
- values() an object providing a view on D's values¶
- class backtrader.Decimal¶
Bases:
objectConstruct a new Decimal object. ‘value’ can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal(‘0’). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active.
- adjusted()¶
Return the adjusted exponent of the number. Defined as exp + digits - 1.
- as_integer_ratio()¶
Return a pair of integers, whose ratio is exactly equal to the original Decimal and with a positive denominator. The ratio is in lowest terms. Raise OverflowError on infinities and a ValueError on NaNs.
- as_tuple()¶
Return a tuple representation of the number.
- canonical()¶
Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.
- compare(other, context=None)¶
Compare self to other. Return a decimal value:
a or b is a NaN ==> Decimal(‘NaN’) a < b ==> Decimal(‘-1’) a == b ==> Decimal(‘0’) a > b ==> Decimal(‘1’)
- compare_signal(other, context=None)¶
Identical to compare, except that all NaNs signal.
- compare_total(other, context=None)¶
Compare two operands using their abstract representation rather than their numerical value. Similar to the compare() method, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:
>>> Decimal('12.0').compare_total(Decimal('12')) Decimal('-1')
Quiet and signaling NaNs are also included in the total ordering. The result of this function is Decimal(‘0’) if both operands have the same representation, Decimal(‘-1’) if the first operand is lower in the total order than the second, and Decimal(‘1’) if the first operand is higher in the total order than the second operand. See the specification for details of the total order.
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- compare_total_mag(other, context=None)¶
Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand.
x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- conjugate()¶
Return self.
- copy_abs()¶
Return the absolute value of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.
- copy_negate()¶
Return the negation of the argument. This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed.
- copy_sign(other, context=None)¶
Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:
>>> Decimal('2.3').copy_sign(Decimal('-1.5')) Decimal('-2.3')
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- exp(context=None)¶
Return the value of the (natural) exponential function e**x at the given number. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- fma(other, third, context=None)¶
Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other.
>>> Decimal(2).fma(3, 5) Decimal('11')
- classmethod from_float(f, /)¶
Class method that converts a float to a decimal number, exactly. Since 0.1 is not exactly representable in binary floating point, Decimal.from_float(0.1) is not the same as Decimal(‘0.1’).
>>> Decimal.from_float(0.1) Decimal('0.1000000000000000055511151231257827021181583404541015625') >>> Decimal.from_float(float('nan')) Decimal('NaN') >>> Decimal.from_float(float('inf')) Decimal('Infinity') >>> Decimal.from_float(float('-inf')) Decimal('-Infinity')
- imag¶
- is_canonical()¶
Return True if the argument is canonical and False otherwise. Currently, a Decimal instance is always canonical, so this operation always returns True.
- is_finite()¶
Return True if the argument is a finite number, and False if the argument is infinite or a NaN.
- is_infinite()¶
Return True if the argument is either positive or negative infinity and False otherwise.
- is_nan()¶
Return True if the argument is a (quiet or signaling) NaN and False otherwise.
- is_normal(context=None)¶
Return True if the argument is a normal finite non-zero number with an adjusted exponent greater than or equal to Emin. Return False if the argument is zero, subnormal, infinite or a NaN.
- is_qnan()¶
Return True if the argument is a quiet NaN, and False otherwise.
- is_signed()¶
Return True if the argument has a negative sign and False otherwise. Note that both zeros and NaNs can carry signs.
- is_snan()¶
Return True if the argument is a signaling NaN and False otherwise.
- is_subnormal(context=None)¶
Return True if the argument is subnormal, and False otherwise. A number is subnormal if it is non-zero, finite, and has an adjusted exponent less than Emin.
- is_zero()¶
Return True if the argument is a (positive or negative) zero and False otherwise.
- ln(context=None)¶
Return the natural (base e) logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- log10(context=None)¶
Return the base ten logarithm of the operand. The function always uses the ROUND_HALF_EVEN mode and the result is correctly rounded.
- logb(context=None)¶
For a non-zero number, return the adjusted exponent of the operand as a Decimal instance. If the operand is a zero, then Decimal(‘-Infinity’) is returned and the DivisionByZero condition is raised. If the operand is an infinity then Decimal(‘Infinity’) is returned.
- logical_and(other, context=None)¶
Return the digit-wise ‘and’ of the two (logical) operands.
- logical_invert(context=None)¶
Return the digit-wise inversion of the (logical) operand.
- logical_or(other, context=None)¶
Return the digit-wise ‘or’ of the two (logical) operands.
- logical_xor(other, context=None)¶
Return the digit-wise ‘exclusive or’ of the two (logical) operands.
- max(other, context=None)¶
Maximum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.
- max_mag(other, context=None)¶
Similar to the max() method, but the comparison is done using the absolute values of the operands.
- min(other, context=None)¶
Minimum of self and other. If one operand is a quiet NaN and the other is numeric, the numeric operand is returned.
- min_mag(other, context=None)¶
Similar to the min() method, but the comparison is done using the absolute values of the operands.
- next_minus(context=None)¶
Return the largest number representable in the given context (or in the current default context if no context is given) that is smaller than the given operand.
- next_plus(context=None)¶
Return the smallest number representable in the given context (or in the current default context if no context is given) that is larger than the given operand.
- next_toward(other, context=None)¶
If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.
- normalize(context=None)¶
Normalize the number by stripping the rightmost trailing zeros and converting any result equal to Decimal(‘0’) to Decimal(‘0e0’). Used for producing canonical values for members of an equivalence class. For example, Decimal(‘32.100’) and Decimal(‘0.321000e+2’) both normalize to the equivalent value Decimal(‘32.1’).
- number_class(context=None)¶
Return a string describing the class of the operand. The returned value is one of the following ten strings:
‘-Infinity’, indicating that the operand is negative infinity.
‘-Normal’, indicating that the operand is a negative normal number.
‘-Subnormal’, indicating that the operand is negative and subnormal.
‘-Zero’, indicating that the operand is a negative zero.
‘+Zero’, indicating that the operand is a positive zero.
‘+Subnormal’, indicating that the operand is positive and subnormal.
‘+Normal’, indicating that the operand is a positive normal number.
‘+Infinity’, indicating that the operand is positive infinity.
‘NaN’, indicating that the operand is a quiet NaN (Not a Number).
‘sNaN’, indicating that the operand is a signaling NaN.
- quantize(exp, rounding=None, context=None)¶
Return a value equal to the first operand after rounding and having the exponent of the second operand.
>>> Decimal('1.41421356').quantize(Decimal('1.000')) Decimal('1.414')
Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.
Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.
If the exponent of the second operand is larger than that of the first, then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given, the rounding mode of the current thread’s context is used.
- radix()¶
Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification.
- real¶
- remainder_near(other, context=None)¶
Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen.
If the result is zero then its sign will be the sign of self.
- rotate(other, context=None)¶
Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.
- same_quantum(other, context=None)¶
Test whether self and other have the same exponent or whether both are NaN.
This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.
- scaleb(other, context=None)¶
Return the first operand with the exponent adjusted the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer.
- shift(other, context=None)¶
Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive, then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.
- sqrt(context=None)¶
Return the square root of the argument to full precision. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.
- to_eng_string(context=None)¶
Convert to an engineering-type string. Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. For example, Decimal(‘123E+1’) is converted to Decimal(‘1.23E+3’).
The value of context.capitals determines whether the exponent sign is lower or upper case. Otherwise, the context does not affect the operation.
- to_integral(rounding=None, context=None)¶
Identical to the to_integral_value() method. The to_integral() name has been kept for compatibility with older versions.
- to_integral_exact(rounding=None, context=None)¶
Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.
- to_integral_value(rounding=None, context=None)¶
Round to the nearest integer without signaling Inexact or Rounded. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given, then the rounding mode of the current default context is used.
- class backtrader.ItemCollection[source]¶
Bases:
objectCollection that allows access by both index and name.
This class holds a list of items that can be accessed either by their numeric index or by a string name. Names are set as attributes on the collection instance.
Example
collection = ItemCollection() collection.append(my_strategy, name=’mystrat’) collection[0] # Access by index collection.mystrat # Access by name
- backtrader.make_legacy_parameter_accessor(params=(), values=None, name='Params')[source]¶
Create a legacy-compatible parameter accessor from old params declarations.
- Parameters:
name (str)
- backtrader.trade_key_from_order(order)[source]¶
Return the trade-group key used by strategy notifications.
- class backtrader.FixedSize[source]¶
Bases:
SizerThis sizer simply returns a fixed size for any operation. Size can be controlled by the number of tranches that a system wishes to use to scale into trades by specifying the
tranchesparameter.This class has been refactored from legacy params tuple to the new ParameterDescriptor system for Day 36-38 of the metaprogramming removal project.
- Params:
stake(default:1)tranches(default:1)
- uses_account_cash = False¶
Whether
_getsizinguses thecashargument (Broker account cash).
- stake¶
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
- tranches¶
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
- class backtrader.Trade[source]¶
Bases:
objectKeeps track the life of an trade: size, price, commission (and value?)
A trade starts at 0 can be increased and reduced and can be considered closed if it goes back to 0.
The trade can be long (positive size) or short (negative size)
A trade is not meant to be reversed (no support in the logic for it) # Track the life of a trade: size, price, commission (and value?) # A trade starts at 0, can be increased and reduced, and is considered closed when it returns to 0 # A trade can be long (positive size) or short (negative size) # A trade cannot reverse from long to short or short to long, such logic is not supported
Member Attributes:
ref: unique trade identifier # Trade identifierstatus(int): one of Created, Open, Closed # Trade statustradeid: grouping tradeid passed to orders during creation The default in orders is 0 # Trade id passed to orders during creation, default value in orders is 0size(int): current size of the trade # Current size of the tradeprice(float): current price of the trade # Current price of the tradevalue(float): current value of the trade # Current market value of the tradecommission(float): current accumulated commission # Current accumulated commissionpnl(float): current profit and loss of the trade (gross pnl) # Current profit and losspnlcomm(float): current profit and loss of the trade minus commission (net pnl) # Current net profit and loss after deducting commissionisclosed(bool): records if the last update closed (set size to null the trade # Whether the last update event closed this trade, if closed, set size to nullisopen(bool): records if any update has opened the trade # Whether the trade has been openedjustopened(bool): if the trade was just opened # Whether the trade was just openedbaropen(int): bar in which this trade was opened # Record which bar opened the positiondtopen(float): float coded datetime in which the trade was opened # Record the time when the trade was opened, can use open_datetime or num2date to get Python format time - Use methodopen_datetimeto get a Python datetime.datetimeor use the platform provided
num2datemethodbarclose(int): bar in which this trade was closed # Which bar the trade ended ondtclose(float): float coded datetime in which the trade was closed - Use methodclose_datetimeto get a Python datetime.datetimeor use the platform provided
num2datemethod# Record the time when the trade was closed, can use close_datetime or num2date to get Python format time
barlen(int): number of bars this trade was open # Number of bars when trade was openhistoryon(bool): whether history has to be recorded # Whether to record historical trade update eventshistory(list): holds a list updated with each “update” event containing the resulting status and parameters used in the update The first entry in the history is the Opening Event The last entry in the history is the Closing Event # Use a list to save past trade events and status, first is opening event, last is closing event
- refbasis = count(1)¶
- status_names = ['Created', 'Open', 'Closed']¶
- Created = 0¶
- Open = 1¶
- Closed = 2¶
- notification_id = None¶
- replayed = False¶
- __init__(data=None, tradeid=0, historyon=False, size=0, price=0.0, value=0.0, commission=0.0)[source]¶
Initialize a Trade object.
- Parameters:
data – Data source associated with this trade.
tradeid – Unique identifier for the trade.
historyon – Whether to record trade history.
size – Initial position size.
price – Initial price.
value – Initial value.
commission – Initial commission.
- __nonzero__()¶
Trade size is not 0
- open_datetime(tz=None, naive=True)[source]¶
Returns a datetime.datetime object with the datetime in which the trade was opened
- close_datetime(tz=None, naive=True)[source]¶
Returns a datetime.datetime object with the datetime in which the trade was closed
- update(order, size, price, value, commission, pnl, comminfo)[source]¶
Updates the current trade. The logic does not check if the trade is reversed, which is not conceptually supported by the object.
If an update sets the size attribute to 0, “closed” will be set to true
Updates may be received twice for each order, once for the existing size which has been closed (sell undoing a buy) and a second time for the the opening part (sell reversing a buy) # Update current trade. Logic doesn’t check if trade is reversed, not conceptually supported :param order: the order object which has (completely or partially)
generated this updatede
- Parameters:
update (# Order that caused trade)
size (int) – amount to update the order if size has the same sign as the current trade a position increase will happen if size has the opposite sign as current op size a reduction/close will happen
trade (# Commission generated by new)
trade
trade
close (causes position reduction or)
price (float) – always be positive to ensure consistency
Price (#)
negative (always positive to ensure consistency. Unknown what happens if)
value (# Market) – (unused) cost incurred in new size/price op Not used because the value is calculated for the trade
value
trade
commission (float) – incurred commission in the new size/price op
trade
pnl (float) – (unused) generated by the executed part Not used because the trade has an independent pnl
part (# Profit/loss generated by executed)
profit/loss (not used because trade has independent)
comminfo – commission information
- class backtrader.AutoDictList[source]¶
Bases:
dictDictionary that creates an empty list for missing keys.
When accessing a key that doesn’t exist, automatically creates a new empty list for that key.
Example
>>> d = AutoDictList() >>> d['key'].append('value') >>> print(d['key']) ['value']
- class backtrader.SpdLogManager[source]¶
Bases:
objectLogger factory using the Python standard
loggingmodule.Creates loggers with daily file rotation and optional console output. API is kept compatible with the previous spdlog-based implementation.
- file_name¶
Name of the log file.
- logger_name¶
Name for the logger.
- rotation_hour¶
Hour of day for log rotation (0-23).
- rotation_minute¶
Minute of hour for log rotation (0-59).
- print_info¶
Whether to also print to console.
- __init__(file_name='log_strategy_info.log', logger_name='hello', rotation_hour=0, rotation_minute=0, print_info=False)[source]¶
Initialize the SpdLogManager.
- Parameters:
file_name – Name of the output log file.
logger_name – Name for the logger.
rotation_hour – Hour (0-23) to rotate log files daily.
rotation_minute – Minute (0-59) to rotate log files.
print_info – Whether to also output to console.
- class backtrader.filter¶
Bases:
objectfilter(function or None, iterable) –> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
- backtrader.keys(d)[source]¶
Return a list of the dictionary’s keys.
- Parameters:
d – Dictionary to extract keys from.
- Returns:
A list containing the dictionary’s keys.
- class backtrader.BtApiStrategy[source]¶
Bases:
StrategyA Strategy subclass with built-in logging capabilities.
This strategy class extends the base Strategy class with automatic logger initialization using the SpdLogManager. It provides a default log() method for logging messages and custom notification handling.
- logger¶
The configured logger instance from SpdLogManager.
- Params:
- log_file_name: Optional custom log file name. If not provided,
defaults to “{ClassName}.log”.
Example
- class MyStrategy(bt.BtApiStrategy):
params = ((‘log_file_name’, ‘my_strategy.log’),)
- def next(self):
self.log(f’Close price: {self.data.close[0]:.2f}’)
- __init__(*args, **kwargs)¶
- init_logger(log_file_name=None)[source]¶
Initialize and return a logger instance.
Creates a logger using SpdLogManager with the specified or default log file name.
- Parameters:
log_file_name – Optional custom log file name. If None, uses “{ClassName}.log” as the default.
- Returns:
A configured logger instance.
- frompackages = ()¶
- packages = ()¶
- class backtrader.TradeHistory[source]¶
Bases:
AutoOrderedDictRepresents the status and update event for each update a Trade has
This object is a dictionary which allows ‘.’ notation # This class saves the status and event updates for each trade .. attribute:: -
statusHolds the resulting status of an update event and has the following sub-attributes # Status, dict format, accessible via ‘.’, used to save the status of an update event, with the following sub-attributes -
status(int): Trade status# Trade status, integer format
dt(float): float coded datetime# Time, string format
barlen(int): number of bars the trade has been active# Number of bars when trade was generated
size(int): current size of the Trade# Current size of the trade, in integer format. In actual trading, non-integer trade sizes may be used
price(float): current price of the Trade# Current price of the trade
value(float): current monetary value of the Trade# Current monetary value of the trade
pnl(float): current profit and loss of the Trade# Current profit and loss of the trade
pnlcomm(float): current profit and loss minus commission# Current net profit and loss of the trade
- type:
dictwith ‘.’ notation
- - ``event``
Holds the event update - parameters # Event attributes, saves event update parameters -
order(object): the order which initiated the``update``# Order that generated the trade
size(int): size of the update# Size of the update
price(float):price of the update# Price of the update
commission(float): price of the update# Commission of the update
- Type:
dictwith ‘.’ notation
- backtrader.num2dt(num, tz=None, naive=True)[source]¶
Convert numeric date to date object.
- Parameters:
num – Numeric date value (days since 0001-01-01 UTC + 1).
tz – Timezone for the result (optional).
naive – If True, return naive date without timezone info.
- Returns:
Date object extracted from the datetime.
- Return type:
- backtrader.num2time(num, tz=None, naive=True)[source]¶
Convert numeric date to time object.
- Parameters:
num – Numeric date value (days since 0001-01-01 UTC + 1).
tz – Timezone for the result (optional).
naive – If True, return naive time without timezone info.
- Returns:
Time object extracted from the datetime.
- Return type:
time
- backtrader.configure_logging(level='INFO', log_file=None, fmt=None, datefmt=None, console=True, max_bytes=10485760, backup_count=5, propagate=False, *, log_dir=None, script_name=None, backend='auto', retention_days=30, _debug_scopes=())[source]¶
Configure the
backtraderlogger hierarchy (opt-in).Backtrader emits nothing until you call this. It configures only the
backtraderlogger (never the root logger), so it will not clobber a host application’s logging. Calling it again replaces backtrader-managed handlers (idempotent) while leaving host-added handlers untouched.- Parameters:
level – Level as int (
logging.INFO) or name ("INFO").log_file – If given, also write to this single file via a
RotatingFileHandler. Mutually exclusive withlog_dir.log_dir – If given, enable the iteration-29 split-file layout
log_dir/<script>/<YYYY_MM_DD>/{error,warning,info}.log(plusdebug.logwhenlevel=DEBUG).<script>comes fromscript_nameor auto-detection ofsys.argv[0].script_name – Directory name under
log_dir.Noneauto-detects fromsys.argv[0](xxx/run.py->xxx_run).backend –
"auto"(default; prefer the optionalspdlogpackage, fall back to stdlib with one diagnostic),"spdlog"(raiseImportErrorif unavailable) or"stdlib".retention_days – Date directories older than this many days under the script’s own directory are removed at configure/rollover time.
fmt – Message format. Defaults to
DEFAULT_FORMAT.datefmt – Date format. Defaults to
DEFAULT_DATEFMT.console – Whether to add a stderr
StreamHandler.max_bytes – Rotating file handler size before rollover (
log_file).backup_count – Number of rotated backups to keep (
log_file).propagate – Whether the backtrader logger propagates to the root logger (default
False).
- Returns:
The configured
backtraderroot logger.- Return type:
- backtrader.reset_logging()[source]¶
Remove backtrader-managed handlers and restore the default NullHandler.
Mainly useful in tests to return to the pristine, no-output state. Also flushes and releases any spdlog-side resources held by managed handlers.
- backtrader.set_level(level, name=None)[source]¶
Set the level of a backtrader logger at runtime.
- Parameters:
level – Level as int or name.
name – Sub-logger name (
__name__-style).Nonetargets the root. A root-level update with active split-file logging atomically rebuilds its handler matrix, so a DEBUG transition createsdebug.logand is inherited by optimization workers. A named DEBUG update creates a DEBUG sink restricted to that logger’s hierarchy, leaving unrelated loggers at the configured root level.
- backtrader.bind_qq_bot(user_openid=None, group_openid=None, persist_path=None)[source]¶
Register a QQ anchor explicitly and apply it live.
Automatic binding needs an event subscription (WebSocket or a public webhook); the standard library has no WebSocket client and adding one would break the zero-dependency rule, so the anchor is supplied by the caller.
- Parameters:
user_openid – Single-chat anchor.
group_openid – Group-chat anchor.
persist_path – Anchor file path; defaults to
~/.backtrader/notifications/qq_bot.json(mode0600).
- Returns:
The anchor mapping.
- Return type:
- Raises:
ValueError – If neither anchor is supplied.
- backtrader.bind_wechat_clawbot(qr_callback=None, persist_path=None, timeout=30.0, poll_interval=2.0, max_polls=150)[source]¶
Run the ClawBot QR login, persist the anchor and apply it live.
- Parameters:
qr_callback – Optional
callable(url)used to display the QR target.persist_path – Anchor file path; defaults to
~/.backtrader/notifications/wechat_clawbot.json(mode0600).timeout – Request timeout in seconds.
poll_interval – Seconds between QR status polls.
max_polls – Maximum number of status polls.
- Returns:
The anchor, or an empty dict when binding did not complete.
- Return type:
Note
The iLink protocol is not officially documented (see the M0 evidence file); verify against a gray-release account before relying on it.
- backtrader.configure_notifications(channels, **overrides)[source]¶
Configure the notification channels (opt-in).
- Parameters:
channels – Sequence of
{"channel": <id>, ...credentials}. An empty sequence is valid and means “configured with no channels”.**overrides – Core options; see
DEFAULT_OPTIONS. Two extra keys are accepted for testing:transportandsmtp_sender.
- Returns:
The configured notifier.
- Return type:
Notifier
- Raises:
ValueError – On an unknown channel, missing credential, malformed entry or out-of-range option. On failure the previous configuration stays in place and usable.
- backtrader.configure_notifications_from_env(prefix='BT_NOTIFY_', **overrides)[source]¶
Configure channels from environment variables.
Channel ids come from
<prefix>CHANNELS(comma separated); each channel’s credentials come from<prefix><ID>_<FIELD>(upper-cased), for exampleBT_NOTIFY_CHANNELS=dingtalk,telegramwithBT_NOTIFY_DINGTALK_ACCESS_TOKENandBT_NOTIFY_TELEGRAM_BOT_TOKEN.- Parameters:
prefix – Environment variable prefix.
**overrides – Core options passed through to
configure_notifications().
- Returns:
The configured notifier.
- Return type:
Notifier
- Raises:
ValueError – If no channel is requested or a required credential is missing.
- backtrader.default_anchor_path(channel_id)[source]¶
Return the default anchor file path for a channel.
- Parameters:
channel_id – Public channel id.
- Returns:
Path under the user’s home directory.
- Return type:
- backtrader.flush_notifications(timeout=5.0)[source]¶
Wait for queued notifications to be delivered.
- Parameters:
timeout – Maximum seconds to wait.
- Returns:
Truewhen every queue drained (or nothing is configured).- Return type:
- backtrader.load_anchor(path)[source]¶
Load a persisted anchor file.
- Parameters:
path – File path to read.
- Returns:
The anchor mapping, or an empty dict when the file is absent or unreadable.
- Return type:
- backtrader.notification_stats()[source]¶
Return a read-only snapshot of per-channel statistics.
- Returns:
Instance name to statistic mapping (empty when unconfigured).
- Return type:
- backtrader.poll_clawbot_once(timeout=None)[source]¶
Refresh WeChat ClawBot anchors from pending inbound messages.
The refresh window (a new inbound message is required periodically) is not maintained by a background thread, so a long-running process should call this periodically - for example from
Strategy.stopor a timer.- Parameters:
timeout – Request timeout override.
- Returns:
Number of ClawBot instances successfully polled.
- Return type:
- backtrader.reset_notifications()[source]¶
Stop every worker, discard queued messages and clear statistics.
- backtrader.send_message(text, *, title=None, level='info', channels=None, wait=None, timeout=None, dedup_key=None, strategy=None, data_name=None, at_time=None)[source]¶
Send one notification (asynchronous by default).
- Parameters:
text – Message body; must be a non-empty string.
title – Optional title.
level –
info/warning/error/critical(any case).channels – Optional subset of channel ids.
wait –
Truesends synchronously and returns delivery results;Noneuses the configured default.timeout – Per-request timeout, only honoured when
waitis true.dedup_key – Deduplication key.
strategy – Strategy class name (injected by
Strategy.send_message).data_name – Data feed name (injected by
Strategy.send_message).at_time – Backtest timestamp (injected by
Strategy.send_message).
- Returns:
Never raises for delivery problems; programming errors (empty text, unknown level, unknown channel id) raise
ValueError.- Return type:
SendResult
- Raises:
ValueError – On empty text, invalid level or unknown channel id.
- backtrader.update_anchor(channel_id, anchor)[source]¶
Apply a freshly bound session anchor to live channel instances.
- Parameters:
channel_id –
wechat_clawbotorqq_bot.anchor – Mapping returned by
bind_wechat_clawbot/bind_qq_bot.
- Returns:
Number of channel instances updated.
- Return type:
- backtrader.cast(typ, val)[source]¶
Cast a value to a type.
This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).
- class backtrader.WriterBase[source]¶
Bases:
ParameterizedBaseBase class for writers.
This is the base class for all writer implementations. Subclasses should override the writing methods to provide custom output formatting.
- class backtrader.WriterStringIO[source]¶
Bases:
WriterFileWriter that outputs to an in-memory StringIO buffer.
This writer stores all output in memory rather than writing to a file. Useful for testing or when you need to capture output programmatically.
- _stringio¶
The StringIO buffer holding the output.
Example
>>> writer = WriterStringIO() >>> cerebro.addwriter(writer) >>> results = cerebro.run() >>> output = writer.getvalue()
- params = (('out', <class '_io.StringIO'>),)¶
- __init__(**kwargs)[source]¶
Initialize the WriterStringIO instance.
Creates a new StringIO buffer for storing output.
- Parameters:
**kwargs – Keyword arguments for writer parameters.
- property out¶
Always return our StringIO object.
- class backtrader.LiveProfile[source]¶
Bases:
objectDeclarative description of a single Cerebro run.
Captures the run mode (
backtestorlive), the strategy class plus its args/kwargs, the data source description (dataname,symbolsor a customdata_factory), the broker construction knobs and the optional live store configuration.__post_init__normalizes the inputs and runs a set of consistency checks so thatbuild_cerebro()can produce a fully wired Cerebro without further validation.- frequency¶
One of
"lowfreq","midfreq"or"hft". Used by downstream broker/feed wiring to pick the right defaults.- Type:
- data_factory¶
Optional callable returning one or more pre-built data instances. Mutually exclusive with
dataname/symbols.- Type:
Callable[[], Any] | None
- property is_live: bool¶
Return
Truewhen the profile’smodeis"live".Used by
build_cerebro()and friends to branch between the live (store-backed) and backtest (CSV-backed) wiring paths without re-comparing the rawmodestring.
- __init__(mode, strategy, frequency='lowfreq', dataname=None, symbols=(), strategy_args=(), strategy_kwargs=<factory>, data_cls=None, data_factory=None, data_kwargs=<factory>, data_name=None, broker_cls=None, broker_factory=None, broker_kwargs=<factory>, store_factory=None, store_kwargs=<factory>, store_provider='btapi', cerebro_kwargs=<factory>)¶
- backtrader.build_cerebro(profile)[source]¶
Construct a fully wired-up
Cerebrofromprofile.The function instantiates the store (for live profiles), the broker and the data feeds according to
profile, attaches them to a freshCerebro, and registers the strategy. The profile and store are exposed back on the Cerebro aslive_profileandprofile_storefor downstream introspection.- Parameters:
profile (LiveProfile) – The
LiveProfiledescribing the run.- Returns:
A Cerebro instance with the broker, data feed(s) and strategy attached.
- Return type:
- class backtrader.BarEvent[source]¶
Bases:
EventDataOHLCV bar event data.
Compatible with existing backtrader bar-level data format.
- __init__(timestamp, symbol, exchange='', asset_type='spot', local_time=None, open=0.0, high=0.0, low=0.0, close=0.0, volume=0.0, openinterest=0.0, *, exchange_time=None, received_wall_time=None, received_monotonic_ns=None, clock_domain_id='process-2328-000e3245897f453592068a565187412f', sequence=0, previous_sequence=None, snapshot_or_delta='', continuity_status='unknown', stale=False, stale_reason='', source='', event_id=None, coalesced_count=1)[source]¶
Build an OHLCV bar event.
- Parameters:
timestamp (float) – Exchange timestamp in seconds.
symbol (str) – Trading pair symbol.
exchange (str) – Exchange name.
asset_type (str) – Asset type (
spot,swaporfutures).local_time (float | None) – Local receive timestamp used for latency tracking.
open (float) – Bar open price.
high (float) – Bar high price.
low (float) – Bar low price.
close (float) – Bar close price.
volume (float) – Traded volume over the bar.
openinterest (float) – Open interest at the close of the bar.
exchange_time (float | None)
received_wall_time (float | None)
received_monotonic_ns (int | None)
clock_domain_id (str)
sequence (int)
previous_sequence (int | None)
snapshot_or_delta (str)
continuity_status (str)
stale (bool)
stale_reason (str)
source (str)
event_id (str | None)
coalesced_count (int)
- Return type:
None
The keyword-only arguments are the shared event envelope documented on
EventData; unset receive-clock fields are filled in by__post_init__.
- class backtrader.FundingEvent[source]¶
Bases:
EventDataFunding rate event for perpetual contracts.
- __init__(timestamp, symbol, exchange='', asset_type='spot', local_time=None, rate=0.0, mark_price=0.0, next_funding_time=0.0, predicted_rate=0.0, *, exchange_time=None, received_wall_time=None, received_monotonic_ns=None, clock_domain_id='process-2328-000e3245897f453592068a565187412f', sequence=0, previous_sequence=None, snapshot_or_delta='', continuity_status='unknown', stale=False, stale_reason='', source='', event_id=None, coalesced_count=1)[source]¶
Build a perpetual-contract funding event.
- Parameters:
timestamp (float) – Exchange timestamp in seconds.
symbol (str) – Trading pair symbol.
exchange (str) – Exchange name.
asset_type (str) – Asset type (
spot,swaporfutures).local_time (float | None) – Local receive timestamp used for latency tracking.
rate (float) – Settled funding rate.
mark_price (float) – Mark price the rate applies to.
next_funding_time (float) – Unix timestamp of the next settlement.
predicted_rate (float) – Exchange-predicted rate for the next interval.
exchange_time (float | None)
received_wall_time (float | None)
received_monotonic_ns (int | None)
clock_domain_id (str)
sequence (int)
previous_sequence (int | None)
snapshot_or_delta (str)
continuity_status (str)
stale (bool)
stale_reason (str)
source (str)
event_id (str | None)
coalesced_count (int)
- Return type:
None
The keyword-only arguments are the shared event envelope documented on
EventData; unset receive-clock fields are filled in by__post_init__.
- class backtrader.MarketOrderBookEnvelope[source]¶
Bases:
objectBacktrader callback envelope retaining one exact SDK book event.
Unlike
OrderBookSnapshot, this envelope does not invent receive clocks, freshness, or a midpoint timestamp. The SDK event remains intact atsdk_eventand carries the authoritative source, cursor, and clock. These events are suitable for notification callbacks only;execution_eligibleis permanently false until a separate clock and execution-quality contract is available.- property key¶
- property instrument¶
- property source_descriptor¶
- property cursor¶
- property clock¶
- property event_time_utc¶
- property timestamp¶
- property local_time¶
- property bids¶
- property asks¶
- property previous_sequence¶
- property freshness_status¶
- class backtrader.OrderBookSnapshot[source]¶
Bases:
EventDataOrder book depth snapshot.
Stores bid/ask depth levels as lists of (price, quantity) tuples. Bids are in descending price order, asks in ascending price order.
- __init__(timestamp, symbol, exchange='', asset_type='spot', local_time=None, bids=None, asks=None, *, exchange_time=None, received_wall_time=None, received_monotonic_ns=None, clock_domain_id='process-2328-000e3245897f453592068a565187412f', sequence=0, previous_sequence=None, snapshot_or_delta='', continuity_status='unknown', stale=False, stale_reason='', source='', recovery_snapshot=False, event_id=None, coalesced_count=1)[source]¶
Build an order-book depth snapshot event.
- Parameters:
timestamp (float) – Exchange timestamp in seconds.
symbol (str) – Trading pair symbol.
exchange (str) – Exchange name.
asset_type (str) – Asset type (
spot,swaporfutures).local_time (float | None) – Local receive timestamp used for latency tracking.
bids (List[Tuple[float, float]] | None) – Bid levels as
(price, quantity)tuples, descending by price.asks (List[Tuple[float, float]] | None) – Ask levels as
(price, quantity)tuples, ascending by price.exchange_time (float | None)
received_wall_time (float | None)
received_monotonic_ns (int | None)
clock_domain_id (str)
sequence (int)
previous_sequence (int | None)
snapshot_or_delta (str)
continuity_status (str)
stale (bool)
stale_reason (str)
source (str)
recovery_snapshot (bool)
event_id (str | None)
coalesced_count (int)
- Return type:
None
The keyword-only arguments are the shared event envelope documented on
EventData; unset receive-clock fields are filled in by__post_init__.
- class backtrader.TickEvent[source]¶
Bases:
EventDataTick/trade event data.
Represents a single trade execution on an exchange. Compatible with the existing TickerData interface via adapter pattern.
- __init__(timestamp, symbol, exchange='', asset_type='spot', local_time=None, price=0.0, volume=0.0, direction='buy', trade_id='', bid_price=None, ask_price=None, bid_volume=None, ask_volume=None, *, exchange_time=None, received_wall_time=None, received_monotonic_ns=None, clock_domain_id='process-2328-000e3245897f453592068a565187412f', sequence=0, previous_sequence=None, snapshot_or_delta='', continuity_status='unknown', stale=False, stale_reason='', source='', event_id=None, coalesced_count=1)[source]¶
Build a tick (trade print) event.
- Parameters:
timestamp (float) – Exchange timestamp in seconds.
symbol (str) – Trading pair symbol.
exchange (str) – Exchange name.
asset_type (str) – Asset type (
spot,swaporfutures).local_time (float | None) – Local receive timestamp used for latency tracking.
price (float) – Trade price.
volume (float) – Trade volume.
direction (str) – Aggressor side,
buyorsell.trade_id (str) – Venue trade identifier, when published.
bid_price (float | None) – Best bid at the time of the print, if known.
ask_price (float | None) – Best ask at the time of the print, if known.
bid_volume (float | None) – Size resting at the best bid, if known.
ask_volume (float | None) – Size resting at the best ask, if known.
exchange_time (float | None)
received_wall_time (float | None)
received_monotonic_ns (int | None)
clock_domain_id (str)
sequence (int)
previous_sequence (int | None)
snapshot_or_delta (str)
continuity_status (str)
stale (bool)
stale_reason (str)
source (str)
event_id (str | None)
coalesced_count (int)
- Return type:
None
The keyword-only arguments are the shared event envelope documented on
EventData; unset receive-clock fields are filled in by__post_init__.
- class backtrader.Event[source]¶
Bases:
objectEvent wrapper for queue ordering.
Events are ordered by (timestamp, priority, sequence) for deterministic processing order. The data field is excluded from comparison.
- class backtrader.EventPriority[source]¶
Bases:
IntEnumEvent processing priority (lower value = higher priority).
Within the same timestamp, events are processed in priority order.
- SYSTEM = 0¶
- FUNDING = 10¶
- TICK = 20¶
- ORDERBOOK = 30¶
- BAR = 40¶
- class backtrader.StreamingEventQueue[source]¶
Bases:
objectMemory-efficient event queue with adaptive preloading.
Merges events from multiple channels and bar data sources into a single ordered stream. Uses a heap (priority queue) for efficient merging and supports adaptive preload windows to control memory usage.
The queue loads data in chunks rather than all at once, keeping memory usage bounded regardless of total data size.
- Parameters:
channels – List of DataChannel instances.
bars – List of bar data iterators.
preload_window – Initial preload time window in seconds.
max_memory_mb – Maximum memory target in MB.
adaptive – Whether to adapt the preload window based on memory.
batch_size – Number of events to load per batch from each channel.
Example:
queue = StreamingEventQueue( channels=[tick_channel, ob_channel], bars=[bar_data], preload_window=300.0, max_memory_mb=200, adaptive=True ) while not queue.empty: event = queue.pop() # process event
- __init__(channels=None, bars=None, preload_window=300.0, max_memory_mb=200, adaptive=True, batch_size=10000)[source]¶
Initialize a StreamingEventQueue.
- Parameters:
channels – List of DataChannel instances.
bars – List of bar data iterators.
preload_window – Initial preload time window in seconds.
max_memory_mb – Maximum memory target in MB.
adaptive – Whether to adapt the preload window based on memory.
batch_size – Number of events to load per batch from each channel.
- pop()[source]¶
Pop the next event from the queue.
Returns the event with the smallest (timestamp, priority, sequence). Triggers preloading if needed.
- Returns:
The next Event, or None if the queue is empty.
- Return type:
Event | None
- peek()[source]¶
Peek at the next event without removing it.
- Returns:
The next Event, or None if the queue is empty.
- Return type:
Event | None
- __len__()[source]¶
Return the current number of events in the heap.
- Returns:
Number of events currently in the heap.
- Return type:
- __iter__()[source]¶
Iterate over all events in timestamp order.
- Yields:
Event – The next event in timestamp order.
Subpackages¶
Submodules¶
- backtrader.cerebro module
OptReturnCerebroCerebro.preloadCerebro.runonceCerebro.maxcpusCerebro.stdstatsCerebro.oldbuysellCerebro.oldtradesCerebro.lookaheadCerebro.exactbarsCerebro.optdatasCerebro.optreturnCerebro.objcacheCerebro.liveCerebro.writerCerebro.tradehistoryCerebro.oldsyncCerebro.tzCerebro.cheat_on_openCerebro.broker_cooCerebro.quicknotifyCerebro.__init__()Cerebro.runningstratsCerebro.setbroker()Cerebro.add_live_bar_cohort()Cerebro.live_bar_cohortCerebro.live_bar_cohort_clockCerebro.live_bar_cohort_winddown_statusCerebro.live_bar_cohort_winddown_reasonCerebro.getbroker()Cerebro.__call__()Cerebro.__getstate__()Cerebro.__setstate__()Cerebro.run()Cerebro.broker
- backtrader.comminfo module
CommInfoBaseCommInfoBase.COMM_PERCCommInfoBase.COMM_FIXEDCommInfoBase.commissionCommInfoBase.maker_commissionCommInfoBase.taker_commissionCommInfoBase.open_commissionCommInfoBase.close_commissionCommInfoBase.close_today_commissionCommInfoBase.close_yesterday_commissionCommInfoBase.multCommInfoBase.marginCommInfoBase.commtypeCommInfoBase.stocklikeCommInfoBase.percabsCommInfoBase.interestCommInfoBase.interest_longCommInfoBase.leverageCommInfoBase.automarginCommInfoBase.__init__()CommInfoBase.set_param()CommInfoBase.get_margin()CommInfoBase.get_leverage()CommInfoBase.getsize()CommInfoBase.getoperationcost()CommInfoBase.getvaluesize()CommInfoBase.getvalue()CommInfoBase.getcommission()CommInfoBase.confirmexec()CommInfoBase.profitandloss()CommInfoBase.cashadjust()CommInfoBase.get_credit_interest()
CommissionInfoComminfoDCComminfoFuturesPercentComminfoFuturesMixedComminfoFuturesInverseComminfoFuturesFixedComminfoFundingRate
- backtrader.dataseries module
TimeFrameDataSeriesDataSeries._nameDataSeries._compressionDataSeries._timeframeDataSeries.plotinfoDataSeries.nameDataSeries.CloseDataSeries.LowDataSeries.HighDataSeries.OpenDataSeries.VolumeDataSeries.OpenInterestDataSeries.DateTimeDataSeries.LineOrderDataSeries.getwriterheaders()DataSeries.getwritervalues()DataSeries.getwriterinfo()DataSeries.get_name()DataSeries.frompackagesDataSeries.packages
OHLCOHLCDateTimeSimpleFilterWrapper
- backtrader.errors module
- backtrader.fillers module
- backtrader.flt module
- backtrader.functions module
- backtrader.linebuffer module
LineBufferLineBuffer.UnBoundedLineBuffer.QBufferLineBuffer.__init__()LineBuffer.get_idx()LineBuffer.set_idx()LineBuffer.idxLineBuffer.reset()LineBuffer.qbuffer()LineBuffer.getindicators()LineBuffer.minbuffer()LineBuffer.__len__()LineBuffer.buflen()LineBuffer.__getitem__()LineBuffer.get()LineBuffer.getzeroval()LineBuffer.getzero()LineBuffer.__setitem__()LineBuffer.set()LineBuffer.home()LineBuffer.forward()LineBuffer.backwards()LineBuffer.safe_backwards()LineBuffer.rewind()LineBuffer.advance()LineBuffer.extend()LineBuffer.addbinding()LineBuffer.plot()LineBuffer.plotrange()LineBuffer.oncebinding()LineBuffer.bind2lines()LineBuffer.bind2line()LineBuffer.__call__()LineBuffer.datetime()LineBuffer.date()LineBuffer.time()LineBuffer.dt()LineBuffer.tm_raw()LineBuffer.tm()LineBuffer.tm_lt()LineBuffer.tm_le()LineBuffer.tm_eq()LineBuffer.tm_gt()LineBuffer.tm_ge()LineBuffer.tm2dtime()LineBuffer.tm2datetime()
LineActionsCacheLineActionsMixinPseudoArrayLineActionsLineDelay()LineNum()LinesOperationLineOwnOperation
- backtrader.lineiterator module
LineIteratorMixinLineIteratorLineIterator._nextforceLineIterator._mindatasLineIterator._ltypeLineIterator.plotinfoLineIterator.plotlinesLineIterator.PlotInfoObjLineIterator.plotinfoLineIterator.PlotLinesObjLineIterator.plotlinesLineIterator.IndTypeLineIterator.StratTypeLineIterator.ObsTypeLineIterator.__new__()LineIterator.__init__()LineIterator.stop()LineIterator.getindicators()LineIterator.getobservers()LineIterator.addindicator()LineIterator.bindlines()LineIterator.bind2lines()LineIterator.bind2line()LineIterator.preonce()LineIterator.oncestart()LineIterator.once()LineIterator.prenext()LineIterator.nextstart()LineIterator.qbuffer()LineIterator.__len__()LineIterator.home()LineIterator.advance()LineIterator.size()LineIterator.frompackagesLineIterator.packages
DataAccessorDataAccessor.PriceCloseDataAccessor.PriceLowDataAccessor.PriceHighDataAccessor.PriceOpenDataAccessor.PriceVolumeDataAccessor.PriceOpenInteresDataAccessor.PriceDateTimeDataAccessor.PriceCloseDataAccessor.PriceLowDataAccessor.PriceHighDataAccessor.PriceOpenDataAccessor.PriceVolumeDataAccessor.PriceOpenInteresDataAccessor.PriceDateTimeDataAccessor.frompackagesDataAccessor.packages
IndicatorBaseObserverBaseStrategyBaseSingleCouplerMultiCouplerLinesCoupler()LineCoupler()
- backtrader.lineroot module
LineRootMixinLineRootLineRoot.IndTypeLineRoot.StratTypeLineRoot.ObsTypeLineRoot.qbuffer()LineRoot.minbuffer()LineRoot.setminperiod()LineRoot.updateminperiod()LineRoot.addminperiod()LineRoot.incminperiod()LineRoot.prenext()LineRoot.nextstart()LineRoot.next()LineRoot.preonce()LineRoot.oncestart()LineRoot.once()LineRoot.size()
LineMultipleLineSingle
- backtrader.lineseries module
MinimalDataMinimalOwnerMinimalClockLineAliasLinesManagerLinesLines.getlinealiases()Lines.itersize()Lines.__init__()Lines.__iter__()Lines.__len__()Lines.size()Lines.fullsize()Lines.extrasize()Lines.__getitem__()Lines.get()Lines.__setitem__()Lines.forward()Lines.backwards()Lines.rewind()Lines.extend()Lines.reset()Lines.home()Lines.advance()Lines.buflen()Lines.__getattr__()Lines.__setattr__()
LineSeriesMixinLineSeriesLineSeries.linesLineSeries.plotinfoLineSeries.__new__()LineSeries.PlotInfoObjLineSeries.plotinfoLineSeries.PlotLinesObjLineSeries.plotlinesLineSeries.csvLineSeries.arrayLineSeries.lineLineSeries.lLineSeries.__getattr__()LineSeries.__setattr__()LineSeries.__len__()LineSeries.__getitem__()LineSeries.__setitem__()LineSeries.__init__()LineSeries.plotlabel()LineSeries.__call__()LineSeries.forward()LineSeries.backwards()LineSeries.rewind()LineSeries.extend()LineSeries.reset()LineSeries.home()LineSeries.advance()LineSeries.size()LineSeries.chkminLineSeries.frompackagesLineSeries.packages
LineSeriesStubLineSeriesStub.extralinesLineSeriesStub.__init__()LineSeriesStub.forward()LineSeriesStub.backwards()LineSeriesStub.rewind()LineSeriesStub.extend()LineSeriesStub.reset()LineSeriesStub.home()LineSeriesStub.advance()LineSeriesStub.qbuffer()LineSeriesStub.minbuffer()LineSeriesStub.frompackagesLineSeriesStub.packages
LineSeriesMaker()
- backtrader.mathsupport module
- backtrader.metabase module
- backtrader.order module
OrderExecutionBitOrderDataOrderParamsOrderBaseOrderBase.refOrderBase.brokerOrderBase.pOrderBase.DAYOrderBase.T_CloseOrderBase.T_DayOrderBase.T_DateOrderBase.T_NoneOrderBase.V_NoneOrderBase.MarketOrderBase.CloseOrderBase.LimitOrderBase.StopOrderBase.StopLimitOrderBase.StopTrailOrderBase.StopTrailLimitOrderBase.HistoricalOrderBase.ExecTypesOrderBase.OrdTypesOrderBase.BuyOrderBase.SellOrderBase.CreatedOrderBase.SubmittedOrderBase.AcceptedOrderBase.PartialOrderBase.CompletedOrderBase.CanceledOrderBase.ExpiredOrderBase.MarginOrderBase.RejectedOrderBase.CancelledOrderBase.StatusOrderBase.refbasisOrderBase.notification_idOrderBase.replayedOrderBase.__init__()OrderBase.plimitOrderBase.clone()OrderBase.position_sideOrderBase.offsetOrderBase.getstatusname()OrderBase.getordername()OrderBase.ExecType()OrderBase.ordtypename()OrderBase.active()OrderBase.activate()OrderBase.alive()OrderBase.addcomminfo()OrderBase.addinfo()OrderBase.isbuy()OrderBase.issell()OrderBase.setposition()OrderBase.submit()OrderBase.accept()OrderBase.brokerstatus()OrderBase.reject()OrderBase.cancel()OrderBase.margin()OrderBase.completed()OrderBase.partial()OrderBase.execute()OrderBase.expire()OrderBase.trailadjust()
OrderBuyOrderStopBuyOrderStopLimitBuyOrderSellOrderStopSellOrderStopLimitSellOrder
- backtrader.parameters module
ParameterDescriptorParameterManagerParameterManager.__init__()ParameterManager.get()ParameterManager.set()ParameterManager.reset()ParameterManager.update()ParameterManager.to_dict()ParameterManager.keys()ParameterManager.items()ParameterManager.values()ParameterManager.copy()ParameterManager.inherit_from()ParameterManager.get_inheritance_info()ParameterManager.lock_parameter()ParameterManager.unlock_parameter()ParameterManager.is_locked()ParameterManager.get_locked_parameters()ParameterManager.create_group()ParameterManager.get_group()ParameterManager.get_parameter_group()ParameterManager.set_group()ParameterManager.get_group_values()ParameterManager.set_lazy_default()ParameterManager.clear_lazy_default()ParameterManager.add_change_callback()ParameterManager.remove_change_callback()ParameterManager.get_change_history()ParameterManager.clear_history()ParameterManager.add_dependency()ParameterManager.remove_dependency()ParameterManager.get_dependencies()ParameterManager.get_dependents()ParameterManager.begin_transaction()ParameterManager.commit_transaction()ParameterManager.rollback_transaction()ParameterManager.is_in_transaction()
ParameterAccessorParameterAccessor.__init__()ParameterAccessor.__getattr__()ParameterAccessor.__getstate__()ParameterAccessor.__setattr__()ParameterAccessor.__getitem__()ParameterAccessor.__setitem__()ParameterAccessor.__contains__()ParameterAccessor.__iter__()ParameterAccessor.__len__()ParameterAccessor.get()ParameterAccessor.isdefault()ParameterAccessor.notdefault()ParameterAccessor.keys()ParameterAccessor.items()ParameterAccessor.values()ParameterAccessor.to_dict()ParameterAccessor.__repr__()
LegacyParamsSchemamake_legacy_parameter_accessor()ParameterizedBaseParameterizedBase.__init_subclass__()ParameterizedBase.__init__()ParameterizedBase.get_param()ParameterizedBase.set_param()ParameterizedBase.get_param_info()ParameterizedBase.validate_params()ParameterizedBase.reset_param()ParameterizedBase.reset_all_params()ParameterizedBase.get_modified_params()ParameterizedBase.copy_params_from()ParameterizedBase.__repr__()
Int()Float()FloatParam()BoolParam()StringParam()String()Bool()OneOf()create_param_descriptor()derive_params()ParamsBridgeParameterValidationErrorParameterAccessErrorvalidate_parameter_compatibility()
- backtrader.position module
- backtrader.signal module
- backtrader.strategy module
StrategyStrategy.envStrategy.cerebroStrategy.brokerStrategy.datasStrategy.dataStrategy.positionStrategy.statsStrategy.analyzersStrategy.__new__()Strategy.__reduce_ex__()Strategy.__init__()Strategy.csvStrategy.log()Strategy.send_message()Strategy.qbuffer()Strategy.prenext_open()Strategy.nextstart_open()Strategy.next_open()Strategy.start()Strategy.getwriterheaders()Strategy.getwritervalues()Strategy.getwriterinfo()Strategy.nextstart()Strategy.stop()Strategy.set_tradehistory()Strategy.clear()Strategy.notify_fee_correction()Strategy.strategy_financial_unavailableStrategy.add_timer()Strategy.notify_timer()Strategy.notify_idle()Strategy.notify_cashvalue()Strategy.notify_fund()Strategy.notify_order()Strategy.notify_trade()Strategy.notify_store()Strategy.notify_data()Strategy.notify_tick()Strategy.notify_orderbook()Strategy.notify_funding()Strategy.notify_bar()Strategy.get_last_tick()Strategy.get_last_orderbook()Strategy.get_last_funding()Strategy.get_hft_data()Strategy.getdatanames()Strategy.getdatabyname()Strategy.cancel()Strategy.bind_service_execution_group()Strategy.submit_group_order()Strategy.query_group_order()Strategy.submit_group_roll_exit()Strategy.query_group_roll_exit()Strategy.recover_group_order()Strategy.read_group_residuals()Strategy.buy()Strategy.sell()Strategy.close()Strategy.buy_bracket()Strategy.sell_bracket()Strategy.order_target_size()Strategy.order_target_value()Strategy.strategy_mark_max_ageStrategy.strategy_mark_max_age_secondsStrategy.order_target_percent()Strategy.notify_ledger_event()Strategy.getposition()Strategy.get_strategy_position()Strategy.get_strategy_cash()Strategy.get_strategy_value()Strategy.positionStrategy.getpositionbyname()Strategy.positionbynameStrategy.getpositions()Strategy.positionsStrategy.getpositionsbyname()Strategy.positionsbynameStrategy.getaccountposition()Strategy.getaccountpositions()Strategy.setsizer()Strategy.getsizer()Strategy.sizerStrategy.getsizing()Strategy.frompackagesStrategy.packages
SignalStrategyBtApiStrategy
- backtrader.talib module
- backtrader.test_helpers module
- backtrader.timer module
- backtrader.trade module
- backtrader.tradingcal module
TradingCalendarBaseTradingCalendarBase._nextday()TradingCalendarBase.schedule()TradingCalendarBase.nextday()TradingCalendarBase.last_weekday()TradingCalendarBase.last_monthday()TradingCalendarBase.schedule()TradingCalendarBase.nextday()TradingCalendarBase.nextday_week()TradingCalendarBase.last_weekday()TradingCalendarBase.last_monthday()TradingCalendarBase.last_yearday()
TradingCalendarPandasMarketCalendar
- backtrader.version module
- backtrader.writer module
WriterBaseWriterFileWriterFile.paramsWriterFile.__init__()WriterFile.headersWriterFile.valuesWriterFile.outWriterFile.close_outWriterFile.start()WriterFile.stop()WriterFile.__enter__()WriterFile.__exit__()WriterFile.next()WriterFile.addheaders()WriterFile.addvalues()WriterFile.writeiterable()WriterFile.writeline()WriterFile.writelines()WriterFile.writelineseparator()WriterFile.writedict()
WriterStringIO