MQL5 Algo Trading
550K subscribers
3.95K photos
6 videos
3.96K 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
MQL5 ships without unit testing tools, so many EAs rely on manual log inspection. That approach misses β€œcorrect-looking” math bugs that only appear with specific inputs, quietly skewing risk and sizing over time.

The article builds a native, zero-dependency test framework as a script: assertion macros capture file/line via __FILE__/__LINE__, suites are isolated behind an ITestSuite interface, and a central runner aggregates STestResult records and prints a clean pass/fail report to the Experts tab.

It targets common utility failures: floating-point comparisons (ASSERT_NEAR with tolerance), lot-step normalization direction, symbol/digit edge cases, and silent overflow/underflow via sentinel flags (ASSERT_THROWS). The design keeps production math utilities separate from tests, making regression checks practical for traders and MT5 developers.

πŸ‘‰ Read | Calendar | @mql5dev
❀18πŸ‘8πŸ‘Œ2πŸ”₯1
Manual Oops gap reversal marking breaks down when gap size, time validity, and first-fill-only rules must be tracked across long histories. The article implements a custom MQL5 indicator that enforces those rules consistently on completed bars, plotting bullish and bearish arrows via two output buffers.

Detection starts with a β€œgap bar” opening outside the prior bar’s range by a configurable minimum (points scaled by _Point). Confirmation requires a bar close back through the prior boundary; intrabar touches are ignored. Signals can confirm on the gap bar or within a max validity window, but only the first qualifying fill is accepted to prevent duplicates.

The indicator architecture separates an initial historical scan that maps all past signals from an incremental update that recalculates only the latest closed bar, avoiding full-history recomputati...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀17πŸ‘5πŸ”₯4⚑2πŸ‘Œ2🀑2
News spikes can make an MT5 EA fire dozens of OrderSend calls per second, hitting undocumented broker rate limits and causing silent delays or retcode failures. A fixed cooldown avoids this but also suppresses legitimate signals.

CTradeThrottle addresses the problem with a token-bucket limiter: allow short bursts up to a configured capacity, then cap sustained flow by a refill rate. When tokens run out, requests are queued instead of discarded, then released via OnTimer() as tokens return, using priority ordering with FIFO tie-breaks.

The design exposes a clear interface (Submit/Cancel/GetStatus) and separates pacing from execution concerns. It also handles broker-specific filling modes by selecting a supported FOK/IOC/RETURN mode per symbol, while leaving validation, price refresh, and fill tracking to a dedicated execution layer via OnTradeTransaction().

πŸ‘‰ Read | NeuroBook | @mql5dev
❀17πŸ‘7πŸ”₯3🀩3🀑3πŸ‘Œ2
The indicator search panel is extended from β€œfind and attach” to β€œconfigure then attach,” removing the detour into MetaTrader’s properties window. After selecting an indicator, a parameter dialog appears first, then the indicator is created with those inputs.

The core design is metadata-driven: each input is described by a parameter definition (name, type, defaults, ranges, enum text/codes). A centralized repository maps ENUM_INDICATOR values to arrays of these definitions, covering 30+ built-ins and cleanly handling indicators with zero inputs.

A single dynamic dialog builds controls at runtime from metadata, reads user edits, validates ranges, and converts values into an MqlParam array. The chart launcher is updated with an AttachIndicator overload that accepts MqlParam, preserving existing default behavior and improving workflow for traders and MT...

πŸ‘‰ Read | Calendar | @mql5dev
❀59πŸ‘16✍5πŸ‘¨β€πŸ’»5πŸ‘€4πŸ”₯2πŸ€”1
A breakout indicator for XAUUSD based on the Asian session range (00:00–06:00) and subsequent London volatility has been released for free use.

The tool marks the overnight consolidation with blue rectangles and plots the range boundaries with light blue lines. Entry levels are calculated as dotted lines: green for buy (upper bound + buffer) and red for sell (lower bound βˆ’ buffer). Breakout signals are printed as up/down arrows, with an on-chart label showing range width in points/pips.

Key parameters include range start/end time (server-adjustable), a trading window for valid breakouts (default until 10:00), breakout buffer size, and optional sound/push alerts.

A typical ruleset is M15 on XAUUSD: trade only after the range completes, filter days where the range is roughly 300–2,000 points, take the first breakout only, place stop at the opposite boun...

πŸ‘‰ Read | Signals | @mql5dev
❀37πŸ‘15πŸ‘¨β€πŸ’»4πŸ‘Œ2🀝2🀩1
An MT5 Expert Advisor focused on managed recovery entries using RSI filtering and ATR-based spacing. Entry logic includes market structure validation via LL/LH and support conditions, with optional news blocking through the MQL5 calendar, a CSV schedule, or both.

Risk controls cover fixed-lot and balance-based compounding sizing, adaptive recovery distance, and basket-level profit management with a target plus trailing. Basket handling also supports smart trimming to reduce exposure during recovery cycles.

Operational safeguards include spread and slippage limits, equity loss thresholds, crash-move detection with pause behavior, and dashboard monitoring for current recovery state and system status. Inputs are fully configurable, including magic number, ATR/RSI modes, recovery parameters, profit targets, trailing rules, news settings, and panel placement.

R...

πŸ‘‰ Read | Freelance | @mql5dev
❀22πŸ‘11πŸ”₯4πŸ‘Œ2
Volume Profile Levels reframes chart context by aggregating traded activity by price, not by time. A recent lookback window is split into equal price rows, volume is tallied per row, and the result is rendered as a horizontal histogram anchored at the latest bar.

