Search code examples
pine-scripttrading

How can I stop pinescript from label repainting?


I am quite new in programming world, and currently I am trying to compile an indicator in Pinescript which would plot today's bar high/low labels on a chart, next to respective lines. But as I apply my script, it keeps repainting the label on each successive candle. How can I make it so that it would keep the label only on THE LAST progressing candle?

Thank you for any help!

Here's my script:

//@version=4
study("Day High/Low with Labels", overlay=true)

t = time("1440", session.extended) // 1440=60*24 is the number of minutes in a whole day. You may use "0930-1600" as second session parameter
//plot(t, style=linebr) // debug
is_first = na(t[1]) and not na(t) or t[1] < t
plotshape(is_first, color=color.red, style=shape.arrowdown)

var float day_high = na
var float day_low = na

if is_first and barstate.isnew
day_high := high
day_low := low
else
day_high := day_high[1]
day_low := day_low[1]

if high > day_high
day_high := high

if low < day_low
day_low := low


plot(day_high, color=color.green)
plot(day_low, color=color.red)

// Add text labels to show the current day's high and low
if barstate.islast
label.new(bar_index, day_high, "TDH", xloc=xloc.bar_index, yloc=yloc.price, color=color.rgb(0, 143, 74), textcolor=color.white, style=label.style_label_down, size=size.normal)
label.new(bar_index, day_low, "TDL", xloc=xloc.bar_index, yloc=yloc.price, color=color.rgb(255, 44, 44), textcolor=color.white, style=label.style_label_up, size=size.normal)`

Solution

  • You either delete the old label or just move your label.

    // Add text labels to show the current day's high and low
    if barstate.islast
        lbl_tdh = label.new(bar_index, day_high, "TDH", xloc=xloc.bar_index, yloc=yloc.price, color=color.rgb(0, 143, 74), textcolor=color.white, style=label.style_label_down, size=size.normal)
        lbl_tdl = label.new(bar_index, day_low, "TDL", xloc=xloc.bar_index, yloc=yloc.price, color=color.rgb(255, 44, 44), textcolor=color.white, style=label.style_label_up, size=size.normal)
        label.delete(lbl_tdh[1])
        label.delete(lbl_tdl[1])