MQL5 Algo Trading
542K subscribers
3.88K photos
6 videos
3.89K 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
LightGTS tokenizes time series by FFT-based period patching, then applies flexible projection to handle variable-length cycles. Transformer Encoder blocks consume these tokens, and Periodical Parallel Decoding emits the forecast in one pass, with a resize stage preserving periodic consistency.

Rotary Positional Encoding replaces additive position vectors by rotating Q/K coordinate pairs. It is parameter-free, requires even embedding size, and improves relative shift handling under variable windowing.

An OpenCL RoPE implementation maps work-items over (D/2, tokens, variables), uses float2 pairs, precomputed sin/cos tables, and minimizes global reads. A backward kernel applies the inverse rotation to propagate gradients.

In MQL5, a CNeuronRoPE wrapper validates even dimensions, builds a cos/sin matrix once on CPU, and queues forward/backward kernels. Encoder...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘11❀9πŸ†3πŸ‘Œ2
The project evolves from a basic FastAPI + Jinja2 MT5 process controller into a terminal manager that can surface live trading-account metrics in the UI. Hard-coded terminal paths are replaced by startup-selectable configuration, preparing the app for real deployments with many instances.

A new endpoint (/instances/{name}) returns per-terminal status as JSON, with request handlers organized into a dedicated controller class. The UI is refined using Bootstrap and jQuery, enabling simple periodic polling to refresh terminal data without manual page reloads.

Account and terminal characteristics are read via the MetaTrader5 Python library by connecting to a specific terminal executable (portable mode), using a short initialize() timeout to avoid blocking on disconnected terminals, then querying terminal_info(), account_info(), and last_error() before ...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘13❀8πŸ‘Œ3
SuperTrend is a volatility-band indicator rendered as a single line that flips sides by trend. It combines ATR with a ratchet that preserves prior band state, so each bar depends on the stored state of the previous bar.

Most β€œrepainting” reports are state-management faults: closed bars changing due to broken recursion, series/normal indexing mismatches, or buffer history being reset. In MT5 this is amplified by call-based execution, so recursive state must persist across calls.

A robust approach uses calculation buffers (sUp, sDn, sTrend) instead of manually resized arrays, creates the ATR handle once in OnInit, and copies ATR data defensively. Live updates typically reprocess only the forming bar and the last closed bar.

Arrows should be delayed until reversals are no longer at risk of being invalidated by the next ticks.

πŸ‘‰ Read | CodeBase | @mql5dev
❀26πŸ‘6πŸ‘Œ2
MetaTrader 5 positions are isolated, which makes basket-level risk control awkward when trades are correlated. The article solves this with CBasketManager: positions are grouped by a basket ID stored in POSITION_COMMENT using a simple β€œBASKET:ID” convention, enabling basket-wide P&L tracking and coordinated exits.

The design separates concerns cleanly: a scanner aggregates state into a single CBasketInfo snapshot (sum P&L, long/short volume, volume-weighted pips, distance to stop), an executor handles order sends and closes legs safely in reverse order, and a stop registry enforces a unified equity threshold via a callback so risk logic stays decoupled from execution.

Practical details target real brokers: filling mode is resolved from SYMBOL_FILLING_MODE to avoid common retcode failures, symbols like gold are configurable and selected early to ensure prope...

πŸ‘‰ Read | VPS | @mql5dev
❀18πŸ‘6πŸ‘Œ2
Broker Execution Diagnostics MT5 is a read-only script that reports symbol constraints commonly linked to invalid volume, invalid stops, and inconsistent risk calculations.

Output includes digits, point, tick size, tick value, current spread (points), min/max/step volume, and a conservative normalized volume for a requested size. It also reports stops and freeze levels in points and price distance, plus trade mode and execution mode values. Optional checks cover entry-to-Stop-Loss distance and an OrderCalcProfit estimate in account currency.

