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
Gaussian Processes in Machine Learning (Part 2): Implementing and Testing a Classification Model in MQL5

Gaussian Processes in Machine Learning (Part 2): Implementing and Testing a Classification Model in MQL5

In this section, we will look at the implementation of the key interfaces of the library of Gaussian processes in MQL5: IKernel, ILikelihood, and IInference. We will also demonstrate its operation on synthetic data and implement indicators for classification and regression, demonstrating its operation in online mode - with retraining of the model on each new bar.
preview
Linear Regression Prediction Channels in MQL5: Constructing Statistically Grounded Confidence and Prediction Bands

Linear Regression Prediction Channels in MQL5: Constructing Statistically Grounded Confidence and Prediction Bands

The article implements rolling OLS regression channels in MQL5 and computes confidence and prediction bands with Student's t critical values instead of a fixed standard-deviation multiplier. It explains the leverage-driven widening at window edges, contrasts the result with Bollinger and Donchian channels, and reviews OLS assumptions on price data. A five-line rendering is documented to ensure reliable display in MetaTrader 5.
preview
The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

The MQL5 Standard Library Explorer (Part 13): Implementing the Math Solvers Library in Trading

We present a complete workflow for adaptive filtering in MQL5 using the CNlEq Levenberg–Marquardt–like solver. The EA fits a VAMAC model—two EWMAs with an ATR‑based scaling—by supplying residuals and a Jacobian through CNlEq's reverse‑communication loop, with optional numerical or analytical derivatives. Code, setup instructions, and GBPUSD H1 tests show how to replace static thresholds with on‑bar re‑estimation.
preview
Meta-Labeling the Classics (Part 2): Filtering and Sizing ADX Trades

Meta-Labeling the Classics (Part 2): Filtering and Sizing ADX Trades

The DI crossover often triggers in ranges where +DI and -DI oscillate without persistence. We build a two-layer hybrid: Optuna's TPE optimizes a regime gate over ADXR threshold, DI lookback, and minimum DI separation to maximize signal precision on a held-out window, then a Random Forest uses eleven ADX-derived features to accept or scale entries via afml.bet_sizing. The result filters ranging-market bursts and calibrates position size on EURUSD H1.
preview
Designing a Strategy State Machine in MQL5: Replacing Nested If-Else Logic with Formal States

Designing a Strategy State Machine in MQL5: Replacing Nested If-Else Logic with Formal States

Nested if-else logic inside OnTick() creates implicit states that are hard to isolate, debug, and extend without regressions. A formal finite state machine in MQL5 uses an IState interface, a CStrategyContext mediator, and four concrete states to separate detection from behavior. A three-file include structure resolves circular dependencies and keeps declarations, definitions, and instantiation clean, making changes safer and debugging faster.
preview
MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

We add a tabbed settings window opened from the ribbon and bound to the selected object. The tabs — Style, Text, Coordinates, and Visibility — are built from the same descriptor system, with scrolling, per-level rows, and shared color/width/style popovers. The article covers layout, rendering, interaction, and inline price/time and numeric editing. You get one place to edit every property with live preview and commit-or-discard on close.
preview
From Cloud to Complex: The Vietoris-Rips Filtration in MQL5

From Cloud to Complex: The Vietoris-Rips Filtration in MQL5

We turn a price-embedded point cloud into a Vietoris–Rips filtration and its boundary matrix. The article enumerates vertices, edges, and triangles with filtration values, sorts them in entry order, and builds O(1) vertex/edge lookups. You get MQL5 classes CTDARips and CTDABoundary and a sparse Z/2 boundary suitable for the next-step persistence reduction.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part II): Event-Driven Architecture and Persistent Lifecycle Logging

Interactive Supply and Demand Zone Manager in MQL5 (Part II): Event-Driven Architecture and Persistent Lifecycle Logging

This article advances the stateful supply and demand zone framework for MetaTrader 5 by replacing polling with an event-driven model based on OnChartEvent(). We split synchronization into dedicated handlers for creation, modification, and deletion, and separate market logic in OnTick() from user interactions in OnChartEvent(). A persistent, append-only CSV logger records all lifecycle events, improving responsiveness, state consistency, and recoverable history for downstream analysis.
preview
Artificial Atom Algorithm (A3)

