Search code examples
pine-scripttrading

Draw labels on for loops generated lines


I use for loops to generate horizontal lines on round numbers (00s and 50s). In order to have those lines labeled with the price they correspond to, I draw labels using var and label.set_y. However, only one line gets labeled (the highest value one). How to have each 5 lines labeled ?

Please find my code below :

//@version=4
study(title="Round Numbers 2", overlay=true)

StepSize = 500
nbarsforward = input(title="Extend bar", defval = 70)
dt = time - time[1]

var number_of_lines = 5
var step = syminfo.mintick*StepSize
var float roundNumberLine = na
var label1 = label.new(x=na, y=na, xloc=xloc.bar_time, style=label.style_none, textcolor=color.black)

for counter = 0 to number_of_lines - 1
    roundNumberLine := ceil(close / step) * step + (counter * step)
    line.new(bar_index, roundNumberLine, bar_index - 1, roundNumberLine, xloc=xloc.bar_index, extend=extend.both, color=color.black, width=2)

label.set_y(label1, roundNumberLine)
label.set_x(label1, x=time + nbarsforward * dt)
label.set_text(label1, text=tostring(roundNumberLine))

Here's a picture of the issue when the code runs as written above.


Solution

  • Try this:

    //@version=4
    study(title="Round Numbers 2", overlay=true)
    
    StepSize = 500
    nbarsforward = input(title="Extend bar", defval = 70)
    dt = time - time[1]
    
    var number_of_lines = 5
    var step = syminfo.mintick*StepSize
    
    var lines = array.new_line(number_of_lines)
    var labels= array.new_label(number_of_lines)
    for counter = 0 to number_of_lines - 1
        roundNumberLine = ceil(close / step) * step + (counter * step)
        if na(array.get(lines, counter))
            l = line.new(bar_index, roundNumberLine, bar_index - 1, roundNumberLine, xloc=xloc.bar_index, extend=extend.both, color=color.black, width=2)
            array.set(lines, counter, l)
        else
            l = array.get(lines, counter)
            line.set_x1(l, bar_index - 1)
            line.set_x2(l, bar_index)
            
        if na(array.get(labels, counter))        
            l = label.new(x=time + nbarsforward * dt, y=roundNumberLine, text=tostring(roundNumberLine), xloc=xloc.bar_time, style=label.style_none, textcolor=color.black)
            array.set(labels, counter, l)
        else
            l = array.get(labels, counter)
            label.set_x(l, time + nbarsforward * dt)