myeatrade

Blog

MQL4 Date & Time functions (2)

A group of functions providing the working with data of the datetime type (integer representing the amount of seconds elapsed from midnight, 1 January, 1970).

 

TimeDay()

int TimeDay(datetime date)

Returns day of month (1 – 31) for the specified date.

Parameters:

date   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int day=TimeDay(D'2003.12.31');
  // day is 31

TimeDayOfWeek()

int TimeDayOfWeek(datetime date)

Returns the zero-based day of week (0 means Sunday,1,2,3,4,5,6) for the specified date.

Parameters:

date   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int weekday=TimeDayOfWeek(D'2004.11.2');
  // day is 2 - Tuesday

TimeDayOfYear()

int TimeDayOfYear(datetime date)

Returns day (1 means 1 January,..,365(6) does 31 December) of year for the specified date.

Parameters:

date   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int day=TimeDayOfYear(TimeCurrent());

TimeHour()

int TimeHour(datetime time)

Returns the hour for the specified time.

Parameters:

time   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int h=TimeHour(TimeCurrent());

TimeMinute()

int TimeMinute(datetime time)

Returns the minute for the specified time.

Parameters:

time   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int m=TimeMinute(TimeCurrent());

TimeMonth()

int TimeMonth(datetime time)

Returns the month number for the specified time.

Parameters:

time   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int m=TimeMonth(TimeCurrent());

TimeSeconds()

int TimeSeconds(datetime time)

Returns the amount of seconds elapsed from the beginning of the minute for the specified time.

Parameters:

time   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int s=TimeSeconds(TimeCurrent());

TimeYear()

int TimeYear(datetime time)

Returns year for the specified date. The returned value can be within the range of 1970 to 2037.

Parameters:

time   -   Datetime as number of seconds elapsed since midnight (00:00:00), January 1, 1970. 

Sample:

  int y=TimeYear(TimeCurrent());

TimeLocal()

datetime  TimeLocal()

Returns local computer time as number of seconds elapsed from 00:00 January 1, 1970.

Note: At the testing, local time is modelled and is the same as the modelled last known server time

Sample:

  if(TimeLocal()-OrderOpenTime()<360) return(0);

MQL4 Date & Time functions (1)

A group of functions providing the working with data of the datetime type (integer representing the amount of seconds elapsed from midnight, 1 January, 1970).

 

Year()

int Year()

Returns the current year, i.e., the year of the last known server time.

Note: At the testing, the last known server time is modelled.

Sample:

  // return if the date is within the range from 1 Jan. to 30 Apr., 2006.
    if(Year()==2006 && Month()<5)
    return(0);

Month()

int Month()

Returns the current month as number (1-January,2,3,4,5,6,7,8,9,10,11,12), i.e., the number of month of the last known server time.

Note: At the testing, the last known server time is modelled.

Sample:

  if(Month()<=5)
    return("the first half year");

Day()

int Day()

Returns the current day of the month, i.e., the day of month of the last known server time.

Note: At the testing, the last known server time is modelled.

Sample:

  if(Day()<5) return(0);

DayOfWeek()

int DayOfWeek()

Returns the current zero-based day of the week (0-Sunday,1,2,3,4,5,6) of the last known server time.

Note: At the testing, the last known server time is modelled.

Sample:

  // does not work on holidays.
  if(DayOfWeek()==0 || DayOfWeek()==6) return(0);

DayOfYear()

int DayOfYear()

Returns the current day of the year (1 means 1 January,..,365(6) does 31 December), i.e., the day of year of the last known server time.

Note: At the testing, the last known server time is modelled.

Sample:

  if(DayOfYear()==245)
    return(true);

Hour()

int Hour()

Returns the hour (0,1,2,..23) of the last known server time by the moment of the program start (this value will not change within the time of the program execution).

Note: At the testing, the last known server time is modelled.

Sample:

  bool is_siesta=false;
  if(Hour()>=12 || Hour()<17)
     is_siesta=true;

