MQL5 is the programming language for MetaTrader 5, used to create automated trading systems (Expert Advisors), custom indicators, and scripts. This guide introduces MQL5 and helps you write your first lines of code.
What Is MQL5?
MQL5 (MetaQuotes Language 5) is:
- A C++-based programming language
- Designed specifically for trading
- Used exclusively with MetaTrader 5
- Object-oriented and powerful
What You Can Create
| Type | Purpose | Example |
|---|---|---|
| Expert Advisor (EA) | Automated trading | MA Crossover Bot |
| Indicator | Custom chart analysis | Custom RSI variant |
| Script | One-time actions | Close all trades |
| Library | Reusable code | Risk calculator |
Setting Up Your Environment
Step 1: Install MetaTrader 5
- Download MT5 from your broker or metaquotes.com
- Install and create demo account
- Log in to the platform
Step 2: Open MetaEditor
MetaEditor is where you write code:
- In MT5, press F4 or click Tools → MetaQuotes Language Editor
- MetaEditor opens in new window
- This is your programming environment
Step 3: Create Your First File
- In MetaEditor: File → New
- Select Expert Advisor (template)
- Name it "MyFirstEA"
- Click Finish
Understanding the EA Structure
When you create a new EA, you get a template:
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Called once when EA starts
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Called when EA stops
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Called on every price tick
}
Key Functions Explained
OnInit():
- Runs once when EA starts
- Initialize variables here
- Return INIT_SUCCEEDED if okay
OnDeinit():
- Runs when EA stops
- Clean up resources here
- Free any allocated memory
OnTick():
- Runs on every new price tick
- Main trading logic goes here
- This is where decisions happen
Your First MQL5 Code
Hello World EA
Let's create a simple EA that prints a message:
//+------------------------------------------------------------------+
//| My First Expert Advisor |
//+------------------------------------------------------------------+
int OnInit()
{
Print("Hello! My EA has started.");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
Print("Goodbye! My EA is stopping.");
}
void OnTick()
{
// Get current price
double currentPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Print it (only once per 100 ticks to avoid spam)
static int tickCount = 0;
tickCount++;
if(tickCount % 100 == 0)
{
Print("Current price: ", currentPrice);
}
}
Compiling Your Code
- Press F7 or click Compile button
- Check the Errors tab at bottom
- Fix any errors (red)
- Warnings (yellow) are usually okay
Running Your EA
- Go back to MT5
- Find your EA in Navigator → Expert Advisors
- Drag it onto a chart
- Click OK to attach
- Check Experts tab for your messages
MQL5 Basic Syntax
Variables
// Integer (whole numbers)
int myNumber = 10;
// Double (decimal numbers)
double myPrice = 1.23456;
// String (text)
string myText = "Hello";
// Boolean (true/false)
bool isActive = true;
Data Types Summary
| Type | Use For | Example |
|---|---|---|
| int | Whole numbers, counts | 10, -5, 0 |
| double | Prices, calculations | 1.23456 |
| string | Text | "EURUSD" |
| bool | Yes/No conditions | true, false |
| datetime | Date and time | D'2024.01.15' |
Comments
// This is a single-line comment
/*
This is a
multi-line comment
*/
Conditional Statements
// If-else
if(price > 1.1000)
{
Print("Price is high");
}
else if(price > 1.0500)
{
Print("Price is medium");
}
else
{
Print("Price is low");
}
Loops
// For loop
for(int i = 0; i < 10; i++)
{
Print("Count: ", i);
}
// While loop
int count = 0;
while(count < 5)
{
Print("While count: ", count);
count++;
}
Getting Market Data
Current Prices
// Get bid and ask prices
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Get spread in points
int spread = (int)SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
Print("Bid: ", bid, " Ask: ", ask, " Spread: ", spread);
Symbol Information
// Current symbol name
string symbol = _Symbol; // or Symbol()
// Point size (0.0001 for most pairs)
double point = _Point;
// Digits after decimal
int digits = _Digits;
Historical Data
// Get last 10 close prices
double closes[];
ArraySetAsSeries(closes, true); // Newest first
CopyClose(_Symbol, PERIOD_H1, 0, 10, closes);
// closes[0] = most recent candle
// closes[1] = previous candle
// etc.
Built-In Functions
Printing and Alerts
// Print to Experts log
Print("This is a log message");
// Show alert popup
Alert("This is an alert!");
// Comment on chart
Comment("Current price: ", bid);
Mathematical Functions
double x = MathAbs(-5.5); // Absolute value: 5.5
double y = MathSqrt(16); // Square root: 4
double z = MathPow(2, 3); // Power: 8
double r = MathRound(3.7); // Round: 4
Next Steps
Practice Exercises
- Create EA that prints "New candle!" on each new bar
- Create EA that shows current spread on chart
- Create EA that alerts when price crosses a level
Learning Path
| Step | Focus |
|---|---|
| 1 | Basic syntax and variables |
| 2 | Getting market data |
| 3 | Placing orders |
| 4 | Managing positions |
| 5 | Indicators in EAs |
| 6 | Risk management |
| 7 | Backtesting |
| 8 | Optimization |
Common Beginner Mistakes
| Mistake | Solution |
|---|---|
| Missing semicolons | End statements with ; |
| Wrong case | MQL5 is case-sensitive |
| Not compiling | Always compile before testing |
| Ignoring errors | Read error messages carefully |
Key Takeaways
- MQL5 is the programming language for MetaTrader 5
- MetaEditor is where you write and compile code
- OnInit, OnDeinit, OnTick are the main EA functions
- Start with simple Print statements to learn
- Compile (F7) to check for errors
- Test on demo accounts first
- Learn systematically: syntax → data → orders → management
What's Next?
Learn MQL5 basic syntax in detail, including variables, operators, and control structures.
This article is for educational purposes only and does not constitute financial advice.