How to Create an Expert Advisor: No-Code to MQL5

0
11
How to Create an Expert Advisor: No-Code to MQL5: title card from ForexMT4Indicators.com

Last updated: November 18, 2026 · By: Tim Morris

To create an expert advisor (EA), write your trading rules as an exact spec, then build it with the MQL5 Wizard or a visual builder, your own MQL5 or MQL4 code, or a developer. Compile it in MetaEditor, test it in the Strategy Tester, demo it for at least four weeks, then go live.

  1. Write the EA spec: every rule as a number.
  2. Choose a build route: no-code, your own code, or a developer.
  3. Build or code the EA (.mq5 for MT5, .mq4 for MT4).
  4. Compile it in MetaEditor (F7) to 0 errors, 0 warnings.
  5. Backtest it in the Strategy Tester (Ctrl+R) with “Every tick based on real ticks” modelling over several years, then demo it for at least four weeks.
  6. Go live at the smallest size, on a VPS.
From trading idea to live expert advisorSix numbered stage cards in two rows: write the spec, choose a build route, build or code the EA, compile it in MetaEditor, backtest it in the Strategy Tester and then demo it for at least four weeks, then go live small, with a strip saying that a failed step means going back, fixing it and repeating from compile.From trading idea to live EASix steps, in order. Each one has to pass before the next one starts.1SpecWrite the rules firstEvery rule as a number:entry, exit, stop, size,hours, max trades, news2RoutePick how to buildMQL5 Wizard, visualbuilder, your own code,or a developer3BuildCode or generate itWizard output, builderexport, or your own.mq5 or .mq4 code4CompileF7 in MetaEditorErrors tab must read0 errors, and fix everywarning too5TestTester, then demoReal-tick mode, severalyears, then at least4 weeks on demo6LiveStart smallAlgo Trading on,smallest size first,VPS keeps it runningA step fails? Go back, fix the spec or the code, and repeat from Compile.Illustrative workflow. Testing shows the EA follows its rules; it does not prove future profit.
The six steps from trading idea to live EA: write the spec, choose a build route, build it, compile in MetaEditor, backtest then demo for at least four weeks, and go live small.

An EA is a program that runs on a MetaTrader chart and trades by itself, exactly as its rules say, including the parts you forgot to specify. Still deciding whether to automate? Start with forex robots vs manual trading.

This guide follows MetaTrader 5, with notes for MetaTrader 4, and builds a complete EA in MQL5 (MetaQuotes Language 5, MT5’s programming language).

What do you need before you start?

  • MT5 or MT4, logged in to a demo account with the broker you plan to use live.
  • MetaEditor, which ships with the platform (press F4 in the terminal).
  • A written spec of your rules (Step 1).

Step 1: Write the EA spec

Write the rules before you open any editor: an EA cannot act on “buy when the trend looks strong”; it needs a number for every decision. A written trading plan already holds most of the answers. Copy this template and fill every line:

EA SPEC (fill every line with a number or a clear yes/no)
Symbol and timeframe : EURUSD, H1
Long entry           : 20 EMA crosses above 50 EMA, judged on a CLOSED bar
Short entry          : 20 EMA crosses below 50 EMA, judged on a CLOSED bar
Stop loss            : 300 points from entry (30 pips on a 5-digit quote)
Take profit          : 600 points from entry (0 = no target)
Other exits          : none (alternative: close on the opposite cross)
Position size        : 1% of balance lost if the stop is hit
Open trades          : max 1 per symbol for this EA (magic number 20261118)
Trading hours        : all hours (or e.g. 07:00-16:00 broker SERVER time)
Spread limit         : no new entry while the spread is above 30 points
News                 : no filter (or no entries 30 min either side of high-impact events)
Weekends and gaps    : hold (or close everything Friday 20:00 server time)
If an order fails    : log the error code, do not retry blindly

Points and pips. A point is the smallest price step your broker quotes. On a 5-digit EUR/USD quote (1.08452) a point is 0.00001 and a pip is 0.0001, so 1 pip = 10 points. MetaTrader works in points, which is why the spec does too.

Two lines catch most people out. Trading hours run on broker server time, which for many brokers is two or three hours ahead of GMT, not your local clock. And “closed bar” matters because a cross that appears mid-candle can vanish by the close.

