'how do you store a value when a condition happens in pinescript ? ONLY ONCE

lets say i want the price when 2 EMAs crosses and use that price to create another variable as an stoploss but in realtime the price always changes in realtime candle so my stoploss and takeprofit always changes. i understand i have to use varip but i dont know how to use it with valuewhen

please help me correct my code. thank you :)

varip float Current_Close = na

/////
Long_Cond = crossover(ema1 , ema2)

////
Current_Close := valuewhen(Long_Cond , close , 0)

///
Stop_loss = Current_Close * 0.995

// "Risk Ratio 1/1"

takeprofit__long := Current_Close * (1 + (1 * ((Current_Close - Stop_loss) / Current_Close)))

i don't know how to use varip in this code with valuewhen .



Solution 1:[1]

Example:

//@version=5
indicator("My Script")

captureValueOnce(cond, float value)=>
    var float store = na
    if cond and na(store)
        store := value
    store

Long_Cond = ta.crossover(ta.ema(close, 50) , ta.ema(close, 200))
plot( captureValueOnce(Long_Cond, bar_index) )

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