Quick Answer
The error "Calculation takes too long to execute" means that your script ran past a time limit. There are two limits. According to TradingView's support page for this error, the total time that a script gets for all bars depends on the plan: 20 seconds on Basic, 40 seconds on Essential, Plus and Premium, and 100 seconds on Ultimate. The Pine limitations page adds a second limit: the execution time of any loop on any single bar is limited to 500 milliseconds, and in nested loops the outer loop counts as one loop, so it times out first.
A loop can pass the 500 ms check and still break the total limit. The documentation gives the example: a loop that takes 400 ms on each bar of a 20,000-bar dataset would need 8,000 seconds. The fixes are to use built-in functions instead of your own loops, to stop repeating the same calculation, to combine request.*() calls, to limit the bars that the script processes, and to find the slow line with the Pine Profiler before you change anything. This post shows each with a short script.
From the author: I convert Pine Script to MQL5 and cTrader C#. Slow scripts are a sign of a design that will also be slow in MQL5: a loop over a long history on every tick is a bad idea on any platform. Fixing the loop in Pine first gives a better design to convert.
Key Facts
| Topic | What the documentation says |
|---|---|
| Message | Calculation takes too long to execute |
| Total time limit | 20 s (Basic), 40 s (Essential, Plus, Premium), 100 s (Ultimate), per the support page |
| Loop limit | 500 ms for any loop on any single bar |
| Nested loops | The outer loop counts as one loop and times out first |
| Request calls | The profiling page notes a limit of 40 unique request.*() calls per script (64 on Ultimate) and advises to stay far below it |
| Profiler | Switch "Profiler mode" on in the Pine Editor, works for editable Pine v6 scripts |
| Fix families | Split the script, limit the bar range, optimize the code |
The plan limits can change. Check the TradingView pricing page and the support article before you rely on a number.
The Broken Script
This script finds the highest close over 500 bars with a loop, on every bar:
//@version=6
indicator("Slow: loop on every bar")
highestClose(int length) =>
float result = close
for i = 0 to length - 1
result := math.max(result, close[i])
result
plot(highestClose(500))
On a chart with a long history this is 500 reads on every bar. The limit that you hit depends on the plan and the number of bars, and I have not run this script in TradingView, so test the time on your own chart.
Fix 1: Use a Built-in
The profiling page compares a loop-based "highest value" function with the built-in. The loop version took about 57.9 ms over 20,735 executions, and the built-in ta.highest(close, 20) took about 3.2 ms for the same output. The same idea for the script above:
//@version=6
indicator("Fast: built-in")
plot(ta.highest(close, 500))
A built-in is both shorter and faster, and it keeps its own history correctly (see the CW10003 warning for why history functions belong at the top level).
Fix 2: Do Not Repeat the Same Calculation
The profiling page shows a script that called the same function up to 11 times per execution. Assigning the result once to a variable and reusing it cut the cost, and the page notes that the compiler does not do this for you:
//@version=6
indicator("Calculate once")
float avgRange = ta.sma(high - low, 50) // calculated once
plot(avgRange * 1.5, "Upper")
plot(avgRange * 0.5, "Lower")
Fix 3: Combine request Calls
Several requests from the same context should be one call that returns a tuple. The profiling page says this reduces runtime, memory use and compiled size:
//@version=6
indicator("One request")
[dailyHigh, dailyLow, dailyClose] = request.security(syminfo.tickerid, "1D", [high, low, close])
plot(dailyClose)
See also request.security to MQL5 and the memory limits post, because too many requests also use memory.
Fix 4: Limit the Bars
The support page says to limit the bars that the script processes with date and time filtering. A simple version is to skip your own heavy loop before a start date:
//@version=6
indicator("Date filter")
startTime = timestamp(2025, 1, 1)
float heavy = na
if time >= startTime
float total = 0.0
for i = 0 to 199
total += close[i]
heavy := total / 200
plot(heavy)
The loop runs only on bars from the start date on. The date filter helps when the heavy part is your own loop. Do not put a history function such as ta.sma() inside the condition: it can trigger the CW10003 warning, see the CW10003 post. (This loop also needs at least 200 past bars at the start date, so check the buffer limit, see the historical offset error.)
Fix 5: Find the Slow Line With the Profiler
Do not guess. The profiling page says to add the script to a chart, open its source in the Pine Editor, and switch on Profiler mode under the "More" menu. It shows bars and approximate runtime percentages beside the significant lines, and flame icons on the three highest-impact regions. The page also says that the results are estimates, because profiling adds overhead, and that runtimes vary between runs, so profile more than once and with different inputs.
Fix 6: Split the Script
If the script does several jobs, split it. The support page lists splitting a script into several smaller ones as the first fix. The same idea helps against the size limit, see too many tokens.
What This Means for the MQL5 or cTrader Version
| Pine Script | MQL5 | cTrader C# |
|---|---|---|
| A loop over 500 bars on every bar | A loop in OnCalculate that should only touch new bars (use prev_calculated) | Only compute index in Calculate(int index) |
| ta.highest(close, 500) | iHighest with a count | Bars.HighPrices.Maximum(500) |
| Time limit per script | No fixed limit, but a slow OnTick blocks the EA | The same: a slow handler delays the next one |
The lesson carries over: do the heavy work once per new bar, not once per tick, and never loop over the full history on each event. See barstate.isnew to MQL5 for once-per-bar logic.
Similar Pine Script Messages
| Message | What it means | Where to look | |---|---|---| | Calculation takes too long to execute | A time limit was passed | This post | | Memory limits exceeded | The script uses too much memory | Memory limits exceeded | | Maximum number of orders (9000) was reached | A strategy placed too many orders | Maximum number of orders | | Compiled code contains too many tokens | The script is too large after compilation | Too many tokens | | Historical offset beyond the buffer's limit | A buffer is too small | Historical offset error | | Function should be called on each calculation | A history function runs conditionally | CW10003 warning |
Checklist: What to Check When You See "Calculation Takes Too Long"
- Switch on the Profiler and find the heaviest lines.
- Replace your own loops with built-ins where one exists.
- Calculate once and reuse the variable.
- Combine
request.*()calls into one tuple. - Limit the bars with a date filter, if the heavy part is your own loop.
- Check nested loops: the outer loop times out first.
- Split the script if it does several jobs.
- Test on a long chart and with your plan's limit in mind.
Common Mistakes
- Guessing which line is slow.
- Writing a loop for something that has a built-in.
- Calling the same function several times.
- One
request.security()call per value. - Testing on a short chart only.
- Putting history functions inside the date filter.
FAQ
Related Guides
- Pine Script maximum number of orders (9000): the strategy order limit.
- Pine Script memory limits exceeded: the memory limit and how to stay below it.
- Pine Script compiled code contains too many tokens: the size limit.
- Pine Script function should be called on each calculation: history functions and conditions.
- Pine Script historical offset beyond the buffer limit: buffer size.
- Pine Script request.security to MQL5: multi-timeframe data.
- Pine Script barstate.isnew to MQL5: once-per-bar logic.
- Pine Script var and varip to MQL5: keep state between bars.
- Pine Script to MQL5 guide: converting a script step by step.
Convert Without Guessing
If you want a first draft of your Pine Script in MQL5 or cTrader C#, try the CodeFlowOS converter. It produces a draft that you still have to review, and the compiler check is optional. Outputs are not guaranteed, and code that compiles can still have wrong logic, so always compare the result with the chart. If the converted code does not compile, paste it with the message into the Error Fixer: it suggests a minimal fix and shows what changed (1 credit, with up to 3 attempts included).
This article is educational. It does not describe trading performance and is not financial advice. Test every script on a chart or a demo account before you rely on it.