MQL5 Algo Trading
542K subscribers
3.88K photos
6 videos
3.89K 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
Backtest output is bounded by history quality, yet MT5 data gaps often go unverified. A read-only Python audit can export M5 bars from multiple terminals, cache them as Parquet, and report missing bars per pair and per year instead of a single “History Quality” number.

The workflow validates terminal identity, avoids concurrent API sessions, and resolves broker-specific symbol suffixes. One broker required paging via copy_rates_from_pos, which exposed synthetic “fill” bars detectable only by timestamp spacing.

On a shared 2025-02-07 to 2026-06-12 window, the same deterministic breakout strategy drifted by 2,300–4,400 net pips across three feeds. Spread differences dominated, but data/price differences and missing-bar trade mismatches remained material.

👉 Read | NeuroBook | @mql5dev
23👍7👌1
Market structure analysis in MQL5 often ships as closed indicators that mix computation with rendering, expose limited buffers, and provide no stable query interface. Integration into EAs typically requires copying indicator logic or rebuilding it, increasing coupling, duplication, and maintenance cost.

A prototype modular framework addresses this by separating swing detection, level tracking, break detection, BOS/CHoCH classification, an event bus with deduplication, a market state machine, optional CSV persistence, and a unified public API. It runs as a standard custom indicator but behaves like a reusable service for EAs, dashboards, and research pipelines.

The codebase is split into 10 include modules plus one indicator entry point, supports internal and external timeframes, and avoids full recomputation via incremental bar processing. Trend a...

👉 Read | Calendar | @mql5dev
32👍5🏆2👌1
Backtest headlines can hide fragility: the same net profit and win rate may come from a repeatable edge or from a few oversized trades. This article builds an MT5-native analyzer that shows where profits really come from by measuring profit concentration.

The script reads closed deals from a simple Date/Profit CSV and computes top-N contribution (vs net and gross profit), the Gini coefficient over winning trades, and a stress test that removes the best winners to see if profitability survives.

It also aggregates results by day to flag “one big day” risk against prop-firm consistency limits, then combines concentration, consistency, and survival into a weighted A+–F grade with actionable recommendations.

👉 Read | Calendar | @mql5dev
40👍52👌2
External Range Liquidity (ERL) is a custom MetaTrader 4 indicator aimed at Price Action and Smart Money Concepts workflows. It scans swings to map market structure and flags liquidity sweeps where price pierces a prior swing but closes back inside the range, leaving a wick.

Structure labeling is applied in real time using HH/HL for bullish conditions and LH/LL for bearish conditions. When a sweep condition is detected, the prior swing level is relabeled as “Sweep”, supporting analysis of stop hunts and failed breakouts.

Key options include swing validation (InpSwingCandles, default 5), history scan cap (InpMaxBarsToScan, default 200), projection line length (InpLineLengthBars, default 15), plus colors, line style/width, and text size/offset. Visual output uses projected horizontal levels to keep charts readable with low terminal overhead.

👉 Read | AlgoBook | @mql5dev
33👍103👌2👨‍💻2
Aegis Quantum Lite is a free educational Expert Advisor for MetaTrader 5, distributed as a single commented MQ5 file. It implements a completed-candle trend entry with a compact on-chart dashboard.

Buy logic requires Fast EMA above Slow EMA, RSI above the configured buy level, spread within the maximum, no existing position on the symbol, and a new completed candle. Sell logic mirrors this with Fast EMA below Slow EMA and RSI below the configured sell level.

Default inputs: FastEMA 9, SlowEMA 21, RSIPeriod 14, BuyRSILevel 48, SellRSILevel 52, FixedLot 0.01, MaximumSpreadPoints 50, StopLossPoints 500, TakeProfitPoints 500, OneEntryPerCandle true. The dashboard shows symbol, timeframe, EMA/RSI values, spread, signal, and trading status.

Execution safeguards include fixed lot only, no grid or martingale, position blocking per symbol, permission and margin che...

👉 Read | Calendar | @mql5dev
👍1514👌3👨‍💻2
Markets switch regimes. A fixed 14-period moving average can track momentum in trends, then generate repeated whipsaws during consolidation. An auto-optimizer mitigates this by continuously testing a period range (for example 10–100) and selecting the parameter set that best matches current price behavior.

