MQL5 Algo Trading
537K subscribers
3.77K photos
6 videos
3.78K 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
Just three weeks after the official launch of MCP support and the built-in AI Assistant, MetaTrader 5 users have already processed more than 1 trillion tokens through the free MQL5 Lite model.

To understand the scale, 1 trillion tokens is roughly equivalent to:

• 700–750 billion English words
• 2.5–3 billion pages of text, assuming 250 words per page
• Around 9 million books with 80,000 words each
• Nearly 7,000 years of continuous reading at 200 words per minute

These figures show how actively thousands of MetaTrader 5 users are applying AI Assistant for a wide range of tasks — from market analysis to developing trading robots.

No API keys or third-party service setup are required to get started. Just sign in to MetaTrader 5 with your MQL5.com account, and the free MQL5 Lite model is available automatically.

Explore the capabilities of agentic AI for trading and programming.

Read more...
27👍18🔥7👌41👨‍💻1
MetaTrader 5 exposes OHLC and volume, but not exchange liquidation or open interest. Liquidity zones can only be estimated from on-chart data.

A Liquidity Heatmap approach flags candles where volume exceeds a moving average, then projects an estimated long/short liquidation price using candle direction plus an assumed leverage. Signals are ranked via a rolling buffer: HD mode uses raw volume, Normal mode uses volume delta.

Visualization relies on chart objects: lines for levels and tiered bubbles for strength. Levels extend forward until swept, then stop updating. Object limits, timestamp de-duplication, and per-bar processing reduce redraw and tick overhead. Output is probabilistic and should not be treated as confirmed liquidations.

👉 Read | AppStore | @mql5dev
20👍16😁2🤔1👌1
Backtesting a custom MQL5 indicator in Python often forces a reimplementation that can drift due to bar indexing, rounding, or warm-up rules. A cleaner approach is to export the exact indicator buffers calculated by the terminal and read them in Python as-is.

An MQL5 script can attach via iCustom(), wait using BarsCalculated(), fetch rates with CopyRates() and buffers with CopyBuffer(), then write a locale-stable CSV to MQL5/Files/. Avoid FILE_CSV; format numbers with DoubleToString() and write full lines with FileWriteString().

Handle warm-up by converting EMPTY_VALUE to empty fields so pandas loads NaN. iCustom() parameter forwarding needs a fixed-arity dispatch block due to compile-time call signatures.

👉 Read | CodeBase | @mql5dev
23👍11🤝32👀2👌1
TimeFound reframes forecasting as a foundation-model problem: a Transformer pre-trained on diverse time series can produce usable predictions even with little or no asset history, enabling zero-shot forecasts for newly traded instruments.

Core mechanics combine encoder–decoder attention with multi-resolution patching, capturing fast spikes and slow trends simultaneously. Standardization aligns scales across domains, while relative positional attention preserves temporal relevance and the decoder enforces causal generation.

Training blends point accuracy (MSE) with quantile loss to output uncertainty bands alongside forecasts.

The MQL5 implementation replaces costly patch replication with parallel multi-window convolution for aligned multi-scale features, then uses a multi-head residual feed-forward block and convolution/max-pooling aggregation for low-l...

👉 Read | VPS | @mql5dev
19👍5👌1
MQL evolved from early “Expert Advisor” concepts into an integrated environment where strategy code runs inside the terminal, with direct access to market series, indicators, and order execution. The key shift was treating automation as native, not an external add-on.

Early MQL was minimal, but MetaTrader 2 introduced MQL II with loops, arrays, richer types, and math functions, enabling real program logic per tick. MetaTrader 3 then expanded beyond execution into research by adding custom indicators and file I/O.

MetaTrader 4 and MQL4 completed the transition to a developer workflow: a structured language with user functions, scripts, libraries, DLL calls, plus MetaEditor bundling compiler, help, and tooling. Community infrastructure (MQL4.COM, Code Base, forums) and the automated trading championship validated autonomous trading at scale and push...

👉 Read | AppStore | @mql5dev
14👍12🔥1👌1
Reinforcement learning in algo trading shifts strategy creation from fixed rules to continuous updating from trade outcomes. An MQL5/MetaTrader 5 implementation uses a multi-agent layout with experience stored as discrete “memory neurons” and aggregated into independent decision agents.

Each neuron encodes a quantized 32-bit market state, a continuous action value (sell to buy), activation stats, and a score combining hit rate and usage frequency. Inputs are built from mostly stationary features (RSI, CCI, stochastics, MACD, ATR, Bollinger position, MA relations, fractals, ADX, WPR, normalized returns).

Learning is modified Q-learning with staged exploration, epsilon control, class-balance correction, and pruning when memory exceeds 1,000 nodes. Ensemble voting weights agents by recent success to reduce single-model bias.

👉 Read | Forum | @mql5dev
23👍9👨‍💻21👌1👀1
Indicator architecture follows an event-driven, sequential pipeline split across OnInit, OnCalculate, and OnTimer, with additional tick-level checks for alerts.

