MQL5 Algo Trading
581K subscribers
4.7K photos
7 videos
4.71K 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
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
โค53๐Ÿ‘Œ8๐Ÿ‘5๐Ÿ†1
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
โค44๐Ÿ‘6๐Ÿ‘Œ6โœ1
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
โค32๐Ÿ‘9โœ1
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
โค26๐Ÿ‘11๐Ÿ†5โœ1๐ŸŽ‰1
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
โค27๐Ÿ‘5๐Ÿคฏ4
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
โค32๐Ÿ‘8
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
โค25๐Ÿ‘11
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
โค39๐Ÿ‘8๐Ÿคก5๐Ÿ†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
โค38๐Ÿ‘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
โค25๐Ÿ‘7๐Ÿ”ฅ1
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
โค39๐Ÿ‘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
โค37๐Ÿ‘5๐Ÿ‘Œ2
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
โค23๐Ÿ‘11๐Ÿ‘Œ3๐Ÿ‘€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
โค43๐Ÿ‘9๐Ÿ‘€5
An Expert Advisor is available as a research implementation of the Inside Bar continuation hypothesis. The setup requires a two-candle pattern: a Main Bar and a Signal Bar fully contained within the Main Bar range. On a bullish Main Bar close, a Buy Stop is placed above the Main Bar high; on a bearish close, a Sell Stop is placed below the Main Bar low.

Risk controls use Stop Loss as a fraction of Main Bar range and Take Profit via a configurable Risk/Reward ratio, with TP optional. Position sizing supports fixed lots or percent risk from the starting balance captured at EA launch.

Filters include an optional ATR condition requiring Main Bar size to exceed a multiple of recent volatility, plus constraints on Main Bar body and maximum Inside Bar size. Logic runs on new bars only, with one open position and one pending order per symbol, and automatic pending ...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค21๐Ÿ‘8๐ŸŽ‰2โœ1๐Ÿ‘Œ1
AFML-style microstructure features are ported from Python to MetaTrader 5 as a single include file, CMicrostructureFeatures.mqh, so EAs can compute seven bar-level signals directly from OHLCV without external dependencies. It implements Roll spread/impact, Corwinโ€“Schultz spread and intraday volatility, plus Kyle, Amihud, and Hasbrouck lambdas.

A key constraint is MT5 โ€œtick volumeโ€: it counts price updates, not trades. Lambda estimators therefore use a bar-close tick rule and tick volume as approximations, making them best for regime ranking rather than broker-comparable impact levels. Roll and Corwinโ€“Schultz remain volume-free and robust.

The design emphasizes single-pass running sums (no temp arrays), strict new-bar execution to avoid look-ahead, and clean accessors for EA/ONNX pipelines. A companion MicrostructureViewer indicator plots all features wi...

๐Ÿ‘‰ Read | VPS | @mql5dev
โค31๐Ÿ‘7โœ3
High-volatility trading exposes a gap in accessibility: no standard hands-free, low-latency input path for MQL5 tools that works under motor impairments and market stress. Mouse, keyboard macros, hotkeys, and voice pipelines add delay or fail in noisy environments.

A gesture-controlled system is presented using a webcam with MediaPipe Hands and OpenCV in Python, sending gesture codes to MetaTrader via MQL5 Global Variables. An EA polls every 10 ms and executes via CTrade, using a busy-flag and neutral reset to avoid repeated orders.

Benchmarks on an i7-1165G7 laptop (30 FPS, 640ร—480, confidence 0.7) show mean end-to-end latency and accuracy over 100 runs: Buy (index) 68 ms, 97.2%; Sell (thumbs-up) 72 ms, 96.8%; Close-all (fist) 85 ms, 95.4%. 95th percentile stays within 110 ms.

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค29๐Ÿ‘9
This article turns the NLMS-based SAMA from a textbook update rule into a production-grade MQL5 indicator designed to behave predictably in live charts. The implementation avoids common pitfalls: it never trains on the still-forming candle, seeds weights to a neutral 1/N prior to prevent startup instability, and enforces a warm-up phase to reduce session-to-session re-render differences.

Robustness is handled explicitly: NLMS energy normalization is protected with an epsilon floor, extreme one-bar shocks are capped via ATR-based error clamping, and weight leakage adds controlled forgetting. An optional constraint normalizes weights to sum to 1.0, keeping outputs on the price scale.

Tuning is practical: inputs support PRICE/DIFF/RET training, an Efficiency-Ratio adaptive learning rate, and guidance to keep ฮผ โ‰ค 1.0 for stable tracking. Limitations are ...

๐Ÿ‘‰ Read | Docs | @mql5dev
โค33๐Ÿ‘8
Part 71โ€™s weekend-gap marker is upgraded into a rule-based, automatable signal model for MT5. The indicator defines each gap using Friday close and Monday open, filters by minimum tradable size, and only confirms entries on candle close (optionally requiring a price offset), keeping signals non-repainting.

Bullish logic: after a gap-down, a bullish close back above the gap low triggers a buy. Bearish logic: after a gap-up, a bearish close back below the gap high triggers a sell. Take-profit targets the opposite gap boundary; stop-loss anchors to the current weekโ€™s swing extreme with an optional buffer.

Implementation focuses on EA integration: six CopyBuffer-readable outputs (buy/sell arrows plus TP/SL for each), historical signal reconstruction, and a structured pipeline from gap detection to live updates and cleanup.

๐Ÿ‘‰ Read | NeuroBook | @mql5dev
โค28๐Ÿ‘7
Chart objects can now be edited after placement via a floating property ribbon. The update replaces fixed-at-creation styles with descriptor-driven editing and a snapshot-based preview/rollback model.

Four components back the system: per-tool property descriptors, engine get/set by string ID, widget renderers per property type, and a ribbon that binds widgets to the selected object and applies changes live.

Descriptors define type, label, range, defaults, and visibility for ribbon vs settings. Composite types cover compact rows, per-level lists for Fibonacci/Gann, and action entries.

Engine property access resolves object ID, dispatches by property ID, supports per-level arrays, and rejects non-applicable properties cleanly. Changes can be previewed immediately and reverted on cancel.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค25๐Ÿ‘6๐Ÿ˜ฑ4