It’s a common query: “How to add MQL5 in MT4?” While the desire to leverage MQL5’s advanced features within the widely-used MT4 platform is understandable, it’s crucial to begin with a fundamental clarification: MQL5 programs cannot be directly executed or “added” to MetaTrader 4. The platforms utilize different versions of the MetaQuotes Language (MQL4 for MT4, MQL5 for MT5), which, despite their shared lineage, have significant architectural and syntactical distinctions. This guide focuses on the process of adapting or converting MQL5 code for use in an MQL4 environment.
Brief Overview of MQL5 and MT4
MetaTrader 4 (MT4), along with its MQL4 language, has been a cornerstone of retail forex trading for years. MQL4 is a procedural language with a C-like syntax, primarily designed for creating Expert Advisors (EAs), custom indicators, and scripts. Its strengths lie in its simplicity and a vast ecosystem of existing code.
MetaTrader 5 (MT5) introduced MQL5, a more powerful and flexible language. Key MQL5 advancements include:
- Object-Oriented Programming (OOP): Full support for classes, inheritance, encapsulation, and polymorphism.
- Enhanced Standard Library: A comprehensive set of built-in functions and classes for common tasks (e.g., trading, collections, file operations, string manipulation).
- Different Trading System: MQL5 uses a position-based accounting system (netting), whereas MQL4 uses an order-based system (hedging by default).
- Expanded Event Model: MQL5 offers more event handlers like
OnTrade,OnTradeTransaction,OnTester,OnBookEvent, andOnChartEventbeyond MQL4’s core set (OnInit,OnDeinit,OnStart,OnTick,OnTimer,OnChartEvent– thoughOnChartEventin MQL4 is less comprehensive). - Advanced Data Types: Structures can have methods, and there’s better support for enumerations and templates (though MQL4 has enums).
Why Add MQL5 Programs to MT4?
Despite the direct incompatibility, traders and developers might seek to use MQL5 logic in MT4 for several reasons:
- Access to MQL5-exclusive strategies: A particular EA or indicator might only be available in MQL5.
- Leveraging advanced MQL5 features: Developers might be more comfortable with MQL5’s OOP capabilities or its richer function set and wish to port that logic.
- Broker preference: Many traders still use brokers that primarily offer MT4.
The goal, therefore, is not a simple copy-paste but a careful translation of concepts and code from MQL5 to MQL4.
Limitations of Using MQL5 Code in MT4
This conversion process is fraught with challenges due to fundamental differences:
- OOP translation: MQL5’s class structures require significant refactoring into MQL4’s procedural style, often using structs and functions to simulate object-like behavior. True inheritance and polymorphism are difficult to replicate cleanly.
- Trading functions: MQL5’s
CTradeclass and its methods for order and position management have no direct MQL4 counterparts. MQL4 relies onOrderSend(),OrderModify(),OrderClose(), etc., which operate on individual orders. - Standard Library functions: Many MQL5 standard library functions (e.g., for collections, advanced date/time manipulation, complex data structures) must be rewritten from scratch or suitable MQL4 alternatives found/created.
- Event handling: MQL5’s granular event handlers (e.g.,
OnTradeTransaction) often lack direct MQL4 equivalents, requiring manual logic to deduce similar states. - Depth of Market (DOM): MQL5 offers more detailed DOM access which is limited in MQL4.
- Built-in Indicators: While many core indicators exist in both, some MQL5-specific indicators or their advanced drawing styles might not be directly available or easy to replicate in MQL4.
Step-by-Step Guide: Converting MQL5 Code for MT4
Converting MQL5 code to MQL4 is a manual, often complex, development task. There’s no magic bullet or automated tool that can perfectly translate all MQL5 features.
Identifying Compatible Functions and Indicators
Start by analyzing the MQL5 code. Some elements might have straightforward MQL4 equivalents:
- Basic arithmetic and logic: These are generally compatible.
- Standard technical indicators: Functions like
iMA,iMACD,iRSIexist in both, though parameters and return values might differ slightly. For example, MQL5’siMAreturns a handle, which is then used withCopyBuffer, while MQL4’siMAdirectly returns the calculated value for a specific bar.
mq5
// MQL5 example
int ma_handle = iMA(_Symbol, _Period, 20, 0, MODE_SMA, PRICE_CLOSE);
double ma_value_current_bar;
CopyBuffer(ma_handle, 0, 0, 1, &ma_value_current_bar);
mq4
// MQL4 equivalent
double ma_value_current_bar = iMA(NULL, 0, 20, 0, MODE_SMA, PRICE_CLOSE, 0);
- String and array manipulation: Many basic functions are similar, but always verify syntax and behavior.
Rewriting or Replacing Incompatible MQL5 Code
This is the most demanding part of the conversion. Key areas include:
- Object-Oriented Structures:
- MQL5 classes: Translate properties to MQL4
structmembers and methods to global functions that take the struct (or a pointer/reference to it) as the first parameter, mimickingthis. - Inheritance: This is very difficult. Often, you’ll need to flatten hierarchies or use composition within MQL4 structs.
- MQL5 classes: Translate properties to MQL4
- Trading Logic:
- Replace MQL5’s
CTradeclass usage with MQL4’sOrderSend(),OrderSelect(),OrderModify(),OrderClose(),OrderDelete(). Remember MQL4 works with ticket numbers and an order pool, while MQL5 focuses on net positions. - Carefully manage magic numbers and order comments in MQL4 to identify and group trades belonging to a specific strategy, a task simplified by MQL5’s position properties.
- Replace MQL5’s
- Event Handling:
- MQL5’s
OnTrade()orOnTradeTransaction(): In MQL4, you typically check trade results afterOrderSend()or iterate through the order pool inOnTick()to detect changes in trade states. - Other MQL5-specific events (e.g.,
OnBookEvent) often have no direct MQL4 parallel and may require omitting the feature or finding a workaround.
- MQL5’s
- MQL5 Standard Library Usage:
- Functions from
<Trade,
Trade.mqh><Arrays, etc., will need to be manually implemented in MQL4 or equivalent MQL4 libraries sourced/created.
ArrayObj.mqh>
- Functions from
- Custom Indicator Calls: If the MQL5 code uses
iCustomto call other MQL5 indicators, those indicators also need to be converted to MQL4, or MQL4 equivalents found.
Adjusting Syntax and Data Types for MT4
- Function Signatures: MQL5 allows function overloading; MQL4 does not. Ensure unique function names.
- Data Types: While core types like
int,double,bool,string,datetime, andcolorare common, MQL5 allowsstructs to have methods and has more robustenumhandling. MQL4datetimeis essentiallylong(Unix timestamp), which is similar in MQL5, but MQL5 provides more extensive date/time manipulation functions. - Preprocessor Directives: Review
#propertydirectives. MQL5 has more options (e.g.,#property strictis implicit in MQL5 but good practice in MQL4). - Error Handling: MQL5’s
GetLastError()often provides more detailed error codes. MQL4’sGetLastError()is still used, but the context might differ. - Scope Resolution Operator
::: MQL5 uses this for static class members or enums within classes. MQL4 does not have classes in the same way.
Using Compatibility Libraries (if available)
Occasionally, developers release MQL4 libraries that aim to mimic certain MQL5 functionalities (e.g., MQL5-style collections). While these can be helpful, evaluate their reliability, performance, and completeness before integrating. They are not a universal solution and may introduce their own complexities or limitations.
Implementing the Converted Code in MT4
Once you have a syntactically valid MQL4 version of the code, you can implement it in MetaTrader 4.
Locating the MT4 Experts or Indicators Folder
In MT4, go to File -> Open Data Folder. This will open the terminal’s data directory.
- For Expert Advisors: Navigate to
MQL4\Experts. - For Custom Indicators: Navigate to
MQL4\Indicators. - For Scripts: Navigate to
MQL4\Scripts.
Copying the Converted MQL4 File into the Correct Folder
The converted file should have an .mq4 extension (source code) or an .ex4 extension (compiled program).
Compiling the Code in MetaEditor (MT4)
- Open MetaEditor for MT4 (press F4 from MT4, or find it in the MT4 installation directory as
metaeditor.exe). - In MetaEditor, open the
.mq4file you copied. - Click the Compile button (or press F7).
Troubleshooting Compilation Errors
Compilation after conversion is rarely error-free. Common issues include:
- Undeclared identifiers: Functions, variables, or constants from MQL5 that weren’t properly translated or defined in MQL4.
- Type mismatches: Passing a variable of one type to a function expecting another (e.g., MQL5 handle vs. MQL4 direct value).
- Incorrect function parameters: MQL4 functions may have different numbers or types of parameters than their MQL5 conceptual counterparts.
#property strictissues: If you use#property strictin MQL4 (highly recommended), you’ll need to declare all variables explicitly, which might highlight uninitialized variables missed during conversion.- Array out of range: Differences in how dynamic arrays are handled or sized between MQL5 and MQL4.
Carefully analyze each error message. The MetaEditor will usually highlight the problematic line of code.
Testing and Optimizing the MQL5 Program in MT4
After successful compilation, rigorous testing is paramount. The converted program is essentially a new piece of software.
Attaching the Expert Advisor or Indicator to a Chart
In MT4’s Navigator window, find your compiled EA or indicator. Drag and drop it onto a chart, or right-click and select “Attach to a chart.”
Configuring Input Parameters
Ensure all input variables (extern in MQL4) are correctly displayed in the properties window and behave as expected. Test different parameter combinations.
Backtesting the Strategy (if applicable)
For EAs, use MT4’s Strategy Tester:
- Select the EA, symbol, period, and date range.
- Pay close attention to modeling quality (Every tick is most accurate but slowest).
- Crucially, results may differ significantly from an MQL5 backtest of the original program. This is due to differences in:
- Historical data quality and availability.
- Spread and slippage modeling.
- Order execution logic (MQL4’s order-based vs. MQL5’s position-based system can lead to different trade sequences and outcomes, especially for strategies involving multiple open trades on the same symbol).
- Tick generation algorithms in the tester.
Monitoring Performance and Making Adjustments
- Demo Trading: Run the converted EA or indicator on a demo account for an extended period to observe its real-time behavior.
- Log Monitoring: Check the Experts tab and Journal tab in MT4 for errors or unexpected behavior.
- Performance Profiling: If the converted code runs slowly, identify bottlenecks. MQL4 lacks MQL5’s advanced profiling tools, so this often involves manual timing of code sections or simplifying complex logic inherited from MQL5 that MQL4 handles less efficiently (e.g., extensive string operations in loops).
- Memory Management: While MQL4 is less prone to memory leaks from dynamic objects compared to unmanaged C++, inefficient use of arrays or global variables can still impact performance. MQL5’s OOP can encapsulate resource management (e.g., in destructors), which needs manual replication in MQL4 (e.g., in
OnDeinit).
Conclusion: Key Considerations and Best Practices
Successfully converting MQL5 code to MQL4 requires diligence, MQL4 expertise, and a thorough understanding of the differences between the two languages and platforms.
Potential Issues and Solutions
- Logical Divergence: The most significant risk. Even if syntactically correct, the converted MQL4 code might not perfectly replicate the MQL5 strategy’s logic due to fundamental platform differences (e.g., order execution, position netting vs. hedging). Solution: Meticulous side-by-side logic review and extensive testing.
- Loss of Features: Some MQL5 features (e.g., certain event types, advanced chart objects, integrated economic calendar access) have no direct MQL4 counterparts and may need to be omitted or approximated, potentially altering the program’s behavior.
- Performance Degradation: MQL5 code relying heavily on its optimized standard library or OOP features might perform less efficiently when translated to procedural MQL4, especially if the translation is not optimized. Solution: Profile and refactor critical MQL4 code sections.
Importance of Thorough Testing
Never assume a converted program will work identically to its MQL5 original. Treat it as a new program requiring comprehensive functional, performance, and backtesting validation in the MT4 environment.
Ethical Considerations When Using Converted Code
- Intellectual Property: If converting code written by someone else, ensure you have the right to do so. Respect licenses and copyrights.
- Attribution: If you adapt and share or sell a converted program, ethical practice dictates acknowledging the original MQL5 source or author if their work formed a substantial basis for yours.
- Transparency: Be clear about the origin of the code if you are not the original author. Do not pass off a simple conversion as entirely original work.
Ultimately, while “adding MQL5 to MT4” isn’t directly possible, converting MQL5 code to MQL4 can be achieved. It’s a challenging but potentially rewarding task for experienced MQL developers aiming to bridge the gap between these two popular trading platforms.