Trading forex and CFDs on leverage is high risk. Most retail accounts lose money. Read the risk warning

MQL4 vs MQL5 Programming: How the Languages Differ and Which to Learn

MQL4 and MQL5 look alike on the surface, since both are C++-style languages from MetaQuotes, but they handle trading in fundamentally different ways. MQL4 treats everything as an "order" identified by a ticket, and indicator functions return values directly; MQL5 separates orders, deals and positions, uses indicator handles and buffers, and adds richer events and a far more capable tester. For new projects MQL5 is usually the better choice; MQL4 remains relevant mainly for maintaining existing EAs and for traders whose broker or prop firm only offers MT4.

Key takeaways

  • Code is not interchangeable: .ex4 runs only on MT4 and .ex5 only on MT5, and source must be ported, not just recompiled.
  • The biggest difference is the trading model: MQL4 orders versus MQL5 orders, deals and positions.
  • MQL5 indicators return a handle you read with CopyBuffer; MQL4 indicator calls return a value immediately.
  • Since MT4 build 600 the languages share much syntax, including classes and structs, so the gap is mostly in APIs, not grammar.
  • MQL5's tester supports real ticks, multiple symbols and multi-core optimisation, which matters for serious testing.

A short history that explains the differences

MQL4 was built for MetaTrader 4, released in 2005, at a time when retail forex brokers mostly offered hedging-style accounts where each trade lived independently. MetaTrader 5 arrived in 2010 designed for exchange-traded markets as well as forex, which is why its trading model follows exchange conventions: you send an order, it produces one or more deals (fills), and those deals change a position. Early MT5 only supported netting, one position per symbol, which kept many forex traders on MT4. MetaQuotes later added a hedging account mode to MT5, removing the main objection.

In 2014, MT4 build 600 rebuilt MQL4 on the MQL5 compiler. MQL4 gained classes, structs, the OnInit/OnTick/OnDeinit event structure and much stricter compilation. That is why modern MQL4 and MQL5 source files look so similar, and also why very old MQL4 code using init() and start() sometimes needs fixing even within MT4.

Side-by-side comparison

AreaMQL4MQL5
Trading modelOrders identified by ticket; open trades are "orders"Orders, deals and positions are separate objects
Sending a tradeOrderSend() with many positional parametersOrderSend() with MqlTradeRequest/MqlTradeResult structs, or the CTrade class
IndicatorsiMA(...) returns a value for a given shiftiMA(...) returns a handle; values read with CopyBuffer()
Price dataPredefined Bid, Ask, Close[], High[]SymbolInfoTick(), CopyRates(), iClose() and similar
Trade eventsPoll orders on each tickOnTrade() and OnTradeTransaction() notify you of changes
Account modesHedging-styleNetting or hedging, depending on account
Strategy testerSingle-threaded, one symbol, generated ticksMulti-threaded, multi-symbol, real-tick mode, cloud agents
Standard librarySmallerExtensive: trade classes, indicators, collections, controls

The trading model: the difference that breaks ports

In MQL4, opening a buy is one function call that returns a ticket number. Managing trades means looping through OrdersTotal(), calling OrderSelect() on each, and checking its type, symbol and magic number.

int ticket = OrderSend(Symbol(), OP_BUY, 0.10, Ask, 3, Ask - 300*Point, Ask + 600*Point, "demo", 12345, 0, clrGreen);

In MQL5 the same intention can be written with the standard library's CTrade class:

#include <Trade\Trade.mqh>

CTrade trade;

trade.SetExpertMagicNumber(12345);

double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

trade.Buy(0.10, _Symbol, ask, ask - 300*_Point, ask + 600*_Point, "demo");

That looks similar, but what happens next differs. In MQL5 the request produces an order, which is filled as a deal, which opens or modifies a position. To find open trades you loop through PositionsTotal() and PositionGetTicket(); pending orders are a separate list via OrdersTotal(); and closed trades live in the deal history. On a netting account, a second buy on the same symbol does not create a second position, it increases the existing one, and a sell reduces it. Code written assuming each trade is independent, as most MQL4 code does, can therefore behave completely differently on a netting account. US accounts, which follow NFA FIFO and no-hedging rules, add further constraints. Our article on forex hedging covers why some accounts forbid opposite positions.

MQL5 also expects you to handle broker-specific details MQL4 hid: the allowed order filling mode (Fill or Kill, Immediate or Cancel, Return) and detailed return codes in MqlTradeResult. That extra verbosity is a nuisance at first, but it gives far better control over execution and error handling.

Indicators: values versus handles

MQL4 indicator functions calculate on demand. To get the 50-period simple moving average on the previous closed bar, you write:

double ma = iMA(NULL, 0, 50, 0, MODE_SMA, PRICE_CLOSE, 1);

MQL5 splits that into two steps. You create the indicator once, usually in OnInit(), and receive a handle. Then, each time you need values, you copy them into an array:

int maHandle = iMA(_Symbol, _Period, 50, 0, MODE_SMA, PRICE_CLOSE);

double ma[];

ArraySetAsSeries(ma, true);

if (CopyBuffer(maHandle, 0, 0, 3, ma) == 3) { double prev = ma[1]; }

The MQL5 approach is more efficient, because the terminal calculates the indicator once and updates it incrementally, and it makes multi-symbol and multi-timeframe work cleaner. It is also the single most common source of bugs in ported code: forgetting ArraySetAsSeries reverses the index order, and not checking CopyBuffer's return value means reading empty or stale data when history is still loading. If you are coding something like a moving average crossover strategy, this is the part to get right first.

Events, structure and language features

Both languages now use the same core structure: OnInit() for set-up, OnTick() for each new price, OnDeinit() for clean-up, plus OnTimer() and OnChartEvent(). MQL5 adds event handlers MQL4 lacks, notably OnTradeTransaction(), which fires when orders, deals or positions change, so an EA can react to a fill or a stop-out immediately rather than discovering it on the next tick. It also offers OnBookEvent() for depth-of-market data where the broker provides it.

On language features, the post-2014 MQL4 is closer to MQL5 than many tutorials suggest. Both support classes, inheritance, structs, enumerations and function overloading. MQL5 goes further, with fuller support for templates, interfaces and a much larger standard library covering trade operations, collections, mathematics and user interface controls. In practice, an experienced MQL5 programmer can read MQL4 easily; the reverse takes a few weeks of adjustment, mostly to the trading and data APIs.

Testing and optimisation

For anyone building automated strategies, the tester may matter more than the language. The MT4 tester runs one symbol at a time, on one CPU core, with ticks generated from one-minute bars and a single fixed spread. Getting realistic results for scalpers requires third-party tick data tools, as described in our guide to 99.9% tick data backtesting in MT4.

The MT5 tester can replay the broker's real recorded ticks with variable spreads, test EAs that trade several symbols at once, simulate execution delay, and spread optimisation across all your CPU cores, local network machines or a paid cloud network of testing agents. A forward-testing option holds back part of the data automatically. See how to backtest an EA in MT5 for the full workflow. For a strategy with eight parameters and thousands of combinations, the speed difference can be the difference between an overnight run and a week.

Key risk point: porting an EA between MQL4 and MQL5, or learning a new language, introduces bugs that may not show in a backtest: wrong position counting on netting accounts, stale indicator buffers, mishandled filling modes or lot sizes rounded incorrectly. These bugs can open unintended trades or leave positions unprotected. Leverage magnifies the damage, and most retail forex and CFD accounts lose money. Always run new or ported code on a demo account and log every trade action before using real money.

Porting MQL4 code to MQL5: a checklist

There is no reliable automatic converter for anything beyond trivial code. A manual port usually involves the following.

  1. Replace predefined variables. Bid, Ask, Point, Digits and the Close[]-style arrays become SymbolInfoDouble(), _Point, _Digits and CopyRates() or iClose().
  2. Move indicator creation into OnInit. Store handles; read values with CopyBuffer(); release handles in OnDeinit().
  3. Rewrite order sending with CTrade or MqlTradeRequest, including filling mode and error handling based on return codes.
  4. Rewrite trade loops to iterate positions, pending orders and history separately, filtering by symbol and magic number.
  5. Decide on netting versus hedging behaviour and test on both account types if the EA will be distributed.
  6. Re-test from scratch. Treat the port as a new EA: backtest, compare trade lists against the MQL4 version, then demo test.

