MQL5 Algo Trading
586K subscribers
4.89K photos
7 videos
4.89K 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
EEMFlow in MQL5 is positioned as an event-driven pipeline that converts non-uniform market event streams into a stable motion representation for downstream forecasting.

The core path is: Adaptive Density Module (ADM) for density normalization, pyramidal encoder for compact embeddings, Multiscale Feature Correlation (MSFC) for cross-horizon matching, MeshFlow estimation for global motion fields, and CDC for detail recovery with boundary preservation.

ADM is split into Multi-Density Changer (MDC) and Multi-Density Selector (MDS). Current implementation work targets MDC, including a spiking Feature Alignment Module (CNeuronSpikeFAM) that combines cProduct, cActivation, and cConv, with padding-aware windows and residual normalization in feedForward.

Next build step is CNeuronSpikeMDC: channel scaling (cSCMs), embedded FAM array (cFAMs), adaptive fusion ...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘10πŸ”₯6🀩4❀3⚑2
Event streams in markets behave closer to sensor data than uniformly sampled time series. Mesh approximation can aggregate irregular events into a stable structure while keeping local dynamics.

EEMFlow applies this idea with a compact pyramidal encoder, symmetric feature extraction for adjacent windows, and a multiscale cost volume using sparse dilated correlation. Feature levels are normalized, fused, and decoded into a MeshFlow field at ground-truth resolution, with grouped convolutions to control latency.

EEMFlow+ adds boundary handling via a confidence-driven detail completion module, combining local CNN corrections with broader autocorrelation and confidence-weighted fusion. An adaptive density module calibrates event rate to reduce noise without losing microstructure signals.

πŸ‘‰ Read | CodeBase | @mql5dev
🀩18❀10πŸ‘10πŸ”₯4🀝2⚑1
MQL5 data export typically falls back to CSV files or ad-hoc text sockets. Both lack an on-wire schema and add parsing overhead that grows with volume. Arrow Flight addresses this with Arrow IPC payloads over gRPC/HTTP/2, but MQL5 has no HTTP/2, gRPC, or Arrow bindings.

A full Arrow Flight client is implemented on top of an MQL5 socket: HTTP/2 framing with HPACK, gRPC framing and status handling, protobuf encoding for FlightData, and FlatBuffers-based Arrow IPC schema and record batches. A CFlightClient supports DoPut, DoGet, and ListFlights against a pyarrow Flight server.

Validation is end-to-end. Offline self-tests cover varints, HPACK cases from RFC 7541, FlatBuffers alignment, IPC round-trips, and golden-hash checks. Live benchmarks upload and immediately download datasets, comparing decoded values row-by-row, plus an independent Python reader cr...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘9πŸ”₯4🀩4⚑2❀2
MetaTrader 5 EAs often need low-latency telemetry outside the terminal. Common options rely on files, WebRequest, or external messaging stacks, which add delay and deployment work. A practical alternative is embedding a WebSocket server inside the EA and streaming ticks, deals, and periodic account/position snapshots over one persistent connection.

MQL5 provides only client sockets, so a server requires Winsock imports for bind/listen/accept plus non-blocking I/O. RFC 6455 is implemented in MQL5: HTTP upgrade validation, frame parsing, masking rules, fragmentation, ping/pong, UTF-8 checks, and close handling, with limits to prevent unbounded buffering.

The design runs one non-blocking service pass per timer event, enforces backpressure via per-client TX queue caps, and closes reliably without losing the close frame. Live measurements reported 327 Β΅s median...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘9❀5🀩4πŸ”₯3⚑2
A Donchian-style channel indicator plots the highest high and lowest low of the previous N bars for each bar, plus a midline. It marks the first confirmed close outside the channel with arrows: blue is the upper band, orange the lower band, dotted the midline. A green up arrow prints on the first close above the upper band, and a red down arrow on the first close below the lower band.

Non-repainting behavior is enforced by using only bars iβˆ’N to iβˆ’1 to form the channel for bar i, and by writing arrows only after bar close. The higher-timeframe trend filter reads only the last completed daily bar, avoiding look-ahead in testing.

An optional filter restricts signals to trend direction based on the D1 EMA slope over the last k completed daily bars. Buffers expose upper/lower/mid channels and breakout markers for EA use. Typical setups include XAUUSD H1 ...

