MQL5 Algo Trading
540K subscribers
3.86K photos
6 videos
3.87K 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
ACEFormer extends time-series forecasting for noisy markets by pairing ACEEMD denoising (explicitly dropping the first IMF to reduce high-frequency noise while keeping turning points) with a Transformer distillation stack that mixes probabilistic attention for informative regions and standard self-attention for global context.

The article focuses on integrating the OpenCL probabilistic-attention kernels into an MT5-side module: CNeuronMHProbAttention. It inherits a residual two-convolution backbone, keeps internal components statically allocated for predictable lifetime, and centralizes setup in Init, including Top-K queries and random key counts computed from sequence length.

Key handling is practical: a single index buffer stores both sampled keys and selected queries sized by max(randomKeys, topK)*heads. Random key selection uses uniform stratif...

πŸ‘‰ Read | Calendar | @mql5dev
❀27πŸ‘5πŸ‘€4⚑3πŸ‘Œ1
MQTTFive is an MQTT 5.0 client library for MQL5, delivered as an #include package for MetaTrader 5 expert advisors and scripts. It connects directly to MQTT brokers such as Mosquitto, EMQX, and HiveMQ, enabling outbound publishing of prices/signals and inbound command handling for EA control and status monitoring.

The implementation is pure MQL5 with an internal socket API and no DLL dependency. It supports QoS 0/1/2 with automatic retry, delayed publish queues, topic aliases, and flow control for receive quotas. MQTT v5 features include CONNECT/CONNACK properties (session expiry, packet limits, topic alias limits) and subscription options (no_local, retain_as_published, retain_handling). TLS/SSL, binary payloads, and UTF-8 are included.

Installation is file-copy based into MQL5/Include/MQTTFive/ and inclusion via MQTTClient.mqh. Core API: Connect, Disconnect...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀31πŸ‘8⚑2πŸ‘Œ1
Prop Firm Risk Dashboard is a lightweight, read-only account monitoring panel designed for prop-firm risk limits. Attach it to a single chart to monitor the entire trading account across any symbol and timeframe.

The panel displays balance and equity, floating P/L, today’s P/L based on equity change since the trading day start, daily loss usage versus a configurable daily-loss limit, max drawdown usage versus a configurable max-drawdown limit measured from a configurable starting balance, and current margin level. Status is color-coded (green/orange/red) as thresholds are approached.

Configuration inputs include daily-loss and max-drawdown percent limits, starting balance (0 uses current balance), warning and danger thresholds, and UI settings such as corner position, offsets, font, colors, and background. Day-start equity is stored in a terminal global var...

πŸ‘‰ Read | Calendar | @mql5dev
❀26πŸ‘10πŸ‘€2πŸ‘Œ1
Mamba4Cast targets real-time market forecasting where RNNs miss impulses and Transformers become too heavy. It combines Mamba state-space blocks (linear cost over sequence length) with Prior-data Fitted Networks, pretrained on many synthetic market-like tasks to enable zero-shot generalization across symbols and timeframes.

The pipeline normalizes inputs, adds timestamp-aware positional features (minute/hour/day/month/year) via multi-harmonic sine/cosine components, then uses causal and multi-kernel convolutions plus inception-style mixing before stacked Mamba blocks. It outputs multi-step forecasts in one pass, reducing autoregressive drift, with optional variance heads for uncertainty and regime classification losses.

The MQL5 implementation focuses on computing temporal encodings in an OpenCL kernel directly from timestamps, avoiding lookup t...

πŸ‘‰ Read | CodeBase | @mql5dev
❀22πŸ‘8πŸ‘Œ1
Brain-Computer Interfaces are moving from lab demos to clinical trials, with systems such as Neuralink N1 and the Blackrock Utah Array already decoding motor-cortex activity into discrete commands.

A practical gap remains: no standard software bridge from neural command streams into trading terminals such as MetaTrader 5.

A reference prototype can be built today using simulated neural commands. A Python Flask service emits BUY/SELL/CLOSE/HOLD over JSON via HTTP, while an MQL5 Expert Advisor polls with WebRequest, parses commands, deduplicates execution, and routes actions through CTrade.

This simulation validates integration points, safety behavior (reset-to-HOLD), and transport latency without requiring BCI hardware or clinical access.

