Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

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.


[wp_ad_camp_5]

 
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 Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Fisher Transform – Amibroker AFL Code

The Fisher Transform is a technical analysis indicator developed by John F. Ehlers, designed to identify potential turning points in the price movements of...
Rajandran R
2 min read

My Experience Converting SSL Hybrid from PineScript to Amibroker…

As a trader and coding enthusiast, I often find myself needing to translate trading indicators from one programming language to another. Recently, I embarked...
Rajandran R
8 min read

Line Trading – OpenAlgo Automation Module for Amibroker Users

The line Trading Automation tool is designed for Manual traders who want to perform level-based trade execution faster and also bring some advanced trade...
Rajandran R
59 sec 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