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

Pine Script 5中能否获取PivotHigh的bar_index并动态绘制线段?

在Pine Script 5中基于ta.pivothigh动态绘制线段

你需要实现的是自动连接ta.pivothigh识别出的所有高点,替代原来静态指定bar_index的方式。核心思路是记录每一个有效 pivot high 的K线索引和价格,再用这些记录动态生成线段。

先看你的现有代码:

// PivotHigh Check
leftBars= input(4)
rightBars = input(4)
ph = ta.pivothigh(leftBars, rightBars)
plot(ph, style=plot.style_circles, linewidth=3, color=#ffffff, offset=-rightBars)

// Draw the line
upperLine = line.new(bar_index[10], high[10], bar_index[20], high[20], color=#ffffff, width = 2)

下面是实现动态连线的完整代码:

//@version=5
indicator("动态连接Pivot High", overlay=true)

leftBars= input.int(4, "左侧确认K线数")
rightBars = input.int(4, "右侧确认K线数")
ph = ta.pivothigh(leftBars, rightBars)

// 存储pivot high的K线索引和价格(var关键字保证数据跨K线保留)
var array<int> pivotBarIndexes = array.new_int()
var array<float> pivotHighPrices = array.new_float()

// 检测到新pivot high时,记录对应K线和价格
if not na(ph)
    // ta.pivothigh在右侧确认后触发,实际高点K线为当前bar减去rightBars
    targetBar = bar_index - rightBars
    array.push(pivotBarIndexes, targetBar)
    array.push(pivotHighPrices, ph)

// 删除旧线段避免画面堆积
var line prevLine = na
if not na(prevLine)
    line.delete(prevLine)

// 数组中至少有两个高点时,连接最新的两个点
if array.size(pivotBarIndexes) >= 2
    bar1 = array.get(pivotBarIndexes, array.size(pivotBarIndexes)-2)
    price1 = array.get(pivotHighPrices, array.size(pivotHighPrices)-2)
    bar2 = array.get(pivotBarIndexes, array.size(pivotBarIndexes)-1)
    price2 = array.get(pivotHighPrices, array.size(pivotHighPrices)-1)
    
    prevLine := line.new(bar1, price1, bar2, price2, color=#ffffff, width=2)

// 绘制pivot high标记
plot(ph, style=plot.style_circles, linewidth=3, color=#ffffff, offset=-rightBars)

关键逻辑说明:

  • 数组持久化存储:用var声明数组,确保数据不会在每根K线重新初始化,能持续记录所有识别到的pivot high。
  • 修正高点位置:ta.pivothigh是在右侧满足rightBars根K线后才返回高点价格,因此实际高点K线为bar_index - rightBars,和你plot时的offset=-rightBars对应。
  • 避免线段堆积:每次绘制新线段前删除旧线段,防止画面出现过多重复元素。
  • 动态连线逻辑:当数组积累至少两个高点时,自动连接最新的两个高点;如果需要连接所有历史连续高点,可遍历数组创建多段线段(注意控制数量避免性能问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:43:06