MQL4 Basics:Preprocessor

Preprocessor is a special subsystem of MQL4 compiler that is intended for preparation of the program source code immediately before the program is compiled.

Preprocessor allows enhancement of the source code readability. The code can be structured by including of specific files containing source codes of MQL4 programs. The possibility to assign mnemonic names to specific constants contributes to enhancement of the code readability.

Preprocessor also allows determining of specific parameters of MQL4 programs.

If the # symbol is used in the first line of the program, this line is a preprocessor directive. A preprocessor directive ends with a line feed character.

Constant declaration

Using the #define construction, one can define the symbolic name or symbolic constant at the program start to be the specific symbol string. Later on, the compiler will replace all appearances of this name without quotation marks with the corresponding string. In fact, this name can be replaced by any absolutely arbitrary text, not necessary with digits:

#define identifier value

The constant identifier conforms to the same rules as those regulating names of variables. The value can be of any type:

#define ABC          100
#define PI           0.314
#define COMPANY_NAME "MetaQuotes Software Corp."
void ShowCopyright() { Print("Copyright © 2001-2007, ",COMPANY_NAME); Print(""); }

Controlling compilation

Every MQL4 program allows to specify additional specific parameters named #property that help client terminal in proper servicing for programs without the necessity to launch them explicitly. This concerns external settings of indicators, first of all.

#property identifier value
Constant Type Description
link string a link to the company website
copyright string the company name
stacksize int stack size
library   a library; no start function is assigned, non-referenced functions are not removed
indicator_chart_window void show the indicator in the chart window
indicator_separate_window void show the indicator in a separate window
indicator_buffers int the number of buffers for calculation, up to 8
indicator_minimum double the bottom scaling limit for a separate indicator window
indicator_maximum double the top scaling limit for a separate indicator window
indicator_colorN color the color for displaying line N, where N lies between 1 and 8
indicator_widthN int width of the line N, where N lies between 1 and 8td>
indicator_styleN int style of the line N, where N lies between 1 and 8
indicator_levelN double predefined level N for separate window custom indicator, where N lies between 1 and 8
indicator_levelcolor color level line color
indicator_levelwidth int level line width
indicator_levelstyle int level line style
show_confirm void before script run message box with confirmation appears
show_inputs void before script run its property sheet appears; disables show_confirm property


#property link        ""
#property copyright   "MetaQuotes Software Corp."
#property library
#property stacksize   1024

Compiler will write the declared values in the settings of the executed module.

Including of files

The #include command line can be placed anywhere in the program, but usually all inclusions are placed at the beginning of the source code. Call format:

#include <file_name>
#include "file_name";


#include <WinUser32.mqh>
#include "mylib.mqh"

Preprocessor replaces this line with the content of the file WinUser32.mqh. Angle brackets mean that the WinUser32.mqh file will be taken from the default directory (usually terminal_directory\experts\include). The current directory is not searched.

If the file name is enclosed in quotation marks, the search will be performed in the current directory (where the main file of the source code is located). The standard directory is not searched in.

Importing of functions

Functions are imported from compiled MQL4 modules (*.ex4 files) and from operating system modules (*.dll files). The module name is specified in the #import directive. For compiler to be able to form the imported function call and pass parameters in a proper way, the full description of functions is needed. Functions descriptions follow the #import "module name" immediately. The new #import command (can be without parameters) completes the imported functions description block.

#import "file_name"
    func1 define;
    func2 define;
    funcN define;

Imported functions must have their unique names. Functions having the same names cannot be imported simultaneously from different modules. Imported functions names may not coincide with those of built-in functions.

Since the imported functions are out of the module to be compiled, the compiler cannot check correctness of parameters passed. This is why, to avoid runtime errors, it is necessary to declare the compliance of types and order of parameters precisely. The parameters passed to imported functions (both from EX4 and from DLL modules) cannot have values by default.


#import "user32.dll"
   int    MessageBoxA(int hWnd, string lpText, string lpCaption, int uType);
#import "stdlib.ex4" string ErrorDescription(int error_code); int RGB(int red_value, int green_value, int blue_value); bool CompareDoubles(double number1, double number2); string DoubleToStrMorePrecision(double number, int precision); string IntegerToHexString(int integer_number);
#import "ExpertSample.dll" int GetIntValue(int); double GetDoubleValue(double); string GetStringValue(string); double GetArrayItemValue(double arr[], int, int); bool SetArrayItemValue(double& arr[], int,int, double); double GetRatesItemValue(double rates[][6], int, int, int); int SortStringArray(string& arr[], int); int ProcessStringArray(string& arr[], int); #import

For importing of functions during execution of an mql4 program, the so-called late binding is used. This means that until the imported function has not been called, the corresponding module (ex4 or dll) will not be loaded.

It is not recommended to use the fully qualified name of loaded module appearing as Drive:\Directory\FileName.Ext. MQL4 libraries are loaded from the terminal_dir\experts\libraries folder. If the library has not been found, there will be an attempt to load a library from the terminal_dir\experts folder.

MQL4 Basics:Variables

Variables must be declared before they are used. Unique names are used to identify variables. Descriptions of variables are used for them to be defined and for types to be declared. Description is not an operator.

The basic types are:

  • bool – boolean values of true and false;
  • string – character strings;
  • double – double-precision numbers with floating point.


