Explainers / Pine Script errors
Pine Script errors: what the common messages mean and how to fix them
The Pine Editor stops at the first problem it finds and prints one line, in the editor's own words, with a line number. The words are precise but not friendly. This page lists the messages people search for most, what each one is actually saying, and the fix that usually works. Everything here is free. The last section is about the scripts that compile and still behave wrong, which no error message will ever tell you about.
First, three things that solve most of it
- Read the line number, then the line above it. The editor reports where it gave up, which is often one line after the mistake. An unclosed bracket on line 12 is reported on line 13.
- Check the version line. The first line of a script should be
//@version=6(or 5, or 4). Code written for one version pasted under another version's line produces half of the errors below. The editor's menu has a converter for older versions; it rewrites what it can and leaves comments where it cannot. - Paste the error and the line into an AI chat. For a compile error, a chatbot with the error text and the offending lines fixes it correctly most of the time, at no cost. Give it the version line too. This is the right first stop. Where it stops being enough is covered at the end.
"Syntax error at input 'end of line without line continuation'"
The parser reached the end of a line and was still expecting more. Three causes cover nearly every case:
- An unclosed bracket. Count the
(and)on the reported line and the line before it. A missing closing bracket on a longplot()orinput()call is the most common single cause. - A multi-line expression that is not indented. Pine lets you continue a long expression on the next line, but the continuation has to be indented, and not by a multiple of four spaces, because four-space steps mean "this is a block inside an if or a function". Two spaces, or a tab, works. Four does not.
- A block body that is not indented. The lines under
if,for,whileor a function definitionf(x) =>must be indented by four spaces (or a tab). Mixed tabs and spaces from a copied script look right and compile wrong. Select all, reindent, try again.
"Mismatched input 'X' expecting 'end of line without line continuation'"
The same family. The parser found something where it expected the line to end. "X" is the thing it found. If X is ) or ], there is one closing bracket too many. If X is =, you probably wrote = where the language wanted := (reassignment of an existing variable) or wrote a comparison with one = instead of two. If X is else, the else is on a line of its own but not aligned with its if, or the body between them is indented wrongly.
"Undeclared identifier 'X'"
The script uses a name it has never seen defined. Four causes, in order of how often they come up:
- A typo or the wrong case. Pine is case sensitive.
Closeis notclose,myLenis notmylen. - A version namespace. From version 5, most built-in functions live in a namespace:
sma()becameta.sma(),rsi()becameta.rsi(),sum()becamemath.sum(),security()becamerequest.security(),tostring()becamestr.tostring(). A v4 script under a v5 or v6 version line fails on the first one of these it meets. The converter in the editor's menu handles this mechanically. - Defined inside a block, used outside it. A variable first assigned inside an
ifbody does not exist outside it. Declare it before theif(float x = na) and assign inside with:=. - Used before its line. Pine reads top to bottom. A function or variable has to be defined above the line that uses it.
"Could not find function or function reference 'study'"
The script says study(...) but the version line is 5 or 6, where the declaration is indicator(...). Change the word, and check the arguments: study(title, shorttitle, overlay) maps onto indicator(title, shorttitle, overlay) directly. The same message with ta.sum means the function is in the wrong namespace: it is math.sum(). With security it is request.security(). With input.resolution it is input.timeframe().
"Cannot use 'plot' in local scope"
plot(), plotshape(), plotchar(), hline(), fill(), bgcolor() and alertcondition() can only sit at the top level of the script, never inside an if, for or a function. The compiler is not being difficult: a plot is a fixed output of the script, so it has to exist on every bar. The fix is to move the plot to global scope and put the condition inside it:
// not allowed
if longCondition
plotshape(true, style=shape.triangleup)
// allowed
plotshape(longCondition ? true : na, style=shape.triangleup)
For colours, plot(x, color = cond ? color.green : color.red) does the same job. Drawings (label.new, line.new, box.new) are different: they are allowed inside blocks, which is why people reach for them when a plot is refused.
"Cannot call 'na' with argument 'x'=... (series bool)"
From version 5 a bool can only be true or false, never na, so na(someBoolean) is rejected. The script, usually converted from v4, is testing whether a condition "has no value yet". Replace the test with what it meant: not someBoolean, or test the number that feeds the condition (na(close[20])) instead of the condition itself.
"The script must have one indicator(), strategy() or library() function call"
Either the declaration line is missing, there are two of them (a copied script pasted under another one), or it is misspelled. Exactly one, near the top. A script with strategy() cannot also call indicator().
"Cannot assign a tuple to a variable" and "Tuple size mismatch"
Some functions return several values at once, for example ta.macd() returns three and ta.supertrend() returns two. They have to be unpacked into the same number of names: [macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9). Assigning the result to one name, or to the wrong number of names, gives these two messages.
"Pine cannot determine the referencing length of a series. Try using max_bars_back"
The script reads a past value with a bracket, x[n], where n is itself computed and the compiler cannot work out the deepest n it will ever need, so it cannot reserve history. Fixes, from cheap to blunt: use a fixed number instead of a computed one where you can; wrap the series with max_bars_back(x, 500); or set max_bars_back = 500 in the indicator() call, which costs memory on every series in the script. The related runtime message, "The requested historical offset (N) is beyond the historical buffer's limit", means the same thing happened while running: the script asked for more history than was reserved.
"Script requesting too many securities"
Each request.security() call with a different symbol, timeframe or expression counts toward a fixed limit per script (40 in recent versions). Multi-timeframe scripts hit it by requesting one value at a time. Request a tuple in one call instead of several calls, [o, h, l, c] = request.security(syminfo.tickerid, "D", [open, high, low, close]), and reuse the result.
Runtime errors: "Loop is too long" and "Memory limits exceeded"
These appear after the script compiles, as a red mark on the chart. A for or while loop ran past the time the engine allows on one bar, or the script holds too many drawings and array elements. Reduce the loop bound, exit early, cap arrays with array.shift() when they grow, and delete old labels and lines instead of letting them pile up. If the script was copied from a published one that works, the difference is usually the chart: a one-second chart with years of history runs the same loop many more times.
Fixing the error is not fixing the script
Every message above is about whether the script can run. None of them is about whether it is right. The problems that matter compile without a word:
- A script that reads a higher timeframe with
request.security()andbarmerge.lookahead_on, or reads the current unfinished bar of it, so its historical signals use information the live chart never had. It compiles; it draws beautifully; the signals change after a reload. The mechanics are on the repainting page. - A strategy whose entries fire on a condition that uses the current bar's close before the bar is closed, so the backtest fills at prices that were never offered.
- An alert that fires on
alert()inside a condition that flickers within a bar, so it fires, and the marker it was supposed to match never prints.
For those there is no error line. The free repaint checker runs in your browser and flags the known patterns in a pasted source. When a script compiles and still behaves differently live from how it looked in history, that is what the audit below reads for, line by line.
Where it fails
- The messages change between versions. The wording above is from versions 5 and 6. Older scripts print older text, and TradingView rewrites messages from time to time.
- One line, one error. The editor stops at the first problem. A converted script can have thirty; fixing one reveals the next.
- The converter does not finish the job. It renames what it recognises and leaves a comment where it does not. The comments still have to be read.
- AI fixes can compile and be wrong. A chatbot asked to "make it compile" will sometimes delete the line that was failing, or replace a function with one that returns a different thing. Diff its output against your original before trusting it.
- This page cannot see your script. It lists causes in order of how common they are, not in the order they apply to you. The line number in your editor beats any list.
- Runtime limits depend on the chart. A script that runs on a daily chart can fail on a one-minute chart with the same code, so a fix that works on one chart proves nothing about another.
Educational only. Not financial advice. Nothing here is a recommendation to buy or sell anything, and nothing here says that a script which compiles, or passes a checker, is correct or safe to trade. Pine Script and TradingView are products of TradingView, Inc.; this page describes their published language and editor in our own words and is not affiliated with them.
Also explained: Repaint checker, VWAP, Supertrend, RSI, UT Bot Alerts, Nadaraya-Watson Envelope, Squeeze Momentum, What is repainting on TradingView?, Is TradingView backtesting accurate?, Chandelier Exit, WaveTrend Oscillator, QQE MOD, Pivot highs and lows, Hull Suite, Range Filter, Twin Range Filter, HalfTrend, ZigZag++, SSL Hybrid, CM MacD Ultimate MTF, Volume Profile / Fixed Range, ADX and DI, Support Resistance Channels, Market Structure Break & Order Block, Order Block Finder, Pivot Point SuperTrend, Trendlines with Breaks [LuxAlgo], Divergence for Many Indicators, TradingView script selling terms, Support and Resistance Levels with Break, Liquidity Swings [LuxAlgo], Breakout Probability (Expo), Did ChatGPT or Claude write your Pine Sc, Lorentzian Classification, SuperTrend AI (Clustering), Machine Learning Adaptive SuperTrend, Dynamic Swing Anchored VWAP, Support and Resistance Power Channel by , Support and Resistance (High Volume Boxe, Trendline Breakouts With Targets by Char, Breakout Finder by LonesomeTheBlue
Get the next teardown by email
One short email when a new teardown or free tool goes live, about twice a month. No signals, no hype. Unsubscribe in one click.
Almost done. Check your inbox and click the confirmation link.
Sent with Kit. Your address is used only for these emails. Privacy
No TradingView account yet? This affiliate link gives you a $15 coupon toward a paid plan, and we earn a commission if you buy one. The free plan is enough to follow this page.