How to Write and Run a MetaTrader 5 Bot (Expert Advisor)
Last updated: October 2026
A MetaTrader 5 bot — officially an Expert Advisor (EA) — is a small program that watches the market and places trades for you based on rules you define. This beginner guide walks you through writing your first EA in MQL5, testing it safely, drafting one with AI, and keeping it running 24/7.
What is an Expert Advisor?
An EA is code attached to a chart in the desktop MetaTrader 5 terminal. Every time the price changes (a tick), MT5 calls the EA, which can read indicators, open and close positions and manage stops. EAs are written in MQL5, a C++-like language, using the MetaEditor that ships with MT5.
Important: EAs run only on the desktop terminal. The MT5 mobile app can trade manually but cannot run bots.
What you need
- MetaTrader 5 desktop (from your broker or metatrader5.com) — MetaEditor is included.
- A demo account with your broker. Never start on a live account.
- A clear rule set: when to enter, when to exit, how much to risk.
The anatomy of an EA
OnInit()runs once when the EA starts — create indicator handles, check inputs.OnTick()runs on every price change — your trading logic lives here.OnDeinit()runs when the EA is removed — release resources.inputvariables become settings you can change without editing code.
Your first EA: moving-average crossover
In MetaEditor choose File → New → Expert Advisor (template), name it, and replace the code with:
#include <Trade\Trade.mqh>
input int FastMA = 10; // fast average
input int SlowMA = 30; // slow average
input double Lots = 0.01; // lot size
input ulong Magic = 260101; // tags this robot's orders
CTrade trade;
int hFast, hSlow;
int OnInit() {
hFast = iMA(_Symbol, _Period, FastMA, 0, MODE_SMA, PRICE_CLOSE);
hSlow = iMA(_Symbol, _Period, SlowMA, 0, MODE_SMA, PRICE_CLOSE);
if (hFast == INVALID_HANDLE || hSlow == INVALID_HANDLE) return INIT_FAILED;
trade.SetExpertMagicNumber(Magic);
return INIT_SUCCEEDED;
}
void OnDeinit(const int reason) {
IndicatorRelease(hFast);
IndicatorRelease(hSlow);
}
void OnTick() {
static datetime lastBar = 0;
datetime bar = iTime(_Symbol, _Period, 0);
if (bar == lastBar) return; // decide once per new candle, not every tick
lastBar = bar;
double f[2], s[2]; // [0] = two bars ago, [1] = last closed bar
if (CopyBuffer(hFast, 0, 1, 2, f) < 2 || CopyBuffer(hSlow, 0, 1, 2, s) < 2) return;
bool crossUp = f[0] <= s[0] && f[1] > s[1];
bool crossDown = f[0] >= s[0] && f[1] < s[1];
bool hasPos = PositionSelect(_Symbol);
if (crossUp && !hasPos) trade.Buy(Lots, _Symbol);
if (crossDown && hasPos) trade.PositionClose(_Symbol);
}It buys when the fast average crosses above the slow one and closes when it crosses back down. It only decides once per new candle, which avoids duplicate orders, and tags its trades with a magic number so they can be told apart from manual trades or other robots.
Compile it: .mq5 → .ex5
Press F7 (Compile) in MetaEditor. If there are no errors you get an .ex5 file — that's what MT5 runs. Read every warning in the Errors tab; most beginner problems show up here.
Backtest it in the Strategy Tester
- In MT5 open View → Strategy Tester (Ctrl+R).
- Select your EA, symbol, timeframe and a date range of at least a year.
- Use "Every tick based on real ticks" for the most realistic results.
- Check net profit, maximum drawdown and the number of trades — not just profit.
A good backtest is not a promise. Markets change; an EA that looked great on past data can lose money live.
Run it on a chart
- Drag the EA from the Navigator onto a chart.
- In the settings tick Allow Algo Trading and set your inputs.
- Turn on the Algo Trading button in the toolbar. An active icon on the chart means it's running.
- Watch the Experts and Journal tabs for messages and errors.
Writing an EA with AI
AI assistants (ChatGPT, Claude and others) can draft MQL5 code quickly. Give them precise rules:
Write a MetaTrader 5 Expert Advisor in MQL5.
Strategy: buy when the 10-period SMA crosses above the 30-period SMA on the current chart,
close the position when it crosses below. One position at a time.
Requirements: use CTrade, a magic number input, lot size input, decide only on a new bar,
check every trade result and Print the error code, no Sleep(), no DLL imports.
Add short comments.Then treat the result like code from a stranger:
- Compile it and fix every error — AI often mixes MQL4 and MQL5 functions.
- Check lot size and risk logic line by line.
- Make sure every order has stops or a clear exit and a unique magic number.
- Backtest, then demo-test for weeks before going live.
Running it 24/7
An EA only works while the terminal is open and connected. If your PC sleeps or loses internet, the bot stops. Options: keep a PC on, rent a Windows VPS, or use a managed cloud. On etrink you upload the .mq5 or .ex5 file on the Add bot page — we compile it, show any errors and place it on your always-on MT5 terminal; you can watch the live screen from your phone.
Go-live checklist
- Backtested over a long period and several market conditions.
- Ran on a demo account for weeks with results you understand.
- Risk per trade defined; maximum drawdown you can accept.
- Stops and exits on every position; unique magic number.
- Start live with the smallest lot size.
FAQ
Do I need to know how to code to run an MT5 bot?
No. You can run a ready-made Expert Advisor (.ex5) without coding. To write your own, basic MQL5 helps — or you can draft it with an AI assistant and test it carefully.
What is the difference between .mq5 and .ex5?
.mq5 is the source code you edit in MetaEditor. .ex5 is the compiled file MetaTrader 5 actually runs.
Can I run an MT5 bot on my phone?
No. The MetaTrader 5 mobile app cannot run Expert Advisors. Bots need the desktop terminal running 24/7 — on your PC, a VPS or a managed cloud like etrink.
How long should I test a bot before going live?
Backtest it in the Strategy Tester, then run it on a demo account for at least a few weeks across different market conditions before risking real money.
Start free — run your tested EA on an always-on MT5 terminal in the cloud. Related: Run an MT5 EA 24/7 without a VPS.