Quick Answer
The TradingView compiler stops with "Cannot use 'plot' in local scope" when a plot() call sits inside an if, a for, or any other indented block. The TradingView FAQ states the rule directly: scripts cannot place plot() calls directly within if or for statements, or in any other local scopes, because the compiler needs to know about all plots during script compilation.
The fix is to keep the plot() call at the top level of the script and make the value conditional, not the call. There are three patterns: a ternary expression that gives na when the plot should be hidden, a variable that you set inside the if block and plot once outside, and the display parameter for plots that should only feed other calls. The sections below show each one with a short script. If you plan to convert the indicator to MQL5 later, the same thinking applies: the plot always exists, and the value is empty when there is nothing to draw.
From the author: I convert Pine Script indicators and strategies to MQL5 and cTrader C#. The "plot only when the condition is true" idea comes up in almost every indicator, and the first try, an
ifaroundplot(), is the error in this post. The right pattern is also the one that converts cleanly.
Key Facts
| What you wrote | Result | Fix |
|---|---|---|
| if cond then an indented plot(...) | Error: cannot use plot in local scope | Move plot() to the top level |
| Same, inside a for loop | Same error | Plot once, outside the loop |
| You want a line only when a condition holds | The value must be conditional | plot(cond ? value : na, ...) |
| The line is joined across the gaps | Default line style bridges na | Add style = plot.style_linebr |
| A plot that only feeds fill() | You do not want it on the chart | Assign it to a variable, display = display.data_window |
| A user input should turn a plot off | The plot cannot be inside if input | plot(showIt ? value : na, ...) |
The Broken Script
//@version=6
indicator("Conditional plot", overlay = true)
showMa = input.bool(true, "Show moving average")
ma = ta.sma(close, 20)
if showMa
plot(ma, "SMA 20", color = color.orange) // Cannot use 'plot' in local scope
The indented line belongs to the if block, so it is in a local scope. The compiler needs every plot at the top level, where it can see them all before the script runs.
Pattern 1: A Ternary With na
According to the TradingView FAQ, scripts can plot values conditionally by changing the series or the color of the plot. The simplest way is to give na when the plot should be empty:
//@version=6
indicator("Conditional plot", overlay = true)
showMa = input.bool(true, "Show moving average")
ma = ta.sma(close, 20)
plot(showMa ? ma : na, "SMA 20", color = color.orange, linewidth = 2, style = plot.style_linebr)
Use plot.style_linebr for a line. The FAQ recommends it so that the line does not span the bars where the value is na. This pattern is also the accepted answer for the same error on a well known forum question: the plot stays at the top level and the if block disappears.
Pattern 2: A Variable Set Inside the if Block
When the condition is longer than one line, put the logic in an if block that assigns a variable, and plot the variable once. Declare the variable first, with na as its start value, and use := to change it:
//@version=6
indicator("Plot above the average", overlay = true)
ma = ta.sma(close, 20)
float aboveLine = na
if close > ma
aboveLine := ma
plot(aboveLine, "Average while price is above it", color = color.green, linewidth = 2, style = plot.style_linebr)
A well known answer from a Pine community moderator uses this shape for an equity curve with three input modes: a variable equity starts as na, the if branches set it, and plot(equity, ...) is called once at the end. A shorter answer in the same thread says the same thing: set the variable to na under a condition, then plot it.
Pattern 3: Hidden Plots With display
Some plots exist only to feed fill(). The FAQ says to assign them to variables and control where they show with the display parameter:
//@version=6
indicator("Fill between two averages", overlay = true)
fastMa = ta.sma(close, 10)
slowMa = ta.sma(close, 30)
p1 = plot(fastMa, "Fast", display = display.data_window, editable = false)
p2 = plot(slowMa, "Slow", display = display.data_window, editable = false)
fill(p1, p2, color = color.new(color.blue, 85))
The two plots are at the top level, they are assigned to variables, and they do not draw lines on the chart. The fill() call uses them.
A Note About the Condition Itself
The FAQ also advises to declare the Boolean that controls a plot in the global scope, so that all plot() and fill() calls can use it, and to update it inside a local block with :=. If the condition is a state (such as "the fast average crossed the slow one and has not crossed back"), keep it in a var variable at the top level and change it inside if blocks. For the conversion of var, see Pine Script var and varip to MQL5.
Other Local-Scope Mistakes
| You wrote | Problem | Do this |
|---|---|---|
| plot() in a function body | A function body is a local scope | Return the value, plot outside the function |
| plot() in a switch case | A switch branch is a local scope | Set a variable in the branch, plot once |
| A plot() call with a for loop to plot many lines | One call per line is needed at the top level | Write the calls, or use arrays and a fixed number of plots |
Drawing objects such as labels and lines are a different case: they are created with their own functions and are not limited in the same way. If you are unsure, check the page for the function in the Pine Script reference.
When You Convert the Script to MQL5 or cTrader
A conditional plot becomes an indicator buffer that holds an "empty" value on the bars where nothing is drawn:
| Pine Script | MQL5 | cTrader C# |
|---|---|---|
| plot(cond ? value : na) | A buffer set to its empty value when cond is false | Result[index] left as double.NaN |
| plot.style_linebr | The plot's empty value property | Not needed, NaN is not drawn |
| display = display.data_window | A buffer that is not drawn | An output you do not show |
In MQL5, a buffer is filled in OnCalculate (see OnCalculate function not found), and in cTrader an indicator writes to its output in Calculate(int index) (see CS0534). The exact empty value rules differ by platform, so check the plot style on a chart before you rely on them.
Similar Pine Script Errors
| Message | What it means | Where to look |
|---|---|---|
| Cannot use 'plot' in local scope | plot() is inside a block | This post |
| Function should be called on each calculation | A history function is called inside a condition | CW10003 warning |
| Undeclared identifier | A name Pine does not know | Pine undeclared identifier |
| End of line without line continuation | A line is broken in the wrong place | Pine end of line error |
| series int vs simple int | A function needs a constant length | series int, simple int |
| Could not find function | A ta.* function that does not exist | ta.cmf not found |
Checklist: What to Check When You See "Cannot Use plot in Local Scope"
- Find the
plot()line and look at its indentation. - Move the call to the top level of the script.
- Make the value conditional:
cond ? value : na. - Use
plot.style_linebrfor lines that have gaps. - Use a variable (
float x = na, thenx := ...) when the condition has several steps. - Use
displayfor plots that only feedfill(). - Keep the controlling Boolean in the global scope.
- Check the result on a chart with a symbol you know.
Common Mistakes
- Wrapping
plot()in anifto turn a line on and off. - Forgetting
na, so that the line is drawn at 0 when it is "off". - Using a plain line style, so that the gaps are joined.
- Declaring the variable inside the
if, so that the plot cannot see it. - Writing
=instead of:=when you update a variable. - Putting
plot()in a function.
FAQ
Related Guides
- Pine Script undeclared identifier: a name that Pine does not know.
- Pine Script end of line without line continuation: a line broken in the wrong place.
- Pine Script series int, simple int: a length that must be a constant.
- Pine Script function should be called on each calculation: the other common "conditional scope" problem, for
ta.*calls. - Pine Script var and varip to MQL5: keep state between bars.
- Pine Script v6 to MQL5: what changes when you convert a v6 script.
- MQL5 OnCalculate not found: the indicator entry point on MetaTrader.
- cTrader C# error CS0534: the indicator entry point in cTrader.
- Pine Script to MQL5 guide: converting a script step by step.
Convert Without Guessing
If you want a first draft of your Pine Script indicator 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.