返回列表 回复 发帖 点我体验网上斗地主的乐趣

Hi folks,

Today we are going to study some of important function that MetaTrader has grouped them under the topic "Checkup Functions".

The Checkup functions are a set of functions that are telling you some of useful information about the current statue of the client terminal (for example is dlls calling allowed or not and is the expert advisor allowed or not ) and the MQL4 environment (for example what's the last error has been occurred and is the trade context busy or not).

Let's go ahead and study this group of functions!

 

GetLastError

Syntax

int GetLastError()

 Description: 

The GetLastError function returns the code last error occurred during the execution of the MQL4 program or zero if there was nor errors. After that (after calling it) the last error be set back to zero.

We are going to set aside a separated article for MQL4 error tracking!

Note: To get a text representation of the error code you can use the function ErrorDescription(), but don't to forget to include stdlib.mqh

Note: All of the Checkup functions don't take any parameters, see the examples!

Example

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

 

IsConnected

Syntax

bool IsConnected()

 Description: 

The IsConnected function tells you if the terminal is connected to the server (True) or not (False). You can use it before any code of your Expert Advisor that needs to be connected to the server first.

Example

if(!IsConnected())
{
Print("No connection!");
return(0);
}
// Expert body that needs the connection opened
// ...

 

IsDemo

Syntax

bool IsDemo()

 Description: 

The IsDemo function tells you if the expert advisor runs in demo (True) or live (False) account. You can use this function for instance to protect you trial expert advisor from working in a live account and work only in a demo account.

Example

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

 

IsDllsAllowed

Syntax

bool IsDllsAllowed()

 Description: 

The IsDllsAllowed function tells you if the expert advisor is allowed to call dlls (True) or not (False). To allow dlls calling you go to Tools -> Options -> Expert Advisors then check "Allow DLL Imports" .

Example

#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);

 

 

 

Hi folks,

Today we are going to talk about a very important set of MQL4 functions; the Conversion functions.

Why should I use Conversion functions?

In many of situations you have a variable in a specific format and you want to use it in another format.

For example: When we use the CurTime() function which returns the current server time; it returns this time in datetime format.
It will not problem for us if we are going to use this time as a datatime format for example adding to 2 hours to it or substracting it from the local time.

But if we want to display this time to the user using the Alert() function we will face a problem. the Alert() can't convert automatically from datetime data type to string data type which we want the user to see. In this case we have to use the conversion function TimeToStr().

 

Implicit conversions:

Beside the conversions functions we are going to study I have to mention that MQL4 will make implicit conversions from a data type to other data type when you assign a wrong value for this data type.

For example:

string var1 = 100;
Alert(var1);

In the above code you have assigned an integer to a string variable. MQL4 will convert the number 100 from integer to string.
If you don't sure of that add this line:

Alert(var1+10);

What do you think you'll get? No, not 110 but you will get 10010 (Figure 1). That's because MQL4 has converted the 100 to string and 10 to string then added them to each others as strings.


 

Figure 1

Let's study the conversion function available in MQL4!

 

 

CharToStr

Syntax

string CharToStr( int char_code)

 Description: 

The CharToStr function converts from Char type to string type; it converts  the ASCII char code passed to it to string.

Parameters:

This function takes only one parameter:

 int char_code

The ASCII char code of the character you want to convert it to string.

 Example

for (int cnt = 1 ; cnt < 255 ; cnt++)
{
Print("ASCII code: " + cnt + ": " + CharToStr(cnt));
}

 

DoubleToStr

Syntax

string DoubleToStr( double value, int digits)

 Description: 

The DoubleToStr function converts from double data type to string type; it converts  the double value passed to the function to string with the number of digits passed to the function.

Parameters:

This function takes two parameters:

 double value

The double value you want to convert it to string.

int digits

The number of digits you want the function to use in converting the double value to string. it can be ranged from 0 (no digits) to 8 (8 digits).

 Example

string value=DoubleToStr(1.2345678, 4);
// value is 1.2346

 

NormalizeDouble

Syntax

double NormalizeDouble( double value, int digits)

 Description: 

The NormalizeDouble function rounds the double value passed to it to the number of digits passed. It's like DoubleToStr function but it returns double value instead of string.

Parameters:

This function takes two parameters:

 double value

The double value you want to round it.

int digits

The number of digits you want the function to use in rounding  the double value. it can be ranged from 0 (no digits) to 8 (8 digits).

 Example

double value=1.2345678;
Print(NormalizeDouble(value,5));
// output: 1.2346

 

StrToDouble

Syntax

double StrToDouble( string value)

 Description: 

The StrToDouble function converts from string data type to double type; it converts  the string value passed to the function to a double.

Parameters:

This function takes only one parameter:

 string value

The string value you want convert it to double value.

 Example

double value=StrToDouble("1.2345678");
Print(value);
// output: 1.2346

 

StrToInteger

Syntax

int  StrToInteger( string value)

 Description: 

The StrToInteger function converts from string data type to integer type; it converts  the string value passed to the function to an integer.

Parameters:

This function takes only one parameter:

 string value

The string value you want convert it to integer value.

 Example

double value=StrToInteger("1999");
Print(value);

 

StrToTime

Syntax

datetime StrToTime( string value)

 Description: 

The StrToTime function converts from string data type to datetime data type; the string value passed to the function must be in the format: "yyyy.mm.dd hh:mi"

Parameters:

This function takes only one parameter:

 string value

The string value you want convert it to datatime data type. This string have in one of these formats:
"yyyy.mm.dd hh:mi"
"hh:mi"
"yyyy.mm.dd"
 

 Example

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

 

TimeToStr

Syntax

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

 Description: 

The TimeToStr function converts from datetime data type to string data type; the return string value will be in the format "yyyy.mm.dd hh:mi".

Parameters:

This function takes two parameters:

 datetime value

The datatime value you want to convert it to string. It starts from 00:00 January 1, 1970.

int mode

Optional parameter determine the mode of conversion; what the string format the function will return.
It can be one or combination of these modes:
TIME_DATE the result will be in the format "yyyy.mm.dd",
TIME_MINUTES the result will be in the format"hh:mi",
TIME_SECONDS the result will be in the format "hh:mi:ss".

The default value is TIME_DATE|TIME_MINUTES which means the result will be in the format "yyyy.mm.dd hh:mi".

 Example

 strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);

 

 

 

 

 

 

 

 

Hi folks!

Today we are going to go step by step creating our first MetaTrader extension (dll) in C++, let's don't waste the time and start by defining what's the MetaTrader extension (dll)?

What's the MetaTrader extension (dll)?

 

MQL4 language give you a limited things to do with it and there are a lot of things you can not do in MQL4. To get the full control of your Windows operating system (For example, accessing the window registry or file handling APIs) you have to choices:
 

1- To call/use the windows common dlls and import the functions you want, and this is an example:

#import "user32.dll"
int MessageBoxA(int hWnd, string lpText, string lpCaption, int uType);

In the line above we used the #import keyword to import one of the "user32.dll" function; MessageBoxA function. Then we can use this function in our code like any normal function.
 

2- The second choice is creating our own dll in c++ and use it in our code the same as the common windows dlls. And that's what are we going to learn today.
 

The Tools you need:

 

I tried Visual Basic to create the MetaTrader dll but it failed, the truth is I didn't give it a lot of time and trials because the fact that the Visual Basic is not a real dll (activex) creator.

Note: If you find here any new terms that you don't understand them (like activex), if you can't ignore them you can ask me to explain them to you. But you don't need to know these terms to understand how to create your own dll.

So, the best choice was to use Visual c++, I used Microsoft Visual c++ 6 which you can download free express version of it from here: http://msdn.microsoft.com/vstudio/express/visualc/download/

Note:  The version of Visual C++ used in this tutorial is Microsoft Visual c++ 6 not the express version.

Now let's create our first dll that says "hello world!"

Hello world!

 

1- The first step you have to run Visual C++ (Figure 1).


Figure 1 - Visual C++ 6 

2- Now from File menu choose New and a dialog like that (Figure 2) will appear.


 

Figure 2 - New project dialog 

3- From this dialog choose "MFC AppWizard (dll)" and write a name for the project in the ";Project Name" field (Figure 3) and click "OK".


 

Figure 3 - MFC dll 

Note: You can choose "Win32 Dynamic-Link Library" instead of "MFC AppWizard (dll)" but this means you will not able to use "CString" string type, CString is a string type in MFC that makes the world easier.

