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
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.
preview
Bimodal Market Profile with Delta and Memory in MQL5

Bimodal Market Profile with Delta and Memory in MQL5

The classic Market Profile from forty years ago is still replicated in dozens of indicators that differ only in the color of their bars. In this article, I examine three conceptual blind spots in the original theory — the monolithic Value Area in bimodal distributions, TPO’s blindness to the aggressor, and the lack of memory between sessions — and build an indicator that addresses each of them: bimodality detection with a dead zone, order flow via CopyTicksRange with absorption detection, and composite market memory using Naked POC and HVN/LVN. The complete source code is included.
preview
Automating Classic Market Methods in MQL5 (Part 9): Linda Bradford Raschke's 3/10 Oscillator System

Automating Classic Market Methods in MQL5 (Part 9): Linda Bradford Raschke's 3/10 Oscillator System

The article implements two swing setups in MQL5: Anti, which enters on the first 3/10 oscillator pullback after a signal line zero confirmation with price confirmation, and Holy Grail, which enters on the first pullback to the 20 EMA in a strong rising ADX trend. A single EA runs two independent state machines with precise entry and exit rules, ATR-based stops, and state recovery. You get runnable code and traceable logging.
preview
Engineering Trading Discipline into Code (Part 9): Building a Trade Activity Audit Trail in MQL5

Engineering Trading Discipline into Code (Part 9): Building a Trade Activity Audit Trail in MQL5

Trade authorization controls what a cooperating Expert Advisor is permitted to send, but not every account action passes through that code. A trade may originate from the desktop terminal, a mobile device, the web terminal, or another Expert Advisor. This installment develops an independent auditor that records live transaction stages through OnTradeTransaction(), reconciles available historical orders and deals within a configured recovery window, and writes an account-bound CSV journal. An on-chart panel summarizes the selected period and provides refresh, detail, and export controls without modifying trades.
preview
Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

This update adds manual position adoption and multi-symbol lifecycle management. The manager detects and tracks positions regardless of the chart, applies initial protection, transitions to break-even under fixed or ATR triggers, and validates broker constraints per symbol. Using the MACD sample for context, it demonstrates reusable management across instruments and manually opened trades.
preview
Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

The article develops a practical MetaTrader 5 tool that synchronizes charts of the same symbol across timeframes, starting from a script and moving to an interactive indicator. It uses time as a common reference, converts it to bar indices with iBarShift(), and navigates charts with ChartNavigate(). The result is a synchronized workspace for efficient MTF analysis. This is Part 1 of a three-part development series.
preview
Where your backtest stops being real: Measuring the depth of your broker's tick history

Where your backtest stops being real: Measuring the depth of your broker's tick history

In the "Every tick based on real ticks" mode, the Strategy Tester's journal reports the minutes for which real ticks were absent or discarded and says that every tick generation was used for them. We show where the journal records this, measure how far back usable tick history goes on two demo servers, and check the ticks from inside an Expert Advisor, so a test range can be chosen by its real-tick share.
preview
The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The article introduces a centralized cache that serves indicators to multiple strategy nodes. It encodes full indicator identity in keys, stores Standard Library objects in CArrayObj entries, reuses matching instances, verifies readiness, refreshes data, and deletes each indicator on final release. Readers gain a predictable resource lifecycle and reduced duplication in multi‑symbol Expert Advisors.
preview
Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

This article presents an exception-like model for MQL5 that prevents VM faults through defensive guards and cooperative TRY/CATCH/FINALLY macros. It introduces structured error objects (CException), result propagation (CResult), manual stack tracing, and integrated logging for clear diagnostics. Readers learn how to validate risky operations, propagate failures predictably, and keep EAs stable when facing zero‑divide, null access, invalid handles, and array‑bounds conditions.
preview
The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

We present a multi‑symbol EA structure that moves symbol‑specific state into independently initialized CStrategyNode objects and manages them with CPortfolioManager. Using CArrayObj with FreeMode, Add(), At(), Delete(), Total(), and Clear(), the manager ensures safe ownership and isolation, while timer‑driven routing and completed‑bar gates keep processing deterministic. This lets you scale portfolios, control risk per node, and avoid duplicated event handling.
preview
Building Your Personal Expert Advisor (Part 7): Risk Management VI (Final)—Consolidating the Risk Framework

Building Your Personal Expert Advisor (Part 7): Risk Management VI (Final)—Consolidating the Risk Framework

The article consolidates trade, basket, and account risk into a modular framework for MQL5 EAs. Risk logic moves into reusable classes and shared types, leaving the EA with its inputs, signal, configuration, and call sequence. The result is a shorter strategy file and a second EA that reuses the basket tier and the shared conversions.
preview
Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 87): Searching Chart History with Recorded Double-Bottom Samples

