如何用PineScript计算252周期内最高K线至末K线的对应周期数
Pine Script:计算过去252周期内高点到当前的周期数
下面是满足需求的代码,会根据当前图表的时间框架(日线/周线/月线)自动返回对应单位的周期数:
//@version=5 indicator("高点距当前周期数", overlay=true, shorttitle="High Periods") // 设置回溯周期:过去252个周期 lookback_period = 252 // 获取指定周期内的最高价 recent_high = ta.highest(high, lookback_period) // 计算该最高价K线到当前K线的间隔周期数 bars_since_high = ta.barssince(high == recent_high) // 处理初始加载时的空值情况 periods_to_current = na(bars_since_high) ? 0 : bars_since_high // 在图表右上角显示结果,自动适配时间框架单位 var label result_label = label.new(bar_index, high, "", color=color.navy, textcolor=color.white, style=label.style_label_down) label.set_text(result_label, str.format("高点距当前: {0} {1}", periods_to_current, timeframe.period)) // 在数据窗口展示数值(可选) plotchar(periods_to_current, title="高点周期数", char=' ', location=location.bottom, display=display.data_window)
代码说明
- 核心逻辑:用
ta.highest()锁定过去252周期内的最高价,再通过ta.barssince()计算该高点K线到当前最后一根K线的间隔周期数,这个数值本身就对应时间框架的单位(日线=天数,周线=周数,月线=月数) - 空值处理:初始加载图表时可能出现空值,用
na()判断后默认返回0,避免显示异常 - 可视化:通过标签在图表右上角实时显示结果,
timeframe.period会自动获取当前时间框架的标识(比如"D"代表日线,"W"代表周线) - 数据窗口展示:可选的
plotchar可以让数值出现在数据窗口,方便和其他指标对比查看
内容的提问来源于stack exchange,提问作者NSW
相关产品推荐
相关产品推荐

