Skip to main content

What is valuewhen in Pine Script?

· 5 min read

Ever stared at a chart wondering "What was the exact price when that moving average crossover happened three weeks ago?" I know I have. That's where Pine Script's valuewhen function becomes your best friend.

Think of valuewhen as your chart's memory bank. It's like having a photographic memory that captures and stores specific values at precise moments when interesting things happen. Whether it's a breakout, a crossover, or any condition you define, valuewhen remembers it for you.

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

Let's 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 incredibly useful for several scenarios:

Support and Resistance Levels: When price makes a significant high or low, valuewhen helps you remember those exact levels. This is crucial for identifying future support and resistance zones.

Indicator Context: Want to know what the RSI reading was when price broke through a key resistance level? valuewhen captures that context for you.

Strategy Development: Instead of just knowing an event occurred, you can remember the market conditions surrounding that event. This context is gold for building better Pine Script strategies.

Backtesting Enhancement: When testing strategies, valuewhen helps you analyze what happened at specific trigger points, making your backtesting more thorough.

Advanced Techniques with Historical References

Here's where valuewhen gets really powerful. You can 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

This is like having a time machine that lets you peek around important events. You're not just capturing the moment—you're capturing the story around it.

Common Pitfalls to Avoid

When working with valuewhen, watch out for these mistakes:

Repainting Issues: If your condition can change retrospectively, your valuewhen values might change too. Always test your logic thoroughly.

Occurrence Parameter Confusion: Remember that occurrence 0 is the most recent, not the first occurrence. It's backwards from what you might expect.

Condition Frequency: If your condition triggers too often, you might not get the historical data you expect. Make sure your conditions are specific enough.

Building More Complex Trading Logic

valuewhen becomes even more powerful when combined with other Pine Script functions. For instance, if you're interested in multiple conditions in Pine Script, you can use valuewhen to capture values when multiple criteria are met:

// 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 for Different Trading Styles

Day Traders: Use valuewhen to remember opening prices, pre-market highs, or the exact level where volume spikes occurred.

Swing Traders: Capture weekly or daily pivot points, remembering exact levels where momentum shifted.

Position Traders: Track monthly breakout levels or remember prices at major fundamental news events.

If you're just getting started with Pine Script, understanding valuewhen is crucial for developing more sophisticated indicators. It's one of those functions that separates basic scripts from professional-grade tools. Check out our comprehensive Pine Script tutorial to build a solid foundation.

Why This Function Changes Everything

Look, I've been coding Pine Script for years, and valuewhen is one of those functions that completely changed how I think about market analysis. Instead of just reacting to current conditions, you start thinking about market memory and context.

Most traders focus on what's happening right now. But the smart money remembers what happened before. valuewhen gives you that institutional-level memory in your custom indicators.

Whether you're building a simple moving average system or a complex multi-timeframe strategy, valuewhen helps you connect the dots between past and present. And in trading, that connection often makes the difference between profit and loss.

The beauty of valuewhen lies in its simplicity. Three parameters, infinite possibilities. Once you start using it, you'll wonder how you ever traded without this kind of market memory at your fingertips.

For those looking to take their Pine Script skills to the next level, mastering functions like valuewhen is essential. If you want to explore more advanced Pine Script techniques without getting bogged down in complex coding, tools like Pineify's AI-powered Pine Script generator can help you implement these concepts quickly and efficiently.