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

backtrader.__version__

Package version string

Type:

str

backtrader.__btversion__

Package version as tuple

Type:

tuple

class backtrader.OrderedDict[source]

Bases: dict

Dictionary 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: object

Enumeration 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:

str

classmethod TFrame(name)[source]

Get TimeFrame constant from name.

Parameters:

name – String name like ‘Days’, ‘Minutes’.

Returns:

TimeFrame constant.

classmethod TName(tframe)[source]

Get name string from timeframe constant.

Parameters:

tframe – TimeFrame constant.

Returns:

Name of the timeframe.

Return type:

str

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: ObserverBase

Base 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: object

Enhanced 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.

__init__(**kwargs)[source]

Initialize the parameterized object.

get_param(name, default=None)[source]

Get parameter value with fallback.

Parameters:
  • name (str) – Parameter name

  • default (Any) – Default value if parameter not found

Returns:

Parameter value

Return type:

Any

set_param(name, value, validate=True)[source]

Set parameter value with optional validation.

Parameters:
  • name (str) – Parameter name

  • value (Any) – Parameter value

  • validate (bool) – Whether to perform validation

Raises:
Return type:

None

get_param_info()[source]

Get comprehensive information about all parameters.

Returns:

Dictionary with parameter information

Return type:

Dict[str, Dict[str, Any]]

validate_params()[source]

Validate all parameters and return list of validation errors.

Returns:

List of validation error messages (empty if all valid)

Return type:

List[str]

reset_param(name)[source]

Reset parameter to its default value.

Parameters:

name (str) – Parameter name

Raises:
Return type:

None

reset_all_params()[source]

Reset all parameters to their default values.

Return type:

None

get_modified_params()[source]

Get parameters that have been modified from their defaults.

Returns:

Dictionary of modified parameter names and values

Return type:

Dict[str, Any]

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

__repr__()[source]

Enhanced string representation with parameter information.

Return type:

str

class backtrader.Strategy[source]

Bases: StrategyBase

Base 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 a SendResult whose outcomes classify 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. accepted is False and reason explains 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 invalid level or 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:

list

getwritervalues()[source]

Get current values for writer output.

Returns:

Current values from indicators and observers

Return type:

list

getwriterinfo()[source]

Get comprehensive writer information including params and analysis.

Returns:

Nested structure containing params, indicators,

observers, and analyzer results

Return type:

AutoOrderedDict

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/nextstart overrides 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 by delta.

trade (or None) already includes the change. Default: no-op.

property strategy_financial_unavailable

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 timer is the timer instance returned by add_timer, and when is the calling time. args and kwargs are any additional arguments passed to add_timer.

The actual when time 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_bar callbacks.

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 symbol is 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:

list

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

cancel(order)[source]

Cancel an order in the broker.

Parameters:

order – The order to cancel

bind_service_execution_group()[source]

Bind this Strategy to its explicit managed group-order route.

submit_group_order(intent)[source]

Submit one typed P5A group intent through the managed Broker.

query_group_order(group_id)[source]

Query an existing group ID without placing another group.

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 buy for 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; 0 means 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 time of each mark must not exceed it, where now is 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 own valuation_mark_max_age and 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=...). event is a bt_api_py.strategy_ledger.LedgerEvent with a stable event_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 by event_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 position is 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.

get_strategy_cash(broker=None, *, currency=None)[source]
get_strategy_value(broker=None, *, datas=None, currency=None)[source]
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 position is 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 positionbyname is 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 positionbyname is 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 positions is 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 positions is 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 positionsbyname is 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 positionsbyname is 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 sizer property.

property sizer

Get the current sizer for automatic stake calculation.

Returns:

The current sizer instance

Note

Also available as the sizer property.

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: ParameterizedBase

Analyzer 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 reference

  • self.data, giving access to self.datas[0]

  • self.dataX -> self.datas[X]

  • self.dataX_Y -> self.datas[X].lines[Y]

  • self.dataX_name -> self.datas[X].name

  • self.data_name -> self.datas[0].name

  • self.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 setup

  • start / stop to signal the begin and end of operations

  • prenext / nextstart / next family of methods that follow the calls made to the same methods in the strategy

  • notify_trade / notify_order / notify_cashvalue / notify_fund which 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 next calls, at the end of operations during stop and even with a single method like notify_trade

The important thing is to override get_analysis to 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 len on 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 rets created by the default create_analysis method

# Return dict-like result analysis, specific format depends on implementation

print(*args, **kwargs)[source]

Prints the results returned by get_analysis via a standard print call

pprint(*args, **kwargs)[source]

Prints the results returned by get_analysis via a pretty print call

class backtrader.TimeFrameAnalyzerBase[source]

Bases: Analyzer

Base 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).

on_dt_over()[source]

Override to handle timeframe changes.

params = (('timeframe', None), ('compression', None), ('_doprenext', True))
__init__(*args, **kwargs)[source]

Initialize with functionality previously in MetaTimeFrameAnalyzerBase

on_dt_over()[source]

Called when the timeframe period changes.

This method is called when the datetime crosses into a new period of the configured timeframe (e.g., new week, new month).

Note

Override this method to implement period-based analysis logic.

class backtrader.CommInfoBase[source]

Bases: ParameterizedBase

Base 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

__init__(**kwargs)[source]

Initialize CommInfo object

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 bypass get_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 margin if param automargin evaluates to False

  • Use param mult * price if automargin < 0

  • Use param automargin * price if automargin > 0

get_leverage()[source]

Returns the level of leverage allowed for this commission scheme

getsize(price, cash)[source]

Returns the needed size to meet a cash operation at a given price

getoperationcost(size, price)[source]

Returns the needed amount of cash an operation would cost

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

getcommission(size, price, role=None)[source]

Calculates the commission of an operation at a given price.

confirmexec(size, price, role=None)[source]

Confirms execution and returns commission.

profitandloss(size, price, newprice)[source]

Return actual profit and loss a position has

cashadjust(size, price, newprice)[source]

Calculates cash adjustment for a given price difference

get_credit_interest(data, pos, dt)[source]

Calculates the credit due for short selling or product specific

class backtrader.ParameterDescriptor[source]

Bases: object

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__(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)

  • type_ (Type | Tuple[Type, ...] | None)

name: str | None
__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.

__get__(obj, objtype=None)[source]

Get parameter value from object instance.

__set__(obj, value)[source]

Set parameter value on object instance with validation.

__delete__(obj)[source]

Delete parameter value, reverting to default.

validate(value)[source]

Validate a value for this parameter.

Parameters:

value (Any) – Value to validate

Returns:

True if value is valid, False otherwise

Return type:

bool

get_type_info()[source]

Get type information for this parameter.

Return type:

Dict[str, Any]

backtrader.get_logger(name=None)[source]

Return a logger under the backtrader namespace.

Parameters:

name – Usually __name__ of the calling module. If it already starts with "backtrader" it is used as-is; otherwise it is nested under the backtrader root (e.g. "mystuff" -> "backtrader.mystuff"). None returns the root logger.

Returns:

A logger in the backtrader hierarchy.

Return type:

logging.Logger

class backtrader.BrokerAliasMixin[source]

Bases: object

Mixin to provide method aliases without using metaclasses.

This mixin creates method aliases for compatibility with different naming conventions (e.g., get_cash/getcash, get_value/getvalue).

__init__(*args, **kwargs)[source]

Initialize the broker alias mixin.

Creates method aliases for compatibility:
  • get_cash -> getcash

  • get_value -> getvalue

Parameters:
  • *args – Positional arguments passed to parent.

  • **kwargs – Keyword arguments passed to parent.

class backtrader.BrokerBase[source]

Bases: BrokerAliasMixin, ParameterizedBase

Base 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.

start()[source]

Start the broker. Re-initializes commission info.

stop()[source]

Stop the broker.

Override this method in subclasses for cleanup operations.

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:

CommInfoBase

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 CommInfoBase

If name is None, this will be the default for assets for which no other CommissionInfo scheme 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:

float

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:

float

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(), and getposition(), because live brokers may refresh those values synchronously. A caller may receive None when a broker does not expose a local report cache.

Returns:

A mapping with optional cash, value, and positions entries, plus an optional position_legs mapping for dual-side brokers, or None if no read-only cache exists.

Return type:

dict | None

get_cached_mark_price(data)[source]

Return a local-only mark for data when 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. None means that no cached mark is available.

get_fundshares()[source]

Get the current number of shares in fund-like mode.

Returns:

Number of shares (1.0 for abstract mode).

Return type:

float

property fundshares

Get the current number of shares in fund-like mode.

Returns:

Number of shares (1.0 for abstract mode).

Return type:

float

get_fundvalue()[source]

Get the current fund value.

Returns:

Current fund value.

Return type:

float

property fundvalue

Get the current fund value.

Returns:

Current fund value.

Return type:

float

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:

bool

property fundmode

Get the current fund mode status.

Returns:

True if fund mode is enabled, False otherwise.

Return type:

bool

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:

Position

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:

Order

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:

Order

Raises:

NotImplementedError – Must be implemented by subclasses.

next()[source]

Process the next bar in the backtest.

