Articles on MQL4
Functions init() and deinit()

Functions init() and deinit()


for example, forex

Before we write our first indicator we should complete script CrossMASignals. Let's add to our script a possibility to write buy and sell signals into the file, for it we should place a file opening block at the very beginning of the script, add an operation of signals record to the cycle, at the very end define the file closing. Let's name this script CrossMASignals-2. I should note that bars on the chart are divided into two types, bars with up and down arrows and bars without arrows. Let's write into the file the bar opening time, number, price, at which the up arrow and down arrow are drawn. That is, we will have a csv-bar containing 4 columns: Time[Bar_Index], Bar_Index, Blue_Arrow_Price, Red_Arrow_Price. Bars without arrows will contain zero values in the last two columns. I have added several lines at the beginning of the script:






and at the end


and at the very end of the script:



The ready file you can download here .

int start()
  {
   double maLongCur, maLongPrev, maShortCur, maShortPrev;
string arrowName; // here a unique name of the object-arrow will be set int arrowCounter=0; int deletedArrows;
string FileName; int FileHandle;
// let's create the file name FileName="CrossMA.csv"; //let's open a file with name FileName (let's create a handle for it)
FileHandle=FileOpen(FileName,FILE_WRITE | FILE_CSV,";"); if (FileHandle<1)
{ Print("The file has not been opened, error ",GetLastError()); return; } // let's write down names of the columns (heading creation) FileWrite(FileHandle,"Date","Bar number","Up Arrow","Down Arrow"); // let's delete arrows if there are any
deletedArrows=ObjectsDeleteAll(0,OBJ_ARROW); Comment("Deleted ",deletedArrows," objects OBJ_ARROW");

// let's publish utility variables where we will store arrows price coordinates double value1,value2;
//---- for(int i=Bars-1;i>=0;i--)
{ // let's zero utility variables value1=0.0; value2=0.0; maLongCur=iMA(NULL,0,21,0,MODE_SMA,PRICE_CLOSE,i+1);// slow average on the previous bar
maLongPrev=iMA(NULL,0,21,0,MODE_SMA,PRICE_CLOSE,i+2);// slow average two bars before
maShortCur=iMA(NULL,0,13,0,MODE_SMA,PRICE_CLOSE,i+1);// quick average two bars before
maShortPrev=iMA(NULL,0,13,0,MODE_SMA,PRICE_CLOSE,i+2);// quick average on the previous bar


//If there is a buy signal on the previous bar let's put a blue up arrow // at the bar opening price if((maShortCur>maLongCur)&&(maShortPrev<maLongPrev)) { // Put arrow
// object name - arrowName // object type - OBJ_ARROW // horizontal coordinate - Time[i] time of the bar opening // vertical coordinate - Open[i] price of the bar opening arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// let's set the arrow type - 241, up arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,241); //let's set the arrow color – light blue ObjectSet(arrowName,OBJPROP_COLOR,Blue);
// increase arrow counter arrowCounter++; value1=Open[i];//remember the price of the light-blue arrow } //If there is a sell signal on the previous bar put a red down arrow
// at the price of the bar opening if((maShortCur<maLongCur)&&(maShortPrev>maLongPrev)) { // Let's put an arrow // object name - arrowName
// object type - OBJ_ARROW // horizontal coordinate - Time[i] bar opening time // vertical coordinate - Open[i] bar opening price arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// let's set arrow type - 242 , down arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,242);
// set arrow color - red ObjectSet(arrowName,OBJPROP_COLOR,Red);
// increase arrows counter arrowCounter++; value2=Open[i];//remember the price of the red arrow }
//write down the data for the current bar into the file
FileWrite(FileHandle,TimeToStr(Time[i]),i,value1,value2);
} //close file (free the handle, in order we could open the file to // edit it with other programs) if(FileHandle>0) FileClose(FileHandle);

return(0); }


We see that functionally the code consists from three parts:
  1. Preparation unit, where old marks (arrows) are deleted and a record file opens.
  2. Unit of arrows application to the chart and arrows values record into the file.
  3. Finishing unit, where the file is closed.
