You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Pine Script v6:如何让指标图例背景与面板背景透明一致?

Pine Script 指标图例背景透明度问题解决方案

问题概述

使用Pine Script创建带自定义面板背景的指标时,通过bgcolor()fill()实现的面板背景显示正常,但指标图例(显示指标名称和数值)区域存在独立的不透明背景矩形,与面板背景形成视觉反差。希望仅针对当前指标面板解决该问题,而非通过全局图表设置影响所有面板。

现有代码

//––––– Visuals –––––
grpBG      = "Background"
bgStyle    = input.string("Pane background", "Grey",
               options=["None","Pane background"], group=grpBG)
bgColor    = input.color(color.rgb(130, 130, 136), "grey BG colour", group=grpBG)
bgOpacity  = input.int(20, "Grey BG opacity (0–100)", minval=0, maxval=100, group=grpBG)

// Background using fills (only affects this indicator pane)
pBgBottom = plot(b0, title="Background bottom", display=display.none)
pBgTop = plot(bTop * 1.15, title="Background top", display=display.none, trackprice=false)
fill(pBgBottom, pBgTop, color = bgStyle == "Pane background" ? color.new(bgColor, bgOpacity) : na, title="Pane Background")

解决方案说明

TradingView的默认图例背景是全局UI设置的一部分,Pine Script目前没有提供直接控制单个指标图例背景透明度的参数,但可以通过以下变通方法实现预期效果:

方法1:隐藏默认图例,自定义绘制匹配面板背景的图例

通过隐藏默认图例,使用label函数在指标面板内绘制完全自定义的图例,让其背景色和透明度与面板背景保持一致。

修改后的代码示例:

//––––– Visuals –––––
grpBG      = "Background"
bgStyle    = input.string("Pane background", "Grey",
               options=["None","Pane background"], group=grpBG)
bgColor    = input.color(color.rgb(130, 130, 136), "grey BG colour", group=grpBG)
bgOpacity  = input.int(20, "Grey BG opacity (0–100)", minval=0, maxval=100, group=grpBG)
showCustomLegend = input.bool(true, "Show Custom Legend", group=grpBG)

// 隐藏默认面板图例,仅在数据窗口显示
indicator("Custom BG Indicator", overlay=false, display=display.data_window)

// 定义面板背景的上下基准值(根据你的指标逻辑调整)
b0 = low - ta.tr/2
bTop = high + ta.tr/2

// Background using fills (only affects this indicator pane)
pBgBottom = plot(b0, title="Background bottom", display=display.none)
pBgTop = plot(bTop * 1.15, title="Background top", display=display.none, trackprice=false)
fill(pBgBottom, pBgTop, color = bgStyle == "Pane background" ? color.new(bgColor, bgOpacity) : na, title="Pane Background")

// 自定义图例:持久化标签,动态更新内容与样式
var legendLabel = label.new(bar_index, bTop, "", color=color.new(bgColor, bgOpacity), textcolor=color.white, style=label.style_label_left)
if showCustomLegend and bgStyle == "Pane background"
    // 替换为你需要显示的指标名称和数值逻辑
    legendText = "自定义指标: " + str.tostring(close, "#.##")
    label.set_xy(legendLabel, bar_index, bTop)
    label.set_text(legendLabel, legendText)
    label.set_color(legendLabel, color.new(bgColor, bgOpacity))
else
    label.set_text(legendLabel, "")

关键说明

  • indicator()display=display.data_window隐藏面板上的默认图例,仅保留数据窗口中的显示。
  • 通过var label创建持久化标签,动态更新位置、文本和背景色,确保与面板背景完全匹配。
  • 可根据需求自定义图例的位置、文本内容和样式,完全适配指标逻辑。

方法2:简化图例显示(轻量方案)

如果不需要在面板上显示实时数值,可以通过以下方式简化:

  • shorttitle设置简短的指标名称,减少图例占比
  • display=display.none完全隐藏图例(仅适用于不需要图例显示的场景)

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

火山引擎 最新活动