Inputs: InpRequestedVolume for normalization, optional InpEntryPrice and InpStopLossPrice for distance and P/L checks, plus InpShowOnChart to print the report on-chart.

Usage: compile in MetaEditor, attach to the target symbol, and read results in Experts log or chart comment. No orders are sent or modified. Sui...

πŸ‘‰ Read | Forum | @mql5dev
❀16πŸ‘7πŸ‘Œ2⚑1
Session Sweep Reversal Detector flags intraday reversals around completed session boundaries. It plots the finished session high/low as forward reference lines, then monitors post-session price action for a liquidity sweep.

A sweep requires price to breach the frozen high/low by more than a configurable buffer, then close back inside the range within a limited number of bars. Breaches that fail to reverse in time are treated as breakouts and ignored.

Signals are shown as arrows: bullish when the session low is swept and price closes back above it, bearish when the session high is swept and price closes back below it. Key inputs include session start/end hours, sweep buffer in pips, reversal bar limit, and the number of prior sessions displayed. Most relevant on M5–M30, commonly aligned to London or New York hours on major FX pairs.

πŸ‘‰ Read | VPS | @mql5dev
❀27πŸ‘7πŸ‘Œ2πŸ‘¨β€πŸ’»2
Trade Transaction Trace Logger is a read-only MT5 Expert Advisor designed to diagnose the lifecycle of orders, deals, and positions. It records OnTradeTransaction events in arrival order to a local CSV file and can optionally mirror a compact line to the Experts Journal.

Captured fields include a monotonic event sequence with server time, transaction type, symbol, resolved magic number, and order/deal/position tickets. It also logs order type and state, deal type, price, trigger, SL/TP, volume, plus request action and server retcode/comment. If an event lacks context, the core attempts resolution via request data, live orders, order history, deal history, or current positions.

Configuration covers symbol scope (chart or all), magic filtering (-1 or exact), CSV filename, Common Files storage, and Journal printing. The module sends no trade requests, uses no DLL/W...

πŸ‘‰ Read | AppStore | @mql5dev
❀18πŸ‘11πŸ‘Œ3
Stop Geometry Visualizer for MT5 is a free, read-only indicator that renders broker Stops Level and Freeze Level as chart references.

It displays current Bid, Ask, spread, Stops/Freeze values in points and price distance, plus upper/lower geometry references for Buy Stop, Sell Stop, Buy Stop Loss, and Sell Stop Loss. Optional freeze reference lines can be enabled. It also reports tick size, volume min/step/max, and filling-mode flags.

A timer-based refresh is configurable via InpRefreshSeconds. Visibility of stop/freeze references and change logging is controlled by inputs, along with line color settings. When a broker reports zero Stops or Freeze, lines are omitted and the dashboard explicitly shows zero.

No orders are placed, modified, or deleted. Lines are diagnostic only; final validation should use the current broker state and OrderCheck.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘16❀10πŸ‘Œ2⚑1
Round Trip Cost Reconciler is a free, read-only MT5 utility that generates two CSV outputs for trade cost accounting. One file contains filtered deal records. The second aggregates buy/sell deals by DEAL_POSITION_ID to produce position-level round-trip figures.

Partial fills are consolidated into volume-weighted entry and exit prices. Commission, swap, and fee remain separated from gross trading result, enabling cleaner reconciliation of broker-recorded costs versus PnL.

Reports include deal/order/position identifiers, symbol, magic number, direction, entry type, timestamps, price/volume, broker profit and costs, total entry/exit volume, weighted prices, gross result, total costs, net result, deal count, and lifecycle status.

Lifecycle states: COMPLETE, OPEN_OR_INCOMPLETE, EXCESS_EXIT, and COMPLEX_REVERSAL (INOUT reversals are not simplified).

Setup: compile t...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘11❀7πŸ‘Œ2
Broker Session Schedule Inspector for MT5 reads the weekly trading-session schedule directly from the connected broker, without using predefined London, New York, or other global session templates.

