Articles with MQL5 programming examples

icon

Access a huge collection of articles with code examples showing how to create indicators and trading robots for the MetaTrader platform in the MQL5 language. Source codes are attached to the articles, so you can open them in MetaEditor and run them to see how the applications work.

These articles will be useful both for those who have just started exploring automated trading and for professional traders with programming experience. They feature not only examples, but also contain new ideas.

Add a new article
latest | best
preview
How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

The article describes a practical approach to synchronizing bars between instruments in a portfolio in MQL5. Classes are provided for loading, storing, and aligning OHLCV data, with options to use an empty bar or carry over values from the previous bar, select a synchronization symbol, and process new bars asynchronously. Examples of use in multi-chart and basket indicators are shown. Readers receive a ready-to-use API for reliable portfolio calculations.
preview
Automating Classic Market Methods in MQL5 (Part 8): Ed Seykota's Trend Following System

Automating Classic Market Methods in MQL5 (Part 8): Ed Seykota's Trend Following System

The article presents a full MQL5 implementation of a multi-symbol trend system: dual EMA crossovers for entries, ADX to avoid ranges, ATR to normalize position size, and a heat monitor to cap total portfolio risk. We explain the architecture, calculation details, and entry/exit logic on daily bars. The result is a practical EA template for systematic, risk-aware portfolio trading.
preview
From Basic to Intermediate: Queues, Lists, and Trees (VIII)

From Basic to Intermediate: Queues, Lists, and Trees (VIII)

In this article, we will examine how to implement a tree balancing algorithm. Here, I will present my own version of an implementation of this algorithm. There are many other algorithms that serve the same purpose. Nevertheless, each of them has its own advantages and disadvantages. You, my dear reader, will need to explore them and find the one that best suits your needs.
preview
Automating Classic Market Methods in MQL5 (Part 7): The Nicolas Darvas Box System

Automating Classic Market Methods in MQL5 (Part 7): The Nicolas Darvas Box System

This article implements the Darvas Box method as a complete MQL5 Expert Advisor. We code box detection with a three-session hold, volume contraction during consolidation, and volume-confirmed breakouts, plus a staircase pyramid with a shared, rolling stop at the latest box floor. The EA uses a state machine to run box scanning and trade management in parallel, providing a ready-to-compile system with configurable inputs and clear on-chart diagnostics.
preview
From Basic to Intermediate: Queues, Lists, and Trees (VII)

From Basic to Intermediate: Queues, Lists, and Trees (VII)

In this article, we will clearly and simply demonstrate and explain how to remove a node from a tree. This process usually confuses beginners rather than helping them understand how it's done and why it needs to be done that way.
preview
The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

The ZeroMQ Message Transfer Protocol in MQL5: Implementing the REQ/REP pattern

This article presents a native MQL5 implementation of the ZeroMQ Message Transfer Protocol (ZMTP) built on raw MQL5 sockets. It explains the REQ/REP pattern via the CZmqReqSocket class, including framing, handshake, and strict send/receive alternation. A practical pipeline shows an MQL5 script streaming returns to a Python/R server running MS‑GARCH and receiving regime probabilities, enabling integration without DLLs.
preview
The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

The MQL5 Standard Library Explorer (Part 16): Building a Regime-Adaptive Expert Advisor

We convert the Part 15 decision‑forest classifier into a regime‑adaptive Expert Advisor that decouples statistical inference from trading authority. The EA trains on completed bars, scores each new completed bar, and confirms stable bullish, neutral, or bearish regimes before acting. It then applies spread, ownership, risk, and execution checks to authorize opening, holding, closing, or blocking a position.
preview
Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

Measuring What Matters (Part 4): Reading the Spectrum — What Eigenvalues Tell You About Risk

We turn eigenvalues from a covariance matrix into a normalized spectral‑entropy score that measures how evenly variance is spread across factors. SpectralEntropyCalculator.mq5 compares two portfolios in one run, using native vector summation, ArraySort()-based ordering, element‑wise division, and the Shannon entropy formula. The report makes dominant factors visible and enables quick, repeatable checks of diversification quality.
preview
Building Your Personal Expert Advisor (Part 6): Risk Management V — Portfolio and Correlated Risk

Building Your Personal Expert Advisor (Part 6): Risk Management V — Portfolio and Correlated Risk

This part implements PortfolioRisk.mqh, a shared library that shifts risk management to the account level. It scans positions and pending orders, computes margin and floating results, counts symbols, and decomposes pairs into currencies to detect concentration, then validates each new trade against portfolio limits. The Series EA example illustrates configuring scope (account-wide or magic-filtered), registering magics, and integrating the pre-trade gate.
preview
From Basic to Intermediate: Queues, Lists, and Trees (VI)