πŸ‘‰ Read | Forum | @mql5dev
❀6πŸ‘4πŸ”₯3⚑2
Lot sizing in common MQL5 examples typically targets a single position on one symbol. Multi-symbol EAs also need to account for existing stop-loss exposure, free margin headroom, and symbol volume limits, and they need to report which constraint reduced volume.

CRiskBudget consolidates sizing into one include. It computes risk per lot via OrderCalcProfit() plus commission, applies an optional slippage buffer, and returns both the final volume and the binding cap. Caps cover per-trade risk, remaining open-risk budget across positions and pending orders, a share of free margin, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT.

The implementation refuses quotes when account open risk cannot be computed, including missing stops or failed OrderCalcProfit() calls. A tick-value ratio check is logged to flag symbols where SYMBOL_TRADE_TICK_VALUE-based sizing diverges, ob...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ”₯5❀3πŸ‘3⚑2
MetaTrader 5 terminals cannot read each other’s live quotes, so this design bridges brokers through FILE_COMMON: each terminal runs a lightweight publisher EA that overwrites a broker-keyed one-line file on every tick.

A separate aggregator EA polls those files on a fixed timer, parses and validates bid/ask/volume/timestamp, explicitly drops stale or malformed feeds, and computes a volume-weighted mid-price (with a fallback weight when tick volume is zero).

The result is written into a custom synthetic symbol via CustomSymbolCreate/CustomRatesUpdate. Bars are intentionally flat (OHLC identical, zero spread), with volume fields reused as diagnostics to show contributing broker count and total weight. This makes execution comparison and spread auditing practical, while avoiding silent averaging of frozen quotes.

πŸ‘‰ Read | VPS | @mql5dev
❀12πŸ‘6⚑2πŸ”₯2
Volatility tends to cluster: extended quiet phases are often followed by sharp expansions, with abrupt transitions. A squeeze scanner flags compression by comparing two envelopes around the same 20-bar basis.

Bollinger Bands use 2.0 standard deviations of closes. Keltner Channels use 1.5Γ— ATR. A squeeze is active when Bollinger Bands sit inside the Keltner Channel, indicating unusually low range.

Signals: a red dot marks squeeze on; a green dot marks squeeze release. Momentum bars quantify direction and strength: bright/pale green for rising momentum, bright/pale red for falling momentum. Momentum is calculated as close minus the average of the Donchian midline and the SMA.

On XAUUSD, major moves (2019 breakout, 2024 rally) followed prolonged compression. Testing cited strongest profit factor on H4 long-only squeeze breakouts with a D1 uptrend filte...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘6🀩4❀3⚑2πŸ”₯2
MetaTrader 5 can generate ticks and deals reliably, but long retention and analysis require a columnar store. ClickHouse fits this use case, and its HTTP interface on 8123 can be called directly from MQL5 WebRequest() without a queue, DLL, or sidecar process.

RowBinary is used for INSERT because it is a strict, compact, row-oriented encoding. It avoids JSON/CSV parsing cost but has no tolerance for byte-count errors. Schema column order must match encoder write order, or values will land in the wrong columns.

Implementation centers on a RowBinary writer (little-endian primitives, VarUInt for string lengths, raw IEEE-754 double bytes, DateTime64(3) milliseconds) plus an HTTP client that separates GET for reads from POST for INSERT/DDL. Nullable(T) requires a NULL flag byte, and in RowBinary a NULL writes no payload bytes.

Self-tests and backfill ...

πŸ‘‰ Read | Quotes | @mql5dev
❀5πŸ‘4πŸ”₯4⚑2🀩2
INI-style configuration remains a practical option when settings must stay outside compiled code. Python ships configparser; MQL5 typically relies on inputs and .SET files, which limits portability across tools.

A Python-like CConfigParser for MQL5 can mirror the section/key model using simple structures and dynamic arrays, supporting read, get, set, add_section, and write. Parsing includes section detection via [brackets], key=value extraction, and comment filtering.

Key behavior details include duplicate handling (later values override, repeated sections merge) and configurable inline comment stripping, which differs from Python’s default. Typed getters in MQL5 can be implemented with templates, returning success flags and writing results via output parameters.

πŸ‘‰ Read | CodeBase | @mql5dev
❀7πŸ”₯6πŸ‘4✍2🀩2⚑1
Indicator workflow sets position size from a fixed risk budget using chart lines and broker contract specs.

