如何抵消 2 条移动平均线并在它们相互交叉时更改背景颜色?

how to offset 2 moving averages and change the background color whenever they cross each other?

我创建了一个穿越移动平均线的指标,当 ema1 穿过 ema2 时,它是一个上升趋势,所以背景颜色变为绿色,当 ema1 穿过 ema2 下方时,它是一个下降趋势,背景颜色变为红色但是我希望能够 offset/shift 移动平均线并且在它们交叉时仍然得到相同的结果,我该怎么做?

//@version=5

indicator(title="Offset Emas Crossover", shorttitle="OEC", overlay=true, timeframe="", timeframe_gaps=true)

// EMA 1
length_of_ema_1 = input.int(50, minval=1, title="Length", group="EMA 1")
source_of_ema_1 = input(close, title="Source", group="EMA 1")
offset_of_ema_1 = input.int(title="Offset", defval=0, minval=-500, maxval=500, group="EMA 1")
ema_1 = ta.ema(source_of_ema_1, length_of_ema_1)

// EMA 2
length_of_ema_2 = input.int(100, minval=1, title="Length", group="EMA 2")
source_of_ema_2 = input(close, title="Source", group="EMA 2")
offset_of_ema_2 = input.int(title="Offset", defval=0, minval=-500, maxval=500, group="EMA 2")
ema_2 = ta.ema(source_of_ema_2, length_of_ema_2)

// TREND
float color = 255
float transparency = 75
uptrend = ema_1 > ema_2
downtrend = ema_1 < ema_2

// BACKGROUND COLOR
background_color = if uptrend
    color.rgb(0, colour, 0, transparency)
else
    color.rgb(colour, 0, 0, transparency)

// PLOTTING
plot(ema_1, color=color.blue, title="MA", offset=offset_of_ema_1)
plot(ema_2, color=color.red, title="MA", offset=offset_of_ema_2)

offset plot() 参数将在视觉上移动该行。这并不意味着您正在检查带有偏移量的值。

如果您想参考历史值(例如,如果交叉发生在两个柱前),您需要使用 history reference operator.

uptrend = ema_1 > ema_2
downtrend = ema_1 < ema_2

// uptrend[2] -> get the value of uptrend two bars ago
// downtrend[2] -> get the value of downtrend two bars ago