Called by the cerebro engine for each iteration. Override in subclasses to perform per-bar operations.

class backtrader.timezone[source]

Bases: tzinfo

Fixed 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: BrokerBase

Broker Simulator

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

cash is adjusted on each iteration for instruments like futures for

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

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

Supported order types:

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

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

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

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

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

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

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

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

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

Note

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

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

Params:

# The meanings of some parameters are below

  • cash (default: 10000): starting cash

    # cash is the starting capital amount, default is 10000

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

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

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

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

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

  • filler (default: None)

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

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

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

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

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

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

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

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

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

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

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

    Note:

    • 0.01 is 1%

    • 0.001 is 0.1%

    # Percentage slippage form

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

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

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

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

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

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

  • slip_match (default: True)

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

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

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

  • slip_limit (default: True)

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

    This option controls that behavior.

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

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

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

  • slip_out (default: False)

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

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

  • coc (default: False)

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

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

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

  • coo (default: False)

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

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

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

  • int2pnl (default: True)

    Assign generated interest (if any) to the profit and loss of operation that reduces a position (be it long or short). There may be cases in which this is undesired, because different strategies are competing and the interest would be assigned on a non-deterministic basis to any of them. int2pnl defaults 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 False then the cash will be deducted as operation cost and the calculated value will be positive to end up with the same amount

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

  • fundstartval (default: 100.0)

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

  • fundmode (default: False)

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

cash
checksubmit

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

eosbar

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

filler

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_perc

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_fixed

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_open

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_match

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_limit

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

slip_out

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

coc

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

coo

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

int2pnl

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

shortcash

Advanced parameter descriptor with type checking and validation.

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

  • Automatic type checking and conversion

  • Value validation

  • Default value handling

  • Documentation support

  • Python 3.6+ __set_name__ support

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_mode parameter.

After the broker has been started the position_mode parameter is frozen (see _freeze_position_mode()). This mirrors the behaviour of BtApiBroker and 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 guard position_mode changes.

The position_mode parameter is treated specially: it is immutable once start() has run (frozen via _freeze_position_mode()), and its raw value is normalized through normalize_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_mode the value is normalized before being applied.

  • validate – When True (default), delegate to the base class so that the registered validator runs. Set to False to 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 by start().

get_notification()[source]

Get the next notification from the notification queue.

Returns:

Order notification if available, None otherwise

set_fundmode(fundmode, fundstartval=None)[source]

Set the actual fundmode (True or False)

If the argument fundstartval is not None, it will use

get_fundmode()[source]

Get the current fund mode status.

Returns:

True if fund mode is enabled, False otherwise

Return type:

bool

set_fundstartval(fundstartval)[source]

Set the starting value for fund-like performance tracking.

Parameters:

fundstartval – The starting value for the fund

set_int2pnl(int2pnl)[source]

Configure assignment of interest to profit and loss.

Parameters:

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

set_coc(coc)[source]

Configure Cheat-On-Close behavior.

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

Parameters:

coc – If True, enable cheat-on-close

set_coo(coo)[source]

Configure Cheat-On-Open behavior.

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

Parameters:

coo – If True, enable cheat-on-open

set_shortcash(shortcash)[source]

Configure short cash behavior for stock-like assets.

Parameters:

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

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

Configure percentage-based slippage.

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

  • slip_open – Apply slippage to opening prices

  • slip_limit – Allow limit order matching with slippage capping

  • slip_match – Cap slippage at high/low prices

  • slip_out – Provide slippage even outside high-low range

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

Configure fixed-point slippage.

Parameters:
  • fixed – Fixed slippage amount in price units

  • slip_open – Apply slippage to opening prices

  • slip_limit – Allow limit order matching with slippage capping

  • slip_match – Cap slippage at high/low prices

  • slip_out – Provide slippage even outside high-low range

set_filler(filler)[source]

Set a volume filler callable for order execution.

Parameters:

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

set_checksubmit(checksubmit)[source]

Set whether to check margin/cash before accepting orders.

Parameters:

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

set_eosbar(eosbar)[source]

Set end-of-session bar behavior.

Parameters:

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

seteosbar(eosbar)

Set end-of-session bar behavior.

Parameters:

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

get_cash()[source]

Get the current available cash.

Returns:

Current cash amount. Returns parameter value if not yet

initialized, otherwise returns current cash status.

Return type:

float

getcash()

Get the current available cash.

Returns:

Current cash amount. Returns parameter value if not yet

initialized, otherwise returns current cash status.

Return type:

float

set_cash(cash)[source]

Set the broker cash amount.

Parameters:

cash – Cash amount to set

setcash(cash)

Set the broker cash amount.

Parameters:

cash – Cash amount to set

add_cash(cash)[source]

Add or remove cash from the system.

Parameters:

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

get_fundshares()[source]

Get the current number of fund shares.

Returns:

Current number of shares in fund-like mode

Return type:

float

property fundshares

Get the current number of fund shares.

Returns:

Current number of shares in fund-like mode

Return type:

float

get_fundvalue()[source]

Get the fund share value.

Returns:

Current fund-like share value

Return type:

float

property fundvalue

Get the fund share value.

Returns:

Current fund-like share value

Return type:

float

cancel(order, bracket=False)[source]

Cancel an order.

Parameters:
  • order – The order to cancel

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

Returns:

True if order was cancelled, False if not found

Return type:

bool

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

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

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

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

get_leverage()[source]

Get the current account leverage ratio.

Returns:

Current leverage ratio

Return type:

float

get_orders_open(safe=False)[source]

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

The orders returned must not be touched.

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

