• No results found

FILE FUNCTIONS

In document MQL4_Documentation (Page 98-110)

A group of functions for working with files.

There are three directories (with subdirectories) where working files can be placed:

• /HISTORY/<current broker> - especially for the FileOpenHistory function;

• /EXPERTS/FILES - common case;

• /TESTER/FILES - especially for testing.

Working with files from other directories is prohibited.

FILECLOSE

void FileClose( int handle)

Closes file previously opened by the FileOpen() function. Parameters:

handle - File handle returned by the FileOpen() function

Sample:

int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0)

{

// working with file ... FileClose(handle);

}

FileDelete

void FileDelete( string filename)

Removes specified file name. To get the detailed error information, call GetLastError(). Files can only be deleted if they are in the terminal_dir\experts\files directory

(terminal_directory\tester\files, in case of testing) or its subdirectories. Parameters:

filename - Path to the file.

Sample:

// file my_table.csv will be deleted from terminal_dir\experts\files directory int lastError; FileDelete("my_table.csv"); lastError=GetLastError(); if(laseError!=ERR_NOERROR) {

Print("An error ocurred while (",lastError,") deleting file my_table.csv");

return(0); }

99

FILEFLUSH

void FileFlush( int handle)

Flushes all data stored in the file buffer to the disk.

Notes: The FileFlush() function must be called between operations of file reading and writing in the file.

At file closing, the data are flushed to the disk automatically, so there is no need to call the FileFlush() function before calling of the FileClose() function.

Parameters:

handle - File handle, returned by FileOpen() functions.

Sample: int bars_count=Bars; int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE); if(handle>0) { FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW"); for(int i=0;i<bars_count;i++)

FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]); FileFlush(handle);

...

for(int i=0;i<bars_count;i++)

FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]); FileClose(handle);

}

FILEISENDING

bool FileIsEnding( int handle)

Returns logical true if file pointer is at the end of the file, otherwise returns false. To get the detailed error information, call GetLastError() function. If the file end is reached during reading, the GetLastError() function will return error ERR_END_OF_FILE (4099).

Parameters:

handle - File handle, returned by FileOpen() functions.

Sample: if(FileIsEnding(h1)) { FileClose(h1); return(false); } FILEISLINEENDING

bool FileIsLineEnding( int handle)

For CSV file returns logical true if file pointer is at the end of the line, otherwise returns false. To get the detailed error information, call GetLastError() function.

Parameters:

handle - File handle, returned by FileOpen() function.

Sample:

if(FileIsLineEnding(h1)) {

100 return(false);

}

FILEOPEN

int FileOpen( string filename, int mode, int delimiter=';')

Opens file for input and/or output. Returns a file handle for the opened file or -1 (if the function fails). To get the detailed error information, call GetLastError() function. Notes: Files can only be opened in the terminal_directory\experts\files folder (terminal_directory\tester\files if for expert testing) or in its subfolders. FILE_BIN and FILE_CSV modes cannot be used simultaneously.

If FILE_WRITE does not combine with FILE_READ, a zero-length file will be opened. If even the file containd some data, they will be deleted. If there is a need to add data to an existing file, it must be opened using combination of FILE_READ | FILE_WRITE. If FILE_READ does not combine with FILE_WRITE, the file will be opened only if it already exists. If the file does not exist, it can be created using the FILE_WRITE mode. No more than 32 files can be opened within an executable module simultaneously. Handles of files opened in the same module cannot be passed to other modules (libraries).

Parameters:

filename - Filename.

mode - Opening mode. It can be one or combination of values: FILE_BIN,

FILE_CSV, FILE_READ, FILE_WRITE.

delimiter - Delimiter character for csv files. By default, the ';' symbol applies.

Sample:

int handle;

handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';'); if(handle<1)

{

Print("File my_data.dat not found, the last error is ", GetLastError());

return(false); }

FILEOPENHISTORY

int FileOpenHistory( string filename, int mode, int delimiter=';')

Opens file in the current history directory (terminal_directory\history\server_name) or in its subfolders. Returns the file handle for the opened file. If the function fails, the returned value is -1. To get the detailed error information, call the GetLastError()

