MQL5 Development

Home Technologies MQL5 Development

Overview

MQL5 is the programming language for MetaTrader 5 — a substantially more capable language than MQL4, with full object-oriented programming support, a richer standard library, improved data structures, and the multi-symbol trading capabilities that complex systematic strategies require. Where MQL4 is a procedural language with trading functions bolted on, MQL5 is a genuinely object-oriented language that supports classes, inheritance, polymorphism, templates, and the architectural patterns that well-structured complex software requires.

The MetaTrader 5 platform builds on these language capabilities with improved infrastructure: a multi-asset trading environment that covers forex, equities, futures, and options from a single platform; a Strategy Tester that uses real tick data rather than simulated ticks, producing more accurate backtesting results; multi-symbol testing that allows portfolio strategies to be backtested across multiple instruments simultaneously; and a more capable execution model that supports both hedging and netting account modes.

The MT5 ecosystem is growing. More brokers are offering MT5 alongside or instead of MT4. Prop trading firms increasingly require MT5 for its superior account monitoring infrastructure. The broader instrument coverage makes MT5 the platform of choice for traders who want to operate across asset classes from a single platform. For new systematic trading development, MT5 is the forward-looking choice — the platform that will have the greatest broker support and development investment going forward.

MQL5's additional capabilities over MQL4 come with additional complexity. The trade execution model — the MqlTradeRequest and MqlTradeResult structures, the asynchronous execution model, the separation between orders, deals, and positions in the history — is more complex than MT4's OrderSend() and requires correct implementation that accounts for MT5's specific execution semantics. The hedging versus netting account mode distinction requires EAs to detect and handle both modes correctly. The indicator handle model replaces MQL4's direct indicator function calls with a two-step pattern of handle creation and buffer copying.

We provide MQL5 development for forex traders, prop firm traders, multi-asset systematic traders, and trading firms that need professional-grade custom software for the MetaTrader 5 platform.


MQL5 Language Capabilities

Object-oriented programming. MQL5's full OOP support enables software architecture patterns that MQL4's procedural model cannot accommodate.

Classes and objects: defining classes that encapsulate related data and behaviour — the strategy class that contains signal generation logic, the order manager class that handles all trade operations, the risk manager class that enforces position sizing and portfolio limits. Instance data maintained as class member variables. Constructor and destructor patterns for resource management.

Inheritance and polymorphism: base classes that define common interfaces with virtual methods overridden by derived classes. A strategy base class with virtual OnSignal() and OnManage() methods that derived classes implement for specific strategies, allowing the EA framework to run multiple strategy variants through the same execution infrastructure.

Templates: generic code that operates on multiple types — the typed collection that stores objects of a specific class, the generic calculation that works on any numeric type.

Standard library. MQL5's built-in standard library provides tested implementations of common trading and utility patterns that reduce the custom code required for each EA.

CTrade: the standard trade execution class that encapsulates the MqlTradeRequest/MqlTradeResult interaction pattern — the class that handles request construction, OrderSend() calling, result checking, and error reporting through a clean interface that EA code calls without implementing the raw trade request handling.

CPositionInfo: position query methods that wrap the PositionGetDouble(), PositionGetInteger(), PositionGetString() functions behind a typed interface. Position selection, property access, and the position iteration patterns that position management code uses.

COrderInfo: pending order query methods analogous to CPositionInfo. Order property access and the order iteration patterns.

CAccountInfo: account property access methods — balance, equity, margin, free margin, margin level — through a consistent typed interface.

CExpert: the base class framework for building EAs with a structured architecture — signal generation, money management, and trade management as separate components with defined interfaces.

Collection classes: CArrayObj for typed object collections, CHashMap for key-value storage, CList for linked list operations — the container types that well-structured MQL5 code uses rather than raw array management.

Improved data access. MQL5's data access model is more efficient and more capable than MQL4's for multi-symbol and multi-timeframe strategies.

CopyRates(), CopyClose(), CopyHigh(), CopyLow(), CopyOpen(), CopyTime(): functions that copy historical price data into local arrays with a single call — a more efficient and cleaner pattern than MQL4's direct array indexing for accessing historical bars.

CopyBuffer(): the function that reads indicator buffer values into a local array — the second step of the handle-based indicator access model. Together with the indicator creation function (iMA(), iRSI(), etc. in MQL5 return handles rather than values), CopyBuffer() provides the indicator value access pattern.

Multi-symbol data access: the same data access functions work for any symbol and timeframe, making multi-symbol EA development natural — the portfolio EA that accesses price data and indicator values for twenty symbols from a single OnTick() handler.


MT5 Trade Execution Model

The MT5 trade execution model differs from MT4's in ways that require specific implementation to handle correctly.

Trade requests and results. MT5 trade execution uses the MqlTradeRequest structure to specify trade parameters and the MqlTradeResult structure to receive execution results. OrderSend() takes both structures as arguments and returns bool — true for request submission success, false for failure. The result.retcode field in MqlTradeResult contains the execution result code — TRADE_RETCODE_DONE for success, other codes for specific failure conditions.

The CTrade class from the standard library abstracts this pattern — Buy(), Sell(), BuyLimit(), SellLimit(), and other methods that construct the appropriate MqlTradeRequest, call OrderSend(), and check the result, returning bool indicating success or failure. Using CTrade for trade operations eliminates the need to implement request construction and result handling in EA code.

Hedging versus netting. MT5 brokers configure their accounts in either hedging mode or netting mode. In hedging mode, each trade opens an independent position with its own ticket — similar to MT4's model. In netting mode, all trades in the same symbol are netted into a single position with a running average price.

EA logic that assumes hedging mode will produce incorrect results on netting mode accounts. Correct MT5 EA development detects the account mode using AccountInfoInteger(ACCOUNT_MARGIN_MODE) and implements position management logic appropriate to the detected mode — or explicitly documents that the EA requires hedging mode and validates this at startup.

In netting mode, position management is different: there is at most one position per symbol, its volume is the net of all buy and sell trades, and reducing the position requires a trade in the opposite direction rather than closing a specific position by ticket. EAs designed for netting mode account for this in their position sizing, direction logic, and exit handling.

Orders, deals, and positions. MT5 history separates the concepts that MT4 conflates in a single order record. An order is the trade request. A deal is the execution that results from an order. A position is the current open exposure resulting from unmatched deals. Historical trade analysis in MT5 uses HistorySelect() and HistoryDealSelect() to access the deal history — different functions from the HistoryOrderSelect() that accesses the order history.

Performance tracking, trade logging, and any EA logic that analyses past trades must use the MT5 history access model — selecting the appropriate history range, iterating deals or orders, and reading the relevant properties — rather than the MQL4 pattern that used MODE_HISTORY with OrderSelect().


What MQL5 Development Covers

Multi-strategy EA architecture. The object-oriented EA architecture that MQL5 enables for complex multi-strategy systems.

Strategy manager pattern: an EA framework class that instantiates and manages multiple strategy objects, each implementing a common interface. The framework handles OnTick() dispatch, portfolio-level risk management, and execution coordination while each strategy handles its own signal generation and position management logic. Individual strategies independently developed and tested, combined into a portfolio EA through the manager framework.

Strategy parameters as objects: strategy configuration encapsulated in parameter objects rather than scattered across input variables — the pattern that makes complex multi-strategy EAs configurable without an unmanageable input variable count.

Event-driven architecture: custom event handling between EA components using MQL5's EventChartCustom() and OnChartEvent() — strategy components that raise events when signals fire, risk components that respond to events when limits are approached.

Multi-symbol trading. MT5's native support for accessing data and placing trades across multiple symbols from a single EA instance.

Multi-symbol price monitoring: the OnTick() handler that identifies which symbol fired the tick event using _Symbol, and dispatches to the appropriate strategy handler for that symbol. Symbol subscription using ChartOpen() for symbols that the EA needs to monitor but that do not have open charts.

Multi-symbol position management: iterating positions across all symbols using PositionsTotal() and PositionGetSymbol(), aggregating portfolio-level exposure, and managing positions across the full traded universe from a single EA.

MT5 Strategy Tester optimisation. Writing EAs that work correctly with MT5's advanced testing capabilities.

Real tick data backtesting: EA logic that behaves correctly under the full tick stream that MT5's real tick data testing provides — handling every tick rather than only OHLC values, with the position management logic that operates correctly at sub-bar granularity.

