What is valuewhen in Pine Script?
valuewhen
is a built-in Pine Script function that returns the value of a specified series at the time when a given condition was true, for the nth most recent occurrence. This means you can retrieve historical values tied to specific events or conditions, such as a crossover or a fractal high, which is essential for backtesting and signal analysis.
Syntax
valuewhen(condition, source, occurrence)
- condition: A boolean expression that triggers the event.
- source: The data series from which to return the value.
- occurrence: The nth occurrence back (0 for the most recent).
How Does valuewhen
Work?

When the condition is true, valuewhen
captures the value of the source series at that bar. You can then reference this value later, even several bars after the event occurred. For example, if you want to get the closing price when a moving average crossover happened three bars ago, valuewhen
makes this straightforward.
Practical Example
// Get the close price at the last golden cross (fast MA crossing above slow MA)
goldenCross = ta.crossover(fastMA, slowMA)
lastCrossClose = ta.valuewhen(goldenCross, close, 0)
plot(lastCrossClose, color=color.yellow)
This code plots the closing price at the most recent golden cross event.
Common Use Cases
- Detecting fractal highs or lows: By combining
valuewhen
with fractal conditions, you can identify and reference previous significant price points. - Tracking indicator crossovers: Retrieve values at the time of RSI or MACD crossovers to build entry or exit signals.
- Backtesting strategies: Access historical values tied to specific triggers to evaluate strategy performance.
Understanding Historical Referencing with valuewhen
A common point of confusion is that valuewhen
returns a value series that can be further indexed with historical referencing (e.g., [depth]
). This allows you to access the value at a specific offset from the occurrence, enabling more complex logic such as confirming fractal patterns or divergence signals.
For instance:
prevTopFractal = ta.valuewhen(topFractalCondition, source[depth], 0)[depth]
Here, valuewhen
returns the value at the most recent fractal occurrence, and [depth]
accesses the value at a specific bar offset relative to that occurrence.
Conclusion
Understanding valuewhen
is crucial for Pine Script developers who need to track and analyze historical events in their trading strategies. This versatile function provides a reliable way to access past values based on specific conditions, making it invaluable for building sophisticated technical indicators and trading systems. When used correctly, it can significantly enhance your ability to develop more precise and effective trading strategies.