string MessageBox;
int    Orders;
double SymbolPrice;
bool   bLog;

Additional types:

  • color is an integer representing an RGB color;
  • datetime is date and time, an unsigned integer containing seconds that have passed since 0.00 a.m. on 1 January, 1970.

Additional data types make sense only at the declaration of input parameters for their more convenient representation in the properties window.


datetime tBegin_Data   = D'2004.01.01 00:00';
color    cModify_Color = C'0x44,0xB9,0xE6';


Array is the indexed sequence of the identical-type data.

int    a[50];       // A one-dimensional array of 50 integers.
double m[7][50];    // Two-dimensional array of seven arrays,
                    //each of them consisting of 50 integers.

Only an integer can be an array index. No more than four-dimensional arrays are allowed. Numbering of array elements starts with 0. The last element of a one-dimensional array has the number which is 1 less than the array size. This means that call for the last element of an array consisting of 50 integers will appear as a[49]. The same concerns multidimensional arrays: A dimension is indexed from 0 to the dimension size-1. The last element of a two-dimensional array from the example will appear as m[6][49].

If there is an attempt to access out of the array range, the executing subsystem will generate error named ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got using the GetLastError() function.

Local variables

A variable declared inside any function is local. The scope of a local variable is limited to the function range inside which it is declared. A local variable can be initialized by outcome of any expression. Every call of the function initializes a local variable. Local variables are stored in memory area of the corresponding function.


int somefunc()
   int ret_code=0;

Formal parameters

Parameters passed to the function are local. Scope is the function block. Formal parameters must have names differing from those of external variables and local variables defined within one function. In the block of the function to the formal parameters some values can be assigned. Some values can be assigned to formal parameters in the function block.


void func(int x[], double y, bool z)
   if(y>0.0 && !z)

Formal parameters can be initialized by constants. In this case, the initializing value is considered as the default value. Parameters, next to the intialized one, must also be initialized.


void func(int x, double y = 0.0, bool z = true)

When calling such a function, the initialized parameters can be omitted, the defaults being substituted instead of them.


func(123, 0.5);

MQL4-library functions imported within other modules cannot have parameters initialized by default values.

Parameters are passed by value, i.e., modifications of the corresponding local variable inside the called function will not be shown in the calling function in any way. It is possible to pass arrays as parameters. However, for an array passed as parameter, it is impossible to change values of its elements.

It is also possible to pass parameters by reference. In this case, modification of such parameters will be shown in the corresponding variables in the called function passed by reference. Array elements cannot be passed by reference. Parameters can be passed by reference only within one module, such possibility being not provided for libraries. In order to inform that a parameter is passed by reference, it is necessary to put the & modifier after the data type.


void func(int& x, double& y, double& z[])
   double calculated_tp;
   for(int i=0; i<OrdersTotal(); i++)
      if(i==ArraySize(z))       break;
      if(OrderSelect(i)==false) break;

Arrays can be passed by reference, as well, all changes being shown in the source array. Unlike simple parameters, arrays can be passed by reference into library functions, as well.

Parameters passed by reference cannot be initialized with defaults.

Into function cannot be passed more than 64 parameters.

Static variables

The memory class of "static" defines a static variable. The specifier "static" is declared before a data type.


int somefunc()
   static int flag=10;

Static variables are stored in the permanent memory, their values do not get lost when the function is exited. Any variables in a block, except for formal parameters of the function, can be defined as static. The static variable can be initialized by a constant of the corresponded type, unlike a simple local variable which can be initialized by any expression. If there is no explicit initialization, the static variable is initialized with zero. Static variables are initialized only once before calling of the "init()" function, that is at exit from the function inside which the static variable is declared, the value of this variable not getting lost.

Global variables

Global variables are defined at the same level as functions, i.e. they are not local in any block.


int GlobalFlag=10;   // global variable
int start()

Scope of global variables is the entire program. Global variables are accessible from all functions defined in the program. They are initialized with zero if no other initial value is explicitly defined. A global variable can be initialized only by a constant that corresponds with its type. Global variables can be initialized only once after program loading into client terminal memory.

Note: Variables declared at global level must not be mixed up with the Client Terminal global variables that can be accessed unsing the GlobalVariable…() functions.

Defining extern variables

The extern memory class defines an extern variable. The extern specifier is declared before a data type.


extern double InputParameter1 = 1.0;
extern color  InputParameter2 = red;
int init() { ... }

Extern variables determine inputs of the program, they are accessible from a program properties window. Arrays cannot represent themselves as extern variables.

Initialization of variables

Any variable can be initialized at its defining. Any variable is initialized with zero (0) if no other initial value is explicitly defined. Global and static variables can be initialized only by a constant of the corresponding type. Local variables can be initialized by any expression, not only constant.

Global and static variables are initialized only once. Local variables are initialized every time by call of the corresponded functions.


int    n       = 1;
double p       = MarketInfo(Symbol(),MODE_POINT);
string s       = "hello";
double f[]     = { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 };
int    a[4][4] = { 1, 1, 1, 1,  2, 2, 2, 2,  3, 3, 3, 3,  4, 4, 4, 4 };

