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

如何获取最近20根K线中最高与最低K线的时间以绘制箱体

获取最近20根K线中高低点对应的时间并绘制箱体

以TradingView的Pine Script为例,你可以通过以下步骤实现需求:

1. 获取高低点的K线偏移量

使用ta.highestbars()和ta.lowestbars()函数,它们会返回当前K线到目标高低点的偏移数(负数表示过去的K线,比如返回-3代表3根K线前是高点)。指定参数length=20即可限定在最近20根K线范围内:

// 最近20根K线的高点偏移量
highBarOffset = ta.highestbars(high, 20)
// 最近20根K线的低点偏移量
lowBarOffset = ta.lowestbars(low, 20)

2. 获取对应K线的时间

通过time[]数组,结合偏移量就能拿到高低点K线的时间戳:

// 高点K线的时间
highBarTime = time[math.abs(highBarOffset)]
// 低点K线的时间
lowBarTime = time[math.abs(lowBarOffset)]

注:用math.abs()转换为正数索引,因为偏移量是负数,数组索引需要从当前K线往前数。

3. 获取箱体的上下边界

用你提到的ta.highest()和ta.lowest()获取高低价:

boxTop = ta.highest(high, 20)
boxBottom = ta.lowest(low, 20)

4. 绘制完整箱体

使用line.new()函数绘制四个边,需要确定箱体的左右边界(取高低点时间的最小值和最大值作为箱体的左右端):

// 确定箱体的左右时间边界
boxLeftTime = math.min(highBarTime, lowBarTime)
boxRightTime = math.max(highBarTime, lowBarTime)

// 绘制上边
line.new(boxLeftTime, boxTop, boxRightTime, boxTop, color=color.red, width=2)
// 绘制下边
line.new(boxLeftTime, boxBottom, boxRightTime, boxBottom, color=color.green, width=2)
// 绘制左边
line.new(boxLeftTime, boxTop, boxLeftTime, boxBottom, color=color.blue, width=2)
// 绘制右边
line.new(boxRightTime, boxTop, boxRightTime, boxBottom, color=color.blue, width=2)

注意事项

  • 如果最近20根K线中,高点和低点出现在同一根K线上,箱体会变成一条竖线,可添加判断逻辑避免这种情况。
  • 若要实时更新箱体,需添加var关键字声明线条变量,并在每根K线更新线条位置,避免重复绘制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:18:26