After attaching, a red STOP line is placed at 3 Γ— ATR below price and a green TARGET line at 2R. Drag the STOP line to the intended stop location; for sells, place it above price. The panel updates every second and immediately after line changes. Read LOTS in the panel and use that value in the order.

Panel fields include: Risk (percent and amount), Entry (ask for buys, bid for sells), Stop (price and points), 1 lot loses (money loss for 1.00 lot to stop), LOTS (rounded down to volume step, raw in brackets), At risk (actual risk at that size), Target (reward:risk at target line).

Gold/CFDs are handled via OrderCalcProfit() to avoid pip-value errors from varying contract sizes, profit currencies, and account currencies. Wider stops reduce size ...

πŸ‘‰ Read | Signals | @mql5dev
❀4πŸ‘3⚑1
Most risk-sized EAs convert a volatility estimate into stops and lot size, then never verify whether the quoted loss limit is correct. A 99% limit is falsifiable on both breach frequency and breach independence, and clustering is the failure mode that drives account blowups.

A practical approach is a test battery, not a single count. Kupiec checks breach rate. Christoffersen checks one-step dependence. Duration checks multi-day clustering. Dynamic quantile checks remaining predictability, including whether breaches happen when limits are already wide. Expected shortfall checks breach magnitude.

On EURUSD, model quality depends more on scale responsiveness than on parametric vs empirical choice. Slow-moving scales tend to pass rate tests while failing arrival tests, which is the key signal to feed back into EA position sizing.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘9❀4🀩3⚑1πŸ”₯1
An MQL5 audit harness validates a volatility-targeting sizing rule before any orders exist. It checks unit correctness (std dev vs variance), information timing (no lookahead), and how close next-bar conditional risk stays to a 0.75% target under a 1.5 exposure cap.

Synthetic returns are generated with known next-bar variance: constant variance and GARCH(1,1) clustering. Rolling (20-bar mean square) and EWMA (Ξ»=0.94) estimators drive the same sizing function, alongside a fixed-exposure control.

A per-bar decision ledger separates the forecast-based request from audit-only β€œtruth” risk, tracking excess/shortfall, turnover, and cap binding. Fixtures include hand-checks and a cutoff test to ensure decisions don’t change when future data changes.

πŸ‘‰ Read | Signals | @mql5dev
❀9πŸ‘6πŸ”₯6🀩4⚑1
In MetaTrader 5 beta build 6360, we have expanded the AI Assistant capabilities. We have added over 40 new MCP tools that allow performing even more AI-powered actions directly within the trading platform:

β€’ Manage MQL5 services
β€’ Customize charts and objects
β€’ Analyze the market depth
β€’ Calculate margin and potential profits
β€’ Check parameters of trading operations
β€’ Handle alerts and financial news

The capabilities of the MQL5 language have been expanded for developers. New functions for working with complex numbers have been added, support for complex matrices and vectors has been expanded, mathematical calculations have been optimized and their numerical stability has been increased.

The strategy tester has been significantly enhanced: trade calculations, tick modeling, historical data handling, and distribution of tasks between agents have been improved.

We have also updated the deposits and withdrawals interface, improved handling custom symbols, charts and MQL5.com services.

Read more...
πŸ‘16❀13πŸ”₯13🀩2⚑1
This article builds an ATR-driven structure indicator for MT5 that defines potential reaction areas without waiting for repeated touches. Each structure anchors to a candle’s high/low midpoint, then sets fixed upper/lower boundaries using ATR(200) further stabilized by a 100-bar average and a multiplier.

Breaks are confirmed only on completed candles: an upside break occurs when lows move from at/below the upper boundary to above it; the downside case mirrors this on the lower boundary. A confirmed break resets the entire structure around the new midpoint and updates direction.

Inside the structure, mid-level zones and optional rules flag bullish/bearish midpoint crosses and failed breakouts (returns back inside after a boundary test). Visualization relies on rectangles, horizontal levels, and markers, with object naming and cleanup to keep charts respons...

