In this article you will learn the concept of functions and especially MQL5 User Functions, which are sections of code that will make your code much better!
What Are Functions in MQL5?
Functions are a fundamental building block of any programming language, and MQL5 is no different.
They allow you to structure your code into reusable blocks, making your programs more readable, efficient, and easier to maintain.
In this beginner friendly article we’ll explore everything you need to know about MQL5 functions: what they are, how to use them, the different types, and best practices.
A function is a self-contained block of code that performs a specific task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed. This saves time and reduces the chance of errors.
In MQL5, functions play a crucial role in organizing trading algorithms. Whether you’re creating custom indicators, expert advisors, or scripts, using functions properly ensures modular, clean, and efficient code.
You can find some information about functions also on the official documentation.
Benefits of Using Functions
Programs could run even without functions, but in that case you would see the source code very unorganized, long and inefficient.
Using functions provides several benefits with the main being:
- Reusability: Write once, use multiple times.
- Readability: Break complex logic into smaller, understandable pieces.
- Maintainability: Easier to update and debug.
- Abstraction: Hide implementation details from other parts of the program.
- Modularity: You can organize your program in module having different purposes and easier to manage.
Types of Functions in MQL5
Functions are divided in different types depending if they are native from the application or custom created by the programmer (you)
MQL5 supports two main types of functions:
Built-in Functions
These are functions provided by the MQL5 language. They come as part of the basic installation and have been written by the MQL5/Metatrader developers.
They handle common tasks like opening orders, calculating indicators, and managing positions.
Examples:
|
1 2 3 4 5 6 |
//OrderSend is a built-in function int ticket = OrderSend("EURUSD", OP_BUY, 0.1, Ask, 3, 0, 0); //Print is a built-in function //TimeCurrent is a built in function Print("Current time: ", TimeCurrent()); |
User-Defined Functions
These are custom functions created by the programmer to encapsulate specific behaviors or calculations.
You might not use them at the beginning of your coding journey but you will as you become more advanced and you build more complex tools.
Syntax:
|
1 2 3 4 |
return_type FunctionName(parameters) { // Function body return value; // Optional, depending on return type } |
Example:
|
1 2 3 4 5 6 7 8 |
double CalculateSpread() { return Ask - Bid; } void OnTick() { double spread = CalculateSpread(); Print("Current spread: ", spread); } |
Function Parameters and Return Types
Functions can accept parameters and return values.
Parameters: Values passed to the function. Return Type: The type of data the function sends back.
Example with Parameters:
|
1 2 3 4 5 6 7 8 |
void PrintMessage(string message) { Print(message); } void OnStart() { PrintMessage("Hello, MQL5!"); } |
Example with Return Type:
|
1 2 3 4 5 6 7 8 |
int Add(int a, int b) { return a + b; } void OnStart() { int sum = Add(5, 3); Print("Sum: ", sum); } |
Void Functions
Void functions don’t return any value and use the void keyword in their declaration.
|
1 2 3 4 5 6 7 |
void ShowGreeting() { Print("Welcome to MQL5 programming!"); } void OnStart() { ShowGreeting(); } |
Overloading Functions
MQL5 supports function overloading, which means defining multiple functions with the same name but different parameter types or counts.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
void Display(int number) { Print("Number: ", number); } void Display(string text) { Print("Text: ", text); } void OnStart() { Display(100); Display("Hello MQL5"); } |
Recursion in Functions
A function calling itself is known as recursion.
I admit that these aren’t very frequently used but it’s important to understand the concept.
Example: Factorial calculation
|
1 2 3 4 5 6 7 8 9 |
int Factorial(int n) { if(n <= 1) return 1; return n * Factorial(n - 1); } void OnStart() { int result = Factorial(5); Print("Factorial: ", result); } |
Best Practices for MQL5 Functions
To make your code more efficient and supportable as possible there are some Best Practices that is good to follow when it comes to MQL5 Functions.
- Keep functions focused: Each function should perform one task.
- Use meaningful names: Names should clearly indicate what the function does.
- Avoid global variables: Pass data through parameters instead.
- Comment your code: Explain the function’s purpose and any complex logic.
- Handle errors: Ensure functions manage unexpected input gracefully.
How to Use MQL5 User Functions
As mentioned above, MQL5 User Functions are functions that the developer of custom tools, you, create to manage better the program.
If I can give you a suggestion, the sooner you get familiar with building and using functions, the sooner you will be able to create better programs.
Using functions will take you to a significant higher level of expertise and quality of your code.
Steps to Create and Use User Functions
All functions work the same way in the few steps explained below.
In the case of built-in functions they are already declared and defined and you only call them.
In the case of your MQL5 User Defined Functions you need to do it all, including declaration, definition and call.
- Declare the Function: Specify its return type, name, and parameters.
- Define the Function: Write the code that performs the function’s task.
- Call the Function: Use the function where needed in your program.
Example:
|
1 2 3 4 5 6 7 8 9 10 |
//Declare and define the function int AddNumbers(int a, int b) { return a + b; } //Call the function void OnStart() { int result = AddNumbers(5, 3); Print("Sum: ", result); } |
Conclusion
MQL5 functions are vital for writing clean, efficient, and scalable trading algorithms.
By mastering functions, you can create well-structured programs, reuse code easily, and reduce the risk of errors.
Whether you’re just starting with MQL5 or looking to refine your skills, understanding functions is a step toward becoming a more effective algorithmic trader.
For questions and support please Contact Us.