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
Microstructural features treat each OHLCV bar as an aggregation of trades and attempt to recover spread, price impact, and order-flow imbalance at bar close.

A two-layer design is used. compute_all_microfeatures() runs on OHLCV only and produces Roll spread, Corwin-Schultz spread and sigma, plus Kyle, Amihud, and Hasbrouck lambdas with rolling t-stats where applicable. Kernels are Numba-accelerated and avoid Pandas in inner loops.

When tick data exists, bar_microstructure_features() and vpin() add per-bar imbalance stats and VPIN from volume-synchronized buckets. Tick preprocessing and bar boundary indexing via searchsorted enable parallel bar kernels while keeping VPIN bucket filling sequential.

Outputs converge to a bar-indexed feature frame suitable for downstream ML pipelines.

๐Ÿ‘‰ Read | Signals | @mql5dev
โค21๐Ÿ‘8
Part 35 upgrades the custom MT5 canvas layer from simple two-point line tools to a full analytical toolkit with 15 new objects: channels (parallel, equidistant, regression), pitchforks (Andrews, Schiff, modified Schiff), Gann tools (line, fan, box), multiple Fibonacci variants, plus delete-all.

The core change is support for multi-anchor geometry, derived handles, and per-tool โ€œlevel arraysโ€ (ratios, styles, visibility) stored with each object. Three-click placement and dual-state rubber-band previews standardize interaction across complex tools.

Key implementation details include OLS regression channels that recompute endpoints on redraw, sigma bands with proper alpha compositing, scanline quadrilateral fills, dashed/AA line reuse, and hit-testing that recalculates live geometry so tools stay aligned with evolving price data.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค23๐Ÿ‘10
Part 2 extends an MQL5 chart object detector beyond basic time/price pairs to support complex analytical objects used in rule-based strategies.

Focus areas include extracting Fibonacci level arrays via OBJPROP_LEVELS and OBJPROP_LEVELVALUE, collecting three-point geometry for OBJ_CHANNEL and OBJ_PITCHFORK, and normalizing the results into an extended data structure suitable for deterministic checks such as 0.618 retracement alignment or median-line contact conditions.

Implementation targets OBJ_FIBO, OBJ_FIBOTIMES, OBJ_FIBOFAN, OBJ_FIBOARC, OBJ_CHANNEL, and OBJ_PITCHFORK, with the same approach applicable to cycles and Gann tools. Delivery consists of ComplexObjectDataCollector.mqh (derived from the Part 1 detector) and a timer-based TestComplexObjectsEA.mq5 that logs extracted levels and geometry for validation.

๐Ÿ‘‰ Read | Signals | @mql5dev
โค16๐Ÿ‘10๐Ÿ‘Œ3
Recurrence matrices in RQA are reinterpreted as adjacency matrices: each time index becomes a node, each recurrence becomes an undirected edge, and the diagonal is cleared to remove self-loops. This turns pattern counting into graph topology analysis, exposing structure like clustering, shortest paths, centrality, and degree correlation.

The MQL5 library adds CRNAMetrics to compute 12 network measures (degree stats, clustering/transitivity, path length/diameter, betweenness/closeness, assortativity, density). Rolling analyzers (CRNAWindow, CJRNAWindow) apply the metrics per window for single-series and joint recurrence, with facades (CRNA, CJRNA) for one-call use.

Two indicators plot five live metrics (ACC, transitivity, normalized APL, assortativity, avg betweenness). The approach is practical but CPU-bound; betweenness and triangle counting scal...

๐Ÿ‘‰ Read | Docs | @mql5dev
โค20๐Ÿ‘9
Regression replaces buy/sell labels with a continuous target: expected price change. This removes a key weakness of binary models in tradingโ€”directional accuracy ignores move size, so it cannot rank opportunities or avoid low-payoff trades.

The article shows two target designs: point-to-point future delta and an averaged future-price delta over a horizon. Averaging captures intermediate excursions and reduced overfitting in tests.

A meta โ€œcausal inferenceโ€ layer trains multiple regressors on random subsets and filters trades when the main forecast is likely to be unreliable, using a tolerance on prediction error.

Models are exported to MetaTrader 5 via ONNX (Random Forest used due to CatBoost ONNX limits). In-terminal thresholds for buy/sell magnitude and meta deviation turn raw regression outputs into tradable signals, improving forward stability.

