请求修复Supertrend指标Pine Script代码的未声明标识符错误
修复Pine Script v5中Supertrend指标的未声明标识符错误
错误原因
代码第10、11行的TrendUp[1]和TrendDown[1]在变量声明阶段就被引用,但此时这两个变量还未完成初始化,Pine Script无法识别这些未声明的标识符。
修复后的代码
//@version=5 indicator(title="Supertrend", shorttitle="SuperTrend", overlay = true, timeframe="", timeframe_gaps=true) Factor=input.int(defval=3, minval=1,maxval = 100, title="Factor") Pd=input.int(10, minval=1, maxval = 100, title="ATR Length") Up=hl2-(Factor*ta.atr(Pd)) Dn=hl2+(Factor*ta.atr(Pd)) // 使用nz()初始化历史值,避免未声明标识符错误 TrendUp = close[1] > nz(TrendUp[1], Up) ? math.max(Up, nz(TrendUp[1], Up)) : Up TrendDown = close[1] < nz(TrendDown[1], Dn) ? math.min(Dn, nz(TrendDown[1], Dn)) : Dn 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, color=linecolor, style=plot.style_line, linewidth=2, title="SuperTrend")
关键修改说明
- 在引用
TrendUp[1]和TrendDown[1]时,用nz()函数设置默认值:第一次计算时,若历史值不存在(即na),则用当前的Up或Dn作为初始值,确保变量能正常初始化。 - 这样修改后,Pine Script可以正确识别变量的历史引用,解决未声明标识符的报错问题。
内容的提问来源于stack exchange,提问作者Krishnendu Bhattacharyya
相关产品推荐
相关产品推荐

