Search code examples
pine-scriptlinepine-script-v4crossover

pinescript - draw a horizontal line immediately (not at closing) when the price cross over a line


Long will open when price cross over ema10 and short when it price cross under. Long target is l line and short target is s line.

For example, while in long, I want to draw a horizontal line immediately (not at closing) when the price cross over l line. Likewise, I want to draw a horizontal line when price cross under s line while in short. I could not draw a line because l and s are not constant. I want to calculate the price at the cross over and cross under.

Here is an example of a picture

//@version=4
study(title="ema buy sell", overlay=true)
ema1 = ema(close, 10)
l = ema1 * 1.02
s = ema1 * 0.98


plot(ema1, title="Ema 10", color=color.blue, linewidth=1, transp=0)
plot(l, title="Take Long TP", color=color.red, linewidth=2, transp=0)
plot(s, title="Take Short TP", color=color.green, linewidth=1, transp=0)


longCond = crossover(high, ema1)
shortCond = crossunder(low, ema1)

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

Solution

  • This script will print the line on the high/upperband crossover as you described.

    //@version=4
    study(title="ema buy sell", overlay=true)
    ema1 = ema(close, 10)
    l = ema1 * 1.02
    s = ema1 * 0.98
    
    plot(ema1, title="Ema 10", color=color.blue, linewidth=1, transp=0)
    plot(l, title="Take Long TP", color=color.red, linewidth=2, transp=0)
    plot(s, title="Take Short TP", color=color.green, linewidth=1, transp=0)
    
    longCond = crossover(high, ema1)
    shortCond = crossunder(low, ema1)
    
    plotshape(series=longCond, title="Long", style=shape.triangleup, location=location.belowbar, color=color.green, text="LONG", size=size.small)
    plotshape(series=shortCond, title="Short", style=shape.triangledown, location=location.abovebar, color=color.red, text="SHORT", size=size.small)
    
    var float lineOnCrossOver = na
    if crossover(high, l)
        lineOnCrossOver := l
    plot(lineOnCrossOver, color = change(lineOnCrossOver)? na : color.green)
    

    enter image description here