You add a loop to an indicator, load it on a long chart, and TradingView answers with an error saying the loop takes too long to execute. The same script ran fine on a 100-bar test, and the loop looks harmless. Nothing in it is wrong, so the message feels unfair. It is not a syntax problem at all. It is a budget problem, and once you know how the budget is counted, the fixes are mostly mechanical.
This guide explains what the limit is, why loops that look small can blow through it, and the five rewrites that cover nearly every case: swapping the loop for a built-in, keeping a running total instead of re-reading history, shortening the window, stopping early, and moving the work to the last bar.
What the error actually measures
Pine Script runs your code once for every bar in the chart's history, then keeps running it as new ticks arrive. TradingView's documentation on Pine Script limitations states the rule for loops directly: the execution time for any loop on any single bar is limited to 500 milliseconds. Half a second sounds generous until you remember that the loop runs on every bar. A loop that costs 2 milliseconds on one bar costs 10 seconds across 5,000 bars, and a script has a total time allowance as well. That allowance varies with the account type, so check the plan comparison on TradingView's pricing page for your own figure.
Two details in that rule matter. The first is that the limit is per loop per bar, not per script. A script with ten small loops is not hit by the 500 millisecond rule the way one with a single huge loop is, though it can still run into the total execution limit. The second is that embedded loops count together. The documentation notes that the outer loop of nested loops is the one that times out first, because it contains the time of everything inside it. A loop of 200 iterations wrapped around a loop of 200 iterations is 40,000 steps per bar, and that is usually where this error comes from.
If you want the wider picture of how the runtime decides what to execute and when, how Pine Script's execution model works covers the bar-by-bar model in detail. For the more general case where a script is slow but not failing, see why your Pine Script is slow and how to fix it.
Why a small-looking loop still fails
Most loop timeouts come from one of four shapes, and it helps to recognize yours before changing anything.
The first is a loop whose length comes from an input. You write for i = 0 to len - 1 and let the user pick len. On the default of 20 it is fine. A user sets it to 5,000, and every bar now does 5,000 iterations of history lookups. The code did not change, but the work did.
The second is nesting. Computing a pairwise comparison, a rank, or a custom correlation by hand tends to produce a loop inside a loop, and the cost multiplies rather than adds.
The third is expensive work inside the loop body. A call to a function that itself loops, a request.security style call, or a string operation repeated thousands of times costs far more per iteration than simple arithmetic.
The fourth is doing the same work on every bar when only the latest result matters. If a loop scans 500 bars to find the biggest candle and you only draw one label at the right edge of the chart, you are paying for 5,000 scans to display one.
Here is the most common starting point, a plain average written as a loop.
//@version=6
indicator("Slow Loop Mean", overlay = false)
len = input.int(200, "Length", minval = 1, maxval = 5000)
total = 0.0
for i = 0 to len - 1
total += close[i]
plot(total / len, "Loop mean")With a length of 200 this does 200 history reads on every bar. It works, and it is exactly the shape that gets slower as the input grows. Everything below is a way to avoid writing it.
Fix 1: replace the loop with a built-in
Pine Script's built-in functions are implemented by the platform and keep their own running state, so they do not repeat the whole window on every bar the way your loop does. The loop above is ta.sma(close, len). Most loops that traders write by hand have a built-in equivalent, and checking the reference before writing the loop is the single most effective habit for avoiding this error.
Some common substitutions: a loop that finds the largest value in a window is ta.highest, and the smallest is ta.lowest. A loop that adds up a condition, such as counting bars that closed above their open, is math.sum over a numeric version of the condition. A loop that computes a standard deviation is ta.stdev. A loop that computes how two series move together is ta.correlation.
//@version=6
indicator("Window Stats Built-ins", overlay = true)
len = input.int(200, "Length", minval = 1)
hi = ta.highest(high, len)
lo = ta.lowest(low, len)
upBars = math.sum(close > open ? 1.0 : 0.0, len)
plot(hi, "Highest high")
plot(lo, "Lowest low")
plot(upBars, "Up bars in window", display = display.data_window)The counting trick is worth remembering. A condition is a boolean, and math.sum wants numbers, so you turn the condition into 1.0 or 0.0 with a ternary and let math.sum add them. It replaces a loop with an if inside it, which is another very common pattern.
Nested loops that build a correlation or a regression by hand usually collapse the same way.
//@version=6
indicator("Correlation Built-in")
len = input.int(50, "Length", minval = 2)
r = ta.correlation(close, volume, len)
plot(r, "Close vs volume")
hline(0)If you have a loop and cannot tell whether a built-in exists, describe what the loop computes in plain words, for example "the average of the last N closes weighted by volume", and look for it. In that case it is ta.vwma, which is covered in Pine Script VWMA. For moving averages in general, Pine Script moving average types lists the built-ins and how they differ.
Fix 2: keep a running total instead of re-reading history
Sometimes there is no built-in, because the quantity is your own. You still do not need to re-read the whole window on every bar. A rolling sum can be updated in constant time: add the newest value, subtract the value that just fell out of the window. Each bar does two operations regardless of how long the window is.
//@version=6
indicator("Incremental Window Mean")
len = input.int(200, "Length", minval = 1)
var float runSum = 0.0
runSum += close
runSum -= nz(close[len])
count = math.min(bar_index + 1, len)
plot(runSum / count, "Running mean")
plot(ta.sma(close, len), "ta.sma for comparison")The two plots should sit exactly on top of each other, which is the point of plotting the built-in beside it. The nz call matters. Before the chart has len bars of history, close[len] is na, and subtracting na would turn the whole total into na permanently. nz turns it into 0 until a real value exists. If this kind of silent propagation is new to you, how Pine Script handles na explains why one na can wipe out a running calculation.
The pattern applies to anything you can add and remove: sums, counts, sums of squares for a variance. It does not apply to a maximum or a rank, which is why those have built-ins of their own. For state that persists between bars, var, varip, and persistent state explains the keyword used above.
Fix 3: shorten or cap the window
Many loops are longer than they need to be. A lookback of 5,000 bars to find a swing high is almost never doing useful work, because a swing that far back is not relevant to the current bar. Cap the input with maxval so the user cannot ask for more than the script can afford, and pick a default that reflects how far back the logic really needs to look.
In the examples above, maxval = 5000 on the input is a ceiling, not a recommendation. If your indicator only needs the last 300 bars, set the ceiling to 300 and the error cannot be reached from the settings dialog at all. That is a better outcome than documenting a safe range in the description and hoping people read it.
There is a related error to watch for when you start using large dynamic lookbacks. History references with a computed index need the script to know how much history to keep, and when it cannot work that out you get a different message. That one is covered in the max_bars_back error guide. Setting max_bars_back explicitly in the indicator() call, as the next two examples do, avoids it.
Fix 4: stop early with break
A loop that searches for something does not have to finish once it has found it. Scanning backward for the most recent bar that closed above the current close can stop at the first match.
//@version=6
indicator("Bars Since Higher Close", max_bars_back = 500)
maxBack = input.int(300, "Max lookback", minval = 1, maxval = 500)
int age = na
for i = 1 to maxBack
if close[i] > close
age := i
break
plot(age, "Bars since a higher close")On a falling market the first bar back already qualifies, so the loop exits at once. On a market at new highs it runs the whole window and returns na, which is the correct answer. The worst case is the same as before, but the typical cost drops a lot. Early exit helps most when matches are common, and it does nothing when matches are rare, so treat it as an average-case improvement and keep the cap from Fix 3 as the guarantee.
Fix 5: run the loop on the last bar only
If the loop produces something that is only drawn once, such as a label, a table cell, or a line at the right edge, there is no reason to run it on historical bars. Wrap it in barstate.islast and it executes once per tick on the final bar instead of once per bar.
//@version=6
indicator("Last Bar Loop", overlay = true, max_bars_back = 5000)
len = input.int(500, "Length", minval = 1, maxval = 5000)
if barstate.islast
float best = 0.0
int bestAge = 0
for i = 0 to len - 1
float move = math.abs(close[i] - open[i])
if move > best
best := move
bestAge := i
label.new(bar_index, high, str.format("Largest body {0} bars ago", bestAge), style = label.style_label_down)This is the biggest saving of all, because 500 iterations once is nothing next to 500 iterations on every one of thousands of bars. The tradeoff is real, though. A value computed only on the last bar does not exist on earlier bars, so you cannot plot it as a history line, use it in a condition that fires on past bars, or look at it in replay. Use this fix for display, not for logic that other parts of the script depend on. The same idea applies to tables, and Pine Script table objects shows how to build a dashboard that fills in on the last bar.
Loops over arrays
Looping over an array is the other place this error appears, especially in scripts that collect values into an array and then sum or search it with a hand-written loop. Arrays have their own built-ins: array.sum, array.avg, array.max, array.min, array.sort, and array.indexof all do the work without a Pine-level loop.
//@version=6
indicator("Array Built-ins", overlay = true)
len = input.int(100, "Length", minval = 1)
var array<float> buf = array.new<float>()
buf.push(close)
if buf.size() > len
buf.shift()
plot(buf.avg(), "Window average")
plot(buf.max(), "Window max")The array is trimmed to len elements so it does not grow without bound, and the statistics come from built-ins rather than from a loop you wrote. For a fuller treatment of storing, iterating, and sorting, see Pine Script arrays: store, loop, and sort.
A short diagnostic routine
When the error appears, resist the urge to try random changes. Work through the same few questions each time. Is the loop length driven by an input, and what happens at the maximum? Is there a loop inside a loop? Does the loop body call anything expensive? Does the result need to exist on every historical bar, or only the last one? Then pick the fix that matches: a built-in if the quantity is standard, a running total if it is an additive custom quantity, a cap if the window is oversized, a break if you are searching, and barstate.islast if the output is drawn once.
To confirm a rewrite did not change the answer, plot the old and new versions together, as the running-mean example does, and compare them. Since the point is to change how the number is computed without changing the number, an overlay that does not match tells you immediately that something is off. The same habit applies to code you did not write yourself, which checking AI-generated Pine Script discusses.
Using PineScripter for the rewrite
If you have a slow loop and would rather not hunt for the matching built-in, you can paste the script into the PineScripter AI editor and ask for the loop to be rewritten with built-in functions. PineScripter writes Pine Script v6, checks every script for compile errors the same way TradingView does, and fixes errors it finds on its own. A follow-up request changes only the affected lines, and the Code Changes view shows line by line what changed, so you can compare the rewrite with your original. You can also run the new version on the chart inside PineScripter against its crypto spot market data and step through it bar by bar in replay before pasting it into TradingView. As always, check the rewrite against your original on the chart yourself. Plans and pricing are on the PineScripter site, and how PineScripter works walks through the workflow.
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.
Frequently asked questions
What is the time limit for a loop in Pine Script?
TradingView documents that the execution time for any loop on any single bar is limited to 500 milliseconds. The outer loop of nested loops counts everything inside it.
Does the error mean my code is wrong?
No. The code is valid. The loop does more work per bar than the runtime allows, usually because an input makes the window long or because loops are nested.
Can I just make the loop shorter?
Often yes. Cap the input with maxval to the longest window the logic needs. If the window cannot shrink, use a built-in or a running total instead.
Is a built-in always faster than a loop?
Usually, because the platform maintains its own running state. Plot the loop and the built-in together to confirm they give the same values before you swap.
When is barstate.islast the right fix?
When the loop output is only drawn once, such as a label or table. It cannot feed logic on earlier bars, since the value exists only on the last bar.
Describe your indicator in plain English and get Pine Script that compiles →
Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.