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

One thing at the very beginning: The Expert Advisor you will learn to programme in this MQL4 tutorial is not enough stable to trade it on a live account. Do never ever run this EA on a live account unless you want to lose your money!! To make it ready for a live account you have to include a lot more security functions. But this MQL4 tutorial will at least allow you to easily test some basic strategies and you can download the source code at the bottom. Have fun 🙂

Before we begin with this mql4 tutorial, make sure you understand the follow 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.

The 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 noticed 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 programme 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 where bullish.

Now lets 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. Its 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 programme 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 programme a new function calles 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 look 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 programme a simple Expert Advisor. Try now for your self 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

22 thoughts on “MQL4 tutorial: My first Expert Advisor

  1. Gud tut to make me get started..i hwe a question to ask with the line “if(OrderSelect(order,SELECT_BY_POS,MODE_TRADES)==false) ”

    why hwe 2 taken as “FALSE”…i didnt understood this..hw does it impact the programm code taking false & true??

  2. Hi Yannick,

    I want to start learning to program my own EA’s.
    There are a load of programs that work with a drag and drop GUI. Some I will use for sure, but I always was interested in learning to code so this might be the right time.

    My Question: should I immediately start learning to program with MQL4 or should I first learn a specific computer programming language? Like C# or C++ etc.
    My highly skilled programmer friend once told me I got the skills to become a very talented programmer in just 2 months time. But should I start with MQL4 language? Or something else? …. Why?

    I hope you can give me good and detailed answer about what steps would be the most wise for me.

    And I would also like to know what the major differences are between MQL4 and MQL5 and which one I should focus on.
    I can google it, but I prefer hearing from an experienced mql programmer.

    Regards,

    Greatness

    1. You can immediately learn mql4 without knowing any other language. But since mql and c++ are very similar and there are much more tutorials for c++ on the web, it would be a advantageous to first learn c++. If you know c++ and you make my tutorial, you will immediately understand everything I wrote.

      Nowadays mql4 and mql5 are very similar. Some small things are quite different, but they are actually pretty much the same. But here again, I advise to first learn mql4 because most users use MT4 and you will find much more tutorials and help online than you would get with mql5.

      So, learn the basics of C++ (youtube tutorial etc.), then mql4 then mql5.

      Hope this helps 🙂

  3. Great guide Yannick. I though you used Molanis Strategy Builder in part to build your EAs.

  4. hi! i tried the strategy but stoploss and take profit not working. can you please fix and also add trailing stop.
    Thanks

      1. Thank you for your reply. Please can you show me how yo modify code such that new trades will be open when ever a new signal is valid even if there is an existing trade, for instance if there is a buy trade and a sell signal is generated ea should open sell even if a buy trade is still open. when another buy signal is generated, ea should buy without closing the two existing trades. in this way more trades could be added to existing trades. trailing stop, stop loss or take profit will be used to close trades.

        Thank you

  5. Hi

    Martingale i not advised for safety of your money, jut curious to know if i wanted to implement martigale in this chapter one tutorial what should be added?

    1. You have to set an initial LotSize like 0.1 Lot. Each time the EA opens a trade he would have to check if the last closed trade (same MagicNumber and symbol) was a looser. If it was a looser, the lotsize of the next trade will be the lotsize of the last trade multiplied by X.

      1. If you will not mind can you assist me the code of checking whether the trade finished as a loser or winner

  6. Hi Yannick,
    Need help. Need an ea that places a trade at each candle, buy for a bull candle, sell for a bear candle.
    Exits all open trades when the candle changes direction.
    Example, if the trend was up and we buy at several times, we exit when a bear candle appears, and enter new sell.
    Patrick

    1. After this tutorial you should be able to program your entry strategy.
      I will explain how you can close trades in a next chapter. If you can’t wait, I’m sure you’ll find the code somewhere online.

Leave a Reply

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