Edgoro
Compile error · Syntax and indentation

Pine Script error: variable is already defined (fix)

"is already defined" in Pine Script means a name was declared twice in the same scope. When to rename the variable and when to use := instead of =.

Pine Editor console · line 4
"signal" is already defined

Cause

The same name is declared twice in the same scope with =. In Pine Script, = declares a new variable; changing the value of an existing one takes :=.

Broken code

TradingView reports the error on line 4.

Pine Script v6
//@version=6
indicator("Two averages", overlay = true)
signal = ta.sma(close, 20)
signal = ta.sma(close, 50)
plot(signal)

Fixed code

The same script, corrected for Pine Script v6. Paste it into the Pine Editor and save.

Pine Script v6
//@version=6
indicator("Two averages", overlay = true)
fastMa = ta.sma(close, 20)
slowMa = ta.sma(close, 50)
plot(fastMa, "Fast SMA", color.teal)
plot(slowMa, "Slow SMA", color.orange)

Why it works

Each declaration with = creates a variable, and a scope can hold only one variable per name. Giving each value its own name keeps both. If you really meant to replace the value, use the reassignment operator instead: signal := ta.sma(close, 50). Reassignment needs the variable to exist already, and the new value must have the same type.

= versus :=

  • x = 1 declares x. Once per scope.
  • x := 2 assigns a new value to an existing x.
  • var x = 1 declares x once, on the first bar, and keeps its value from bar to bar.
  • x = 2 inside an if block declares a new local x that hides the outer one. The compiler warns about it: see Shadowing variable which exists in parent scope.

Questions

How do I change the value of a variable in Pine Script?

Declare it once with = (or with var to keep its value across bars), then assign new values with :=, for example total := total + close. Using = a second time in the same scope is what triggers "is already defined".

Can I reuse a variable name inside an if block?

Technically yes: = inside a block declares a new local variable that hides the outer one, and the compiler warns about shadowing. It is almost always a bug. Use := to update the outer variable.

The scripts on this page are minimal examples written to show the error and its fix, not trading systems. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Still getting an error?

Paste your script and the message into the free Pine Script error fixer: it explains what went wrong and returns a corrected v6 version. Or describe the indicator in plain English and let Edgoro write the code.