MT5 Expert Advisor Development: Build Your First MQL5 EA (2026)

An Expert Advisor (EA) is a program that runs inside MetaTrader 5 and trades your account by fixed rules. This guide shows how to build your first MT5 EA in MQL5 from an empty file: the structure every EA shares, reading indicators, sizing lots from risk, placing trades with a stop loss and take profit, and backtesting the result in the Strategy Tester. The example is a moving average crossover. It is there to teach the structure, not to be traded as it is.

What you need

  • MetaTrader 5 with a demo account from any broker.
  • MetaEditor, which is installed with MT5. Press F4 in the terminal to open it.
  • Your strategy written as rules. If you cannot state exactly when to enter, where the stop goes and when to exit, the code cannot either.

In MetaEditor choose New, then Expert Advisor (template). The file is saved under MQL5/Experts and appears in the Navigator panel of the terminal after you compile it with F7.

MQL5 and MQL4 are different languages

MT4 EAs are written in MQL4 and do not run on MT5. The syntax looks similar, but order handling is different: MT5 works with positions, orders and deals, and indicators are read through handles and buffers. An MT4 EA has to be ported, not just recompiled.

The structure of every MT5 EA

An EA is built around three event functions:

  • OnInit() runs once when the EA is attached to a chart. Create indicator handles and check inputs here.
  • OnTick() runs on every price tick. This is where the trading logic lives.
  • OnDeinit() runs when the EA is removed. Release indicator handles here.

Step 1: Inputs

Inputs are the settings a user can change without touching the code. Give every EA its own magic number, so it can tell its trades apart from manual trades and from other EAs on the same account.

#include <Trade\Trade.mqh>

input int    FastPeriod   = 20;      // Fast MA period
input int    SlowPeriod   = 50;      // Slow MA period
input double RiskPercent  = 1.0;     // Risk per trade, % of balance
input int    StopPoints   = 300;     // Stop loss in points
input int    TargetPoints = 600;     // Take profit in points
input long   Magic        = 20260501;

CTrade   trade;
int      fastHandle, slowHandle;
datetime lastBarTime = 0;

Step 2: Create indicator handles

In MQL5 you create an indicator once and receive a handle. You then copy values out of its buffer when you need them.

int OnInit()
{
   fastHandle = iMA(_Symbol, _Period, FastPeriod, 0, MODE_SMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, _Period, SlowPeriod, 0, MODE_SMA, PRICE_CLOSE);
   if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
      return(INIT_FAILED);

   trade.SetExpertMagicNumber(Magic);
   return(INIT_SUCCEEDED);
}

void OnDeinit(const int reason)
{
   IndicatorRelease(fastHandle);
   IndicatorRelease(slowHandle);
}

Step 3: Act once per bar, not on every tick

OnTick() can fire many times per second. A strategy based on closed candles should evaluate once, when a new bar opens. Without this check the EA can open several trades on the same signal.

bool IsNewBar()
{
   datetime t = iTime(_Symbol, _Period, 0);
   if(t == lastBarTime) return(false);
   lastBarTime = t;
   return(true);
}

Step 4: Size the lot from risk

A fixed lot size ignores the account balance and the stop distance. Calculate the lot so that a stopped trade loses a fixed percentage of the balance, then round it to what the broker accepts.

double RiskLots(int stopPoints)
{
   double riskMoney = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100.0;
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double tickSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double lossPerLot = stopPoints * _Point / tickSize * tickValue;
   if(lossPerLot <= 0) return(0);

   double step   = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);

   double lots = MathFloor(riskMoney / lossPerLot / step) * step;
   if(lots < minLot) return(0);          // risk too small for this stop
   return(MathMin(lots, maxLot));
}

Step 5: Check for an existing position

bool HasPosition()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      if(PositionGetSymbol(i) == _Symbol &&
         PositionGetInteger(POSITION_MAGIC) == Magic)
         return(true);
   }
   return(false);
}

Step 6: The trading logic

Read the last two closed bars from each moving average, detect a cross, and open a trade with the stop loss and take profit attached. The CTrade class from the standard library handles the order request for you.