getposition(data, 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:

Position

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:

Order

transmit(order, check=True)[source]

Transmit an order for execution.

Parameters:
  • order – Order to transmit

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

Returns:

The transmitted order

Return type:

Order

check_submitted()[source]

Check and validate submitted orders against available cash and margin.

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

submit_accept(order)[source]

Accept and activate a submitted order.

Parameters:

order – Order to accept

add_order_history(orders, notify=True)[source]

Add historical orders to the broker.

Parameters:
  • orders – Iterable of historical orders to add

  • notify – If True, send notifications for these orders

set_fund_history(fund)[source]

Set fund history for fund-like performance tracking.

Parameters:

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

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

Create and submit a buy order.

Parameters:
  • owner – Strategy or object creating the order

  • data – Data feed for the order

  • size – Order size (positive for buy)

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

  • plimit – Limit price for stop-limit orders

  • exectype – Order execution type

  • valid – Order validity

  • tradeid – Trade identifier

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

  • trailamount – Trailing stop amount

  • trailpercent – Trailing stop percentage

  • parent – Parent order (for bracket orders)

  • transmit – If True, transmit order immediately

  • histnotify – If True, notify for historical orders

  • _checksubmit – If True, validate order before submission

  • **kwargs – Additional order parameters

Returns:

The submitted buy order

Return type:

Order

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

Create and submit a sell order.

Parameters:
  • owner – Strategy or object creating the order

  • data – Data feed for the order

  • size – Order size (positive for sell)

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

  • plimit – Limit price for stop-limit orders

  • exectype – Order execution type

  • valid – Order validity

  • tradeid – Trade identifier

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

  • trailamount – Trailing stop amount

  • trailpercent – Trailing stop percentage

  • parent – Parent order (for bracket orders)

  • transmit – If True, transmit order immediately

  • histnotify – If True, notify for historical orders

  • _checksubmit – If True, validate order before submission

  • **kwargs – Additional order parameters

Returns:

The submitted sell order

Return type:

Order

notify(order)[source]

Add an order notification to the notification queue.

Parameters:

order – Order to create notification for

next()[source]

Process broker operations for the current time step.

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

class backtrader.ChannelDataRef[source]

Bases: object

Lightweight data reference for channel-only strategies.

Channel-mode HFT strategies submit orders through the standard Strategy.buy / Strategy.sell APIs but may not have LineSeries data feeds. This object provides the minimal data identity expected by brokers and order objects: _name, name and symbol.

__init__(symbol, channel_name=None)[source]

Build the minimal data identity channel strategies expect.

Parameters:
  • symbol – Instrument symbol, also used as _name and name.

  • channel_name – Channel label; defaults to symbol.

class backtrader.AbstractDataBase[source]

Bases: OHLCDateTime

Base 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:

float

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:

datetime

haslivedata()[source]

Check if this data feed has live data.

Returns:

False for base class, override for live data feeds.

Return type:

bool

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, Cerebro will deactivate preload and runonce because a live data source must be fetched tick by tick (or bar by bar)

put_notification(status, *args, **kwargs)[source]

Add arguments to notification queue

get_notifications()[source]

Return the pending “store” notifications

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.

start()[source]

Start the data feed.

Resets internal queues and sets initial status to CONNECTED.

stop()[source]

Stop the data feed.

Override in subclasses for cleanup.

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:

DataClone

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:

DataClone

setenvironment(env)[source]

Keep a reference to the environment

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:

float

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:

bool

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:

bool

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: object

Context 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.

static pop_owner()[source]

Pop the current owner from the stack.

Returns:

The popped owner, or None if the stack was empty.

static clear()[source]

Clear the owner stack (useful for testing).

class backtrader.SignalStrategy[source]

Bases: Strategy

A 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:
  • > 0 indicates a long (buy) signal

  • < 0 indicates 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 position

    • If LONGEXIT exists, it is used to exit longs

    • If SHORT signal exists and no LONGEXIT, it will close longs before opening a short

  • SHORT: - Negative (short) indications: Go short - Positive (long) indications: Close short position

    • If SHORTEXIT exists, it is used to exit shorts

    • If LONG signal exists and no SHORTEXIT, 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 positions

  • SHORTEXIT: 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 through cerebro.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 be

    • None: The first data in the system will be used

    • An int: indicating the data that was inserted at that position

    • An str: name given to the data when creating it (parameter name) or when adding it cerebro with cerebro.adddata(..., name=)

    • A data instance

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: ParameterizedBase

Timer 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.

start(data)[source]

Initialize the timer with the associated data source.

Parameters:

data – Data source for time reference and session information.

check(dt)[source]

Check if the timer should trigger at the given time.

Parameters:

dt – Numeric datetime to check.

Returns:

True if timer should trigger, False otherwise.

Return type:

bool

class backtrader.PandasMarketCalendar[source]

Bases: TradingCalendarBase

Wrapper of pandas_market_calendars for a trading calendar. The package pandas_market_calendar must be installed # pandas_market_calendar must be installed Params:

  • calendar (default None)

    The param calendar accepts 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 (default 365)

    Number of days to cache in advance for lookup

    # How many dates to cache in advance for convenient lookup

params = (('calendar', None), ('cachesize', 365))
__init__(**kwargs)[source]

Initialize the PandasMarketCalendar.

Parameters:

**kwargs – Keyword arguments for calendar parameters.

schedule(day, tz=None)[source]

Returns the opening and closing times for the given day. If the method is called, the assumption is that day is an actual trading day

The return value is a tuple with 2 components: opentime, closetime

class backtrader.TradingCalendarBase[source]

Bases: ParameterizedBase

Base 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.

_nextday(day)[source]

Returns next trading day and isocalendar components.

schedule(day)[source]

Returns opening and closing times for a day.

nextday(day)[source]

Returns next trading day.

last_weekday(day)[source]

Returns True if day is last trading day of week.

last_monthday(day)[source]

Returns True if day is last trading day of month.

schedule(day)[source]

Returns a tuple with the opening and closing times (datetime.time) for the given date (datetime/date instance)

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 True if the given day (datetime/date) instance is the last trading day of this week

last_monthday(day)[source]

Returns True if the given day (datetime/date) instance is the last trading day of this month

last_yearday(day)[source]

Returns True if the given day (datetime/date) instance is the last trading day of this month

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: object

map(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: object

range(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: object

zip(*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: WriterBase

The 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.

__enter__()[source]

Support context manager protocol.

__exit__(exc_type, exc_val, exc_tb)[source]

Ensure output stream is closed when exiting context.

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.

writelineseparator(level=0)[source]

Write a separator line for visual formatting.

Parameters:

level – Indentation level that determines separator style.

writedict(dct, level=0, recurse=False)[source]

Write a dictionary to the output with formatting.

Parameters:
  • dct – Dictionary to write.

  • level – Indentation level for nested output.

  • recurse – Whether this is a recursive call.

class backtrader.OptReturn[source]

Bases: object

Lightweight 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.

__init__(params, **kwargs)[source]

Initialize the OptReturn object.

Parameters:
  • params – Strategy parameters used in this optimization run.

  • **kwargs – Additional keyword arguments to set as attributes.

class backtrader.Cerebro[source]

Bases: RegistryMixin, NotificationMixin, RunLifecycleMixin, ChannelMixin, ExecutionMixin, RunNextMixin, RunOnceMixin, PresentationMixin, ParameterizedBase

Params:

  • preload (default: True)

    Whether to preload the different data feeds passed to cerebro for the Strategies

    Note: 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 islive method but the end user still wants to run in live mode, this parameter can be set to true

    This will simultaneously deactivate preload and runonce. 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 stdstats is True and observers are getting automatically added, this switch controls the main behavior of the BuySell observer

    • False: use the modern behavior in which the buy / sell signals are plotted below / above the low / high prices respectively to avoid cluttering the plot

    • True: 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 stdstats is True and observers are getting automatically added, this switch controls the main behavior of the Trades observer

    • False: use the modern behavior in which trades for all datas are plotted with different markers

    • True: 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:
    • True or 1: 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 preload and runonce

      • Using this setting also deactivates plotting

    • -1: datafeeds and indicators/operations at strategy level will keep all data in memory.

      For example: a RSI internally uses the indicator UpDay to make calculations. This subindicator will not keep all data in memory

      • This allows keeping plotting and preloading active.

      • runonce will be deactivated

    • -2: data feeds and indicators kept as attributes of the strategy will keep all points in memory.

      For example: a RSI internally uses the indicator UpDay to make calculations. This subindicator will not keep all data in memory

      If in the __init__ something like a = self.data.close - self.data.high is defined, then a will not keep all data in memory

      • This allows keeping plotting and preloading active.

      • runonce will 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) inside TrueRange matches the signature of the one in the bp calculation. 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 True a 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 method set_tradehistory

    Note: Enables trade update logging for all strategies. Can also be enabled per-strategy using set_tradehistory method.

  • optdatas (default: True)

    If True and optimizing (and the system can preload and use runonce, 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 in 83 seconds to 66

    Note: 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 Strategy objects (and all datas, indicators, observers …) but object with the following attributes (same as in Strategy):

    • params (or p) the strategy had for the execution

    • analyzers the 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 tz can be

    • None: in this case the datetime displayed by strategies will be in UTC, which has always been the standard behavior

    • pytz instance. It will be used as such to convert UTC times to the chosen timezone

    • string. Instantiating a pytz instance will be attempted.

    • integer. Use, for the strategy, the same timezone as the corresponding data in the self.datas iterable (0 would use the timezone from data0)

    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_open method of strategies will be called. This happens before next and 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 the open price for stake calculations

    For cheat_on_open order execution, it is also necessary to make the call cerebro.broker.set_coo(True) or instantiate a broker with BackBroker(coo=True) (where coo stands for cheat-on-open) or set the broker_coo parameter to True. 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_coo method of the broker with True to activate cheat_on_open execution. Will only do it if cheat_on_open is also True

    Note: 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 True notifications will be delivered as soon as possible (see qcheck in live feeds)

    Set to False for compatibility. May be changed to True

    Note: 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 broker instance 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.

clock must provide utc_now(), monotonic_ns(), and a single wait(timeout_seconds) operation. A clock that needs provider-event interruption may additionally provide wait_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 injected wait method. The callback waits on the engine’s generation-checked event condition and returns a boolean. A legacy clock’s wait cannot be interrupted externally; runstop() is observed after that wait returns. Cerebro never substitutes its process wall clock for this source-time mapping.

winddown_timeout_seconds is 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 property by the name broker

__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

__setstate__(state)[source]

Restore process-local run-stop state after multiprocessing pickle.

run(**kwargs)[source]

The core method to perform backtesting. Any kwargs passed to it will affect the value of the standard parameters Cerebro was instantiated with.

If cerebro has no data and no channel is 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 Event stream (StreamingEventQueue, LiveEventQueue, or any iterable yielding Event objects). Events are dispatched to the broker and then to every strategy via their notify_* 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 calling strategy.notify_tick() directly). Call cerebro.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 addstrategy

  • For Optimization: a list of lists which contain instances of the Strategy classes added with addstrategy

Return type:

list

property broker

Returns the broker instance.

This is also available as a property by the name broker

backtrader.BoolParam(default=None, doc=None)[source]

Create a boolean parameter descriptor.

Parameters:

doc (str)

Return type:

ParameterDescriptor

backtrader.Float(min_val=None, max_val=None)[source]

Create a float validator function.

Parameters:
  • min_val (float | None) – Minimum allowed value

  • max_val (float | None) – Maximum allowed value

Returns:

Validator function for float parameters

Return type:

Callable[[Any], bool]

class backtrader.CommissionInfo[source]

Bases: CommInfoBase

Base 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 percabs is also changed to True

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: CommInfoBase

Digital 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

get_margin(price)[source]

Calculate the margin required for digital currency trading.

Parameters:

price – Current price of the asset.

Returns:

Margin calculated as price * mult * margin parameter.

Return type:

float

get_credit_interest(data, pos, dt)[source]

Simplified implementation for digital currency interest calculation

class backtrader.ComminfoFuturesPercent[source]

Bases: CommInfoBase

Futures 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

get_margin(price)[source]

Calculate the margin required for futures percentage commission.

Parameters:

price – Current price of the asset.

Returns:

Margin calculated as price * mult * margin parameter.

Return type:

float

class backtrader.ComminfoFuturesMixed[source]

Bases: ComminfoFuturesPercent

Futures 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: ComminfoFuturesMixed

Inverse 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 * mult notional.

get_margin(price)[source]

Return per-contract margin from fixed contract notional.

profitandloss(size, price, newprice)[source]

Return quote-equivalent inverse-contract PnL.

cashadjust(size, price, newprice)[source]

Mark inverse futures with the same quote-equivalent PnL rule.

class backtrader.ComminfoFuturesFixed[source]

Bases: CommInfoBase

Futures 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

get_margin(price)[source]

Calculate the margin required for futures fixed commission.

Parameters:

price – Current price of the asset.

Returns:

Margin calculated as price * mult * margin parameter.

Return type:

float

class backtrader.ComminfoFundingRate[source]

Bases: CommInfoBase

Funding 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

get_margin(price)[source]

Calculate the margin required for funding rate trading.

Parameters:

price – Current price of the asset.

Returns:

Margin calculated as price * mult * margin parameter.

Return type:

float

get_credit_interest(data, pos, dt)[source]

Calculate funding rate for Binance futures

class backtrader.LineSeries[source]

Bases: LineMultiple, LineSeriesMixin, ParamsMixin

Base 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: object

Plot 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.

__contains__(key)[source]

Check if an attribute exists in the plotinfo object.

Parameters:

key – Attribute name to check.

Returns:

True if the attribute exists, False otherwise.

Return type:

bool

keys()[source]

Return list of public attribute names.

Returns:

List of non-private, non-callable attribute names.

Return type:

list

plotinfo = <backtrader.lineseries.LineSeries.PlotInfoObj object>
class PlotLinesObj[source]

Bases: object

Plot lines configuration object for LineSeries.

Stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.

__init__()[source]

Initialize plotlines container.

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.

__contains__(key)[source]

Check if an attribute exists in the plotlines object.

Parameters:

key – Attribute name to check.

Returns:

True if the attribute exists, False otherwise.

Return type:

bool

__getattr__(name)[source]

Return an empty plotline object for missing attributes.

Parameters:

name – Name of the missing attribute.

Returns:

A default plotline object with safe defaults.

Return type:

PlotLineObj

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:

array

property line

Return the first line (lines[0]) for single-line indicators.

Returns:

The first line in the lines collection.

Return type:

LineBuffer

property l

Alias for lines - used in indicator next() methods like self.l.sma[0].

Returns:

The lines container object.

Return type:

Lines

__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:

str

__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).

home()[source]

Reset all lines to the home position (beginning).

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:

int

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:

int

frompackages = ()
packages = ()
class backtrader.AutoOrderedDict[source]

Bases: OrderedDict

OrderedDict 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.

_close()[source]

Set _closed to True to prevent auto-creation.

_open()[source]

Set _closed to False to enable auto-creation.

Example

>>> d = AutoOrderedDict()
>>> d['a']['b'] = 1  # Automatically creates nested dicts
>>> d._close()  # Prevent further auto-creation
lvalues()[source]

Return dictionary values as a list.

Provides Python 2/3 compatible list of values.

Returns:

List of all values in the dictionary.

Return type:

list

class backtrader.DataSeries[source]

Bases: LineSeries

Base 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:

list

getwritervalues()[source]

Get current values for writing.

Returns:

List of current values including data name, length, and line values.

Return type:

list

getwriterinfo()[source]

Get information about the data series.

Returns:

Dictionary with name, timeframe, and compression info.

Return type:

OrderedDict

get_name()[source]

Get the name of this data series.

Returns:

Data series name.

Return type:

str

frompackages = ()
packages = ()
class backtrader.OHLC[source]

Bases: DataSeries

DataSeries with OHLCV lines but no datetime line.

Lines:

close, low, high, open, volume, openinterest

frompackages = ()
packages = ()
class backtrader.OHLCDateTime[source]

Bases: OHLC

DataSeries with datetime line plus OHLCV lines.

This is the full-featured data series for financial data.

frompackages = ()
packages = ()
class backtrader.SimpleFilterWrapper[source]

Bases: object

Wrapper 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

__init__(data, ffilter, *args, **kwargs)[source]

Initialize the filter wrapper.

Parameters:
  • data – Data source to filter.

  • ffilter – Filter class or callable.

  • *args – Positional arguments for the filter.

  • **kwargs – Keyword arguments for the filter.

__call__(data)[source]

Apply the filter to the data.

Parameters:

data – Data source to filter.

Returns:

True if bar was filtered (removed), False otherwise.

Return type:

bool

exception backtrader.BacktraderError[source]

Bases: Exception

Base exception for all backtrader exceptions.

exception backtrader.StrategySkipError[source]

Bases: BacktraderError

Requests the platform to skip this strategy for backtesting. To be raised during the initialization (__init__) phase of the instance

exception backtrader.DataError[source]

Bases: BacktraderError

Raised for data-feed problems: loading, parsing, or alignment failures.

exception backtrader.BrokerError[source]

Bases: BacktraderError

Raised for broker/execution problems: cash, margin, or matching failures.

exception backtrader.OrderError[source]

Bases: BrokerError

Raised for order-related problems: invalid size/price or rejected orders.

exception backtrader.ConfigError[source]

Bases: BacktraderError

Raised for invalid configuration or parameter values.

exception backtrader.ResearchError[source]

Bases: BacktraderError

Base class for stable, machine-readable research failures.

default_code = 'RESEARCH_ERROR'
__init__(message='', *, code=None, report=None)[source]
Parameters:
Return type:

None

exception backtrader.ResearchConfigError[source]

Bases: ResearchError, ValueError

Invalid or unsupported research configuration.

default_code = 'INVALID_CONFIG'
exception backtrader.DatasetError[source]

Bases: ResearchError, ValueError

Invalid, incomplete, or unsupported research input data.

default_code = 'INVALID_DATASET'
exception backtrader.DependencyError[source]

Bases: ResearchError, ImportError

A required runtime or public dependency is unavailable.

default_code = 'DEPENDENCY_UNAVAILABLE'
exception backtrader.DataQualityError[source]

Bases: ResearchError, ValueError

A requested quality bound is exceeded by the collected dataset.

default_code = 'LOSS_LIMIT_EXCEEDED'
exception backtrader.FactorComputationError[source]

Bases: ResearchError, RuntimeError

An unexpected native factor or line calculation failure.

__cause__ is kept by normal Python exception chaining. Callers should raise the result of FactorComputationContext.wrap() with from the original exception so its type and traceback remain available.

default_code = 'FACTOR_COMPUTATION_FAILED'
__init__(message='factor computation failed', *, factor, asset, phase, code='FACTOR_COMPUTATION_FAILED', report=None)[source]
Parameters:
Return type:

None

class backtrader.FactorComputationContext[source]

Bases: object

Duck-typed strict policy context propagated through one native factor.

The core only needs the public phase, asset_for and wrap protocol. Feed and output-line references are retained by identity so an error is attributed only when one asset can be identified unambiguously.

__init__(factor, assets_by_object=None, *, phase='construct')[source]
Parameters:
Return type:

None

factor
phase
failed
error
bind_object(obj, asset)[source]

Bind a feed or concrete output line to its declared asset name.

Parameters:
Return type:

None

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.

Parameters:

operation (Any)

Return type:

str | None

wrap(exc, *, phase=None, asset=None)[source]

Build a safe structured error; preserve exc via raise from.

Parameters:
Return type:

FactorComputationError

class backtrader.Replayer[source]

Bases: _BaseResampler

This 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:

bool

class backtrader.Resampler[source]

Bases: _BaseResampler

This 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
last(data)[source]

Called when the data is no longer producing bars

Can be called multiple times. It has the chance to (for example) produce extra bars which may still be accumulated and have to be delivered

__call__(data, fromcheck=False, forcedata=None)[source]

Called for each set of values produced by the data source

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: AbstractDataBase

Full-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: object

Base 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.

start()[source]

Start all managed data feeds.

stop()[source]

Stop all managed data feeds.

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:

DataBase

class backtrader.CSVDataBase[source]

Bases: DataBase

Base 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 _load which 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).

start()[source]

Start the CSV data feed.

Opens the CSV file and optionally skips headers.

stop()[source]

Stop the CSV data feed.

Closes the CSV file if open.

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: FeedBase

Base class for CSV feed containers.

Manages CSV data feeds with support for base path prefixing.

__init__(basepath='', **kwargs)[source]

Initialize the CSV feed base.

Parameters:
  • basepath – Base path to prepend to data file names.

  • **kwargs – Additional keyword arguments for parameters.

class backtrader.DataClone[source]

Bases: AbstractDataBase

Clones 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).