Gaps need a line too. A stop loss is an instruction, not a promise: if price opens beyond it after a weekend or a news spike, the trade closes at the next available price, as with the order types you place by hand.

Step 2: Choose a build route

All three routes need the same spec and testing. They differ in cost, control, and how much you can change later.

RouteBest forMain limit
MQL5 Wizard (MT5 only)Standard indicator signals, quick prototypesLibrary modules only; the code is hard to extend
Visual EA builderNon-coders with custom rulesOnly the builder’s blocks; check you can export the source
Write MQL5 or MQL4Full controlWeeks of learning; every bug is yours
Have it builtClear rules, no time to codeCosts money; only as good as your spec
Three ways to build an expert advisorThree ways to build an EA compared: no-code tools (the MQL5 Wizard or a visual builder), writing MQL5 or MQL4 yourself, and having a developer build it, each with what it suits and its main trade-off.Three ways to build an EAChoose by time and control. None of them skips the spec or the testing.No-codeMQL5 Wizard or visual builderGOOD FORStandard indicator signalsQuick prototypes, nocoding neededTRADE-OFFOnly the blocks on offerWizard: MT5 only, and itscode is hard to extendCode it yourselfMQL5 or MQL4 in MetaEditorGOOD FORFull control of everyentry, exit and size ruleLearning the platformTRADE-OFFWeeks of learningEvery bug is yours to findand fixHave it builtBuilt from your written specGOOD FORClear rules, little timeComplex logic you do notwant to codeTRADE-OFFCosts moneyOnly as good as your specInsist on the source codeEvery route needs the same spec, a clean compile and the same testing.Illustrative comparison. Builder features and developer terms vary, so check each one before you commit.
Three ways to build an EA compared: no-code tools (the MQL5 Wizard or a visual builder), writing MQL5 or MQL4 yourself, and having a developer build it, each with what it suits and its main trade-off.

The no-code route: MQL5 Wizard and visual builders

In MetaEditor for MT5, choose File, then New, then “Expert Advisor (generate)”. The MQL5 Wizard walks you through signal modules, a trailing stop, and money management, then writes an .mq5 file for you to compile. MT4’s wizard cannot generate EAs, and the MT5 output is built from library classes that beginners find hard to modify.

Visual builders offer drag-and-drop blocks for both platforms. We compare EA builders, prices and limits included.

Having it built

With clear rules but little time, a developer such as our custom EA development team can build from the spec. Whoever builds it, insist on the full source code and a Strategy Tester run showing the EA following your rules.

Step 3: Build or code the EA: a complete MQL5 example

This EA buys when a 20-period EMA (exponential moving average) crosses above a 50-period EMA on a closed bar, and sells on the opposite cross when it has no open position. It does not close or reverse a trade on a cross: exits are the fixed stop and target only, and each trade risks about 1% of the balance. The crossover is easy to read, not an edge.

Not coding it yourself? Skip to Step 4 or Step 5. The code has five parts:

  1. Inputs: settings you can change.
  2. OnInit(): checks the inputs, creates the EMA handles.
  3. OnTick(): once per new bar, with no open position, looks for a cross.
  4. LotsForRisk(): sizes the trade from the stop and balance.
  5. OpenTrade(): runs the checks, sends the order, reads the result.

To use it, open MetaEditor (F4), choose File, then New, then “Expert Advisor (template)”, name it EmaCrossTutorial, paste this over the generated text, and save. It compiled with 0 errors and 0 warnings on MetaEditor 5 on 18 November 2026.

//+------------------------------------------------------------------+
//| EmaCrossTutorial.mq5                                             |
//| Teaching EA: EMA crossover on closed bars, stop and target in    |
//| points, position size from a fixed percentage risk.              |
//| A code example, not a trading system with a proven edge.         |
//+------------------------------------------------------------------+
#property copyright "ForexMT4Indicators.com"
#property link      "https://forexmt4indicators.com/how-to-create-expert-advisor/"
#property version   "1.00"
#property description "Tutorial EA: EMA cross on closed bars with risk-percent sizing."

#include <Trade/Trade.mqh>

//--- inputs: everything a user might want to change lives here
input group "Signal"
input int    InpFastPeriod   = 20;        // Fast EMA period
input int    InpSlowPeriod   = 50;        // Slow EMA period

