backtrader.lineiterator module

Backtrader LineIterator Module.

This module provides the LineIterator class which is the base for all objects that iterate over data in a time-series manner. This includes Indicators, Observers, Strategies, and other line-based objects.

The LineIterator manages: 1. Data feeds and their access patterns 2. Minimum period calculations 3. Execution phases (prenext, nextstart, next) 4. Clock synchronization between multiple data feeds 5. Registration of child lineiterators (indicators, observers)

class backtrader.lineiterator.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.lineiterator.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

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