MQL4 and MQL5 Source Code Library

icon

You don't know where to start learning the MQL5 or MQL4 programming language? Various programs for your MetaTrader terminal are available here. Download and study published code examples, develop your own indicators and Expert Advisors. Publish your applications in the largest library of MQL5 and MQL4 codes, and they will be available in every MetaTrader terminal and MetaEditor.

Your code examples in MQL4 and MQL5 will be distributed worldwide, and thousands of traders will know about you!

Submit your code

Fits five bivariate copulas on ranks, with Kendall's tau, tail dependence, the probability of joint extreme days, AIC and the conditional probabilities of pairs trading.

Online detection of changes in the mean or volatility (Adams-MacKay): probability of a change in the last k bars, current segment length, forecast, and an indicator.

Exact maximum likelihood of an Ornstein-Uhlenbeck spread and Bertram's optimal entry and exit levels for a given cost, with the expected length of a trade cycle.

For every closed position the script measures how far the price went against it (MAE) and in its favour (MFE), and shows what that says about your stops and exits. Table, summary on the chart and a CSV file. Read-only, it never trades.

A table on the chart: the typical spread of the symbol for every hour and weekday, read from the history of your broker. Green is cheap, red is expensive. Hours in server time, UTC or a city with the right summer time. Read-only.

EURUSD EA that trades both directions: when the Awesome Oscillator turns against a weighted moving average filter, it places a stop order at the daily low or high of three days ago, with an ATR stop. Self-contained, no custom indicators. Backtest on EURUSD H1, October 2021 to October 2026: +209% on a 1,000 USD deposit with a fixed 20 USD risk per trade, 15.55% maximum equity drawdown.

A lightweight tab bar for chart panels, drawn with the standard CCanvas class. One include file, several independent instances per chart, click selection, resizing and safe cleanup. Includes a demo Expert Advisor.

Candle countdown timer for Gold (XAUUSD), EURUSD and any symbol: time left on the current candle next to price or in a corner, spread, color change and alert before the close. Server time, no ticks needed. Open source code.

Draws Asia, London and New York session boxes on the chart with each session's high and low.

Closes all open positions and optionally deletes pending orders with one click. Filter by symbol and magic number.

Parkinson, Garman-Klass, Rogers-Satchell and Yang-Zhang estimators, daily realized and bipower variance from intraday bars, and HAR volatility forecasts.

Five tests to tell a random walk from a mean-reverting series: KPSS, Phillips-Perron, DF-GLS, Zivot-Andrews with the break date, and the variance ratio.

Drag the stop-loss line and read the lot size that risks exactly your money or percent. The CRiskSizer class does the same in an EA: lot rounded down, minimum lot never forced, max lot, volume limit, stop level and margin checked.

CBrokerTime converts server time, UTC, New York, London, Sydney and Tokyo with the real summer time of every year and finds your broker's clock from the history (also in the tester). The indicator draws session lines and a clock panel.

A clean Heikin Ashi indicator that draws on the main chart window. It also adds one horizontal line at the average price, (Open + High + Low + Close) / 4, of the last closed candle of a chosen timeframe. By default this is H1, and the line uses the normal candles, not Heikin Ashi.

Market structure indicator for Gold (XAUUSD), EURUSD and any symbol: swing highs and lows with HH HL LH LL labels, BOS and CHoCH drawn on closed candles, alerts and 4 buffers for EAs. Open source code.

Tick Scalper Helper is a manual trading utility for traders who work on very short time frames and want to see every price change.

A Supertrend scalping EA with 14 switchable filters and a self-measuring panel that shows the actual win rate next to the win rate needed to break even after real spread, so you can see whether a setting has an edge or only a high percentage.

Range boxes that are drawn when market trend strength weakens

Detects the broker's GMT offset and its daylight-time rule (fixed, US or European) from the weekly closes in the H1 history, the same way live and in the Strategy Tester, with functions that convert New York times to server time and back.

Partial close expert advisor for MetaTrader 5: closes a percent of the position at TP1, TP2, TP3, TP4 and TP5, moves the stop loss to breakeven and trails it. Works on manual trades and on positions of any EA, on any symbol, Gold (XAUUSD) included. Open source code.

Shows the broker's hidden financing markup and the carry for every symbol, as annual % of notional.

Is the best of many strategies really better than the benchmark? Hansen's SPA test, White's Reality Check, Romano-Wolf StepM and the model confidence set.

Position manager for MT5 that closes the best winner together with the worst loser when their combined result reaches your minimum. Basket take profit and stop loss in money, magic filter, simple panel. Works with grid, martingale and manual trades. Open source code.

Unit root and cointegration tests (ADF, Engle-Granger, Johansen) with MacKinnon p-values, hedge ratio, half-life and z-score of the spread, and a pair scanner.

Kalman filter and smoother with an exact diffuse start, missing values and maximum likelihood: local level, local linear trend and a regression whose hedge ratio drifts.

Gaussian hidden Markov model fitted by Baum-Welch: regime probabilities without look-ahead, most likely path, expected durations and regime forecasts.

Holidays and early halts of the CME equity index futures (S&P 500, Nasdaq-100, Dow, Russell 2000, E-mini and Micro), computed from the US holiday rules for any year, with a script that checks the calendar against your broker's own M1 history.

Include for EAs running 24/7 on an MQL5 VPS or PC: run-where switch, order send with OK/FAIL/UNKNOWN result (no duplicate orders after a timeout), restart-safe counters, positions closed while the EA was off, append-only log and optional Telegram. No trading logic inside.

Fits GARCH(1,1), GJR-GARCH and EGARCH with normal, Student t or GED shocks by maximum likelihood, with robust standard errors and variance forecasts.

Highlights the Asia, London and New York sessions and the London/New York overlap using real local time and daylight saving rules, so the session boxes are correct on any broker.

Read-only watchdog for MT5: alerts on unknown magic numbers, duplicate positions after reconnects, missing SL, stop outs and what happened while it was off. Never trades.

Marks daily and weekend opening gaps on any chart, tracks when each gap is filled, alerts on new gaps, logs one CSV line per gap and exposes the gap to iCustom.

Script that reports what an EA has to cope with here: hedging or netting, trade permissions, filling modes, stop and freeze levels, volume rules, swaps and the positions already open on the symbol. Saves a report file you can attach to a Freelance order.

An indicator to reveal the the time candles breached an extreme price boundary

Detects the ICT model on closed bars (killzone liquidity sweep, MSS with displacement or inverted FVG, retrace entry with SL and TP) and follows every setup to its result with worst-case statistics. It never trades and never repaints; EA-ready buffers.

On-chart panel that turns a risk setting into a lot size and shows what the broker's volume step and minimum lot do to that risk. Display only - it never places, modifies or closes an order.

Probability of Backtest Overfitting (PBO) of an MT5 optimization by combinatorially symmetric cross-validation. Every pass sends its daily results as a frame, and the PBO is computed when the optimization ends.

Block bootstrap of daily results: how deep the drawdown of an account or strategy can get over the next months, with percentiles and a seeded generator for repeatable runs.

Portfolio weights from the returns of symbols or Expert Advisors: inverse volatility, risk parity, hierarchical risk parity, minimum variance, maximum diversification, Ledoit-Wolf covariance.