MQL5 Algo Trading
561K subscribers
4.16K photos
6 videos
4.17K 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
Modern FX trading stacks still face a trade-off between deterministic indicators and ML models that overfit, especially when train/test boundaries are weak. Information leakage remains a primary source of inflated backtest results.

A hybrid design is described: a fine-tuned Llama 3.2 model paired with Self-Evolving Adversarial Learning (SEAL), deployed on MetaTrader 5. The pipeline enforces a forward-test split (last 7 days held out) to keep validation unbiased.

Data generation labels 24h direction on M15 across eight major pairs, applies a 0.05% move threshold, and uses active class balancing near 50/50. Prompts include RSI, MACD, ATR, Bollinger position, stochastic, and volume ratio with a strict parsable output format.

SEAL adds adversarial self-play, prioritized replay, curriculum difficulty, and evolutionary updates to improve robustness und...

πŸ‘‰ Read | Freelance | @mql5dev
❀17πŸ‘5🀩3⚑1πŸ‘Œ1πŸ†1
MetaTrader 5 Strategy Tester can produce a strong equity curve that fails to reproduce in forward or live trading. A single backtest reflects one ordering of trades and hides the range of possible equity paths, including tail drawdowns.

Monte Carlo simulation reshuffles the closed-trade PnL sequence to generate many alternative equity curves. Monte Carlo analysis then extracts metrics from that distribution, including bust rate, profit rate, and worst observed drawdown.

A practical Python pipeline can parse the MT5 HTML report, extract initial balance and β€œDirection=out” PnL rows, run N shuffled paths, and output a mean curve with 5–95% bands plus summary stats. This supports position sizing based on tail risk rather than one curve.

πŸ‘‰ Read | Quotes | @mql5dev
❀22πŸ”₯5πŸ‘4⚑2🀩1πŸ†1πŸ‘€1
Moving from point-to-point bridges to an event-bus design, this article builds a native Kafka producer directly in MQL5 so one terminal can publish signals to a topic while any number of consumers independently subscribe, replay, and track offsets.

The core work is implementing Kafka’s wire protocol over raw TCP: big-endian framing with a 4-byte length prefix, RecordBatch v2 encoding, base-128 varints with zigzag for deltas, and CRC32C (Castagnoli) with a runtime-built lookup table. RecordBatch encoding is handled as a two-pass β€œwrite placeholders then patch” process for lengths and checksums.

On the trading side, signals are versioned and schema-checked at init, keyed by symbol+timeframe for partition ordering, queued and flushed on a timer or batch size, with configurable acks and exponential-backoff retries. Logging via FILE_COMMON produces tester-friendly,...

πŸ‘‰ Read | Quotes | @mql5dev
❀17πŸ‘11🀩3πŸ‘¨β€πŸ’»2πŸ”₯1🀣1
Part 15’s decision-forest classifier is turned into a tradable EA by separating prediction from execution. The model produces three class scores (bearish/neutral/bullish) from normalized bar features, but a decision layer gates whether that output is allowed to influence positions.

The classifier is refactored into a reusable module that encapsulates feature building, training stats, ALGLIB forest objects, and safe lifecycle rules (no inference until training succeeds, completed-bar history only, reproducible seeding, OOB error exposed for diagnostics).

The EA runs once per new bar, converts raw votes into a stable β€œdirectional regime” using a minimum-confidence filter, multi-bar confirmation, and a post-change cooldown. Trade policy is intentionally simple: long-only in bullish, short-only in bearish, otherwise no-entry, with strict risk sizing, spread/...

πŸ‘‰ Read | CodeBase | @mql5dev
❀21πŸ‘13πŸ”₯7🀩3πŸŽ‰2🀣2πŸ‘Œ1
Most trading anomaly detection watches price; this design watches execution quality: slippage, fill latency, spread paid, partial fills, and clustered requotes. A native Isolation Forest is implemented entirely in MQL5 and scored on every confirmed entry inside OnTradeTransaction(), acting as a monitoring/circuit-breaker layer rather than a signal generator.

The EA logs a 5D feature vector per fill, trains on a rolling window, and flags multivariate anomalies that single thresholds miss. Isolation Forest is chosen for unsupervised training, low parameter load, and fast scoring (trees x height), with configurable timing logs to verify runtime.

Implementation details that matter: strict feature-count enforcement to prevent invalid scoring, flat-array tree storage for serialization, subsampling without replacement, leaf-size path-length correction, binary p...