4- Another dialog (Figure 4) will appear to you asking you for some option. leave the default options and click "Finish" button. And when the information dialog appear click "OK".


 

Figure 4 - Project options 

5- Congratulation! You have a new project now "demo" project which you can start to write your dll in. Please open the file "demo.cpp" and give it a look.
Now, we are going to write some code in this file:

#define MT4_EXPFUNC __declspec(dllexport)

you put this line after the lines:

#include "stdafx.h"
#include "demo.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

6- Add the end of the file "demo.cpp" and after this line:

CDemoApp theApp;

We are going to write our "Hello" function like that:

MT4_EXPFUNC void __stdcall Hello(char* say)
{
MessageBox(NULL,say,"demo",NULL);
}

 

7- Now we have the function "Hello" which takes a string to say it and returns no thing (void).
But the world want to know our function and in c++ to make the function availabe to the world we have to add the function name in a file called the .def file.
Now open the demo.def file and add this line (the bold line) at the end of the file:

; demo.def : Declares the module parameters for the DLL.

LIBRARY "demo"
DESCRIPTION 'demo Windows Dynamic Link Library'

EXPORTS
; Explicit exports can go here
Hello

8- Compile the dll by pressing F7, if you are a lucky man like me you will not get any errors or warnings. Search for the demo.dll in Debug folder in the Demo project folder.

In the coming article we are going to test our dll and we are going to know more about the data type passed and received to and from the dll that we can use to write more advanced dlls.

Hope you find it a useful article!

Coders' Guru

 

Hi folks!

In the previous part of this article we created step-by-step our first MetaTrader extension (dll) in C++ and in this article we are going to give it a test.

Also we are going to study in this article and the coming article some of the advanced topics briefly (like how to use arrays and structure in your dll).

Hope you are ready for this hard journey which deserves the effort.

Let's test our demo.dll

We are going to write some code to test our demo.dll. These are the steps we have to take before saying "Hello World!"

1- We have the demo.dll in the debug folder in your Visual C++ projects folder. Copy the demo.dll to the library folder ("MetaTrader 4\experts\libraries").

2- Open MetaEditor to create the include file which will hold the declaration of our "Hello" function. This is the code of demo.mqh
 

#import "demo.dll"
void Hello(string say);
#import

Note how we have imported the dll and how we have declared the "Hello" function with the same parameters (string say) and return value (void) as the function in the dll.

This file will be saved at the Include folder (MetaTrader 4\experts\include).

3- Now, let's create the script to test the demo.dll. We are going to name it "Hello.mq4" and it must be saved at the Scripts folder (MetaTrader 4\experts\scripts).

#include <demo.mqh>

int start()
{
Hello ("Hello World!");
return(0);
}

Note how we have started the code by including the demo.mqh file to make it a part of our code.

4- Compile the script (F5) and load it now (double click it in the Navigator window in the Terminal). What did you get? a nice dialog like the one showed in figure 1, if not please check everything or email me!


 

Note: You have to enable the option "Allow DLL imports" in MetaTrader before using any code that import external functions (from the common windows dlls or you custom dlls like our demo.dll) that's by going to Tools -> Options -> Expert Advisors tab then checking "Allow DLL imports" (Figure 2).


 

Advanced Sample (ExpertSample)!

Our demo.dll was a simple one yet it was a completed dll. There's an advanced sample that shipped with MetaTrader program which include advanced programming topics. We are going to study it and thank MetaQuotes for its ideal sample.

You will find the sample of the dll in "MetaTrader 4\EXPERTS\SAMPLES"; the dll (ExpertSample.dll) in the folder "MetaTrader 4\EXPERTS\SAMPLES\ExpertSample", the include file (sampledll.mqh) in "MetaTrader 4\EXPERTS\SAMPLES\INCLUDE" and the script (ExportFunctions.mq4) in "MetaTrader 4\EXPERTS\SAMPLES".

You have to open the source code of the dll (To open the source code double click ExpertSample.dsw file) and give the code a look. You will find it more advanced and to some degree a complex one compared to the demo.dll, but don't be afraid we are going to know everything in the next article.

 

 

Hi folks,

Today we are going to study a very important set of function that handles our custom indicators created in MQL4; the Custom indicator functions.

The Custom indicator functions are a set of functions that we use to set low level properties of the custom indicator we want to code, and they can not be used with the code of Expert Advisors or Scripts.

Let's give these functions a deep look:

 

IndicatorBuffers: 

Syntax

void IndicatorBuffers (int count)

 Description: 

The IndicatorBuffers function allocates the required memory (buffer) needed for the indicator calculation.
The IndicatorBuffers value range from 1 to 8 and it must be equal to or less than the buffers count indicated by the indicator_buffers property.

Note: The difference between the buffers allocated by the indicator_buffers property and  IndicatorBuffers function is that the indicator_buffers property allocate the buffers needed to draw the indicators lines while the IndicatorBuffers allocate the extra buffers that needed for extra calculation.

Parameters:

This function takes only one parameter:

 int count:

The count of the buffers, the range is 1 to 8.

 Example

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

Syntax

int IndicatorCounted()

 Description: 

The IndicatorCounted function returns the amount of the bars that the indicator has been calculated them.
In the first launch of the indicator this count will be 0 because the indicator didn’t calculate any bars yet. And after that it will be the count of total bars on the chart -1.

Parameters:

This function takes no parameters:

Example

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=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//---- done
return(0);
}

 

 

IndicatorDigits: 

Syntax

void IndicatorDigits (int digits)

 Description: 

The IndicatorDigits function sets the count of digits after decimal point (precision format) of the indicator, the default value is the Symbol of the used chart precision format.

Parameters:

This function takes only one parameter:

 int digits:

The count of digits after decimal point.

 Example

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: 

Syntax

void IndicatorShortName (string name)

 Description: 

The IndicatorShortName function sets the text that will be showed on the upper left corner of the separate chart window (Figure 2).

Parameters:

This function takes only one parameter:

 string name:

The text you want to display in the indicator short name.

 Example

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);
}

 

 

 

 

 

Hi folks,

We are going to study today a very important set of MQL4 functions; the Date and Time Functions, which are the functions that returns the local (your computer) and server time.

As an example to show the importance of these function you can manage the time your expert advisor will enter the market and exist from the market. Another example with the aid of these functions you can know how long a position has been opened by subtracting the order opened time (returned by the function OrderOpenTime) from the current time (returned by he function CurTime which we are going to study it later).
There are a lot of useful usages of the date and time function that can't be listed here.

Before we dig into studying the date and time function we have to review the datetime data type because it's the cornerstone of understanding how the date and time is calculating in MQL4.

datatime data type:

datetime data type is a special MQL4 data type, which holds a date and time data. You set the datetime variable by using the keyword (D) followed by two signal quotations ('). Between the two signal quotations you write a character line consisting of 6 parts for value of year, month, date, hour, minutes, and seconds. datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.

For example:

D'2004.01.01 00:00' // New Year
D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12' //equal to D'1980.07.19 12:00:00'
D'01.01.2004' //equal to D'01.01.2004 00:00:00'

 

We use the keyword datetime to create a datetime variable.

For example:

datetime dtMyBirthDay= D'1972.10.19 12:00:00';
datetime dt1= D'2005.10.22 04:30:00';

 

 

Now, let's give the date and time functions a study trip:

 

CurTime:

 

Syntax

datetime CurTime( )

 Description: 

The CurTime function returns the current server time, it's not always the exact current server time but it's the last know server time that the terminal has been retrieved it from the server with the last price quotation.

The return value of the CurTime function is a datetime data type and it's the number of seconds elapsed from 00:00 January 1, 1970.

What if you used this function (and all the date & time functions) in the testing mode - Back Testing?
In the testing mode the server time will be modeled by the tester.

Parameters:

This function takes no parameters and return datetime value.

Example

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

 

Day:

 

Syntax

int Day( )

 Description: 

The Day function returns the current day of the month (1, 2, 3, 4, ..... 31) of the last known server time.
The day is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

DayOfWeek:

 

Syntax

int DayOfWeek( )

 Description: 

The DayOfWeek function returns the current day of the week of the last know server time:

0 = Sunday
1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday

The day of week is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

DayOfYear:

 

Syntax

int DayOfYear( )

 Description: 

The DayOfYear function returns the current day of the year (1, 2, 3, .... 365 (366) ) of the last know server time.
The day of year is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

Hour:

 

Syntax

int Hour( )

 Description:

The Hour function returns the current hour (0, 1, 2, .... 23 ) of the last know server time.
The hour is modeled in the testing mode.

Note: The hour returned by the Hour function is the hour of the moment the program start and will not change during the execution of the program.

Parameters:

This function takes no parameters and return integer value.

 Example

if(Hour()>=12 || Hour()<17) return(true);

 

LocalTime:

 

Syntax

datetime LocalTime( )

 Description: 

The LocalTime function returns the current local computer time. The return value of the LocalTime function is a datetime data type and it's the number of seconds elapsed from 00:00 January 1, 1970.
The local time is modeled in the testing mode as well as the server time.

Parameters:

This function takes no parameters and return datetime value.

Example

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

 

Minute:

 

Syntax

int Minute( )

 Description: 

The Minute function returns the current minute (0, 1, 2, .... 59 ) of the last know server time. Like the Hour function the minute returned by the Minute function is the minute of the moment the program start and will not change during the execution of the program.
The minute is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

Month:

 

Syntax

int Month( )

 Description: 

The Month function returns the current month (0, 1, 2, 3, .... 12 ) of the last know server time.
The month is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

Seconds:

 

Syntax

int Seconds( )

 Description: 

The Seconds  function returns the current seconds (0, 1, 2, .... 59 ) of the minute of the last know server time. Like the Hour and the Minute functions the seconds returned by the Seconds function is the second of the moment the program start and will not change during the execution of the program.
The minute is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

Year:

 

Syntax

int Year( )

 Description: 

The Year function returns the current year of the last know server time.
The year is modeled in the testing mode.

Parameters:

This function takes no parameters and return integer value.

Example

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

 

TimeDay:

 

Syntax

int TimeDay(datetime date)

 Description: 

The TimeDay function returns the day of the month (1, 2, 3, ... 31) of the given date. It extracts the day of the month from the given date

Parameters:

datetime date:

The date (datetime data type) you want to extract the day of the month from.

Example

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

 

TimeDayOfWeek:

 

Syntax

int TimeDayOfWeek(datetime date)

 Description:

The TimeDayOfWeek function returns the day of the week (0,1, 2, .... 6) of the given date. It extracts the day of the week from the given date

Parameters:

datetime date:

The date you want to extract the day of the week from.

Example

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

 

TimeDayOfYear:

 

Syntax

int TimeDayOfYear(datetime date)

 Description:

The TimeDayOfYear function returns the day of the year (1, 2, 3, .... 365 (366)) of the given date. It extracts the day of the year from the given date

Parameters:

datetime date:

The date you want to extract the day of the year from.

Example

int day=TimeDayOfYear(CurTime());

 

TimeHour:

 

Syntax

int TimeHour(datetime date)

 Description: 

The TimeHour function returns the hour of the day (0,1, 2, .... 23) of the given date. It extracts the hours of the day from the given date

Parameters:

datetime date:

The date you want to extract the hour of the day from.

Example

int h=TimeHour(CurTime());

 

TimeMinute:

 

Syntax

int TimeMinute(datetime date)

 Description: 

The TimeMinute function returns the minute of the hour (0,1, 2, .... 59) of the given date. It extracts the minute of the hour from the given date

Parameters:

datetime date:

The date you want to extract the minute of the hour from.

Example

int m=TimeMinute(CurTime());

 

TimeMonth:

 

Syntax

int TimeMonth(datetime date)

 Description: 

The TimeMonth function returns the month of the year (1, 2, 3, .... 12) of the given date. It extracts the month of the year from the given date

Parameters:

datetime date:

The date you want to extract the month of the year from.

Example

int m=TimeMonth(CurTime());

 

TimeSeconds:

 

Syntax

int TimeSeconds(datetime date)

 Description: 

The TimeSeconds function returns the seconds of the minute (0,1, 2, .... 59) of the given date. It extracts the seconds of the minute from the given date

Parameters:

datetime date:

The date you want to extract the seconds of the minute from.

Example

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

 

TimeYear:

 

Syntax

int TimeYear(datetime date)

 Description: 

The TimeYear function returns the year of the given date. It extracts the year from the given date

Parameters:

datetime date:

The date you want to extract the year from.

Example

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

 

Hope you enjoyed the lesson!

Coders Guru 

Hi folks,

One of the most important keys (if not the most important one) of success trading is the Money Management technique you apply to your trading operations.

The Money Management is how to handle the money you put in one or more trades, where you put more money in the good trades and put less money in the bad trades. And at the same time how to handle the capital you using in your trading account where you spend more when you have more balance and spend less when you have less balance.

The most of traders think first in when to buy/sell but the successful ones think first how manage the risk before buying/selling
The Money Management briefly is the art of handling the size of the trade


Because we are in the development section we are taking another approach of talking about the Money Management, we are going to talk about a MQL4 code which enable us to apply our Money Managements and Risk controller techniques in the case of writing an expert advisor.

We have a simple here in MQL4.

//+------------------------------------------------------------------+
//| EMA_CROSS_2.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+


#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"
#define MAGICMA 20060306



//---- Trades limits
extern double TakeProfit=180;
extern double TrailingStop=30;
extern double StopLoss=70;
extern bool UseStopLoss = false;

extern double HedgingTakeProfit=20;
extern double HedgingStopLoss=10;
extern bool UseHedging = true;
extern bool ContinuesHedging = true;


//---- EMAs paris
extern int ShortEma = 10;
extern int LongEma = 80;

//---- Crossing options
extern bool ImmediateTrade = true; //Open trades immediately or wait for cross.
extern bool CounterTrend = true; //Use the originally CounterTrend crossing method or not

//---- Money Management
extern double Lots = 1;
extern bool UseMoneyManagement = true; //Use Money Management or not
extern bool AccountIsMicro = false; //Use Micro-Account or not
extern int Risk = 10; //10%

//---- Time Management
extern bool UseHourTrade = false;
extern int FromHourTrade = 8;
extern int ToHourTrade = 18;

extern bool Show_Settings = true;
extern bool Summarized = false;
extern double slippage = 3;


//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
if(Show_Settings && Summarized == false) Print_Details();
else if(Show_Settings && Summarized) Print_Details_Summarized();
else Comment("");
//----

return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}

bool isNewSumbol(string current_symbol)
{
//loop through all the opened order and compare the symbols
int total = OrdersTotal();
for(int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
string selected_symbol = OrderSymbol();
if (current_symbol == selected_symbol)
return (False);
}
return (True);
}

int Crossed()
{
double EmaLongPrevious = iMA(NULL,0,LongEma,0,MODE_EMA, PRICE_CLOSE, 1);
double EmaLongCurrent = iMA(NULL,0,LongEma,0,MODE_EMA, PRICE_CLOSE, 0);
double EmaShortPrevious = iMA(NULL,0,ShortEma,0,MODE_EMA, PRICE_CLOSE, 1);
double EmaShortCurrent = iMA(NULL,0,ShortEma,0,MODE_EMA, PRICE_CLOSE, 0);

if(ImmediateTrade)
{
if (EmaShortCurrent<EmaLongCurrent)return (1); //down trend
if (EmaShortCurrent>EmaLongCurrent)return (2); //up trend
}

if (EmaShortPrevious>EmaLongPrevious && EmaShortCurrent<EmaLongCurrent ) return (1); //down trend
if (EmaShortPrevious<EmaLongPrevious && EmaShortCurrent>EmaLongCurrent ) return (2); //up trend

return (0); //elsewhere
}


//--- Bassed on Alex idea! More ideas are coming
double LotSize()
{
double lotMM = MathCeil(AccountFreeMargin() * Risk / 1000) / 100;

if(AccountIsMicro==false) //normal account
{
if (lotMM < 0.1) lotMM = Lots;
if ((lotMM > 0.5) && (lotMM < 1)) lotMM=0.5; //Thanks cucurucu
if (lotMM > 1.0) lotMM = MathCeil(lotMM);
if (lotMM > 100) lotMM = 100;
}
else //micro account
{
if (lotMM < 0.01) lotMM = Lots;
if (lotMM > 1.0) lotMM = MathCeil(lotMM);
if (lotMM > 100) lotMM = 100;
}

return (lotMM);
}

