// Downloaded From https://www.WiseStockTrader.com
_SECTION_BEGIN("RSI DIVERGENCE");
GraphXSpace=7;
 n=Param("% Reverse ",20,0,100,1);
 Buy=Sell=0;

Var = Zig(RSI(), n); 
 t= Trough(RSI(), n, 1); 
 p= Peak(RSI(), n, 1); 
 x[0] =Var[0];
 price[0] = C[0];
 j=0;

// bearish divergence
 for ( i=0; i<BarCount; i++) 
 {
 if(Var[i] == p[i])
 {

j++;
 x[j] =Var[i];
 price[j] =C[i];
 if(x[j] <x[j-1] && price[j-1]< price[j]) 
 Sell[i] =1;
 }
 }

// bullish divergence
 for ( i=0; i<BarCount; i++) 
 {
 if(Var[i] == t[i])
 {
 j++;
 x[j] =Var[i];
 price[j] =C[i];
 if(x[j] >x[j-1] && price[j]<price[j-1]) 
 Buy[i] =1;
 }
 }

//Plot(Var, "", 40, styleThick); 

Plot(RSI(n),"RSI",IIf(RSI(n) <= 30, colorBrightGreen,IIf(RSI(n) <= 50, colorGreen,IIf(RSI(n) <= 70, colorRed,colorPink))),stylethick);

 PlotShapes ( IIf(Sell, shapeCircle, shapeNone), colorGold, 0 , Var,0);
 PlotShapes ( IIf(Sell, shapeDownArrow, shapeNone), colorRed, 0 , Var,-10);
 
 PlotShapes( IIf(Buy, shapeCircle, shapeNone), colorGold, 0, Var,0);
 PlotShapes( IIf(Buy, shapeUpArrow, shapeNone), colorBrightGreen, 0, Var,-10);
 
Plot(70, "Overbought", colorRed,styledots) ;
Plot(30, "Oversold", colorGreen,styledots) ;
Plot(50, "Center", colorBlue,styledots) ;  

_SECTION_END();