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

如何基于两个独立枢轴点创建箱体?以枢轴高点与前枢轴低点为例

基于独立枢轴点创建箱体的实现方案(以Pine Script为例)

核心思路

以交易场景常用的Pine Script为例,我们需要先识别出枢轴高点/低点,再将最新的枢轴高点与前一个未配对的枢轴低点关联,以此绘制箱体的上下边界,同时确定箱体的时间范围(从枢轴低点出现的K线到枢轴高点出现的K线)。

步骤1:定义枢轴点识别规则

首先用内置函数或自定义条件识别枢轴点:

  • 枢轴高点:当前K线的高点高于前后N根K线的高点,用pivotHigh(high, leftbars, rightbars)实现
  • 枢轴低点:当前K线的低点低于前后N根K线的低点,用pivotLow(low, leftbars, rightbars)实现

示例代码片段:

// 定义枢轴点的前后K线数量
leftBars = 2
rightBars = 2

// 识别枢轴高点和低点
isPivotHigh = pivotHigh(high, leftBars, rightBars)
isPivotLow = pivotLow(low, leftBars, rightBars)

// 获取枢轴点的价格
pivotHighPrice = valuewhen(isPivotHigh, high, 0)
pivotLowPrice = valuewhen(isPivotLow, low, 0)

步骤2:跟踪并配对枢轴点

用var变量存储最近的未配对枢轴低点信息,当新的枢轴高点出现时,完成配对并绘制箱体:

// 存储最近的枢轴低点价格和K线索引
var float lastPivotLowPrice = na
var int lastPivotLowBarIndex = na

// 当出现新的枢轴低点时,更新存储的信息
if isPivotLow
    lastPivotLowPrice := pivotLowPrice
    lastPivotLowBarIndex := bar_index

// 当出现新的枢轴高点,且存在未配对的枢轴低点时,绘制箱体
if isPivotHigh and not na(lastPivotLowPrice)
    // 创建箱体:左边界为枢轴低点的K线,右边界为当前枢轴高点的K线
    box.new(
        left = lastPivotLowBarIndex,
        top = pivotHighPrice,
        right = bar_index,
        bottom = lastPivotLowPrice,
        border_color = color.blue,
        fill_color = color.new(color.blue, 90),
        border_width = 1
    )

步骤3:优化逻辑(可选)

  • 如果需要避免重复配对同一个枢轴低点,可以在绘制箱体后重置lastPivotLowPrice为na
  • 若要支持连续枢轴高点更新箱体上沿,可以修改逻辑:当新的枢轴高点出现且未出现新的枢轴低点时,更新现有箱体的上沿和右边界

完整示例代码

//@version=5
indicator("基于独立枢轴点的箱体", overlay=true)

leftBars = input.int(2, "枢轴点左侧K线数")
rightBars = input.int(2, "枢轴点右侧K线数")

isPivotHigh = pivotHigh(high, leftBars, rightBars)
isPivotLow = pivotLow(low, leftBars, rightBars)

pivotHighPrice = valuewhen(isPivotHigh, high, 0)
pivotLowPrice = valuewhen(isPivotLow, low, 0)

var float lastPivotLowPrice = na
var int lastPivotLowBarIndex = na
var box currentBox = na

if isPivotLow
    lastPivotLowPrice := pivotLowPrice
    lastPivotLowBarIndex := bar_index
    // 出现新的枢轴低点时,结束上一个箱体
    if not na(currentBox)
        box.set_right(currentBox, bar_index - 1)
        currentBox := na

if isPivotHigh and not na(lastPivotLowPrice)
    if na(currentBox)
        // 创建新箱体
        currentBox := box.new(
            left = lastPivotLowBarIndex,
            top = pivotHighPrice,
            right = bar_index,
            bottom = lastPivotLowPrice,
            border_color = color.blue,
            fill_color = color.new(color.blue, 90),
            border_width = 1
        )
    else
        // 更新现有箱体的上沿和右边界
        box.set_top(currentBox, pivotHighPrice)
        box.set_right(currentBox, bar_index)

关键说明

  • var变量用于跨K线保存状态,确保不会在每根K线重置数据
  • box.new()和box.set_*()函数用于创建和更新箱体的属性
  • 可通过调整leftBars和rightBars参数,改变枢轴点的灵敏度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:20:13