MQL4 and MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
preview
Digital Signal Processing for Traders (Part 2): The Dominant Cycle, MAMA, and a Regime-Switching Expert Advisor

Digital Signal Processing for Traders (Part 2): The Dominant Cycle, MAMA, and a Regime-Switching Expert Advisor

In Part 2 we measure the market's dominant cycle using Ehlers' Hilbert-transform homodyne discriminator and wrap it as an indicator. We then build the MESA Adaptive Moving Average (MAMA) and its follower FAMA from that phase information. Finally, we combine MAMA/FAMA with the Even Better Sinewave to form a regime-switching Expert Advisor and test it on EURUSD in the Strategy Tester, giving you a complete, reproducible MQL5 implementation.
preview
Execution Cost and Slippage Sensitivity Analyzer

Execution Cost and Slippage Sensitivity Analyzer

Backtests often understate spread, commission, and slippage. This MQL5 analyzer loads closing deals and simulates rising execution costs to measure robustness. It computes the breakeven cost per deal, the cushion over an assumed cost, the net profit and profit factor at that cost, and how many winners turn into losers, then summarizes the result with an A+ to F grade and targeted guidance.
preview
Multi-Threaded Trading Robot with Machine Learning: From Concept to Implementation

Multi-Threaded Trading Robot with Machine Learning: From Concept to Implementation

The article presents a step-by-step development of a multi-threaded trading robot with machine learning in Python and MetaTrader 5. The system architecture is considered – from data collection and creation of technical indicators to training XGBoost models with portfolio risk management. The implementation of data augmentation, feature clustering via Gaussian Mixture Models, and flow coordination for parallel trading of multiple currency pairs is described in detail.
preview
A Symbol Metadata and Trading Hours Cache in MQL5: Eliminating Redundant SymbolInfo Calls in Multi-Symbol EAs

A Symbol Metadata and Trading Hours Cache in MQL5: Eliminating Redundant SymbolInfo Calls in Multi-Symbol EAs

This article presents CSymbolMetaCache, an MQL5 layer that preloads contract specifications and trading-session schedules for monitored symbols at EA startup and then serves typed getters from memory. It explains which properties are safe to cache versus dynamic ones, including the semi-dynamic tick value on cross-currency pairs, and implements an in-memory IsMarketOpen() evaluator. A benchmark quantifies latency reduction across a set of twenty symbols.
preview
Broker Reality Check (Part 1): Why Your EA Works on a Demo and Breaks on a Client's Broker

Broker Reality Check (Part 1): Why Your EA Works on a Demo and Breaks on a Client's Broker

Your Expert Advisor runs clean on your demo, then throws errors on a client's broker and quietly stops trading - and the code never changed. What changed is the broker's rulebook. This first article of the Broker Reality Check series builds a diagnostic EA that reads every relevant symbol trading condition - filling policy, stops and freeze levels, volume step, trade mode, swap and the triple-swap day - and flags the ones that silently break EAs, in plain language. It shows a green/amber/red panel, prints a report and dumps every Market Watch symbol to CSV, so you see why an OrderSend fails (10030, invalid stops, invalid volume) before it costs you a trade.
preview
The MQL5 Standard Library Explorer (Part 14): Building a Dynamic Hedge EA with the ALGLIB Port (ap.mqh)

The MQL5 Standard Library Explorer (Part 14): Building a Dynamic Hedge EA with the ALGLIB Port (ap.mqh)

This article introduces ap.mqh, the ALGLIB port for MQL5, and demonstrates its use in multi‑asset workflows that require robust linear algebra. It covers why built-in indicators fall short, then implements polynomial regression, a rolling correlation matrix indicator, and an adaptive hedge ratio estimator using ridge regression with Cholesky. Practical code shows how to compute spread z‑scores and execute coordinated pairs trades entirely within MetaTrader 5.
preview
Mapping Dealer Gamma Exposure (GEX) in MetaTrader 5: Walls, the Zero-Gamma Flip, and a Chart Overlay

Mapping Dealer Gamma Exposure (GEX) in MetaTrader 5: Walls, the Zero-Gamma Flip, and a Chart Overlay

