Reputation: 125
This code compiles like a charm with //@version=2 :
//@version=2
study("My Script")
Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend = close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? green : red
plot(Tsl)
The same with //@version=4
Add to Chart operation failed, reason: line 9: Undeclared identifier `TrendUp`;
line 10: Undeclared identifier `TrendDown`;
line 11: Undeclared identifier `TrendDown`;
line 11: Undeclared identifier `TrendUp`;
line 11: Undeclared identifier `Trend`;
line 12: Undeclared identifier `Trend`;
line 12: Undeclared identifier `TrendUp`;
line 12: Undeclared identifier `TrendDown`;
line 13: Undeclared identifier `Trend`;
line 13: Undeclared identifier `green`;
line 13: Undeclared identifier `red`;
line 14: Undeclared identifier `Tsl`
How to convert this code to compile in version 4 ? Thanks
Upvotes: 2
Views: 1206
Reputation: 21121
You cannot use the variable you are about to declare, in the declaration statement.
You should first declare the variable and use the :=
operator later to assign some value to it.
//@version=4
study("My Script2")
Factor=input(3, minval=1,maxval = 100)
Pd=input(7, minval=1,maxval = 100)
Up=hl2-(Factor*atr(Pd))
Dn=hl2+(Factor*atr(Pd))
TrendUp=Up
TrendUp:=close[1]>TrendUp[1]? max(Up,TrendUp[1]) : Up
TrendDown=Dn
TrendDown:=close[1]<TrendDown[1]? min(Dn,TrendDown[1]) : Dn
Trend=TrendUp
Trend := close > TrendDown[1] ? 1: close< TrendUp[1]? -1: nz(Trend[1],1)
Tsl = Trend==1? TrendUp: TrendDown
linecolor = Trend == 1 ? color.green : color.red
plot(Tsl)
Upvotes: 2