MQL4 tutorial: My first Expert Advisor

In this MQL4 tutorial you will learn how to programme your own Expert Advisor in Metatrader 4 (MetaEditor to be precise)

Table of Contents

Before we begin with this mql4 tutorial, make sure you understand the following data types. Every variable we use has to be defined with a data type. Here are the most used:

  • int = integer – this is a normal „number“. Example: 1, 15, 521
  • double = a number with decimal points. Example: 1.154, 0.0144, 255.145.
  • string = a word/phrase. example: „BuyOrder“, „OrderSend placed successfully“.
  • bool = either false or true.

You will see soon how to use these.

Chapter 1: My First EA

3 white soldiers EA

Before beginning, please note that after chapter 1 you maybe will not be able to run the EA. Not all brokers work the same way. If it does not work on your broker, please continue reading until the end of chapter 2, where we will make the EA compatible with all brokers.

BThe write your own Expert Advisor you first have to switch to the MetaEditor. You do this by clicking on this MetaEditor icon icon. In the MetaEditor click on New and choose „Expert Advisor“.
In the next window, we write the Expert Advisors Name and the Authors name with his website link. We also want to add our first variables. We add the standard variables that an Expert Advisor needs. We add a TakeProfit, StopLoss, LotSize, Slippage and MagicNumber. All types are int (integer) except the LotSize. The LotSize must have a decimal point in it so you have to define it as a double. You may notice that I have defined the TakeProfit, StopLoss and Slippage a bit high. This is because I am using an 5 Digits Broker. Because the EA will not automatically recognize a 4 or 5 Digits broker, we have to add a function which does this for him. But you will learn this later (in the next MQL4 tutorial). For now, leave it like this. (If you have a 4 Digits Broker, divide these 3 values by 10)

MetaEditor - MQL Wizard

Then you click next and finish and we see that the MetaEditor has generated a file with your predefined variables. You can see 3 areas. The OnInit(), OnDeinit() and the OnTick() area. Quickly explained. All code you write goes to one of these areas. We will put all the code we want to call if we attach the Expert Advisor to the chart into the OnInit() area. The OnDeinit() is executed if we detach the EA. And finally, the area in which we work most, the OnTick() area. The OnTick() function is called every time if we receive a new price (tick) from the broker for the Symbol (Currency Pair) the EA is attached to.

If you compile the EA with F7 and return to your Metatrader, you can already find the EA in the Navigator (Crtl+N). If you try to attach it to a chart and you go to the Inputs tab you can now see our defined variables.

expert advisor inputs

What we do in this mql4 tutorial: We want to learn how to program an Expert Advisor which trade the 3 white soldiers. It’s a simple strategy where the EA opens a buy trade when the last 3 candles were bullish.

Now let’s begin!

We write this in it:

void OnTick()
  {

   if(Close[1] > Open[1] && Close[2] > Open[2] && Close[3] > Open[3])
   {
      //Open Buy Order
   }

  }

For this strategy, we call a predefined variable. The Close[] which is a double (remember from above). The Close[] gives us a close price (example 1.24577) for each bar of the current chart. Close[0] means the current Close price; Close[1] the previous and so on. Same with the Open[], Low[] and High[].
So when you look at the code, this logic should be clear now.
The “//Open Buy Order” is a help for me. I will put here the function to open a buy order. The 2 // means that this line is commented out. The EA will ignore this. It’s only a help for us.

Tip: If you place the cursor on a predefined function/variable and press F1, the MQL4 Reference will open and you can read what this function/variable does!

If you wrote it press F7 to compile the EA and to check if you got some errors!

Now we use the OrderSend function to Send our buy order to the broker. We write:

      if(Close[1] > Open[1] && Close[2] > Open[2] && Close[3] > Open[3])
      {
         //Open Buy Order
         OrderSend(_Symbol,OP_BUY,LotSize,Ask,Slippage,Ask-StopLoss*_Point,Ask+TakeProfit*_Point,"BUY",MagicNumber);
      }

(The OrderSend function like this will not work on ECN Brokers. You will learn how to make it compatible for ECN Brokers in the next tutorial)

Quickly explained the OrderSend function:

  • _Symbol = First we have the enter on which pair the Expert Advisor should open the trade. _Symbol returns the pair on which the EA is attached to.
  • OP_BUY = We want to open a buy order.
  • LotSize = What LotSize should the order have. This is actually the variable we defined at the very beginning in the MQL Wizard.
  • Ask = the current Ask price. (use Bid for a sell order)
  • Slippage = self-explanatory (The value we defined above)
  • StopLoss = This is the StopLoss price. It’s simply the Ask price minus the StopLoss price. Now, remember the StopLoss is an integer (500 pips) the Ask is a price (ex. 1.20521). Now to subtract the StopLoss from the Ask price you have to multiply it times 0.00001 or 0.001 (5 or 3 digit pair). We do this with the predefined variable “_Point”, which is the current symbol point value.
  • TakeProfit = Almost the same like the StopLoss.
  • Comment = the comment that should appear in the Journal if we open a buy.
  • MagicNumer = And finally we enter the MagicNumber. (Defined above)

