基于Supertrend信号修改EMA Crossover策略背景色需求
基于Supertrend信号切换背景色的EMA交叉策略修改
现有一套9-18周期EMA交叉策略代码,当前背景色根据9周期EMA与18周期EMA的相对位置设置,效果如图所示。现需修改该策略,将背景色的切换逻辑改为依据Supertrend指标的买卖信号执行。

原策略代码
//@version=5 indicator(title='EMA Crossover', overlay=true) s9ema = ta.ema(close, 9) s18ema = ta.ema(close, 18) longCond = ta.crossover(s9ema, s18ema) shortCond = ta.crossunder(s9ema, s18ema) bgcolor(s9ema>s18ema?color.new(color.green,92):s9ema<s18ema?color.new(color.red,92):na) barcolor(s9ema>s18ema?color.new(color.green,0):s9ema<s18ema?color.new(color.red,0):na) plotshape(series=longCond, title='BUY', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.green, 0), text='BUY', size=size.small) plotshape(series=shortCond, title='SELL', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.red, 0), text='SELL', size=size.small)
修改后的策略代码
我们引入Supertrend指标,根据其趋势方向(多头/空头)来切换背景色和K线颜色,同时保留原EMA交叉的买卖信号标记:
//@version=5 indicator(title='EMA Crossover with Supertrend Background', overlay=true) // 原EMA指标计算 s9ema = ta.ema(close, 9) s18ema = ta.ema(close, 18) // Supertrend指标参数(可自定义调整) atrLength = input.int(10, title="ATR周期") multiplier = input.float(3.0, title="ATR乘数") [supertrendLine, trendDirection] = ta.supertrend(multiplier, atrLength) // 原EMA交叉信号 longCond = ta.crossover(s9ema, s18ema) shortCond = ta.crossunder(s9ema, s18ema) // 根据Supertrend趋势方向设置背景色和K线颜色 bgcolor(trendDirection == 1 ? color.new(color.green, 92) : trendDirection == -1 ? color.new(color.red, 92) : na) barcolor(trendDirection == 1 ? color.new(color.green, 0) : trendDirection == -1 ? color.new(color.red, 0) : na) // 保留原EMA交叉买卖标记 plotshape(series=longCond, title='BUY', style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.green, 0), text='BUY', size=size.small) plotshape(series=shortCond, title='SELL', style=shape.triangledown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.red, 0), text='SELL', size=size.small) // 可选:绘制Supertrend轨道线,方便直观查看 plot(supertrendLine, color=trendDirection == 1 ? color.green : color.red, title="Supertrend轨道", linewidth=2)
关键修改说明
- 新增Supertrend指标计算:使用
ta.supertrend()函数获取轨道线和趋势方向,trendDirection=1代表多头趋势,trendDirection=-1代表空头趋势 - 替换背景色/ K线颜色逻辑:将原有的EMA相对位置判断,改为基于Supertrend的趋势方向
- 保留原EMA交叉信号:继续显示EMA金叉/死叉的买卖标记,不影响原有信号逻辑
- 可选添加轨道线:绘制Supertrend的轨道线,方便直观确认当前趋势状态
内容的提问来源于stack exchange,提问作者Rashmi Rahul
相关产品推荐
相关产品推荐

