I'm trying to calculate the close - ta.sma(close, 5)
of 4H and display it on 1H. I have the following code:
//@version=5
indicator("close - SMA(5)")
[momentumClose, momentumClose4] = request.security(syminfo.tickerid, "240", [close - ta.sma(close, 5), close[4] - ta.sma(close[4], 5)], barmerge.gaps_on)
plot(momentumClose)
hline(0, "Zero Line", color=color.black, linestyle=hline.style_solid, linewidth=2)
bgcolor(momentumClose - momentumClose4 > 0 ? color.green : color.red)
I get the below image. This is understandable as for every bar on current timeframe's momentumClose
, momentumClose4
may not have any data as it contains data every 4 (1H) bars.
If I use barmerge.gaps_off
instead, I get the below image. While the background is now correct, I don't want to be recalculating this chart on every bar of the lower timeframe.
Is it possible to make this plot only calculate every 4H rather than every 1H on a 1H timeframe? Should I deal with barmerge.gaps_off
or plotting on the higher timeframe instead?
I decided to go with the following:
indicator("Momentum 4H")
momentumClose = request.security(syminfo.tickerid, "240", ta.sma(close, 20), barmerge.gaps_on)
calculate_difference_htf_current_vs_bars_ago(indicator, htf_bars_ago) =>
float _current_val = na
float _previous_val = na
int _count = 0
for i = 0 to 100 // 100 is placeholder
if not na(indicator[i])
_count += 1
if _count == 1
_current_val := indicator[i]
else if _count == htf_bars_ago
_previous_val := indicator[i]
break
_current_val - _previous_val
bgcolor(calculate_difference_htf_current_vs_bars_ago(momentumClose, 5) > 0 ? color.green : color.red)
It will fetch the value of the latest value from the HTF, then traverse backwards until it gets the value of the HTF htf_bars_ago
then return the difference.
If anyone has any better ideas than this, I'd be keen to know.