Pine Script Drawing a horizontal line to the right of bars

ta_zoa picture ta_zoa · Aug 15, 2020 · Viewed 8.1k times · Source

I am currently trying to write up a script in Pine Script for TradingView, and am having difficulties drawing a horizontal line that only draws between the last close price/time and the end of the graph. Picture for reference attached. Link

I am current trying using line.set and line.new so that I can take in a custom price input and take the statement into an if function.

Any help to get this going would be appreciated.

Code here attached, with option to either draw a line across the entire chart or only as above.

show1 = input(true, title="|- Use Line1?")
dS1 = input(true, title="|- Short Line1")
price1 = input(title="Price1", type=input.integer, defval=0)

var line l1 = na
if show1 
    line.set_x2(l1, bar_index)
    line.set_extend(l1, extend.none)
    line.set_color(l1, color.green)
    line.set_style(l1, line.style_solid)
    line.set_width(l1, 2)
    if dS1
        l1 := line.new(bar_index, price1, bar_index, price1, extend=extend.right)
    else
        l1 := line.new(bar_index, price1, bar_index, price1, extend=extend.both)

    label label1 = label.new(bar_index, price1, "Line1", textcolor=color.green, style=label.style_none), label.delete(label1[1])

Answer

André picture André · Aug 18, 2020

The original code had a few issues including:

  • overriding extend to none
  • not deleting the line previously printed bar (like the label was)

This will do what you're looking for with one caveat (it draws it from the previous bar). its slightly more tricky to draw it from the current bar.

//@version=4
study("Line Example [MS]", overlay=true)

show1 = input(true, title="|- Use Line1?")
dS1 = input(true, title="|- Short Line1")
price1 = close

var line l1 = na
if show1 
    l1 := line.new(bar_index[1], price1, bar_index, price1, color=color.red, style=line.style_solid, width=2, extend=dS1 ? extend.right : extend.both)
    label label1 = label.new(bar_index, price1, "Line1", textcolor=color.green, style=label.style_none)
    
    line.delete(l1[1])
    label.delete(label1[1])

I suggest reading up more on line.new: https://marketscripters.com/how-to-use-pine-scripts-v4-line-function/