You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Pine Script计算最近3个pivot high至今分别间隔bar数的实现方法

问题核心原因

  • pivothigh()返回的是满足条件的高点数值,不满足时返回na,你没有将其转换为布尔触发信号就直接传入valuewhen,会导致匹配逻辑异常
  • 用高点数值相等作为匹配条件存在漏洞:出现两个数值相同的pivot high时会匹配错误
  • 没有考虑pivot high的确认滞后性:pivothigh(high, left, right)会在pivot点出现后第right根bar才给出确认信号,直接计算间隔会少算right根bar

修正后可运行代码

//@version=5
indicator("最近3次Pivot High间隔Bar数", overlay=false)

left = input(15, "left")
right = input(15, "right")

// 生成pivot high确认的布尔信号
is_pivot_high = not na(pivothigh(high, left, right))

// 直接通过bar索引匹配,避免数值重复问题
// 0=最近一次pivot high,1=上一次,2=上上次
bh3 = ta.barssince(ta.valuewhen(is_pivot_high, bar_index, 0) == bar_index) + right
bh2 = ta.barssince(ta.valuewhen(is_pivot_high, bar_index, 1) == bar_index) + right
bh1 = ta.barssince(ta.valuewhen(is_pivot_high, bar_index, 2) == bar_index) + right

plot(bh1, "bars since high 1", color=color.new(color.red, 0))
plot(bh2, "bars since high 2", color=color.new(color.yellow, 0))
plot(bh3, "bars since high 3", color=color.new(color.green, 0))

代码说明

  • 如果你需要统计的是从pivot high确认信号发出开始的间隔bar数,删除代码中最后的+ right即可
  • 当前K线数量不足形成3次pivot high时,返回值为na属于正常情况,可通过na(bh1) ? 0 : bh1的逻辑替换为默认值

内容的提问来源于stack exchange,提问作者Andrew Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 03:15:03