Skip to main content

What is valuewhen in Pine Script?

· 10 min read
Pineify Team
Pine Script and AI trading workflow research team

ta.valuewhen is a Pine Script function that returns a value from a historical bar where a specified condition was true. It acts as market memory for your scripts. Instead of watching price move in real time and guessing what happened last time something similar occurred, you capture the exact number and use it.

I spent last month backtesting a golden cross strategy on AAPL. Without valuewhen, I had to scroll around the chart manually, trying to remember what the RSI was reading when each cross happened. With it, I pulled those values in seconds. That single function changed how I build indicators.

Understanding the valuewhen Function

The valuewhen function in Pine Script follows this simple syntax:

valuewhen(condition, source, occurrence)

Here's what each parameter does:

  • condition: The trigger event you're watching for (like a price crossing above a moving average)
  • source: The value you want to capture when that condition occurs (price, volume, RSI, etc.)
  • occurrence: How many instances back you want to look (0 = most recent, 1 = second most recent, and so on)

Real-World Example That Makes Sense

The Best Pine Script Generator

Say you're tracking golden cross signals (when a fast moving average crosses above a slow one). You want to remember the exact closing price when this happens:

// Define your moving averages
fastMA = ta.sma(close, 20)
slowMA = ta.sma(close, 50)

// Detect the golden cross
goldenCross = ta.crossover(fastMA, slowMA)

// Capture the price when it happened
priceAtGoldenCross = ta.valuewhen(goldenCross, close, 0)

// Plot it as a reference line
plot(priceAtGoldenCross, color=color.yellow, title="Golden Cross Price")

Now you have a yellow line showing exactly where price was during the most recent golden cross. It's like having a bookmark for that important moment.

Where valuewhen Really Shines

After years of working with Pine Script, I've found valuewhen useful in several scenarios:

Support and Resistance Levels: When price makes a significant high or low, valuewhen remembers those exact levels. For my TSLA swing trades, I use it to capture pivot highs and lows from weekly data. I haven't found a cleaner approach for dynamic S/R levels.

Indicator Context: What was the RSI reading when price broke through that key resistance level on NVDA last Tuesday? valuewhen gives you that answer without digging through bar history.

Strategy Development: Instead of knowing an event occurred, you remember the market conditions surrounding it. I prefer valuewhen over barssince when I need actual price levels, not just a bar count. This context helps when building Pine Script strategies.

Backtesting Enhancement: When testing strategies, valuewhen helps you analyze trigger points more thoroughly.

Advanced Techniques with Historical References

valuewhen gets more powerful when you combine it with historical referencing using square brackets [n]:

// Get the price from 3 bars before the golden cross
priceBeforeCross = ta.valuewhen(goldenCross, close[3], 0)

// Get the volume when the cross happened
volumeAtCross = ta.valuewhen(goldenCross, volume, 0)

// Compare current price to the cross price
percentChange = (close - priceAtGoldenCross) / priceAtGoldenCross * 100

You're not just capturing the moment — you're capturing the context around it.

Common Pitfalls

Watch out for these mistakes:

Repainting Issues: If your condition can change retrospectively, your valuewhen values change too. I've seen this break strategies that looked good in replay mode but failed in real trading. Always test with calc_on_every_tick=false.

Occurrence Parameter Confusion: Zero is the most recent occurrence, not the first. It's backward from what most people expect. I've tripped on this more than once.

Condition Frequency: If your condition triggers on every bar, valuewhen doesn't give you anything useful. Be specific with your conditions.

Data Limitations: On new instruments or short timeframes, valuewhen returns na if the condition never happened before. You need to handle that case in your code.

Building More Complex Trading Logic

valuewhen works well when combined with other Pine Script functions. If you're interested in multiple conditions in Pine Script, you can capture values when several criteria align:

// Complex condition: price above MA and RSI oversold
complexCondition = close > fastMA and ta.rsi(close, 14) < 30

// Capture the exact price when both conditions align
entryPrice = ta.valuewhen(complexCondition, close, 0)

Practical Applications by Trading Style

Day Traders: Remember opening prices, pre-market highs, or the level where volume spiked. I track VWAP deviation on MES futures this way.

Swing Traders: Capture weekly pivot points and momentum shifts. My NVDA swing system uses valuewhen to mark prior resistance before earnings announcements.

Position Traders: Track monthly breakout levels or prices at major news events. You can combine this with multi-timeframe data using request.security.

If you're newer to Pine Script, valuewhen separates basic scripts from tools that actually hold up in backtesting. Our Pine Script tutorial for beginners covers the fundamentals you'll need.

What Changes With Market Memory

I've been coding Pine Script for about four years now. valuewhen is one of the few functions that changed my approach to market analysis. Instead of reacting to current conditions, I started thinking about what happened before and why it matters.

Most traders look at what's happening right now. The function lets you remember what happened last time — and in trading, that connection often separates a decent strategy from a losing one.

Three parameters, a lot of possibilities. You'll probably find yourself using it in places you didn't expect.

For more advanced Pine Script work, tools like the AI Pine Script generator can help implement these concepts quickly.

Frequently Asked Questions

What does valuewhen do in Pine Script?

valuewhen (called as ta.valuewhen) returns the value of a source series at the most recent bar where a specified condition was true. It lets your script remember what a price, indicator reading, or any series value was the last time a particular event occurred.

How do I use the occurrence parameter in ta.valuewhen?

The occurrence parameter controls how far back in history you look. 0 returns the value from the most recent bar where the condition was true, 1 returns the value from the second most recent occurrence, and so on. Higher numbers look further into the past.

What is the difference between valuewhen and barssince in Pine Script?

ta.valuewhen captures the actual value of a series at the time a condition fired, while ta.barssince only tells you how many bars ago that condition occurred. Use valuewhen when you need the price, RSI, or volume at a past event; use barssince when you need the elapsed bar count.

Can valuewhen cause repainting in TradingView indicators?

Yes, valuewhen can contribute to repainting if the underlying condition itself repaints. If your condition uses future data or can change on historical bars, the captured value changes retroactively. Verify your condition logic is non-repainting before relying on valuewhen in a live strategy.

How do I capture support and resistance levels with valuewhen?

Detect a pivot high or low using ta.pivothigh or ta.pivotlow, then pass that as the condition to ta.valuewhen with high or low as the source. The result is a persistent horizontal level that updates only when a new pivot forms.

What are the limitations of valuewhen in Pine Script?

Key limitations: it only looks back through available chart history, so data may be limited on new instruments; it returns na if the condition has never been true; the occurrence value must be a non-negative integer literal and cannot be a dynamic series; excessive use can slow script execution on long histories.

Can I use valuewhen with multi-timeframe data in Pine Script?

Yes. Pass a request.security series as the source argument to ta.valuewhen. For example, capture the daily RSI value at the moment a 1-hour condition fires. Use barmerge.lookahead_off in your request.security call to avoid lookahead bias.