Guide

Pine Script ta.valuewhen: Get the Value at the Last Signal

Learn how ta.valuewhen returns a value from the last time a condition was true, with v6 examples for swing levels, signal bars, and occurrences.

•10 min read

You have a condition that fires now and then, a moving average cross, a pivot, a volume spike, and you want to know what something was the last time it fired. What was the close on the bar of the last cross? What was the ATR when the last swing high formed? The obvious attempt is a loop or a pile of if statements with var variables, and it works, but Pine Script has a built-in for exactly this: ta.valuewhen. It looks back through the bars for the most recent time a condition was true and hands you the value of any series from that bar.

This guide covers the signature and what the occurrence argument really counts, then four practical uses: remembering a price level, reading the previous occurrence, building swing levels from pivots, and carrying a stop distance from the bar that triggered it. We also cover the three mistakes that cause most ta.valuewhen bugs, and when a plain var variable is the better tool.

What ta.valuewhen does

The signature in Pine Script v6 is ta.valuewhen(condition, source, occurrence). The condition is a boolean series. The source is the series whose value you want, such as close, high, an indicator, or any expression. The occurrence is an integer: 0 means the most recent bar where the condition was true, 1 means the one before that, 2 the one before that, and so on.

Two details matter. First, the count includes the current bar. If the condition is true on the bar you are looking at, occurrence 0 returns that bar's own source value. Second, until the condition has been true at least occurrence + 1 times, the function returns na. On a fresh chart with a rare condition, the first hundred bars may plot nothing, and that is correct behavior rather than a bug. If na values trip up your downstream math, our guide on how Pine Script handles na shows how to guard against it.

Here is the smallest useful example. It marks the close of the bar where price last crossed above its 50-period average and draws it as a step line that holds until the next cross:

pine
//@version=6
indicator("valuewhen basics", overlay = true)

ma = ta.sma(close, 50)
crossUp = ta.crossover(close, ma)

lastCrossClose = ta.valuewhen(crossUp, close, 0)

plot(ma, "SMA 50", color = color.gray)
plot(lastCrossClose, "Close at last cross", color = color.orange, style = plot.style_stepline)

The step line is flat between crosses and jumps each time a new cross fires. Without ta.valuewhen you would need a var variable and an if block to get the same thing. If the cross logic itself is new to you, see ta.crossover and ta.crossunder explained.

Why it is not just a lookback

A common first instinct is close[10], but a fixed offset only works when you know how many bars ago something happened. Signals are irregular. The last cross might be 3 bars back or 300. ta.valuewhen solves this by tracking the event, not the distance. You describe what you are waiting for, and Pine Script handles the bookkeeping.

The other tool people reach for is ta.barssince, which tells you how many bars ago the condition was true. You can combine it with an offset, as in close[ta.barssince(crossUp)], but that is more fragile. It breaks when barssince returns na before the first event, and it needs the historical buffer to be large enough. ta.valuewhen handles both for you, and it reads more clearly. We keep ta.barssince for when we want the age of the signal itself, for example to fade a line as it gets stale.

Reading the previous occurrence

The occurrence argument is where ta.valuewhen gets more useful than a var variable. A var variable only remembers the latest value. With ta.valuewhen you can ask for the last, the one before, and the one before that, all from the same condition, in one line each.

This example plots the close at the last two golden crosses of a 20 and 50 average. Comparing the two tells you whether the latest cross happened above or below the previous one:

pine
//@version=6
indicator("valuewhen occurrence", overlay = true)

fastMa = ta.sma(close, 20)
slowMa = ta.sma(close, 50)
crossUp = ta.crossover(fastMa, slowMa)

lastUp = ta.valuewhen(crossUp, close, 0)
prevUp = ta.valuewhen(crossUp, close, 1)

plot(lastUp, "Last cross", color = color.green, style = plot.style_stepline)
plot(prevUp, "Previous cross", color = color.gray, style = plot.style_stepline)

bgcolor(lastUp > prevUp ? color.new(color.green, 92) : color.new(color.red, 92))

There is a subtlety worth knowing. On the bar where crossUp is true, occurrence 0 is that very bar and occurrence 1 is the earlier cross. One bar later, nothing has changed, so both values hold. This is why lastUp > prevUp is a stable comparison between consecutive events rather than something that flickers bar to bar. The background tint shows whether each new cross came in higher than the last, which is a plain description of the past and nothing more.