start()[source]

Start the data clone.

Initializes internal tracking variables.

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: ParameterizedBase

Base 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.

nextstart(data)[source]

Called on the first bar before filtering starts.

Parameters:

data – The data feed being filtered.

Note

Override this method to perform one-time initialization.

next(data)[source]

Process each data bar.

Parameters:

data – The data feed being filtered.

Note

Subclasses must override this method to implement filtering logic.

class backtrader.LineActions[source]

Bases: LineBuffer, LineActionsMixin, ParamsMixin

Base 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:

list

qbuffer(savemem=0)[source]

Enable queued buffer mode for memory-efficient storage.

Parameters:

savemem – Memory saving mode (0=normal, >0=enable cache mode).

plotlabel()[source]

Return the plot label for this line object

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.

classmethod cleancache()[source]

Clean the cache - called by cerebro

classmethod usecache(enable=True)[source]

Enable or disable the cache

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:

int

class backtrader.Logic[source]

Bases: LineActions

Base 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: Logic

This 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.

next()[source]

Calculate the next value with zero-division protection.

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: Logic

This 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.

next()[source]

Calculate the next value with zero/zero indetermination protection.

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: Logic

Comparison 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.

next()[source]

Calculate the next comparison value.

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: Logic

Extended 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.

next()[source]

