如何从request.security_lower_tf函数返回的低时间框架数组中获取特定值?1小时K线场景下索引越界问题求助
解决Pine Script中request.security_lower_tf数组索引越界的问题
我来帮你排查这个问题,其实核心原因是**request.security_lower_tf返回的数组长度并不是固定12个元素**,直接硬写索引2就很容易触发越界错误,具体原因和解决方法如下:
为什么会出现索引越界?
当你在1小时K线图上调用
request.security_lower_tf获取5分钟数据时,返回的数组长度取决于当前1小时K线的完成状态:- 如果是已经收盘的1小时K线,数组会有完整的12个5分钟K线数据;
- 如果是正在运行的实时1小时K线(比如当前时间是3:07),此时只生成了2根5分钟K线(3:00、3:05),数组长度只有2,这时候去取索引
2自然就会报"out of index"; - 另外在非交易时段(比如美股盘前/盘后,或者休市日),可能根本没有足够的5分钟K线生成,数组长度会更短。
还有个小细节:你认为索引
2对应3:15的K线可能有误——1小时内的5分钟K线顺序是:- 索引0 → 3:00-3:05
- 索引1 → 3:05-3:10
- 索引2 → 3:10-3:15
- 索引3 → 3:15-3:20
如果你要的是3:15的收盘价,应该取索引3才对(前提是该K线已经生成)。
修复代码的步骤
1. 先判断数组长度,再安全取值
在获取数组元素前,先通过array.size()检查数组长度是否足够,避免越界:
//@version=5 indicator("Get 5min Close at 3:15", overlay=true) // 获取5分钟收盘价数组 arrClose = request.security_lower_tf(syminfo.tickerid, "5", close) // 安全获取3:15对应的收盘价(索引3) var float targetClose = na if array.size(arrClose) >= 4 // 要取索引3,数组长度至少为4 targetClose = array.get(arrClose, 3) // 输出结果 plot(targetClose, color=color.new(color.blue, 0), linewidth=2)
2. 可选:通过时间条件精准定位目标K线
如果你担心索引对应关系出错,可以直接通过时间过滤来获取3:15的收盘价,这种方式更可靠:
//@version=5 indicator("Get 5min Close at 3:15", overlay=true) // 在5分钟时间框架下,筛选出时间为3:15的K线收盘价 targetClose = request.security(syminfo.tickerid, "5", close, barmerge.gaps_on, barmerge.lookahead_on) isTargetBar = hour == 3 and minute == 15 // 只保留目标时间的收盘价 var float filteredClose = na if isTargetBar filteredClose := targetClose plot(filteredClose, color=color.new(color.red, 0), linewidth=2)
这种方法不需要依赖数组索引,直接通过时间条件锁定目标K线,能避免索引对应错误的问题。
内容的提问来源于stack exchange,提问作者Punya
相关产品推荐
相关产品推荐

