MQL5 Algo Trading
577K subscribers
4.55K photos
7 videos
4.56K 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
Single-neuron models still hit hard limits: some simple-looking patterns (like XOR) cannot be learned without changing the architecture. The article reframes a neuron as linear regression and focuses on why scaling inputs and training loops quickly raises runtime and resource use, especially when code must be rewritten for every new parameter.

It then derives gradient descent from the least-squares error, showing how separate partial updates handle weight and bias. A MetaTrader 5 implementation trains a 1-in/1-out neuron with both linear regression and gradient descent and compares results: regression converges faster, while gradient descent can yield a slightly better weight estimate, with error behavior differing by method.

Practical takeaway for algo trading code: optimization is workload-dependent; choose the training approach based on data shape and performa...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀7πŸ‘5πŸ”₯3🀩3
A GPL-3.0 MT4 port of the β€œChandelier Exit” indicator, kept line-by-line with the original logic and default inputs (ATR Period 22, Multiplier 3.0, extremums from Close enabled). ATR is computed as multiplier Γ— ATR(length) using Wilder RMA seeded by an SMA.

Long stop is highest(close/high, length) minus ATR and only ratchets upward while the prior close remains above the prior stop. Short stop is lowest(close/low, length) plus ATR and only ratchets downward while the prior close remains below the prior stop. Direction flips to long when price closes above the previous short stop, and to short when it closes below the previous long stop; otherwise state is preserved.

MT4 additions include a signal statistics panel with spread/commission-aware figures, optional session filter with shading and end-of-session close, tooltipped trade marks, alerts, and EA...

πŸ‘‰ Read | Calendar | @mql5dev
❀8πŸ‘7πŸ”₯7
A Trade Replay Tool for MetaTrader 5 is outlined as an MQL5 indicator that combines candle-by-candle playback with automatic reconstruction of historical trades.

Key additions over a basic bar replay include adjustable playback speed, anchor-based range selection (single or dual anchor), and trade synchronization. Historical deals within the selected interval are retrieved and converted into replay records preserving entry/exit time, direction, price, volume, SL, and TP.

The workflow covers initialization (buffers, UI, timer), event-driven control via OnChartEvent(), interactive anchor movement, deal extraction from account history, progressive candle reveal, and paper-position lifecycle management. Playback uses UI controls and hotkeys (Ctrl +/- for speed, Shift+E for dual-anchor mode), then restores the chart state when replay is disabled.

πŸ‘‰ Read | Docs | @mql5dev
❀10πŸ”₯5🀩3πŸ‘2
An MT4 line-by-line port of the TradingView β€œRange Filter Buy and Sell 5min” (open-source). Core logic matches the original: Smoothed range = EMA(EMA(|close βˆ’ close[1]|, period), 2Γ—periodβˆ’1) Γ— multiplier, with EMA seeding via SMA consistent with ta.ema.

The range filter remains fixed until price exceeds it by more than the smoothed range, then steps to maintain that distance. Direction counters drive long/short conditions, with Buy/Sell printed once per side change using the original CondIni behavior. Target bands are filter Β± range, with original-style bar coloring.

