What is an Expert Advisor?

An Expert Advisor (EA) is a program that trades automatically inside the MetaTrader platform. You attach it to a chart, and it reads prices, decides when to enter and exit, and sends orders to the broker without a human clicking buttons. EAs are written in MQL4 for MetaTrader 4 (MT4) or MQL5 for MetaTrader 5 (MT5).

An Expert Advisor follows fixed rules. The same market data always produces the same decision. That makes an EA easy to test on historical data, and it removes emotional mistakes like moving a stop loss or skipping a planned trade.

An Expert Advisor is written in MetaEditor, the code editor that ships with MetaTrader. The source file (.mq4 or .mq5) is compiled into an executable file (.ex4 or .ex5). Only the compiled file is needed to run the EA, which is also how EAs are sold on the MQL5 Market.

How does an Expert Advisor run?

An Expert Advisor is event-driven. The terminal calls special functions, called event handlers, when something happens. You do not write a main loop. You fill in the handlers you need.

The three core event handlers are:

  • OnInit() runs once when the EA is attached to a chart, when settings change, or when the terminal starts. Use it to check inputs and set up objects.
  • OnTick() runs every time a new price (a tick) arrives for the chart's symbol. This is where the trading logic lives.
  • OnDeinit(const int reason) runs once when the EA is removed, the chart closes or the terminal shuts down. Use it to clean up.

MQL5 adds more handlers, such as OnTimer() for scheduled work, OnTradeTransaction() for reacting to fills and order changes, and OnTester() for a custom score in the Strategy Tester. Most simple EAs only need the three core handlers.

A minimal MQL5 Expert Advisor

The skeleton below uses the standard CTrade class from Trade/Trade.mqh. On each new bar it opens one buy position with a stop loss and take profit if none is open. It is a structure example, not a trading strategy.

#include <Trade/Trade.mqh>

input double InpLots       = 0.10;      // fixed lot size
input int    InpStopPoints = 300;       // stop loss distance in points
input int    InpTakePoints = 600;       // take profit distance in points
input long   InpMagic      = 20260924;  // tags this EA's trades

CTrade   trade;
datetime lastBarTime = 0;

int OnInit()
{
   trade.SetExpertMagicNumber(InpMagic);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   Print("EA removed, reason code: ", reason);
}

void OnTick()
{
   datetime barTime = iTime(_Symbol, _Period, 0);
   if(barTime == lastBarTime)
      return;                            // act once per new bar
   lastBarTime = barTime;

   if(PositionSelect(_Symbol))
      return;                            // one position at a time

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double sl  = NormalizeDouble(ask - InpStopPoints * _Point, _Digits);
   double tp  = NormalizeDouble(ask + InpTakePoints * _Point, _Digits);

   if(!trade.Buy(InpLots, _Symbol, ask, sl, tp, "skeleton"))
      Print("Buy failed, retcode: ", trade.ResultRetcode());
}

The magic number is an ID stamped on every trade the EA opens. It lets the EA tell its own trades apart from manual trades or trades from other EAs on the same account.

What is the difference between an EA, an indicator and a script?

An Expert Advisor, an indicator and a script are all MQL programs, but each has a different job. Only an EA runs continuously and trades.

  • An indicator calculates values and draws them on the chart, such as a moving average. Its main handler is OnCalculate(). Indicators cannot send trade orders.
  • A script runs once, from OnStart(), and then stops. It is useful for one-off jobs, such as closing all positions.
  • An Expert Advisor stays attached to the chart, reacts to every tick and can open, modify and close trades.

EAs often read indicator values. In MQL5, an EA creates an indicator handle (for example with iMA()) in OnInit() and reads its values with CopyBuffer() in OnTick().

How is MQL4 different from MQL5?

MQL4 and MQL5 look similar, since both use C++-style syntax. The biggest difference is the trade model, which changes how every EA handles orders.

The order model

In MT4, everything is an order. A pending order and an open trade are both orders with a ticket number. An MT4 EA loops through OrdersTotal(), calls OrderSelect(), and opens trades with OrderSend().