Minute()

int Minute()

Returns the current minute (0,1,2,..59) of the last known server time by the moment of the program start (this value will not change within the time of the program execution).

Sample:

  if(Minute()<=15)
    return("first quarter");

Seconds()

int Seconds()

Returns the amount of seconds elapsed from the beginning of the current minute of the last known server time by the moment of the program start (this value will not change within the time of the program execution).

Sample:

  if(Seconds()<=15)
    return(0);

TimeCurrent()

datetime TimeCurrent()

Returns the last known server time (time of incoming of the latest quote) as number of seconds elapsed from 00:00 January 1, 1970.

Note: At the testing, the last known server time is modelled.

Sample:

  if(TimeCurrent()-OrderOpenTime()<360) return(0);

MQL4 Custom indicators (2)

A group of functions used at producing of custom indicators.

These functions cannot be used in experts and scripts.

 

SetIndexDrawBegin()

void SetIndexDrawBegin(int index, int begin)

Sets the bar number (from the data beginning) from which the drawing of the given indicator line must start. The indicators are drawn from left to right. The indicator array values that are to the left of the given bar will not be shown in the chart or in the DataWindow. 0 will be set as default, and all data will be drawn.

Parameters:

index - Line index. Must lie between 0 and 7.
begin - First drawing bar position number.

Sample:

int init()
  {
//---- 2 additional buffers are used for counting.
   IndicatorBuffers(3);
//---- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
   SetIndexDrawBegin(0,SignalSMA);
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
   SetIndexBuffer(0,ind_buffer1);
   SetIndexBuffer(1,ind_buffer2);
   SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
   return(0);
  }

SetIndexEmptyValue()

void SetIndexEmptyValue(int index, double value)

Sets drawing line empty value. Empty values are not drawn or shown in the DataWindow. By default, empty value is EMPTY_VALUE.

Parameters:

index - Line index. Must lie between 0 and 7.
value - New "empty" value.

Sample:

int init()
  {
//---- 2 allocated indicator buffers
    SetIndexBuffer(0,ExtUppperBuffer);
    SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
    SetIndexStyle(0,DRAW_ARROW);
    SetIndexArrow(0,217);
    SetIndexStyle(1,DRAW_ARROW);
    SetIndexArrow(1,218);
//---- 0 value will not be displayed
    SetIndexEmptyValue(0,0.0);
    SetIndexEmptyValue(1,0.0);
//---- displaying in DataWindow
    SetIndexLabel(0,"Fractal Up");
    SetIndexLabel(1,"Fractal Down");
//---- initialization done
   return(0);
  }

SetIndexLabel()

void SetIndexLabel(int index, string text)

Sets drawing line description for showing in the DataWindow and in the tooltip.

Parameters:

index - Line index. Must lie between 0 and 7.
text  - Label text. NULL means that index value is not shown in the DataWindow.

Sample:

//+------------------------------------------------------------------+
//| Ichimoku Kinko Hyo initialization function                       |
//+------------------------------------------------------------------+
int init()
  {
//----
   SetIndexStyle(0,DRAW_LINE);
   SetIndexBuffer(0,Tenkan_Buffer);
   SetIndexDrawBegin(0,Tenkan-1);
   SetIndexLabel(0,"Tenkan Sen");
//----
   SetIndexStyle(1,DRAW_LINE);
   SetIndexBuffer(1,Kijun_Buffer);
   SetIndexDrawBegin(1,Kijun-1);
   SetIndexLabel(1,"Kijun Sen");
//----
   a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan;
   SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);
   SetIndexBuffer(2,SpanA_Buffer);
   SetIndexDrawBegin(2,Kijun+a_begin-1);
   SetIndexShift(2,Kijun);
//---- Up Kumo bounding line does not show in the DataWindow
   SetIndexLabel(2,NULL);
   SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
   SetIndexBuffer(5,SpanA2_Buffer);
   SetIndexDrawBegin(5,Kijun+a_begin-1);
   SetIndexShift(5,Kijun);
   SetIndexLabel(5,"Senkou Span A");