The script can be run against the current chart symbol, a comma-separated custom list, or all visible Market Watch symbols. For each symbol it enumerates sessions returned by SymbolInfoSessionTrade, checks whether current server time is inside a scheduled window, and identifies the next open or close transition. Trade mode and synchronization status are also reported.

Midnight-crossing sessions are marked with (+1d). If the broker does not provide schedule data, the output returns SCHEDULE_UNAVAILABLE rather than generating fallback hours. Optional CSV snapshots with timestamps can be written to the terminal Common Files folder.

Inputs include symbol scope, custom...

πŸ‘‰ Read | AppStore | @mql5dev
❀10πŸ‘10πŸ‘Œ3✍1
Look-ahead bias remains a primary reason ML trading models fail on non-stationary live data. It appears when labels are derived from future price movement, producing inflated backtests, weak out-of-sample results, and low robustness due to overfitting.

A proposed alternative is oscillator-based labeling that avoids future information. Labels are generated from overbought/oversold thresholds with an added β€œdo not trade” zone, enabling cleaner cross-validation and simpler decision boundaries.

Key limitations persist: oscillator selection and parameterization, poor behavior in trends, and instrument dependence. Adding profitability checks can smooth equity curves but reintroduces look-ahead.

Implementation details include Numba-accelerated indicator calculation, threshold-to-label mapping, optional profitability filtering, and ONNX export for deploymen...

πŸ‘‰ Read | Freelance | @mql5dev
❀11πŸ‘9πŸ‘Œ1
Financial time series work increasingly depends on probabilistic forecasts, not point estimates. Longer horizons amplify error accumulation, volatility sensitivity, and compute costs, especially under regime shifts driven by earnings, macro data, and geopolitics.

KΒ²VAE combines Koopman linearization, Kalman-style online correction, and a VAE for scenario generation. Tokens are built from multivariate patches to capture cross-asset interactions, then mapped into an observable space where a learned Koopman operator rolls dynamics forward.

Residuals from the linear rollout feed KalmanNet via control inputs, producing updated state and covariance per step. The decoder samples multiple future trajectories, returning distributions with confidence intervals suited for risk-aware trading and portfolio sizing.

πŸ‘‰ Read | VPS | @mql5dev
❀10πŸ‘4πŸ†2πŸ‘Œ1
Differential Search Algorithm (DSA), proposed by Pinar Civicioglu (2012), targets continuous optimization as an alternative to PSO and DE. It maintains a population and updates candidates through directed moves with controlled randomness.

Per iteration, each agent picks a direction via B-DSA (permutation), S-DSA (top-N sampling), E1-DSA (single random leader), or E2-DSA (best leader). Step magnitude uses Gamma-distributed scaling, allowing occasional large jumps and negative steps.

A coordinate mask restores selected dimensions to previous values, then greedy selection keeps only improved candidates. Typical implementation separates Init, Moving, Revision, plus direction generation, mask creation, scale factor (Gamma RNG), and boundary control.

πŸ‘‰ Read | Forum | @mql5dev
❀8πŸ‘5πŸ‘Œ2
Moving-average inputs were extended with statistical signal processing to reduce market noise, using Independent Components Analysis (ICA) as a blind source separation step.

Pipeline used SMA-filtered OHLC data with 5-day lags, exported from MQL5 (49 columns) and modeled in Python. A surrogate target based on future SMA change aligned with raw return direction about 81% of the time, and showed improved classification accuracy as lags increased, unlike raw returns.

FastICA on 24 SMA/lag features peaked near 18 components and plateaued after ~13; 12 components were retained to control complexity. KMeans on the ICA manifold showed mostly uniform error rates, with one small, unreliable low-error cluster.

Models were tuned via RandomizedSearchCV, exported to ONNX, then loaded in an MQL5 EA alongside indicators and trade management.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀3πŸ‘2πŸ‘Œ1