Pine Script使用var初始化数组后array.get报下标越界错误求解
问题根因
- 未做数组空值校验:当没有符合条件的亏损订单生成时,
lossPath和lossPercent两个数组始终是空状态,直接调用array.min()会返回na,后续array.indexof()查找不到对应值就会返回-1,最终调用array.get()时直接触发索引越界报错。 - 计算逻辑执行时机错误:查找最差路径的代码当前是每根K线都会执行,在行情初期还没有亏损订单生成时,空数组调用相关方法必然会触发报错,不需要全量K线执行该逻辑。
修复方案
// 原数组初始化逻辑保留 var lossPath = array.new_string(0) var lossPercent = array.new_float(0) var table worstPerfTable = table.new(position.top_right, 2, 2, border_width=1) // 新增右上角2列2行表格存放统计数据 if (change(entryPrice) and color_WINLOSS == color.new(color.red, 0)) array.push(lossPath, path[1]) percent = isLong ? (entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : isShort ? -(entryPrice[0] - entryPrice[1]) / entryPrice[1] * 100 : na if not na(percent) // 新增校验:仅有效收益率存入数组,避免脏数据影响后续计算 array.push(lossPercent, percent) // 新增默认值兜底,无亏损记录时不会出现空值报错 var string worstPathName = "无亏损记录" var string worstLoss = "0%" if barstate.islast // 仅在全量K线计算完成、且数组有有效值时计算最差路径 if array.size(lossPercent) > 0 minLoss = array.min(lossPercent) worstPathIndex = array.indexof(lossPercent, minLoss) // 二次校验索引有效性,避免越界 if worstPathIndex >= 0 and worstPathIndex < array.size(lossPath) worstPathName = array.get(lossPath, worstPathIndex) worstLoss = tostring(minLoss / 100, format.percent) // 按需求填充右上角表格 table.cell(worstPerfTable, 0, 0, "最差亏损路径") table.cell(worstPerfTable, 1, 0, "最大亏损幅度") table.cell(worstPerfTable, 0, 1, worstPathName) table.cell(worstPerfTable, 1, 1, worstLoss) // 原调试标签逻辑保留 label.new(bar_index, high, "Loss Path: " + tostring(lossPath) + "\nLoss Percent: " + tostring(lossPercent) + "\nArray Size: " + tostring(array.size(lossPath)), style=label.style_label_down) // 修复plot逻辑:数组非空时才取值,否则返回na不绘制,避免越界 plot(array.size(lossPercent) > 0 ? array.get(lossPercent, 0) : na, title="首笔亏损幅度")
核心修改说明
- 所有数组操作前置非空校验,从根源避免空数组调用方法返回无效索引的问题
- 新增收益率有效性校验,避免na值存入数组导致计算异常
- 最差路径计算逻辑挪到
barstate.islast判断内,仅在全量K线计算完成后执行一次,减少无效计算同时避免前期无数据时报错 - 新增无亏损场景的默认值兜底,不会出现空值报错
- 新增需求要求的右上角表格,按对应位置填充最差路径和最大亏损值
- plot逻辑新增空值兜底,数组为空时返回na不触发越界报错
内容的提问来源于stack exchange,提问作者Hugo
相关产品推荐
相关产品推荐

