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

如何在TradingView中计算当前K线高点高于此前多少根K线?

在TradingView中计算当前K线高点的新高距离N值

要计算当前K线高点高于此前多少根K线的高点(即N值,当当前为最近N根K线的新高时),可以结合ta.valuewhen或ta.barssince函数实现,以下是具体的Pine Script代码方案及说明:

核心思路

找到上一次出现比当前高点更高的K线位置,计算当前K线与该位置的间隔数——这个间隔数就是N(中间所有K线的高点都低于当前高点)。如果在max_bars_back范围内没有找到更高的高点,说明当前是该范围内的历史新高,N值即为max_bars_back。

代码实现(两种方式)

方式一:使用ta.valuewhen

//@version=5
indicator("新高距离计算", overlay=true)
max_bars_back = 5000

// 获取当前K线高点
current_high = high

// 找到最近一次高点大于当前高点的K线索引
prev_higher_high_idx = ta.valuewhen(high > current_high, bar_index, 0)

// 计算N值:无历史更高点则返回max_bars_back,否则返回间隔K线数
n_value = na(prev_higher_high_idx) ? max_bars_back : bar_index - prev_higher_high_idx

// 仅在当前为新高时显示N值
is_new_high = ta.highest(high, max_bars_back) == current_high
if is_new_high
    label.new(bar_index, high + ta.atr(1)*0.1, str.tostring(n_value), 
              color=color.new(color.green, 0), textcolor=color.white, size=size.small)

方式二:使用ta.barssince

//@version=5
indicator("新高距离计算(barssince版)", overlay=true)
max_bars_back = 5000

current_high = high
// 定义"高点大于当前高点"的条件
prev_higher_condition = high > current_high

// 计算距离最近一次满足条件的K线数
bars_since_prev_higher = ta.barssince(prev_higher_condition)

// 确定N值
n_value = na(bars_since_prev_higher) ? max_bars_back : bars_since_prev_higher

// 新高时显示N值
is_new_high = ta.highest(high, max_bars_back) == current_high
if is_new_high
    label.new(bar_index, low - ta.atr(1)*0.1, "N: " + str.tostring(n_value), 
              color=color.new(color.red, 0), textcolor=color.white, size=size.small)

关键说明

  • ta.valuewhen(condition, value, occurrence):在历史K线中找到第occurrence次满足condition的位置,返回对应的value(这里返回bar_index即K线索引)。
  • ta.barssince(condition):返回从当前K线到最近一次满足condition的K线之间的间隔数,无满足条件的K线时返回na。
  • is_new_high判断:通过ta.highest(high, max_bars_back) == current_high确认当前是否为max_bars_back范围内的新高,避免在非新高时显示无效的N值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:09:50