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[源代码]¶
基类:
objectMixin for LineIterator that handles data argument processing.
This mixin provides the donew() method which processes constructor arguments to extract and properly configure data feeds before instance creation.
- classmethod __init_subclass__(**kwargs)[源代码]¶
Handle subclass initialization.
- 参数:
**kwargs -- Additional keyword arguments
- classmethod donew(*args, **kwargs)[源代码]¶
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.
- 参数:
*args -- Positional arguments that may include data feeds
**kwargs -- Keyword arguments for instance creation
- 返回:
(created_object, remaining_args, kwargs)
- 返回类型:
- classmethod dopreinit(_obj, *args, **kwargs)[源代码]¶
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
- 参数:
_obj -- The instance being initialized
*args -- Remaining positional arguments
**kwargs -- Remaining keyword arguments
- 返回:
(_obj, args, kwargs)
- 返回类型:
- classmethod dopostinit(_obj, *args, **kwargs)[源代码]¶
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
- 参数:
_obj -- The instance being finalized
*args -- Remaining positional arguments
**kwargs -- Remaining keyword arguments
- 返回:
(_obj, args, kwargs)
- 返回类型:
- class backtrader.lineiterator.LineIterator[源代码]¶
基类:
LineIteratorMixin,LineSeriesBase class for all objects that iterate over time-series data.
LineIterator is the foundation for Indicators, Strategies, Observers, and other objects that process data bar-by-bar. It manages:
Multiple data feeds with automatic clock synchronization
Minimum period calculations before full processing begins
Execution phases: prenext -> nextstart -> next
Child lineiterator registration (indicators within strategies)
Plotting configuration via plotinfo and plotlines
- _nextforce¶
Force cerebro to run in next mode instead of runonce
- _mindatas¶
Minimum number of data feeds required (default: 1)
- _ltype¶
Line type (IndType=0, StratType=1, ObsType=2)
- plotinfo¶
Plotting configuration object
- plotlines¶
Line-specific plotting configuration
- Class Attributes:
IndType: Constant for indicator type (0) StratType: Constant for strategy type (1) ObsType: Constant for observer type (2)
- class PlotInfoObj[源代码]¶
基类:
objectPlot information container for LineIterator objects.
This class stores plotting configuration attributes that control how the LineIterator is displayed in plots.
- __init__()[源代码]¶
Initialize plotinfo with default values.
Sets up default plotting attributes including subplot position, plot name, and various display options.
- get(key, default=None)[源代码]¶
Standard get method for compatibility.
- 参数:
key -- Attribute name.
default -- Default value if attribute not found.
- 返回:
The attribute value or default.
- plotinfo = <backtrader.lineiterator.LineIterator.PlotInfoObj object>¶
- class PlotLinesObj[源代码]¶
基类:
objectPlot lines configuration container for LineIterator objects.
This class stores configuration for individual lines in plots, such as colors, line styles, and other visual properties.
- get(key, default=None)[源代码]¶
Get plotlines attribute value.
- 参数:
key -- Attribute name.
default -- Default value if attribute not found.
- 返回:
The attribute value or default.
- plotlines = <backtrader.lineiterator.LineIterator.PlotLinesObj object>¶
- IndType = 0¶
- StratType = 1¶
- ObsType = 2¶
- static __new__(cls, *args, **kwargs)[源代码]¶
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.
- 参数:
*args -- Positional arguments including data feeds.
**kwargs -- Keyword arguments for parameter initialization.
- 返回:
The newly created instance.
- 返回类型:
- __init__(*args, **kwargs)¶
- stop()[源代码]¶
Called when backtesting stops.
This method ensures TestStrategy chkmin is handled properly. Can be overridden in subclasses for cleanup operations.
- getindicators()[源代码]¶
Get all indicators registered with this lineiterator.
- 返回:
List of all registered indicators.
- 返回类型:
- getobservers()[源代码]¶
Get all observers registered with this lineiterator.
- 返回:
List of all registered observers.
- 返回类型:
- addindicator(indicator)[源代码]¶
Add an indicator to this lineiterator.
- 参数:
indicator -- The indicator instance to add.
- bindlines(owner=None, own=None)[源代码]¶
Bind lines from owner to lines from own.
This creates line bindings that automatically update when the source line changes.
- 参数:
owner -- Index or name of the owner's line(s).
own -- Index or name of this object's line(s).
- 返回:
Returns self for method chaining.
- 返回类型:
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.
- 参数:
owner -- Index or name of the owner's line(s).
own -- Index or name of this object's line(s).
- 返回:
Returns self for method chaining.
- 返回类型:
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.
- 参数:
owner -- Index or name of the owner's line(s).
own -- Index or name of this object's line(s).
- 返回:
Returns self for method chaining.
- 返回类型:
self
- preonce(start, end)[源代码]¶
Process bars before minimum period is reached in runonce mode.
- 参数:
start -- Starting index.
end -- Ending index.
- oncestart(start, end)[源代码]¶
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.
- 参数:
start -- Starting index for processing.
end -- Ending index for processing.
- once(start, end)[源代码]¶
Process bars in runonce mode.
- 参数:
start -- Starting index.
end -- Ending index.
- prenext()[源代码]¶
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()[源代码]¶
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)[源代码]¶
Enable memory saving mode for lines and indicators.
- 参数:
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
- advance(size=1)[源代码]¶
Advance the line position by the specified size.
- 参数:
size -- Number of steps to advance (default: 1).
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineiterator.DataAccessor[源代码]¶
基类:
LineIteratorBase class for accessing data feed price series.
This class provides convenient aliases for accessing different price series from data feeds (open, high, low, close, volume, etc.).
- PriceClose¶
Alias for DataSeries.Close
- PriceLow¶
Alias for DataSeries.Low
- PriceHigh¶
Alias for DataSeries.High
- PriceOpen¶
Alias for DataSeries.Open
- PriceVolume¶
Alias for DataSeries.Volume
- PriceOpenInteres¶
Alias for DataSeries.OpenInterest
- PriceDateTime¶
Alias for DataSeries.DateTime
- PriceClose = 0¶
- PriceLow = 1¶
- PriceHigh = 2¶
- PriceOpen = 3¶
- PriceVolume = 4¶
- PriceOpenInteres = 5¶
- PriceDateTime = 6¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineiterator.IndicatorBase[源代码]¶
基类:
DataAccessorBase class for all indicators.
This class provides the foundation for creating custom indicators. It handles plot initialization and indicator type registration.
- _ltype¶
Set to IndType (0) to indicate this is an indicator.
- __init__(*args, **kwargs)¶
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineiterator.ObserverBase[源代码]¶
基类:
DataAccessorBase class for all observers.
Observers are similar to indicators but are used primarily for monitoring and recording strategy state rather than generating trading signals.
- _ltype¶
Set to ObsType (2) to indicate this is an observer.
- _mindatas¶
Set to 0 because observers don't consume data arguments.
- classmethod __init_subclass__(**kwargs)[源代码]¶
Automatically wrap __init__ methods of observer subclasses to handle extra arguments
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineiterator.StrategyBase[源代码]¶
基类:
DataAccessorBase class for all trading strategies.
This class provides the foundation for creating custom trading strategies. It handles indicator registration, data management, and the once() method override for proper backtesting behavior.
- _ltype¶
Set to StratType (1) to indicate this is a strategy.
- static __new__(cls, *args, **kwargs)[源代码]¶
Ensure strategies get proper data setup by directly calling LineIterator.__new__.
- once(start, end)[源代码]¶
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)[源代码]¶
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[源代码]¶
基类:
LineActionsCoupler for single line operations.
This class couples a single line source with a clock, allowing synchronization of data from different sources.
- cdata¶
The data source being coupled.
- dlen¶
Current data length.
- val¶
Current value.
- __init__(*args, **kwargs)¶
Initialize the LineBuffer instance.
Sets up all internal attributes including the array storage, index pointer, buffer mode, and performance optimization flags.
- next()[源代码]¶
Advance the coupler to the next bar.
Updates the current value if new data is available.
- frompackages = ()¶
- packages = ()¶
- class backtrader.lineiterator.MultiCoupler[源代码]¶
基类:
LineIteratorCoupler for multiple line operations.
This class couples multiple line sources with a clock, allowing synchronization of data from different sources.
- dlen¶
Current data length.
- dsize¶
Number of lines being coupled.
- dvals¶
Current values for all lines.
- frompackages = ()¶
- packages = ()¶
- __init__(*args, **kwargs)¶
- backtrader.lineiterator.LinesCoupler(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.
- 参数:
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.
- 返回:
A coupler instance for the data source.
- 返回类型:
- 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.
- 参数:
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.
- 返回:
A coupler instance for the data source.
- 返回类型: