MQL4 Development

Home Technologies MQL4 Development

Overview

MQL4 is the programming language embedded in MetaTrader 4 — the language in which all custom software for the MT4 platform is written. Expert Advisors that automate strategy execution, custom indicators that implement proprietary signal calculations and visual analysis tools, scripts that perform one-time operations on demand, and library files that provide reusable code components for other MQL4 programs — all are written in MQL4 and run within the MetaTrader 4 environment.

MT4 remains the most widely deployed retail forex and CFD trading platform in the world. Despite being a mature platform that has been available since 2005, it continues to dominate because the broker ecosystem built around it — thousands of brokers running MT4 servers — creates a network effect that keeps it relevant for retail algorithmic traders. For traders who operate through MT4 brokers, MQL4 is the primary automation and analytical tool available within the platform they use for live trading.

MQL4 is a C-style procedural language with trading-specific functions, data types, and conventions. It is not a general-purpose programming language and it is not equivalent to C or C++ despite the syntactic similarity. The trading functions — OrderSend(), OrderModify(), OrderClose(), the historical data access arrays, the broker communication functions — behave in ways that are specific to the MetaTrader 4 execution model, and understanding those behaviours is the difference between MQL4 code that works reliably in live trading and code that fails in the edge cases that only appear in production.

We provide MQL4 development for forex traders, prop firm traders, systematic trading firms, and any operation that needs professional-grade custom software for the MetaTrader 4 platform.


MQL4 Program Types

Expert Advisors. The primary automation mechanism for MT4 — MQL4 programs that run continuously within a MetaTrader 4 chart, processing each new price tick and executing trading logic automatically. Expert Advisors implement the full trading cycle: evaluating market conditions, generating entry and exit signals, calculating position sizes, placing and managing orders, and monitoring open positions.

The EA executes its main logic in OnTick() — called by the platform on every new price update — and uses MT4's trading functions to interact with the broker. OnInit() runs when the EA is attached to a chart, handling initialisation: validating inputs, setting up indicator handles, establishing initial state. OnDeinit() runs when the EA is removed, handling cleanup: closing external connections, saving state if recovery across restarts is required.

Expert Advisors can operate in the Strategy Tester for historical backtesting, which is the primary validation mechanism before live deployment. The Strategy Tester simulates market conditions from historical data and executes the EA's logic against it, producing performance statistics and a visual record of trades on the price chart.

Custom indicators. MQL4 indicator programs that calculate and display custom data on MT4 charts. Indicators run in OnCalculate() — called on every new bar or tick — computing values that are stored in indicator buffers and rendered on the chart as lines, histograms, dots, arrows, or other visual elements.

Indicators do not place trades — they compute and display data. The data they produce can be read by Expert Advisors through iCustom(), making indicators a natural way to separate signal logic from execution logic: the indicator handles the signal calculation and rendering, the EA handles the trading decisions and order management that the signal implies.

Indicators can render in the main price chart window as overlays on the price bars, or in a separate sub-window below the main chart. An indicator that renders in a sub-window has its own value scale independent of the price chart, appropriate for oscillators and normalised indicators that do not share the price axis.

Scripts. Single-execution MQL4 programs that run once when applied to a chart and terminate when their logic completes. Scripts are used for discrete operations that need to be performed on demand: closing all open positions, placing a set of pending orders, modifying stop losses on existing trades, calculating and displaying position sizing for a specified risk amount, or any other operation that a trader needs to perform quickly and reliably without the overhead of a continuously running EA.

Scripts execute in OnStart() — the single function that contains all the script's logic, running from top to bottom and terminating when it returns. Because scripts run once and terminate, they do not respond to price ticks and cannot manage ongoing trades. They are operational tools rather than automated trading systems.

Libraries. MQL4 library files that contain reusable functions and data structures shared between multiple EAs, indicators, or scripts. Library functions are compiled separately and linked to the programs that use them, allowing common logic — order management functions, risk calculation utilities, string formatting helpers — to be implemented once and reused without code duplication.


