RSI Divergence Trading System: Unbelievable profit potential

Divergences are one of the most reliable trading concepts that provide very good buy/sell opportunities. Though it belongs to  classical technical analysis, yet it is widely used by modern hedge fund trading systems. In a very layman term, divergences are said to happen when price and momentum does not confirm the same direction. For ex:- if price is going up but momentum is going down or vice versa. There are various momentum based indicator available through which you can quantify divergences. In this post, we will go through a RSI Divergence Trading System. This system has a very high success rate and the credit for its development goes to Brad Konia, who has uploaded it in WiseStockTrader. We have added Buy/Sell signals to this systems and made it back-testable.

Read our article on AFL tutorial here.

RSI Divergence

RSI Divergence occurs when price and RSI does not move in same direction. If Price is going up and RSI is going down it’s called Bearish RSI Divergence, while if price is going down and RSI is going up it’s called Bullish RSI Divergence. The below image explains it in a better way:

rsi divergence

Image Source: http://www.guppytraders.com/gup342.shtml

The next section is going to describe Amibroker AFL code for RSI Divergence Trading system. This system has unbelievable profit potential. In a sample backtest for 16 years, it shows 100% success rate for NSE Nifty. Even for other scrips it performs exceptionally well.

AFL Overview

Parameter Value
Preferred Time-frame
Daily
Indicators Used RSI(14)
Buy Condition RSI Bullish Divergence
Short Condition RSI Bearish Divergence
Sell Condition New peak formation in RSI chart
Cover Condition New Trough formation in RSI chart
Stop Loss No fixed stoploss
Targets No fixed target
Position Size 150 (fixed)
Initial Equity 200000
Brokerage 100 per order
Margin 10%

AFL Code

Note: This AFL uses Zig Zag indicator which makes it prone to look into future. While its good for backtesting purpose, we do not recommend to use the buy/sell signals for live trading.

//------------------------------------------------------
//
//  Formula Name:    RSI Divergance
//  Author/Uploader: Brad Konia
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com
//------------------------------------------------------

SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C ));
Plot(Close,"Price",color=colorBlue,style=styleCandle);


SetTradeDelays( 1, 1, 1, 1 );
SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",50);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);
SetPositionSize(150,spsShares);
//SetPositionSize(20,spsPercentOfEquity);
SetOption( "AllowPositionShrinking", True );

 
indName = "RSI"; // Specify the name of the indicator. This is cosmetic only.
length = Param(indName + " Length", 14, 8, 100, 1); // Indicator length
threshold = Param("Zig/Zag Threshold %", 10, 1, 50, 1); // Minimum % change in indicator value to be considered a zig/zag
indVal = RSI(length); // Load the indVal array with the values from the indicator of your choice
indZig = Zig(indVal, threshold); // Set the zig/zag values for the indicator
indPeakVal1 = Peak(indVal, threshold, 1); // Most recent peak value
indPeakBars1 = PeakBars(indVal, threshold, 1); // Bars since most recent peak
indPeakVal2 = Peak(indVal, threshold, 2); // Second most recent peak value
indPeakBars2 = PeakBars(indVal, threshold, 2); // Bars since second most recent peak
indTroughVal1 = Trough(indVal, threshold, 1); // Most recent trough value
indTroughBars1 = TroughBars(indVal, threshold, 1); // Bars since most recent trough
indTroughVal2 = Trough(indVal, threshold, 2); // Second most recent trough value
indTroughBars2 = TroughBars(indVal, threshold, 2); // Bars since second most recent trough
 
// Determine if current bar is a peak or trough
peakBar = indPeakBars1 == 0;
troughBar = indTroughBars1 == 0;

printf("\n peakBar  : " + peakBar ); 
printf("\n troughBar  : " + troughBar ); 

 
// Bearish divergence
divergeBear = IIf(peakBar AND (indPeakVal1 < indPeakVal2) AND  High > Ref(High, -indPeakBars2), True, False);
Short=divergeBear;
Cover=troughBar;
Short=ExRem(Short,Cover);
Cover=ExRem(Cover,Short);
 
// Bullish divergence
divergeBull = IIf((indTroughBars1 == 0) AND (indTroughVal1 > indTroughVal2) AND Low < Ref(Low, -indTroughBars2), True, False);
Buy=divergeBull;
Sell=peakBar;
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);

printf("\n divergeBear  : " + divergeBear ); 
printf("\n divergeBull  : " + divergeBull ); 

BuyPrice=Open;
SellPrice=Open;
ShortPrice=Open;
CoverPrice=Open;

printf("\nBuy : " + Buy );  
printf("\nSell : " + Sell );  
printf("\nShort : " + Short );  
printf("\nCover : " + Cover );  
 

/* Plot Buy and Sell Signal Arrows */
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Cover, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Cover, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

_SECTION_END();

RSI Divergence Trading System: Screenshot

RSI Divergence AFL

RSI Divergence Trading System: Backtest Report

Parameter Value
Fixed Position Size
Initial Capital 200000
Final Capital 2425937
Scrip Name NSE Nifty
Backtest Period 08-Mar-2000 to 11-Aug-2016
Timeframe Daily
Net Profit % 1112.97%
Annual Return % 16.12%
Number of Trades 88
Winning Trade % 100%
Average holding Period 7.09 periods
Max consecutive losses 0
Max system % drawdown -4.83%
Max Trade % drawdown -37.3%

Th Annual return can increase multi-fold if you allow compounding. Download the detailed backtest report here.

Equity Curve

RSI Divergance - Equity Curve

Profit Table

rsi-divergance-profit-table

