如何在Pine Script v5中基于time/time_close返回的pdOT、pdCT绘制垂直线?
在Pine Script v5中基于日线时间戳绘制垂直线的解决方案
你遇到的问题核心是日线时间戳与当前图表周期不匹配,直接使用line.new()或plot()时,无法正确定位到低周期图表中对应的K线位置。以下是两种可行的实现方案:
方案1:使用line.new()动态绘制(推荐)
通过定位日线时间戳对应的低周期K线索引,结合barstate.islast避免重复创建线条:
//@version=5 indicator("昨日日线开/收盘垂直线", overlay=true) // 获取日线级别前一根K线的开盘时间(pdOT)和收盘时间(pdCT) [pdOT, pdCT] = request.security(syminfo.tickerid, 'D', [time[1], time_close[1]]) // 绘制昨日日线开盘线 if barstate.islast // 找到pdOT对应的当前周期K线索引 otBarOffset = ta.barssince(time == pdOT) if not na(otBarOffset) otLine = line.new( x1=bar_index - otBarOffset, y1=ta.lowest(low, 50), // 取最近50根K线的最低点作为线的下端 x2=bar_index - otBarOffset, y2=ta.highest(high, 50), // 取最近50根K线的最高点作为线的上端 color=color.new(color.green, 0), width=2, style=line.style_solid ) // 绘制昨日日线收盘线 ctBarOffset = ta.barssince(time == pdCT) if not na(ctBarOffset) ctLine = line.new( x1=bar_index - ctBarOffset, y1=ta.lowest(low, 50), x2=bar_index - ctBarOffset, y2=ta.highest(high, 50), color=color.new(color.red, 0), width=2, style=line.style_dashed )
关键说明:
ta.barssince(time == pdOT):计算从当前K线到匹配pdOT时间戳的K线的间隔数,从而定位到目标K线的索引。barstate.islast:仅在最后一根K线执行绘制逻辑,避免每根K线都创建新线条导致性能问题。- 自定义
y1和y2的取值范围,确保垂直线覆盖当前图表的主要价格区间。
方案2:使用vline()配合plot()绘制
通过ta.valuewhen()获取目标时间对应的K线索引,再用vline()生成垂直线:
//@version=5 indicator("昨日日线开/收盘垂直线", overlay=true) [pdOT, pdCT] = request.security(syminfo.tickerid, 'D', [time[1], time_close[1]]) // 获取目标时间对应的K线索引 otBarIndex = ta.valuewhen(time == pdOT, bar_index, 0) ctBarIndex = ta.valuewhen(time == pdCT, bar_index, 0) // 绘制垂直线 plot(vline(otBarIndex, "昨日开盘线", color=color.green, width=2)) plot(vline(ctBarIndex, "昨日收盘线", color=color.red, width=2, style=line.style_dashed))
关键说明:
ta.valuewhen(condition, value, occurrence):当time == pdOT条件满足时,返回对应的bar_index,0表示取最近一次匹配的结果。vline()专门用于绘制垂直线,直接传入K线索引即可定位。
常见问题排查
- 无线条显示:
- 确认当前图表周期低于日线(如1H、15M),若使用日线周期,pdOT为前一日开盘时间,pdCT为前一日收盘时间,需检查时间匹配逻辑。
- 验证
pdOT和pdCT的取值是否正确:可通过plotchar(pdOT, "pdOT", "•", location.belowbar)打印时间戳,确认是否存在有效数据。
- 线条重复创建:
- 方案1中使用
barstate.islast可避免重复创建;若需动态更新线条,可结合var关键字存储线条对象并在条件满足时更新位置。
- 方案1中使用
内容的提问来源于stack exchange,提问作者Lew2234
相关产品推荐
相关产品推荐

