Pine Script中检查两根K线间蜡烛条件及历史限制报错解决
Pine Script 历史蜡烛访问限制问题解决办法
你通过a_index:= bar_index记录某根K线的索引,想要检查该K线到当前K线之间所有蜡烛是否满足close[i] > open[i]的条件,但不管有没有加范围限制,都触发了蜡烛历史限制错误。
问题原因
Pine Script对脚本能访问的历史K线数量有默认限制,即使你加了bar_index - a_index <= maxHistory的判断,当a_index指向的K线超出允许的历史范围时,脚本会先尝试访问循环内的close[i],直接触发错误——条件判断根本没机会生效。
解决办法
方案1:用内置函数替代循环(推荐,效率更高)
Pine Script提供了很多内置函数可以替代手动循环,避免触发历史访问限制。比如用ta.barssince()配合ta.highest()判断区间内是否存在阳线:
//@version=5 indicator("检查区间内蜡烛", overlay=true) maxHistory = 100 // 自定义最大允许的历史范围 // 示例:当收盘价上穿20日均线时记录a_index var int a_index = na if ta.crossover(close, ta.sma(close, 20)) a_index := bar_index // 判断a_index到当前K线之间是否存在阳线 has_bull_candle = not na(a_index) and ta.barssince(bar_index == a_index) >= 0 and ta.highest(close > open ? 1 : 0, ta.barssince(bar_index == a_index) + 1) == 1 plotshape(has_bull_candle, title="存在阳线", location=location.belowbar, color=color.green, style=shape.triangleup)
方案2:提前限制a_index的历史范围
在记录a_index时就强制限制它不能早于bar_index - maxHistory,确保后续循环访问的K线始终在允许范围内:
//@version=5 indicator("带范围限制的蜡烛检查", overlay=true) maxHistory = 100 var int a_index = na if ta.crossover(close, ta.sma(close, 20)) // 强制让a_index不超过maxHistory的历史范围 a_index := math.max(bar_index - maxHistory, bar_index) var bool allssma = false if not na(a_index) allssma := false // 循环范围被限制在maxHistory内,不会触发历史限制错误 for i = a_index to bar_index if close[i] > open[i] allssma := true plotshape(allssma, title="存在阳线", location=location.belowbar, color=color.green, style=shape.triangleup)
为什么之前的代码会出错
- 第一个代码块没有任何范围限制,当
a_index指向太久远的K线时,直接触发历史访问限制 - 第二个代码块的
if (bar_index - a_index <= maxHistory)判断是在循环之后生效的——Pine Script会先尝试访问循环内的close[i],此时已经触发了历史限制,条件判断根本没机会执行
内容的提问来源于stack exchange,提问作者Hedi
相关产品推荐
相关产品推荐

