如何获取并修改函数的bar_index值(实现1单位偏移)
关于获取并修改函数对应bar_index的问题解答
在Pine Script中,针对你的问题可以这样处理:
核心结论
可以获取指定函数(如request.security)对应时间框架的bar_index,并对其进行偏移计算,但无法修改系统内置的bar_index本身(它是只读变量)。
具体实现方式
获取目标时间框架的bar_index
直接通过request.security请求目标时间框架的bar_index字段,就能拿到对应标的/时间框架下的K线索引:targetBarIndex = request.security(symbol, timeframe.period, bar_index)对bar_index进行1单位偏移
要得到偏移1单位的索引,直接在请求时对bar_index做减法即可,或者请求目标时间框架下前一根K线的索引:// 方式1:直接计算偏移 offsetBarIndex = request.security(symbol, timeframe.period, bar_index - 1) // 方式2:请求目标时间框架前一根K线的索引(和方式1效果一致,仅当bar_index连续时) offsetBarIndex_v2 = request.security(symbol, timeframe.period, bar_index[1])针对你的示例场景
如果你需要同时获取request.security(symbol, timeframe.period, close[1])对应的偏移后bar_index,可以一次性请求多个字段:// 同时获取目标时间框架前一根K线的收盘价和对应的bar_index [targetClose, targetOffsetBarIndex] = request.security(symbol, timeframe.period, [close[1], bar_index[1]])
注意事项
request.security中的偏移(如close[1])是相对于目标时间框架的当前K线,而非主图时间框架。- 确保偏移后的索引对应的K线存在,避免因历史最早K线导致的无效数据问题。
内容的提问来源于stack exchange,提问作者Kira94
相关产品推荐
相关产品推荐

