MQL5 Algo Trading
541K subscribers
3.88K photos
6 videos
3.88K 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
The article breaks Forex arbitrage into a graph problem: currencies are vertices, tradable pairs are directed edges weighted by executable bid/ask prices. Profitable β€œcycles” are those where the rate product stays above 1 after subtracting relative spreads, enabling near-zero market risk when executed correctly.

It outlines an MT5 Expert Advisor built as modular components: real-time graph construction, cycle discovery using a modified Floyd–Warshall (maximize products, track spread growth, reconstruct paths) plus a DFS pass to enumerate alternative cycles while avoiding reuse of the same symbol.

A key engineering focus is zero-exposure sizing: lots are derived by propagating a base notional through the cycle, then normalized to broker constraints (contract size, min lot, step), with proportional downscaling to cap risk. Execution and fault handling are tr...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀23πŸ‘5πŸ‘Œ3
MetaTrader 5 ships with a single-timeframe volume histogram, but multi-timeframe volume context and anchoring require custom tooling. An MQL5 implementation can render synchronized profiles across the main chart and a subwindow using objects, not indicator plots.

The design uses a draggable vertical anchor to define the start of analysis, with the viewport’s right edge as the end. Anchor time is normalized to valid bar times, restored if deleted, and auto-centered when needed. HTF selection is validated to ensure it is above the chart timeframe.

Bin sizing is interactive and stateful. Edit mode activates only when the anchor is selected: double-click E to enter numeric input, double-click S to commit. Invalid or empty input falls back to the last valid value. OnChartEvent drives recalculation on zoom, scroll, drag, and keystrokes, while rendering POC and...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀27πŸ‘Œ4πŸ‘3
AFML’s sequential bootstrap is often presented as the fix for bagging with overlapping triple-barrier labels, by supposedly decorrelating trees. This study isolates what actually reduces between-tree correlation: fewer sampled rows, not the sequential sampling rule itself.

A four-regime experiment holds the same DecisionTree base learner constant and varies only the row sampler: full vs uniqueness-throttled sample count, and standard vs sequential draw rule. The key metric is correlation of out-of-bag probability predictions, making the AFML variance term observable.

Results are consistent across tick, tick-imbalance, and a higher-density M5 replication: cutting max_samples to average uniqueness produces most of the decorrelation; switching to sequential sampling at the same count adds little and can even worsen correlation at full count. Out-of-bag...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘3πŸ‘Œ2⚑1
This article digs into why random-access file code fails when the file’s internal layout is misunderstood. The key takeaway: file position doesn’t advance by β€œone byte” in a meaningful way unless reads and writes are defined by an explicit structure.

Using MQL5-style examples, it contrasts text parsing (tab-delimited strings) with binary layouts, showing how a small format change turns clean reads into garbage output. The fix is to design a self-describing record: write a length field, then the payload, and use FileSeek to backfill the length after writing.

For trading systems, this enables fast, reliable logging and replay of variable-length messages, with deterministic offsets and safer recovery during analysis or debugging.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀14πŸ‘5πŸ†1
Part 8 adds the missing bar-by-bar trend readout on NQ M1: a continuous micro-trend strength score in [-1, +1] that measures how cleanly fast/medium/slow EMAs align and accelerate, instead of relying on lagging, binary crossovers.

GetMicroTrendStrength() combines four EMA-derived components: 5/8/13 EMA ordering, ATR-normalized price position with tanh bounding, 5-bar slope agreement, and a bounded volume multiplier. A contradiction penalty sharply reduces the score when EMA alignment disagrees with price vs the fast EMA, suppressing common false positives during reversals.

The signal plugs into the Part 7 regime layer via confidence-scaled thresholds: high-confidence Trending/Informed sessions loosen cutoffs, low-confidence Stressed/Noisy sessions tighten them. On 514 NY sessions (May 2024–May 2026), Trending shows the most persistent directional ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀20πŸ‘5
Trading systems degrade when regimes shift, and fixed-window indicators react after the distribution has already changed. A sequential CUSUM detector updates bar by bar, accumulates evidence, and flags a breakpoint the moment a threshold is crossed.

The detector runs on standardized log-returns z_t built from a strictly historical rolling window. Two accumulators track upward and downward drift with a slack term k, then reset to zero after a hit. Threshold h sets the false-alarm versus detection-speed trade-off, often expressed via ARL0, with theory only approximate on real returns.

Implementation notes for MetaTrader 5 focus on execution constraints: handling full vs incremental recalculation in OnCalculate(), persisting S+ and Sβˆ’ via indicator buffers, and creating chart objects idempotently to avoid duplicates on live ticks.

πŸ‘‰ Read | AppStore | @mql5dev
❀25πŸ‘10😁1πŸ‘€1
Alpha-Beta Trend Filter is a predictive smoothing indicator based on steady-state estimation. Unlike SMA/EMA-style averaging, it maintains an internal price estimate and a trend velocity term, updating both each bar via a prediction step and a residual-based correction using alpha (price sensitivity) and beta (velocity sensitivity).

This MQL5 build extends the classic single-line output with a multi-symbol, multi-timeframe matrix dashboard. The chart plot uses DRAW_COLOR_LINE to switch state from bullish to bearish based on the velocity sign, while the dashboard renders Bull/Bear/Wait across selectable timeframes for a parsed symbol list.

Implementation details include ArraySetAsSeries() alignment, a helper that computes state from a minimal CopyClose() window without iCustom, and full UI cleanup on deinit. Typical tuning ranges: alpha 0.1–0.9, beta ...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘6✍2πŸ‘¨β€πŸ’»2πŸ‘Œ1πŸ‘€1
Adaptive trading framework for FX, crypto, and high-digit instruments using a velocity-driven baseline and ER-based bands.

Trend filter uses baseline color: LimeGreen signals positive acceleration, Crimson signals negative acceleration. Volatility state is defined by band width: compressed bands indicate low ER and pending expansion; expanded bands indicate high ER and potential trend efficiency or extension.

Momentum breakout: wait for a squeeze and flat baseline. Go long on a candle close above the upper band with baseline turning LimeGreen. Go short on a close below the lower band with baseline turning Crimson. Stop sits beyond the baseline or opposite band. Hold while baseline color persists; exit on a color flip.

Mean reversion: require a flat baseline with wide bands. Enter only after a probe outside a band fails to flip the baseline, then p...

πŸ‘‰ Read | VPS | @mql5dev
❀21πŸ‘5⚑2πŸ”₯1πŸ‘Œ1
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
❀31πŸ‘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πŸ‘5✍2πŸ‘Œ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πŸ‘10✍3πŸ‘Œ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
πŸ‘15❀14πŸ‘Œ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πŸŽ‰2✍1
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
❀22πŸ‘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