MACD金叉时25日内最高K线索引查找及指标报错求助
Pine Script 报错解决:
label.new() 索引值超出范围问题 问题场景
需求:当macdLine与signalLine金叉且macdLine < -4.1时,查找过去25日内最高K线的索引(非价格值),并基于该高点设置标记。
原代码:
//@version=5 indicator("top finder 25 days ago", overlay=true) [macdLine, signalLine, _] = ta.macd(close, 12, 26, 9) var int MyHighestIndex = na // when macdLine and signalLine cross and -4.1 if ta.crossover(macdLine, signalLine) and macdLine < -4.1 MyHighestIndex := ta.highestbars(high, 25) label.new(MyHighestIndex, high, "high", yloc = yloc.abovebar, style = label.style_arrowdown)
报错信息
Error on bar 11737: Bar index value of the 'x' argument (0.0000) in 'label.new()' is too far from the current bar index try to use 'time' instead.
问题原因
ta.highestbars()返回的是相对于当前K线的偏移值(比如返回-5代表当前K线往前数第5根是高点),并非绝对K线索引,直接传入label.new()的x参数会导致索引定位错误。- 全局作用域下的
label.new()会在每根K线执行,即使未触发金叉条件,也会尝试用初始值na创建标签,引发越界问题。
解决方法
- 用
time参数定位标签位置(替代K线索引,避免偏移误差),通过偏移量获取高点的时间戳和价格。 - 仅在触发金叉条件时执行标签创建逻辑,将
label.new()放入if代码块内。
修正后的代码
//@version=5 indicator("top finder 25 days ago", overlay=true) [macdLine, signalLine, _] = ta.macd(close, 12, 26, 9) // 触发金叉且macdLine < -4.1时执行 if ta.crossover(macdLine, signalLine) and macdLine < -4.1 // 获取过去25根K线内高点的相对偏移 highestOffset = ta.highestbars(high, 25) // 计算高点的绝对时间戳与价格 highestTime = time[math.abs(highestOffset)] highestPrice = high[math.abs(highestOffset)] // 在高点位置创建标签 label.new(highestTime, highestPrice, "High", yloc=yloc.abovebar, style=label.style_arrowdown, color=color.red)
补充说明
ta.highestbars()返回负数表示高点在当前K线之前,用math.abs()取偏移量后,通过[偏移量]索引获取对应K线的时间和价格。- 标签创建逻辑放在
if块内,仅满足条件时执行,避免无效计算和错误。
内容的提问来源于stack exchange,提问作者Dan Press
相关产品推荐
相关产品推荐

