Ed Seykota implemented an early computerized trend system in 1970 using FORTRAN on mainframes. Core logic: dual EMA crossover for direction, daily execution, multi-week holding, no intraday monitoring.
Key rules: fast/slow EMA (commonly ~20/200) plus an ADX filter to avoid range conditions (ADX > 20). Position sizing uses ATR-based risk parity: equity risk % divided by ATR stop value (typical ATR(20) with 3β5x multiplier). Exits use EMA reversal or ATR stop, no fixed take profit.
Main differentiator is portfolio heat. Residual risk is summed across all open positions and capped (often 10β20%); new entries are blocked when the cap is reached, limiting correlated drawdowns in multi-symbol portfolios. MQL5 EA architecture monitors a symbol list on D1, computes heat first, then evaluates exits and entries per symbol.
π Read | VPS | @mql5dev
Key rules: fast/slow EMA (commonly ~20/200) plus an ADX filter to avoid range conditions (ADX > 20). Position sizing uses ATR-based risk parity: equity risk % divided by ATR stop value (typical ATR(20) with 3β5x multiplier). Exits use EMA reversal or ATR stop, no fixed take profit.
Main differentiator is portfolio heat. Residual risk is summed across all open positions and capped (often 10β20%); new entries are blocked when the cap is reached, limiting correlated drawdowns in multi-symbol portfolios. MQL5 EA architecture monitors a symbol list on D1, computes heat first, then evaluates exits and entries per symbol.
π Read | VPS | @mql5dev
β€22π8π€£5π₯4π€©1
High-impact economic releases routinely cause spread expansion and slippage that invalidate clean backtests. Event timing is known in advance; the failure point is delivering a reliable schedule into an EA.
Web scraping breaks on HTML changes. Paid calendar APIs add cost and require runtime connectivity, which is fragile on VPS setups. A file-based news filter avoids both by loading a Forex Factory CSV export from MQL5/Files at startup and running fully offline.
Core components: typed CNewsEvent records with an impact enum, a quote-aware CSV parser, symbol currency extraction that handles broker suffixes, and an inclusive time-window checker with CheckAt for boundary tests. Optional chart rectangles visualize pre/post buffers for qualifying events.
π Read | Freelance | @mql5dev
Web scraping breaks on HTML changes. Paid calendar APIs add cost and require runtime connectivity, which is fragile on VPS setups. A file-based news filter avoids both by loading a Forex Factory CSV export from MQL5/Files at startup and running fully offline.
Core components: typed CNewsEvent records with an impact enum, a quote-aware CSV parser, symbol currency extraction that handles broker suffixes, and an inclusive time-window checker with CheckAt for boundary tests. Optional chart rectangles visualize pre/post buffers for qualifying events.
π Read | Freelance | @mql5dev
β€21π₯11π9π€©5π€£1
This article builds a MetaTrader 5 indicator that extracts the full risk-neutral distribution from an option chain, answering questions like P(close above X), expected move, tail thickness, and confidence bands.
The core method fits a smooth implied-volatility smile (using liquid OTM quotes), reconstructs clean call prices, then applies BreedenβLitzenberger (second strike-derivative) to recover the density. It avoids the common failure mode where differentiating noisy quotes produces spiky, negative βprobabilities.β
Implementation details emphasize numerical reliability: a bracketed Newton/bisection IV solver, forward-price cross-checks via put-call parity regression, spline extrapolation that preserves slope continuity to prevent boundary spikes, and diagnostics like clipped-negative counts and pre-normalization integral error.
For traders, it overl...
π Read | AppStore | @mql5dev
The core method fits a smooth implied-volatility smile (using liquid OTM quotes), reconstructs clean call prices, then applies BreedenβLitzenberger (second strike-derivative) to recover the density. It avoids the common failure mode where differentiating noisy quotes produces spiky, negative βprobabilities.β
Implementation details emphasize numerical reliability: a bracketed Newton/bisection IV solver, forward-price cross-checks via put-call parity regression, spline extrapolation that preserves slope continuity to prevent boundary spikes, and diagnostics like clipped-negative counts and pre-normalization integral error.
For traders, it overl...
π Read | AppStore | @mql5dev
β€19π₯7π6π€©5π€‘1π―1
Portfolio trading logic breaks quickly when OHLCV series are not time-aligned, especially with illiquid instruments that produce missing bars. A synchronizer should output equal-length arrays with identical bar open times over a selected interval.
Two fill modes are typically required: keep gaps as explicit empty bars, or forward-fill prices from the previous Close with zero volume. Both are needed for different research and execution workflows.
A practical design uses MetaTrader 5 Standard Library CSortedMap keyed by bar open time, backed by red-black trees. A CSymbolData container stores OHLCV plus bar type (real/empty/interpolated), while a manager layer handles loading, updates, direction normalization, and asynchronous bar arrival policies (wait for all symbols vs incremental recalculation).
π Read | Signals | @mql5dev
Two fill modes are typically required: keep gaps as explicit empty bars, or forward-fill prices from the previous Close with zero volume. Both are needed for different research and execution workflows.
A practical design uses MetaTrader 5 Standard Library CSortedMap keyed by bar open time, backed by red-black trees. A CSymbolData container stores OHLCV plus bar type (real/empty/interpolated), while a manager layer handles loading, updates, direction normalization, and asynchronous bar arrival policies (wait for all symbols vs incremental recalculation).
π Read | Signals | @mql5dev
β€20π₯12π6β‘4π€‘2π€©1
Smart Loss Exit is an exit manager, not a strategy. It does not open trades; it monitors selected positions (manual or EA) by symbol and magic number and only closes positions that are currently in floating loss. Positions in profit are never modified.
The design targets a common backtest failure mode: high win rate but low profit factor because a small number of losing trades reach full stop. The goal is to close trades that are likely to hit the stop while avoiding premature exits on recoveries. Each rule is configurable, supports a grace period, and logs the first rule that triggers.
Five loss-only rules are available: ATR adverse excursion, time-in-trade while losing, EMA trend invalidation (20/50 default), RSI momentum thresholds (optional), and an account-currency loss cap (optional). Tick-based checks are used for ATR and time; EMA/RSI use last cl...
π Read | Forum | @mql5dev
The design targets a common backtest failure mode: high win rate but low profit factor because a small number of losing trades reach full stop. The goal is to close trades that are likely to hit the stop while avoiding premature exits on recoveries. Each rule is configurable, supports a grace period, and logs the first rule that triggers.
Five loss-only rules are available: ATR adverse excursion, time-in-trade while losing, EMA trend invalidation (20/50 default), RSI momentum thresholds (optional), and an account-currency loss cap (optional). Tick-based checks are used for ATR and time; EMA/RSI use last cl...
π Read | Forum | @mql5dev
β€19π7π€©5π₯2
HimNet targets market robustness over flashy complexity: a lean EncoderβDecoder that limits trainable parameters to reduce overfitting while staying adaptable to regime changes. It combines graph recurrent units with Chebyshev polynomial aggregation to model structured dependencies without slowing execution.
The Temporal Encoder runs two parallel time-scale embedding dictionaries. Each timestamp produces compact embedding βqueriesβ that select a suitable meta-parameter subspace, letting the model switch behavior by time context instead of retraining. These embeddings are concatenated and fed through a stacked GCRU pipeline where the first layer builds context and deeper layers refine it.
Implementation details emphasize reliability: strict layer validation, centralized Init, OpenCL binding, pointer sharing to avoid tensor copies, and careful backp...
π Read | Docs | @mql5dev
The Temporal Encoder runs two parallel time-scale embedding dictionaries. Each timestamp produces compact embedding βqueriesβ that select a suitable meta-parameter subspace, letting the model switch behavior by time context instead of retraining. These embeddings are concatenated and fed through a stacked GCRU pipeline where the first layer builds context and deeper layers refine it.
Implementation details emphasize reliability: strict layer validation, centralized Init, OpenCL binding, pointer sharing to avoid tensor copies, and careful backp...
π Read | Docs | @mql5dev
β€18π7π₯5π3π€©1
Position indicator work for a replay/simulation service moved toward decoupling. C_ElementsTrade removed direct dependencies on live position APIs by concentrating changes around DispatchMessage.
Symbol retrieval via PositionGetString was replaced by passing the symbol into the constructor and storing it as a private member. Iteration over PositionsTotal and PositionGetTicket was dropped; a chart-wide custom event now triggers per-indicator refresh using the already known ticket.
PositionGetDouble for SL/TP was removed by pushing SL/TP values into UpdatePrice, using cross-references so the opposite level is available when editing. Position API calls were relocated to main indicator code for controlled use.
A chart-duplication bug was fixed by replacing ObjectFind with ChartWindowFind. Additional logic was added to flag invalid SL/TP ranges via color...
π Read | Freelance | @mql5dev
Symbol retrieval via PositionGetString was replaced by passing the symbol into the constructor and storing it as a private member. Iteration over PositionsTotal and PositionGetTicket was dropped; a chart-wide custom event now triggers per-indicator refresh using the already known ticket.
PositionGetDouble for SL/TP was removed by pushing SL/TP values into UpdatePrice, using cross-references so the opposite level is available when editing. Position API calls were relocated to main indicator code for controlled use.
A chart-duplication bug was fixed by replacing ObjectFind with ChartWindowFind. Additional logic was added to flag invalid SL/TP ranges via color...
π Read | Freelance | @mql5dev
β€16π€©4π2π₯2π1π¨βπ»1
Operator overloading can improve readability, but it can also make debugging harder when expressions are not evaluated the way they look.
A practical pattern is to overload operators to route assignments and arithmetic through a Debug function, adding call-site context (for example, passing the source line) and printing to the MetaTrader 5 terminal.
A key detail is return type. Debugging inserted into assignment expressions fails if the debug hook is void. Fixes require returning the current object (or a suitable proxy) so the full expression remains valid.
Using this avoids creating temporary instances. Temporary objects can change memory addresses and behavior, and with aggressive operator overloading can yield inconsistent results that are difficult to reproduce.
π Read | NeuroBook | @mql5dev
A practical pattern is to overload operators to route assignments and arithmetic through a Debug function, adding call-site context (for example, passing the source line) and printing to the MetaTrader 5 terminal.
A key detail is return type. Debugging inserted into assignment expressions fails if the debug hook is void. Fixes require returning the current object (or a suitable proxy) so the full expression remains valid.
Using this avoids creating temporary instances. Temporary objects can change memory addresses and behavior, and with aggressive operator overloading can yield inconsistent results that are difficult to reproduce.
π Read | NeuroBook | @mql5dev
β€16π4π₯2π2π€©1
Part 6 revisits the earlier DFT + Leaky Integrate-and-Fire SNN EA, shifting from finding new techniques to stress-testing known components across seven operating modes. The DFT extracts the strongest cycle from a rolling window (price, MACD, or RSI) and gates direction via a phase threshold; the SNN accumulates bullish/bearish βchargeβ across bars using decay and a firing threshold.
Each mode is optimized on ~2/3 of data, then forward-walked on the final third with frozen inputs while varying symbol, timeframe, and test window. Results were mixed: five forward runs profitable, two losing, highlighting parameter fragility rather than a confirmed edge.
Key takeaways: window length vs noise/lag is critical; MACD/RSI smoothing interacts with DFT memory; multi-source voting underperformed without per-source tuning; SNN modes need input normalization (e.g., vo...
π Read | AppStore | @mql5dev
Each mode is optimized on ~2/3 of data, then forward-walked on the final third with frozen inputs while varying symbol, timeframe, and test window. Results were mixed: five forward runs profitable, two losing, highlighting parameter fragility rather than a confirmed edge.
Key takeaways: window length vs noise/lag is critical; MACD/RSI smoothing interacts with DFT memory; multi-source voting underperformed without per-source tuning; SNN modes need input normalization (e.g., vo...
π Read | AppStore | @mql5dev
β€17π3π₯1
MetaTrader history reports closed deals as a flat list and offers no session-level attribution. Session performance testing usually requires exporting to spreadsheets and tagging rows by UTC hour.
A modular MQL5 pipeline automates this: read closed deals for a lookback window, assign each deal to Sydney/Tokyo/London/New York by UTC close hour, and aggregate net P&L, win rate, trade count, and average hold time. Output is a CCanvas bar chart plus a plain-text table in Experts, with an account-wide totals row.
Implementation uses a history reader (DEAL_ENTRY_OUT/INOUT), position open-time recovery via DEAL_POSITION_ID scan, overlap resolution by boundary order, and tests that assert boundary classification, midnight wrapping, aggregation sums, and hold-time math.
Known constraints: fixed UTC boundaries, broker time-basis must be verified, and earliest pos...
π Read | Calendar | @mql5dev
A modular MQL5 pipeline automates this: read closed deals for a lookback window, assign each deal to Sydney/Tokyo/London/New York by UTC close hour, and aggregate net P&L, win rate, trade count, and average hold time. Output is a CCanvas bar chart plus a plain-text table in Experts, with an account-wide totals row.
Implementation uses a history reader (DEAL_ENTRY_OUT/INOUT), position open-time recovery via DEAL_POSITION_ID scan, overlap resolution by boundary order, and tests that assert boundary classification, midnight wrapping, aggregation sums, and hold-time math.
Known constraints: fixed UTC boundaries, broker time-basis must be verified, and earliest pos...
π Read | Calendar | @mql5dev
β€16β4π2π€©1
Work begins on integrating core components into an MT5 replay/simulation system, prioritizing progress over minor UI edge cases in the position indicator. Duplicate drawing logic is consolidated with scoped macros, reducing maintenance and simplifying porting by removing symbol-specific dependencies.
The key blocker is reliance on live-server position APIs. The indicator is refactored to route all PositionGet*/Select calls through wrapper functions, enabling the same codepath to work on real accounts or in replay mode.
Replay mode uses SQLite as the trade βserverβ state: the Expert Advisor creates and updates the database, while the indicator only reads it and refreshes via custom events. The replay framework is also updated for current MT5 behavior, including Z-order fixes for clickable controls and inheritance/constructor changes in the control classes.
π Read | Freelance | @mql5dev
The key blocker is reliance on live-server position APIs. The indicator is refactored to route all PositionGet*/Select calls through wrapper functions, enabling the same codepath to work on real accounts or in replay mode.
Replay mode uses SQLite as the trade βserverβ state: the Expert Advisor creates and updates the database, while the indicator only reads it and refreshes via custom events. The replay framework is also updated for current MT5 behavior, including Z-order fixes for clickable controls and inheritance/constructor changes in the control classes.
π Read | Freelance | @mql5dev
β€12π₯4π3π3π¨βπ»2
Operator overloading in MQL5 moves past arithmetic quickly once flow control depends on relational and logical operators.
A stComplex example shows typical compiler failures: missing overloads for β<β and for β+=β when the right operand is another stComplex. Adding the required overloads fixes compilation but can still break loop behavior if the comparison returns false early, producing wrong counters or infinite loops.
Operand order is another constraint. Overloads defined on stComplex cannot be called when the left operand is a built-in type. The workaround is explicit construction or casting to stComplex via a constructor.
Further examples extend to β>β and bitwise operators, noting that bitwise operations on doubles depend on integer reinterpretation and IEEE-754 details.
π Read | Freelance | @mql5dev
A stComplex example shows typical compiler failures: missing overloads for β<β and for β+=β when the right operand is another stComplex. Adding the required overloads fixes compilation but can still break loop behavior if the comparison returns false early, producing wrong counters or infinite loops.
Operand order is another constraint. Overloads defined on stComplex cannot be called when the left operand is a built-in type. The workaround is explicit construction or casting to stComplex via a constructor.
Further examples extend to β>β and bitwise operators, noting that bitwise operations on doubles depend on integer reinterpretation and IEEE-754 details.
π Read | Freelance | @mql5dev
β€8π4π₯2π€©1
Most EAs treat exits as fixed-point stops. That keeps risk deterministic but ignores volatility regime shifts: tight during spikes, loose during quiet sessions.
A reusable MQL5 volatility trailing stop can be built around Simple True Range (closed bars only) with a live Bid/Ask anchor. The stop ratchets one-way and is quantized to SYMBOL_TRADE_TICK_SIZE to avoid off-tick rejections.
A broker-aware engine should validate SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL before calling CTrade::PositionModify(), and confirm success via ResultRetcode() rather than boolean returns. A minimum-step filter and optional only-in-profit guard reduce modification noise.
A non-repainting diagnostic indicator can approximate the logic using Close[i-1] anchoring, while an EA template can log telemetry (evaluations, updates, skips, retcodes) for Strategy Tester ...
π Read | Calendar | @mql5dev
A reusable MQL5 volatility trailing stop can be built around Simple True Range (closed bars only) with a live Bid/Ask anchor. The stop ratchets one-way and is quantized to SYMBOL_TRADE_TICK_SIZE to avoid off-tick rejections.
A broker-aware engine should validate SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL before calling CTrade::PositionModify(), and confirm success via ResultRetcode() rather than boolean returns. A minimum-step filter and optional only-in-profit guard reduce modification noise.
A non-repainting diagnostic indicator can approximate the logic using Close[i-1] anchoring, while an EA template can log telemetry (evaluations, updates, skips, retcodes) for Strategy Tester ...
π Read | Calendar | @mql5dev
β€11π5π€©4π₯3
A recurring failure mode in ML trading shows up again: out-of-sample direction accuracy above 60% can still produce weak or negative PnL once spreads, swaps, slippage, and regime shifts are included.
Version updates improved dataset quality via strict UP/DOWN balancing, richer features (ATR/RSI/Bollinger position), and structured fine-tuning examples. These steps raise predictive consistency but do not align labels with profit.
Key issues remain: forced binary outputs remove the βno tradeβ state; confidence tied to move magnitude does not map to expectancy after costs; parsers with hard fallbacks can introduce systematic bias; backtests with few trades and no costs inflate results.
Next iteration needs profit-based targets (LONG/SHORT/FLAT or expected PnL), cost-aware validation, and evaluation by trading metrics rather than accuracy.
π Read | CodeBase | @mql5dev
Version updates improved dataset quality via strict UP/DOWN balancing, richer features (ATR/RSI/Bollinger position), and structured fine-tuning examples. These steps raise predictive consistency but do not align labels with profit.
Key issues remain: forced binary outputs remove the βno tradeβ state; confidence tied to move magnitude does not map to expectancy after costs; parsers with hard fallbacks can introduce systematic bias; backtests with few trades and no costs inflate results.
Next iteration needs profit-based targets (LONG/SHORT/FLAT or expected PnL), cost-aware validation, and evaluation by trading metrics rather than accuracy.
π Read | CodeBase | @mql5dev
π9π€©7β€2π₯2
Finite differences provide a discrete approximation of derivatives and align naturally with price series sampled in bars and ticks. First and higher-order differences can be chained to characterize momentum and curvature without assuming continuity.
A binomial transform built from successive differences can be inverted after attenuating higher orders, producing a practical smoothing and noise-reduction pipeline with explicit control over how noise scales by order.
Differences also support pattern encoding by quantizing D differences into L levels, then mapping level indices into a pattern ID for statistics-based forecasts. Similar logic applies to OHLC candlestick structure using derived differences, extending to multi-candle sequences.
Forecasting options include naive models (SMA shift, average rate-of-change), higher-order extrapolation, adapti...
π Read | Calendar | @mql5dev
A binomial transform built from successive differences can be inverted after attenuating higher orders, producing a practical smoothing and noise-reduction pipeline with explicit control over how noise scales by order.
Differences also support pattern encoding by quantizing D differences into L levels, then mapping level indices into a pattern ID for statistics-based forecasts. Similar logic applies to OHLC candlestick structure using derived differences, extending to multi-candle sequences.
Forecasting options include naive models (SMA shift, average rate-of-change), higher-order extrapolation, adapti...
π Read | Calendar | @mql5dev
β€14π11π€©3π₯2
APB Channel EA implements a two-step entry for XAUUSD/XAGUSD using Heikin-Ashi reversal detection plus a Keltner-style EMA/ATR channel confirmation. Logic executes once per closed bar and starts with a Heikin-Ashi colour flip that arms a pending direction.
A trade is only permitted after a re-entry trigger: buy requires a close at/above the lower band, sell requires a close at/below the upper band. The pending signal expires after MaxBarsToTrigger bars unless set to 0.
Before order placement, time-window, tick-volume ratio, and ATR-based volatility filters must all pass. Position sizing targets constant monetary risk using entry-to-stop distance, with TP at RR_Ratio.
Stops are structural (recent swing high/low plus buffer), with optional break-even and an immediate exit on an opposite Heikin-Ashi arrow. Correct PointsPerPip configuration is critical for al...
π Read | AlgoBook | @mql5dev
A trade is only permitted after a re-entry trigger: buy requires a close at/above the lower band, sell requires a close at/below the upper band. The pending signal expires after MaxBarsToTrigger bars unless set to 0.
Before order placement, time-window, tick-volume ratio, and ATR-based volatility filters must all pass. Position sizing targets constant monetary risk using entry-to-stop distance, with TP at RR_Ratio.
Stops are structural (recent swing high/low plus buffer), with optional break-even and an immediate exit on an opposite Heikin-Ashi arrow. Correct PointsPerPip configuration is critical for al...
π Read | AlgoBook | @mql5dev
β€8π3π€©3π₯1