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
Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)

Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)

Learn how to create advanced visualizations in MetaTrader 5 using a Matplotlib-like API from MQL5 while Python handles rendering. We implement key chart types—scatter, bar, horizontal bar, histogram, pie, and hexbin—and show how to control axes, legends, colorbars, and styles. The result is a consistent workflow for exploring trading and financial datasets.
preview
Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier

Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier

The article focuses on label-auditing for meta-labeling, not on a new entry signal. It presents a native MQL5 implementation of confident learning with out-of-fold scoring and calibrated pruning, plus an EA switch that trains the meta-filter on raw or cleaned datasets. A controlled Strategy Tester comparison helps you quantify noise and choose a pruning level that preserves generalization.
preview
How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5

How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5

The article continues the series on AI Hedge Fund and addresses three limitations of v4: analysts' reputation scores are now stored persistently in SQLite, the EA has been removed from the critical execution path, and signals from the council of fifteen are distributed to multiple brokers via the TradeMux REST API. The logic behind the council and risk management has remained the same: Python retrieves data via the MetaTrader 5 SDK and executes orders directly. The result is resilience to restarts and scalability across multiple terminals.
preview
Crypto Exchange Integration with MQL5 (Part 1): Connecting to MEXC Futures

Crypto Exchange Integration with MQL5 (Part 1): Connecting to MEXC Futures

This article introduces the foundations of connecting MetaTrader 5 to a cryptocurrency exchange using MQL5 and the MEXC Futures API. It covers terminal configuration, JSON response processing, WebRequest() execution and validation, and conversion of API data into native MQL5 types. Practical examples demonstrate retrieving and processing exchange data. These components establish the basis for a reusable MEXC Futures client, developed progressively throughout the series. The series focuses exclusively on exchange integration; how readers use the retrieved data remains outside its scope.
preview
Creating Custom Indicators in MQL5 (Part 12): Mapping Liquidity with a Volume Profile Heatmap

Creating Custom Indicators in MQL5 (Part 12): Mapping Liquidity with a Volume Profile Heatmap

We build a volume profile heatmap indicator in MQL5 that bins window volume into uniform price levels and paints each bar as a column of colored cells behind the candles. We cover binning, heat coloring, the side profile, the point-of-control and value-area lines, and the liquidity readouts, with every level published to buffers. The result is a map of dense bands and thin gaps, showing how much traded volume sits above and below the current price.
preview
Constant Proportion Portfolio Insurance (CPPI) for MQL5: A Floor-Protected Capital Allocation Strategy

Constant Proportion Portfolio Insurance (CPPI) for MQL5: A Floor-Protected Capital Allocation Strategy

Build Constant Proportion Portfolio Insurance natively in MQL5. The article details the floor and cushion formulas, a rebalance engine that operates safely on both netting and hedging accounts, and a price‑only reference indicator that reuses the same math. A real Strategy Tester run on XAUUSD M5 demonstrates configuration, order sizing, and stability under a rebalance band.
preview
Neural Additive Models for Fully Interpretable Signal Attribution in MQL5

Neural Additive Models for Fully Interpretable Signal Attribution in MQL5

Build and deploy a Neural Additive Model natively in MQL5: one small network per feature, additive output, and no post-hoc explainability. The article provides a PyTorch trainer, two‑output ONNX export (signal and contributions), an include wrapper using OnnxCreateFromBuffer/OnnxRun, and an EA that prints real per‑feature contributions each bar. It covers identical feature math for training/export, threshold measurement, Strategy Tester results, and edge cases such as NaNs and out‑of‑distribution inputs.
preview
Neural Networks in Trading: Temporal Motion Aggregation (Key Components)

Neural Networks in Trading: Temporal Motion Aggregation (Key Components)

In this article, theory meets practice. We implement the key modules of the TMA framework — MPE and MPA. Here, data takes on meaning, and cross-attention becomes a tool for precise analysis of market dynamics. Minimal unnecessary operations, maximum efficiency — a step toward next-generation intelligent trading.
preview
A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part I): Continuous Adaptation of the Trading Model on Each Bar