Swing levels from pivots

The most popular use of ta.valuewhen in indicator code is turning pivots into persistent levels. ta.pivothigh returns the pivot price on the bar where the pivot is confirmed, and na on every other bar. That is awkward to draw on its own, because you get isolated points. Feeding it to ta.valuewhen gives you a continuous level that holds until the next pivot.

pine
//@version=6
indicator("Last swing levels", overlay = true)

len = input.int(5, "Pivot length", minval = 1)

ph = ta.pivothigh(high, len, len)
pl = ta.pivotlow(low, len, len)

lastHigh = ta.valuewhen(not na(ph), ph, 0)
lastLow = ta.valuewhen(not na(pl), pl, 0)
midLevel = (lastHigh + lastLow) / 2

plot(lastHigh, "Last swing high", color = color.red, style = plot.style_stepline)
plot(lastLow, "Last swing low", color = color.green, style = plot.style_stepline)
plot(midLevel, "Midpoint", color = color.gray, style = plot.style_stepline)

The condition is not na(ph), which is true only on the bar where the pivot is confirmed. The source is ph itself, the pivot price. Because a pivot with len bars on each side can only be confirmed len bars after it forms, the level appears with a delay. That is not a flaw in ta.valuewhen, it is how pivots work, and our article on why pivot signals arrive late explains the offset in full. Do not shift the plot back to line it up with the pivot bar and call the result a live indicator, because that would show levels the script could not have known at the time.

Once you hold the last swing high and low as series, other calculations get simple. The midpoint above is one. You could also measure how far price has pulled back into the range, or compute the range width. For a wider treatment of marking structure in code, see higher highs and lower lows in Pine Script.

Carry a value from the signal bar

The second big use is freezing a value at the moment of the trigger. Suppose you want a reference stop level that sits two ATRs below the close of the bar where a signal fired, and stays fixed until the next one. If you simply compute close - 2 * ta.atr(14) every bar, the level moves with every candle. What you want is the ATR and the close as they were on the signal bar.

pine
//@version=6
indicator("Reference level from signal bar", overlay = true)

atrLen = input.int(14, "ATR length", minval = 1)
mult = input.float(2.0, "ATR multiple", minval = 0.1, step = 0.1)

ma = ta.sma(close, 50)
crossUp = ta.crossover(close, ma) and barstate.isconfirmed

atrNow = ta.atr(atrLen)
signalClose = ta.valuewhen(crossUp, close, 0)
signalAtr = ta.valuewhen(crossUp, atrNow, 0)

refLevel = signalClose - mult * signalAtr

plot(ma, "SMA 50", color = color.gray)
plot(refLevel, "Reference level", color = color.new(color.red, 20), style = plot.style_stepline)
plotshape(crossUp, "Cross up", shape.triangleup, location.belowbar, color.green, size = size.tiny)

Two choices here are deliberate. The ATR is computed once, on every bar, into atrNow, and then passed to ta.valuewhen as the source. Calling ta.atr straight inside a conditional would break the calculation, which is the first mistake covered below. And the condition includes barstate.isconfirmed, so on a live chart the level only locks in when the bar closes, which keeps what you see in realtime consistent with history. We cover that setting in barstate.isconfirmed in Pine Script.

This pattern is how many scripts store an anchor value for stop and target logic. If you are building out risk handling, stop loss and take profit in Pine Script shows how to feed a level like this into strategy.exit.

Mark it on the chart before you code it

Before writing any of this, it helps to see the thing you are about to calculate. If the idea is "the last swing high and low, and the midpoint between them," you can look at that range on a real chart first and decide whether the pivot length makes sense for the market you care about. PineScripter's chart runs on real crypto spot market data, and its AI chart agent can read the swing levels and draw them with its drawing tools while you watch, with each batch of drawings undoable. You might ask, in plain English, "Mark the last swing high and low on BTCUSDT 4h and draw the midpoint between them." You then check the result yourself by switching timeframe and stepping through replay, bar by bar, to see when each level would have appeared. The markup is a starting point to verify, not an answer.

