MQL5 Algo Trading
579K subscribers
4.62K photos
7 videos
4.63K 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
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
❤17👍10👨‍💻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
❤14👍8🔥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
❤16👍8🤩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
👍13❤9🤩9🔥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
❤23👍18🤩17🔥13⚡3
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
👍27❤24🔥20🤩20🏆1
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
👍25❤14🔥13🤩13
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
❤15👍12🤩8🔥4
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
❤21👍15🔥7🤩4
Temporal Motion Aggregation (TMA) reframes market data as motion: the model prioritizes transition speed, direction, and continuity over raw price snapshots. A three-stage pipeline filters/normalizes the stream, learns primitive movement motifs, then aggregates them into higher-level structures usable for forecasting and decision logic.

The MQL5 implementation builds a top-level CNeuronTMA object on RAFT-style recurrent refinement, reusing proven module orchestration and OpenCL acceleration. Initialization assembles an encoder/context backbone with ResNeXt-like blocks, ConvGRU-based memory, a state stack for sequential latent updates, and multiscale segment correlation to compare multiple time windows.

Two attention-style Motion Pattern Aggregation blocks suppress noisy fragments and amplify high-energy, repeatable moves. The forward pass iterativ...

👉 Read | Forum | @mql5dev
👍13❤9🔥9🤩7
Clarification on loss visualization in gradient descent: a 2D curve plot does not imply a unique minimum error. The loss landscape is high-dimensional, and “valleys” depend on initialization and parameter space, not the dataset chart.

An update to a single-neuron gradient-descent implementation adds a bias term. Weight and bias gradients differ, so the loss function must return two doubles; a struct-based return is one practical approach in MQL5.

Stochastic gradient descent is outlined as a performance variant: compute gradients on slices of the dataset instead of full passes, using bounded index ranges per iteration to reduce runtime on large training sets.

👉 Read | CodeBase | @mql5dev
👍16🔥9❤4🤩3
The article breaks down why subwindows in MetaTrader 5 are often misunderstood: indicator_chart_window ties an indicator to the window it is dropped into, not necessarily the price chart. Dropping a moving average into the Volumes subwindow displays it there, but does not automatically switch its input series to volume.

A common failure case is expecting iMA to average another indicator’s values. MT5 cannot feed iMA with data it doesn’t own, so the MA either tracks price or fails when pointed at external indicator buffers.

The practical fix is to implement the moving average calculation inside the custom indicator and explicitly select the source buffer (e.g., “first indicator’s data”). This produces a true MA of volume and scales to other subwindow-based workflows with controlled resource use.

👉 Read | Freelance | @mql5dev
👍12❤8🔥5🤩2👨‍💻2👌1
A follow-up on a gradient-descent neuron highlights why activation functions and network depth are context-dependent, and why a neural network is often not the best tool.

A single linear neuron can fail to converge on datasets that are solvable via least squares or pseudoinverse. With unchanged update logic, the observed error can grow instead of shrinking, indicating mismatch between model assumptions, scaling, and objective.

Key points: input normalization frequently determines whether training converges; “backpropagation” in this setting is the parameter update inside the loop; and the loss function can block learning for specific data.

Activation functions are not universal fixes. They matter mainly for non-linear separability and certain architectures, and require deliberate selection rather than default choices.

👉 Read | Docs | @mql5dev
❤12👍7🔥5🤩4🤯2
A utility script is available to close open positions with a single action and optionally remove pending orders. It is intended for rapid exposure reduction, including pre-event risk control and end-of-session cleanup.

Configuration options include selecting scope (all symbols or only the current chart), filtering by magic number (-1 for no filtering), enabling deletion of pending orders, and an optional confirmation prompt before execution. A maximum slippage value in points can be set to constrain close price deviation.

The script supports both hedging and netting account modes. Execution results are summarized in the Experts log. Validation on a demo environment is recommended before live use.

👉 Read | AppStore | @mql5dev
👍9❤7🔥3🤩2
A few hand-picked sizing examples can look correct while hiding rounding and boundary defects. This article builds a deterministic, broker-free MQL5 test harness for a pure risk-to-volume model and treats the sizing rule as an executable contract.

Instead of only example-based assertions, it uses property-based checks over generated scenarios plus fixed regressions for known edges. A seeded xorshift RNG provides reproducible runs, and failures are recorded with enough precision to replay independently of call order.

The model is explicit about IEEE-754 behavior, step-based volume grids, and conservative “never round up” selection. Eight metamorphic properties validate monotonicity (budget vs. stop distance), symmetry, scaling/translation cohorts, and strict contract adherence, while intentional wrong outputs test the checker itself. A separate demo...