A Grid Expert Advisor Based on a Cellular Automaton with Online Learning in MQL5 (Part I): Continuous Adaptation of the Trading Model on Each Bar

The article examines the architecture of an Expert Advisor based on a cellular automaton with 10,000 adaptive parameters and an independent binary predictor with a 10-bar prediction horizon. The article demonstrates a three-level online learning process, the evolution of strategies, and validation using a ring buffer and a confusion matrix. The input parameters are reduced to Magic Number, while trading settings are calculated from ATR and five genomes. The EURUSD H1 test yielded an approximate hit rate of 58%, compared to roughly 51% for the fixed MLP.
preview
From Basic to Intermediate: Technical Indicators (II)

From Basic to Intermediate: Technical Indicators (II)

In this article, we'll show you how to create an MQL5 indicator that plots multiple moving averages on a single chart, reducing the amount of duplicate code. This uses iMA, indicator buffers, CopyBuffer, PlotIndexSetInteger/String, and a const array of structures that brings together periods, methods, and colors. The sizes of `indicatorbuffers` and `indicatorplots` are determined based on `Averange.Size()`. This approach simplifies maintenance and allows you to add or remove moving averages by modifying just one list.
preview
Building a Trade Replay Tool in MQL5

Building a Trade Replay Tool in MQL5

This article presents a Trade Replay Tool for MetaTrader 5 implemented as an MQL5 indicator. It replays historical candles within an anchor-defined range and automatically reconstructs historical trades as paper positions with entry, SL, and TP. Users control start/end anchors and playback speed via UI buttons and hotkeys, enabling focused study of price evolution and trade lifecycle in a precise, event-driven environment.
preview
Neural Networks in Practice: Gradient Descent

Neural Networks in Practice: Gradient Descent

In this article, I will try to explain as simply and clearly as possible one of the most controversial issues that arises when discussing neural networks: how to find the best possible point, or the minimum of the loss function. I'll show you the difference between linear regression and gradient descent. Both methods are fairly simple and serve as examples of how the path that seems obvious isn't always the best one.
preview
From Basic to Intermediate: Technical Indicators (I)

From Basic to Intermediate: Technical Indicators (I)

In this article, we will examine the basic principles of using the technical indicators built into MetaTrader 5 and supported by this platform. Knowing and understanding these indicators can make implementing a solution much simpler, faster, and more efficient, since you won't have to worry about the necessary calculations. The platform handles them for us automatically.
preview
Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have

Using the MQL5 Economic Calendar for News Filter (Part 5): The Tier the Calendar Does Not Have

This part extends the news filter with an ordered tier scale that adds a special tier above the broker's High, per‑event time windows, and one classifier shared by live calendar data and historical CSV. A rule table (with optional CSV overrides) promotes or demotes specific releases and can set custom windows. A diagnostic script prints your broker's calendar, event codes, and server time so your rules match what the terminal actually reports.
preview
Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer

Building a PDF Creation Library in MQL5 (Part 3): The Byte-Exact Writer

The article presents CPdfBuffer and CPdfWriter, a minimal MQL5 pair that derives all offsets from the output buffer instead of hand-maintaining numbers. CPdfWriter records object starts, writes a fixed-width cross-reference table and trailer, and ensures structural consistency. The result passes Part 2's validator, and a ready-to-use script converts arbitrary text to a paginated PDF.
preview
Neural Networks in Trading: Temporal Motion Aggregation (TMA)

Neural Networks in Trading: Temporal Motion Aggregation (TMA)

The TMA framework offers a new perspective on market dynamics, enabling models to capture not only the state of the market but also the passage of time itself. Its ability to identify patterns in a continuous stream of data makes the analysis more in-depth and accurate than with traditional approaches. Recurrent adaptation turns this method into a practical tool for working with real-world quotes.
preview
Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading

Trading Strategy Beyond Raw Volume: Using Transformed Volume Change for Trading