Additional Amibroker settings for backtesting

Goto Symbol–>Information, and specify the lot size and margin requirement. The below screenshot shows lot size of 75 and margin requirement of 10% for NSE Nifty:

Symbol Info_Nifty

Check out our other profitable Trading systems in the below link:

Amibroker Trading Systems

Excel Based Trading Systems

Disclaimer:

All the AFL’s posted in this section are for learning purpose. Trading Tuitions does not necessarily own these AFL’s and we don’t have any intellectual property rights on them. We might copy useful AFL’s from public forums and post it in this section in a presentable format. The intent is not to copy anybody’s work but to share knowledge. If you find any misleading or non-reproducible content then please inform us at support@tradingtuitions.com

21 Comments

      • /——————————————————
        //
        // Formula Name: NR7 Trading Strategy
        // Author/Uploader: Trading Tuitions
        // E-mail: support@tradingtuitions.com
        // Website: http://www.tradingtuitions.com
        //——————————————————

        _SECTION_BEGIN(“NR7 Trading Strategy”);

        SetChartOptions(0,chartShowArrows|chartShowDates);
        _N(Title = StrFormat(“{{NAME}} – {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}”, O, H, L, C ));

        //Initial Parameters
        SetTradeDelays( 0,0,0, 0 );
        SetOption( “InitialEquity”, 200000);
        SetOption(“FuturesMode” ,True);
        SetOption(“MinShares”,1);
        SetOption(“CommissionMode”,2);
        SetOption(“CommissionAmount”,100);
        SetOption(“AccountMargin”,10);
        SetOption(“RefreshWhenCompleted”,True);
        SetPositionSize(50,spsPercentOfEquity);
        //SetPositionSize(150,spsShares);
        SetOption( “AllowPositionShrinking”, True );

        Plot( Close, “Price”, colorWhite, styleCandle );

        //==================================================================================
        //NR7 RANGE IDENTIFICATION

        range = H-L;
        Condition0 = range<Ref(range,-1) AND range<Ref(range,-2) AND range<Ref(range,-3)AND range<Ref(range,-4)AND range<Ref(range,-5)AND range=BuyTgt OR L<=BuySL;

        ShortTgt=ValueWhen(Short,ShortPrice,1)*(1-TGT/100);
        ShortSL=ValueWhen(Short,ShortPrice,1)*(1+SL/100);
        Cover= L=ShortSL;

        SellPrice = IIf(Sell, IIf(H>=BuyTgt, BuyTgt, BuySL), Null);
        CoverPrice = IIf(Cover, IIf(L<=ShortTgt, ShortTgt, ShortSL), Null);

        Buy = ExRem(Buy,Sell);
        Sell =ExRem(Sell,Buy);
        Short=ExRem(Short,Cover);
        Cover=ExRem(Cover,Short);

        printf("\nBuy : " + Buy );
        printf("\nSell : " + Sell );
        printf("\nShort : " + Short );
        printf("\nCover : " + Cover );
        printf("\nBuyPrice : " + BuyPrice );
        printf("\nShortPrice : " + ShortPrice );
        printf("\nSellPrice : " + SellPrice );
        printf("\nCoverPrice : " + CoverPrice );
        printf("\nBuyTgt : " + BuyTgt );
        printf("\nBuySL : " + BuySL );
        printf("\nShortTgt : " + ShortTgt );
        printf("\nShortSL : " + ShortSL );

        /* Plot Buy and Sell Signal Arrows */
        PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
        PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
        PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);
        PlotShapes(IIf(Short, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);
        PlotShapes(IIf(Short, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);
        PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);
        PlotShapes(IIf(Sell, shapeStar, shapeNone),colorWhite, 0, H, Offset=25);
        PlotShapes(IIf(Cover, shapeStar, shapeNone),colorWhite, 0,L, Offset=-25);

        _SECTION_END();

        //hello admin can u share ur view regarding this afl

    • Hi Karan,

      Thanks for the feedback. What makes you think that this AFL looks into future? Can you please explain with an example.

  1. SIR, BUY ARROW OR SELL ARROW SIGNALS DO NOT APPEAR ON THE CURRENT BAR, ARROW APPEARS 3 CANDLES PRIOR TO CURRENT CANDLE.
    EXAMPLE LAST BUY SIGNAL APPEARED BELOW 25/8/2016 CANDLE ON 29/8/2016, KINDLY CHECK.

    • Hi Karan,

      We will report the same to the original author of this AFL. But can you please provide few more examples, I do not see any Buy Signal on 25/08. Also Bar Replay do not show any overlooking signals.

  2. Means is this formula repainting ? Admin please check and correct the error if any…

    I also checked on Bar replay it shows signals on previous 3 bars and not on current bar

  3. SIR, KINDLY CHECK ON BAR REPLAY FOR LAST 10 SIGNALS, YOU WILL FIND SIGNALS ARE SHOWN ON 3 PREVIOUS BARS & NOT ON CURRENT BAR.

    • Hi Animesh,

      We do not recommend this for auto trading. The code is just for backtesting purpose.

    • Hi Animesh,

      This system looks slightly into future for buy/sell decisions. Paste this snippet at the end of the code to get voice alerts:
      if (SelectedValue(Buy)==1) Say(“BUY Signal Now “);
      if (SelectedValue(Sell)==1) Say(“Sell Signal Now”);

  4. So as per the strategy , one can sell a stock when RSI hits upper limit ( >=80 ) without looking into any other technical indicators and one can BUY a stock when its at lower limit ( <=20 ) ?

Leave a Reply

Your email address will not be published. Required fields are marked *