Artificial Atom Algorithm (A3)

The article describes implementation of the A3 algorithm - a metaheuristic optimization method inspired by chemical processes - in MQL5. Only two adjustable parameters, compactness and a small population, ensure high operating speed with sufficient quality of solutions.
preview
Quantum Neural Network in MQL5 (Part III): A Virtual Quantum Processor Based on Qubits

Quantum Neural Network in MQL5 (Part III): A Virtual Quantum Processor Based on Qubits

The article focuses on creating a trading system with a real quantum simulator instead of mathematical analogies. The system uses 3 virtual qubits, quantum gates and superposition principles to analyze markets. It is implemented as a trading EA for MetaTrader 5 in MQL5. The main achievement is the transition from simulation to real quantum principles of financial information processing.
preview
MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

MQL5 Wizard Techniques you should know (Part 98): Using an Unscented Kalman Filter and a Capsule Network in a Custom Signal Class

This article presents 'CSignalUKFCapsNet', as a custom class coded in MQL5. This class is meant to be used with the MQL5 Wizard when assembling an Expert Advisor and when selected in the Wizard it defines the Expert Advisor's entry signals. In building this custom class, we brought together the algorithm Unscented Kalman Filter and the Capsule Neural Network. Our algorithm is showcased with four operation modes, and the coding of this as a custom class for the MQL5 Wizard, allows testing with various Trailing Stop methods and Money Management systems.
preview
Encoding Candlestick Patterns (Part 3): Frequency Analysis for Single Candlestick Type Structure

Encoding Candlestick Patterns (Part 3): Frequency Analysis for Single Candlestick Type Structure

This article introduces a frequency-analysis framework for encoded candlestick patterns in MQL5. By transforming candlesticks into alphabetic symbols, historical price action can be analyzed as a statistical sequence rather than a visual chart. Using GBPUSD and Gold across multiple timeframes, the study examines the occurrence frequency of individual candlestick types, identifies dominant market structures, and reveals the symmetry between bullish and bearish price movements. The results establish a quantitative foundation for pattern discovery and prepare the way for analyzing multi-candlestick sequences and their predictive potential in algorithmic trading systems.
preview
CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

CSV Data Analysis (Part 5): Real-Time CSV Streaming from Live MetaTrader 5 Sessions

This article describes a live data export framework for MetaTrader 5 built around a decoupled, three‑layer design. The MQL5 component batches bar and tick records via a write buffer and rotates CSV files daily; a Python daemon tails the stream, renders a live dashboard, and flags anomaly thresholds. The demo indicator illustrates integration points, enabling real‑time monitoring and auditability during trading sessions.
preview
Market Simulation: Getting Started with SQL in MQL5 (V)

Market Simulation: Getting Started with SQL in MQL5 (V)

In the previous article, I showed how to proceed in order to add a query mechanism. This was needed so that, inside MQL5 code, you could fully use SQL and retrieve results using an SQL SELECT query. But there is still one last function we need to implement. This is the DatabaseReadBind function. Since understanding it properly requires a slightly more detailed explanation, it was decided to cover it not in the previous article, but in today's article. So, since the topic will be fairly extensive, let us proceed directly to the next section.
preview
From Basic to Intermediate: Object Events (II)

From Basic to Intermediate: Object Events (II)

In this article, we will look at how the last three types of events generated by an object work. Understanding this will be very interesting, because in the end we will do something that may seem crazy to many people, but it is entirely possible and produces a very surprising result.
preview
Community of Scientists Optimization (CoSO): Practice

Community of Scientists Optimization (CoSO): Practice

We resume the topic of optimization by the scientific community. CoSO should not be viewed as a ready-made solution, but as a promising research platform. With proper development, CoSO can find its niche in tasks where adaptability and resilience to change are important, and computation time is not critical.
preview
Market Microstructure in MQL5 (Part 6): Order Flow

Market Microstructure in MQL5 (Part 6): Order Flow