In MQL-4 there are three predefined procedures executed in some certain order, when the code is run (script, adviser or indicator) at first init() function is executed (if it is declared) where preparatory work, initialization, is convenient. Values of the necessary variables are set there, global arrays are filled out, files are opened etc. In block init() heavy calculating work can not be done as it slows down the work of the code. Then function start() is executed, there the major work is done while the code is working in the terminal memory, this is the main working function. There trading operations (advisors and scripts) are fulfilled, indicators values are calculated, any available values are processed. Function deinit() is the last one to be executed (if it is declared), there the code is finished. This function is executed when we delete an indicator or an advisor from the chart. This function can not be overloaded with calculations as there are no more than 2.5 seconds for the function to be executed. Then it will be compulsory completed. For more detailed information see the inbuilt help «Programs execution» .
Let's change our script in accordance with these standards and name it CrossMASignals-3. I have added operator Print() at the beginning of each function in order we could see the sequence of these functions execution. Moreover, I have placed variable
int FileHandle;  // pointer at the file, global variable,
to the very beginning of the script, beyond functions start, init and deinit. Such variables are called global, they may be run wherever in the program. They say these variables are seen on the global level. We run it in init() when the file pointer is created, in block start() for filing and in block deinit() when file closing. At the same time
string FileName; // file name, local variable
  
was left in block init(), as it is not used anywhere else. This variable is deleted in the terminal memory once block init() is executed and an attempt to run it in the other functions of the script (start or deinit) will call the error notice. Such variables, which exist only within the function where they were declared, are called local. We may declare such variables in other functions and they will not know about existence of each other but it is not recommended as the code becomes too complicated in this case.

int FileHandle;  // file pointer, global variable
int init() { string FileName; // file name, local variable
int deletedArrows;
// let's create the file name Print("init() is executed"); FileName="CrossMA.csv"; //let's open the file with name FileName (create a handle)
FileHandle=FileOpen(FileName,FILE_WRITE | FILE_CSV,";"); if (FileHandle<1)
{ Print("Failed to open the file, error ",GetLastError()); return; } // write columns headings (heading creation) FileWrite(FileHandle,"Date","Bar number","Up arrow","Down arrow"); // let's delete arrows if there are any
deletedArrows=ObjectsDeleteAll(0,OBJ_ARROW); Comment("Deleted ",deletedArrows," of objects OBJ_ARROW");

} //---- int deinit() { Print("deinit() is executed"); //let's close the file (free the handle, in order the file could be
//opened to be edited by other programs) if(FileHandle>0) FileClose(FileHandle);
return(0);
} //---- int start() { double maLongCur, maLongPrev, maShortCur, maShortPrev;
string arrowName; // here a unique name of the object-arrow will be set int arrowCounter=0;// arrows counter // let's declare utility variables where arrows price coordinates will be stored
double value1,value2;
Print("start() is executed"); for(int i=Bars-1;i>=0;i--)
{ // let's zero utility variables value1=0.0; value2=0.0; maLongCur=iMA(NULL,0,21,0,MODE_SMA,PRICE_CLOSE,i+1);// slow average on the previous bar
maLongPrev=iMA(NULL,0,21,0,MODE_SMA,PRICE_CLOSE,i+2);// slow average two bars before
maShortCur=iMA(NULL,0,13,0,MODE_SMA,PRICE_CLOSE,i+1);// quick average two bars before
maShortPrev=iMA(NULL,0,13,0,MODE_SMA,PRICE_CLOSE,i+2);// quick average on the previous bar


//If there is a buy signal on the previous bar let's put a blue up arrow // at the bar opening price if((maShortCur>maLongCur)&&(maShortPrev<maLongPrev)) { // Let's put an arrow
// object name, - arrowName // object type, OBJ_ARROW // horizontal coordinate, Time[i], bar opening time // vertical coordinate, Open[i], bar opening price arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// let's set the arrow type, 241 , up arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,241); // let's set the arrow color, blue ObjectSet(arrowName,OBJPROP_COLOR,Blue);
// increase the arrow counter arrowCounter++; value1=Open[i];//let's remember the blue arrow price } //If there is a sell signal on the previous bar let's put a red down arrow
// at the bar opening price if((maShortCur<maLongCur)&&(maShortPrev>maLongPrev)) { // Let's put an arrow // object name - arrowName
// object type - OBJ_ARROW // horizontal coordinate, Time[i], bar opening time // vertical coordinate, Open[i], bar opening price arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// let's set the arrow type, 242 , down arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,242);
// let's set the arrow color, red ObjectSet(arrowName,OBJPROP_COLOR,Red);
// let's increase the arrows counter arrowCounter++; value2=Open[i];//let's remember the red arrow price }
//let's write the data for the current bar into the file
FileWrite(FileHandle,TimeToStr(Time[i]),i,value1,value2);
} return(0); }

Everything is ready now, though the script's code is not convenient. It has been set that the period of a slow average is equal to 21 and the period of the fast average is equal to 13. Next time when we want to check other periods we will have to change the figures in the code and compile them again. For such cases there are external parameters, parameters of indicators, advisors and scripts. Let's type in new parameters LongPeriod and ShortPeriod, set the initial values and declare parameters with the key word extern (external).



