I have my code written to detect whether a candle closes above a higher timeframe EMA or not. The idea is to have the EMA change color to green when the current bar closes above the higher timeframe EMA and color to red when the current bar closes below the higher timeframe EMA. But I have observed some points where the opposite (or unexpected color) is shown. This totally works fine when barmerge is off. But when i turn barmerge on in order to smoothen the EMA, the inaccuracies come up in certain zones such that in some zone on the Hourly timeframe, I was seeing a discrepancy of over 10 hourly candles which were closing below the EMA which basically meant the EMA was supposed to turn red but it did not and it stayed green during all those candles. What would be likely causing this?
Below is my code.
Code: Select all
//@version=5
indicator("HTF EMA", overlay = true)
// User inputs
timeFrame = input.timeframe(defval = "D", title = "EMA Timeframe")
emaLength = input.int(title = "EMA Length", defval = 50)
smooth = input.bool(defval = false, title = "Smooth EMA?")
// Calculate EMA
ema = ta.ema(close, emaLength)
htfEMA = request.security(syminfo.tickerid, timeFrame, ema[barstate.isconfirmed ? 0 : 1], gaps = smooth ? barmerge.gaps_on : barmerge.gaps_off)
// Draw HTF EMA to chart
plot(title = "HTF EMA", series = htfEMA, color = close > htfEMA ? color.green : color.red, linewidth = 2)