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

Pine Script "Pine cannot determine the referencing length of a series" (max_bars_back) — cause & fix

The error
Pine cannot determine the referencing length of a series. Try using max_bars_back in the study or strategy function.

Pine could not statically infer how far back a series is referenced, usually because the history access happens inside a conditional branch. Educational only — this reference explains the buffer-inference failure and its fixes; no profitability is implied.

Why it happens

Pine builds a fixed historical buffer for every series at compile time by scanning the [] history-referencing operator. When the depth of a reference depends on runtime flow — for example a var accessed with [] only inside an if branch, or a reference offset that is itself a series value — the compiler cannot determine the maximum lookback and refuses to guess. This most often appears with variables read with [] inside if / iff / ternary branches, or with recursive var references.

How to fix it

Either lift the history reference out of the conditional so it is evaluated on every bar (giving Pine a static reference depth), or declare the buffer size explicitly. You can set max_bars_back on the whole script via the indicator()/strategy() max_bars_back parameter, or scope it to a single variable with max_bars_back(myVar, N). Prefer moving the reference to global scope when practical; use the parameter only when the reference genuinely must stay conditional.

What triggers it

//@version=6
indicator("Referencing length", overlay = true)
var float anchor = na
// close[] is only referenced inside a conditional branch, so Pine
// cannot infer how far back the buffer must reach.
if ta.crossover(close, ta.sma(close, 20))
    anchor := close[300]
plot(anchor)

The fix, in code

✓ Validated clean by our own engine

//@version=6
indicator("Referencing length fixed", overlay = true, max_bars_back = 500)

len = input.int(20, "SMA length", minval = 1)

// Read the historical value unconditionally so Pine can size the buffer,
// then select it with a conditional. max_bars_back also guarantees depth.
float past = close[300]
var float anchor = na
if ta.crossover(close, ta.sma(close, len))
    anchor := past

plot(anchor, "Anchor", color = color.teal)

Related errors

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

Catch the bug that compiles.Run auditGet Pro