MQL5 Algo Trading
561K subscribers
4.17K photos
6 videos
4.18K 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
This part advances an automated MT5 optimization pipeline that stores sequential Strategy Tester jobs in an SQLite database, turning manual multi-currency EA research into repeatable projects. The “project creation” EA behaves like a script: it generates stage-specific tasks, writes them to the DB, then exits.

Focus shifts to stage 2: combining top stage-1 passes into strategy groups and re-optimizing them with a chosen criterion (often a custom normalized annual profit) and an optional time cap to cut wasted tester runtime.

Key controls include filters on minimum custom metric, trade count, and Sharpe ratio, plus group size (2–16). The article also shows why iterative dry runs matter: a detected bug and missing symbol history can mark tasks “done” while preventing the pipeline from producing the final EA, so DB inspection becomes part of debugging.

👉 Read | Signals | @mql5dev
❤17🔥7🤩5👍4
This stage makes the replay/simulation framework usable without rewriting the Expert Advisor or position indicator. A small addition to C_InServer enables correct handling of symbols used on hedging accounts, keeping server vs simulator execution transparent.

The focus shifts to C_Orders, where trade requests are decoded. Error handling is refactored so messages look consistent across real and simulated servers, with symbol-tagged output to trace request origin.

TRADE_ACTION_DEAL is implemented incrementally, since it must behave differently on netting vs hedging: update an existing position (including average price logic) or create a new one. The simulator also introduces an optional server-response delay hook, and fixes ticket generation to prevent duplicates.

Result: market opens and SL/TP edits can be tested end-to-end in replay; full closing ...

👉 Read | NeuroBook | @mql5dev
❤13🤩10👍9🔥4🏆1👀1
This article proposes a reusable MQL5 Expert Advisor template that separates strategy rules from platform plumbing. Instead of mixing signals, execution, and risk logic inside OnTick, the framework standardizes recurring tasks: history loading, new-bar detection, order management, spread checks, commission/swap handling, and UI updates.

Core architecture: a Virtual Chart (cached OHLC/time), a Robot class (state + trading operations), and a single Simulated() loop. Live trading uses a 1-second timer for stability with sparse ticks; the Strategy Tester runs on ticks, but both share the same entry point.

Trading logic plugs into one method that sets two variables: entry direction and close direction. Built-in modules cover auto lot sizing, risk controls, additional entries, martingale, and timed “waiting out losses,” with inputs grouped for safer testing and o...

👉 Read | Signals | @mql5dev
❤20👍10🔥8🤩3
Average True Range (ATR) is derived from True Range (TR), defined as max(High-Low, abs(High-Close[1]), abs(Low-Close[1])). Initialization typically computes TR over Length bars, then uses the SMA of those values as the first ATR.

RMA uses alpha=1/Length and updates as: rma = alpha*TR + (1-alpha)*prev_rma. SMA mode recalculates the simple average of TR over the last Length bars on each candle. EMA uses alpha=2/(1+Length) with: ema = alpha*TR + (1-alpha)*prev_ema. WMA applies linear weights: sum = N*TR[0] + (N-1)*TR[1] + … + 1*TR[N-1], then wma = sum / (N*(N+1)/2).

Common validation setup: XAUUSD on H1, comparing RMA, EMA, SMA, and WMA outputs side by side.

👉 Read | Docs | @mql5dev
❤10👍7🤩5🔥3👨‍💻1
The article shows how MQL5 operator overloading can be used to express data-structure operations with stream-style syntax similar to C++ input/output, improving readability when done with clear intent.

A pointer-based queue is rebuilt using overloaded operators, where a small header-only change switches behavior between LIFO (stack) and FIFO without rewriting the calling code. This demonstrates separating policy (order) from usage.

The same idea is extended to a linked list: adding a subscript operator enables array-like access, then the implementation is revised so assignments append new nodes instead of overwriting existing values. The final design uses a doubly linked list and avoids traversal by maintaining links during insertion, making updates predictable for trading utilities like event queues and order pipelines.

👉 Read | Quotes | @mql5dev
❤16🔥6👍5⚡1
This update finalizes the MT5 replay/simulation system for training by aligning simulated pricing with live-server behavior. A small fix removes hardcoded SYMBOL_DIGITS side effects, and a new config option lets users set per-symbol decimal precision so the position indicator formats prices correctly (e.g., instruments with 0.5 ticks).

