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

MQL5 Basic Syntax: Variables, Operators, and Control Structures

Master MQL5 basic syntax including variables, data types, operators, and control structures. Essential knowledge for EA development.

6 min read TradingTeaching Team

Understanding MQL5 syntax is fundamental to building Expert Advisors. This guide covers variables, operators, and control flow—the building blocks of every trading program.

Variables and Data Types

Declaring Variables

Variables store data your program uses:

// Syntax: type variableName = value;
int myInteger = 100;
double myPrice = 1.12345;
string mySymbol = "EURUSD";
bool isBullish = true;

Numeric Types

Integer Types (Whole Numbers):

int count = 42;           // Regular integer
long bigNumber = 9999999; // Large integer
short smallInt = 100;     // Small integer
char tiny = 1;            // Very small (0-255)

Floating Point (Decimals):

double price = 1.23456;   // High precision (standard)
float approx = 1.234f;    // Lower precision (rarely used)

String Type

string symbol = "EURUSD";
string message = "Trade opened at " + DoubleToString(price, 5);

// String concatenation
string fullMessage = "Symbol: " + symbol + " Price: " + DoubleToString(1.12345, 5);

Boolean Type

bool isActive = true;
bool hasPosition = false;

// Used in conditions
if(isActive)
{
   Print("System is active");
}

Datetime Type

datetime currentTime = TimeCurrent();
datetime specificDate = D'2024.06.15 14:30:00';

// Get time components
MqlDateTime timeStruct;
TimeToStruct(currentTime, timeStruct);
int hour = timeStruct.hour;
int minute = timeStruct.min;

Arrays

// Static array (fixed size)
double prices[10];

// Dynamic array (resizable)
double closePrices[];
ArrayResize(closePrices, 100);

// Accessing elements
prices[0] = 1.1234;  // First element
prices[9] = 1.1240;  // Last element (index 9 for size 10)

// Array as series (newest = index 0)
ArraySetAsSeries(closePrices, true);

Variable Scope

Local Variables

Exist only inside their function:

void OnTick()
{
   int localVar = 10;  // Only exists in OnTick
   // localVar is destroyed when OnTick ends
}

Global Variables

Exist throughout the program:

// Declared outside functions
int globalCounter = 0;

void OnTick()
{
   globalCounter++;  // Accessible here
}

void SomeFunction()
{
   globalCounter++;  // Accessible here too
}

Static Variables

Keep value between function calls:

void OnTick()
{
   static int tickCount = 0;  // Initialized once
   tickCount++;               // Keeps counting

   if(tickCount % 100 == 0)
      Print("Tick count: ", tickCount);
}

Operators

Arithmetic Operators

int a = 10, b = 3;

int sum = a + b;      // Addition: 13
int diff = a - b;     // Subtraction: 7
int product = a * b;  // Multiplication: 30
int quotient = a / b; // Division: 3 (integer)
int remainder = a % b;// Modulo: 1

double c = 10.0, d = 3.0;
double result = c / d; // Division: 3.333...

Comparison Operators

`mql5 int x = 5, y = 10;

bool equal = (x == y); // Equal to: false bool notEqual = (x != y); // Not equal: true bool greater = (x > y); // Greater than: false bool less = (x < y); // Less than: true bool greaterEq = (x >= y); // Greater or equal: false bool lessEq = (x <= y); // Less or equal: true `

Logical Operators

`mql5 bool a = true, b = false;

bool andResult = (a && b); // AND: false bool orResult = (a || b); // OR: true bool notResult = !a; // NOT: false

// Practical example if(price > MA && RSI < 30) { // Both conditions must be true }

if(price > upperBand || price < lowerBand) { // Either condition can be true } `

Assignment Operators

int x = 10;

x += 5;   // Same as: x = x + 5; (15)
x -= 3;   // Same as: x = x - 3; (12)
x *= 2;   // Same as: x = x * 2; (24)
x /= 4;   // Same as: x = x / 4; (6)

// Increment/Decrement
x++;      // Same as: x = x + 1;
x--;      // Same as: x = x - 1;

Control Structures

If-Else Statements

double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

// Simple if
if(price > 1.1000)
{
   Print("Price is above 1.1000");
}

