MQL5 Algo Trading
541K subscribers
3.87K photos
6 videos
3.88K links
The best publications of the largest community of algotraders.

Subscribe to stay up-to-date with modern technologies and trading programs development.
Download Telegram
MetaTrader 5 charts remain symbol-centric, which limits visibility into correlated moves across related instruments. A practical workaround is a synthetic custom symbol built from multiple markets by averaging aligned OHLC bars.

An MQL5 Expert Advisor can load OHLCV for selected source symbols, match candles by timestamp, and compute per-bar averages for open, high, low, close, and optionally volume. Only bars present across all sources are included to avoid skew from missing sessions.

The EA then creates or reuses a custom symbol, copies formatting from a template symbol, disables trading mode, clears prior history, and writes the reconstructed series. Live synchronization is handled via a timer that recalculates only the most recent bars to keep updates lightweight.

πŸ‘‰ Read | Quotes | @mql5dev
❀20πŸ‘6⚑1πŸ‘Œ1
Trend and breakout EAs often assume returns are always predictable. When the series is near-random, signals become noise and performance degrades through spreads and commissions. Standard MQL5 indicators track price, momentum, volatility, or volume, but do not quantify predictability of returns.

Approximate Entropy (ApEn) is presented as a native MQL5 measure of short-term serial structure on closed-bar log-returns. It is implemented as a standalone CApEnCalculator class, plus a subwindow indicator that marks regime zones via configurable thresholds, and a test script for synthetic validation.

ApEn is positioned as a gating filter, not a trade trigger. EAs can read it via iCustom/CopyBuffer with shift=1 and disable directional entries when ApEn exceeds an upper threshold. Parameters m=2, r=0.2Β·SD, and window sizes around 50–200 balance stability a...

πŸ‘‰ Read | Calendar | @mql5dev
❀17πŸ‘8πŸ‘Œ2✍1
This indicator implements a volatility breakout model using two independent envelopes around a moving-average baseline. The inner envelope defines the normal range, while the outer envelope models expanded volatility for target placement.

Entry logic uses Envelope 1 as the trigger. A long setup occurs when a candle closes above the inner upper band after the prior candle closed at or below that band. A short setup occurs when a candle closes below the inner lower band after the prior candle closed at or above that band.

Exit logic uses Envelope 2 as a dynamic take-profit. Positions are closed when price touches the corresponding outer band, treating the higher deviation as a statistically consistent exhaustion zone.

Risk is controlled with a structural stop at the prior bar’s opposite inner band. A return through the full inner channel invalidates the...

πŸ‘‰ Read | Calendar | @mql5dev
❀21πŸ‘7πŸ‘Œ3🀑2πŸ‘¨β€πŸ’»2
Kronos brings foundation-model ideas to candlesticks: a tokenizer compresses each 6-field bar into two discrete tokens, and a decoder-only transformer predicts future tokens autoregressively, then decodes them back to OHLCV(+amount).

The key engineering focus is running inference entirely inside MetaTrader 5. Weights are exported once from PyTorch into flat float32 .bin tensors with a manifest, then loaded in MQL5 and executed with native matrix/vector opsβ€”no Python at runtime.

This part implements the front pipeline: exact z-score normalization per window (with correct ddof=0), careful timestamp features (pandas weekday remap), and Binary Spherical Quantization where tokens depend only on latent sign bits, avoiding unnecessary normalization.

Correctness is established via golden-reference, bit-for-bit verification against the original model, making later ...

πŸ‘‰ Read | Signals | @mql5dev
❀22πŸ‘11πŸ‘Œ2🀑2
This update extends an MT5 drawing toolkit that creates chart objects from keyboard shortcuts, using the mouse position to pick the nearest Highs or Lows as anchor points. It adds configurable object presets and consistent naming via prefix arrays, making later automation like deleting compound objects practical.

The drawing layer now covers infinite horizontal/vertical lines, trend lines as rays or segments (including controlled extension into the future), fixed-length horizontal levels (length by pixels or bars, with scalable β€œextended” variants), vertical lines with labels, a configurable Fibonacci fan, and an Andrews’ Pitchfork set (regular, Schiff, reverse) built from shared point calculations.

A key engineering focus is reliable β€œfuture time” placement. MT5 time-based endpoints can shrink across weekends or break near chart boundaries, so th...