Database stability is improved by moving table-creation SQL into an external script embedded as a resource and adding constraints to prevent invalid or duplicate records, reducing corruption risks without extra application logic.

Take Profit and Stop Loss become functional by adding a close-price check inside the position indicator and firing a custom event to the EA to close positions. The same event-driven pattern can be adapted to simulate pending orders by changing the trigger conditions and emitting the appropri...

👉 Read | Freelance | @mql5dev
❤17🤩8👍4🔥3
PDF generation in MQL5 can work without DLLs when the format is treated as plain text plus a bottom index.

A minimal PDF has five regions: header, numbered objects, xref table, trailer, and %%EOF. Only the object list grows; most of the file is boilerplate.

The body is a flat set of indirect objects referenced by “N 0 R”. Pages do not embed content or fonts directly; they reference a content stream and resource objects.

PDF values are limited to eight types, with names (/Helvetica) distinct from strings ((Hello)). Streams require an exact /Length byte count.

A single page typically needs Catalog, Page Tree, Page, Contents stream, and Font. Correct xref byte offsets and startxref are critical; a one-byte shift breaks the file.

Content streams use postfix operators (BT, Tf, Td, Tj, ET). Multi-line layouts rely on relative Td moves and can switch fonts mid-s...

👉 Read | Docs | @mql5dev
❤26👍4⚡3🎉3🤩2
SAGDFN targets noisy, redundant market data by keeping only neighbors that measurably influence the system. After implementing Significant Neighbors Sampling in OpenCL, the focus shifts to Sparse Spatial Multi-Head Attention to extract structure from the selected links while staying compute-efficient.

A key optimization avoids per-pair embedding concatenation. By splitting the first linear layer into separate query/key projections computed once per node, pair logits become simple vector additions, cutting complexity from O(NMhd) to O(Nhd)+O(NMh) and reducing memory pressure—well-suited to GPU execution in MQL5+OpenCL.

For attention normalization, iterative α-Entmax is replaced with Sparse-SoftMax to keep sparsity without expensive τ searches. The OpenCL forward kernel computes head-wise sparse weights with local reductions, NaN/Inf guards, bounds-che...

👉 Read | Calendar | @mql5dev
❤13🔥4🤩2👌2👨‍💻1
Dragonfly Algorithm (DA), proposed by Seyedali Mirjalili in 2015, models two swarm modes: static hunting and dynamic migration. These map directly to exploitation and exploration in population-based optimization.

Each agent applies five terms per iteration: separation, alignment, cohesion, attraction to the current best (Food), and repulsion from the current worst (Enemy). Velocity is updated as a weighted sum plus inertia, then position is advanced and clamped to bounds.

When an agent has insufficient neighbors and Food is out of range, DA switches to Lévy flight using Mantegna sampling to generate heavy-tailed steps.

Adaptive control drives convergence: neighborhood radius increases over epochs, inertia drops from 0.9 to 0.4, and s/a/c/e decay to zero mid-run, leaving Food attraction dominant. Population size is the main external parameter.

👉 Read | Signals | @mql5dev
❤17👍4🔥1🤩1
Tree-based feature_importances_ (MDI) answers what the forest split on, not what a feature is worth. As features multiply, correlated indicators become interchangeable, and their “credit” gets diluted across copies, letting weak or even useless columns outrank a real signal with no warning.

Permutation importance (MDA) is out-of-sample but can fail harder: if a signal has duplicates, permuting one column leaves substitutes intact, so the measured impact can collapse toward zero.

The robust fix is clustered MDA: group dependent features using an unsupervised clustering step on a denoised correlation matrix (Marčenko–Pastur + effective sample size), then permute entire clusters. This recovers the true signal in a synthetic triple-barrier setup and produces a clean separation between informative and noise blocks.

Clustered MDI can invert rankings when ...

👉 Read | Quotes | @mql5dev
❤10👍5🤩4🔥2
MetaTrader 5 reports blend partial exits into a single result, hiding whether scaling out improved or weakened performance. This article builds a native MQL5 Scale-Out Value Analyzer that reconstructs positions from deal history, detects multi-exit closures, and evaluates scaling against counterfactual full exits using only the trader’s realized exit prices.

For each scaled position, it reprices the full volume at the first, last, and best per-lot exit outcome (including profit, commission, and swap). It then measures value added vs holding to the last exit, efficiency vs the best achievable exit, and aggregates results safely via ratio-of-sums.