This article adds six order-flow functions and a new OrderFlowAnalysis struct to MicroStructureFoundation.mqh: VPINOHLC, signed flow imbalance, trade intensity versus a 20-session baseline, a late-minus-early smart-money index, flow momentum, and a wrapper that outputs a confidence weight. Flow confidence is gated by noise and jump intensity from Parts 5 and 4. Calibrated on 602 NQ M1 NY sessions, it provides ready-to-use intraday flow signals with documented thresholds.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 3): Alerting and Automated Trading from Manually Drawn Objects

How to Detect and Normalize Chart Objects in MQL5 (Part 3): Alerting and Automated Trading from Manually Drawn Objects

This article extends the chart‑object detector into a modular monitoring and execution layer. It defines objective interaction rules (touch, cross, breakout) for trendlines, Fibonacci levels, channels, rectangles, and pitchforks, then routes events through an interaction detector, alert manager, and optional trade executor. Orders use object geometry for stop‑loss and take‑profit. The result is a reproducible pipeline that converts static drawings into actionable alerts and, if enabled, trades.
preview
Beyond GARCH (Part VI): Fractional Brownian Motion And The Multiplicative Cascade in MQL5

Beyond GARCH (Part VI): Fractional Brownian Motion And The Multiplicative Cascade in MQL5

This article implements the MMAR Simulation Engine that turns fitted parameters (H, distribution, coefficients, sample volatility) into synthetic price paths. It builds multifractal trading time via a multiplicative cascade, synthesizes fractional Brownian motion with Davies–Harte or Cholesky, scales it to target volatility, and composes the process by time deformation. Readers get a reusable MQL5 class, method choices by path length, and validation steps for scenario testing and Monte Carlo use in the next part.
preview
Price Action Analysis Toolkit Development (Part 74): Building an MQL5 Expert Advisor from Indicator Buffers

Price Action Analysis Toolkit Development (Part 74): Building an MQL5 Expert Advisor from Indicator Buffers

This article implements an MQL5 Expert Advisor that connects to a weekend gap indicator via iCustom and CopyBuffer, reading six buffers for buy/sell signals and SL/TP. It validates broker stop-distance rules, handles closed-bar confirmation and duplicate-signal control, and executes orders with a configurable magic number. The EA also includes midpoint stop-loss management and a backtesting procedure so you can verify behavior and adapt parameters to your setup.
preview
Building a Traditional Point and Figure Indicator in MQL5

Building a Traditional Point and Figure Indicator in MQL5

This article implements a custom Point and Figure indicator in MQL5 that maps price movement into X/O columns using a fixed box size and three-box reversal logic. We define the base price, convert prices into box intervals, manage trends and reversals, auto-scale the indicator window, and render symbols with objects, providing a clean, time-independent view of trends, breakouts, and support/resistance.
preview
Rolling Sharpe Ratio with Statistical Significance Bands in MQL5

Rolling Sharpe Ratio with Statistical Significance Bands in MQL5

This article presents a custom MetaTrader 5 indicator that computes a rolling annualized Sharpe ratio and plots configurable z-score significance bands based on Lo's asymptotic standard error. It uses a circular return buffer with incremental variance to keep O(1) updates. We explain the n^(-1/2) uncertainty scaling, the inflation of intervals at high Sharpe values, and how to set per-instrument annualization for correct deployment.
preview
A Practical Kalman Filter Price Smoother in MQL5: Adaptive Noise Estimation Without External Libraries

A Practical Kalman Filter Price Smoother in MQL5: Adaptive Noise Estimation Without External Libraries

Fixed-weight moving averages introduce regime-insensitive lag. This work presents an adaptive scalar Kalman filter indicator in native MQL5 that estimates process noise Q from rolling return variance and measurement noise R from rolling price variance, with floor clamps for stability, and recomputes the Kalman Gain on every bar. The chart-overlay output is benchmarked against a 20-period EMA using MAE, RMSE, lag, and smoothness metrics to quantify tracking and noise suppression.
preview
From Basic to Intermediate: Object Events (I)

From Basic to Intermediate: Object Events (I)

In this article, we will look at three of the six events that MetaTrader 5 can generate when some change occurs to an object on the chart. These events are very useful from the standpoint of user interaction. This is because, without understanding these events, we would have to put in much more effort to maintain a specific chart configuration when trying to manage objects for particular purposes.
preview
From Basic to Intermediate: Objects (III)