πŸ‘‰ Read | Quotes | @mql5dev
❀42πŸ‘12😁3πŸ‘Œ3🀑3πŸŽ‰2πŸ‘¨β€πŸ’»2
A practical example shows how a traditional trend indicator such as SuperTrend can be converted into a profitable trading EA when the logic is engineered beyond entry signals.

Results are driven primarily by the exit model: stop placement, trailing rules, and conditions for closing on trend weakening or volatility shifts. Risk sizing and slippage handling remain core to expectancy.

The takeaway is that indicator-based automation should treat the indicator as a state filter, while exits and risk management define the profit profile and drawdown behavior.

πŸ‘‰ Read | Quotes | @mql5dev
❀23πŸ‘11πŸ‘Œ4πŸ‘¨β€πŸ’»3
The article explains why FileSave/FileLoad are convenient for logging but awkward for true random access, since they encourage sequential reads or full file reloads.

It walks through MQL5’s lower-level file API, showing how FileOpen flags change what actually lands on disk. In text mode, extra bytes like format markers, tabs, and CR/LF can be inserted, breaking position-based reads and causing FileReadString to stop early when it treats separators as delimiters.

By adjusting open/read flags and forcing FileFlush before reading, the code reliably repositions the file pointer and retrieves expected content.

The final step shifts toward binary-style access: treating the file as a byte array, using FileReadInteger with CHAR_VALUE to control 1-byte reads and predictable indexingβ€”essential groundwork for fast, block-based random access in trading tools.

πŸ‘‰ Read | Quotes | @mql5dev
❀19πŸ‘5πŸ†5πŸ‘Œ2
Work on a market replay/simulation stack continues with four components: Expert Advisor, position indicator, Chart Trade, and Mouse Study. Current guidance is demo-first; the EA and position indicator still require stability work, while Chart Trade and Mouse Study are safe but depend on the EA for execution.

Two cleanup issues are addressed: removing the EA leaves orphaned position indicators, and switching the tracked contract can leave misleading visuals. Handling DeInit in OnDeinit and deleting indicators by their short name (derived from the position ticket) resolves both.

A separate failure appears on timeframe changes due to pointer state across OnInit reinitialization. Explicitly resetting pointers in OnInit prevents runtime unloads.

Next focus is NETTING vs HEDGING behavior. NETTING changes average price on volume increases, but indicators...

πŸ‘‰ Read | Forum | @mql5dev
❀53πŸ‘17⚑3πŸ‘Œ2πŸ”₯1
CKS Position Risk Dashboard is a lightweight MT5 chart indicator focused on pre-trade risk review and position visibility. It is informational only and does not open, modify, or close orders.

The panel shows account and symbol metrics including balance, equity, free margin, margin level, bid/ask, spread, and broker volume constraints (min/max/step). It also reports open-position count and floating P/L for the current chart symbol, plus estimated protected risk when a stop loss is present. Tick size, tick value, and symbol digits are handled automatically. Panel colors, placement, width, and refresh interval are configurable.

Key inputs include risk percent, planned stop distance in points, balance vs equity selection, and a maximum cap for suggested lot size. The suggested volume remains an estimate and should be verified against final margin and sym...

πŸ‘‰ Read | AppStore | @mql5dev
❀23πŸ‘6πŸ‘Œ2😁1
A multi-timeframe, multi-symbol SuperTrend setup can simplify monitoring when it is implemented with strict data handling and clear output.

Key requirements include per-symbol and per-timeframe state separation, deterministic bar indexing, and consistent ATR/SuperTrend parameterization across feeds. Updates should be event-driven to avoid redundant recalculation, with safeguards for missing history and session gaps.

For usability, dashboards should prioritize current direction, last flip time, and distance to the band. Alerts need debouncing and a cooldown window to prevent repeated signals during consolidation.

πŸ‘‰ Read | CodeBase | @mql5dev
❀23πŸ‘7πŸ‘Œ3
Building time-aware EAs starts with timezone hygiene. Session-based logic breaks when broker server time shifts for DST, and MT5 testing does not provide reliable GMT via TimeGMT(). Without a verified broker UTC offset and DST rule, session windows cannot be mapped correctly.