string BoolToStr ( bool value)
{
if(value) return ("True");
else return ("False");
}
void Print_Details()
{
string sComment = "";
string sp = "----------------------------------------\n";
string NL = "\n";

sComment = sp;
sComment = sComment + "TakeProfit=" + DoubleToStr(TakeProfit,0) + " | ";
sComment = sComment + "TrailingStop=" + DoubleToStr(TrailingStop,0) + " | ";
sComment = sComment + "StopLoss=" + DoubleToStr(StopLoss,0) + " | ";
sComment = sComment + "UseStopLoss=" + BoolToStr(UseStopLoss) + NL;
sComment = sComment + sp;
sComment = sComment + "ImmediateTrade=" + BoolToStr(ImmediateTrade) + " | ";
sComment = sComment + "CounterTrend=" + BoolToStr(CounterTrend) + " | " ;
if(UseHourTrade)
{
sComment = sComment + "UseHourTrade=" + BoolToStr(UseHourTrade) + " | ";
sComment = sComment + "FromHourTrade=" + DoubleToStr(FromHourTrade,0) + " | ";
sComment = sComment + "ToHourTrade=" + DoubleToStr(ToHourTrade,0) + NL;
}
else
{
sComment = sComment + "UseHourTrade=" + BoolToStr(UseHourTrade) + NL;
}


sComment = sComment + sp;
sComment = sComment + "Lots=" + DoubleToStr(Lots,0) + " | ";
sComment = sComment + "UseMoneyManagement=" + BoolToStr(UseMoneyManagement) + " | ";
sComment = sComment + "AccountIsMicro=" + BoolToStr(AccountIsMicro) + " | ";
sComment = sComment + "Risk=" + DoubleToStr(Risk,0) + "%" + NL;
sComment = sComment + sp;

Comment(sComment);
}

void Print_Details_Summarized()
{
string sComment = "";
string sp = "----------------------------------------\n";
string NL = "\n";

sComment = sp;
sComment = sComment + "TF=" + DoubleToStr(TakeProfit,0) + " | ";
sComment = sComment + "TS=" + DoubleToStr(TrailingStop,0) + " | ";
sComment = sComment + "SL=" + DoubleToStr(StopLoss,0) + " | ";
sComment = sComment + "USL=" + BoolToStr(UseStopLoss) + NL;
sComment = sComment + sp;
sComment = sComment + "IT=" + BoolToStr(ImmediateTrade) + " | ";
sComment = sComment + "CT=" + BoolToStr(CounterTrend) + " | " ;
if(UseHourTrade)
{
sComment = sComment + "UHT=" + BoolToStr(UseHourTrade) + " | ";
sComment = sComment + "FHT=" + DoubleToStr(FromHourTrade,0) + " | ";
sComment = sComment + "THT=" + DoubleToStr(ToHourTrade,0) + NL;
}
else
{
sComment = sComment + "UHT=" + BoolToStr(UseHourTrade) + NL;
}


sComment = sComment + sp;
sComment = sComment + "L=" + DoubleToStr(Lots,0) + " | ";
sComment = sComment + "MM=" + BoolToStr(UseMoneyManagement) + " | ";
sComment = sComment + "AIM=" + BoolToStr(AccountIsMicro) + " | ";
sComment = sComment + "R=" + DoubleToStr(Risk,0) + "%" + NL;
sComment = sComment + sp;

Comment(sComment);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

if (UseHourTrade)
{
if (!(Hour()>=FromHourTrade && Hour()<=ToHourTrade))
{
Comment("Time for trade has not come yet!");
return(0);
}
}

int cnt, ticket, ticket2, total;

string comment = "";
if(CounterTrend==true) comment = "EMAC_Counter";
if(CounterTrend==false) comment = "EMAC_Pro";
if(ImmediateTrade==true) comment = comment + "_Immediate";
if(ImmediateTrade==false) comment = comment + "Postponed";

if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(TakeProfit<10)
{
Print("TakeProfit less than 10");
return(0); // check TakeProfit
}

int isCrossed = 0;
isCrossed = Crossed ();

if(CounterTrend==false)
{
if(isCrossed==1) isCrossed=2;
if(isCrossed==2) isCrossed=1;
}

if(UseMoneyManagement==true) Lots = LotSize(); //Adjust the lot size

total = OrdersTotal();

if(total < 1 || isNewSumbol(Symbol()))
{
if(isCrossed == 1)
{

if(UseStopLoss)
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,slippage,Ask-StopLoss*Point,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);
else
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,slippage,0,Ask+TakeProfit*Point,comment,MAGICMA,0,Green);

if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());

if(UseHedging) Hedge(ticket,Lots);

return(0);
}
if(isCrossed == 2)
{
if(UseStopLoss)
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,slippage,Bid+StopLoss*Point,Bid-TakeProfit*Point,comment,123,0,Red);
else
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,slippage,0,Bid-TakeProfit*Point,comment,MAGICMA,0,Red);

if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());

if(UseHedging) Hedge(ticket,Lots);

return(0);
}
return(0);
}




for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

if(OrderType()<=OP_SELL && OrderSymbol()==Symbol() && OrderMagicNumber() == MAGICMA)
{
if(OrderType()==OP_BUY) // long position is opened
{
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}

if(ContinuesHedging && OrdersCount(Symbol()) < 2)
{
//Print(OrdersCount(Symbol()));
for(cnt=0;cnt<total;cnt++)
{
ticket = OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol() == Symbol())
Hedge(OrderTicket(),OrderLots());
}
}

return(0);
}
//+------------------------------------------------------------------+

int OrdersCount(string symbol)
{
int total = OrdersTotal();
int count =0;
for(int cnt = 0 ; cnt < total ; cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if (symbol == OrderSymbol())
count++;
}
return (count);
}

void Hedge (int order_ticket , double hlots)
{
int ticket, order_type;
double order_profit;
string hcomment = "EMAC_" + Symbol() + "_Hedging";

if(OrderSelect(order_ticket,SELECT_BY_TICKET,MODE_TRADES))
{
order_type = OrderType();
order_profit = OrderProfit();

if(order_type == OP_SELL && order_profit < 0 - slippage)
{
ticket=OrderSend(Symbol(),OP_BUY,hlots,Ask,slippage,Ask-HedgingStopLoss*Point,Ask+HedgingTakeProfit*Point,hcomment,123,0,Yellow);

if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("Hedgin BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening Hedgin BUY order : ",GetLastError());
}

if(order_type == OP_BUY && order_profit < 0 - slippage)
{

ticket=OrderSend(Symbol(),OP_SELL,hlots,Bid,slippage,Bid+HedgingStopLoss*Point,Bid-HedgingTakeProfit*Point,hcomment,MAGICMA,0,Gold);

if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("Hedgin SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening Hedgin SELL order : ",GetLastError());
}

}
}

中间的为字母P

Hi folks,

Today we are going to take an idea to create Expert Advisor (That the Expert Advisors are for).

The idea:

 

How to protect my profits of all opening orders (if there's any) by the mean I want to take them when they reach a specific amount and close all the trades when the drop down to a specific amount.

For example: There are 4 opened positions and they make profit. They've made 200 Pip right now. suddenly the profit went to 150 then 100 then I'm losing money.

Our code today will prevent this situation, let's see the idea programicaly.

The problem:

 

First we want a way to calculate the profit of all opened positions.

When the profit goes to specific amount we are going to close all the opened position. But, we want the program too to prevent the profit to drop again. So, we want to set another profit point that the program will prevent any drops below it.

For example: the program will take the profit when it reaches 200 Pips and prevent the profit to drop below to 100 Pips .

The programming problem now is when to start preventing the profit drop. How to tell the program that the profit went over 100 Pip and we don't want it drop back?

We need a third point when the profit reach it the program will start to monitor the profit drop.

The example right now is: the program will take the profit when it reaches 200 Pips and start to monitor the drop down of the profit when the profit reaches 150 Pips and prevent the profit to drop again to 100 Pips level.

Let's convert that to code!

The code:

 

Please download the code. I've added the profit protector code to a normal expert advisor of mine. We will not study the expert advisor strategy in buying/selling/closing/trailing. But we are going to study the code aimed to protect the profit.

These are the pieces of code concerning our idea:

.....//your normal code

extern double    ProfitToProtect = 200;
extern double    ProtectStarter = 150;
extern double    LossToProtect = 100;
extern bool      ProtectProfit= true;

bool      ProtectLoss= false;

.....//your normal code

int start()
{
...... //your normal code

if(ProtectProfit)
   ProfitProtect(ProfitToProtect);
   
   if(ProtectLoss)
   LossProtect(LossToProtect);
.......//your normal code
}

void ProfitProtect(double profit)
{
      int total  = OrdersTotal();
      double MyCurrentProfit=0;
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            MyCurrentProfit += OrderProfit();
      }
      
      if(MyCurrentProfit>=ProtectStarter) //start protection at this level!
         ProtectLoss=true;
      if(MyCurrentProfit>=profit)
         CloseAll();
}

