MQL5 Algo Trading
512K subscribers
3.44K photos
3 videos
3.44K links
The best publications of the largest community of algotraders.

Subscribe to stay up-to-date with modern technologies and trading programs development.
Download Telegram
Fixed-period SMA/EMA filters fail when regime changes: short periods amplify noise, long periods add lag, and manual retuning becomes constant maintenance.

A Self-Adaptive Moving Average (SAMA) in MQL5 can be implemented as an adaptive FIR filter using NLMS. Core loop per closed bar: compute input energy, predict via dot product, measure error, clamp error by ATR on spikes, then update weights with a normalized step. No repainting when updates are restricted to finalized bars.

Stability controls include weight leakage to limit drift, optional weight-sum normalization to keep output on price scale, and adaptive learning rate via Efficiency Ratio to reduce overfitting in ranges and tighten tracking in trends. Input modes can train on price, differences, or returns with reconstruction back to price.

Part 2 covers the full indicator build; Part 3 ben...

👉 Read | Quotes | @mql5dev
11👍11🏆4
A structure-based MT5 EA can detect swings and pullbacks yet still fail because it treats every retracement the same. The core upgrade here is volatility-normalized pullback analysis: retracement depth is measured relative to the prior impulse and evaluated against an ATR regime, so the same point pullback can be “too deep” in low volatility and acceptable during expansion.

The system is layered: swing candidates are validated via structure break, displacement, liquidity sweep, and time-respect; a state machine classifies accumulation/expansion/distribution/reversal; liquidity zones track equal highs/lows and untouched swings. Pullbacks are scored using depth, ATR-normalized distance, candle overlap, momentum decay, and volatility compression.

Trades require alignment between market state and a high-scoring pullback, plus sweep or displacement confirmat...

👉 Read | NeuroBook | @mql5dev
12👍5🤯2
MT5 Strategy Tester scales well for parameter sweeps, but the output layer becomes limiting in multi-asset, multi-timeframe work with custom counters. Treat MT5 as compute and export only, then run ranking, mapping, visualization, and reporting in Python.

A strict CSV schema is the contract. Required fields include Test_Phase (Baseline/InSample/OutSample), Symbol, Timeframe, Indicator_Name, Filter_Period, optional Param_SAMA_LR, Net_Profit_$, Sortino_Ratio, plus custom counters like False_Flips_Whipsaws and Avg_Lag_On_Turn_Bars.

Two Python modules cover baseline comparisons (phase filter plus cross-timeframe averaging) and walk-forward validation (pick best InSample by Sortino, lock parameters, report matched OutSample and profit_drop). Outputs stay reproducible, auditable, and consistent for publication constraints such as 980px figures.

👉 Read | NeuroBook | @mql5dev
22👍7
Actor–Director–Critic extends Actor–Critic with a Director that provides binary action fit/no-fit feedback alongside the Critic’s continuous reward estimate. This reduces early-training instability, which is critical in trading where random actions are costly.

A practical implementation adapts ADC to a HiSSD multi-agent setup. Critic and Director train on latent skill representations from the shared encoder, not raw market features, improving generalization and feedback stability under uncertainty.

Training is split into offline pretraining on a fixed dataset, then online fine-tuning with live interaction. Offline uses replay-buffer sampling, recurrent-state resets per minibatch, and strict chronological sequences for RNN components.

Offline targets use a “near-perfect” trajectory built with limited look-ahead, requiring consistent recalculation o...

👉 Read | Signals | @mql5dev
14👍8
Gaussian Process classification shifts from closed-form regression to approximate inference. With logit likelihood, the posterior over latent f is non-Gaussian, so Laplace approximation is used to fit a Gaussian around the posterior mode via Newton iterations on log p(y|f)+log p(f|X). The Hessian yields the covariance of the approximation.

Prediction becomes two-stage: compute a Gaussian predictive distribution for f* at x*, then integrate σ(f*) over that distribution to obtain π*. Averaged predictive probability accounts for uncertainty, unlike σ(E[f*]) MAP.

An MQL5 modular GP library is outlined, centered on GaussianProcess plus a GPOptimizationObjective for Alglib integration, with multiple π* approximations (probit, numeric integration, Monte Carlo) and LML-based hyperparameter optimization with analytic gradients.

👉 Read | CodeBase | @mql5dev
30👍8🤡4🏆2
Many technical indicators are known to generate false signals. Geometric signal validation is used to filter these in real time, keeping valid signals unchanged while rejecting candidates that imply an impossible zigzag leg.

