How to create algo for MACD Intraday Trend Following strategy?

How to create algo for MACD Intraday Trend Following strategy?

Welcome to Episode 17 of Algo Trading Series from MarketSecrets.

In this episode , we are going to learn how to code MACD Intraday Trend Following Strategy.

Let’s get into the set-up.

Condition:

This is a slightly complicated strategy, we will be using Bollinger Band in combination with MACD to take buying, selling, shorting and short covering decisions.

Buy: When MACD line crosses signal line, with histogram above 0 and closing price of the candle is above Top Bollinger Band.

Short: When signal line crosses MACD line, with histogram below 0 and closing price of the candle is below Bottom Bollinger Band.

Sell: When we get Short signal

Cover: When we get Buy signal

Let’s begin with the script set-up now.

Script:

_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);

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

 

First of the script is self explanatory – these are used for setting up the values to the parameters to be used for backtesting , which we have already discussed in detail in the previous episodes. So I’m skipping this part.

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);

 

Next 4 lines are used to assign the buying, selling, shorting and short covering prices whenever buying, selling, shorting and short covering are triggered by the system. We will use the open price of the candle to enter and exit the trades.

BuyPrice=Open;

SellPrice=Open;

ShortPrice=Open;

CoverPrice=Open;

Next 3 lines are used for setting up the chart and plotting the chart title and price candles.

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 );

 

Next 2 lines are used to plot every alternate day in different color shades.

NewDay = (Day()!= Ref(Day(), -1)) OR BarIndex() == 0;

Plot(NewDay,””,colorlightGrey,styleHistogram|styleDots|styleNoLabel|styleOwnScale);

Next 2 lines are used to set the time limit for the trades. We will take the trades only after 9.30 and will square off all the trades by 3.15.

FirstTradeTime=093000;

SquareOffTime = 151500;

 

Next 6 lines are used for setting up the parameters for MACD and signal line. This is typical MACD set-up we discussed using 2 Moving Averages and a signal line. We are also calculating the histogram.

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;

Next 6 lines are used for assigning parameters for Bollinger Band. We will be using Periods and Width to create the top and bottom Bollinger bands and plotting the same in the chart.

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 );

 

The next part is crucial and we will be using Bollinger Band and MACD to take buying, selling, shorting and short covering decisions.

Buy: When MACD line crosses signal line, with histogram above 0 and current time is within the allowable trade time of 9.30 & 3.15 and closing price of the candle is above Top Bollinger Band.

Short: When signal line crosses MACD line, with histogram below 0 and current time is within the allowable trade time of 9.30 & 3.15 and closing price of the candle is below Bottom Bollinger Band.

Sell: When we get Short signal or if time crosses 3.15

Cover: When we get Buy signal or if time crosses 3.15

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;

 

Next 4 lines are used to remove excess buying , selling, shorting and short covering signals.

Buy=ExRem(Buy,Sell);

Sell=ExRem(Sell,Buy);

Short=ExRem(Short,Cover);

Cover=ExRem(Cover,Short);

Next part is used for printing the buying , selling, shorting and short covering prices and also the value of MACD, MACD Signal line and Histogram value.

printf(“\nBuy : ” + Buy );

printf(“\nSell : ” + Sell );

printf(“\nShort : ” + Short );

printf(“\nCover : ” + Cover );

printf(“\nml : ” + ml );

printf(“\nsl : ” + sl );

printf(“\nHist : ” + Hist );

 

Next Part is used to plot the shapes like up and down arrow in the chart, whenever there is a buy, sell, shorting and short covering signals.

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);

If you look at the charts, you can spot the buy, sell, shorting and short covering signals using the up and down arrows.

 

You can also run a backtest on this code, I am running the backtest now on Nifty and BankNifty for 6 months. This is being executed on 15 minute Timeframe and we are taking only long positions. This generates approximately 11K profits on a capital of 1L in 6 months with annual return of 10%.

You can play around the parameters we have used in this strategy to optimize the returns further. Do give this a try and let us know in case of any issues.

For more details and examples, checkout the video:

 

Leave a Reply

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

error: Content is protected !!