Writing a simple, indicator-based expert advisor for algorithmic trading— 1

Ben Diagi
6 min readSep 1, 2019

--

In my first article, I made an introduction to indicator-based algorithmic trading strategies.

Here’s a recap -

These are the easiest and simplest strategies to implement through algorithmic trading because these strategies do not involve making any predictions or price forecasts. Indicators are mathematical measurements, represented visually on the charts, which indicate the previous nature of the market. Essentially, indicators just show you what is already visible on the charts, it just helps you visualize them using lines, bars, icons etc. Some examples are: Simple Moving Average, Bollinger Bands, Relative Strength Index. I won’t go into these indicators in detail. With indicator based strategies, the trader would gather historical data as far back as possible, and look for recurring indicator based patterns. For Example, a widely popular and very basic indicator strategy is the MA(Moving Average) crossover. This involves buying the market when the short term MA crosses above the long term MA, and selling when the long term MA crosses below the short term MA. Note that indicators form slowly and are purely descriptive hence this is only a reactive strategy. I spent most of the early part of my quantitative analysis career building over 100 indicator based algorithms. I will talk more about the failures and successes in future posts in this series.

What I want to do with this article is walk through the process of coding a simple algorithm for a basic indicator-based strategy. It’s going to be pretty slow-paced; because I hope it could be useful to beginners that are absolutely new to these concepts.

I would be using the popular Moving Average as my choice indicator today. 📈📉

Moving Averages? — Moving averages calculate the arithmetic mean of the price of a forex pair, index, commodity or stock over a number of time periods and plots it as a line on the chart. It is visually used to smooth out price action, by eliminating the noise caused by short-term price volatility.

Moving averages are quantified in periods(days) over which they are measured. A 20-day moving average, for example is the average of price action 20 days before the current price point, at every candle(time instant).

Here’s a screenshot of my H1 EurUsd chart without an MA

EurUsd without MA

Here’s one with a 20-day (period) moving average

As shown here, the moving average is a lagging indicator and it reacts slowly to price. As a general rule, when price action is trading above the MA, the market is in an uptrend, and when price is trading below the MA, the market is in a downtrend. With higher time frames and higher periods for the MA, you get a more accurate representation of market trends. The longer the time period for the moving average, the greater the lag.

You can read more on moving averages here. (Knock yourself out)

The 50-day and 200-day MAs are widely followed by investors and traders, with price breaks above and below these moving averages considered to be important.

This is a 50-day moving average on my EU(EurUsd) chart:

50-day MA represented as a blue line

Here is a 200-day moving average:

50-day MA represented as a red line

As we see here, the 50-day moving average reacts quickly to price action, compared to the 200-day moving average which reacts much slower.

Long term traders sometimes use the 200-day MA, along with other technical analysis methods to determine the direction of market trends.

Here are some of the ways I’ve used MA’s in my algorithmic trading.

  • Support/Resistance: Moving averages are a self-fulfilling prophecy, and prices always revert to mean. This is why moving averages can sometimes be helpful in finding support/resistance points, and if you look well enough, you would find points at which price seems to bounce off moving averages. I have written an algorithm in the past to identify those key points and place trades depending on a couple of other factors.
  • Cross-over: No, not the church service that holds in most Nigerian churches on the night before January 1st every year. I’m talking about those points at which slow moving averages cross fast moving averages and give us trend signals in the market. I have created tons of algorithms for this; in different forms; and that’s what I’m writing about today.

Look what happens when you place both the 50-day and 200-day moving averages on the same chart:

50-day MA and 200-day MA represented on EurUsd H1

Notice that; when the fast 50-day MA(blue) crosses above the slow 200-day MA(red), it signifies that a strong move to the upside(traders lingo) has occurred, and when it crosses below, it signifies that a strong move to the downside has occurred.

I will go through the process of writing an algorithm that trades only based on this basic strategy, and I will share the results on a $10,000 account, simulated from January 2019 till date.

I am going to do this using mql4, a programming language built for the Meta Trader 4 platform, which is based off C++.

First of all, I would create a function that determines when those two MAs cross, but first, I have to get the numerical values of the two MAs.

Using the double datatype, that would be

double 50MA = iMA(Symbol(),60,50,0,MODE_SMA,PRICE_CLOSE,1);

Symbol() — refers to the whatever instrument the chart represents

60 — is the number of minutes. 1 hour = 60 mins

50 — is the MA period. 50 day moving average

0 —this is the MA shift. It’s the amount of offset of the indicator to the chart

MODE_SMA — means that this is a Simple Moving Average

PRICE_CLOSE — means we will be using the MA formula to calculate MA based on the closing price of all the candles, rather than the open, high or low price. Read more about OHLC here.

1 — this is the shift value; which is the number of candles behind the current candle which you want to reference. ‘1’ means that you want to reference the candle just before the candle currently forming.

Now, we have to do the same thing for the 200 MA

double 50MA = iMA(Symbol(),60,50,0,MODE_SMA,PRICE_CLOSE,1);
double 200MA = iMA(Symbol(),60,200,0,MODE_SMA,PRICE_CLOSE,1);

This is going to return the values of the 50 and 200 MA in decimals eg 1.1201

Now, we’ve gotta figure out a way to determine when 50 MA line crosses the 200 MA line. This basically, is when the 50MA is higher than the 200MA now, but was lower than the 200MA a (minute, hour etc) ago.

int CrossUp()
{
double 50MA = iMA(Symbol(),NULL,50,0,MODE_SMA,PRICE_CLOSE,1);
double 200MA = iMA(Symbol(),NULL,200,0,MODE_SMA,PRICE_CLOSE,1);
double 50MAprev = iMA(Symbol(),NULL,50,0,MODE_SMA,PRICE_CLOSE,2);
double 200MAprev = iMA(Symbol(),NULL,200,0,MODE_SMA,PRICE_CLOSE,2);

if( 50MA>200MA && 50MAprev<200MAprev) {return(1);}
else {return(0);}
}

What I’ve done here is simply;

If 50MA is greater than 200MA now, and 50MA was less than 200MA one period ago, then return yes for this CrossUp function.

I’d pause here. I would continue the development process in the next part of this article. ✌️

Ben

--

--

Ben Diagi

I’m a Product Manager & Designer. I write about Product, Design and Finance. In my spare time, I build trading algorithms and create UX prototypes.