pine script in trading view - the first occurrence of a candle condition

Viewed 18

I only need to tag the first eligible candle. I have a set price level - and only the first candle that closes above it should be marked. I can't do this. Can anyone help me? On the screenshot I marked which candle I care about (in green), the one marked in red I do not need. Thank you for any help. enter image description here enter image description here

1 Answers

You need to use the var keyword so that the value of the variable does not reset on every new bar. Then, if triggered, you will redefine its state to a new one, because the variable will not reset between bars, its state will not change anymore, so you can determine the first change in its state by comparing the value with the previous bar, the change will only be on the first bar of the state change. Something like that

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

var state = 0
condition = close>open

if condition
    state := 1

plotshape(ta.change(state))

As you can see in the screenshot, only the first bar on which the close > open condition is met is marked with a plot shape

example

Related