The list of array elements values must be enclosed in braces. Initializing values omitted are considered as equal to 0. If the initializing array size is not defined, it will be defined by the compiler from the size of the initializing sequence. Multidimensional arrays are initialized by a one-dimensional sequence, i.e. sequence without additional braces. All arrays, including those declared in the local scope, can be initialized with constants only.

External functions definition

The type of external functions defined in another component of a program must be explicitly described. The absence of such a definition may result in errors during the compilation, linkage, or execution of the program. While describing an external object, the keyword of #import must be used with the reference to the module.

#import "user32.dll"
  int     MessageBoxA(int hWnd ,string szText,string szCaption,int nType);
  int     SendMessageA(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex4"
  double  round(double value);

Import can be used to easily describe functions called from external DLLs or compiled EX4 libraries.

Pointers to variables can be passed to imported dll functions. Data of the string type are passed as a pointer to the corresponding memory block (one should keep in mind that internal representation of string data consists of two parts: the memory block length and the memory block pointer). If there is a need to pass data of the int or double type, then the one-dimensional array of the corresponding type should be passed by reference as a parameter.


#import "some_lib.dll"
  void    PassIntegerByref(int& OneInt[]);
int start()
   int array[1];

MQL4 Basics:Functions

Function is a named part of a program that can be called from other parts of the program so many times as it is necessary. It consists of type definition for the value to be returned, name, formal parameters, and a composite operator (block) of actions to be performed. Amount of passed parameters is limited and cannot exceed 64.


double                       // type of value to be returned
linfunc (double x, double a, double b) // function name and parameters list
                             // composite operator
   return (a + b);           // returned value

The "return" operator can return the value of the expression included into this operator. If necessary, the expression value can be transformed into the type of function result. A function that does not return values must be of "void" type.


void errmesg(string s)
   Print("error: "+s);

Parameters to be passed to the function can have default values that are defined by constants of the appropriate type.


int somefunc(double a, double d=0.0001, int n=5, bool b=true, string s="passed string")
   Print("Required parameter a=",a);
   Print("The following parameters are transmitted: d=",d," n=",n," b=",b," s=",s);
   return (0);

If the default value was assigned to a parameter, all follow-up parameters must have the default value, too.

Example of a wrong declaration:

int somefunc(double a, double d=0.0001, int n, bool b, string s="passed string")

Function call

If a name that has not been described before appears in an expression and is followed by the left parenthesis, it will be contextually considered as the name of a function.

function_name (x1, x2,..., xn)

Arguments (formal parameters) are passed by value, i.e., each expression xl, . . . , xn is calculated, and the value is passed to the function. The order of expressions calculation and that of values loading are guaranteed. During the execution, the system checks the number and type of arguments given to the function. Such way of addressing to the function is called a value call. Function call is an expression thy value of which is the value returned by the function. The function type described above must correspond with the type of the returned value. The function can be declared or described in any part of the program on the global scope, i.e., outside other functions. The function cannot be declared or described inside of another function.


int start()
   double some_array[4]={0.3, 1.4, 2.5, 3.6};
   double a=linfunc(some_array, 10.5, 8);
double linfunc(double x[], double a, double b)
   return (a*x[0] + b);

At calling of a function with default parameters, the list of parameters to be passed can be limited, but not before the first default parameter.


void somefunc(double init,double sec=0.0001,int level=10);  // function prototype
somefunc();                   // wrong call, the first required parameter must be presented.
somefunc(3.14);               // proper call
somefunc(3.14, 0.0002);       // proper call
somefunc(3.14, 0.0002, 10);   // proper call

When calling a function, one may not skip parameters, even those having default values:

somefunc(3.14, , 10);         // wrong call. the second parameter was skipped.

Special functions

There are three functions with pre-defined names in MQL4:

  • init() is a function to be called during the module initialization. If it is not available, no function will be called at initialization.
  • start() is the basic function. For experts, it is called after the next tick has income. For custom indicators, it is called at recalculation after the indicator has been attached to the chart, at opening of the client terminal (if the indicator is attached to the chart), and after the next tick has income, as well. For scripts, it is executed immediately after the script has been attached to the chart and initialized. If there is no start() function in the module, the module (expert, script, or custom indicator) cannot be launched.
  • deinit() is a function to be called during deinitialization of the module. If it is not available, no function will be called at deinitialization.

Pre-defined functions can have some parameters. However, no parameters will be taken from outside when these functions are called by the client terminal, but the default values will be used. Functions of start(), init(), and deinit() can be called from any point of the module according to the common rules, equally to other functions.

It is not recommended to call start() function from init() function or to perform trade operations, as chart data, market prices, etc. can be incomplete by the moment of the module initialization. The init() and deinit() functions must finish their working as soon as possible and, in no case, shall they loop when trying to start its full-fledged working before the start() function is called.

MQL4 Basics:Operators

Language operators describe some algorithmic operations that must be executed to accomplish a task. The program body is a sequence of such operators. Operators following one by one are separated with a semicolon.

One operator can occupy one or several lines. Two or more operators can be located in the same line. Operators that control over the execution order (if, if-else, switch, while and for) can be nested into each other.


if(Month() == 12)
  if(Day() == 31) Print("Happy New Year!");

Compound operator

A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. The closing brace must not be followed by a semicolon (;).


   Print("invalid position x=",x);

Expression operator

Any expression followed by a semicolon (;) is an operator. Here are some examples of expression operators:

Assignment operator:

y=x=3; // error

Assignment operator can be used in an expression only once.

Function call operator:

Function_name(argument1,..., argumentN);

Empty operator

It consists of a semicolon (;) only and used to denote a null body of a control operator.

Break operator

A break operator terminates the execution of the nearest nested outward switch, while, or for operator. The control is given to the operator that follows the terminated one. One of the purposes of this operator is to finish the looping execution when a certain value is assigned to a variable.


// searching for the first zero element

Continue operator

A continue operator gives control to the beginning of the nearest outward cycle while or for operator, the next iteration being called. The purpose of this operator is opposite to that of break operator.


// summary of nonzero elements of array
int func(int array[])
   int array_size=ArraySize(array);
   int sum=0;
   for(int i=0;i<array_size; i++)
      if(a[i]==0) continue;

Return operator

A return operator terminates the current function execution and returns the control to the calling program. A return(expression); operator terminates the current function execution with result transmission. The operator expression must be enclosed in parentheses and should not contain an assignment operator.


int CalcSum(int x, int y)

In functions with the value of void type to be returned, the return operator must be used without the expression:

void SomeFunction()
   return;    // this operator can be deleted

The right brace of the function means implicit execution of the return operator without expression.

Conditional operator if-else

If the expression is true, operator1 is executed and the control is given to the operator that follows operator2 (operator2 is not executed). If the expression is false, operator2 is executed.

if (expression)

The else part of the if operator can be omitted. Thus, a divergence may appear in nested if operators with omitted else part. In this case, else addresses to the nearest previous if operator in the same block that has no else part.


//   The else part refers to the second if operator:
  if(y==2) z=5;
  else     z=6;

//   The else part refers to the first if operator:
   if(y==2) z=5;
else        z=6;

//   Nested operators
else if(x=='b')
else if(x=='c')
   y = 4;
else Print("ERROR");

Switch operator

It compares the expression value with constants in all variants of case and gives control to the operator that corresponds with the expression value. Each variant of the case can be marked with an integer or literal constant or with a constant expression. The constant expression cannot contain variables or function calls. Expression of the switch operator must be of integer type.

   case constant: operators
   case constant: operators
   default: operators

Operators connected with the default label are executed if none of the constants in case operators equals the expression value. The default variant must be necessarily final. If none of the constants corresponds to the expression value and the default variant is not available, no actions are executed. The keyword case and the constant are just labels, and if operators are executed for some case variant, the program will further execute the operators of all following variants until break operator occurs. It makes it possible to bind a subsequence of operators with several variants.

A constant expression is calculated during compilation. No two constants in one switch operator can have the same values.


   case 'A':
      Print("CASE A");
   case 'B':
   case 'C':
      Print("CASE B or C");
      Print("NOT A, B or C");

Cycle operator while

If the expression is true, the operator is executed until the expression becomes false. If the expression is false, the control will be given to the next operator.


An expression value has been defined before the operator is executed. Therefore, if the expression is false from the very beginning, the operator will not be executed at all.



Cycle operator for

Expression1 describes the cycle initialization. Expression2 is the conditional test for the cycle termination. If it is true, the loop body for operator will be executed. The cycle repeats until Expression2 becomes false. If it is false, the cycle will be terminated, and the control will be given to the next operator. Expression3 is calculated after each iteration.

for (Expression1; Expression2; Expression3)

The for operator is equivalent to the following succession of operators:


Any of the three or all three expressions can be absent in the for operator, but the semicolons (;) that separate them must not be omitted. If Expression2 is omitted, it is considered constantly true. The for (;;) operator is a continuous cycle equivalent to the while(1) operator. Either expression 1 or 3 can consist of several expressions combined by a comma operator ‘,’.


for(x=1;x<=7;x++) Print(MathPower(x,2));
for(;;) { Print(MathPower(x,2)); x++; if(x>10) break; }
for(i=0,j=n-l;i<n;i++,j--) a[i]=a[j];

MQL4 Basics:Operations & Expressions

Some characters and character sequences are of a special importance. These are so-called operation symbols, for example:

+ - * / %     symbols of arithmetic operations
&& ||         symbols of logic operations
= += *=       symbols of assignment operations

Operation symbols are used in expressions and have sense when appopriate operands are given them

Punctuation marks are emphasized, as well. These are parentheses, braces, comma, colon, and semicolon.

Operation symbols, punctuation marks, spaces are used to separate language elements from each other.


An expression consists of one or more operands and operation characters. An expression can be written in several lines.


a++; b = 10;
x = (y * z) /
    (w + 2) + 127;

An expression that ends with a semicolon (;) is an operator.

Arithmetical operations

Arithmetical operations include additive and multiplicative operations:

Sum of values                           i = j + 2;
Difference of values                    i = j - 3;
Changing the operation sign             x = - x;
Product of values                       z = 3 * x;
Division quotient                       i = j / 5;
Division remainder                      minutes = time % 60;
Adding 1 to the variable value          i++;
Subtracting 1 from the variable value   k--;

The operations of adding/subtracting 1 (increment/decrement) cannot be used in expressions.


int a=3;
a++;              // valid expression
int b=(a++)*3;    // invalid expression

Assignment operation

The value of the expression that includes the given operation is the value of the left operand after assignment.

Assigning the y value to the x variable                   y = x;

The following operations unite arithmetic or bitwise operations with operation of assignment:

Adding x to the y variable                               y += x;
Subtracting x from the y variable                        y -= x;
Multiplying the y variable by x                          y *= x;
Dividing the y variable by x                             y /= x;
Module x value of y                                      y %= x;
Logical shift of y representation to the right by x bit  y >>= x;
Logical shift of y representation to the left by x bit   y <<= x;
Bitwise operation AND                                    y &= x;
Bitwise operation OR                                     y |= x;
Bitwise operation exclusive OR
of x and y binary notations                              y ^= x;

There can be only one operation of assignment in an expression. Bitwise operations are performed with integer numbers only. The logical shift operation uses values of x less than 5 binary digits. The greater digits are rejected, so the shift is for the range of 0 to 31 bit. By %= operation (y value by module of x), the result sign is equal to the sign of divided number.

Operations of relation

The logical value FALSE is represented with an integer zero value, while the logical value TRUE is represented with any value differing from zero.

The value of expressions containing operations of relation or logical operations is 0 (FALSE) or 1 (TRUE).

True if a equals b                        a == b;
True if a does not equal b                a != b;
True if a is less than b                  a < b;
True if a is greater than b               a > b;
True if a is less than or equals b        a <= b;
True if a is greater than or equals b     a >= b;

Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why it is necessary to subtract one from another, and the normalized outcome needs to be compared to null.

Boolean operations

Operand of logical negation (operation NOT displayed as exclamation mark) must be of arithmetic type. The result equals TRUE (1) if the operand value is FALSE (0); and it equals FALSE (0) if the operand differs from FALSE (0).

if(!a) Print("not 'a'");

Logical operation OR (||) of x and y values. The expression value is TRUE (1) if x or y value is true (not null). Otherwise, it is FALSE (0). Logical expressions are calculated completely, i.e., the so-called "short estimate" method does not apply to them.

if(x<0 || x>=max_bars) Print("out of range");

Logical operation AND (&&) of x and y values. The expression value is TRUE (1) if both x and y values are ture (not null). Otherwise, it is FALSE (0).

if(p!=x && p>y) Print("TRUE");

Bitwise operations

Complement of the variable value up to one. The value of the expression contains 1 in all digits where n contains 0, and it contains 0 in all digits where n contains 1.

b = ~n;

Binary-coded representation of x is shifted to the right by y digits. The right shift is a logical one, i.e., the freed left-side bits will be filled with zeros.

x = x >> y;

The binary-coded representation of x is shifted to the right by y digits, the freed digits on the right will be filled with zeroes.

x = x << y;

Bitwise operation AND of binary-coded x and y representations. The value of the expression contains 1 (TRUE) in all digits where both x and y do not contain zero; and it contains 0 (FALSE) in all other digits.

b = ((x & y) != 0);

Bitwise operation OR of binary-coded x and y representations. The expression value contains 1 in all digits where x or y is not equal to 0, and it contains 0 in all other digits.

b = x | y;

Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression value contains 1 in all digits where x and y have different binary values, and it contains 0 in all other digits.

b = x ^ y;

Bitwise operations are executed with integers only.

Other operations


At addressing to the i-th element of array, the expression value is the value of the variable with serial number of i.


array[i] = 3; //Assign the value of 3 to the i-th element of the array.

Only an integer can be index of an array. Four-dimensional and below arrays are allowed. Each measurement is indexed from 0 to measurement size-1. In particular case, for a one-dimensional array consisting of 50 elements, the reference to the first element will look like array[0], that to the the last element will array[49].

At access beyond the array, the executing subsystem will generate the error of ERR_ARRAY_INDEX_OUT_OF_RANGE that can be got through the GetLastError() function.

Call for function with x1,x2,…,xn arguments.

Each argument can represent a constant, a variable, or an expression of the corresponding type. The arguments passed are separated by commas and must be inside of parentheses, the opening parenthesis to follow the name of the called function.

The expression value is the value returned by the function. If the returned value is of the void type, such function call cannot be placed to the right in the assignment operation. Please make sure that the expressions x1,x2,…,xn are executed exactly in this order.


double SL=Bid-25*Point;
int    ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,Ask+25*Point,"My comment",123,0,Red);