function.

Notes: Client terminal can connect to servers of different brokerage companies. History data (HST files) for each brokerage company are stored in the corresponding subfolder of the terminal_directory\history folder.

The function can be useful to form own history data for a non-standard symbol and/or period. The file formed in the history folder can be opened offline, not data pumping is needed to chart it.

Parameters:

filename - Filename.

101

FILE_CSV, FILE_READ, FILE_WRITE.

delimiter - Delimiter for csv files. By default, the ';' symbol will be passed.

Sample:

int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE); if(handle<1)

{

Print("Cannot create file USDX240.HST"); return(false);

}

// work with file // ...

FileClose(handle);

FILEREADARRAY

int FileReadArray( int handle, void array[], int start, int count)

Reads the specified amount of elements from the binary file into array. Before reading, make sure that the array is large enough. Returns the amount of actually read elements. To get the detailed error information, call the GetLastError() function.

Parameters:

handle - File handle returned by the FileOpen() function. array[] - Array where data will be stored.

start - Starting position for storing in array.

count - Count of elements to be read.

Sample: int handle; double varray[10]; handle=FileOpen("filename.dat", FILE_BIN|FILE_READ); if(handle>0) { FileReadArray(handle, varray, 0, 10); FileClose(handle); } FILEREADDOUBLE

double FileReadDouble( int handle, int size=DOUBLE_VALUE)

Reads the double-precision number with floating point from the current binary file position. The number format size can be 8 bytes (double) or 4 bytes (float).

To get the error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function.

size - Number format size. Can be DOUBLE_VALUE(8 bytes) or

FLOAT_VALUE(4 bytes). Sample: int handle; double value; handle=FileOpen("mydata.dat",FILE_BIN); if(handle>0) { value=FileReadDouble(handle,DOUBLE_VALUE);

102 FileClose(handle);

}

FILEREADINTEGER

int FileReadInteger( int handle, int size=LONG_VALUE)

The function reads the integer from the current binary file position. The integer format size can be 1, 2 or 4 bytes. If the format size is not specified, the system tries to read the 4-bytes value. To get the detailed error information, one has to call the GetLastError()

function. Parameters:

handle - File handle returned by the FileOpen() function.

size - Format size. Can be CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) or

LONG_VALUE(4 bytes). Sample: int handle; int value; handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ); if(handle>0) { value=FileReadInteger(h1,2); FileClose(handle); } FILEREADNUMBER

double FileReadNumber( int handle)

Read the number from the current file position before the delimiter. Only for CSV files. To get the detailed error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function.

Sample: int handle; int value; handle=FileOpen("filename.csv", FILE_CSV, ';'); if(handle>0) { value=FileReadNumber(handle); FileClose(handle); } FILEREADSTRING

string FileReadString( int handle, int length=0)

The function reads the string from the current file position. Applies to both CSV and binary files. For text files, the string will be read before the delimiter. For binary file, the given count of characters will be read to the string. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

103

length - Amount of characters for reading.

Sample: int handle; string str; handle=FileOpen("filename.csv", FILE_CSV|FILE_READ); if(handle>0) { str=FileReadString(handle); FileClose(handle); } FILESEEK

bool FileSeek( int handle, int offset, int origin)

The function moves the file pointer to a new position that is an offset, in bytes, from the beginning, the end or the current file position. The next reading or writing are made at a new position.

If file pointer has been moved successfully, the function returns TRUE, otherwise, it returns FALSE. To get the detailed error information, one has to call the GetLastError()

function. Parameters:

handle - File handle returned by the FileOpen() functions. offset - Offset, in bytes, from origin.

origin - Initial position. Value can be one of the following constants:

SEEK_CUR - from current position, SEEK_SET - from begin,

SEEK_END - from end of file. Sample:

int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ|FILE_WRITE, ';');

if(handle>0) {

FileSeek(handle, 0, SEEK_END); //---- add data to the end of file FileWrite(handle, data1, data2); FileClose(handle);

handle=0; }

FILESIZE

int FileSize( int handle)

The function returns file size in bytes. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

