I have a variable defined by a fairly simple if else if statement.
cb_dif = if not avg_range_style and close > open
close - open
else if not avg_range_style and close < open
open - close
else if avg_range_style
close - open
I don't have any issues with the final part of the statement 'else if avg_range_style', but the first part (first 4 lines) is giving me some problems. This is a volatility indicator that simply measures the value of a candle between its close and open and then applies a moving average to it. Values are always positive because I'm always subtracting the smaller value from the larger (except for the final 'else if' which turns the indicator into an oscillator around a 0 line, but as I said, the indicator works properly in this case).
////MOVING AVERAGE TO USE TO CREATE THE AVERAGE
cb_range(type, src, period) =>
float result = 0
if type == 'EMA'
result := ta.ema(cb_dif, period)
if type == 'HMA'
result := ta.hma(cb_dif, period)
if type == 'RMA'
result := ta.rma(cb_dif, period)
if type == 'SMA'
result := ta.sma(cb_dif, period)
if type == 'VWMA'
result := ta.vwma(cb_dif, period)
if type == 'WMA'
result := ta.wma(cb_dif, period)
result
avg_range = cb_range(average_type, cb_dif, period)
plot(avg_range, title='Average Candle Bodies Range', color=avg_range_color, linewidth=2, style=plot.style_histogram)
Sometimes the indicator doesn't plot for anywhere for 2 candles. This begins with a candle whose close is equal to its open, thus, a 0 difference. I'm not sure how this is an issue though, given that I'm taking a moving average of all numbers in a defined period and adding 0 to it while dropping the oldest value. I'm not a great coder though, and certainly no mathematician, so I'm probably overlooking something here.
My thoughts are this has something to do with na, nz, or NaN values, but I'm unsure as to how to go about incorporating them into the code. Also, I'm not sure what I should be looking for exactly here. Like, is there a way to make this continue the calculations in such a way that a moving average of a series of numbers with a 0 added to it simply becomes a smaller average number (what I would think should happen)? It makes sense to me that if I have the lookback set to 1 that on bars that produce 0 price difference between close and open the indicator wouldn't plot for that part, but I don't understand why it should affect so profoundly an average.
I've looked at na, nz, and NaN in the pinescript manual, but I'm struggling to wrap my head around what I would need to do here.
Thanks anyone for the help. This is pretty much the last bit before I can get this indicator published.
That first statement syntax looks incorrect. You cant use an if statement inside of a variable declaration.
float cb_dif = 0.0
if not avg_range_style and close > open or
cb_dif := close - open
else if not avg_range_style and close < open
cb_dif := open - close
else if avg_range_style
cb_dif := close - open