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
This part refactors a simple candle-imbalance EA into a more adaptive series trader for MetaTrader, targeting stability without losing too many entries.

Key upgrade: replace a fixed β€œbull/bear excess” threshold with a probability-aware, non-linear threshold that decreases as the sample size grows. This keeps signal frequency roughly consistent across different window lengths and avoids unrealistic thresholds on large samples.

Signal quality is improved by treating the analysis window as a range, not a single N: use weighted aggregation across multiple sample lengths, and require the imbalance condition to appear in several samples to confirm a regime.

Risk control focuses on fewer, better-timed grid adds: open new positions only on counter candles (sell on bullish, buy on bearish) and/or only when the imbalance strengthens. This cuts position coun...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀53πŸ‘13πŸ‘€5πŸ†2πŸŽ‰1πŸ‘Œ1
An immediate stop-loss closure triggers an OnTradeTransaction event that can be used to react without polling.

A common approach is to detect the stop-loss deal, confirm the position was closed, and read the closed side, volume, and close price.

Based on those values, logic can place an opposite-side pending order right away, with predefined distance, expiration, and risk limits.

Key points include filtering only the relevant transaction types, avoiding duplicate submissions on partial fills, validating symbol trading conditions, and enforcing spread and freeze-level checks before sending the pending order.

πŸ‘‰ Read | Forum | @mql5dev
❀36πŸ‘8πŸ€”3
Brute-force pattern search for Expert Advisors can remain competitive when combined with strict sample segmentation. Compute limits on multi-year M5 data make full-pass searches impractical even on multi-core hardware.

Segmenting by day of week and intraday time corridors reduces data volume and exposes time-quantized effects. Predictability varies by segment; expected payoff and profit factor often peak in different windows, requiring trade-off analysis.

Algorithm updates add fixed time-interval search, selectable or randomized day sets, randomized server-time windows with duration bounds, and multi-threaded optimization. Templates were adjusted to write day/time fields into quote files to avoid terminal time-function overhead and inconsistencies.

Testing on 2010–2020 with 2020 as forward period shows higher quality patterns with fewer trades. A ...

πŸ‘‰ Read | VPS | @mql5dev
❀69πŸ‘13⚑4😐2
Universal Breakout Study is an open-source Expert Advisor for systematic breakout research on H1. It forms a range (β€œbox”) from a configurable number of hourly candles using GMT-adjusted session time, then places Buy Stop and Sell Stop orders beyond the boundaries with an optional distance shift and order expiration.

Trade protection supports disabled, fixed-point, or box-coefficient Stop Loss and Take Profit. Position sizing is risk-based via a configurable percent of balance. Post-entry management includes breakeven, classic trailing stop with start/step rules, and time-based exits conditioned on minimum profit.

Testing controls include a weekday enable/disable filter to isolate calendar effects. The tool targets hypothesis testing and parameter studies, with forward validation required before any live deployment.

πŸ‘‰ Read | Quotes | @mql5dev
❀43πŸ‘11✍4
Frequent new/delete inside OnCalculate() adds measurable overhead in MT5, mainly from allocation bookkeeping and constructor/destructor work, plus timing jitter that hurts latency consistency during high tick rates. For single-object-per-tick logic, the simplest fix is reusing a persistent object and calling Reset().

When many short-lived objects coexist, a fixed-capacity object pool moves all heap activity to OnInit(). A free-list built from an index stack enables O(1) Acquire/Release without scans, supports ownership validation, and guards against double-release. On exhaustion, Acquire() returns NULL by design to avoid reintroducing heap calls in the hot path.

A benchmark indicator compares pooled vs unpooled paths using GetMicrosecondCount(), with careful buffer handling (EMPTY_VALUE sentinel, no ArraySetAsSeries on INDICATOR_DATA, and DRAW_SECTION for ...

πŸ‘‰ Read | VPS | @mql5dev
❀41πŸ‘Œ6πŸ‘5
A Multi Forex Scanner indicator has been ported to MT5 from an earlier MT4 version, targeting faster identification of potentially tradable FX pairs.

The scanner reads symbols directly from the Market Watch list and displays the currently available currencies without requiring separate configuration.

Visibility is controlled through the platform: to exclude a currency or pair from the output, hide the corresponding symbol in Market Watch. This keeps the scanner aligned with the active watchlist and reduces manual filtering.

πŸ‘‰ Read | Signals | @mql5dev
❀28πŸ‘6πŸ‘Œ6
Part 36 turns the MT5 canvas from pure β€œanalysis lines” into a full annotation surface by adding 17 tools: 8 filled/reshapable shapes (rectangle with 8 handles, triangle, rotated rectangle/ellipse, circle, N-point path, arc, curve) and 9 text-driven markers (text, multiple arrows, note, price note, callout, comment).

The core upgrade is an in-place text editor rendered entirely on the canvas: caret/timer blinking, click-to-caret mapping, multi-line wrap via prefix measurement with binary search, keycode-to-Unicode input, arrow navigation with shift-selection, and anti-aliased text via supersampling and alpha extraction.

Implementation keeps the existing tool pipeline (hit testing, selection, handles, rubber-band preview) and extends the class chain (Fibonacci β†’ shapes β†’ annotations). Shapes use signed-distance anti-aliasing, point-in-polygon tests, a...

πŸ‘‰ Read | AppStore | @mql5dev
❀20πŸ‘9
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
❀20πŸ‘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
❀13πŸ‘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
❀23πŸ‘6πŸ‘€3