MQL4 (MetaQuotes Language 4) is the programming language for creating custom indicators, Expert Advisors, and scripts on the MetaTrader 4 platform. Learning MQL4 programming allows you to automate trading strategies, build custom technical analysis tools, and create personalized trading solutions without depending on commercial products.
While MQL4 requires programming knowledge, it’s more accessible than general-purpose languages like C++ or Java. The language focuses specifically on trading functions, reducing the scope of what you need to learn compared to broader programming languages.
This guide covers MQL4 programming fundamentals for beginners with little or no programming experience, explaining basic syntax, essential functions, how to create simple Expert Advisors and indicators, testing and debugging approaches, and common mistakes that trip up new MQL4 programmers.

This is part of our Automated Forex Trading & Expert Advisors: Complete Guide, covering MQL4/MQL5 programming, EA development, backtesting, and optimization strategies.
Why Learn MQL4 Programming
Understanding your motivation for learning MQL4 programming helps maintain focus through the learning curve’s challenging early stages.
Complete Strategy Control
Commercial Expert Advisors often function as black boxes with limited customization options. Coding your own EAs provides complete transparency and control over every trading decision, entry signal, exit condition, and risk management parameter.
You’re not limited by vendor-provided settings or mysterious “secret” strategies. You implement exactly what you want, understanding precisely why each trade executes.
Custom Technical Analysis
Standard MT4 indicators cover common needs, but custom analysis often requires unique combinations or novel calculations. MQL4 programming lets you create custom indicators displaying exactly the information you need in the format you prefer.
Strategy Backtesting Capabilities
Learning MQL4 enables you to backtest trading ideas systematically, discovering which approaches work before risking real money. You can test hundreds of variations quickly, optimizing parameters and identifying robust strategies.
For proper backtesting methodology using your custom EAs, see our backtesting guide.
Independence from Vendors
Rather than buying commercial EAs that might stop working or get abandoned by developers, you build and maintain your own systems. You’re not dependent on vendor support, updates, or honesty about strategy mechanics.
Marketable Skill
MQL4 programming skills are valuable. Traders pay developers to create custom EAs and indicators. Learning MQL4 opens freelance opportunities beyond your personal trading.
For broader context on automated trading and where MQL4 programming fits, see our automated forex trading guide.
MQL4 vs Other Programming Languages
Understanding how MQL4 programming compares to other languages helps set appropriate expectations for the learning process.
Similarities to C++
MQL4 syntax closely resembles C++. Variables, functions, loops, and conditional statements work similarly. Programmers with C, C++, or Java experience will find MQL4 familiar.
However, MQL4 is simpler than C++ because it focuses exclusively on trading functions rather than general-purpose programming. You won’t deal with memory management, complex data structures, or many complications that make C++ challenging.
Easier Than General Languages
MQL4 is more accessible for beginners than Python, JavaScript, or C++ because:
- Narrower scope focusing on trading-specific tasks
- Extensive built-in trading functions handling complex operations
- Immediate practical application to trading rather than abstract concepts
- Active community providing examples and support
Different from MQL5
MQL4 and MQL5 are distinct languages for MT4 and MT5 platforms respectively. While similar, they’re incompatible—MQL4 code won’t run on MT5 and vice versa.
MQL5 is more powerful but also more complex. For beginners, MQL4’s simplicity and larger community make it the better starting point. You can learn MQL5 later once you grasp fundamental programming concepts through MQL4 programming.
For MQL5 information, see our MQL5 programming guide.
Setting Up Your MQL4 Development Environment
Before writing code, configure your development environment properly.
Install MetaTrader 4
Download and install MT4 from any forex broker offering the platform. The platform includes MetaEditor, the integrated development environment (IDE) for writing MQL4 code.
For MT4 installation and basic platform navigation, see our MT4 tutorial.
Open MetaEditor
Launch MetaEditor from within MT4 by clicking Tools → MetaQuotes Language Editor or pressing F4. MetaEditor provides the code editor, compiler, and debugging tools for MQL4 development.