What MQL4 Development Covers

Signal generation and technical analysis. The MQL4 code that implements the market condition evaluation that drives trading decisions.

Built-in indicator access: using MT4's built-in indicator functions — iMA(), iRSI(), iMACD(), iBands(), iATR(), iStochastic() and others — to read indicator values at specified bars and timeframes. The correct parameter configuration, the correct bar offset to avoid lookahead bias, and the correct handling of insufficient historical data.

Multi-timeframe analysis: accessing price data and indicator values from timeframes other than the chart the EA is attached to. The iClose(symbol, timeframe, shift) pattern for reading price data from a higher timeframe. The synchronisation considerations that multi-timeframe access requires — the higher-timeframe bar that the current lower-timeframe bar belongs to, and the correct shift to access.

Price action analysis: direct price data access through MT4's built-in arrays (Open[], High[], Low[], Close[], Volume[], Time[]) for bar-based analysis. Candlestick pattern detection, support and resistance level identification, swing high and low detection, and the other price structure analysis that discretionary strategies use formalised in explicit MQL4 logic.

Custom indicator integration via iCustom(): calling custom indicators from within an EA and reading specific buffer values. The function signature, the buffer index, and the bar offset that correctly target the indicator value the EA logic requires.

Order management. The MQL4 functions that interact with the MT4 broker to place, modify, and close orders.

OrderSend() for new position opening: the function call with the correct operation type (OP_BUY, OP_SELL, or pending order types), the correct price (Ask for buys, Bid for sells), the lot size, the stop loss and take profit levels, the magic number for EA identification, and the slippage parameter. The return value check that confirms success or identifies the error.

Error handling: reading GetLastError() after failed order operations, classifying the error as transient (ERR_REQUOTE, ERR_PRICE_CHANGED, ERR_OFF_QUOTES — appropriate for retry) or permanent (ERR_INVALID_STOPS, ERR_INVALID_TRADE_VOLUME — requiring different handling), and applying the appropriate response.

Order selection and modification: iterating open orders with OrdersTotal() and OrderSelect(), filtering by magic number and symbol to identify the EA's own positions, and applying modifications with OrderModify() for stop loss and take profit adjustments, trailing stop logic, and breakeven moves.

Order closure: OrderClose() for market order closure with the correct lot size and price. Partial closure with a fraction of the original lot size. Handling the case where the position has already been closed externally (by stop loss, take profit, or manual action) before the EA's closure attempt.

Position sizing and risk management. The calculations that determine how much capital to risk on each trade.

Lot size calculation: computing the correct lot size for a defined percentage risk of account equity, given the entry price, the stop loss level, and the pip value for the traded instrument. The formula that correctly handles the currency pair between the account currency and the instrument's quote currency, the lot step that produces a valid lot size within the broker's constraints, and the minimum and maximum lot size bounds.

Account equity and balance access: AccountEquity(), AccountBalance(), AccountFreeMargin() for the account financial data that risk calculations depend on.

Portfolio risk controls: counting open positions by magic number and symbol, aggregating current floating P&L, calculating the total open risk from current positions, and implementing the limits that prevent the EA from opening positions that would exceed the configured aggregate risk.

Broker compatibility. MQL4 code that handles the broker-specific behaviours that affect order operations.

Execution mode detection: identifying whether the broker operates in instant execution mode (with requotes) or market execution mode (no requotes, filled at best available price). The order placement code that handles both modes correctly — retry on requote for instant execution, no retry needed for market execution.

Minimum stop distance: reading MarketInfo(symbol, MODE_STOPLEVEL) for the broker's minimum distance between order price and stop loss/take profit levels. Adjusting calculated stop levels when they fall within the minimum distance. Handling the ERR_INVALID_STOPS error that results when a stop level violates the minimum.

Symbol specifications: MarketInfo() calls for the symbol's tick size, tick value, minimum lot size, lot step, and maximum lot size — the parameters that position sizing calculations require for correctness across different instruments and brokers.