Direction alone is not an edge. The optimization layer scores candidates by mathematical expectancy, combining win rate and average payoff to avoid high-hit-rate/low-net systems and low-hit-rate/high-variance profiles.

Take-profit placement can be made objective. By measuring maximum favorable excursion and maintaining an average peak distance before reversal, exits can be based on observed distribution rather than arbitrary ratios.

Single-timeframe signals are filtered by higher-timeframe alignment. Multi-timeframe state checks reduce counter-t...

👉 Read | CodeBase | @mql5dev
22👍9👌4🤣2
Simple moving averages lag trend changes because they only aggregate past prices. A velocity-adjusted average can reduce that lag by incorporating the average rate of price movement into the calculation.

This indicator offers three measurement modes. Central velocity produces a smoother output. Forward velocity is calculated relative to the current bar, increasing sensitivity to recent moves. Backward velocity is calculated relative to the initial bar, preserving more information about earlier movement within the window.

Any mode aims to reduce lag versus a standard SMA, making the result suitable as an SMA replacement where faster reaction is required.

Parameters: Type selects the velocity mode. iPeriod sets the calculation length.

👉 Read | Docs | @mql5dev
20👍7👌3
Linear regression is commonly used to estimate market slope, but many MQL5 indicators recompute rolling OLS on every bar. On tick charts, large lookbacks, or multi-symbol scanners, that O(n) per-bar cost becomes a measurable bottleneck.

Recursive Least Squares (RLS) keeps a compact state and updates it with the latest observation using a Sherman–Morrison rank-1 update. The result is O(1) work per bar, independent of history length, with an adjustable forgetting factor (typical λ range: 0.95–0.99).

A complete MQL5 implementation is outlined via a reusable CRLSRegression class plus two indicators: RLSForecast.mq5 plots a 1-bar-ahead forecast on the main chart, and RLSSlope.mq5 plots a signed slope histogram in a subwindow. Both run incrementally, reset cleanly on full recalculation, and gate output until a minimum warm-up observation count is reached.

👉 Read | Forum | @mql5dev
29👍6👌3
Dingo Optimization Algorithm (DOA) was proposed in 2021 by Peraza-Vázquez et al. in Mathematical Problems in Engineering (DOI: 10.1155/2021/9107547). It is a population-based metaheuristic with three update modes plus a survival rule.

Core behaviors: group attack (subset averaging, then update relative to the best solution with a signed β1 term), chase (update biased toward the best solution using a random neighbor distance scaled by exp(β2)), and scavenging (random neighbor reference with optional sign inversion to increase step variance).

Implementation notes: a C_AO_DOA_dingo class typically exposes popSize, P (hunt vs scavenging), and Q (group attack vs chase). Moving() initializes positions once, updates survival, selects a mode per agent via P/Q, applies bounds/step quantization, then triggers a survival procedure when survival < 0.3.

👉 Read | Quotes | @mql5dev
20👍4👌3🏆2
Backtests produce an equity curve and a trade list, but neither reveals what price did around each entry, during the hold, or near the stop. Visual, trade-by-trade review answers whether signals came from real structure or noise, whether moves were clean or choppy, and whether stops were placed beyond normal volatility.

The article builds an MQL5 Trade Replay Engine that reconstructs closed positions from deal history, draws entry/exit/SL/TP as chart objects, and steps through trades with left/right arrows while auto-centering the chart. It handles partial closes by aggregating multiple OUT deals via shared position IDs, and retrieves missing SL/TP from the original order when brokers don’t populate deal fields.

Implementation is split into focused modules: a trade record struct with derived metrics (duration, pips, R-multiple), a loader that filters/so...

👉 Read | VPS | @mql5dev
20👍7👌5👏2🎉21
Index price behaviour into option expiry is largely mechanical. Dealer hedging flows can suppress moves under long gamma and amplify moves under short gamma.

A practical way to quantify this is Gamma Exposure (GEX): compute Black-Scholes gamma per contract, weight by open interest, apply a dealer sign convention, and aggregate by strike into a signed profile. Key outputs are the call wall, put wall, and the zero-gamma flip level separating mean-reverting vs trending regimes.

