pine-script

Label (text) next to moving averages


I have been looking in the documentation and I only find how to write labels above candles and such.

what i want to achieve is write some text next to a moving average. For instance i have a script with multiple moving averages, i would like to put next to each line what MA it is

something like this: enter image description here

any pointers on how to do this?

plot(show25SMA ? security(syminfo.tickerid, tf, sma(src, 25)) : na, title="25 SMA", color=color.white, linewidth=1)

Solution

  • SMA25 = sma(close, 25)
    
    var SMA25Label = label.new(x = bar_index, y = SMA25, style = label.style_label_left, color = color.rgb(0, 0, 0, 100), textcolor = color.yellow, text = "SMA25")
    
    label.set_xy(SMA25Label, x = bar_index, y = SMA25)
    

    By making a var declared label we create the label once, and then we use label.set_xy() to move that label every bar update to follow the MA's value.

    Using style = label.style_label_left it positions the label to the right because the point of this label's shape on the left is used as the origin of the label's x,y coordinates.

    You can then set the label itself to be invisible by being fully transparent with color.rgb(0, 0, 0, 100).