MQL5 Algo Trading
577K subscribers
4.54K photos
7 videos
4.55K 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
BacktestOverfitting.mqh calculates the Probability of Backtest Overfitting (PBO) for an MT5 optimization. PBO measures how often the pass that ranks best in one half of the history ends up in the lower half across all passes on the other half. High PBO indicates parameter selection driven mainly by noise rather than repeatable edge.

The implementation follows combinatorially symmetric cross-validation (Bailey, Borwein, Lopez de Prado, Zhu, 2017). Daily results are emitted per pass from OnTester() as frames, then consolidated into a matrix in OnTesterDeinit() after the final pass.

History is partitioned into S equal day blocks; all S/2 vs S/2 in-sample/out-of-sample combinations are evaluated (for S=16: C(16,8)=12,870 splits). Selection uses in-sample Sharpe (or mean with PBO_MEAN), then ranks the chosen pass out of sample to form logits. Output includes PBO, los...

πŸ‘‰ Read | Freelance | @mql5dev
❀11πŸ‘5πŸ”₯3😁2
Most β€œEA does not work” reports come from the trading environment, not the code: terminal AutoTrading disabled, netting vs hedging mismatch, unsupported filling mode, stops inside StopsLevel/FreezeLevel, or volume not matching step and limits.

TradeEnvCheck is a read-only script that generates a single report before installing or commissioning an EA. Run it once on a chart for the target symbol. Output goes to the Experts log, a short on-chart summary, and a text file at MQL5\Files\TradeEnvCheck_<symbol>.txt. No trading actions are performed.

The report captures account details, margin mode with hedging/netting implications, required trading permissions, and margin call/stop out levels. Per symbol it lists trade/execution/profit modes, price/contract parameters, supported filling modes (and the one to use), allowed order/expiration types, stops and freeze lev...

πŸ‘‰ Read | Forum | @mql5dev
❀12πŸ‘11πŸ”₯2🀩2
Single-layer neurons can learn linearly separable logic (AND/OR/NAND/NOR) but fail on XOR/XNOR, a concrete example of why β€œone neuron learns everything” is false.

The workaround borrows from digital electronics: build XOR as a small circuit composed of gates the neuron can already model. A NOR and an AND feed a second NOR, matching the XOR truth table.

In MQL5, this is implemented by storing separate weights and biases per internal gate, training only NOR and AND via finite-difference gradient updates. XOR output is then computed by composing these learned gates, effectively embedding a tiny network inside one neuronβ€”useful for designing non-linear decision logic in trading code without expanding model complexity.

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘8🀩6❀5
GapTracker scans any symbol and timeframe for opening gaps where the bar open is a configurable number of points away from the prior close. Gaps are categorized as daily (first bar of a new server day), weekend/holiday (first bar after a pause beyond a threshold, 36h default), and optionally intraday bar-to-bar.

Each gap is tracked until filled, defined as price trading back to the previous close. The gap bar counts, so same-bar closures report as 0 bars to fill, with an optional cutoff after N bars.

On-chart output uses rectangles from previous close to open, extended to the fill bar or the latest bar if still open, with size labels and configurable colors; filled gaps turn grey. Drawing is capped (200 recent gaps by default) to limit clutter, with hover tooltips for full details.

Realtime alerts support pop-up, push, and sound, while CSV logging r...

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘8❀7🀩6πŸ”₯5✍2
This follow-up completes a doubly linked list in MQL5 built around operator overloading, moving from β€œpush/read” basics to a safer, more usable container.

A class destructor is added to guarantee allocated nodes are released, eliminating MT5 resource warnings and enabling predictable lifetime management when lists go out of scope.

The list gains non-destructive element access: values can be read or modified by index without consuming nodes, with optional syntax that keeps call sites compact via overloaded operators.

For deletion, the implementation is refactored so a manager class owns list structure while node objects handle linkage, simplifying pointer updates. Edge-node removal initially crashes due to missing head/tail fixes, then is corrected with explicit boundary handling.

Finally, the article explores an advanced pattern: overloading subscript ...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ”₯9πŸ‘7❀3🀩3
Order Watchdog is a read-only MT5 Expert Advisor for account-wide monitoring. It never opens, closes, or modifies trades on live or demo charts. It only reads positions, orders, and deal history, then sends alerts when account state deviates from expected rules, including after reconnects, restarts, or broker-side issues.

