Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

RSI Divergence Indicator – Optimized AFL code

1 min read

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);
Buy=Sell=0;
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]) 
Buy[i] =1;
}
}
Short=Sell;
Cover=Buy;

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

Trades Settings
Buy Delay =1
Sell Delay =1
Short Delay =1
Cover Delay =1

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

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

Portfolio Settings

Max Open Trade =1

Backtested Results are shown below

Equity Curve

Max Drawdown

Profit Table

Profit Distribution

Download RSI Divergence – AFL code – Optimized Version

Rajandran R Founder of Marketcalls and Co-Founder Algomojo. Full-Time Derivative Trader. Expert in Designing Trading Systems (Amibroker, Ninjatrader, Metatrader, Python, Pinescript). Trading the markets since 2006. Mentoring Traders on Trading System Designing, Market Profile, Orderflow and Trade Automation.

How to Install Amibroker and Ninjatrader on MacBook Air

This is a routine question we get from Mac users and in this tutorial, we will be learning how to install Windows 11 inside...
Rajandran R
49 sec read

What is Algomojo – Smart Order Execution Module for…

Smart Order Module brings a 100% end-to-end automated trading solution for Amibroker users to automate their trading ideas with a simple plug-and-play module. Traders...
Rajandran R
26 min read

Virtual Trade Simulator Module Version 1.0 – Amibroker AFL…

Thought of launching a simple and user-friendly Virtual Trade Simulator to study/test your inner intuition before practicing in the live markets. Virtual Trade Simulator...
Rajandran R
3 min read

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

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

  2. 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. Hi Rajandran, Can you please guide us how to use this RSI to take a trade in intraday trade in 5 min time frame.

  4. 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?

  5. 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. 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.
      Rajendran can you please share your thoughts on this?

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

  7. 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..

    thanx in advance..

      1. 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?
        Thank you for your answer in advance.
        Regards from Poland.

  8. 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

  9. 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

  10. 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.

    Your efforts is appreciated.

      1. 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.

  11. Hi,

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

    plese help

    thanks in advance .

    – Ravi

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More