MQL5 Algo Trading
580K subscribers
4.68K photos
7 videos
4.68K 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
Slice sampling is presented as an adaptive MCMC alternative that avoids the step-size tuning pain of Metropolis and the conditional-derivation burden of Gibbs. It only needs an unnormalized density (typically evaluated as a log-posterior), then samples by defining a β€œslice” level, expanding or placing an interval/hyperrectangle, and shrinking it until a valid draw is found.

The article details an MQL5 implementation: 1D sampling uses stepping-out plus shrinkage; the multivariate version simplifies by skipping stepping-out and shrinking a randomly placed hyperrectangle.

Tests on Bayesian linear and logistic regression show posterior means and 95% credible intervals closely match OLS and IRLS estimates, while adding full uncertainty quantification. Practical notes include tracking log-density evaluations (neval) and validating chains with trace plots, ACF, an...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀36πŸ‘6πŸ‘Œ3πŸ‘¨β€πŸ’»3✍1
MQL5 backtests often assume ideal fills. Live trading adds slippage, spread widening, requotes, price changes, and latency across the full path: terminal/VPS, network, broker gateway, and liquidity.

A diagnostic EA, Execution Quality Monitor, records execution metrics to separate strategy issues from execution issues. It runs in two modes: an active probe that opens and closes a minimum-lot trade and measures request-to-fill slippage, latency, and retcodes; and a passive listener via OnTradeTransaction that estimates fill quality for normal deals (approximate because the quote is read after execution).

Metrics are split by entry vs exit to detect slippage asymmetry, and reported as distributions (mean, median, p95, worst), plus observed spread. Samples are written to CSV with timestamps for per-hour analysis. Use on demo or minimum lot; probes place real tr...

πŸ‘‰ Read | AppStore | @mql5dev
❀30πŸ‘8πŸ‘Œ2✍1
This article ports level-2 path signatures to MQL5 to measure lead–lag without scanning lags. Instead of shifting series and correlating, it treats two aligned streams as a 2D path and uses the Levy area (the antisymmetric part of level 2) as an ordering-sensitive statistic: sign indicates which channel tends to move first, and zero-crossings mark flips.

The implementation builds a correct incremental engine via Chen’s identity with O(d^2) work per bar, plus a shuffle-relation residual to verify results. A facade class handles preprocessing (time augmentation, window normalization, optional lead–lag staircase transform), and exposes compact features.

Practical output is an indicator plotting a rolling Levy-area oscillator and an EA using the reading directly, with notes on scaling choices and non-stationary behavior in real markets.

πŸ‘‰ Read | Forum | @mql5dev
❀26πŸ‘9πŸ‘Œ2✍1πŸ€”1
This article shows how to generate a portable, one-page trading performance PDF directly from MQL5, without DLL imports or external converters. The approach writes a minimal PDF (catalog, pages, page, font, content stream) using plain strings and the standard file API.

The core constraint is correctness of the cross-reference table: every object’s byte offset must be exact. Offsets are precomputed from ASCII lengths and the file is written in FILE_BIN to avoid newline translation that would corrupt positions.

The solution is modular: one component extracts closed-trade net results (profit+swap+commission) and builds stats plus an equity curve; another renders text and vector graphics via PDF operators, handling string escaping and drawing the curve as a single polyline for efficiency.

πŸ‘‰ Read | Forum | @mql5dev
❀31πŸ‘8πŸŽ‰3πŸ‘Œ2✍1
Financial forecasting remains difficult due to noise, non-stationarity, regime shifts, and event shocks. Classical models assume stability; LSTM/GRU often overfit and degrade under asset or regime changes.

TimeFound targets zero-shot forecasting via a Transformer trained on diverse cross-domain time series. Multi-Resolution Patching converts sequences into multi-scale tokens; independent projection modules with masks improve robustness to padding, missing data, and phase shifts.

The Encoder–Decoder block uses bidirectional self-attention in the Encoder and causal decoding with cross-attention in the Decoder. Forecasting is autoregressive: one next-token segment per step, appended back into history.

