Watch how to download trading robots for free
Find us on Twitter!
Join our fan page
Access the CodeBase from your MetaTrader 5 terminal
Couldn't find the right code? Order it in the Freelance section
How to Write an Expert Advisor or an Indicator

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

This Expert Advisor integrates a TradingView chart directly within the MT5 window, replacing the native chart. It uses a web view (WebView2) to render HTML with the official TradingView widget, allowing you to change symbol, seasonality and theme (dark/light) without leaving MT5. Includes a date-based licensing system that blocks the EA if it is outside the authorised period.

A quantitative stochastic probability engine that utilizes Markov Chain transition matrices to mathematically forecast the percentage chance of bullish or bearish continuation on the next algorithmic execution cycle.

Dynamic Fair Value Gap (FVG) is an MQL5 indicator for MetaTrader 5 that automatically detects market price imbalances. This indicator is perfectly suited for traders utilizing the Smart Money Concepts (SMC) strategy.

IMR is a multi-layered quantitative reversal finder designed for discretionary price-action traders who refuse to trade blind. It helps traders understand what's the current market regime. Whether its an accumulation, distribution or continuation.

Displays the current bid-ask spread in points and pips directly on the chart, with live tracking of session minimum, maximum and average spread since the indicator was attached. Color changes to alert when spread exceeds a user-defined threshold.

Educational MT5 chart utility that monitors XAUUSD spread on the chart and alerts when spread rises above user-defined warning or danger levels.

Educational MT5 chart panel for XAUUSD showing live spread, ATR volatility, EMA trend bias, RSI condition, daily range and active trading session.

Script to set Stop Loss on every open position based on a target loss in the account's currency (e.g. $50 per position). Works on any deposit currency and any forex symbol. Validates broker stops/freeze levels. Currency conversion handled automatically.

Diagnostic script that compares SYMBOL_TRADE_TICK_VALUE, SYMBOL_TRADE_TICK_VALUE_LOSS and SYMBOL_TRADE_TICK_VALUE_PROFIT for every symbol in Market Watch. Classifies each symbol into one of four categories (ALL_EQUAL, TV_MATCHES_PROFIT, TV_MATCHES_LOSS, ALL_DIFFER) and provides an aggregated summary plus interpretation tip. Useful for verifying which tick-value property to rely on when implementing risk-based lot sizing in EAs. Exports full per-symbol report to CSV in MQL5/Files.

Heiken ashi with all buffers set as series

Triple-barrier labeling pipelines frequently use an arbitrary constant (0.5–1.0%) or a legacy spread assumption as the min_ret threshold. A threshold set below the actual round-trip transaction cost causes the pipeline to label cost-driven noise as tradeable signal. The labeled dataset then systematically overstates edge, and any model trained on those labels overfits to an artifact of the labeling scheme rather than to genuine market structure. TransactionCostCollector.mq5 is a standalone script that resolves the data-collection step of this problem.

Allows to monitor spread and swaps!

A quantitative volume density engine utilizing weighted Harmonic Mean mathematics to eliminate arithmetic outliers and map the true institutional liquidity center of gravity.

Close Profit Positions

A library to retrieve proximity signals for channel based indicators

MACD Multi-color Histogram

This custom indicator displays the ADX Wilder, +DI, and -DI lines together with Bollinger Bands calculated on the ADX main line in a separate window. It helps traders evaluate both trend strength and the volatility range of ADX values. The middle, upper, and lower bands can be used to identify ADX expansion, contraction, and potential strength breakouts. The indicator is useful for confirming trending conditions, spotting increasing momentum, and detecting when ADX moves outside its normal range. Input parameters allow adjustment of the ADX period, Bollinger Bands period, deviation, and applied price settings.

MQL5 implementation of the fixed-width fractional differencing (FFD) method from López de Prado's Advances in Financial Machine Learning (Chapter 5). Transforms a non-stationary price series into a stationary one while preserving maximum historical memory; output cross-validates against the Python afml library to within 1e-12.

A quantitative physics engine that applies differential calculus to price action, extracting true Market Velocity (1st Derivative) and Market Acceleration (2nd Derivative) to predict trend exhaustion before it happens.

A candlestick chart which colors OHLC candles based on directional price momentum and news impact

Automatically detect Inside Bar patterns, draw projection rectangles, and receive real‑time alerts – all in one powerful indicator. Swing And Full Margin trader

