pine-scriptpine-script-v5tradingview-apiline-drawing

In pine language how to express a bar is finished and a new bar starts because I want to draw new lines once a new bar starts?


Let me give an example demand: I want to draw 2 horizontal lines which are based on the last bar once a new bar starts. One line is last bar's high price and the other line is its low price.

//@version=5
indicator(title="testing", overlay=true)

var line pressure = na
var line support  = na

if(?????)   //I don't know in pine language how to express a bar is finished and a new bar starts. 
   pressure = line.new(bar_index-1, high[1], bar_index+9, high[1], color = color.red, width=1)
   support = line.new(bar_index-1, low[1], bar_index+9, low[1], color = color.green, width=1)

I want the below result(the 2 lines are drawn by me manually for explanation): enter image description here

I think my code logic is correct but I just don't know how to express a bar is finished and a new bar starts. Or else is there any other way to achieve the same demand?

And one more result I want is to show the price numbers on the 2 lines just like the tradingview built-in Fibonacci retracement lines which shows both lines and price numbers: enter image description here

Thank you!


Solution

  • Use barstate to draw a line on a bar when it closes (this does not draw a line on a bar unless it just closed):

    //@version=5
    indicator(title="Testing", overlay=true)
    
    var line redLine = na
    var line greenLine = na
    
    if barstate.islast
        redLine := line.new(bar_index - 1, high[1], bar_index, high[1], width=1, color=color.red)
        greenLine := line.new(bar_index - 1, low[1], bar_index, low[1], width=1, color=color.green)
    

    This produces this picture with lines on the previous bar:

    enter image description here

    As for the "Fibonacci" part, are you sure thats what you want? If you just want a line that connects the bottom of a bar to the top of another bar, you can use this:

    //@version=5
    indicator(title="Testing", overlay=true)
    
    if barstate.islast and bar_index >= 3
        line.new(bar_index - 4, high[4], bar_index, low, width=1, color=color.blue)
    

    Which produces this overlay on the chart:

    enter image description here