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.
//@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.
//@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 = 1declaresx. Once per scope.x := 2assigns a new value to an existingx.var x = 1declaresxonce, on the first bar, and keeps its value from bar to bar.x = 2inside anifblock declares a new localxthat 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.