Pine Script短期高点标记位置偏移问题求助及代码优化建议
Pine Script 短期高点标记位置修正方案
问题根源
你的代码中,ta.highest(high,3) == high[1]的判断是在当前K线走完后触发的,此时给highestHigh赋值的是前一根K线的高点,但plotshape默认会在当前K线显示该值,导致标记位置与实际高点出现的K线不符。
解决思路
要将标记精准放在高点出现的K线,核心是:
- 记录高点对应的K线索引(
bar_index) - 通过
plotshape的x参数,指定标记显示的目标K线位置
优化后代码(标记最近一个高点)
//@version=5 indicator("短期高点标记", overlay=true) // 用var变量存储高点价格和对应K线索引,避免每次K线重置 var float targetHigh = na var int targetBarIndex = na // 当前K线走完后,确认前一根是3周期内的高点 if barstate.isconfirmed and ta.highest(high, 3) == high[1] targetHigh := high[1] targetBarIndex := bar_index[1] else // 不满足条件时清空变量,避免旧标记残留 targetHigh := na targetBarIndex := na // 指定x参数为目标K线索引,将标记显示在高点出现的K线上 plotshape(targetHigh, shape.circle, color=color.green, size=size.small, x=targetBarIndex)
扩展:标记所有历史高点
如果需要保留并标记所有符合条件的历史高点,可以用数组存储所有高点的信息,再遍历绘制:
//@version=5 indicator("所有短期高点标记", overlay=true) // 用数组存储所有高点的价格和对应的K线索引 var float[] highPrices = array.new_float() var int[] highBarIndexes = array.new_int() // 当前K线走完后确认前一根是3周期高点 if barstate.isconfirmed and ta.highest(high, 3) == high[1] array.push(highPrices, high[1]) array.push(highBarIndexes, bar_index[1]) // 遍历数组,绘制所有历史高点标记 for i = 0 to array.size(highPrices) - 1 plotshape(array.get(highPrices, i), shape.circle, color=color.green, size=size.small, x=array.get(highBarIndexes, i))
内容的提问来源于stack exchange,提问作者Kristaps11
相关产品推荐
相关产品推荐