Institutional MACD is an advanced indicator designed for traders looking to trade in tune with smart money. Unlike the standard MACD, which processes each tick or candle close without distinction, this indicator reconstructs the price structure using a dynamic volume filter before calculating its moving averages.

An aerospace-grade state estimation algorithm that dynamically filters out market noise and manipulation wicks to reveal the true underlying execution price with zero static phase-lag.

Symbol Summary is a service for MT5 that opens a separate viewer window and shows a detailed report on a trading symbol. It supports Russian and English language, window resizing, scrolling, automatic report update when changing symbol or timeframe of the chart without restarting the service.

A quantitative Information Theory engine that calculates the Shannon Entropy of price distribution to mathematically measure market randomness and algorithmic predictability.

The Weekend Gap Statistics & Distribution Analyzer is a purely analytical MQL5 indicator designed to evaluate the historical behavior of weekend price gaps. It scans chart data to calculate gap closure rates and measures the adverse excursion (drawdown) experienced before a gap successfully closes. By providing statistical distributions—including the 70th and 90th percentiles of adverse heat—this tool enables traders to make data-driven decisions. It moves beyond simple averages, allowing traders to properly assess risk, filter out low-probability instruments, and optimize stop-loss placement when fading weekend gaps.

Chart Water Mark Transform your MetaTrader 5 charts to look as elegant and professional as TradingView.

Swap Monitor Panel is a lightweight, fully customizable indicator that overlays a live swap rate dashboard directly on your MT5 chart. It scans every symbol in your MarketWatch window and presents long swap, short swap, estimated daily cost, and weekly cost side by side — all in one clean, readable panel.

Interactive Correlation Heatmap using high-performance MQL5 matrix functions. > Features a draggable, minimizable dashboard with instant multi-timeframe switching and a vivid 5-band color scale for real-time currency relationship analysis.

Prime Quantum AI is an MT5 Expert Advisor combining a classical pre-filter (ADX + Alligator) with AI vision-based chart confirmation from major AI providers (Anthropic Claude, OpenAI GPT, Google Gemini, DeepSeek, xAI Grok). When the pre-filter detects a trend setup, the EA captures three adaptive- timeframe chart screenshots and sends them to the configured AI provider, which returns direction, confidence, stop-loss and take-profit. A trade is opened only when the AI confirms the pre-filter signal with sufficient confidence. Features: dual Standard Broker / Prop Firm risk modes, configurable lot sizing, optional martingale, multiple SL/TP modes, trailing stop, partial close, news/time/day/spread filters, draggable on-chart info panel, and fully exposed indicator parameters. Requires MetaTrader 5, WebRequest enabled for your provider's URL, and a valid API key. Provider auto-detected from key format.

A digital signal processing (DSP) engine that applies the Discrete Fourier Transform (DFT) to market data, isolating the dominant cyclical frequency to project turning points and eliminate phase-lag.

The Supertrend indicator plots an ATR-based dynamic trend line on the MetaTrader 5 chart, switching between a green uptrend and red downtrend line with optional buy/sell arrow signals at every trend reversal.

ASQ Order Executor — Institutional order execution wrapper for MQL5 EAs ASQ Order Executor provides institutional-grade order execution with automatic retry logic, slippage monitoring, partial fill handling, requote management, and comprehensive execution statistics. Drop it into any EA for production-ready trade execution.

Utility script that exports your MetaTrader 5 trading history to a CSV file. It automatically calculates Maximum Favorable Excursion (MFE), Maximum Adverse Excursion (MAE), and Forward Returns (Time-Based Excursions) in whole points for deep quantitative analysis in Excel. It will allow you to understand whether you close your trades too early and can help optimize overall trading execution.

A chart-cleanup + quick-trading layer for MT5

Function for lot calculation from deposit percentage

Keltner Channel strategy for XAUUSD with optional Progressive Recovery System and basket level risk control. Source code for educational purposes.

Self-Aware Trend System (SATS) is an advanced MQL5 indicator that combines an adaptive SuperTrend engine with a Trend Quality Index (TQI) dashboard, offering dynamic signal detection, risk management levels, and self-learning calibration for smarter, more reliable trade entries.

Daily Risk Monitor Lite is a lightweight MetaTrader 5 indicator that displays daily realized P/L, floating P/L, daily total, current drawdown, and color-based risk status directly on the chart. It is a read-only monitoring tool and does not close trades or block trading.

The script shows the usage of L1 Trend Filter methods in MQL5 for float and double vectors on random walk simulated data.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199