MQL5 Algo Trading
510K subscribers
3.4K photos
3 videos
3.41K 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
Multi-Head Attention extends self-attention by running several parallel attention β€œheads” with independent weights, then concatenating their outputs and applying a final projection matrix to combine perspectives. This helps a model capture different dependencies in market sequences before producing a single decision tensor.

The article shows a practical MT5/OpenCL implementation that reduces computation by removing the explicit Keys tensor and training a single matrix where possible, while noting the trade-off when dimension reduction makes separate matrices cheaper.

For time-series, positional encoding is added to preserve distance information between candles using deterministic sine/cosine vectors, summed with inputs to avoid widening tensors.

Implementation details include a dedicated multi-head class, OpenCL kernels for concatenation/deconcatenation, and opt...

πŸ‘‰ Read | Docs | @mql5dev
❀56πŸ‘11✍6πŸ‘Œ3⚑2
A common approach for consuming news in a trading or automation stack is a scheduled web request to a remote endpoint, followed by local persistence and XML export.

Implementation typically includes HTTP GET with explicit timeouts, response code validation, and UTF-8 handling. Payloads are parsed as JSON, XML, or HTML depending on the source, then normalized into a compact internal structure with stable keys, timestamps, and de-duplication based on ID or checksum.

Stored records can be exported to XML using a fixed schema, proper escaping, and deterministic ordering. Production setups also add retry with backoff, rate limiting, and a cache layer to reduce repeated downloads.

πŸ‘‰ Read | Signals | @mql5dev
❀21πŸ‘6
Part 2 extends the breakeven subsystem with two dynamic modes and a selector to standardize configuration.

CBreakEvenAtr implements ATR-based levels. Fixed-point distances are replaced by two ATR multipliers: one for activation distance and one for the final breakeven stop offset. The class manages an ATR handle, a one-element buffer, and an ATR index for CopyBuffer reads. SetSimple supports either a ready handle or period-based handle creation, while Set(MqlParam[]) switches using a HANDLE_INSTEAD_OF_PERIOD flag.

CBreakEvenRR adds an RRR trigger and optionally computes the breakeven offset via points or ATR, controlled by an enum. Add() validates StopLoss presence, reads ATR when enabled, checks stop distance vs activation distance, then computes break_even_price and price_to_beat.

A CBreakEven selector class stores per-mode MqlParam arrays, allocates th...

πŸ‘‰ Read | Signals | @mql5dev
❀32πŸ‘4✍3πŸ‘Œ3
The article moves a MetaTrader 5 market simulation project into a database-driven stage, using the platform’s built-in SQLite to avoid DLLs or sockets while keeping full SQL control.

It demonstrates creating/opening a database via DatabaseOpen, choosing storage scope (RAM vs terminal Files vs COMMON\Files) through flags, and handling failures cleanly. Table creation is then executed with DatabaseExecute, separating simple commands from future query workflows.

A key design choice is wrapping SQLite access in a class. This encapsulation centralizes the database handle, prevents misuse, and prepares the codebase to switch later from file-based SQLite to a DLL build or client-server databases over sockets with minimal refactoring.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀15πŸ‘4⚑2
CATCH extends multivariate time-series anomaly detection with frequency-domain processing. Data is transformed via FFT, partitioned into frequency patches, and analyzed to separate low-frequency structure from high-frequency deviations. Anomalies are flagged by reconstruction error after the inverse transform.

Channel dependencies are handled by an adaptive masked-attention module that learns inter-series correlations while suppressing noise. Attention is constrained to matching frequency patches across variables, improving robustness for coupled signals such as financial instruments.

An MQL5/OpenCL implementation continues with a complex-valued multi-head masked attention object. Q/K/V are generated by complex convolution, masks by a real-valued conv layer with sigmoid and zero-initialized weights. Kernel scheduling merges segment and head dimensions to apply at...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀24πŸ‘7
Fixed RSI/Stochastic thresholds break in trends because they ignore volatility, leaving oscillators pinned at extremes and triggering repeated counter-trend entries. A Z-Score normalizes price deviation by rolling standard deviation, giving a volatility-aware mean-reversion signal: (Price - SMA) / StdDev, with extremes treated as anomalies rather than guaranteed reversals.

