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
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.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 6): Curves and Adaptive Flattening

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 6): Curves and Adaptive Flattening

This part introduces cubic Bézier curves and a quadratic verb, flattened on append by recursive midpoint splitting (De Casteljau). A conservative flatness test sums distances of control points to the chord and stops within a pixel-based tolerance, adapting detail to curvature. The design keeps downstream code intact while giving you efficient, scale-independent curve quality.
preview
Neural Networks in Trading: Iterative Forecast Refinement Models (RAFT)

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

The RAFT framework offers a fundamentally different approach to forecasting market dynamics — not as a one-time snapshot, but as an iterative refinement of the state in real time. It takes both local and global changes into account, maintaining a high degree of accuracy even with complex price structures.
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
Buzzard Optimization Algorithm (BUZOA)

Buzzard Optimization Algorithm (BUZOA)

BUZOA is a population-based metaheuristic algorithm in which each agent randomly selects one of three hunting tactics at each iteration: a narrow search around its personal best, a classic PSO step toward the flock leader, or full teleportation to a random point in the search space. The article examines the implementation of the algorithm in MQL5, identifies a coefficient sign error in the original formulation, and presents benchmark results on a standard test bench.
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
Building a Prop Firm Compliance Monitor in MQL5 (Part 3): Daily Drawdown, Overall Drawdown, and Profit Targets

Building a Prop Firm Compliance Monitor in MQL5 (Part 3): Daily Drawdown, Overall Drawdown, and Profit Targets

This part turns stored account references into a financial monitoring engine for MetaTrader 5. It calculates daily drawdown from the confirmed session balance, overall drawdown from the initial challenge balance with a static equity floor, and profit‑target progress from realized balance. The EA derives usage, remaining allowance, and status for each rule, then aggregates them into a single guard state where risk conditions override target completion.
preview
Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Build and deploy a conservative, offline‑trained policy entirely in MQL5. Logged trades become a fixed dataset for a two‑layer Q‑network trained with Conservative Q‑Learning, which pushes down Q‑values for poorly supported actions to limit extrapolation error. The EA loads the frozen weights and applies an out‑of‑distribution guard using saved feature statistics. This yields reproducible training and execution without live exploration.
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
The Hilbert Spectrum in MQL5 — Live Time-Frequency-Energy Visualization of Market Cycles

The Hilbert Spectrum in MQL5 — Live Time-Frequency-Energy Visualization of Market Cycles

The article guides you through building a real‑time Hilbert Spectrum indicator in MQL5: EMD produces IMFs, a discrete FIR Hilbert transform yields analytical signals, and a CCanvas renderer draws a time–frequency–energy heatmap. Implementation details include extrema detection, SD stopping, phase unwrapping, Nyquist clipping, and bin accumulation. Use the panel to identify active cycle bands and regime shifts while keeping trade rules separate.
preview
Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

The article implements Online Portfolio Selection in MQL5: exact simplex projection, four allocators (EG, Universal Portfolio, PAMR, OLMAR), and a BCRP solver on a concave objective. We verify weight paths against the published Python reference and self-check the optimizer. A drift-aware transaction cost model measures turnover and net wealth on a multi-asset basket. Readers get a tested library and evidence on when regret-bounded methods lose to costs.
preview
The Fractional Fourier Domain — A Chirp-Rate Adaptive Cycle Indicator for MetaTrader 5

The Fractional Fourier Domain — A Chirp-Rate Adaptive Cycle Indicator for MetaTrader 5

This article presents a native MQL5 Fractional Fourier indicator for measuring whether the dominant cycle is speeding up or slowing down. It searches for the rotation that maximizes spectral concentration in a detrended analytic window, using a unitary eigenvector FrFT and a golden‑section entropy search, and reconstructs a band‑limited cycle line. Results on known chirps and on real closes across symbols/timeframes show where the method is reliable, its bias, and its limited forward information in practice.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

The article continues the work on implementing the STE-FlowNet framework, which combines multi-stream processing with recurrent structures for accurate analysis of complex data. The tests conducted confirmed its stability and flexibility in various scenarios. This architecture speeds up computations and enables deeper modeling of dependencies in time series. This approach opens up new possibilities for practical application in trading and analytics.
preview
Using Renko-bar Regression with Error Correction

Using Renko-bar Regression with Error Correction

The article presents a regression-based approach to forecasting Renko bars using CatBoost: the model estimates the logarithmic return of the next bar and the uncertainty of the forecast. We will examine a cascade of residual models with OOF validation using TimeSeriesSplit, shrinkage, and overall early stopping, as well as conditional bias correction. On EURUSD D1, a reduction in OOF-MAE was achieved, along with approximately 65% directional accuracy. A working script for MetaTrader 5 is provided that generates a signal, position size, SL, and TP in brick units.
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
Integrating News Sentiment to Avoid Strategy Disruption in MQL5

Integrating News Sentiment to Avoid Strategy Disruption in MQL5

We present a dynamic news‑sentiment filter for MQL5 Expert Advisors. It uses WebRequest to query a REST API, parses JSON sentiment and confidence, and gates entries and exits alongside Moving Average and RSI signals. You get an example EA, integration steps, timer‑based updates, and Strategy Tester workarounds. The outcome is fewer trades against dominant news flow and earlier risk reduction when sentiment flips.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

The article presents the comprehensive architecture of the STE-FlowNet encoder, which combines stack memory, recurrent processing, and a correlation mechanism to extract hidden market dependencies. The article demonstrates how these modules are sequentially integrated into a single computational chain capable of performing comprehensive time-series analysis.
preview
Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

We adapt the Savitzky–Golay filter to a strictly causal, real-time form for MQL5 and derive the fixed coefficients for end-point evaluation. The article provides a full indicator and an Expert Advisor, explains the edge-evaluation noise sensitivity, and implements a multi-bar confirmation safeguard. Backtests on several symbols are shown without cherry-picking. You get ready-to-compile code, parameter guidance, and a reduced-lag alternative to moving averages.
preview
Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

The article constrains the optimal trading rule by a prop-firm stop-loss ceiling and corrects OU fitting by pooling within-trade pairs per AFML eq. 13.6. We apply the ceiling as a feasibility mask on a shared PT–SL mesh, ensuring the constrained set is a subset of the baseline. Practical guidance covers when the ceiling binds, the Sharpe cost, and how exposure and live budget state affect the bound.
preview
Population-Based Optimization Algorithms: Building a Defense Against Cheaters

Population-Based Optimization Algorithms: Building a Defense Against Cheaters

The algorithms were rerun on the updated functions, and a method was proposed for quickly verifying their "honesty". The composite test combines five different landscapes and eliminates the possibility of gaining an advantage based on the geometry of individual problems, allowing for a quick assessment of the algorithm's actual search capability. A script is provided for preliminary validation of algorithms before they are applied to the optimization of trading strategies.