MQL5 Algo Trading
578K subscribers
4.58K photos
7 videos
4.59K 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
The article builds an MT5 Expert Advisor that trains a fully connected CNet model to predict Bill Williams fractal pivots one bar earlier than the standard indicator’s confirmation delay. It frames the task as supervised learning: feed the latest market context, then label the previous bar after the next candle closes.

Inputs combine normalized candle features (Close/High/Low relative to Open), time components (month, hour, weekday), volumes, and four standard oscillators (RCI, CCI, ATR, MACD), producing 12 values per bar across a configurable history window. The network uses 4 hidden layers starting at 1000 neurons and shrinking by 70% per layer with a floor of 20.

Two output designs are compared: a single tanh neuron encoding buy/sell/none, or a 3-neuron probability classifier. Implementation details include loading a saved trained network, tracking MSE and hit...

👉 Read | Docs | @mql5dev
👍16❤15🔥8🤩8
This article refactors an MQL5 SQLite helper to make SQL script execution cleaner, testable, and future-proof. The original design is reworked into a single C_DB_SQL class with a constructor that opens the database (optionally in-memory) and a destructor that guarantees proper close, reducing lifecycle bugs.

Script execution is improved by returning status text instead of printing to the terminal, enabling UI-agnostic error reporting. Failures are traced back to the exact script line, while successful runs return null, keeping calling code simple.