Implementation notes: a central unit coordinates both streams. The Encoder uses per-variable attention (CNeuronMVMHAttentionMLKV) with MLKV reuse; the...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘17❀10⚑2πŸ‘Œ2😁1
Anchored VWAP extends standard VWAP by starting accumulation from a user-defined anchor time, preserving full history from that point. This supports event-based analysis, swing-structure study, and custom session boundaries, with optional standard deviation bands.

An MQL5 implementation focuses on indicator architecture: OnInit for input validation, buffer binding, properties, and anchor-line creation; OnCalculate for cumulative VWAP and bands; OnChartEvent for draggable anchor updates; OnDeinit for object cleanup.

Key design points include unique chart object naming via an instance ID, applied price selection, fixed-anchor vs session-reset modes (daily/weekly/monthly), auxiliary calculation buffers, and recalculation control using stored anchor state.

πŸ‘‰ Read | CodeBase | @mql5dev
❀22πŸ‘9πŸ‘Œ2
AutoML confidence gating for EMA crossover systems, built for MetaTrader 5 deployment.

Pipeline runs in Python: fetch XAUUSD H1 from MT5, engineer 9 features (normalized EMAs, EMA distance, RSI and momentum, normalized ATR, volatility ratio, close-range %, direction). Each crossover is simulated with next-bar entry and opposite-crossover exit, then labeled profit=1 or loss=0.

FLAML trains a classifier with time-ordered splits and searches LightGBM/XGBoost/RF. Best model exports to ONNX with a plain probability tensor, then is parity-checked in ONNX Runtime.

MQL5 EA embeds the ONNX model as a resource. On bar close it computes the same feature contract, runs inference, and only trades when P(profit) exceeds a tunable threshold. Exits mirror labeling via ATR trailing and opposite crossover.

πŸ‘‰ Read | Freelance | @mql5dev
❀25πŸ‘6πŸ‘Œ3✍1πŸ‘1
This article reviews a full MT5-ready feature pipeline built on Bill Williams fractals: detecting swing highs/lows, then deriving strength, validity, dynamic support/resistance, breakout flags, trend direction/strength, and whipsaw-filtered entry signals. The goal is structural, timeframe-invariant market context that can feed ML models and rule-based systems.

The key engineering lesson is a look-ahead leak caused by centered rolling windows: raw fractal and derived columns depend on future bars, inflating backtests and even walk-forward results. The fix is to shift leaky columns by n at the feature-matrix boundary while leaving already-causal breakout/trend outputs untouched.

Two additional silent bugs are addressed: a hardcoded shift that breaks when n changes, and a β€œvolatility” threshold that never uses volatility, requiring ATR-scaled validation.

πŸ‘‰ Read | Forum | @mql5dev
❀22πŸ‘6πŸ‘Œ2✍1⚑1πŸ†1
Modern RL Trader v3.1 describes an ensemble RL system with seven agents, each configured for different market regimes and trained on the same 500-bar lookback with distinct network/attention setups.

Core loop follows agent–environment–reward, but adds episode-level updates via BackwardMonteCarlo(), adaptive optimization, and stateful modifiers such as GetEmotionalInfluence() plus m_wisdomAccumulated derived from past outcomes.

Portfolio control is handled by DistributeVolumesAndRewards(), applying weighted voting, lot/reward multipliers, and 24-hour rotation so capital and learning rate concentrate on strategies with current edge while underperformers are throttled.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘15❀11πŸ‘¨β€πŸ’»2πŸ‘Œ1
Time-MoE reframes time-series forecasting as a scalable, decoder-only Transformer tuned for trading data. It keeps strict causality (no future leakage), supports variable history/forecast lengths, and is designed for real-time streams.

Instead of window aggregation, it tokenizes every time step, preserving tick-level detail. Tokens are embedded with SwiGLU, combining smooth nonlinear features with gating to stay stable under noise.

The core adds Sparse Mixture-of-Experts: only a small set of specialist subnetworks activates per token, so capacity scales to billions of parameters without exploding inference cost.

Forecasting is multiscale via parallel heads trained for multiple horizons, with dynamic head selection at runtime based on market conditions.

The MQL5 path breaks this into testable modules: tokenization via 1D convolution, an OpenCL-...