Calculate the next extended comparison value.

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: Logic

Conditional 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.

next()[source]

Calculate the next conditional value.

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: Logic

Base 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.

next()[source]

Apply the logic function to current values from all arguments.

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: MultiLogic

MultiLogic 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: MultiLogicReduce

Generic 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: MultiLogicReduce

Logical 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: MultiLogicReduce

Logical 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: MultiLogic

Maximum operation across all arguments.

Returns the maximum value from all input lines.

static flogic(values)
frompackages = ()
packages = ()
class backtrader.Min[source]

Bases: MultiLogic

Minimum operation across all arguments.

Returns the minimum value from all input lines.

static flogic(values)
frompackages = ()
packages = ()
class backtrader.Sum[source]

Bases: MultiLogic

Sum 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: MultiLogic

Any 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: MultiLogic

All 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: DataAccessor

Base 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, LineSeries

Base 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:

  1. Multiple data feeds with automatic clock synchronization

  2. Minimum period calculations before full processing begins

  3. Execution phases: prenext -> nextstart -> next

  4. Child lineiterator registration (indicators within strategies)

  5. 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: object

Plot 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.

__contains__(key)[source]

Check if a plotinfo attribute exists.

Parameters:

key – Attribute name to check.

Returns:

True if the attribute exists, False otherwise.

Return type:

bool

keys()[source]

Return list of public attribute names.

Returns:

List of non-private, non-callable attribute names.

Return type:

list

plotinfo = <backtrader.lineiterator.LineIterator.PlotInfoObj object>
class PlotLinesObj[source]

Bases: object

Plot lines configuration container for LineIterator objects.

This class stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.

__init__()[source]

Initialize plotlines container.

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.

__contains__(key)[source]

Check if a plotlines attribute exists.

Parameters:

key – Attribute name to check.

Returns:

True if the attribute exists, False otherwise.

Return type:

bool

__getattr__(name)[source]

Get a plotline configuration, returning default for missing attributes.

Parameters:

name – Name of the plotline to retrieve.

Returns:

A default plotline object for the requested name.

Return type:

PlotLineObj

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:

LineIterator

__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:

list

getobservers()[source]

Get all observers registered with this lineiterator.

Returns:

List of all registered observers.

Return type:

list

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

__len__()[source]

Return the length of the lineiterator’s lines - optimized for hot path

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:

int

frompackages = ()
packages = ()
class backtrader.Lines[source]

Bases: object

Defines 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:

tuple

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:

int

size()[source]

Return the number of lines excluding extra lines.

Returns:

Number of main lines.

Return type:

int

fullsize()[source]

Return the total number of lines including extra lines.

Returns:

Total number of lines.

Return type:

int

extrasize()[source]

Return the number of extra lines.

Returns:

Number of extra lines.

Return type:

int

__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:

LineBuffer

get(ago=0, size=1, line=0)[source]

Get a slice of values from a specific line.

Parameters:
  • ago – Number of periods to look back (0=current).

  • size – Number of values to return.

  • line – Line index to get values from.

Returns:

Slice of values from the specified line.

Return type:

list or array

__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).

reset()[source]

Reset all lines to their initial state.

home()[source]

Reset all lines to the home position (beginning).

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:

int

__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

__setattr__(name, value)[source]

Handle attribute setting, especially _owner and line bindings

class backtrader.AutoInfoClass[source]

Bases: object

Dynamic 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.

isdefault(pname)[source]

Check if a parameter has its default value.

notdefault(pname)[source]

Check if a parameter differs from its default value.

get(name, default=None)[source]

Get a parameter value by name with optional default.

Parameters:
  • name – Name of the parameter to get.

  • default – Default value if parameter is not found.

Returns:

The parameter value or default if not found.

static __new__(cls, *args, **kwargs)[source]

Create a new instance with recursive parameter initialization.

class backtrader.IndicatorRegistry[source]

Bases: object

Registry 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 cleancache()[source]

Clear the indicator cache.

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: IndicatorBase

Base 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

classmethod cleancache()[source]

Clear the indicator cache

classmethod usecache(onoff)[source]

Enable or disable caching

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: type

Base 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.

donew(*args, **kwargs)[source]

Create a new LinePlotterIndicator instance.

Parameters:
  • *args – Positional arguments

  • **kwargs – Keyword arguments, must include ‘name’

Returns:

(created_object, args, kwargs)

Return type:

tuple

class backtrader.LinePlotterIndicator[source]

Bases: Indicator, LinePlotterIndicatorBase

Indicator 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: object