OnInit sets chart precision from _Digits, removes legacy objects prefixed with “SMC_OB_”, and initializes buffers plus state arrays.

OnCalculate iterates from prev_calculated - 1 for incremental updates. A price-boundary filter skips non-essential work when price remains between prev_valid_high and prev_valid_low, reducing CPU usage.

Market structure uses a rolling 3-bar window (vb1/vb2/vb3) keyed by datetime for stable swing tracking across reloads and timeframe changes. Order blocks are derived from swing confirmation plus displacement and a measurable FVG. Nested zones are filtered by comparing FVG size and deactivating weaker blocks.

Mitigation scans bars against active zones with body ...

👉 Read | Signals | @mql5dev
👍94🔥3👌1👀1
A mean-reversion signal indicator pairs Bollinger Bands with an embedded Stochastic RSI and triggers only after a close returns inside the band following an oscillator extreme.

Bearish logic: the prior bar closes above the upper band while StochRSI %K and %D are above the upper limit, then the current bar closes back inside. Bullish logic mirrors this below the lower band with both lines under the lower limit. Arrows are plotted on the signal bar and offset by a fraction of ATR(14) to avoid candle overlap.

Everything is calculated in a single .mq5 file: Bollinger Bands with shaded fill and basis line, StochRSI built from RSI plus rolling stochastic and double SMA smoothing, and an on-chart panel with live BB/ATR values, %K/%D zone, armed setup flags, and last signal details. Signals are evaluated on closed bars, with no trade execution or order manag...

👉 Read | Docs | @mql5dev
14👍8👌1
Trade Manager is an MT5 Expert Advisor focused on fast manual execution with automated risk controls. Trade parameters are managed on-chart through draggable horizontal lines for entry, stop loss, and take profit, with real-time recalculation as levels are adjusted.

The interface uses native MT5 graphic objects and supports instant minimize/maximize. Two workflows are provided: market execution at current Bid/Ask, and pending orders with automatic routing to limit or stop based on the entry line position versus current price (Buy Limit/Stop, Sell Limit/Stop).

Stop loss can be set by fixed points or an ATR multiplier, with separate settings for execution and pending modes. Position sizing is risk-based, calculating volume from account balance risk percent and SL distance while respecting broker constraints. State is persisted via terminal global variables, an...

👉 Read | CodeBase | @mql5dev
25👍7👌2👨‍💻1
A multi-timeframe trend-agreement indicator consolidates fast/slow moving-average direction across three configurable horizons (default H4, D1, W1) into a single bias score from -3 to +3. Each timeframe contributes +1 when FastMA > SlowMA, -1 when below, and 0 when equal. MA method is selectable (SMA, EMA, SMMA, LWMA) and applied consistently.

The histogram reports only the current live state, avoiding backfilled history. Higher-timeframe read failures retain the last valid value to prevent flicker. A throttled dashboard panel shows per-timeframe direction, total score, and a bias label, with DPI-aware scaling and strict input validation.

Typical use: trade only at ±3 for full alignment, use any non-zero score as a directional filter, validate existing entry signals with macro agreement, and treat score sign flips as exit warnings.

👉 Read | Quotes | @mql5dev
👍1211👌2🤯1
Slice sampling is presented as an adaptive MCMC alternative that avoids the step-size tuning pain of Metropolis and the conditional-derivation burden of Gibbs. It only needs an unnormalized density (typically evaluated as a log-posterior), then samples by defining a “slice” level, expanding or placing an interval/hyperrectangle, and shrinking it until a valid draw is found.

The article details an MQL5 implementation: 1D sampling uses stepping-out plus shrinkage; the multivariate version simplifies by skipping stepping-out and shrinking a randomly placed hyperrectangle.

Tests on Bayesian linear and logistic regression show posterior means and 95% credible intervals closely match OLS and IRLS estimates, while adding full uncertainty quantification. Practical notes include tracking log-density evaluations (neval) and validating chains with trace plots, ACF, an...

👉 Read | AlgoBook | @mql5dev
22👍4👌3👨‍💻1
MQL5 backtests often assume ideal fills. Live trading adds slippage, spread widening, requotes, price changes, and latency across the full path: terminal/VPS, network, broker gateway, and liquidity.

A diagnostic EA, Execution Quality Monitor, records execution metrics to separate strategy issues from execution issues. It runs in two modes: an active probe that opens and closes a minimum-lot trade and measures request-to-fill slippage, latency, and retcodes; and a passive listener via OnTradeTransaction that estimates fill quality for normal deals (approximate because the quote is read after execution).

Metrics are split by entry vs exit to detect slippage asymmetry, and reported as distributions (mean, median, p95, worst), plus observed spread. Samples are written to CSV with timestamps for per-hour analysis. Use on demo or minimum lot; probes place real tr...

👉 Read | AppStore | @mql5dev
18👍5👌1
This article ports level-2 path signatures to MQL5 to measure lead–lag without scanning lags. Instead of shifting series and correlating, it treats two aligned streams as a 2D path and uses the Levy area (the antisymmetric part of level 2) as an ordering-sensitive statistic: sign indicates which channel tends to move first, and zero-crossings mark flips.

