A custom indicator is a class that inherits from bt.Indicator. It declares its output lines, for example lines = ('ecart',): each line holds one value per bar, like a feed’s close.
Parameters are declared in params = (('period', 20),) and read with self.p.period. You can then create EcartSMA(period=50) without touching the class code.
The calculation goes in __init__, using line operations: self.lines.ecart = self.data.close - bt.ind.SMA(self.data.close, period=self.p.period). Backtrader then computes the whole line, bar after bar, with no loop to write.
Backtrader works out the minimum period by itself: until the SMA 20 has 20 bars, the indicator has no value and the strategy waits. In the strategy you write self.ecart = EcartSMA(), then in next() you read self.ecart[0] (current bar) or self.ecart[-1] (previous bar).
Examples
MU-X (fictional market) : On this fictional market, the EMA 20 curve follows the price with a slight lag. An EcartSMA indicator would draw underneath the distance between price and its average: positive when the price moves above, negative when it moves below.
1978: J. Welles Wilder publishes the RSI : In his book New Concepts in Technical Trading Systems (1978), Wilder described the RSI, the ATR and the Parabolic SAR. They are just formulas applied to prices, exactly what a custom indicator lets you code. Backtrader already ships ready-made versions, such as bt.ind.RSI.
Key terms
Custom indicator
Class inheriting from bt.Indicator that computes its own lines