MQL4 and MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
preview
Neural Networks in Trading: From Transformers to Spiking Neurons (SpikingBrain)

Neural Networks in Trading: From Transformers to Spiking Neurons (SpikingBrain)

The SpikingBrain framework demonstrates a unique approach to data processing: neurons respond only to significant events, effectively filtering out noise. Its event-driven architecture reduces computational costs while preserving key information about price movements. Adaptive thresholds and the ability to use pre-trained modules ensure the model's flexibility and scalability.
preview
Time Series Shapelets: Learning a Price Shape, and Testing Whether It Means Anything

Time Series Shapelets: Learning a Price Shape, and Testing Whether It Means Anything

We implement a Time Series Shapelet library for MQL5 that finds the subsequence of price history whose z-normalized shape best separates two labels and derives the decision threshold from information gain. Because candidate searches on prices always return a winner, the fit includes a purged hold-out and a calibrated block permutation null. You get a reusable facade and rules you can plot and evaluate against an explicit noise floor.
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
Monthly Profit and Loss Calendar Heatmap Renderer in MQL5

Monthly Profit and Loss Calendar Heatmap Renderer in MQL5

The article presents an MQL5 script that reads closed deals, groups them by date, and renders a calendar grid for daily P&L and trade count. It explains the data model, normalization to midnight, robust week/weekday mapping, diverging and single-hue color scales, and CCanvas-based drawing, plus a verification script and weekday summary. This helps you quickly locate clusters and quiet periods and cross-check findings with logged totals.
preview
Swarm Optimizer with Hierarchical Sub-Flocks — Flock by Leader

Swarm Optimizer with Hierarchical Sub-Flocks — Flock by Leader

We are developing and implementing the Flock by Leader algorithm in MQL5: sub-flocks are formed based on the ARF metric, and the leader is determined by the highest personal best rather than by the centroid's position. We present the update formulas for the swarm roles and the separation mechanism. The C_AO_FBL class is compatible with the test bench and has been tested on the Hilly, Forest, and Megacity functions with dimensionalities from 10 to 1000 coordinates, which simplifies reproduction and comparison.
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
Consecutive Loss Streak Analyzer and Risk-of-Ruin Calculator in MQL5

Consecutive Loss Streak Analyzer and Risk-of-Ruin Calculator in MQL5

This article presents an MQL5 script that extracts closed trade history, computes empirical win rate and payoff, and evaluates consecutive-loss probabilities using the geometric tail, plus risk of ruin from edge and position size. It plots a CCanvas ruin curve with a live marker at the chosen risk and prints a probability summary, including the account's worst historical streak in theoretical context.
preview
The Deflated Sharpe Ratio in MQL5: Telling a Real Edge from a Lucky Backtest

The Deflated Sharpe Ratio in MQL5: Telling a Real Edge from a Lucky Backtest

A Sharpe ratio read off the best of many optimization runs is not the number it looks like. This article ships a reusable native CDeflatedSharpe class that turns a raw Sharpe into an honest confidence statement. The Probabilistic Sharpe Ratio corrects it for sample length and for skew and kurtosis; the Deflated Sharpe Ratio adds the correction almost nobody applies, for the number of variants you tried before keeping the best. Everything is from scratch, the sample moments, the normal CDF and its inverse included, so there is no Python, no DLL and no library. On a real sweep of 56 moving-average variants on XAUUSD the winner looked significant at 98.5 percent by PSR, then fell to 90.6 percent once the 56 trials were admitted, below the usual bar. That gap is the selection bias, made measurable.
preview
Swing Extremes and Pullbacks (Part 5): Filtering Weak Swings Using Candle Imbalance

Swing Extremes and Pullbacks (Part 5): Filtering Weak Swings Using Candle Imbalance

This article implements an MQL5 Expert Advisor that scores each impulse leg behind a swing extreme with a 0–100 Candle Imbalance Score. The score combines four bounded components—body dominance, directional consistency, leg efficiency, and Fair Value Gap coverage—to filter weak swings before any pullback setup is armed. You will see enforced swing alternation, a state machine for first-clean-retest-only entries, and a three-mode trailing stop, enabling consistent setup selection and exit management.
preview
Neural Networks in Trading: Robust Trading Signals in Any Market Regime (Conclusion)

Neural Networks in Trading: Robust Trading Signals in Any Market Regime (Conclusion)

The article provides a detailed examination of the integration of the ST-Expert framework's approaches into the Extralonger architecture, which enables the simultaneous analysis of temporal and spatial representations of data. The results of testing on real historical data are presented, demonstrating the model's effectiveness and its robustness to market anomalies. The article describes the framework's modular structure, which ensures reproducibility, flexibility for research, and the ability to optimize components in stages.
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
Creating and Testing a Council of 15 Models in MetaTrader 5

Creating and Testing a Council of 15 Models in MetaTrader 5