The implementation builds a correct incremental engine via Chen’s identity with O(d^2) work per bar, plus a shuffle-relation residual to verify results. A facade class handles preprocessing (time augmentation, window normalization, optional lead–lag staircase transform), and exposes compact features.

Practical output is an indicator plotting a rolling Levy-area oscillator and an EA using the reading directly, with notes on scaling choices and non-stationary behavior in real markets.

👉 Read | Forum | @mql5dev
18👍6👌1
This article shows how to generate a portable, one-page trading performance PDF directly from MQL5, without DLL imports or external converters. The approach writes a minimal PDF (catalog, pages, page, font, content stream) using plain strings and the standard file API.

The core constraint is correctness of the cross-reference table: every object’s byte offset must be exact. Offsets are precomputed from ASCII lengths and the file is written in FILE_BIN to avoid newline translation that would corrupt positions.

The solution is modular: one component extracts closed-trade net results (profit+swap+commission) and builds stats plus an equity curve; another renders text and vector graphics via PDF operators, handling string escaping and drawing the curve as a single polyline for efficiency.

👉 Read | Forum | @mql5dev
19👍5👌2🎉1
Financial forecasting remains difficult due to noise, non-stationarity, regime shifts, and event shocks. Classical models assume stability; LSTM/GRU often overfit and degrade under asset or regime changes.

TimeFound targets zero-shot forecasting via a Transformer trained on diverse cross-domain time series. Multi-Resolution Patching converts sequences into multi-scale tokens; independent projection modules with masks improve robustness to padding, missing data, and phase shifts.

The Encoder–Decoder block uses bidirectional self-attention in the Encoder and causal decoding with cross-attention in the Decoder. Forecasting is autoregressive: one next-token segment per step, appended back into history.

Implementation notes: a central unit coordinates both streams. The Encoder uses per-variable attention (CNeuronMVMHAttentionMLKV) with MLKV reuse; the...

👉 Read | AppStore | @mql5dev
👍134😁1👌1
Anchored VWAP extends standard VWAP by starting accumulation from a user-defined anchor time, preserving full history from that point. This supports event-based analysis, swing-structure study, and custom session boundaries, with optional standard deviation bands.

An MQL5 implementation focuses on indicator architecture: OnInit for input validation, buffer binding, properties, and anchor-line creation; OnCalculate for cumulative VWAP and bands; OnChartEvent for draggable anchor updates; OnDeinit for object cleanup.

Key design points include unique chart object naming via an instance ID, applied price selection, fixed-anchor vs session-reset modes (daily/weekly/monthly), auxiliary calculation buffers, and recalculation control using stored anchor state.

👉 Read | CodeBase | @mql5dev
10👍6👌1
AutoML confidence gating for EMA crossover systems, built for MetaTrader 5 deployment.

Pipeline runs in Python: fetch XAUUSD H1 from MT5, engineer 9 features (normalized EMAs, EMA distance, RSI and momentum, normalized ATR, volatility ratio, close-range %, direction). Each crossover is simulated with next-bar entry and opposite-crossover exit, then labeled profit=1 or loss=0.

FLAML trains a classifier with time-ordered splits and searches LightGBM/XGBoost/RF. Best model exports to ONNX with a plain probability tensor, then is parity-checked in ONNX Runtime.

MQL5 EA embeds the ONNX model as a resource. On bar close it computes the same feature contract, runs inference, and only trades when P(profit) exceeds a tunable threshold. Exits mirror labeling via ATR trailing and opposite crossover.

👉 Read | Freelance | @mql5dev
12👍4👌1
This article reviews a full MT5-ready feature pipeline built on Bill Williams fractals: detecting swing highs/lows, then deriving strength, validity, dynamic support/resistance, breakout flags, trend direction/strength, and whipsaw-filtered entry signals. The goal is structural, timeframe-invariant market context that can feed ML models and rule-based systems.

The key engineering lesson is a look-ahead leak caused by centered rolling windows: raw fractal and derived columns depend on future bars, inflating backtests and even walk-forward results. The fix is to shift leaky columns by n at the feature-matrix boundary while leaving already-causal breakout/trend outputs untouched.

Two additional silent bugs are addressed: a hardcoded shift that breaks when n changes, and a “volatility” threshold that never uses volatility, requiring ATR-scaled validation.

👉 Read | Forum | @mql5dev
6👍31🏆1
Modern RL Trader v3.1 describes an ensemble RL system with seven agents, each configured for different market regimes and trained on the same 500-bar lookback with distinct network/attention setups.

Core loop follows agent–environment–reward, but adds episode-level updates via BackwardMonteCarlo(), adaptive optimization, and stateful modifiers such as GetEmotionalInfluence() plus m_wisdomAccumulated derived from past outcomes.

Portfolio control is handled by DistributeVolumesAndRewards(), applying weighted voting, lot/reward multipliers, and 24-hour rotation so capital and learning rate concentrate on strategies with current edge while underperformers are throttled.

👉 Read | Docs | @mql5dev
👍52