A practical DST detector can be built from NFP timestamps in the MQL5 Economic Calendar plus EURUSD M15 volatility spikes. When the expected spike alignment flips by one hour, a DST transition is inferred and matched against EU/US/AU transition calendars computed from weekday-occurrence rules.

The implementation uses modular MQL5 architecture: indicator layer (multi-AMA pairwise voting across timeframes), strategy layer (signal-to-direction mapping), and a dedicated time layer (DST-aware session conversion, calendar filters, intraday open/mid/close windows). TimeTradeServer() ...

πŸ‘‰ Read | VPS | @mql5dev
❀35πŸ‘€4πŸ‘¨β€πŸ’»3✍2πŸ‘2πŸ‘Œ2
The article breaks Forex arbitrage into a graph problem: currencies are vertices, tradable pairs are directed edges weighted by executable bid/ask prices. Profitable β€œcycles” are those where the rate product stays above 1 after subtracting relative spreads, enabling near-zero market risk when executed correctly.

It outlines an MT5 Expert Advisor built as modular components: real-time graph construction, cycle discovery using a modified Floyd–Warshall (maximize products, track spread growth, reconstruct paths) plus a DFS pass to enumerate alternative cycles while avoiding reuse of the same symbol.

A key engineering focus is zero-exposure sizing: lots are derived by propagating a base notional through the cycle, then normalized to broker constraints (contract size, min lot, step), with proportional downscaling to cap risk. Execution and fault handling are tr...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀23πŸ‘5πŸ‘Œ3
MetaTrader 5 ships with a single-timeframe volume histogram, but multi-timeframe volume context and anchoring require custom tooling. An MQL5 implementation can render synchronized profiles across the main chart and a subwindow using objects, not indicator plots.

The design uses a draggable vertical anchor to define the start of analysis, with the viewport’s right edge as the end. Anchor time is normalized to valid bar times, restored if deleted, and auto-centered when needed. HTF selection is validated to ensure it is above the chart timeframe.

Bin sizing is interactive and stateful. Edit mode activates only when the anchor is selected: double-click E to enter numeric input, double-click S to commit. Invalid or empty input falls back to the last valid value. OnChartEvent drives recalculation on zoom, scroll, drag, and keystrokes, while rendering POC and...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀27πŸ‘Œ4πŸ‘3
AFML’s sequential bootstrap is often presented as the fix for bagging with overlapping triple-barrier labels, by supposedly decorrelating trees. This study isolates what actually reduces between-tree correlation: fewer sampled rows, not the sequential sampling rule itself.

A four-regime experiment holds the same DecisionTree base learner constant and varies only the row sampler: full vs uniqueness-throttled sample count, and standard vs sequential draw rule. The key metric is correlation of out-of-bag probability predictions, making the AFML variance term observable.

Results are consistent across tick, tick-imbalance, and a higher-density M5 replication: cutting max_samples to average uniqueness produces most of the decorrelation; switching to sequential sampling at the same count adds little and can even worsen correlation at full count. Out-of-bag...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘3πŸ‘Œ2⚑1
This article digs into why random-access file code fails when the file’s internal layout is misunderstood. The key takeaway: file position doesn’t advance by β€œone byte” in a meaningful way unless reads and writes are defined by an explicit structure.

Using MQL5-style examples, it contrasts text parsing (tab-delimited strings) with binary layouts, showing how a small format change turns clean reads into garbage output. The fix is to design a self-describing record: write a length field, then the payload, and use FileSeek to backfill the length after writing.

For trading systems, this enables fast, reliable logging and replay of variable-length messages, with deterministic offsets and safer recovery during analysis or debugging.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀14πŸ‘5πŸ†1
Part 8 adds the missing bar-by-bar trend readout on NQ M1: a continuous micro-trend strength score in [-1, +1] that measures how cleanly fast/medium/slow EMAs align and accelerate, instead of relying on lagging, binary crossovers.

GetMicroTrendStrength() combines four EMA-derived components: 5/8/13 EMA ordering, ATR-normalized price position with tanh bounding, 5-bar slope agreement, and a bounded volume multiplier. A contradiction penalty sharply reduces the score when EMA alignment disagrees with price vs the fast EMA, suppressing common false positives during reversals.

