/// Detector of divergences
/// Version by TempusFugit based on an original idea of jose7674
///The variable "N" is the number of bars backwards that we use to find a divergence
///The variable "a" is the number of bars used to calculate RSI
///The variable "b" is the number of bars checked backwards to detecte swing highs or lows
///The variable "c" is the aditional increase/decrise in price required to get a divergence
defparam calculateonlastbars=500
//N = 29
//a = 14
//b = 5
//c = 0
//
DRSI = Momentum[a](close)
cero = 0
////Searching for swing highs or lows
IF (BarIndex > 10+N) THEN
IF (DRSI[1]>DRSI AND DRSI[1]>highest[b](DRSI[2])) THEN
RSISwingHigh=DRSI[1]
RSIPreviousSwingHigh=highest[N](DRSI)
PriceSwingHigh=close[1]
PricePreviousSwingHigh=Highest[N](close)
ENDIF
IF (DRSI[1]<DRSI AND DRSI[1]<lowest[b](DRSI[2])) THEN
RSISwingLow=DRSI[1]
RSIPreviousSwingLow=lowest[N](DRSI)
PriceSwingLow=close[1]
PricePreviousSwingLow=lowest[N](close)
ENDIF
////Detecting Divergences between RSI and Price
IF(RSISwingHigh<RSIPreviousSwingHigh AND PriceSwingHigh>(PricePreviousSwingHigh[1]*(1+(c/100)))) THEN
signal = -1
ELSE
signal = 0
ENDIF
IF(RSISwingLow>RSIPreviousSwingLow AND PriceSwingLow<(PricePreviousSwingLow[1]*(1-(c/100)))) THEN
signal = 1
ENDIF
ENDIF
Return cero as "0", signal as "Divergence"
/// If Divergence = 1, there is bullish divergence. if D =-1, bearish divergence
///END