Alert conditions include unknown magic numbers (with optional manual-trade allowance), duplicate positions per magic/symbol/direction, missing stop loss after a grace period, broker stop-outs, and stop-loss fills beyond a configured slippage limit. On startup it also reviews history to report unknown-magic opens and stop-outs that occurred while it was offline.

Configuration is based on a magic list supporting ranges, optional max-per-magic limits, and optional SL requirements. Alerts are throttled to one per issue until resolved, merged per sc...

πŸ‘‰ Read | Docs | @mql5dev
❀12πŸ‘10πŸ”₯6🀩6✍2
Color Harmony Algorithm (CHA), Zaeimi/Goddosian 2020, maps a metaheuristic population onto a 100-sector hue circle split into 10 groups, each with a leader β€œagent” in sector centers (5, 15, …, 95). Parent selection is constrained by five geometric harmony templates, enforcing cross-group structure and preserving diversity without relying on incidental clustering.

Execution alternates between concentration and dispersion using measured diversity Dpop versus a threshold Dth, damped after dispersion. Concentration generates linear mixtures with r1 in [0.1, 0.9] plus a decaying Gaussian perturbation (10% to 1% of range); without perturbation, candidates stay inside the initial convex hull and fail on harder landscapes.

Dispersion replaces near-center non-agents using a color-memory buffer of rejected candidates: Xnew = rcmΒ·XCM + (1-rcm)Β·Xold. An MQL5/C_A...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘11πŸ”₯9❀6🀩5
Temporal Motion Aggregation (TMA) reframes market data as an event stream with irregular intensity, instead of fixed bars. The pipeline segments events into overlapping windows, aligns segments to a common scale, then aggregates recurring micro-structures to suppress noise and preserve trend logic.

Current work moves from theory to implementation in MQL5 with OpenCL. Focus is the Motion Feature Encoder (MFE): two channels (raw events and cross-layer correlations) processed in true parallelism using a multi-window convolution layer, followed by SoftPlus and batch normalization per channel.

A new CNeuronTMAMFE class extends CNeuronConvOCL, builds an internal encoder chain (multi-window conv, activation, BN, second conv stage), then hands off to the parent convolution for final feature fusion. The forward pass is a strict layer-by-layer transfer with ea...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ”₯13❀7πŸ‘5🀩5
Volume remains a core market activity input, but it behaves differently across venues. Centralized exchanges provide real trade volume, while spot FX typically exposes tick volume as a proxy. Signal quality depends on broker feed, instrument, and regime, which becomes critical in automated systems.

A proposed pipeline targets volume change rather than level: Ln(volume+1) to compress spikes, then bar-to-bar delta, followed by arctan(x) to bound output within Β±Ο€/2. This yields scale-independent values that remain comparable across symbols and timeframes.

Execution logic uses a user threshold and three entry gates: positive-only, negative-only, or both. Order direction is confirmed by candle close versus open, not by signal sign. Exits support fixed SL/TP, an N-candle time/price rule, or a combined mode, with one position allowed at a time.

πŸ‘‰ Read | Quotes | @mql5dev
πŸ”₯9πŸ‘6❀4🀩4🀝2⚑1
Markets generate asynchronous event streams: quotes, trades, order updates. During volatility, event density rises and time no longer behaves like a uniform index. Point-based time series and bar aggregation lose microstructure ordering and smear causality.

TMA (Temporal Motion Aggregation), built for event-camera optical flow, maps well to market data as event processing. Key blocks are event splitting into short overlapping segments, linear temporal alignment to synchronize displaced activity, and motion-pattern aggregation to suppress noise and keep coherent movement.

Applied to finance, this becomes a way to build a temporally dense correlation field across micro-slices, aligned onto a common timeline, then aggregated into a stable estimate of direction and rate of change for capital flow.

πŸ‘‰ Read | Calendar | @mql5dev
πŸ”₯6❀5πŸ‘5🀩3πŸ‘Œ2
CPPI in MetaTrader 5 is a position sizing rule, not a buy/sell signal. It maps current equity to a floor, a cushion, and a multiplier-based target exposure, then scales a long position up or down without forecasts or indicators.