From Basic to Intermediate: Objects (III)

In today's article, we will look at how to implement a very attractive and interesting interaction system, especially for those who are just beginning to practice programming in MQL5. There is nothing fundamentally new here. Thanks to my approach to the topic, it will be much easier to understand everything, because we will see in practice how to develop a program using a structured approach with a practical and engaging goal.
preview
Quantum Neural Network in MQL5 (Part II): Training a Neural Network with Backpropagation on ALGLIB Markov Matrices

Quantum Neural Network in MQL5 (Part II): Training a Neural Network with Backpropagation on ALGLIB Markov Matrices

The article presents an innovative quantum neural network architecture for algorithmic trading that combines the principles of quantum mechanics with modern machine learning methods. The system includes quantum effects (resonance, interference, decoherence), multi-level memory of different time scales, Markov chains with the ALGLIB library, and adaptive parameter control. The full implementation is done in MQL5 using the built-in matrix/vector types, which removes implementation barriers in MetaTrader 5.
preview
AI Trading Platform: Why MetaTrader 5 Is the Best Choice for Algorithmic Trading with Python, ONNX, and AI Assistant

AI Trading Platform: Why MetaTrader 5 Is the Best Choice for Algorithmic Trading with Python, ONNX, and AI Assistant

MetaTrader 5 is well suited for AI trading because it combines market data, MQL5 development, Python research, ONNX models, Strategy Tester, VPS, and the MQL5.community ecosystem into a single workflow. This article demonstrates a practical path from AI prompts to structured signals, working with code via the AI Assistant in MetaEditor, a quality model, a custom-created Expert Advisor, testing, and a controllable launch of a trading system.
preview
Trading Options Without Options (Part 2): Use in Real Trading

Trading Options Without Options (Part 2): Use in Real Trading

The article considers simple options strategies and their implementation in MQL5. We will develop a basic EA that will be modernized and become more complex.
preview
MQL5 Wizard Techniques you should know (Part 97): Using Convex Hull and a miniature GRU Network in a Custom Trailing Stop Class

MQL5 Wizard Techniques you should know (Part 97): Using Convex Hull and a miniature GRU Network in a Custom Trailing Stop Class

For this article we look at a custom MQL5 Wizard class for Trailing Stops. Our implemented custom class ‘CTrailingConvexHullGRU’, is built from merging the Convex Hull algorithm with a GRU network. As always we seek to develop a model that is testable with MQL5 Wizard-Assembled Expert Advisors and can be tuned with various Money Management and entry Signals classes. Our testing is with the 'Envelopes' and the RSI classes for Signal.
preview
Beyond the Clock (Part 3): Building an Indicator Window for Alternative Bars in MQL5

Beyond the Clock (Part 3): Building an Indicator Window for Alternative Bars in MQL5

