如何用Pine Script V5在TradingView绘制最近50K线的4条动态水平线?
TradingView动态绘制最近N根K线高低水平线的解决方案
问题核心
hline()函数仅支持传入固定数值,而ta.highest()/ta.lowest()返回的是随K线更新的动态序列值,无法直接对接。我们可以用plot()函数替代,它支持动态序列值,能实现跨周期的动态水平线效果。
完整实现代码
//@version=5 indicator("最近N根K线高低水平线", overlay=true, shorttitle="高低水平线") // 可自定义的回溯K线数量,默认50根 lookback = input.int(50, minval=1, title="回溯K线数量", tooltip="设置要计算的最近K线根数") // 计算最近N根K线的四个目标值 recent_high = ta.highest(high, lookback) recent_high_close = ta.highest(close, lookback) recent_low = ta.lowest(low, lookback) recent_low_close = ta.lowest(close, lookback) // 获取最后一根K线对应的目标值,确保水平线贯穿整个图表 last_recent_high = ta.valuewhen(barstate.islast, recent_high, 0) last_recent_high_close = ta.valuewhen(barstate.islast, recent_high_close, 0) last_recent_low = ta.valuewhen(barstate.islast, recent_low, 0) last_recent_low_close = ta.valuewhen(barstate.islast, recent_low_close, 0) // 绘制四条动态水平线 plot(last_recent_high, title="最近N根K线最高值", color=color.new(color.green, 0), linewidth=1, style=plot.style_line) plot(last_recent_high_close, title="最近N根K线最高收盘价", color=color.new(color.black, 0), linewidth=1, style=plot.style_line) plot(last_recent_low, title="最近N根K线最低值", color=color.new(color.red, 0), linewidth=1, style=plot.style_line) plot(last_recent_low_close, title="最近N根K线最低收盘价", color=color.new(color.black, 0), linewidth=1, style=plot.style_line)
关键说明
- 跨周期适配:代码会自动识别当前图表的时间周期(月/周/日/小时/分钟等),计算对应周期下最近N根K线的数值。
- 动态更新:每当有新K线生成时,四个水平线的数值会自动重新计算并更新。
- 自定义调整:可通过输入框修改回溯的K线数量,也可自行调整线条颜色、线宽等样式参数。
内容的提问来源于stack exchange,提问作者user293473
相关产品推荐
相关产品推荐

