How to create algo for Exponential Moving Average Crossover Trading strategy?

MarketSecrets
4 min readJan 10, 2022

Welcome to Episode 15 of Algo Trading Series from MarketSecrets.

In this episode , we are going to learn how to code Exponential Moving Average Crossover Trading strategy.

Let’s get into the set-up.

Condition:

This is a very simple strategy, we will be using Exponential Moving Average crossover to take buying or selling decisions.

Buy: When 2 period Exponential Moving Average crosses above 3 Period Exponential Moving Average

Sell: When 2 period Exponential Moving Average crosses below 3 Period Exponential Moving Average

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

Script:

_SECTION_BEGIN(“Crossover Trading System”);

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

SetOption( “AllowPositionShrinking”, True );

BuyPrice=Open;

SellPrice=Open;

ShortPrice=Open;

CoverPrice=Open;

//Parameters

MALength1 = 2;

MALength2 = 3;

//Buy-Sell Logic

Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 ));

Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) ;

Buy = ExRem( Buy, Sell );

Sell = ExRem( Sell, Buy );

Short = Sell;

Cover = Buy;

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

Plot(ema( C, MALength1 ),”FastEMA”,colorWhite);

Plot(ema( C, MALength2 ),”SlowEMA”,colorBlue);

/* 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 chart title and assign 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.

SetChartOptions(0,chartShowArrows|chartShowDates);

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

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

SetOption( “AllowPositionShrinking”, True );

Next 4 lines are used for assigning the price of buying, selling, shorting and covering.

BuyPrice=Open;

SellPrice=Open;

ShortPrice=Open;

CoverPrice=Open;

Next 2 lines are used to set-up the parameters for Exponential Moving Average.

MALength1 = 2;

MALength2 = 3;

The next part is crucial and represent the Buy & Sell statements.

Buy = Cross(ema( C, MALength1 ),ema( C, MALength2 ));

Sell =Cross( ema( C, MALength2 ), ema( C, MALength1 )) ;

We will Buy: When 2 period Exponential Moving Average crosses above 3 Period Exponential Moving Average

We will Sell: When 2 period Exponential Moving Average crosses below 3 Period Exponential Moving Average

Next 2 lines are used to remove excess buying and selling signals.

Buy = ExRem( Buy, Sell );

Sell = ExRem( Sell, Buy );

Next 2 lines are used for shorting and short covering conditions, which is nothing but selling and buying conditions. This indicates, we will be taking reverse positions whenever we exit a trade.

Short = Sell;

Cover = Buy;

Next 3 lines are used plotting the price and the 2 Exponential moving averages we are using in the charts.

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

Plot(ema( C, MALength1 ),”FastEMA”,colorWhite);

Plot(ema( C, MALength2 ),”SlowEMA”,colorBlue);

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

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 and sell signals using the up and down arrows and also the exponential moving averages.

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 1 hour Timeframe and we are taking only long positions. This generates approximately 17Lakh profits on a capital of 1L in 6 months with annual return of 6000%.

When we execute the backtest of same set-up in the 15 Min Timeframe, this strategy generates approximately 8L profits on a capital of 1L in just 6 months with annual return of 1800%.

Numbers are mind blowing, isn’t it? That’s power of simple strategies, especially in Algo-Trading. 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:

https://youtu.be/MHrwStKM3EI

--

--

MarketSecrets

A full time trader and long-term investor, who loves stock market.