There is only one disadvantage in our advisor. In block
init() there is a procedure of file opening and reading its data. In case of optimisation two problems occur:
- speed of optimisation decreases as reading from files is much slower than reading from the operative memory;
- multiple operations of files opening/close are undesirable for the hard disk.
Programs in MQL-IV have global variables declared in the body of the code out of any function. These values are preserved while the program works and they are available from any point (function) of this program. Some other decision is required for strategies optimiser to preserve variables values between programs launch. In the optimiser we start the same program-advisor several times and sometimes it is required to remember the state of some variables between some separate launches.
For such purposes there are some special variables,
Global Variables. Unlike global variables on the level of a code/program, these variables are global on the level of the terminal. Thus, we can create some global variable in the script and set its value (
GlobalVariableSet()), and then check its value in the indicator or advisor (
GlobalVariableGet()).
Unlike other types of variables these global variables are kept within 4 weeks when the terminal is closed. Let's suppose that our advisor should open only a position a day. If the fact of opening a position is kept in some common variable then when the terminal is closed or supply is off the value of this variable (let's call it
TradeOpen=
true) is not preserved. Then when the terminal is launched again variable
TradeOpen will take the default value (
false). And the advisor will open a new position automatically, which is forbidden by the algorithm. Usage of a global variable solves this problem.
Let's create a script to understand how the method of global variables usage works. This script will create a global arrays of values.
It is important: global variables can have only type double. There is no possibility to create an array of global variables, though we can solve this problem easily. Functions of global variables check and assignment use the name of this variable, set in the text format. That is why we may set the value for the array by the index as
Array_name+index.
Let's name the script as
GlobalArray.mq4. Instead of the global array we will create the array of global variables: