'How to draw MA horizontal lines in Pine Script

dma120=request.security(syminfo.tickerid, "D",ta.sma(close,120))
plot(dma120, color= color.blue, title = "D MA120" )

h4ma30=request.security(syminfo.tickerid, "240",ta.sma(close,30))
plot(h4ma30, color= color.red, title = "4H MA30" )

hline(3.14, title='Pi', color=color.blue, linestyle=hline.style_dotted, linewidth=2)

In this way, it can only plot the lines, and it is impossible to use the value of the MA to the HLINE function.

It is displayed in whole layout by using Hline function, but I don't want it in that way. I want it achieved the result that I attached on the bottom.

enter image description here



Solution 1:[1]

You can do that by using line from drawings.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius

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

dma120=request.security(syminfo.tickerid, "D", ta.sma(close,120))
plot(dma120, color= color.blue, title = "D MA120" )

var line l_dma120 = line.new(bar_index, dma120, bar_index+1, dma120, extend=extend.right, color=color.yellow)

if barstate.islast
    line.set_xy1(l_dma120, bar_index, dma120)
    line.set_xy2(l_dma120, bar_index+1, dma120)

Blue line is the plot, and yellow line is the line.

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vitruvius