ta.valuewhen in MQL5: backward scan with an occurrence index
Short answer
MQL5 has no built-in. Keep a per-bar record of the condition, scan backward from the current bar, skip occurrence matches and return src[k]; return EMPTY_VALUE if there are not enough matches.
ta.valuewhen(condition, source, occurrence) returns the value source had on the most recent bar where condition was true, or, for occurrence = 1, 2, ..., on the bar before that one, and so on. The current bar counts. MQL5 has no built-in for it; the equivalent is a backward scan over a per-bar record of the condition, which is also how a correct implementation stays stable on the realtime bar.
What ta.valuewhen computes
Walk back from the current bar. Each bar where condition is true is a hit; skip occurrence hits and return source at the next one. occurrence = 0 is the latest hit, including the current bar if the condition holds now. If fewer than occurrence + 1 hits exist in the chart's history, the result is na. The returned value is the source as it was on that bar, so ta.valuewhen(cond, close, 0) holds steady until the next hit; on the realtime bar it can switch to the current close while the condition holds and switch back if the condition stops holding before the close.
Typical pairings: ta.valuewhen(ta.crossover(a, b), close, 0) for the price at the last signal, and ta.valuewhen(ph, ph, 1) with ph = ta.pivothigh(...) for the previous swing high in a divergence check, where the condition is "ph is not na".
The MQL5 equivalent
Pine: the close at the most recent breakout bar, with the occurrence as an input.
//@version=6
indicator("Value when", overlay=true)
occ = input.int(0, "Occurrence", minval=0)
cond = close > high[1]
level = ta.valuewhen(cond, close, occ)
plot(level, "Level", style=plot.style_linebr)MQL5. A calculation buffer records the condition per bar as 1.0 or 0.0; ValueWhen scans it backwards. Writing the current bar's condition before the scan reproduces "the current bar counts".
//+------------------------------------------------------------------+
//| Close at the last breakout: Pine's ta.valuewhen(cond, src, occ) |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots 1
#property indicator_label1 "valuewhen"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDodgerBlue
input int Occurrence = 0; // 0 = most recent, 1 = the one before, ...
double Value[]; // what ta.valuewhen returns
double Cond[]; // 1.0 where the condition held, 0.0 elsewhere
// Backward scan from bar i: the source value at the (occ+1)-th most recent
// bar where cond held. na (EMPTY_VALUE) if it has not held that often yet.
double ValueWhen(const double &cond[], const double &src[], const int i, const int occ)
{
int seen = 0;
for(int k = i; k >= 0; k--)
{
if(cond[k] != 1.0) continue;
if(seen == occ) return src[k];
seen++;
}
return EMPTY_VALUE;
}
int OnInit()
{
SetIndexBuffer(0, Value, INDICATOR_DATA);
SetIndexBuffer(1, Cond, INDICATOR_CALCULATIONS);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
return INIT_SUCCEEDED;
}
int OnCalculate(const int rates_total, const int prev_calculated,
const datetime &time[], const double &open[],
const double &high[], const double &low[],
const double &close[], const long &tick_volume[],
const long &volume[], const int &spread[])
{
int start = (prev_calculated > 1) ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// Write this bar's condition first: Pine's valuewhen sees the current bar.
Cond[i] = (i > 0 && close[i] > high[i - 1]) ? 1.0 : 0.0;
Value[i] = ValueWhen(Cond, close, i, Occurrence);
}
return rates_total;
}The scan is O(bars) in the worst case when the condition is rare, which is fine for a chart but can be slow on a very long history. If you need speed, keep a second buffer with the index of the last hit (the barssince state) and chain through it: LastHit[i], then LastHit[LastHit[i] - 1] for the second occurrence, and so on.
Where the two differ
| Topic | Pine Script | MQL5 |
|---|---|---|
| Current bar | Counts as a hit if the condition is true now | Write Cond[i] before scanning, or the current bar is skipped |
| Not enough hits | na | EMPTY_VALUE; set PLOT_EMPTY_VALUE so nothing is drawn |
| State | Implicit history of both series | Two arrays: the condition record and the source (a price array or a buffer) |
| Realtime bar | Recomputed each tick | Same, because Cond[i] is overwritten each tick and the scan reads only written cells |
| Occurrence | 0-based, int, may itself be a series | Any int expression; a buffer-held value needs an (int) cast |
What the Stratlate converter emits
The emitter allocates two state arrays per ta.valuewhen call site and emits pine_valuewhen((cond), (src), __stN, __stbN, __pineBar, (int)(occurrence)), with the occurrence defaulting to 0 when omitted. The runtime writes this bar's condition (1.0/0.0) and value into the two arrays and then scans backwards from i to 0, skipping occurrence hits, returning na when the history runs out. The comment in PineRuntime.mqh gives the reason for a scan over confirmed history rather than a mutable ring: writing the current bar's pair is idempotent, so a recomputed newest bar cannot shift older occurrences. The example above converts CLEAN; the mapping is exact.
Pitfalls
- Scanning from
i - 1. Symptom: the level updates one bar late compared with TradingView on every signal bar. - Caching "the last value" in a scalar that is updated when the condition holds. Symptom: correct on history, wrong live: a condition that was true mid-bar and false at the close leaves the stale value behind.
- Treating
occurrenceas 1-based. Symptom: every level is one signal older than intended. - Returning 0 instead of
EMPTY_VALUEwhen there are not enough hits. Symptom: a line at zero on the first bars and a wrecked autoscale. - Using the current bar's source where Pine reads a historical one, for example
ta.valuewhen(cond, close[1], 0). Symptom: a constant offset of one bar in the values; the[1]must be applied before the record is written.
FAQ
Does ta.valuewhen look at the current bar?
Yes. If the condition is true on the current bar, occurrence 0 returns the current bar's source value. The MQL5 version must record the current bar's condition before it scans.
What does occurrence mean exactly?
How many hits to skip, counting back from the present. 0 is the latest hit, 1 the one before it. If there are not enough hits the result is na.
Why does the engine scan instead of keeping the last value in a variable?
Because the forming bar is recomputed on every tick. A per-bar record that is overwritten and re-scanned gives the same answer however many times the bar is recomputed; a mutable variable does not.
Convert the whole script
Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converter