User Name:  
Forgot Password?
Sign up with

Join now (it's free)

User Name:
First Name:
Last Name:

Basic Structure of an Expert Advisor

There are approximately six structural elements in any given Expert Advisor, with five being optional and only one being essential. That’s right, the structure of an EA can be as simple as just knowing the one essential part, though you will eventually want to know them all.

It is easy to see most of the structural pieces when one clicks on the Expert Advisor Wizard (select New / File in MetaEditor, or New button on the toolbar, or pressing Ctrl + N on keyboard).  From the dialog choose Expert Advisor, press Next, type in whatever Name, Author and Link you want. The EA will be saved to the \experts folder under the name chosen.

Next, you can add a few external variables. Click the Add button (this will add a new record to your external variables list), and every record has three fields: Name (double click to set the name of the variable); Type (double click to set the data type); and Initial Value (double click to give your variable initialization value). We just added three variables to our sample BasicTemplate EA:  

Name Type Initial Value
Lots double 0.1
TakeProfit int 250
StopLoss int 150

It is a waste of time to put too many variables here because most should be put in manually. Press the Finish button and an EA template will open a document that looks like what I have below (note: I have altered it somewhat to make it even more useful to see at a glance what the structure is).

Please note: I remember when I was first learning to program in mql4, I was expecting the Expert Advisor Wizard to help me translate and code my trading ideas. Actually it doesn’t do anything but present a hollow shell of a template. It is a very poor wizard indeed! In subsequent articles I’ll present you with more complete templates for you to use and learn from.

//| BasicTemplate.mq4 |
//| Copyright © 2011, Forex Razor |
//| http://www.forexrazor.com |
// Structure #1 (Optional): Directives
#property copyright "Copyright © 2011, ForexRazor.COM"
#property link "http://www.forexrazor.com"

// Structure #2 (Optional): Input parameters

extern double Lots=0.1;
extern int TakeProfit = 250;
extern int StopLoss = 150;
// Structural #3 (Optional): expert initialization function 

int init() {
//---- start up code
return(0); }

// Structure #4 (Optional): expert deinitialization function
int deinit() {
//----  shutdown code
return(0); }

// Structure #5 (Essential): expert start function

int start() {
//---- your trade conditions and orders
return(0); }

// Structure #6 (Optional): Custom Functions

int customfunction1(){
// your custom option conditions
return (0); }

void customfunction2(){
// your custom function conditions

The above is like the bare bones structure of any given EA without the code that gives it life. Each structural element deserves a bit of explanation. 

Structural Element #1 (Optional): Preprocessor Directives

The first items to appear in the MQL template are preprocessor directives, prefaced by a #, and you can see that this template has two: #property copyright, which is the Author Name, and #property link, which is the link you may or may not have entered into the wizard. These are the only two property directives related to Expert Advisors, and they are completely optional to include or not.

Another type of preprocessor directive that you might see in some EAs is the #include directive. An include file consists of functions and source code that will be included in your project when it is compiled, the syntax of which is:

#include < filename.mqh >

A standard include file which you might see is #include stdlib.mqh, which comes with MetaEditor and includes several functions that programmers may find useful.

If you want to use a function that is already compiled in another file, such as another EA, library file or windows dll file, you can import these functions directly into your project using #import directives. For detailed examples of the import directive, you can check out http://docs.mql4.com/basis/preprosessor/import.

Most library files are called with the #import directive. Using preprocessor directives like #include and #import are usually reserved for advanced programmers. I thought I would stick them in here so that you know what they are when when you look under the hood of expert advisors that use them. 

Structural Element #2 (Optional): External and Global Variables

The next section in our code are the external variables, and these can be very useful. 

A variable is like a small box into which you can store things for later use, particularly numbers. The concept is borrowed from mathematics (remember the statement x = 10, where the value of 1 is stored in the variable x). From that point forward, until the value of x is changed, the value of x is 10. All references to x are replaced by the value of 10.

Of course we can declare any variable internally, from different parts of the program, but putting the variable here in this section, and preceding it with word extern allows you to be able to see the variable from the outside, that is, from the Expert Properties dialog of the expert advisor. 

The external variables is where you can put the adjustable parameters of your program, such as your trade settings (lot size, takeprofit, and stoploss) and indicator settings. When you open the Expert Properties dialog for an expert advisor, you are viewing the external variables of that program. 

Notice that we specify an external variable by adding extern in front of the variable. Extern makes sure that the variable will be external, that is, it will appear in the Expert Properties dialog, viewable and adjustable by the user. 

extern int StopLoss = 150;

As I have hinted at, a variable is the basic storage unit of any programming language, holding data necessary for the program to function. Variables must be declared, and in order to declare a variable, you put three parts together:

data type (example: int), space, identifier (example: StopLoss), equal sign, default value (example: 150).  

The data type specifies the type of information the variable holds, such as a number, a text string, a date or a color. For more on variables, see my description of Variables in Basic Concepts

If you don't put extern in front of the variable, the variable still works, it is just internal, that is, not visible in the Expert Properties dialog. The advantage of declaring internal and external variables in this section is that they are global, meaning that is available to any function within the program. As long as the program is running, the global variables and it's values stays in memory and can be referenced by any function in the program. 

Note: Though it is uniform and convenient to declare external and internal variables in this section of the EA, it is not absolutely necessary. You can declare any or all of your internal (though not external) variables from within any function. The small disadvantage is that the variable will only work for that function, not globally across all functions. 

Structural Element #3 (Optional): Expert Initialization Function

 The init() function is optional and can be left out if you are not using it.   

This is the function that runs before any other functions. 

The init() function will start to run:
  1. after program has been attached to chart; 
  2. after client terminal has been started;
  3. after symbol and/or chart period have been changed; 
  4. after program has been recompiled in metatrader
  5. after inputs have been changed from the window of expert; 
  6. after account  has been changed. 
The start() functions runs at first tick, but init() runs immediately after attachment (regardless of incoming ticks). It won't run if there is no connection to the server. It will be called the one time during the cycle of the program and will not be called again. 
Very little code is usually placed within the init() function when it is used. The most common bit of code I see placed within this function are account protection schemes (bits of code to lock the EA to the user's account number), and locking the program to work with specific currency pairs and trade times.  

I usually put my code that auto-defines Point and Slippage values in this area, as you can see here. 

Structural Element #4 (Optional): Expert Deinitialization Function

The deinit () function is also optional, and it can be left out if you are not using it. It is probably unlikely that you will need it in an expert advisor. 

This is the last function the program will call after it is shutdown, and you can put here any removals you want.  

The function is called:
  1. when we complete the work with MetaTrader 4, or when we close the price chart;
  2. when we switch between trading accounts; 
  3. when we change the time period of the schedule; 
  4. when we remove a judge from the price chart; 
  5. when we change the parameters of the expert; 
  6. when we recompile the program in MetaEditor 
Most of the time I have seen deinit() never being used.  

Structural Element #5 (Essential): Expert Start Function

This function is the most important function of the expert advisor, performing the most important work at any time. It is generally where most of your code will go, unless you are putting most of your code in custom functions, and thus it deserves special attention.

It always starts with:
int start() {
and always ends with
return(0); }

In between the start and end lines can be placed all the conditions to open and close your trades, as well as any number of trade procedures and conditions.  

The start() function is run on every tick, and it will continue to be called for each and every tick of data that is received. Think of it as a loop and every time price moves the start function is triggered, and therefore everything we put in the start function will similarly be triggered. The start function is like the Movie Director of the EA. It calls the action and tells the actors and staff what is it they should be doing. It sets up the code and calls to all other functions. 

I have seen many EA's have all the code placed within this function. If you wanted to examine a fully functional EA that contains this one structural element, along with a few external variables, you can open up the MACD Sample.mq4 from within MetaEditor. You can see that the EA writes all its internal variables, indicators and conditions for entry and exit inside the start function. There are no other structural parts besides a few obvious external variables. It is probably one of the most simply written EAs that you will ever see, and that is probably why it was included with every MT4 download. It may not be that profitable, but it is simply and clearly written, helpful for the notice programmer to learn from.  

In the next few articles we will focus mostly on the code placed within the start() function, along with some custom functions.

Structural Element #6 (Optional): Custom Functions

Any other functions that your EA may use should be declared after the start() function.

These custom functions can be called from the start(), init(), or deinit() functions, or from other functions that are called from the main program. The idea behind creating custom functions is to create blocks of code that carry out specific tasks, and then once created, you can call on these specific tasks from within any part of the program. Custom functions thus make things very tidy and convenient.

Some examples of custom functions are:
  • Lot Sizing Function 
  • Order Counting Funtion
  • Order Placement Function 
  • Order Closing Function 
  • Trailing Stop Function
  • Much, much more 
I have seen many programmers use custom functions to power their EA, so that very little code is needed for the start() function. They just plug the custom functions into the start function, and the EA is off and running. 

When you find interesting custom functions from other EAs, you can copy and paste them into your own Ea and call on them from different parts of the program. It is not necessary that you fully understand how all the code within the custom function works, just that it works. You can figure out the nuts and bolts later.  

In future articles I will be detailing a few useful custom functions that one can implement quickly into any EA.

Note: All custom functions will go below the start function. It must go below and NOT in the start function. If it goes in the start function it will confuse the EA, though it will probably not compile correctly anyway. 

An e-mail with your verification code has been sent to your e-mail address. Please access your in-box and use the verification button or verification code to complete your registration.
You already have an account linked with this E-mail (it maybe standard or social login). Please, sign in with it.
Please, provide us your e-mail so we can verify your account.