islice(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: object

repeat(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, BaseMixin

Defines 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
qbuffer(savemem=0)[source]

Change the lines to implement a minimum size qbuffer scheme

minbuffer(size)[source]

Receive notification of how large the buffer must at least be

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

addminperiod(minperiod)[source]

Add a minperiod to own … to be defined by subclasses

incminperiod(minperiod)[source]

Increment the minperiod with no considerations

prenext()[source]

It will be called during the “minperiod” phase of an iteration.

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

next()[source]

Called to calculate values when the minperiod is over

preonce(start, end)[source]

It will be called during the “minperiod” phase of a “once” iteration

oncestart(start, end)[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 once

once(start, end)[source]

Called to calculate values at “once” when the minperiod is over

size()[source]

Return the number of lines in this object

class backtrader.LineRootMixin[source]

Bases: object

Mixin to provide LineRoot functionality without metaclass

classmethod donew(*args, **kwargs)[source]

Create new instance with owner finding logic

class backtrader.LineSingle[source]

Bases: LineRoot

Base 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
addminperiod(minperiod)[source]

Add the minperiod (substracting the overlapping 1 minimum period)

incminperiod(minperiod)[source]

Increment the minperiod with no considerations

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, LineRootMixin

LineBuffer 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:

int

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:

int

reset()[source]

Resets the internal buffer structure and the indices

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:

list

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

Keyword Arguments:
  • idx (int) – Where to start relative to the real start of the buffer

  • size (int) – size of the slice to return

Returns:

A slice of the underlying buffer

getzero(idx=0, size=1)[source]

Returns a slice of the array relative to the real zero of the buffer

Keyword Arguments:
  • idx (int) – Where to start relative to the real start of the buffer

  • size (int) – size of the slice to return

Returns:

A slice of the underlying 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

Keyword Arguments:
  • size (int) – How many extra positions to rewind the buffer

  • force (bool) – Whether to force the reduction of the logical buffer regardless of the minperiod

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:

bool

rewind(size=1)[source]

Rewind the buffer by decreasing idx and lencount.

Parameters:

size – Number of positions to rewind.

advance(size=1)[source]

Advances the logical index without touching the underlying buffer

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:
  • idx (int) – Where to start relative to the real start of the buffer

  • size (int) – size of the slice to return

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

plotrange(start, end)[source]

Get a slice of data from the array.

Parameters:
  • start – Start index of the slice.

  • end – End index of the slice.

Returns:

Slice of data from start to end.

Return type:

list or array

oncebinding()[source]

Executes the bindings when running in “once” mode

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:

datetime

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:

date

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

dt(ago=0)[source]

Alias to avoid the extra chars in “datetime” for this field

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

tm2dtime(tm, ago=0)[source]

Returns the passed tm (time.struct_time) in a datetime using the timezone (if any) of the line

tm2datetime(tm, ago=0)[source]

Returns the passed tm (time.struct_time) in a datetime using the timezone (if any) of the line

class backtrader.LineActionsCache[source]

Bases: object

Cache system for LineActions to avoid repetitive calculations

classmethod enable_cache(enable=True)[source]

Enable or disable the cache.

Parameters:

enable – True to enable caching, False to disable.

classmethod clear_cache()[source]

Clear all cached values.

classmethod get_cache_key(*args)[source]

Generate cache key from arguments

class backtrader.LineActionsMixin[source]

Bases: object

Mixin to provide LineActions functionality without metaclass

classmethod dopreinit(_obj, *args, **kwargs)[source]

Pre-initialization processing for LineActions

classmethod dopostinit(_obj, *args, **kwargs)[source]

Post-initialization processing for LineActions

class backtrader.PseudoArray[source]

Bases: object

Wrapper 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
__init__(wrapped)[source]

Initialize PseudoArray with a wrapped iterable.

Parameters:

wrapped – The iterable object to wrap.

property array

Get the array representation of the wrapped object.

Returns:

Array representation of the wrapped object.

Return type:

list or array

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: LineActions

Operation 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: LineActions

Operation 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.

once(start, end)[source]

Calculate unary operation results in batch mode (runonce).

Parameters:
  • start – Starting index.

  • end – Ending index.

size()[source]

Return the number of lines in this LineActions object

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: dict

Dictionary 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: object

Mixin 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:

tuple

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:

tuple

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:

tuple

class backtrader.DataAccessor[source]

Bases: LineIterator

Base 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: DataAccessor

Base 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: DataAccessor

Base 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: LineActions

Coupler 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: LineIterator

Coupler 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)
next()[source]

Advance the coupler to the next bar.

Updates current values for all lines if new data is available.

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:

SingleCoupler or MultiCoupler

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:

SingleCoupler or MultiCoupler

class backtrader.LineMultiple[source]

Bases: LineRoot

Base 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.

addminperiod(minperiod)[source]

The passed minperiod is fed to the lines

incminperiod(minperiod)[source]

The passed minperiod is fed to the lines

qbuffer(savemem=0)[source]

Apply queued buffering to all managed lines.

Changes the lines to implement a minimum size qbuffer scheme to control memory usage during backtesting.

Parameters:

savemem – Memory savings mode (0 = normal, higher values reduce memory usage at the cost of performance).

minbuffer(size)[source]

Set minimum buffer size for all managed lines.

Receives notification of how large the buffer must at least be and propagates this requirement to all managed lines.

Parameters:

size – Minimum buffer size required.

class backtrader.MinimalData[source]

Bases: object

Minimal 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:

float

__len__()[source]

Return the length of the internal array.

Returns:

Length of the array.

Return type:

int

__getattr__(name)[source]

Return None for any missing attributes to prevent further errors.

Parameters:

name – Name of the attribute being accessed.

Returns:

Always returns None for missing attributes.

Return type:

None

class backtrader.MinimalOwner[source]

Bases: object

Minimal owner implementation for observers and analyzers.

Performance optimization: define at module level, avoid repeatedly creating classes in __getattr__.

__init__()[source]

Initialize minimal owner with default attributes.

Sets up basic attributes needed for observers and analyzers when the actual owner is not available.

class backtrader.MinimalClock[source]

Bases: object

Minimal 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.

buflen()[source]

Return buffer length.

Returns:

Always returns 1 for minimal clock.

Return type:

int

__len__()[source]

Return the length of the minimal clock.

Returns:

Always returns 0 for minimal clock.

Return type:

int

__getattr__(name)[source]

Return None for any missing attributes to prevent further errors.

Parameters:

name – Name of the attribute being accessed.

Returns:

Always returns None for missing attributes.

Return type:

None

__reduce__()[source]

Support pickling for multiprocessing.

class backtrader.LineAlias[source]

Bases: object

Descriptor 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.

__get__(obj, cls=None)[source]

Get the line from the owner’s lines buffer.

Parameters:
  • obj – The object owning the lines (typically a Lines instance).

  • cls – The class being accessed (unused).

Returns:

The line at the stored index.

Return type:

LineBuffer

__set__(obj, value)[source]

A line cannot be “set” once it has been created. But the values inside the line can be “set”. This is achieved by adding a binding to the line inside “value”

class backtrader.LinesManager[source]

Bases: object

Manager for lines operations without metaclass

class backtrader.LineSeriesMixin[source]

Bases: object

Mixin to provide LineSeries functionality without metaclass

classmethod __init_subclass__(**kwargs)[source]

Called when a class is subclassed - replaces metaclass functionality

class backtrader.LineSeriesStub[source]

Bases: LineSeries

Simulates 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).

reset()[source]

Reset the line if not a slave.

home()[source]

Reset the line to home position if not a slave.

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: object

Intended 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: object

Holds 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:

list

iterpending()[source]

Iterate over pending execution bits.

Returns:

Iterator over pending OrderExecutionBit objects.

Return type:

iterator

markpending()[source]

Mark current execution bits as pending.

Rebuilds the indices to mark which exbits are pending in clone.

clone()[source]

Clone the OrderData object.

Returns:

A cloned copy with marked pending bits.

Return type:

OrderData

class backtrader.OrderParams[source]

Bases: object

Simple 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: object

Base 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:

OrderBase

property position_side

Read-only alias for order.info.position_side.

property offset

Read-only alias for order.info.offset.

getstatusname(status=None)[source]

Returns the name for a given status or the one of the order

getordername(exectype=None)[source]

Returns the name for a given exectype or the one of the order

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:

int

ordtypename(ordtype=None)[source]

Returns the name for a given ordtype or the one of the order

active()[source]

Check if the order is active.

Returns:

True if order is active, False otherwise.

Return type:

bool

activate()[source]

Activate the order.

alive()[source]

Returns True if the order is in a status in which it can still be executed

addcomminfo(comminfo)[source]

Stores a CommInfo scheme associated with the asset

addinfo(**kwargs)[source]

Add the keys, values of kwargs to the internal info dictionary to hold custom information in the order

isbuy()[source]

Returns True if the order is a Buy order

issell()[source]

Returns True if the order is a Sell order

setposition(position)[source]

Receives the current position for the asset and stores it

submit(broker=None)[source]

Marks an order as submitted and stores the broker to which it was submitted

accept(broker=None)[source]

Marks an order as accepted

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

reject(broker=None)[source]

Marks an order as rejected

cancel()[source]

Marks an order as cancelled

margin()[source]

Marks an order as having met a margin call

completed()[source]

Marks an order as completely filled

partial()[source]

Marks an order as partially filled

execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, margin, pnl, psize, pprice)[source]

Receives data execution input and stores it

expire()[source]

Marks an order as expired. Returns True if it worked

trailadjust(price)[source]

Adjust trailing stop price.

Parameters:

price – Current price for trailing calculation.

Note

Generic interface - override in subclasses for specific behavior.

class backtrader.Order[source]

Bases: OrderBase

Order 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.

ordtype

Order type (Buy or Sell).

Type:

int | None

dteos

Date/time of end of session for order validity.

ordtype: int | None = None
__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.

expire()[source]

Check if order should be expired

Returns:

If order has expired False: If order has not expired

Return type:

True

trailadjust(price)[source]

Adjust trailing stop order price.

Parameters:

price – Current market price for trailing calculation.

For buy orders: stop price moves up as price increases. For sell orders: stop price moves down as price decreases.

class backtrader.BuyOrder[source]

Bases: Order

Buy order class.

Represents a buy order with ordtype set to Order.Buy.

ordtype: int | None = 0
class backtrader.StopBuyOrder[source]

Bases: BuyOrder

Stop buy order class.

Used for buy orders that trigger when price crosses a threshold.

class backtrader.StopLimitBuyOrder[source]

Bases: BuyOrder

Stop limit buy order class.

Used for buy orders that become limit orders after stop price is triggered.

class backtrader.SellOrder[source]

Bases: Order

Sell order class.

Represents a sell order with ordtype set to Order.Sell.

ordtype: int | None = 1
class backtrader.StopSellOrder[source]

Bases: SellOrder

Stop sell order class.

Used for sell orders that trigger when price crosses a threshold.

class backtrader.StopLimitSellOrder[source]

Bases: SellOrder

Stop limit sell order class.

Used for sell orders that become limit orders after stop price is triggered.

class backtrader.Position[source]

Bases: object

Keeps 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:

bool

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:

tuple

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:

Position

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:

Position

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: object

Difference 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: object

Provides 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.

num2date(*args, **kwargs)[source]

Convert numeric time to datetime.

Delegates to the underlying data source’s num2date method.

Returns:

Datetime object.

date2num(*args, **kwargs)[source]

Convert datetime to numeric time.

Delegates to the underlying data source’s date2num method.

Returns:

Float representing the datetime.

class backtrader.ResamplerTicks[source]

Bases: Resampler

Resampler for tick-level data.

params = (('timeframe', 1),)
class backtrader.ResamplerSeconds[source]

Bases: Resampler

Resampler for seconds-level data.

params = (('timeframe', 3),)
class backtrader.ResamplerMinutes[source]

Bases: Resampler

Resampler for minute-level data.

params = (('timeframe', 4),)
class backtrader.ResamplerDaily[source]

Bases: Resampler

Resampler for daily data.

params = (('timeframe', 5),)
class backtrader.ResamplerWeekly[source]

Bases: Resampler

Resampler for weekly data.

params = (('timeframe', 6),)
class backtrader.ResamplerMonthly[source]

Bases: Resampler

Resampler for monthly data.

params = (('timeframe', 7),)
class backtrader.ResamplerYearly[source]

Bases: Resampler

Resampler for yearly data.

params = (('timeframe', 8),)
class backtrader.ReplayerTicks[source]

Bases: Replayer

Replayer for tick-level data.

params = (('timeframe', 1),)
class backtrader.ReplayerSeconds[source]

Bases: Replayer

Replayer for seconds-level data.

params = (('timeframe', 3),)
class backtrader.ReplayerMinutes[source]

Bases: Replayer

Replayer for minute-level data.

params = (('timeframe', 4),)
class backtrader.ReplayerDaily[source]

Bases: Replayer

Replayer for daily data.

params = (('timeframe', 5),)
class backtrader.ReplayerWeekly[source]

Bases: Replayer

Replayer for weekly data.

params = (('timeframe', 6),)
class backtrader.ReplayerMonthly[source]

Bases: Replayer

Replayer for monthly data.

params = (('timeframe', 7),)
class backtrader.Signal[source]