void LossProtect(double profit)
{
      int total  = OrdersTotal();
      double MyCurrentProfit=0;
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            MyCurrentProfit += OrderProfit();
      }
      if(MyCurrentProfit<=profit)
         CloseAll();
}

void CloseAll()
{
      int total  = OrdersTotal();
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(0,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            if(OrderType()==OP_BUY)
             OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,  Violet);
            if(OrderType()==OP_SELL)   
             OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,  Violet);
      }

 

Code study:

 

We have defined our profit point as external variables at the top of the program:

extern double    ProfitToProtect = 200;
extern double    ProtectStarter = 150;
extern double    LossToProtect = 100;
extern bool      ProtectProfit= true;

Where the the ProfitToProtect is the amount we want the program to take the profit when it is reached. And the ProtectStarter is the amount the program start at monitoring the profit to prevent drop down again. And finally the LossToProtect is the amount of the profit the program prevent the profit to drop below it.

We have added the option to the user to use our profit protector or not with the variable ProtectProfit;

bool      ProtectLoss= false;

We have declared this variable outside the start() function to make it in a global scope and we will use this variable to start the profit monitoring.

if(ProtectProfit)
   ProfitProtect(ProfitToProtect);

If the user has chosen to use our protect (ProtectProfit=True) then the program will call the function ProfitProtect(). We are going to study this function soon.

if(ProtectLoss)
   LossProtect(LossToProtect);

If the ProtectLoss variable is true (It will be true when the profit reaches the ProtectStarter level) then the program will call the function LossProtect() which we are going to study it soon.

void ProfitProtect(double profit)
{
      int total  = OrdersTotal();
      double MyCurrentProfit=0;
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            MyCurrentProfit += OrderProfit();
      }
      
      if(MyCurrentProfit>=ProtectStarter) //start protection at this level!
         ProtectLoss=true;
      if(MyCurrentProfit>=profit)
         CloseAll();
}

The ProfitProtect() function takes a double parameter (profit you want to protect).
It starts by getting the number of opened orders by calling the function OrdersTotal()
then it declares a double variable MyCurrentProfit  and initialize it to 0. We will use this variable to calculate the profit of the opened positions.

Now we enter in loop from 0 to the count of the opened positions. In every loop we select the order using OrderSelect() function and examine is the MagicNumber of the order is the same as our MagicNumber variable to be sure that we are working only with the positions have been opened with our Expert Advisor. Then we get the profit of the order using OrderProfit() and add it to the MyCurrentProfit variable.

Now we have the total profit stored in the MyCurrentProfit variable, We can check it now to find did it reach the ProtectStarter value; if true we will enable ProtectLoss. And we have to check the MyCurrentProfit variable against ProfitToProtect variable to find did it reach it or not; if true we will call the CloseAll() function which will close all the opened positions.

void LossProtect(double profit)
{
      int total  = OrdersTotal();
      double MyCurrentProfit=0;
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            MyCurrentProfit += OrderProfit();
      }
      if(MyCurrentProfit<=profit)
         CloseAll();
}

The LossProtect() function is very like the ProfitProtect() function, the only difference is it will monitor the MyCurrentProfit value and close all the opened position if it goes below the LossToProtect vlaue.

void CloseAll()
{
      int total  = OrdersTotal();
      for (int cnt = 0 ; cnt < total ; cnt++)
      {
         OrderSelect(0,SELECT_BY_POS,MODE_TRADES);
         if (OrderMagicNumber() == MagicNumber)
            if(OrderType()==OP_BUY)
             OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,  Violet);
            if(OrderType()==OP_SELL)   
             OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,  Violet);
      }

 

The CloseAll() function goes through all the opened position and check them against our expert MagicNubmer then close every buy or sell position using OrderClose() function.

I hope everything is clear, And hope you find it a useful idea!

Coders Guru

 

Hi folks,

Today we are going to study a very important set of functions that enables us to work with external files from the MQL4 programs; the File functions.

Directories limitation:

One of annoying feature of MQL4 that the directories limitation; you can't work with files that outside one of these three directories:

  • Terminal_Install_Dir/HISTORY/<current broker>
    Works with FileOpenHistory() function.
  • Terminal_Install_Dir/EXPERTS/FILES
    The common directory for file saving and opening.
  • Terminal_Install_Dir/TESTER/FILES
    The directory of testing files.

MetaTrader thinks it's safer to limit the directories you can access from the normal MQL4 program and give you the ability to write your MQL4 extension (dll) to do what do you want.

Note: I've wrote a dll that enable you to work with files outside the limited directories of MQL4, you can know more by going there: http://www.forex-tsd.com/tools-u ... ns-replacement.html

There are a lot of functions to study in this section, so, we are going to divide this lesson to two parts each of them study the half of File functions. Let's start this part of the lesson.

 

FileOpen: 

Syntax

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

 Description: 

The FileOpen function opens the given file for a specific mode (purpose) and returns its handle.
You pass to the FileOpen function the file name you want to open; this file must be located in Terminal_Install_Dir/EXPERTS/FILES or Terminal_Install_Dir/TESTER/FILES and their subdirectories.

You open the file for writing, reading or both and you determine that with the mode parameter.

The returned value of the FileOpen function is the file handle if the function successes and -1 if failed. File handle is a unique number assigned for the file which you will use with the most of the File functions to work with the opened file.

Parameters:

This function takes three parameters:

 string filename:

The file name you want to open.

int mode:

The purpose you want to open the file for, there are four modes which you can use and combine them:

FILE_CSV: use this mode to open the csv (Comma-separated values) file format.

FILE_BIN: use this mode to open the binary file format.

FILE_READ: use this mode to open the file for reading (getting data from the file).

FILE_WRITE: use this mode to open the file for writing (saving data to the file).

Note 1: You can not combine the FILE_CSV and FILE_BIN in mode parameter.

Note 2: If you open the file with FILE_WRITE and the file wasn't exist a new file with the filename parameter will be created.

Note 3: If you open an existing file with FILE_WRITE mode (without combining it with FILE_READ) the data in the file will be deleted and will be empty file. If you want to add (append) data to an existing file you have to open it with the combination of FILE_WRITE and FILE_READ.

Note 4: You can not use FILE_READ mode with not existing file.

Note 5: You can open more than 32 files from the same program and you can't use the file handles returned from a program with another program.

int delimiter:

In the case of opening csv the delimiter is the character that separates the data, the default value is ";" delimiter.

 Example

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);
}

 

FileClose: 

Syntax

void FileClose(int handle)

 Description: 