MT5 changes two assumptions. The β€œsafe” leg is just being flat, with no bond yield compounding the floor. Rebalancing is discrete per tick and typically gated by a rebalance band to reduce spread cost.

Implementation is split into stateless math (four formulas), a trading engine that handles lot rounding, netting vs hedging reduction, and cash-lock behavior, plus an indicator that runs a price-only simulation and cannot reproduce real equity history.

Key risks remain: gap breaches versus 1/m, cash-lock persistence, and minimum lot constraints on small accounts.

πŸ‘‰ Read | CodeBase | @mql5dev
❀6πŸ”₯6πŸ‘5πŸ†3🀩2
Manual PDF edits do not scale. Any byte shift breaks /Length, xref offsets, and startxref. Viewers may repair, render blank, or refuse the file, since the format does not validate those numbers.

The core rule is simple: file-describing numbers must be derived from the bytes already written, never maintained as literals. Current position equals buffer Length(); stream size equals content buffer Length().

CPdfBuffer owns a growable uchar array with doubling capacity, cheap reuse via Clear(), ASCII token output, PDF-safe number formatting, and fixed-width xref entry padding. Save writes only used length to avoid trailing zeros.

CPdfWriter allocates object numbers, records each object offset from buffer Length() at BeginObject(), supports forward references, and emits xref from observed offsets. Finish fails if allocated objects were never written or if nesting is ...

πŸ‘‰ Read | Calendar | @mql5dev
🀩6πŸ‘4❀3
Candlesticks show price movement, but not where volume accumulated. A volume-at-price profile solves that by producing reproducible levels: point of control, value area bounds, and volume split above/below current price.

An MQL5 indicator can approximate volume distribution per bar using tick or real volume, with two allocation policies: spread volume across the bar range or concentrate it at the close with a neighbor split. A rolling window is binned into horizontal price levels, then POC and value area are computed and published to six buffers for EAs and alerts.

Visualization includes a heatmap behind candles plus a live side profile with tagged levels. Performance is handled via ring-buffer column storage, cached base-layer rendering, alpha blending, and selective redraw on viewport changes.

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘8❀6πŸ”₯2🀯1
This part upgrades an MT5 news filter from β€œall High events are equal” to a tiered, rule-driven system that handles releases with longer market impact, like rate decisions plus statements and press conferences.

Events are classified once through a shared function used by both the live economic calendar and the Strategy Tester CSV, removing duplicated logic and keeping backtests aligned with live trading.

A new ordered tier scale preserves the calendar’s levels and adds a Special tier above High. Each event now carries its own before/after window, so Special events can pause trading longer without widening every High release.

Special handling is defined as data: a rule table (optionally overridden via CSV) matches events by currency plus name/code (substring or exact), can promote/demote tiers, and can override windows. A companion script prints the broker’...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘8❀4🀩2
Building an MEXC Futures integration in MQL5 starts with a reusable REST layer: configure MetaTrader 5 to allow WebRequest() calls to https://api.mexc.com, then centralize GET request execution, HTTP handling, JSON deserialization, and validation of the common success/code/message fields.

JSON parsing is based on the CJAVal library, extended to make type conversion safe. The key improvement is overloads that validate JSON types before assigning outputs, preventing β€œmissing field becomes 0” bugs. Numeric handling also avoids silent precision loss by only converting integers to double when they are exactly representable.

With these components, public endpoints can be added incrementally by writing only endpoint-specific parsing. The first example uses /api/v1/contract/ping to fetch server time (ms Unix), useful for clock alignment and time-sensitive trad...

πŸ‘‰ Read | Calendar | @mql5dev
❀7🀩5πŸ‘3πŸ”₯1
MetaTrader 5 can calculate many indicators internally via Technical Indicator Functions, so custom indicator code often only needs handle setup and CopyBuffer into an output buffer.

A minimal iMA-based indicator can match the platform MA, while still allowing runtime changes to color, line style, thickness, and applied price through standard indicator inputs.

CopyBuffer parameters matter. By limiting the copied range, the MA can be rendered only for the last N bars, producing a rolling segment tied to the MA period.

To avoid recompiles, MA period/type/price should be exposed as input parameters with clear labels. A common visual glitch comes from uninitialized or stale buffer values when copying partial ranges; buffer management is required to prevent artifacts.

