Resource limit

Fix a Pine Script loop that takes too long

Reduce the work performed by the loop on each bar. Pine limits a single loop to 500 milliseconds, and a million-iteration sum can exceed that runtime budget even though it compiles. The same arithmetic series has a constant-time formula, so the fixed script removes the loop entirely. For nontrivial algorithms, shrink the search range, cache reusable values, or replace linear scans with bounded searches.

This link opens the Pine Script AI Coding Agent overview. It does not run or change code on this page.

Before and after

Make the smallest reviewable change

Both artifacts include the version declaration and the code needed to inspect the stated problem. The diff lists the lines that change between them.

Broken code.pine
//@version=6
indicator("Loop limit demo")
float total = 0.0
for i = 0 to 1000000
    total += i
plot(total)
Fixed code.pine
//@version=6
indicator("Loop limit demo")
float total = 1000000.0 * 1000001.0 / 2.0
plot(total)
Diff.pine
--- broken.pine
+++ fixed.pine
@@
-float total = 0.0
-for i = 0 to 1000000
-    total += i
+float total = 1000000.0 * 1000001.0 / 2.0

Root causes

  • A loop performs too many iterations on a single historical bar or realtime tick.
  • Nested loops make the outer loop exceed the per-bar limit.
  • The same search or aggregation is repeated on every bar instead of using a bounded calculation or cached state.

How the fix was verified

Method
Pineify UAT grammar checker via check-pine-script-grammar.mjs
Broken result
Returned no grammar diagnostics; loop duration is a runtime property.
Fixed result
Returned no grammar diagnostics.
Limit
Not runtime-tested. Actual duration depends on the dataset, nested work, requested data, and plan-level total execution limits.

Bring the actual script, not just the message

Open the Coding Agent overview to paste editable Pine Script, explain the intended behavior, and request a review. Compile and test the result in TradingView before using it.

Paste your code to fix this error