This stage connects structural validation with reference matching for double bottoms. The Expert Advisor scans completed history, filters pairs by the current structural rules, and compares normalized close and low profiles against validated samples from the library. Results that meet the similarity requirement appear in the panel for chart review and are saved to REFERENCE_MATCHES.csv.
preview
How to Detect and Normalize Chart Objects in MQL5 (Part 6): Manipulating Chart Objects with MetaTrader 5 Agentic AI Assistant

How to Detect and Normalize Chart Objects in MQL5 (Part 6): Manipulating Chart Objects with MetaTrader 5 Agentic AI Assistant

This article demonstrates how natural-language prompts generate MQL5 producer programs that place native chart objects, and how a deterministic Expert Advisor (AIObjectTrader) reads them through a structured naming and geometry contract. We compare indicator and script routes, using three cases: horizontal resistance, a persistent Andrews' Pitchfork, and Fibonacci Time Zones. Readers gain a reproducible workflow to connect AI-built objects to TOUCH/BREAK/ZONE evaluation and optional execution.
preview
Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

Recovering Option-Implied Probability Distributions Across Four Markets in MQL5

A practical route from the option chain to probability levels inside MetaTrader 5. For GLD, SLV, SPY, and USO, the risk-neutral density implied by each ETF's options is recovered with the Breeden-Litzenberger identity and checked for static arbitrage, after the method itself is validated against an analytic lognormal. A Python feed publishes the percentiles; an MQL5 service rescales them onto a related symbol, draws levels, and alerts when price leaves the risk-neutral 5 to 95 percent band. Every reading carries its own diagnostics, and full source is included.
preview
Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

Price Action Analysis Toolkit Development (Part 86): Validating the Entire Sample Library

This part adds library-wide validation to the double-bottom toolkit. VALIDATE ALL applies the single-sample rule engine to the stored collection, counts its four outcomes and exports a separate CSV report. The report includes settings, sample context and detailed results. Source samples remain unchanged, and export errors are reported separately from completed validation.
preview
Interactive Supply and Demand Zone Manager in MQL5 (Part V): Persisting Zones Across Terminal and EA Restarts

Interactive Supply and Demand Zone Manager in MQL5 (Part V): Persisting Zones Across Terminal and EA Restarts

We introduce a versioned persistence layer that saves and restores the zone engine's logical state across sessions. The snapshot preserves lifecycle status, interaction history, scores, blacklist prices, and the geometry and time anchors of user‑drawn rectangles, and it is reconstructed and reconciled with chart objects on startup. User zones enter with the minimum score so they integrate into the same lifecycle and trading pipeline.
preview
Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 85): Visualizing and Reviewing Validated Double-Bottom Samples

This part adds a visual review layer to the double-bottom workflow. It checks the chart context, moves to the recorded period, and renders the range, two qualifying lows, neckline, classification, score, and the first decisive close. The annotations mirror the validator's indices and prices, helping you audit outcomes without changing sample data.
preview
Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

Price Action Analysis Toolkit Development (Part 84): Validating Recorded Double-Bottom Samples

This work adds an explainable validation module to the recording toolkit for double bottoms. It finds and filters swing lows, selects the neckline, quantifies depth, low similarity, symmetry and recovery, and assigns a rule-based status and scores accepted pairs. The settings are configurable, the process is reproducible, and the original sample data remains intact for comparison across rule sets.
preview
How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy

How to Test and Customize Built-in MQL5 Programs: Envelopes with Alligator Strategy

Envelopes define percentage boundaries around a moving average, but a boundary touch alone does not identify whether the market is trending or ranging. We build Envelope_Alligator_Strategy.mq5, a custom indicator that reads the built-in Envelopes and Alligator buffers. Ordered Alligator lines classify directional states; interwoven lines identify a neutral state. This context changes how envelope crossings are interpreted and produces testable, non-trading chart signals.
preview
Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library

Price Action Analysis Toolkit Development (Part 83): Building a Reusable Double-Bottom Pattern Library

This recorder bridges visual labeling and systematic research in MQL5. After you position a rectangle, the EA extracts the candles it spans, derives candle geometry, normalizes OHLC values, assigns an ID, and saves the sample for reuse across sessions. The current category is the double bottom, and the module records the chosen sequence without enforcing a predefined pattern definition.
preview
Price Action Analysis Toolkit Development (Part 82): Annotating Historical Bookmarks with Reliable Timeframe Switching

Price Action Analysis Toolkit Development (Part 82): Annotating Historical Bookmarks with Reliable Timeframe Switching

