Sidechair

ta.valuewhen()

Browse the reference

Returns the value of source from the bar where condition was last true, or from an earlier true bar chosen by occurrence.

Try it in the editor

ta.valuewhen keeps the value of source at every bar where condition was true. occurrence 0 returns the most recent one, 1 the one before it, and so on.

The result is na until the condition has been true occurrence + 1 times. The value stays the same on later bars until the condition fires again.

Syntax

Pine Script
ta.valuewhen(condition: series bool, source: series int/float, occurrence: simple int) -> series float
ta.valuewhen(condition: series bool, source: series int, occurrence: simple int) -> series int
ta.valuewhen(condition: series bool, source: series bool, occurrence: simple int) -> series bool
ta.valuewhen(condition: series bool, source: series color, occurrence: simple int) -> series color

Arguments

NameTypeDefaultDescription
conditionseries boolrequiredBoolean series that decides which bars are remembered.
sourceseries int/float or series int or series bool or series colorrequiredSeries whose value is stored on those bars.
occurrencesimple intrequiredWhich remembered bar to read: 0 is the latest, 1 the previous one. A whole number of 0 or more.

Returns

series float or series int or series bool or series color: the stored value of source, or na before enough true bars exist.

Remarks

  • The stored value is the one source had on the true bar, not today's value.

Example

Pine ScriptClose at the last bullish crossOpen in editor
//@version=6
indicator("Last cross price", overlay = true)
fast = ta.sma(close, 10)
slow = ta.sma(close, 30)
plot(ta.valuewhen(ta.crossover(fast, slow), close, 0), "Last up-cross close", color = color.green, style = plot.style_stepline)
plot(ta.valuewhen(ta.crossunder(fast, slow), close, 0), "Last down-cross close", color = color.red, style = plot.style_stepline)

See also

Runs on Sidechair