Compilation error

Fix “Undeclared identifier” in Pine Script

Declare the variable in a scope that includes every place where you use it. In this example, `candleRange` is created inside an `if` block, so the global `plot()` call cannot see it. Declare the variable globally, then use `:=` inside the block to update it. This preserves the conditional calculation while making the identifier available to `plot()`.

This link opens the Pine Script AI Coding Agent overview. It does not run or change code on this page.

Before and after

Make the smallest reviewable change

Both artifacts include the version declaration and the code needed to inspect the stated problem. The diff lists the lines that change between them.

Broken code.pine
//@version=6
indicator("Undeclared identifier demo")
if close > open
    float candleRange = high - low
plot(candleRange)
Fixed code.pine
//@version=6
indicator("Undeclared identifier demo")
float candleRange = na
if close > open
    candleRange := high - low
plot(candleRange)
Diff.pine
--- broken.pine
+++ fixed.pine
@@
+float candleRange = na
 if close > open
-    float candleRange = high - low
+    candleRange := high - low

Root causes

  • The variable is declared inside a local block, but a statement in global scope tries to read it.
  • The identifier is misspelled or its capitalization differs from the declaration.
  • The declaration appears after the first use or belongs to another function or local scope.

How the fix was verified

Method
Pineify UAT grammar checker via check-pine-script-grammar.mjs
Broken result
Returned an undeclared identifier diagnostic at line 5, column 6.
Fixed result
Returned no grammar diagnostics.
Limit
This check proves the scope diagnostic and the static fix. It does not test chart behavior.

Bring the actual script, not just the message

Open the Coding Agent overview to paste editable Pine Script, explain the intended behavior, and request a review. Compile and test the result in TradingView before using it.

Paste your code to fix this error