Part 2 evolves an MVP FastAPI service from controlling one MT5 terminal to managing multiple local instances via a simple web UI.
The codebase is split for maintainability: terminal process logic moves into mt5_control.py, while main.py keeps only route handlers. Templates and static assets are added using Jinja2 plus a mounted /static path.
Instance management becomes name-based with POST /start/{name} and /stop/{name}. A load_instances() scan uses psutil to map registered terminal folders to running PIDs, preventing duplicate starts and handling already-stopped processes. Launch uses subprocess.Popen with /portable to isolate each terminal directory.
π Read | Signals | @mql5dev
The codebase is split for maintainability: terminal process logic moves into mt5_control.py, while main.py keeps only route handlers. Templates and static assets are added using Jinja2 plus a mounted /static path.
Instance management becomes name-based with POST /start/{name} and /stop/{name}. A load_instances() scan uses psutil to map registered terminal folders to running PIDs, preventing duplicate starts and handling already-stopped processes. Launch uses subprocess.Popen with /portable to isolate each terminal directory.
π Read | Signals | @mql5dev
β€16π8π2
Mamba4Cast targets zero-shot time-series forecasting for trading: deploy on new symbols without retraining, while SSM-based blocks keep inference linear in sequence length for low-latency decisions. It outputs the full forecast horizon in one pass, reducing the error drift common in step-by-step approaches.
This part focuses on the preprocessing layer CMamba4CastEmbedding. It standardizes inputs via convolutional projection with TANH, batch normalization, and a parallel path that injects sinusoidal/cosine temporal markers. The two representations are concatenated to form a dense per-bar embedding.
Implementation details matter for MQL5: static submodules avoid dynamic allocation, backprop cleanly de-concatenates gradients per branch, then merges them for stable weight updates. Next, the encoder stacks multi-kernel convolutions, concatenates and normalizes f...
π Read | Docs | @mql5dev
This part focuses on the preprocessing layer CMamba4CastEmbedding. It standardizes inputs via convolutional projection with TANH, batch normalization, and a parallel path that injects sinusoidal/cosine temporal markers. The two representations are concatenated to form a dense per-bar embedding.
Implementation details matter for MQL5: static submodules avoid dynamic allocation, backprop cleanly de-concatenates gradients per branch, then merges them for stable weight updates. Next, the encoder stacks multi-kernel convolutions, concatenates and normalizes f...
π Read | Docs | @mql5dev
β€14π6π€‘3π2
Most MT5 volatility indicators reduce each bar to a single close, ignoring open/high/low and missing most intrabar movement. Range-based estimators use full OHLC to produce a less noisy variance estimate from the same window, making volatility signals smoother and more responsive.
Four estimators are implemented: close-to-close (baseline), Parkinson (high/low, efficient but gap-blind), Garman-Klass (full bar, even more efficient but still gap-blind), and Yang-Zhang (adds previous close plus drift-robust intrabar term to measure overnight gaps directly). Yang-Zhang is the practical default for instruments with session breaks.
A reusable MQL5 library, VolatilityEstimators.mqh, wraps these methods behind one enum-driven interface using an O(1) ring buffer, shared window storage, readiness checks, input validation, and optional annualization. Two indicat...
π Read | Freelance | @mql5dev
Four estimators are implemented: close-to-close (baseline), Parkinson (high/low, efficient but gap-blind), Garman-Klass (full bar, even more efficient but still gap-blind), and Yang-Zhang (adds previous close plus drift-robust intrabar term to measure overnight gaps directly). Yang-Zhang is the practical default for instruments with session breaks.
A reusable MQL5 library, VolatilityEstimators.mqh, wraps these methods behind one enum-driven interface using an O(1) ring buffer, shared window storage, readiness checks, input validation, and optional annualization. Two indicat...
π Read | Freelance | @mql5dev
β€18π6π€3π1
Mantis targets time-series classification for trading tasks where forecasting models struggle: it learns regime and pattern labels efficiently, with reliable confidence for decision-making.
The core design splits a series into a fixed number of patches, then applies hybrid attention using local convolution/pooling tokens plus global tokens. This keeps computation near-linear while still capturing microstructure and longer trends in high-frequency data.
Self-supervised contrastive pretraining builds stable embeddings across augmentations, making patterns robust to timing and amplitude shifts. A calibration step via temperature scaling turns logits into probabilities that better match real-world hit rates for risk management.
For multivariate inputs, lightweight channel adapters compress cross-indicator relationships without parameter blowup, enabling practi...
π Read | AlgoBook | @mql5dev
The core design splits a series into a fixed number of patches, then applies hybrid attention using local convolution/pooling tokens plus global tokens. This keeps computation near-linear while still capturing microstructure and longer trends in high-frequency data.
Self-supervised contrastive pretraining builds stable embeddings across augmentations, making patterns robust to timing and amplitude shifts. A calibration step via temperature scaling turns logits into probabilities that better match real-world hit rates for risk management.
For multivariate inputs, lightweight channel adapters compress cross-indicator relationships without parameter blowup, enabling practi...
π Read | AlgoBook | @mql5dev
β€14π3β‘1π1
MetaTrader 5 stores deal history in an opaque format and exports mainly as static HTML, which limits querying, joins, and automated reporting.
An Expert Advisor can persist each OnTrade() event into an SQLite file in MQL5/Files/ using the built-in Database* API (build 2485+). Deals are captured incrementally by comparing HistoryDealsTotal() to the last processed count, with OnInit() reconciling missing rows after restarts via SELECT COUNT(*).
SQLite provides indexed, parameterized INSERTs via DatabasePrepare/DatabaseBind/DatabaseRead and supports fast analytics with standard SQL. A single trade_events table can store OPEN/CLOSE/BALANCE/OTHER with event_time as sortable YYYY.MM.DD HH:MM:SS text.
π Read | Docs | @mql5dev
An Expert Advisor can persist each OnTrade() event into an SQLite file in MQL5/Files/ using the built-in Database* API (build 2485+). Deals are captured incrementally by comparing HistoryDealsTotal() to the last processed count, with OnInit() reconciling missing rows after restarts via SELECT COUNT(*).
SQLite provides indexed, parameterized INSERTs via DatabasePrepare/DatabaseBind/DatabaseRead and supports fast analytics with standard SQL. A single trade_events table can store OPEN/CLOSE/BALANCE/OTHER with event_time as sortable YYYY.MM.DD HH:MM:SS text.
π Read | Docs | @mql5dev
β€24π3π¨βπ»3β2π1
Mini Panel Manager streamlines manual trade execution through a compact interface with focused controls.
The Information Panel shows account status and all active positions with real-time updates. The Trading Panel provides Buy and Sell actions with Magic Number support so automated logic can tag and manage its own orders consistently.
Position management tools include a dedicated Closing Panel for fast exit of selected trades. The Average TP Panel sets or updates Take Profit from the average entry price across open positions, useful for basket handling.
Risk and automation options include a Break-even Panel that shifts positions to break-even after a defined profit threshold, plus an Auto Grid Panel that can add grid or martingale orders when enabled.
π Read | Calendar | @mql5dev
The Information Panel shows account status and all active positions with real-time updates. The Trading Panel provides Buy and Sell actions with Magic Number support so automated logic can tag and manage its own orders consistently.
Position management tools include a dedicated Closing Panel for fast exit of selected trades. The Average TP Panel sets or updates Take Profit from the average entry price across open positions, useful for basket handling.
Risk and automation options include a Break-even Panel that shifts positions to break-even after a defined profit threshold, plus an Auto Grid Panel that can add grid or martingale orders when enabled.
π Read | Calendar | @mql5dev
β€17π4π€£2π1
A Relative Moving Average (RMA) framework for MT5 implements Daniel A. Blochβs construction, not Wilder-style smoothing. The core output is a fractile f_w: the current close is ranked inside a trailing window of normalised returns (close/SMA - 1) and mapped to a consistent [0, 1] scale across symbols and volatility regimes.
The stack is kept explicit: window SMA as equilibrium, an RMA family of scale-free ratios (sma/x - 1) at key landmarks, and empirical-CDF fractiles for current/min/max. On top, a regime classifier flags expansion, contraction, and transitions using extremum ratios with slope, z-score, and variation corroboration, plus adverse-movement metrics d_med_w and D_k for directional consistency.
Two indicators ship together. An engine publishes 19 buffers for reuse by EAs/indicators and draws f_w, envelope fractiles, smoothed quantile mean...
π Read | Signals | @mql5dev
The stack is kept explicit: window SMA as equilibrium, an RMA family of scale-free ratios (sma/x - 1) at key landmarks, and empirical-CDF fractiles for current/min/max. On top, a regime classifier flags expansion, contraction, and transitions using extremum ratios with slope, z-score, and variation corroboration, plus adverse-movement metrics d_med_w and D_k for directional consistency.
Two indicators ship together. An engine publishes 19 buffers for reuse by EAs/indicators and draws f_w, envelope fractiles, smoothed quantile mean...
π Read | Signals | @mql5dev
β€16π2π2π2
An MT5 Expert Advisor implements the Relative Moving Average framework based on fractiles rather than price levels. Each bar is ranked inside a trailing return distribution as a value in [0, 1], aiming to make thresholds portable across symbols and volatility regimes. The calculation is centralized in a companion indicator loaded via iCustom, so chart state and trading state cannot diverge, and the signal rules remain broker-independent.
All four cross-strategies are included: cross-reverse and cross-revert on both sides. Entries are armed at distribution extremes and triggered by subsequent quantile-bin crossings, not by the extreme itself. Exits use an Adaptive Crossover Exit that switches by regime between a full distribution crossover and an extremum revert trigger, with a separate adverse-movement safety exit and a re-entry block until median recross.
...
π Read | NeuroBook | @mql5dev
All four cross-strategies are included: cross-reverse and cross-revert on both sides. Entries are armed at distribution extremes and triggered by subsequent quantile-bin crossings, not by the extreme itself. Exits use an Adaptive Crossover Exit that switches by regime between a full distribution crossover and an extremum revert trigger, with a separate adverse-movement safety exit and a re-entry block until median recross.
...
π Read | NeuroBook | @mql5dev
π12β€11π2β‘1
This article explores whether astronomical cycles can be modeled as measurable market inputs rather than superstition. The core idea is a layered mechanism: lunar/solar rhythms influence sleep, stress, and risk appetite, which can synchronize trader behavior and show up as volatility and directional bias.
A practical pipeline is built around stable constants (synodic month, tropical year) plus each currencyβs βbirth date.β Currency traits (risk-on vs safe-haven) are encoded as coefficients, then combined with lunar/solar phase angles and multiple harmonics (sin/cos features) to capture overlapping periodic effects. Lagged versions of these signals add market βmemory,β producing 88 features per weekly bar.
Using MetaTrader 5 data (15 years EUR/USD) and CatBoost with chronological splitting, the model predicts βsignificant up-moveβ as a binary task. Results s...
π Read | NeuroBook | @mql5dev
A practical pipeline is built around stable constants (synodic month, tropical year) plus each currencyβs βbirth date.β Currency traits (risk-on vs safe-haven) are encoded as coefficients, then combined with lunar/solar phase angles and multiple harmonics (sin/cos features) to capture overlapping periodic effects. Lagged versions of these signals add market βmemory,β producing 88 features per weekly bar.
Using MetaTrader 5 data (15 years EUR/USD) and CatBoost with chronological splitting, the model predicts βsignificant up-moveβ as a binary task. Results s...
π Read | NeuroBook | @mql5dev
β€15π8π4π€1
Mantis reframes time-series modeling as regime classification with calibrated probabilities, not fragile point forecasting. It standardizes inputs via tokenized patches and uses hybrid attention to capture both local microstructure and long-range context. Contrastive pretraining builds embeddings that stay stable under shifts, scaling, and noise, while temperature scaling turns scores into reliable confidence.
This article moves from theory to MT5 implementation details: adding temporal/positional encoding using an existing CMamba4CastEmbedding module, then building the patching stage that makes processing independent of raw sequence length.
A key engineering change is replacing mean-pooling with per-channel convolution plus max-pooling to preserve sharp moves. The CNeuronMantisPatching pipeline uses transpositions for axis-isolated processing, th...
π Read | VPS | @mql5dev
This article moves from theory to MT5 implementation details: adding temporal/positional encoding using an existing CMamba4CastEmbedding module, then building the patching stage that makes processing independent of raw sequence length.
A key engineering change is replacing mean-pooling with per-channel convolution plus max-pooling to preserve sharp moves. The CNeuronMantisPatching pipeline uses transpositions for axis-isolated processing, th...
π Read | VPS | @mql5dev
β€12π10π2π1
Automatic object placement removes the manual dependency from earlier chart-object pipelines. The system generates pitchforks, trendlines, Fibonacci, channels, and support/resistance directly from detected swing structure, then routes them through the same evaluators used for user-drawn objects.
A modular layout is used: swing detection, object placement, market data caching, signal evaluation, topology management, and adaptive execution. Swing detection relies on cached OHLC arrays to avoid repeated iHigh/iLow calls and identifies highs/lows via strict neighbor comparisons.
TopologyManager coordinates placement, scanning, evaluator lifecycle, and signal processing, with throttling to limit redraw and scan overhead. Chart events trigger immediate refresh to remove timer polling latency.
AdaptiveTrade calculates instrument-aware SL/TP using point size, s...
π Read | NeuroBook | @mql5dev
A modular layout is used: swing detection, object placement, market data caching, signal evaluation, topology management, and adaptive execution. Swing detection relies on cached OHLC arrays to avoid repeated iHigh/iLow calls and identifies highs/lows via strict neighbor comparisons.
TopologyManager coordinates placement, scanning, evaluator lifecycle, and signal processing, with throttling to limit redraw and scan overhead. Chart events trigger immediate refresh to remove timer polling latency.
AdaptiveTrade calculates instrument-aware SL/TP using point size, s...
π Read | NeuroBook | @mql5dev
β€25π4π4π₯1
MetaTrader 5 keeps full tick history in its cache, but exporting it for external analysis is bottlenecked by CSV size, slow parsing, and rounding from text conversion. A binary export solves this with fixed-width records: ~48 bytes per tick versus ~60+ in CSV, faster loads, and exact IEEE-754 price preservation.
The script defines a simple file format: a 64-byte header (magic ID, version, symbol, digits, tick count, time range) followed by contiguous 48-byte tick records (time_msc, bid/ask/last, volume, flags, padding). This enables direct random access and zero-parse reading in Python via NumPy.
Implementation is modular: separate structs for header and tick layout, then an exporter that uses CopyTicksRange(COPY_TICKS_ALL), writes the header with FileWriteStruct, and writes tick batches with FileWriteArray for high throughput.
π Read | Freelance | @mql5dev
The script defines a simple file format: a 64-byte header (magic ID, version, symbol, digits, tick count, time range) followed by contiguous 48-byte tick records (time_msc, bid/ask/last, volume, flags, padding). This enables direct random access and zero-parse reading in Python via NumPy.
Implementation is modular: separate structs for header and tick layout, then an exporter that uses CopyTicksRange(COPY_TICKS_ALL), writes the header with FileWriteStruct, and writes tick batches with FileWriteArray for high throughput.
π Read | Freelance | @mql5dev
β€18π7π2
Mean-variance allocators can become unstable when instruments are highly correlated, due to covariance matrix inversion. Small estimation noise can translate into large, leveraged long/short weights that flip across windows.
Hierarchical Risk Parity (Lopez de Prado, 2016) avoids inversion. The workflow converts prices to simple returns, builds covariance and correlation matrices, clusters instruments via a correlation-to-distance transform, then forms a binary merge tree using single-linkage.
Tree order drives quasi-diagonalization, pushing correlated instruments into blocks. Recursive bisection allocates capital across blocks using cluster variance from an inverse-variance sub-portfolio and a covariance quadratic form, producing long-only weights that sum to 1. A rebalancing EA can apply the output per basket.
π Read | Docs | @mql5dev
Hierarchical Risk Parity (Lopez de Prado, 2016) avoids inversion. The workflow converts prices to simple returns, builds covariance and correlation matrices, clusters instruments via a correlation-to-distance transform, then forms a binary merge tree using single-linkage.
Tree order drives quasi-diagonalization, pushing correlated instruments into blocks. Recursive bisection allocates capital across blocks using cluster variance from an inverse-variance sub-portfolio and a covariance quadratic form, producing long-only weights that sum to 1. A rebalancing EA can apply the output per basket.
π Read | Docs | @mql5dev
β€14π8π1
ACCS (Artificial Coronary Circulation System) is a bio-inspired metaheuristic by Kaveh and Kooshkbaghi (2019). Candidate solutions are modeled as arteries/capillaries, with Coronary Growth Factor (CGF) used to weight solution quality and influence search dynamics.
Core mechanics: random population init, center position calculation, CGF normalization, then alternating global search (direction based on CGF vs center) and local search (update toward best and away from worst with an iteration-dependent factor). Pruning reverts worsening moves.
Implementation uses Heart Memory to retain the top solutions (default 25% of population, minimum 1). Data structures separate persistent best states from temporary trial positions, followed by a selection phase that commits global-search candidates and refreshes memory by fitness sorting.
π Read | Calendar | @mql5dev
Core mechanics: random population init, center position calculation, CGF normalization, then alternating global search (direction based on CGF vs center) and local search (update toward best and away from worst with an iteration-dependent factor). Pruning reverts worsening moves.
Implementation uses Heart Memory to retain the top solutions (default 25% of population, minimum 1). Data structures separate persistent best states from temporary trial positions, followed by a selection phase that commits global-search candidates and refreshes memory by fitness sorting.
π Read | Calendar | @mql5dev
β€15π6π1π1
An indicator calculates the Asian session range (default 00:00β08:00 server time) and plots the high/low as horizontal levels. It then monitors the London session for confirmed breaks and retests of these levels, generating buy/sell signals intended for manual scalping around the London open.
The current session range is drawn on-chart with breakout and retest highlights. Signals are fixed on closed bars with no repainting. Supported timeframes include M1, M5, and M15 across any symbol.
Key inputs include SessionStartHour and SessionEndHour for range definition, optional EMA-based trend confirmation, and an optional volume filter to avoid low-activity moves. SignalMode supports alerts, push notifications, or arrows only. Default trade management levels can be set via StopLevelPips and TakeLevelPips.
π Read | Quotes | @mql5dev
The current session range is drawn on-chart with breakout and retest highlights. Signals are fixed on closed bars with no repainting. Supported timeframes include M1, M5, and M15 across any symbol.
Key inputs include SessionStartHour and SessionEndHour for range definition, optional EMA-based trend confirmation, and an optional volume filter to avoid low-activity moves. SignalMode supports alerts, push notifications, or arrows only. Default trade management levels can be set via StopLevelPips and TakeLevelPips.
π Read | Quotes | @mql5dev
β€9π4π€£2π¨βπ»2πΎ2β‘1
Symbolic Aggregate approXimation (SAX) turns a rolling price window into a short word, enabling text-style matching over market history. The pipeline z-normalises to keep shape only, applies Piecewise Aggregate Approximation to reduce dimensionality, then discretises via Gaussian breakpoints so letters are equiprobable.
Historical search uses a two-stage process: prune candidates with MINDIST, which provably lower-bounds Euclidean distance on z-normalised series, then rank survivors by true Euclidean distance. A validation harness confirms the same matches as brute force while skipping most comparisons.
The indicator scans for prior analogs with strict no-lookahead, measures each analogβs forward path in ATR units, and projects a median plus interquartile band as a fan cone. A verdict panel reports the current word, analog count and distances, forwa...
π Read | Docs | @mql5dev
Historical search uses a two-stage process: prune candidates with MINDIST, which provably lower-bounds Euclidean distance on z-normalised series, then rank survivors by true Euclidean distance. A validation harness confirms the same matches as brute force while skipping most comparisons.
The indicator scans for prior analogs with strict no-lookahead, measures each analogβs forward path in ATR units, and projects a median plus interquartile band as a fan cone. A verdict panel reports the current word, analog count and distances, forwa...
π Read | Docs | @mql5dev
β€11π3
Trade Analytics Dashboard indicator reads the terminalβs closed-deal history via HistorySelect() and HistoryDealGetTicket(), aggregates results, and renders a compact on-chart panel using CCanvas. No price analysis and no order placement, modification, or closure. Since it only reads existing deals, it does not require AutoTrading permission.
Panel fields summarize the selected lookback window: trade count, win rate (at/above break-even including swap/commission), profit factor (gross profit divided by gross loss), and net P/L with visual gain/loss coloring. It also reports current win/loss streak from the most recent deal, best and worst contributing symbols, and a simple cumulative equity curve line.
Inputs are grouped for layout, data scope, and colors: anchor corner and pixel offsets, panel size, refresh interval independent of ticks, history da...
π Read | AppStore | @mql5dev
Panel fields summarize the selected lookback window: trade count, win rate (at/above break-even including swap/commission), profit factor (gross profit divided by gross loss), and net P/L with visual gain/loss coloring. It also reports current win/loss streak from the most recent deal, best and worst contributing symbols, and a simple cumulative equity curve line.
Inputs are grouped for layout, data scope, and colors: anchor corner and pixel offsets, panel size, refresh interval independent of ticks, history da...
π Read | AppStore | @mql5dev
β€11π5π1
Session Volatility Heatmap is a measurement indicator designed to map real, symbol-specific intraday movement instead of relying on textbook session times. It loads InpLookbackDays of history on the active timeframe, groups each barβs (high β low) range by the hour the bar closes, and averages all 24 hourly buckets.
Output is split into two aligned views. A compact heatmap panel shows 24 hourly columns of the broker/server day: higher, warmer columns indicate historically larger hourly ranges; lower, cooler columns indicate quieter periods. Session bands are also drawn behind candles for the last InpSessionDays, marking Asian, London, and New York windows in server time; overlaps typically align with the highest-liquidity hours.
Used together, the heatmap identifies the hour and the session shading provides context. If peak hours do not match sessi...
π Read | NeuroBook | @mql5dev
Output is split into two aligned views. A compact heatmap panel shows 24 hourly columns of the broker/server day: higher, warmer columns indicate historically larger hourly ranges; lower, cooler columns indicate quieter periods. Session bands are also drawn behind candles for the last InpSessionDays, marking Asian, London, and New York windows in server time; overlaps typically align with the highest-liquidity hours.
Used together, the heatmap identifies the hour and the session shading provides context. If peak hours do not match sessi...
π Read | NeuroBook | @mql5dev
π9β€7β‘2
Most risk tooling in MT5 assumes the next worst loss will resemble the worst already observed. ATR sizing, Monte Carlo reshuffles, and historical VaR all stay inside the sampled distribution and tend to understate fat-tailed crash risk.
A native MQL5 indicator applies Extreme Value Theory using Peaks-Over-Threshold. Closes are converted into a one-sided downside loss series, exceedances above a high quantile are extracted, and a Generalized Pareto Distribution is fit with maximum-likelihood optimisation via the terminalβs built-in constrained optimiser, with no external dependencies.
It reports rolling EVT VaR, EVT Expected Shortfall, and the fitted tail shape xi with regime colouring. The engine refuses to print numbers without enough exceedances (floor of 30) and withholds ES when the fitted shape makes the mean diverge. This is a magnitude gauge for ex...
π Read | Signals | @mql5dev
A native MQL5 indicator applies Extreme Value Theory using Peaks-Over-Threshold. Closes are converted into a one-sided downside loss series, exceedances above a high quantile are extracted, and a Generalized Pareto Distribution is fit with maximum-likelihood optimisation via the terminalβs built-in constrained optimiser, with no external dependencies.
It reports rolling EVT VaR, EVT Expected Shortfall, and the fitted tail shape xi with regime colouring. The engine refuses to print numbers without enough exceedances (floor of 30) and withholds ES when the fitted shape makes the mean diverge. This is a magnitude gauge for ex...
π Read | Signals | @mql5dev
β€2π1