The article develops a volume-change strategy that transforms tick or real volume with Ln(volume+1), differences it bar to bar, and applies arctan to produce a bounded, scale‑independent signal. A threshold drives entries, with selectable gates for positive, negative, or bi‑directional signals and candle‑based confirmation. An MQL5 Expert Advisor implements the logic and supports fixed TP/SL, N‑candle exits, or both, enabling straightforward testing and deployment.
preview
Color Harmony Algorithm (CHA)

Color Harmony Algorithm (CHA)

We take a closer look at the Color Harmony Algorithm (CHA) — a meta-heuristic optimization method based on Munsell's theory of color harmony. We explore the structure of the hue circle, harmony templates, the alternation between the concentration and dispersion phases, and the role of solution memory. From a theoretical framework to a working implementation in MQL5 and unbiased testing on a standard benchmark.
preview
From Basic to Intermediate: Operator Overloading (VI)

From Basic to Intermediate: Operator Overloading (VI)

Here, we implement deletion using operator overloading. Without a doubt, many people will have to spend quite a bit of time studying this article to fully grasp everything that will be covered here. I want to remind you that what we're about to see is just a small and insignificant part of what we call programming.
preview
Neural Networks in Practice: An Example of Implementing an XOR Gate

Neural Networks in Practice: An Example of Implementing an XOR Gate

In this article, I will try to show you, dear reader, that things are not always what they seem. We often tend to think that everything is arranged in a certain way, even though we may end up believing something that isn't necessarily true. Neural networks are undoubtedly one of the most interesting topics, whether viewed from the perspectives of mathematics, electronics, or software. Contrary to what many people believe or claim, neural networks are neither a problem nor a definitive solution. This is just one area of research where we should continue to delve deeper and explore what goes on behind the scenes.
preview
How to Train an MLP Using Markov Chain Features in MQL5

How to Train an MLP Using Markov Chain Features in MQL5

The article describes the two-level MarkovMLPOscillator indicator: a three-state Markov chain uses historical data to construct a transition matrix and generate 15 probabilistic features for each bar, and an MLP is trained on these features to predict price direction at a specified forecast horizon. The article covers feature generation, the validation procedure using a holdout set, and parameter settings. The result is an interpretable oscillator with a color histogram, a smoothed signal, and a display of the current transition matrix.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 7): Arcs, Circles and Rounded Rectangles

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 7): Arcs, Circles and Rounded Rectangles

This part finishes the geometry layer: arcs use a sagitta‑based angular step tied to the pixel tolerance, so segment counts are computed, not guessed. The path gains ArcTo, AddCircle, AddEllipse and AddRoundRect with per‑corner radii, enabling common UI shapes such as tabs, pills, badges, rings, gauges and donut wedges.
preview
Building A Candlestick Trend Constraint Model (Part 12) Measuring Lower-Timeframe Trigger Quality

Building A Candlestick Trend Constraint Model (Part 12) Measuring Lower-Timeframe Trigger Quality

This article extends the A‑B‑C‑D constraint model with a measurement layer. We capture confirmation timing, breakout beyond Candle C, and post‑signal MFE/MAE; aggregate results by A‑B relationship; and write one CSV row per completed D window while showing concise CCanvas comments. The separation of detection, replay, visualization, measurement, and optional execution provides clean, analyzable data for further research.
preview
Optimal Trade Exit in MQL5: Longstaff-Schwartz Least-Squares Monte Carlo for Continuation-Value Estimation

Optimal Trade Exit in MQL5: Longstaff-Schwartz Least-Squares Monte Carlo for Continuation-Value Estimation

This article models position exits as an American option and implements the Longstaff–Schwartz least‑squares Monte Carlo in native MQL5. The engine calibrates drift and volatility from recent returns, simulates forward price paths, and uses backward induction to compare immediate exercise to continuation. It integrates into an EA with hard time and price backstops and a live indicator, and is tested on four symbol/timeframe combinations with mixed, reproducible Strategy Tester results.
preview
Building a Prop-Firm Rule Guard in MQL5 (Part 1): The Observation Layer