The article describes the transition from four-voice debates to the Council of Fifteen: ten analysts, four independent risk managers, and a Chair, with strict voting rules. It examines the roles of the participants, the three-phase architecture, and the parallel execution of a full cycle in 10–15 seconds. It shows the operational log, the risk-gate rules, and backward compatibility so you can quickly connect the system to an Expert Advisor.
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
Win Rate and Edge Ratio Heatmap by Hour and Symbol in MQL5

Win Rate and Edge Ratio Heatmap by Hour and Symbol in MQL5

This MQL5 dashboard aggregates closed deals by symbol and UTC hour, calculates win rate and average reward‑to‑risk, and displays the results as two color‑coded heatmaps. A companion table in the Experts tab highlights the strongest and weakest symbol/hour cells, with an option to require a minimum trade count to reduce noise.
preview
Neural Networks in Trading: Robust Trading Signals in Any Market Regime (Attention Modules)

Neural Networks in Trading: Robust Trading Signals in Any Market Regime (Attention Modules)

In this article, we continue implementing the ST-Expert framework approaches, focusing on the practical aspects of applying them using MQL5. Earlier, we examined the theoretical foundations and key components of the model; now we move on to working directly with graph attention algorithms and local and global attention distribution. The main goal of this work is to demonstrate how ST-Expert's conceptual ideas are transformed into workable solutions for analyzing and forecasting financial time series.
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
State Persistence in MQL5 (Part 1): A Crash-Safe State Store That Survives a Restart

State Persistence in MQL5 (Part 1): A Crash-Safe State Store That Survives a Restart

The series develops state persistence for MQL5 Expert Advisors. Part 1 delivers a crash-safe key-value store: a CStateStore class that saves through a temporary file and a rename, carries a versioned header with a checksum, and stores integers, doubles, strings, booleans, and double arrays, plus a demo advisor that resumes a counter and a rolling window after a restart. Readers get a compact include file and a pattern that protects the live state file if the process dies mid-save.
preview
Symbolic Fourier Approximation in MQL5: Benchmarking SFA Against SAX

Symbolic Fourier Approximation in MQL5: Benchmarking SFA Against SAX

We implement Symbolic Fourier Approximation in MQL5 and compare it to SAX under a shared harness on identical price windows. SFA keeps low‑frequency Fourier coefficients and learns per‑position bins (MCB), with a proven, sound lower bound. The measurements show how the same bit budget behaves under different splits of word length and alphabet, and give a practical rule for choosing settings for your symbol.
preview
Uncertainty as a Model (Part 2): Dependence Among Random Variables — From Correlation to Copulas

Uncertainty as a Model (Part 2): Dependence Among Random Variables — From Correlation to Copulas

The second part of the series examines the mathematical framework for multivariate random variables, which is necessary for analyzing the dependence and joint behavior of market assets. This section describes joint distribution functions, the concepts of marginal and conditional distributions, and the conditions for dependence and independence of variables. The theoretical material is based on extending the analogy between probability and mass to multidimensional space. Particular attention is given to measures of association: from classical linear covariance and correlation to modern tools such as copulas and Shannon mutual information.
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
Trade Duration vs Profitability Scatter Plot Indicator in MQL5

Trade Duration vs Profitability Scatter Plot Indicator in MQL5

The article presents a compact dashboard that relates trade duration to net profit using MQL5 and CCanvas. It pulls closed deals, derives duration in minutes, and renders a log‑scaled scatter by symbol, with an overlaid least‑squares line and R². A bucketed duration view identifies which hold‑time range produced the highest average result, helping assess exit timing.
preview
Neural Networks in Trading: Robust Trading Signals in Any Market Regime (ST-Expert)

Neural Networks in Trading: Robust Trading Signals in Any Market Regime (ST-Expert)

In this article, we will explore the ST-Expert framework, which ensures the robustness of forecasts under market uncertainty by taking local and global dependencies in time series into account. Its flexible architecture promotes model adaptability and improves the accuracy of predictions.
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
Market Microstructure in MQL5 (Part 9): Pullback Quality

Market Microstructure in MQL5 (Part 9): Pullback Quality

Part 9 adds a second measurement layer to Part 8's micro‑trend signal: pullback quality. It maps Fibonacci retracement depth to a six‑level PULLBACK QUALITY label, adds an H1 range position from a 60‑bar rolling proxy, and uses lag‑1 momentum autocorrelation. These inputs form a single composite entry‑quality score in [0,1] for filtering setups and sizing trades within MicroStructure_Foundation.mqh.
preview
Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

Intrinsic Time: From the Directional-Change Scaling Laws to the Alpha Engine

The article implements intrinsic-time analysis in MQL5: an event-based directional-change operator that splits ticks into directional-change and overshoot sections. We reproduce the core scaling laws on 17.8 million live EUR/USD ticks and compare them to a random-walk baseline. Finally, we build a hedging-account Expert Advisor that trades the Alpha Engine with limit orders, detailing thresholds, inventory skew, and liquidity control for practical reuse.
preview
Implementing and Comparing Five Historical Volatility Estimators in MQL5

Implementing and Comparing Five Historical Volatility Estimators in MQL5