void OnTick()
{
   if(!IsNewBar()) return;
   if(HasPosition()) return;

   double fast[], slow[];
   ArraySetAsSeries(fast, true);
   ArraySetAsSeries(slow, true);
   // start at index 1: the last closed bar, not the bar still forming
   if(CopyBuffer(fastHandle, 0, 1, 2, fast) < 2) return;
   if(CopyBuffer(slowHandle, 0, 1, 2, slow) < 2) return;

   bool crossUp   = fast[1] <= slow[1] && fast[0] > slow[0];
   bool crossDown = fast[1] >= slow[1] && fast[0] < slow[0];

   double lots = RiskLots(StopPoints);
   if(lots <= 0) return;

   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

   if(crossUp)
   {
      double sl = NormalizeDouble(ask - StopPoints * _Point, _Digits);
      double tp = NormalizeDouble(ask + TargetPoints * _Point, _Digits);
      if(!trade.Buy(lots, _Symbol, ask, sl, tp))
         Print("Buy failed: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());
   }
   else if(crossDown)
   {
      double sl = NormalizeDouble(bid + StopPoints * _Point, _Digits);
      double tp = NormalizeDouble(bid - TargetPoints * _Point, _Digits);
      if(!trade.Sell(lots, _Symbol, bid, sl, tp))
         Print("Sell failed: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());
   }
}

Put the code from the steps together in one file, compile it, and drag the EA onto a chart of a demo account. Turn on the Algo Trading button in the toolbar, otherwise the EA is not allowed to trade.

Backtest it in the Strategy Tester

Open the Strategy Tester with Ctrl+R, choose the EA, symbol, timeframe and date range, and run it. A few settings decide whether the result means anything:

  • Modelling. Use "Every tick based on real ticks" for the final test. "Open prices only" is fast and fine for a first look at a bar-close strategy, but it hides intrabar behaviour.
  • Spread and commission. Test with a realistic spread and your broker's commission. Many strategies that look good with zero costs lose money with real ones.
  • Enough trades. A result from 20 trades says very little. Test over several years and different market conditions.
  • Out-of-sample data. If you optimise inputs, keep part of the history aside and test the chosen settings on data the optimiser never saw. Settings that only work on the data they were tuned on are curve fitted.

Read the drawdown and the longest losing streak, not only the profit. Those tell you whether you could actually live with the EA.

Prop firm rules: daily loss and drawdown

If you trade a prop firm challenge, the EA should enforce the firm's limits itself. The usual approach is to record the account equity at the start of the day and stop trading when the loss for the day reaches your limit.

input double MaxDailyLossPercent = 4.0;
double dayStartEquity = 0;
int    dayOfYear = -1;

bool DailyLossHit()
{
   MqlDateTime now;
   TimeToStruct(TimeCurrent(), now);
   if(now.day_of_year != dayOfYear)
   {
      dayOfYear = now.day_of_year;
      dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
   }
   double loss = dayStartEquity - AccountInfoDouble(ACCOUNT_EQUITY);
   return(loss >= dayStartEquity * MaxDailyLossPercent / 100.0);
}

Call it at the top of OnTick() and return when it is true. Check how your firm defines the day and the loss, because the reset time and whether floating losses count differ between firms.

Common MT5 trade errors

  • 10016, invalid stops. The stop loss or take profit is too close to the price or on the wrong side. Check SYMBOL_TRADE_STOPS_LEVEL and normalise prices to _Digits.
  • 10014, invalid volume. The lot size is below the minimum, above the maximum or not a multiple of the volume step.
  • 10019, not enough money. The margin is not sufficient for that lot size.
  • 10027, autotrading disabled. The Algo Trading button is off in the terminal.
  • 10018, market closed. The symbol is outside its trading session.
  • 10004, requote. The price moved before the order was accepted. Retry with a fresh price.

Always print the return code when a trade fails. The Experts and Journal tabs in the terminal are the first place to look when an EA does nothing.

Going live

  1. Run the EA on a demo account for a few weeks and compare its trades with the backtest for the same period.
  2. Check symbol names on your live broker. Suffixes such as EURUSD.m, different digits and different minimum stop distances are common reasons an EA behaves differently.
  3. Start live with the smallest lot size.
  4. Run MT5 on a VPS so the EA keeps working when your computer is off.

Frequently asked questions

Can an MT5 EA trade any strategy?

Any strategy that can be written as exact rules. Discretionary decisions such as "the trend looks weak" have to be turned into a measurable condition first.

Can I convert my MT4 EA to MT5?

Yes, but it is a rewrite of the order handling and indicator code, not a simple conversion. You need the .mq4 source file.

Can I edit an EA I bought?

Only if you have the .mq5 source code. A compiled .ex5 file cannot be edited.

Does a good backtest mean the EA will be profitable?

No. A backtest shows how the rules behaved on past data under the tester's assumptions. Live spreads, slippage and changing markets can give different results.

Want it built for you?

If you have a strategy and want it coded, tested and delivered with full source code, see MT5 Expert Advisor (EA) development. If your strategy already exists on TradingView, see Pine Script to MQL5 conversion.

This article is for education. It is not financial advice, and no trading system is guaranteed to be profitable.