An MT5 implementation reads an option chain from either broker-native option symbols or a CSV fallback, derives implied volatility when needed, builds the per-strike exposure map, solves for the flip via a sweep plus interpolation, and renders the profile directly on-chart.

👉 Read | NeuroBook | @mql5dev
20👍7👌2🏆2
Multi-asset trading logic increasingly depends on rolling covariance matrices, cointegration vectors, and continuously updated hedge ratios. Standard MQL5 indicators largely stop at scalar correlation over a fixed window and do not scale to N×N portfolio matrices or regime-driven recalculation on each tick.

Regression and optimisation are the other gaps. There is no built-in OLS/least-squares routine, so implementations fall back to manual loops, weak diagnostics, and poor numerical stability, especially under rank deficiency or non-linear constraints.

The ALGLIB port for MQL5, centered on ap.mqh and companion modules, adds linear algebra (EVD/SVD/LU/QR/Cholesky), least-squares fitting, and constrained/unconstrained optimisation. This keeps computation inside the terminal without WebRequest latency, and enables dynamic hedging, risk-parity, and Markowi...

👉 Read | AppStore | @mql5dev
23👍18👌2
An MT5 indicator is available that matches the TradingView MACD display, including its color rules and initialization behavior.

The histogram uses a four-color scheme: dark green when rising above zero, light green when falling above zero, light coral when rising toward zero, and red when falling below zero.

The signal line is seeded with an SMA to mirror Pine Script ta.ema() initialization, targeting bar-for-bar agreement with TradingView.

Inputs are configurable for fast EMA, slow EMA, signal length, and price source. The build requires no DLLs and no external dependencies. An MT4 version is also available: https://www.mql5.com/en/code/74169

👉 Read | CodeBase | @mql5dev
20👍11👀3👨‍💻2👌1
MQL5 EAs often fail after a broker move with no logic changes. Typical logs show 10030 (invalid filling type), invalid stops, or invalid volume, while Strategy Tester stays quiet because it uses the current broker’s specs.

Key broker constraints to audit per symbol: SYMBOL_FILLING_MODE (FOK/IOC/RETURN bitmask), SYMBOL_TRADE_STOPS_LEVEL (fixed or floating even when zero), SYMBOL_TRADE_FREEZE_LEVEL, SYMBOL_TRADE_MODE, SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_STEP, plus swap and the triple-swap weekday.

A small diagnostic EA can read SymbolInfoInteger/SymbolInfoDouble, grade each item as OK/warning/breaker, and print it to a panel, log, and CSV across Market Watch. This surfaces portability issues before OrderSend starts failing.

👉 Read | Signals | @mql5dev
19👍11👌2
The key new feature of MetaTrader 5 Build 6060 is built-in support for the Model Context Protocol (MCP) and agentic AI.

The terminal and MetaEditor now include an integrated AI Assistant that can help analyze markets and trading activity, develop MQL5 applications, explain code, identify errors, and automate complex tasks.

Another important addition is Passkey support — a modern technology for securing trading accounts. Passkeys provide an additional authentication factor during sign-in, protecting users against phishing attacks and unauthorized access.

For developers, we've significantly enhanced MetaEditor. The editor now includes the long-awaited code folding and 'highlight all occurrences' features, making it much easier to work with large projects.

Learn more...
👍1710👌2
Multi-symbol EAs often call SymbolInfoDouble(), SymbolInfoInteger(), and related functions on every tick for every tracked instrument. At 20 symbols, 10 ticks/sec, and 4 properties, that is 800 terminal lookups per second. These lookups cross into terminal internals and add measurable latency at scale.

A dedicated metadata cache removes repeated reads of static contract and session data. CSymbolMetaCache fetches per-symbol specification and weekly trading sessions once during Init(), serves typed getters from memory, and evaluates IsMarketOpen() via cached session windows without touching the terminal API.

Refresh becomes the only post-init API touch point, typically scheduled daily around server midnight. Static fields are safe to cache; dynamic fields like bid/ask/spread are not. Tick value is static only when profit currency matches account currency; othe...

