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

使用request.security_lower_tf函数获取数据遇数组越界问题求助

Pine Script: request.security_lower_tf 数组越界问题解析与解决

问题概述

使用request.security_lower_tf从1分钟周期获取更低周期数据时,触发数组越界错误:

In 'array.get()' function. Index 1 is out of bounds. array size is 0.

测试代码:

plot(array.get(request.security_lower_tf(syminfo.tickerid, '1', close), 1))

但调用array.size()时,当前周期为1小时返回60、4小时返回240,结果正常:

plot(array.size(request.security_lower_tf(syminfo.tickerid, '1', close)))

当当前周期为1分钟时,再次触发错误:

In 'array.get()' function. Index 1 is out of bounds. array size is 1.

原因分析

  1. 周期匹配逻辑:request.security_lower_tf仅返回当前大周期内包含的所有低周期K线数据数组。当当前周期 > 目标低周期时(如1小时→1分钟),数组大小等于大周期包含的低周期K线数量(1小时=60个1分钟K线);但当当前周期 = 目标周期时,函数仅返回当前K线的单个值组成的数组(大小为1),此时索引1超出范围。
  2. 数据加载阶段:脚本初始化时,低周期数据可能未完全加载,导致数组为空(size=0),此时访问任何索引都会报错。

解决方法

1. 先校验数组大小再取值

在访问数组元素前,先判断数组长度是否满足索引要求,避免越界:

lower_tf_data = request.security_lower_tf(syminfo.tickerid, '1', close)
// 仅当数组大小大于1时,才访问索引1
plot(array.size(lower_tf_data) > 1 ? array.get(lower_tf_data, 1) : na)

2. 优先访问最新低周期数据(索引0)

数组的索引0对应最新的低周期K线数据,这是更安全的取值方式:

lower_tf_data = request.security_lower_tf(syminfo.tickerid, '1', close)
// 确保数组非空时取值,否则返回na
plot(array.size(lower_tf_data) > 0 ? array.get(lower_tf_data, 0) : na)

3. 规避周期相等的场景

提前判断当前周期是否等于目标低周期,若相等则直接使用当前周期数据:

// 判断当前是否为1分钟周期
is_current_1min = timeframe.multiplier == 1 and timeframe.period == "m"
if not is_current_1min
    lower_tf_data = request.security_lower_tf(syminfo.tickerid, '1', close)
    plot(array.size(lower_tf_data) > 1 ? array.get(lower_tf_data, 1) : na)
else
    plot(close) // 当前周期就是目标周期,直接用当前close

内容的提问来源于stack exchange,提问作者CrazyLayKer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:36:24