πŸ‘‰ Read | Signals | @mql5dev
❀27πŸ‘12πŸ”₯9🀩6🀣2πŸŽ‰1
TQNet targets time-series problems where both short-term moves and long-range structure matter. It does this by maintaining a global correlation tensor that acts as periodic memory, letting relationships form across the sequence without a fixed direction.

The implementation continues in MQL5 with a TQ-MHA module: multi-head attention where queries come from stored correlation parameters while keys/values come from current market data. This merges global context with fresh price action more safely than standard cross-attention.

A new CNeuronTQMHA class reuses cross-attention internals but changes residual/normalization to avoid overwriting local signals. Init is explicit and OpenCL-backed: GeLU for smoother training on noisy quotes, bounded timeframe indexing for carousel switching, and zeroed correlation buffers to prevent biased starts.

πŸ‘‰ Read | Signals | @mql5dev
❀13πŸ”₯10πŸ‘9🀣4πŸŽ‰1
MQL5 signal experiment shifts focus from detecting setups to timing entries under volatility regime changes. A dual-engine design combines a GARCH(1,1) volatility expansion gate with an optional volatility-scaled LSTM that scores short feature sequences.

Seven execution modes cover breakout, squeeze release, re-entry, mid-band impulse, band walk, pullback continuation, and range escape. Modes share a graded 0.5-centered score, then pass common LongCondition/ShortCondition gates: minimum GARCH expansion, raw pattern threshold, and final entry probability.

LSTM inputs are volatility-normalized (returns scaled by GARCH sigma, ATR and band metrics, expansion ratio). The key test is redundancy: ATR/Bollinger and GARCH can overlap, so validation requires switching algorithm-only vs blended LSTM and comparing backtests plus forward walks.

πŸ‘‰ Read | CodeBase | @mql5dev
❀15πŸ‘9🀣3πŸ”₯1🀩1πŸ‘€1
Running multiple MQL5 Expert Advisors in one terminal means no shared state beyond GlobalVariables. That namespace is untyped, schema-free, and cannot distinguish stale from current values.

A named-pipe message bus provides explicit message framing and a fixed, typed schema agreed by all participants. The broker EA owns the pipe server, message registry, risk aggregator, and a chart dashboard. Slave EAs connect as clients, report per-magic position state, and receive a centrally computed portfolio risk figure plus the symbol identified as the cause.

Implementation details matter: kernel32.dll imports, message-mode pipes, non-blocking accept via PIPE_NOWAIT, and connection confirmation via PeekNamedPipe due to unreliable last-error reads in MQL5. Messages serialize to a fixed 52-byte little-endian layout, with doubles copied bit-exact.

Limits remain expl...

πŸ‘‰ Read | CodeBase | @mql5dev
❀13πŸ‘4πŸ”₯2🀣2
Supertrend MTF Indicator is a free multi-timeframe trend tool for MT4. It plots bullish and bearish conditions on the chart using colored Supertrend lines and signal arrows.

Key capabilities include multi-timeframe trend confirmation, Buy/Sell arrow signals, and parameter controls for adapting sensitivity. It can be applied to Forex, Gold, indices, and other MT4 instruments, across different chart timeframes.

This is a visual indicator only and does not place or manage orders. An Expert Advisor based on the same Supertrend MTF logic is available separately for automated execution, while the indicator source is suited to manual analysis, education, and custom modifications.

Any trading tool should be validated on a demo account before live use.

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘11❀9πŸ”₯5🀩3πŸŽ‰2πŸ‘¨β€πŸ’»2🀣1
A Renko indicator for MT5 that renders fixed-size bricks using BID ticks and outputs only completed bricks. Reversal logic follows the classic two-brick rule, with square, equal-width brick rendering.

The chart window is used only as a host. Visible brick count is calculated automatically, the Renko range is vertically centered, and the real price scale remains on the right.

Implementation avoids offline charts, custom symbols, DLLs, and external libraries. A single primary input is used: Brick Size. Original chart visual settings are restored after removal.

Published as a CodeBase example aimed at studying Renko construction and MQL5 Canvas rendering.

πŸ‘‰ Read | Calendar | @mql5dev
❀19πŸ‘6πŸ”₯2🀣2πŸ‘¨β€πŸ’»2🀩1
Incoming BID ticks are routed to a classic Renko builder using a two-brick reversal rule. ADX, +DI, and -DI update only after a brick is completed. ADX acts as a strength gate, while +DI/-DI restrict trade direction. Entries require the newest completed brick to confirm direction and meet the configured Renko run. Exits can be requested by opposite DI, plus virtual TP/SL and a maximum holding time.

