To ensure the continued availability of computing resources to all TradingView users, indicators and strategies must not use more memory than specified by our memory limit. If the amount of memory the study requires exceeds that limit, the ‘Memory limits exceeded’ error will appear and the study will return a runtime error. If you encountered the error, you can try optimizing your code so that it consumes less memory. Here are some of the things to pay attention to when you try to optimize your code:
- Refrain from using `max_bars_back` unless necessary. `max_bars_back` is an argument that sets a specified history buffer for all series variables the indicator uses. By default, Pine already automatically allocates a fitting buffer for each variable, so `max_bars_back` is only necessary when you get the Pine cannot determine the referencing length of a series error. In case you do get the error, try to make the `max_bars_back` value as small as possible: if you have one variable that goes 400 bars back and causes an error, setting `max_bars_back` to 5000 would mean that all variables in the code have a 5000-bar historical buffer on every bar, which requires a lot of memory that is wasted on data that is ultimately not used in the script. You can read up on how to optimize your `max_bars_back` usage in our Help Center.
- Try to use as few `security()` calls as possible. The `security()` function is computationally expensive. Excessive use can easily make your indicator reach the memory limit. This is especially relevant for security() calls that request data from lower timeframes: if you request '1m' data on a '1D' chart, for each 1D bar, the indicator will have to load data for hundreds of 1m bars, allocating a lot of memory in the process. Changing the security timeframe to a higher one or removing security() might help.
- The historical buffer is usually created automatically, even when you don’t use `max_bars_back`. Variables referring to distant points in bar history will also increase memory use. Be aware of that when you create variables that reference thousands of bars into history with the `[ ]` operator.
- If you are writing a strategy, the number of trades or orders can also impact the memory used by the script. You can limit the starting point of your strategy to get rid of the unnecessary orders, for example, by adding a separate condition to your entry/exit that compares bar time with a specified timestamp. A good example of date filtering in strategies can be found here.
- Lines and labels created with `line.new()` and `label.new()` functions respectively also use a lot of memory. Make sure to delete unnecessary lines and labels using `line.delete()` and `label.delete()` functions.