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

如何仅在最近10根K线上显示20周期最高高点标签?

问题分析与解决办法

原代码的核心问题在于两处逻辑错误:

  1. Lookback = bar_index - 10 放在全局作用域时,每根K线的bar_index都会变化,导致bar_index > Lookback等价于bar_index > bar_index - 10,这个条件永远成立,起不到过滤最近10根K线的作用。
  2. 仅依赖barstate.islast会让代码只在最后一根K线执行,无法遍历最近10根K线去判断哪些是20周期高点并添加标签。

修正后的代码

//@version=5
indicator("20周期高点标签(仅最近10根K线显示)", overlay=true)

highestHigh = ta.highest(high, 20)
is_high = high >= highestHigh

// 遍历最近10根K线,判断是否为20周期高点并添加标签
if barstate.islast
    for i = 0 to 9
        target_bar = bar_index - i
        if target_bar >= 0 and ta.valuewhen(bar_index == target_bar, is_high, 0)
            label.new(target_bar, ta.valuewhen(bar_index == target_bar, high, 0), 
                     "HH: " + str.tostring(ta.valuewhen(bar_index == target_bar, highestHigh, 0)), 
                     color=color.green, textcolor=color.black, 
                     style=label.style_label_down, yloc=yloc.abovebar)

代码说明

  • 利用barstate.islast触发一次遍历逻辑,避免重复创建标签。
  • 通过for循环覆盖最近10根K线(包含当前K线),用ta.valuewhen获取对应K线的状态和数值。
  • 增加target_bar >= 0判断,避免图表初始阶段出现索引越界问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 17:05:18