MetaQuotes Language 5 (MQL5) Reference
```wiki
- MetaQuotes Language 5 (MQL5) Reference
MetaQuotes Language 5 (MQL5) is a high-level programming language developed by MetaQuotes Software Corp. specifically for creating automated trading strategies, custom technical indicators, scripts, and Expert Advisors (EAs) for the MetaTrader 5 (MT5) trading platform. It is a powerful and versatile language, allowing traders and developers to automate their trading activities and perform complex analyses with ease. This article provides a comprehensive reference for beginners looking to understand and utilize MQL5.
== Overview of MQL5
MQL5 builds upon the foundation laid by its predecessor, MQL4, but introduces significant improvements in performance, functionality, and code structure. Key features of MQL5 include:
- **Object-Oriented Programming (OOP):** MQL5 supports OOP principles like classes, inheritance, and polymorphism, allowing for more organized and reusable code.
- **Enhanced Data Types:** A richer set of data types, including integers, floating-point numbers, strings, booleans, and datetime, provides greater flexibility in handling trading data.
- **Event-Driven Programming:** MQL5 programs respond to various events within the MT5 platform, such as new tick arrival, chart events, and timer events.
- **Optimized Execution:** MQL5 code is compiled to native machine code, resulting in significantly faster execution speeds compared to interpreted languages.
- **Testing and Optimization:** The MT5 Strategy Tester allows for backtesting and optimization of trading strategies using historical data, helping to identify the most profitable parameters.
- **Access to Market Data:** MQL5 provides access to a wide range of market data, including price history, order book information, and real-time quotes.
== Basic Syntax and Structure
MQL5 syntax is similar to C++, making it relatively easy to learn for programmers familiar with that language. Here's a breakdown of the basic structure:
- **Includes:** `#include <Trade\Trade.mqh>` – Includes header files that provide access to pre-defined functions and classes. Essential includes depend on the type of program you are writing (EA, indicator, script).
- **Declarations:** Variables must be declared with a specific data type. Examples:
* `int myInteger = 10;` * `double myDouble = 3.14;` * `string myString = "Hello, world!";`
- **Functions:** Blocks of code that perform specific tasks. Every MQL5 program must have at least one function, typically `OnInit()` for initialization.
* `int OnInit() { // Initialization function }`
- **Comments:** Used to explain code and make it more readable.
* `// Single-line comment` * `/* Multi-line comment */`
- **Operators:** Used to perform operations on variables and values (e.g., +, -, *, /, ==, !=, >, <).
== Program Types in MQL5
MQL5 supports three main program types:
- **Expert Advisors (EAs):** Automated trading systems that can execute trades based on predefined rules. EAs require the `OnInit()`, `OnDeinit()`, `OnTick()` and `OnTrade()` functions. Expert Advisor Development
- **Custom Indicators:** Technical indicators that can be displayed on charts to analyze market data. Indicators require the `OnInit()`, `OnDeinit()`, `OnCalculate()` and `OnChartEvent()` functions. Technical Indicators
- **Scripts:** Programs that perform a specific task once when executed and then terminate. Scripts require the `OnStart()` function. MQL5 Scripts
== Core Functions and Classes
MQL5 provides a rich set of built-in functions and classes for interacting with the MT5 platform. Some of the most important ones include:
- **`OrderSend()`:** Sends a trading order to the market. Requires parameters like symbol, order type, volume, price, and stop loss/take profit levels. Order Management
- **`OrderModify()`:** Modifies an existing trading order.
- **`OrderClose()`:** Closes an existing trading order.
- **`iMA()`:** Calculates the moving average. A fundamental tool for trend following strategies.
- **`iRSI()`:** Calculates the Relative Strength Index (RSI). A popular momentum indicator.
- **`iMACD()`:** Calculates the Moving Average Convergence Divergence (MACD). Used to identify trend reversals.
- **`SymbolInfoDouble()`:** Retrieves information about a trading symbol, such as the bid and ask prices.
- **`AccountInfoDouble()`:** Retrieves information about the trading account, such as the balance and equity.
- **`TimeCurrent()`:** Returns the current server time.
- **`NormalizeDouble()`:** Rounds a double value to a specified number of decimal places. Important for accurate price calculations.
== Data Types in MQL5
Understanding data types is crucial for writing correct and efficient MQL5 code. Here’s a summary of commonly used data types:
- **`int`:** Integer (whole number).
- **`double`:** Floating-point number (number with decimal places). Used for prices and calculations.
- **`string`:** Text string.
- **`bool`:** Boolean (true or false).
- **`datetime`:** Date and time. Represents a specific point in time.
- **`color`:** Represents a color value.
- **`enum`:** Enumerated type – defines a set of named integer constants.
== Working with Arrays
MQL5 supports one-dimensional and multi-dimensional arrays. Arrays are used to store collections of data.
- **Declaration:** `int myArray[10];` Declares an integer array with 10 elements.
- **Accessing Elements:** `myArray[0] = 5;` Assigns the value 5 to the first element of the array (index 0).
== Control Flow Statements
MQL5 provides standard control flow statements for controlling the execution of code.
- **`if-else`:** Executes different code blocks based on a condition.
- **`for`:** Repeats a block of code a specified number of times.
- **`while`:** Repeats a block of code as long as a condition is true.
- **`switch`:** Selects one of several code blocks to execute based on the value of a variable.
== Error Handling
Robust error handling is essential for reliable trading systems. MQL5 provides mechanisms for detecting and handling errors.
- **`GetLastError()`:** Returns the error code of the last operation.
- **`ErrorDescription()`:** Returns a human-readable description of the error.
- **`Print()`:** Prints messages to the Experts tab in the MT5 terminal, useful for debugging.
== Optimization and Backtesting
The MT5 Strategy Tester is a powerful tool for backtesting and optimizing trading strategies.
- **Backtesting:** Simulates the performance of a trading strategy on historical data.
- **Optimization:** Finds the optimal parameters for a trading strategy by testing different combinations of values. Backtesting Strategies
== Advanced Concepts
- **Custom Classes:** Define your own classes to encapsulate data and functionality.
- **File I/O:** Read and write data to files.
- **Dynamic Arrays:** Arrays that can grow or shrink in size dynamically.
- **Events:** Handle events such as chart events and timer events.
- **DLLs:** Call functions from external Dynamic Link Libraries (DLLs).
== Resources and Further Learning
- **MQL5 Documentation:** [1](https://www.mql5.com/en/docs) - The official MQL5 documentation.
- **MQL5 Community:** [2](https://www.mql5.com/en/forum) - A forum where you can ask questions and share knowledge.
- **MQL5 Code Base:** [3](https://www.mql5.com/en/code) - A repository of MQL5 code examples.
- **Trading Strategy Guides:** [4](https://www.babypips.com/learn/forex) - Basic Forex trading education.
- **Investopedia:** [5](https://www.investopedia.com/) - Financial definitions and explanations.
- **DailyFX:** [6](https://www.dailyfx.com/) - Forex news and analysis.
- **TradingView:** [7](https://www.tradingview.com/) - Charting and social networking platform.
- **Fibonacci Retracements:** [8](https://www.investopedia.com/terms/f/fibonacciretracement.asp)
- **Bollinger Bands:** [9](https://www.investopedia.com/terms/b/bollingerbands.asp)
- **Moving Average Convergence Divergence (MACD):** [10](https://www.investopedia.com/terms/m/macd.asp)
- **Relative Strength Index (RSI):** [11](https://www.investopedia.com/terms/r/rsi.asp)
- **Ichimoku Cloud:** [12](https://www.investopedia.com/terms/i/ichimoku-cloud.asp)
- **Elliott Wave Theory:** [13](https://www.investopedia.com/terms/e/elliottwavetheory.asp)
- **Head and Shoulders Pattern:** [14](https://www.investopedia.com/terms/h/headandshoulders.asp)
- **Double Top/Bottom:** [15](https://www.investopedia.com/terms/d/doubletop.asp)
- **Triangles (Ascending, Descending, Symmetrical):** [16](https://www.investopedia.com/terms/t/triangle.asp)
- **Candlestick Patterns:** [17](https://www.investopedia.com/terms/c/candlestickpattern.asp)
- **Support and Resistance Levels:** [18](https://www.investopedia.com/terms/s/supportandresistance.asp)
- **Trend Lines:** [19](https://www.investopedia.com/terms/t/trendline.asp)
- **Breakout Trading:** [20](https://www.investopedia.com/terms/b/breakout.asp)
- **Scalping:** [21](https://www.investopedia.com/terms/s/scalping.asp)
- **Swing Trading:** [22](https://www.investopedia.com/terms/s/swingtrading.asp)
- **Position Trading:** [23](https://www.investopedia.com/terms/p/positiontrading.asp)
- **Risk Management in Forex:** [24](https://www.investopedia.com/articles/forex/04/riskmanagement.asp)
- **Money Management Techniques:** [25](https://www.investopedia.com/articles/trading/05/moneymanagement.asp)
MQL5 is a powerful language that can significantly enhance your trading capabilities. With dedication and practice, you can develop sophisticated trading strategies and automate your trading activities. Remember to always test your strategies thoroughly before deploying them live.
MQL4 vs MQL5 MQL5 IDE Debugging MQL5 Code MQL5 Strategy Tester MQL5 Indicators MQL5 Expert Advisors MQL5 Optimization MQL5 Data Structures MQL5 Functions MQL5 Events ```