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
Change Point Detection for Financial Time Series in MQL5

Change Point Detection for Financial Time Series in MQL5

Financial markets can shift between regimes, so detecting when the statistical behavior of returns changes is valuable for analysis. An MQL5 change point detector segments historical returns into periods with different mean and volatility using optimal partitioning with PELT pruning and a BIC-style default penalty. A sensitivity scan tests robustness by showing which detected breaks persist as settings vary.
preview
How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

How Far Away Is the Stop-Out? A Stop-Out Threshold Finder and Pre-Trade Guard in MQL5

CStopOutGuard shows how far a symbol's price can move before the modeled margin level reaches stop-out, and how much closer a planned order would bring that threshold. Positions are valued with OrderCalcProfit() and OrderCalcMargin() at each tested price instead of a fixed tick value, so volume margin tiers are included. Unit tests, test EAs, and a Python consistency check cover the search. The model keeps the spread and swaps at their current values, and CanAdd() does not replace OrderCheck().
preview
Building a Dynamic Drop List in MQL5

Building a Dynamic Drop List in MQL5

This article describes CDropList, a composite class that implements an interactive drop-down list from standard MQL5 chart objects. It details creation/destruction, coordinates and sizes, color configuration, item management, and a Refresh method that keeps objects in sync. Event handling covers opening/closing, hover highlight, item clicks, and scrolling, helping you embed consistent selection controls in indicators, dashboards, and trading panels.
preview
Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines

Developing Smart Chart Objects in MQL5 (Part 3): Integrating Lifecycle Alerts into Managed Trendlines

This article adds a lifecycle-driven alert layer to the Smart Trendline Manager. Alerts originate from state transitions (touch, bounce, break, resurrection), pass configurable event and source filters, and are delivered via terminal popups and push notifications. You will see how to wire the alert engine through the manager, configure inputs in the indicator, and receive timely notifications without constant chart monitoring.
preview
Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

Modular Indicator Architecture in MQL5 (Part 2): Standard Smoothing Methods as Interchangeable Modules

EMA, SMMA, and LWMA join SMA as modules of the indicator framework from Part 1, all four derived from a new base class, CSmoothingBase. The root object, CIndicator, dynamically creates the module of the chosen smoothing method and works with it through a base-class pointer. Besides the code, the article explains the smoothing methods themselves, with formulas and worked examples, and compares the four: how they weight the bars, what they need to start, and what their calculation costs.
preview
MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

MQL5 Developer Gotchas (Part 1): A Parameter Mapper for Calling Indicators with Input Groups

Group lines in a custom indicator take parameter slots in iCustom() and IndicatorCreate(), so numbers passed without placeholders silently shift to the wrong inputs. CIndicatorInputs reads the live slot layout, fills the group slots, rejects values the terminal would change, and verifies the handle on a chart, so an EA gets the requested settings or an error. In the Strategy Tester it builds the handle from a saved layout without verification. Unit tests and a tester EA show both modes.
preview
Building a Divergence System (Part VI): A Scoring Divergence Engine

Building a Divergence System (Part VI): A Scoring Divergence Engine

A reusable MQL5 divergence engine that stores all confirmed pivots, selects clean pivot pairs, and measures price extension in ATR, oscillator disagreement, and bar spacing into a 0–100 score. It logs named rejection reasons for filtered pairs and exposes per‑bar queries. Integration is reduced to four steps, and the score can drive an adaptive trailing system that scales its SAR step by divergence strength.
preview
Do My EA's Losses Come in Clusters? A Wald-Wolfowitz Runs Test for Trade Outcomes in MQL5

Do My EA's Losses Come in Clusters? A Wald-Wolfowitz Runs Test for Trade Outcomes in MQL5

A pause after a losing streak assumes that losses come in clusters. CRunsTest turns the closed trades of an account or a tester run into a sequence of wins and losses and checks it with the Wald-Wolfowitz runs test, streak checks against shuffled orders, and a drift test. No dependence was detected on the tested EAs. A power simulation shows which effects each check could see, and on the shorter test runs a "not detected" result carries little weight.
preview
Developing Statistical Market Inflection Forecasting Indicator

