How to add text to a custom plotted line?

144 Views Asked by At

I am trying to label my line plots, but I can't seem to figure it out. here's the code I have so far...

if PSILastDOt
    line1 = line.new(x1=bar_index[1], y1=close, x2=bar_index, y2=close, extend = extend.both, style = line.style_solid, color = color_change, width = 2)
    label1 = label.new(bar_index + 5, close, str.tostring(close), xloc.bar_index, yloc.price, color.rgb(255, 255, 255, 100), label.style_label_up, color.white)
    line.delete(line1[CC])

This results in the following ... Screenshot

I can't use the line itself (line1) has the y variable since it's a custom plotted line. That results in " Cannot call 'label.new' with argument 'y'='line1'. An argument of 'series line' type was used but a 'series float' is expected. "

I also tried using plotshape but that didn't work either.

I've also now tried vitruvius' solution but that didn't work either.

2

There are 2 best solutions below

1
On BEST ANSWER

The error message says that you putting an object into a field which needs a number instead.
To solve that problem you could extract the x&y-positions of lines/boxes via *.get_*.

Here is an example...

line1  = line.new(x1=bar_index[1], y1=close, x2=bar_index, y2=close, extend = extend.both, style = line.style_solid, color = color_change, width = 2)
label1 = label.new(line.get_x1(line1), line1.get_y1(), "Hello World!))

It is also recommended to edit/update objects via *.set_*,
instead of creating the same instance over and over again.

3
On

Label styles matter. It will affect the placement of the text.

See the below example. I have used three different label styles, label.style_label_up, label.style_label_center, label.style_label_down. The rest is the same except for the label color. As you can see, the placement is different.

//@version=5
indicator("My script", overlay=true)

l = line.new(bar_index, close, bar_index + 1, close, extend=extend.both)
line.delete(l[1])

lbl1 = label.new(bar_index + 5, close, str.tostring(close), style=label.style_label_up, color=color.green, textcolor=color.white)
lbl2 = label.new(bar_index + 10, close, str.tostring(close), style=label.style_label_center, color=color.blue, textcolor=color.white)
lbl3 = label.new(bar_index + 15, close, str.tostring(close), style=label.style_label_down, color=color.red, textcolor=color.white)

label.delete(lbl1[1])
label.delete(lbl2[1])
label.delete(lbl3[1])

enter image description here

If you want to have your text exactly on the line, you can use label.style_label_center.