The value of the average is calculated as follows:


This is the fourth variant of such a simple script.


extern int LongPeriod=21; // slow average period
extern int ShortPeriod=13; // fast average period

int FileHandle; // file pointer - global variable int init() { string FileName; // file name – local variable
int deletedArrows;
// let's generate file name Print("Processing init()"); FileName="CrossMA.csv"; //let's open the file with name FileName (create a handle)
FileHandle=FileOpen(FileName,FILE_WRITE | FILE_CSV,";"); if (FileHandle<1)
{ Print("Failed to open the file, error",GetLastError()); return; } // write down the title of the columns (heading creation) FileWrite(FileHandle,"Date","Bar number","Up arrow","Down arrow"); // delete arrows if there are any
deletedArrows=ObjectsDeleteAll(0,OBJ_ARROW); Comment("Deleted ",deletedArrows," of objects OBJ_ARROW");

} //---- int deinit() { Print("Processing deinit()"); //close the file (free the handle, in order the file could be
//opened to edit it by other programs) if(FileHandle>0) FileClose(FileHandle);
return(0);
} //---- int start() { double maLongCur, maLongPrev, maShortCur, maShortPrev;
string arrowName; // here a unique name of the object-arrow will be specified int arrowCounter=0;// arrows counter // let's declare utility variables where arrows price coordinates will be stored
double value1,value2;
Print("start() is executed"); for(int i=Bars-1;i>=0;i--)
{ // let's zero utility variables value1=0.0; value2=0.0; maLongCur=iMA(NULL,0,LongPeriod,0,MODE_SMA,PRICE_CLOSE,i+1);// slow average on the previous bar
maLongPrev=iMA(NULL,0,LongPeriod,0,MODE_SMA,PRICE_CLOSE,i+2);// slow average two bars before
maShortCur=iMA(NULL,0,ShortPeriod,0,MODE_SMA,PRICE_CLOSE,i+1);// fast average two bars before
maShortPrev=iMA(NULL,0,ShortPeriod,0,MODE_SMA,PRICE_CLOSE,i+2);// fast average on the previous bar


//If there is a signal to buy on the previous bar let's put a blue up arrow // at the bar opening price if((maShortCur>maLongCur)&&(maShortPrev<maLongPrev)) { // Let's put an arrow
// object name - arrowName // object type - OBJ_ARROW // horizontal coordinate, Time[i], bar opening time // vertical coordinate, Open[i], bar opening price arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// set the arrow type, 241, up arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,241); // set the arrow color, blue ObjectSet(arrowName,OBJPROP_COLOR,Blue);
// increase arrows counter arrowCounter++; value1=Open[i];//let's remember blue arrow price } //If there is a sell signal on the previous bar let's put a red up arrow
// at the bar opening price if((maShortCur<maLongCur)&&(maShortPrev>maLongPrev)) { // Let's put an arrow // object name, arrowName
// object type, OBJ_ARROW // horizontal coordinate, Time[i], bar opening price // vertical coordinate, Open[i], bar opening price arrowName="arrow"+arrowCounter; ObjectCreate(arrowName,OBJ_ARROW,0,Time[i],Open[i]);
// let's set the arrow type, 242 , down arrow ObjectSet(arrowName,OBJPROP_ARROWCODE,242);
// let's put the arrow color, red ObjectSet(arrowName,OBJPROP_COLOR,Red);
// let's increase the arrows counter arrowCounter++; value2=Open[i];//let's remember the red arrow price }
//let's write the data for the current bar to the file
FileWrite(FileHandle,TimeToStr(Time[i]),i,value1,value2);
} return(0); }

When an adviser or indicator is started, a dialog window appears in the charts where input parameters may be set, but there is no such window when a script is started (as in our case). In this case, if it is required, in order the script got input parameters (offered the user to enter them) the following command is used
#property show_inputs

Let's add this line and get the fifth final variant. Using it on the chart we will see the following:



If we just close the dialog window we will see by tab «Experts» that neither of the functions was called, the script was deleted immediately without execution. Let's open file CrossMA.csv , there are four columns there. The last two columns will be necessary to write an indicator.



Scripts may be downloaded here
Go to article «Indicator Creation».

+7 (495) 710-76-76
© 1998—2008 «Alpari»

close

Your Personal Area

For alpari.classic enter your account number (a letter and 4 figures) and the code word for the Personal Area.

For alpari.micro account: enter your login (6 figures) and the password for MT.

Open an account!Forgotten your password?