๐Ÿ‘‰ Read | Docs | @mql5dev
โค26๐Ÿ‘9
MetaTrader 5 Strategy Tester optimization output remains transient and fragmented, which complicates comparative studies across SMA, EMA, KAMA and other filter families. Native reports do not persist custom metrics and the XML report is not practical for downstream tooling.

A reusable include, CSVExportEngine.mqh, exports standard TesterStatistics() fields plus derived metrics such as Sortino Ratio from deal history, average trade duration via DEAL_POSITION_ID matching, and signal-quality measures tracked per bar (lag on turns, whipsaws, price-to-line distance, intersection frequency).

Multi-core optimization introduces file-lock contention: parallel agents can lose rows when FileOpen() returns INVALID_HANDLE, and Sleep() does nothing in the Tester. The fix is an iteration-based spin-lock retry around FileOpen(), with phase-aware filenames (Baselin...

๐Ÿ‘‰ Read | Quotes | @mql5dev
โค22๐Ÿ‘9
Most MT5 EA reviews rely on account history or post-trade CSV exports. Both omit intratrade behavior because history stores only endpoints, not what happened while a position was open.

Tick-level maximum adverse excursion (MAE) and maximum favorable excursion (MFE) capture worst drawdown and best run-up in account currency. Trades with identical final PnL can have materially different MAE/MFE, changing conclusions about entry timing, stop placement, and whether mean reversion is doing the work.

A reusable MQL5 class, CTradeJournal, tracks all open positions on every tick, stores initial risk at entry for R-multiple normalization, and writes a structured CSV on close. Integration stays minimal: Init on OnInit, NotifyOpen on fill, Update on every tick, NotifyClose from OnTradeTransaction.

๐Ÿ‘‰ Read | Freelance | @mql5dev
โค14๐Ÿ‘7โšก2
MetaTrader 5 custom symbols can turn raw market data into synthetic instruments, and 3DBarCustomSymbol.mq5 is a concrete example. It builds โ€œ3D barsโ€ that encode price action alongside volume behavior, time-cycle features, and volatility measures, making anomalies and regime shifts easier to spot than on standard candles.

The indicator is structured like a solid MQL5 project: init validates inputs and loads history; symbol-creation configures precision, sessions, and metadata; processing computes normalized metrics (returns/acceleration, volume changes, volatility); an update loop refreshes the current bar on a timer for near real-time use.

Practical benefits: traders can monitor volatility bursts, volume spikes, and acceleration changes on a dedicated custom chart, while developers can feed the synthetic symbol into indicators or EAs. Performance is...

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค23๐Ÿ‘7๐Ÿ‘Œ3
Version 2.3 continues the 2.x line with bug fixes, code refinement, and added Price-to-MA Distance reporting.

Trade value is tied to price positioning relative to a moving average. That positioning can be characterized by MA speed and the price-to-MA distance, giving two measurable signals for pressure and trend conditions.

The indicator outputs MA speed as a histogram normalized against its historical average, and price-to-MA distance as a percentage line. Both metrics are packaged in one view for operational convenience rather than strict signal compatibility.

In practical use, the combined display helps separate directional pressure from mean-reversion behavior around a trending moving average.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค20๐Ÿ‘9
MetaTrader 5 backtests and optimizations generate rich statistics, but exporting them into Python, Excel, or a database often turns into repetitive manual work. MQL5 file I/O can convert the tester into a repeatable research pipeline, with CSV as a practical interchange format.

File access is sandboxed. Without FILE_COMMON, paths resolve under the terminal data folder. With FILE_COMMON, output is redirected to a shared directory usable by multiple terminal instances and external tools. Local sandbox fits internal logs; common sandbox fits cross-process workflows.

FileOpen flags define behavior. FILE_WRITE truncates; append needs FILE_WRITE|FILE_READ plus FileSeek to end. FILE_CSV reads and writes field-by-field. FILE_ANSI maximizes compatibility for ASCII data; FILE_UNICODE is needed for non-English symbols.

A dedicated CCSVExporter class keeps file...

๐Ÿ‘‰ Read | AppStore | @mql5dev
๐Ÿ‘12โค11๐Ÿ‘€7
Stop losses automate exits at a trigger price, reducing downside risk and removing emotional decision-making. In leveraged forex/CFDs, they also support profit protection by adjusting the stop without reducing position size.

Exchange-side stops expose the stop level, enabling stop runs around clustered liquidity, broker-imposed minimum stop distances, and spread widening that can force premature exits.

A local stop-loss system keeps the stop price only in the MetaTrader 5 terminal. The EA monitors bid/ask correctly (bid for closing buys, ask for closing sells) and closes via CTrade when conditions are met.

The implementation uses OOP with per-position stop objects, CPositionInfo for position access, and CHashMap keyed by ticket for O(1) tracking and scalable multi-position management in OnInit/OnTick/OnDeinit.

๐Ÿ‘‰ Read | VPS | @mql5dev
โค23๐Ÿ‘5๐Ÿ‘€3
This article replaces gap-focused trailing logic (Skip-List + Hopfield) with a two-stage trailing stop built for smoother, continuous trends: Reservoir Sampling as a memory-fixed price โ€œengineโ€, plus an OLS Linear Regression โ€œfilterโ€ that decides when trailing should pause.

Reservoir Sampling maintains a statistically fair buffer of k prices from an unbounded stream using replacement probability k/i, avoiding full-history moving-average storage. For Strategy Tester repeatability, randomness is isolated with an internal deterministic LCG instead of MathRand().

The class offers four reservoir evaluation modes (mean, min/max midpoint, volatility-adjusted via standard deviation, and a recent-biased blend). Linear Regression predicts the next bar; if the forecast moves against the position, stop updates freeze to avoid micro-pullback stopouts. Broker stop/f...

๐Ÿ‘‰ Read | Docs | @mql5dev
โค26๐Ÿ‘6๐Ÿ†3๐Ÿ‘€3โšก2
Part III adds a regression gate on top of the Part II artifacts without changing their contracts. The profiler CSV and deterministic TestLite report stay stable, while the gate compares current evidence to an accepted baseline and emits PASS, WARN, SKIP, or FAIL.

The workflow stays file-based and sequential: run UnitTestRunner.mq5, run ProfilerExampleEA.mq5 in Strategy Tester, promote a clean profile to ProfilerExampleEA_Baseline.csv, then run DiagnosticGateRunner.mq5 after changes. Outputs include delta and failure CSVs plus a final machine-readable status.

RegressionGate.mqh matches profiler rows by section name, computes call-count and timing deltas, and classifies movement using combined absolute and percentage thresholds to avoid microsecond noise. New or missing sections warn by default.

TradeAssertions.mqh reuses TestLite to add symbol-awar...

๐Ÿ‘‰ Read | Freelance | @mql5dev
๐Ÿ‘17โค15
HiSSD (Hierarchical and Separate Skill Discovery) is being adapted from offline multi-agent training to trading, targeting fast regime shifts without full retraining. The design splits behavior into common skills and task-specific skills, supporting stability under changing market conditions and coordination across many agents.

Implementation in MQL5 continues with a dedicated Controller object (CNeuronHiSSDLowLevelControler) built on convolutional layers to run independent agents in parallel. Inputs combine local observations, Planner-provided common skills, and encoder-generated specific skills, with row-wise concatenation, transposition for univariate streams, and batch normalization.

Training defines four models: a Planner-style environmental state encoder for multi-step forecasting and common skill output, the Controller for agent actions, a ...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค29๐Ÿ‘8๐Ÿ’”4
An Expert Advisor has been released to test the โ€œTurnaround Tuesdayโ€ hypothesis using daily candle data. The rule set is simple: if Monday closes below its open, a Buy is opened at the start of Tuesday; if Monday closes above its open, a Sell is opened. Trades are always taken against Mondayโ€™s direction, with one position per symbol.

Optional controls include an ATR-based volatility filter and SL/TP derived from daily ATR. Lot sizing supports fixed volume or risk from start balance, with the limitation that risk sizing cannot be computed when Stop Loss is disabled. Positions are force-closed at a configurable CloseHour if exits are not hit.

Backtests on EURUSD, XAUUSD, and SP500 (2016โ€“2026) showed no stable edge in the baseline variant, while ATR filtering and management rules improved XAUUSD to +38% and SP500 to +40%, with 11% max drawdown on SP500. Full r...

๐Ÿ‘‰ Read | VPS | @mql5dev
โค28๐Ÿ‘9
MSNR v5.31Plus AEU EA targets XAUUSD execution on M5, while scanning W1, D1, H4 and H1 to map support and resistance zones. Entries are gated by multi-layer price action confirmation rather than a single trigger.

Core logic includes Malaysian SNR body-level detection, liquidity sweep with MISS and engulfing validation, plus trendline confluence, QML, breakout-retest, CRT, and a confluence cluster filter. Trading can be restricted by Asia, Europe, and US sessions.

Risk controls cover percentage-based sizing, partial close and break-even handling, and protection against losing streaks and drawdown expansion. Output includes an on-chart dashboard with key levels and CSV exports for backtest deals, signal logs, and closed trades.

Targets prioritize DOL references such as prior day/week highs and lows and nearby swing liquidity, with risk-reward projection as fal...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค34๐Ÿ‘5๐Ÿ‘Œ3
Standard volatility bands such as Bollinger Bands and Keltner Channels often rely on symmetric, time-independent assumptions. Standard deviations around an arithmetic mean do not test whether price has a statistical tendency to revert, which can cause mean-reversion systems to keep trading into sustained drift and accumulate drawdowns.

A more robust filter is the Ornstein-Uhlenbeck process: dX_t = ฮธ(ฮผ โˆ’ X_t)dt + ฯƒ dW_t. Estimating ฮผ, ฮธ, and ฯƒ turns โ€œbandsโ€ into an equilibrium model: ฮผ as the baseline, ฮธ as the reversion or drift regime flag, and ฯƒ as diffusion limits derived from residual variance rather than rolling deviation.

Operationally, ฮธ > 0 supports mean reversion, while ฮธ < 0 indicates trend drift and should disable reversion logic. For liquid instruments on M30/H1, trades are taken only when price exceeds diffusion boundaries, targeting con...

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค25๐Ÿ‘5โœ2
Partial position closing in MQL5 is a position management method that closes a defined percentage of volume at intermediate Take Profit levels. It can lock profit earlier than breakeven or trailing stop logic, while keeping exposure for further movement.

Key constraints include extra commissions per partial close and missed execution if price never reaches the defined levels. Suitability depends on strategy horizon, with wider swing targets generally fitting better than tight scalping targets.

Implementation focuses on predefined TP percentages between entry and final TP, paired with volume percentages. A CPartials class can track positions by magic number, calculate TP1/TP2/TP3 prices, and call CTrade::PositionClosePartial.

Recent architecture changes include shared logging (CLoggerBase), a Utils library, risk management split into modules, Accou...

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค24๐Ÿ‘8๐Ÿ†2
Extremal Optimization (EO) targets hard trading-style objective landscapes where gradients fail: discontinuities, multiple local optima, and non-differentiable regions. Inspired by the Bakโ€“Sneppen model, it updates the worst parts of a solution rather than refining the best, using punctuated changes to escape stagnation.

The MT5-oriented implementation builds a population, ranks agents and their parameter โ€œcomponents,โ€ then selects an agent and a component via a power-law (tau). The chosen component is replaced with a bounded random value, keeping step discretization, while Revision tracks the best global candidate.

Bench tests showed weak convergence (~25% overall score), leading to a revised variant: explicitly mutate selected components, tune selection/mutation distributions, and manage epochs to stabilize search and improve practical performance for pa...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค21๐Ÿ‘9๐Ÿ”ฅ4
Growing EAs often devolve into hidden coupling via global state. Replacing globals with a publish/subscribe event bus makes dependencies explicit: modules publish typed events and subscribe to what they need, turning an N-to-N mesh into a star centered on the bus.

The design uses an enum for event routing (compile-time safety, O(1) lookup), a fixed-size payload passed by const reference to avoid copies, and an abstract listener interface for polymorphic dispatch. An MQL5 pointer-array limitation is handled with a slot wrapper struct per event type.

Dispatch is synchronous and validated with CheckPointer(), so handler cost impacts tick time and listener lifetimes must be managed carefully. In practice, signal, execution, and risk components stay independent while still coordinating reliably.

๐Ÿ‘‰ Read | Docs | @mql5dev
โค16๐Ÿ‘9
Part 2 extends MT5 EA restart recovery beyond SQLite persistence by handling virtual stop-loss and take-profit. When protection exists only in runtime memory, a terminal shutdown can leave positions unprotected and still open after price already crossed the intended exit.

The recovery flow adds broker-side position discovery using symbol and magic number, then restores virtual levels from SQLite and validates them against current price before resuming management. If a position exists without saved state, the EA switches to safe mode.

Testing uses controlled trades opened without broker SL/TP, builds initial virtual protection immediately, stores state, and recovers it on startup. A controlled close path updates SQLite from ACTIVE to CLOSED after the position is exited.

๐Ÿ‘‰ Read | AlgoBook | @mql5dev
โค17๐Ÿ‘5