You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求修复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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:20:28