👉 Read | NeuroBook | @mql5dev
❤11🔥8👍7⚡3🤩3
A session-box indicator is available for marking the three primary FX trading windows: Asia, London, and New York.

For each session, a box is drawn between the configured start and end times using broker server time. The box boundaries are based on the session high and low, providing a consistent view of intraday ranges, breakout areas, and frequently traded liquidity zones.

Configuration includes the number of historical days to display, per-session start/end hours, per-session colors, optional box fill, and optional session labels. Time settings require adjustment when broker server time differs from local or market convention. Supported chart timeframes range from M1 to H1.

👉 Read | VPS | @mql5dev
❤11👍4🔥3✍2🤩2
Backtests can hide which part of an EA is failing when multiple entries share one magic number. In an order-block liquidity-sweep scalper, splitting results by setup showed most losses came from only one side, despite identical code and risk.

CSetupLedger fixes this by encoding a setup id into the magic number (not comments, which brokers overwrite), then rebuilding per-setup stats from account deal history so restarts, file loss, and manual closes don’t erase the record. Correct aggregation requires scoring by position id, summing partial fills, and using net P/L including commission and swap.

Instead of trusting raw win rate, it reports a Wilson confidence interval and compares it to the setup’s real breakeven rate derived from observed average wins/losses. The output becomes actionable: too few trades, undecided, trusted, or rejected.

👉 Read | AppStore | @mql5dev
❤14👍7🔥7🤩5🎉2👀1
A lightweight MT5 candle-close countdown indicator for any symbol and timeframe, including XAUUSD and EURUSD. The timer uses the broker trade-server clock, so it keeps updating during low-tick periods and aligns with broker candles rather than the local PC time.

Display supports either a price-attached mode (offset to the right of the last bar) or a fixed chart corner with configurable pixel offsets. Output formatting adapts to timeframe: mm:ss on intraday, hh:mm:ss from H1, and days+hours on D1 and higher. Optional spread display, optional symbol/timeframe prefix, and a last-seconds color change are available.

Alerts can trigger once per candle a configurable number of seconds before close, via pop-up and/or sound. Implementation uses a single text object created once and rewritten every 500 ms; no canvas or buffers. On weekends or outside sessions, ...

👉 Read | AlgoBook | @mql5dev
❤9👍5🔥5🤩4
Backtests built on smooth-volatility assumptions tend to fail when volatility shifts fast. Empirical realized-volatility studies (Gatheral, Jaisson, Rosenbaum, 2014) estimate the Hurst exponent for log volatility around H≈0.10, consistent with rough, anti-persistent dynamics that classical GBM/GARCH families cannot model.

A practical implementation is a moving-window Hurst estimator using R/S analysis with OLS in log-log space and logarithmically spaced scales. Non-overlapping subsample averaging improves stability; safeguards avoid degenerate R/S and regression cases.

Signal mapping is operational: H<0.3 indicates rough/mean-reverting conditions, 0.3–0.5 neutral, H>0.5 trending/persistent. The output is a regime filter for strategy selection and a risk metric for reducing exposure during regime transitions.

👉 Read | AlgoBook | @mql5dev
❤18👍10🔥6🤩3
CanvasTabs provides a lightweight tab bar for charts using the standard CCanvas class. Distributed as a single include file, it has no DLL dependencies, no trading logic, and no built-in persistence. Intended for panels that need basic tabs without a full GUI framework.

Supports tab titles, an active tab, and a minimal hover state. Tabs can be changed by mouse click or via SetActiveTab. Resize updates width without recreating the chart object. Long titles are truncated to fit, with an ellipsis when space permits.

Multiple independent instances are supported on the same chart, each with unique object and resource names. Height, padding, and font size are scaled once from screen DPI. Destroy() cleans up only the instance resources and is safe to call repeatedly. OnChartEvent returns true only when a click changes the selected tab.

A demo expert shows tw...

👉 Read | Quotes | @mql5dev
❤11👍8🤩4
Multiple regression is a baseline tool for trading models where returns respond to several drivers at once. Single-factor fits often shift missing effects into the error term, producing biased coefficients and unstable results when regimes change.

Core setup uses OLS with matrix notation: b = (XᵀX)⁻¹Xᵀy. This requires no multicollinearity; otherwise XᵀX becomes singular. Model building stays iterative: add, remove, and transform regressors, then re-run diagnostics.

Standard checks include residual plots, QQ/EPDF, autocorrelation tests, and stability tests. Factor diagnostics rely on correlation matrices, partial regression plots, VIF for multicollinearity, and Cook’s distance for influential observations. Formal testing typically adds Ljung–Box, Jarque–Bera, Breusch–Pagan, Ramsey, and F-tests.

👉 Read | Freelance | @mql5dev
❤13👍9🔥6🤩6