EXECUTIVE QUANTITATIVE BRIEFING

Algorithmic execution dominates modern foreign exchange, representing over 75% of daily interbank trade volume. For quantitative traders, proprietary algorithmic desks, and retail bot developers, choosing the correct development environment between MetaQuotes Language 4 (MQL4) and MetaQuotes Language 5 (MQL5) is a vital technological decision. While MQL4 powered the retail algorithmic revolution for nearly two decades, MQL5 represents a modern C++ style object-oriented language engineered for institutional order books, asynchronous networking, and multi-threaded hardware acceleration. This guide breaks down the core syntax differences, event handlers, order execution models, and migration strategies required to transition legacy EAs to MQL5.

1. Core Paradigm Differences: Procedural vs. Object-Oriented

The fundamental divide between both programming environments lies in their underlying language paradigms:

MQL4 (Legacy & Procedural): Early versions of MQL4 were strictly procedural, mimicking ANSI C. While MetaQuotes later introduced object-oriented syntax (OOP) to MQL4 via the unified compiler in Build 600, the underlying terminal runtime remains single-threaded. State management, order ticketing, and trade history arrays must be traversed procedurally using global memory buffers.

MQL5 (Strict Object-Oriented C++ Style): MQL5 adopts strict C++ OOP syntax, complete with class inheritance, encapsulation, polymorphism, pointer management, and abstract interfaces. In MQL5, complex execution engines—such as multi-timeframe risk managers, trailing stop algorithms, and trailing drawdown guards—can be decoupled into reusable modular classes (#include <Trade\Trade.mqh>).

2. Order Execution Models: OrderSend vs. MqlTradeRequest

The single biggest hurdle when migrating from MQL4 to MQL5 is how trades are submitted, verified, and executed by the broker's server.

MQL4 OrderSend Model

In MQL4, opening a market order is a straightforward, synchronous function call returning a unique ticket integer:

QUANTITATIVE EXECUTION // CODE
PYTHON / MT5
// MQL4 Synchronous Order Placement
int ticket = OrderSend(
    Symbol(),          // Currency Pair
    OP_BUY,            // Order Type
    1.0,               // Lot Size
    Ask,               // Current Market Price
    3,                 // Slippage Tolerance (Points)
    Ask - 30 * Point,  // Stop Loss
    Ask + 60 * Point,  // Take Profit
    "Algo Scalper",    // Order Comment
    123456,            // Magic Number
    0,                 // Expiration
    clrGreen           // Arrow Color
);

This command pauses the entire EA thread until the broker server answers with an accept or reject. If the broker is experiencing peak volatility, your robot freezes for 500ms to 2000ms while waiting for the response.

MQL5 Asynchronous Trade Request Model

MQL5 replaces this monolithic function with a structured, institutional payload system utilizing the MqlTradeRequest structure and the OrderSendAsync() API:

QUANTITATIVE EXECUTION // CODE
PYTHON / MT5
// MQL5 Institutional Trade Request
#include <Trade\Trade.mqh>
CTrade trade; // Institutional Standard Library Instance

void OpenInstitutionalBuy(double volume, double sl_points, double tp_points)
{
    trade.SetExpertMagicNumber(123456);
    trade.SetDeviationInPoints(30);
    trade.SetTypeFilling(ORDER_FILLING_IOC); // Immediate or Cancel

    double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double sl = (sl_points > 0) ? ask - (sl_points * _Point) : 0;
    double tp = (tp_points > 0) ? ask + (tp_points * _Point) : 0;

    // Asynchronous or Synchronous Execution
    if(!trade.Buy(volume, _Symbol, ask, sl, tp, "MQL5 Execution Engine"))
    {
        Print("Execution Error: ", trade.ResultRetcode(), " - ", trade.ResultRetcodeDescription());
    }
}

With OrderSendAsync(), MQL5 fires the trade payload across the socket and immediately releases the CPU to continue processing tick streams without waiting for server confirmation. When the server responds, MQL5 triggers the native OnTradeTransaction() event handler.

3. Key Event Handlers: Comparing Execution Life Cycles

A trading robot operates as an event-driven state machine. Notice how MQL5 expands the event listener ecosystem:

Event Type MQL4 Handler MQL5 Handler Institutional Capability
Terminal Init OnInit() OnInit() Pre-allocates memory and validates broker license
New Price Tick OnTick() OnTick() Calculates price action and trigger conditions
Timer Interrupt OnTimer() OnTimer() Millisecond clock cycles for trailing stop automation
Order Book / DOM Not Supported OnBookEvent() Real-time Level 2 Market Depth liquidity analysis
Trade State Change Polling required OnTradeTransaction() Zero-latency fill, partial fill, and cancel notifications
Chart Interaction OnChartEvent() OnChartEvent() Interactive UI dashboards and custom on-chart buttons

4. The Strategy Tester: Multi-Threaded Cloud Computing in MQL5

Perhaps the most compelling argument for algorithmic migration is the MQL5 Strategy Tester. In MQL4, backtesting is constrained to single-currency testing on a single CPU core. Simulating an EA across 5 years of M1 data takes hours, if not days.

MQL5 introduces revolutionary quantitative backtesting capabilities:

  • True Multi-Currency Backtesting: An MQL5 robot can monitor, calculate, and execute trades across 28 currency pairs simultaneously in a single backtest run, properly calculating portfolio equity drawdown.
  • Genetic Optimization & Parallel Grid: MT5 distributes optimization parameters across all CPU cores (e.g., 16 threads on AMD Ryzen or Intel Core i9), completing tasks in minutes.
  • MQL5 Cloud Network: Developers can rent thousands of distributed CPU nodes across the globe to run millions of parameter combinations in seconds.
  • Real Tick Millisecond Precision: MT5 backtests using actual historical bid/ask tick data provided by the broker, completely eliminating the synthetic 99.9% interpolations of MQL4.

5. Architectural Step-by-Step Migration Guide

When porting your proprietary code from MQL4 to MQL5, execute these three structural refactoring steps:

  • Replace Predefined Variables: Replace legacy MQL4 variables like Ask, Bid, Digits, and Point with MQL5 equivalents: SymbolInfoDouble(_Symbol, SYMBOL_ASK), _Digits, and _Point.
  • Integrate the Standard Trade Library: Do not write low-level MqlTradeRequest structures manually. Adopt #include <Trade\Trade.mqh> and instantiate the CTrade class to handle order fills cleanly.
  • Refactor Indicator Access via Handles: In MQL4, calling an indicator like RSI was inline (iRSI(NULL, 0, 14, PRICE_CLOSE, 0)). In MQL5, indicators require creating a persistent handle in OnInit() using iRSI() and then copying values into a local array in OnTick() via CopyBuffer(). This reduces computational overhead by 90%.
Summary: While legacy MT4 bots still function on existing retail setups, MQL5 is the indisputable platform of the future for proprietary desks, prop firm evaluations, and high-performance automated trading systems.