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

Pine Script v5数组与for循环结合时的索引越界问题求助

Pine Script v5数组与for循环结合时的索引越界问题求助

我最近在写一个基于分形识别支撑位的Pine Script指标,目前先只处理了低点分形(代码里用upFractal变量命名)的判断逻辑,但卡在了for循环和数组配合的部分,一直报这个错误:

Error on bar 6: In 'array.get() function. Index -1 is out of bounds, array size is 1.

我试了好多次调整循环的写法,但好像还是没搞懂Pine Script里数组和循环配合的逻辑,下面是我的完整代码,关键逻辑和疑问都写在注释里了,麻烦帮忙看看问题出在哪!

//@version=5
indicator('Williams Fractals', shorttitle='WICK.ED Fractals', overlay=true, max_bars_back = 100)

n = 2

var int[] barIndexes = array.new_int()

// 定义低点分形(变量名upFractal是暂时的命名)
upFractal = low[n - 1] > low[n] and low[n + 1] > low[n]

if upFractal
    array.push(barIndexes, bar_index)

// 自定义函数:处理分形K线索引
f_indexes(barIndexes) =>
    if array.size(barIndexes) > 0
        // 循环目的:遍历所有满足upFractal条件的K线索引
        for i = array.size(barIndexes) - 1 to 0 by 1 
            // 前一个分形K线的索引(从左到右看的前一个分形)
            PreviousBarIndex = array.get(barIndexes, i - 1) 
            // 当前分形K线的索引(从左到右看的后一个分形)
            CurrentBarIndex = array.get(barIndexes, i) 
            
            PreviousBarLow = low[PreviousBarIndex]
            CurrentBarClose = close[CurrentBarIndex]
            CurrentBarOpen = open[CurrentBarIndex]
            
            // 判断当前分形K线是阴线(开>收)
            if CurrentBarOpen > CurrentBarClose 
                // 前一个分形的低点 > 当前分形的收盘价,认为价格跌破了前一个分形支撑
                isPreviousBarOpenLesser = PreviousBarLow > CurrentBarClose 
                if isPreviousBarOpenLesser
                    // 满足条件的话打标记
                    label.new(bar_index[n], low, text="yes", yloc=yloc.belowbar) 
    
    // 尝试限制数组元素数量避免报错,但这个判断好像没意义
    if array.size(barIndexes) > -100 
        array.shift(barIndexes)

// 调用自定义函数
f_indexes(barIndexes)

我自己梳理的核心疑问:

  • 循环的目的是从后往前遍历分形K线的索引,依次对比前一个分形K线和当前分形K线的价格,但每次运行都会触发索引越界的错误,是不是循环的起始/结束条件写得有问题?
  • 后面那个array.shift的判断条件array.size(barIndexes) > -100是不是完全无效?因为数组的长度不可能是负数,我本来想限制数组最多存100个元素,是不是写法错了?

备注:内容来源于stack exchange,提问作者igor_ozon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 11:57:59