Search code examples
pine-scriptpine-script-v5stocktradingview-api

How to add text to a custom plotted line?


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.


Solution

  • 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.