'Plotting previous day high/low/close using pine script

I have a pine script to draw previous day high/open/low as shown below:

//@version=4
strategy("Plot Lines", overlay=true)

PDH = security(syminfo.tickerid,"D",high)
PDO = security(syminfo.tickerid,"D",open)
PDL = security(syminfo.tickerid,"D",low)

plot(PDH, title="High",color=color.red,linewidth=2,trackprice=true)
plot(PDO, title="Open",color=color.yellow,linewidth=2,trackprice=true)
plot(PDL, title="Low",color=color.green,linewidth=2,trackprice=true)

The script work well but I only want previous day to be shown and ignore the others day before previous day so that the chart will not be that messy.

This is what I get from the script above: enter image description here

As you can see, it plot the PDH/PDO/PDL for every previous day, but I just want previous day (one day) only. Any help or advice will be greatly appreciated!

New Edited enter image description here

Result after apply the script enter image description here



Solution 1:[1]

You can use the line() function instead of plot().

Draw the lines if it is the last bar, and delete the previous ones along the way.

//@version=4
study("Plot Lines", overlay=true)

PDH = security(syminfo.tickerid,"D",high)
PDO = security(syminfo.tickerid,"D",open)
PDL = security(syminfo.tickerid,"D",low)

var line l_pdh = na, var line l_pdo = na, var line l_pdl = na

if barstate.islast
    l_pdh := line.new(bar_index-1, PDH, bar_index, PDH, extend=extend.both, color=color.green)
    l_pdo := line.new(bar_index-1, PDO, bar_index, PDO, extend=extend.both, color=color.blue)
    l_pdl := line.new(bar_index-1, PDL, bar_index, PDL, extend=extend.both, color=color.red)

line.delete(l_pdh[1])
line.delete(l_pdo[1])
line.delete(l_pdl[1])

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