The implementation defines a strict β€œsignal contract”: symmetric Β±2.5 thresholds, calculations on closed bars only (shift=1), and safeguards for missing history and zero StdDev. The math is isolated in a CZScore class (include file) to reuse identical logic in both an indicator and an EA, avoid code duplication, and manage object lifetime to prevent memory leaks.

An indicator validates behavior visually and optimizes CPU using prev_calculated. The EA uses CTrade, runs once per ba...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘12
This article builds an MT5 weekend-gap indicator that turns Friday-close vs Monday-open discontinuities into persistent chart structures, so older gaps stay readable as the week evolves.

Gaps are detected from session time breaks (>= 48 hours) rather than day-name rules, then filtered by a minimum pip threshold with digit-aware pip sizing. Each gap is stored as a record with boundaries, midpoint, and an active-week flag.

Instead of buffers, the framework uses chart objects (rectangles, lines, labels) to keep multiple gaps visible and independently editable. A simple state machine updates the active gap in real time (fresh, partial, reaction, filled) and restyles objects on transitions.

Lifecycle handling is explicit: one-time historical scan on first calculate, tick-by-tick state updates, week rollover promotion to historical zones, and full cleanup...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘8
Traditional money management in MT5 often reduces risk only after closed losses, which can be too slow for pattern-based strategies. The article builds CMoneySuffixAE, a custom Wizard-compatible money module that sizes positions proactively using current market structure instead of loss counters.

The model combines two real-time checks. A suffix automaton indexes β€œPrice DNA” (Up/Down/Flat sequences) in linear time, letting the EA measure how familiar the latest 16-bar pattern is and scale lot size from exact historical repetition without expensive O(nΒ²) scans.

An autoencoder adds structural risk control. It reconstructs normalized recent prices and uses reconstruction error as an anomaly signal; when geometry breaks (news shocks), confidence collapses and position size is aggressively cut before losses accumulate.

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘22❀20πŸ‘Œ5
Quantum XAUUSD Silver Trader is a multi-indicator Expert Advisor for XAUUSD and XAGUSD on MT5, combining RSI, ADX, fast/slow moving averages, and a volatility filter into a single weighted decision. Separate presets are applied per metal to account for different volatility profiles, while a configurable threshold gates trade entries.

The weighting is adaptive: recent closed-trade outcomes adjust the contribution of each component, aiming to reduce overreliance on any single signal.

Risk controls are part of the core design. Orders use ATR-based stop loss and take profit, plus an adaptive ATR trailing stop. Account protection includes daily and total drawdown limits, daily loss limits, a position-size cap, and an optional hard stop. A micro/cent mode targets small deposits, with conservative defaults of 0.5% risk on Gold and 0.3% on Silver, typically on M15 an...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀26πŸ‘5πŸ‘Œ3
Exchange Market Algorithm (EMA) is a population metaheuristic modeled as a trading session: agents are ranked by fitness, split into elite, middle, and beginners, then updated with group-specific rules while elites remain fixed to preserve the best solutions.

Each iteration runs two modes. In a balanced market, the middle moves toward a random elite mentor, while beginners blend guidance from elite and middle. In a fluctuating market, the middle either copies the global best or samples around the elite centroid; beginners use resets, wide local searches, or opposition moves away from poor regions.

Exploration-to-exploitation is controlled by a sigmoid decay rate. An MQL5 C_AO_EMA class encapsulates parameters (r1/r2, riskAlpha), initialization, movement, and revision/sorting. Tests show modest but consistent improvement as problem size grows under a ...

πŸ‘‰ Read | Signals | @mql5dev
❀22πŸ‘6✍2
Many EAs treat overnight swap as an afterthought, even though it can materially change expectancy on multi-day trades, especially on high-differential pairs like AUDJPY. Swap is effectively daily interest: long positions can earn credit, shorts often pay, and triple-swap rollovers must be projected inside the holding window.

