Intraday Trend Following Strategy: MACD and Bollinger Band

Trend following is certainly a sure-shot way to mint money during rising or falling markets. At sideways trend it can be painful due to consecutive whipsaws but there is no way to avoid that. The only thing we can try is to minimize whipsaws using combination of indicators. The intraday trend following strategy that we are going to discuss uses combination of MACD and Bollinger Bands to indicate trading opportunities. MACD is used to identify the direction of market (uptrend or downtrend) while Bollinger bands are used to catch only strong trends and avoid unnecessary whipsaws. This is a pure intraday strategy as none of the positions are carried forward. The strategy has a decent success rate in 5 minutes timeframe. Also, the CAGR of 40%~ in 4 years backtesting period is commendable.

Read our article on AFL tutorial here.

Intraday Trend Following Strategy – AFL Overview

Parameter Value
Preferred Time-frame
5 Minutes
Indicators Used MACD (12,26,9), Bollinger Bands (20,3)
Buy Condition
  • MACD Line Crosses the signal line upwards.
  • MACD Histogram is greater than 0.
  • Close is greater than Bollinger Band Top.
Short Condition
  • MACD Line Crosses the signal line downwards.
  • MACD Histogram is less than 0.
  • Close is less than Bollinger Band Bottom.
Sell Condition
  • Same as Short
  • Stop Loss Hit
  • Target met
  • End of Trading Day
Cover Condition
  • Same as Buy
  • Stop Loss Hit
  • Target met
  • End of Trading Day
Stop Loss 0.5%
Targets 3%
Position Size 150 Quantities
Initial Equity 200000
Brokerage 100 per order
Margin 10%

Intraday Trend Following Strategy– AFL Code

//------------------------------------------------------
//
//  Formula Name:    Intraday Trend Following Strategy
//  Author/Uploader: Trading Tuitions
//  E-mail:          support@tradingtuitions.com
//  Website:         www.tradingtuitions.com
//------------------------------------------------------

_SECTION_BEGIN("MACD Intraday Trend Following Strategy"); 

SetTradeDelays( 1, 1, 1, 1 );
SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",2);
SetOption("CommissionAmount",100);
SetOption("AccountMargin",10);
SetOption("RefreshWhenCompleted",True);
SetPositionSize(100,spsPercentOfEquity);
SetOption( "AllowPositionShrinking", True );
SetOption("MaxOpenPositions",10);
BuyPrice=Open;
SellPrice=Open;
ShortPrice=Open;
CoverPrice=Open;

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", colorWhite, styleCandle );

NewDay = (Day()!= Ref(Day(), -1)) OR BarIndex() == 0;  
Plot(NewDay,"",colorlightGrey,styleHistogram|styleDots|styleNoLabel|styleOwnScale);

FirstTradeTime=093000;
SquareOffTime = 151500;

r1 = Param( "Fast avg", 12, 2, 200, 1 );
r2 = Param( "Slow avg", 26, 2, 200, 1 );
r3 = Param( "Signal avg", 9, 2, 200, 1 );
 
ml = MACD(r1, r2);
sl = Signal(r1,r2,r3);
Hist= ml-sl;

Periods = Param("Periods", 20, 10, 100, 10 );
Width = Param("Width", 3, 1, 10, 1 );
Color = ParamColor("Color", colorCycle );
Style = ParamStyle("Style");
Plot( BBandTop( C, Periods, Width ), "BBTop" + _PARAM_VALUES(), Color, Style ); 
Plot( BBandBot( c, Periods, Width ), "BBBot" + _PARAM_VALUES(), Color, Style ); 

 
Buy= Cross(ml , sl) AND Hist>0 AND TimeNum()>= FirstTradeTime AND Close>BBandTop( C, Periods, Width ) AND TimeNum()<SquareOffTime;
Short= Cross( sl, ml) AND hist<0 AND TimeNum()  >= FirstTradeTime AND Close<BBandBot( C, Periods, Width ) and TimeNum()<SquareOffTime;
Sell=short OR TimeNum() >= SquareOffTime;
Cover=buy OR TimeNum() >= SquareOffTime;

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

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

