Pine Script问题:最近亚洲时段高点绘制不准且重复显示
Pine Script代码问题排查:仅显示最近亚洲时段高点
问题描述
我需要实现跨K线绘制最近一期亚洲时段高点的功能,参考相关代码编写后遇到两个问题:
- 计算出的高点数值不准确
show_last=1参数未生效,仍会绘制多个时段的高点标签
原代码如下:
study("Sessions high and lows", overlay=true) // User adjustment inputs offset_val = input(title="Label Offset", type=input.integer, defval=10) // Asian High time_int_02 = input("2000-2359", "Assian High", input.session) in_time_int_02 = time(timeframe.period, time_int_02) var highe_02 = 0.0 var lowe_02 = 10e10 if in_time_int_02 if not in_time_int_02[1] highe_02 := high else highe_02 := max(high, highe_02) plot(not in_time_int_02 ? highe_02 : na, title="Asian High", color=color.purple, linewidth=2, style=plot.style_linebr) plotshape(not in_time_int_02 ? highe_02 : na, style=shape.labelup, location=location.absolute, color=color.purple, textcolor=color.white, show_last=1, text="Asian High", offset = offset_val, transp=20, title="Asian High")
问题原因分析
1. 高点数值不准确
- 初始化
highe_02为固定值0.0,若标的价格低于0(如部分加密货币)会直接出错 - 未处理跨时段数据重置逻辑:旧时段的高点会被一直保留,无法确保显示的是最新一期亚洲时段的高点
2. show_last=1未生效
plotshape的show_last=1控制的是显示最后N个符合条件的形状,但原代码中not in_time_int_02会让所有非亚洲时段的K线都触发标签绘制,符合条件的K线数量过多,导致show_last=1无法只显示一个标签。
修正后的代码
//@version=5 indicator("Sessions High and Lows", overlay=true) // 用户可调节参数 offset_val = input.int(title="标签偏移量", defval=10) asian_session = input.session("2000-2359", title="亚洲时段") // 判断当前K线是否处于亚洲时段 in_asian = time(timeframe.period, asian_session) // 用数组存储最新亚洲时段的高点,仅保留最近一期数据 var float[] asian_highs = array.new_float() // 处理时段切换与高点更新 if in_asian // 刚进入新的亚洲时段:清空历史数据,初始化当前K线高点 if not in_asian[1] array.clear(asian_highs) array.push(asian_highs, high) else // 时段内持续更新高点,保留最大值 current_high = array.get(asian_highs, 0) array.set(asian_highs, 0, math.max(high, current_high)) // 获取最新的亚洲时段高点 latest_asian_high = array.size(asian_highs) > 0 ? array.get(asian_highs, 0) : na // 绘制跨K线的高点线:仅在亚洲时段结束后显示最新高点 plot(not in_asian ? latest_asian_high : na, title="亚洲时段高点", color=color.purple, linewidth=2, style=plot.style_linebr) // 绘制标签:仅在亚洲时段结束的第一根K线触发,配合show_last=1确保只显示一个 plotshape(not in_asian and in_asian[1] ? latest_asian_high : na, style=shape.labelup, location=location.absolute, color=color.purple, textcolor=color.white, text="亚洲高点", offset=offset_val, transp=20, title="亚洲高点标签", show_last=1)
修正说明
- 升级为Pine Script v5语法(若需兼容v4可调整变量声明方式)
- 使用数组存储高点,确保仅保留最新一期亚洲时段的数据,避免历史数据干扰
- 精准判断时段开始与结束节点,确保高点计算准确
- 标签仅在亚洲时段结束后的第一根K线绘制,配合
show_last=1实现只显示一个标签的需求 - 移除固定初始值,改用动态初始化,适配所有价格区间的标的
内容的提问来源于stack exchange,提问作者Snak3d0c
相关产品推荐
相关产品推荐