The key upgrade is supporting SQL embedded as an MQL5 resource. The implementation converts resource text into a byte buffer, parses it into statements, and reuses one private ExecSQL pipeline for both files and resources. This encapsulation keeps the public API stable while allowing future backends (e.g., client-s...

👉 Read | Forum | @mql5dev
❤12👍10🤩9🔥8🎉2😁1
Live tick transfer from MetaTrader 5 to Python can avoid per-tick allocations by sharing an Apache Arrow columnar layout in shared memory and importing it with zero copies.

Part 1 implemented the MT5 writer: two double-buffered slots, fixed headers, six 8-byte columns with padded buffers, and a lock-free seqlock where odd generation means “writing” and even means “stable”.

This follow-up implements the Python reader with ctypes definitions of ArrowArray and ArrowSchema, points their buffers directly into an mmap, and builds a pyarrow.RecordBatch without struct.unpack loops or boxing.

A standalone benchmark reproduces the exact memory layout locally and compares the zero-copy import path against legacy field-by-field unpacking across batch sizes.

Notes: schema and column-count contracts must match; seqlock assumes correct memory ordering; imported batch...

👉 Read | NeuroBook | @mql5dev
❤9👍6🤩6🔥4⚡2
RAFT is adapted from optical flow to market forecasting by treating past vs present as two “frames” and iteratively refining a prediction instead of producing a one-shot output. The core gain is an all-pairs correlation field that compares current features against a historical stack, capturing global interactions rather than local matches.

A key upgrade for finance is replacing fixed context with a recurrent contextual encoder, letting the model track regime shifts (volatility, liquidity, correlation changes) as an internal state. This keeps context current without the cost of expanding the entire history window.

In MQL5, the CNeuronRAFT object assembles encoders, multiscale stack correlation, concatenation, GRU-based refinement, and a stabilizing residual path. The model predicts a delta update each iteration, improving training stability and making real-t...

👉 Read | VPS | @mql5dev
❤12👍7🤩5
This article breaks down why prop-firm protection logic in MT5 often fails even when the math is correct: rules interfere with each other, actions change the data mid-pass, and state resets/reboots silently reopen risk.

The core fix is architectural. All firm checks read a single account snapshot struct built once per tick, passed as a const reference. Rules never query live account state and never act directly; they only return a verdict with separate severity and directive so advisory payout constraints don’t trigger forced closes.

It adds a firm-time session clock (non-midnight rollovers), a daily profit ledger aligned to the firm’s day for consistency/min-days rules, explicit enable flags plus validation, two distinct reset paths (challenge vs intraday), and built-in serialization so a VPS reboot can’t refill drawdown budget.

👉 Read | AppStore | @mql5dev
👍14❤10🤩4
An MT5 exit module adapts Longstaff‑Schwartz LSM from American option pricing to trade management. The decision is framed as exercise (close now, realize PnL net costs) versus continuation, with a forced horizon to supply expiry.

Calibration uses recent log‑returns to estimate per‑bar drift and volatility, then simulates GBM paths. Backward induction fits continuation value via regression on in‑the‑money simulated paths only; the live position is compared once at step zero, allowing exits on losers if continuation is worse. Hard backstops remain: max holding period and fixed stop distance.

Implementation is native MQL5: no DLLs or libraries. Least squares uses ridge‑regularized normal equations with Gauss‑Jordan and pivoting, with explicit failure handling. Components are split into linear algebra, engine, EA, and an indicator that plots the exerci...

👉 Read | VPS | @mql5dev
❤13👍8👨‍💻4🔥3🤩3
A–B–C–D recognition can be correct and still generate triggers that are late, rare, or carry high adverse movement. Without measurement, A–B relationships cannot be compared and filtered with evidence.

A measurement layer can be added without changing pattern rules. For each completed D window, record C setup time, D confirmation time, breakout distance versus C, and directional MFE/MAE from processed M1 ranges, including the confirmation bar range. Also track trigger rate per A–B relationship.

Implementation is done in an MT5 EA with recognition, measurement, reporting, and execution separated. Trading stays disabled by default behind an explicit gate. The higher-timeframe open after D is the commit boundary; detach writes a snapshot with record_kind so incomplete windows do not pollute completed statistics. CSV export includes run_id, grouped counters, an...

👉 Read | CodeBase | @mql5dev
❤9👍6🔥3🤩3
A Supertrend flip scalper for MT5 built around optional filters: RSI, ADX/DI, MACD divergence, Bollinger Bands, EMA trend/slope/zone, VWAP, ATR range/strength, distance to Supertrend, support/resistance, minimum bars between signals, plus a probability threshold. Filters can be toggled from the chart and statistics update immediately.

The on-chart panel compares actual win rate to breakeven win rate for the configured SL/TP ratio, and accounts for recorded per-bar spread plus round-trip slippage. If actual performance is not clearly above breakeven, expectancy is negative.

On ~5 years of XAUUSD M5 with real per-bar spread, the core signal sat on the breakeven line across multiple targets (1.5, 1.85, 3.0 ATR). Flat before costs, slightly negative after spread. Presented as a research/learning tool, not a profitable system.

Signals trigger on a closed-bar Sup...

👉 Read | VPS | @mql5dev
❤14👍5🤩5🔥4✍3
Bezier curves remain a general tool, but UI geometry is dominated by arcs and rectangles with corner radii. Approximating arcs with cubic Beziers adds avoidable error and makes segment sizing indirect.

A circle arc can be flattened into chords with a segment count derived from the sagitta bound. One acos gives the maximum per-segment angle for a pixel tolerance, then the count is rounded up. Guards cap unusable extremes: overly large tolerance clamps the step to π, and microscopic tolerance falls back to a coarse step to prevent runaway vertex counts.

ArcTo precomputes vertex capacity and must handle the missing first vertex case. Behavior matches Cairo: MoveTo when no current point, LineTo if needed, and avoid duplicates when already at the start.

Rounded rectangles use four independent corner radii (CSS order). Each radius is clamped to half the s...

👉 Read | CodeBase | @mql5dev
👍9🤩9❤8🔥5
Tick Scalper Helper is a manual trading utility for ultra-short timeframes that replaces the standard chart with a compact tick chart and a fast order panel. Each tick is rendered as a 2‑pixel bar, with grouping controls (1, 2, 4, 8… ticks per bar), optional time-scaled mode, configurable colors, and light/dark themes. BID and ASK lines update on every tick, with vertical zoom and panning optimized for rapid inspection.

The trading panel provides BUY/SELL plus Close Buy, Close Sell, Close Profit, and Close All for the chart symbol. Optional SL/TP can be set in points, with enforcement of broker minimum distances. Ctrl/Shift-click places pending orders at the cursor price with automatic limit/stop selection, with crosshair preview and stops-level blocking.

Strategy Tester support covers visual and non-visual modes plus optimization, using an optional de...

👉 Read | Freelance | @mql5dev
❤20🤩17👍16🔥13⚡2
A market structure indicator for XAUUSD, EURUSD, and any symbol/timeframe, calculated strictly from closed candles. Swings are confirmed by N candles on both sides, labeled as HH/HL/LH/LL with an inherent delay; the forming candle never paints.

Breaks are drawn from the last swing to the candle that closes beyond it. In bullish structure, a close above the last swing high is BOS; in bearish structure, the same event is CHoCH and flips trend. Optional pop-up, push, and sound alerts trigger only on the just-closed bar.

Four iCustom-readable buffers are filled for automation: 0 BOS up, 1 BOS down, 2 CHoCH up, 3 CHoCH down. Values are set to the breaking candle low for bullish breaks and high for bearish breaks; otherwise EMPTY_VALUE. Parameters include swing length, bars processed, per-type line display/style, colors, widths, label size, and an object p...

👉 Read | Quotes | @mql5dev
👍25❤21🔥18🤩18
Time-based rules like “08:00 New York” are fragile in MetaTrader due to nonstandard broker server clocks and DST gaps between the US and Europe. Strategy Tester time functions also collapse to server time, and live TimeGMT() depends on the PC clock.

A small package addresses this with explicit date rules, no web requests, and no DLL. BrokerTime.mqh provides CBrokerTime; BrokerTimeLines.mq5 draws daily session lines and a clock panel.

Supported zones include UTC, New York, London, Frankfurt, Sydney, Tokyo, broker server, and a fixed offset. DST rules are implemented for US/EU/UK/Sydney; Tokyo is constant. Broker server mode can be US-style, EU-style, or fixed offset.

DetectFromHistory(symbol) infers the broker clock from up to 40 Friday H1 closes (needs 4+ weekends), reports confidence, and works in Strategy Tester. Conversion helpers cover zone/server/UTC...

👉 Read | Freelance | @mql5dev
👍21❤12🔥12🤩11
Stationarity.mqh adds five unit root and mean reversion diagnostics beyond ADF: KPSS, Phillips-Perron, DF-GLS (Elliott–Rothenberg–Stock), Zivot-Andrews (single structural break with estimated date), and the Lo–MacKinlay variance ratio. Each test reports statistic, p-value, 1/5/10% critical values, plus the selected lags or bandwidth. Implementation runs without DLL dependencies.

KPSS supports constant or trend with automatic or specified bandwidth and interpolated p-values. Phillips-Perron supports Z-tau and Z-rho with Newey-West variance and MacKinnon reference values. DF-GLS performs GLS detrending (c = -7 or -13.5) with lag selection by AIC, BIC, or t-stat rules. Zivot-Andrews supports level, trend, or both breaks with trimmed search and cached cross-products for speed. Variance ratio supports overlapping/non-overlapping, debiasing, and heteroskeda...

👉 Read | Quotes | @mql5dev
❤12🤩7👍6🔥3
RealizedVol.mqh provides volatility estimation and forecasting from price data without DLL dependencies. It implements five OHLC range estimators: close-to-close, Parkinson, Garman-Klass, Rogers-Satchell, and Yang-Zhang. Range-based methods use high/low data and typically need fewer bars than close-to-close for comparable precision; Rogers-Satchell supports drift and Yang-Zhang incorporates inter-bar gaps.

For intraday series, CRealized::Daily computes daily realized variance, bipower variation (variance component excluding jumps), realized quarticity, and a Jump() measure above bipower variation. Parameters include session start shift and minimum bar count per day.

Forecasting uses the HAR model (Corsi, 2009) with 1/5/22-day horizons, optional log specification, and Newey-West standard errors, reporting coefficients, t-stats, R², and forecasts. Vola...

👉 Read | AlgoBook | @mql5dev
❤10👍7🔥1