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

如何为TradingView枢轴高低点Pine Script指标添加中点绘制功能?

高低枢轴中点标记实现方案

核心实现逻辑

  • 保留原有代码的高低枢轴识别、标签绘制逻辑,不改动原有指标的展示效果
  • 重构枢轴识别函数,增加返回值:将已确认的枢轴对应的K线横坐标、价格纵坐标传递到全局作用域
  • 用var修饰的持久化变量存储最近一次识别到的有效高枢轴、低枢轴坐标,避免每根K线运行时被重置
  • 新增消费标记机制,避免同一组高低枢轴被反复计算中点
  • 当同时存在未消费的高低枢轴时,分别计算两个枢轴横坐标、纵坐标的算术平均值,得到几何中点坐标后在图表上绘制标记

完整代码

//@version=5
indicator("Pivot Points High Low with Midpoint", shorttitle="Pivots HL + Mid", overlay=true)
lenH = input.int(title="Length High", defval=10, minval=1)
lenL = input.int(title="Length Low", defval=10, minval=1)

// 持久化存储最近的高低枢轴坐标
var float last_h_pivot_x = na
var float last_h_pivot_y = na
var float last_l_pivot_x = na
var float last_l_pivot_y = na
// 枢轴消费标记,避免重复计算
var bool h_pivot_consumed = false
var bool l_pivot_consumed = false

// 枢轴识别函数,返回识别到的枢轴坐标
f_detect_pivot(src, len, is_high) =>
    is_valid = true
    pivot_price = nz(src[len])
    // 校验枢轴左侧K线
    for i = 0 to len - 1
        if is_high and src[i] > pivot_price
            is_valid := false
        if not is_high and src[i] < pivot_price
            is_valid := false
    // 校验枢轴右侧K线
    for i = len + 1 to 2 * len
        if is_high and src[i] >= pivot_price
            is_valid := false
        if not is_high and src[i] <= pivot_price
            is_valid := false
    // 识别到有效枢轴时绘制原有标签,返回坐标
    if is_valid
        pivot_x = bar_index[len]
        if is_high
            label.new(pivot_x, pivot_price, str.tostring(pivot_price), style=label.style_labeldown, yloc=yloc.abovebar, color=color.lime, textcolor=color.white)
        else
            label.new(pivot_x, pivot_price, str.tostring(pivot_price), style=label.style_labelup, yloc=yloc.belowbar, color=color.red, textcolor=color.white)
        [pivot_x, pivot_price]
    else
        [na, na]

// 执行高低枢轴检测
[detect_h_x, detect_h_y] = f_detect_pivot(high, lenH, true)
[detect_l_x, detect_l_y] = f_detect_pivot(low, lenL, false)

// 更新持久化存储的枢轴位置
if not na(detect_h_x)
    last_h_pivot_x := detect_h_x
    last_h_pivot_y := detect_h_y
    h_pivot_consumed := false
if not na(detect_l_x)
    last_l_pivot_x := detect_l_x
    last_l_pivot_y := detect_l_y
    l_pivot_consumed := false

// 计算并绘制中点标记
if not na(last_h_pivot_x) and not na(last_l_pivot_x) and not h_pivot_consumed and not l_pivot_consumed
    mid_point_x = (last_h_pivot_x + last_l_pivot_x) / 2
    mid_point_y = (last_h_pivot_y + last_l_pivot_y) / 2
    label.new(mid_point_x, mid_point_y, "", style=label.style_circle, color=color.orange, size=size.tiny)
    // 标记对应枢轴已被使用
    h_pivot_consumed := true
    l_pivot_consumed := true

效果说明

  • 原有绿色向下标签的高枢轴、红色向上标签的低枢轴展示逻辑与原代码完全一致
  • 每一组相邻的高低枢轴对应的几何中心位置,会生成一个橙色小圆点标记作为中点
  • 同一组高低枢轴只会计算一次中点,不会出现重复绘制的冗余标记

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 13:24:04