MetaTrader 5 hides powerful βindicator-likeβ behavior inside chart objects. By programmatically repurposing OBJ_FIBO, the article builds a custom risk tool that visually marks entry, stop, and target using only a few configured levels.
The core technique sets a fixed number of Fibonacci levels, then assigns each level its value, color, and style via parallel arrays. Using values outside 0..1 turns Fibonacci into a projection engine, making it easy to express 1:1, 1:1.5, and partial-exit layouts that canβt be recreated manually from the UI.
Practical refinements include locking selection to prevent accidental moves, hiding unwanted guide lines, exposing a stop/target ratio as an input, and optionally disabling right-side extension so multiple analyses can coexist cleanly. The article also explores switching drawing flow toward left-click interaction, ...
π Read | Signals | @mql5dev
The core technique sets a fixed number of Fibonacci levels, then assigns each level its value, color, and style via parallel arrays. Using values outside 0..1 turns Fibonacci into a projection engine, making it easy to express 1:1, 1:1.5, and partial-exit layouts that canβt be recreated manually from the UI.
Practical refinements include locking selection to prevent accidental moves, hiding unwanted guide lines, exposing a stop/target ratio as an input, and optionally disabling right-side extension so multiple analyses can coexist cleanly. The article also explores switching drawing flow toward left-click interaction, ...
π Read | Signals | @mql5dev
π17β€12π3
Replay/simulation work in MQL5 is moving past sockets and SQL basics into chart-side tooling needed for realistic interaction.
Current components (mouse pointer, Chart Trade indicator, EA messaging) can submit market execution, but cross-orders and replay symbols lack reliable visual feedback for positions and orders.
Next step is a minimal position-visualization indicator. An indicator can read position state and print details, without attempting trade actions, which remain EA-only. This also highlights a platform constraint: indicators share a single chart thread, so the logic must avoid blocking and unnecessary updates.
Focus shifts to controlled chart objects for position lines, with attention to object lifecycle and cleanup to prevent long-term chart degradation.
π Read | Docs | @mql5dev
Current components (mouse pointer, Chart Trade indicator, EA messaging) can submit market execution, but cross-orders and replay symbols lack reliable visual feedback for positions and orders.
Next step is a minimal position-visualization indicator. An indicator can read position state and print details, without attempting trade actions, which remain EA-only. This also highlights a platform constraint: indicators share a single chart thread, so the logic must avoid blocking and unnecessary updates.
Focus shifts to controlled chart objects for position lines, with attention to object lifecycle and cleanup to prevent long-term chart degradation.
π Read | Docs | @mql5dev
π15β€8π3π€2
Protecting profit after a position is opened typically requires rules that react to price movement, not just the entry signal. Common approaches include moving the stop loss to breakeven after a defined profit threshold, then switching to a trailing stop to lock in gains as volatility expands or contracts.
A structured method uses staged stop management: initial fixed stop, breakeven activation, and trailing based on points, ATR, or recent swing levels. Partial closes can reduce risk while keeping exposure for continuation. Controls such as minimum distance, step size, and spread filters help avoid premature stop-outs in noisy conditions.
π Read | AlgoBook | @mql5dev
A structured method uses staged stop management: initial fixed stop, breakeven activation, and trailing based on points, ATR, or recent swing levels. Partial closes can reduce risk while keeping exposure for continuation. Controls such as minimum distance, step size, and spread filters help avoid premature stop-outs in noisy conditions.
π Read | AlgoBook | @mql5dev
π21β€15π3π3
Most MT5 risk tools implicitly cap worst-case planning to what the recent window already contains. ATR, bootstrapped trade resampling, and historical VaR all operate on observed volatility and outcomes, so tail losses beyond the sample are systematically understated.
Financial returns are fat-tailed, so rare moves occur more often than normal assumptions imply. Extreme Value Theory addresses this by modeling only the tail, allowing extrapolation beyond the historical maximum loss.
An MQL5-native implementation can use Peaks-Over-Threshold with a Generalized Pareto fit via ALGLIB MLE. Outputs include EVT VaR, Expected Shortfall, and a shape parameter that quantifies tail heaviness, with hard refusal to report metrics when exceedances are insufficient.
π Read | Signals | @mql5dev
Financial returns are fat-tailed, so rare moves occur more often than normal assumptions imply. Extreme Value Theory addresses this by modeling only the tail, allowing extrapolation beyond the historical maximum loss.
An MQL5-native implementation can use Peaks-Over-Threshold with a Generalized Pareto fit via ALGLIB MLE. Outputs include EVT VaR, Expected Shortfall, and a shape parameter that quantifies tail heaviness, with hard refusal to report metrics when exceedances are insufficient.
π Read | Signals | @mql5dev
β€23π13π2π¨βπ»2
Mean-reversion implementation in MetaTrader 5: weekly channel breaks using two moving averages on High and Low with a shared period. Break above the upper band triggers short bias; break below the lower band triggers long bias.
Signal confirmation uses an ONNX-backed statistical model plus daily open/close moving averages for directional filtering. Data pipeline exports EURUSD daily bars to CSV via MQL5, then trains in Python on 2011β2019 and tests on 2020β2026. Model selection highlights overfitting in flexible learners; a linear regressor is chosen and exported to ONNX.
The EA loads the ONNX model, manages trades via magic number filtering, updates indicator buffers, and applies ATR-based symmetric SL/TP with trailing stops. Backtests with real ticks and random delay show modest positive expectancy, profit factor near 1.1, and larger average win...
π Read | Calendar | @mql5dev
Signal confirmation uses an ONNX-backed statistical model plus daily open/close moving averages for directional filtering. Data pipeline exports EURUSD daily bars to CSV via MQL5, then trains in Python on 2011β2019 and tests on 2020β2026. Model selection highlights overfitting in flexible learners; a linear regressor is chosen and exported to ONNX.
The EA loads the ONNX model, manages trades via magic number filtering, updates indicator buffers, and applies ATR-based symmetric SL/TP with trailing stops. Backtests with real ticks and random delay show modest positive expectancy, profit factor near 1.1, and larger average win...
π Read | Calendar | @mql5dev
β€25π6β3π3β‘2π€1
False breaks of recent N-bar highs/lows often act as liquidity sweeps: price runs stops beyond an obvious extreme, then closes back inside the range. The article turns this into a fully testable Turtle Soup contract: minimum sweep depth (points and % of range), minimum age of the swept level, sweep-window rules, and close-based rejection confirmation (multiple closes, optional reversal body).
The MQL5 implementation focuses on robustness: bar-close execution, duplicate-signal guards, per-direction position caps, and broker stop-level compliance. Stops can be dynamic beyond the sweep extreme or fixed-point; targets support R-multiple projection or the opposite side of the lookback range, with optional trailing.
It also builds chart tooling (levels, sweep zones, risk/reward boxes) and a scan engine using iHighest/iLowest and close checks, ready for S...
π Read | CodeBase | @mql5dev
The MQL5 implementation focuses on robustness: bar-close execution, duplicate-signal guards, per-direction position caps, and broker stop-level compliance. Stops can be dynamic beyond the sweep extreme or fixed-point; targets support R-multiple projection or the opposite side of the lookback range, with optional trailing.
It also builds chart tooling (levels, sweep zones, risk/reward boxes) and a scan engine using iHighest/iLowest and close checks, ready for S...
π Read | CodeBase | @mql5dev
β€28π6π5
Price-window indicators in MQL5 often shift arrays with ArrayCopy() on every bar to keep index 0 as βlatestβ. That design is O(n) per update and scales poorly with large periods, multi-symbol sets, and dense OnCalculate() workloads.
A circular buffer removes the shift. Only a head index advances with modulo arithmetic, and one slot is overwritten. Push and Get become O(1) regardless of window size; allocation is fixed at construction.
An MQL5 template CCircularBuffer<T> fits this pattern but comes with constraints: no specialization, template code must stay in-header, and capacity must be runtime. Statistical routines should use two-pass variance to avoid cancellation common in price series.
Result: less memory movement per bar, improved backtest throughput, and reduced live tick latency under load.
π Read | Signals | @mql5dev
A circular buffer removes the shift. Only a head index advances with modulo arithmetic, and one slot is overwritten. Push and Get become O(1) regardless of window size; allocation is fixed at construction.
An MQL5 template CCircularBuffer<T> fits this pattern but comes with constraints: no specialization, template code must stay in-header, and capacity must be runtime. Statistical routines should use two-pass variance to avoid cancellation common in price series.
Result: less memory movement per bar, improved backtest throughput, and reduced live tick latency under load.
π Read | Signals | @mql5dev
β€25π8π¨βπ»3π2
This article upgrades the classic SuperTrend by making its ATR multiplier responsive to momentum divergence, using MPO4 (or optionally RSI) as the trigger. When a validated bullish/bearish divergence appears, a βshrinkingβ rule reduces the multiplier by a sensitivity factor, pulling the band closer to price. The result is tighter trailing stops near exhaustion and earlier flips for capturing the next trend.
A key focus is non-repainting behavior in MT5 indicators. Instead of fragile global flags, the design persists divergence context per bar via state buffers (last pivot prices/osc values, last divergence type, bars-since counter). State is propagated forward each iteration and reset on trend flips, keeping historical signals stable across ticks, refreshes, and restarts.
Implementation details cover a chart-window MQL5 indicator with a colored SuperTrend...
π Read | Docs | @mql5dev
A key focus is non-repainting behavior in MT5 indicators. Instead of fragile global flags, the design persists divergence context per bar via state buffers (last pivot prices/osc values, last divergence type, bars-since counter). State is propagated forward each iteration and reset on trend flips, keeping historical signals stable across ticks, refreshes, and restarts.
Implementation details cover a chart-window MQL5 indicator with a colored SuperTrend...
π Read | Docs | @mql5dev
β€32π12π3
BBandsPsar is a hybrid indicator combining Bollinger Bands volatility metrics with Parabolic SAR trend signaling in a single output.
The calculation tracks the distance between the Parabolic SAR level and the candle open/close, capturing SARβs alternating behavior during trend changes. This gap is then normalized through Bollinger Bands and rendered as a histogram.
Band-based standardization targets more stable thresholds across instruments, supporting cross-asset comparison on a unified scale. All configuration inputs from both Bollinger Bands and Parabolic SAR are retained, allowing adjustment of sensitivity, smoothing, and switching behavior to match market conditions.
π Read | Quotes | @mql5dev
The calculation tracks the distance between the Parabolic SAR level and the candle open/close, capturing SARβs alternating behavior during trend changes. This gap is then normalized through Bollinger Bands and rendered as a histogram.
Band-based standardization targets more stable thresholds across instruments, supporting cross-asset comparison on a unified scale. All configuration inputs from both Bollinger Bands and Parabolic SAR are retained, allowing adjustment of sensitivity, smoothing, and switching behavior to match market conditions.
π Read | Quotes | @mql5dev
β€25π7π2
Spreadsheets can be used as a lightweight research harness for algorithmic strategies: import MT5 history from CSV/TXT, normalize numeric formats, and keep the dataset small enough (around a few thousand rows) to avoid slow recalculation with minimal impact on results.
The workflow builds indicators directly in cells. A separate βvariablesβ sheet stores parameters, while functions like IF, AVERAGE and INDIRECT generate a configurable SMA over dynamic ranges. Relative vs absolute references ($) make formulas safe to copy across long columns.
A moving-average crossover is then modeled as stateful trade logic: one column detects crossings, another persists position status bar-by-bar, and a signal column maps actions (Buy/Sell/Close) with correct next-bar execution. Additional columns propagate entry price (including spread) and compute pip outcomes for late...
π Read | AppStore | @mql5dev
The workflow builds indicators directly in cells. A separate βvariablesβ sheet stores parameters, while functions like IF, AVERAGE and INDIRECT generate a configurable SMA over dynamic ranges. Relative vs absolute references ($) make formulas safe to copy across long columns.
A moving-average crossover is then modeled as stateful trade logic: one column detects crossings, another persists position status bar-by-bar, and a signal column maps actions (Buy/Sell/Close) with correct next-bar execution. Additional columns propagate entry price (including spread) and compute pip outcomes for late...
π Read | AppStore | @mql5dev
β€43π12β6π¨βπ»3πΎ3π2
Backtests only charge the costs that were configured, so net profit and profit factor do not show how close a strategy is to the execution-cost boundary. This MQL5 tool measures the limit directly: how much cost the strategy can absorb before the edge disappears.
It reads a CSV (Date,Profit,Volume; one row per closing deal) and prints a report to the Experts tab. Output includes breakeven cost per deal, cushion versus an assumed realistic cost, net and profit factor re-priced at the assumed cost, a cost-sensitivity curve from 0 to 3x, and win erosion where costs flip winners into losers. A composite A+ to F score aggregates cushion, profit-factor resilience, and erosion, with recommendations.
Input file goes to MQL5\Files; Volume is optional. If missing on first run, a reproducible sample file is generated. A helper ExportCost.mq5 can export deals from ...
π Read | CodeBase | @mql5dev
It reads a CSV (Date,Profit,Volume; one row per closing deal) and prints a report to the Experts tab. Output includes breakeven cost per deal, cushion versus an assumed realistic cost, net and profit factor re-priced at the assumed cost, a cost-sensitivity curve from 0 to 3x, and win erosion where costs flip winners into losers. A composite A+ to F score aggregates cushion, profit-factor resilience, and erosion, with recommendations.
Input file goes to MQL5\Files; Volume is optional. If missing on first run, a reproducible sample file is generated. A helper ExportCost.mq5 can export deals from ...
π Read | CodeBase | @mql5dev
β€30π9π3π2β‘1
BBandsPsar is a custom hybrid indicator that merges a volatility model (Bollinger Bands) with a trend-following signal (Parabolic SAR) into one output.
The core calculation measures the gap between the Parabolic SAR value and the current candleβs open or close, reflecting SARβs alternating behavior during trend changes. That gap is then normalized using Bollinger Bands, producing a standardized histogram rather than raw price-distance values.
Because the output is scaled, the same threshold logic can be applied across instruments with different price ranges, improving cross-asset comparability.
BBandsPsar inherits the full input sets of both Bollinger Bands and Parabolic SAR, allowing adjustment of period, deviation, price source, step, and maximum settings to control sensitivity.
For dynamic parameter testing, the iBands call can be refactored so ...
π Read | Freelance | @mql5dev
The core calculation measures the gap between the Parabolic SAR value and the current candleβs open or close, reflecting SARβs alternating behavior during trend changes. That gap is then normalized using Bollinger Bands, producing a standardized histogram rather than raw price-distance values.
Because the output is scaled, the same threshold logic can be applied across instruments with different price ranges, improving cross-asset comparability.
BBandsPsar inherits the full input sets of both Bollinger Bands and Parabolic SAR, allowing adjustment of period, deviation, price source, step, and maximum settings to control sensitivity.
For dynamic parameter testing, the iBands call can be refactored so ...
π Read | Freelance | @mql5dev
β€23π6π2π2π―1
Indicator buffer data is being formalized as a first-class timeseries: per indicator, maintain a list containing all buffer values for every bar used in calculations. This enables consistent storage, search, sort, and later statistical analysis across library collections.
Core library changes: the NewBar class is relocated to Services; SeriesDE include paths are updated; new message indices/texts are added; a dedicated collection ID and timer constants are introduced. Indicator data gains an extra integer property for indicator handle, including sorting/search criteria support.
New class CSeriesDataInd stores CDataInd objects per bar/buffer, supports creation, refresh on current bar, append on new bar, and trimming to required depth. Indicator objects are extended with total buffer count and an embedded buffer-data series; the indicators collection and eng...
π Read | AlgoBook | @mql5dev
Core library changes: the NewBar class is relocated to Services; SeriesDE include paths are updated; new message indices/texts are added; a dedicated collection ID and timer constants are introduced. Indicator data gains an extra integer property for indicator handle, including sorting/search criteria support.
New class CSeriesDataInd stores CDataInd objects per bar/buffer, supports creation, refresh on current bar, append on new bar, and trimming to required depth. Indicator objects are extended with total buffer count and an embedded buffer-data series; the indicators collection and eng...
π Read | AlgoBook | @mql5dev
β€57π10π2
An open-source EA focuses on Stochastic-based position closing with three modes. Crossing Mode closes in OB/OS when %K and %D cross. Entering Mode closes when %D enters overbought or oversold. Exiting Mode closes when %D exits those zones. A profit-state filter restricts closures to Loss, Profit, or both.
Core parameters cover %K/%D periods, slowing, OB/OS levels, price field, and a selectable Stochastic timeframe independent of the chart. Logic runs on every tick and affects only the current symbol.
Optional Test Mode adds simple entries for research: 0.01-lot trades when %D crosses 50 with a configurable offset, only when no positions exist. No SL/TP, no magic filtering, and it can run alongside the closing logic. No money management features are included.
π Read | VPS | @mql5dev
Core parameters cover %K/%D periods, slowing, OB/OS levels, price field, and a selectable Stochastic timeframe independent of the chart. Logic runs on every tick and affects only the current symbol.
Optional Test Mode adds simple entries for research: 0.01-lot trades when %D crosses 50 with a configurable offset, only when no positions exist. No SL/TP, no magic filtering, and it can run alongside the closing logic. No money management features are included.
π Read | VPS | @mql5dev
β€26π4π€£3π3π1
MetaTrader 5 object interactivity is extended from simple selection outlines to controlled resizing workflows.
Current implementation highlights a selected object but lacks usable grab handles because helper objects share a protected name prefix, making them non-selectable. Forcing initial selection on specific objects enables MT5 drag behavior, but default anchor handling creates inconsistent resizing visuals and disconnected outline segments.
The update adds dedicated corner points and uses switch fall-through to reuse creation logic while adjusting placement, producing two effective resize handles.
Event handling is then tightened: clicking should move objects without toggling their selected state. A small handler addition blocks selection-state changes while keeping drag operations active.
π Read | Forum | @mql5dev
Current implementation highlights a selected object but lacks usable grab handles because helper objects share a protected name prefix, making them non-selectable. Forcing initial selection on specific objects enables MT5 drag behavior, but default anchor handling creates inconsistent resizing visuals and disconnected outline segments.
The update adds dedicated corner points and uses switch fall-through to reuse creation logic while adjusting placement, producing two effective resize handles.
Event handling is then tightened: clicking should move objects without toggling their selected state. A small handler addition blocks selection-state changes while keeping drag operations active.
π Read | Forum | @mql5dev
β€19π7π3β2
Work continued on MT5 replay/simulation tooling to render position state directly on the chart, not in terminal text. Standard platform position visuals are insufficient under cross-order execution and replay models.
The update adds three HLINE objects per position: open price, stop-loss, and take-profit. Object naming uses the position ticket plus suffixes to keep uniqueness and support bulk cleanup on indicator removal.
A priority enumeration was introduced to reduce selection issues when objects overlap. C_Terminal and C_ChartFloatingRAD were adjusted to consume the shared priority list, keeping Chart Trade above most graphics while allowing order/position overlays to remain selectable.
Further refinements add OBJPROP_TEXT descriptions for each line so the Objects list remains self-explanatory without changing user chart settings.
π Read | CodeBase | @mql5dev
The update adds three HLINE objects per position: open price, stop-loss, and take-profit. Object naming uses the position ticket plus suffixes to keep uniqueness and support bulk cleanup on indicator removal.
A priority enumeration was introduced to reduce selection issues when objects overlap. C_Terminal and C_ChartFloatingRAD were adjusted to consume the shared priority list, keeping Chart Trade above most graphics while allowing order/position overlays to remain selectable.
Further refinements add OBJPROP_TEXT descriptions for each line so the Objects list remains self-explanatory without changing user chart settings.
π Read | CodeBase | @mql5dev
β€22π7π2
MMAR is finalized as a native MQL5 library that packages multifractal analysis, spectrum fitting, simulation, and Monte Carlo forecasting behind a single CMMAR facade. An EA feeds returns, calls Fit(), then Forecast(); optional setters control moments, partitioning, cascade base, and RNG seeding for repeatable runs.
The pipeline extracts scaling exponents and Hurst diagnostics, then fits a singularity spectrum against multiple cascade distributions using bounded optimization. A status enum exposes partial results when spectrum fitting fails, so EAs can still use H and multifractality signals.
Forecasting runs many simulated MMAR paths to produce forward volatility plus a confidence interval, enabling risk-based position sizing and regime monitoring. The demo EA shows full portability: only MT5 Standard Library components (ALGLIB FFT/Cholesky, BLEIC, Math...
π Read | Freelance | @mql5dev
The pipeline extracts scaling exponents and Hurst diagnostics, then fits a singularity spectrum against multiple cascade distributions using bounded optimization. A status enum exposes partial results when spectrum fitting fails, so EAs can still use H and multifractality signals.
Forecasting runs many simulated MMAR paths to produce forward volatility plus a confidence interval, enabling risk-based position sizing and regime monitoring. The demo EA shows full portability: only MT5 Standard Library components (ALGLIB FFT/Cholesky, BLEIC, Math...
π Read | Freelance | @mql5dev
β€18π6π5
Live EAs under news volatility routinely hit failure sequences: requotes, connection drops, spread spikes, and overlapping ticks. Immediate retries inside OnTick() can create duplicate submissions for the same signal, bypassing risk controls and producing untracked exposure.
Common patterns like Sleep(500), local retry loops, and uniform GetLastError() handling fail in three areas: no retcode classification, no cumulative failure state, and duplicated logic across the codebase. This increases missed entries, uncontrolled doubling, and cases where stop attachment fails without recovery or diagnostics.
A structured approach uses three layers: a retry executor with explicit retryable retcodes and exponential backoff; a circuit breaker tracking consecutive failures with OPEN/HALF-OPEN/CLOSED behavior; and a gateway that composes both behind a single, configured...
π Read | Quotes | @mql5dev
Common patterns like Sleep(500), local retry loops, and uniform GetLastError() handling fail in three areas: no retcode classification, no cumulative failure state, and duplicated logic across the codebase. This increases missed entries, uncontrolled doubling, and cases where stop attachment fails without recovery or diagnostics.
A structured approach uses three layers: a retry executor with explicit retryable retcodes and exponential backoff; a circuit breaker tracking consecutive failures with OPEN/HALF-OPEN/CLOSED behavior; and a gateway that composes both behind a single, configured...
π Read | Quotes | @mql5dev
β€26π10π¨βπ»3π2β1
New beta version 6006 is available at MetaQuotes-Demo.
π13β€9π2π₯1
MetaTrader 5 input parameters scale poorly: each chart instance freezes its settings at attach time, so changing lot size, stops, or filters means manually reopening properties and restarting every chart. That breaks down fast when the same EA runs across many symbols or risk profiles.
A shared JSON file becomes the single configuration source. All EA instances can read the same file (or per-symbol files) and refresh settings on a trigger, avoiding reattach cycles and enabling scripted updates outside the terminal.
The design uses a typed SStrategyConfig with safe defaults, plus a lightweight JSON tokenizer focused on a flat object (quoted keys, string/number values). It avoids DLL dependencies, handles commas inside quoted strings, and falls back cleanly when the file is missing or malformed.
π Read | AppStore | @mql5dev
A shared JSON file becomes the single configuration source. All EA instances can read the same file (or per-symbol files) and refresh settings on a trigger, avoiding reattach cycles and enabling scripted updates outside the terminal.
The design uses a typed SStrategyConfig with safe defaults, plus a lightweight JSON tokenizer focused on a flat object (quoted keys, string/number values). It avoids DLL dependencies, handles commas inside quoted strings, and falls back cleanly when the file is missing or malformed.
π Read | AppStore | @mql5dev
β€44π13π3
A common requirement after opening a position is automatic profit protection. The usual approach is a trailing stop that starts only after price reaches a defined profit threshold, then moves the stop to reduce downside while allowing continuation.
Key parameters are activation distance, trailing step, and update frequency to avoid excessive modifications. A break-even rule is often added: once the position is in profit by a set amount, the stop-loss is moved to entry price plus costs and a small offset.
Implementation details matter: handle bid/ask correctly by order type, respect minimum stop levels and freeze levels, and avoid repeated updates when the new stop is not better than the current one. Logging and throttling are recommended for stability under fast ticks.
π Read | Signals | @mql5dev
Key parameters are activation distance, trailing step, and update frequency to avoid excessive modifications. A break-even rule is often added: once the position is in profit by a set amount, the stop-loss is moved to entry price plus costs and a small offset.
Implementation details matter: handle bid/ask correctly by order type, respect minimum stop levels and freeze levels, and avoid repeated updates when the new stop is not better than the current one. Logging and throttling are recommended for stability under fast ticks.
π Read | Signals | @mql5dev
β€29π8β2π1