Search code examples
getpine-scriptlinedrawcrossover

Draw a line in pinescript v5


I wrote a code in pine script v5 for drawing a horizontal line from open of a Bullish engulfing candle to the right side for 100 candle but it should be stop drawing when a candle crossover or cross under the line but it does not work properly. Could anyone help me to correct my faults please?

//@version=5
indicator(   "_Line", overlay = true)
_White = close >= open
_Black = close <= open
_Body = (close - open)

_Eng  = _Black[2] and _White[1] and close[1] >= high[2] and _Body[1] >= 2 * _Body[2]                 

var line _Line = na 
_Level = open[1]
_Over  = ta.crossover(open, _Line.get_y2())
_Under = ta.crossunder(open, _Line.get_y2())

if _Eng
     _Line := line.new(bar_index[1], _Level, bar_index+100, _Level, width = 1)

if _Over or _Under
    line.set_x2(_Line, bar_index) 

I define engulfing candle , draw a line from Engulfing candle' open and expect when a candle in the future crossover or cross under the line, indicator stop drawing line, it draw line very well but often dose not stop drawing when a candle crossover or cross under the line.


Solution

  • You need a flag to see if the price is crossed or not. And only update it when it is not crossed.

    var line _Line = na
    var is_hit = false
    
    _Level = open[1]
    _Over  = ta.crossover(open, _Line.get_y2())
    _Under = ta.crossunder(open, _Line.get_y2())
    
    if _Eng
        _Line := line.new(bar_index[1], _Level, bar_index+100, _Level, width = 1)
        is_hit := false
    
    is_hit := (_Over or _Under) ? true : is_hit
    
    if (not is_hit)
        line.set_x2(_Line, bar_index)
    

    I'm not sure what your main goal is with this indicator because you are using open prices for the crosses and you create your line with x2=bar_index+100, so you might want to re-visit those points.