Press F7 to compile and check the result in the StrategyTester. You will now actually get something like this.

mql4 tutorial - open buy order on every tick

The EA places a buy order on every tick if the 3 last bars where bullish. Not what we want but at least there is something happening 🙂

We have to program a new custom function which lets the EA only have one open trade at once. You have to know: MQL4 has already predefined function like the OrderSend() function. But we can also write our own function, in which we can call other custom or predefined functions. We write them at the very bottom of our file.

So let’s go to the bottom of our file and program a new function called TotalOpenOrders. This function is an integer (int). It returns the value of open trade for this Pair and this MagicNumber. We use our MagicNumber we defined above. The function looks like this:

// Returns the number of total open orders for this Symbol and MagicNumber
int TotalOpenOrders()
{
   int total_orders = 0;

   for(int order = 0; order < OrdersTotal(); order++) 
   {
      if(OrderSelect(order,SELECT_BY_POS,MODE_TRADES)==false) break;

      if(OrderMagicNumber() == MagicNumber && OrderSymbol() == _Symbol)
         {
            total_orders++;
         }
   }

   return(total_orders);
}

Do not forget to call the function in the OnTick area.
Explained: We call our custom function. The function returns the total open trades for this Symbol and this MagicNumber. If the total trades equals to 0, the EA continues with the code inside the brackets.

   if(TotalOpenOrders() == 0)
   { 
      if(Close[1] > Open[1] && Close[2] > Open[2] && Close[3] > Open[3])
      {
         //Open Buy Order
         OrderSend(_Symbol,OP_BUY,LotSize,Ask,Slippage,Ask-StopLoss*_Point,Ask+TakeProfit*_Point),"BUY",MagicNumber);
      }
   }

And if you make a backtest you should have something like this:

MQL4 tutorial: First EA works

Isn’t it amazing? 🙂

Quickly explained the TotalOpenOrders function:
In this function, we have a counter (total_orders), which will at the end of the function return the total open orders. We have a “for loop” which looks at all open order on your account. If the EA finds an order which matched to your Symbol and your MagicNumer, the counter will increase itself my 1 (which is the ++).

But now we still have an issue. If the candle is long the EA open a second buy trade directly after the first buy trade gets closed by the StopLoss or TakeProfit. We have to add a second function. A “IsNewBar” function. This function is a boolean (bool). This function will return a true if a new candle is generated in the Metatrader else it returns a false. This function is self-explanatory so I will not explain how it works in this mql4 tutorial.

Lets put this function right above the TotalOpenOrder function and call it in the OnTick function together with the “TotalOpenOrders() == 0”. It will now look like this and work pretty well.

void OnTick()
  {
//---

   if(TotalOpenOrders() == 0 && IsNewBar() == true)
   { 
      if(Close[1] > Open[1] && Close[2] > Open[2] && Close[3] > Open[3])
      {
         //Open Buy Order
         OrderSend(_Symbol,OP_BUY,LotSize,Ask,Slippage,Ask-StopLoss*_Point,Ask+TakeProfit*_Point,"BUY",MagicNumber);
      }
   }

  }
//+------------------------------------------------------------------+

// Check if there is a new bar
bool IsNewBar()   
{        
      static datetime RegBarTime=0;
      datetime ThisBarTime = Time[0];

      if (ThisBarTime == RegBarTime)
      {
         return(false);
      }
      else
      {
         RegBarTime = ThisBarTime;
         return(true);
      }
}   

// Returns the number of total open orders for this Symbol and MagicNumber
int TotalOpenOrders()
{
   int total_orders = 0;

   for(int order = 0; order < OrdersTotal(); order++) 
   {
      if(OrderSelect(order,SELECT_BY_POS,MODE_TRADES)==false) break;

      if(OrderMagicNumber() == MagicNumber && OrderSymbol() == _Symbol)
         {
            total_orders++;
         }
   }

   return(total_orders);
}

We are finished with the first part of this MQL4 tutorial and you just have learned how to program a simple Expert Advisor. Try now for yourself to add the opposite strategy called 3 black crows (Sell after 3 bearish candles).

In the next mql4 tutorial you will learn how to fix the problem with the 4/5 Digits Broker and how to make it work with an ECN Broker.

This MQL4 tutorial was created on July 14, 2015.

Have questions about this mql4 tutorial? Write a comment or open a topic in the forum (if there is not already an answer for it)

Next Chapter

Download the source code

5/515 ratings

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.