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.
Please visit Trading Tuitions Academy to learn AFL coding and create your own Trading systems.
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:
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, 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: 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
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:
Check out our other profitable Trading systems in the below link:
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
Send me how I can buy Rsi divergent system…. how much is a cost…
Hi Mahesh,
There is no cost involved for any AFL’s in this website.
/——————————————————
//
// 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 Sourav,
Please read about this AFL here https://tradingtuitions.com/nr7-trading-strategy-low-risk-high-reward/
Already posted.
Hi Mahesh,
Can you please elaborate?
SIR, AFL LOOKS IN THE FUTURE, KINDLY CHECK AS THE SIGNAL APPEARS APP. 3 BARS BEFORE.
Hi Karan,
Thanks for the feedback. What makes you think that this AFL looks into future? Can you please explain with an example.
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.
HI,
In AFL reference, the function Peak is discribed as “This uses the Zig Zag function (see Zig Zag) to determine the peaks. […] Caveat: this function is based on Zig-Zag indicator and may look into the future”.
Regards.
Yes Gustavo, this is the drawback of this function. We have updated the same in the article.
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
SIR, KINDLY CHECK ON BAR REPLAY FOR LAST 10 SIGNALS, YOU WILL FIND SIGNALS ARE SHOWN ON 3 PREVIOUS BARS & NOT ON CURRENT BAR.
Thanks Karan! We have added a note in the post.
would u please share the voice alert and auto trading code for this AFL !!
Hi Animesh,
We do not recommend this for auto trading. The code is just for backtesting purpose.
that means I can’t use this code for trading ?
We recommend not to
Reason ? and please share the voice alert at least for this coding @ animeshroy83@gmail.com
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”);
Dear Admin,
It’s showing ‘error 31’,’syntax error’…etc.
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 ) ?
any body having afl for pair trading ?
can you help in deveping rsi divergence afl code for 5 min chart and how to perform scanning in amibroker with it. to find the charts fullfulling criteria.
I have tried RSI Divergence by Brad Konia but it does not give any signal. Kindly help.
hello sir your site is very helpful for new learners.
i m looking for one strategy for afl.
open = high or open = low
2nd candle should be inside candle of first candle.
trade on breakout og 2nd candle.
pls code this sir and post in your website.
THIS STRATEGY WILL HELP SMALL TRADERS TO START ALGO TRADING.
thanks
regards
Hi Lokesh,
Please also mention the BUY/SELL rules