In this article we build a dealer gamma-exposure map in MQL5. From an option chain, the tool computes per-strike GEX, finds the call and put walls, and solves for the zero-gamma flip that separates a mean-reverting regime from a trending one, then draws it all on the chart. CSV and native-symbol data paths included.
preview
Constructing a Trade Replay Engine in MQL5: Stepping Through Historical Trades Bar by Bar for Manual Review

Constructing a Trade Replay Engine in MQL5: Stepping Through Historical Trades Bar by Bar for Manual Review

An MQL5 script reconstructs closed trades from raw deal history and replays them on the chart bar by bar, drawing entry, exit, stop, target, and an annotation with per‑trade statistics. Four classes separate concerns: a trade data record, history reconstruction with a two‑pass SL/TP lookup and partial‑close aggregation, chart rendering, and a controller with polling‑based keyboard navigation. This enables consistent, fast visual review of each trade in its original candlestick context.
preview
Dingo Optimization Algorithm (DOA)

Dingo Optimization Algorithm (DOA)

The article presents a new metaheuristic method based on the hunting strategies of Australian dingoes: group attack, chase, and scavenging. Let's see how the Dingo Optimization Algorithm (DOA) performs algorithmically.
preview
Online Linear Regression with Recursive Least Squares in MQL5: A Parameter-Free Adaptive Trend Estimator

Online Linear Regression with Recursive Least Squares in MQL5: A Parameter-Free Adaptive Trend Estimator

This article implements recursive least squares in native MQL5 with a constant O(1) update per bar, avoiding the per‑bar O(n) rebuild of a rolling OLS. It derives and codes the Sherman–Morrison rank‑1 update, explains the forgetting factor through its effective window, and provides a reusable class. Two coordinated indicators plot a 1‑step‑ahead price forecast on the chart and the signed slope in a correctly scaled subwindow for practical trend tracking.
preview
How To Profile MQL5 Code in MetaEditor

How To Profile MQL5 Code in MetaEditor

This article profiles a rolling z-score indicator with bands using MetaEditor's built-in sampling profiler. We read the Total CPU and Self CPU columns and follow the heat‑mapped source to the true hotspots, replace window rescans with sliding accumulators, remove a redundant array copy, and honor prev_calculated. The result is the same output with measured samples reduced from roughly 7,050 to 59.
preview
Creating a Profit Concentration Analyzer in MQL5

Creating a Profit Concentration Analyzer in MQL5

Net profit and win rate tell you how much a strategy made, not how the result is distributed. This article builds a native MQL5 script that reads your closed trades and measures profit concentration: the top-N trade share, the Gini coefficient of the winners, an outlier-dependence stress test that removes the best few winners, and the largest day against a prop-firm consistency limit. It combines these into one A+ to F score with recommendations, running inside MetaTrader 5.
preview
Building a Hierarchical Market Structure Framework (Prototype) in MQL5 Using Modular Architecture and Event-Driven Design

Building a Hierarchical Market Structure Framework (Prototype) in MQL5 Using Modular Architecture and Event-Driven Design

This article describes a prototype reusable market structure framework for MQL5, built with a clean modular architecture and an internal event queue. It shows how to detect swing points, classify break-of-structure and change-of-character events, maintain a deterministic market state, and persist data to CSV. The focus is entirely on software engineering, component separation, and extensibility, not on trading signals. The prototype is a foundation for further development, not a production-ready library.
preview
Trust Your Backtest Data First: Building a Reproducible Historical Data Audit in Python for MetaTrader 5

Trust Your Backtest Data First: Building a Reproducible Historical Data Audit in Python for MetaTrader 5

A reproducible, read-only Python audit for MetaTrader 5 that verifies history quality before any backtest. It exports M5 data from multiple terminals, detects gaps and synthetic bars by timestamp spacing, and reports coverage per year. The same deterministic strategy then runs on three broker feeds over a common window to quantify result drift and decompose it into spread, data/price, and trade effects.
preview
Detecting Structural Breakpoints in Price Series Using CUSUM in MQL5 (Part 1): From Statistical Theory to a Working MQL5 Indicator

Detecting Structural Breakpoints in Price Series Using CUSUM in MQL5 (Part 1): From Statistical Theory to a Working MQL5 Indicator