Multi-symbol backtesting: EA and indicator code that works correctly when the Strategy Tester loads data for multiple symbols simultaneously — the correct symbol handling in data access and order operations that multi-symbol backtesting requires.

Custom optimisation criteria: implementing OnTester() to return a custom optimisation metric — the risk-adjusted performance measure, the Calmar ratio, or the custom metric that is more relevant to the strategy's evaluation than the default profit criterion.

Prop firm compliance EAs. MT5 EAs that enforce prop firm challenge and funded account rules as operational constraints.

Drawdown rule implementation: reading the firm's drawdown methodology from EA inputs (balance-based, equity-based from peak, trailing) and implementing the precise drawdown calculation that matches the firm's definition. Daily loss monitoring from the session's opening equity. Alert generation as drawdown approaches defined thresholds. Hard stop when limits are reached — no new trades, optional position closure.

Rule-specific enforcement: news trading restrictions enforced through economic calendar integration. Minimum trading day tracking. Consistency rule monitoring for firms that require profit distribution constraints.

WebSocket and external connectivity. MQL5's native WebSocket support for real-time external system communication.

WebSocketClient usage: establishing WebSocket connections to external servers from within MQL5 code — the signal reception system that receives signals from an external Python strategy engine, the monitoring integration that sends trade events to an external risk system. Connection management, message serialisation, and the reconnection logic that maintains WebSocket connections in long-running EAs.

HTTP requests: WebRequest() for REST API calls from MQL5 code — the external data retrieval that populates custom indicator values from an external API, the trade notification that posts to a webhook when a trade is opened.


MQL5 Indicator Development

Handle-based indicator model. MQL5 indicators use a handle-based access model distinct from MQL4's direct function calls. An indicator handle is created once — typically in OnInit() — using the indicator creation function (iMA(), iRSI(), iATR(), iCustom(), etc.). The handle is a reference to the indicator calculation object maintained by the MT5 platform. Buffer values are read from the handle using CopyBuffer() in OnCalculate() or OnTick().

Handle lifecycle management: handles created in OnInit() and released in OnDeinit() using IndicatorRelease(). Multiple handles for the same indicator with different parameters — each parameter combination requires a separate handle. The handle value of INVALID_HANDLE indicating creation failure — checked in OnInit() with the EA or indicator returning false to prevent execution with invalid indicator state.

Custom indicator architecture. The indicator structure that MQL5's improved language features enable.

Class-based calculation: encapsulating indicator calculation logic in classes that manage calculation state, handle incremental updates efficiently, and separate the calculation from the buffer management. The calculation class that maintains internal state between bar updates, updating only the current bar rather than recalculating the full history on each tick.

Multi-buffer indicators: indicators that plot multiple components — the signal line and the histogram, the upper and lower bands, the multiple moving averages — using multiple indicator buffers with appropriate plot styles and colours.


Technologies Used

  • MQL5 — primary development language for MT5
  • MQL5 Standard Library — CTrade, CPositionInfo, COrderInfo, CAccountInfo, CExpert, collection classes
  • MetaEditor — integrated development environment for MQL5
  • MetaTrader 5 Strategy Tester — real tick data backtesting, multi-symbol testing, genetic optimisation
  • MetaTrader 5 platform — live trading deployment environment
  • C++ / C# — DLL development for external integration requiring performance or system access beyond MQL5's native capabilities
  • Python — external signal generation, data processing, file-based and socket-based integration
  • VPS infrastructure — Windows VPS for production MT5 EA deployment

The MT5 Advantage, Correctly Implemented

MQL5's capabilities — object-oriented architecture, multi-symbol trading, real tick backtesting, standard library components, native WebSocket support — are genuine advantages over MQL4 for the right class of trading software. These advantages are only accessible when the MT5 execution model is implemented correctly: the trade request model handled with appropriate result checking, the hedging/netting account mode handled correctly, the indicator handle lifecycle managed properly, and the multi-symbol data access used in ways that produce correct results in both live trading and the Strategy Tester.


Professional MQL5 for MT5

Custom MQL5 Expert Advisors, indicators, libraries, and scripts built to production standards — leveraging MT5's object-oriented architecture, multi-symbol capabilities, and standard library while implementing the MT5 execution model correctly for reliable live trading operation.