Exploring Functions in MQL4 Programming
Watch on YouTube: MQL4 Functions: Syntax, Types, and Event Handling
Functions are fundamental in MQL4 programming, allowing you to bundle a set of commands into a single callable unit. They increase efficiency, enhance code readability, and promote reusability. By using functions, you avoid repeating the same code multiple times throughout your script, which reduces errors and makes your code easier to maintain.
Function Syntax
The basic structure of a function in MQL4 is as follows:
return_type FunctionName(parameters) {
// function body
return value;
}
- return_type: Specifies the type of value the function will return, like
int,double,string, etc. - FunctionName: The name you give to the function (e.g.,
addNumbers). - parameters: These are the inputs you pass to the function (optional).
- return value: The output the function gives back.
Example: A Simple Function
Let’s consider an example where we define a function that adds two integers and returns the result:
// Function definition
int addNumbers(int a, int b) // Function name: addNumbers; Parameters: a, b
{
return a + b; // Body: Logic to add a and b, and return the result
}
void OnStart()
{
// Call the function with arguments 5 and 3
int result = addNumbers(5, 3); // Call: Pass values 5 and 3 to addNumbers
Print("The result is: ", result); // Output the result 8
}In this example, the function addNumbers takes two parameters (a and b), adds them together, and returns the sum. We then call this function from the main body of the program to compute the sum of 5 and 3.
Functions with No Return Value (void)
If a function does not need to return a value, you can use the void return type. A function with void simply performs actions without returning anything.
Example of a void function:
// Function with no return value
void printMessage()
{
Print("Functions with No Return Value: Hello, MQL5!"); // Print a message
}
void OnStart()
{
printMessage(); // Call the function to execute its task
} In this case, printMessage doesn’t return anything but instead simply prints a message to the log when called by the OnStart event handle.
Functions with Multiple Parameters
Functions in MQL4 can accept multiple parameters. The parameters are specified within the parentheses when you define the function.
Example:
// Function with multiple parameters
double multiply(double a, double b)
{
return a * b; // Multiply two numbers and return the result
}
void OnStart()
{
double result = multiply(2.5, 4.0); // Call the function with two arguments
Print("Functions with Multiple Parameters: The result is ", result); // Output: 10.0
}Recursive Functions
In MQL4, a function can call itself. This is known as recursion and is often used for problems that can be broken down into smaller sub-problems, such as calculating factorials or navigating directories.
Example:
// Recursive function
int factorial(int n)
{
if (n == 0) return 1; // Base case: factorial of 0 is 1
return n * factorial(n - 1); // Recursive call
}
void OnStart()
{
int result = factorial(5); // Calculate the factorial of 5
Print("Recursive Functions: Factorial of 5 is ", result); // Output: 120
}Passing Parameters by Value or Reference
In MQL4, you can pass arguments to a function either by value or by reference:
- By Value: A copy of the variable is passed to the function, meaning any changes to the parameter inside the function do not affect the original variable.
- By Reference: The actual variable is passed, so changes made inside the function will affect the original variable. To pass an argument by reference in MQL4, place the ampersand character
&before the parameter name in the function declaration. This signals that the original variable, rather than a copy, will be modified within the function.
Example of passing by value:
// Pass by value
void addTen(int number)
{
number += 10; // Modify local copy only
Print("Inside function, number is: ", number); // Example: 15
}
void OnStart()
{
int num = 5;
addTen(num); // Call the function
Print("Outside function, num is still: ", num); // Output: 5
}Example of passing by reference:
// Pass by reference
void addTen(int &number)
{
number += 10; // Modify the original variable
Print("Inside the function number is changed to: ", number);
}
void OnStart()
{
int num = 5;
addTen(num); // Call the function
Print("Outside the function, now num is: ", num); // Output: 15
}Built-In Functions
MQL4 also comes with a set of built-in functions that provide essential functionality, such as mathematical operations, string manipulation, and trading-related functions.
For example:
OrderSend(): to place a tradePrint(): to print messages to the logNormalizeDouble(): to round numbers
We will frequently use built-in functions throughout our lessons, explaining each one as needed when they come up in the context of the code.
Event Handling Functions
In MQL4, event handling functions are built-in functions that automatically trigger in response to specific actions or events within the MetaTrader platform. These functions allow you to handle tasks like reacting to price changes, trading signals, or user interactions. Common event handling functions include:
OnInit(): Called when the script, expert advisor (EA), or indicator is initialized.OnTick(): Executes every time there’s a new market tick (price update).OnTimer(): Executes based on a set timer interval.OnDeinit(): Runs when the script, EA, or indicator is removed or stopped.
Each function serves to automate responses to platform events, making them integral to MQL4 programming.
Function overloading
Function overloading in MQL4 allows you to define multiple functions with the same name but different parameter types or counts. This lets you create versatile functions that handle various data types or arguments while keeping the code readable and organized. However, note that MQL4 has limited support for overloading compared to some other languages, so parameters must differ clearly in type or number.
Example:
// Overloaded 'add' function for integers
int add(int a, int b) {
return a + b;
}
// Overloaded 'add' function for doubles
double add(double a, double b) {
return a + b;
}
void OnStart() {
int intResult = add(5, 3); // Calls the integer version
double doubleResult = add(5.5, 3.2); // Calls the double version
Print("Integer result: ", intResult); // Output: 8
Print("Double result: ", doubleResult); // Output: 8.7
}
Conclusion
Mastering functions in MQL4 is crucial for writing efficient and readable code. Functions help you modularize your scripts, making them easier to maintain, debug, and extend. By understanding how to define and call functions, as well as how to work with parameters and return types, you’ll be able to create more sophisticated and reusable MQL4 code for algorithmic trading.