πŸ‘‰ Read | Docs | @mql5dev
❀28πŸ‘8✍1πŸ‘Œ1
MetaTrader 5 ships with many built-in indicators, but no terminal-level search. Access still depends on Navigator or Insert menus, which adds friction during frequent indicator switching and increases accidental selection risk.

A practical workaround is a searchable indicator panel implemented in MQL5 with clear separation of concerns. Core modules: IndicatorCatalog (name to ENUM_INDICATOR map), SearchEngine (case-insensitive substring filtering), ChartLauncher (IndicatorCreate plus ChartIndicatorAdd with window selection), and SearchPanel (Standard Library UI with timer-driven updates).

This structure keeps catalog data centralized, search logic reusable, and platform API calls isolated, while allowing indicators to be located and attached from one panel without manual category browsing.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀17πŸ‘15πŸ‘Œ3
This article builds a compact MQL5 implementation of the Avellaneda–Stoikov market-making model, replacing fixed symmetric grids with quotes that adapt to inventory and market conditions. The core outputs are a reservation price (mid adjusted against current position) and an optimal spread that expands with volatility and tightens with liquidity.

Inputs are estimated online from a rolling window: volatility from price increments, and a practical retail proxy for order-flow intensity derived from mean absolute moves. The code is structured as a testable model class plus a self-check harness to catch sign and scaling errors.

A chart indicator plots reservation, bid, and ask in real time, making inventory skew and spread changes visible. A controlled simulation on EURUSD H1 shows the adaptive quotes keeping inventory near flat and improving P&L versus a fi...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀16πŸ‘16πŸ”₯2πŸŽ‰1πŸ‘Œ1
Classic trading robots often fail because indicators trigger without context: session liquidity, widened spreads, day-of-week effects, and event risk. ML models can score direction, but still miss timing and execution constraints.

A practical mitigation is a local LLM layer that can veto trades when conditions are unfavorable. Self-hosting reduces API cost, avoids rate limits, and keeps strategy data off third-party servers.

Ollama enables a local setup in minutes: pull a base model, run it, then create a custom model via a Modelfile with risk rules, low temperature, and a defined context window. Extend it with larger models, longer context, multi-timeframe inputs, calendar data, and post-trade review logs to reduce false entries and drawdown.

πŸ‘‰ Read | VPS | @mql5dev
❀37πŸ‘10πŸ‘Œ2✍1😱1πŸŽ‰1🀑1
Static take-profits and fixed trailing stops often fail for the same reason: they ignore market structure. Price frequently turns at swing extremes, order blocks, and liquidity zones, so round-number targets get missed and tight trails exit on normal pullbacks.

The article proposes a hybrid exit model: take partial profit at a first structural level, then trail only the remaining position using CRT-derived anchors. Stops move only when price reaches new structural levels, reducing noise-driven stop-outs while banking realized gains.

Implementation in MQL5 centers on a reusable class using Standard Library trade/position APIs. It detects CRT patterns from higher-timeframe OHLC mapping, computes range/signal extremes, executes volume-safe partial closes, and applies one-way stop improvements, with an EA wrapper exposing inputs and chart visualization for vali...

πŸ‘‰ Read | Signals | @mql5dev
❀35πŸ‘11πŸ‘¨β€πŸ’»4✍1
OrderSend() logic tends to sprawl across an EA, duplicating lot rounding, stop validation, retry lists, and slippage checks. The article consolidates these concerns into a CExecutionGateway that becomes the only execution entry point, keeping strategy code focused on trade decisions.

The gateway normalizes volume via CLotNormalizer using symbol min/max/step with caching and float-safe rounding, and enforces broker stop-distance rules via CSlTpValidator, including a spread-based fallback when stops level is reported as zero.

A structured CGatewayResult replaces fragile bool/retcode handling, reporting success, slippage rejection, submitted SL/TP, fill price/volume, attempts used, and a human-readable reason. Filling-mode resolution and centralized retryable retcodes reduce avoidable rejections across brokers.