Once the picture matches what you had in mind, the Pine Script above is the permanent version: an indicator that holds those levels on every chart you load it on.

The three mistakes that cause most bugs

The first mistake is calling a function with internal history inside a conditional. Functions like ta.atr, ta.sma, and ta.ema need to run on every bar to keep their state correct. Pine Script warns about this, and wrapping them in an if or a ternary gives wrong numbers. Compute the indicator on its own line first, then pass the result into ta.valuewhen as the source, as the ATR example does. The same applies to ta.valuewhen itself: call it at the top level of your script, not inside an if branch.

The second mistake is forgetting the delay on confirmed events. Pivots, ta.barssince counts, and anything that depends on future bars confirms late. A ta.valuewhen of a pivot price tells you the last confirmed pivot, not the last one that happened. If you mistake one for the other you will misread the chart or, in a strategy, introduce lookahead into your logic. If you have ever had an indicator that looked perfect in hindsight, the lookback bias problem describes what is going on.

The third mistake is ignoring na. Before the first event, ta.valuewhen returns na, and any arithmetic involving na returns na. In the swing example, the midpoint stays blank until both a high and a low pivot have been found. That is usually what you want. If you need a fallback, wrap the result in nz() with a sensible default, but only when a default really makes sense, since a zero line at the bottom of a price chart is rarely meaningful.

ta.valuewhen versus a var variable

You can do the same job with a persistent variable:

pine
//@version=6
indicator("var version", overlay = true)

ma = ta.sma(close, 50)
crossUp = ta.crossover(close, ma)

var float lastCrossClose = na
if crossUp
    lastCrossClose := close

plot(lastCrossClose, "Close at last cross", color = color.orange, style = plot.style_stepline)

This is equivalent to the first example. It is also more flexible: inside the if block you can update several variables, count events, or reset state on a different condition. The trade-off is length and clarity. For one value from one condition, ta.valuewhen is a single readable line, and it is the only option that gives you the previous occurrence without extra bookkeeping. For anything stateful, such as tracking a position size or resetting on an opposite signal, var is the better fit. Our guide to var, varip, and persistent state covers how that mechanism works and where it differs between historical and realtime bars.

Putting it together

A good way to apply this is to pick one irregular event from your own idea, then list the values you wish you could recall from that moment: the price, a volatility reading, a volume figure. Each one becomes a ta.valuewhen call with the same condition and a different source. You end up with a small set of series that describe the last event, and the rest of your script can compare current conditions against them.

If you would rather describe that logic in words and have the code written and checked for you, that is what PineScripter is for. You write something like "plot the close and ATR at the last 50-period cross, and a level two ATRs below it," and it writes Pine Script v6, checks it for compile errors the way TradingView does, and fixes those errors itself. You can then run it on the chart and step through replay to see when it reacts. It is an independent coding tool, so you paste the finished script into TradingView yourself. You can see how that works in how PineScripter works, or look at the plans at pinescripter.app.

PineScripter is a coding tool for Pine Script. Nothing in this article is financial advice, and no indicator or level described here predicts future prices or promises any result.

Frequently asked questions

What does the occurrence argument in ta.valuewhen mean?

It counts back through the times the condition was true. 0 is the most recent one, including the current bar if the condition is true there, 1 is the one before that, and so on. Until enough events have happened, the function returns na.

Why does ta.valuewhen return na at the start of the chart?

Because the condition has not been true often enough yet. For occurrence 0 it needs one event, for occurrence 1 it needs two. Guard downstream math against na, or use nz() only where a default value makes sense.

Can I call ta.valuewhen inside an if block?

You should not. Call it at the top level of the script so it evaluates on every bar. Compute any indicator you pass as the source on its own line first, then give that series to ta.valuewhen.

Should I use ta.valuewhen or a var variable?

Use ta.valuewhen for one value from one condition, especially when you want the previous occurrence. Use a var variable when you need to update several values together, count events, or reset on a different condition.

Does ta.valuewhen repaint?

It returns values from bars where the condition was true, so it repaints only if the condition itself can change on the open bar. Add barstate.isconfirmed to the condition so the value locks in when the bar closes.

Ask the agent to mark it on the chart, then turn it into Pine Script →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.