MT4 additions include a signal statistics panel (trades, win rate, net after spread/commission, profit factor, losing streak, drawdown, cost per trade), optional session filter with shading and end-of-session close, tooltipped trade marks, alerts, and iCustom buffers (5 Buy, 6 Sell, 11 f...

πŸ‘‰ Read | VPS | @mql5dev
❀12πŸ‘5πŸ”₯3🀩2
MetaTrader 5 indicators fall into two groups: built-ins callable directly from MQL5, and custom indicators used to encode a specific market rule set.

A common requirement is bundling multiple moving averages into one indicator so they can be added and removed as a unit, without templates.

A naive implementation scales poorly: repeated input blocks, per-MA handle/buffer declarations, duplicated init/release code, and manual changes to plot/buffer counts that risk chart glitches.

Refactoring focuses on compiler-assisted structure: consolidate repeated calls, move fixed MA parameters into const structure instances, and use const arrays of structs. In MQL5, const applies to the declared instance, not the struct type, and struct initializer order must match member order to avoid silent misconfiguration.

πŸ‘‰ Read | Quotes | @mql5dev
❀9πŸ‘7πŸ”₯5🀩1
A line-by-line MT4 port of QuantNomad’s β€œUT Bot Alerts” (Pine v4, 2020), preserving the original behavior from HPotter and Yo_adriiiiaan. ATR matches Pine’s atr(c): Wilder RMA seeded with an SMA, without using the built-in iATR.

Trailing stop follows the original recursive update: it ratchets upward while price remains above the stop, ratchets downward while below, and resets to price Β± Key Value Γ— ATR on a cross. Buy triggers when the source crosses above the stop; Sell triggers on the inverse. Bar coloring stays consistent: green above, red below. Optional Heikin Ashi source uses HA close = (O+H+L+C)/4. Defaults: Key Value 1, ATR Period 10, HA off.

MT4 additions include a plotted trailing-stop line, an on-chart signal statistics panel, trade markers for counted trades, and alerts on new signals. Trades execute on the bar after a signal, reverse on ...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘15❀8πŸ”₯2🀩2
Fixed-weight neural nets often look solid in backtests but fade in live trading once regimes shift. The article proposes tracking degradation with concrete metrics (Hit Rate, Network Health, long/short bias, 10-bar precision) so performance loss is detected early, not blamed on tester noise.

Instead of periodic retraining, it uses continuous online adaptation: a 100x100 toroidal cellular automaton where each of 10,000 β€œweights” is an agent updated every bar from 50 normalized features plus neighbor influence and evolution rules. Losing cells switch strategies or get reinitialized, while profitable cells gain voting authority.

A separate 10-bar binary predictor maintains a confusion matrix and cross-checks direction before a lightweight grid EA translates confidence into step sizing, reversals, and exits. The key gain is observable, real-time adapt...

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘12❀9πŸ”₯3🀩3
AlgoFX is a trend-following indicator for MetaTrader 5 focused on identifying pullback zones within an established trend. It was built with XAUUSD in mind, but can be applied to any symbol and timeframe. It does not output entries, stops, or targets; it only marks areas of interest and leaves execution to the user.

Trend state is derived from EMA 50 and EMA 200. Uptrend requires EMA 50 above EMA 200 with EMA 200 rising; downtrend requires the opposite with EMA 200 falling. Otherwise the panel reports no clear trend. Zones are ATR-depth pullbacks around EMA 50 with candle-close confirmation, optionally filtered by RSI and spaced via a cooldown.

Zones are calculated on closed candles only, so historical marks match live behavior. An on-chart risk panel shows trend, balance or equity, risk per trade, ATR-based lot sizing with tick value and broker const...

πŸ‘‰ Read | AppStore | @mql5dev
❀8πŸ‘5πŸ”₯4🀩3⚑2
Session indicators that require broker server time tend to break on DST changes and when switching brokers. This session tool defines Asia, London, and New York in their local market times, then converts to broker server time automatically, including the mismatched UK vs US DST transition weeks. An optional overlap marks when London and New York are both open.

Sessions are drawn as high/low boxes or full-height shading, with the overlap as a dashed outline. A top-right panel reports the current state (β€œNOW”), highlights active sessions in green, and shows countdowns to the next open or close. Box hover reveals exact server-time start and end.

Configuration includes server time mode (auto, NY-close model, or manual UTC offset), display controls (history, styles, labels, colors, max timeframe), and per-session toggles, times, and colors. Strategy Teste...

πŸ‘‰ Read | Forum | @mql5dev
❀8πŸ‘3πŸ”₯3🀩3
Pending Panel is a chart-based execution EA for MT5 focused on fast placement of pending orders: Buy Limit, Sell Limit, Buy Stop, and Sell Stop. Order volume and entry distance are adjusted from on-chart controls, avoiding parameter edits and recompiles. Optional SL/TP can be attached at placement.

The EA supports OCO pairing, cancelling the opposing order when one triggers, plus bulk removal of all pending orders created by the tool. A live on-panel list shows current pending orders with type, volume, price, and SL/TP. Implementation is dependency-free, using only the standard library.

Broker constraints are handled via automatic detection of STOPS_LEVEL and filling mode, but behaviour should be validated on a demo due to broker-specific FREEZE_LEVEL rules and execution differences. The tool does not generate signals and manages only orders with its own m...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀6πŸ‘5🀩4πŸ”₯3
Garch.mqh implements maximum-likelihood estimation for GARCH-family volatility models on return series and produces multi-step variance forecasts. Output includes parameter estimates with classic and Bollerslev-Wooldridge robust standard errors, log-likelihood with AIC/BIC, per-period conditional variance, persistence, and shock half-life. No DLL is required; covariances use the MQL5 matrix type.

Supported specifications cover zero or constant mean, and variance models GARCH(1,1), GJR-GARCH(1,1,1), and EGARCH(1,1,1). Innovations can be Normal, standardized Student t, or GED with estimated shape. Initialization uses an EW variance from the first 75 residuals and variance bounds aligned to EWMA, matching common reference behavior for identical parameters.

Optimization is staged: unconstrained BFGS on a free parametrization, bounded Nelder-Mead, then bound...

πŸ‘‰ Read | Freelance | @mql5dev
❀13🀩7πŸ”₯6πŸ‘4πŸ‘¨β€πŸ’»1
A chart indicator quantifies two recurring outcomes for each new bar: whether price trades above the prior high and whether it trades below the prior low. It scans the visible history, groups cases by the prior candle direction (bullish vs bearish), and computes how far beyond the previous high/low price typically extends.

On the active bar it renders up to five levels above and five below, starting at the prior high/low. Each level shows a 0–100% track plus a filled segment and printed percentage, based on the share of comparable historical bars that reached that distance. Level spacing defaults to 0.5x ATR(14) from closed bars, or can be set as percent-of-price; levels remain stable while the current candle forms.

Probabilities are recomputed on every bar so older, unreached levels decay naturally. A panel reports favored-side hit rate over all bar...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘6πŸ”₯6🀩6❀4⚑2
VpsToolkit (VpsToolkit.mqh) is a lightweight include for EAs running 24/7 on an MQL5 VPS or a local PC. It adds no trading logic and is used by calling only the needed functions. A demo EA shows integration and focuses on production issues: concurrent runs on VPS and PC, duplicate orders after timeouts, restarts resetting state, trades closed while the EA was offline, and VPS-only logs.

Core functions include run-location gating (VT_ActiveHere), trading permission diagnostics (VT_CanTrade), and safer market execution (VT_OpenMarket returning OK/FAIL/UNKNOWN and verifying results after timeouts). It also provides restart-safe initialization (VT_Init/VT_Ready), history-based daily stats (VT_TradesToday), detection of positions closed while offline (VT_ClosedWhileOff), restart counters and announcement throttling, and append-only UTF-8 CSV logging with daily counter...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘10❀7πŸ”₯7🀩5
An ICT-style dealing range indicator calculates the current leg from confirmed swing points and plots premium/discount structure with non-repainting logic. The range starts at the older of the last confirmed swing high/low, then expands as new highs or lows print until a new confirmed swing resets it. Swings require N candles on both sides (default 10), confirmed only after right-side closes.

Rendered levels include equilibrium (50%), premium and discount zones, plus OTE as the 62%–79% band with a 70.5% line. Direction is classified as up leg when the low precedes the high, otherwise down leg, placing OTE in the expected zone per ICT conventions. Optional retracements and standard deviation projections are supported.

IPDA reference ranges (20/40/60 completed trading days) are plotted with merged labels for equal levels. Alerts fire on candle close fo...

πŸ‘‰ Read | Quotes | @mql5dev
❀7🀩5πŸ‘3πŸ”₯2
CMECalendar.mqh provides rule-based session halts for CME Globex equity index futures in New York time, aimed at EAs that must exit before the daily stop or avoid trading on short sessions. It covers regular 17:00 halts, full closures (New Year’s Day, Good Friday, Christmas), 13:00 early halts on major US holidays, 13:15 halts on 3 July, the day after Thanksgiving, and 24 December, plus the 09:15 Good Friday halt when it coincides with the US jobs report. Holiday observance shifts are handled, and Good Friday is computed via the Gregorian Easter algorithm.

Unpredictable one-offs are handled through a small CME_SPECIAL_DAYS string. All functions use New York dates/times; server time must be converted using the broker offset.

CMECalendarScan.mq5 validates the rules against M1 history by finding the last real trade per day, accounting for stray weekend/after-h...

πŸ‘‰ Read | Forum | @mql5dev
❀7πŸ‘5🀩4πŸ”₯3
An ICT Power of Three workflow relies on tracking higher-timeframe candle structure while executing on lower timeframes. This indicator renders one or two higher-timeframe candles at their real price levels beside the active chart, allowing an H4 or D1 candle to be monitored while trading M5 or M15.

It shows the last completed candles plus the live candle, with auto timeframe pairing (for example M5 -> H1 + H4, M15/M30 -> H4 + D1, H1 -> D1 + W1). Each set includes timeframe, time remaining to close, and whether price is above or below the open. Live candles project dashed open/high/low references back to where they formed. Labels avoid overlap, and hover displays OHLC. Optional prior candle high/low can be plotted.

Candles are synthesized from current-chart bars (first open, last close, max high, min low) with no external timeframe data loading, matc...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘6❀3🀩3πŸ”₯2πŸŽ‰2
RegimeHMM.mqh implements market regime detection using a Hidden Markov Model. Returns or custom feature vectors are modeled as emissions from a small set of Gaussian states, with state transitions governed by a Markov chain. The implementation supports multiple features, full covariance, and runs without DLL dependencies.

Model fitting uses Baum-Welch with scaled forward-backward to avoid underflow on long series. Initialization is based on k-means++ with multiple restarts, keeping the best likelihood. Covariance stability is enforced with a small variance floor, and states are sorted by the variance of the first feature so regime 0 is consistently the lowest-volatility state.

Outputs include filtered probabilities per bar for non-look-ahead use, smoothed posteriors for charting, the Viterbi path, expected state durations, transition-matrix forecasts, and l...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘8πŸ”₯5🀩4❀3
Margin Call Radar is a read-only risk panel for MetaTrader 5 focused on margin call and stop out proximity, plus projected margin level under adverse moves. It does not open, modify, or close orders, so it can run alongside EAs or manual trading.

It reports margin level (%) with status colors, and distance to margin call/stop out in account currency, % of equity, and points for the netted book. Hedge handling is net exposure per symbol; fully hedged books return points as n/a. Brokers with stop out in money or percent are supported.

Shock scenarios include adverse price moves of 1% and 3% across positions and a 5% equity drop, each returning the resulting margin level. A positions table shows symbol, side, volume, and P/L including swap.

Calculations use margin level = equity/margin*100, refreshed by timer. A separate core library ships with a test ...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘7πŸ”₯4❀3🀩3
Kalman.mqh provides a Kalman filter and smoother for linear Gaussian state space models with one observation per bar. It uses exact diffuse initialization (Durbin–Koopman), accepts missing values, and avoids ad-hoc β€œstarting variance” tuning. No DLL is required.

Three models can be fitted by maximum likelihood: local level, local linear trend, and time-varying regression (e.g., drifting hedge ratio). Custom models can be set via SetModel(Z,T,Q,H), then run with Filter(y) and Smooth(). SetDynamicRegression() runs with user-chosen variances.

Outputs include filtered and smoothed states with standard deviations, one-step forecast errors and variances, forecasts of y, exact diffuse log-likelihood, AIC/BIC, and diffuse-bar count. Variances are optimized on log scale using a multi-start grid plus BFGS and Nelder–Mead. Numerical stability is handled via rank-...

πŸ‘‰ Read | VPS | @mql5dev
❀7πŸ‘4πŸ”₯4🀩1🀣1
News Lines 1.30 for MetaTrader 5 adds an on-chart economic calendar with a movable event panel. Scheduled releases are rendered as vertical lines at exact timestamps, color-coded by impact, with tooltips showing time, currency, event name, forecast, previous, and actual values. Events sharing the same minute are consolidated into a single line and tooltip.

The panel lists upcoming and recent releases with countdowns, supports drag, resize, collapse, and scrolling, and includes quick filters for labels, impact level, instrument groups, source selection, and font size. Clicking an event focuses the chart to that event across occurrences, with a Reset control to restore defaults.

Data can be sourced from the terminal’s built-in calendar or a weekly JSON feed via WebRequest. Refresh is periodic, settings persist across restarts, no DLL imports are used, and no...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ”₯3❀2πŸ‘1πŸ‘1🀣1
Cointegration.mqh provides cointegration diagnostics for multi-series price data, targeting pairs and spread trading workflows. It includes ADF unit root testing, Engle-Granger cointegration for 2–6 series, and Johansen trace and max-eigen tests, with p-values and critical values. It also outputs the spread, half-life of mean reversion, and spread z-score. Operation is self-contained with no DLL dependency.

ADF supports no constant, constant, linear, or quadratic trend, with fixed lags or selection via AIC/BIC/last-lag t-stat and a statsmodels-style default cap. Lag search reuses a single QR factorization per run. Engle-Granger runs OLS on the first series against the rest plus trend, then ADF on residuals with series-count-specific cointegration tables. Johansen supports multiple lagged differences and deterministic options; eigenproblems are solved symmetr...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘1