◆ New — Strategy Validator, Code Fixer & Prop Compliance Checker are live. Try one free →
Home / Pine errors / Scope
Pine Script v6 error · Scope

Pine Script v6 "Cannot use 'plot' in local scope" error — cause & fix

The error
Cannot use 'plot' in local scope

plot(), and the declaration-style calls like indicator()/strategy()/plotshape()/alertcondition(), must live at the script's main scope — never inside an if, for, or function body. Educational content only; not financial advice and no profitability claim.

Why it happens

plot() is a global declaration: it defines one output series for the whole chart, so Pine forbids calling it from a local (indented) scope such as an if branch, a for loop, or a custom function body. The same restriction applies to plotshape(), plotchar(), plotarrow(), plotcandle(), hline(), fill(), barcolor(), bgcolor(), and alertcondition(). Wrapping plot() in `if condition` to plot conditionally is the classic trigger.

How to fix it

Move plot() to the main scope and make it conditional through its arguments instead of through an if block. Compute the value (or na to hide it) in a variable, then pass that variable — or use the ?: ternary in the series/color argument — to plot(). This keeps the plot declaration global while still controlling what it draws per bar.

What triggers it

//@version=6
indicator("Local plot demo", overlay=true)
if ta.crossover(ta.sma(close, 10), ta.sma(close, 20))
    plot(close, color=color.green)

The fix, in code

✓ Validated clean by our own engine

//@version=6
indicator("Local plot demo", overlay=true)
fast = ta.sma(close, 10)
slow = ta.sma(close, 20)
bullish = ta.crossover(fast, slow)
plotColor = bullish ? color.green : na
plot(close, title="Signal close", color=plotColor)
plotshape(bullish and barstate.isconfirmed, title="Cross up", style=shape.triangleup, location=location.belowbar, color=color.green)

Related errors

Educational, code-correctness reference only — not financial advice. Trading involves substantial risk of loss.

Catch the bug that compiles.Run auditGet Pro