Understand File Structure
MT4 organizes MQL4 files in specific folders within the data directory:
- MQL4/Experts: Expert Advisors (.mq4 source files, .ex4 compiled files)
- MQL4/Indicators: Custom indicators
- MQL4/Scripts: Scripts for one-time execution
- MQL4/Include: Reusable code libraries
Understanding this structure helps you locate files and organize your projects.
Create Your First File
In MetaEditor, click File → New → Expert Advisor. The wizard creates a template EA with basic structure. Name it something simple like “MyFirstEA” and save it.
The template provides starter code showing basic EA structure. You’ll modify this template as you learn.
MQL4 Basic Syntax and Structure
Every MQL4 program follows similar structural patterns. Understanding these foundations enables you to read and write any MQL4 code.
Program Structure
MQL4 programs contain:
- Preprocessor directives (#property, #include)
- Global variable declarations
- Initialization function (OnInit)
- Deinitialization function (OnDeinit)
- Main function (OnTick for EAs, OnCalculate for indicators)
Simple EA structure:
#property copyright "Your Name"
#property link "yourwebsite.com"
// Global variables
int MyVariable = 10;
int OnInit()
{
// Initialization code runs once when EA starts
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
// Cleanup code runs when EA stops
}
void OnTick()
{
// Main code runs every time price changes
}
Variables and Data Types
Variables store information your program uses. Common data types:
- int: Whole numbers (1, 100, -50)
- double: Decimal numbers (1.5, 99.99, -0.001)
- string: Text (“EURUSD”, “Hello”)
- bool: True/false values
- datetime: Date and time values
Declare variables:
int MyNumber = 5;
double MyPrice = 1.2345;
string MyCurrency = "EURUSD";
bool IsTrading = true;
Comments
Comments explain code without affecting execution:
// This is a single-line comment
/* This is a
multi-line comment */
Use comments liberally, especially as a beginner. Future you will thank present you for explaining what the code does.
Operators
Operators perform calculations and comparisons:
- Arithmetic: + – * / % (add, subtract, multiply, divide, modulo)
- Comparison: == != > < >= <= (equal, not equal, greater than, less than, etc.)
- Logical: && || ! (and, or, not)
Examples:
int sum = 5 + 3; // 8
bool isGreater = 10 > 5; // true
bool combined = true && false; // false
Control Structures
Control structures determine program flow based on conditions.
If-Else Statements
Execute code conditionally:
if(condition)
{
// Code runs if condition is true
}
else
{
// Code runs if condition is false
}
Example:
double price = Ask;
if(price > 1.3000)
{
Print("Price is above 1.3000");
}
else
{
Print("Price is at or below 1.3000");
}
Loops
Repeat code multiple times:
For loop (known number of iterations):
for(int i = 0; i < 10; i++)
{
Print("Loop iteration: ", i);
}
While loop (condition-based):
int count = 0;
while(count < 5)
{
Print("Count: ", count);
count++;
}
Switch Statements
Handle multiple conditions:
int choice = 2;
switch(choice)
{
case 1:
Print("Choice is 1");
break;
case 2:
Print("Choice is 2");
break;
default:
Print("Other choice");
}
Essential MQL4 Functions
MQL4 provides built-in functions for common trading operations.
Price Information Functions
Access current market prices:
- Ask: Current ask price (buy price)
- Bid: Current bid price (sell price)
- Close[index]: Close price of bar at index (0 = current)
- Open[index]: Open price of bar
- High[index]: High price of bar
- Low[index]: Low price of bar
Example:
double currentAsk = Ask;
double previousClose = Close[1];
double highestRecent = High[0];
Technical Indicator Functions
Calculate indicator values:
- iMA(): Moving average
- iRSI(): Relative Strength Index
- iMACD(): MACD indicator
- iStochastic(): Stochastic oscillator
Example calculating 20-period MA:
double ma20 = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE, 0);
Order Functions
Manage trading positions:
- OrderSend(): Open new position
- OrderClose(): Close existing position
- OrderModify(): Modify stop loss or take profit
- OrdersTotal(): Count open positions
Example opening buy order:
int ticket = OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, 0, 0, "My Order", 0, 0, Blue);
Utility Functions
Helper functions for various tasks:
- Print(): Output to Experts log
- Alert(): Display popup alert
- Sleep(): Pause execution
- Symbol(): Current chart symbol
- Period(): Current chart timeframe
Creating Your First Simple EA
Let’s create a basic Expert Advisor that opens a buy order when RSI crosses above 30 (oversold).

#property copyright "Your Name"
// Input parameters
input int RSI_Period = 14;
input double LotSize = 0.1;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnTick()
{
// Calculate RSI
double rsi = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 0);
double rsiPrevious = iRSI(NULL, 0, RSI_Period, PRICE_CLOSE, 1);
// Check if we have any open positions
if(OrdersTotal() == 0)
{
// Buy condition: RSI crossed above 30
if(rsiPrevious < 30 && rsi >= 30)
{
// Open buy order
int ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, 3, 0, 0, "RSI Buy", 0, 0, Blue);
if(ticket > 0)
{
Print("Buy order opened successfully. Ticket: ", ticket);
}
else
{
Print("Error opening buy order: ", GetLastError());
}
}
}
}
This EA:
- Calculates current and previous RSI values
- Checks if any positions are already open
- If no positions exist and RSI crosses above 30, opens a buy order
- Prints success or error messages
How to Test This EA:
- Copy the code into MetaEditor
- Click Compile (F7) to check for errors
- Open MT4 Strategy Tester
- Select your EA and run a backtest
- Review results and modify as needed
Creating a Simple Custom Indicator
Here’s a basic indicator that draws a horizontal line at a specified price level:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
// Input parameters
input double PriceLevel = 1.3000;
// Indicator buffer
double LineBuffer[];
int OnInit()
{
// Set buffer as indicator data
SetIndexBuffer(0, LineBuffer);
SetIndexStyle(0, DRAW_LINE);
SetIndexLabel(0, "Price Level");
return(INIT_SUCCEEDED);
}
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
// Fill buffer with specified price level
for(int i = 0; i < rates_total; i++)
{
LineBuffer[i] = PriceLevel;
}
return(rates_total);
}
This indicator draws a horizontal line at your specified price level. Simple but demonstrates indicator structure and buffer usage.
Debugging and Error Handling
Debugging finds and fixes code problems that prevent proper execution.
Compile Errors