input group "Risk"
input double InpRiskPercent  = 1.0;       // Risk per trade (% of balance)
input int    InpStopPoints   = 300;       // Stop loss distance (points; 300 = 30 pips on 5 digits)
input int    InpTargetPoints = 600;       // Take profit distance (points; 600 = 60 pips), 0 = none
input int    InpMaxSpread    = 30;        // Skip entries above this spread (points; 30 = 3 pips), 0 = off

input group "Execution"
input long   InpMagic        = 20261118;  // Magic number (unique per EA and chart)
input int    InpDeviation    = 20;        // Maximum slippage (points)

//--- globals
CTrade   trade;
int      fastHandle  = INVALID_HANDLE;
int      slowHandle  = INVALID_HANDLE;
datetime lastBarTime = 0;

//+------------------------------------------------------------------+
int OnInit()
{
   if(InpFastPeriod >= InpSlowPeriod || InpStopPoints <= 0 || InpRiskPercent <= 0)
   {
      Print("Check inputs: fast EMA must be shorter than slow EMA, stop and risk above zero");
      return(INIT_PARAMETERS_INCORRECT);
   }

   //--- in MQL5, iMA returns a handle; the values are read later with CopyBuffer
   fastHandle = iMA(_Symbol, PERIOD_CURRENT, InpFastPeriod, 0, MODE_EMA, PRICE_CLOSE);
   slowHandle = iMA(_Symbol, PERIOD_CURRENT, InpSlowPeriod, 0, MODE_EMA, PRICE_CLOSE);
   if(fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE)
   {
      Print("Could not create the EMA handles");
      return(INIT_FAILED);
   }

   trade.SetExpertMagicNumber(InpMagic);
   trade.SetDeviationInPoints(InpDeviation);
   trade.SetTypeFillingBySymbol(_Symbol);

   //--- start the bar clock now, so attaching mid-bar does not trigger an instant trade
   lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   if(fastHandle != INVALID_HANDLE) IndicatorRelease(fastHandle);
   if(slowHandle != INVALID_HANDLE) IndicatorRelease(slowHandle);
}

//+------------------------------------------------------------------+
void OnTick()
{
   if(!IsNewBar()) return;            // decide once per bar, not on every tick
   if(HasOpenPosition()) return;      // one position per symbol and magic number

   int signal = CrossSignal();        // +1 buy, -1 sell, 0 nothing
   if(signal != 0) OpenTrade(signal);
}

//+------------------------------------------------------------------+
//| True only on the first tick of a new bar                         |
//+------------------------------------------------------------------+
bool IsNewBar()
{
   datetime barTime = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(barTime == 0 || barTime == lastBarTime) return(false);
   lastBarTime = barTime;
   return(true);
}

//+------------------------------------------------------------------+
//| Is this EA already in a trade on this symbol?                    |
//+------------------------------------------------------------------+
bool HasOpenPosition()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);   // also selects the position
      if(ticket == 0) continue;
      if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
         PositionGetInteger(POSITION_MAGIC) == InpMagic)
         return(true);
   }
   return(false);
}

//+------------------------------------------------------------------+
//| EMA cross on the last two CLOSED bars (bar 0 is still forming)   |
//+------------------------------------------------------------------+
int CrossSignal()
{
   double fast[], slow[];
   ArraySetAsSeries(fast, true);
   ArraySetAsSeries(slow, true);

   //--- start at bar 1 and copy 2 values: [0] = last closed bar, [1] = the bar before it
   if(CopyBuffer(fastHandle, 0, 1, 2, fast) != 2) return(0);
   if(CopyBuffer(slowHandle, 0, 1, 2, slow) != 2) return(0);

   if(fast[0] > slow[0] && fast[1] <= slow[1]) return(1);    // fast crossed above slow
   if(fast[0] < slow[0] && fast[1] >= slow[1]) return(-1);   // fast crossed below slow
   return(0);
}

//+------------------------------------------------------------------+
//| Lots so that hitting the stop loses about InpRiskPercent         |
//+------------------------------------------------------------------+
double LotsForRisk(int stopPoints)
{
   double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);  // account money per tick, 1.00 lot
   double tickSize  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);   // smallest price change
   double step      = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double minLot    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   double maxLot    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
   if(tickValue <= 0 || tickSize <= 0 || step <= 0) return(0);

   double riskMoney  = AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPercent / 100.0;
   double lossPerLot = (stopPoints * _Point / tickSize) * tickValue;      // loss on 1.00 lot at the stop
   if(lossPerLot <= 0) return(0);

   //--- round DOWN to the broker's volume step, cap at the maximum
   double lots = MathFloor(riskMoney / lossPerLot / step + 1e-8) * step;
   lots = MathMin(lots, maxLot);

   //--- below the minimum lot we skip: rounding up would risk more than planned
   if(lots < minLot) return(0);

   int volDigits = (int)MathMax(0, MathCeil(-MathLog10(step)));
   return(NormalizeDouble(lots, volDigits));
}