πŸ‘‰ Read | Docs | @mql5dev
❀28πŸ‘5πŸ‘Œ1
This article implements the core step of persistent homology in MQL5: standard column reduction of a Vietoris–Rips boundary matrix over Z/2, turning sparse column relationships into a readable persistence diagram of (birth, death, dimension) pairs.

The reduction tracks each column’s pivot, uses a pivot-to-owner table for O(1) lookups, and performs fast XOR β€œadditions” via symmetric difference of two sorted face lists. Empty reduced columns mark feature creation; unique pivots mark feature death. Unpaired creators become essential features with infinite death.

A compact data model (SPersistencePair, CTDADiagram) enables persistence, Betti numbers at any epsilon, and barcode/diagram views. A CTDA facade runs the full pipeline (Takens embedding β†’ distances β†’ filtration β†’ boundary β†’ reduction) from a price window in one call.

Correctness is cross-chec...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀19πŸ‘5πŸ‘Œ2
MetaTrader 5 EA portability often fails due to broker-specific symbol identifiers, not strategy logic. Variants like EURUSD, EURUSDm, EURUSD.fx, GOLD, XAUUSD.a, or US30.cash can break SymbolSelect, bid/ask reads, and OrderSend, sometimes without explicit errors.

A broker-agnostic symbol layer addresses this with deterministic translation, terminal validation, caching, and CSV persistence. Resolution is defined as testable behavior: Resolve("EURUSD") returns a selectable symbol with non-zero quotes, or an empty result with logging.

Architecture splits responsibilities into modules: mapping storage, resolver with hash-based lookup plus controlled discovery, a small resolution cache, a host verification EA for live checks, and a benchmark tool for latency measurement.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀19πŸ‘7πŸ‘Œ2🀩1
Media is too big
VIEW IN TELEGRAM
Do you have Expert Advisors written in MQL4 and think migrating them to MetaTrader 5 will take too much time? Let's check this out right now.

We'll take an existing Expert Advisor from the MQL5.com CodeBase, feed it into ChatGPT, generate an MQL5 version, compile it in MetaEditor, and run it in the Strategy Tester. The entire process will take just a few minutes.

If you don't want to work with the code or handle the migration manually, there's an even easier option. MQL5.com offers a Freelance service where you can hire professional developers to convert Expert Advisors, indicators, and other applications.

Discuss the video:
πŸ‘‰ MQL5.community for traders
πŸ‘‰ MetaQuotes official YouTube channel
❀34πŸ‘9πŸ”₯6πŸ‘Œ5🀣4πŸ’”1
Spread Monitor Panel is a lightweight on-chart panel for tracking the live spread of the current chart symbol, refreshed every second. Spread is calculated from Ask-Bid in points, avoiding issues with integer symbol properties on float-spread accounts.

The panel reports current spread plus minimum, average, and maximum since attachment, including sample count and start time. Current value is color-coded against user thresholds: green below warning, orange between warning and danger, red at or above danger.

Optional alerting triggers when spread remains at or above the danger threshold for a configurable number of consecutive seconds, with a cooldown to prevent repeated notifications during spikes. Configuration includes thresholds, alert settings, panel corner, offsets, and font size.

Designed for monitoring only: no trades, buffers, or plots. Suitabl...

πŸ‘‰ Read | Quotes | @mql5dev
❀36πŸ‘6πŸ’”3πŸ”₯1πŸ‘Œ1
A position sizing script calculates lot size directly on the active chart symbol using a user-defined risk budget (percent of equity or fixed account currency) and stop-loss distance (points or explicit price level).

The calculation pulls live contract specs: tick size and tick value for money-per-point conversion, then applies volume min/max/step rules. Output is normalized by rounding down to the volume step so risk does not exceed the limit, and the exact risk at the normalized size is reported.

Margin is estimated for the intended direction using OrderCalcMargin. Clear warnings are generated when free margin is insufficient, when the computed size is below the symbol minimum (minimum volume exceeds the risk budget), or when the result is capped at the symbol maximum.

A full report is printed to the chart Comment, Experts journal, and a single-line Alert....

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘6πŸ‘Œ2
A trading-journal export script pulls raw account history from the terminal and writes it to a single CSV in one run.

The script loads deals for the last N days, then aggregates them into closed positions by position ID. It works on both netting and hedging accounts and supports partial fills. Entry and exit prices are volume-weighted across all entry and exit deals per position.