From Basic to Intermediate: Queues, Lists, and Trees (VI)

In this article, we will return to the tree implementation. Now that we are familiar with the basic principles of constructors and destructors, we can finally fix the code presented in the previous article. Get ready for a real adventure in MQL5 programming.
preview
From Basic to Intermediate: Classes (III)

From Basic to Intermediate: Classes (III)

In this article, we will explore the best ways to manage code when working with object-oriented programming. Although we are just beginning to learn about object-oriented programming, what we will cover here will help you understand its various aspects. This will also help dispel any doubts that may arise later.
preview
The MQL5 Standard Library Explorer (Part 15): Building a Market-Regime Classifier with dataanalysis.mqh

The MQL5 Standard Library Explorer (Part 15): Building a Market-Regime Classifier with dataanalysis.mqh

This part focuses on practical data analysis in MQL5 with dataanalysis.mqh. We prepare a labeled dataset from bars, apply normalization, explore redundancy with PCA, and train a decision forest to classify future bar regimes. The article shows how to obtain out-of-bag estimates and permutation importance, helping you validate the model and understand which inputs matter most.
preview
A Forgotten Classic in Volume Analysis: The Finite Volume Elements Indicator for Today's Markets

A Forgotten Classic in Volume Analysis: The Finite Volume Elements Indicator for Today's Markets

In this article, we will examine the Finite Volume Elements (FVE) indicator, which helps identify genuine capital flows in the market. We will implement FVE for MetaTrader 5 and review recommendations for using it in trading.
preview
Automating Classic Market Methods in MQL5 (Part 6): Jesse Livermore's Pivotal Point System

Automating Classic Market Methods in MQL5 (Part 6): Jesse Livermore's Pivotal Point System

This article presents a complete MQL5 Expert Advisor that implements Jesse Livermore's market key as a deterministic state machine. It detects pivotal levels from consolidations using ATR and volume expansion, scales in across four tranches, and exits on abnormal behavior defined by range and volume. The EA validates inputs in OnInit, requires a hedging account, and compiles out of the box for testing Livermore's rules on daily data.
preview
Building Your Personal Expert Advisor (Part 3): Risk Management II—Margin and Allowable Risk

Building Your Personal Expert Advisor (Part 3): Risk Management II—Margin and Allowable Risk

Risk-based lot sizing can still exceed what free margin allows. The article adds a margin-aware cap using OrderCalcMargin(), an optional adaptive cap that scales with ACCOUNT MARGIN LEVEL, and a single pre-trade validation gate that unifies position limits, risk sizing, and margin checks. Readers get concrete code to prevent order rejections and over-committing margin, with clear logs when a trade is reduced or skipped.
preview
From Basic to Intermediate: Classes (II)

From Basic to Intermediate: Classes (II)

This article is intended to be as educational as possible, since the topic we will be discussing often causes considerable confusion in itself. Therefore, dear reader, please try to put what is explained here into practice. If you have any questions, be sure to leave a comment—after all, understanding destructors is no easy task.
preview
Building Your Personal Expert Advisor (Part 5): Risk Management IV—Basket Risk and Strategy-Specific Sizing

Building Your Personal Expert Advisor (Part 5): Risk Management IV—Basket Risk and Strategy-Specific Sizing

Part 5 moves risk control from single trades to a basket-level framework. The EA aggregates its own positions, computes volume‑weighted entry, floating P/L including swap, and used margin, then enforces limits on combined loss, margin, position count, and time underwater, while logging maximum adverse excursion. A companion mean‑reversion EA demonstrates target‑based sizing and caps on implied risk that remains hidden when trades are evaluated in isolation.
preview
Master MQL5 — From Beginner to Pro (Part VII): Principles of Debugging MQL Applications

Master MQL5 — From Beginner to Pro (Part VII): Principles of Debugging MQL Applications

Debugging is an integral part of the programming cycle. This article discusses common techniques for debugging any application running in the MetaTrader 5 environment.
preview
The Mathematics of Volatility: Why the GRI Indicator Deserves to Return to Your Trading Terminal

The Mathematics of Volatility: Why the GRI Indicator Deserves to Return to Your Trading Terminal

The article focuses on the Gopalakrishnan Range Index (GRI/ROCI), which quantitatively assesses the market's "degree of chaos" using the logarithm of the closing price range over a given period. The article shows how to implement GRI in MetaTrader 5, resolve the issue of negative values using a shifted logarithm, and convert the scale to convenient "points" by normalizing it by Point. Next, we examine practical scenarios for using GRI as a filter for volatility and market phases.
preview
From Basic to Intermediate: Classes (I)

