TradingTeaching Press · Dubai, UAE Trading is high-risk. Check local laws, your residency rules and your finances. Risk warning
🤖 Trading Automation

MQL5 Introduction: Getting Started with MetaTrader Programming

Start learning MQL5 programming for MetaTrader 5. This beginner's guide covers the basics of creating Expert Advisors and indicators.

5 min read TradingTeaching Team

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

  1. Download MT5 from your broker or metaquotes.com
  2. Install and create demo account
  3. Log in to the platform

Step 2: Open MetaEditor

MetaEditor is where you write code:

  1. In MT5, press F4 or click Tools → MetaQuotes Language Editor
  2. MetaEditor opens in new window
  3. This is your programming environment

Step 3: Create Your First File

  1. In MetaEditor: File → New
  2. Select Expert Advisor (template)
  3. Name it "MyFirstEA"
  4. 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

  1. Press F7 or click Compile button
  2. Check the Errors tab at bottom
  3. Fix any errors (red)
  4. Warnings (yellow) are usually okay

Running Your EA

  1. Go back to MT5
  2. Find your EA in Navigator → Expert Advisors
  3. Drag it onto a chart
  4. Click OK to attach
  5. 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

  1. Create EA that prints "New candle!" on each new bar
  2. Create EA that shows current spread on chart
  3. 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.

Risk warning. This is education only, not financial, investment, tax or legal advice, and not a recommendation to buy or sell anything. Trading forex, CFDs, stocks, commodities, futures, options and crypto is high-risk; with leverage you can lose more than you deposit, and most retail traders lose money. Before you trade or invest in any form, check the local laws where you are and the rules of your country of residence, and consider your own financial situation; if in doubt, ask a licensed adviser. Past and tested results, and all examples, are for illustration only and do not guarantee future results.

Get the strategy right before you automate it

An automated system is only as good as the rules behind it. The book series covers building and testing those rules before a line of code is written.

Explore the books