# RSI Divergence Indicator – Optimized AFL code

RSI Divergence Indicator – Hope most of them had heard it. Does anyone tested the accuracy of this trading indicator. This RSI Divergence is the modified and optimized version for Nifty and its good EOD Scanner in selecting the stocks from the momentum pack. The accuracy of the trading system is more than 75% for Nifty.backtested with better results.

Optimization code is added to the AFL so that it can optimized for max profits/Max Winning Ratio and better results. The Green dot in the indicator shows positive divergence and Red dot in the indicator shown negative divergence.

```_SECTION_BEGIN("RSI Divergence");
//------------------------------------------------------------------------------
//
//  Formula Name:    RSI divergence
//  Author:          Rajandran R
//  Url:             www.marketcalls.in
//  Formula URL:
//  Details URL:
//
//------------------------------------------------------------------------------
//
//  + scanner
//
//------------------------------------------------------------------------------

/*---------------------------------------------------
RSI Divergence
--------------------------------------------------------*/

GraphXSpace=7;
//n=Param("% Reverse ",12,0,100,1);
n=Optimize("ZIG",9,5,50,1);
per=Optimize("rsi",28,5,50,1);
Var = Zig(RSI(per), n);
t= Trough(RSI(per), n, 1);
p= Peak(RSI(per), 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])
}
}
Short=Sell;

Plot(Var, "", 39);
PlotShapes ( IIf(Sell, shapeSmallCircle, shapeNone), colorRed, 0 , Var,0);
PlotShapes( IIf(Buy, shapeSmallCircle, shapeNone),  colorBrightGreen, 0, Var,0);

Title ="RSI Divergence" ;
_SECTION_END();

_SECTION_BEGIN("TEMA");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 200, 1, 10 );
Plot( TEMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();```

The accuracy of predicting the exact bottom/Top of the trend is higher in case of our optimized version of RSI Divergence. RSI, Zig-Zag period are used for optimization inputs and the optimized paraters are RSI=28 and Zig-Zag=9. It could a good scanner in selecting NSE stocks.

While scanning stocks are applied with profit target of 20% with the trailing stop loss of 5% and backtested with 12 years of Nifty EOD Historical data. And the results are shown below.

Signals are scanned after EOD. And Stocks are Bought/Sold at next day open.

Settings Parameters for the Backtest
General Settings
Initial Equity – 10000
Postions – Long/Short
Periodicity – Daily

Sell Delay =1
Short Delay =1
Cover Delay =1

Sell Price = Open
Short Price = Open
Cover Price = Open

Stop Loss Settings
Stop Loss – Disabled
Profit Target – 20%
Trailing Stop Loss – 5%

Portfolio Settings

Backtested Results are shown below

Equity Curve

Max Drawdown

Profit Table

Profit Distribution

## [Free Course] Mini Certification on Amibroker AFL Programming

Interested in getting to know the basics of Amibroker AFL Programming then here is a free live training course to access hands-on training on...

This Algomojo Button trading module provides 4 modes of the button to place orders with a single click directly from Amibroker using simple smart...

## AlphaTrend – Amibroker AFL Code to Manage Sideways Markets

Very simple and interesting trend following strategy which could manage sideways markets to a greater extent while following the trend. Recently I got inspired...

## 25 Replies to “RSI Divergence Indicator – Optimized AFL code”

1. kalyan says:

thanx sir . many of us dont know how to backtest and optimize , if u do article about that

1. @Kalyan : Very soon planning to do an article for the same

2. Ashwini Khanna says:

Hello Rajandran,

I am using the optimised RSI Divergance you made. I need to get the Buy/Sell signal on the crossover, but I cant see the signal for all the crossovers. Its only showing Red/Green dots in few places.

Can you please tell me how to modify the code to get the signal at any crossover?

Thanks,
Regards,
Ashwini

3. debashish says:

Hi Rajandran, Can you please guide us how to use this RSI to take a trade in intraday trade in 5 min time frame.

1. @Debasish – The above AFL code is purely for EOD strategies and not for intra

4. SAMEER says:

where is the afl for rsi divergence sir.

1. @Sameer

AFL code is at the bottom of the post for your convenience i had added the code to the post

1. SAMEER says:

thanx sir……..

5. Mahender Reddy says:

good work.
Thanks a lot.

6. Sheikh says:

Will it be possible for you to add in the code, the buy and sell signals or get an alert whenever green or red dot appears?

7. Mark says:

This is lookin into future and repainting after few bars… It´s risky to trade this system or I´m not understanding how it really works. Thanks a lot!!!!!

1. Ravi Shanker Reddy Kourla says:

Hi Rajandran/Mark,

I agree with Mark comment, this system look into future and repainting the divergence dots.
For ex: If I user the scan/back testing say today EOD [say 13th December], I don’t get any divergence indicators[dots], but when I do the Scan/Back Testing after say 3 days [Say 16th December], I will get the divergence indicator for some stocks but the date is approx around 10th December. As per the above post I need to take the positions next day after seeing the divergence dot which is not possible.

8. Alok says:

RAJANDRAN, i have tracked your views and codes.
I must say, you are awesome…
Great going buddy….. thanks for sharing your priceless analysis.

9. chan says:

Hi rajandran the above afl is working very good in EOD thanx alot for that.but can u plz provide a alert window afl so that it will be easy to know which stock has given the divergence in the running market itself.in Intraday also plotting is happening but we are missing the trades..

10. Marcin says:

In my opinion there should be two days of delay in the case of BUY. Am I right?

1. Yes you are! It looks two bars into the future.

1. Marcin says:

So you can’t set Buy/Sell/Short/Cover Delay = 1 for correct backtesting. There should be 2 days of delay in each case because in reality you can put a market order (opening price) two days after the green/red signal appears. The equity curve is worse in this case. Am I still right?
Regards from Poland.

11. sagar says:

8648 data bars used during this check. Total execution time: 0.0295951 sec.
Approximately 2390 past and 1500 future quotes are needed to calculate the formula properly

sir when i open the analysis tool and in code check and profile i get the above error, what is it…

regards
sagar

12. haider says:

hi Rajandran R, nice afl , thank for sharimg

13. haider says:

any one can modify the same afl for complex divergence i.e divergen of rsi(15) with respect to rsi(45) or higher not with price

Dear Rajendran,

There is repainting issue in this afl, however it is a really good tool, can you please provide a version which does not repaint and helps you making fair judgement.

1. Hi the repainting in this case cannot be solved as some of the function used here doesnt allow to make it as non repainting.

It is a very good indicator for exiting the calls but repainting is becoming a concern now, please do look into it. I am using it for 3 min. timeframe and if we are able to remove repainting it will turn out to be a very good tool indeed clubbed with other AFL.

1. The above doesn’t suit for lower timeframe trading.

15. Ravi Chokshi says:

Hi,

how can i run this code on MT4 or Tradingview website ?

plese help