Building a Prop-Firm Rule Guard in MQL5 (Part 1): The Observation Layer

Prop-firm accounts operate under a second rulebook that MetaTrader 5 does not model. This first part builds the observation layer: a per-pass frozen account snapshot read by every rule, a verdict record that reports without acting, explicit enable flags in the profile, and a session clock aligned to the firm's reset time. The result is a reproducible pass that prevents cascading effects and prepares the ground for safe decisions in Part 2.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (Conclusion)

Neural Networks in Trading: Iterative Forecast Refinement Models (Conclusion)

Introducing the RAFT framework — a powerful tool for analyzing and forecasting financial time series. Its flexible and optimized architecture ensures accurate forecasts, stable performance, and faster data processing. RAFT reduces the risk of errors and makes it easier to create effective trading strategies.
preview
Zero-Copy Tick Streaming (Part 2) : Reading MetaTrader 5 Ticks into Python and Benchmarking the Result

Zero-Copy Tick Streaming (Part 2) : Reading MetaTrader 5 Ticks into Python and Benchmarking the Result

We build a Python reader that attaches to the MetaTrader 5 shared memory segment, reproduces the Arrow columnar layout, and constructs ArrowArray/ArrowSchema via ctypes so pyarrow imports ticks without copying. The code honors the three-way schema contract and the seqlock generation counter to read consistent batches. A standalone benchmark verifies performance against a legacy per-field struct.unpack path with real numbers.
preview
Market Simulation: First Steps with SQL in MQL5 (III)

Market Simulation: First Steps with SQL in MQL5 (III)

In the previous article, we looked at an example of implementing a class in MQL5 to provide basic support. Its purpose is specifically to allow SQL code to be stored in a separate script file. This way, we won't need to write the same SQL statements as string literals in the MQL5 source code. Although this solution is functional, there are some aspects of it that we can and should improve.
preview
Market Simulation: First Steps with SQL in MQL5 (II)

Market Simulation: First Steps with SQL in MQL5 (II)

Although many people believe that we can easily embed SQL code into other code, this is usually not the case. The reason is that the SQL code is included in the executable as a string. Embedding SQL code as a string, while not a problem for small snippets, can ultimately cause us quite a few headaches.
preview
Bull Optimization Algorithm (BOA)

Bull Optimization Algorithm (BOA)

We present an evolutionary algorithm without a selection operator: the best individual becomes the sole mating partner for the entire population, and classical mutation is replaced by multiplicative mutation with a self-adjusting step size. In this article, we examine three key ideas, implement the algorithm in MQL5 using the C_AO framework, and test it on the standard benchmark suite and in an anti-cheat test — where BOA comes very close to the cutoff for the top 45 but does not make the ranking.
preview
Beyond Squared Returns: Path-Dependent Volatility

Beyond Squared Returns: Path-Dependent Volatility

This article implements a path-dependent volatility model in MQL5 that keeps the sign of returns. The engine uses two-timescale EWMA kernels (four accumulators) to form activity and trend features, with closed-form coefficients and a lightweight kernel search. We provide a calibration workflow and an indicator that plots the decomposition, then test out of sample against EWMA and GARCH on multiple symbols. Results show clear gains on equity indicators and minimal gains on FX.
preview
Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

Behavioural Cloning in a Live Trading System: What Live Experience Can and Cannot Teach

This article measures a live-to-train behavioral-cloning loop for an RL trading system across 83 models. Outcome-weighted imitation shifted the policy toward Hold (48% → 82%), with 12 final models not trading at all. Live records were instead used to fit spread and slippage to broker fills, revealing execution costs ~85× higher than in simulation. We describe the loop, the failure mechanism, the calibration, and a protocol to apply.
preview
Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

Fundamentals of Bayesian Inference in Discrete and Continuous Settings: From Theory to Practical Model Implementation