πŸ‘‰ Read | VPS | @mql5dev
❀11πŸ‘6πŸ‘3🀩3πŸ”₯1
Single-neuron models still hit hard limits: some simple-looking patterns (like XOR) cannot be learned without changing the architecture. The article reframes a neuron as linear regression and focuses on why scaling inputs and training loops quickly raises runtime and resource use, especially when code must be rewritten for every new parameter.

It then derives gradient descent from the least-squares error, showing how separate partial updates handle weight and bias. A MetaTrader 5 implementation trains a 1-in/1-out neuron with both linear regression and gradient descent and compares results: regression converges faster, while gradient descent can yield a slightly better weight estimate, with error behavior differing by method.

Practical takeaway for algo trading code: optimization is workload-dependent; choose the training approach based on data shape and performa...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀6πŸ‘5πŸ”₯3🀩3
A GPL-3.0 MT4 port of the β€œChandelier Exit” indicator, kept line-by-line with the original logic and default inputs (ATR Period 22, Multiplier 3.0, extremums from Close enabled). ATR is computed as multiplier Γ— ATR(length) using Wilder RMA seeded by an SMA.

Long stop is highest(close/high, length) minus ATR and only ratchets upward while the prior close remains above the prior stop. Short stop is lowest(close/low, length) plus ATR and only ratchets downward while the prior close remains below the prior stop. Direction flips to long when price closes above the previous short stop, and to short when it closes below the previous long stop; otherwise state is preserved.

MT4 additions include a signal statistics panel with spread/commission-aware figures, optional session filter with shading and end-of-session close, tooltipped trade marks, alerts, and EA...

πŸ‘‰ Read | Calendar | @mql5dev
❀8πŸ‘7πŸ”₯7
A Trade Replay Tool for MetaTrader 5 is outlined as an MQL5 indicator that combines candle-by-candle playback with automatic reconstruction of historical trades.

Key additions over a basic bar replay include adjustable playback speed, anchor-based range selection (single or dual anchor), and trade synchronization. Historical deals within the selected interval are retrieved and converted into replay records preserving entry/exit time, direction, price, volume, SL, and TP.

The workflow covers initialization (buffers, UI, timer), event-driven control via OnChartEvent(), interactive anchor movement, deal extraction from account history, progressive candle reveal, and paper-position lifecycle management. Playback uses UI controls and hotkeys (Ctrl +/- for speed, Shift+E for dual-anchor mode), then restores the chart state when replay is disabled.

πŸ‘‰ Read | Docs | @mql5dev
❀9πŸ”₯5🀩3πŸ‘2
An MT4 line-by-line port of the TradingView β€œRange Filter Buy and Sell 5min” (open-source). Core logic matches the original: Smoothed range = EMA(EMA(|close βˆ’ close[1]|, period), 2Γ—periodβˆ’1) Γ— multiplier, with EMA seeding via SMA consistent with ta.ema.

The range filter remains fixed until price exceeds it by more than the smoothed range, then steps to maintain that distance. Direction counters drive long/short conditions, with Buy/Sell printed once per side change using the original CondIni behavior. Target bands are filter Β± range, with original-style bar coloring.

MT4 additions include a signal statistics panel (trades, win rate, net after spread/commission, profit factor, losing streak, drawdown, cost per trade), optional session filter with shading and end-of-session close, tooltipped trade marks, alerts, and iCustom buffers (5 Buy, 6 Sell, 11 f...

πŸ‘‰ Read | VPS | @mql5dev
❀11πŸ‘5πŸ”₯3🀩2
MetaTrader 5 indicators fall into two groups: built-ins callable directly from MQL5, and custom indicators used to encode a specific market rule set.

A common requirement is bundling multiple moving averages into one indicator so they can be added and removed as a unit, without templates.

A naive implementation scales poorly: repeated input blocks, per-MA handle/buffer declarations, duplicated init/release code, and manual changes to plot/buffer counts that risk chart glitches.

Refactoring focuses on compiler-assisted structure: consolidate repeated calls, move fixed MA parameters into const structure instances, and use const arrays of structs. In MQL5, const applies to the declared instance, not the struct type, and struct initializer order must match member order to avoid silent misconfiguration.

πŸ‘‰ Read | Quotes | @mql5dev
❀9πŸ‘7πŸ”₯5🀩1