Search code examples
pine-scriptpine-script-v5pine-script-v4

pinescript to draw horizontal lines with for loop


Below pinescript code gives me an error,

Cannot call 'hline' with argument 'price'='open_grid'. An argument of 'series float' type was used but a 'input float' is expected.

Cannot use 'hline' in local scope.

Basically I would like to draw horizontal lines by for loop.

Any help would be appreciated.

//@version=5
indicator("Example 1", overlay = true)


float open_init = 20000
float tp = 100


for var i = 0 to 2
    float open_grid = open_init + (tp) * i

    hline( open_grid, "open",  color.lime)

Solution

  • To draw horizontal lines from the for loop, use the line.new() function instead of hline(). The script below also uses the barstate.islast condition to prevent lines from being drawn on every bar of the chart.

    //@version=5
    indicator("Example 1", overlay = true)
    
    float open_init = 20000
    float tp = 100
    
    if barstate.islast
        for i = 0 to 2
            float open_grid = open_init + (tp) * i
            line.new(bar_index, open_grid, bar_index + 1, open_grid, xloc.bar_index, extend.both, color.lime)