MQL5 Algo Trading
586K subscribers
4.88K 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
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
πŸ”₯4❀3πŸ‘3⚑1
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
❀11πŸ‘6πŸ”₯2⚑1
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
πŸ‘5🀩4❀3πŸ”₯2⚑1
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
❀4πŸ‘4πŸ”₯4🀩2⚑1
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
❀6πŸ”₯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
❀3πŸ‘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
πŸ‘8❀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
❀7πŸ‘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...
πŸ‘14πŸ”₯13❀12🀩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
❀11πŸ‘11🀩11πŸ”₯2⚑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
❀11πŸ‘8πŸ”₯3🀩3
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
❀8✍1πŸ‘1