Pine Script for语句未声明标识符引发负索引错误排查求助
问题排查与修复方案
核心错误原因
- 负索引报错:原代码直接套用了MT4/MQL的代码逻辑,Pine Script的执行模型与MQL不同,不需要手动声明数组存储历史K线数据。原代码中循环逻辑冗余,首次循环时取
open[bar-1]在历史K线不足的场景下会触发负索引异常,同时数组push后用bar作为索引读取的逻辑也不符合数组的下标规则(数组下标从0开始,push是追加到末尾,循环变量作为下标读取的位置根本不存在对应数据)。 bar变量未声明报错:bar是for循环内部的局部变量,作用域仅在循环内部,循环外无法直接访问,自然无法绘制。
修复后可用代码
// This source code is subject to the terms of the Mozilla Public License 2.0 // © TD_DaFen //@version=5 indicator("DAF_Swing_Index", shorttitle= 'DAF_SwInd', overlay=false) // Input T = input.int(30000, title = 'Ratio de escala', minval = 1000, maxval = 150000) Shift = input.int(0, title = 'Desplazamiento horizontal', minval = 0, maxval = 100) var float SwingIndex = na // 直接用Pine内置历史引用,无需数组 if bar_index > 0 // 取当前K线和前一根K线的OHLC o = open o1 = open[1] c = close c1 = close[1] h = high l = low K = math.max(math.abs(h - c1), math.abs(l - c1)) TR = math.max(math.max(math.abs(h - c1), math.abs(l - c1)), math.abs(h - l)) ER = 0.0 if c1 > h ER := math.abs(h - c1) if c1 < l ER := math.abs(l - c1) SH1 = math.abs(c1 - o1) R = TR - 0.5 * ER + 0.25 * SH1 SI = 0.0 if R != 0 SI := 50 * ((c - c1) + 0.5 * (c - o1)) * (K / T) / R SwingIndex := SI // 原代码颜色透明度为10几乎不可见,可根据需要自行添加alpha参数 plot(SwingIndex, title = 'Swing Index', style = plot.style_line, color = color.rgb(193, 150, 51), offset=Shift)
优化说明
- 移除了冗余的数组存储逻辑,直接使用Pine Script原生的历史偏移语法
[1]获取前一根K线数据,大幅简化代码逻辑 - 增加了
bar_index > 0的判断,避免首根K线取前值触发负索引报错 - 修正了SwingIndex的赋值逻辑,每根K线直接计算对应数值,绘图正常
- 补充了横向偏移参数的生效逻辑
内容的提问来源于stack exchange,提问作者Clint Ramirez Branada
相关产品推荐
相关产品推荐

