Strategy Design: The Setup

Trend trading strategies have always been the favorite of all serious traders, and the king of the trend trading indicators has always been the moving average. There is probably more money being traded today using moving averages than with all other technical indicators combined. They have enjoyed such popularity because they provide the clearest method to identify a trend. They show the direction of the trend and then smooth out or dampen its volatility. There are different ways of trading the moving average, but we are going to work with the most popular of them all: the Dual MA Crossover. 

The Dual MA Crossover consists of a longer-term average that serves to define the trend, and a shorter-term average that gives trading signals as it crosses the longer-term average. For instance, in the popular 20-200 MACross (called the “Golden Cross” because of its huge significance, at least in the world of stocks), trading signals are given when the faster 20-period MA crosses over/under the longer 200 period moving average. 

Example of 20-200 MACross on EUR/USD Daily chart. 

You can see in the example above that the red sell arrow initiated on April 19, 2010 at 1.3485,  seemed to detect and capture the huge fall right up to the blue arrow on June 18 at 1.2385, for 1100 pips profit.  More recently, the blue arrow initiated on July 1, 2010 at 1.2500 seemed to detect and capture the run up to the red arrow on August 12, 2010 at 1.2832, for 330 pips profit. It seems that there is promise in this classic indicator setup. I am aware that I might be just noticing the hits and ignoring the misses, but the only way to test to see if the dual MA crossover is a valid indicator for entries and exits would be to convert it into an EA that can be backtested and statistically evaluated.  

Our initial idea, then, is to code the entry conditions of the 20-200 period MACross,  but instead of testing it on the higher daily timeframe, as it was originally intended, we are going to test on the H4 timeframe. We are hoping to retrieve a more reasonable trade sample size with on the H4. We will convert opposite entries into exits in order to make it a simple stop and reverse system–which is the best method for testing the strength of the entry method. A good entry method, flipped around so that opposite entries become exits, should also work sufficiently well as an exit method. 

Entry Conditions: 

If the short SMA line crosses above the long SMAbuy (long). 
If the short SMA line crosses below the long SMAsell (short). 

We will open one order at the same time. 

Exit Conditions: 

If the short SMA line crosses below the long SMA, Close (Buy)
If the short SMA line crosses above the long SMA, Close (Short)

In addition, we will work with a 200-pip stop loss, at least for now, reserving the play of other types of stops in the exits article.

With MT4, there is often more than way of creating an EA for the exact same conditions, and so I was prepared to try two different methods.  

Method#1: Current Line Greater Than / Less Than Previous Line

The standard way of coding a moving average crossover is to indicate two sets of variables and conditions: The FastMA relationship (greater than / less than) to SlowMA on the current bar and the FastMA relationship to SlowMA on previous bar.

Example of variable definitions: 

Double Current = 1; 

double FastMACurrent = iMA(NULL, 0, 9, 0, 0, 0, Current+0);
double FastMAPrevious = iMA(NULL, 0, 9, 0,0,0, Current+1);
double SlowMACurrent = iMA(NULL, 0, 18, 0,0,0, Current + 0);
double SlowMAPrevious = iMA(NULL, 0, 18,0,0,0, Current + 1);

Note: for a handy reference on the parameters of the iMA (Moving Average), please go here: http://docs.mql4.com/indicators/iMA

What differentiates a FastMACurrent from the FastMAPrevious is not the variable name I assigned to each (I just chose these names to help me remember which moving averages I am dealing with); it is the last parameter of the iMA. This last parameter called “shift” indicates the current bar with 0, the previous bar with 1, two bars back from current with 2, etc. I created an outside variable called Current =1, and added this to the shift number to allow me to work with the idea that my current is really the previous, and my previous is really the previous to that. Hint: It is more effective to start with previous bars. To start with current bars only would be to invite too many instant opening and closing trades within the same bar. 

In my setup, I will reference these variables thus for the entry conditions:  

int signal=0;

if(FastMACurrent > SlowMACurrent && FastMAPrevious < SlowMAPrevious) signal=1; // Buy

if(FastMACurrent < SlowMACurrent && FastMAPrevious > SlowMAPrevious) signal=2;// Sell

For the buy signal, you can see that I needed to indicate that fast moving average of current bar had to be greater than slow moving average of the current bar. That condition with the current bar makes sense.

Why, then, did I also have to indicate that the second condition, that the fast moving average of previous bar had to be less than the slow moving average of previous bar? 

If I did not indicate the second condition, and used only the current Ma relationship for a buy signal -- example, if ( FastMACurrent > SlowMACurrent)—I would be buying positions continuously when the current fast moving average is above the slow moving average. However, I do not want continuous entry: I want to enter on the moment of crossover. Since there is no native crossover function in MT4, I have to create a workaround: I had to create a second condition that states that I cannot enter when fast MA is currently above slow MA unless fast MA was previously below the slow MA.   