From Basic to Intermediate: Classes (I)

In this article, we explain what a class is and why this concept came about. Although the topic is interesting, we will focus here on the principles underlying MQL5 programming. This article is just an introduction.
preview
From Basic to Intermediate: Queues, Lists, and Trees (V)

From Basic to Intermediate: Queues, Lists, and Trees (V)

In this article, we implemented the first components of a tree structure. Since I realize that this structure can be very complex at the beginning of the learning process, we will introduce it gradually, step by step. This way, everyone will be able to understand how a tree works and when it is best to use one.
preview
Walsh Functions in Modern Trading

Walsh Functions in Modern Trading

The article discusses the application of Walsh functions in trading. We will explore the basic principles of using these functions to analyze financial markets, forecast prices, and make trading decisions. We will also discuss the advantages and disadvantages of these functions, as well as the prospects for their application in trading and technical analysis.
preview
Decoding Market Intent: Reading Structure, Liquidity, and Price Behavior

Decoding Market Intent: Reading Structure, Liquidity, and Price Behavior

We implement a five-stage MQL5 pipeline that quantifies market structure, liquidity interaction, and price behavior on four timeframes, then resolves them into a 0–100 Market Intent Score. Decision states (WAIT/WATCH/ACTION) are driven by explicit weights plus hard gates. The analytical core feeds a concise dashboard and, when AutoTrade is on, an execution layer with entry zones, invalidation and liquidity‑based targets.
preview
From Basic to Intermediate: Queues, Lists, and Trees (IV)

From Basic to Intermediate: Queues, Lists, and Trees (IV)

In this article, we will conclude the section on the implementation and explanation of the linked list. However, the implementation presented here omits one detail that can be implemented in a linked list. We will discuss this later, in another article.
preview
Tables in the MVC Paradigm in MQL5: Symbol Correlation Table

Tables in the MVC Paradigm in MQL5: Symbol Correlation Table

In this article, we will refine the graphics library classes by adding a vertical header to the table and use the table classes to create an indicator that displays the correlation between the symbols specified in the settings.
preview
Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

Self-Optimizing Expert Advisors in MQL5 (Part 19): Parameter Optimization For Time-Lagged Independent Components Analysis (2)

The article shows how to tune ICA hyperparameters with a supervised evaluation pipeline and apply spectral clustering to time-lagged indicators. Cross-validation identifies the optimal number of clusters, which are translated into expected return and risk measures. These signals drive dynamic position sizing and stop-loss control, with surrogate models converted to ONNX and integrated into an MQL5 Expert Advisor.
preview
From Basic to Intermediate: Queues, Lists, and Trees (III)

From Basic to Intermediate: Queues, Lists, and Trees (III)

In this article, we will take the next step in understanding what a linked list is and how it works. Although the content of this article may seem rather complex and confusing to beginners, I will try to explain it in the simplest terms possible. This will help you understand why and when to use linked lists.
preview
From Basic to Intermediate: Queues, Lists, and Trees (II)

From Basic to Intermediate: Queues, Lists, and Trees (II)

This is an article that you, dear reader, should study carefully. That is due to the nature of the material presented here. Although we have tried to present the material as simply and informatively as possible, the information provided here can certainly seem quite complex to those who are just beginning to learn programming. Nevertheless, this is no reason to lose heart or ignore what is explained here, as this article will establish a link between two completely different, though closely related, topics.
preview
Building a Bar Replay Tool in MQL5

Building a Bar Replay Tool in MQL5

This article shows how to build an interactive bar replay tool in MQL5 for MetaTrader 5 that reveals historical candles one by one without exposing future data. You will implement custom candles with DRAW COLOR CANDLES, an event-driven engine with OnChartEvent and OnTimer, a dashboard with Play/Pause, a draggable replay anchor, and Buy/Sell paper trading with SL/TP lines, while keeping the active bar in view to practice discretionary analysis and execution.
preview
From Basic to Intermediate: Queues, Lists, and Trees (I)

From Basic to Intermediate: Queues, Lists, and Trees (I)

In this article, we'll begin exploring a short series of concepts that are of immense importance to anyone who truly wants to learn how to program properly. Since this may seem very complicated at first—even though it is based on simple elements—we will go through the material step by step. So, let's start by figuring out what queues are.
preview
From Basic to Intermediate: Like Bubbles

From Basic to Intermediate: Like Bubbles