//----
   SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
   SetIndexBuffer(3,SpanB_Buffer);
   SetIndexDrawBegin(3,Kijun+Senkou-1);
   SetIndexShift(3,Kijun);
//---- Down Kumo bounding line does not show in the DataWindow
   SetIndexLabel(3,NULL);
//----
   SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
   SetIndexBuffer(6,SpanB2_Buffer);
   SetIndexDrawBegin(6,Kijun+Senkou-1);
   SetIndexShift(6,Kijun);
   SetIndexLabel(6,"Senkou Span B");
//----
   SetIndexStyle(4,DRAW_LINE);
   SetIndexBuffer(4,Chinkou_Buffer);
   SetIndexShift(4,-Kijun);
   SetIndexLabel(4,"Chinkou Span");
//----
   return(0);
  }

SetIndexShift()

void SetIndexShift(int index, int shift)

Sets offset for the drawing line. For positive values, the line drawing will be shifted to the right, otherwise it will be shifted to the left. I.e., the value calculated on the current bar will be drawn shifted relatively to the current bar.

Parameters:

index - Line index. Must lie between 0 and 7.
shift - Shitf value in bars.

Sample:

//+------------------------------------------------------------------+
//| Alligator initialization function                                |
//+------------------------------------------------------------------+
int init()
  {
//---- line shifts when drawing
   SetIndexShift(0,JawsShift);
   SetIndexShift(1,TeethShift);
   SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
   SetIndexDrawBegin(0,JawsShift+JawsPeriod);
   SetIndexDrawBegin(1,TeethShift+TeethPeriod);
   SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
   SetIndexBuffer(0,ExtBlueBuffer);
   SetIndexBuffer(1,ExtRedBuffer);
   SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
   SetIndexStyle(0,DRAW_LINE);
   SetIndexStyle(1,DRAW_LINE);
   SetIndexStyle(2,DRAW_LINE);
//---- index labels
   SetIndexLabel(0,"Gator Jaws");
   SetIndexLabel(1,"Gator Teeth");
   SetIndexLabel(2,"Gator Lips");
//---- initialization done
   return(0);
  }

SetIndexStyle()

void SetIndexStyle(int index, int type, int style=EMPTY, 
                   int width=EMPTY, color clr=CLR_NONE)

Sets offset for the drawing line. For positive values, the line drawing will be shifted to the right, otherwise it will be shifted to the left. I.e., the value calculated on the current bar will be drawn shifted relatively to the current bar.

Parameters:

index - Line index. Must lie between 0 and 7. 
type  - Shape style. Can be one of Drawing shape styles listed. 
style - Drawing style. It is used for one-pixel thick lines. 
        It can be one of the Drawing shape styles listed. 
        EMPTY value means that the style will not be changed. 
width - Line width. Valid values are: 1,2,3,4,5. 
        EMPTY value means that width will not be changed. 
clr   - Line color. Absence of this parameter means that the color will not be changed. 

Sample:

  SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red);

SetLevelStyle()

void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE)

The function sets a new style, width and color of horizontal levels of indicator to be output in a separate window.

Parameters:

draw_style - Drawing style. Can be one of the Drawing shape styles listed. 
             EMPTY value means that the style will not be changed. 
line_width - Line width. Valid values are 1,2,3,4,5. 
             EMPTY value indicates that the width will not be changed. 
clr        - Line color. Empty value CLR_NONE means that the color will not be changed. 

Sample:

//---- show levels as thick red lines
   SetLevelStyle(STYLE_SOLID,2,Red);

SetLevelValue()

void SetLevelValue(int level, double value)

The function sets a value for a given horizontal level of the indicator to be output in a separate window.

Parameters:

level - Level index (0-31). 
value - Value for the given indicator level. 

Sample:

SetLevelValue(1,3.14);

