pinescript - plot cross when EMA crosses over SMA while above/ below 200 moving average

13,151

The way to do this would be using the plotshape() function. There are also different plot functions but I prefer using plotshape() for this purpose. Definitely check out other plot functions as well. Tradingview has a nice documentation for pine-script.

Also, cross() returns 1 if two series has crossed each other. It could be from below or above, it doesn't matter. However, you want to trigger your condition when a crossover happens. There is a function called crossover() for that purpose (also see crossunder() for the opposite).

//@version=3
study(title="MA Cross ATTEMPT", overlay=true)

s10ema = ema(close, 10)
s21ema = ema(close, 21)
s50ema = ema(close, 50)
s200ema = ema(close, 200)

plot(s10ema, title="Ema 10", color = red, linewidth = 1, transp=0)
plot(s21ema, title="Ema 21", color = aqua, linewidth = 1, transp=0)
plot(s50ema, title="Ema 50", color = orange, linewidth = 2, transp=0)
plot(s200ema, title="Ema 200", color = blue, linewidth = 2, transp=0)

longCond = crossover(s10ema, s21ema) and (s21ema > s50ema) and (s50ema > s200ema)
shortCond = crossunder(s10ema, s21ema) and (s21ema < s50ema) and (s50ema < s200ema)

plotshape(series=longCond, title="Long", style=shape.triangleup, location=location.belowbar, color=green, text="LONG", size=size.small)
plotshape(series=shortCond, title="Short", style=shape.triangledown, location=location.abovebar, color=red, text="SHORT", size=size.small)

enter image description here

Share:
13,151
forexfibs
Author by

forexfibs

Updated on June 09, 2022

Comments

  • forexfibs
    forexfibs about 2 years

    I am very NEW to pinescript and I am stuck at this point... I would like to plot a cross ONLY when 10 EMA crosses over 21 EMA while 21 is above 50 EMA and 50 EMA is above 200 EMA. This is to indicate Long signal. And at the same time, when 10 EMA crosses over 21 EMA while 21 is below 50 EMA and 50 EMA is below 200 EMA. This is to indicate Short signal.

    I have this much code but I don't know how to proceed further:

    //@version=3
    study(title="MA Cross ATTEMPT", overlay=true)
    
    s10ema = ema(close, 10)
    s21ema = ema(close, 21)
    s50ema = ema(close, 50)
    s200ema = ema(close, 200)
    
    plot(s10ema, color = red, linewidth = 1, transp=0)
    plot(s21ema, color = aqua, linewidth = 1, transp=0)
    plot(s50ema, color = aqua, linewidth = 2, transp=0)
    plot(s200ema, color = red, linewidth = 2, transp=0)
    
    mycond = s200ema < s50ema and s50ema < s21ema and s21ema < s10ema
    EMACross = cross(s10ema, s21ema) ? s10ema : na, style = cross, linewidth = 4, color = yellow, transp=0
    
    plot(?????)
    

    Any help would be greatly appreciated