• No results found

ARRAY FUNCTIONS

In document MQL4_Documentation (Page 68-79)

A group of functions to work with arrays.

Arrays are allowed to be maximum four-dimensional. Each dimension is indexed from 0 to dimension size-1. In a particular case of a one-dimensional array of 50 elements, calling of the first element will appear as array[0], of the last one - as array[49]. Using these functions (except for those which change quantitative and qualitative characteristics of the array) one can process predefined time

series Time[], Open[], High[], Low[], Close[], Volume[]

ARRAYBSEARCH

int

ArrayBsearch(

double array[], double value, int count=WHOLE_ARRAY, int start=0,

int direction=MODE_ASCEND)

If the element with the specified value doesn't exist in the array, the function returns the index of the nearest smallest value of the elements between which the searched value is located.

The function cannot be used with string arrays and series arrays (with the exception of the series array of the bar open time).

Note: Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort() function.

Parameters:

array[] - The numeric array to search for.

value - The value to search for.

count - Count of elements to search for. By default, it searches in the whole

array.

start - Starting index to search for. By default, the search starts at the first

element.

direction - Search direction. It can be any of the following values:

MODE_ASCEND searching in forward direction, MODE_DESCEND searching in backward direction. Sample:

datetime daytimes[];

int shift=10,dayshift;

// All the Time[] series are sorted in descendant mode ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND) ; if(Period()<PERIOD_D1) dayshift++; }

Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ",

69

ARRAYCOPY

int

ArrayCopy(

void dest[], object source[], int start_dest=0, int start_source=0,

int count=WHOLE_ARRAY)

Copies an array to another one. Arrays must be of the same type, but arrays with type double[], int[], datetime[], color[], and bool[] can be copied as arrays of the same type. Returns the amount of copied elements.

Parameters:

dest[] - Destination array.

source[] - Source array.

start_dest - Starting index for the destination array. By default, start index is 0.

start_source - Starting index for the source array. By default, start index is 0.

count - The count of elements that should be copied. By default, it is

WHOLE_ARRAY constant. Sample:

double array1[][6]; double array2[10][6];

// array2 is filled with some data ArrayCopyRates(array1);

ArrayCopy(array2,array1,0,0,60);

// array2 is having the first 10 bars from the history now (first bar considered as bar with index [Bars-1])

ArrayCopy(array2,array1,0,Bars*6-60,60);

// array2 is having the last 10 bars from the history now (last bar considered as current bar, bar wit index [0])

ARRAYCOPYRATES

int ArrayCopyRates( void dest_array[], string symbol=NULL, int timeframe=0)

Copies rates to the two-dimensional array from chart RateInfo array and returns copied bars amount, or -1 if failed. First dimension of RateInfo array contains bars amount, second dimension has 6 elements:

0 - time, 1 - open, 2 - low, 3 - high, 4 - close, 5 - volume.

If data (symbol name and/or timeframe differ from the current ones) are requested from another chart, the situation is possible that the corresponding chart was not opened in the client terminal and the necessary data must be requested from the server. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - the requested history data are under updating) will be placed in the last_error variable, and one will has to re-request (see example of ArrayCopySeries()).

Notes: This rates array is normally used to pass data to a DLL function.

Memory is not really allocated for data array, and no real copying is performed. When such an array is accessed, the access will be redirected.

70

dest_array[] - Reference to the two-dimensional destination array of double type.

symbol - Symbol name (currency pair name)

timeframe - Timeframe. It can be any of the listed timeframes values.

Sample:

double array1[][6];

ArrayCopyRates(array1,"EURUSD", PERIOD_H1);

Print("Current bar ",TimeToStr(array1[0][0]),"Open", array1[0][1]);

ARRAYCOPYSERIES

int

ArrayCopySeries(

void array[], int series_index, string symbol=NULL,

int timeframe=0)

Copies a series array to another one and returns the count of the copied elements. There is no real memory allocation for data array and nothing is copied. When such an array is accessed, the access is redirected. Excluded are arrays that are assigned as indexed ones in custom indicators. In this case, data are really copied.

If data are copied from another chart with different symbol and/or timeframe, it is possible that the necessary data will lack. In this case, error

ERR_HISTORY_WILL_UPDATED (4066 - requested history data under updating) will be placed into the last_error variable, and there will be necessary to retry copying after a certain period of time.

Note: If series_index is MODE_TIME, the array to be passed to the function must be of the datetime type.

Parameters:

array[] - Reference to the destination one-dimensional numeric array.

series_index - Series array identifier. It must be one of series array listed identifiers

values.

symbol - Symbol name (the name of the currency pair)

timeframe - Timeframe of the chart. It can be any of Timeframe list values.

Sample:

datetime daytimes[];

int shift=10,dayshift,error;

//---- the Time[] array was sroted in the descending order ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); error=GetLastError();