Default demo profile: brick size 16, ADX(14) threshold 8.5, min DI separation 2.5, entry run 3 bricks, TP 9.5 bricks, SL 42 bricks, max hold 1060 minutes, cooldown 6 bricks, max spread/brick 0.35, lot 0.01.

Real-tick test: XAUUSD M1, 2026-05-01 to 2026-09-08, 100% quality, 48,458,994 ticks. 46 trades, net +$1,095.53, PF 3.14, max equity DD 1.36%. Educational backtest only; outcomes depend on symbol specs, tick data, spread, execution, and broker conditions....

πŸ‘‰ Read | Forum | @mql5dev
❀21πŸ‘5πŸ‘Œ2πŸ”₯1🀣1
A Renko + Bollinger EA design ships with four modes enabled by default: Breakout (brick close beyond outer band), Re-entry/mean reversion (outside then back inside), Midline Cross (state change on middle line cross), and Squeeze Breakout (band-width filter before accepting breakout). Each mode has its own demonstration profile: brick size, Bollinger period/deviation, entry run, TP/SL in bricks, max hold time, and cooldown.

Portfolio controls allow per-mode enable/disable, one position per mode on hedging accounts, and an effective single net position per symbol on netting accounts. An optional conflict filter skips entries when modes signal opposite directions on the same tick. Separate magic numbers identify which mode opened a position after restarts.

A historical educational run on XAUUSD M1 (2026-05-01 to 2026-09-08, real ticks) reported 108 trades wit...

πŸ‘‰ Read | AppStore | @mql5dev
❀21πŸ‘6✍1πŸ”₯1🀣1
New CodeBase indicator example demonstrates custom Renko brick rendering with a causal Bollinger Bands overlay.

Parameters include Brick Size in price units, Bollinger lookback measured in completed Renko bricks, and the standard-deviation multiplier.

Rendering uses cyan up bricks and red down bricks, with blue outer Bollinger bands and a gold middle band. Bricks are square with automatic scaling. Drawing is handled through a single Canvas bitmap layer rather than large sets of rectangle objects, with automatic redraw on chart resize.

No DLLs, custom symbols, offline charts, or external indicators are required. Intended for education and implementation reference only, with no trading signals and no performance claims.

πŸ‘‰ Read | Docs | @mql5dev
❀17πŸ”₯5πŸ‘3🀩2🀣1
A Renko statistics panel is available for monitoring recent price action using only completed bricks and the classic two-brick reversal rule.

Displayed metrics include up/down brick counts with percentages, directional balance, reversal rate, average and maximum run length, current run direction with length, bricks formed per hour, and average minutes per completed brick.

Key inputs are Brick Size (fixed Renko brick size in price units) and Lookback Bricks (number of recent completed bricks used to compute statistics).

Implementation does not create offline charts or custom symbols and requires no DLLs or external indicators. The tool is intended for educational and statistical use, provides no BUY/SELL signals, and makes no claims of predictability or future profitability.

πŸ‘‰ Read | Signals | @mql5dev
❀18πŸ‘4🀩4πŸ”₯2🀣1
Renko charting is rendered on a sequence axis rather than time. The internal Renko builder consumes incoming BID ticks and applies the classic two-brick reversal rule.

The Donchian Channel is calculated causally. On each newly completed brick, upper and lower bounds are derived only from the previous N completed Renko bricks. The active brick is excluded from its own channel window. Inputs include fixed Brick Size in price units and Donchian Period as the lookback in completed bricks.

Implementation details include an internal fixed-size Renko, square bricks, and stepped Donchian boundaries with a midpoint. Rendering uses a single CCanvas bitmap layer instead of many chart objects, with no offline chart, custom symbol, DLL, or external indicator dependencies.

Provided as an educational visualization, not a trading system or a recommendation to trade br...

πŸ‘‰ Read | Signals | @mql5dev
❀14πŸ‘9πŸ”₯5🀩5🀣2⚑1
This update to the MT5 replay/simulation position indicator adds switchable display modes so traders can avoid focusing on monetary P/L while still monitoring risk during volatile periods.

A scoped enum inside the position structure defines modes (money, ticks, points, percent), letting the ViewValue routine format output via a clean switch and scope resolution. An extra β€œticks-to-price” support value is computed once and passed into the class to keep formatting fast and consistent.