The article discusses the fundamentals of Bayesian statistics in both discrete and continuous settings. We will progress from classical Bayes’ theorem and simple examples involving coin flips to conjugate distributions and dynamic Bayesian updating, which enables real-time analysis of market quotes. Using the beta-binomial model as an example, a simple change-point detection indicator has been implemented to help identify shifts in market regimes.
preview
Measuring the Probability of Backtest Overfitting of Your MetaTrader 5 Optimization (Part 1): The CSCV Engine in MQL5

Measuring the Probability of Backtest Overfitting of Your MetaTrader 5 Optimization (Part 1): The CSCV Engine in MQL5

This article implements the Probability of Backtest Overfitting in MQL5 with Combinatorially Symmetric Cross-Validation. It shows how to build the bar-by-bar returns matrix of a parameter grid, aggregate it by blocks and rank the in-sample winner out-of-sample across every split of the history. You get a single probability that this winner ends up in the lower half of the grid out-of-sample, along with the MQL5 code to compute it on your own optimizations.
preview
Broker Time vs Real Market Time — Building a DST-Aware Session Clock in MQL5

Broker Time vs Real Market Time — Building a DST-Aware Session Clock in MQL5

Session filters can run an hour off when a broker and a market change their clocks on different dates. This article presents an MQL5 include file, SessionClock.mqh, that converts London, New York, and Tokyo sessions to broker hours for a stated daylight saving time (DST) schedule (EU, US, or fixed) and winter offset. A second script estimates the schedule from server history. It uses calendar arithmetic, so it also works in the Strategy Tester.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (Key Components)

Neural Networks in Trading: Iterative Forecast Refinement Models (Key Components)

In this article, we explore the inner workings of the RAFT framework — one of the most precise and elegant approaches to analyzing dynamic processes. Step by step, we adapt its idea of iterative refinement to financial time series, laying a solid foundation for a future model. Readers can look forward to an engaging exploration of the architecture, where every component has its own purpose and function.
preview
From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

From Signal to Trade via a Chain of Agents: LangChain Architecture on Top of MQL5

The article describes an architecture in which the MQL5 Expert Advisor (EA) handles only data collection and execution, while the logic is moved to a Python server with three LangChain agents: a signal agent, a news agent, and a risk manager. Agents process the WebSocket request sequentially; if any agent rejects it, "hold" is returned. Decisions and actual PnL are stored in SQLite, forming memory and statistics. The reader will receive an interaction diagram, a command protocol, and a feedback approach.
preview
How to Implement Metaprompting for Trading Signals in an MQL5 Expert Advisor

How to Implement Metaprompting for Trading Signals in an MQL5 Expert Advisor

Metaprompting is an approach in which the LLM itself optimizes trading instructions based on actual P&L and signal quality metrics. The article demonstrates a practical implementation in Python and MQL5: a prompt version registry, an execution agent, an evaluator for directional accuracy and profit factor, and a meta-LLM that generates improvements in a loop. The solution is integrated into the Expert Advisor without interrupting trading.
preview
Numerical Fidelity Under Fire: Benchmarking Native MQL5, ONNX Runtime, and ALGLIB

Numerical Fidelity Under Fire: Benchmarking Native MQL5, ONNX Runtime, and ALGLIB

This article benchmarks one MLP forward pass implemented three ways in MQL5: native code, ALGLIB, and ONNX Runtime. We quantify numerical fidelity versus a float64 ground truth and execution latency (mean/percentiles), then outline practical criteria and a ready‑to‑use harness to help you choose and integrate the right engine in an EA.
preview
Implementing Session Volume Profile in MQL5

Implementing Session Volume Profile in MQL5

Build a responsive session volume profile indicator in MQL5 from tick data with draggable session bounds and dual anchoring. The article details hash-based bucket aggregation for historical and live ticks, a timer-driven rendering loop with partial updates, automatic or custom bucket sizing, pixel-anchored proportional bars, POC highlighting, and multi‑instance safety—so you can implement, optimize, and run multiple profiles on one chart without UI lag.