πŸ‘‰ Read | Docs | @mql5dev
🀩18πŸ‘14❀13πŸ”₯4⚑1
Daily loss limits have two inputs: the amount and the reset moment. The reset is defined in a specific time zone and can differ from the broker server clock. Using TimeCurrent() and β€œserver midnight” shifts deals across days when the reset is at 00:00 CET/CEST or 17:00 New York, especially during mismatched US/EU DST weeks.

A compact MQL5 include set addresses one question: given a server timestamp, which trading day does it belong to, and where are that day’s start/end boundaries. Inputs are server zone, reset zone, and reset clock time.

Core parts: CTradingDay (day resolver with DST edge handling), CServerClockFit (infer server zone from Friday close bars), CDayTracker (detect boundary, snapshot balance/equity, rebuild from history), CDealDays (group history by resolved day). Validation includes unit checks against IANA dates, Strategy Tester runs, and a...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘18❀15πŸ”₯9🀩9
KAMA Ribbon aggregates multiple Kaufman Adaptive Moving Averages into a single view to track trend persistence across several horizons. Each line uses the standard KAMA formula with an Efficiency Ratio (ER): net price change over N bars divided by the sum of absolute bar-to-bar changes. ER near 1 implies directional movement; ER near 0 implies noise. ER drives the smoothing constant between fast and slow EMA bounds, so KAMA accelerates in trends and slows in ranges.

The ribbon draws up to 8 lines using increasing ER periods (default 5, 8, 11 … 26). A bullish state requires strict ordering with the fastest line above the rest plus visible fanning; bearish is the inverse. Crossed or tightly clustered lines indicate range or transition conditions. Ribbon width (fastest vs slowest distance) serves as a strength gauge, widening in stronger trends and narrowing...

πŸ‘‰ Read | VPS | @mql5dev
❀21πŸ‘13🀩10πŸ”₯9✍2
R-based trade management standardizes risk by defining R as the initial stop distance. A setting expressed in R remains consistent across instruments and price levels, allowing one rule set to scale across gold, Bitcoin, and FX.

In breakout testing on Bitcoin, moving the stop to break-even at +1R produced the largest single improvement. Win rate increased from roughly 20% to around 50%, while the longest losing streak dropped from 16–21 trades to 8–9. Many losses became scratch outcomes, with large winners largely unaffected.

Implementation stores R = |open βˆ’ SL| in a terminal global variable per ticket, persisting across restarts and later stop edits. At +BE_R the stop shifts to entry plus/minus Lock_R. At +TrailStart_R it trails Trail_R behind the reference price. Stops only move in the favorable direction. Reference price can be last closed bar on a chos...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀12🀩11πŸ‘8πŸ”₯5πŸ‘€2
A multi-timeframe dashboard summarizes trend and volatility using one row per timeframe and five signals per row.

EMA slope flags direction over the last k completed bars, while β€œvs EMA” checks whether the last close is above or below the EMA. Donchian position normalizes the close inside the last N-bar range (0–100%), with extremes highlighting breakout pressure. ATR percentile ranks current volatility against the last 250 bars to separate quiet from hot conditions.

A derived REGIME state marks UP when slope and price location agree, DOWN when both agree bearish, otherwise RANGE. Trend-breakout logic benefits most when higher timeframes align; mixed regimes often indicate correction or consolidation and justify lower risk.

Default inputs: EMA 100, slope look-back 3, Donchian 50, ATR rank 250. Implementation uses one EMA and one ATR handle per timef...

πŸ‘‰ Read | Quotes | @mql5dev
❀8🀩5πŸ‘4πŸ”₯3πŸ‘Œ1
An MQL5 port of the TradingView β€œRange Filter Buy and Sell 5min” has been released, matching the original Range Filter logic (DonovanWall), the simplified variant (guikroth), and the Pine v5 update (tvenn). The core calculation uses a double EMA of |close - close[1]| with SMA seeding (ta.ema-compatible), scaled by a multiplier. The filter only updates after price exceeds it by more than the smoothed range, with directional counters and one signal per side change using the original CondIni behavior.

Signals are non-repainting on MT5: Buy/Sell arrows are fixed on the bar close. Alerts are supported once per closed-bar signal (popup, sound, push, email). Target bands are plotted at filter +/- range, with automatic theme-safe coloring.

Includes a statistics panel showing trade-style outcomes (reverse on opposite signal), win rate, net after spread/commis...

πŸ‘‰ Read | Freelance | @mql5dev
❀14🀩4