When you click Compile, MetaEditor checks for syntax errors. Common compile errors:
- Missing semicolons at line ends
- Mismatched brackets { }
- Misspelled function names
- Incorrect parameter types
Fix compile errors before running code. The Errors tab shows exact line numbers and error descriptions.
Runtime Errors
Runtime errors occur when code runs but encounters problems:
- Division by zero
- Array index out of bounds
- Invalid order parameters
Use GetLastError() to retrieve error codes and Print() to output diagnostic information:
int ticket = OrderSend(...);
if(ticket < 0)
{
int error = GetLastError();
Print("Order failed with error: ", error);
}
Using Print Statements
Liberally use Print() to output variable values and program state:
Print("RSI Value: ", rsi);
Print("Previous Close: ", Close[1]);
Print("Orders Total: ", OrdersTotal());
Check the Experts log (View → Toolbox → Experts tab) to see Print output and diagnose issues.
Strategy Tester for Debugging
The Strategy Tester lets you run EAs on historical data, useful for debugging:
- Set breakpoints in MetaEditor
- Run EA in visual mode
- Watch variable values change
- Identify where logic fails
Common Beginner Mistakes
Avoiding these common errors accelerates your learning progress.
Mistake 1: Forgetting Semicolons
Every statement needs a semicolon:
int x = 5; // Correct
int y = 10 // WRONG - missing semicolon
Mistake 2: Mismatched Brackets
Every opening bracket needs a closing bracket:
if(condition)
{
// Code
} // Don't forget this closing bracket
Mistake 3: Comparing with = Instead of ==
Use == for comparison, = for assignment:
if(x == 5) // Correct - checking if x equals 5
if(x = 5) // WRONG - assigns 5 to x
Mistake 4: Array Index Errors
Arrays in MQL4 use zero-based indexing. Close[0] is current bar, Close[1] is previous bar:
double price = Close[0]; // Correct
double price = Close[-1]; // WRONG - negative index
Mistake 5: Order Management Without Checks
Always check OrdersTotal() and order ticket validity:
// Good practice
if(OrdersTotal() == 0)
{
int ticket = OrderSend(...);
if(ticket > 0)
{
Print("Success");
}
}
Mistake 6: Not Handling Errors
Always check function return values and handle errors:
int ticket = OrderSend(...);
if(ticket < 0)
{
Print("Error: ", GetLastError());
// Handle the error appropriately
}
Learning Resources and Next Steps
Continued learning accelerates your MQL4 proficiency.
Official MQL4 Documentation
MetaQuotes provides comprehensive documentation at docs.mql4.com covering all functions, syntax, and examples. This should be your primary reference.
MQL4 Community Forums
The MQL4.community and MQL5.com forums contain thousands of code examples, answered questions, and helpful community members. Search before asking questions—most beginner issues have been addressed.
Practice Projects
Build increasingly complex projects:
- Simple indicator displaying moving average
- EA trading MA crossover
- Multi-indicator EA with proper money management
- Custom risk management functions
- Complex strategy with multiple entry conditions
Each project reinforces concepts while introducing new challenges.
Code Reading
Read other programmers’ code. The MT4 CodeBase contains thousands of free indicators and EAs. Study how experienced developers structure code, handle errors, and implement strategies.
Incremental Learning
Don’t try to learn everything immediately. Master basics before advancing:
- Variables and data types
- If-else and loops
- Basic functions and indicators
- Simple EA structure
- Order management
- Advanced techniques and optimization
For guidance on building complete Expert Advisors after learning basics, see our building your first EA guide.
Final Thoughts on Learning MQL4
MQL4 programming opens automated trading possibilities unavailable to traders relying solely on commercial products. The learning curve is steep initially but manageable with consistent practice and patience.
Start with simple programs, gradually increasing complexity as you master fundamentals. Don’t expect to build sophisticated EAs immediately—programming skill develops through iterative learning and lots of practice.
Use available resources extensively: official documentation, community forums, code examples, and tutorial content. Programming is learned by doing, not just reading, so write code constantly even if it’s simple or seems pointless initially.
Most importantly, remember that programming skill and trading strategy skill are separate. Learning MQL4 doesn’t automatically make you a profitable trader—it provides tools to implement and test trading ideas systematically. Combine programming knowledge with sound trading principles, risk management, and realistic expectations for best results.
For understanding different EA types you can build with MQL4, see our EA types guide.
For broader automated trading context, see our automated forex trading guide.



