Destructors in MQL5 become clearer when compared to MetaTraderβs event model. OnInit/OnDeinit behave like constructor/destructor pairs: allocate resources (create chart objects) on init, and reliably release them on deinit.
The article refactors a simple regression-channel example from an indicator into a script, then into a class where the destructor (~ClassName) deletes the OBJ_REGRESSION automatically when the instance goes out of scope. No explicit call is needed; lifetime rules trigger cleanup.
Key rules: destructors return nothing, take no parameters, and are invoked implicitly. To reuse the pattern across scripts, indicators, and EAs, the class is moved into a header and included where needed, making chart-object management predictable and leak-free.
π Read | AppStore | @mql5dev
The article refactors a simple regression-channel example from an indicator into a script, then into a class where the destructor (~ClassName) deletes the OBJ_REGRESSION automatically when the instance goes out of scope. No explicit call is needed; lifetime rules trigger cleanup.
Key rules: destructors return nothing, take no parameters, and are invoked implicitly. To reuse the pattern across scripts, indicators, and EAs, the class is moved into a header and included where needed, making chart-object management predictable and leak-free.
π Read | AppStore | @mql5dev
π14β€8π€©3π₯2π1
An EA can place a valid trade while still accumulating unsafe account exposure. Multiple βcorrectβ entries on the same symbol can turn 1% per trade into 3β6% combined risk, increase margin usage, and extend time spent underwater.
The fix is basket accounting: total volume, volume-weighted average entry, floating P/L including swap, estimated margin via OrderCalcMargin, position count, oldest open time, plus MAE/MFE and peak count for diagnostics. Netting vs hedging changes what βposition countβ means, but money-based aggregates still apply.
Controls split into every-bar protections (aggregate loss cut, time stop, MAE tracking, pending-order cleanup) and pre-trade admissions (position ceilings, margin ceilings, implied-risk caps). A target-sized mean-reversion demo highlights that profit-target sizing makes risk an output, requiring separate implied-loss che...
π Read | CodeBase | @mql5dev
The fix is basket accounting: total volume, volume-weighted average entry, floating P/L including swap, estimated margin via OrderCalcMargin, position count, oldest open time, plus MAE/MFE and peak count for diagnostics. Netting vs hedging changes what βposition countβ means, but money-based aggregates still apply.
Controls split into every-bar protections (aggregate loss cut, time stop, MAE tracking, pending-order cleanup) and pre-trade admissions (position ceilings, margin ceilings, implied-risk caps). A target-sized mean-reversion demo highlights that profit-target sizing makes risk an output, requiring separate implied-loss che...
π Read | CodeBase | @mql5dev
β€13π8π₯2π€©2β‘1π1π1
Backtests showing 0% history quality usually come down to missing tick data. A tester can still run across periods with no real ticks, silently generating ticks from M1 bars. That produces smooth intra-bar movement, no gaps, no spread expansion, and can make fragile systems look profitable, especially grids, martingales, tight-stop scalpers, and small-target strategies.
A TickAudit script queries the terminal month by month and prints what exists before running a test: real ticks, partial ticks (holes), GENERATED TICKS (bars only), or nothing. The key risk is months that have bars but no ticks, because they still output results.
Outputs include the month where continuous real ticks begin and how many months would force synthetic ticks. Options include a full daily scan (slow), sampling, a wait time for downloads, and optional CSV export. It places no or...
π Read | Calendar | @mql5dev
A TickAudit script queries the terminal month by month and prints what exists before running a test: real ticks, partial ticks (holes), GENERATED TICKS (bars only), or nothing. The key risk is months that have bars but no ticks, because they still output results.
Outputs include the month where continuous real ticks begin and how many months would force synthetic ticks. Options include a full daily scan (slow), sampling, a wait time for downloads, and optional CSV export. It places no or...
π Read | Calendar | @mql5dev
β€12π5π₯2π2π€©1
A harmonic pattern script can reduce late entries by combining multi-scale structure detection with live PRZ validation.
A dual Zigzag engine runs βMajorβ and βMinorβ wave scans in parallel. The logic prioritizes macro setups, then falls back to minor structure when the broader swing becomes noisy.
Point D is tracked in real time using the current candle wick, updating Fibonacci ratios as price moves into the Potential Reversal Zone instead of waiting for a confirmed pivot.
Entry signals are gated by RSI momentum exhaustion. Bull and Bear triggers are issued only when Point D forms and RSI crosses the configured oversold/overbought thresholds.
On trigger, risk and targets are plotted automatically: TP1 at 38.2% and TP2 at 61.8% of the AβD retracement. Stop loss is placed 20% beyond Point Dβs structural size to account for deeper extensions.
π Read | NeuroBook | @mql5dev
A dual Zigzag engine runs βMajorβ and βMinorβ wave scans in parallel. The logic prioritizes macro setups, then falls back to minor structure when the broader swing becomes noisy.
Point D is tracked in real time using the current candle wick, updating Fibonacci ratios as price moves into the Potential Reversal Zone instead of waiting for a confirmed pivot.
Entry signals are gated by RSI momentum exhaustion. Bull and Bear triggers are issued only when Point D forms and RSI crosses the configured oversold/overbought thresholds.
On trigger, risk and targets are plotted automatically: TP1 at 38.2% and TP2 at 61.8% of the AβD retracement. Stop loss is placed 20% beyond Point Dβs structural size to account for deeper extensions.
π Read | NeuroBook | @mql5dev
β€23π8π₯3π¨βπ»3π2β‘1π1
Grid, martingale, and averaging risk is often misread by focusing on loss at the last planned level. Account failure typically happens earlier, when margin level hits broker stop-out while the position chain is still open.
A read-only EA calculates the adverse move that triggers stop-out, then scans the symbolβs M1 history to count how often a move of that size occurred over a chosen window. This turns a cash figure into a probability-relevant frequency and shows whether failure occurs before the configured leg cap is reached.
Key corrections: floating loss grows as step Γ N(Nβ1)/2, not step Γ N. Margin usage rises with open legs, so equity drops while margin used increases. Stop-out is percentage-based, so liquidation can occur after partial equity loss.
Outputs include full chain span, floating loss, margin locked, stop-out move distance, legs open at st...
π Read | AppStore | @mql5dev
A read-only EA calculates the adverse move that triggers stop-out, then scans the symbolβs M1 history to count how often a move of that size occurred over a chosen window. This turns a cash figure into a probability-relevant frequency and shows whether failure occurs before the configured leg cap is reached.
Key corrections: floating loss grows as step Γ N(Nβ1)/2, not step Γ N. Margin usage rises with open legs, so equity drops while margin used increases. Stop-out is percentage-based, so liquidation can occur after partial equity loss.
Outputs include full chain span, floating loss, margin locked, stop-out move distance, legs open at st...
π Read | AppStore | @mql5dev
β€17π5π€£3π₯2π€©1π1
A lightweight approach to customizing the MetaTrader 5 AI Assistant is shown via a prompt file generated by an MQL5 script. The assistantβs language, persona, menu structure, and response behavior can be adjusted by editing a plain text prompt, without using an AI API, DLL, or external service.
The AI_Prompt_Writer.mq5 script writes AI_Prompt.txt into the terminalβs MQL5\Files folder. Users select one of 11 response languages and a predefined persona, optionally set the output filename, and choose whether to overwrite an existing file. After loading the prompt in the assistant, a custom numbered menu becomes available for actions such as news checks, chart analysis, and trade review.
The sample is positioned as a template rather than a complete solution. It also enforces strict safety limits: no order placement or modification, no position management, no para...
π Read | Quotes | @mql5dev
The AI_Prompt_Writer.mq5 script writes AI_Prompt.txt into the terminalβs MQL5\Files folder. Users select one of 11 response languages and a predefined persona, optionally set the output filename, and choose whether to overwrite an existing file. After loading the prompt in the assistant, a custom numbered menu becomes available for actions such as news checks, chart analysis, and trade review.
The sample is positioned as a template rather than a complete solution. It also enforces strict safety limits: no order placement or modification, no position management, no para...
π Read | Quotes | @mql5dev
β€23π8π4π€‘2π₯1π€©1
Gold intraday range is session-driven. For XAUUSD, most of the daily move typically forms between 13:00 and 16:00 GMT during the London/New York overlap, while Sydney and Tokyo often stay confined. The 22:00 GMT rollover hour frequently prints the widest spread.
An indicator can visualize this with one high/low box per session (Sydney, Tokyo, London, New York), plus a thicker outline for the 13:00β16:00 overlap and a shaded rollover band across the dayβs high/low. Each box is labeled with the current session range and the average of the last N completed sessions.
Session inputs are defined in GMT. Server offset is computed via TimeTradeServer() minus TimeGMT(), rounded to 15 minutes, and refreshed on every new bar to stay aligned through DST changes.
Implementation uses chart objects only (no buffers), exact ranges via CopyHigh/CopyLow, redraw on new ...
π Read | Docs | @mql5dev
An indicator can visualize this with one high/low box per session (Sydney, Tokyo, London, New York), plus a thicker outline for the 13:00β16:00 overlap and a shaded rollover band across the dayβs high/low. Each box is labeled with the current session range and the average of the last N completed sessions.
Session inputs are defined in GMT. Server offset is computed via TimeTradeServer() minus TimeGMT(), rounded to 15 minutes, and refreshed on every new bar to stay aligned through DST changes.
Implementation uses chart objects only (no buffers), exact ranges via CopyHigh/CopyLow, redraw on new ...
π Read | Docs | @mql5dev
β€25π9π€©2π€‘2π¨βπ»2β1π₯1
Completed Bar Trend Regime Dashboard is a lightweight MT5 indicator that summarizes market structure using completed candles only. The panel combines EMA structure and slope, ADX/DI strength, higher-timeframe confirmation, ATR-based volatility context, breakout position, and spread versus ATR.
Regime classification requires agreement between the signal timeframe and the higher timeframe. When alignment is missing, the output switches to range or transition rather than assigning a directional label.
Panel interpretation focuses on EMA stack and the close versus the filter EMA, fast EMA slope, ADX with DI+/DI- pressure, and higher-timeframe validation. ATR and body/ATR provide volatility context, breakout flags location versus the recent range, and spread/ATR highlights execution friction relative to volatility.
Suggested US500 configuration uses H4 a...
π Read | AlgoBook | @mql5dev
Regime classification requires agreement between the signal timeframe and the higher timeframe. When alignment is missing, the output switches to range or transition rather than assigning a directional label.
Panel interpretation focuses on EMA stack and the close versus the filter EMA, fast EMA slope, ADX with DI+/DI- pressure, and higher-timeframe validation. ATR and body/ATR provide volatility context, breakout flags location versus the recent range, and spread/ATR highlights execution friction relative to volatility.
Suggested US500 configuration uses H4 a...
π Read | AlgoBook | @mql5dev
β€16π9π₯2π€©2π2π€‘1
Pending Order Inspector MT5 is a read-only indicator for pre-validating BUY_STOP and SELL_STOP inputs against the current symbol contract. It converts common server-side rejections into a client-side report before Send is pressed. No trading functions are used: no OrderSend, OrderCheck, CTrade, price suggestion, auto-normalization, or risk sizing in v1.00.
It reads Point, tick size, volume min/max/step, stops and freeze levels, Bid/Ask/spread, trade mode, order permissions, and quote age. Point and tick size are shown separately to catch prices that have valid digits but violate the tick grid.
Checks include order side vs Bid/Ask, tick-grid validity for entry/SL/TP, volume bounds and step, stops-level distances, permission for stop orders and SL/TP, and stale quotes. Results are PASS, INVALID, CHECK, UNKNOWN, or INFO, with adjacent grid values shown for of...
π Read | CodeBase | @mql5dev
It reads Point, tick size, volume min/max/step, stops and freeze levels, Bid/Ask/spread, trade mode, order permissions, and quote age. Point and tick size are shown separately to catch prices that have valid digits but violate the tick grid.
Checks include order side vs Bid/Ask, tick-grid validity for entry/SL/TP, volume bounds and step, stops-level distances, permission for stop orders and SL/TP, and stale quotes. Results are PASS, INVALID, CHECK, UNKNOWN, or INFO, with adjacent grid values shown for of...
π Read | CodeBase | @mql5dev
π14β€3π€‘3π€©2
A SuperTrend port is only useful if it matches the reference numerically, not just visually. This implementation aligns with TradingView output bar-for-bar and includes a reproducible verifier based on exported OHLC plus indicator outputs.
Ports typically drift for three reasons. Pineβs ta.rma uses Wilder smoothing with alpha=1/n and specific seeding, not EMA with 2/(n+1). Platform ATR functions also differ in warm-up and true range handling, creating a permanent offset inside the recursion. A common logic error is ignoring βstickyβ bands that only tighten and only flip after a close through the band, which can change the trend on roughly half the bars.
Validation compares MQL5 results against a Python recomputation from identical inputs and reports the first failing bar. Tests across EURUSD, USDJPY, XAUUSD, GER40, and BTCUSD show zero direction mi...
π Read | AlgoBook | @mql5dev
Ports typically drift for three reasons. Pineβs ta.rma uses Wilder smoothing with alpha=1/n and specific seeding, not EMA with 2/(n+1). Platform ATR functions also differ in warm-up and true range handling, creating a permanent offset inside the recursion. A common logic error is ignoring βstickyβ bands that only tighten and only flip after a close through the band, which can change the trend on roughly half the bars.
Validation compares MQL5 results against a Python recomputation from identical inputs and reports the first failing bar. Tests across EURUSD, USDJPY, XAUUSD, GER40, and BTCUSD show zero direction mi...
π Read | AlgoBook | @mql5dev
β€16π7π₯4β3
This part closes a common gap in MT5 EAs: risk-based position sizing can still generate lots the account cannot margin, especially when ATR stops get tight and computed volume rises. Risk (loss at stop) and margin (capital locked at entry) are independent constraints, and ignoring margin leads to rejected orders or trades that consume nearly all free margin.
The fix adds a margin-aware lot cap using OrderCalcMargin() to price 1 lot, then converts free margin into a broker-valid maximum volume with step-aware rounding. If even the minimum lot exceeds the cap, the trade is skipped; otherwise the risk-based lot is reduced.
An optional adaptive layer scales the cap by ACCOUNT_MARGIN_LEVEL, tightening exposure as margin level deteriorates and blocking new trades below a danger threshold.
Finally, checks are consolidated into a named pre-trade validation gate (pos...
π Read | CodeBase | @mql5dev
The fix adds a margin-aware lot cap using OrderCalcMargin() to price 1 lot, then converts free margin into a broker-valid maximum volume with step-aware rounding. If even the minimum lot exceeds the cap, the trade is skipped; otherwise the risk-based lot is reduced.
An optional adaptive layer scales the cap by ACCOUNT_MARGIN_LEVEL, tightening exposure as margin level deteriorates and blocking new trades below a danger threshold.
Finally, checks are consolidated into a named pre-trade validation gate (pos...
π Read | CodeBase | @mql5dev
β€14π9π₯1π€©1
LLM trading models can decay faster than they can be retrained: strong short-term accuracy collapses as regimes shift, and standard fine-tuning overwrites older behaviors that may return in cyclic markets.
SEAL (Self-Evolving Adaptive Learning) reframes the loop into continual learning from live outcomes. Each closed trade becomes feedback, but examples are weighted by move size and βconfident but wrongβ cases to correct false pattern detection.
A prioritized ring-buffer memory blends freshness with retention of rare, high-value events, while retraining is triggered by quality/regime-change signals (volatility, volume, error distribution) and runs asynchronously to avoid blocking execution. Switching training data from raw JSON to narrative context improves indicator relationship learning.
Operational safeguards cover black swans (anomaly stop), overfitti...
π Read | Calendar | @mql5dev
SEAL (Self-Evolving Adaptive Learning) reframes the loop into continual learning from live outcomes. Each closed trade becomes feedback, but examples are weighted by move size and βconfident but wrongβ cases to correct false pattern detection.
A prioritized ring-buffer memory blends freshness with retention of rare, high-value events, while retraining is triggered by quality/regime-change signals (volatility, volume, error distribution) and runs asynchronously to avoid blocking execution. Switching training data from raw JSON to narrative context improves indicator relationship learning.
Operational safeguards cover black swans (anomaly stop), overfitti...
π Read | Calendar | @mql5dev
β€18π13π5π€©3π₯1π1
Forum demand for indicator alerts and multi-timeframe signals remains constrained by a common limitation: many users only have compiled .ex5 files, not source, and maintaining custom edits across multiple indicators does not scale.
A standalone approach uses iCustom to load indicators by name and read their buffers without source. EXPLORE mode probes buffers, counts non-empty/zero/blank values across recent bars, and prints a per-bar table so the visible plot or sparse signal buffer can be identified reliably.
WATCH mode then applies triggers to the selected buffer: value appears, level cross, buffer-to-buffer cross, or value change. Closed bars are evaluated by default, with optional tick-by-tick evaluation on the forming bar, still limited to one alert per bar.
A separate change audit distinguishes late values (blank becomes populated later) from repain...
π Read | Quotes | @mql5dev
A standalone approach uses iCustom to load indicators by name and read their buffers without source. EXPLORE mode probes buffers, counts non-empty/zero/blank values across recent bars, and prints a per-bar table so the visible plot or sparse signal buffer can be identified reliably.
WATCH mode then applies triggers to the selected buffer: value appears, level cross, buffer-to-buffer cross, or value change. Closed bars are evaluated by default, with optional tick-by-tick evaluation on the forming bar, still limited to one alert per bar.
A separate change audit distinguishes late values (blank becomes populated later) from repain...
π Read | Quotes | @mql5dev
β€17π5π€©3π₯2
An Expert Advisor built around a SuperTrend port where correctness is defined by matching TradingView output and by matching trades to signals, not by profit claims.
Execution is limited to closed bars to prevent transient intra-bar flips from generating trades that do not exist at bar close. The EA reads the SuperTrend direction via iCustom, trades one position at a time, tags orders with a magic number, and places the stop on the line with an optional points offset. On a flip, the position is closed and reversed.
A known edge case is handled: if the next-tick entry would place the stop on the wrong side (price already beyond the line), the signal is dropped and logged rather than forcing an invalid or near-instant stop-out.
An audit logs the indicator value on every closed bar, then a Python check verifies one entry per flip and zero mismatches (example:...
π Read | CodeBase | @mql5dev
Execution is limited to closed bars to prevent transient intra-bar flips from generating trades that do not exist at bar close. The EA reads the SuperTrend direction via iCustom, trades one position at a time, tags orders with a magic number, and places the stop on the line with an optional points offset. On a flip, the position is closed and reversed.
A known edge case is handled: if the next-tick entry would place the stop on the wrong side (price already beyond the line), the signal is dropped and logged rather than forcing an invalid or near-instant stop-out.
An audit logs the indicator value on every closed bar, then a Python check verifies one entry per flip and zero mismatches (example:...
π Read | CodeBase | @mql5dev
β€23π5π₯5π€©4
Trading-system costs are measurable, but commonly underestimated. A read-only Expert Advisor calculates one round-trip cost per broker and symbol using tick-sampled live spread, swap for long and short including the triple-charge day, and commission derived from closed deals. It also prints the spread value many tools rely on next to the measured one.
Bar βspreadβ fields are per-bar summaries, not the current quote. On XAUUSD, 60 live readings showed 20 points while the M1 field median was 6, which breaks spread filters and flatters backtests, especially with high trade counts.
Swap is often omitted in custom simulators. It is asymmetric and includes a triple weekday. Example on gold per 0.01 lot: β0.5842 long, +0.4098 short, Wednesday tripled.
Implementation details include counting distinct quotes, refusing closed-market sampling via TimeCurrent vs TimeTra...
π Read | AppStore | @mql5dev
Bar βspreadβ fields are per-bar summaries, not the current quote. On XAUUSD, 60 live readings showed 20 points while the M1 field median was 6, which breaks spread filters and flatters backtests, especially with high trade counts.
Swap is often omitted in custom simulators. It is asymmetric and includes a triple weekday. Example on gold per 0.01 lot: β0.5842 long, +0.4098 short, Wednesday tripled.
Implementation details include counting distinct quotes, refusing closed-market sampling via TimeCurrent vs TimeTra...
π Read | AppStore | @mql5dev
β€28π11π₯1π1π1
Prop Firm Rule Checker is a read-only diagnostic script that evaluates closed-trade history from a live/demo account or Strategy Tester runs against common prop-firm evaluation constraints. Results are printed as a PASS/FAIL report in the Experts/Journal log, reducing manual post-backtest calculations.
Checks include profit target versus starting balance, max daily loss by calendar day, peak-to-valley overall drawdown, a consistency limit to flag single-day profit concentration, and minimum distinct trading days.
Usage involves attaching the script to any chart or running it after a tester pass, then configuring inputs for balance, thresholds, and date range. It uses HistorySelect() only and does not open, modify, or close trades. Rules differ by firm and must be set from the official rule sheet.
π Read | VPS | @mql5dev
Checks include profit target versus starting balance, max daily loss by calendar day, peak-to-valley overall drawdown, a consistency limit to flag single-day profit concentration, and minimum distinct trading days.
Usage involves attaching the script to any chart or running it after a tester pass, then configuring inputs for balance, thresholds, and date range. It uses HistorySelect() only and does not open, modify, or close trades. Rules differ by firm and must be set from the official rule sheet.
π Read | VPS | @mql5dev
β€14π6π€©3π₯2π€£2
Most position size calculators evaluate only the next trade and ignore existing exposure. That approach can overstate available risk when multiple symbols are correlated, such as stacking EURUSD and GBPUSD in the same direction and effectively increasing USD exposure.
This script estimates a standard risk-based lot size, then reviews all open positions across the account. It computes recent correlation between each open symbol and the target symbol using the last N bars on a selected timeframe, evaluates whether directions amplify or offset, and aggregates risk already allocated to correlated positions. If combined exposure approaches or exceeds a configurable basket limit, the recommended lot size is reduced.
Output is written to the Experts/Journal log with the positions flagged, correlation values, direction impact, and the adjusted lot size. If any ...
π Read | Signals | @mql5dev
This script estimates a standard risk-based lot size, then reviews all open positions across the account. It computes recent correlation between each open symbol and the target symbol using the last N bars on a selected timeframe, evaluates whether directions amplify or offset, and aggregates risk already allocated to correlated positions. If combined exposure approaches or exceeds a configurable basket limit, the recommended lot size is reduced.
Output is written to the Experts/Journal log with the positions flagged, correlation values, direction impact, and the adjusted lot size. If any ...
π Read | Signals | @mql5dev
β€14π5π₯3π€2π€©2
Risk-Based Lot Size Calculator is a lightweight MQL5 script designed to standardize position sizing using fixed account risk.
Inputs are limited to InpRiskPercent (risk as a percent of balance, default 1.0) and InpStopLossPips (stop distance in pips, default 20). The script reads the current account balance and symbol trading properties including tick value, tick size, and volume limits (min, max, step).
Lot size is calculated so that a stop-out at the specified pip distance equals the configured risk amount. Output volume is rounded down to the nearest valid step and constrained to broker limits. The calculated lot size and a full breakdown are displayed on-chart and written to the Experts log. Live broker parameters are used, avoiding hard-coded pip assumptions across symbols and account types.
π Read | Docs | @mql5dev
Inputs are limited to InpRiskPercent (risk as a percent of balance, default 1.0) and InpStopLossPips (stop distance in pips, default 20). The script reads the current account balance and symbol trading properties including tick value, tick size, and volume limits (min, max, step).
Lot size is calculated so that a stop-out at the specified pip distance equals the configured risk amount. Output volume is rounded down to the nearest valid step and constrained to broker limits. The calculated lot size and a full breakdown are displayed on-chart and written to the Experts log. Live broker parameters are used, avoiding hard-coded pip assumptions across symbols and account types.
π Read | Docs | @mql5dev
π4π₯3π€©1