handle - File handle returned by the FileOpen() function.

Sample: int handle; int size; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); if(handle>0) {

104 size=FileSize(handle);

Print("my_table.dat size is ", size, " bytes"); FileClose(handle);

}

FILETELL

int FileTell( int handle)

Returns the current position of the file pointer. To get the detailed error information, one has to call GetLastError() function.

Parameters:

handle - File handle returned by the FileOpen() function.

Sample:

int handle; int pos;

handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); // reading some data

pos=FileTell(handle);

Print("current position is ", pos);

FILEWRITE

int FileWrite( int handle, ...)

The function is intended for writing of data into a CSV file, delimiter being inserted automatically. After writing into the file, the line end character "\r\n" will be added. Numbers will be converted into a text at output (see the Print() function).

Returns the count of written characters or a negative number if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function.

... - User data to write, separated by commas. It can be up to 63 parameters. Data of int and double types are automatically converted into a string, but those of color, datetime and bool typesare not automatically converted and will be written to file as they are (as integers).

Arrays cannot be passed as a parameter, they can be output elementwise. Sample: int handle; datetime orderOpen=OrderOpenTime(); handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';'); if(handle>0) {

FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen));

FileClose(handle); }

FILEWRITEARRAY

int FileWriteArray( int handle, object array[], int start, int count)

The function writes the array to a binary file. Arrays of int, bool, datetime and color types will be written elementwise, as 4-bytes integers. Arrays of double type will be

105

written elementwise, as 8-bytes floating point numbers. Arrays of string type will be written by strings, the line end character "\r\n" to be added at each string automatically. Returns the number of written elements or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

handle - File handle returned by the FileOpen() function. array[] - Array to write.

start - Starting index in the array (the first written element number).

count - Count of elements to be written.

Sample:

int handle;

double BarOpenValues[10];

// copy first ten bars to the array for(int i=0;i<10; i++)

BarOpenValues[i]=Open[i]; // writing array to the file

handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle>0)

{

FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7 elements

FileClose(handle); }

FILEWRITEDOUBLE

int FileWriteDouble( int handle, double value, int size=DOUBLE_VALUE)

The function writes a double value with floating point to a binary file. If the format is specified as FLOAT_VALUE, the value will be written as a 4-bytes floating point number (of the float type), otherwise, it will be written in the 8-bytes floating point format (of the double type).

Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function. value - Double precision value.

size - Optional format flag. It can be any of the following values:

DOUBLE_VALUE (8 bytes, default) FLOAT_VALUE (4 bytes). Sample: int handle; double var1=0.345; handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle<1) {

Print("can't open file error-",GetLastError()); return(0);

}

FileWriteDouble(h1, var1, DOUBLE_VALUE); //...

106

FILEWRITEINTEGER

int FileWriteInteger( int handle, int value, int size=LONG_VALUE)

The function writes the integer value to a binary file. If the size is SHORT_VALUE, the value will be written as a 2-byte integer (the short type), if the size is CHAR_VALUE, the value will be written as a 1-byte integer (the char type), and if the size is

LONG_VALUE, the value will be written as a 4-byte integer (the long int type). Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function. value - Value to be written.

size - Optional format flag. It can be any of the following values:

CHAR_VALUE (1 byte), SHORT_VALUE (2 bytes), LONG_VALUE (4 bytes, default). Sample: int handle; int value=10; handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE); if(handle<1) {

Print("can't open file error-",GetLastError()); return(0);

}

FileWriteInteger(handle, value, SHORT_VALUE); //...

FileClose(handle);

FILEWRITESTRING

int FileWriteString( int handle, string value, int length)

The function writes the string to a binary file from the current file position. Returns the actually written bytes count or a negative value if an error occurs. To get the detailed error information, one has to call the GetLastError() function. Parameters:

handle - File handle returned by the FileOpen() function. value - String to be written.

length - The length of the string to be written. If the string length exceeds the given

value, it will be truncated. If it is shorter, it will be extended by binary 0s up to the given length.

Sample:

int handle;

string str="some string";

handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE); if(handle<1)

{

Print("can't open file error-",GetLastError()); return(0);

}

