Watch how to download trading robots for free
Find us on Telegram!
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 monitors the Stochastic oscillator to automatically close positions based on user-selected conditions: crossovers above overbought or below oversold, entry into overbought/oversold zones, or exit from those zones. Positions are filtered for closure by profit state (loss, profit, or both). An optional Test Mode enables basic entry signals when the %D line crosses configurable offset levels around the midline (50).

BBandsPsar is a custom hybrid indicator that fuses Bollinger Bands’ volatility framework with the Parabolic SAR’s trend-following logic. By integrating these two methodologies, it effectively reconciles market volatility with emerging trend dynamics within a single, cohesive tool.

A pure-MQL5 script that measures how robust a strategy's edge is to execution costs. It reads a Date,Profit,Volume CSV of closing deals and models each deal's cost as a fixed part plus a per-lot part. It prints the breakeven cost per deal, the cushion (the multiple of an assumed realistic cost at which the net profit reaches zero), the net profit and profit factor re-priced at the assumed cost, the share of winners the cost turns into losers, and a composite A+ to F cost-robustness score with recommendations. If no file is present it generates a reproducible sample and analyzes it, so the output is visible on the first run. No external libraries, no Python, no AI.

The KCI Embedded Sniper is an algorithmic trading solution designed for high-precision reversal entries. Unlike conventional Expert Advisors that rely on external indicator dependencies (which often suffer from thread desynchronization and latency), this EA features a fully embedded Kinetic Compression Index (KCI) engine. By transplanting the entire mathematical framework of the KCI—calculating Velocity Quotients, Kinetic Displacement, Energy Dispersion, and Phase Velocity—directly into the EA’s core logic, we have eliminated "asynchronous lag." The result is a lightning-fast sniper engine that validates market exhaustion (Singularity) and momentum extremes (Williams %R) with micro-second precision, operating solely on completed bars to ensure zero-repaint performance.

The Kinetic Compression Index (KCI) is a custom oscillator designed to detect market exhaustion and localized compression events. By calculating its kinematic metrics internally rather than relying on external standard indicator handles, the KCI reduces overhead and simplifies buffer management for Expert Advisor (EA) integration. This article details the mathematical foundation, system architecture, buffer mapping, and practical integration guides for developers looking to implement this tool in MetaTrader 5.

SMC/ICT market-structure indicator for MT5: swing highs/lows, BOS (continuation) and CHoCH (reversal) confirmed on close, Order Blocks, Fair Value Gaps, and QML (Quasimodo) levels. Every feature is toggle-able, with adjustable swing sensitivity and colors. Works on any symbol and timeframe.

Exports your closed positions for a configurable period to a CSV file for journal analysis in Excel or Google Sheets: entry and exit time and price (volume-weighted over partial fills), volume, result in points, commission, swap, net profit and trade duration.

Calculates the correct lot size for a planned trade from your risk (percent of equity or a fixed money amount) and stop-loss distance (points or a price level). Respects the symbol's contract specification - tick size and value, volume min/max/step - and estimates the required margin.

On-chart panel with the live spread of the chart symbol - current, minimum, average and maximum since attach - color-coded against your warning and danger thresholds, plus an optional alert when the spread stays at the danger level for N consecutive seconds (news and rollover spikes).

A read-only on-chart panel that tracks your account against a daily-loss limit and a max-drawdown limit, with color-coded OK / WARNING / DANGER status. Monitoring only - it does not place, modify or close any orders.

MQTTFive — a fully-featured implementation of the MQTT 5.0 client for MQL5. Features: • MQTT v5.0 — all packet types, properties, QoS 0/1/2 • TCP + TLS via the native MQL5 Socket API • Will messages with properties (will_delay_interval, payload_format, message_expiry) • Topic aliases for outgoing PUBLISH messages • Flow Control (Receive Maximum) • Subscription Options (no_local, retain_as_published, retain_handling) • Binary and UTF-8 payloads • Automatic retry for QoS 1/2 • Zero DLL dependencies — pure MQL5 Tested with Mosquitto 5.0 (15 tests, all PASS). Documentation: https://github.com/chekh/MQTTFive Licence: MIT

An oscillator that shows 2 line studies: 1 for consecutive up bars, and 1 for consecutive down bars.

An educational MT5 panel that maps the live price vertically inside four developing candles and summarizes location alignment, dispersion, candle direction and time remaining.

Multi-timeframe Support & Resistance zone scanner with strength rating and instant alerts — M15, H1, H4, D1.

Account-level daily loss guardian: when your daily loss reaches a configurable trigger, it closes all positions and pending orders and keeps the account flat until the next daily reset. Limits in percent or money, configurable reset time (server time), draggable visual panel with live gauge, and manual CLOSE ALL / LOCK buttons with click-to-confirm. Works on any broker, symbol, account size and currency — hedging and netting, no DLLs.