AlternativeBarsViewer is a subwindow indicator that renders all ten alternative bar types as color‑coded candles using the same CBarConstructor hierarchy as BarBuilderEA, ensuring identical bars. It supports three data sources (real ticks, synthetic OHLC ticks, or the EA's CSV) and two render modes (TIME and INDEX) toggleable at runtime. Degenerate bars are highlighted and summarized on a compact panel, enabling live calibration without leaving the terminal.
preview
Building a Divergence System: Creating the MPO4 Custom Indicator

Building a Divergence System: Creating the MPO4 Custom Indicator

We introduce MPO4, a pressure-based oscillator that emphasizes the body and direction of candles in the context of current volatility. The article details its mathematics, normalization into a bounded range, and the EMA smoothing, then builds a pivot-driven divergence module designed not to repaint. You get complete MQL5 implementation and practical guidance for interpreting signals, including a comparison with RSI as an alternative source.
preview
Implementing the Decorator Pattern in MQL5: Adding Logging, Timing, and Filtering to Any Indicator Non-Invasively

Implementing the Decorator Pattern in MQL5: Adding Logging, Timing, and Filtering to Any Indicator Non-Invasively

Cross-cutting concerns like logging, timing, and threshold filtering should not live inside indicator classes. We show how to apply the decorator pattern in MQL5 with a shared IIndicator interface, an owning CBaseDecorator, and concrete CLoggingDecorator, CTimingDecorator, and CThresholdFilterDecorator layers. You can stack behaviors per EA, keep computation code closed to modification, and get deterministic cleanup by deleting only the outermost decorator.
preview
Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (Final Part)

Neural Networks in Trading: LSTM Optimization for Multivariate Time Series Forecasting (Final Part)

We continue to implement the DA-CG-LSTM framework, which offers innovative methods for time series analysis and forecasting. The use of CG-LSTM and dual attention allows for more accurate detection of both long-term and short-term dependencies in data, which is particularly useful for working with financial markets.
preview
Market Simulation: Getting started with SQL in MQL5 (IV)

Market Simulation: Getting started with SQL in MQL5 (IV)

Many people tend to underestimate SQL, or even not use it at all, because they do not fully understand how it actually works. When running queries against an SQL database, we are not always looking for a universal answer; in some cases, we need a very specific and practical answer. If a database is created with a proper structure and data model, almost any type of information can be integrated into it.
preview
From Basic to Intermediate: Handling Mouse Events

From Basic to Intermediate: Handling Mouse Events

This article belongs to the category of materials where simply looking through and studying the code is definitely not enough to understand the processes involved. In fact, you need to create an executable application and run it on any chart. This is done so that you can understand small details that would otherwise be extremely difficult to grasp, such as using the keyboard and mouse together to create certain elements.
preview
Community of Scientists Optimization (CoSO): Theory

Community of Scientists Optimization (CoSO): Theory

Secrets of effective optimization of trading strategies in metaheuristic approaches. Community of Scientists Optimization is a new population-based algorithm inspired by the mechanisms of the scientific community. Unlike traditional nature-inspired metaphors, CoSO models unique aspects of human scientific activity: publishing results in journals, competing for grants, and forming research teams.
preview
Shape of Price: An Introduction to TDA and Takens Embedding in MQL5

Shape of Price: An Introduction to TDA and Takens Embedding in MQL5

The article presents a practical foundation for shape analysis of price series in MQL5. It implements Takens time‑delay embedding to build a phase‑space point cloud and computes the full pairwise distance matrix under selectable norms. The CTDAPointCloud and CTDADistance classes are provided with a demo script that embeds chart data and outputs results, preparing inputs for downstream topological tools.
preview
MQL5 Trading Tools (Part 37): Adding a Per-Object Property-Editing Ribbon to the Canvas Drawing Layer

MQL5 Trading Tools (Part 37): Adding a Per-Object Property-Editing Ribbon to the Canvas Drawing Layer

We add a descriptor-driven property stack and a floating ribbon that binds to the current selection on the drawing layer. The article covers the descriptor list for each tool, the engine get/set API with snapshot-and-restore live preview, and widget renderers for color, opacity, line width, line style, fonts, and level visibility. You get in-place, real-time editing of object appearance via a compact, draggable panel.
preview
Price Action Analysis Toolkit Development (Part 73): Building a Weekend Gap Trading Signal System in MQL5

Price Action Analysis Toolkit Development (Part 73): Building a Weekend Gap Trading Signal System in MQL5

We extend the weekend gap toolkit with an indicator that turns gap structure into tradeable signals. When price confirms back into the gap, the indicator issues buy/sell arrows, sets TP at the opposite edge, and places SL using current-week extremes. It maintains non-repainting behavior, reconstructs historical signals, updates live, and provides EA-ready buffers for entry markers and TP/SL to support automation.
preview
From Static MA to Adaptive Filtering (Part 2): Implementing the SAMA_NLMS Indicator in MQL5

From Static MA to Adaptive Filtering (Part 2): Implementing the SAMA_NLMS Indicator in MQL5

This article implements the NLMS-based Self-Adaptive Moving Average as a working MQL5 indicator. It provides the complete source code and explains the key design choices, including inline execution, uniform weight seeding, closed‑bar updates, and stability bounds, along with installation, usage, and limitations. The result is a compiled, chart‑ready SAMA_NLMS indicator and a clear basis for subsequent EA benchmarking.