This article will explain a very simple and easy-to-understand mechanism whose purpose is to sort any array. In it, we will see that the result obtained does not always meet expectations, so the implementation itself will need to be adapted to achieve the desired results.
preview
From Basic to Intermediate: Navigating the Sandbox

From Basic to Intermediate: Navigating the Sandbox

In this article, we'll look at two ways to inspect the contents of the sandbox and even interact with it, using MetaTrader 5 as the base platform. Understanding the material in this article is essential to understanding what will be covered in subsequent articles.
preview
Price Action Analysis Toolkit Development (Part 80): Building a History Navigator for MetaTrader 5

Price Action Analysis Toolkit Development (Part 80): Building a History Navigator for MetaTrader 5

We implement a History Navigator for MetaTrader 5 that jumps the chart to an exact historical period by date and time. The dialog validates inputs, converts them to datetime, and searches bar times with a binary-search routine before centering the selected candle. The navigation logic is separated from chart control, improving testability and maintenance, and a one-click return restores the live market view.
preview
Hypothesis Testing for Trading Strategies — Proving Whether Your Edge is Real

Hypothesis Testing for Trading Strategies — Proving Whether Your Edge is Real

Net profit and win rate do not tell you if a strategy's edge is statistically real. This MQL5 toolkit analyzes return series built from price data or deal history and reports t‑statistics, p‑values, and confidence intervals using one-sample and Welch t‑tests, the Mann–Whitney U test, and volatility‑regime analysis to support evidence‑based trading decisions.
preview
Controller Objects for Everything: Draggable Slider Control

Controller Objects for Everything: Draggable Slider Control

The article details a complete MQL5 implementation of a draggable slider for controlling ranges on the chart. It introduces the CDragHandle class, private state, public APIs for dimensions, colors, range, and value, plus Refresh* and UpdateHandlePosition logic and event processing. A working example changes CHART_SCALE, demonstrating how to connect the control to platform properties.
preview
Building a Gold Volatility Regime Monitor from Options Data in MQL5

Building a Gold Volatility Regime Monitor from Options Data in MQL5

A practical bridge from the options market into MetaTrader 5 for gold. We compute near-the-money implied volatility by solving Black-Scholes from quoted prices, compare it with 30-day realized volatility, and use the ratio as a regime proxy. A Python feed publishes the value, an MQL5 script consumes it with WebRequest, and a background service keeps a panel current and alerts on changes. Source code for all parts is provided.
preview
From Novice to Expert: Candlestick Momentum Confirmation for Classic Crossover Strategies

From Novice to Expert: Candlestick Momentum Confirmation for Classic Crossover Strategies

In this article, we refine a moving average crossover strategy with a momentum candle filter and an immediate retracement bar confirmation. When both conditions are met, a pending stop order is placed using a pivot-based stop loss and a 2R take profit. The complete MQL5 Expert Advisor code, finite-state-machine logic, and chart annotations are detailed.
preview
Automating Chart Patterns in MQL5 (Part 1): The Multi-Timeframe Swing Structure Engine

Automating Chart Patterns in MQL5 (Part 1): The Multi-Timeframe Swing Structure Engine

This article presents CSwingEngine, a reusable MQL5 class that detects H4 swing highs and lows, labels them HH, LH, HL, or LL, and classifies market structure as trend or range. Swings are always computed on H4, regardless of the attached chart, and each point draws correctly on lower timeframes via native datetime anchoring. The engine exposes a clean interface to query the current trend and retrieve the swing array for context-aware pattern logic.
preview
Self Optimizing Expert Advisors in MQL5 (Part 18): Time Lagged Independent Components Analysis

Self Optimizing Expert Advisors in MQL5 (Part 18): Time Lagged Independent Components Analysis

We evaluate blind source separation for market noise control using FastICA applied to SMA-filtered, time-lagged OHLC features. The study compares classical and surrogate targets, measures accuracy across lags, tunes KNN models, and inspects residual structure with clustering. Models are exported to ONNX and integrated into an MQL5 Expert Advisor for testing. The result is a reproducible pipeline from data extraction to deployment.
preview
Building a Crosshair Volume Profile Indicator in MQL5

Building a Crosshair Volume Profile Indicator in MQL5

We implement an interactive Crosshair Volume Profile indicator in MQL5 for MetaTrader 5. Using a right-click-and-drag crosshair, you select a chart region; the indicator then builds adaptive price bins, accumulates tick or real volume, detects the POC, and renders the profile on the chart. You will practice OnChartEvent()-driven interaction, cursor-to-time/price mapping, and price-source models (Close, Median, Typical, Weighted, OHLC4) for on-demand volume analysis.