DataSnooping.mqh adds data-snooping controls to strategy and parameter optimizations, addressing whether the top result is statistically better than a benchmark or simply the best outcome among many trials.
It implements Hansen’s SPA test, White’s Reality Check, the Romano-Wolf StepM procedure, and the Hansen-Lunde-Nason model confidence set. Resampling is done with a stationary bootstrap to preserve dependence in daily returns, with a configurable seed and no DLL requirement.
Components include CSuperiorAbility (SPA p-values, Reality Check, critical values, and StepM results), CModelConfidenceSet (per-strategy p-values and best-set selection using R or max statistics), and CStationaryBootstrap (bootstrap indices and efficient mean computation). A provided example generates 100 moving-average rules or reads CSV returns, illustrating how single-test...
👉 Read | Calendar | @mql5dev
It implements Hansen’s SPA test, White’s Reality Check, the Romano-Wolf StepM procedure, and the Hansen-Lunde-Nason model confidence set. Resampling is done with a stationary bootstrap to preserve dependence in daily returns, with a configurable seed and no DLL requirement.
Components include CSuperiorAbility (SPA p-values, Reality Check, critical values, and StepM results), CModelConfidenceSet (per-strategy p-values and best-set selection using R or max statistics), and CStationaryBootstrap (bootstrap indices and efficient mean computation). A provided example generates 100 moving-average rules or reads CSV returns, illustrating how single-test...
👉 Read | Calendar | @mql5dev
❤13👍6🤩3🔥2
Session Range Breakout displays the intraday high/low for up to three configurable sessions and keeps those levels visible after the session ends by extending them to the right.
Sessions are defined by start hour (inclusive) and end hour (exclusive) in server time. While a session is active, the running high and low are tracked. After the close, both levels are finalized and drawn as dotted lines, with optional “NAME H / NAME L” labels and an optional thin range rectangle. Values are not recalculated later, so the output does not repaint.
Configuration includes per-session enable/disable, name, hours, and color, plus history depth, extension length (bars), and line width. Optional features cover labels, the range rectangle, and alerts (popup, sound, push) when a bar closes outside a session range. An auto-zoom option can rescale the chart on load to ...
👉 Read | VPS | @mql5dev
Sessions are defined by start hour (inclusive) and end hour (exclusive) in server time. While a session is active, the running high and low are tracked. After the close, both levels are finalized and drawn as dotted lines, with optional “NAME H / NAME L” labels and an optional thin range rectangle. Values are not recalculated later, so the output does not repaint.
Configuration includes per-session enable/disable, name, hours, and color, plus history depth, extension length (bars), and line width. Optional features cover labels, the range rectangle, and alerts (popup, sound, push) when a bar closes outside a session range. An auto-zoom option can rescale the chart on load to ...
👉 Read | VPS | @mql5dev
❤8👍6🤩4🔥1
Swap is presented as a single value in the terminal, but it consists of two components: carry (interest-rate differential) and broker markup (financing fee). Carry changes sign between long and short, while markup is paid in both directions.
Given long and short swaps for a symbol, markup and carry can be derived as:
markup = -(long + short) / 2
carry = (long - short) / 2
The script normalizes all swap calculation modes into one comparable metric: annual percentage of the position notional. This enables direct comparison across FX, metals, indices, and commodities.
This matters for multi-week holding strategies where daily markup compounds into a material drag. A 0.75% annual markup on FX or 2.5% on index CFDs can eliminate expected returns even when price-only backtests look acceptable.
Output includes an on-chart table with risk bands, a full ranked...
👉 Read | VPS | @mql5dev
Given long and short swaps for a symbol, markup and carry can be derived as:
markup = -(long + short) / 2
carry = (long - short) / 2
The script normalizes all swap calculation modes into one comparable metric: annual percentage of the position notional. This enables direct comparison across FX, metals, indices, and commodities.
This matters for multi-week holding strategies where daily markup compounds into a material drag. A 0.75% annual markup on FX or 2.5% on index CFDs can eliminate expected returns even when price-only backtests look acceptable.
Output includes an on-chart table with risk bands, a full ranked...
👉 Read | VPS | @mql5dev
❤14👍7🤩4🔥3🎉1
A non-repainting three-bar Fair Value Gap detector for MT5 is available, based strictly on closed-bar data. Each imbalance is drawn as a rectangle with an optional 50% Consequent Encroachment line. Gap levels are derived from three closed candles (pre-impulse, impulse, and the candle that leaves the imbalance) and are persisted without later rewriting.
The gap lifecycle is implemented as an explicit state machine. In TRIM mode, a gap is anchored to the first closed bar that trades into it, preventing rectangles from extending into future bars after mitigation. Mitigation display is selectable: TRIM shortens, DELETE removes, DIM greys out, and NONE leaves full length. Open gaps can be forward-extended via a configurable bar count.
Processing is incremental, scanning only newly closed bars instead of rebuilding history on each tick. A self-audit can re...
👉 Read | Quotes | @mql5dev
The gap lifecycle is implemented as an explicit state machine. In TRIM mode, a gap is anchored to the first closed bar that trades into it, preventing rectangles from extending into future bars after mitigation. Mitigation display is selectable: TRIM shortens, DELETE removes, DIM greys out, and NONE leaves full length. Open gaps can be forward-extended via a configurable bar count.
Processing is incremental, scanning only newly closed bars instead of rebuilding history on each tick. A self-audit can re...
👉 Read | Quotes | @mql5dev
❤9👍7🔥3🏆3🤩2
A trade manager for MetaTrader 5 that splits take profit into up to five levels (TP1–TP5) for any existing position on XAUUSD, FX pairs, indices, or crypto. Distances can be set in points or as multiples of stop loss (R), with per-level close percentages and optional “close remainder on last active level”.
The tool monitors manual trades and positions opened by other experts, with filtering by symbol scope and magic number. It never opens trades and performs partial closes immediately on level hits, rounding volumes to broker lot step and closing the position fully if the remainder would fall below minimum lot. Taken levels are persisted via terminal global variables to avoid repeats after restarts.
Risk controls include optional automatic stop loss assignment, breakeven move after a selected TP level with offset, and trailing stop that activates only after...
👉 Read | Signals | @mql5dev
The tool monitors manual trades and positions opened by other experts, with filtering by symbol scope and magic number. It never opens trades and performs partial closes immediately on level hits, rounding volumes to broker lot step and closing the position fully if the remainder would fall below minimum lot. Taken levels are persisted via terminal global variables to avoid repeats after restarts.
Risk controls include optional automatic stop loss assignment, breakeven move after a selected TP level with offset, and trailing stop that activates only after...
👉 Read | Signals | @mql5dev
❤12👍10🤩4🔥3
GM Matrix Monitor is a read-only dashboard for supervising multi-EA accounts without repeatedly opening the terminal. It aggregates per-magic net P/L by combining closed deals with current floating profit, and presents each EA’s running result in a single column.
Risk visibility is provided via real-time drawdown, calculated from current equity against a configurable reference balance. It also tracks realized losses since day start against a daily-loss cap, and signals proximity to freeze and liquidation thresholds using color states (green/amber/red) based on user-defined percentages.
Setup consists of attaching the panel to a chart, entering a comma-separated magic list, selecting a base equity (or current balance), and configuring freeze, liquidation, and daily-loss limits. The tool reads history and positions only; it does not send, modify, or close ord...
👉 Read | Forum | @mql5dev
Risk visibility is provided via real-time drawdown, calculated from current equity against a configurable reference balance. It also tracks realized losses since day start against a daily-loss cap, and signals proximity to freeze and liquidation thresholds using color states (green/amber/red) based on user-defined percentages.
Setup consists of attaching the panel to a chart, entering a comma-separated magic list, selecting a base equity (or current balance), and configuring freeze, liquidation, and daily-loss limits. The tool reads history and positions only; it does not send, modify, or close ord...
👉 Read | Forum | @mql5dev
❤8👍7🤩7🔥6
EAs that trade New York hours need a reliable broker server offset to UTC. Many brokers run UTC+2 in winter and UTC+3 in summer, but apply either US or EU daylight rules, creating 1-hour errors during the spring and autumn gaps between clock changes.
TimeTradeServer() - TimeGMT() works on live charts but depends on the local PC clock and becomes unusable in Strategy Tester, where TimeGMT() mirrors simulated server time. BrokerClock.mqh instead infers the offset from H1 history by using the known weekend close for CME-linked symbols: the last H1 bar before the weekend ends at 17:00 New York, which maps to a specific UTC instant.
The library scores candidate offset rules (fixed, US DST, EU DST) across up to 60 weekends, prioritizing the last 8 weeks, then breaks ties with the full set. It provides current server offset, live cross-check offset, calendar-based NY/L...
👉 Read | Quotes | @mql5dev
TimeTradeServer() - TimeGMT() works on live charts but depends on the local PC clock and becomes unusable in Strategy Tester, where TimeGMT() mirrors simulated server time. BrokerClock.mqh instead infers the offset from H1 history by using the known weekend close for CME-linked symbols: the last H1 bar before the weekend ends at 17:00 New York, which maps to a specific UTC instant.
The library scores candidate offset rules (fixed, US DST, EU DST) across up to 60 weekends, prioritizing the last 8 weeks, then breaks ties with the full set. It provides current server offset, live cross-check offset, calendar-based NY/L...
👉 Read | Quotes | @mql5dev
👍16❤13🔥8🤩6
An ADX-based indicator automates detection of consolidation ranges by tracking trend strength decay. It replaces discretionary price-action calls with a repeatable rule set that flags when a prior trend is losing momentum and price action becomes choppy, where risk typically increases for in-range trading.
Sensitivity is controlled by InpSlopeBars, comparing ADX[shift] to ADX[shift - InpSlopeBars]. Lower values react faster and add noise; higher values smooth readings and favor broader fades.
Confirmation uses InpDeclineBars to require multiple consecutive negative ADX slope samples before opening a range.
Range termination is managed by InpEndOnStrengthRise (optional close on strength recovery) or by price breakout only. Breakout validation uses InpBreakoutPercent, while InpMinRangeBars enforces a minimum range duration before drawing.
👉 Read | CodeBase | @mql5dev
Sensitivity is controlled by InpSlopeBars, comparing ADX[shift] to ADX[shift - InpSlopeBars]. Lower values react faster and add noise; higher values smooth readings and favor broader fades.
Confirmation uses InpDeclineBars to require multiple consecutive negative ADX slope samples before opening a range.
Range termination is managed by InpEndOnStrengthRise (optional close on strength recovery) or by price breakout only. Breakout validation uses InpBreakoutPercent, while InpMinRangeBars enforces a minimum range duration before drawing.
👉 Read | CodeBase | @mql5dev
❤14👍11🤩11🔥10
The article builds an MT5 Expert Advisor that trains a fully connected CNet model to predict Bill Williams fractal pivots one bar earlier than the standard indicator’s confirmation delay. It frames the task as supervised learning: feed the latest market context, then label the previous bar after the next candle closes.
Inputs combine normalized candle features (Close/High/Low relative to Open), time components (month, hour, weekday), volumes, and four standard oscillators (RCI, CCI, ATR, MACD), producing 12 values per bar across a configurable history window. The network uses 4 hidden layers starting at 1000 neurons and shrinking by 70% per layer with a floor of 20.
Two output designs are compared: a single tanh neuron encoding buy/sell/none, or a 3-neuron probability classifier. Implementation details include loading a saved trained network, tracking MSE and hit...
👉 Read | Docs | @mql5dev
Inputs combine normalized candle features (Close/High/Low relative to Open), time components (month, hour, weekday), volumes, and four standard oscillators (RCI, CCI, ATR, MACD), producing 12 values per bar across a configurable history window. The network uses 4 hidden layers starting at 1000 neurons and shrinking by 70% per layer with a floor of 20.
Two output designs are compared: a single tanh neuron encoding buy/sell/none, or a 3-neuron probability classifier. Implementation details include loading a saved trained network, tracking MSE and hit...
👉 Read | Docs | @mql5dev
❤15👍14🔥8🤩8
This article refactors an MQL5 SQLite helper to make SQL script execution cleaner, testable, and future-proof. The original design is reworked into a single C_DB_SQL class with a constructor that opens the database (optionally in-memory) and a destructor that guarantees proper close, reducing lifecycle bugs.
Script execution is improved by returning status text instead of printing to the terminal, enabling UI-agnostic error reporting. Failures are traced back to the exact script line, while successful runs return null, keeping calling code simple.
The key upgrade is supporting SQL embedded as an MQL5 resource. The implementation converts resource text into a byte buffer, parses it into statements, and reuses one private ExecSQL pipeline for both files and resources. This encapsulation keeps the public API stable while allowing future backends (e.g., client-s...
👉 Read | Forum | @mql5dev
Script execution is improved by returning status text instead of printing to the terminal, enabling UI-agnostic error reporting. Failures are traced back to the exact script line, while successful runs return null, keeping calling code simple.
The key upgrade is supporting SQL embedded as an MQL5 resource. The implementation converts resource text into a byte buffer, parses it into statements, and reuses one private ExecSQL pipeline for both files and resources. This encapsulation keeps the public API stable while allowing future backends (e.g., client-s...
👉 Read | Forum | @mql5dev
❤12🤩9👍8🔥8🎉2😁1
Live tick transfer from MetaTrader 5 to Python can avoid per-tick allocations by sharing an Apache Arrow columnar layout in shared memory and importing it with zero copies.
Part 1 implemented the MT5 writer: two double-buffered slots, fixed headers, six 8-byte columns with padded buffers, and a lock-free seqlock where odd generation means “writing” and even means “stable”.
This follow-up implements the Python reader with ctypes definitions of ArrowArray and ArrowSchema, points their buffers directly into an mmap, and builds a pyarrow.RecordBatch without struct.unpack loops or boxing.
A standalone benchmark reproduces the exact memory layout locally and compares the zero-copy import path against legacy field-by-field unpacking across batch sizes.
Notes: schema and column-count contracts must match; seqlock assumes correct memory ordering; imported batch...
👉 Read | NeuroBook | @mql5dev
Part 1 implemented the MT5 writer: two double-buffered slots, fixed headers, six 8-byte columns with padded buffers, and a lock-free seqlock where odd generation means “writing” and even means “stable”.
This follow-up implements the Python reader with ctypes definitions of ArrowArray and ArrowSchema, points their buffers directly into an mmap, and builds a pyarrow.RecordBatch without struct.unpack loops or boxing.
A standalone benchmark reproduces the exact memory layout locally and compares the zero-copy import path against legacy field-by-field unpacking across batch sizes.
Notes: schema and column-count contracts must match; seqlock assumes correct memory ordering; imported batch...
👉 Read | NeuroBook | @mql5dev
❤7🤩6👍4🔥4⚡1
RAFT is adapted from optical flow to market forecasting by treating past vs present as two “frames” and iteratively refining a prediction instead of producing a one-shot output. The core gain is an all-pairs correlation field that compares current features against a historical stack, capturing global interactions rather than local matches.
A key upgrade for finance is replacing fixed context with a recurrent contextual encoder, letting the model track regime shifts (volatility, liquidity, correlation changes) as an internal state. This keeps context current without the cost of expanding the entire history window.
In MQL5, the CNeuronRAFT object assembles encoders, multiscale stack correlation, concatenation, GRU-based refinement, and a stabilizing residual path. The model predicts a delta update each iteration, improving training stability and making real-t...
👉 Read | VPS | @mql5dev
A key upgrade for finance is replacing fixed context with a recurrent contextual encoder, letting the model track regime shifts (volatility, liquidity, correlation changes) as an internal state. This keeps context current without the cost of expanding the entire history window.
In MQL5, the CNeuronRAFT object assembles encoders, multiscale stack correlation, concatenation, GRU-based refinement, and a stabilizing residual path. The model predicts a delta update each iteration, improving training stability and making real-t...
👉 Read | VPS | @mql5dev
❤10🤩5👍4
This article breaks down why prop-firm protection logic in MT5 often fails even when the math is correct: rules interfere with each other, actions change the data mid-pass, and state resets/reboots silently reopen risk.
The core fix is architectural. All firm checks read a single account snapshot struct built once per tick, passed as a const reference. Rules never query live account state and never act directly; they only return a verdict with separate severity and directive so advisory payout constraints don’t trigger forced closes.
It adds a firm-time session clock (non-midnight rollovers), a daily profit ledger aligned to the firm’s day for consistency/min-days rules, explicit enable flags plus validation, two distinct reset paths (challenge vs intraday), and built-in serialization so a VPS reboot can’t refill drawdown budget.
👉 Read | AppStore | @mql5dev
The core fix is architectural. All firm checks read a single account snapshot struct built once per tick, passed as a const reference. Rules never query live account state and never act directly; they only return a verdict with separate severity and directive so advisory payout constraints don’t trigger forced closes.
It adds a firm-time session clock (non-midnight rollovers), a daily profit ledger aligned to the firm’s day for consistency/min-days rules, explicit enable flags plus validation, two distinct reset paths (challenge vs intraday), and built-in serialization so a VPS reboot can’t refill drawdown budget.
👉 Read | AppStore | @mql5dev
👍10❤7🤩3
An MT5 exit module adapts Longstaff‑Schwartz LSM from American option pricing to trade management. The decision is framed as exercise (close now, realize PnL net costs) versus continuation, with a forced horizon to supply expiry.
Calibration uses recent log‑returns to estimate per‑bar drift and volatility, then simulates GBM paths. Backward induction fits continuation value via regression on in‑the‑money simulated paths only; the live position is compared once at step zero, allowing exits on losers if continuation is worse. Hard backstops remain: max holding period and fixed stop distance.
Implementation is native MQL5: no DLLs or libraries. Least squares uses ridge‑regularized normal equations with Gauss‑Jordan and pivoting, with explicit failure handling. Components are split into linear algebra, engine, EA, and an indicator that plots the exerci...
👉 Read | VPS | @mql5dev
Calibration uses recent log‑returns to estimate per‑bar drift and volatility, then simulates GBM paths. Backward induction fits continuation value via regression on in‑the‑money simulated paths only; the live position is compared once at step zero, allowing exits on losers if continuation is worse. Hard backstops remain: max holding period and fixed stop distance.
Implementation is native MQL5: no DLLs or libraries. Least squares uses ridge‑regularized normal equations with Gauss‑Jordan and pivoting, with explicit failure handling. Components are split into linear algebra, engine, EA, and an indicator that plots the exerci...
👉 Read | VPS | @mql5dev
❤9👍3🤩3👨💻2
A–B–C–D recognition can be correct and still generate triggers that are late, rare, or carry high adverse movement. Without measurement, A–B relationships cannot be compared and filtered with evidence.
A measurement layer can be added without changing pattern rules. For each completed D window, record C setup time, D confirmation time, breakout distance versus C, and directional MFE/MAE from processed M1 ranges, including the confirmation bar range. Also track trigger rate per A–B relationship.
Implementation is done in an MT5 EA with recognition, measurement, reporting, and execution separated. Trading stays disabled by default behind an explicit gate. The higher-timeframe open after D is the commit boundary; detach writes a snapshot with record_kind so incomplete windows do not pollute completed statistics. CSV export includes run_id, grouped counters, an...
👉 Read | CodeBase | @mql5dev
A measurement layer can be added without changing pattern rules. For each completed D window, record C setup time, D confirmation time, breakout distance versus C, and directional MFE/MAE from processed M1 ranges, including the confirmation bar range. Also track trigger rate per A–B relationship.
Implementation is done in an MT5 EA with recognition, measurement, reporting, and execution separated. Trading stays disabled by default behind an explicit gate. The higher-timeframe open after D is the commit boundary; detach writes a snapshot with record_kind so incomplete windows do not pollute completed statistics. CSV export includes run_id, grouped counters, an...
👉 Read | CodeBase | @mql5dev
❤5👍2🤩1