This article builds a sequential CUSUM breakpoint detector for MetaTrader 5, starting from the statistical construction and ending with a working indicator. It explains standardized log-returns, dual accumulators, the role of k and h, and the ARL₀ baseline from Siegmund. The code walkthrough covers buffer persistence, recalculation handling, idempotent chart objects, and a three-pass engine, so you can compile, attach, and use the detector to flag structural regime shifts earlier than fixed-window smoothers.
preview
Market Microstructure in MQL5 (Part 8): Micro-Trend Strength

Market Microstructure in MQL5 (Part 8): Micro-Trend Strength

Part 8 adds bar-by-bar micro-trend scoring for NQ M1. GetMicroTrendStrength() builds a continuous [-1, +1] composite from EMA alignment, ATR‑normalized price position, slope consistency, and volume, with a contradiction penalty to suppress alignment/price conflicts. Session-adaptive thresholds scale by Part 7 confidence to modulate signal frequency across regimes. Outputs include a seven-state label, a binary signal, and a persistence check, calibrated on 514 New York sessions (May 2024–May 2026).
preview
From Basic to Intermediate: Random Access (II)

From Basic to Intermediate: Random Access (II)

In this article, we will examine how two slightly different approaches can significantly affect the overall implementation strategy, both in performance and in disk I/O design, while helping to prevent compatibility issues between applications.
preview
MetaTrader 5 Machine Learning Blueprint (Part 19): Bagging Regimes

MetaTrader 5 Machine Learning Blueprint (Part 19): Bagging Regimes

We test AFML's claim that the sequential bootstrap decorrelates bagged trees on overlapping triple‑barrier labels by isolating two levers: draw count and draw rule. One decision identical tree is bagged under four row‑sampling regimes and evaluated on EURUSD 2022–2023 for draw uniqueness, between‑tree correlation, AUC, and calibration. Decorrelation comes almost entirely from throttling max_samples to average uniqueness; the sequential draw adds little. Out-of-bag inflation is largest under full-count sequential sampling.
preview
Building an Interactive AnchorFlow Volume Profile Indicator (MTF) in MQL5

Building an Interactive AnchorFlow Volume Profile Indicator (MTF) in MQL5

We implement an interactive, anchored multi-timeframe volume profile in MQL5 for MetaTrader 5. The indicator draws the current-timeframe profile on the main chart and a higher timeframe profile in a subwindow, both aligned by a draggable anchor and the visible range. You will learn keyboard-driven bin editing (E/S double-click), robust timeframe validation, viewport-aware updates, and object restoration to build a reliable, synchronized volume workflow.
preview
Algorithmic Arbitrage Trading Using Graph Theory

Algorithmic Arbitrage Trading Using Graph Theory

In this article, triangular arbitrage is presented as a problem of finding cycles in a directed graph, where the vertices are currencies and the edges are currency pairs with weight rates. Profitable cycle: product of weights >1. Our Floyd-Warshall and DFS algorithms find optimal currency exchange paths that return to the starting point with a profit.
preview
Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

We describe an MQL5 framework that aligns entries with session rhythms and scheduled clock events. A script identifies the broker's time zone and DST by detecting NFP spikes on EURUSD and matching them to EU/US/AU transition dates, producing EA‑ready settings. Session-to-broker time conversion and 15-minute marks constrain execution. A multi‑timeframe AMA signal aggregates trends for strategy selection and optimization.
preview
Market Simulation: Position View (V)

Market Simulation: Position View (V)

Despite what was shown in the previous article, all of this may seem simple at first. In reality, several problems remain, along with many tasks that still need to be completed. You, dear reader, may imagine that everything is easy and straightforward. Out of inexperience, you may simply accept whatever is presented to you. And that is a mistake you should try to avoid. Even worse is trying to use something without truly understanding what exactly you are using. Beginners often pass through a copy-and-paste stage. If you do not want to remain stuck at that stage forever, you should learn how to use certain tools. One of the tools most often used by programmers is documentation. The second is testing, supported by log files. Here we will see how to do this.
preview
From Basic to Intermediate: Random Access to Files (I)

From Basic to Intermediate: Random Access to Files (I)

In today's article, we will explore random access to file contents for the first time. This applies to both writing and reading information stored in a file. However, since the topic is too broad to cover in a single article, we will limit ourselves here to an introduction to random access.
preview
Foundation Models for Trading (Part I): Porting Kronos to Native MQL5

