Retail volume bars report transaction count per period, but without price response they add little. High volume with limited price progress often signals absorption rather than trend strength, with aggressive flow being met by resting liquidity.
Kyleโs Lambda measures liquidity density via a simple impact ratio: |ฮPrice|/Volume. The result approximates the cost to move price by one point, separating real participation from low-quality moves driven by thin liquidity.
Low lambda during high volume indicates absorption and potential accumulation or distribution zones. High lambda spikes flag liquidity vacuums where small volume produces outsized gaps and unstable continuation.
Implementation notes for MT4 include backward-index parsing to minimize CPU load in a single-threaded runtime, plus division guards for session opens, weekend gaps, and zero-v...
๐ Read | Calendar | @mql5dev
Kyleโs Lambda measures liquidity density via a simple impact ratio: |ฮPrice|/Volume. The result approximates the cost to move price by one point, separating real participation from low-quality moves driven by thin liquidity.
Low lambda during high volume indicates absorption and potential accumulation or distribution zones. High lambda spikes flag liquidity vacuums where small volume produces outsized gaps and unstable continuation.
Implementation notes for MT4 include backward-index parsing to minimize CPU load in a single-threaded runtime, plus division guards for session opens, weekend gaps, and zero-v...
๐ Read | Calendar | @mql5dev
โค43๐15๐3๐3๐ฏ1
An Expert Advisor design combines three standard building blocks: ADX for trend strength confirmation, EMA for pullback timing, and ATR for volatility-scaled risk controls. Signal processing is restricted to closed bars on a selectable indicator timeframe and evaluated once per new bar.
Entry requires ADX above a threshold and rising versus the prior bar, filtering out flat or weakening conditions. A pullback is identified when the price-to-EMA distance (normalized by ATR) transitions from at-or-above a configured ratio to below it on the next bar, indicating a completed approach-and-rejection sequence.
Direction is taken from +DI and -DI on the prior bar, with optional buy-only or sell-only constraints. Stop loss is set as ATR multiplied by an SL factor, while take profit is derived via a fixed risk-reward ratio. Execution enforces one open position per sy...
๐ Read | Forum | @mql5dev
Entry requires ADX above a threshold and rising versus the prior bar, filtering out flat or weakening conditions. A pullback is identified when the price-to-EMA distance (normalized by ATR) transitions from at-or-above a configured ratio to below it on the next bar, indicating a completed approach-and-rejection sequence.
Direction is taken from +DI and -DI on the prior bar, with optional buy-only or sell-only constraints. Stop loss is set as ATR multiplied by an SL factor, while take profit is derived via a fixed risk-reward ratio. Execution enforces one open position per sy...
๐ Read | Forum | @mql5dev
๐21โค15๐3
The article reframes โmarket physicsโ as modeling price with measurable components rather than intuitive narratives. Since price is discrete, derivatives are treated as average changes over a fixed step, and only statistical properties (expectation, variance) are considered realistically exploitable.
A practical simplification is proposed: approximate the predictable component via market-player pressure, expressed as the imbalance between aggregated buy and sell volumes. To avoid unreliable, broker-specific tick streams, the model prefers bar data (O/H/L/C) for stability and speed.
It then outlines four ways to extract patternsโhand-built formulas, order-flow simulation, general mathematical principles, and machine learningโhighlighting a position-simulator EA that places stop/limit/market order grids per bar, updates incrementally, and trades on the evolvi...
๐ Read | Forum | @mql5dev
A practical simplification is proposed: approximate the predictable component via market-player pressure, expressed as the imbalance between aggregated buy and sell volumes. To avoid unreliable, broker-specific tick streams, the model prefers bar data (O/H/L/C) for stability and speed.
It then outlines four ways to extract patternsโhand-built formulas, order-flow simulation, general mathematical principles, and machine learningโhighlighting a position-simulator EA that places stop/limit/market order grids per bar, updates incrementally, and trades on the evolvi...
๐ Read | Forum | @mql5dev
โค42๐25โ7๐2
A time-based exit routine can be built by storing configured hour and minute values, then checking the platform time on each tick. When the current time matches the configured schedule, the logic can run only once per day to prevent repeated triggers.
A separate date check should confirm that the current weekday is Friday before acting. If not Friday, the routine should exit without changes.
When both conditions are met, filter open positions by symbol (currency pair) and evaluate profit per position. Close only positions with positive profit, leaving losing or zero-profit positions untouched. Use reliable order/position iteration, handle partial fills, validate trade permissions, and log close results and error codes for auditing.
๐ Read | Signals | @mql5dev
A separate date check should confirm that the current weekday is Friday before acting. If not Friday, the routine should exit without changes.
When both conditions are met, filter open positions by symbol (currency pair) and evaluate profit per position. Close only positions with positive profit, leaving losing or zero-profit positions untouched. Use reliable order/position iteration, handle partial fills, validate trade permissions, and log close results and error codes for auditing.
๐ Read | Signals | @mql5dev
โค20๐8๐1
MetaTrader 5 frames AI trading as an end-to-end engineering workflow: terminal-grade market data, research in Python, model deployment, deterministic testing, and automated execution in one ecosystem. The emphasis is on turning ideas into reproducible systems, not persuasive predictions.
Python integration pulls bars, ticks, symbol specs, and account state directly from the terminal, reducing train/live data mismatches. Trained models can be exported to ONNX and embedded into MQL5 EAs, keeping inference local and testable in the Strategy Tester.
For LLM-assisted analysis, WebRequest can power an on-chart assistant, but external services are non-deterministic and unavailable in the Strategy Tester. The practical pattern is structured LLM outputs plus an โAI signal dispatcherโ that validates confidence, margin, broker limits, duplicates, and strategy r...
๐ Read | NeuroBook | @mql5dev
Python integration pulls bars, ticks, symbol specs, and account state directly from the terminal, reducing train/live data mismatches. Trained models can be exported to ONNX and embedded into MQL5 EAs, keeping inference local and testable in the Strategy Tester.
For LLM-assisted analysis, WebRequest can power an on-chart assistant, but external services are non-deterministic and unavailable in the Strategy Tester. The practical pattern is structured LLM outputs plus an โAI signal dispatcherโ that validates confidence, margin, broker limits, duplicates, and strategy r...
๐ Read | NeuroBook | @mql5dev
โค31๐5๐5๐1
Many MT5 trading models fail live because they overfit history and donโt cope with regime shifts; accuracy often collapses to the lowโ50% range with large drawdowns. The article proposes a โquantum-inspiredโ architecture that treats market signals as interacting components: superposition (conflicting multi-timeframe evidence), interference (signals reinforcing/canceling), decoherence (event impact decays), and resonance (cycle alignment amplifies trends).
The EA processes 400+ quantized features (price, volume, indicators, patterns, time/cycle signals) through a pipeline combining quantum-style signal processing, multi-level memory, Markov regime states, transformer attention, and a 256-dim state-space model for long-horizon dynamics. It also uses dynamic class weighting to improve recall on rare strong-move events.
Delivered as MQL5 source (Simpl...
๐ Read | NeuroBook | @mql5dev
The EA processes 400+ quantized features (price, volume, indicators, patterns, time/cycle signals) through a pipeline combining quantum-style signal processing, multi-level memory, Markov regime states, transformer attention, and a 256-dim state-space model for long-horizon dynamics. It also uses dynamic class weighting to improve recall on rare strong-move events.
Delivered as MQL5 source (Simpl...
๐ Read | NeuroBook | @mql5dev
โค25๐6๐1
Work on a MetaTrader 5 custom crosshair indicator in MQL5, built from mouse event handling without requiring OOP.
Key point is converting OS screen X/Y into chart time/price via ChartXYToTimePrice, then driving OBJ_VLINE and OBJ_HLINE with those values. Intraday timestamps on higher timeframes are expected due to fractional coordinate mapping.
Implementation evolves from always-on crosshair to middle-button toggle, then adds hide/show control via a key event. Price is normalized to the symbol tick size to keep the horizontal line on valid tradable prices.
Final step extracts the crosshair logic into a header, adds a structure to return current mouse-derived values, and keeps the indicator file minimal for reuse across tools.
๐ Read | Signals | @mql5dev
Key point is converting OS screen X/Y into chart time/price via ChartXYToTimePrice, then driving OBJ_VLINE and OBJ_HLINE with those values. Intraday timestamps on higher timeframes are expected due to fractional coordinate mapping.
Implementation evolves from always-on crosshair to middle-button toggle, then adds hide/show control via a key event. Price is normalized to the symbol tick size to keep the horizontal line on valid tradable prices.
Final step extracts the crosshair logic into a header, adds a structure to return current mouse-derived values, and keeps the indicator file minimal for reuse across tools.
๐ Read | Signals | @mql5dev
โค18๐8๐1
MetaTrader 5 object events provide a structured way to react to chart object lifecycle changes, including click, move, property edits, creation, and deletion. Most of these notifications are disabled by default and must be explicitly enabled, reducing overhead when object monitoring is not required.
Event-based handling avoids constant polling of object state, which increases CPU use and complexity. It also supports defensive logic when users modify application-owned objects, intentionally or accidentally.
A practical case is object duplication via Ctrl+drag. MT5 generates a new standardized name (timeframe, object type, random suffix), which can be used to detect likely duplicates and enforce rules such as single-instance informational objects.
๐ Read | Forum | @mql5dev
Event-based handling avoids constant polling of object state, which increases CPU use and complexity. It also supports defensive logic when users modify application-owned objects, intentionally or accidentally.
A practical case is object duplication via Ctrl+drag. MT5 generates a new standardized name (timeframe, object type, random suffix), which can be used to detect likely duplicates and enforce rules such as single-instance informational objects.
๐ Read | Forum | @mql5dev
โค23๐6๐1๐1
Static-weight SMA/EMA filters canโt handle regime shifts: they jitter in tight ranges and lag on breakouts. This piece replaces the fixed blend with a scalar Kalman smoother where the per-bar Kalman Gain becomes the optimal, adaptive weight between the latest close and the prior estimate.
The model treats price as a latent โtrueโ state with a random-walk process and noisy measurements. Process noise Q and measurement noise R are estimated online from rolling variances of returns and price deviations, then floor-clamped to avoid zero-volatility degeneration.
Implementation details focus on MT5 usability: a native MQL5 indicator with controlled warmup, stable single-pass rolling variance, incremental OnCalculate updates, and Kalman Gain exposed in the Data Window via an invisible INDICATOR_DATA plot (clrNONE) without adding chart clutter.
๐ Read | AppStore | @mql5dev
The model treats price as a latent โtrueโ state with a random-walk process and noisy measurements. Process noise Q and measurement noise R are estimated online from rolling variances of returns and price deviations, then floor-clamped to avoid zero-volatility degeneration.
Implementation details focus on MT5 usability: a native MQL5 indicator with controlled warmup, stable single-pass rolling variance, incremental OnCalculate updates, and Kalman Gain exposed in the Data Window via an invisible INDICATOR_DATA plot (clrNONE) without adding chart clutter.
๐ Read | AppStore | @mql5dev
โค23๐4๐2๐1
Short rolling Sharpe readings in MT5 often look like โalphaโ but are mostly estimation noise: the standard error shrinks only with 1/โn, so 40โ60 bars canโt reliably separate skill from randomness. The article formalizes this using Loโs Sharpe standard error, then annualizes both Sharpe and its uncertainty to build a practical confidence band.
RollingSharpe.mq5 plots annualized Sharpe plus upper/lower bounds at ยฑ1.96ยทSE. The core rule is simple: if the band crosses zero, the observed Sharpe is not statistically significant.
On the engineering side, it addresses MT5โs recalculation pitfalls (prev_calculated=0, partial history) by using stateless per-bar, two-pass variance computation for the indicator, while providing reusable O(1) circular-buffer classes for EAs where sequential updates are safe.
๐ Read | Calendar | @mql5dev
RollingSharpe.mq5 plots annualized Sharpe plus upper/lower bounds at ยฑ1.96ยทSE. The core rule is simple: if the band crosses zero, the observed Sharpe is not statistically significant.
On the engineering side, it addresses MT5โs recalculation pitfalls (prev_calculated=0, partial history) by using stateless per-bar, two-pass variance computation for the indicator, while providing reusable O(1) circular-buffer classes for EAs where sequential updates are safe.
๐ Read | Calendar | @mql5dev
โค31๐5๐2
Weekend gap trading can be automated by pairing a custom indicator with an MQL5 Expert Advisor that executes orders from indicator buffers.
The indicator must expose buffers read via CopyBuffer(). Six buffers are used: buy/sell arrows plus TP/SL for each direction. Buffers are registered with SetIndexBuffer(), and the EA connects through iCustom() to avoid re-implementing gap detection.
The EA structure centers on inputs (lot size, slippage, magic, closed-bar confirmation, duplicate handling, opposite-position logic, midpoint SL rules), a CTrade instance, an indicator handle, buffer arrays, and state variables. Utility functions centralize buffer reads, empty checks, duplicate-bar tracking, position lookup, stop validation, and optional reversal.
OnTick() runs once per new bar, copies buffers, validates setups against broker stop distances, places Buy/Sel...
๐ Read | CodeBase | @mql5dev
The indicator must expose buffers read via CopyBuffer(). Six buffers are used: buy/sell arrows plus TP/SL for each direction. Buffers are registered with SetIndexBuffer(), and the EA connects through iCustom() to avoid re-implementing gap detection.
The EA structure centers on inputs (lot size, slippage, magic, closed-bar confirmation, duplicate handling, opposite-position logic, midpoint SL rules), a CTrade instance, an indicator handle, buffer arrays, and state variables. Utility functions centralize buffer reads, empty checks, duplicate-bar tracking, position lookup, stop validation, and optional reversal.
OnTick() runs once per new bar, copies buffers, validates setups against broker stop distances, places Buy/Sel...
๐ Read | CodeBase | @mql5dev
โค19๐5๐2๐1
This part turns MMAR parameter estimates into a full synthetic price path via a single, stateless CSimulationEngine class designed for repeatable Monte Carlo runs. It relies only on MT5 Standard Library components: ALGLIB FFT and linear algebra plus Normal/Gamma/Poisson RNG, while keeping each intermediate array for inspection and validation.
Stage 1 builds multifractal trading time with a binary multiplicative cascade. Random multipliers come from the fitted distribution using M = b^(-V), are clamped for numerical safety, pair-normalized to conserve mass, then integrated into a CDF theta(t) that creates fast/slow market time.
Stage 2 generates fractional Brownian motion with H using either exact Cholesky (small n) or FFT-based DaviesโHarte (large n), with fallback on failure, then rescales to match observed volatility.
Stage 3 composes X(t)=B_H[theta...
๐ Read | Freelance | @mql5dev
Stage 1 builds multifractal trading time with a binary multiplicative cascade. Random multipliers come from the fitted distribution using M = b^(-V), are clamped for numerical safety, pair-normalized to conserve mass, then integrated into a CDF theta(t) that creates fast/slow market time.
Stage 2 generates fractional Brownian motion with H using either exact Cholesky (small n) or FFT-based DaviesโHarte (large n), with fallback on failure, then rescales to match observed volatility.
Stage 3 composes X(t)=B_H[theta...
๐ Read | Freelance | @mql5dev
โค14๐11๐1
Manual chart-object monitoring fails for three reasons: reaction latency, poor scalability across symbols/timeframes, and subjective โdid it touch?โ decisions. The article extends earlier MT5 object enumeration/normalization work into an automated pipeline that turns drawn tools into consistent, testable triggers.
The solution reuses normalized geometry in SComplexObjectInfo, then adds interaction logic that evaluates sloped objects at the current time (trendlines, channels, pitchfork median/levels) instead of comparing against static anchors. It also handles mixed object models: HLINE/VLINE single-axis coordinates, rectangles as zones, and Fibonacci levels read from the objectโs level arrays.
Architecture is split into modules: an updated collector (now includes HLINE/VLINE), an InteractionDetector that outputs touch/cross/breakout events with dir...
๐ Read | Signals | @mql5dev
The solution reuses normalized geometry in SComplexObjectInfo, then adds interaction logic that evaluates sloped objects at the current time (trendlines, channels, pitchfork median/levels) instead of comparing against static anchors. It also handles mixed object models: HLINE/VLINE single-axis coordinates, rectangles as zones, and Fibonacci levels read from the objectโs level arrays.
Architecture is split into modules: an updated collector (now includes HLINE/VLINE), an InteractionDetector that outputs touch/cross/breakout events with dir...
๐ Read | Signals | @mql5dev
โค21๐10๐5
This CoSO implementation treats optimization like managing a research lab: โfundsโ act as discrete compute/iteration budget, allocated between proven agents and new entrants. AssignFunds splits budget by omegaCurrent, then distributes the main share via rank-weighted lottery so higher-ranked researchers get more opportunities without fully eliminating randomness.
Diversity is injected through CreateOutsiders, which spawns a limited number of new agents, initializes coordinates within bounds (with step snapping), normalizes per-agent probability vectors, and enforces population caps with controlled growth.
HireResearchers adds exploitation: funded supervisors spawn nearby variants that inherit best-known positions and bias parameters, with Gaussian perturbations to keep local search active.
ComputeStdDev measures population dispersion, and UpdateOm...
๐ Read | VPS | @mql5dev
Diversity is injected through CreateOutsiders, which spawns a limited number of new agents, initializes coordinates within bounds (with step snapping), normalizes per-agent probability vectors, and enforces population caps with controlled growth.
HireResearchers adds exploitation: funded supervisors spawn nearby variants that inherit best-known positions and bias parameters, with Gaussian perturbations to keep local search active.
ComputeStdDev measures population dispersion, and UpdateOm...
๐ Read | VPS | @mql5dev
โค18๐6๐1
This MT5/MQL5 deep dive focuses on the last three chart object events that matter when objects interact with users: delete, change, and end-edit. One key detail: some of these events are not generated unless explicitly enabled, so handlers can be correct yet never fire.
For CHARTEVENT_OBJECT_DELETE, the article shows how to catch deletions and immediately recreate โprotectedโ objects, including edge cases around when notifications are disabled and how UI lists lag behind recreated objects. A practical pattern is keeping an internal snapshot of object properties for reliable restoration.
For CHARTEVENT_OBJECT_CHANGE, it explains why user edits donโt persist after recreation unless the EA captures updated properties itself. Since MT5 reports only the object name, developers must selectively read and store relevant properties, with strict filtering to avoid...
๐ Read | NeuroBook | @mql5dev
For CHARTEVENT_OBJECT_DELETE, the article shows how to catch deletions and immediately recreate โprotectedโ objects, including edge cases around when notifications are disabled and how UI lists lag behind recreated objects. A practical pattern is keeping an internal snapshot of object properties for reliable restoration.
For CHARTEVENT_OBJECT_CHANGE, it explains why user edits donโt persist after recreation unless the EA captures updated properties itself. Since MT5 reports only the object name, developers must selectively read and store relevant properties, with strict filtering to avoid...
๐ Read | NeuroBook | @mql5dev
โค15๐9๐1
SQLite access in MetaTrader 5 still needs defensive testing, especially around result handling. Query execution and result reading are coupled: ExecRequestOfData must run before any read, because DatabaseReadBind returns rows from the last executed request.
A generic wrapper around DatabaseReadBind is used to mitigate MQL5 type constraints. The binding API effectively behaves like a void reference in C/C++, so templates are used to accept varying row structures without rewriting code when result shapes change.
Testing shows strict ordering rules. Field order in SELECT must match the structure used for reading, including joins. Extra columns can be returned and selectively ignored by switching structures, but mismatches between expected fields and returned columns produce unexpected output and require careful validation.
๐ Read | NeuroBook | @mql5dev
A generic wrapper around DatabaseReadBind is used to mitigate MQL5 type constraints. The binding API effectively behaves like a void reference in C/C++, so templates are used to accept varying row structures without rewriting code when result shapes change.
Testing shows strict ordering rules. Field order in SELECT must match the structure used for reading, including joins. Extra columns can be returned and selectively ignored by switching structures, but mismatches between expected fields and returned columns produce unexpected output and require careful validation.
๐ Read | NeuroBook | @mql5dev
โค36๐8โก3๐2๐2
The logic targets sessions with high-impact (red) economic events. It counts qualifying news items for the current date, then evaluates the next scheduled release time.
Before the release window, the EA places a pending order based on the configured direction, either Buy Stop/Buy Limit or Sell Stop/Sell Limit. Order placement is gated by the news count and the remaining time to the event, to avoid triggering outside the defined pre-news period.
Typical safeguards include preventing duplicate pending orders for the same event, applying spread and slippage limits, and removing or disabling orders after the release if the setup is no longer valid.
๐ Read | Quotes | @mql5dev
Before the release window, the EA places a pending order based on the configured direction, either Buy Stop/Buy Limit or Sell Stop/Sell Limit. Order placement is gated by the news count and the remaining time to the event, to avoid triggering outside the defined pre-news period.
Typical safeguards include preventing duplicate pending orders for the same event, applying spread and slippage limits, and removing or disabling orders after the release if the setup is no longer valid.
๐ Read | Quotes | @mql5dev
โค13๐6
This article moves MT5 metric export from backtest-only CSV dumps to a live streaming pipeline that stays useful during active market hours. The goal is continuous observability: indicator values, session counters, and equity snapshots become an auditable stream instead of an end-of-session artifact.
The design is a decoupled three-layer system: an MQL5 include that buffers rows and flushes in batches, a daily rotating CSV in the common files folder, and a Python tail daemon that reads appended rows, maintains rolling windows, and logs anomalies.
Key engineering details: open-write-close I/O to avoid long-held handles, configurable buffering to control latency vs. data loss risk, midnight-UTC rotation to cap file size, and per-symbol/timeframe filenames to prevent multi-chart conflicts. A demo indicator shows gating to avoid exporting historical back...
๐ Read | Signals | @mql5dev
The design is a decoupled three-layer system: an MQL5 include that buffers rows and flushes in batches, a daily rotating CSV in the common files folder, and a Python tail daemon that reads appended rows, maintains rolling windows, and logs anomalies.
Key engineering details: open-write-close I/O to avoid long-held handles, configurable buffering to control latency vs. data loss risk, midnight-UTC rotation to cap file size, and per-symbol/timeframe filenames to prevent multi-chart conflicts. A demo indicator shows gating to avoid exporting historical back...
๐ Read | Signals | @mql5dev
โค7๐7
This article turns candlestick charts into analyzable data by encoding each bar as a single symbol (A/G/H/E for bullish types, a/g/h/e for bearish, D for doji, and โ_โ for unclassified). Using 1,500-bar samples of GBPUSD and XAUUSD on H1/M15/M5, an MQL5 script generates an encoded series plus per-symbol counts and percentages in a TXT report.
On GBPUSD, Marubozu-like candles (A/a) dominate at ~20โ22% each, while 32โ36% of bars fall into the unclassified bucket, signaling where the taxonomy may need refinement. Bullish and bearish totals stay nearly symmetric across timeframes, and M5 shows a noticeable rise in doji frequency.
The practical output is a reproducible market โprofileโ that can feed next-step modeling: two-symbol pattern frequencies and transition probabilities for systematic strategy research.
๐ Read | AppStore | @mql5dev
On GBPUSD, Marubozu-like candles (A/a) dominate at ~20โ22% each, while 32โ36% of bars fall into the unclassified bucket, signaling where the taxonomy may need refinement. Bullish and bearish totals stay nearly symmetric across timeframes, and M5 shows a noticeable rise in doji frequency.
The practical output is a reproducible market โprofileโ that can feed next-step modeling: two-symbol pattern frequencies and transition probabilities for systematic strategy research.
๐ Read | AppStore | @mql5dev
๐1