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
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❀16
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
❀35πŸ‘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πŸ‘6
MQL5 order submission starts with MqlTradeRequest, a 21-field struct with tight semantic coupling. The compiler checks types, not intent, so invalid combinations often pass build and fail at runtime, sometimes after broker-side normalization.

A fluent COrderBuilder shifts correctness from caller discipline to validated configuration. It keeps shadow fields plus validity flags and a single error string. Send() acts as a dispatch gate: mandatory flags, cross-field stop logic, OrderCheck(), then OrderSend(), returning one boolean and a diagnostic message.

Pointer-return chaining is the practical mechanism in MQL5 because method references are unsupported. Buy/Sell and pending variants set action and type as a pair, removing a common class of mismatches.

Stop-loss and take-profit checks are directional, deferred, and enforce SYMBOL_TRADE_STOPS_LEVEL befor...

πŸ‘‰ Read | Forum | @mql5dev
❀23πŸ‘5
MQL5 custom signals shift from multi-asset arbitrage to single-asset breakout handling under macro volatility. The earlier B-Tree plus Bayesian model fits cross-sectional lookup and uncertainty scoring, but is less suitable for localized, sequential shock detection.

The proposed stack pairs Disjoint Set Union (DSU) with a Deep Belief Network (DBN). DSU partitions adjacent bars into connected volatility components using MakeSet/Find/Union, driven by ATR expansion and Bollinger bandwidth change to avoid smoothing lag.

DBN (stacked RBMs) validates each DSU cluster via an energy score and a tanh-bounded output in [-1, 1]. Trades pass only when the DBN output exceeds a tuned threshold, targeting regime shifts while filtering stop-hunt noise.

πŸ‘‰ Read | Quotes | @mql5dev
❀13πŸ‘13
MetaTrader 5 generates rich tester logs and optimization data, but its built-in reports can’t answer portfolio-grade questions like cross-symbol robustness, drawdown recovery behavior, or session-based edge. The workaround is straightforward: log normalized trade and optimization fields to CSV from MQL5, then analyze in Python with pandas plus matplotlib/seaborn.

The article defines a reusable pipeline and five charts that fill key gaps: a multi-asset parameter match matrix for consistency checks, a lag-vs-whipsaw scatter to quantify filter efficiency, a walk-forward paired-slope view to expose overfitting, KDE distributions for drawdown depth and duration, and an hour-by-day heatmap to reveal intraday/intraweek alpha clusters.

A deployment wrapper runs the full suite against new exports, reading directly from the terminal’s MQL5\Files directory to a...

πŸ‘‰ Read | AppStore | @mql5dev
❀16πŸ‘9
Three FX setups were captured across multiple timeframes, highlighting current technical structure and key decision zones.

EURCAD on H1 shows a clearly defined range with repeated reactions at prior swing levels. Price action remains sensitive to nearby support and resistance, with short-term momentum shifting quickly after each rejection.

AUDUSD on D1 reflects a broader directional phase, with candles compressing around recent highs and lows. The next sustained move likely depends on a clean break and acceptance beyond the latest daily structure.

EURJPY on M15 presents faster rotation and tighter swings, typical of intraday conditions. Multiple retests suggest liquidity is being worked around local extremes, increasing the importance of confirmation before entry.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀33πŸ‘4⚑2
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
❀52πŸ‘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
❀40πŸ‘Œ6πŸ‘5