In MT5, there are three separate things:

  • An order is a request to buy or sell, such as a pending buy stop.
  • A deal is the actual fill that happens when an order executes.
  • A position is the resulting open exposure on a symbol.

An MT5 EA checks open trades with PositionsTotal() and PositionSelect(), and usually sends requests through the CTrade class instead of filling in a raw MqlTradeRequest structure by hand.

Netting vs hedging accounts

MT5 accounts use one of two position modes. On a netting account, there is only one position per symbol. A new buy on a symbol with an open sell reduces or reverses that position. On a hedging account, each trade is a separate position, so you can hold a buy and a sell on the same symbol, just like MT4.

An MT5 EA should read the mode with AccountInfoInteger(ACCOUNT_MARGIN_MODE) if its logic depends on it. Code written for a hedging account can behave very differently on a netting account.

The Strategy Tester

The MT4 Strategy Tester runs one symbol at a time on a single CPU thread. The MT5 Strategy Tester is multi-threaded, can use local and remote testing agents, can model trades on real tick data from the broker, and can test an EA that trades several symbols in the same run. For a deeper look, see how to backtest an EA in the MT5 Strategy Tester.

MT4 vs MT5: side-by-side comparison

Feature MT4 (MQL4) MT5 (MQL5)
Trade model Orders only Orders, deals and positions
Position modes Hedging only Netting or hedging (set by broker account)
Opening a trade OrderSend() CTrade::Buy() / CTrade::Sell() or OrderSend() with MqlTradeRequest
Standard trade library None built in Trade/Trade.mqh (CTrade, CPositionInfo, and more)
Timeframes 9 21
Strategy Tester Single symbol, single thread Multi-symbol, multi-threaded, real ticks
Compiled file .ex4 .ex5
Runs the other's EAs No No

Should you build a new EA on MT4 or MT5?

For a new Expert Advisor, MT5 is usually the better choice. MQL5 has a cleaner trade library, a stronger tester and more active development. MT4 still makes sense if a broker or client only offers MT4 accounts.

As an example of an MT5 EA, Sigma7 Gold Swing trades gold (XAUUSD) with resting stop orders. It places a hard stop loss and take profit on every trade, moves the stop to break-even once in profit, and uses no grid, martingale or averaging. It also sizes each position from risk, which is covered in risk-based position sizing in MQL5.

Summary

An Expert Advisor is an MQL program that runs on a MetaTrader chart and trades by itself through the OnInit, OnTick and OnDeinit event handlers. MT4 uses a simple order list, while MT5 splits trading into orders, deals and positions and adds netting accounts, CTrade and a much stronger Strategy Tester. If you need an EA built or ported from MQL4 to MQL5, see the MT4/MT5 Expert Advisor development service.

Need this built? See MT4 / MT5 Expert Advisors or get in touch.

FAQ

Questions about this topic

Can an MT4 Expert Advisor run on MT5?

No. MT4 EAs are compiled to .ex4 files for MQL4, and MT5 only runs .ex5 files compiled from MQL5. The indicator math often ports easily, but the order handling must be rewritten for the MT5 trade model.

Do I need to keep my computer on for an EA to trade?

Yes. An EA only runs while the MetaTrader terminal is open and connected. Many traders run the terminal on a virtual private server (VPS) so the EA keeps working 24 hours a day.

Is MT5 better than MT4 for building a new EA?

For new work, MT5 is usually the better choice. MQL5 has a standard trade library, a faster multi-threaded Strategy Tester with real tick data, and support for both netting and hedging accounts.

Why is my EA attached to the chart but not trading?

The most common cause is that the Algo Trading button in MT5 (AutoTrading in MT4) is switched off, or "Allow Algo Trading" is not ticked in the EA's settings. Check the Experts and Journal tabs for error messages.

Keep reading

More on MT4 / MT5 Expert Advisors

Have a bot, a backend or a strategy in mind?

Tell me what you want to build and where you are with it. Send a few lines about the project and I’ll reply with questions and next steps.

Rajshahi, Bangladesh