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

Pine Script "Loop is too long (> 500 ms)" error — cause & fix

The error
Loop is too long (> 500 ms).

A single execution of a loop exceeded Pine's 500 ms per-bar time budget, usually from an unbounded or very large iteration count. Educational only — this reference explains the loop time limit; it makes no claim about profitability.

Why it happens

Pine caps how long one loop may run on a single bar to protect shared compute. If a for/while loop iterates too many times per bar — for example bounding the range by bar_index (which grows without limit), scanning thousands of historical bars every bar, or a while whose condition rarely becomes false — the loop can breach the ~500 ms budget and the script is halted with this error.

How to fix it

Bound every loop with a small, constant, simple upper limit rather than a growing series like bar_index. Cap lookback ranges with math.min(...) against a fixed constant, precompute values outside the loop, and prefer built-in ta.* functions (which are optimized in the engine) over hand-rolled bar scans. For while loops, guarantee the exit condition is reached within a bounded number of iterations.

What triggers it

//@version=6
indicator("Unbounded loop")
sum = 0.0
// Range grows with bar_index, so on late bars the loop runs
// tens of thousands of iterations and exceeds the 500 ms limit.
for i = 0 to bar_index
    sum += close[i]
plot(sum)

The fix, in code

✓ Validated clean by our own engine

//@version=6
indicator("Bounded loop")

len = input.int(100, "Lookback", minval = 1, maxval = 500)

// Cap the iteration count with a fixed constant and clamp to
// available history so the loop can never run away.
int maxLen = math.min(len, bar_index)
float sum = 0.0
for i = 0 to maxLen - 1
    sum += close[i]
avg = sum / maxLen

plot(avg, "Manual SMA", color = color.orange)
// For production, prefer the optimized built-in:
plot(ta.sma(close, len), "Built-in SMA", 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