Strategy Tester compatibility. MQL4 code written to work correctly in both live trading and Strategy Tester environments.

The IsTesting() function for conditional logic that behaves differently in testing versus live trading — logging verbosity, external connectivity, and other behaviours that should differ between the two environments. IsOptimization() for code paths that should be suppressed during optimisation passes to reduce execution time.

Input parameter design: exposing the right strategy parameters as EA inputs with appropriate default values and data types, enabling the Strategy Tester's optimisation to vary them across defined ranges. Input parameter organisation that makes the EA usable without excessive configuration complexity.

External connectivity. MQL4 code that communicates with systems outside the MetaTrader platform.

File I/O: reading signal files or configuration files written by external processes, writing trade logs or data exports to files that external systems read. MT4's file I/O functions operate within the MetaTrader sandbox — the MQL4\Files directory — with the path handling that correctly targets files within this sandbox.

DLL calls: calling external DLL functions from MQL4 code using #import declarations. The P/Invoke-compatible function signatures that allow MQL4 to call C-compatible DLL exports. The data type mappings between MQL4 types and C types that ensure correct data passing across the MQL4/DLL boundary.

Debugging and diagnostics. The logging and diagnostic infrastructure that makes MQL4 code debuggable in production.

Print() and Alert() for writing diagnostic output to the MT4 Expert log and generating visual alerts. Structured log messages with sufficient context — the current symbol, the current time, the relevant indicator values, the order ticket involved — to make log entries useful for debugging without requiring the log reader to reconstruct the context.

Chart objects for visual debugging: ObjectCreate() for drawing vertical lines, horizontal lines, arrows, and text labels on the chart at specific price levels and times — the visual debugging technique that shows what the EA was seeing at specific decision points.


Production Quality Standards for MQL4

Every OrderSend() call is checked. Production MQL4 code never ignores the return value of OrderSend(). A return value of -1 indicates failure; the specific error from GetLastError() determines the correct response. EAs that ignore order placement failures accumulate position state errors that become apparent only when the position the EA believes it opened does not actually exist.

State recovery after reconnection. MT4's connection to the broker drops and reconnects during normal operation. After reconnection, the EA's understanding of its current positions may not match reality — positions may have been closed by stops or take profits during the disconnection. Position state reconciliation on reconnection — reading the actual open orders from the broker and comparing against expected state — prevents the accumulated state divergence that EAs without reconciliation develop.

Magic number discipline. Every order placed by an EA carries a magic number — the unique identifier that allows the EA to distinguish its orders from orders placed manually or by other EAs on the same account. Consistent magic number use and filtering by magic number in all position iteration code is the basis for correct multi-EA account operation.

Compilation without warnings. MQL4 code that compiles without warnings is code that the compiler has not flagged for potential issues. Treating warnings as errors during development — resolving every compiler warning rather than accepting warning-producing code — produces cleaner code and prevents the class of bugs that warnings indicate.


Technologies Used

  • MQL4 — primary development language
  • MetaEditor — integrated development environment for MQL4
  • MetaTrader 4 Strategy Tester — backtesting and optimisation environment
  • MetaTrader 4 platform — live trading deployment environment
  • C++ / C# — DLL development for external integration
  • Python — external data processing and file-based integration
  • VPS infrastructure — Windows VPS for production EA deployment

MQL4 Experience That Shows in Production

The difference between MQL4 code written by someone who understands the MetaTrader 4 execution model and code written by someone who does not is not visible in backtesting. It is visible in live trading — in the EA that handles requotes correctly instead of failing silently, in the state reconciliation that survives connectivity interruptions without accumulating errors, in the broker compatibility code that works across different execution modes without modification. These are the qualities that production MQL4 development requires and that experience with the platform's specific behaviours provides.


Professional MQL4 for Live Trading

Custom MQL4 Expert Advisors, indicators, and scripts built to production standards — with complete error handling, correct order management, proper state management, and the broker compatibility that live trading environments require.