Expect a simple single-symbol EA to take hours to port and a complex multi-trade system days, plus testing time.

A practical tip: before porting, export the MQL4 version's trade list from a backtest over a fixed period, then run the MQL5 version over the same period on the same broker's data and compare entries, exits and lot sizes line by line. Small differences in entry price are expected, because MT5 uses real ticks and MT4 uses generated ones. Differences in the number of trades, the direction of trades or the size of positions are not expected, and each one points to a logic difference you need to explain. Keep both versions in version control so you can see exactly what changed when results diverge. If the original MQL4 code relied on undocumented quirks, such as reading indicator values from the still-forming bar, decide deliberately whether to replicate that behaviour or fix it, and note the decision, because it will change backtest results.

Which should you learn?

Your situationSensible choiceWhy
Starting from zero, building new EAsMQL5Better tester, active development, broader asset support
Maintaining existing MT4 EAsMQL4 (then plan a port)Fixes and small changes are faster in the original language
Broker or prop firm offers only MT4MQL4You can only run what the platform supports
Want a general-purpose languageConsider C# on cTrader or PythonSkills transfer beyond MetaTrader
Selling EAs commerciallyBoth, MQL5 firstBuyers use both platforms; MT5 is where new demand is moving

MetaQuotes has been steering brokers towards MT5 for years, and many newer brokers launch with MT5 only. MT4 remains widely installed, though, so MQL4 knowledge is not wasted. If you are also weighing non-MetaTrader options, our guides to cTrader cBots and algorithmic forex trading for beginners compare the wider landscape.

Frequently asked questions

Can MQL4 code run in MetaTrader 5?

No. MT5 cannot load .ex4 files, and MQL4 source will not compile in MetaEditor for MT5 without changes, because the trading functions, predefined variables and indicator calls differ. Very simple utility code may need only minor edits, but anything that trades must be rewritten for MQL5's order, deal and position model and then retested.

Is MQL5 harder to learn than MQL4?

It is more verbose, especially for trading and indicator access, so the first EA takes longer. The core syntax is almost the same since MT4 build 600. Many programmers find MQL5 easier in the long run because the standard library's CTrade class and the clearer separation of orders and positions reduce ambiguity in complex EAs.

Is MQL4 being discontinued?

MetaQuotes focuses development on MT5 and has encouraged brokers to move to it, and many newer brokers offer only MT5. MT4 still runs at a large number of brokers and receives occasional builds, so MQL4 code continues to work. For long-lived new projects, MQL5 is the safer investment of your time.

What is the CTrade class in MQL5?

CTrade is part of MQL5's standard library, included from Trade\Trade.mqh. It wraps the low-level OrderSend request and result structures in simpler methods such as Buy, Sell, PositionClose and PositionModify, and lets you set a magic number, slippage and filling mode once. It is the usual starting point for anyone moving from MQL4's OrderSend.

Why does my ported EA behave differently on MT5?

Common causes are a netting account merging positions, indicator buffers read in reverse order or before data has loaded, unsupported filling modes, different symbol names or contract specifications, and using real ticks instead of MT4's generated ticks. Compare trade lists from both versions over the same period and check the Experts log for return codes.

Should I learn MQL or Python for forex trading?

Learn MQL if you want to run EAs inside MetaTrader with its integrated tester and the broad broker support it brings. Learn Python if you want stronger data analysis, research tools and skills that transfer outside trading, using broker APIs for execution. Many algorithmic traders end up using both: Python for research and MQL5 for running the final strategy.

This article is general information, not personal financial advice. Figures such as spreads, fees, leverage and rules change; confirm them with the provider and check the provider is authorised for your country of residence.