Mode changes are triggered by clicking the OBJ_EDIT field: a custom event cycles the enum and forces a refresh of all indicator segments (entry, SL, TP) to prevent mixed units. On hedging accounts, updates are isolated per position via a ticket check, with an easy path to broadcast changes if desired.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀15πŸ‘9🀩6πŸ”₯4⚑2🀣1
This article digs into a practical pain point in MQL5 data structures: deleting nodes in a binary tree without corrupting links.

It starts by showing how traversal output (pre-order and post-order) can be used to reconstruct the tree shape, and why a small change in traversal logic produces different sequencesβ€”so reading output without checking the traversal code is unreliable.

A search routine is added by adapting the existing insertion-walk to return a node address. The article also highlights how seemingly equivalent loop conditions can trigger crashes due to compiler/short-circuit behavior, reinforcing the need for precise pointer checks.

Deletion is introduced with the simplest case: removing a leaf. The key rule is updating the parent’s child pointer before freeing memory; otherwise later traversals follow dangling pointers. An iterative de...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘10🀩8❀6πŸ”₯4πŸŽ‰1
Nicolas Darvas’ box method can be coded with clear rules, but automation tends to fail on two mechanics: rolling box replacement and staircase pyramiding with a shared stop.

This EA confirms a box after a new N-bar extreme, three consecutive sessions without exceeding the top, contracted average volume, and a minimum height filter. Entry triggers only when the close breaks the box boundary with breakout volume above the box average by a configurable multiplier.

Trade management is state-driven. Each subsequent breakout adds a new unit, moves all stops to the latest box floor, and closes all units together on a stop violation. A stall timer exits if no new box forms within a set bar count.

Known constraints include repeated top resets on tight ranges, tick-volume calibration per broker, and premature exits in strong trends when no new box forms.

πŸ‘‰ Read | Forum | @mql5dev
❀13🀩6πŸ”₯3πŸ‘€3πŸ†1
Pure MQL5 logistic regression built from scratch: no Python bridges, ONNX, DLLs, matrix classes, or external libraries. The core is a single-neuron classifier that maps a standardized feature vector to a probability via a numerically stable sigmoid, trained with stochastic gradient descent using cross-entropy where the gradient reduces to (prediction - label) * input.

The article emphasizes evaluation discipline over model complexity: standardize using only the training segment to prevent look-ahead leakage, split history into train/test blocks, and compare against a majority-class baseline.

Results illustrate why this matters: a small out-of-sample lift on EURUSD, but underperformance on XAUUSD, showing that clean testing can reveal when β€œworking” ML has no tradable edge.

πŸ‘‰ Read | VPS | @mql5dev
❀13🀩5πŸ‘Œ4
MSB Pro ALGO Neon Account Dashboard is a free on-chart account monitoring panel for MetaTrader 5. It shows key metrics including balance, equity, floating P/L, today’s realized P/L, closed trades today, daily win rate, open positions, and BUY/SELL counts.

The open positions table lists up to five entries with symbol, side, volume, open price, and current P/L. When more positions exist, an additional count is shown. Market open/closed status is derived from the attached symbol’s trading session. Data refresh runs automatically every second.

The tool is read-only and contains no trade execution or strategy logic. It works on demo and live accounts without DLLs, external APIs, or extra files. Settings include panel X/Y placement, refresh interval, max rows, table visibility, and color customization.

πŸ‘‰ Read | CodeBase | @mql5dev
❀13πŸ‘Œ3πŸ‘2πŸ‘¨β€πŸ’»2✍1🀩1
Beetle Swarm Optimization (BSO) merges Beetle Antennae Search (two-point probing without gradients) with Particle Swarm Optimization to reduce sensitivity to the initial point and improve performance on rugged, multi-dimensional objectives.

Each beetle maintains position, velocity, personal best, and a shared global best. Per iteration it samples fitness at two antenna tips aligned with velocity, converts the better side into a BAS increment, updates velocity via PSO (inertia + cognitive/social pulls), then blends both moves using a Ξ» coefficient to switch from pure BAS to pure PSO.

Exploration-to-exploitation is handled by linearly decreasing inertia and exponentially shrinking antenna step size and spacing.

The MQL5 implementation fits a standard Moving/Revision test bench using a phase-driven state machine, because each logical step needs three fitn...

πŸ‘‰ Read | Docs | @mql5dev
❀14πŸ‘13🀩7πŸ”₯6