Developing Statistical Market Inflection Forecasting Indicator

An MQL5 indicator forecasts where a movement is likely to terminate and how far the opposite leg has typically traveled, using statistics from completed moves on the same symbol and timeframe. It detects confirmed pivots, takes a single snapshot, selects similar historical observations, and reads entry, stop loss, and take profit from their distributions. Empirical hit rates come from a chronological replay without look‑ahead, and resolved forecasts leave the chart with an option to review them.
preview
Chart Synchronization in MQL5 (Part 2): Building an Interactive Multi-Chart Tool

Chart Synchronization in MQL5 (Part 2): Building an Interactive Multi-Chart Tool

This article turns the Part 1 prototype into an interactive MetaTrader 5 indicator that synchronizes charts of the same symbol across different timeframes. It handles keyboard input and drag events via OnChartEvent, traverses charts with ChartFirst/ChartNext, and maps time using iBarShift and ChartNavigate. A draggable vertical line keeps the selected time near the chart center, while a horizontal line propagates a chosen price level. The result streamlines multi-timeframe comparison.
preview
From Basic to Intermediate: Objects and Subwindows (III)

From Basic to Intermediate: Objects and Subwindows (III)

This article describes a safe way to handle the deletion of graphical objects: event interception, object recreation, and restoration of a minimal set of properties. We'll show you how to avoid errors when working with pointers, prevent unwanted object recreation during shutdown, and preserve object positions and dimensions by updating them using DRAG/CHANGE. As a result, the indicator remains intact, and the user retains some of their settings.
preview
From Basic to Intermediate: Objects and Subwindows (II)

From Basic to Intermediate: Objects and Subwindows (II)

This article explains how to track and handle the removal of objects from the chart in MQL5 using MetaTrader 5 events. When the code detects that an object created by an indicator has been deleted, it deletes the corresponding instance to avoid inconsistencies and prevent subwindows from being left behind. This approach uses unique names and a header file, prioritizing simplicity and predictable behavior.
preview
Temporal Causality Audit in MQL5: Validating Recorded Dependencies Against the Decision Time

Temporal Causality Audit in MQL5: Validating Recorded Dependencies Against the Decision Time

Look-ahead errors arise when a decision consumes values that did not yet exist, such as a partially formed higher-timeframe bar. This MQL5 library logs input timing metadata and validates declarations against the decision time with eight ordered rules, returning PASS, WARNING, or FAIL and a named violation. A demo EA plus twelve deterministic tests at a fixed timestamp illustrate correct and failing cases.
preview
A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

A Trade Request Preflight Class in MQL5: Checking Volume, Stops, Margin and Sessions Before OrderSend

CTradePreflight checks a trade request before OrderSend(), so an EA finds an off-step volume, a wrong-side stop, missing margin or a closed session instead of getting a server rejection. The class repairs only safe cases, reads the OrderCheck() retcode, and counts every refusal by reason. Unit tests and a random-delay stress EA show that levels placed very close to the price can still fail, and an optional delay buffer stops those rejections at the cost of blocking some valid requests.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

Overcoming Accessibility Problems in MQL5 Trading Tools (Part VIII): Building a Floating Risk Management Calculator Module for Any EA

A reusable MQL5 component measures floating P/L with swap, gross loss, two stop‑loss quantities, equity gap, margin level, and stop coverage, then classifies results for selected positions and the whole account. The snapshot records validity and readable reasons, supporting a quote‑age policy and missing‑stop handling. Integrate it into an Expert Advisor and block new exposure when thresholds or data checks fail.
preview
Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

Measuring What Matters (Part 5): The Risk Concentration Indicator — Plotting Eigenvalue Dominance Live