👉 Read | Signals | @mql5dev
18👍51👌1
A revived MT5 trading robot is rebuilt as a hybrid system: Python handles data pipelines, feature building, model training, and signal generation, while MetaTrader 5 executes trades via the Python API. Multithreading assigns each symbol its own model context to avoid sequential bottlenecks when trading portfolios.

The design adds portfolio-level risk control with a global TOTAL_PORTFOLIO_RISK so position sizing depends on both instrument volatility and existing exposure across symbols.

Core infrastructure focuses on reliability: queued logging with a dedicated printer thread for readable multithreaded diagnostics, and market-data retrieval with retry windows to survive broker outages.

The ML pipeline expands limited history using noise, time shifts, scaling, and price inversion with robust NaN/inf cleaning. Labels range from simple forward moves to ...

👉 Read | Quotes | @mql5dev
20👍12🏆3👌1
Backtest profitability often collapses live due to execution costs, not logic errors. Spread, slippage, and commissions accumulate, especially in high-frequency systems with small average wins.

An MT5-native MQL5 analyzer can quantify this risk from closing-deal CSV data (date, result, volume). It applies a linear cost model per deal: Fixed + (CostPerLot * Volume), then recomputes net profit and profit factor across rising cost multipliers.

Key outputs: breakeven cost per deal, cushion (net profit divided by assumed total cost), retention, profit factor after costs, win erosion (winners that flip), thin-winner share, plus a composite A+ to F robustness grade with recommendations.

👉 Read | CodeBase | @mql5dev
19👍112👌1
Part 2 extends an Ehlers-style DSP stack from “detect regime” to “adapt parameters” and “consume modules deterministically” in an MT5 EA. All logic runs on closed bars, filters are replayed from history, and modules expose stable accessors like Ready(), Value(), InPhase(), Quadrature().

CyclePeriod uses an Ehlers Hilbert-transform homodyne discriminator to estimate dominant period in bars, with clamp limits (6–50, +/-50% step) and double smoothing to control noise. The same engine feeds MAMA/FAMA by computing phase from I/Q components and making EMA alpha adaptive via deltaPhase, bounded by FastLimit/SlowLimit.

A regime-switching EA classifies trend vs cycle (via Even Better Sinewave) and applies separate playbooks, validated in Strategy Tester with real ticks as an engineering demonstration, not a profit claim.

👉 Read | NeuroBook | @mql5dev
45👍3👌2👀2
Tool logic is built around a 25 EMA centerline plus volatility envelopes. Price near the EMA implies neutral conditions. Pushes into upper red/orange bands signal overextension; moves into lower blue/violet bands signal underpricing. Bands are spaced in fixed 0.1% steps, giving a consistent deviation map.

A 7-timeframe scanner (1M through Daily) produces a consensus bias. Higher timeframes define the primary direction, while lower timeframes identify pullbacks or short-lived counter moves. ADX acts as a filter: weak ADX supports range behavior; strong ADX signals trend strength and reduces the quality of reversal entries.

Classical usage falls into three cases. Trend continuation: strong bullish/bearish consensus, then enter on a pullback into outer bands aligned with the macro trend. Mean reversion: mixed consensus plus weak ADX, then fade extreme d...

👉 Read | CodeBase | @mql5dev
31👍13👌3🎉2👨‍💻1
A modular MQL5 multi-symbol trading panel streamlines portfolio management from a single chart, removing repeated chart switching and context-menu actions. It supports per-symbol Buy/Sell, close by symbol or globally, one-click closing of winners/losers, and bulk SL/TP updates, while showing live account stats and floating P/L.

The design separates responsibilities: CSymbolManager parses and validates a comma-separated symbol list, ensures symbols exist and are selected in Market Watch. CTradeManager wraps execution via CTrade/CPositionInfo, filters by magic number, iterates positions safely in reverse, and exposes aggregated profit/position metrics. CPanel builds UI objects with a consistent prefix, updates values without recreating controls, and routes chart events to trading actions through small parsing helpers, keeping the EA focused on lifecycle and...

👉 Read | NeuroBook | @mql5dev
23👍12👌1