FileWriteString(handle, str, 8); FileClose(handle);

107

GLOBAL VARIABLES

A group of functions intended for working with global variables.

Global variables of the client terminal should not be mixed up with variables declared in the global scope of the MQL4 program.

Global variables are kept in the client terminal within 4 weeks since the last access, then they will be deleted automatically. An access to a global variable is not only setting of a new value, but reading of the global variable value, as well.

Global variables of the client terminal are accessible simultaneously from all MQL4 programs launched in the client terminal.

GLOBALVARIABLECHECK

bool GlobalVariableCheck( string name)

Returns TRUE if the global variable exists, otherwise, returns FALSE. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

name - Global variable name.

Sample:

// check variable before use if(!GlobalVariableCheck("g1")) GlobalVariableSet("g1",1);

GLOBALVARIABLEDEL

bool GlobalVariableDel( string name)

Deletes the global variable. If the function succeeds, the returned value will be TRUE, otherwise, it will be FALSE. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

name - Global variable name.

Sample:

// deleting of the global variable named "gvar_1" GlobalVariableDel("gvar_1");

GLOBALVARIABLEGET

double GlobalVariableGet( string name)

Returns the value of an existing global variable or 0 if an error occurs. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

name - Global variable name.

Sample:

double v1=GlobalVariableGet("g1"); //---- check function call result if(GetLastError()!=0) return(false);

108 //---- continue processing

GLOBALVARIABLENAME

string GlobalVariableName( int index)

The function returns the name of a global variable by its index in the list of global variables. To get the detailed error information, one has to call the GetLastError(). Parameters:

index - Index in the list of global variables. It must exceed or be equal to 0 and be

less than GlobalVariablesTotal(). Sample: int var_total=GlobalVariablesTotal(); string name; for(int i=0;i<var_total;i++) { name=GlobalVariableName(i);

Print(i,": Global variable name - ",name); }

GLOBALVARIABLESET

datetime GlobalVariableSet( string name, double value)

Sets a new value of the global variable. If it does not exist, the system creates a new gloabl variable. If the function succeeds, the returned value will be the last access time. Otherwise, the returned value will be 0. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

name - Global variable name. value - The new numeric value.

Sample:

//---- try to set new value

if(GlobalVariableSet("BarsTotal",Bars)==0) return(false);

//---- continue processing

GLOBALVARIABLESETONCONDITION

bool GlobalVariableSetOnCondition( string name, double value, double check_value) Sets the new value of the existing global variable if the current value equals to the third parameter check_value. If there is no global variable, the function will generate error

ERR_GLOBAL_VARIABLE_NOT_FOUND (4058) and return FALSE. When successfully executed, the function returns TRUE, otherwise, it returns FALSE. To get the detailed error information, one has to call the GetLastError() function.

If the current value of the global variable differs from the check_value, the function will return FALSE.

The function provides atomic access to the global variable, this is why it can be used for providing of a semaphore at interaction of several experts working simultaneously within one client terminal.

Parameters:

109

value - New value.

check_value - Value to be compared to the current global variable value.

Sample:

int init() {

//---- create global variable

GlobalVariableSet("DATAFILE_SEM",0); //... } int start() {

//---- try to lock common resource while(!IsStopped())

{

//---- locking

if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break;

//---- may the variable be deleted?

if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0); //---- sleeping Sleep(500); } //---- resource locked // ... do some work //---- unlock resource GlobalVariableSet("DATAFILE_SEM",0); } GLOBALVARIABLESDELETEALL

int GlobalVariablesDeleteAll( string prefix_name=NULL)

Deletes global variables. If the name prefix is not specified, all global variables will be deleted. Otherwise, only those variables will be deleted, the names of which begin with the specified prefix. The function returns the count of deleted variables.

Parameters:

prefix_name - Name prefix of the global variables to be deleted.

Sample:

Print(GlobalVariablesDeleteAll("test_")," test globals deleted");

GLOBALVARIABLESTOTAL

int GlobalVariablesTotal( )

The function returns the total count of global variables. Sample:

110

In document MQL4_Documentation (Page 98-110)