I am trying to create a simple bit of code where you can lookback a certain amount of candles and find the last Bull or Bear candle but I seem to have completely missed something as when I add to the chart I am getting a Negative Index Study Error the idea is that when I work this out can then use to say where the last opposite candle is and when it gets broken to give a "Signal" which I will use in other code.
I expect I'm being blind to what I have missed.
//@version=5
indicator('Candle Lookback')
int lookback = input.int(title='Lookback', defval=10, minval=1)
int bearCount = 0
int bullCount = 0
int lastBearCandle = 0
int lastBullCandle = 0
int previousCandle = 2
for i = bar_index - lookback + 1 to bar_index by 1
if previousCandle == 1 and close[i] < open[i]
bearCount += 1
bearCount
else if previousCandle == 0 and close[i] >= open[i]
bullCount += 1
if bearCount > 0
lastBearCandle := i
lastBearCandle
if bullCount > 0
lastBullCandle := i
lastBullCandle
previousCandle := close[i] < open[i] ? 1 : 0
previousCandle
bearback = lastBearCandle < lookback
bullback = lastBullCandle < lookback
plot(lastBearCandle, 'Last Bear Candle', color.new(color.green, 0), linewidth=1)
plot(lastBullCandle, 'Last Bull Candle', color.new(color.red, 0), linewidth=1)`
The error was actually happening on the plot which I resolved but still the issue is somewhere else