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

TradingView Pine Script:无法为EMA买卖信号设置背景与K线颜色

EMA买卖信号指标:添加背景色与K线颜色实现方案

需求说明

  • 买入信号:9周期EMA(绿色)上穿18周期EMA(红色)
  • 卖出信号:9周期EMA(绿色)下穿18周期EMA(红色)
  • 已实现信号标签,需补充:触发信号时的K线颜色修改、背景色标记

修改后的完整代码

//@version=5
indicator(title='EMA', overlay=true)

s9ema = ta.ema(close, 9)
s18ema = ta.ema(close, 18)

longCond = ta.crossover(s9ema, s18ema)
shortCond = ta.crossunder(s9ema, s18ema)

// 绘制EMA线
plot(s9ema, color=color.green, title="9周期EMA")
plot(s18ema, color=color.red, title="18周期EMA")

// 买卖信号标签
plotshape(series=longCond, title='BUY', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), text='BUY', size=size.small)
plotshape(series=shortCond, title='SELL', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), text='SELL', size=size.small)

// 设置K线颜色:买入信号K线绿,卖出信号K线红,默认不变
barcolor(longCond ? color.green : shortCond ? color.red : na)

// 设置背景色:买入信号背景浅绿,卖出信号背景浅红
bgcolor(longCond ? color.new(color.green, 90) : shortCond ? color.new(color.red, 90) : na)

关键代码说明

  1. K线颜色设置:使用barcolor()函数,当longCond成立时K线设为绿色,shortCond成立时设为红色,其他情况保持默认(na)。
  2. 背景色设置:使用bgcolor()函数,通过color.new()调整透明度(第二个参数90表示高透明度,避免遮挡K线),仅在信号触发时显示对应背景色。
  3. 补充绘制两条EMA线,让指标逻辑更直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:09:24