The study implements five historical-variance estimators in MQL5 and evaluates their one-session-ahead persistence forecasts for EURUSD D1 sessions using an M1 realized-variance proxy. Deterministic tests cover formulas, chronological order, and target construction. A configurable indicator, comparison scripts, and CSV outputs provide reproducible losses, calibration diagnostics, a common‑target mask, and sensitivity to the estimation window.
preview
Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

Money Management in MQL5 (Part 1): Kelly Position Sizing from the Strategy's Own Edge

This article applies the Kelly criterion to position sizing in native MQL5. It presents a reusable CKelly class that estimates win rate and payoff from closed deals, derives the Kelly fraction, and sizes lots from a stop distance. A Monte Carlo sweep of the Kelly multiplier shows growth peaking at full Kelly while drawdown and ruin increase, motivating fractional Kelly such as half Kelly that preserves most growth with materially lower drawdown.
preview
Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 5): Fill Rules, Holes and Borders

Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 5): Fill Rules, Holes and Borders

Part 5 adds a fill rule to the rasterizer and a stroke helper to the path. The engine now supports both non-zero and even-odd fills via a single enum parameter, enabling rings, true borders that do not repaint interiors, and glyph counters. AddThickLine() builds strokes from fills in one path and one pass, preserving uniform opacity at joints and showing why strokes require the non-zero rule.
preview
How to Implement Competition Among LLM Agents in MetaTrader 5

How to Implement Competition Among LLM Agents in MetaTrader 5

The article describes a competitive architecture for MetaTrader 5 in which ten LLM agents, each with different trading rules, manage their own capital and open independent positions using unique magic numbers. The system prompt and the agent's trading aggressiveness are adjusted based on PnL results and the trade streak. A reproducible framework with operating modes and monitored metrics is presented, suitable for testing and further optimization.
preview
Neural Networks in Trading: A Unified View of Space and Time (Conclusion)

Neural Networks in Trading: A Unified View of Space and Time (Conclusion)

The Extralonger framework demonstrates a unique ability to integrate spatial and temporal factors into a single model, ensuring high forecast accuracy. Its architecture allows it to adapt to different planning horizons and financial instruments while maintaining the system's transparency and manageability.
preview
Profit Factor Stability Chart Across Rolling Windows in MQL5

Profit Factor Stability Chart Across Rolling Windows in MQL5

A modular MQL5 toolkit computes and visualizes rolling Profit Factor over fixed trade-count windows. It presents the statistical motivation, an incremental algorithm that avoids recomputation, and a dedicated CCanvas rendering pipeline. The dashboard adds reference lines, shading for weak periods, and summary metrics, while a separate test suite validates the math, giving a practical way to monitor stability and detect deterioration in strategy behavior.
preview
Beyond REST and ZeroMQ: Building a gRPC/Protocol Buffers Bridge for Real-Time MetaTrader 5–Python Inference

Beyond REST and ZeroMQ: Building a gRPC/Protocol Buffers Bridge for Real-Time MetaTrader 5–Python Inference

This article defines a Protocol Buffers contract for the MetaTrader 5-Python boundary and implements a length-prefixed Protobuf-over-TCP client in MQL5, since MQL5 cannot speak real gRPC natively. A small Python shim relays those frames to a genuine grpc.aio server, unary today, with streaming already live on the backend. You get schema-enforced, strongly-typed messages, explicit errors, retry/backoff, and a Strategy Tester cache for reproducible backtests where sockets don't run.
preview
Self-Exciting Markets: Building a Hawkes Process from Scratch

Self-Exciting Markets: Building a Hawkes Process from Scratch

Volatility arrives in clusters: one large move makes the next large move more likely, and quiet spells stay quiet. This article builds a Hawkes self-exciting point process in pure MQL5 to measure that effect directly, ending in a single number, the branching ratio, that says how reflexive a market currently is. You get a small, tested library, an indicator that plots the fitted intensity live, and a demonstration Expert Advisor, along with the honest limits of all three.
preview
Architecture for Collective Trading Decisions by AI Agents

Architecture for Collective Trading Decisions by AI Agents

The article describes the architecture of a multi-agent trading system based on the grok-4-fast language model, in which, instead of a single system prompt, four independent analysts with fundamentally different roles operate: a bull, a bear, a risk manager, and an arbiter. Three analysts run in parallel using a ThreadPoolExecutor and, within 3–5 seconds, formulate well-reasoned positions based on the same market data; after that, a deterministic judge renders a final verdict according to strict rules.
preview
From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

From Deal History to Hazard Curves: Survival Analysis Applied To Strategies

This article reframes performance from unconditional win rate to conditional probability given survival time. It introduces an MQL5 library, an on‑chart indicator, and a demo Expert Advisor that read deal history, fit Kaplan–Meier and Aalen–Johansen curves with competing risks, and report forward probabilities over a bar‑based horizon. Readers gain a reproducible way to quantify the chance that the current position reaches its target or stop, and to see the bias of the naive censoring approach.