// If-else
if(price > 1.1000)
{
   Print("Price is high");
}
else
{
   Print("Price is low or medium");
}

// If-else if-else chain
if(price > 1.1500)
{
   Print("Price is very high");
}
else if(price > 1.1000)
{
   Print("Price is high");
}
else if(price > 1.0500)
{
   Print("Price is medium");
}
else
{
   Print("Price is low");
}

Ternary Operator

Shorthand for simple if-else:

// Syntax: condition ? valueIfTrue : valueIfFalse

string status = (price > 1.1000) ? "High" : "Low";
double risk = (accountBalance > 10000) ? 0.02 : 0.01;

Switch Statement

For multiple specific values:

int dayOfWeek = DayOfWeek();

switch(dayOfWeek)
{
   case 0:
      Print("Sunday - Market closed");
      break;
   case 1:
      Print("Monday - Week starts");
      break;
   case 5:
      Print("Friday - Week ends");
      break;
   default:
      Print("Regular trading day");
      break;
}

For Loop

When you know iteration count:

`mql5 // Count from 0 to 9 for(int i = 0; i < 10; i++) { Print("Iteration: ", i); }

// Count backwards for(int i = 9; i >= 0; i--) { Print("Countdown: ", i); }

// Loop through array double prices[]; CopyClose(_Symbol, PERIOD_H1, 0, 10, prices);

for(int i = 0; i < ArraySize(prices); i++) { Print("Price[", i, "] = ", prices[i]); } `

While Loop

When condition controls iterations:

int count = 0;

while(count < 5)
{
   Print("Count: ", count);
   count++;
}

// Careful: avoid infinite loops!
// while(true) { } // This runs forever

Do-While Loop

Execute at least once:

int value = 0;

do
{
   Print("Value: ", value);
   value++;
} while(value < 5);

Break and Continue

Control loop flow:

// Break: exit loop immediately
for(int i = 0; i < 100; i++)
{
   if(i == 10)
      break;  // Stops at i=10
   Print(i);
}

// Continue: skip to next iteration
for(int i = 0; i < 10; i++)
{
   if(i % 2 == 0)
      continue;  // Skip even numbers
   Print(i);     // Only prints odd: 1,3,5,7,9
}

Functions

Creating Functions

// Function with no return value
void PrintPrice()
{
   double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   Print("Current price: ", price);
}

// Function with return value
double GetSpread()
{
   double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   return (ask - bid);
}

// Function with parameters
double CalculateLotSize(double riskPercent, double stopLossPips)
{
   double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
   double riskAmount = accountBalance * riskPercent;
   double pipValue = 10;  // Simplified
   return riskAmount / (stopLossPips * pipValue);
}

Calling Functions

void OnTick()
{
   // Call void function
   PrintPrice();

   // Call function with return
   double spread = GetSpread();
   Print("Spread: ", spread);

   // Call with parameters
   double lots = CalculateLotSize(0.02, 50);
   Print("Lot size: ", lots);
}

Practical Example

Combining everything learned:

`mql5 // Global variables input double RiskPercent = 2.0; input int MAPeriod = 20;

double maValues[];

int OnInit() { ArraySetAsSeries(maValues, true); Print("EA initialized with MA period: ", MAPeriod); return(INIT_SUCCEEDED); }

void OnTick() { // Get MA values if(CopyBuffer(iMA(_Symbol, PERIOD_H1, MAPeriod, 0, MODE_SMA, PRICE_CLOSE), 0, 0, 3, maValues) < 3) return;

double currentMA = maValues[0]; double previousMA = maValues[1]; double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);

// Check conditions string signal = "None";

if(price > currentMA && previousMA < maValues[2]) { signal = "BUY"; } else if(price < currentMA && previousMA > maValues[2]) { signal = "SELL"; }

// Print signal if(signal != "None") { Print("Signal: ", signal, " at price ", price); } } ``

Key Takeaways

  • Choose appropriate data types for your data
  • Use meaningful variable names
  • Understand scope: local, global, static
  • Master comparison and logical operators
  • Use if-else for branching logic
  • Use loops for repetitive tasks
  • Create functions for reusable code
  • Always consider edge cases and errors

What's Next?

Learn how to create your first complete Expert Advisor that can place and manage trades.


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