Indicator¶
The Indicator class is the base class for all technical indicators.
Backtrader Indicator Module.
This module provides the base Indicator class and related infrastructure for creating and managing technical analysis indicators. It replaces the metaclass-based approach with explicit inheritance and registration.
The Indicator class serves as the foundation for all technical indicators in backtrader, managing line data, minimum periods, and calculation logic.
- class backtrader.indicator.IndicatorRegistry[source]
Bases:
objectRegistry to manage indicator classes and provide caching functionality.
This class replaces the metaclass-based indicator registration and caching mechanism from the original backtrader implementation.
- classmethod register(name, indicator_cls)[source]
Register an indicator class in the registry.
- Parameters:
name – Name of the indicator class
indicator_cls – The indicator class to register
- classmethod 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.Indicator[source]
Bases:
IndicatorBaseBase class for all technical indicators in Backtrader.
This class provides the foundation for creating custom indicators. It manages line data, minimum periods, and calculation logic. Indicators inherit from IndicatorBase and integrate with the LineIterator system for data flow.
- _ltype
Line type set to IndType (0) for indicators
- csv
Whether to output this indicator to CSV (default: False)
- aliased
Whether this indicator has an alias name
- csv = False
- __getitem__(ago)[source]
CRITICAL FIX: Forward item access to the first line (e.g., sma line)
For indicators with named lines like SMA (which has lines.sma), accessing indicator[0] should return the value from the first line, not the indicator’s own array.
- aliased = False
- classmethod __init_subclass__(**kwargs)[source]
Handle subclass registration and initialization.
This method is called when a subclass of Indicator is created. It performs: 1. Lines creation using Lines infrastructure 2. Automatic registration in IndicatorRegistry 3. Alias handling for module-level access 4. next/once method setup for calculation modes
- Parameters:
**kwargs – Additional keyword arguments
- 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.indicator.LinePlotterIndicatorBase[source]
Bases:
typeBase class for indicators that plot multiple lines.
Note: These classes are not currently used in the project. They are kept for compatibility with the original backtrader.
- class backtrader.indicator.LinePlotterIndicator[source]
Bases:
Indicator,LinePlotterIndicatorBaseIndicator that plots multiple lines.
Note: This class is not currently used in the project.
- frompackages = ()
- packages = ()
Overview¶
Indicators calculate values from data feeds and can be used in strategies for trading decisions. Backtrader includes many built-in indicators and supports custom indicator creation.
Built-in Indicators¶
Moving Averages¶
SMA: Simple Moving AverageEMA: Exponential Moving AverageWMA: Weighted Moving AverageSMMA: Smoothed Moving AverageDEMA: Double Exponential Moving AverageTEMA: Triple Exponential Moving Average
Momentum¶
RSI: Relative Strength IndexMACD: Moving Average Convergence DivergenceStochastic: Stochastic OscillatorROC: Rate of ChangeMomentum: Momentum indicatorCCI: Commodity Channel Index
Volatility¶
ATR: Average True RangeBollingerBands: Bollinger BandsStandardDeviation: Standard Deviation
Trend¶
ADX: Average Directional IndexAroon: Aroon IndicatorParabolicSAR: Parabolic SAR
Volume¶
OBV: On Balance VolumeVWAP: Volume Weighted Average Price
Creating Custom Indicators¶
class MyIndicator(bt.Indicator):
lines = ('myline',)
params = (('period', 20),)
def __init__(self):
self.addminperiod(self.params.period)
def next(self):
# Calculate indicator value
self.lines.myline[0] = sum(
self.data.close.get(size=self.params.period)
) / self.params.period
Using Indicators¶
class MyStrategy(bt.Strategy):
def __init__(self):
# Create indicators
self.sma = bt.indicators.SMA(self.data.close, period=20)
self.rsi = bt.indicators.RSI(self.data.close)
self.macd = bt.indicators.MACD(self.data.close)
# Combine indicators
self.crossover = bt.indicators.CrossOver(
self.data.close, self.sma
)
def next(self):
if self.crossover > 0 and self.rsi < 30:
self.buy()