Variables, Constants and Functions

Variables

A variable is the basic storage unit of any programming language. Variables hold data necessary for our program to function, such as prices, settings and indicator values. Variables must be declared before they are used. To declare a variable, you specify it’s data type, an identifier, and optionally a default value. If you declare a variable more than once, or not at all, you’ll get a compilation error. The data type specifies the type of information the variable holds, whether it be a number, a text string, a date or a color. Here are the data types in MQL:

  • int – A integer (whole number) such as 0, 3, or -5. Any number assigned to an integer variable is rounded up to the next whole number.
  • double – A fractional number such as 1.5765, 0.03 or -2.376. Use these for price data, or in mathematical expressions involving division.
  • string – A text string such a “The quick brown fox jumped over the lazy dog”. Strings must be surrounded by double quotes.
  • boolean – A true/false value. Can also be represented as 1 (true) or 0 (false). Use these anytime you need to evaluate an binary, or on/off condition.
  • datetime – A time and date value such as 2009.01.01 00:00.Internally, a datetime variable is represented as the number of seconds passed since January 1, 1970.
  • color – A constant representing a color, such as Red or DarkSlateBlue. These are generally used for changing indicator or object colors.

Here’s an example of a variable declaration. This is an integer variable, with the identifier MyVariable and a default value of 1.

int MyVariable = 1;

Once a variable has been declared, you can change its value by assigning a new value to it. Here’s an example where we assign the number 5 to MyVariable:

MyVariable = 5;

You can also assign the value of one variable to another variable:

int YourVariable = 2;
MyVariable = YourVariable;
// MyVariable is 2

The assigned variable should be of the same data type. If a double is assigned to an integer variable,for example, the double will be rounded to the nearest whole number. This may lead to an undesirable result.

Constants

Just like its name suggests, a constant is a data value that never changes. For example, the number 5 is an integer constant, the letter ‘A’ is a character constant, and 2009.01.01 is a datetime constant for January 1, 2009.

MQL has a wide variety of standard constants for things like price data, chart periods, colors and trade operations. For example PERIOD_H1 is a constant for the H1 chart time frame, OP_BUY refers to a buy market order, and Redis a color constant for the color red.
You can even create your own constants using the #define preprocessor directive. We’ll get to that shortly. You can learn more about MQL’s standard constants in the Standard Constants section of the MQL Reference.

Functions*
Functions are the building blocks of modern programming languages. A function is a block of code that is designed to carry out a certain task, such as placing an order or calculating a stop loss. MQL has dozens of built-in functions for everything from technical indicators to order placement.

Functions are designed to be reused over and over again. Learning how to create functions for common trading tasks is essential to productive programming. We will work on creating reusable functions for many of the tasks that we will learn in this book.

Let’s start with a simple function called PipPoint(), that calculates the number of decimal points in the current pair, and automatically adjusts for 3 and 5 digit brokers so that the result is always equal to one pip. For Yen pairs (2 or 3 digits), the function returns 0.01. For all other pairs (4 and 5 digits),the function returns 0.0001. Here’s how we would call the function from code:

double UsePoint;
UsePoint = PipPoint();

We declare a variable of type double named UsePoint. Then we call the PipPoint() function and assign the result to UsePoint. Now we can use the value stored in UsePoint to calculate a stop loss,for example. Here is the code for thePipPoint() function:

double PipPoint()
{
    if (Digits == 2 || Digits == 3)
        double UsePoint = 0.01;
    else if (Digits == 4 || Digits == 5)
        UsePoint = 0.0001;
    return (UsePoint);
}

The first line is our function declaration. Like variables, function declarations have a data type and an identifier. Functions use the same data types as variables do. The data type is dependent on the type of data the function returns. Since this function returns a fractional number, we use the double datatype.

The body of the function is contained within the brackets {}. We have an if-else statement that valuates the number of digits after the decimal place, and assigns the appropriate value to the UsePoint variable. Following that, we have the return operator, which returns the value of UsePoint to the calling function.
There is a special data type for functions that do not return a value. The void data type is used for functions that carry out a specific task, but do not need to return a value to the calling function.Void functions do not require a return operator in the body of the function.

Let’s consider a simple function for placing a buy order. This function has arguments that need to be passed to the function. This function will place a buy market order on the current symbol with the specified lot size, stop loss and take profit.

int OpenBuyOrder(doubleLotSize, doubleStopLoss, doubleTakeProfit)
{
    int Ticket = OrderSend(Symbol(), OP_BUY, LotSize, Ask, StopLoss, TakeProfit);
    return (Ticket);
}

This function has three arguments, LotSize, StopLoss and TakeProfit. Arguments are variables that are used only within the function. Their value is assigned by the calling function. Here’s how we would call this function in code using constants:

 OpenBuyOrder(2, 1.5550, 1.6050);

This will place a buy order of 2 lots, with a stop loss of 1.5550 and a take profit of 1.6050. Here’s another example using variables. We’ll assume that the variables UseLotSize, BuyStopLoss and BuyTakeProfit have the appropriate values assigned:

int GetTicket = OpenBuyOrder(UseLotSize, BuyStopLoss, BuyTakeProfit);

In this example, we are assigning the return value of OpenBuyOrder() to the variable GetTicket, which the ticket number of the order we just placed. Assigning the output of a function to a variable is optional. In this case, it is only necessary if you plan to do further processing using the ticket number of the placed order.
Arguments can have default values, which means that if a parameter is not explicitly passed to the function, the argument will take the default value. Default value arguments will always be at the end of the argument list. Here is an example of a function with several default values:

int DefaultValFunc(intTicket, doublePrice, intNumber = 0, stringComment = NULL)

This function has two arguments with default values,Number and Comment, with default values of 0 and NULL respectively. If we want to use the default values for both Number and Comment, we simply omit those arguments when calling the function:

DefaultValFunc(TicketNum,UsePrice);

Note that we only specified the first two arguments.Number and Comment use the default values of 0 and NULL. If we want to specify a value for Number, but not for Comment, we simply omit the last argument:

DefaultValFunc(TicketNum,UsePrice,UseNumber);

Again, Comment uses the default value of NULL. But, if we want to specify a value for Comment, regardless of whether or not we want to use the default value for Number, we have to specify a value for Number as well:

 DefaultValFunc(TicketNum,UsePrice, 0, "Comment String");

In this example, we used 0 as the value for Number, which is the same as the default value, and a string constant as the value for Comment. Remember that when you’re dealing with multiple arguments that have default values, you can only omit arguments if you want to use the default values for all of the remaining arguments!