Foundation Models for Trading (Part I): Porting Kronos to Native MQL5

Kronos is a pretrained transformer that models OHLCV bars the way a language model predicts words. We reimplement its tokenizer/encoder and transformer block in native MQL5, export weights to flat .bin files, and remove Python from runtime entirely. Part 1 delivers preprocessing and BSQ tokenization plus a bit-for-bit verification harness against PyTorch, so you can run the encoder inside MetaTrader 5 with confidence.
preview
Entropy-Based Market Efficiency Indicator in MQL5: Measuring Randomness in Price Returns Using Approximate Entropy

Entropy-Based Market Efficiency Indicator in MQL5: Measuring Randomness in Price Returns Using Approximate Entropy

A rolling-window Approximate Entropy oscillator for MQL5, built without external dependencies. Covers the full mathematics of template matching, Chebyshev distance, and the Phi-function derivation before presenting a reusable CApEnCalculator class and a color-zoned subwindow indicator. Includes a synthetic-data verification script and an honest discussion of bias, parameter sensitivity, and computational cost.
preview
Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

This article shows how to build a synthetic custom symbol in MQL5 by averaging OHLC data from multiple instruments into a single derived price series. It covers symbol collection and validation, custom symbol creation and configuration, timestamp alignment, historical reconstruction, and lightweight live updates. The result is a reusable method for creating synthetic instruments suitable for correlation analysis, index-style modeling, indicator development, and strategy testing.
preview
Beyond the Clock (Part 4): Efficacy of Bars on Trending and Mean-Reversion Strategies

Beyond the Clock (Part 4): Efficacy of Bars on Trending and Mean-Reversion Strategies

Does better return conditioning buy strategy performance? We hold bar count fixed across time, tick, tick-imbalance, and tick-runs on 60.5 million EURUSD ticks, then meta-label RSI, Bollinger, and ADX/DI entries and score with purged cross-validation. No family delivers a consistent edge; efficacy varies narrowly and the best case fails a permutation test. Readers learn how to control overlap, leakage, and multiple testing in bar studies.
preview
Market Simulation: Position View (IV)

Market Simulation: Position View (IV)

Here we will start bringing together different components or applications that were previously completely isolated from each other. Chart Trade, the mouse indicator, and the Expert Advisor had already been linked to one another, but there was still no way to directly display on the chart the positions open on the trading server, which are often managed using a cross-order system. From this point on, this becomes possible, opening the way for various ideas and future implementations. Although we are only beginning to put these components into operation, we already have a direction for further development.
preview
From Basic to Intermediate: FileSave and FileLoad

From Basic to Intermediate: FileSave and FileLoad

In today’s article, we will look at several ways to work with the FileSave and FileLoad library functions. Although many people consider them of limited use because of certain limitations or difficulties they create in specific scenarios, properly understanding how these two functions work can save us a great deal of effort at certain points. They are also an excellent way to work with log files.
preview
Trading Robot Based on a GPT Language Model

Trading Robot Based on a GPT Language Model

The article presents a complete implementation of TimeGPT, a specialized Transformer-based architecture for forecasting financial time series on the MetaTrader 5 platform. Adaptation of the attention mechanism to financial data, selective tokenization of price changes, hardware-aware optimizations, and advanced learning techniques are discussed. Included are practical testing results showing 87% forecast accuracy over a 24-bar horizon with a training time of 15 minutes on the CPU. We also present a ready-made trading EA with automatic retraining.
preview
Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

This article shows how to build an MQL5 Expert Advisor around the UT Bot Alerts indicator. The EA reads custom indicator signals via iCustom() and CopyBuffer(), evaluates entries only on new bars, using the last closed candle at index 1, and enforces a one-direction-at-a-time model by closing opposite positions before taking new entries. It also adds optional ATR-based stop-losses, reward-to-risk take-profits, dedicated buy/sell execution functions, magic-number tracking, and basic backtesting for repeatable evaluation.
preview
Creating an Interactive Portfolio Analyzer Dashboard with CCanvas in MQL5

Creating an Interactive Portfolio Analyzer Dashboard with CCanvas in MQL5