Note:  In Tradestation’s EasyLanguage you use a resident function called “cross over” that saves this extra step; you just need to say, “if AverageFC (C,20) cross over AverageFC (C,20) then buy”. However, in MT4, it is not as simple. You do not have the convenience of a “cross over” function unless you create one yourself (CodersGuru did, see method#2). Instead, you must spell out the procedure of a crossover with two conditions:  if MA (20) > MA (200) for current bar, and MA (20) < MA (200) for past bar, then buy. 

That is about all for Method1 of the MA Crossover. 

All we need now to do is insert our setup parameters into an EA. 

For my purposes, I am going to insert my code into the open source template EA created by Funyoo (this generous coder creates beautiful open source EA templates with lots of functionality), and I am going to call it MACrossover_Method1_v1.  

You can see where I have inserted my code above here. 

Download the EA and pop open the hood to see what it looks like. 

Preliminary Backtest With MACross_Method1_v1

I am planning to test my newly minted EA on the EUR/USD H4 timeframe. Because this is an MA Crossover, the best signals are often generated from the longer timeframes (shorter timeframes generate more false signals). I am choosing a backtesting period from 01.01.2000 to 08.20.2010, more than 10 years, in order, in order to see how the system performed over the long run, under a multitude of different market scenarios.   

As you can see, the EA looks promising. It executed 138 trades during the last 10 years, and produced a 3:1 risk reward ratio ($6000 net profit compared to $1900 max DD).  I think I can be comfortable trading with that. At least it can make money in trending times. 

For now, I want to turn your attention to a second method of creating a setup for an MA Crossover. 

Method#2: MA Cross Condition Assisted By CoderGuru’s Cross Function

Earlier in the article, I discussed how Tradestation had a native function called “cross over” to help express your crossover condition (example, “if AverageFC (C,9) cross over AverageFC (C,18) then buy”). Well, a person named CodersGuru created such a function for MT4 and wrote about it in his online MT4 development course, Lesson 14 (Part 2).  The course itself is worth reading.  

The code looks like this: 

int Crossed (double line1 , double line2)

static int last_direction = 0;
static int current_direction = 0;

if(line1 > line2)current_direction = 1; //up

if(line1 < line2)current_direction = 2; //down

if(last_direction == 0) //first use
last_direction = current_direction;

if(current_direction != last_direction) //changed 
last_direction = current_direction;
return (last_direction);
return (0); //not changed

I will not bother trying to explain this function when he does a better job at it, but suffice it to say, this code helps to create an alternative method of coding a crossover, and in his particular example of it, it is a MA Crossover. You no longer have to indicate that the current line must be greater than/less than previous line. Instead, the function watches for the crossover of the two lines and indicates the crossing direction.   

He makes a note saying “you can use this function in your coming EA to monitor any two lines and the crossing direction.” This is intriguing. I can imagine many possibilities for a two-line crossover.  

Once you put that block of code somewhere in your EA, perhaps above your start section, you can then call it from your setup. Here I have coded a setup to work with that function. 

  int signal=0;      
  FastMA = iMA(NULL,0,9,0,0,0,1);
  SlowMA =iMA(NULL,0,18,0,0,1);
   static int isCrossed  = 0;
   isCrossed = Crossed (FastMA,SlowMA);
      )signal=2;// Sell
      )signal=1; // Buy

Notice how I did not need to spell out the past and present conditions in order to indicate that a crossover took place. The Crossed function, called by the isCrossed code, indicates the onetime crossover of the FastMA over the SlowMA in the upward or downward direction.
CodersGuru's crossover function was adopted and modified by FireDave and others to create the Universal MA Cross EA, and you can read about it and download its many versions in the forex-tsd forum thread. Earlier versions of the Universal MA Cross EA employed the standard dual MA crossover, and later versions incorporated Codersguru’s version. I have experimented with the Universal MA Cross EA, and I did like it for a time. I encourage you to test out the different versions to see for yourself.  

I am going to adopt CodersGuru’s original crossover function idea and place it in the more functional Funyoo EA template, and call it MACross_Method2_v1.  

You can download it, open it up, and check it out. 

Now let us see how it runs. 

Preliminary Backtest With MACross_Method2_v1

Just like the backtest with MACross_Method1_v1, I am going to conduct the initial backtest on the 10 year period from 01.01.2000 to 08.20.2010: 

Though the total net result of $6000 looks very similar to method1, there are some striking differences: here you have 80 trades versus method1's 138, profit factor is 1.90 versus 1.51. Even maximal drawdown is $300 less. It is overall a better strategy, but not by much.  

What accounts for the difference in performance? After some playing around with the code a bit more, I discovered that difference in performance lies in how they open their trades. The codersguru function, by default, opens the trade at the open of next bar, whereas the standard coding method by default opens the trade intrabar. Whenever you open trades intrabar you produce more crossover instances. Conveniently enough, Funyoo's template has a switch called enteronopenbar = true/false, and when it is switched to true, meaning that method1 can also generate its trades at open of next bar, method1 generates the same performance as method2. 

The difference in coding is thus an aesthetic and not substantive difference, for the performances are the same when both are setup to trade at open of next bar. 


I had intended to create a simple moving average setup for an EA, and yet the more I looked into, the more textured it became. I discovered that there is not just one standard way of coding a simple MA Cross setup but two ways: one standard and one alternative. The standard way calls for conjoining of the present and past conditions prior to entry. The fast MA must be currently above the slow MA, and it must have been previously below it. This is the most often used method of indicating

Từ khóa

Đăng ký tài khoản

Log In Your Account