Signals from an indicator should be treated as candidate pivots, not immediate entries. Candidate highs and lows are connected using zigzag-based state logic. If accepting a candidate would create a geometric inconsistency, the candidate is classified as unsafe and the pivot search state does not change.

Pivot confirmation occurs only when a leg completes and the search state switches. Confirmed pivots are marked with arrows, while rejected candidates are marked with an arrow plus an X. The method is indicator-agnostic; Donchian channel signals are used here as an example.

👉 Read | Signals | @mql5dev
21👍6
Competitive Learning Algorithm (CLA) is a population-based optimizer that structures candidates as students grouped into classes. Updates combine three signals: movement toward the class teacher (best member), a delayed personal-best component, and optional inter-class guidance via an average-teacher vector.

A reference implementation (C_AO_CLA_l) exposes popSize, numClasses, beta, gamma, and deltaIter. Each iteration updates teachers, computes class costs and normalized ranks, then adjusts agent coordinates with progress-dependent Teaching/Confirmatory factors plus boundary and step constraints.

Benchmarks at 10,000 function runs show solid early convergence but frequent stagnation later from local trapping. Aggregate score reported: 3.96687 (44.08%), with results improving as dimension scales from 5 to 500 across Hilly, Forest, and Megacity suites.

👉 Read | AlgoBook | @mql5dev
18👍5
Directly calling the MT5 History API inside analytics methods creates hidden terminal-state dependencies: results silently break without the right connection, history cache, or HistorySelect() range. This makes unit tests, edge cases, and long-term maintenance costly, especially when brokers or deal classifications change.

The design is refactored using dependency inversion: analytics modules depend on an ITradeRepository interface, not the History API. A shared STradeRecord struct standardizes trade data and returns safe defaults on invalid access.

CLiveTradeRepository isolates all HistorySelect/HistoryDeal* usage behind two helpers, while CMockTradeRepository serves deterministic in-memory datasets for CI and edge-case simulation. Consumers (analytics engine, risk, equity curve panel) run unchanged, with comparable net-of-cost metrics and negligible dispa...

👉 Read | Freelance | @mql5dev
23👍8
This article outlines an MQL5 Expert Advisor that adds a quantitative filter to ICT-style setups. Instead of trading solely on Fair Value Gaps, Order Blocks, and liquidity pools, it measures whether price has enough “path capacity” to actually reach the target liquidity.

Market structures are detected automatically (swings, FVGs, OBs, equal highs/lows) and converted into nodes of a directed graph. Edges between nodes get capacity scores from tick volume, prior reaction strength, travel distance, and structure importance, then Edmonds-Karp (Ford-Fulkerson) computes maximum flow from current price (source) to nearest liquidity (sink).

Trades require both: valid ICT direction and flow above a threshold. The EA skips bottlenecked paths, compares bullish vs bearish flow, supports multi-timeframe weighting, and sizes positions dynamically based on flow strength.

👉 Read | Freelance | @mql5dev
20👍5
Weekend gap fill logic can be formalized into an MQL5 indicator that detects Friday close vs Monday open gaps, tracks them until fully filled, then writes non-repainting buy/sell signals to EA-readable buffers via CopyBuffer().

Implementation uses four buffers (buy, sell, gap state, fill price), explicit buffer initialization with EMPTY_VALUE, and non-series indexing to avoid off-by-one errors. A gap record struct stores boundaries, direction, lifecycle state, fill time/price, and a “signal published” flag.

Processing is split into historical reconstruction on first run and incremental updates on new bars. A simple state machine (fresh, partial, reaction, filled, historical) drives transitions and arrow plotting, with optional alerts and an InvertSignals switch for reversal vs continuation testing.

👉 Read | Docs | @mql5dev
14👍11👌2👀1
Multivariate market series now routinely exceed what ARIMA/SARIMA can handle under non-stationarity, regime shifts, and microstructure noise. RNNs improve sequence handling, while LSTM/GRU extend context but remain sensitive to feature quality and may miss decisive short-term spikes.

Attention improves long-range dependency capture by reweighting relevant features and time steps, yet can still underreact to fast shocks. DA-CG-LSTM addresses this with dual-stage attention plus a Conversion-Gated LSTM that modifies input/forget gate activations to reduce saturation and improve responsiveness.

Implementation notes in MQL5/OpenCL: split CG-LSTM into (1) linear pre-activation generation and (2) a kernel applying custom activations and state updates. Use float4 loads for bandwidth efficiency. Backprop recomputes required intermediates from pre-activations to avoid extr...

👉 Read | AppStore | @mql5dev
27👍7👀3