This is another spin of the classic MACD divergence indicator except we use a zero lag MACD and also consider the immediate price action to filter for stronger signals.
The only adjustable parameter is the lookback period to consider for calculating the divergence between price and the MACD crossover.
Note that the indicator only loads 5000 bars per default in order to load faster but this can easily be changed in the code if required.
Defparam CalculateOnLastBars = 5000
MACD1 = DEMA[12](close) //Moving Average 1
MACD2 = DEMA[26](close) //Moving Average 2
MACDSource = MACD1 - MACD2
MACDSignal = DEMA[9](MACDSource) //MACD Signal Line
DivergencePeriod = 20
If MACDSignal > 2 and MACDSignal[1] <= MACDSource[1] and MACDSignal >= MACDSource Then
MACDCrossHigh = MACDSignal
ElsIf MACDSignal < -2 and MACDSignal[1] >= MACDSource[1] and MACDSignal <= MACDSource Then
MACDCrossLow = MACDSignal
EndIf
If MACDCrossHigh < MACDCrossHigh[DivergencePeriod] and close > close[DivergencePeriod] and (high-max(open,close) > (max(open,close)-min(open,close)) or (close[1] > open[1] and close < min(open,close))) Then
Divergence = -1
r = 255
g = 0
ElsIf MACDCrosslow > MACDCrossLow[DivergencePeriod] and close < close[DivergencePeriod] and (min(open,close)-low > (max(open,close)-min(open,close)) or (close[1] < open[1] and close > max(open,close))) Then
Divergence = 1
r = 0
g = 255
Else
Divergence = 0
r = 0
g = 0
EndIf
Return Divergence coloured(r,g,0) style(histogram) as "Divergence"