The tool ships as two scripts: an exporter using HistorySelect() to write deal-level CSV, and an analyzer that parses, groups by PositionID, validates volumes, excludes multi-entry positions, runs a single-trade depende...

👉 Read | AlgoBook | @mql5dev
❤15🤩5🔥4⚡2👍2👌1
Double tops/bottoms look obvious in hindsight but are hard to automate because pivots, necklines, and tolerances are often subjective. This article turns the pattern into a deterministic contract suitable for MT5 Strategy Tester.

The MQL5 design confirms swing pivots using a fixed left/right bar window, then pairs two same-type pivots only if their prices match within a tolerance scaled by pattern height. The neckline is strictly the opposite pivot between peaks, with spacing, leg-balance, and optional prior-trend filters to reject noisy shapes.

A small state machine manages progression from detection to entry: arm the setup, trigger on a close through the neckline or wait for a retest, then invalidate on extreme breach or timeout. Risk rules are explicit: stop beyond the paired extreme with buffer, targets via measured-move or reward-to-risk, opti...

👉 Read | Freelance | @mql5dev
❤11🔥8👍4🤩2
MetaTrader 5 ships with MarketProfile, but it does not segment volume by individual swing legs. A swing-based profile can be built from OHLC and platform tick volume to study volume concentration inside each completed high-to-low and low-to-high move.

Core logic: confirm swing highs/lows using a configurable window and next-bar validation, then connect confirmed points with a ZigZag leg. For each finished leg, compute the swing range, create ATR(200)/2 adaptive price bins, and allocate each bar’s tick volume to a bin using the close.

After aggregation, the highest-volume bin is marked as the POC and the full profile is rendered with chart rectangles scaled by relative volume. Results reflect tick volume, not exchange-level order flow.

👉 Read | AlgoBook | @mql5dev
❤10🤩6🔥5👍3
ATR-smoothed Heiken Ashi candles are drawn directly on the chart: blue for bullish and red for bearish. Smoothing is ATR-driven: if the new HA close deviates from the prior smoothed close by at least ATR x sensitivity, the candle uses raw HA values; otherwise open/close are blended via a configurable factor to suppress minor colour flips.

Trend bias is provided by Fast EMA (default 20) and Slow EMA (default 50). Early-entry arrows trigger only when a smoothed candle flips direction in line with EMA bias and while EMAs remain close, with “close” measured in ATR units to adapt across symbols and timeframes. Signals are skipped once EMAs separate beyond the ATR threshold.

Buy arrows print below candles and sell arrows above, offset by an ATR fraction. Optional popup and push alerts fire once per bar per direction. No trade execution, no SL/TP, and the c...

👉 Read | AlgoBook | @mql5dev
❤12🔥7🤩2👍1
Probability theory remains a practical dependency for trading systems, from strategy PnL estimates to risk models. Modern ML also inherits classical statistics: neural nets are probabilistic models optimized via maximum likelihood, with predictable strengths and limits.

A random variable is a deterministic function X(ω) on an assumed probability space Ω, used because Ω is rarely tractable directly. The working representation is the distribution on R via the CDF F(x)=P(X≤x), which supports interval probabilities by differences F(b)-F(a).

Distributions split into discrete (PMF with point masses, stepwise CDF), continuous (PDF as dF/dx, interval probabilities via integrals), and mixed. Degenerate variables map all outcomes to a constant and appear in convergence results like LLN.

Practical tooling includes CDF/PDF and QQ comparisons and MQL5 standard library...

👉 Read | Quotes | @mql5dev
❤6👍4🤩3🔥2👨‍💻1
FX options desks work in delta space, not strike space. Standard quotes per expiry are ATM volatility, 25-delta risk reversal, and 25-delta butterfly, with optional 10-delta wings. Strikes are derived from these pillars plus an interpolation choice.

Equity-style tooling in MetaTrader 5 commonly starts from listed strike chains and single-rate Black-Scholes. For FX this misses both market quoting practice and the two-rate setup required for carry.

A correct implementation uses Garman-Kohlhagen and treats delta as a convention: spot vs forward delta, and premium-adjusted vs unadjusted. The convention varies by pair, premium currency, and tenor, and can shift 1Y strikes by tens of pips or more without triggering obvious errors.

The reconstruction pipeline converts RR/BF to wing vols, then solves each pillar’s delta back to its strike at that vol. Outpu...

👉 Read | Docs | @mql5dev
🔥1