//+------------------------------------------------------------------+
//| Checks, then send the order and read the server's answer         |
//+------------------------------------------------------------------+
void OpenTrade(int direction)
{
   if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED) || !MQLInfoInteger(MQL_TRADE_ALLOWED))
   {
      Print("Algo trading is switched off in the terminal or in the EA settings");
      return;
   }

   long spread = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
   if(InpMaxSpread > 0 && spread > InpMaxSpread)
   {
      Print("Spread of ", spread, " points is above the limit, entry skipped");
      return;
   }

   //--- broker minimum stop distance, plus the spread as a safety margin
   long minPoints = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL) + spread;
   if(InpStopPoints < minPoints || (InpTargetPoints > 0 && InpTargetPoints < minPoints))
   {
      Print("Stop or target is inside the broker minimum of ", minPoints, " points");
      return;
   }

   double lots = LotsForRisk(InpStopPoints);
   if(lots <= 0)
   {
      Print("Risk amount is too small for the minimum lot, entry skipped");
      return;
   }

   MqlTick tick;
   if(!SymbolInfoTick(_Symbol, tick)) return;

   bool   isBuy = (direction > 0);
   double price = isBuy ? tick.ask : tick.bid;
   double sl    = isBuy ? price - InpStopPoints * _Point : price + InpStopPoints * _Point;
   double tp    = 0;
   if(InpTargetPoints > 0)
      tp = isBuy ? price + InpTargetPoints * _Point : price - InpTargetPoints * _Point;
   sl = NormalizeDouble(sl, _Digits);
   tp = NormalizeDouble(tp, _Digits);

   //--- enough free margin for this size?
   double margin = 0;
   if(!OrderCalcMargin(isBuy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL, _Symbol, lots, price, margin) ||
      margin > AccountInfoDouble(ACCOUNT_MARGIN_FREE))
   {
      Print("Not enough free margin for ", DoubleToString(lots, 2), " lots");
      return;
   }

   bool sent = isBuy ? trade.Buy(lots, _Symbol, price, sl, tp, "EMA cross")
                     : trade.Sell(lots, _Symbol, price, sl, tp, "EMA cross");

   //--- true from Buy/Sell only means the request passed local checks: read the retcode
   uint code = trade.ResultRetcode();
   if(!sent || (code != TRADE_RETCODE_DONE && code != TRADE_RETCODE_PLACED))
      PrintFormat("Order failed: retcode %u (%s)", code, trade.ResultRetcodeDescription());
   else
      Print(isBuy ? "Buy " : "Sell ", DoubleToString(lots, 2), " lots, SL ",
            DoubleToString(sl, _Digits), ", TP ", DoubleToString(tp, _Digits));
}
//+------------------------------------------------------------------+

Inputs, OnInit and the new-bar check

The magic number in the input block is an ID the EA stamps on every order, so it can tell its own positions from manual trades and other EAs.

OnInit() runs once when the EA loads. It rejects impossible inputs and creates two EMA handles: in MQL5, iMA() returns a handle (a reference to an indicator the terminal calculates), not a price. It also sets the slippage limit (how far the fill may move from the requested price, under instant or request execution) and the filling mode (what happens when the full volume is not immediately available: fill it all or cancel, fill what is available and cancel the rest, or keep the rest as an order). Some brokers reject every order sent with the wrong filling mode.

OnTick() fires on every price change. IsNewBar() lets the entry logic run once per bar, so one cross cannot send a second order on the next tick. HasOpenPosition() stops the EA while a position with this symbol and magic number is open. On a netting account MT5 merges all trades on a symbol into one position, so keep manual trades off the EA’s symbol or use a hedging account, which keeps each trade separate.

CrossSignal() reads bar 1, the last closed bar, and bar 2, never bar 0, which is still forming.

Risk-percent sizing from the stop distance