The signal plugs into the Part 7 regime layer via confidence-scaled thresholds: high-confidence Trending/Informed sessions loosen cutoffs, low-confidence Stressed/Noisy sessions tighten them. On 514 NY sessions (May 2024–May 2026), Trending shows the most persistent directional ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀20πŸ‘5
Trading systems degrade when regimes shift, and fixed-window indicators react after the distribution has already changed. A sequential CUSUM detector updates bar by bar, accumulates evidence, and flags a breakpoint the moment a threshold is crossed.

The detector runs on standardized log-returns z_t built from a strictly historical rolling window. Two accumulators track upward and downward drift with a slack term k, then reset to zero after a hit. Threshold h sets the false-alarm versus detection-speed trade-off, often expressed via ARL0, with theory only approximate on real returns.

Implementation notes for MetaTrader 5 focus on execution constraints: handling full vs incremental recalculation in OnCalculate(), persisting S+ and Sβˆ’ via indicator buffers, and creating chart objects idempotently to avoid duplicates on live ticks.

πŸ‘‰ Read | AppStore | @mql5dev
❀25πŸ‘10😁1πŸ‘€1
Alpha-Beta Trend Filter is a predictive smoothing indicator based on steady-state estimation. Unlike SMA/EMA-style averaging, it maintains an internal price estimate and a trend velocity term, updating both each bar via a prediction step and a residual-based correction using alpha (price sensitivity) and beta (velocity sensitivity).

This MQL5 build extends the classic single-line output with a multi-symbol, multi-timeframe matrix dashboard. The chart plot uses DRAW_COLOR_LINE to switch state from bullish to bearish based on the velocity sign, while the dashboard renders Bull/Bear/Wait across selectable timeframes for a parsed symbol list.

Implementation details include ArraySetAsSeries() alignment, a helper that computes state from a minimal CopyClose() window without iCustom, and full UI cleanup on deinit. Typical tuning ranges: alpha 0.1–0.9, beta ...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘6✍2πŸ‘¨β€πŸ’»2πŸ‘Œ1πŸ‘€1
Adaptive trading framework for FX, crypto, and high-digit instruments using a velocity-driven baseline and ER-based bands.

Trend filter uses baseline color: LimeGreen signals positive acceleration, Crimson signals negative acceleration. Volatility state is defined by band width: compressed bands indicate low ER and pending expansion; expanded bands indicate high ER and potential trend efficiency or extension.

Momentum breakout: wait for a squeeze and flat baseline. Go long on a candle close above the upper band with baseline turning LimeGreen. Go short on a close below the lower band with baseline turning Crimson. Stop sits beyond the baseline or opposite band. Hold while baseline color persists; exit on a color flip.

Mean reversion: require a flat baseline with wide bands. Enter only after a probe outside a band fails to flip the baseline, then p...

πŸ‘‰ Read | VPS | @mql5dev
❀21πŸ‘5⚑2πŸ”₯1πŸ‘Œ1
Backtest output is bounded by history quality, yet MT5 data gaps often go unverified. A read-only Python audit can export M5 bars from multiple terminals, cache them as Parquet, and report missing bars per pair and per year instead of a single β€œHistory Quality” number.

The workflow validates terminal identity, avoids concurrent API sessions, and resolves broker-specific symbol suffixes. One broker required paging via copy_rates_from_pos, which exposed synthetic β€œfill” bars detectable only by timestamp spacing.

On a shared 2025-02-07 to 2026-06-12 window, the same deterministic breakout strategy drifted by 2,300–4,400 net pips across three feeds. Spread differences dominated, but data/price differences and missing-bar trade mismatches remained material.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀23πŸ‘7πŸ‘Œ1
Market structure analysis in MQL5 often ships as closed indicators that mix computation with rendering, expose limited buffers, and provide no stable query interface. Integration into EAs typically requires copying indicator logic or rebuilding it, increasing coupling, duplication, and maintenance cost.

A prototype modular framework addresses this by separating swing detection, level tracking, break detection, BOS/CHoCH classification, an event bus with deduplication, a market state machine, optional CSV persistence, and a unified public API. It runs as a standard custom indicator but behaves like a reusable service for EAs, dashboards, and research pipelines.

The codebase is split into 10 include modules plus one indicator entry point, supports internal and external timeframes, and avoids full recomputation via incremental bar processing. Trend a...

πŸ‘‰ Read | Calendar | @mql5dev
❀31πŸ‘5πŸ†2πŸ‘Œ1