MQL4 Custom indicators (1)

A group of functions used at producing of custom indicators.

These functions cannot be used in experts and scripts.

 

IndicatorBuffers()

void IndicatorBuffers(int count)

Allocates memory for buffers used for custom indicator calculations. The amount of buffers cannot exceed 8 or be less than the value given in the indicator_buffers property. If custom indicator requires additional buffers for counting, this function must be used for specifying of the total amount of buffers.

Parameters:

count - Amount of buffers to be allocated. Should be within the range between indicator_buffers and 8 buffers.

Sample:

#property  indicator_separate_window
#property  indicator_buffers 1
#property  indicator_color1  Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double     ind_buffer1[];
double     ind_buffer2[];
double     ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- 2 additional buffers are used for counting.
   IndicatorBuffers(3);
//---- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
   SetIndexDrawBegin(0,SignalSMA);
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
   SetIndexBuffer(0,ind_buffer1);
   SetIndexBuffer(1,ind_buffer2);
   SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
   return(0);
  }

IndicatorCounted()

int IndicatorCounted()

The function returns the amount of bars not changed after the indicator had been launched last. The most calculated bars do not need any recalculation. In most cases, same count of index values do not need for recalculation. The function is used to optimize calculating.

Note: The latest bar is not considered to be calculated and, in the most cases, it is necessary to recalculate only this bar. However, there occur some boundary cases where custom indicator is called from the expert at the first tick of the new bar. It is possible that the last tick of the previous bar had not been processed (because the last-but-one tick was being processed when this last tick came), the custom indicator was not called and it was not calculated because of this. To avoid indicator calculation errors in such situations, the IndicatorCounted() function returns the count of bars minus one.

Sample:

  int start()
    {
     int limit;
     int counted_bars=IndicatorCounted();
  //---- check for possible errors
     if(counted_bars<0) return(-1);
  //---- the last counted bar will be recounted
     if(counted_bars>0) counted_bars--;
     limit=Bars-counted_bars;
  //---- main loop
     for(int i=0; i<limit; i++)
       {
        //---- ma_shift set to 0 because SetIndexShift called abowe
        ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
        ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
        ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
       }
  //---- done
     return(0);
    }

IndicatorDigits()

void IndicatorDigits(int digits)

Sets precision format (the count of digits after decimal point) to visualize indicator values. The symbol price preicision is used by default, the indicator being attached to this symbol chart.

Parameters:

digits - Precision format, the count of digits after decimal point.

Sample:

int init()
  {
//---- 2 additional buffers are used for counting.
   IndicatorBuffers(3);
//---- setting of drawing parameters
   SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
   SetIndexDrawBegin(0,SignalSMA);
   IndicatorDigits(Digits+2);
//---- 3 allocated buffers of an indicator
   SetIndexBuffer(0,ind_buffer1);
   SetIndexBuffer(1,ind_buffer2);
   SetIndexBuffer(2,ind_buffer3);
//---- "short name" for DataWindow and indicator subwindow
   IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
   return(0);
  }

IndicatorShortName()

void IndicatorShortName(string name)

Sets the "short" name of a custom indicator to be shown in the DataWindow and in the chart subwindow.

Parameters:

name - New short name.

Sample:

int init()
  {
//---- 2 additional buffers are used for counting.
   IndicatorBuffers(3);
//---- drawing settings
   SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
   SetIndexDrawBegin(0,SignalSMA);
   IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
   SetIndexBuffer(0,ind_buffer1);
   SetIndexBuffer(1,ind_buffer2);
   SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
   IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
   return(0);
  }

SetIndexArrow()

void SetIndexArrow(int index, int code)

Sets an arrow symbol for indicators line of the DRAW_ARROW type.

Arrow codes out of range 33 to 255 cannot be used.

Parameters:

index - Line index. Must lie between 0 and 7. 
code  - Symbol code from Wingdings font or Array constants. 

Sample:

int init()
  {
//---- 2 allocated indicator buffers
    SetIndexBuffer(0,ExtUppperBuffer);
    SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
    SetIndexStyle(0,DRAW_ARROW);
    SetIndexArrow(0,217);
    SetIndexStyle(1,DRAW_ARROW);
    SetIndexArrow(1,218);
//---- displaying in the DataWindow
    SetIndexLabel(0,"Fractal Up");
    SetIndexLabel(1,"Fractal Down");
//---- initialization done
   return(0);
  }

SetIndexBuffer()

bool SetIndexBuffer(int index, double array[])

Binds the array variable declared at a global level to the custom indicator pre-defined buffer. The amount of buffers needed to calculate the indicator is set with the IndicatorBuffers() function and cannot exceed 8. If it succeeds, TRUE will be returned, otherwise, it will be FALSE. To get the extended information about the error, one has to call the GetLastError() function.

Parameters:

index   - Line index. Must lie between 0 and 7. 
array[] - Array that stores calculated indicator values. 

Sample:

  double ExtBufferSilver[];
  int init()
    {
      SetIndexBuffer(0, ExtBufferSilver); // first line buffer
      // ...
    }

MQL4 Conversion functions

A group of functions that provide conversion of data from one format into another.

The NormalizeDouble() function must be specially noted as it provides the necessary accuracy of the price presentation. In trading operations, no unnormalized prices may be used if their accuracy even a digit exceeds that required by the trade server.

 

CharToStr()

string CharToStr(int char_code)

Conversion of the symbol code into a one-character string.

Parameters:

char_code - ASCII char code.

Sample:

  string str="WORL" + CharToStr(44); // 44 is code for 'D'
  // the resulting string will be WORLD

DoubleToStr()

string DoubleToStr(double value, int digits)

Returns text string with the specified numerical value converted into a specified precision format.

Parameters:

value  - Floating point value. 
digits - Precision format, number of digits after decimal point (0-8). 

Sample:

  string value=DoubleToStr(1.28473418, 5);
  // the value is "1.28473"

NormalizeDouble()

double NormalizeDouble(double value, int digits)

Rounds the floating point value to the given precision. Returns normalized value of the double type.

The calculated StopLoss and TakeProfit values, as well as open price of pending orders must be normalized with a precision the value of which is stored in the pre-defined variable of Digits.

Parameters:

value  - Floating point value. 
digits - Precision format, number of digits after decimal point (0-8). 

Sample:

  double var1=0.123456789;
  Print(DoubleToStr(NormalizeDouble(var1,5),8));
  // output: 0.12346000

StrToDouble()

double StrToDouble(string value)

Converts string representation of number to double type (double-precision format with floating point).

Parameters:

value  - String containing the number character representation format.  

Sample:

  double var=StrToDouble("103.2812");

StrToInteger()

int StrToInteger(string value)

Converts string containing the value character representation into a value of the int (integer) type.

Parameters:

value  - String containing the number character representation format.  

Sample:

  int var1=StrToInteger("1024");

StrToTime()

datetime StrToTime(string value)

Converts string in the format "yyyy.mm.dd hh:mi" to datetime type (the amount of seconds that have passed since 1 Jan., 1970).

Parameters:

value  - String value of date/time format as "yyyy.mm.dd hh:mi".  

Sample:

  datetime var1;
  var1=StrToTime("2003.8.12 17:35");
  var1=StrToTime("17:35");      // returns the current date with the given time
  var1=StrToTime("2003.8.12");  // returns the date with the midnight time of "00:00"

TimeToStr()

string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES)

Converts value containing time in seconds that has passed since January 1, 1970, into a string of "yyyy.mm.dd hh:mi" format.

Parameters:

value - Positive amount of seconds that have passed since 00:00, January 1, 1970. 
mode  - Optional data output mode can be one or combination of:
        TIME_DATE gets result as "yyyy.mm.dd",
        TIME_MINUTES gets result as "hh:mi",
        TIME_SECONDS gets result as "hh:mi:ss". 

