Skip to main content

Divergences stand out as one of the most dependable trading concepts, offering excellent buy and sell opportunities. While rooted in classical technical analysis, modern hedge fund trading systems frequently incorporate them. In simple terms, divergences occur when the price and momentum move in different directions. For example, when the price rises while momentum falls, or vice versa. Various momentum-based indicators are available to identify divergences. In this post, we’ll delve into an RSI Divergence Trading System. This system boasts a high success rate, thanks to Brad Konia, who shared it on WiseStockTrader. We’ve added Buy/Sell signals and made it suitable for backtesting.

Click here to learn about AFL coding and create your own trading systems.

Understanding RSI Divergence

RSI Divergence occurs when the price and RSI (Relative Strength Index) do not move in the same direction. When the price climbs while RSI falls, it’s called Bearish RSI Divergence. Conversely, when the price drops while RSI rises, it’s known as Bullish RSI Divergence. The image below illustrates this concept:

RSI Divergence

The next section provides an overview of the Amibroker AFL code for the RSI Divergence Trading System. This system exhibits remarkable profit potential, with a 100% success rate for NSE Nifty in a 16-year backtest. It also performs exceptionally well with other securities.

AFL Code 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 stop-loss
Targets No fixed targets
Position Size 150 (fixed)
Initial Equity 200000
Brokerage 100 per order
Margin 10%

Important Note

Note: This AFL uses the Zig Zag indicator, which can sometimes appear to predict the future. While it’s suitable for backtesting, we do not recommend using the buy/sell signals for live trading.

				
					//------------------------------------------------------
//
//  Formula Name:    RSI Divergance
//  Website:         https://zerobrokerageclub.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, SelectedValue( ROC( C, 1 ) ) ));
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 Trading System

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%

The annual return can increase significantly with compounding. Download the detailed backtest report here.

Equity Curve

RSI-Divergance-Equity-Curve

RSI-Divergance-Profit-Table

Additional Amibroker Settings for Backtesting

Go to Symbol → Information and specify the lot size and margin requirement. The screenshot below shows a lot size of 75 and a margin requirement of 10% for NSE Nifty:

Check out our other profitable trading systems in the links below:

Amibroker Trading Systems

Excel-Based Trading Systems

Leave a Reply