hi…
From your original post, I think the reason you may be getting the infinite loop is this:
To exit the loop ‘i’ has to equate up to ‘triggerBars’+1.
Now let’s say halve the candles in your chart are bull candles, ‘i’ can only increment up to halve of what ever you set ‘triggerBars’ to, since it only increments on a bull candle via the if condition. Along with this may be some error checking of historical bars loaded and also it has to end the loop before moving on to next bar. Don’t really fully understand whats going on, but that’s my thinking
If you replace ‘i’ with runback in the ‘while’ condition, ‘runback’ always ends up ‘1’ bigger at the end of each loop iteration. This then terminates the loop at the end of the iteration when ‘triggerBars’ value is hit.
Any way, I was looking at huge problem and your ‘up candle moving average’ kind of brushed against a concept I come up with and was thinking of using to solve it.
While testing the concept I knocked up this code, which I think does something very close to what you were trying to do.
It identify up candle’s and uses them to display a SMA via a lookback value. Two things to note, your up candle may be different from my define, and the SMA doesn’t use the current candle, not tested.
Hold on to nuts, get your head around this!
defparam drawOnLastBarOnly = true // comment out to see arrows over up candles
once cnt = -1 // up candle barindex count
lookback = 10
//---------------------- indentify up candles - see below
candle = 0
if open < close or (open[1] < close[1] and close[1] < close) then // define up candle
candle = 1
endif
//---------------------- on up candles
if candle then // if a up candle
cnt=cnt+1 // increment the count on a new up candle
upBarindex = cnt // store the count
accClose = accClose + close // keep an accumulated total of the up candle close's for sma calculation
drawArrowDown(barindex,high+10)
else
upBarindex = -1 // if not up candle fill value with -1 for an identifier
endif
//---------------------- indentify last closed up candle
for i = 1 to barindex[1] // loop back to find previous upBarindex
if upBarindex[i] > -1 then // stop on first non -1
x= upBarindex[i]
drawtext("previous #x#",0,0)anchor(middle)
previous = i // previous lookback distance
break // terminate loop when found
endif
next
//---------------------- indentify lookback up candle
for i = 1 to barindex[1] // loop back to find lookback upBarindex
if upBarindex[i] = upBarindex[previous]-(lookback) then // stop
y = upBarindex[i]
drawtext("lookback #y#",0,-20)anchor(middle)
back = i // lookback distance
break // terminate loop when found
endif
next
//---------------------- calculate sma using accumulated total data
upSMA = (accClose[previous] - accClose[back])/lookback
//---------------------- compare sma
sma= average[lookback](close)
return UpSma as"upSma", sma as"sma"style(dottedline,1)