A small, dependency-light library that brings a Rust-style Result type to MQL5. Functions return a single value-or-error object instead of relying on the global GetLastError() state, so failures are explicit and impossible to ignore. Includes ResultValue (value types) and Result (pointer-held objects), an Error struct, early-return macros (TRY, RETURN_ON_ERROR, ...) and optional Then/Match/MapError callbacks.

Live pip value, risk-based lot sizing, custom volume risk analysis & open position P/L — all in one panel.

An educational MT5 indicator that builds support and resistance as price zones from confirmed pivots. Nearby reactions are merged using ATR-based distance, then ranked by repeated tests, rejection strength and recency. Only the strongest zones are displayed to keep the chart readable.

Spread calculator is created to display the current spread on any currency pair on the chart.

On-Chart Candle Countdown Clock is a simple indicator created to display the countdown timing of the last candle on any time frame.

A lightweight educational MetaTrader 5 indicator that maps Premium, Equilibrium and Discount areas from a selected market range.

Open-source MT5 script that records XAUUSD/GOLD symbol settings, spread, tick value, contract size, volume step, stop/freeze levels, swap, and account context to the log and optional CSV.

A native MQL5 script that measures how concentrated a strategy's profit is — whether the edge is broad or rests on a few lucky trades. It reads a per-trade CSV (Date,Profit) and reports the share of net profit from the largest trades, the Gini coefficient of the winners, a concentration profile, a survival test that removes the best few trades and recomputes net profit and profit factor, and the largest single day versus a configurable consistency limit, combined into a concentration-and-consistency score (A+ to F) with recommendations. If no file is found it generates a sample set, so it runs out of the box. No external libraries, no Python, no AI. The helper ExportTrades.mq5 writes the file from your trade history.

A native MQL5 script that analyzes the structure of an account's drawdowns, not just the single "maximum drawdown" figure. It reads a daily equity curve (Date,DailyPnL CSV), rebuilds the underwater curve, and splits it into individual drawdown episodes with their depth, duration and recovery time. It then reports the Ulcer Index, Pain Index, Recovery Factor and time spent underwater, and combines them into a single resilience score (A+ to F) with recommendations, printed in the Experts tab. No external libraries; if no file is found it generates a sample curve so it runs out of the box.

A small educational MetaTrader 5 indicator that marks simple three-candle bullish and bearish Fair Value Gaps on the chart.

A small educational MetaTrader 5 indicator that marks confirmed swing highs and lows and labels market structure as HH, HL, LH and LL.

Daily Range Tracker — Live Today's Range vs Average Daily Range. Daily Range Tracker shows you, at a glance, how much of the symbol's typical daily movement has already happened today — helping you judge whether the day still has room to run or is already exhausted.

Swap Meter displays the live SELL and BUY swap rates for your current chart symbol in a clean, color-coded panel — and instantly alerts you the moment your broker changes either rate.

Spread Meter — Live Single-Symbol Spread Tracker with Max/Min Record Spread Meter by Fox Wave is a sleek, single-symbol dashboard that displays the live spread of your current chart symbol in real time, while permanently recording the widest and tightest spread ever seen — with exact timestamps.

Open source MT5 spread logger with average, p50, p90, p95, p99, maximum spread, alerts and CSV export.

Open-source Expert Advisor for testing day-of-week reversal and continuation effects. Built for systematic research, strategy validation, and further development by the MQL5 community.

A simple Expert Advisor based on the crossover of two EMAs (fast and slow), with configurable Stop Loss, Take Profit, lot size, and Magic Number.

Asian Range Breakout day-trading EA. Multi-symbol, M15/M30/H1. Places pending stop orders during the London session outside the pre-London Asian range, using PSAR + MACD + Stochastic signals, with automatic London/NY DST handling, structural stops, trailing and break-even.

The indicator identifies areas of imbalance (Fair Value Gaps) on the chart and signals them with an arrow when the price returns to them. It is suitable for Gold, Forex and any liquid instruments on timeframes ranging from M5 to H4.

Session Boxes is a custom indicator for MetaTrader 5 that draws color-coded rectangular boxes on the chart representing the high-low range of the Asia, London, and New York trading sessions. The indicator uses H1 data internally and supports configurable session hours in GMT along with a broker server offset parameter

A long-term momentum and trend oscillator based on dual TRIX and LWMA filtering.

This Expert Advisor combines an ADX-based trend strength filter with an EMA pullback entry technique, using ATR for dynamic stop loss and take profit sizing. It is designed for trading a single symbol with one position open at a time.

Expert Advisor for testing the Inside Bar continuation hypothesis. The EA places pending orders in the direction of the Main Bar after a valid Inside Bar pattern is detected, with optional ATR and pattern quality filters.

A state engine to provide geometric signal validation for indicator signals

Instead of having to analyze each pair individually, you can see at a glance what are the most promising pairs according to your own criteria.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200