We implement visible bookmark annotations and a hand-off mechanism for cross-symbol and cross-timeframe recall. The navigator stores the target in terminal Global Variables, waits for stable bars after reinitialization, and rebuilds only matching markers with safe cleanup. Traders can inspect saved events in context and navigate back to them without reconstructing chart settings.
preview
Inside MetaEditor's AI Assistant: Writing, Repairing and Testing MQL5 with an Agent

Inside MetaEditor's AI Assistant: Writing, Repairing and Testing MQL5 with an Agent

We use the MetaTrader 5 AI Assistant to execute the full workflow end to end: create an EA from a natural‑language prompt, compile it, break and watch it self‑correct from compiler output, backtest it, and compare a controlled re‑run. The article details the underlying MCP extensions, configuration and safety limits, and how to connect external AI clients. Readers get a repeatable process for building and testing EAs inside the platform.
preview
Developing Smart Chart Objects in MQL5 (Part 2): Automating Trendline Discovery and Lifecycle Management

Developing Smart Chart Objects in MQL5 (Part 2): Automating Trendline Discovery and Lifecycle Management

Learn how Smart Trendline Manager separates creation from lifecycle control while handling both manual and auto-generated trendlines. It demonstrates discovery, registration, proximity and touch handling, bounce/break confirmation, post-break resurrection, expiration, and state-driven visualization. This gives you a consistent, configurable way to manage multiple lines through one orchestrated update process.
preview
Meta-Labeling the Classics (Part 4): Filtering and Sizing MACD Trades

Meta-Labeling the Classics (Part 4): Filtering and Sizing MACD Trades

MACD signal-line crossovers often reflect range noise rather than true momentum shifts, producing whipsaws. We apply a two-layer meta-labeling pipeline with an Optuna-optimized regime gate to filter entries on EURUSD H1, turning a gross-losing rule into a positive but not statistically significant track. A secondary Random Forest adds no lift due to too few gated samples, clarifying when filtering helps and when the ML layer is data-starved.
preview
How MQL5 Lite MCP AI Assistant Changed My Debugging Approach on Generated MQL5 Codes

How MQL5 Lite MCP AI Assistant Changed My Debugging Approach on Generated MQL5 Codes

This article presents a practical debugging workflow with MetaEditor's integrated AI Assistant and a comparison to the previous external approach. We fix a controlled set of syntax and API errors in a D1 PriceMarker EA, inspect modifications, and recompile. The result is validated in the Strategy Tester, with clear boundaries between compilation success and required runtime checks.
preview
Developing a Quantitative Session Analysis Tool (Part 1): Building a Data-Driven View of Market Sessions

Developing a Quantitative Session Analysis Tool (Part 1): Building a Data-Driven View of Market Sessions

The article presents a session analysis workflow in MQL5 that standardizes sessions as structured data with timing, OHLC, range, net move, and the sequence of extremes. It measures how range builds at 25%, 50%, 75%, and 100% of session duration. The chart shows session markers, a compact comparison panel, and an interactive inspector to review individual occurrences.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part VII): MetaTrader 5 Model Context Protocol (MCP) the Grand Solution

Overcoming Accessibility Problems in MQL5 Trading Tools (Part VII): MetaTrader 5 Model Context Protocol (MCP) the Grand Solution

Many traders know what they want to analyze or automate but cannot navigate MetaTrader 5, use MetaEditor, or translate an idea into working MQL5 code. This article shows how the AI Assistant and MCP turn one natural-language prompt into a complete workflow: strategy development, editing, debugging, chart interaction, testing, and permission-controlled trading. We apply the process by building MCP_Accessibility_Assistant.mq5, leaving you with a working, accessible EA and a reusable prompt-driven development method.
preview
Markov Chains in Trading and Price Forecasting

Markov Chains in Trading and Price Forecasting

In this article, we will examine how to build and apply Markov chains in market conditions: from selecting states and counting transitions to generating forecasts of trajectories and levels. We will also see how Markov chains can be applied to qualitative and quantitative data, ways to account for rare events, and the impact of the forecast horizon. Examples are provided using prices and indicators, as well as an option for evaluating a sequence of trades, with ready-to-use implementations in MQL5.
preview
Graph Theory: Study of Graphs Generated by Some Random Process

Graph Theory: Study of Graphs Generated by Some Random Process

This article describes an MQL5 Expert Advisor that models the market as a random graph rather than a fixed structure. Bars are encoded into discrete states; bar-to-bar moves form a decaying, Laplace-smoothed transition matrix, and a k-step random walk yields a bounded directional signal gated by an Erdos–Renyi null-model test. A separate trade-outcome graph over R-milestones learns survival probabilities to manage exits, turning position management into evidence-based rules.
preview
Building a Divergence System (Part IV): Creating a Reusable Divergence Engine for MQL5

Building a Divergence System (Part IV): Creating a Reusable Divergence Engine for MQL5