StopLoss=Param("stop",0.5,0.5,3,0.5);
ApplyStop(Type=0,Mode=1,Amount=StopLoss);

Target=Param("Target",3,0.5,5,0.5);
ApplyStop(Type=1,Mode=1,Amount=Target);

printf("\nBuy : " + Buy );  
printf("\nSell : " + Sell );  
printf("\nShort : " + Short );  
printf("\nCover : " + Cover ); 
printf("\nml : " + ml ); 
printf("\nsl : " + sl ); 
printf("\nHist : " + Hist ); 

/* 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();

AFL Screenshot

Intraday Trend Following Strategy

 

Intraday Trend Following Strategy – Backtest Report

Parameter Value
Nifty
Initial Capital 200000
Final Capital 1075018.50
Scrip Name NSE Nifty
Backtest Period 08-Feb-2012 to 21-Nov-2016
Timeframe 5 Minutes
Net Profit % 437.51%
Annual Return % 40.80%
Number of Trades 106
Winning Trade % 67.92%
Average holding Period 24.20 periods
Max consecutive losses 4
Max system % drawdown -13.03%
Max Trade % drawdown -8.13%

Download the detailed backtest report here.

Equity Curve

intraday-trend-following-strategy-equity-curve

Profit Table

This intraday trend following strategy has been profitable on all the years from 2012 to 2016

ntraday-trend-following-strategy-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

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

26 Comments

  1. Dear Admin, i look behind in data yes buy and sell signals can be seen but it is very long signals in 5 min chart….please explain a bit more about this AFL, what kind of trade is good in this AFL intraday positional….

  2. Hello sir, Can you please suggest me some Afls(consistent & back tested) that can be used for years for proprietary trading? It would be great if u can help me in this matter. Thank you.

    • Hi Shailesh,

      All the AFL’s posted in this website are well tested and can be used for live trading. But we would recommend you to perform paper trading for few days to figure out which trading system suits you.

  3. Excellent help resources for traders. I have been trying to create an automated system but Amibroker is not suited for my non-cross over strategies. Do you think I can write in XL with with free live data? Can you please guide?

    • Thanks Sandip. If you can provide us the gist of your strategy, probably we would be able to advise on how to proceed.

      • i have paid good amount of money to desi and “firen” coders but it is very difficult to crite a code effective for skope based indicators. So I now agree to cross over based strategies.
        To start with, it can be simple, a MACD cross, stoch already crossed (“lies over”), histogram favourable and that’s that. In Ami there will be blinking signals sometimes, like a buy comes but then stoch crosses back and the signal vanishes. Can you find a code to prevent that?

        • Hi Sandip,

          The blinking signals usually occur for repainting strategies or the ones which look into future. Most of the AFL’s posted in this site are non-repainting though.

          • Thanks for the answer! My strategy includes possibilities of repainting because of their very nature. It can’t be avoided. But I am looking for a few lines of code where a buy/short arrow will be made to remain painted forever irrespective of signal remaining valid later or not. There were codes I have seen somewhere but can’t remember where.

  4. Feeling excited! A few more questions:
    a) Can I handle time frames from XL? Can I switch to say a 1 day tf from a 5 mins tf and continue to get data stream undisturbed?
    b) Of course the formulas of indicators are to be written-like MACD, MA, etc..Is there a library somewhere?
    c) Can this site take up a project like an automated system with members contributing?
    d) If not, do you know someone who can write the entire program in XL?
    Thanks in advance!

    • Hi Sandip,

      Everything you mentioned is possible to do in a Excel sheet. Right now, we do not cater to individual projects. Please send us a note on your idea and we would try to create an Excel sheet for it and post it in the website.

      • Thanks Admin!! Here we go:
        Time frame 1 day. All Nifty 50 stocks on list. List to be scanned and stocks that match criteria to be traded automatically as per following strategy.
        Entry: (a) MACD 6,13,5 crosses (b) EMA 200 is not passing too close to the candle’s path (at least 0.5% of price away) (c) your MacGinly Dynamic 25,10,40 (user definable) is sloping favorably and is not too far away from bar (say within 0.5%).
        Exit: stop loss to be defined by user and TSL formula. I prefer a formula but if we start I will try to make an XL sheet for you.

        When we write the indicator formulas it will be easy for XL experts. Please test the strategy with Amibroker and you will find it hits big in 90% trades, at least if the target is modest. It will be great if we can add back and forward testing later.
        Eager for your response!

  5. Dear ADmin,

    nice work. Just a small query.. On my charts buy and sll signal arrows are missing. Please help

  6. one clarification when you say 0.5% stoploss and 3% profit you mean on margin or money invested right ? so if nifty is 8800 than stoploss would be 0.5% of margin invest (8800x75x10%) = 330 rs or 4.4 points right ? and target would be3% of (8800x75x10%) = 1980 rs or 26.4 points per lot please guide. i am thank ful to you for your resources and support

  7. Sir, when i backtest it is coming with some different results with the 5min TF, what could be the reason? below is the result,

    Initial capital 200000.00 200000.00 200000.00
    Ending capital 301851.25 239778.50 262072.75
    Net Profit 101851.25 39778.50 62072.75
    Net Profit % 50.93 % 19.89 % 31.04 %
    Exposure % 1.55 % 0.73 % 0.82 %
    Net Risk Adjusted Return % 3289.23 % 2737.54 % 3777.02 %
    Annual Return % 5.96 % 2.58 % 3.87 %
    Risk Adjusted Return % 384.68 % 355.42 % 471.23 %
    Total transaction costs 38800.00 18000.00 20800.00

    ——————————————————————————–

    All trades 194 90 (46.39 %) 104 (53.61 %)
    Avg. Profit/Loss 525.01 441.98 596.85
    Avg. Profit/Loss % 0.05 % 0.03 % 0.06 %
    Avg. Bars Held 24.22 24.54 23.93

    ——————————————————————————–

    Winners 99 (51.03 %) 45 (23.20 %) 54 (27.84 %)
    Total Profit 406589.25 187852.50 218736.75
    Avg. Profit 4106.96 4174.50 4050.68
    Avg. Profit % 0.41 % 0.40 % 0.42 %
    Avg. Bars Held 28.58 31.18 26.41
    Max. Consecutive 8 6 10
    Largest win 23739.25 11410.00 23739.25
    # bars in largest win 3 45 3

    ——————————————————————————–

    Losers 95 (48.97 %) 45 (23.20 %) 50 (25.77 %)
    Total Loss -304738.00 -148074.00 -156664.00
    Avg. Loss -3207.77 -3290.53 -3133.28
    Avg. Loss % -0.33 % -0.35 % -0.32 %
    Avg. Bars Held 19.67 17.91 21.26
    Max. Consecutive 12 8 7
    Largest loss -6905.00 -6905.00 -6869.00
    # bars in largest loss 33 33 11

    ——————————————————————————–

    Max. trade drawdown -14700.00 -14700.00 -11279.40
    Max. trade % drawdown -1.54 % -1.54 % -1.27 %
    Max. system drawdown -62798.75 -51741.55 -35892.45
    Max. system % drawdown -29.35 % -23.57 % -17.75 %
    Recovery Factor 1.62 0.77 1.73
    CAR/MaxDD 0.20 0.11 0.22
    RAR/MaxDD 13.11 15.08 26.55
    Profit Factor 1.33 1.27 1.40
    Payoff Ratio 1.28 1.27 1.29
    Standard Error 17093.46 11619.19 15754.19
    Risk-Reward Ratio 0.83 -0.12 1.00
    Ulcer Index 8.78 12.34 6.30
    Ulcer Performance Index 0.06 -0.23 -0.24
    Sharpe Ratio of trades 2.11 1.34 2.69
    K-Ratio 0.0047 -0.0007 0.0056

  8. What is the significance of Parameter value 20 in Bollinger Band ? Can we synchronise Bollinger band with changing its parameter to 12 instead of 20 ?

Leave a Reply

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