pine-scriptpine-script-v5indicator

PineScript proper way of comparing previous indicator data?


I'm trying to do an indicator on pinescript and I'm pretty much new to the language. This is the code:

study("Tester", overlay = true)

ma = ema(close, 50)

signal = (high[1] > ma[1] and close[1] < ma[1])? true : false

plotshape(signal, location = location.abovebar, style = shape.xcross)

And my expected result is an x every time the upper wick of a candle goes above the 50 period ema but closes below it. I'm getting Xs where I can't seem to find any reason on why the condition triggers.

enter image description here

EDIT

Code adjusted to non-shifted bar:

study("Tester", overlay = true)

ma = ema(close, 50)

signal = (high > ma and close < ma)? true : false

plotshape(signal, location = location.abovebar, style = shape.xcross)

Image of the issue:

enter image description here


Solution

  • Thats because you shift your signal by 1 bar, so the signal X is printed on the candle when the condition was met on the previous bar.

    if you want to plot X exactly on the candle where the condition was met - don't use history reference operator ([1]).

    study("Tester", overlay = true)
    ma = ema(close, 50)
    plot(ma)
    signal = (high > ma and close < ma)? true : false
    plotshape(signal, location = location.abovebar, style = shape.xcross)