A thin demo EA shows integration, while a test s...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘7πŸ‘€4⚑3✍2πŸŽ‰1
Multi-timeframe Renko for MT5 consolidates M5/M15/H1/H4 into a single custom symbol updated from ticks. Each timeframe maintains EMA state, Renko direction, last update time, and a signal-strength metric, then a synthesizer builds a unified price stream and writes bricks via CustomRatesUpdate().

Combination options include simple average, weighted average (default weights 1/2/3/4), and a consensus rule requiring 3-of-4 agreement with weighted fallback.

Brick sizing can be fixed or ATR-adaptive using daily ATR with a multiplier (commonly 0.3–0.7). Supports historical rebuild from M5 and real-time updates, enabling indicators, strategy testing, and EAs on the synthetic symbol.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀43πŸ‘14πŸ‘¨β€πŸ’»5⚑3πŸ‘Œ2πŸ‘€2✍1
Quantora Trade Manager MT4 is a trade management utility focused on risk control for existing positions. It does not generate signals or place new orders, but automates common protective actions on open trades.

Core functions include automatic stop loss and take profit placement, break-even handling, and trailing stop management to lock in gains during favorable moves. Management can be applied to manual-only trades, all positions, or subsets filtered by magic number, with independent handling for buy and sell orders.

Account-level controls include daily profit and loss limits to cap exposure across the session. An integrated dashboard summarizes key account and position metrics for faster monitoring and operational checks.

πŸ‘‰ Read | Quotes | @mql5dev
❀31πŸ‘11πŸ‘Œ2πŸ‘€1
Quantora Break Even Manager for MT4 is a position management utility that shifts stop loss to break-even after a configurable profit threshold is reached. It does not place orders or provide trade signals, and is limited to risk control on existing positions.

The tool monitors open trades and applies break-even rules based on user settings, including a trigger level and an optional offset to lock in a small gain. It can operate on manual orders, all positions, or a subset filtered by magic number, with independent handling for buy and sell directions.

Additional controls include symbol filtering, a compact dashboard for account and trade status, and a one-click action to apply break-even immediately to eligible positions. Designed for consistent automation of profit protection with minimal workflow overhead.

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘16❀14πŸ‘¨β€πŸ’»3πŸ‘Œ2πŸ†1
Quantora Trailing Stop Manager for MT4 is a trade management utility focused on stop-loss automation. It does not place orders and does not generate trade signals.

Trailing is enabled only after a configurable profit threshold is reached. Once active, the stop loss is adjusted in defined steps, using parameters for start level, trailing distance, and update increment, with an optional minimum-profit wait condition.

Operation can be applied to manual trades, all open positions, or a filtered set via magic number. Buy and sell orders can be managed with separate settings.

A compact dashboard displays current status and key values, and a one-click action can apply trailing immediately to qualifying positions.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀28πŸ‘10πŸ‘Ύ4✍2πŸ‘Œ2
Quantora Position Size Calculator for MT4 calculates a broker-compatible lot size from a defined risk and stop loss distance. It is a pre-trade risk utility and does not place orders or generate trade signals.

Risk can be set as a percentage or fixed amount, then converted using account balance, equity, or a custom account value. Stop loss input supports points or direct price difference.

Symbol parameters are read automatically, including tick value, tick size, and volume limits, to align sizing with contract specifications. Output includes basic risk/reward figures and an estimated margin requirement.

Designed for traders seeking consistent position sizing and risk control across instruments.

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘13❀12πŸ‘Œ3πŸ†1
Quantora Risk Calculator MT4 is an open-source utility for pre-trade risk and reward estimation on MetaTrader 4. It calculates money risk, account risk percentage, potential profit, and reward-to-risk using symbol, direction, lot size, entry, stop loss, and take profit.

The tool supports buy and sell scenarios, works with balance, equity, or a custom account value, and allows current-chart or custom symbol selection. It includes automatic risk level classification with configurable thresholds.

Additional outputs cover margin requirement, margin vs free margin percentage, margin status, and position value, with warnings on excessive margin usage. A dashboard provides recalculation and reset controls.

No trades are opened and no signals are generated; results depend on broker contract specs, currency conversion, and execution conditions.

πŸ‘‰ Read | Quotes | @mql5dev
❀30πŸ‘6πŸ‘Œ2πŸ‘¨β€πŸ’»2πŸ†1