Comma operation

Expressions separated by commas are executed from left to right. All side effects of the left expression calculation can appear before the right expression is calculated. The result type and value coincide with those of the right expression. The list of parameters to be passed (see above) can be considered as an example.


for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);

Precedence rules

Each group of operations in the table has the same priority. The higher is the priority, the higher is the position of the group in the table. The precedence rules determine the grouping of operations and operands.

()     Function call                     From left to right
[]     Referencing to an array element
!      Logical negation                  From right to left
-      Sign changing operation
++     Increment
--     Decrement
~      Bitwise negation (complement)
&      Bitwise operation AND             From left to right
|      Bitwise operation OR
^      Bitwise operation exclusive OR
<<     Left shift
>>     Right shift
*      Multiplication                    From left to right
/      Division
%      Module division
+      Addition                          From left to right
-      Subtraction
<      Less than                         From left to right
<=     Less than or equal
>      Greater than
>=     Greater than or equal
==     Equal
!=     Not equal
||     Logical OR                        From left to right
&&     Logical AND                       From left to right
=      Assignment                        From right to left
+=     Assignment addition
-=     Assignment subtraction
*=     Assignment multiplication
/=     Assignment division
%=     Assignment module
>>=    Assignment right shift
<<=    Assignment left shift
&=     Assignment bitwise AND
|=     Assignment bitwise OR
^=     Assignment exclusive OR
,      Comma                             From left to right

