Quick Answer
The runtime error "Memory limits exceeded" (RE10139 in the TradingView documentation) means that your script used more memory than the Pine runtime allows. The documentation names the most common cause: a script that requests custom objects or collections (arrays, maps, matrices) from request.*() functions. A call that returns the ID of a large array on every bar copies that data again and again, and a long history runs out of memory.
The documentation lists ten fixes. The ones that solve most cases are: return only the last state of a collection (with barstate.islast), return calculated values instead of the collection's ID, reduce the number of request.*() calls, use max_bars_back only as large as needed, create tables once with var and update them only on the last bar, and use setter functions for drawings instead of creating new ones. This post shows a broken script, the fixes as short scripts, a list of the other memory costs, and what this means when you convert the script to MQL5 or cTrader C#.
From the author: I convert Pine Script to MQL5 and cTrader C#. Scripts that hit this error are usually the ones with a dashboard, a multi-timeframe table or a large history array. They are also the scripts that are hardest to convert, because the memory is used by a feature that has no direct copy in MQL5 or C#.
Key Facts
| Topic | What the documentation says |
|---|---|
| Message | Memory limits exceeded (RE10139) |
| Most common cause | Requesting custom objects and collections from request.*() functions |
| Why | Requesting the IDs of large collections on each bar can lead to excessive memory use |
| Other causes | Many request.*() calls (notably request.security_lower_tf()), a max_bars_back that is too large, references to distant history, inefficient drawings and tables, many strategy orders and trades |
| Numeric memory cap | The page does not state one |
| Related stated limits | Collections up to 100,000 elements, maps up to 50,000 key-value pairs, up to 1,200 variables per scope, history buffers up to 5000 bars for most series |
The limits in the last row come from the Pine Script limitations page, not from the RE10139 page.
The Broken Script
This is a short version of the pattern that the documentation describes: a function stores values in a var array and returns the array's ID, and request.security() brings that ID back on every bar:
//@version=6
indicator("Broken: collection returned on every bar")
dataFunction() =>
var array<float> values = array.new<float>()
values.push(close - open)
values
array<float> daily = request.security(syminfo.tickerid, "1D", dataFunction())
plot(daily.size())
On a short chart this may run. On a long history, the repeated copies of the collection exhaust the memory and the runtime stops with RE10139. I have not run this script in TradingView, so check the message on a long chart before you rely on it.
Fix 1: Return Calculated Values, Not the Collection
The documentation's third fix is to compute inside the requested function and return only the results:
//@version=6
indicator("Fixed: return results")
dataFunction() =>
var array<float> values = array.new<float>()
values.push(close - open)
[values.avg(), values.size()]
[avgBody, count] = request.security(syminfo.tickerid, "1D", dataFunction())
plot(avgBody, "Average body")
Two numbers cross the request boundary on each bar, and the array stays inside the function.
Fix 2: Return the Collection Only on the Last Bar
When you do need the collection outside, the first fix in the documentation is to return its ID only on the last bar, and na on the others:
//@version=6
indicator("Fixed: last bar only")
dataFunction() =>
var array<float> values = array.new<float>()
values.push(close - open)
[values.avg(), barstate.islast ? values : na]
[avgBody, lastValues] = request.security(syminfo.tickerid, "1D", dataFunction())
if barstate.islast and not na(lastValues)
label.new(bar_index, high, "Count: " + str.tostring(lastValues.size()))
A variant from the documentation returns the ID on a few chosen bars, for example the first bar of each month, using timeframe.change("1M").
Fix 3: Fewer request Calls
The documentation says to remove unnecessary request.*() calls, to use higher timeframes where you can, to combine requests to the same dataset into one call that returns a tuple, and to use calc_bars_count to limit how many bars a request calculates. request.security_lower_tf() is named as a heavy case, because it returns intrabar arrays for every bar. For the conversion side of these calls, see Pine Script request.security to MQL5.
//@version=6
indicator("One request, three values")
[h, l, c] = request.security(syminfo.tickerid, "1D", [high, low, close])
plot(c)
Fix 4: Keep Buffers Small
An oversized max_bars_back stores more data than needed and uses memory. The documentation says to set it only when needed, to the smallest size that covers your references, and to avoid references to very distant history. See the historical offset error for the opposite problem, a buffer that is too small.
Fix 5: Tables and Drawings
Dashboards use memory in two ways: they rebuild a table, and they create drawings that are not needed. The documentation's fixes:
//@version=6
indicator("Table created once", overlay = true)
var table info = table.new(position.top_right, 2, 1)
if barstate.islast
table.cell(info, 0, 0, "Bars")
table.cell(info, 1, 0, str.tostring(bar_index + 1))
- Create the table once with
var, and fill it only whenbarstate.islastis true. - Do not update drawings on historical bars. Update them on realtime bars where you can.
- Use setter functions such as
line.set_x2()instead of creating a new drawing. - Delete drawings that you no longer need, and set
max_lines_count,max_labels_count,max_boxes_countormax_polylines_countin the declaration to what the script really uses.
Fix 6: Strategies With Many Orders
A strategy that opens and closes thousands of trades stores them all. The documentation suggests filtering by date, so that orders start only after a chosen date:
//@version=6
strategy("Date filter", overlay = true)
startTime = timestamp(2024, 1, 1)
canTrade = time >= startTime
smaValue = ta.sma(close, 20) // history function at the top level
if canTrade and ta.crossover(close, smaValue)
strategy.entry("Long", strategy.long)
The history function is called at the top level on purpose, see the CW10003 warning.
What This Means When You Convert the Script
| Pine Script feature | MQL5 | cTrader C# |
|---|---|---|
| Arrays and maps from request.security | No direct copy: read data with CopyBuffer, CopyRates and iCustom | MarketData.GetBars and series |
| A table on the last bar | Chart objects or Comment() | Chart.DrawText and similar |
| Drawings with setters | Chart objects with ObjectSet... functions | Chart objects |
| Memory cap per script | A different cost model: terminal memory and your own arrays | The same |
A script that used the memory tricks above needs a design decision, not a line-by-line copy: what data the EA really needs on each tick. See Pine Script to MQL5 guide and Pine Script var and varip to MQL5 for state that lives between bars.
Similar Pine Script Messages
| Message | What it means | Where to look |
|---|---|---|
| Memory limits exceeded | The script uses too much memory | This post |
| 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 |
| Cannot use plot in local scope | plot() is inside a block | Plot in local scope |
| series int vs simple int | A function needs a constant length | series int, simple int |
Checklist: What to Check When You See "Memory Limits Exceeded"
- List the
request.*()calls and what each returns. - Check if one returns an array, map or matrix on every bar.
- Return results instead, or return the collection only on the last bar.
- Merge requests to the same dataset into one tuple.
- Check
max_bars_backand remove it if it is not needed. - Create tables once and fill them on the last bar.
- Use setters and delete drawings you do not need.
- Filter dates in strategies that trade a lot.
- Test on a long chart, not only a short one.
Common Mistakes
- Returning a big array from a request on every bar.
- Calling
request.security()once per value. - Setting a large
max_bars_backfor the whole script. - Rebuilding a table on every bar.
- Creating a new line or label instead of updating one.
- Testing on a short chart only.
FAQ
Related Guides
- Pine Script historical offset beyond the buffer limit: the opposite buffer problem.
- Pine Script request.security to MQL5: multi-timeframe data in MQL5.
- Pine Script function should be called on each calculation: history functions and conditions.
- Pine Script cannot use plot in local scope: conditional plots.
- Pine Script var and varip to MQL5: keep state between bars.
- Pine Script series int, simple int: a length that must be a constant.
- Why a Pine strategy gives different results in MQL5: where differences come from.
- Pine Script to MQL5 guide: converting a script step by step.
- Pine Script compiled code contains too many tokens: the CE10117 size limit and the edits that really shrink a script.
- Pine Script calculation takes too long to execute: the script time limits and the Profiler.
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.