◆ New — Strategy Validator, Code Fixer & Prop Compliance Checker are live. Try one free →
Home / Pine errors / Scope
Pine Script v6 error · Scope

Pine Script "The function 'ta.ema' should be called on each calculation for consistency" — cause & fix

The error
The function 'ta.ema' should be called on each calculation for consistency. It is recommended to extract the call from this scope.

A stateful ta.* function is being called inside a conditional/local scope, so it does not update on every bar and can produce wrong values. Educational only — this reference explains the consistency warning; it makes no claim about profitability.

Why it happens

Functions like ta.ema, ta.sma, ta.rsi, ta.barssince and other ta.* built-ins are stateful: they maintain an internal series that must be updated on every bar to stay correct. When you call one inside an if block, a ternary (?:), or a function body that is not entered on every bar, its internal state is only advanced on the bars where that branch runs. The result drifts from what a per-bar call would produce, so Pine emits this warning (the script still compiles, but the value is likely wrong).

How to fix it

Call the ta.* function unconditionally in the global scope so it evaluates on every bar, assign the result to a variable, and then use that variable inside your conditional. Never place the ta.* call itself behind a branch. If you gate an alert or plot on the outcome, add 'and barstate.isconfirmed' so the signal fires only on the closed bar.

What triggers it

//@version=6
indicator("Conditional ta call", overlay = true)
// ta.ema is evaluated only when the ternary picks this branch,
// so its internal state is not updated every bar.
signal = close > open ? ta.ema(close, 20) : ta.ema(close, 50)
plot(signal)

The fix, in code

✓ Validated clean by our own engine

//@version=6
indicator("Consistent ta call", overlay = true)

fastLen = input.int(20, "Fast length", minval = 1)
slowLen = input.int(50, "Slow length", minval = 1)

// Evaluate both EMAs on every bar in global scope...
fastEma = ta.ema(close, fastLen)
slowEma = ta.ema(close, slowLen)

// ...then choose between the already-computed values.
signal = close > open ? fastEma : slowEma
plot(signal, "Selected EMA", color = color.blue)

plotshape(ta.crossover(fastEma, slowEma) and barstate.isconfirmed,
     title = "Cross up", style = shape.triangleup, location = location.belowbar, color = color.green)

Related errors

Educational, code-correctness reference only — not financial advice. Trading involves substantial risk of loss.

Catch the bug that compiles.Run auditGet Pro