This article presents a standalone Portfolio Analyzer dashboard implemented as an Expert Advisor for MetaTrader 5. It reads account deal history, reconstructs closed positions, and attributes results by magic number or normalized comment to deliver clear per-strategy metrics. The interface provides a vector equity curve, date filters, and strategy selectors, plus a Pearson correlation matrix to reveal strategy redundancy. You can attach it to a separate chart without modifying existing trading EAs.
preview
Exponentially Weighted Covariance Matrix in MQL5: Building an Adaptive Correlation Monitor for Multi-Symbol EAs

Exponentially Weighted Covariance Matrix in MQL5: Building an Adaptive Correlation Monitor for Multi-Symbol EAs

This article builds a constant-memory EW covariance engine and a chart heatmap for monitoring cross-symbol correlations in MQL5. CEWCovariance updates in O(N²) time per bar and exposes covariance/correlation accessors; CHeatmapRenderer shows a five‑symbol matrix with values and colors. You will learn λ-to‑window mapping, how to set a meaningful min_obs warm‑up, and how to size the variance guard epsilon for real FX M1 data.
preview
N-BEATS Network-Based Forex EA

N-BEATS Network-Based Forex EA

Implementation of the N-BEATS architecture for Forex trading in MetaTrader 5 with quantile forecasting and adaptive risk management. The architecture is adapted through bilinear normalization and specialized loss functions for financial data. Backtesting on 2025 data shows inability to generate profits, confirming the gap between theoretical achievements and practical trading performance.
preview
From Option Chain to 3D Volatility Surface in MetaTrader 5

From Option Chain to 3D Volatility Surface in MetaTrader 5

This article walks through creating an MT5 indicator that ingests option chains from native symbols or CSV, inverts prices to implied volatility via a hybrid Newton–Raphson/bisection method, and assembles a clean strike–expiry grid. It then renders a shaded, rotatable 3D surface with the platform's DirectX layer, enabling clear, in-terminal analysis of skew and term structure using live or file-based data.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part III): Zone Analysis, Stateful Interaction, and Pending Event Management

Interactive Supply and Demand Zone Manager in MQL5 (Part III): Zone Analysis, Stateful Interaction, and Pending Event Management

We extend the stateful supply and demand framework for MetaTrader 5 with a quantitative admission model and a dedicated interaction engine. Candidate zones are scored by structural symmetry, volume participation, and ATR‑normalized displacement, then classified into objective tiers. Admitted zones follow a deterministic lifecycle that tracks first touch, validates bounces, or confirms breakouts, with full telemetry for analysis and reproducibility.
preview
Persistence Entropy as a Market Regime Indicator in MQL5

Persistence Entropy as a Market Regime Indicator in MQL5

This article turns the verified TDA pipeline into a live MQL5 indicator. It reduces each price window to two persistence-entropy lines (H0 and H1), computes a normalized loop-strength metric with an adaptive percentile band, and places fade marks only when loop strength is high and price hits a window extreme. You can attach the indicator, read six buffers from an Expert Advisor, and tune key window, ranking, and performance parameters.
preview
Building an Object-Oriented Order Block Engine in MQL5

Building an Object-Oriented Order Block Engine in MQL5

The article presents a production-oriented Order Block engine for MQL5 packaged as an include class, it validates zones via displacement and market structure break, maintains mitigation state only on closed bars, and avoids heavy copies by passing data by reference. A diagnostic indicator plots zones, and an EA gates logic to new bars for stable performance and reproducible tests.
preview
Encoding Candlestick Patterns (Part 4): Frequency Analysis for Double-Candlestick Structures

Encoding Candlestick Patterns (Part 4): Frequency Analysis for Double-Candlestick Structures

This article extends single-candlestick analysis to ordered double-candlestick patterns using an MQL5 script. The script encodes candles into symbols, extracts every consecutive two-symbol sequence (treating Aa and aA as different), counts occurrences and percentages, and writes sorted frequency tables to a text file. Readers can quickly identify the most recurrent transitions by symbol, timeframe, and lookback for further statistical testing.
preview
Neural network trading EA based on PatchTST

Neural network trading EA based on PatchTST

The article presents the revolutionary architecture of PatchTST, a tailored transformer for financial time series analysis that breaks market data into 16-bar patches for efficient processing. We will discuss the full implementation of a trading robot in MQL5 covering everything from mathematical fundamentals and data structures to a ready-made EA with risk management and continuous learning systems.