Lets say you have a moving average names ma (note that this has to be defines in your init() as self.movingaverage = bt.ind.SMA(self.data, period=10) and called in your next() as ma = self.movingaverage, which is the currently moving average value).
If your data is already in bar format, you can call the close of the bar by self.data.close.
Therefore, in your next() you can include a counter that increases every time self.data.close > ma or self.data.close < ma.
A naive example can look like this:def __init__(self): self.movingaverage = bt.ind.SMA(self.data1, period=10) def next(self): ma = self.movingaverage counter_above = 0 counter_below = 0 if self.data.close > ma: counter_above += 1 elif self.data.close < ma: counter_below += 1 else: pass
Now each time is changes (bars which were above go to be below), you can reset the counters.