LotsForRisk() calculates what 1.00 lot (a standard lot: 100,000 units of the base currency on most forex pairs) would lose at the stop and divides your risk amount by it. SYMBOL_TRADE_TICK_VALUE (money per tick for 1.00 lot, in account currency) and SYMBOL_TRADE_TICK_SIZE come from the broker’s symbol properties, so the formula works on any symbol without pip conversion.

On EUR/USD with a USD account, $5,000 at 1% risk is $50. A 300-point stop on a 5-digit quote is 30 pips, and each 0.00001 tick is worth $1 per 1.00 lot, so 1.00 lot loses $300. $50 ÷ $300 = 0.167, rounded down to the 0.01 step = 0.16 lots, risking $48; our lot size calculator gives the same answer.

Lots round down and are capped at the broker’s maximum. Below the minimum lot the EA skips the trade rather than round up and risk more than you set: on a $200 account, 1% at this stop needs 0.0067 lots, so it stays out. The percentage is a plan, not a ceiling, because gaps and slippage can push a stopped trade past it.

What does the EA check before it sends an order?

OpenTrade() runs five checks before it sends anything. Buys fill at the ask and sells at the bid, so the EA measures the stop and target from the price it will actually get.

  1. Permission. It stops if the Algo Trading button or the EA’s own permission is off.
  2. Spread. The spread is the gap between the bid you sell at and the ask you buy at. The EA skips entries while it is above 30 points (3 pips on a 5-digit quote), a common sign of rollover (the broker’s end-of-day changeover) or a news spike.
  3. Stops level. Brokers set a minimum distance between price and your stop or target (SYMBOL_TRADE_STOPS_LEVEL), and the EA refuses anything closer than that plus the current spread. Adding the spread is a buffer: stops trigger on the opposite price, and some brokers report zero while enforcing a floating minimum on the server, as the MQL4 OrderSend documentation warns. A rejection is still possible, so the EA logs the server’s return code (retcode).
  4. Volume. The lot size from LotsForRisk() must be above zero.
  5. Margin. OrderCalcMargin() confirms the free margin (your equity minus the margin already held for open positions) covers the trade.

A true from Buy() or Sell() only means the request passed local checks; the CTrade Buy documentation says to read the retcode. The EA accepts 10009 (TRADE_RETCODE_DONE) or 10008 (TRADE_RETCODE_PLACED) and logs anything else, such as 10016 for invalid stops (full retcode list).

How is an MT4 (MQL4) EA different?

The logic ports almost line for line; the plumbing does not. Our MQL4 version also compiles with 0 errors and 0 warnings. The differences:

TaskMQL5 (MT5)MQL4 (MT4)
Read a moving averageiMA() returns a handle; read it with CopyBuffer()iMA() returns the value for the bar shift you pass
Open a tradeCTrade Buy() or Sell(), then ResultRetcode()OrderSend() returns a ticket, or -1 on failure
Find the EA’s tradesPositionsTotal(), PositionGetTicket()OrdersTotal(), OrderSelect()
Symbol dataSymbolInfoDouble(), SymbolInfoInteger()MarketInfo() with MODE_TICKVALUE, MODE_STOPLEVEL
Stop too closeRetcode 10016Error 130

Here is the MT4 entry logic, then its order call:

void OnTick()
{
   if(Time[0] == lastBarTime) return;   // once per bar
   lastBarTime = Time[0];
   if(HasOpenOrder()) return;           // one trade per symbol and magic number

   //--- MQL4: iMA returns the value directly; the last argument is the bar shift
   double fast1 = iMA(NULL, 0, InpFastPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
   double fast2 = iMA(NULL, 0, InpFastPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);
   double slow1 = iMA(NULL, 0, InpSlowPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
   double slow2 = iMA(NULL, 0, InpSlowPeriod, 0, MODE_EMA, PRICE_CLOSE, 2);

   if(fast1 > slow1 && fast2 <= slow2) OpenTrade(OP_BUY);
   else if(fast1 < slow1 && fast2 >= slow2) OpenTrade(OP_SELL);
}

// ... inside OpenTrade(), after the spread, stops-level, lot and margin checks:
   //--- MQL4: OrderSend returns a ticket number, or -1 on failure
   int ticket = OrderSend(Symbol(), type, lots, price, InpSlippage,
                          NormalizeDouble(sl, Digits), NormalizeDouble(tp, Digits),
                          "EMA cross", InpMagic, 0, clrNONE);
   if(ticket < 0)
      Print("OrderSend failed, error ", GetLastError());

An .ex4 file will not run in MT5, and a compiled file is not source code you can edit. Our explainer on EX4 vs MQ4 files covers what you can do with each.

Step 4: Compile the EA in MetaEditor

Save the file in the MQL5\Experts folder (MQL4\Experts in MT4, compiled to .ex4); in the terminal, File, then Open Data Folder shows where it is. In MetaEditor press F7; the Errors tab of the Toolbox ends with a line such as “0 errors, 0 warnings”.

Errors stop the build, so no .ex5 file is created. Warnings still produce one, but the MetaEditor compile help says they point at potential errors and should not be ignored. Common early ones are “possible loss of data due to type conversion” and, in MQL4, “return value of ‘OrderSend’ should be checked”.

A clean EA then appears in the Navigator under Expert Advisors; if not, right-click the Navigator and choose Refresh.

Step 5: How do you backtest and demo-test an EA?

Backtest the EA in the Strategy Tester (Ctrl+R) over several years with “Every tick based on real ticks” modelling and a forward period, and check the trade list against your spec. Then demo it with your intended broker for at least four weeks. Neither test proves future profit: they prove the EA follows its rules.

Strategy Tester settings that matter

These are our defaults for any new EA in the MT5 Strategy Tester:

  • Symbol and timeframe: EUR/USD H1.
  • Date: several years, so the test meets trends, ranges, and news spikes.
  • Forward: 1/3, which tests the latest third of the range separately.
  • Execution: Random Delay, so fills are not unrealistically perfect.
  • Modelling: “Every tick based on real ticks”, which replays the broker’s recorded ticks with their real spread. Where a minute has no recorded ticks, the tester generates them, so check how far back your broker’s real ticks go.
  • Visualization: on for the first run, so you can watch it trade bar by bar.

In MT4, pick the “Every tick” model, type a realistic value in the Spread field instead of “Current”, and tick “Use date” and “Visual mode”. MT4 builds its ticks from lower-timeframe bars rather than recorded ticks, so treat its results as rougher.

What to check, then demo

Read the trade list before the profit figure. Each entry should open at the start of the bar after a cross, with the stop and target about 300 and 600 points from the entry and the lot size the sizing maths gives. Random Delay can shift the fill a few points from the price the EA read, so small differences are normal. Two positions at once or mid-bar entries mean a bug: fix it before trusting the profit figure.

On demo, let the four weeks cover several high-impact news releases and check each trade in the Experts tab against the spec. Our demo vs live accounts guide covers what still differs.

Step 6: Go live at the smallest size

Drag the EA from the Navigator onto the right chart. On the Common tab, tick the trading permission (Allow Algo Trading in current MT5 builds, Allow live trading in MT4) and click OK, then switch on the Algo Trading toolbar button (AutoTrading in MT4). An icon next to the EA’s name in the chart’s top-right corner shows whether it may trade.

Start at the smallest size your rule allows. The Experts tab shows the EA’s own messages, such as the retcode lines; the Journal tab logs the terminal’s connections and trade operations.

An EA trades only while its terminal runs, so a sleeping laptop means a sleeping EA: stops and targets already placed stay on the broker’s server, but new entries and the EA’s own exits stop. A live EA belongs on a VPS (virtual private server): either MetaTrader’s built-in virtual hosting or a Windows server of your own.

Trading a prop account or a TradingView idea?

Prop firm rules differ by firm and change over time, so check the current ones and our guide to prop firm EA rules first. Ideas that start in TradingView take one of two routes: rewrite the Pine Script in MQL5 so it runs like any other EA, or keep TradingView as the signal source, which needs an alert bridge plus a paid TradingView plan (webhooks are not on the free plan). See how to connect TradingView to MT5.

Six mistakes that break first EAs

  1. No new-bar check. Entries run on every tick, so one signal can open several positions. Fix: gate entries with IsNewBar().
  2. Points vs pips. “30” typed as points is 3 pips on a 5-digit quote, not 30. Fix: code in points; note the pip equivalent in the input comment (300 points = 30 pips on a 5-digit quote, as in the Step 3 inputs).
  3. Ignoring spread and stops level. Close stops get rejected (retcode 10016, MT4 error 130), and wide spreads hit tight stops. Fix: check both before every order.
  4. A hardcoded lot. With a 30-pip stop, 0.10 lot of EUR/USD risks $30: 1% of a $3,000 account but 10% of a $300 one. Fix: size from the stop distance and balance.
  5. One short test period. Three good months usually means three months that suited the rules. Fix: test several years, on real ticks wherever your broker’s history allows.
  6. Over-optimising. Among thousands of input combinations, one will almost always fit the past beautifully. Fix: optimise few inputs and trust only settings that hold on the forward period.

Does any of this change for gold (XAU/USD)?

Yes. Brokers quote gold with different numbers of decimals and label its “pip” differently, so a pip-based stop can be off by a factor of ten. Work in price distance and contract size instead.

A typical XAU/USD contract is 100 troy ounces per 1.00 lot, with a $0.01 minimum price change, but check your broker’s contract specification. On that contract, a $5.00 stop costs $5.00 × 100 = $500 per 1.00 lot, so 1% of a $5,000 account ($50) allows 0.10 lots.

The Step 3 EA sizes gold correctly because it uses tick value and tick size. The trap is the stop input: 300 points is $3.00 on a 2-digit gold quote but $0.30 on a 3-digit one. Choose the price distance first, then convert it ($5.00 is 500 points on 2 digits, 5,000 on 3), and set the spread filter from the gold symbol’s own specification, not your forex settings.

Rather have it built?

Have the spec but not the weeks to code it? Our in-house development team led by Tim Morris builds EAs from written rules or marked-up screenshots, with a free quote at a fixed price before you pay and the full source code included. Trading from an indicator? The indicator to EA service turns its signals into an EA with your own stop, target, and sizing rules.

Risk disclaimer: Forex and CFD trading carries a high level of risk and may not be suitable for all traders. The strategies and indicators described in this article are educational. Past performance does not guarantee future results. Always test on a demo account before risking real capital.

Frequently asked questions

Should I learn MQL4 or MQL5 to make my first EA?

Start with MQL5 if you can: MT5 adds real-tick testing and both netting and hedging accounts. Choose MQL4 if your broker or prop firm only offers MT4. The trading logic carries over; order functions, indicator calls, and position handling get rewritten.

How much does it cost to create an EA?

Building it yourself costs only time: MetaEditor, the MQL5 Wizard and the Strategy Tester come free with MetaTrader, as does a demo account. Visual builders range from free tiers to paid plans, and developers quote per project, so the price follows the complexity of your rules.

How long does it take to create an EA?

Testing sets the timeline more than the build. Even a simple EA needs a multi-year backtest, then at least four weeks on demo, so plan on a month or more from spec to live. Complex rules add build and debugging time.

Are expert advisors safe and allowed?

An EA is only as safe as its rules and code. It creates no edge, and a bug can lose money fast because it trades without asking, so cap the risk per trade, test, demo and start small. MT4 and MT5 run EAs natively, but broker and prop firm terms vary, so read them first.

How do I install an EA in MetaTrader 5?

In the terminal choose File, then Open Data Folder, and copy the .ex5 file into MQL5\Experts (or compile the .mq5 there). Right-click the Navigator, choose Refresh, then drag the EA onto a chart and click OK. One EA runs per chart, so run several on separate charts, each with a unique magic number.

Why does my EA work in the Strategy Tester but lose on a live account?

Usually because the test was kinder than the market: a fixed or zero spread, a short period that suited the rules, settings fitted to history, and no live slippage. Re-test over several years on real ticks where available, keep a forward period, and compare demo trades with tester trades for the same dates.

Can ChatGPT write an expert advisor for me?

It can draft MQL code, and so can MetaEditor’s built-in AI Assistant, which MT5 build 6060 (23 July 2026) made a full development assistant. Either draft may not compile, or may compile and still mishandle lot rounding, stop distances, or closed-bar logic. Compile to 0 errors and 0 warnings, read every block, and test it like your own code; our AI expert advisor guide covers the rest.

Explore forex broker accounts

Visit these broker websites to check the account options, regional availability and terms that apply to you before opening an account.

Trading forex and CFDs carries a significant risk of loss and is not suitable for everyone. Broker links are affiliate links; we may earn a commission if you use them.

SuperNeura trading tool: get it free

LEAVE A REPLY

Please enter your comment!
Please enter your name here