Parentheses that have higher priority are applied to change the execution order of the operations.

Attention: Priority of performing operations in MQL4 differs to some extent from that conventional in the C language.

MQL4 Basics:Data types

Any program operates with data. Data can be of different types depending on their purposes. For example, integer data are used to access to array components. Price data belong to those of double precision with floating point. This is related to the fact that no special data type is foreseen for price data in MQL 4.

Data of different types are processed with different rates. Integer data are processed at the fastest. To process the double precision data, a special co-processor is used. However, because of complicity of internal presentation of data with floating point, they are processed slower than the integer ones. String data are processed at the longest because of dynamic computer memory allocation/reallocation.

The main data types are:

The color and datetime types make sense only to facilitate visualization and enter those parameters that had been set from expert advisor property tab or custom indicator "Inputs" tab. The data of color and datetime types are represented as integer values. int and double are called arithmetic (numeric) types.

Type casting

Only implicit type casting is used in MQL 4 expressions. The type priority grows at casting:

int  (bool,color,datetime);

Before operations (except for the assignment ones) are performed, the data have been conversed into the maximum priority type. Before assignment operations are performed, the data have been cast into the target type.


int    i = 1 / 2;     // no types casting, the result is 0
int    i = 1 / 2.0;   // the expression is cast to the double type, then is to the target type of int, the result is 0
double d = 1.0 / 2.0; // no types casting, the result is 0.5
double d = 1 / 2.0;   // the expression is cast to the double type that is the same as the target type, the result is 0.5
double d = 1 / 2;     // the expression of the int type is cast to the target type of double, the result is 0.0
string s = 1.0 / 8;   // the expression is cast to the double type, then is to the target type of string, the result is "0.12500000" (the string containing 10 characters)
string s = NULL;      // the constant of type int is cast to the target type of string, the result is "0" (the string containing 1 character)
string s = "Ticket #"+12345; // the expression is cast to the string type that is the same as the target type, the result is "Ticket #12345"

