Migration · MetaTrader 4 to MetaTrader 5
MQL4 to MQL5 migration
Your Expert Advisor has been running reliably on MetaTrader 4 for years — but your broker is switching to MetaTrader 5, or the instrument you want is only available there. We convert your system to MQL5 and then prove that it produces the same entries and exits on the same price data as the original.
Also for indicators and scripts. If required, in the other direction too, or to and from cTrader, TradingView and TradeStation.
Why the switch is due
For most MT4 users, the question is no longer whether to migrate but when — and whether it happens in an orderly way or under time pressure.
| No further development | MetaQuotes no longer develops MetaTrader 4. No new features appear, only security updates and bug fixes. |
|---|---|
| No new licences | New brokers receive MT5 licences only. If you change broker today, you will find MetaTrader 4 on offer less and less often. |
| New instruments only in MT5 | Exchange-traded instruments, futures, many share CFDs and newer cryptocurrency pairs are now connected by brokers only in MetaTrader 5. |
| Technical advantages | True multi-symbol and multi-timeframe handling from one chart, 21 instead of 9 timeframes, access to the economic calendar, market depth and a strategy tester that uses all processor cores and distributed computing. |
| Test quality | The MT5 tester can calculate with real ticks and variable spreads and test several symbols at once. This makes backtests not only faster but more reliable. |
Why a migration is not a translation
MQL4 and MQL5 look similar enough that automatic conversion seems tempting. But the languages differ not in syntax but in the model behind them — and that is exactly where the errors arise that go unnoticed in the backtest and cost money in live trading.
The difference that silently changes most systems: netting or hedging
MetaTrader 4 only knows hedging: every order is its own position, and several positions in the same symbol can be open in both directions at the same time. MetaTrader 5 knows both account models — and many brokers run netting accounts, where only one net position exists per symbol.
On a netting account, two buys merge into one position with an averaged entry price, and a sell of the same size closes it instead of opening an opposite position. Every strategy with position baskets, grid, averaging or hedging logic therefore behaves fundamentally differently — without a single error message. This is the most common reason why a migrated system “somehow trades differently”.
That is why every migration includes clarifying which account model your target broker uses and, if necessary, a separate management layer that reproduces the original behaviour on a netting account.
Comparison of the most important constructs
| Task | MQL4 (MetaTrader 4) | MQL5 (MetaTrader 5) |
|---|---|---|
| Opening a position | OrderSend() with individual parameters, returns the ticket number |
Fill MqlTradeRequest and call OrderSend(), or CTrade::Buy(). The return value only confirms acceptance, not execution |
| Iterating over positions | OrdersTotal() with OrderSelect() per index |
PositionsTotal() with PositionGetTicket(); pending orders are kept separately in OrdersTotal() |
| Closing a position | OrderClose() with ticket and volume |
CTrade::PositionClose(), partial close via PositionClosePartial() |
| Changing stop and target | OrderModify() for order and position together |
PositionModify() for positions, OrderModify() only for pending orders — two separate operations |
| Querying an indicator | iMA(...) returns the value directly on every call |
iMA(...) returns a handle, created once in OnInit(); the values are fetched by CopyBuffer() |
| Reading price series | Direct arrays: Close[i], High[i], Time[i] |
CopyRates(), CopyClose() into your own arrays; set the indexing direction with ArraySetAsSeries() |
| Number of bars | Bars as a predefined variable |
Bars(_Symbol, _Period) as a function with symbol and timeframe |
| Current price | Bid and Ask as predefined variables |
SymbolInfoTick() with MqlTick, so it also works for other symbols |
| Account model | always hedging | Netting or hedging depending on the broker — ACCOUNT_MARGIN_MODE must be checked at runtime |
| Error handling | Error code after the call via GetLastError() |
Additionally MqlTradeResult with its own return code; the trade only counts as completed with the trade event |
| Trade events | not available | OnTradeTransaction() reports every change of state — a prerequisite for reliable state management |
| Timeframes | 9 timeframes | 21 timeframes; not every MT4 constant has a direct equivalent |
Add to this differences in minimum stop distances, in normalising position sizes, in symbol properties and in the behaviour of the strategy tester. A migration is therefore porting work followed by proof — not search and replace.
An example: the same rule in MQL4 and MQL5
Buy when the 10-bar moving average crosses the 50-bar average from below. In MQL4 this takes a few lines:
// MQL4: buy when the fast average crosses the slow one from below
double fastNow = iMA(NULL, 0, 10, 0, MODE_EMA, PRICE_CLOSE, 1); // bar 1 = last closed bar
double fastPrev = iMA(NULL, 0, 10, 0, MODE_EMA, PRICE_CLOSE, 2);
double slowNow = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_CLOSE, 1);
double slowPrev = iMA(NULL, 0, 50, 0, MODE_EMA, PRICE_CLOSE, 2);
if(fastPrev < slowPrev && fastNow > slowNow && OrdersTotal() == 0)
{
double sl = NormalizeDouble(Ask - 500 * Point, Digits);
double tp = NormalizeDouble(Ask + 1000 * Point, Digits);
int ticket = OrderSend(Symbol(), OP_BUY, 0.10, Ask, 3, sl, tp, "", 4711, 0, clrNONE);
if(ticket < 0)
Print("OrderSend failed: ", GetLastError());
}
The same rule in MQL5, the way we implement it:
// MQL5: the same rule
#include <Trade/Trade.mqh>
CTrade trade;
int hFast, hSlow;
int OnInit()
{
hFast = iMA(_Symbol, _Period, 10, 0, MODE_EMA, PRICE_CLOSE); // handle, created once
hSlow = iMA(_Symbol, _Period, 50, 0, MODE_EMA, PRICE_CLOSE);
if(hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE)
return(INIT_FAILED);
trade.SetExpertMagicNumber(4711);
trade.SetTypeFillingBySymbol(_Symbol); // broker's filling mode
return(INIT_SUCCEEDED);
}
void OnTick()
{
double fast[], slow[];
ArraySetAsSeries(fast, true); // [0] = newest value
ArraySetAsSeries(slow, true);
if(CopyBuffer(hFast, 0, 1, 2, fast) != 2 || CopyBuffer(hSlow, 0, 1, 2, slow) != 2)
return; // data not ready yet
if(fast[1] < slow[1] && fast[0] > slow[0] && !PositionSelect(_Symbol))
{
MqlTick tick;
if(!SymbolInfoTick(_Symbol, tick))
return;
double sl = NormalizeDouble(tick.ask - 500 * _Point, _Digits);
double tp = NormalizeDouble(tick.ask + 1000 * _Point, _Digits);
if(!trade.Buy(0.10, _Symbol, tick.ask, sl, tp) || trade.ResultRetcode() != TRADE_RETCODE_DONE)
Print("Buy failed: ", trade.ResultRetcode());
}
}
Four places where the behaviour changes without a single compiler message:
- Order of indicator values.
CopyBuffer()copies the values into your own array. WithoutArraySetAsSeries()the older value comes first; the condition then compares the wrong way round, and the system buys precisely when the averages cross from above. - Checking for open positions. In MQL4,
OrdersTotal() == 0counts every order on the account, including pending orders, other symbols and other Expert Advisors. MQL5 keeps positions and orders apart, and on a hedging accountPositionSelect()finds only one of several positions. The right check depends on the account model and on whether other systems run on the account. We clarify that before implementation. - Execution. In MQL4,
OrderSend()returns the ticket number. In MQL5 a successful call only means that the request was formally valid; it has been executed when the return code isTRADE_RETCODE_DONE. If the filling mode does not match the broker, every market order is rejected. - Prices.
Askis a predefined variable in MQL4. MQL5 gets the price withSymbolInfoTick(), which also works for symbols other than the chart's.
Converters and AI tools usually translate lines like these without an error message. Whether the order of values, the position check and the filling mode are right only shows when the trade lists of both versions are compared, which is why that comparison is part of every migration. If you already have a converted version, we check it against the original. The review with effort estimate is free of charge.
How a migration works
The decisive step is the last one: without comparison against the original system, a migration is not complete, merely ended.
Review of the original system
We look at your MQL4 source code and determine which constructs are affected: order model, indicator calls, time series access, libraries used and any DLLs included. The result is an effort estimate with an upper limit.
Clarifying target broker and account model
Netting or hedging, symbol names, contract specifications, minimum stop distances. These points decide whether the logic can be adopted unchanged or whether a management layer is needed.
Implementation on native MQL5 structures
No compatibility layer that emulates MQL4 calls, but a clean switch to position logic, indicator handles and trade events. This takes a little more time to implement and saves it again with every later extension.
Signal comparison against the original
Both systems run over the same period on comparable price data. The trade lists are then compared: entry time, direction, position size, exit time. Deviations are either explained — for example by different price sources — or fixed.
Handover with migration log
You receive the complete, commented .mq5 source code, brief documentation of the input parameters and a log recording every deliberate deviation from the original — for example where an MT4 peculiarity has no equivalent in MT5.
Effort and pricing
Migrations are billed by time because the scope depends entirely on the original system. The effort estimate after the review is free of charge and contains an upper limit that will not be exceeded.
| Low effort | Indicators and scripts without trading logic, simple systems with one position, standard indicators and no basket management. Here the effort is usually in the low single-digit hours. |
|---|---|
| Medium effort | Systems with money management, trailing logic, partial exits, several symbols or timeframes, and custom indicators that also need to be migrated. |
| High effort | Position baskets, grid and averaging techniques, hedging strategies on netting accounts, included DLLs, external data sources and undocumented third-party code that first has to be reconstructed. |
| Without source code | If only the compiled .ex4 file is available, no migration is possible. In this case the option is a new development based on a description of the trading behaviour — the pricing for new developments applies. |
Included in delivery
- Complete, commented .mq5 source code
- Migrated custom indicators, if any
- Signal comparison against the original system
- Migration log with all deliberate deviations
- Brief documentation of the input parameters
- One round of corrections after the acceptance test
Not included
- Changes to the trading logic itself
- Re-optimising the parameters for MT5
- Guarantee of identical trading results — price data and execution differ between the platforms
- Operation, server provisioning and monitoring
Frequently asked questions about migration
Can't MQL4 code simply be converted automatically?
Partly. There are libraries and AI tools that emulate MQL4 calls in MQL5, and that produces code that compiles. But the differences lie not in the syntax but in the model: order system versus position system, direct indicator access versus handles, hedging versus netting. An automatically converted system runs — it just doesn't necessarily trade the same way. That is exactly why signal comparison is our acceptance criterion.
Will my migrated system deliver the same results?
The same signals, yes; the same results, not necessarily. Price data, spreads and execution differ between MT4 and MT5 accounts, even with the same broker. We prove that entries and exits happen at the same times and in the same direction. Minor deviations in the prices achieved are normal and explainable.
What is the difference between netting and hedging accounts?
On a hedging account, every order is its own position; several positions in the same symbol can be open in both directions at the same time — this is how MetaTrader 4 always works. On a netting account, only one net position exists per symbol: a second buy increases the existing position and averages the entry price, a sell reduces or closes it. MetaTrader 5 supports both models, and the broker decides which one applies. For strategies with position baskets, grid or averaging logic, this is the most important check of the entire migration.
I only have the .ex4 file, no source code. Is it still possible?
It cannot be migrated — a compiled file does not contain the source code in reconstructable form, and an attempt at decompilation could also be legally problematic depending on its origin. What is possible is a new development based on a description of the trading behaviour: if you know the rules or can derive them from trade logs, we rebuild the system. The pricing for new developments applies.
Do my parameters need to be re-optimised after the migration?
Not necessarily. If the system produces the same signals, the parameters remain valid. A review still makes sense, because the MT5 tester uses more accurate price data and sometimes reveals that the original optimisation was based on overly optimistic data. Re-optimisation is a separate service and not part of the migration.
My system uses a DLL. Is that a problem?
Not in principle, but it increases the effort. The calling conventions differ, and MQL5 is stricter about data types and pointer passing. If the DLL's source code is available, the adaptation is manageable. Otherwise we check whether the functionality can be reproduced in MQL5.
Can you also migrate indicators?
Yes, and for most systems it is necessary anyway: an Expert Advisor that uses its own indicators only runs once these are also available in MQL5. The conversion mainly concerns buffer management and access to price series.
How long does a migration take?
A few days for simple systems, one to two weeks for extensive ones with basket management and custom indicators. The binding date is stated in the effort estimate you receive after the source code review.
Can I keep using my MT4 system?
Yes. The migration creates an additional version; your original remains unchanged. Many clients run both versions in parallel for a while to compare their behaviour in live trading. That is the best acceptance test there is.
What exactly changes in the code when moving from MQL4 to MQL5?
Mainly four things: in MQL5 indicators return a handle, and the values are copied with CopyBuffer into your own array, whose order you have to set. Positions and orders are kept separately, and netting accounts hold only one position per symbol. A trade request only counts as executed with the return code TRADE_RETCODE_DONE, and the filling mode has to match the broker. Prices come from SymbolInfoTick instead of the Bid and Ask variables. An example with both versions is shown above on this page.
Send us your source code
After the review you receive an effort estimate with an upper limit — free of charge and without obligation. On request we sign a non-disclosure agreement before you send anything.
EA-Programmierung is a service of NordZentrum GmbH & Co. KG, Germany: Expert Advisors, indicators and trading systems for MetaTrader 5 and 4, cTrader, TradingView and ATAS, developed by André Liebetrau, Dipl.-Inf., a development service provider since 2009. Fixed price based on a written specification, complete source code included.
After the migration, the file is located in the MQL5\Experts directory instead of MQL4\Experts. Setting it up in detail: Installing an Expert Advisor.
Still undecided whether switching is worth it at all? The comparison MetaTrader 4 or 5? sets order model, strategy tester and costs side by side.