This article presents a live MQL5 indicator for monitoring portfolio risk concentration through eigenvalue decomposition. The indicator calculates rolling covariance statistics for three instruments using persistent prefix sums, aligns price data by timestamp, handles missing observations, and plots the dominant eigenvalue as a percentage of total portfolio variance. The implementation provides a practical way to observe changes in portfolio risk concentration as the covariance structure evolves over time.
preview
From Basic to Intermediate: Objects and Subwindows (I)

From Basic to Intermediate: Objects and Subwindows (I)

This article provides a detailed look at creating and positioning the OBJ_CHART object in subwindows, with a particular focus on the differences between the main window and the subwindows. It shows how to integrate indicators using resources (#resource, ChartIndicatorAdd) and identify the desired subwindow by the indicator short name. As a result, the code becomes more stable, portable, and reusable.
preview
From Basic to Intermediate: Resources

From Basic to Intermediate: Resources

In this article, you'll learn about a concept that can prove extremely useful in many situations and significantly simplify the sharing of your apps and projects. Although it is not easy to fully explain this concept in a single article, what will be presented and explained here will be enough to enable us to accomplish a great deal in the future—including things that would otherwise be impossible. That is exactly why this article has not been published until now: to give you supporting material and a starting point for your studies.
preview
Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

Why My MQL5 EA Passed Validation and Still Failed Under Execution Delay

An EA that passes CodeBase validation can still fail under execution delay and a freeze level. Using a tick scalper, the article reproduces four such failures in the Strategy Tester and shows each fix with its limits. An ablation under a fixed delay measures each change on its own. The burst-based stop distance removes most rejected modifications, while the weekend case behind the session buffer did not recur in those runs.
preview
Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

A published daily history of option-implied variance is combined with a broker symbol's daily bars to fit a HAR model of realized volatility in MQL5; the implied term enters the regression as a predictor, not as a ready-made forecast. Out-of-sample tests on four funds paired with their Cboe indices, ten US equities, and two broker symbols show where it improves the forecast. A background service refits on the broker's bars and draws a five-session price range on the chart, and a self-test matches independent C++ and Python implementations.
preview
From Basic to Intermediate: Subwindows (IV)

From Basic to Intermediate: Subwindows (IV)

In this article, we'll see that things aren't quite what many people initially think they are. One of the most interesting aspects of programming is that we can guarantee that everything will always turn out exactly as we planned. So please read this article carefully to understand some of the most confusing concepts related to the use of subwindows. If you understand what is explained here, you'll be able to understand much of what we'll be doing next.
preview
Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

The Session Analyzer is upgraded to define sessions by local market time and to translate those windows into broker/server time with date-aware DST logic. We describe the session model, broker offset treatment, and efficient bar selection, then add a relationship layer that measures temporal overlap, shared price range, range breaks, and size ratios. This provides a clear, reusable basis for session-based research and chart inspection
preview
Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

The EA now computes an equal-weight score at M1 confirmation from normalized body fraction, breakout relative to C's range, and elapsed time, while excursions are measured only afterward. We refine processing of closed minutes and export a typed CSV that distinguishes completed observations from snapshots. The result is a clearer, reproducible basis for analyzing confirmed-signal behavior.
preview
From Basic to Intermediate: Subwindows (III)

From Basic to Intermediate: Subwindows (III)

This article takes a detailed look at using subwindows in MQL5 indicators: creating them, detecting instances, and preventing duplication. It also covers INDICATOR_SHORTNAME, querying information about chart windows and indicators, and the difference between displaying indicators in the main chart window and in a separate window. The article also shows how to set the height and boundaries of a subwindow to standardize the interface and simplify the placement of objects.
preview
Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

The article delivers AdaptivePSARTrail.mqh: a reusable header that lets an EA trail positions (its own or external, by symbol/magic) with an adaptive Parabolic SAR. The utility adapts the step from divergence, guards flips with a side check, and orders broker and improvement gates (stops/freeze, tick grid, break‑even, start and step thresholds). A calculation‑only build serves indicators, result codes aid logging, and a demo EA verifies the integration.
preview
From Novice to Expert: Using Market Structure to Validate RSI Signals

From Novice to Expert: Using Market Structure to Validate RSI Signals

Oscillator thresholds are often treated as direct reversal instructions, causing traders to sell strong bullish markets or buy persistent bearish declines too early. We develop an analytical Expert Advisor that interprets Relative Strength Index events through confirmed swing structure. The model distinguishes continuation, reversal, pending, and expired conditions by combining closed-bar RSI crossings with higher highs, higher lows, lower highs, lower lows, and breaks of structure. It displays each validated interpretation without placing trades.
preview
From Basic to Intermediate: Subwindows (II)

From Basic to Intermediate: Subwindows (II)

This article examines the use of subwindows in MetaTrader 5 in detail and shows how the calculation direction in OnCalculate affects indicator buffers and the plotting of averages. Practical examples explain how indicators are linked using FIRST INDICATOR’S DATA and PREVIOUS INDICATOR’S DATA, the effect of cascading removal of dependent indicators, and how indicator_separate_window behaves. Readers will learn how to diagnose display issues and create indicators that work correctly in subwindows.
preview
Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test

Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test

Implements the Lo–MacKinlay Variance Ratio Test in MQL5 to assess serial dependence via random‑walk variance scaling. Provides a reusable CVarianceRatio class with classical (homoskedasticity) and heteroskedasticity‑robust statistics, plus a script that scans multiple horizons and logs VR and Z‑values. Shows how to embed the test in an Expert Advisor as a statistical gate for mean‑reversion logic.
preview
From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI

From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI

An evidence-first workflow for Range Breakout in MQL5: a non-trading logger captures session/time windows and records 61 fields per breakout to CSV, with a strict split between entry features and hindsight labels. The MT5 AI Assistant processes the dataset in nine phases, helping validate data, quantify baselines, and locate stable, entry-usable thresholds for subsequent EA coding.
preview
Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts

Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts

This article shows how to make EA close operations comply with broker-enforced FIFO (ACCOUNT FIFO CLOSE) on hedging accounts, so naive exits stop failing. It introduces CFifoPositionQueue to order an EA's own tickets by time and CFifoComplianceGuard to execute closes in two modes: strict reject or auto-cascade, with optional per-direction scope. The guard re-verifies eligibility before each step, normalizes volumes, and inspects real server retcodes. You get reusable code, tests, and clear limits.
preview
From Basic to Intermediate: Subwindows (I)

From Basic to Intermediate: Subwindows (I)

In this article, we'll start exploring how to work with subwindows in MetaTrader 5 using MQL5. This is a broad topic with several practical aspects that may prove challenging, so we'll start with a brief introduction. And yet, dear reader, it’s important that you understand what we’re going to discuss here, because it could play an important role in your future.
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
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
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
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
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
Automating Chart Patterns in MQL5 (Part 3): The Head and Shoulders and Inverse Head and Shoulders

Automating Chart Patterns in MQL5 (Part 3): The Head and Shoulders and Inverse Head and Shoulders

The article implements a deterministic MQL5 detector for head and shoulders and its inverse, validating structure from swing labels (HH, LH, HL, LL) rather than raw peak geometry. Seven ATR-aware checks enforce time order, pattern span, head clearance, shoulder symmetry, and height. A three-state lifecycle separates formation from neckline break, locks a setup, and prevents re-entry. Entries trigger only on a chart-timeframe close through the neckline.
preview
Building A Candlestick Trend Constraint Model (Part 11): Revealing Lower-Timeframe Triggers Within Higher-Timeframe Candle Relationships

Building A Candlestick Trend Constraint Model (Part 11): Revealing Lower-Timeframe Triggers Within Higher-Timeframe Candle Relationships

This article develops an A-B-C-D candlestick constraint model for MetaTrader 5. Candles A and B establish a completed D1 relationship, Candle C supplies a historical M1 setup, and closed M1 candles inside the developing Candle D either confirm or invalidate the sequence. We implement the design as a visual Expert Advisor with optional trading disabled by default, sequence-specific chart objects, restart-safe history reconstruction, spread and position gates, normalized trade parameters, and a reproducible testing plan.