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
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
An H1 EURUSD pullback system combines a 14-period linear weighted moving average, Awesome Oscillator, and a daily reference level from three sessions back. Entries are never at market. Signals place stop orders at the prior daily low/high, so execution occurs only if price reclaims that level.

Buy setup: the open from two bars ago is below the WMA and AO is decreasing on the last closed bar. A buy stop is set at the daily low from three days back, only if that level is above current price. Sell setup mirrors this logic using the daily high, only if it is below current price.

Risk uses an internal ATR(24) with Wilder smoothing. Stop is 1.5 ATR from entry, target is 0.7% of entry, and volume is sized so a stop-out costs a fixed 20 USD by default. Pending orders expire after 12 bars and are replaced by newer same-side signals. Evaluation occurs once per bar; o...

πŸ‘‰ Read | Quotes | @mql5dev
❀11πŸ‘10πŸ”₯2πŸ‘Œ2πŸŽ‰1
MQL5 exposes AccountInfoInteger(ACCOUNT_FIFO_CLOSE) to detect FIFO close enforcement. On FIFO accounts, closing anything but the oldest ticket on a symbol can be rejected with TRADE_RETCODE_FIFO_CLOSE (10045), breaking exit logic that targets recent adds in pyramiding systems.

A practical approach is a two-part design. CFifoPositionQueue snapshots the EA’s own positions per symbol (magic-filtered), sorts by POSITION_TIME_MSC with ticket tie-breaks, and provides eligibility plus a required close sequence. CFifoComplianceGuard owns all CTrade calls, runs async off, rechecks eligibility before each step, and either rejects non-eligible requests or executes a cascade.

Included examples show an EA that intentionally requests the wrong ticket, plus synthetic tests for ordering, cascades, and volume normalization. Backtests validate decision logic, not broker...

πŸ‘‰ Read | Signals | @mql5dev
❀15πŸ‘10πŸ”₯5🀩2
Spread behavior is session-dependent: typically tighter during London and New York, wider at the daily rollover around 17:00 New York and in the first minutes after the weekend open. SpreadHeatmap visualizes this as a 24x8 table per chart symbol, with weekdays plus an β€œAll” column. Each cell shows the typical spread for that hour/day in points, color-mapped from low to high cost.

Values come from historical bar data (MqlRates.spread). The chosen timeframe (M5 default) is sampled across the last N days (60 default). Per-cell statistics can be median, average, 90th percentile, or maximum. Coloring is relative to the symbol-wide median, with configurable thresholds; cells with fewer than 3 bars display β€œ-”, and the current hour is marked.

Time display can switch between server time, UTC, and major market centers with DST handled per bar. Optional CSV expo...

πŸ‘‰ Read | Freelance | @mql5dev
❀8πŸ‘8🀩2