Type casting is applied to not only constants, but also variables of corresponding types.

Integer constants

Decimals: numbers from 0 to 9; zero must not be the first number.


12, 111, -956 1007

Hexadecimals: numbers from 0 to 9, letters from a to f or A to F to represent the values 10 to 15; they start with 0x or 0X.


0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7

Its internal representation is a long 4-byte integer number. Integer constants can assume values from -2147483648 to 2147483647. If the constant exceeds this range, the result is undefined.

Literal constants

Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like ‘\x10’ is a character constant of integer type. Some characters like a single quote (‘), double quote (") a question mark (?), a reverse slash (\), and control characters can be represented as a combination of characters starting with a reverse slash (\) according to the table below:

line feed                NL (LF)  \n
horizontal tab           HT       \t
carriage return          CR       \r
reverse slash            \        \\
single quote             '        \'
double quote             "        \"
hexadecimal ASCII-code   hh      \xhh

If a character different from those listed above follows the reverse slash, the result will not be defined:

int a = 'A';
int b = '$';
int c = '©'; // code 0xA9
int d = '\xAE';   // symbol code ®

Its internal representation is a long 4-byte integer number. Literal constants can assume values from 0 to 255. If the constant exceeds this given range, the result is undefined.

Boolean constants

Boolean constants may have the value of true or false, numeric representation of them is 1 or 0, respectively. True or TRUE, False or FALSE can be used, as well.


bool a = true;
bool b = false;
bool c = 1;

Its internal representation is a long 4-byte integer number. Boolean constants can assume the values of 0 or 1.

Floating-point number constants (double)

Floating-point constants consist of an integer part, a point (.), and a fractional part. The integer and the fractional parts represent sequences of decimal numbers.


double a = 12.111;
double b = -956.1007;
double c = 0.0001;
double d = 16;

Its internal representation is a double-precision number of 8 bytes. Floating-point constants can assume values from -1.7 * e-308 to 1.7 * e308. If a constant exceeds this range, the result is undefined.

String constants

String constant is a sequence of ASCII-code characters enclosed in double quotes: "Character constant".

A string constant is an array of characters enclosed in quotes. It is of the string type. If there is a need to insert a double quote (") into the string, a reverse slash (\) must be put before it. Any special character constants can be inserted into the string if they have a reverse slash (\) before them. The length of a string constant lies between 0 and 255 characters. If the string constant is longer, the superfluous characters on the right will be rejected, and compiler will alert correspondingly.


"This is a character string"
"Copyright symbol \t\xA9"
"this line contains a line feed symbol \n"
"C:\\Program Files\\MetaTrader 4"
"A" "1234567890" "0" "$"

Its internal representation is a structure of 8 bytes. The first element of the structure is a long integer that contains the size of the buffer distributed for the line. The second element of the structure is 32-order address of the buffer that contains the line.

Color constants

Color constants can be represented in three ways: literally, by integers, or by name (for named Web colors only).

Literal representation consists of three parts representing numerical rate values of three main color components: red, green, blue. The constant starts with C and is enclosed in single quotes. Numerical rate values of a color component lie in the range from 0 to 255.

Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component, GG – of the green one, and BB – of the blue one. Decimal constants are not directly reflected in RGB. They represent a decimal value of the hexadecimal integer representation.

Specific colors reflect the so-called Web colors set.


// symbol constants
C'128,128,128'    // gray
C'0x00,0x00,0xFF' // blue
// named color
// integer-valued representation
0xFFFFFF          // white
16777215          // white
0x008000          // green
32768             // green

Its internal representation is a long integer number of 4 bytes. The first byte will not be considered. The other three bytes contain RGB components.

Datetime constants

Datetime constants can be represented as a literal line consisting of 6 parts for values of year, month, date, hours, minutes, and seconds. The constant is enclosed in single quotes and starts with D. Either date (year, month, date) or time (hours, minutes, seconds), or both can be skipped. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.


D'2004.01.01 00:00'     // New Year
D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12'        //equal to D'1980.07.19 12:00:00'
D'01.01.2004'           //equal to D'01.01.2004 00:00:00'
D'12:30:27'             //equal to D'[compilation date] 12:30:27'
D''                     //equal to D'[compilation date] 00:00:00'

Its internal representation is a long integer number of 4 bytes. The value represents the amount of seconds elapse from 00:00 Jan 1, 1970

MQL4 Basics:Syntax

MetaQuotes Language 4 (MQL4) is a new integrated language for programming of trading strategies. This language allows users writing of their own programs (Expert Advisors) that automate trading management and ideally suit for implementing of their own trading strategies. Besides, one can create one’s own technical indicators (Custom Indicators), scripts, and libraries in MQL 4.

Syntax of MQL4 is much a C-like syntax, apart from some features:

  • no address arithmetic;
  • no operator do … while;
  • no operator goto …;
  • no operation of [condition]?[expression 1]:[expression 2];
  • no compound data types (structures);
  • complex assignments are impossible; for example, val1=val2=0; arr[i++]=val; cond=(cnt=OrdersTotal)>0; etc.;
  • calculation of a logical expression is always completed, never early terminated.



Multiline comments start with /* symbols and end with */ symbols. Such comments cannot be nested. Single comments start with // symbols, end with the symbol of a new line and can be nested into multiline comments. Comments are allowed where blank spaces are possible and tolerate any number of spaces.


// single comment
/*  multi-
    line         // nested single comment



Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 31 character.

Symbols you can use: numbers from 0 to 9, Latin capital and small letters a to z, A to Z (recognized as different symbols), the symbol of underlining (_). The first symbol cannot be a number. The identifier must not coincide with any reserved word.


NAME1 namel Total_5 Paper


Reserved words

The identifiers listed below are fixed reserved words. A certain action is assigned to each of them, and they cannot be used for other purposes:

Data types Memory classes Operators Other
bool extern break false
color static case true
datetime   continue  
double   default  
int   else  
string   for  
void   if  

MQL4 Summary

MetaQuotes Language 4 (MQL4) is a new built-in language for programming of trading strategies. This language allows to create your own Expert Advisors that make trading management automated and are perfectly suitable for implementing of one’s own trade strategies. Besides, one can use MQL4 for creation of one’s own Custom Indicators, Scripts, and Libraries. You can start learning the language using Sergey Kovalyov’s book named Programming in Algorithmic Language MQL4 published and supported by MetaQuotes Software Corp.

A large amount of functions necessary for analysis of the current and previously income quotes, as well as basic arithmetic and logic operations are included in MQL4 structure. There are also basic indicators built in and commands of order placement and control.

The MetaEditor 4 (text editor) that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orientate themselves in the expert system text quite easily. We use MetaQuotes Language Dictionary as a Help System for MQL4 language. An abridged guide contains functions divided into categories, operations, reserved words, and other language constructions and allows finding the description of every element we use.

Programs written in MetaQuotes Language 4 have different features and purposes:

  • Expert Advisor is a mechanical trading system (MTS) linked up to a certain chart. An Advisor starts to run with every incoming tick for a given symbol. The Advisor will not be launched for a new, tick if it is processing the previous one at this moment (i.e., the Advisor has not completed its operation yet). The Advisor can both inform you about a possibility to trade and trade at an account automatically sending orders directly to the trade server. Like most trading systems, the terminal supports testing strategies on history data with displaying trading in-and-out points in the chart.
    Experts are stored in terminal_directory\experts.
  • Custom Indicator is a technical indicator written independently in addition to those already integrated into the client terminal. Like built-in indicators, they cannot trade automatically and are intended for implementing of analytical functions only.
    Custom Indicators are stored in terminal_directory\experts\indicators.
  • Script is a program intended for a single execution of some actions. Unlike Expert Advisors, Scripts are not run tick wise, but on request.
    Scripts are stored in terminal_dictionary\experts\scripts.
  • Library is a set of custom functions containing programs most frequently used. Libraries cannot start execution by itself.
    Libraries are recommended to be stored in terminal_directory\experts\libraries.
  • Included file is a source text of the most frequently used blocks of custom programs. Such files can be included into the source texts of experts, scripts, custom indicators, and libraries at the compiling stage. The use of included files is more preferable than the use of libraries because of additional burden occurring at calling library functions.
    Included files are recommended to be stored in terminal_directory\experts\include

Accelerator Oscillator(AC)


Acceleration/Deceleration Technical Indicator (AC) measures acceleration and deceleration of the current driving force. This indicator will change direction before any changes in the driving force, which, it its turn, will change its direction before the price. If you realize that Acceleration/Deceleration is a signal of an earlier warning, it gives you evident advantages.

The nought line is basically the spot where the driving force is at balance with the acceleration. If Acceleration/Deceleration is higher than nought, then it is usually easier for the acceleration to continue the upward movement (and vice versa in cases when it is below nought). Unlike in case with Awesome Oscillator, it is not regarded as a signal when the nought line is crossed. The only thing that needs to be done to control the market and make decisions is to watch for changes in color. To save yourself serious reflections, you must remember: you can not buy with the help of Acceleration/Deceleration, when the current column is colored red, and you can not sell, when the current column is colored green.

Accelerator Oscillator(AC)

If you enter the market in the direction of the driving force (the indicator is higher than nought, when buying, or it is lower than nought, when selling), then you need only two green columns to buy (two red columns to sell). If the driving force is directed against the position to be opened (indicator below nought for buying, or higher than nought for selling), a confirmation is needed, hence, an additional column is required. In this case the indicator is to show three red columns over the nought line for a short position and three green columns below the nought line for a long position.



AC bar chart is the difference between the value of 5/34 of the driving force bar chart and 5-period simple moving average, taken from that bar chart.

AO = SMA(median price, 5)-SMA(median price, 34)
AC = AO-SMA(AO, 5)



Signals of Accelerator Oscillator(AC)

Unlike the Awesome Oscillator, if the Acceleration / Deceleration Oscillator (AC) crosses the zero line, then it is not a signal. However, we still never buy if a histogram bar is red and never sell if it is green.


Buy above the zero line / sell below the zero line

A buy above the zero line signal is generated when there are two consecutive green histogram bars (a green histogram bar is a bar whose high is higher than the preceding bar’s high):

The historgam is above the zero line. Place a Buy Stop one tick above the high of the price bar that corresponds to the second highest high (“c”).

A sell below the zero line signal is generated when there are two consecutive red histogram bars (a red histogram bar is the bar whose low is lower than the preceding bar’s low). The historgam is below the zero line. Place a Sell Stop one tick below the low of the price bar that corresponds to the second lowest low (“c”).


Buy below the zero line / sell above the zero line

If the histogram is below the zero line, a buy signal is generated when there are three consecutive green histogram bars. Place a Buy Stop one tick above the high of the price bar that corresponds to the third highest high (“d”).

If the histogram is above the zero line , a sell signal is generated when there are three consecutive red histogram bars:


Place a Sell Stop one tick below the low of the price bar that corresponds to the third lowest low on the histogram (“d”).

If histogram “b” or “c” bar crosses the zero line, then histogram “c” bar becomes a signal bar, and there is no need to wait for the “d” bar to occur.

  • No matter what signal is created you must ignore it until the first fractal buy or sell signal is triggered outside the Alligator’s mouth.
  • You should ignore signals that are not in the same direction as the first signal from fractal.
  • If Acceleration / Deceleration Oscillator generates a signal but the histogram changes its color before the pending order is executed, then the signal has to be ignored and the order has to be deleted.

Gator Oscillator(Gator)


Gator Oscillator is based on the Alligator and shows the degree of convergence/divergence of the Balance Lines (Smoothed Moving Averages). The top bar chart is the absolute difference between the values of the blue and the red lines. The bottom bar chart is the absolute difference between the values of the red line and the green line, but with the minus sign, as the bar chart is drawn top-down.

Gator Oscillator(Gator)

The Gator Oscillator is displayed as two histograms:

  • the histogram above zero shows the distance between the blue and the red lines (between the Alligator’s jaw and teeth);
  • the histogram below zero shows the distance between the red and the green lines (between the Alligator’s teeth and lips).

All the bars of each histogram are either green or red:

  • histogram bar is red if it is lower than the preceding one;
  • histogram bar is green if it is higher than the preceding one.

The Gator Oscillator clearly shows convergence and intertwining of the Balance Lines when the Alligator is asleep or awake thus helps identify a trend.





  • HIGH — is the maximum price;
  • LOW — is the minimum price;
  • SMMA (A, B, C) — smoothed moving average. Parameter А — smoothed data, В — period of smoothing, С — Shift in the future.


Main Parameters

  • Mode:
    • Upper: Upper line
    • Lower: Lower line
  • Jaw period: Blue line averaging period (Alligator’s Jaw), default is 13
  • Jaw shift: Blue line shift relative to the chart, default is 8
  • Teeth period: Red line averaging period (Alligator’s Teeth), default is 8
  • Teeth shift: Red line shift relative to the chart, default is 5
  • Lips period: Green line averaging period (Alligator’s Lips), default is 5
  • Lips shift: Green line shift relative to the chart, default is 3
  • MA method:
    • Simple
    • Exponential
    • Smoothed, (default option)
    • Linear weighted
  • Apply to: Applied price
    • Close
    • Open
    • High
    • Low
    • Median Price, (high+low)/2, (default option)
    • Typical Price, (high+low+close)/3
    • Weighted Close, (high+low+close+close)/4
第 4 页,共 7 页« 最新...23456...最旧 »
menu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loader