Bases: Indicator

Signal 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: ParameterizedBase

Base class for position sizers.

This is the base class for sizers. Any sizer should subclass this and override the _getsizing method to provide custom position sizing logic.

strategy

The strategy using this sizer.

broker

The broker instance for portfolio information.

getsizing(data, isbuy)[source]

Get the position size for an order.

_getsizing(comminfo, cash, data, isbuy)[source]

Override to implement sizing logic.

set(strategy, broker)[source]

Set the strategy and broker references.

Example

>>> cerebro.addsizer(bt.sizers.FixedSize, stake=100)
uses_account_cash = True

Whether _getsizing uses the cash argument (Broker account cash).

strategy = None
broker = None
__init__(**kwargs)[source]

Initialize the Sizer with any provided parameters.

getsizing(data, isbuy)[source]

Get the position size for an order.

Parameters:
  • data – The target data for the order.

  • isbuy – True for buy operations, False for sell operations.

Returns:

The position size to use for the order, as determined

by the _getsizing method.

Return type:

int

set(strategy, broker)[source]

Set the strategy and broker references for this sizer.

Parameters:
  • strategy – The strategy instance using this sizer.

  • broker – The broker instance for portfolio information.

backtrader.SizerBase

alias of Sizer

backtrader.SizerFix

alias of FixedSize

class backtrader.Store[source]

Bases: StoreParams

Per-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.

BrokerCls

The broker class to use (None by default).

Type:

Any

DataCls

The data class to use (None by default).

Type:

Any

params = ()
BrokerCls: Any = None
DataCls: Any = None
__init__()[source]

Initialize parameters and per-instance Store lifecycle state.

getdata(*args, **kwargs)[source]

Construct the configured feed and bind it to this Store instance.

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.

put_notification(msg, *args, **kwargs)[source]

Add a message to the notification queue.

Parameters:
  • msg – The notification message.

  • *args – Additional positional arguments to store with the message.

  • **kwargs – Additional keyword arguments to store with the message.

get_notifications()[source]

Return the pending “store” notifications

class backtrader.Mapping

Bases: Collection

A 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: object

Construct 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: object

Collection 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.

items

The underlying list of items.

Type:

list

Example

collection = ItemCollection() collection.append(my_strategy, name=’mystrat’) collection[0] # Access by index collection.mystrat # Access by name

__init__()[source]

Initialize the collection with an empty items list.

__len__()[source]

Return the number of items in the collection.

append(item, name=None)[source]

Add an item to the collection with an optional name.

__getitem__(key)[source]

Get item by index.

getnames()[source]

Get list of all item names.

getitems()[source]

Return list of (name, item) tuples for unpacking.

getbyname(name)[source]

Get item 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.normalize_position_mode(mode)[source]

Normalize and validate a broker position mode.

backtrader.normalize_position_side(side)[source]

Normalize and validate a position side.

backtrader.trade_key_from_order(order)[source]

Return the trade-group key used by strategy notifications.

class backtrader.FixedSize[source]

Bases: Sizer

