Vendrel
Vendrel

Reputation: 987

How to display only 1 plotchar() or label.new() instance?

Basic situation: Boolean variables get their true value so plotchar() or label.new() functions get triggered.

How to display only the last one of them, deleting the previous one every time?

Of course, a plotchar() should remove the previous plotchar() instance, and a label.new() removes its last label instance; no need to crosswire them. I just don't know if the solution is universal, working for both, or it's different for plotchar() and label.new() functions.

It's important that it should be limited to certain plotchar or label functions, not everything in the script.

Upvotes: 0

Views: 2301

Answers (2)

Marcus Cazzola
Marcus Cazzola

Reputation: 333

You can first create a var variable that is na. A var variable saves its value between bars. Then if something happens check if the variable is na, then create a label. This only happens one time, because right after you set the variable to the newly created label. If something happens again, just update the position.

Code example: where two labels mark where the latest "up" bar is and what the lastest "down" bar is. Tradingview image

Code:

//@version=5
indicator("one label", overlay=true)

//"var" variable that gets saved between bars. First set to na
var label up = na
var label down = na

if(close > close[1])
    if(na(up)) //Does not exist, create one
        up := label.new(bar_index, close, "last up", color=color.green, yloc=yloc.abovebar)
    else
        label.set_x(up, bar_index)
    
if(close < close[1])
    if(na(down)) //Does not exist, create one
        down := label.new(bar_index, close, "last down", color=color.red, yloc=yloc.abovebar)
    else
        label.set_x(down, bar_index)

Upvotes: 1

vitruvius
vitruvius

Reputation: 21219

You cannot remove previous plotchar() instances.

You can use label.delete() function to remove the previous label instances. Or, better, just use the label.set_x() fucntion to move it to the last bar. Deleting old ones and creating new labels will reduce the performance.

lbl = label.new(bar_index, high, "Test")
label.delete(lbl[1])

lbl2 = label.new(bar_index, high, "Test")

if barstate.islast
    label.set_x(lbl2, bar_index)
    // Update y and text if necessary

Upvotes: 3

Related Questions