Each CSV row includes: position ID, symbol, direction, volume, open time and VWAP open price, close time and VWAP close price, points result (direction-aware), commission, swap, net profit, duration (minutes), and the first deal comment for strategy-level filtering.

Inputs cover: period (days), file name (or auto TradeJournal_YYYY-MM-DD.csv), CSV separator (default β€œ;” for Excel), optional common-folder output, and an optional current-symbol filter. Output goes to MQL5\Files o...

πŸ‘‰ Read | Signals | @mql5dev
❀27πŸ‘11πŸ‘Œ1
A Smart Money Concepts (SMC/ICT) market-structure indicator for MetaTrader 5 that derives structure from swing-high/swing-low sequencing and renders the current state directly on the chart.

Swing points are detected via N-bar fractals and plotted as arrows. Breaks are classified as BOS when price closes beyond the prior swing in the trend direction, and as CHoCH when the close exceeds the prior swing against the trend. On each structure break, the last opposite candle is flagged as an Order Block. Fair Value Gaps are identified as 3-candle imbalance zones. After a CHoCH, QML draws a dotted retrace level at the left-shoulder swing.

Key inputs include swing sensitivity, close vs wick confirmation, lookback bars, and per-feature toggles with configurable colors. Runs on any symbol and timeframe, recalculating on every new bar with close-confirmed markings.

πŸ‘‰ Read | Docs | @mql5dev
❀44πŸ‘7πŸ‘Œ3✍1
The Kinetic Compression Index (KCI) is a custom oscillator for detecting market exhaustion and localized compression events. It computes kinematic-style metrics directly inside the indicator loop, reducing reliance on multiple external indicator handles and simplifying EA buffer management.

The design exposes reproducible components such as Velocity, Deviation, and Dispersion, with Z-Score normalization applied over a rolling window before forming a composite KCI value. Signal buffers are built to validate on closed bars to reduce intrabar repainting and async tick timing issues.

A unified buffer map is central to integration: KCI main line and color index, buy/sell signal buffers, plus internal calculation arrays including Velocity Quotient, Kinetic Displacement, Energy Dispersion (usable as a volatility proxy for SL/TP logic), Phase Velocity, and R...

πŸ‘‰ Read | Forum | @mql5dev
❀26πŸ‘5πŸ‘Œ3
KCI Embedded Sniper is an algorithmic reversal-entry EA built around a fully embedded Kinetic Compression Index engine. KCI math (Velocity Quotients, Kinetic Displacement, Energy Dispersion, Phase Velocity) runs inside the EA, avoiding iCustom() latency and thread desynchronization. Signals are computed on closed bars only, targeting non-repainting execution with Singularity exhaustion validation and a Williams %R momentum gate.

The design removes external indicator files, reducing memory overhead and eliminating indicator path, loading, and buffer read errors. Computation is event-driven via rates_total and internal matrices, optimized for multi-asset operation in a single process loop.