The FileClose function closes the given file; you pass to it the file handle (you've got this handle when you opened the file with FileOpen function) and it will close it.

Parameters:

This function takes only one parameter:

 int handle:

The handle of the opened file you want to close.

 Example

int handle=FileOpen("filename", FILE_CSV|FILE_READ);
if(handle>0)
{
// working with file ...
FileClose(handle);
}

 

 

 

Hi folks,

Today we are going to study a set of MQL4 functions which needs to be clearer for the new comers to the language. We are going to study the Global variables and the MQL4 functions that handle them.

 

What are the global variables?

 

The global variables are places to store data between the instances of MQL4 programs and MetaTrader launches too.

In MQL4 you use the normal variables to store the data temporary and it exists only at the time that program is running and vanishes with the un-initialization of the program. But the global variables exist when you un-initialize the program and even if you shut down the terminal itself. The terminal can store the global variables for four weeks from the last store.

 

How useful the global variables?

 

The main job of the global variables is enabling the inner communication between the experts advisor.

 

Assume that you have created two expert advisors:

The first expert advisor works on daily time frame and buys the EURUSD when the Moving Averages of the price of the last 10 days crosses upward the Moving Averages of the price of the last 80 days.

And it sells the EURUSD when the Moving Averages of the price of the last 10 days crosses downward the Moving Averages of the price of the last 80 days.

 

And the second expert advisor works on 1 hour time frame and buys the EURUSD when the Moving Averages of the price of the last 10 hours crosses upward the Moving Averages of the price of the last 80 hours.

And it sells the EURUSD when the Moving Averages of the price of the last 10 hours crosses downward the Moving Averages of the price of the last 80 hours.

 

You don't want the two expert advisors to take conflicted decisions. You don't want the first expert advisor to sell the EURUSD while the second expert advisor is buying the EURUSD.

 

Any of the two expert advisors doesn't know anything about the other. How can they communicate?

They can communicate with the aid of writing/reading global variables.

For instance the first expert advisor can write a global variable when it open sell/buy order while the second expert advisor can read this variable to be sure that it will not open a conflicting orders.

 

Of course the possibilities of using global variables are not limited. Our example today will use the global variables in a very useful way.

 

Our example:

When you attach an expert advisor to more than one chart/pair and want to change one of the expert advisor inputs values for all the charts you have to change this input for every chart.

If your expert advisor attached to ten pairs it will be a real problem to make the change 10 times.

Our program today will use the global variables to make the changes available to all the charts hold our expert advisor.

 

 

Global variables functions:

There are 6 functions in MQL4 responsible of handling the global variables. These are the global variables functions:

 

GlobalVariableCheck:

Syntax:

bool GlobalVariableCheck (string name)

Description:

The GlobalVariableCheck function checks if there's a global variable with the name passed to, it returns true if it exists and false if not exists.

You can use GetLastError to get the error information if any error has been occurred will you calling this function.

Parameters:

This function takes only one parameter:

string name

The global variable name the function will check is it exists or not.

Example:
 

if(!GlobalVariableCheck("ge_TakeProfit "))

Alert("ge_TakeProfit global variable is not exist");

 
 

GlobalVariableDel:

Syntax:
 

bool GlobalVariableDel (string name)

Description:
 

The GlobalVariableDel function deletes the global variable you passed its name and return true in success and false if it failed to delete it.

You can use GetLastError to get the error information if any error has been occurred will you calling this function.
 

Note: If the global variable not found the returned value will be 0 while the error code will be 4057 which means global variables processing error.
 

Parameters:

This function takes only one parameter:

string name

The global variable name the function will delete.
 

Example:
 

Alert(GlobalVariableDel("ge_TakeProfit "));

 
 

GlobalVariableGet:

Syntax:
 

double GlobalVariableGet (string name)

 

Description:
 

The GlobalVariableGet function returns the value of the global variable name passed to it. This value must to be double data type.

You can use GetLastError to get the error information if any error has been occurred will you calling this function.

 

Note: You can store in the global variable and data type but the double data type. And if you tried to store any data type other than the double data type, MQL4 will try to convert it to double data type.
 

Note: If the global variable not found the returned value will be 0 while the error code will be 4058 which means global variable not found. So, you have to use GlobalVariableCheck function before using GlobalVariableGet if your variable maybe 0.

 

Parameters:

This function takes only one parameter:

string name

The global variable name the function will return its stored value.

Example:
 

if(GlobalVariableCheck("ge_TakeProfit"))

   TakeProfit = GlobalVariableGet("ge_TakeProfit");

 
 

GlobalVariableSet:

Syntax:
 

datetime GlobalVariableSet (string name, double value)

 

Description:
 

The GlobalVariableSet function sets the variable name passed to it with the value passed to it.

If the global variable name does not exist the function will create it and set it to the passed value. If it exists the function will change its old value to the new one.

The returned value is a datetime data type which is the time of the last access time of the global variable if the function successes and if it failed the return value will be 0.

You can use GetLastError to get the error information if any error has been occurred will you calling this function.
 

Parameters:

This function takes two parameters:

string name

The global variable name the function will set its value (or create it and sets its value).

double value

The value of the global variable you want to set (or create). This value must be double (numeric) data type.
 

Example:
 

Alert(GlobalVariableDel("ge_TakeProfit "));

 

 

GlobalVariableDel:

Syntax:
 

bool GlobalVariableDel (string name)

 

Description:
 

The GlobalVariableDel function deletes the global variable you passed its name and return true in success and false if it failed to delete it.

You can use GetLastError to get the error information if any error has been occurred will you calling this function.
 

Note: If the global variable not found the returned value will be 0 while the error code will be 4057 which means global variables processing error.
 

Parameters:

This function takes only one parameter:
 

string name

The global variable name the function will delete.

 

Example:
 

Alert(GlobalVariableDel("ge_TakeProfit "));

 

 

Kalenzo's picture
Metatrader 4

Many people are asking me how to create a label or other object in the separate window so I will describe it now. First we will see what can be created using labels.


As we see on the example, label can be put at any place on the chart. Label can be put at any window that u want to. You can point the window on which label should be put. But let's start from the begining.



What is label?

Label is an object. It means that when u draw label (manual or by script), u can change it's properties. U can change the color, and placement, even the shape of it. The second very important property of the object is that he don't vanish when u close metatrader and open it again. Once drow it stays on the chart till u close the chart window or delete the object.

(...) to be continoued...

Hi folks,

I've got a lot messages in the forex-tsd forum asking me how to use iMaOnArray function to get the Moving Average of a specific indicator. Today I'm going to answer all of you in this article.

What's the moving average of indicator?

When you attach an indicator to the chart it uses the price to for it calculation and save (draw) them . You can calculate the moving average of this array.

I'll give you a manual example before going to create our mql4 version.

Let's say that we will attach the CCI (Commodity Channel Index) indicator to our chart (Figure 1).


Now we want to get the moving average of the CCI. We can do that by dragging the Moving Average indicator to the window holds the CCI indicator and choose the Apply to: Previous Indicator's Data (Figure 2).


And that's what you get (Figure 3)


How to do that programicly?

If you are interested in getting the moving average of any indicator like the above manual setup, you can 'trigger' your MetaEditor and write this code:

//+------------------------------------------------------------------+
//| iMAOnArray.mq4 |
//| Coders Guru |
//| http://www.metatrader.info |
//+------------------------------------------------------------------+

#property copyright "Coders Guru"
#property link "http://www.metatrader.info"


#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1 LawnGreen
#property indicator_color2 DarkBlue

double ExtMapBuffer1[];
double ExtMapBuffer2[];

int init()
{
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
SetIndexStyle(1,DRAW_LINE,STYLE_SOLID,2);
SetIndexBuffer(1,ExtMapBuffer2);

return(0);
}

int deinit()
{
return(0);
}

int start()
{
int bar, limit;

int counted_bars=IndicatorCounted();
if(counted_bars<0) return(-1);
if(counted_bars>0) counted_bars--;
limit=Bars-IndicatorCounted();


for(bar=0; bar<limit; bar++)
ExtMapBuffer1[bar] = iCCI(NULL,0,14,PRICE_TYPICAL,bar);

for(bar=0; bar<limit; bar++)
ExtMapBuffer2[bar]=iMAOnArray(ExtMapBuffer1,Bars,14,0,MODE_EMA,bar);

return(0);
}

As you can notice in the above code that we use the function iCCI and iMAOnArray to calculate the Moving average of the CCI indicator.

The iCCI function simply calculate the CCI of a giving bar and return its value. We store those values returned by iCCI function in our buffer ExtMapBuffer1.

Now we have a full of data buffer (ExtMapBuffer1), how to get the Moving Average of this buffer?

iMAOnArray:

With the aid of the iMAOnArray function we can calculate the moving average of the values stored in an array(buffer).

This is the syntax of the iMAOnArray function:

double iMAOnArray(double array [],int total,int period,int ma_shift,int ma_method,int shift)

The iMAOnArray - as you see in its syntax - returns double value; this is the value of the moving average - counted on the array - of the given bar. Don't worry you will understand well when you know the parameters of the iMAOnArray function.

Parameters:

double array []:

This is the array of the values you want to calculate the moving average of it.
You have to fill this array with double data type items.
In our example we used the bufferex1 as the array[] parameter passed to iMAOnArray after filling that array with the values of the CCIs of the bars in our chart.

int total:

You use the total parameter to indicate the count of items of the data from the array you want to use to calculate the moving average.
If you want to use all the items in the array in your moving average calculation pass 0 in the total parameter.

int period:

The moving average period of the moving average you want to use.
If you are familiar to moving average you can skip this section.
when use the moving average indicator with the hourly chart and use 12 as the period of moving average calculation ; it means that you want to know the average of the price of the previous 12 hours.
when use the moving average indicator with the daily chart and use 30 as the period of moving average calculation ; it means that you want to know the average of the price of the previous 30 days.

int ma_method:

The moving average method you want to use in your calculation.
These are the moving average methods available in MetaTrader

:victory: :victory: :victory:

Welcome to the practical world of MQL4 courses; welcome to your first indicator in MQL4.

I recommend you to read the previous nine lessons very carefully, before continuing with these series of courses, that’s because we will use them so much in our explanations and studies of the Expert Advisors and Custom Indicators which we will create in this series of lessons.

Today we are going to create a simple indictor which will not mean too much for our trade world but it means too much to our MQL4 programming understanding.

It simply will collect the subtraction of High [] of the price – Low [] of the price; don’t be in a hurry, you will know everything very soon.

Let’s swim!

MetaEditor:

This is the program which has been shipped with MT4 (MetaTrader 4) enables you to write your programs, read MQL4 help, compile your program and More.

I’ve made a shortcut for MetaEditor on my desktop for easily access to the program.
If you want to run MetaEditor you have three choices.

1- Run MT4, then click F4, choose MetaEditor from Tools menu or click its icon on the Standard toolbar (Figure 1).

2- From Start menuà Programs, find MetaTrader 4 group then click MetaEditor.

3- Find the MT4 installation path (usually C:\Program Files\MetaTrader 4), find the MetaEditor.exe and click it (I recommend to make a shortcut on you desktop).


Figure 1 – MetaTrader Standard Toolbar

Any method you have chosen leads you to MetaEditor as you can see in figure 2.

As you can see in figure 2, there are three windows in MetaEditor:

1- The Editor window which you can write your program in.

2- The Toolbox window which contains three tabs:

a. Errors tab, you see here the errors (if there any) in your code.

b. Find in files tab, you see here the files which contain the keyword you are searching for using the toolbar command “Find in files” or by clicking CTRL +SHIFT+ F hotkeys.

c. Help tab, you can highlight the keyword you want to know more about it and click F1, and you will see the help topics in this tab.

3- The Navigator window which contains three tabs:

a. Files tab, for easy access to the files saved in the MT4 folder.

b. Dictionary tab enables you to access the MQL4 help system.

c. Search tab enables you to search the MQL4 dictionary.


Figure 2 – MetaEditor Windows

I recommend you to navigate around the MetaEditor Menus, Toolbar and windows to be familiar with it.

Now let’s enjoy creating our first custom indicator.

Note:Custom Indicator is a program which enables you to use the functions of the technical indicators and it cannot automate your deals.

First three steps:

Now you have run your MetaEditor and navigated around its Menus, Toolbar and windows, let’s USE it.

To create a custom indicator you have to start with three steps (you will learn later how to skip these boring steps (my personal opinion).

Step 1: Click File menu à New (you use CTRL+N hotkey or click the New Icon in the Standard toolbar).

You will get a wizard (Figure 3) guiding you to the next step.

Choose Custom Indicator Program option, and then click next.


Figure 3 - New project wizard

Step 2: When you clicked Next, you will get the second step wizard (Figure 4) which will enable you to edit the properties of your program. In this step you can enter these properties:

1- Name of your program, this is the name which the world will call you program with and it will be saved as the_name_you_have_chosen.mq4

2- Author name, the creator of the program name.

3- Link to your web site.

4- External variables list: I want to pause here to remember you about external variable.

External variables are the variables which will be available to the user of you indicator to set from the properties tab of your indicator in MetaTrader. For example: MA_Period in the very popular EMA indicator. And these variables will be declared with the “extern” keyword in your code (Please review Variables lesson).

So, this section of the wizard enables you to add these kinds of variables.

In our first indicator example we will not need any external variables just write the values you see in figure 4 and let’s go to step 3 by clicking Next button.


Figure 4 – Program properties wizard.

Step 3: The third wizard you will get when you clicked Next button is the Drawing properties wizard (Figure 5).

Its job is enabling you to set the dawning properties of the lines of your indicator, for example: how many lines, colors and where to draw your indicator (in the main chart or in separate windows).

This wizard contains the following options:

1- Indicator in separate window option: by clicking this option, your indicator will be drawn in separate windows and not on the main chart window. If you didn’t check the option, your indicator will be drawn in the main chart window.

2- Minimum option: it will be available (enabled) only if you have checked the Indicator in separate window option, and its job is setting the bottom border for the chart.

3- Maximum option: it will be available (enabled) only if you have checked the Indicator in separate window option, and its job is setting the top border for the chart

4- Indexes List: here you add your indicator line and set its default colors.

I want you to wait to the next lesson(s) to know more about these options and don’t be in a hurry.

For our first indicator example, choose Indicator in separate window option and click Add button, when you click add button the wizard will add a line to the indexes list like you see in figure 5.


Figure 5 - Drawing properties wizard.

When you click Finish button the Magic will start. You will see the wizard disappeared and the focus returned to the MetaEditor environment and… guess what?

You have ready to use first indicator draft code.

This is the code you will get:

//+------------------------------------------------------------------+
//| My_First_Indicator.mq4 |
//| Codersguru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Codersguru"
#property link "http://www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- buffers
double ExtMapBuffer1[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();
//----

//----
return(0);
}
//+------------------------------------------------------------------+

As you see in the above code, the wizard has written a lot of code for you, now I have to thank the wizard and to thank you too.

In the next lesson we will discover every line of code you have seen above and add our code to make our first indicator. To this lesson I hope you be ready!

Please don’t forget to download the source code of the first indicator and warm yourself for the next lesson.

I welcome very much the questions and the suggestions.

See you

Coders’ Guru

Welcome to the second part of “Your First Indicator” lesson.

In the previous lesson we didn’t write any line of code, that’s because the New Project

Wizard wrote all the code for us. Thanks!

Today we are going to add few lines to the code the wizard had generated to make our

program more useful.

Afterwards, we are going to explain the whole of the code line by line.

Let’s coding

Code we have added:

We have added the code which in a bold dark blue to our previous code:

//+------------------------------------------------------------------+

//| My_First_Indicator.mq4 |

//| Codersguru |

//| http://www.forex-tsd.com |

//+------------------------------------------------------------------+

#property copyright "Codersguru"

#property link "http://www.forex-tsd.com"

#property indicator_separate_window

#property indicator_buffers 1

#property indicator_color1 Red

//---- buffers

double ExtMapBuffer1[];

//+------------------------------------------------------------------+

//| Custom indicator initialization function |

//+------------------------------------------------------------------+

int init()

{

//---- indicators

SetIndexStyle(0,DRAW_LINE);

SetIndexBuffer(0,ExtMapBuffer1);

string short_name = "Your first indicator is running!";

IndicatorShortName(short_name);

//----

return(1);

}

//+------------------------------------------------------------------+

//| Custor indicator deinitialization function |

//+------------------------------------------------------------------+

int deinit()

{

//----

//----

return(0);

}

//+------------------------------------------------------------------+

//| Custom indicator iteration function |

//+------------------------------------------------------------------+

int start()

{

int counted_bars=IndicatorCounted();

//---- check for possible errors

if (counted_bars<0) return(-1);

//---- last counted bar will be recounted

if (counted_bars>0) counted_bars--;

int pos=Bars-counted_bars;

double dHigh , dLow , dResult;

Comment("Hi! I'm here on the main chart windows!");

//---- main calculation loop

while(pos>=0)

{

dHigh = High[pos];

dLow = Low[pos];

dResult = dHigh - dLow;

ExtMapBuffer1[pos]= dResult ;

pos--;

}

//----

return(0);

}

//+------------------------------------------------------------------+

How will we work?

We will write the line(s) of the code we are going to explain then we will explain them

afterwards, if there are no topics, we will explain the line(s) of code directly. But at the

most of the time we will pause to discuss some general topics.

I want to here your suggestion about this method please!

Now let’s crack this code line by line.

//+------------------------------------------------------------------+

//| My_First_Indicator.mq4 |

//| Codersguru |

//| http://www.forex-tsd.com |

//+------------------------------------------------------------------+

Comments:

The first five lines of code (which are in gray color) are comments.

You use Comments to write lines in your code which the compiler will ignore them.

You are commenting your code for a lot of reasons:

_ To make it clearer

_ To document some parts like the copyright and creation date etc.

_ To make it understandable.

_ To tell us how the code you have written is work.

_ …

You can write comments in two ways:

Single line comments: The Single line comment starts with “//” and ends with the new

line.

Multi-line comments: The multi-line comment start with “/*” and ends with “*/” and

you can comment more than one line.

In our program the MQL4 wizard gathered from the data we entered the name of the

program, author and the link and wrote them as comments at the top of our program.

#property copyright "Codersguru"

#property link "http://www.forex-tsd.com"

#property indicator_separate_window

#property indicator_buffers 1

#property indicator_color1 Red

Property directive:

As you notice all of these lines start with the word (#property). That’s because they are

kind of the Preprocessors directives called property directives.

The Preprocessors are the instructions you give to the compiler to carry them out before

starting (processing) your code.

The property directives are predefined constants called “Controlling Compilation

built in the MQL4 language; their job is setting the properties of your program.

For example: is your Indicator will appear in the main chart window or in a separate

window? Who is the writer of the program?

Note: The preprocessors lines end with a carriage-return character (new line) not a

semi-colon symbol.

We will try to discuss here the property directives available in MQL4.

link:

This property setting the web link to your web site which you asked to enter it in step 2

in the Expert Advisor Wizard (review the previous lesson).

The data type of this property is string.

copyright:

It’s the name of the author of the program, same as the link property you asked to enter

it in step 2 in the Expert Advisor Wizard.

The data type of this property is string.

stacksize:

It’s an integer value sets the memory size for every thread, the default value is 16384.

The data type of this property is integer.

indicator_chart_window:

When you set this property, your indicator will be drawn in the main chart window

(Figure 1). You have to choose one of two options for your Indicators, drawing them in

the main chart windows by using this property, or drawing them in separate windows by

choosing the indicator_separate_window. You can’t use the both of them at the same

time.

The data type of this property is void, which means it takes no value.

indicator_separate_window:

When you set this property, your indicator will be drawn in a separate window (Figure

1). You can set the scale of the separate indicator window using two properties

indicator_minimum for the minimum value and indicator_maximum for the

maximum value of the scale.

And you can set the level of your indicators on these scales using the property

indicator_levelN where’s the N is the indicator number.

Both of the properties indicator_chart_window and indicator_separate_window are

void data type, which mean they don’t take value and you just write them.

In our program we will draw our indicator in a separate window:

#property indicator_separate_window

Figure 1

indicator_minimum:

With the aid of this property we are setting the minimum value of the separate windows

scale, which is the bottom border of the windows. For example:

#propery indicator_minimum 0

#propery indicator_ maximum 100

Here we have set the bottom border of the window to 0 and the top border to 100 (see

indicator_ maximum), hence we have a scale ranged from 0 to 100 in our separate

window which we are drawing our indicator.

The data type of this property is integer.

indicator_maximum:

With the aid of this property we are setting the maximum value of the separate windows

scale, which is the top border of the windows.

This value must be greater than the indicator_minimum value.

The data type of this property is integer.

Main chart window

Separate window

indicator_levelN:

With the aid of this property we are setting the level of the indicator in the scale we have created with the properties indicator_minimum and indicator_maximum, this value

must be greater than the indicator_minimum value and smaller than the

indicator_maximum value.

N is the indicator number which we are setting its level, it must range from 1 to 8

(because we are allowed only to use up to 8 indicator buffers in our program, so we can

set the indicator_level for each of them using its number). For example:

#property indicator_minimum 0

#property indicator_minimum 100

#property indicator_level1 10 //set the first indicator level

#property indicator_level2 65.5 //set the second indicator level

The data type of this property is double.

indicator_buffers:

With the aid of this property we are setting the number of memories spaces (Arrays)

allocated to draw our line(s). When we set the number (ranged from 1 up to 8) we are

telling MQL4: “Please allocate a memory space for me to draw my indicator line”.

In our program we used only one buffer.

#property indicator_buffers 1

That’s because we will draw only one line.

indicator_colorN:

We can use up to 8 lines in our indicator, you can set the color of each of them using this

property indicator_colorN , where the N is the line number which defined by

indicator_buffers.

The user of your Indicator can change this color from the properties dialog of your

Indicator (Figure 2).

In our program the indicator line color will be red.

#property indicator_color1 Red

The data type of this property is color.

Figure 2

double ExtMapBuffer1[];

Arrays:

In our life we usually group similar objects into units, in the programming we also need

to group together the data items of the same type. We use Arrays to do this task.

Arrays are very like the list tables, you group the items in the table and access them the

number of the row. Rows in the Arrays called Indexes.

To declare an array you use a code like that:

int my_array[50];

Here, you have declared an array of integer type, which can hold up to 50 items.

You can access each item in the array using the index of the item, like that:

My_array[10] = 500;

Here, you have set the item number 10 in the array to 500.

You can initialize the array at the same line of the declaration like that:

int my_array[5] = {1,24,15,66,500};

In our program we used this line of code:

double ExtMapBuffer1[];

Here we have declared and array of double type. We will use array to calculate our

values which we will draw them on the chart.

int init()

{

}

Special functions:

Functions are blocks of code which like a machine takes inputs and returns outputs

(Please review lesson 7 – Functions).

In MQL4 there are three special functions

init():

Every program will run this function before any of the other functions, you have to put

here you initialization values of you variables.

start():

Here’s the most of the work, every time a new quotation have received your program

will call this function.

deinit():

This is the last function the program will call before it shutdown, you can put here any

removals you want.

SetIndexStyle(0,DRAW_LINE);

SetIndexBuffer(0,ExtMapBuffer1);

string short_name = "Your first indicator is running!";

IndicatorShortName(short_name);

Custom indicator functions:

I can’t give you a description for all of the indicators functions in this lesson. But we

will use them all in our next lessons with more details. So, we will study here the

functions used in our program.

SetIndexStyle:

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

clr=CLR_NONE)

This function will set the style of the drawn line.

The index parameter of this function ranges from 1 to 7 (that’s because the array

indexing start with 0 and we have limited 8 line). And it indicte which line we want to

set its style.

The type parameter is the shape type of the line and can be one of the following shape

type’s constants:

DRAW_LINE (draw a line)

DRAW_SECTION (draw section)

DRAW_HISTOGRAM (draw histogram)

DRAW_ARROW (draw arrow)

DRAW_NONE (no draw)

The style parameter is the pen style of drawing the line and can be one of the following

styles’ constants:

STYLE_SOLID (use solid pen)

STYLE_DASH (use dash pen)

STYLE_DOT (use dot pen)

STYLE_DASHDOT (use dash and dot pen)

STYLE_DASHDOTDOT (use dash and double dots)

Or it can be EMPTY (default) which means it will be no changes in the line style.

The width parameter is the width of line and ranges from 1 to 5. Or it can be EMPTY

(default) which means the width will not change.

The clr parameter is the color of the line. It can be any valid color type variable. The

default value is CLR_NONE which means empty state of colors.

In our line of code:

SetIndexStyle(0,DRAW_LINE);

We have set the index to 0 which means we will work with the first (and the only) line.

And we have set the shape type of our line to DRAW_LINE because we want to draw a

line in the chart.

And we have left the other parameters to their default values.

SetIndexBuffer:

bool SetIndexBuffer( int index, double array[])

This function will set the array which we will assign to it our indicator value to the

indicator buffer which will be drawn.

The function takes the index of the buffer where’s 0 is the first buffer and 1 is the second,

etc. Then it takes the name of the array.

It returns true if the function succeeds and false otherwise.

In our program the array which will hold our calculated values is ExtMapBuffer1.

And we have only one indicator buffer (#property indicator_buffers 1). So it

will be the buffer assigned.

IndicatorShortName:

void IndicatorShortName( string name)

This function will set the text which will be showed on the upper left corner of the chart

window (Figure 3) to the text we have inputted.

In our program we declared a string variable and assigned the value “You first indicator

is running” to it, then we passed it to the IndicatorShortName function.

string short_name = "Your first indicator is running!";

IndicatorShortName(short_name);

Figure 3

return(0);

This is the return value of the init() function which terminate the function and pass the

program to the execution of the next function start().

int deinit()

{

//----

//----

return(0);

}

Nothing new to say about deinit() function.

We will continue with remaining of the code in the next lesson.

I hope you enjoyed the lesson and I welcome your questions.

See you

Coders’ Guru

返回列表
高级回复 | 发新话题
B Color Image Link Quote Code Smilies
换一个