Key references are derived from the same profile: Point of Control (highest-volume row) and Value Area High/Low, built outward from the POC to contain a configurable share of total volume rather than using a fixed range percentage. Each row is also classified by whether volume came mainly from up-closing or down-closing bars to show directional dominance at that price.

Inputs cover lookback length, row count, tick vs real volume, value area percent, update frequency (per bar or per tick), visibility toggles, sidebar width scaling, and line/colors. The implementation assigns each bar’s full...

πŸ‘‰ Read | VPS | @mql5dev
❀25πŸ‘11πŸ‘Œ2⚑1🀩1
Anomaly-detection logic from the deterministic Dendritic Cell Algorithm is repurposed for continuous optimization by treating dendritic cells as search agents and antigens as candidate solutions. Solution quality is converted into β€œdanger” and β€œsafe” signals via population-normalized fitness, then combined into a context value that steers behavior.

A deterministic, uniformly distributed lifespan gives agents different observation windows, smoothing decisions over time and improving stability. Context is accumulated and averaged to reduce noise, then selects among three moves: local mutation for exploitation, movement toward the current best with exploration noise, or full random reinitialization when the region looks consistently poor.

The implementation outlines an MQL5-style class design with explicit signal computation, boundary control, and modu...

πŸ‘‰ Read | VPS | @mql5dev
❀16πŸ‘3πŸ”₯2πŸ‘Œ2🀩1
In MetaTrader 5 build 6180, we have significantly expanded the capabilities of the AI Assistant for working with the trading platform and Strategy Tester. The assistant can now retrieve and analyze tester reports and logs, check its current settings, help launch optimizations, add indicators to charts with specified parameters, and work with terminal and Expert Advisor logs.

For developers, we have expanded the capabilities for working with complex matrices and vectors in MQL5. Support for additional methods simplifies the processing, conversion, and validation of complex data in mathematical and analytical tasks.

The web terminal now provides improved handling of stop levels on netting accounts. When placing a new trade for an instrument that already has an open position, the terminal preserves the position's current Stop Loss and Take Profit levels, preventing them from being accidentally removed. We have also fixed data loading and quote display issues in Market Watch.

Read more...
πŸ‘12❀6πŸŽ‰2🀩2πŸ‘Œ2πŸ”₯1
MetaTrader 5 can open and modify trades, but it lacks a reusable pattern for what happens after entry. This article builds a Position Lifecycle Manager that decouples trade generation from trade management, so different EAs can share the same post-entry logic.

The framework discovers open positions, wraps each one in a CManagedPosition object, and drives it through explicit states: NEW, PROTECTED, BREAKEVEN, and CLOSED. State tracking preserves action history, avoiding repeated terminal queries and preventing duplicate stop or break-even operations.

A CPositionManager coordinates all managed objects, while a CRiskEngine calculates ATR-based protective stops without placing orders itself. Integration is shown with the standard MACD EA: entries stay intact; lifecycle handling becomes a reusable layer.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀10πŸ‘9πŸ”₯2πŸ‘Œ2
This article builds a compact MT5 position planning tool that turns Entry, Stop-Loss, and Take-Profit into interactive chart lines, so risk and sizing math updates instantly while levels are dragged.

It supports market, limit, and stop scenarios for both BUY and SELL. Market Entry auto-tracks Bid/Ask on every tick, while pending Entry stays user-controlled. Initial SL/TP spacing is derived from ATR to reflect current volatility, with a safe fallback when ATR isn’t available.

The EA validates the price structure (BUY: SL below Entry, TP above; SELL reversed) before computing stop distance, monetary risk from balance and risk %, normalized lot size using tick size/value plus min/max/step rules, reward, and risk-to-rewardβ€”without placing or modifying orders.

πŸ‘‰ Read | Docs | @mql5dev
❀29πŸ‘16✍3🀩3πŸ‘¨β€πŸ’»3πŸ‘Œ2πŸ‘€1
Rare β€œoutlier” bars break the core trading assumption that today resembles yesterday, yet they have no labels. This article implements Isolation Forest for MT5 as a compact MQL5 library that isolates points via random partitions, avoiding density modeling and handling multivariate features efficiently.

Key engineering choices make it testable and fast: a replayable 64‑bit RNG (splitmix64 + xorshift64*) for deterministic forests, iterative array-based trees with in-place partitioning, and the correct truncated-depth path-length correction and normalization. A 100‑tree fit on ~2.4k bars builds in ~2.4 ms; scoring one new bar is ~12 Β΅s.

Feature design is treated as the real lever: no raw prices, no lookahead, and careful column selection because isolation trees sample features uniformlyβ€”uninformative columns directly degrade detection. Validation includes b...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘10❀6🀩2πŸ”₯1πŸ‘Œ1
Dendritic Cell Algorithm (DCA) is a metaheuristic derived from innate immunity, originally published in 2005 for anomaly detection. The model integrates multiple signals over time and uses migration thresholds to avoid reacting to noise in single evaluations.

Optimization mapping treats high fitness as PAMP/Danger and low fitness as Safe, with Inflammation derived from population spread. Cells transform inputs into CSM, Semi, Mature via weighted sums and a shared (1+Inflammation) multiplier; migration triggers context selection (mature vs semi).

Per-solution MCAV aggregates contexts with exponential decay. MCAV drives control flow: above 0.5 triggers local mutation, otherwise either move toward best or reinitialize based on exploration rate. Implementation typically models cells, thresholds, weight matrices, agent assignment, and MCAV bookkeeping w...

πŸ‘‰ Read | AppStore | @mql5dev
❀18πŸ‘8πŸ‘Œ3πŸ”₯1