The article extracts the series' divergence logic into DivergenceEngine.mqh, a reusable header for MQL5 indicators and Expert Advisors. It details the struct-based design, oscillator options (MPO4 or RSI), pivot and state handling, and the minimal access API. A Parabolic SAR EA demonstrates integration by adapting the acceleration factor from the detected divergence, providing a clear pattern you can reuse without duplicating code.
preview
Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

Building Volatility Models in MQL5: Implementing the APARCH Volatility Process

The article introduces the APARCH volatility process to the MQL5 library via the CAparchProcess class, estimating the power exponent (delta) jointly with other parameters. It details the recursion, parameter bounds, stationarity constraints, and starting values and reports SLSQP solver updates that streamline optimization. Implementation correctness is partially validated by reproducing approximations of GARCH and GJR-GARCH conditional volatility under parameter restrictions. A companion APARCH indicator visualizes conditional volatility, standardized residuals, and delta to track volatility dynamics and parameter drift.
preview
Building a Market Behavior Analyzer in MQL5

Building a Market Behavior Analyzer in MQL5

We outline a modular analyzer for MetaTrader 5 that separates detection, interpretation, and visualization. The engine identifies swing highs and lows, assigns structural labels, evaluates impulses and pullbacks, and stores results in a market state object. An on‑chart dashboard and interactive inspection tools make the latest structure and measurements immediately accessible.
preview
From Novice to Expert: Trading Multi-Symbol Basket

From Novice to Expert: Trading Multi-Symbol Basket

The article develops a multi-symbol basket EA that standardizes prices, derives PCA weights with native MQL5 matrices, forms a synthetic spread, and trades z-score deviations from a rolling mean. It validates symbols and synchronized history, stabilizes component orientation, maps signed weights to leg directions, and applies broker-aware volumes, stops, and netting rules. Basket entries run with rollback protection and chart status, with a reproducible testing procedure.
preview
Position Management: Deriving a Self-Calibrating Exit Ladder From Historical MFE in MQL5

Position Management: Deriving a Self-Calibrating Exit Ladder From Historical MFE in MQL5

We implement three MQL5 classes that replace fixed 1R/2R/3R targets with data-driven scale-out levels. CExcursionTracker records each closed trade's maximum favorable excursion in R, CExitLadderCalibrator derives runs from distribution percentiles with lookback and minimum-sample controls, and CLadderExecutor executes them on open positions. The ladder recalibrates as trades accumulate and uses a fallback until enough samples exist.
preview
Building a Neural Loss-Pattern Auditor in MQL5

Building a Neural Loss-Pattern Auditor in MQL5

Aggregate metrics like win rate or profit factor miss sequence-dependent behavior, such as sizing up right after a loss. This MQL5 script trains a small native neural network on closed-deal history to estimate loss probability from behavioral and market-context features. It reports accuracy uplift over a baseline, probability calibration, and permutation feature importance, then combines them into a configurable A-F grade with concise, plain-language recommendations.
preview
Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

A complete MQL5 implementation of the Ljung-Box test helps verify independence in trading data and fitted-model residuals. It computes sample autocorrelations, the Q statistic over selected horizons, degrees of freedom with user-controlled adjustments, and right-tail p-values via the regularized incomplete gamma function. Run it on returns, deal outcomes, or external residuals and review decisions directly in the Experts tab.
preview
Building a Dynamic and Customizable Table in MQL5

Building a Dynamic and Customizable Table in MQL5

This article presents a reusable CTable class for building chart-based tables in MQL5. It covers table architecture, creation and destruction of objects, coordinates and sizing, cell properties, horizontal/vertical headers, dynamic row/column edits, object naming, index conversion, and efficient refreshing. You will be able to assemble consistent, aligned on-chart dashboards for market data, indicators, and signals with minimal boilerplate.
preview
From Basic to Intermediate: Operator Overloading (V)

From Basic to Intermediate: Operator Overloading (V)

In this article, we will look at how to modify the code to implement a solution entirely unlike what many consider possible in MQL5. Important note: To fully understand this material, you must have a solid grasp of the concepts covered in the previous articles.
preview
MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

The article examines an example of a multipurpose trading robot template that is suitable both for creating your own strategies and as a codebase for freelance work. A key feature of the solution is bar-based trading; the code already includes built-in modes for averaging, martingale, and holding positions for extended periods. This material will be most useful to beginners who want to develop their own simple strategies or learn about common trading techniques.
preview
From Basic to Intermediate: Operator Overloading (IV)

From Basic to Intermediate: Operator Overloading (IV)

In this article, we will take a first step toward showing how to implement operator overloading for the index operator and the assignment operator, while striving to offer a practical and interesting approach for everyone. What we will see here is only part of what I still intend to show, and it is directly related to the overloading of these operators.