A fixed 3-qubit quantum circuit is used as a nonlinear feature generator for MT5 price windows, modeling โuncertainty structureโ rather than claiming any quantum computing advantage. Mean return, volatility, and range drive RY rotations; a CNOT chain adds dependencies; 1000-shot simulation yields an 8-bin outcome histogram.
Seven metrics are extracted from that histogram: entropy, dominant-state probability, superposition width, outcome coherence, neighbor-bit correlation (entanglement proxy), variance, and count of significant states. Caching via window hashing is required to keep sliding-window runs practical.
These features are fused with classical OHLCV-derived inputs in a bidirectional LSTM pipeline (BatchNorm, ReLU, Dropout), trained with Focal Loss plus weighted sampling to handle directional imbalance. On a small EURUSD H1 sample, reported ga...
๐ Read | Quotes | @mql5dev
Seven metrics are extracted from that histogram: entropy, dominant-state probability, superposition width, outcome coherence, neighbor-bit correlation (entanglement proxy), variance, and count of significant states. Caching via window hashing is required to keep sliding-window runs practical.
These features are fused with classical OHLCV-derived inputs in a bidirectional LSTM pipeline (BatchNorm, ReLU, Dropout), trained with Focal Loss plus weighted sampling to handle directional imbalance. On a small EURUSD H1 sample, reported ga...
๐ Read | Quotes | @mql5dev
โค28๐4โก2๐ฅ2๐คฉ2๐2๐จโ๐ป2
Position replay/simulation indicator update: C_IndicatorPosition is removed to eliminate an intermediate layer between the indicator and C_ElementsTrade. Methods and state move into the indicator so the new P/L label can access the opening-price component directly.
Profit/loss is computed as points to the best close price, not POSITION_PROFIT. Spread makes POSITION_PROFIT unreliable for exit viability, so closing logic uses Bid for long exits and Ask for short exits, sourced via SymbolInfoTick in OnCalculate.
C_ElementsTrade gains a label anchored to the opening line, updated with a formatted points delta using the symbolโs digits. The label color indicates positive vs negative, and ChartRedraw is used to avoid delayed UI refresh.
๐ Read | VPS | @mql5dev
Profit/loss is computed as points to the best close price, not POSITION_PROFIT. Spread makes POSITION_PROFIT unreliable for exit viability, so closing logic uses Bid for long exits and Ask for short exits, sourced via SymbolInfoTick in OnCalculate.
C_ElementsTrade gains a label anchored to the opening line, updated with a formatted points delta using the symbolโs digits. The label color indicates positive vs negative, and ChartRedraw is used to avoid delayed UI refresh.
๐ Read | VPS | @mql5dev
โค21๐9๐คฉ4๐2โก1๐ฅ1๐1
Time-series forecasting is seeing diminishing returns from scaling Transformer-style models. Reported MSE/MAE gains stay under ~30% while parameter counts rise by orders of magnitude, and progress after PatchTST appears incremental.
A key cost driver is patching with attention: fragmenting sequences removes temporal/spatial identifiers, then position/identity encodings are added back, expanding latent dimensionality and increasing overfitting risk on limited datasets.
SSCNN (โParsimony or Capability? Decomposition Delivers Both in Long-term Time Series Forecastingโ) argues for structured decomposition over patching, with formal analysis. The model extracts long-term, seasonal, short-term, plus spatial components via temporal/spatial attention normalization and selection maps, then extrapolates and combines them using polynomial regression.
Benchmarks repor...
๐ Read | Freelance | @mql5dev
A key cost driver is patching with attention: fragmenting sequences removes temporal/spatial identifiers, then position/identity encodings are added back, expanding latent dimensionality and increasing overfitting risk on limited datasets.
SSCNN (โParsimony or Capability? Decomposition Delivers Both in Long-term Time Series Forecastingโ) argues for structured decomposition over patching, with formal analysis. The model extracts long-term, seasonal, short-term, plus spatial components via temporal/spatial attention normalization and selection maps, then extrapolates and combines them using polynomial regression.
Benchmarks repor...
๐ Read | Freelance | @mql5dev
โค19๐6๐ฅ5๐คฉ3๐ฑ1๐1
MetaTrader 5 projects that rely on structs often end up with warnings about undeleted instances or unreleased memory. A common root cause is skipped initialization routines, which turns structured code into a source of inconsistent state.
In MQL5, a class is effectively a struct with lifecycle hooks. Constructors run automatically on instance creation and can take parameters; destructors run when an instance ends and are intended for explicit resource release. Multiple constructors are allowed, but only one destructor.
Replacing manual Init() calls with constructors removes the dependency on callers remembering setup steps. If no constructor is defined, MQL5 generates a default one, and member state may remain effectively uninitialized from a logic standpoint. Initialization lists can also be used to set members before the constructor body executes.
๐ Read | Forum | @mql5dev
In MQL5, a class is effectively a struct with lifecycle hooks. Constructors run automatically on instance creation and can take parameters; destructors run when an instance ends and are intended for explicit resource release. Multiple constructors are allowed, but only one destructor.
Replacing manual Init() calls with constructors removes the dependency on callers remembering setup steps. If no constructor is defined, MQL5 generates a default one, and member state may remain effectively uninitialized from a logic standpoint. Initialization lists can also be used to set members before the constructor body executes.
๐ Read | Forum | @mql5dev
โค28๐6๐คฉ3๐ฅ1๐1
Update to an MQL5 replay/simulation position view focuses on UI robustness and event-driven interaction.
OBJ_EDIT fields now auto-adjust size based on font metrics computed in the C_ElementsTrade constructor, removing manual width/height tuning and preventing text clipping after font changes. Font name/size are centralized via macros, and a deliberate compile-stop guard avoids conflicting macro redefinitions.
Distance readouts reuse the existing P/L display logic: take-profit and stop-loss lines show point distance from the open price without overwriting the open-line P/L value.
Runtime behavior is fixed at the indicator layer. Update logic is extracted into a helper and invoked from both OnCalculate and OnChartEvent, enabling live distance updates during drag and proper cleanup when creation is canceled with ESC.
๐ Read | CodeBase | @mql5dev
OBJ_EDIT fields now auto-adjust size based on font metrics computed in the C_ElementsTrade constructor, removing manual width/height tuning and preventing text clipping after font changes. Font name/size are centralized via macros, and a deliberate compile-stop guard avoids conflicting macro redefinitions.
Distance readouts reuse the existing P/L display logic: take-profit and stop-loss lines show point distance from the open price without overwriting the open-line P/L value.
Runtime behavior is fixed at the indicator layer. Update logic is extracted into a helper and invoked from both OnCalculate and OnChartEvent, enabling live distance updates during drag and proper cleanup when creation is canceled with ESC.
๐ Read | CodeBase | @mql5dev
โค18๐7๐ฅ2๐คฉ2๐2
Part 2 extends the Cairo-style split between geometry and rendering by adding Path.mqh as a common shape representation.
A path is geometry only: points grouped into outlines, with no color, thickness, fill rule, or destination buffer. This removes shape-specific render loops and enables reuse across different fills and transforms.
Points are stored as doubles to preserve sub-pixel coordinates. This is required for later anti-aliasing, smooth animation, and curve flattening without quantization.
A path can contain multiple contours (open or closed) to support glyph holes, rings, borders, and multi-part icons. Storage uses one flat vertex array plus a contour start index array and a closed-flag array for contiguous traversal and low overhead.
๐ Read | AlgoBook | @mql5dev
A path is geometry only: points grouped into outlines, with no color, thickness, fill rule, or destination buffer. This removes shape-specific render loops and enables reuse across different fills and transforms.
Points are stored as doubles to preserve sub-pixel coordinates. This is required for later anti-aliasing, smooth animation, and curve flattening without quantization.
A path can contain multiple contours (open or closed) to support glyph holes, rings, borders, and multi-part icons. Storage uses one flat vertex array plus a contour start index array and a closed-flag array for contiguous traversal and low overhead.
๐ Read | AlgoBook | @mql5dev
โค13๐8๐คฉ1๐1
Gopalakrishnan Range Index (GRI), published in TASC in 2001, measures market activity using the closing-price range over N bars, normalized on a log scale. It remains a practical volatility gauge and is easy to implement in MetaTrader 5.
Implementation computes High/Low of Close over ChaoticPeriod, takes log10(range)/log10(N), returning 0 when range is zero. For range < 1, values become negative; a shifted range can clamp the minimum toward zero. Scaling by Point makes thresholds usable in EA inputs.
In testing, an EA using TEMA for direction and AMA for confirmation improved behavior when trades were filtered by rising GRI, avoiding low-activity phases. GRI is a condition filter, not a directional signal, and benefits from per-symbol threshold calibration and backtesting.
๐ Read | Quotes | @mql5dev
Implementation computes High/Low of Close over ChaoticPeriod, takes log10(range)/log10(N), returning 0 when range is zero. For range < 1, values become negative; a shifted range can clamp the minimum toward zero. Scaling by Point makes thresholds usable in EA inputs.
In testing, an EA using TEMA for direction and AMA for confirmation improved behavior when trades were filtered by rising GRI, avoiding low-activity phases. GRI is a condition filter, not a directional signal, and benefits from per-symbol threshold calibration and backtesting.
๐ Read | Quotes | @mql5dev
โค10๐6๐2๐คฉ2๐1๐1
Post-trade stats typically report what a trade earned. This utility records what each trade had available, and what it returned.
On first detection it captures the initial stop distance as 1R, then measures max favorable and adverse excursion in R until the position closes. Trailing stops do not alter the reference, so the measurement stays consistent.
One CSV row per closed position is written to MQL5\Files: ticket, symbol, side, open/close time, entry, risk distance, peak R, worst R, realised R, and profit. Trades without a stop are skipped and counted.
Use case: equity curves that spike and fade can come from trades reaching high peak R and giving it back, or from trades never traveling far. Comparing average peak R vs realised R, plus average giveback on the chart panel, separates these cases.
The EA is read-only: no open/modify/close. Attach alongsid...
๐ Read | VPS | @mql5dev
On first detection it captures the initial stop distance as 1R, then measures max favorable and adverse excursion in R until the position closes. Trailing stops do not alter the reference, so the measurement stays consistent.
One CSV row per closed position is written to MQL5\Files: ticket, symbol, side, open/close time, entry, risk distance, peak R, worst R, realised R, and profit. Trades without a stop are skipped and counted.
Use case: equity curves that spike and fade can come from trades reaching high peak R and giving it back, or from trades never traveling far. Comparing average peak R vs realised R, plus average giveback on the chart panel, separates these cases.
The EA is read-only: no open/modify/close. Attach alongsid...
๐ Read | VPS | @mql5dev
๐10โค7๐คฉ4๐ฅ3๐1
A read-only MQL5 Expert Advisor logs each closed position to CSV with market-state context at entry and exit. Recorded fields include RSI, Stochastic, EMA20/EMA50 distance, Bollinger %B, ATR, and ADX on two timeframes, enabling post-trade rule reconstruction and strategy evaluation without relying on undocumented logic.
Several data-loss traps are handled explicitly. Deduplication avoids position_id and close_time watermarks; position_id reflects open order, not close order, and datetime has 1-second resolution. A set of logged position IDs is rebuilt from the CSV on restart. HistorySelectByPosition() is isolated from the main scan to prevent global history selection from being overwritten during iteration.
Close detection includes DEAL_ENTRY_OUT and DEAL_ENTRY_OUT_BY. Magic filtering reads the opening dealโs magic, not the closing deal, to avoid dropping m...
๐ Read | AlgoBook | @mql5dev
Several data-loss traps are handled explicitly. Deduplication avoids position_id and close_time watermarks; position_id reflects open order, not close order, and datetime has 1-second resolution. A set of logged position IDs is rebuilt from the CSV on restart. HistorySelectByPosition() is isolated from the main scan to prevent global history selection from being overwritten during iteration.
Close detection includes DEAL_ENTRY_OUT and DEAL_ENTRY_OUT_BY. Magic filtering reads the opening dealโs magic, not the closing deal, to avoid dropping m...
๐ Read | AlgoBook | @mql5dev
โค15๐5๐ฅ3๐ค2๐1
MetaTrader 5 includes an economic calendar accessible from MQL5 via CalendarValueHistory(), but external tooling cannot query it. The Python MetaTrader5 package exposes market data and trading state, yet provides no calendar API, leaving research scripts, dashboards, bots, and spreadsheets blind to upcoming releases.
A read-only Expert Advisor can bridge this gap by exporting calendar data to a CSV file under MQL5\Files on a fixed interval. It never opens, closes, or modifies positions.
Key implementation points: UTF-8 output to preserve localized event names, chronological sorting across currencies, atomic write (build in memory, then write once), HTML entity decoding (e.g., S&P), and a freshness header with server time, event count, and UTC offset. Update time is taken from the trade server clock, not the last tick.
Inputs include currency filter, ho...
๐ Read | AlgoBook | @mql5dev
A read-only Expert Advisor can bridge this gap by exporting calendar data to a CSV file under MQL5\Files on a fixed interval. It never opens, closes, or modifies positions.
Key implementation points: UTF-8 output to preserve localized event names, chronological sorting across currencies, atomic write (build in memory, then write once), HTML entity decoding (e.g., S&P), and a freshness header with server time, event count, and UTC offset. Update time is taken from the trade server clock, not the last tick.
Inputs include currency filter, ho...
๐ Read | AlgoBook | @mql5dev
โค13๐5๐คฉ2๐ฅ1๐1
Trade Guardian is a defensive Expert Advisor designed for risk supervision rather than trade entry. It monitors existing positions and reacts when configured limits are breached. Each function is independent, and position closing is disabled by default to allow warning-only operation on live charts.
Stop-loss enforcement checks open positions on timer events and flags orders without a stop. If enabled, it places a stop at an ATR-based distance using the chart timeframe, respecting a minimum distance in points and the broker stop level. Stops are applied only to the chart symbol.
Risk limits include a daily loss cap referenced to the balance at the dayโs start, auto-refreshed on each new day, and a total drawdown cap referenced to the equity peak. A cooldown can rebase the peak to current equity so the guard can re-arm, with rebase events logged.
Scope can ...
๐ Read | Forum | @mql5dev
Stop-loss enforcement checks open positions on timer events and flags orders without a stop. If enabled, it places a stop at an ATR-based distance using the chart timeframe, respecting a minimum distance in points and the broker stop level. Stops are applied only to the chart symbol.
Risk limits include a daily loss cap referenced to the balance at the dayโs start, auto-refreshed on each new day, and a total drawdown cap referenced to the equity peak. A cooldown can rebase the peak to current equity so the guard can re-arm, with rebase events logged.
Scope can ...
๐ Read | Forum | @mql5dev
โค11๐7๐คฉ3๐1
EOSA (Ebola Optimization Search Algorithm, 2021) is a bio-inspired metaheuristic derived from a SEIR-HDVQ epidemic model, mapping short-range transmission to exploitation and long-range transmission to exploration. Quarantine is used to reduce premature convergence by keeping part of the population static.
A literal implementation exposes issues in the paperโs core equations: missing direction vectors in movement updates, identical exploitation/exploration forms, and a bounds bug in initialization (L + rand(U+L) instead of L + rand(U-L)). These defects can cause non-improving motion and rapid population collapse.
A practical variant keeps the intended mechanics but simplifies to active agents only, adds directed moves, pBest memory, fitness-biased strategy selection, Lรฉvy flights for global search, and a ฯ schedule from 1.0 to 0.5, with boundary re...
๐ Read | NeuroBook | @mql5dev
A literal implementation exposes issues in the paperโs core equations: missing direction vectors in movement updates, identical exploitation/exploration forms, and a bounds bug in initialization (L + rand(U+L) instead of L + rand(U-L)). These defects can cause non-improving motion and rapid population collapse.
A practical variant keeps the intended mechanics but simplifies to active agents only, adds directed moves, pBest memory, fitness-biased strategy selection, Lรฉvy flights for global search, and a ฯ schedule from 1.0 to 0.5, with boundary re...
๐ Read | NeuroBook | @mql5dev
โค11๐5๐คฉ2๐2๐ฅ1
This article focuses on practical debugging in MQL5 using MetaEditor and the terminal logs, bridging the gap between basic syntax and building reliable Expert Advisors.
It breaks down compiler diagnostics (warnings vs errors, file/line/column navigation) and shows why fixing issues top-to-bottom reduces cascading messages, especially when porting MQL4 code with mismatched function signatures.
Runtime failures get equal attention: dynamic arrays without sizing, โarray out of rangeโ cases from unloaded history or off-by-one indexing, and silent logic bugs where an EA simply never trades.
The workflow starts from entry points (OnInit/OnStart, OnTick/OnCalculate, OnTimer), encourages structural analysis, buffer/property checks for indicators, and uses targeted Print/PrintFormat output to pinpoint control-flow mistakes like an accidental semicolon after a loop.
๐ Read | AlgoBook | @mql5dev
It breaks down compiler diagnostics (warnings vs errors, file/line/column navigation) and shows why fixing issues top-to-bottom reduces cascading messages, especially when porting MQL4 code with mismatched function signatures.
Runtime failures get equal attention: dynamic arrays without sizing, โarray out of rangeโ cases from unloaded history or off-by-one indexing, and silent logic bugs where an EA simply never trades.
The workflow starts from entry points (OnInit/OnStart, OnTick/OnCalculate, OnTimer), encourages structural analysis, buffer/property checks for indicators, and uses targeted Print/PrintFormat output to pinpoint control-flow mistakes like an accidental semicolon after a loop.
๐ Read | AlgoBook | @mql5dev
โค15๐4๐คฉ3๐จโ๐ป3๐1
This article builds a Fisher Transformโstyle oscillator for MetaTrader 5, showing how to turn recent price position into a bounded value, smooth it, clamp it near ยฑ1 to keep the logarithm stable, then apply the log transform and recursive smoothing to make extremes and reversals visually sharp.
Key implementation work focuses on correctness in MQL5: preserving recursive state via a calculation buffer, handling series indexing consistently, guarding minimum bars and zero-range windows, and recalculating only new bars for performance.
For trading logic, the signal is not a threshold cross. It waits for the line to exceed an extreme (often ยฑ1.5 to ยฑ2) and then turn back toward zero on closed bars, enabling a non-repainting EA to act on confirmed peaks/troughs across symbols.
๐ Read | Forum | @mql5dev
Key implementation work focuses on correctness in MQL5: preserving recursive state via a calculation buffer, handling series indexing consistently, guarding minimum bars and zero-range windows, and recalculating only new bars for performance.
For trading logic, the signal is not a threshold cross. It waits for the line to exceed an extreme (often ยฑ1.5 to ยฑ2) and then turn back toward zero on closed bars, enabling a non-repainting EA to act on confirmed peaks/troughs across symbols.
๐ Read | Forum | @mql5dev
โค12๐8โก2๐ฅ2๐2๐คฉ1
This article turns the reusable CSwingEngine into a double top/bottom detector that prioritizes market structure over chart โshapesโ. The EA first confirms H4 trend (up for double top, down for double bottom) using labeled swings (HH/HL or LL/LH); if the context is range, it refuses to evaluate the pattern.
Validation is based on confirmed swing points: two matching swings with exactly one opposite swing between them, peaks/troughs within a configurable H4-ATR tolerance, a minimum pattern height in H4-ATR, and time width measured from swing timestamps. ATR is always taken from the swing timeframe to keep thresholds scaled to structure.
Execution is separated from detection via a three-state machine: scan, lock a single pattern once, then wait for a neckline break on the trading chart timeframe with expiry and โno re-entryโ identity tracking. Entries add pra...
๐ Read | Calendar | @mql5dev
Validation is based on confirmed swing points: two matching swings with exactly one opposite swing between them, peaks/troughs within a configurable H4-ATR tolerance, a minimum pattern height in H4-ATR, and time width measured from swing timestamps. ATR is always taken from the swing timeframe to keep thresholds scaled to structure.
Execution is separated from detection via a three-state machine: scan, lock a single pattern once, then wait for a neckline break on the trading chart timeframe with expiry and โno re-entryโ identity tracking. Entries add pra...
๐ Read | Calendar | @mql5dev
โค9๐7๐4๐ฅ2โก1
Mamba4Cast is presented as a modular time-series forecasting core for high-frequency market data, combining compact feature extraction, multi-window convolutions for noise-resistant signal detection, and an SSM-based long-memory block to keep context across dozens of candles. A key design choice is forecasting across the full planning horizon rather than only the next step, improving stability for trading decisions.
The framework is integrated into an ActorโDirectorโCritic agent. The Environment State Encoder normalizes raw OHLCV and indicators (using noisy batch norm for better generalization), adds H1/D1 harmonic time embeddings, then applies stacked convolution + pooling + Chimera SSM blocks, followed by a convolutional decoder and denormalization.
The Actor aligns account state with per-feature latent embeddings via stacked cross-attention before...
๐ Read | Forum | @mql5dev
The framework is integrated into an ActorโDirectorโCritic agent. The Environment State Encoder normalizes raw OHLCV and indicators (using noisy batch norm for better generalization), adds H1/D1 harmonic time embeddings, then applies stacked convolution + pooling + Chimera SSM blocks, followed by a convolutional decoder and denormalization.
The Actor aligns account state with per-feature latent embeddings via stacked cross-attention before...
๐ Read | Forum | @mql5dev
โค6๐4๐ฅ3๐คฉ2๐2
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
๐10โค4๐คฉ3๐ฅ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
๐4โค3โก1