Sample:

  string var1=TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS);

MQL4 Common functions (2)

General-purpose functions not included into any specialized groups.

 

GetTickCount()

int GetTickCount()

The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer. 

Sample:

  int start=GetTickCount();
  // some hard calculations...
  Print("Calculation time is ", GetTickCount()-start, " milliseconds.");

MessageBox()

int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY)

The MessageBox function creates, displays, and operates message box. The message box contains an application-defined message and header, as well as a random combination of predefined icons and push buttons. If the function succeeds, the returned value is one of the MessageBox return code values.

The function cannot be called from custom indicators since they are executed within interface thread and may not decelerate it.

Parameters:

text    - Optional text that contains the message to be displayed. 
caption - Optional text to be displayed in the header of the dialog box. 
          If this parameter is NULL, the expert name will be displayed in the header. 
flags   - Optional flags that determine the type and behavior of the dialog box. 
          They can represent a conbination of flags from the following groups. 

Sample:

  #include <WinUser32.mqh>
  
  if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false)
    {
     int ret=MessageBox(" ObjectCreate() function returned the "+GetLastError()+" error\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION);
     if(ret==IDNO) return(false);
    }
  // continue

SendFTP()

bool SendFTP(string filename, string ftp_path=NULL)

Sends the file to the FTP server set in the Tools->Options->Publisher tab. If the attempt fails, it retuns FALSE.

The function does not operate in the testing mode. This function cannot be called from custom indicators, either.

The file to be sent must be stored in the terminal_directory\experts\files folder or in its sub-folders.

It will not be sent if there is no FTP address and/or access password specified in settings.

Parameters:

filename - File to be sent. 
ftp_path - FTP path. If the path has not been specified, the path described in settings will be used. 

Sample:

int lasterror=0;
  if(!SendFTP("report.txt"))
    lasterror=GetLastError();

SendMail()

void SendMail(string subject, string some_text)

Sends a message to the e-mail set in the Tools->Options->EMail tab.

The sending can be disabled in settings, or it can be omitted to specify the e-mail address. To get the detailed error information, one has to call the GetLastError() function.

Parameters:

subject   - Subject text. 
some_text - Mail body. 

Sample:

  double lastclose=Close[0];
  if(lastclose<my_signal)
    SendMail("from your expert", "Price dropped down to "+DoubleToStr(lastclose,Digits));

SendNotification()

bool SendNotification(string message)

Sends Push notification to mobile terminals whose MetaQuotes IDs are specified on the "Notifications" tab in options window.

Sending notifications can be disabled in the settings. The ID can also be omitted.

In case of error, the function returns false. To get information about the error, call the GetLastError() function.

Note: The SendNotification() function has strict limitations on its usage: no more than 2 calls per second and no more than 10 calls per minute. Frequency of calls is controlled dynamically, and the function can be blocked in case of violation.

Parameters:

message - Message text up to 255 symbols. 

Sample:

  double lastclose=Close[0];
  if(lastclose<my_signal)
    SendNotification("Price changed "+DoubleToStr(lastclose,Digits));

Sleep()

void Sleep(int milliseconds)

The Sleep() function suspends execution of the current expert within the specified interval.

The Sleep() function cannot be called from custom indicators since they calculate in the interface thread and may not decelerate it.

The checking of the expert stop flag status every 0.1 second has been built into the function.

Parameters:

milliseconds   -   Sleeping interval in milliseconds.

Sample:

//---- wait for 10 seconds
   Sleep(10000);

MQL4 Common functions (1)

General-purpose functions not included into any specialized groups.

 

Alert()

void Alert(...)

Displays a dialog box containing the user-defined data. Parameters can be of any type. Amount of passed parameters cannot exceed 64.

Arrays cannot be passed to the Alert function. Arrays should be output elementwise.

Data of double type output with 4 decimal digits after point. To output with more precision use DoubleToStr() function.

Data of bool, datetime and color types will be output as its numeric presentation.

To output values of datetime type as string convert it by TimeToStr() function.

See also Comment() and Print() functions.

Parameters:

...   -   Any values, separated by commas. It can be up to 64 parameters. 

Sample:

  if(Close[0]>SignalLevel)
    Alert("Close price coming ", Close[0],"!!!");

Comment()

void Comment(...)

The function outputs the comment defined by the user in the left top corner of the chart. Parameters can be of any type. Amount of passed parameters cannot exceed 64.

Arrays cannot be passed to the Comment() function. Arrays should be output elementwise.

Data of double type output with 4 digits after the decimal point. To output with more precision, use the DoubleToStr() function.

Data of bool, datetime and color types will be output as their numeric presentation.

To output values of datetime type as strings, convert them with the TimeToStr() function.

See also Alert() and Print() functions.

Parameters:

...   -   Any values, separated by commas. It can be up to 64 parameters. 

Sample:

  double free=AccountFreeMargin();
  Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current time is ",TimeToStr(TimeCurrent()));

Print()

void Print(...)

Prints a message to the experts log. Parameters can be of any type. Amount of passed parameters cannot exceed 64.

Arrays cannot be passed to the Print() function. Arrays should be printed elementwise.

Data of double type are printed with 4 decimal digits after point. To output more precisely, use the DoubleToStr() function.

Data of bool, datetime and color types will be printed as their numeric presentation.

To print values of datetime type as string, convert them with the TimeToStr() function.

See also Alert() and Comment() functions.

Parameters:

...   -   Any values, separated by commas. It can be up to 64 parameters. 

Sample:

  Print("Account free margin is ", AccountFreeMargin());
  Print("Current time is ", TimeToStr(TimeCurrent()));
  double pi=3.141592653589793;
  Print("PI number is ", DoubleToStr(pi,8));
  // Output: PI number is 3.14159265
  // Array printing
  for(int i=0;i<10;i++)
    Print(Close[i]);

PlaySound()

void PlaySound(string filename)

Function plays a sound file. The file must be located in the terminal_dir\sounds directory or in its subdirectory.

Parameters:

filename - Path to the sound file. 

Sample:

  if(IsDemo()) PlaySound("alert.wav");

MarketInfo()

double MarketInfo(string symbol, int type)

Returns various data about securities listed in the Market Watch window. A part of information about the current security is stored in predefined variables.

Parameters:

symbol - Security symbol. 
type   - Request identifier that defines the type of information to be returned. 
         Can be any of values of request identifiers. 

Sample:

   double bid   =MarketInfo("EURUSD",MODE_BID);
   double ask   =MarketInfo("EURUSD",MODE_ASK);
   double point =MarketInfo("EURUSD",MODE_POINT);
   int    digits=MarketInfo("EURUSD",MODE_DIGITS);
   int    spread=MarketInfo("EURUSD",MODE_SPREAD);

MQL4 Client terminal

Functions returning information about client terminal.

TerminalCompany()

string TerminalCompany()

Returns the name of company owning the client terminal.

Sample:

Print("Company name is ",TerminalCompany());

TerminalName()

string TerminalName()

Returns client terminal name.

Sample:

Print("Terminal name is ",TerminalName());

TerminalPath()

string TerminalPath()

Returns the directory, from which the client terminal was launched.

Sample:

Print("Working directory is ",TerminalPath());

MQL4 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:

  #import "user32.dll"
     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 advisors 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:

  if(IsOptimization()) return(0);

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:

  if(IsVisualMode()) Comment("Visual mode turned on");

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
       }
     //...
    }

MQL4 Array functions (3)

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[]

 

ArrayRange()

int ArrayDimension(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.

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(object &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(double &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++)
   signal_buffer[i]=iMAOnArray(macd_buffer,limit,9,0,MODE_SMA,i);

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(double &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
第 2 页,共 7 页12345...最旧 »
menu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loadermenu image pre-loader