This 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 tranches parameter.

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 _getsizing uses the cash argument (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

__init__(**kwargs)[source]

Initialize the FixedSize sizer.

Parameters:

**kwargs – Keyword arguments for sizer configuration including stake and tranches parameters.

setsizing(stake)[source]

Set the fixed stake size for operations.

Parameters:

stake (int) – The stake size to set. If tranches > 1, this value will be divided by tranches and stored as the internal stake.

class backtrader.Trade[source]

Bases: object

Keeps 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 identifier

  • status (int): one of Created, Open, Closed # Trade status

  • tradeid: 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 0

  • size (int): current size of the trade # Current size of the trade

  • price (float): current price of the trade # Current price of the trade

  • value (float): current value of the trade # Current market value of the trade

  • commission (float): current accumulated commission # Current accumulated commission

  • pnl (float): current profit and loss of the trade (gross pnl) # Current profit and loss

  • pnlcomm (float): current profit and loss of the trade minus commission (net pnl) # Current net profit and loss after deducting commission

  • isclosed (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 null

  • isopen (bool): records if any update has opened the trade # Whether the trade has been opened

  • justopened (bool): if the trade was just opened # Whether the trade was just opened

  • baropen (int): bar in which this trade was opened # Record which bar opened the position

  • dtopen (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 method open_datetime to get a Python datetime.datetime

    or use the platform provided num2date method

  • barclose (int): bar in which this trade was closed # Which bar the trade ended on

  • dtclose (float): float coded datetime in which the trade was closed - Use method close_datetime to get a Python datetime.datetime

    or use the platform provided num2date method

    # 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 open

  • historyon (bool): whether history has to be recorded # Whether to record historical trade update events

  • history (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.

__len__()[source]

Absolute size of the trade

__bool__()[source]

Trade size is not 0

__nonzero__()

Trade size is not 0

getdataname()[source]

Shortcut to retrieve the name of the data this trade references

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: dict

Dictionary 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: object

Logger factory using the Python standard logging module.

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.

create_logger()[source]

Create and return a configured logging.Logger instance.

Returns:

Logger with file handler (daily rotation) and optionally a console handler.

Return type:

logging.Logger

class backtrader.filter

Bases: object

filter(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: Strategy

A 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 = ()
log(txt)[source]

Log a message at INFO level.

Parameters:

txt – The message text to log.

packages = ()
class backtrader.TradeHistory[source]

Bases: AutoOrderedDict

Represents 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:: - status

Holds 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:

dict with ‘.’ 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:

dict with ‘.’ notation

__init__(status, dt, barlen, size, price, value, pnl, pnlcomm, tz, event=None)[source]

Initializes the object to the current status of the Trade

doupdate(order, size, price, commission)[source]

Used to fill the update part of the history entry

datetime(tz=None, naive=True)[source]

Returns a datetime for the time the update event happened

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:

date

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 backtrader logger hierarchy (opt-in).

Backtrader emits nothing until you call this. It configures only the backtrader logger (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 with log_dir.

  • log_dir – If given, enable the iteration-29 split-file layout log_dir/<script>/<YYYY_MM_DD>/{error,warning,info}.log (plus debug.log when level=DEBUG). <script> comes from script_name or auto-detection of sys.argv[0].

  • script_name – Directory name under log_dir. None auto-detects from sys.argv[0] (xxx/run.py -> xxx_run).

  • backend – "auto" (default; prefer the optional spdlog package, fall back to stdlib with one diagnostic), "spdlog" (raise ImportError if 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 backtrader root logger.

Return type:

logging.Logger

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). None targets the root. A root-level update with active split-file logging atomically rebuilds its handler matrix, so a DEBUG transition creates debug.log and 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 (mode 0600).

Returns:

The anchor mapping.

Return type:

dict

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 (mode 0600).

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

dict

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: transport and smtp_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 example BT_NOTIFY_CHANNELS=dingtalk,telegram with BT_NOTIFY_DINGTALK_ACCESS_TOKEN and BT_NOTIFY_TELEGRAM_BOT_TOKEN.

Parameters:
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:

str

backtrader.flush_notifications(timeout=5.0)[source]

Wait for queued notifications to be delivered.

Parameters:

timeout – Maximum seconds to wait.

Returns:

True when every queue drained (or nothing is configured).

Return type:

bool

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:

dict

backtrader.notification_stats()[source]

Return a read-only snapshot of per-channel statistics.

Returns:

Instance name to statistic mapping (empty when unconfigured).

Return type:

dict

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.stop or a timer.

Parameters:

timeout – Request timeout override.

Returns:

Number of ClawBot instances successfully polled.

Return type:

int

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 – True sends synchronously and returns delivery results; None uses the configured default.

  • timeout – Per-request timeout, only honoured when wait is 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_clawbot or qq_bot.

  • anchor – Mapping returned by bind_wechat_clawbot/bind_qq_bot.

Returns:

Number of channel instances updated.

Return type:

int

class backtrader.Iterable

Bases: object

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: ParameterizedBase

Base 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: WriterFile

Writer 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.

stop()[source]

Seek to beginning for reading.

getvalue()[source]

Get the content from the StringIO object.

class backtrader.LiveProfile[source]

Bases: object

Declarative description of a single Cerebro run.

Captures the run mode (backtest or live), the strategy class plus its args/kwargs, the data source description (dataname, symbols or a custom data_factory), the broker construction knobs and the optional live store configuration. __post_init__ normalizes the inputs and runs a set of consistency checks so that build_cerebro() can produce a fully wired Cerebro without further validation.

mode

"backtest" or "live". Validated in __post_init__.

Type:

str

strategy

The strategy class to register on the Cerebro.

Type:

type

frequency

One of "lowfreq", "midfreq" or "hft". Used by downstream broker/feed wiring to pick the right defaults.

Type:

str

dataname

Optional single-source identifier (e.g. CSV path).

Type:

str | None

symbols

Optional tuple of symbol identifiers for multi-feed runs.

Type:

Tuple[str, …]

strategy_args

Positional arguments forwarded to the strategy constructor.

Type:

Tuple[Any, …]

strategy_kwargs

Keyword arguments forwarded to the strategy constructor.

Type:

Dict[str, Any]

data_cls

Optional explicit data feed class.

Type:

type | None

data_factory

Optional callable returning one or more pre-built data instances. Mutually exclusive with dataname/symbols.

Type:

Callable[[], Any] | None

data_kwargs

Keyword arguments forwarded to the data feed constructor.

Type:

Dict[str, Any]

data_name

Optional explicit name attached to the (single) data feed.

Type:

str | None

broker_cls

Optional explicit broker class.

Type:

type | None

broker_factory

Optional callable returning a broker instance.

Type:

Callable[[…], Any] | None

broker_kwargs

Keyword arguments forwarded to the broker constructor.

Type:

Dict[str, Any]

store_factory

Optional callable returning a live store instance.

Type:

Callable[[], Any] | None

store_kwargs

Keyword arguments forwarded to the live store constructor.

Type:

Dict[str, Any]

store_provider

Live-store provider name ("btapi" by default).

Type:

str

cerebro_kwargs

Keyword arguments forwarded to the Cerebro constructor.

Type:

Dict[str, Any]

mode: str
strategy: type
frequency: str = 'lowfreq'
dataname: str | None = None
symbols: Tuple[str, ...] = ()
strategy_args: Tuple[Any, ...] = ()
strategy_kwargs: Dict[str, Any]
data_cls: type | None = None
data_factory: Callable[[], Any] | None = None
data_kwargs: Dict[str, Any]
data_name: str | None = None
broker_cls: type | None = None
broker_factory: Callable[[...], Any] | None = None
broker_kwargs: Dict[str, Any]
store_factory: Callable[[], Any] | None = None
store_kwargs: Dict[str, Any]
store_provider: str = 'btapi'
cerebro_kwargs: Dict[str, Any]
__post_init__()[source]

Run every input-normalization and validation pass.

property is_live: bool

Return True when the profile’s mode is "live".

Used by build_cerebro() and friends to branch between the live (store-backed) and backtest (CSV-backed) wiring paths without re-comparing the raw mode string.

__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>)
Parameters:
Return type:

None

backtrader.build_cerebro(profile)[source]

Construct a fully wired-up Cerebro from profile.

The function instantiates the store (for live profiles), the broker and the data feeds according to profile, attaches them to a fresh Cerebro, and registers the strategy. The profile and store are exposed back on the Cerebro as live_profile and profile_store for downstream introspection.

Parameters:

profile (LiveProfile) – The LiveProfile describing the run.

Returns:

A Cerebro instance with the broker, data feed(s) and strategy attached.

Return type:

Cerebro

class backtrader.BarEvent[source]

Bases: EventData

OHLCV bar event data.

Compatible with existing backtrader bar-level data format.

open

Opening price.

Type:

float

high

Highest price.

Type:

float

low

Lowest price.

Type:

float

close

Closing price.

Type:

float

volume

Total volume during bar period.

Type:

float

openinterest

Open interest (for futures).

Type:

float

__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, swap or futures).

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

open: float = 0.0
high: float = 0.0
low: float = 0.0
close: float = 0.0
volume: float = 0.0
openinterest: float = 0.0
property event_type: str

Return the event type identifier.

Returns:

The string ‘bar’ for OHLCV bar events.

Return type:

str

validate()[source]

Validate bar event fields.

Checks:
  • Common fields valid (via super)

  • All OHLC prices > 0

  • High >= Low

  • High >= Open, Close

  • Low <= Open, Close

  • Volume >= 0

Return type:

bool

class backtrader.FundingEvent[source]

Bases: EventData

Funding rate event for perpetual contracts.

rate

Current funding rate.

Type:

float

mark_price

Current mark price.

Type:

float

next_funding_time

Timestamp of next funding settlement.

Type:

float

predicted_rate

Predicted next funding rate.

Type:

float

__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, swap or futures).

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

rate: float = 0.0
mark_price: float = 0.0
next_funding_time: float = 0.0
predicted_rate: float = 0.0
property event_type: str

Return the event type identifier.

Returns:

The string ‘funding’ for funding rate events.

Return type:

str

validate()[source]

Validate funding event fields.

Checks:
  • Common fields valid (via super)

  • Mark price > 0

  • Funding rate within reasonable range (-1, 1)

  • Next funding time > current timestamp

Return type:

bool

class backtrader.MarketOrderBookEnvelope[source]

Bases: object

Backtrader 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 at sdk_event and carries the authoritative source, cursor, and clock. These events are suitable for notification callbacks only; execution_eligible is permanently false until a separate clock and execution-quality contract is available.

sdk_event: object
data_name: str
exchange_name: str
execution_eligible: bool = False
property event_type: str
property symbol: str
property exchange: str
property asset_type: str
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 sequence: int
property previous_sequence
property snapshot_or_delta: str
property continuity_status: str
property stale: bool
property stale_reason: str
property recovery_snapshot: bool
property freshness_status
property event_id: str
__init__(sdk_event, data_name, exchange_name, execution_eligible=False)
Parameters:
  • sdk_event (object)

  • data_name (str)

  • exchange_name (str)

  • execution_eligible (bool)

Return type:

None

class backtrader.OrderBookSnapshot[source]

Bases: EventData

Order 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.

bids

List of (price, quantity) tuples, descending by price.

Type:

List[Tuple[float, float]]

asks

List of (price, quantity) tuples, ascending by price.

Type:

List[Tuple[float, float]]

__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, swap or futures).

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

bids: List[Tuple[float, float]]
asks: List[Tuple[float, float]]
recovery_snapshot: bool = False
property event_type: str

Return the event type identifier.

Returns:

The string ‘orderbook’ for order book snapshot events.

Return type:

str

property best_bid: float | None

Best (highest) bid price.

property best_ask: float | None

Best (lowest) ask price.

property spread: float | None

Spread between best ask and best bid.

property mid_price: float | None

Mid price between best bid and best ask.

validate()[source]

Validate order book specific fields.

Checks:
  • Common fields valid (via super)

  • At least one bid and one ask level

  • Bids in descending order

  • Asks in ascending order

  • Best ask > best bid (positive spread)

  • All prices > 0 and quantities > 0

Return type:

bool

class backtrader.TickEvent[source]

Bases: EventData

Tick/trade event data.

Represents a single trade execution on an exchange. Compatible with the existing TickerData interface via adapter pattern.

price

Trade execution price.

Type:

float

volume

Trade execution volume/amount.

Type:

float

direction

Trade direction (‘buy’ or ‘sell’).

Type:

str

trade_id

Exchange trade identifier.

Type:

str

bid_price

Best bid price at time of trade.

Type:

float | None

ask_price

Best ask price at time of trade.

Type:

float | None

bid_volume

Best bid volume at time of trade.

Type:

float | None

ask_volume

Best ask volume at time of trade.

Type:

float | None

__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, swap or futures).

  • local_time (float | None) – Local receive timestamp used for latency tracking.

  • price (float) – Trade price.

  • volume (float) – Trade volume.

  • direction (str) – Aggressor side, buy or sell.

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

price: float = 0.0
volume: float = 0.0
direction: str = 'buy'
trade_id: str = ''
bid_price: float | None = None
ask_price: float | None = None
bid_volume: float | None = None
ask_volume: float | None = None
property event_type: str

Return the event type identifier.

Returns:

The string ‘tick’ for tick events.

Return type:

str

validate()[source]

Validate tick-specific fields.

Checks:
  • Common fields valid (via super)

  • Price > 0

  • Volume >= 0

  • Direction is ‘buy’ or ‘sell’

  • Optional bid/ask prices > 0 if present

Return type:

bool

class backtrader.Event[source]

Bases: object

Event wrapper for queue ordering.

Events are ordered by (timestamp, priority, sequence) for deterministic processing order. The data field is excluded from comparison.

timestamp

Event timestamp (seconds).

Type:

float

priority

Processing priority (lower = first).

Type:

int

sequence

Insertion sequence number for stable sort.

Type:

int

channel_type

Source channel type identifier.

Type:

str

channel_name

Source channel/symbol name.

Type:

str

data

The actual event data (EventData subclass instance).

Type:

Any

timestamp: float = 0.0
priority: int = 20
sequence: int = 0
channel_type: str = ''
channel_name: str = ''
data: Any = None
__init__(timestamp=0.0, priority=EventPriority.TICK, sequence=0, channel_type='', channel_name='', data=None)
Parameters:
Return type:

None

class backtrader.EventPriority[source]

Bases: IntEnum

Event 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: object

Memory-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.

property empty: bool

Whether the queue is empty and all sources exhausted.

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

property heap_size: int

Current number of events in the heap.

property total_events_popped: int

Total number of events popped from the queue.

property current_timestamp: float

Current processing timestamp.

__len__()[source]

Return the current number of events in the heap.

Returns:

Number of events currently in the heap.

Return type:

int

__iter__()[source]

Iterate over all events in timestamp order.

Yields:

Event – The next event in timestamp order.

__bool__()[source]

Return whether the queue has events available.

Returns:

True if the queue is not empty, False otherwise.

Return type:

bool

__repr__()[source]

Return a string representation of the queue.

Returns:

Representation showing heap size, popped count, and window.

Return type:

str

Subpackages

Submodules