ta.* inside if in Pine Script: per-call history explained
Short answer
Each textual ta.* call keeps its own series and advances only on bars where the line executes, so a ta.* call inside an if block sees only the bars on which it ran. Window functions look back over their calls and recursive ones advance one step per call; reproduce that in MQL5 to get the same output.
A ta.* call inside an if block does not see the chart's bars. It sees only the bars on which it ran. TradingView's compiler warns about it, many published scripts depend on it anyway, and it is the reason a Pine script can change its output when a line moves into or out of a block. This guide explains the rule, shows when it is a bug and when it is intended, and how to reproduce it in MQL5.
One history per call, updated only when the call runs
Every textual ta.* call in a script keeps its own internal series. A value is appended to that series only on bars where the line actually executes. Functions that look back over a window (ta.sma, ta.highest, ta.stdev) look back over their calls, and recursive ones (ta.ema, ta.rma, ta.rsi, ta.atr) advance one step per call.
//@version=6
indicator("Conditional SMA", overlay = true)
var float x = na
if bar_index % 2 == 0
x := ta.sma(close, 3) // averages the closes of the last 3 CALLS
plot(x, "x")With closes of 10, 11, 12, 13, 14, 15 on bars 0 to 5, this is what happens:
| Bar | Close | ta.sma inside the if (x) | ta.sma on every bar |
|---|---|---|---|
| 0 | 10 | na (1 call so far) | na |
| 1 | 11 | na (x keeps its value) | na |
| 2 | 12 | na (2 calls) | 11 |
| 3 | 13 | na | 12 |
| 4 | 14 | 12, mean of 10, 12, 14 | 13 |
| 5 | 15 | 12 | 14 |
The conditional call averages bars 0, 2 and 4, a span of five bars. That is why the compiler warns that the function should be called on each calculation for consistency, and suggests extracting it from the local scope.
Where calls become conditional
if,elseandswitchbranches, as above.- Ternary arms: in
cond ? ta.ema(close, 20) : nathe EMA advances only whilecondis true. - The right operand of
and/orin Pine v6. v6 evaluates these lazily, so the right side is skipped when the left side already decides the result. A script that was fine in v5 can change values when migrated to v6. - User functions called conditionally. Each call site of a function has its own copy of the history of the
ta.*calls inside it. - Loops. A
ta.*call inside aforloop can execute several times per bar and append several values.
//@version=6
indicator("Lazy and", overlay = true)
trendUp = close > ta.sma(close, 50)
// v6 skips the right operand when trendUp is false, so ta.crossover and the
// ta.ema inside it only see the bars where trendUp was true
buySig = trendUp and ta.crossover(close, ta.ema(close, 20))
plotshape(buySig, "Buy", shape.triangleup, location.belowbar)Usually a bug: hoist the call
Most of the time the author meant the indicator computed over every bar. The fix is to compute the call unconditionally at the top level and use the result inside the condition:
//@version=6
indicator("Hoisted", overlay = true)
trendUp = close > ta.sma(close, 50)
crossUp = ta.crossover(close, ta.ema(close, 20)) // runs on every bar
buySig = trendUp and crossUp
plotshape(buySig, "Buy", shape.triangleup, location.belowbar)Before hoisting, check that the per-call behaviour is not the point. Some scripts sample on purpose. Here ta.sma runs only when a pivot is confirmed, so it averages the last five pivot highs, which is exactly what the name says. Hoisting it would average five bars of a series that is mostly na, a different result.
//@version=6
indicator("Average of the last 5 pivot highs", overlay = true)
ph = ta.pivothigh(high, 5, 5)
var float avgPivot = na
if not na(ph)
avgPivot := ta.sma(ph, 5) // intended: one value per pivot, not per bar
plot(avgPivot, "Pivot average")Reproducing per-call history in MQL5
MetaTrader's built-in indicators and the obvious hand-written loops compute over every bar, so they match the hoisted version, not TradingView. To reproduce a conditional call, give it its own history: record its input in an array at a call counter, and compute over the last n recorded entries. Store the counter per bar, not in a global, so that recomputing the forming bar on every tick does not count the same call twice.
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrOrange
#property indicator_label1 "Conditional SMA"
double XBuf[]; // the Pine variable x (plotted)
double CallSrc[]; // close recorded at each CALL of ta.sma, in call order
double CallPos[]; // how many calls had happened up to and including bar i
int OnInit()
{
SetIndexBuffer(0, XBuf, INDICATOR_DATA);
SetIndexBuffer(1, CallSrc, INDICATOR_CALCULATIONS);
SetIndexBuffer(2, CallPos, 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[])
{
const int len = 3;
int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++)
{
// Calls made before this bar (re-read on every tick, never accumulated)
int calls = (i > 0) ? (int)CallPos[i - 1] : 0;
XBuf[i] = (i > 0) ? XBuf[i - 1] : EMPTY_VALUE; // var x keeps its value
if(i % 2 == 0) // if bar_index % 2 == 0
{
CallSrc[calls] = close[i]; // this call's input joins its own history
calls++;
if(calls >= len) // x := ta.sma(close, 3) over the last 3 CALLS
{
double sum = 0.0;
for(int k = 1; k <= len; k++)
sum += CallSrc[calls - k];
XBuf[i] = sum / len;
}
else
XBuf[i] = EMPTY_VALUE; // fewer than 3 calls so far: na
}
CallPos[i] = calls;
}
return rates_total;
}For a recursive function such as ta.ema, the same idea applies: keep the previous EMA of the last call, indexed by call number, and update it only when the condition holds. Note that i % 2 on MT5 lands on the same candles as bar_index % 2 on TradingView only if both charts start on the same bar.
What Stratlate's converter does
Since engine 0.6.48, a ta.* call that runs on only some bars keeps its own per-call history in the MQL5 output, as in TradingView. This covers calls in if and switch branches, ternary arms, the right operand of a v6 and / or, and calls inside a user function whose one call site is itself conditional. It applies to the moving averages, ta.rsi, ta.atr, ta.stdev, ta.highest / ta.lowest, ta.crossover and similar history-based functions. Two shapes are not converted that way: calls inside loops, and calls in a helper function used from several places. Those are listed in the conversion report as approximations; hoist them in Pine and reconvert, or compare their signals against TradingView. Compile and backtest the result in every case.
Pitfalls
- Hoisting an intentional sample. The pivot average above turns into a different number that still looks plausible.
- Chart-wide MQL5 for a conditional call. An
iMAor a plain loop gives the hoisted values; symptom: lines match TradingView on bars where the condition was always true and drift elsewhere. - Counting calls per tick. A global counter incremented in
OnCalculategrows on every tick of the live bar; values move during the bar and change again after a reload. - v5 to v6 migration. Lazy
and/orchanges the history ofta.*calls on the right-hand side, so the same strategy can trade differently after an upgrade. - One helper, several call sites. In Pine each site has its own history; one shared MQL5 state array merges them.
- Bar-number conditions.
bar_indexparity or modulo tests select different candles when the MT5 history starts on a different bar.
FAQ
Why does TradingView warn that a ta function should be called on each calculation?
Because each ta.* call keeps its own history and only updates it on bars where the call runs. Inside an if, a ternary or a v6 and/or operand, the call skips bars, so its result is not the indicator computed over the chart's bars.
How do I fix a ta.* call inside an if block?
Compute it unconditionally on every bar, assign it to a variable at the top level, and use that variable inside the if. Keep the call inside the block only when you really want it to work over the bars on which the condition held.
Does Stratlate keep Pine's per-call history when converting to MQL5?
Yes, since engine 0.6.48, for the common history-based ta.* functions when they run on only some bars because of an if, switch, ternary or v6 and/or. Calls inside loops or in a helper function used from several places are reported as approximations in the conversion report.
Convert scripts with conditional ta.* calls
Stratlate gives each conditional ta.* call its own history in MQL5, the way TradingView runs it, and tells you where it cannot. Compile the output and backtest it before you rely on it.