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

求助:手动斐波那契(Fib)指标各层级标签重复问题

解决手动斐波那契指标标签重复显示问题

原代码的问题在于每根K线都会执行label.new(),导致不断生成新标签,最终出现重复堆积的情况。以下是修复后的完整代码,核心思路是用var持久化存储标签对象,每次更新时先删除旧标签再创建新的,同时处理开关关闭时的标签清理:

//@version=6
indicator(title="手动斐波那契水平", shorttitle="手动Fib", overlay=true)

// 手动高低点输入
pHigh = input.price(title="高点价格", defval = 0.0000, confirm = true) 
pLow = input.price(title="低点价格", defval = 0.0000, confirm = true)

// 斐波那契水平显示开关
show_000  = input.bool(title="0.000" , defval=true)
show_236  = input.bool(title="0.236" , defval=true)
show_382  = input.bool(title="0.382" , defval=true)
show_500  = input.bool(title="0.500" , defval=true)
show_618  = input.bool(title="0.618" , defval=true)
show_786  = input.bool(title="0.786" , defval=true)
show_100  = input.bool(title="1.000" , defval=true)
show_1618 = input.bool(title="1.618" , defval=true)
show_2618 = input.bool(title="2.618" , defval=true)

// 斐波那契比率
f_000  = 0.000
f_236  = 0.236
f_382  = 0.382
f_500  = 0.500
f_618  = 0.618
f_786  = 0.786
f_100  = 1.000
f_1618 = 1.618
f_2618 = 2.618

// 计算并绘制斐波那契水平的函数
plotFibLevel(level, show, color, levelName) =>
    if show
        fibLevelPrice = pLow + (pHigh - pLow) * level
        // 绘制水平线
        line.new(bar_index[+100], fibLevelPrice, bar_index, fibLevelPrice, color=color, width=1)
        // 用var持久化标签变量,避免重复创建
        var label fibLabel = na
        // 删除旧标签
        if not na(fibLabel)
            label.delete(fibLabel)
        // 创建新标签
        fibLabel := label.new(bar_index, fibLevelPrice, levelName + " =  " + str.tostring(fibLevelPrice, "###.####"), color=color, textcolor=color.black, style=label.style_label_left)
    else
        // 关闭显示时删除对应标签
        var label fibLabel = na
        if not na(fibLabel)
            label.delete(fibLabel)

// 绘制各斐波那契水平
plotFibLevel(f_000,  show_000, color.rgb(253, 254, 255), "00.0%")
plotFibLevel(f_236,  show_236, color.rgb(253, 254, 255), "23.6%")
plotFibLevel(f_382,  show_382, color.rgb(253, 254, 255), "38.2%")
plotFibLevel(f_500,  show_500, color.rgb(253, 254, 255), "50.0%")
plotFibLevel(f_618,  show_618, color.rgb(245, 201, 6), "61.8%")
plotFibLevel(f_786,  show_786, color.rgb(253, 254, 255), "78.6%")
plotFibLevel(f_100,  show_100, color.rgb(253, 254, 255), "100.0%")
plotFibLevel(f_1618, show_1618, color.rgb(253, 254, 255), "161.8%")
plotFibLevel(f_2618, show_2618, color.rgb(253, 254, 255), "261.8%")

核心改动说明

  1. var关键字持久化标签:用var label fibLabel = na声明标签变量,确保变量在脚本运行期间只初始化一次,不会每根K线都重新创建新变量
  2. 旧标签删除逻辑:在创建新标签前,先检查旧标签是否存在,若存在则用label.delete()删除,彻底避免标签堆积
  3. 开关关闭时的清理:增加else块,当关闭某水平的显示开关时,自动删除对应的标签,保持界面整洁
  4. 标签创建范围控制:将label.new()移入if show块内,避免不显示该水平时仍创建无效标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 15:44:51