if(error==4066) {

//---- make two more attempts to read for(int i=0;i<2; i++)

{

Sleep(5000);

ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); //---- check the current daily bar time

datetime last_day=daytimes[0];

if(Year()==TimeYear(last_day) && Month()==TimeMonth(last_day) && Day()==TimeDay(last_day)) break;

} }

71 if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND) ; if(Period()<PERIOD_D1) dayshift++; }

Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ", TimeToStr(daytimes[dayshift]));

ARRAYDIMENSION

int ArrayDimension( object array[]) Returns the multidimensional array rank. Parameters:

array[] - Array for which the rank will be returned.

Sample: int num_array[10][5]; int dim_size; dim_size=ArrayDimension(num_array); // dim_size=2 ARRAYGETASSERIES

bool ArrayGetAsSeries( object array[])

Returns TRUE if array is organized as a series array (array elements are indexed from the last to the first one), otherwise returns FALSE.

Parameters:

array[] - Array to be checked.

Sample:

if(ArrayGetAsSeries(array1)==true)

Print("array1 is indexed as a series array"); else

Print("array1 is indexed normally (from left to right)");

ARRAYINITIALIZE

int ArrayInitialize( void array[], double value)

Sets all elements of a numeric array to the same value. Returns the count of initialized elements.

Note: It is not recommended to initialize index buffers in the custom indicator init() function as such functions are initialized automatically with an "empty value" at allocation and re-allocation of buffers.

Parameters:

array[] - Numeric array to be initialized. value - New value to be set.

Sample:

//---- initializing of all array elements with 2.1 double myarray[10];

72

ARRAYISSERIES

bool ArrayIsSeries( object array[])

Returns TRUE if the array under check is a series array

(Time[],Open[],Close[],High[],Low[], or Volume[]), otherwise returns FALSE. Parameters:

array[] - Array under check.

Sample:

if(ArrayIsSeries(array1)==false) ArrayInitialize(array1,0); else

{

Print("Series array cannot be initialized!"); return(-1);

}

ARRAYMAXIMUM

int ArrayMaximum( double array[], int count=WHOLE_ARRAY, int start=0) Searches for the element with maximum value. The function returns position of this maximum element in the array.

Parameters:

array[] - The numeric array to search in. count - The amount of elements to search in.

start - Initial search index.

Sample:

double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; int maxValueIdx=ArrayMaximum(num_array);

Print("Max value = ", num_array[maxValueIdx]);

ARRAYMINIMUM

int ArrayMinimum( double array[], int count=WHOLE_ARRAY, int start=0) Searches for the element with minimum value. The function returns position of this minimum element in the array.

Parameters:

array[] - The numeric array to search in. count - The amount of elements to search in.

start - Initial search index.

Sample:

double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; int minValueidx=ArrayMinimum(num_array);

Print("Min value = ", num_array[minValueIdx]);

ARRAYRANGE

int ArrayRange( object array[], int range_index)

Returns the count of elements in the given dimension of the array. Since indexes are zero-based, the size of dimension is 1 greater than the largest index.

73

Parameters:

array[] - Array to check

range_index - Dimension index.

Sample:

int dim_size;

double num_array[10,10,10];

dim_size=ArrayRange(num_array, 1);

ARRAYRESIZE

int ArrayResize( void array[], int new_size)

Sets a new size for the first dimension. If executed successfully, it returns count of all elements contained in the array after resizing, otherwise, returns -1, and array is not resized.

Note: Array declared at a local level in a function and resized will remain unchanged after the function has completed its operation. After the function has been recalled, such array will have a size differing from the declared one.

Parameters:

array[] - Array to resize.

new_size - New size for the first dimension.

Sample:

double array1[][4];

int element_count=ArrayResize(array1, 20); // new size - 80 elements

ARRAYSETASSERIES

bool ArraySetAsSeries( void array[], bool set)

Sets indexing direction of the array. If the set parameter has the TRUE value, the array will be indexed in a reversed order, i.e., the last element has a zero index. The FALSE value sets a standard indexing order. The function returns the previous status.

Parameters:

array[] - The numeric array to set. set - Array indexing order. Sample: double macd_buffer[300]; double signal_buffer[300]; int i,limit=ArraySize(macd_buffer); ArraySetAsSeries(macd_buffer,true);

for(i=0; i<limit; i++)

macd_buffer[i]=iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)- iMA(NULL,0,26,0,MODE_EMA,PRICE_CLOSE,i);

for(i=0; i<limit; i++)

74

ARRAYSIZE

int ArraySize( object array[])

Returns the count of elements contained in the array. For a one-dimensional array, the value to be returned by the ArraySize function is equal to that of ArrayRange(array,0). Parameters:

array[] - Array of any type.

Sample:

int count=ArraySize(array1); for(int i=0; i<count; i++) { // some calculations. } ARRAYSORT int ArraySort(

void array[], int count=WHOLE_ARRAY, int start=0,

int sort_dir=MODE_ASCEND)

Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort(). Parameters:

array[] - The numeric array to be sorted.

count - Count of elements to be sorted.

start - Starting index.

sort_dir - Array sorting direction. It can be any of the following values:

MODE_ASCEND - sort ascending, MODE_DESCEND - sort descending. Sample:

double num_array[5]={4,1,6,3,9};

// now array contains values 4,1,6,3,9 ArraySort(num_array);

// now array is sorted 1,3,4,6,9

ArraySort(num_array,WHOLE_ARRAY,0,MODE_DESCEND); // now array is sorted 9,6,4,3,1

75

CHECKUP

A group of functions that allow determining of the current status of the client terminal, including the environment status of the MQL4 program.

GETLASTERROR

int GetLastError( )

The function returns the last occurred error, then the value of special last_error variable where the last error code is stored will be zeroized. So, the next call for GetLastError() will return 0.

Sample:

int err;

int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN); if(handle<1) { err=GetLastError(); Print("error(",err,"): ",ErrorDescription(err)); return(0); } ISCONNECTED bool IsConnected( )

The function returns the status of the main connection between client terminal and server that performs data pumping. It returns TRUE if connection to the server was successfully established, otherwise, it returns FALSE.

Sample: if(!IsConnected()) { Print("No connection!"); return(0); }

// Expert body that needs the connection opened // ...

ISDEMO

bool IsDemo( )

Returns TRUE if the expert runs on a demo account, otherwise returns FALSE. Sample:

if(IsDemo()) Print("I work at a demo account"); else Print("I work at a real account");

ISDLLSALLOWED

bool IsDllsAllowed( )

Returns TRUE if the function DLL call is allowed for the expert, otherwise returns FALSE.

See also IsLibrariesAllowed(), IsTradeAllowed().

Sample:

76

int MessageBoxA(int hWnd, string szText, string szCaption,int nType);

... ...

if(IsDllsAllowed()==false) {

Print("DLL call is not allowed. Experts cannot run."); return(0);

}

// expert body that calls external DLL functions MessageBoxA(0,"an message","Message",MB_OK);

ISEXPERTENABLED

bool IsExpertEnabled( )

Returns TRUE if expert adwisors are enabled for running, otherwise returns FALSE. Sample: while(!IsStopped()) { ... if(!IsExpertEnabled()) break; } ISLIBRARIESALLOWED bool IsLibrariesAllowed( )

Returns TRUE if the expert can call library function, otherwise returns FALSE. See

also IsDllsAllowed(), IsTradeAllowed().

Sample: #import "somelibrary.ex4" int somefunc(); ... ... if(IsLibrariesAllowed()==false) {

Print("Library call is not allowed."); return(0);

}

// expert body that calls external DLL functions somefunc();

ISOPTIMIZATION

bool IsOptimization( )

Returns TRUE if expert runs in the strategy tester optimization mode, otherwise returns FALSE.

Sample:

77

ISSTOPPED

bool IsStopped( )

Returns TRUE if the program (an expert or a script) has been commanded to stop its operation, otherwise returns FALSE. The program can continue operation for 2.5 seconds more before the client terminal stops its performing forcedly.

Sample:

while(expr!=false) {

if(IsStopped()==true) return(0); // a long run-time cycle

// ... }

ISTESTING

bool IsTesting( )

Returns TRUE if expert runs in the testing mode, otherwise returns FALSE. Sample:

if(IsTesting()) Print("I am testing now");

ISTRADEALLOWED

bool IsTradeAllowed( )

Returns TRUE if the expert is allowed to trade and a thread for trading is not occupied, otherwise returns FALSE.

See also IsDllsAllowed(), IsLibrariesAllowed(), IsTradeContextBusy().

Sample:

if(IsTradeAllowed()) Print("Trade allowed");

ISTRADECONTEXTBUSY

bool IsTradeContextBusy( )

Returns TRUE if a thread for trading is occupied by another expert advisor, otherwise returns FALSE.

See also IsTradeAllowed().

Sample:

if(IsTradeContextBusy()) Print("Trade context is busy. Please wait");

ISVISUALMODE

bool IsVisualMode( )

Returns TRUE if the expert is tested with checked "Visual Mode" button, otherwise returns FALSE.

Sample:

78

UNINITIALIZEREASON

int UninitializeReason( )

Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. The returned values can be ones of Uninitialize reason codes. This function can also be called in function init() to analyze the reasons for deinitialization of the previour launch. Sample: // this is example int deinit() { switch(UninitializeReason()) { case REASON_CHARTCLOSE:

case REASON_REMOVE: CleanUp(); break; // cleaning up and deallocation of all resources.

case REASON_RECOMPILE: case REASON_CHARTCHANGE: case REASON_PARAMETERS:

case REASON_ACCOUNT: StoreData(); break; // prepare to restart

} //... }

79

In document MQL4_Documentation (Page 68-79)