A utility script generates a CSV report with one row per closed position, grouped by DEAL_POSITION_ID, supporting hedging and netting accounts. Output columns include ticket, symbol, direction, entry/exit timestamps, entry/exit prices, profit in points, MFE/MAE in points, capture ratio, bars spanned, and holding time.
Key inputs: InpDias (history days, default 365), InpSoEsteAtivo (restrict to chart symbol or read all symbols), InpTF (timeframe used for excursion measurement, default current), and InpArquivo (CSV name under MQL5\Files).
A summary is printed to the Experts log: trade count, winners/losers, net result, median MFE/MAE for winners, median MAE for losers, median capture ratio, median bars per trade, single-bar trade count, and a count of trades not measurable due to missing historical bars (reported explicitly).
Excursions are computed from bar...
π Read | Docs | @mql5dev
Key inputs: InpDias (history days, default 365), InpSoEsteAtivo (restrict to chart symbol or read all symbols), InpTF (timeframe used for excursion measurement, default current), and InpArquivo (CSV name under MQL5\Files).
A summary is printed to the Experts log: trade count, winners/losers, net result, median MFE/MAE for winners, median MAE for losers, median capture ratio, median bars per trade, single-bar trade count, and a count of trades not measurable due to missing historical bars (reported explicitly).
Excursions are computed from bar...
π Read | Docs | @mql5dev
β€16π10π₯2π€©1
CME gold has a daily maintenance break. Across an 11-year hourly sample, the first hour after the reopen shows a repeatable upward drift, while other hours are near flat.
An EA was built around a single rule: buy at the reopen, hold a fixed time, use a server-side stop sized by volatility, then stand down. One trade per session. No averaging, grid, martingale, or recovery logic.
Initial research assumed ~19 points round-trip cost and measured +3.34 bps with t=7.40 (59.3% wins, PF 1.63, 11/11 positive years). Real-tick testing showed the reopen cost is closer to ~60 points because bar-level spread summaries understate the reopen spread. After correction: +1.60 bps, t=3.42, ~50.8% wins, PF 1.30, 10/11 positive years.
Sizing for ~20% drawdown gives ~3.3%/yr with ~4.6% max drawdown, Sharpe ~1.23, ~200 trades/yr, implying non-trivial negative-year risk. Validat...
π Read | Docs | @mql5dev
An EA was built around a single rule: buy at the reopen, hold a fixed time, use a server-side stop sized by volatility, then stand down. One trade per session. No averaging, grid, martingale, or recovery logic.
Initial research assumed ~19 points round-trip cost and measured +3.34 bps with t=7.40 (59.3% wins, PF 1.63, 11/11 positive years). Real-tick testing showed the reopen cost is closer to ~60 points because bar-level spread summaries understate the reopen spread. After correction: +1.60 bps, t=3.42, ~50.8% wins, PF 1.30, 10/11 positive years.
Sizing for ~20% drawdown gives ~3.3%/yr with ~4.6% max drawdown, Sharpe ~1.23, ~200 trades/yr, implying non-trivial negative-year risk. Validat...
π Read | Docs | @mql5dev
π10β€7π₯2
Reusable MQL5 trade-management blocks were added to the Bootstrap library to standardize trailing-stop and break-even handling across EAs. The helpers focus on safe stop updates: validating broker stop levels, preventing βreverseβ stop loosening when indicator values change, converting money targets into price distances correctly, and applying consistent symbol/magic and BUY/SELL filtering.
Trailing is covered in multiple styles: fixed points with step control, moving-average, ATR (volatility-adaptive with anti-reverse protection), Parabolic SAR, monetary trailing based on account currency, and periodic trailing that tightens stops over time rather than by price movement.
Break-even is implemented as a one-time stop move after an activation threshold, with optional offsets, available in both point-based and money-based forms. The result is less duplicated c...
π Read | Freelance | @mql5dev
Trailing is covered in multiple styles: fixed points with step control, moving-average, ATR (volatility-adaptive with anti-reverse protection), Parabolic SAR, monetary trailing based on account currency, and periodic trailing that tightens stops over time rather than by price movement.
Break-even is implemented as a one-time stop move after an activation threshold, with optional offsets, available in both point-based and money-based forms. The result is less duplicated c...
π Read | Freelance | @mql5dev
β€15π7π₯4β1
M1 OHLC backtests rely on an implicit intra-bar path model. Since OHLC does not record the sequence of prints, the assumed order only becomes material when the bar that closes a trade touches both stop and target, leaving the outcome dependent on the model rather than the market.
A script quantifies this error rate by opening a virtual bracket each minute around the bar open, then advancing until one level is reached. If the closing minute touches both levels, the assumed OHLC path is checked against real tick history. Multiple bracket sizes are swept to produce an error curve.
XAUUSD results over 30 days (27,844 virtual trades): 20pt 62.6% contested, 23.84% wrong; 50pt 30.1%, 8.25%; 100pt 8.9%, 1.66%; 200pt 1.5%, 0.18%; 500pt 0.1%, 0.00%; 1000pt none.
Inputs include symbol, days, bracket list, horizon, sampling step, and optional CSV of mis-resolved cases...
π Read | Freelance | @mql5dev
A script quantifies this error rate by opening a virtual bracket each minute around the bar open, then advancing until one level is reached. If the closing minute touches both levels, the assumed OHLC path is checked against real tick history. Multiple bracket sizes are swept to produce an error curve.
XAUUSD results over 30 days (27,844 virtual trades): 20pt 62.6% contested, 23.84% wrong; 50pt 30.1%, 8.25%; 100pt 8.9%, 1.66%; 200pt 1.5%, 0.18%; 500pt 0.1%, 0.00%; 1000pt none.
Inputs include symbol, days, bracket list, horizon, sampling step, and optional CSV of mis-resolved cases...
π Read | Freelance | @mql5dev
π6β€3β1π₯1π€©1
This article turns Jesse Livermoreβs βMarket Keyβ into a rule-driven MT5 Expert Advisor using a state machine: uptrend, natural reaction, natural rally, and downtrend. Signals come from a frozen consolidation βpivotβ that must break by an ATR-based clearance on expanding volume, with a strict one-bar reversal filter.
Position building is explicit pyramiding across four tranches, sized from a single stored full-lot calculation to keep risk consistent. Adds occur only after follow-through and a low-volume reaction, then a high-volume resumption; exits trigger immediately on βabnormalβ against-trend ATR moves with elevated volume, not just stop hits.
Correctness is enforced in OnInit(): tranche percents must total 100, parameters must be sane, and the account must support hedging so each tranche remains a separate ticket. Known gap: no state recovery after ter...
π Read | AlgoBook | @mql5dev
Position building is explicit pyramiding across four tranches, sized from a single stored full-lot calculation to keep risk consistent. Adds occur only after follow-through and a low-volume reaction, then a high-volume resumption; exits trigger immediately on βabnormalβ against-trend ATR moves with elevated volume, not just stop hits.
Correctness is enforced in OnInit(): tranche percents must total 100, parameters must be sane, and the account must support hedging so each tranche remains a separate ticket. Known gap: no state recovery after ter...
π Read | AlgoBook | @mql5dev
β€23π4β‘2π€©2π₯1
Gold trading automation often fails due to broker-side inconsistencies in symbol naming, contract size, and pricing format. Symbols may be XAUUSD, GOLD, XAUUSD.m, XAUUSDpro, or variants, while contracts can represent 100, 10, or 1 ounce, and quotes may use two or three digits.
A robust approach queries the terminal instead of relying on hardcoded constants. Symbol detection ranks available instruments by name match, avoids false positives such as XAGUSD, and optionally accepts an explicit override for non-standard broker symbols. Full specification is read from the terminal: contract size, digits, point, tick size, tick value loss, volume limits/steps, and stops/freeze levels.
Risk functions convert distance into account-currency loss and compute volume from money-at-risk via tick value loss, rounding down to volume steps and returning zero if even the minimu...
π Read | Forum | @mql5dev
A robust approach queries the terminal instead of relying on hardcoded constants. Symbol detection ranks available instruments by name match, avoids false positives such as XAGUSD, and optionally accepts an explicit override for non-standard broker symbols. Full specification is read from the terminal: contract size, digits, point, tick size, tick value loss, volume limits/steps, and stops/freeze levels.
Risk functions convert distance into account-currency loss and compute volume from money-at-risk via tick value loss, rounding down to volume steps and returning zero if even the minimu...
π Read | Forum | @mql5dev
β€18π5π€©1
This EA update removes two hidden assumptions that break real trading workflows: risk is not always β% of account,β and trades do not always enter at the current price. The code now exposes these as explicit choices and builds a cleaner interface for testing and reuse.
Risk per trade supports three models: percent (from balance or equity), fixed cash, or fixed lot. Percent and cash converge into one monetary pipeline; fixed lot treats risk as an outcome, with an optional drawdown override.
Position sizing is corrected for broker volume steps by always rounding down, with normalization to avoid floating-point truncation errors. When minimum lot exceeds the intended risk, the EA can either warn and trade the minimum or skip the trade.
Entry handling adds market, limit, and stop modes. Pending orders size stops/targets/volume from the intended entry price, no...
π Read | CodeBase | @mql5dev
Risk per trade supports three models: percent (from balance or equity), fixed cash, or fixed lot. Percent and cash converge into one monetary pipeline; fixed lot treats risk as an outcome, with an optional drawdown override.
Position sizing is corrected for broker volume steps by always rounding down, with normalization to avoid floating-point truncation errors. When minimum lot exceeds the intended risk, the EA can either warn and trade the minimum or skip the trade.
Entry handling adds market, limit, and stop modes. Pending orders size stops/targets/volume from the intended entry price, no...
π Read | CodeBase | @mql5dev
β€18π7π3π₯2π¨βπ»2
Certain trading hours are measurably better than others, but generic session rules miss broker-specific behavior. This script quantifies hourly conditions using the brokerβs own M1 history over the last N days.
For each hour it calculates average movement (M1 high-low range summed into points per hour) and average spread (from the M1 spread field). The key metric is movement-to-spread ratio: how many spreads of movement an hour provides, allowing direct comparison between high-volatility/high-cost hours and lower-volatility/low-cost hours.
Designed around XAUUSD but supports a comma-separated symbol list and prints results side by side. Inputs include symbols, lookback days (default 90), hour shift for timezone alignment, and optional per-symbol CSV output.
Example findings on one broker: XAUUSD spread stayed near 18.1β19.8 points; best hour 16:00 at 1...
π Read | Docs | @mql5dev
For each hour it calculates average movement (M1 high-low range summed into points per hour) and average spread (from the M1 spread field). The key metric is movement-to-spread ratio: how many spreads of movement an hour provides, allowing direct comparison between high-volatility/high-cost hours and lower-volatility/low-cost hours.
Designed around XAUUSD but supports a comma-separated symbol list and prints results side by side. Inputs include symbols, lookback days (default 90), hour shift for timezone alignment, and optional per-symbol CSV output.
Example findings on one broker: XAUUSD spread stayed near 18.1β19.8 points; best hour 16:00 at 1...
π Read | Docs | @mql5dev
β€16π8π€―1
ClockDiagnostic.mq5 samples TimeCurrent() and TimeLocal() every few seconds over a fixed observation window to detect server clock failure modes relevant to MT5 scripts and EAs.
Two cases are reported: TimeCurrent() freezing when no ticks arrive, and TimeCurrent() stepping backwards after symbol changes, reconnections, or cross-instrument ticks. Inputs include InpSeconds=60 for observation length and InpStep=2 for the sampling interval.
Output includes both clocks, the initial offset in seconds and hours, a β>>> STEP BACKβ line on each backward move, and a window summary: number of readings, seconds advanced by each clock, longest freeze, and step-back count, followed by a verdict. Documented rule: use TimeLocal() for timestamps, date/day transitions, and expiry; use TimeCurrent() for session hours and alignment with market data. The measurement is lim...
π Read | Forum | @mql5dev
Two cases are reported: TimeCurrent() freezing when no ticks arrive, and TimeCurrent() stepping backwards after symbol changes, reconnections, or cross-instrument ticks. Inputs include InpSeconds=60 for observation length and InpStep=2 for the sampling interval.
Output includes both clocks, the initial offset in seconds and hours, a β>>> STEP BACKβ line on each backward move, and a window summary: number of readings, seconds advanced by each clock, longest freeze, and step-back count, followed by a verdict. Documented rule: use TimeLocal() for timestamps, date/day transitions, and expiry; use TimeCurrent() for session hours and alignment with market data. The measurement is lim...
π Read | Forum | @mql5dev
π19β€7π€©3π3π₯1
SafeLogger.mqh provides serialized CSV logging for multiple concurrent EAs without missing lines. It appends a single record per call by opening the file with exclusive access (no FILE_SHARE_WRITE) and retrying up to 8 times with 40 ms backoff, for 320 ms total wait while another writer holds the handle. If all attempts fail, it emits an explicit error and prints the dropped line content.
SafeLogWrite(file, fields) prefixes TimeLocal() and the current symbol and writes time;symbol;fields. SafeLogHeader(file, header) writes the header once when the file does not yet exist.
A demo script supports InpFile, InpLines, and InpSafeMode. It reports mode, successful writes, line counts before/after, elapsed time, and flags >>> N LINE(S) LOST when contention causes missing records. Data loss is only reproducible with concurrent writers; running on four charts with InpS...
π Read | VPS | @mql5dev
SafeLogWrite(file, fields) prefixes TimeLocal() and the current symbol and writes time;symbol;fields. SafeLogHeader(file, header) writes the header once when the file does not yet exist.
A demo script supports InpFile, InpLines, and InpSafeMode. It reports mode, successful writes, line counts before/after, elapsed time, and flags >>> N LINE(S) LOST when contention causes missing records. Data loss is only reproducible with concurrent writers; running on four charts with InpS...
π Read | VPS | @mql5dev
β€18π₯8π7π€©2
ContractSizer.mqh provides balance-based contract sizing with three independent protections: a ladder, a floor, and a breaker. The ladder assigns one contract per balance factor with a hard cap. The floor blocks trading below a minimum capital threshold. The breaker halts sizing after drawdown exceeds a defined fraction of the balance peak and does not rearm automatically.
Deposits and withdrawals are taken from deal history via DEAL_TYPE_BALANCE and applied to the stored peak by the same delta. This prevents deposits during drawdown from masking the drawdown state. Peak is persisted under MQL5\Files and survives terminal restarts.
Usage calls ContractsToday(TimeLocal()) on each tick, recalculating only on day change. CapByBalance() enforces limits even with manual lots; Rearm() remains a manual action. Demo inputs simulate a 12-day path including a deposit...
π Read | AppStore | @mql5dev
Deposits and withdrawals are taken from deal history via DEAL_TYPE_BALANCE and applied to the stored peak by the same delta. This prevents deposits during drawdown from masking the drawdown state. Peak is persisted under MQL5\Files and survives terminal restarts.
Usage calls ContractsToday(TimeLocal()) on each tick, recalculating only on day change. CapByBalance() enforces limits even with manual lots; Rearm() remains a manual action. Demo inputs simulate a 12-day path including a deposit...
π Read | AppStore | @mql5dev
π11π₯11β€7π€©6π1
A diagnostic Expert Advisor for MetaTrader 5 has been released as a non-trading utility focused on runtime environment auditing. After being attached to a chart, it collects broker and terminal specifications and presents them via an on-chart panel with live updates, the terminal Experts log, and an exported CSV stored under MQL5/Files.
Captured data is grouped by operational category. Time zone metrics calculate broker server time, local PC time, and the precise offset versus UTC. Trading cost fields include swap calculation method, long and short swap values per 1 lot in account currency, and current spread.
Symbol rules cover digits, contract size, min/max/step volume, Stop Levels, and Freeze Level. Execution and connectivity reporting includes ping latency, connection state, supported filling modes (FOK, IOC), and margin calculation method. Account deta...
π Read | AlgoBook | @mql5dev
Captured data is grouped by operational category. Time zone metrics calculate broker server time, local PC time, and the precise offset versus UTC. Trading cost fields include swap calculation method, long and short swap values per 1 lot in account currency, and current spread.
Symbol rules cover digits, contract size, min/max/step volume, Stop Levels, and Freeze Level. Execution and connectivity reporting includes ping latency, connection state, supported filling modes (FOK, IOC), and margin calculation method. Account deta...
π Read | AlgoBook | @mql5dev
π14β€10π₯5π€©4
RiskPilot Pro reduces trade setup friction by keeping entry, stop loss, and take profit as draggable chart objects. Position size is recalculated on mouse release, using a fixed risk percentage of account balance rather than a fixed lot size, keeping exposure consistent across different stop distances.
Cross-pair sizing is handled via broker-provided currency conversion instead of assuming the account currency matches the symbol profit currency, improving accuracy on pairs such as USDCHF and USDJPY.
Functions include one-click order placement, ATR-based RESET for volatility stops, optional break-even and trailing stop automation, and account-level guards. Daily loss and max-drawdown limits can close tool-opened positions and block new trades until the next day. A basket-risk readout shows projected combined exposure before adding another position.
π Read | AlgoBook | @mql5dev
Cross-pair sizing is handled via broker-provided currency conversion instead of assuming the account currency matches the symbol profit currency, improving accuracy on pairs such as USDCHF and USDJPY.
Functions include one-click order placement, ATR-based RESET for volatility stops, optional break-even and trailing stop automation, and account-level guards. Daily loss and max-drawdown limits can close tool-opened positions and block new trades until the next day. A basket-risk readout shows projected combined exposure before adding another position.
π Read | AlgoBook | @mql5dev
π8β€7π₯5π€©4
SMC Liquidity Sweep Scalper is an EA for MetaTrader built around liquidity sweeps: price wicks beyond a recent swing high/low, then closes back through the level. The sweep candle is treated as an order block, and entry is taken only after a configurable confirmation break of structure through that zone.
Swing levels are tracked using closed bars to avoid repainting. Risk is managed with SL beyond the sweep extreme and TP set by fixed R:R, sized by risk % of balance. Parameters are normalized with ATR so the same configuration behaves consistently across symbols.
A higher-timeframe EMA trend filter can restrict trades to the broader bias. Additional gates reject weak setups based on ATR, spread, and confirmation momentum. The EA also maintains an on-chart scorecard: each setup is labeled with its own historical win rate and updated to WIN/LOSS after close.
...
π Read | VPS | @mql5dev
Swing levels are tracked using closed bars to avoid repainting. Risk is managed with SL beyond the sweep extreme and TP set by fixed R:R, sized by risk % of balance. Parameters are normalized with ATR so the same configuration behaves consistently across symbols.
A higher-timeframe EMA trend filter can restrict trades to the broader bias. Additional gates reject weak setups based on ATR, spread, and confirmation momentum. The EA also maintains an on-chart scorecard: each setup is labeled with its own historical win rate and updated to WIN/LOSS after close.
...
π Read | VPS | @mql5dev
π5