Risk and filtering are parameterized: fixed lot sizing, ED-based dynamic SL/TP scaling, WPR period and extreme levels, plus KCI sensitivity controls (ZScorePeriod, Compress...

πŸ‘‰ Read | Docs | @mql5dev
❀26πŸ‘5⚑2πŸ‘Œ2πŸŽ‰1
Walk-Forward Analysis is reframed as a measurable robustness test for MT5 EAs: optimize on in-sample windows, score degradation on forward windows, and summarize it as a reproducible metric instead of eyeballing equity curves.

The core score is Walk-Forward Efficiency (WFE): per-window ratio of out-of-sample to in-sample Sharpe. Windows pass only if they retain at least 50% efficiency, with guards that force failure when in-sample Sharpe is non-positive or too small to be meaningful.

A native MQL5 pipeline implements the full loop: an EA logs per-bar equity to CSV, a fast reader ingests it, WFE_Engine.mqh computes Sharpe/WFE with numerical stability and validity flags, and a CCanvas histogram renders pass/fail windows and reference lines directly on-chart for immediate diagnosis.

πŸ‘‰ Read | Calendar | @mql5dev
❀27πŸ‘7πŸ‘Œ2
This part adds a pinned-tools ribbon to complement the deep, tabbed sidebar: the sidebar stays optimized for discovery, while the ribbon provides one-click access to a small set of frequently used drawing tools. The ribbon auto-hides when empty and preserves pin order.

Pinned tools are stored in the engine as an ordered list with a minimal API (count, get, contains, pin/unpin, toggle). Pinning appends; unpinning compacts the array without reordering, keeping behavior predictable.

A shared anti-aliased pushpin glyph is rendered via polygon coverage and alpha blending, reused consistently across flyout rows, the Pinned sidebar tile, and the ribbon.

The ribbon is a floating surface with drag, resize, and horizontal scrolling. It clips overflowing icons using an offscreen canvas and shows a proportional scrollbar thumb, keeping interaction smooth eve...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀24πŸ‘8🀯3πŸŽ‰2πŸ‘Œ2
Reliable MT5 Expert Advisors require systematic validation before sending trade requests. Common constraints include max positions/orders, volume min/max/step, SL/TP distance, margin, session limits, symbol permissions, and news filters. Market publication tests already enforce many of these cases, so reusable checks reduce duplication and regressions.

A compact MQL5 validator set can cover: lot sizing with step-based normalization (avoids retcode 10014), SL/TP distance vs SYMBOL_TRADE_STOPS_LEVEL, price digit normalization (avoids retcode 10015), freeze-level checks for order modifications, margin/funds checks, and β€œno changes” guards to prevent TRADE_RETCODE_NO_CHANGES.

Additional utilities include: pending-order limits, lightweight new-bar detection, tradability checks for SYMBOL_TRADE_MODE_DISABLED, calendar-based news windows (live only), and UTC sess...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘21❀11πŸ‘Œ3πŸ‘€3πŸŽ‰2πŸ’”2
This article extends the MCP approach from trading execution to the full development workflow by connecting AI agents to MQL5 Algo Forge, a Git-based host backed by Forgejo. Using its HTTPS REST API, an assistant can programmatically create repos, commit EA files, manage branches, open pull requests, file issues, and publish releases.

The server is a portable Python project (no MetaTrader/Windows dependencies) built in layers: JSON config + token, an httpx-based API client with consistent error normalization, domain handlers, and a FastMCP tool surface exposing 12 tools.

Key implementation details include safe token handling (config or environment variable) and Base64 encoding/decoding for file endpoints. A single β€œcommit file” tool abstracts POST vs PUT by detecting existing files and retrieving sha automatically, enabling reliable updates without t...

πŸ‘‰ Read | Docs | @mql5dev
❀20πŸ‘6πŸŽ‰2πŸ†2πŸ‘Œ1
MetaTrader 5 hides powerful β€œindicator-like” behavior inside chart objects. By programmatically repurposing OBJ_FIBO, the article builds a custom risk tool that visually marks entry, stop, and target using only a few configured levels.

The core technique sets a fixed number of Fibonacci levels, then assigns each level its value, color, and style via parallel arrays. Using values outside 0..1 turns Fibonacci into a projection engine, making it easy to express 1:1, 1:1.5, and partial-exit layouts that can’t be recreated manually from the UI.

Practical refinements include locking selection to prevent accidental moves, hiding unwanted guide lines, exposing a stop/target ratio as an input, and optionally disabling right-side extension so multiple analyses can coexist cleanly. The article also explores switching drawing flow toward left-click interaction, ...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘17❀12πŸ‘Œ3
Replay/simulation work in MQL5 is moving past sockets and SQL basics into chart-side tooling needed for realistic interaction.

Current components (mouse pointer, Chart Trade indicator, EA messaging) can submit market execution, but cross-orders and replay symbols lack reliable visual feedback for positions and orders.

Next step is a minimal position-visualization indicator. An indicator can read position state and print details, without attempting trade actions, which remain EA-only. This also highlights a platform constraint: indicators share a single chart thread, so the logic must avoid blocking and unnecessary updates.

Focus shifts to controlled chart objects for position lines, with attention to object lifecycle and cleanup to prevent long-term chart degradation.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘15❀8πŸ‘Œ3πŸ€”2
Protecting profit after a position is opened typically requires rules that react to price movement, not just the entry signal. Common approaches include moving the stop loss to breakeven after a defined profit threshold, then switching to a trailing stop to lock in gains as volatility expands or contracts.

A structured method uses staged stop management: initial fixed stop, breakeven activation, and trailing based on points, ATR, or recent swing levels. Partial closes can reduce risk while keeping exposure for continuation. Controls such as minimum distance, step size, and spread filters help avoid premature stop-outs in noisy conditions.

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘21❀15πŸ‘Œ3πŸ‘€3