The article shows how to make swap actionable in MQL5 by reading SYMBOL_SWAP_LONG/SHORT plus SYMBOL_SWAP_MODE, then converting broker-specific units into a per-lot, per-day value in account currency. It handles common retail modes (points, deposit currency, interest-based using the 360-day convention), warns and returns 0 for reopening/margin modes, and notes where currency conversion or open-price accuracy is required.

Four drop-in building blocks tie this into real EA decisions: daily swap calculation, expected swap over a planned hol...

πŸ‘‰ Read | CodeBase | @mql5dev
❀23πŸ‘5πŸ†1
This part turns multifractal diagnostics into simulation-ready inputs for MMAR. A new Spectrum Fitter converts the scaling curve Ο„(q) into the singularity spectrum f(Ξ±) via a discrete Legendre transform (central differences, low-q filtering, and rejection of invalid negative f(Ξ±) points).

The empirical f(Ξ±) is then matched to four parametric cascade models (Normal, Binomial, Poisson, Gamma). Each fit minimizes SSE using ALGLIB’s BLEIC optimizer with strict parameter bounds to keep solutions physically meaningful.

A CSpectrumFitter class encapsulates the pipeline and selects the best distribution by lowest SSE. On EURUSD M10, the Binomial model wins, yielding Ξ±_min/Ξ±_max that quantify spectrum width and directly control cascade heterogeneity, supporting realistic volatility clustering with negligible extra runtime versus partition analysis.

πŸ‘‰ Read | Calendar | @mql5dev
❀14πŸ‘4
Cooperative MARL is moving toward offline multi-task training, driven by the cost of new environment interaction and poor scaling when agent counts or objectives change. Transformer-based models help, but many pipelines still miss task-specific structure and the temporal buildup of coordination.

HiSSD (Hierarchical and Separable Skill Discovery) proposes joint, hierarchical learning of shared cooperation skills and task-specific skills from offline datasets. Modules are trained end-to-end, with a multi-agent IQL-style value model, a planner selecting high-level skills, and a controller trained via VAE objectives plus contrastive separation across tasks.

An MQL5-oriented adaptation maps agents to univariate market sequences, adds controlled cross-sequence information exchange via masked attention (CATCH), then produces per-agent skill vectors with independent conv...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀25πŸ‘3
This article adds β€œdiscipline” to MetaTrader 5 EAs by separating strategy signals from an equity governance layer that supervises execution during stress. It tracks peak equity, drawdown, daily loss, and rapid equity drops, then drives a four-state machine: NORMAL, CAUTION, RESTRICTED, LOCKDOWN.

The design is modular: monitoring and analysis feed a state engine with cooldown and recovery checks (hysteresis to avoid flip-flopping). CAUTION scales risk via lot multipliers, position caps, and trade spacing; stricter states can block entries while still allowing position management.

Implementation uses a clean MQL5 library of specialized classes plus a thin EA wrapper. A single Authorize() call becomes the trade gate, with hard limits as an immediate backstop. A built-in SMA test engine and on-chart dashboard make behavior easy to validate in backtests.

πŸ‘‰ Read | Signals | @mql5dev
❀32πŸ‘5πŸ†2
Long-only trend breakout EA for MetaTrader 5 with fixed-currency risk per trade and execution restricted to the open of a new bar.

Signal logic: on the last completed bar, a buy setup triggers when Close(Bar 1) is strictly above High(Bar 2). Stop loss is set at Low(Bar 1). Take profit is derived from a configurable risk-to-reward ratio. Designed for indices with persistent upside bias, including NAS100, and typically evaluated on H4.

Risk management uses tick value and tick size to convert the stop distance into position volume, normalized to broker volume steps. Trades are skipped if the required size is below the minimum.

Backtests referenced: NAS100, H4, ~3.5 years, M1 OHLC modelling. Real-tick validation and broker-specific spread/contract checks remain required before live use.

πŸ‘‰ Read | AppStore | @mql5dev
❀23πŸ‘8
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
❀16πŸ‘5
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
❀18πŸ‘5
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
❀14πŸ‘7πŸ‘Œ2
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
❀12πŸ‘4
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
❀15πŸ‘4
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
❀10πŸ‘4