MQL4 COURSE By Coders’ guru www.forex-tsd.com -1 WELCOME
-------------------Welcome to the MQL4 course. In this series, I will try to strip the mystique and confusion from MQL4 by giving you comprehensive comprehensive tutorials with a straight forward example. ex ample. In this series of lessons, I will show you how to use the MQL4 for building your own Expert Advisors, Custom Indicators and Scripts. If you are programming in C (or its superset C++) then you know a lot of MQL4 before even I start my lessons, if you didn’t write in any programming language before, no problem, I’ll guide you to understand the concept of programming in general as well. So, let’s start from the beginning.
MQL4? What, Why and Where? MQL4 stands for MetaQuotes Language 4. MetaQuotes is the company who built the MetaTrader Trading Platform. And to make it stronger than the other trading platforms the company extended it by a built-in programming language that enables the user (you) to write his own trading strategies. The language enables you to create one of the following: 1- Expert Advisors. 2- Custom Indicators. 3- Scripts. •
•
Expert Advisor is a program which can automate trading deals for you. For example it can automate your market orders, stops orders automatically, cancels/replaces orders and takes your profit. p rofit. Custom Indicator is a program which enables you to use the functions of the technical indicators and it cannot automate your deals.
•
Script is a program designed for single function execution. Unlike the Advisor, scripts are being be ing held only once (on demand), and not by ticks. And of course has no access to indicator functions.
These were “What” MQL4 is? “Why ” to use MQL4? Now, “Where” do I write MQL4? To write your MQL4 code and as anything else in world, you can choose one of two ways, the hard way and the easy way. 1- The hard way The hard way is using your favorite text editor and the command prompt to compile your program. Notepad is not bad choice, but do not forget two things: 1- To save the file you have created crea ted in plain text format. 2- To save the file as .mp4 (that’s to be easy to t o reopen it with Metaeditor), but you can save it as any extension you prefer.
After saving your program there is an extra step to make your code comes out to the light. It’s the Compiling step. step. Compiling means to convert the human readable script that yo u have just wrote to the machine language that your y our computer understands. MetaTrader has been shipped with its own compiler (the program which will convert your script to the machine ma chine language) called MetaLang.exe. Metalang.exe is a console program which takes 2 parameters and output an .ex4 file (the file which Metatrader understands). u nderstands). The first parameter is “options” parameter and the only option available is –q quit The second parameter is the full path to your .mql file. The syntax will be in this format. metalang [options…] filename Example 1- Find your metalang.exe path, it will be the same path of MetaTrader (here my path is D:\Program Files\MetaTrader 4) 2- Create a batch file and name it compile.bat (or any name you prefer). 3- Write these lines into the bat file then save sa ve it. cd D:\Program Files\MetaTrader 4 metalang -q "D:\Program Files\Met F iles\MetaTrader aTrader 4\my_first_mql4_script.mq4" 4\my_first_mql4_script.mq4" (Don’t forget to change the path to you MetaTrader installed path) 4- Run the batch file and if you are lucky person like me you will get a screen like this.
Figure 1 Metalang compiler
As you see you will get the output file “my_first_mql4_script.ex4”
2-The easy way Metatrader has been shipped with a good IDE (integrated development editor) editor) called MetaEditor which has these features:
1- A text editor has the feature of highlighting different constructions of MQL4 language while you are writing/reading code. 2- Easy to compile your program, just click F5 and the MetaEditor will make all the hard work for yo u and produces the “ex4” file. Besides it’s easy to see what the wrong in your program is (in the Error Tab – see figure 2). 3- Built-in a dictionary book which you can access by highlight the keyword you want to know further about it then press F1.
Figure 2 MetaEditor 4
In the coming lessons we will know more about MetaEditor.
Today I just came to say hello, tomorrow we will start the real works. Tomorrow we will study the Syntax of MQL4? I welcome very much the questions questions and the suggestions. suggestions.
See you Coders’ Guru 19-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -2SYNTAX
-------------------which tried to answer the t he very basic ba sic I hope you enjoyed the “Welcome” lesson which questions; what MQL4 is, why MQL4 and where (to write) MQL4? Always the biggest and the most important question(s) are how, and the entire coming lessons are the answer. Now, I want you to empty your mind from any confusion and read carefully the next few concepts. We are talking today about a bout the SYNTAX rules of MQL4. And as I told you before, before, If you are programming in C (or its superset superset C++) then you know a lot of MQL4 before even I start my lessons. lessons. That’s because the syntax of MQL4 is very like of the syntax of C. The dictionary means of the word SYNTAX of a programming language is: “The set of allowed a llowed reserved words and their parameters and the correct word order in the expression is called the syntax of language”. language”. “ Wikipedia Wikipedia ” So, when we are studying the syntax of the language we are studying its grammar and writing rules which consist of: •
Format
•
Comments
•
Identifiers
•
Reserved words
Let’s slice the cake.
1- Format:
When you write your code, you can freely use any set of spaces, tabs and empty lines you want to separate your code and your line of code to make them readable and eyes pleasing. For example all of these lines are valid in MQL4: double MacdCurrent, MacdPrevious, SignalCurrent; double MacdCurrent, MacdPrevious, SignalCurrent; double
MacdCurrent,
MacdPrevious,
SignalCurrent;
But, as you see, the first line is more readable and easy to understand. And as everything in the world there are exceptions to the rule: 1- You can’t use new line in the “Controlling compilation” You will know more about “Controlling compilation” in next lesson but just remember this is an exception. For example the next line of code is invalid and the MQL4 compiler will complain: #property copyright "Copyright © 2004, MetaQuotes Software Corp." This is the valid “Controlling compilation”: #property copyright "Copyright © 2004, MetaQuotes Software Corp."
2- You can’t use new line or space in the middle of Constant values, Identifiers or Keywords. For example this line is valid: extern int MA_Period=13;
“extren” and “int” here are Keywords , “MA_Period” is an Identifier and “13” is a Constant value.. You will know more in the next lessons. For example the next lines are invalids: extern int MA_Period=1 3;
extern int MA_Period=1
3;
Notice the tab between 1 and 3. ex tern int MA_Period=13;
2- Comments:
To make the programming world easier, any programming language has its style of writing comments. You use Comments to write lines in your code which the compiler will ignore then but it clears your code and makes it understandable. Assume that you write a program in the summer and in the winter you want to read it. Without comments -even you are the code’s creator- you can’t understand all these puzzled lines. MQL4 (& C/C++) uses two kinds of comments styles: 1- Single line comments The Single line comment starts with “//” and ends with the new line. For example: //This is a comment extern int MA_Period=13; extern int MA_Period=13; //This is another comment
2- Multi-line comments The multi-line comment start with “/*” and ends with “*/”. And you can comment more than line or more by putting “/*” at the start of the first line, and “*/” at the end of the last line. For example: /* this is multi line comment*/
You can also nest single line comment inside multi lines comment like that: /* this is multi //another comment nested here. line comment*/
This is a valid comment too: extern int /*HELLO! I’m a comment*/ MA_Period=13; But this is invalid comment: extern int //test MA_Period=13;
3- Identifiers:
An identifier is the name you choose to your variables, constants and functions. For example MA_Period here is an identifier: extern int MA_Period=13;
There are few rules and restrictions for choosing those names: 1- The length of the Identifier must not exceed 31 characters. 2- The Identifier must begin with a letter (capital or small) or the underlining symbol _. So, it can’t be started with a number or an other symbol except the underlining symbol. 3- You can’t use any reserved words as an Identifier. You will see the list of the reserved words too soon. 4- The identifiers’ names are case sensitive. So, MA_PERIOD not the same as ma_period or MA_Period Let’s take some examples: Name1 Valid _Name1 Valid Invalid (don’t start with number) 1Name Invalid (you can only use underline symbol) ~Name1 Invalid (you can only use underline symbol) N~ame1 i_love_my_country_and_my_country_loves_all_the_world Invalid (you can’t exceed the 31 characters length) Color Valid color Invalid (you can’t use reversed word, and color is one of them)
4- Reserved words:
There are “words” which the language uses them for specific actions. So, they are reserved to the language usage and you can’t use them as an identifier name or for any other purpose. This is the list of the reserved words ( from the MQL4 guide): Data types
Memory classes
Operators
Other
bool
extern
break
false
color
static
case
true
datetime
continue
double
default
int
else
string
for
void
if return switch while
For example the next lines of code are invalid: extern int datetime =13; int extern =20; double continue = 0;
I hope you enjoyed the lesson. The next lesson will be about the “Data Types”. So, Be Ready, the real hard work is coming! I welcome very much the questions and the suggestions.
See you Coders’ Guru 20-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -3DATA TYPES -------------------Welcome to my third lesson in my MQL4 course. I hope you enjoyed the “SYNTAX” lesson, which tried to give you the answers for: What format you can use to write MQL4 code? How to make the world better by commenting your code? What the Identifiers are, and what are the rules of choosing them? What are the MQL4 Reserved words? • • • •
If you didn’t read the “SYNTAX” lesson please download it from here: http://forex-tsd.com/attachment.php?attachmentid=399 And you can download the “Welcome” lesson from here: http://forex-tsd.com/attachment.php?attachmentid=372 Don’t forget to login first. Now, let’s enjoy the DATA TYPES. What’s the Data type mean?
Any programming language has a set of names of the memory representation of the data. For example if the memory holds numbers between -2147483648 to 2147483647, the most of the programming languages will name this data as “Integer” data type. Variables?
Variables are the names that refer to sections of memory into which data can be stored. To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes. •
•
In order to use a box to store data, the box must be given a name; this process is known as declaration. In the declaration process you use a word tell the computer what’s the kind and size of the box you want to use, this word known as keyword.
•
• •
It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant. Data is placed into a box by assigning the data to the box. When we set the value of the box you have created in the same line you declared the variable; this process is known as initialization.
When we create a variable we are telling the computer that we want him to assign a specified memory length (in bytes) to our variable, since storing a simple number, a letter or a large number is not going to occupy the same space in memory, so the computer will ask us what’s the kind of data and how much the length of the data? That is the Data type for. For example if we said this line of code to the computer: int MyVaraible=0; That’s mean we are asking the computer to set a block of 4 bytes length to our variable named “MyVaraiable”. In the previous example we have used: int Keyword int Integer data type. int Declaration MyVaraible Variable’s constant. =0 Initialization We will know more about variables in a coming lesson. In MQL4, these are the kinds of Data types: • • • • • • •
Integer (int) Boolean (bool) Character (char) String (string) Floating-point number (double) Color (color) Datetime (datetime)
1- Integer An integer, is a number that can start with a + or a - sign and is made of digits. And its range value is between -2147483648 to 2147483647. MQL4 presents the integer in decimal or hexadecimal format.
For example the next numbers are Integers: 12, 3, 2134, 0, -230 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7 We use the keyword int to create an integer variable. For example: int intInteger = 0; int intAnotherIntger = -100; int intHexIntger=0x12;
Decimal and Hexadecimal: Decimal notation is the writing of numbers in the base of 10, and uses digits (0, 1, 2, 3, 4, 5, 6, 7, 8 and 9) to represent numbers. These digits are frequently used with a decimal point which indicates the start of a fractional part, and with one of the sign symbols + (plus) or − (minus) to indicate sign. Hexadecimal is a numeral system with a base of 16 usually written using the symbols 0–9 and A–F or a–f. For example, the decimal numeral 79 can be written as 4F in hexadecimal.
2- Boolean Boolean variable is a data type which can hold only two values, true and false (or their numeric representation, 0 and 1). And it occupies 1 bit o f the memory. In MQL4, false,FALSE,False,true,TRUE and True are equals. Boolean named like this in the honor of the great mathematician Boole George.
We use the keyword bool to create a boolean variable. For example: bool I = true; bool bFlag = 1; bool bBool=FALSE;
3- Character MQL4 names this Data type “Literal”. A character is one of 256 defined alphabetic, numeric, and special key elements defined in the ASCII (American Standard Code for Information Interchange) set. Characters have integer values corresponding to location in the ASCI I set. You write the character constant by u sing single quotes (') surrounding the character.
For example: 'a' , '$' , 'Z'
We use the keyword int to create a character variable. For example: int chrA = 'A'; int chrB = '$'; Some characters called Special Characters can ’t present directly inside the single quotes because they have a reserved meanings in MQL4 language. Here we use something called Escape Sequence to present those special characters, And that by prefixing the character with the backslash character (\). For example: int chrA = '\\'; int chrB = '\n';
//slash character //new line
This is the list of Escape Sequence characters used in MQL4. carriage return new line horizontal tab reverse slash single quote double quote hexadecimal ASCII-code
\r \n \t \\ \' \" \xhh
ASCII table Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex ------------------------------------------------------------------------------------(nul) 0 0000 0x00 | (sp) 32 0040 0x20 | @ 64 0100 0x40 | ` 96 0140 0x60 (soh) 1 0001 0x01 | ! 33 0041 0x21 | A 65 0101 0x41 | a 97 0141 0x61 (stx) 2 0002 0x02 | " 34 0042 0x22 | B 66 0102 0x42 | b 98 0142 0x62 (etx) 3 0003 0x03 | # 35 0043 0x23 | C 67 0103 0x43 | c 99 0143 0x63 (eot) 4 0004 0x04 | $ 36 0044 0x24 | D 68 0104 0x44 | d 100 0144 0x64 (enq) 5 0005 0x05 | % 37 0045 0x25 | E 69 0105 0x45 | e 101 0145 0x65 (ack) 6 0006 0x06 | & 38 0046 0x26 | F 70 0106 0x46 | f 102 0146 0x66 (bel) 7 0007 0x07 | ' 39 0047 0x27 | G 71 0107 0x47 | g 103 0147 0x67 (bs) 8 0010 0x08 | ( 40 0050 0x28 | H 72 0110 0x48 | h 104 0150 0x68 (ht) 9 0011 0x09 | ) 41 0051 0x29 | I 73 0111 0x49 | i 105 0151 0x69 (nl) 10 0012 0x0a | * 42 0052 0x2a | J 74 0112 0x4a | j 106 0152 0x6a (vt) 11 0013 0x0b | + 43 0053 0x2b | K 75 0113 0x4b | k 107 0153 0x6b (np) 12 0014 0x0c | , 44 0054 0x2c | L 76 0114 0x4c | l 108 0154 0x6c (cr) 13 0015 0x0d | 45 0055 0x2d | M 77 0115 0x4d | m 109 0155 0x6d (so) 14 0016 0x0e | . 46 0056 0x2e | N 78 0116 0x4e | n 110 0156 0x6e (si) 15 0017 0x0f | / 47 0057 0x2f | O 79 0117 0x4f | o 111 0157 0x6f (dle) 16 0020 0x10 | 0 48 0060 0x30 | P 80 0120 0x50 | p 112 0160 0x70 (dc1) 17 0021 0x11 | 1 49 0061 0x31 | Q 81 0121 0x51 | q 113 0161 0x71 (dc2) 18 0022 0x12 | 2 50 0062 0x32 | R 82 0122 0x52 | r 114 0162 0x72 (dc3) 19 0023 0x13 | 3 51 0063 0x33 | S 83 0123 0x53 | s 115 0163 0x73 (dc4) 20 0024 0x14 | 4 52 0064 0x34 | T 84 0124 0x54 | t 116 0164 0x74 (nak) 21 0025 0x15 | 5 53 0065 0x35 | U 85 0125 0x55 | u 117 0165 0x75 (syn) 22 0026 0x16 | 6 54 0066 0x36 | V 86 0126 0x56 | v 118 0166 0x76 (etb) 23 0027 0x17 | 7 55 0067 0x37 | W 87 0127 0x57 | w 119 0167 0x77 (can) 24 0030 0x18 | 8 56 0070 0x38 | X 88 0130 0x58 | x 120 0170 0x78 (em) 25 0031 0x19 | 9 57 0071 0x39 | Y 89 0131 0x59 | y 121 0171 0x79 (sub) 26 0032 0x1a | : 58 0072 0x3a | Z 90 0132 0x5a | z 122 0172 0x7a (esc) 27 0033 0x1b | ; 59 0073 0x3b | [ 91 0133 0x5b | { 123 0173 0x7b (fs) 28 0034 0x1c | < 60 0074 0x3c | \ 92 0134 0x5c | | 124 0174 0x7c (gs) 29 0035 0x1d | = 61 0075 0x3d | ] 93 0135 0x5d | } 125 0175 0x7d (rs) 30 0036 0x1e | > 62 0076 0x3e | ^ 94 0136 0x5e | ~ 126 0176 0x7e (us) 31 0037 0x1f | ? 63 0077 0x3f | _ 95 0137 0x5f | (del) 127 0177 0x7f
4- String The string data type is an array of characters enclosed in double quote ("). The array of characters is an array which holds one character after another, starting at index 0. After the last character of data, a NULL character is placed in the next array location. It does not matter if there are unused array locations after that. A NULL character is a special character (represented by the ASCII code 0) used to mark the end of this type of string. See figure 1 for a simple representation of the string constant “hello” in the characters array.
Figure 1 – Characters array MQL4 limits the size of the string variable to 255 characters and any character above 255 characters will generate this error: (too long string (255 characters maximum) ). You can use any special character -mentioned above- in your string constant by prefixing it with the backslash (\). We use the keyword string to create a string variable. For example: string str1 = "Hello world1, with you coders guru”; string str2 = "Copyright © 2005, \"Forex-tsd forum\"."; //Notice the use of (") character. string str3 = "1234567890";
5- Floating-point number (double) Floating point number is the Real Number (that is, a number that can contain a fractional part beside the integer part separated with (.) dot).Ex: 3.0,-115.5, 15 and 0.0001. And its range value is between 2.2e-308 to 1.8e308. We use the keyword double to create a floating-point variable. For example: double dblNumber1 = 1000000000000000; double dblNumber3 = 1/4; double dblNumber3 = 5.75;
6- Color Color data type is a special MQL4 data type, which holds a color appears on the MetaTrader chart when you create your own Expert Advisor or Custom Indictor and the user can change it from the property tab of your Expert Advisor or Custom Indictor. You can set the Color variable constant in three ways: 1- By the color name: For the well know colors (called Web Colors Set) you can assign the name of the color to the color variable, see the list of the Web Colors Set. 2- By Character representation (MQL4 named it this name): In this method you use the keyword (C) followed by two signal quotations ('). Between the two signal quotations you set the value of the red, green and blue (know as RGB value of the color). These values have to be between: 0 to 255. A nd you can write these values in decimal or hexadecimal format. 3- By the integer value: Every color in the Web Colors Set has its integer value which you can write it in decimal or hexadecimal format. And you can assign the Integer value of the color to the color variable. The hexadecimal color format looks like this: 0xBBGGRR where BB is the blue value, GG is gree n value and RR is the red value. For example: // symbol constants C'128,128,128' // gray C'0x00,0x00,0xFF' // blue // named color Red Yellow Black // integer-valued representation 0xFFFFFF // white 16777215 // white 0x008000 // green 32768 // green We use the keyword color to create a color variable. For example: color clr1= Red; color clr1= C'128,128,128' ;
color clr1=32768;
Web Colors Set Black
DarkGreen
DarkSlateGray
Olive
Green
Maroon
Indigo
MidnightBlue
DarkBlue
SeaGreen
DarkGoldenrod
DarkSlateBlue
Sienna
MediumBlue
LightSeaGreen
DarkViolet
FireBrick
MediumVioletRed
Goldenrod
MediumSpringGreen
LawnGreen
DarkOrange
Orange
DeepSkyBlue
Teal
Navy
Purple
ForestGreen
OliveDrab
Brown
DarkTurquoise
DimGray
MediumSeaGreen
Chocolate
Crimson
SteelBlue
CadetBlue
DarkOrchid
YellowGreen
LimeGreen
OrangeRed
Gold
Yellow
Chartreuse
Lime
SpringGreen
Aqua
Blue
Magenta
Red
Gray
SlateGray
Peru
BlueViolet
LightSlateGray
DeepPink
MediumTurquoise
DodgerBlue
Turquoise
RoyalBlue
SlateBlue
DarkKhaki
IndianRed
MediumOrchid
GreenYellow
MediumAquamarine
DarkSeaGreen
Tomato
RosyBrown
Orchid
MediumPurple
PaleVioletRed
Coral
CornflowerBlue
DarkGray
DarkSalmon
BurlyWood
HotPink
Salmon
Violet
LightCoral
SkyBlue
LightSalmon
Plum
Khaki
LightGreen
Aquamarine
Silver
LightSkyBlue
LightSteelBlue
LightBlue
PaleGreen
Thistle
PowderBlue
PaleGoldenrod
PaleTurquoise
LightGrey
Wheat
NavajoWhite
Moccasin
LightPink
Gainsboro
PeachPuff
Pink
Bisque
LemonChiffon
Beige
AntiqueWhite
PapayaWhip
Cornsilk
LightYellow
LightCyan
Linen
Lavender
MistyRose
OldLace
WhiteSmoke
Seashell
Ivory
Honeydew
AliceBlue
LavenderBlush
MintCream
Snow
White
DarkOliveG reen SaddleBrown
SandyBrown MediumSlateBlue
LightGoldenRod BlanchedAlmond
7- Datetime 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.
Tan
For example: datetime dtMyBirthDay= D'1972.10.19 12:00:00'; datetime dt1= D'2005.10.22 04:30:00';
I hope you enjoyed the lesson. The next lesson will be about the “Operations & Expressions”. I welcome very much the questions and the suggestions.
See you Coders’ Guru 22-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -4Operations & Expressions -------------------Welcome to the fourth lesson in my course about MQL4. The previous lesson “Data Types” presented a lot of new concepts; I hope you understand it, and above all you enjoyed it. You can download the previous lesson from here: http://forex-tsd.com/attachment.php?attachmentid=399 http://forex-tsd.com/attachment.php?attachmentid=372 http://forex-tsd.com/attachment.php?attachmentid=469 Don’t forget to login first. Now, let’s enjoy the Operations & Expressions.
What’s the meaning of Operations & Expressions?
You know the operations very well. If I told you that (+,-,*, /) a re the basic arithmetical operators, you will remember very fast what’s the operator means. I hear you saying “OK, I know the operations; could you tell me what’s the meaning of the expression?” Identifiers (do you remember them? If not, Review the SYNTAX lesson) together with the Operations produce the Expressions. Puzzled? Let’s illustrate it in an example: x = (y*z)/w; x,y,z and w, here are identifiers. =,* and / are the operators. The whole line is an expression. When the expressions combined together it makes a statement. And when the statements combined together it makes a function and when the functions combined together it makes a program.
In the remaining of this lesson we are going to talk about the kinds operators used in MQL4. So, let’s start with the basic arithmetical operators:
1- Arithmetical operators: In MQL4 there are 9 Arithmetical operations This is the list of them with the usage of each: Operator
Name
Example
Description
+
Addition operator
A = B + C;
Add B to C and assign the result to A.
-
Subtraction operator
A = B - C;
Subtract C from B and assign the result to A.
+-
Sign changer operators
A = -A;
Change the sign of A from positive to negative.
*
Multiplication operator
A = B * C;
Multiply B and C and assign the result to A.
/
Division operator
A = B / C;
Divide B on C and assign the result to A.
%
Modulus operator
A =A % C;
A is the reminder of division of B on C. (ex: 10%2 will produce 0, 10%3 will produce 1).
++
Increment operator
A++;
Increase A by 1 (ex: if A =1 make it 2).
--
Decrement operator
A--;
Decrease 1 from A (ex: if A =2 make it 1).
Note: The remainder operator works by dividing the first number by the second number for the first integer results and then returns the remaining number.
For example: 10%5=0 This is because if you divide 10 by 5 you will get 2 and there no remaining value, so the remainder is 0. 10%8=2 This is because if you divide 10 by 8 you will get 1 (1*8=8), so the remainder is (10-8 = 2). 100%15=10
This is because if you divide 100 by 15 you will get 6 (6*15=90), so the remainder is (100-90=10). What about 6%8? It will be 6 because if you d ivide 6 by 8 you will get 0 (8*0=0), so the remainder is (60=6). Note: You can’t combine the increment and decrement operator with other expressions. For example you can’t say:
A=(B++)*5; But you can write it like that: A++; B=A*5; Note: How the above example works? Let’s assume: int A=1; //set A to 1 int B; A++; //increase A by 1, now A=2 B=A*5; //which means B=2*5
2- Assignment operators: The purpose of any expression is producing a result and the assignment operators setting the left operand with this result. For example: A = B * C; Here we multiply B and C and assign the result to A. (=) here is the assignment operator. In MQL4 there are 11 assignments operations This is the list of them with the usage of each: Operator
Name
Example
Description
=
Assignment operator
A = B;
Assign B to A.
+=
Additive Assignment operator
A += B;
It’s equal to: A = A + B; Add B to A and assign the result to A.
-=
Subtractive Assignment A -= B; operators
It’s equal to: A = A - B; Subtract B from A and assign the result to A.
*=
Multiplicative Assignment operator
A *= B;
It’s equal to: A = A * B; Multiply A and B and assign the result to A.
/=
Divisional Assignment operator
A /= B;
It’s equal to: A = A / B; Divide A on B and assign the result to A.
%=
Modulating Assignment A %= B; operator
It’s equal to: A = A % B; Get the reminder of division of A on B and assign the result to A.
>>=
Left Shift Assignment operator
It shifts the bits of A left by the number of bits specified in B.
<<=
Right Shift Assignment A <<= B; operator
It shifts the bits of A right by the number of bits specified in B.
&=
AND Assignment operator
A &= B;
Looks at the binary representation of the values of A and B and does a bitwise AND operation on them.
A |= B;
Looks at the binary representation of the values of A and B and does a bitwise OR operation on them.
A ^= B;
Looks at the binary representation of the values of two A and B and does a bitwise exclusive OR (XOR) operation on them.
|=
^=
OR Assignment operator
XOR Assignment operator
A >>= B;
3- Relational operators: The relational operators compare two values (operands) and result false or true only. It’s is like the question “Is John taller than Alfred? Yes / no?” The result will be false only if the expression produce zero and true if it produces any number differing from zero; For example: 4 == 4; 4 < 4; 4 <= 4
//true //false //true;
In MQL4 there are 6 Relational operations This is the list of them with the usage of each:
Operator
Name
Example
Description
==
Equal operator
A == B;
True if A equals B else False.
!=
Not Equal operator
A != B;
True if A does not equal B else False.
<
Less Than operators
A < B;
True if A is less than B else False.
>
Greater Than operator
A > B;
True if A is greater than B else False.
<=
Less Than or Equal operator
A <= B;
True if A is less than or equals B else False.
>=
Greater Than or Equal operator
A >= B;
True if A is greater than or equals B else False.
4- Logical operators: Logical operators are generally derived from Boolean algebra, which is a mathematical way of manipulating the truth values of concepts in an abstract way without bothering about what the concepts actually mean. The truth value of a concept in Boolean value can have just one of two possible values: true or false. MQL4 names the Logical operators as Boolean operators MQL4 uses the most important 3 logical operators. This is the list of them with the usage of each: Operator
&&
Name
AND operator
Example
Description
A && B;
If either of the values are zero the value of the expression is zero, otherwise the value of the expression is 1. If the left hand value is zero, then the right h and value is not considered.
||
OR operator
A || B;
If both of the values are zero then the value of the expression is 0 otherwise the value of the expression is 1. If the left hand value is non-zero, then the right hand value is not considered.
!
NOT operator
!A;
Not operator is applied to a non-
zero value then the value is zero, if it is applied to a zero value, the value is 1.
5- Bitwise operators: The bitwise operators are similar to the logical operators, except that they work on a smaller scale -- binary representations of data. The following operators are available in MQL4: Operator &
Name
AND operator
Example
Description
A & B;
Compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.
A | B;
Compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.
|
OR operator
^
EXCLUSIVE-OR operator
A ^ B;
Compares two bits and generates a result of 1 if either or both bits are 1; otherwise, it returns 0.
~
COMPLEMENT operator
~A;
Used to invert all of the bits of the operand.
A >> B;
Moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half.
A << B;
Moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.
>>
<<
The SHIFT RIGHT operator
The SHIFT LEFT operator
Note Both operands associated with the bitwise operator must be integers.
6- Other operators: There are some operators which used in MQL4 and don’t belong to one of the previous categories: 1- The array indexing operator ([]). 2- The function call operator (()); 3- The function arguments separator operator -comma (,) We will know more about the Arrays and Functions in the next lessons, so just remember these 3 operators as “Other operators”.
Operators Precedence: If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent: x + y / 100 x + (y / 100) //unambiguous, recommended
When writing compound expressions, you should be explicit and indicate with parentheses () which operators should be evaluated first. This practice will ma ke your code easier to read and to maintain. The following table shows the precedence assigned to the operators in the MQL4. The operators in this table are listed in precedence order: The higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same group have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right. Assignment operators are evaluated right to left. () []
Function call From left to right Array element selection
!
Negation
From left to right
~ -
Bitwise negation Sign changing operation
* Multiplication / Division % Module division
+ -
<< >>
From left to right
Addition Subtraction
From left to right
Left shift Right shift
From left to right
< Less than From left to right <= Less than or equals > Greater than >= Greater than or equals
== !=
Equals Not equal
&
Bitwise AND operation
^
&&
||
= += -= *= /= %=
Bitwise exclusive OR
Logical AND
Logical OR
From left to right
From left to right
From left to right
From left to right
From left to right
Assignment From right to left Assignment addition Assignment subtraction Assignment multiplication Assignment division Assignment module
>>= Assignment right shift <<= Assignment left shift &= Assignment bitwise AND |= Assignment bitwise OR ^= Assignment exclusive OR
,
Comma
From left to right
I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 23-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -5Loops & Decisions Part 1
----------------------------
Welcome to the fifth lesson in my course about MQL4. You can download the previous lesson from here: http://forex-tsd.com/attachment.php?attachmentid=399 http://forex-tsd.com/attachment.php?attachmentid=372 http://forex-tsd.com/attachment.php?attachmentid=469 http://forex-tsd.com/attachment.php?attachmentid=481 Don’t forget to login first.
The normal flow control of the program you write in MQL4 (And in others languages as well) executes from top to bottom, A statement by a statement. A statement is a line of code telling the computer to do something. For example: Print("Hello World"); return 0; A semicolon at end of the statement is a crucial part of the syntax but usually easy to forget, and that's make it the source of 90% of errors.
But the top bottom execution is not the only case and it has two exceptions, They are the loops and the decisions. The programs you write like -the human- decides what to do in response of circu mstances changing. In these cases the flow of control jumps from one part of the program to another. Statements cause such jumps is called Control Statements. Such controls consist of Loops and Decisions.
LOOPS ----------------Loops causing a section of your program to be repeated a cer tain number of times. And this repetition continues while some condition is true and ends when it becomes false. When the loop end it passes the control to next statement follow the loop section. In MQL4 there are two kinds of loops:
The for Loop --------------------------
The for loop considered the easiest loop because all of its control elements are gathered in one place. The for loop executes a section of code a fixed number of times. For example: int j; for(j=0; j<15; j++) Print(j); How does this work?
The for statement consists of for keyword, followed by parentheses that contain three expressions separated by semicolons: for(j=0; j<15; j++)
These three expressions are the initialization expression, the test expression and the increment expression: j=0 initialization expression j<15 test expression J++ increment expression
The body of the loop is the code to be executed the fixed number of the loop: Print(j); This executes the body of the loop in our example for 15 times. Note: the for statement in not followed by a semicolon. That's because the for statement
and the loop body are together considered to be a program statement.
The initialization expression: The initialization expression is executed only once, when the loop first starts. And its purpose to give the loop variable an initial value (0 in our example). You can declare the loop variable outside (before) the loop like our example: int j;
Or you can make the declaration inside the loop parentheses like this: for(int j=0; j<15; j++)
The previous two lines of code are equal, except the Scope of each variable (you will know more about the variable declaration and scopes in the Variables lesson). The outside declaration method makes every line in the code block to know about the variable, while the inside declaration makes only the for loop to know about the variable. You can use more that one initialization expression in for loop by separating them with comma (,) like this: int i; int j; for(i=0 ,j=0;i<15;i++) Print(i);
The Test expression: The test expression always a relational expression that uses relational operators (please refer to relational operators in the previous lesson). It evaluated by the loop every time the loop executed to determine if the loop will continue or will stop. It will continue if the result of the expression is true and will stop if it false. In our example the body loop will continue printing i (Print(i)) while the case j<15 is true. For example the j = 0,1,2,3,4,5,6,7,8,9,10,11,12,13 and 14. And when j reaches 15 the loop will stops and the control passes to the statement following the loop.
The Increment expression:
The increment expression changes the value of the loop variable ( j in our example) by increase it value by 1. It executed as the last step in the loop steps, after initializing the loop variable, testing the test expression and executing the body of the loop. Figure 1 shows a flow chart of the for loop. Initialization expression
Test expression
Exit False
Body of loop
Increment expression
Figure 1 - Flow chart of the for loop
Like the initialization expression, in the increment expression you can use more than one increment expression in the for loop by separating them with comma (,) like this: int i; int j; for(i=0 ,j=0;i<15,i<;i++,j++) Print(i); But you can only use one test expression.
Another notice about the increment expression, it’s not only can increase the variable of the loop, but it can perform and operation it like for example decrements the loop variable like this: int i; for(i=15;i>0,i<;i--) Print(i); The above example will initialize the i to 15 and start the loop, every time it decreases i by 1 and check the test expression (i>0). The program will produce these results: 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1. Multi statement in the loop body:
In our previous examples, we used only one statement in the body of t he loop, this is not always the case. You can use multi statements in the loop body delimited by brac es like this: for(int i=1;i<=15;i++) { Print(i); PlaySound("alert.wav"); } In the above code the body of the loop contains two statements, the program will execute the first statement then the second one every time the loop executed. Don’t forget to put a semicolon at the end of every statement. The Break Statement:
When the keyword presents in the for loop (and in while loop and switch statement as well) the execution of the loop will terminate and the con trol passes to the statement followed the loop section. For example: for(int i=0;i<15;i++) { if((i==10) break; Print(i); } The above example will execute the loop until i reaches 10, in that case the break keyword
will terminate the loop. The code will produce these values: 0,1,2,3,4,5,6,7,8,9. The Continue Statement:
The break statement takes you out the loop, while the continue statement will get you back to the top of the loop (parentheses). For example: for(int i=0;i<15; i++) { if(i==10) continue; Print(i) } The above example will execute the loop until i reaches 10, in that case the continue keyword will get the loop back to the top of the loop without printing i the tenth time. The code will produce these values: 0,1,2,3,4,5,6,7,8,9,11,12,13,14. Latest note:
You can leave out some or all of the expressions in for loop if you want, for example: for(;;) This loop is like while loop with a test expression always set to true. We will introduce the while loop to you right now.
The while Loop --------------------The for loop usually used in the case you know how many times the loop will be executed. What happen if you don’t know how many times you want to execute the loop? This the while loop is for. The while loop like the for loop has a Test expression. But it hasn’t Initialization or Increment expressions. This is an example: int i=0; while(i<15) { Print(i); i++;
} In the example you will notice the followings: •
•
The loop variable had declared and initialized before the loop, you can not declare or initialize it inside the parentheses of the while loop like the for loop. The i++ statement here is not the increment expression as you may think, but the body of the loop must contain some statement that changes the loop variable, otherwise the loop would never end.
How the above example does work?
The while statement contains only the Test expression, and it will examine it ev ery loop, if it’s true the loop will continue, if it’s false the loop will end and the control passes to the statement followed the loop section. In the example the loop will execute till i reaches 16 in this case i<15=false and the loop ends.
Figure 2 shows a flow chart of the while loop.
Test expression
Exit False
True Body of loop
Figure 2 - Flow chart of the while loop
I told you before that the while loop is like the for loop, these are the similar aspects:
1. You can use break statement and continue in both of them. 2. You can single or multi statements in the body of the loop in both of them, in the case of using multi statements you have to delimit them by braces. 3. The similar copy of for(;;) is while(true)
I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 24-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com
-6Loops & Decisions Part 2
----------------------------
Welcome to the sixth lesson in my course about MQL4. I hope you enjoyed the previous lessons. In the previous lesson, we have talked about the Loops. And we have seen that the Loops are one of two ways we u se to change the normal flow of the program execution -from top to bottom. The second way is the Decisions. Decisions in a program cause a one-time jump to a different part of the program, depending on the value of an expression. These are the kinds of decisions statements available in MQL4:
The if Statement --------------------------------
The if statement is the simplest decision statement, here’s an example: if( x < 100 ) Print("hi"); Here the if keyword has followed by parentheses, inside the parentheses the Test expression ( x < 100), when the result of test expression is true the body of the if will execute (Print("hi");) ,and if it is false, the control passes to the statement follows the if block. Figure 1 shows the flow chart of the if statement:
Test expression
False
True Body of if
Exit
Figure 1 - Flow chart of the if statement Multi Statements in the if Body :
Like the loops, the body of if can consist of more than statement delimited by braces. For example: if(current_price==stop_lose) { Print("you have to close the order"); PlaySound("warning.wav"); }
Notice the symbol == in the Test expression; it's one of the Relational Operators you have studied in the lesson 4, operations & expressions. This is a source of a lot of errors, when you forget and use the assignment operator =. Nesting:
The loops and decision structures can be basted inside one another; you can nest ifs
inside loops, loops inside ifs, ifs inside ifs, and so on. Here's an example: for(int i=2 ; i<10 ; i++) if(i%2==0) { Print("It's not a prime nomber"); PlaySound("warning.wav"); }
In the previous example the if structure nested inside the for loop. Notice: you will notice that there are no braces around the loop body, this is because the if statement and the statements inside its body, are considered to be a single statement.
The if...else Statement ------------------------------------------
The if statement let's you to do something if a condition is true, suppose we want to do another thing if it's false. That's the if...else statement comes in. It consist of if statement followed by statement or a block of statements, then the else keyword followed by another statement or a block of statements. Like this example: if(current_price>stop_lose) Print("It’s too late to stop, please stop!"); else Print("you playing well today!"); If the test expression in the if statement is true, the program one message, if it isn’t true, it prints the other. Figure 2 shows the flow chart of the if…else statement:
Test expression
False
True Body of if
Body of else
Exit
Figure 2 - Flow chart of the if..else statement Nested if…else Statements
You can nest if…else statement in ifs statements, you can nest if…else statement in if…else statement, and so on. Like this:
if(current_price>stop_lose) Print("It’s too late to stop, please stop!"); if(current_price==stop_lose) Print("It’s time to stop!"); else Print("you playing well today!"); There’s a potential problem in nested if…else statements, you can inadvertently match an else with the wrong if. To solve this case you can do one of two things:
1- you can delimited the if…else pairs with braces like this: if(current_price>stop_lose) { Print("It’s too late to stop, please stop!"); if(current_price==stop_lose) Print("It’s Print("It’s time to stop!"); else Print("you playing well today!"); }
2- If you can’t do the first solution (in the case of a lot l ot of if…else statements or you are lazy to do it) take it as rule. Match else with the nearest if. (Here it’s the line if(current_price==stop_lose)).
The switch Statement ------------------------------------------
If you have a large decision tree, and all the decisions depend on the value of the same variable, you can use a switch statement here. Here’s an example: switch(x) { case 'A': Print("CASE A"); break; case 'B': case 'C': Print("CASE B or C"); break; default: Print("NOT Print("NOT A, B or C"); break; } In the above example the switch keyword is followed fo llowed by parentheses, inside the parentheses you’ll find the switch constant, this constant can be an integer, a character constant or a constant c onstant expression. The constant expression mustn’t include include variable varia ble for example: case X+Y : is invalid switch constant. How the above example works?
The switch statement matches the constant x with one of the cases constants. In the case x=='A' the program will print "CASE A" and the break statement will take you the control out of the switch block. In the cases x=='B' or x=='C', the program will print "CASE B or C" . That’s because there’s no break statement after case 'B':. In the case that x != any of o f the cases ca ses constants the switch statement will execute execute the default case and print "NOT A, B or C". Figure 3 shows the flow chart of the switch statement
switch variable equals first ca e c n tant
True
First case body
False
switch variab v ariable le equals second ca e c n tant
True
Second case body
False
switch variab v ariable le equals third ca e c n tant
True
Third case body
False Default body
Exit
Figure 3 - Flow chart of the switch statement
I hope you enjoyed the lesson. I welcome very much the questions questions and the suggestions. suggestions. See you Coders’ Guru 25-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com
-7Functions -------------------
Welcome to the world of MQL4 Functions. The functions in any language take two phases: Learning them which sometimes a boring thing. Using them which always a lifeboat. I want to tell you my traditional sentence: I hope you enjoyed the previous lessons, which you can download them from here: 1- Lesson 1 - Welcome to the MQL4 course. http://www.forex-tsd.com/attachment.php?attachmentid=372 2- Lesson 2 – SYNTAX. http://www.forex-tsd.com/attachment.php?attachmentid=399 3- Lesson 3 - MQL4 Data types. http://www.forex-tsd.com/attachment.php?attachmentid=469 4- Lesson 4 - MQL4 Operations & Expressions. http://www.forex-tsd.com/attachment.php?attachmentid=481 5- Lesson 5- Loops & Decisions (Part1). http://www.forex-tsd.com/attachment.php?attachmentid=504 6- Lesson 6 - Loops & Decisions (Part2). http://www.forex-tsd.com/attachment.php?attachmentid=547 Let’s start the seventh lesson.
What’s the meaning of functions? The function is very like the sausage machine, you input the meat and the spices and it outs the sausage. The meat and the spices are the function parameters; the sausage is the function return value. The machine itself is the function body. There’s only one difference between the functions and your s ausage machine, some of the functions will return nothing (nothing in MQL4 called void).
Let’s take some examples: double // type of the sausage – return value my_func (double a, double b, double c) // function name and parameters list (meat & spices) { return (a*b + c); // sausage outs - returned value }
As you see above, the function starts with the type of the returned value “double ” followed by the function name which followed by parentheses. Inside the parentheses you put the meat and a nd spices, sorry, you put p ut the parameters of the function. Here we have put three parameters double a, double b, double c . Then the function body starts and ends with braces. In o ur example the function body will produce the operation (a*b + c). The return keyword is responsible responsible about returning the final fin al result.
Return Return keyword: The return keyword terminate the function (like the break keyword does in the loop), and it gives the control to the function caller (we will know it soon). The return keyword can include an expression inside its parentheses like the above example return (a*b + c); and this means to terminate the function and return the result of the expression. And it can be without expression expression and its only job j ob in this case is to terminate the function. Notice: Not all the functions use the return keyword, especially if there’s no return value. Like the next example: void // void mean there’s no sausage – returned value. my_func (string s) s ) // function name and parameters list (meat & spices) { Print(s); } The function above will not return value, but it will print the parameter s you provided. When the function has no return value va lue you use “ void” as the funciotn returns type. These kinds of functions in some programming language ca lled “Methods”, but MQL4 calling them functions.
Function call:
We know very well now what the function is (I hope)? How to use the functions in your MQL4? There’s an extra steps after writing your function to use the function in you program. This step is calling it (using it). Assume you have a function which collects the summation of two integers. This is the function: int collect (int first_number, int second_number) { return(first_number+ second_number); } You know how the previous function works, but you want to use it. You use it like this: int a = 10; int b = 15; int sum = collect(a,b); Print (sum); The example above will print 25 (is it a magic). But how did it know? The magic line is int sum = collect(a,b); here you declared a variable (sum) to hold the function return value and gave the function its two parameters (a,b). You basically called the function. MQL4 when see your function name, it will take you parameters and go to the function and it will return –soon- with the result and place them in same line. It’s very like copying all the lines of the function instead of the place you called the function in, easy right?
Nesting functions inside function: You can nest function (or more) inside the body of another function. That’s because the caller line is treated like any normal statement (it’s actually a statement). For example: We will use the collect function described above inside another new function which its job is printing the result of the collection: void print_collection (int first_number, int second_number) { int sum = collect(first_number, second_number); Print(sum);
} Here we called the collect function inside the print_collection function body and printed the result. void means there’s no return vale (do you still remember?).
MQL4 Special functions init(), deinit() and start(): In MQL4, every program begins with the function “init()” (initialize) and it occurs when you attach your program(Expert advisor or Custom indicator) to the MetaTrader charts or in the case you change the financial symbol or the chart periodicity. And its job is initializing the main variables of your program (you will know about the variables initialization in the next lesson). When your program finishes its job or you close the chart window or change the financial symbol or the chart periodicity or shutdown MetaTrader terminal, the function "deinit()" (de-initialize) will occur. The third function (which is the most important one) “start()” will occur every time new quotations are received , you spend 90 of your programmin g life inside this function. We will know a lot about these functions in our real world lessons when we write our own Expert advisor and Custom Indictor. I hope you enjoyed the lesson. I welcome very much the questions and the suggestions. See you Coders’ Guru 25-10-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com
-8Variables -------------------Welcome to my MQL4 variables. I hope you enjoyed the previous lessons and I hope you are ready for the variables challenge: I recommend you to read the “DATA TYPES” lesson before reading this lesson. You can download it here: http://forex-tsd.com/attachment.php?attachmentid=469 Now, let’s enjoy the Variables. What are the variables mean?
As I told you the secret before, the variables are the names that refer to sections of memory into which data can be stored. To help you think of this as a picture, imagine that memory is a series of different size boxes. The box size is memory storage area required in bytes. •
•
•
• •
In order to use a box to store data, the box must be given a name; this process is known as declaration. In the declaration process you use a word tell the computer what’s the kind and size of the box you want to use, this word known as keyword. It helps if you give a box a meaningful name that relates to the type of information which make it easier to find the data, this name is the variable constant. Data is placed into a box by assigning the data to the box. When we set the value of the box you have created in the same line you declared the variable; this process is known as initialization.
When we create a variable we are telling the computer that we want him to assign a specified memory length (in bytes) to our variable, since storing a simple number, a letter or a large number is not going to occupy the same space in memory, so the computer will
ask us what’s the kind of data and how much the length of the data? That is the Data type for. For example if we said this line of code to the computer: int MyVaraible=0; That’s mean we are asking the computer to set a block of 4 bytes length to our variable named “MyVaraiable”. In the previous example we have used: int Keyword int Integer data type. int Declaration MyVaraible Variable’s constant. =0 Initialization We will know more about variables in a coming lesson. In MQL4, these are the kinds of Data types: • • • • • • •
Integer (int) Boolean (bool) Character (char) String (string) Floating-point number (double) Color (color) Datetime (datetime)
I’ve copied the previous few lines from the DATA TYPES lesson for you. To know what’s the variable, now how do to declare the variables:
Declaration: Declaring a variable means to introduce it to the world and specify its type. By using the keywords you have learned in the DATA TYPES lesson (int, double, char, bool, string, color and datetime) with the name you chose to the variable. For example: int MyVaraible;
Here you declared a variable named MyVaraible which is an integer type. And before the declaration you can’t use the MyVariable in your code. If you used it without declaration the MQL4 compiler will complain and will tell you something like this:'MyVaraible' - variable not defined . 1 error(s), 0 warning(s).
Initialization: Initializing the variable means to assign a value to it, for example MyVaraible=0; You can initialize the variable at the same line of the declaration like the example: int MyVaraible=0; And you can declare the variable in one place and initialize it in another place like this: int MyVaraible; … … MyVaraible=5; But keep in your mind this fact: the declaration must be before the initialization.
Scopes of variables: There are two scopes of the variables, Local and Global. Scope means, which part of code will know about the variable and can use it. Local variable means they are not seen to outside world where they had declared. For example the variables declared inside function are local to the function block of code, and the variables declared inside the loop or decisions block of code are loca l to those blocks and can be seen or used outside them.
For example: double my_func (double a, double b, double c) { int d ; return (a*b + c); }
In the above example the variables a,b,c and d are local variables, which can be used only inside the function block of code ( any thing beside the braces) and can’t be used by outside code. So we can’t write a line after the function above saying for example: d=10; because d is not seen to the next line of the function because it’s outside it.
The second kind of the scopes is the Global variables , and they are the variables which had declared outside any block of code and can be seen from an y part of your code. For example: int Global_Variable; double my_func (double a, double b, double c) { return (a*b + c + Global_Variable); } Here the variable Global_Variable declared outside the function (function level declaration) so, it can be seen by all the functions in you program. The Global variables will automatically set to zero if you didn’t initialize them.
Extern variables: The keyword “extern” used to declare a special kind of variables; those kinds of variables are used to define input date of the program, which you can set them form the property of your Expert advisor or Custom indicator. For example: extern color Indicator_color = C'0x00,0x00,0xFF'; // blue int init() { ... }
Here the variable Indicator_color had defined as an extern variable which you will see it the first time you attach your indicator (or EA) to the MetaTrader chart and which you can change it from the properties sheet windows. Look at Figure 1.
Figure 1: Property sheet of MA indicator
Here the variables Period, Shift, MA_method, Apply_to and Style are variables defined using the “extern” keyword so they appear in the property sheet. Any variable you want the user of your program be able to change and set, make it extern variable.
I hope you enjoyed the lesson. I welcome very much the questions and the suggestions.
See you Coders’ Guru 29-10-2005
MQL4 COURSE By Coders’ guru
-9Preprocessors -------------------Welcome to my last theoretical lesson in this series. In the next series of lessons we will start to build our first Customer Indicator, So I recommend you to read all the nine lessons carefully before the real work starts.
Now, let’s enjoy the Preprocessors:
What are the Preprocessors mean? Preprocessors are the instructions you give to the compiler to carry them out before starting (processing) your code. For example if you used the preprocessor directive #include
that’s mean you telling the compiler to include the content of the file “ win32.h” in the place you wrote the include keyword before processing your code. In MQL4 there are four of preprocessors directives:
1- define directive: define directive used to generate a constant.
The constant is very like the variable with only one different, you set its value only once and you can not change its value in your code like the variable. For example:
#define my_constant
100
As you can notice in the above example there’s no assignment symbol (=) but only space between the constant name (my_constant ) and its value (100). And you can notice too that the line didn’t end with semi-colon but it ended with a carriage-return character (new line). The name of constant obeys the same rules you had learnt about choosing the identifier names (lesson 2 SYNTAX), for example you can’t start the constant name with a number or exceeds 31 characters. The value of the content can be any type you want. The compiler will replace each occurrence of constant name in your source code with the corresponding value. So you can use the above constant in your code like that:
sum = constant1 * 10;
2- property directive: There are predefined constants called “Controlling Compilation ” included in the MQL4 language, which you can set them in your program. They are the properties of your program which you can set them using the compiler directive “property ” and the compiler will write them in the settings of your executable program (ex4 file). For example:
#property link "http://www.forex-tsd.com" #property copyright "Anyone wants to use" This is the list of the MQL4 predefined constants:
Constant
Type
Description
link
string
a link to the company website
copyright
string
the company name
stacksize
int
stack size
indicator_chart_window
void
show the indicator in the chart window
indicator_separate_window void
show the indicator in a separate window
indicator_buffers
int
the number of buffers for calculation, up to 8
indicator_minimum
int
the bottom border for the chart
indicator_maximum
int
the top border for the chart
indicator_colorN
color
the color for displaying line N, where N lies between 1 and 8
indicator_levelN
double
predefined level N for separate window custom indicator, where N lies between 1 and 8
show_confirm
void
before script run message box with confirmation appears
show_inputs
void
before script run its property sheet a ppears; disables show_confirm property
3- include directive: When you asking the compiler to include a file name with the “include” directive, it’s very like when you copy the entire file content and paste it in the place of the line you write include. For example:
#include In the above example you telling the compiler to open the file “ win32.h” and reads all of its content and copy them in the same place of the include statement. Note: in the above example you enclosed the file name with Angle brackets (<>) and that’s mean you telling the compiler to use the default directory (usually, terminal_directory\experts\include) to search for the file win32.h and don’t search the current directory.
If the file you want to include located at the same path of your code, you have to use quotes instead of angle brackets like this:
#include “mylib.h” In the both cases if the file can’t be found you will get an error message. You can use include at anywhere you want but it usually used at the beginning of the source code. Tip: It’s a good programming practice to write the frequently used code in a separate file and use include directive to put it in your code when you need (just an advice).
4- import directive: It’s like include directive in the aspect of using outside file in your program. But there are differences between them. You use import only with MQL4 executables files (.ex4) or library files (.dll) to import their functions to your program. For example:
#import "user32.dll" int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); int MessageBoxExA(int hWnd,string lpText,string lpCaption, int uType,int wLanguageId); #import "melib.ex4" #import "gdi32.dll" int GetDC(int hWnd); int ReleaseDC(int hWnd,int hDC); #import When you import functions from “ex4” file you haven’t to declare their functions to be ready for use. While importing the functions from a “.dll” file requires you to declare the functions you want to use like this:
int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); And only the functions you has declared you can use in your code.
You must end the import directives with a blank import line #import (without parameters).
I hope you enjoyed the lesson. And I hope you are ready now for your first Custom Indicator. I welcome very much the questions and the suggestions.
See you Coders’ Guru 30-10-2005
MQL4 COURSE By Coders’ guru
-10Your First Indicator Part 1
------------------------------Welcome to the practical world of MQL4 courses; welcome to yo ur 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.
Editor window
Navigator Window
Toolbox window
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.
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 yo u 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 t he 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 ad d 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 c ode 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 01-11-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -11-
Your First Indicator Part 2 -------------------------------
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
Main chart window
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.
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: #propery indicator_minimum
0
#propery indicator_minimum
100
#propery indicator_level1
10
//set the first indicator buffer level
#propery indicator_level2
65.5
//set the second indicator buffer 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 2 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);
The 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 06-11-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -12-
Your First Indicator Part 3 -------------------------------
Welcome to the third part of “Your First Indicator” lesson. In the previous lesson we studied the code of our first indicator line by line and we reached the function dinit(). I hope you’ve came from the previous lessons with a clear idea about what we have done. Today we are going to study start() function and its content. And – finally- we will compile and run our first Indicator. Are you ready? Let’s hack the code line by line:
Our 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); } //+------------------------------------------------------------------+
int start() {... return(0); }
As I told you before, we will spend 90% of programming life inside the braces of start() function. That’s because it’s the most important MQL4 Special functions. On the contrary of the init() and deinit function, start() will not be called (by the terminal client) only one time, But every time a new quotation arrives to MetaTrader terminal client, every time the start() function has been called.
start() function returns an integer value like all of the MQL4 special function, where 0 means no error and any number else means an error has been occurred.
int
counted_bars=IndicatorCounted();
Here, we have defined the variable counted_bars as an integer type, and we have assigned to it the returned value of the function IndicatorCounted().
int IndicatorCounted() This function will return an integer type value holds the count of the bars which our indicator has been calculated them. In the first launch of your 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. (Please see the function Bars below).
if (counted_bars<0) return(-1);
We have got the number of counted_bars in the previous line of code by using IndicatorCounted() function. This number must be 0 or greater if there’s no errors have been occurred. If it’s less than 0 that’s means we have an error and we have to terminate the start() function using the return statement.
if (counted_bars>0) counted_bars--;
We are checking here if the counted_bars are greater than 0. If that’s true we decrease this number by subtracting 1 from it. That’s because we want to recount the last bar again. We use the decrement operator (please review Lesson 4 - Operations & Expressions) for decreasing the value of counted_bars by 1. Note: We can write the expression counted_bars-- like this: counted_bars = counted_bars-1;
int
pos=Bars-counted_bars;
Here, we are declaring the variable pos to hold the number of times our calculation loop
will work (see while loop later in this lesson). That’s by subtracting the counted_bars from the count of total bars on the chart, we get the total bars count using Bars() function. It’s a good time to discuss Bars() function and its brother.
Pre-defined MQL4 variables: Ask, Bid, Bars, Close, Open, High, Low, Time and Volume are functions although MQL4 called them Pre-defined variables. And I’ll proof to you why they are functions. Variable means a space in memory and data type you specify. Function means do something and return some value, For example Bars collects and returns the number of the bars in chart. So, is it a variable? Another example will proof for you that they are not variables: If you type and compile this line of code: Bars=1; You will get this error: 'Bars' - unexpected token That’s because they are not variables hence you can’t assign a value to them. Another proof, the next line of code is a valid line and will not generate and error in compiling: Alert(Bars(1)); You can’t pass parameter to a variable, parameters passed only to the functions. I’m so sorry for the lengthiness, let’s discuss every function. int Bars
This function returns an integer type value holds count of the total bars on the current chart. double Ask
This function (used in your Expert Advisors) returns a double type value holds the buyer’s price of the currency pair. double Bid
This function (used in your Expert Advisor) returns a double type value holds the seller’s price of the currency pair.
Note: For example, USD/JPY = 133.27/133.32 the left part is called the bid price (that is a price at which the trader sells), the second (the right part) is called the ask price (the price at which the trader buys the currency).
double Open[]
This function returns a double type value holds the opening price of the referenced bar. Where opening price is the price at the beginning of a trade period (year, month, day, week, hour etc) For example: Open[0] will return the opening price of the current bar. double Close[]
This function returns a double type value holds the closing price of the referenced bar. Where closing price is the price at the end of a trade period For example: Close[0] will return the closing price of the current bar. double High[]
This function returns a double type value holds the highest price of the referenced bar. Where it’s the highest price from prices observed during a trade period. For example: High [0] will return the highest price of the current bar. double Low[]
This function returns a double type value holds the lowest price of the referenced bar. Where it’s the lowest price from prices observed during a trade period. For example: Low [0] will return the lowest price of the current bar. double Volume[]
This function returns a double type value holds the average of the total amount of currency traded within a period of time, usually one day. For example: Volume [0] will return this average for the current bar. int Digits
This function returns an integer value holds number of digits after the decimal point (usually 4). double Point
This function returns a double value holds point value of the current bar (usually 0.0001.
datetime Time[]
This function returns a datetime type value holds the open time of the referenced bar. For example: Time [0] will return the open time of the current bar.
double dHigh , dLow , dResult;
We declared three double type variables which we will use them later. Notice the way we used to declare the three of them at the same line by separating them by coma.
Comment("Hi! I'm here on the main chart windows!");
This line of code uses the Comment function to print the text “Hi! I'm here on the main chart windows!” on the left top corner of the main chart (figure1). There are two similar functions: void Comment( ... )
This function takes the values passed to it (they can be any type) and print them on the left top corner of the chart (figure 1). void Print ( ... ) This function takes the values passed to it (they can be any type) and print them to the expert log (figure 2). void Alert( ... )
This function takes the values passed to it (they can be any type) and display them in a dialog box (figure 3)
Figure 1 – Comment
Figure 2- Expert log
Figure 3 - Alerts
while(pos>=0) { dHigh = High[pos]; dLow = Low[pos]; dResult = dHigh - dLow; ExtMapBuffer1[pos]= dResult ; pos--; }
Now, it’s the time to enter the loop for calculating our indicator points to draw them. Any value we assign to the array ExtMapBuffer1[] will be drawn on the chart (because we have assign this array to the drawn buffer using SetIndexBuffer function). Before we enter the loop we have got the number of times the loop will work by subtracting the counted_bars from the total count of the bars on chart. The number of times the loop will work called Loop variable which it’s pos variable in our example. We use the loop variable as a current bar of the calculation for example High[pos] will return the highest price of the pos bar. In the loop body we assign to the variable dHigh the value of the highest price of the current loop variable.
And assign to the variable dLow the value of the lowest price of the current loop variable. The result of subtracting dLow from dHigh will be assigned to the variable dResult. Then we using the dResult to draw or indicator line, by assigning it to the drawn buffer array ExtMapBuffer1[]. The last line of the loop is a decrement expression which will decrease the loop variable pos by 1 every time the loop runs. And when this variable reaches -1 the loop will be terminated.
Finally, we can compile our indicator. Press F5 or choose Compile from file menu. That will generate the executable file “My_First_indicator.ex4” which you can load in your terminal client. To load your indicator click F4 to bring the terminal client. Then From the Navigator window find the My_First_indicator and attach it to the chart (figure4). Note: The indicator will not do much, but it believed that the subtraction of the highest and lowest of the price gives us the market's volatility.
Figure 4 – My_First_Indicator
I hope you enjoyed your first indicator. And be prepared to your first Expert Advisor in the next lesson(s). I welcome very much your questions and suggestions.
Coders’ Guru 13-11-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -13Your First Expert Advisor Part 1 --------------------
In the previous lesson we created our first indicator. Although this indicator wasn’t useful for us as trader, but it was very useful for us as programmers. The indicators –in general- are very important for the technical analysis of the market in trying to predict the future prices. But with the indicators we observe the chart then use our h ands to sell, buy and modify our orders manually. You have to set in front of your terminal, and keep your eyes widely open. If you get tired, want to drink a cup of tea or even take a short vacation. You have to consider one of these solutions: You may rent someone to observe the terminal for you and calling your mobile phone every five minutes to tell you what’s going on. If t his employee is an expert, he will cost you the pips you earn. And if he is novice one, he will cost you your capital. The second solution is using a program to automate your trades. That’s what the Expert Advisor is for. The Expert advisor is a program wrote in MQL4 (we are studying MQL4 huh?) uses your favorite indicators and trade methods to automate your orders. It can buy, sell and modify the orders for you. It enables you to drink a cup of tea and save the salary you gave out to your employee or the bunch of flowers you bring to your assistant wife. Today we are going to create our first expert advisor so let’s go.
First two steps: Step1: If you didn’t open your MetaEditor yet, I think it’s the time to run it.
From the MetaEditor File menu click New (you can use CTRL+N hotkey or click the New icon in the standard toolbar). That will pop up the new program wizard which you have seen when you created your first indicator (Figure 1). This time we will choose the first option “Expert Advisor program” then click Next button.
Figure 1 – the first step wizard
Step2: When you clicked Next, you have got the general properties wizard (Figure 2). This wizard enables you to set the properties of your expert advisor and to set the external variables you will use in your expert advisor. In this step you can set these properties: 1234-
Name of your expert advisor, in our sample we will use My_First_EA. Author name of the program, type your name (I typed mine in the sample). Link to your web site. External variables list:
This is the list of the external variables you allow the user of your expert advisor to change them from the Expert properties window.
To add a new variable you click the Add button, clicking it will add a new record to the external variables list. Every record has three fields: Name: double click this field to set the name (identifier) of the variable. Type: double click this field to set the data type of the variable. Initial value : double click this field to give your variable initialization value. This field is optional which means you can leave it without setting
In our sample we have added three variables: Varaible Type initial value --------------------------------------TakeProfit double 350 Lots double 0.1 TrailingStop double 35
Figure 2 – the second step wizard
Now click the Finish button to close the wizard, and MetaEditor will bring to you the code created by the wizard and saves the file My_First_EA.mq4 in the MetaTrader 4 \experts path. Note: you have to put the expert advisors in MetaTrader 4\experts path and the indicators in MetaTrader 4\experts\indicators path, otherwise they will not work.
This is the code we have got from the wizard:
//+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---//---return(0); } //+------------------------------------------------------------------+
As you see above, the code generated by the wizard is a template for you to add your code without bothering you by typing the main functions from scratch. Now let’s add our own code:
//+------------------------------------------------------------------+ //| My_First_EA.mq4 |
//| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0); } int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_dirction = 0; if(line1>line2)current_dirction = 1; //up if(line1
if(current_dirction != last_direction) //changed { last_direction = current_dirction ; return (last_direction); } else { return (0); } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //----
int cnt, ticket, total; double shortEma, longEma;
if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit }
shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0); longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0); int isCrossed
= Crossed (shortEma,longEma);
total = OrdersTotal(); if(total < 1) { if(isCrossed == 1) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point, "My EA",12345,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()); return(0); } if(isCrossed == 2) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0, Bid-TakeProfit*Point,"My EA",12345,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()); return(0); } return(0); } for(cnt=0;cnt
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol()) { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(isCrossed == 2) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()0) { if((OrderOpenPrice()-Ask)>(Point*TrailingStop)) { if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0)) { OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop, OrderTakeProfit(),0,Red); return(0); } } } } } } return(0); } //+------------------------------------------------------------------+
Note: don’t copy and paste the code above because it warped and will not work for you, use the code provided with lesson in www.forex-tsd.com .
Scared? Don’t be scared of the 160 lines you have seen above, we will know everything about this code line by line, I promise it’s an easy task.
Test the Expert Advisor: Before studying our expert advisor code we have to be check is it profitable one or not. Note: Our expert advisor will work with EURUSD pairs in 4 Hours timeframe. So compile the expert advisor by pressing F5 and load it in MetaTrader.
You can test your expert advisor using two methods: 1- Live trading
In live trading testing the results are more accurate but you have to spend days (and maybe months) to know is the expert advisor profitable or not. You have to enable the expert advisor to automate your trades. To enable it click Tools Option menu (or use CTRL+O hotkey), that’s will bring the Options windows (figure 3), click Expert Advisors tab and enable these options: Enable Expert Advisors Allow live trading And click Ok button
Figure 3 – Enabling expert advisor auto trade
You will see the Smile symbol beside the expert advisor name which means your expert advisor is working and ready to trade for you (Figure 4).
Figure 4 – Expert advisor is enabled 2- Strategy Tester:
The second method of testing your expert advisor which is less accurate but will not take time is the Strategy tester. We will know e verything about Strategy tester later, let’s now bring its window by pressing F6 (Figure 5). When you get the window enter these options: Symbol: EURUSD. Period: H4 (4 Hours). Model: Open price only.
Figure 5 – Strategy tester window
Now click Start button to start testing the expert advisor. You will see a progress bar and the two tabs (Settings and Journal) became five tabs. We interested in Report tab (Figure 6); click it to see your profit.
We have a lot to say and to do in the next lesson; I hope you are ready for the challenge. I welcome very much the questions and the suggestions. See you Coders’ Guru 24-11-2005
MQL4 COURSE By Coders’ guru www.forex-tsd.com -14Your First Expert Advisor Part 2 --------------------
Welcome to the second part of creating Your First Expert Advisor lesson. In the previous part we have taken the code generated by the new program wizard and added our own code which we are going to crack it today line by line. Did you wear your coding gloves? Let’s crack. Note:
I have to repeat that our expert advisor is for educational purpose only and will not (or aimed to) make profits.
The code we have: //+------------------------------------------------------------------+ //| My_First_EA.mq4 | //| Coders Guru | //| http://www.forex-tsd.com | //+------------------------------------------------------------------+ #property copyright "Coders Guru" #property link "http://www.forex-tsd.com" //---- input parameters extern double TakeProfit=250.0; extern double Lots=0.1; extern double TrailingStop=35.0; //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //----
//---return(0); } int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_direction = 0; if(line1>line2)current_direction = 1; //up if(line1
if(current_direction != last_direction) //changed { last_direction = current_direction; return (last_direction); } else { return (0); } } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //----
int cnt, ticket, total; double shortEma, longEma;
if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit }
shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0); longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0); int isCrossed
= Crossed (shortEma,longEma);
total = OrdersTotal(); if(total < 1) { if(isCrossed == 1)
{ ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point, "My EA",12345,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()); return(0); } if(isCrossed == 2) { ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0, Bid-TakeProfit*Point,"My EA",12345,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()); return(0); } return(0); } for(cnt=0;cnt0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()
// should it be closed? if(isCrossed == 1) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // 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); } } } } } } return(0); } //+------------------------------------------------------------------+
The idea behind our expert advisor. Before digging into cracking our code we have to explain the idea behind our expert advisor. Any expert advisor has to decide when to enter the market and when to exit. And the idea behind any expert advisor is what the e ntering and exiting conditions are? Our expert advisor is a simple one and the idea behind it is a simple too, let’s see it. We use two EMA indicators, the first one is the EMA of 8 days (sort EMA) and the second one is the EMA of 13 days (long EMA). using those EMAs or any thought in this lesson is not a recommendation of mine, they are for educational purpose only.
Note:
Entering (Open): Our expert advisor will enter the market when the short EMA line crosses the long EMA line, the direction of each lines will determine the order type: If the short EMA is above the long EMA will buy (long). If the short EMA is below the long EMA we will sell (short).
We will open only one order at the same time.
Exiting (Close): Our expert advisor will close the buy order when the short EMA crosses the long EMA and the short EMA is below the long EMA. And will close the sell order when the short EMA crosses the long EMA and the short EMA is above the long EMA. Our order (buy or sell) will automatically be closed too when the Take profit or the Stop loss points are reached.
Modifying: Beside entering (opening) and exiting (closing) the market (positions) our expert advisor has the ability to modify existing positions based on the idea of Trailing stop point. We will know how we implemented the idea of Trialing stop later in this lesson. Now let’s resume our code cracking. //---extern extern extern
input parameters double TakeProfit=250.0; double Lots=0.1; double TrailingStop=35.0;
In the above lines we have asked the wizard to declare three external variables (which the user can set them from the properties window of our expert advisor). The three variables are double data type. We have initialized them to default values (the user can change these values from the properties window, but it recommended to leave the defaults). I have to pause again to tell you a little story about those variables. Stop loss:
It’s a limit point you set to your order when reached the order will be closed, this i s useful to minimize your lose when the market going against you. Stop losses points are always set below the current asking price on a buy or above the current bid price on a sell. Trailing Stop
It’s a kind of stop loss order that is set at a percentage level below (for a long position) or above (for a short position) the market price. The price is adjusted as the p rice fluctuates. We will talk about this very important concept later in this lesson.
Take profit:
It’s similar to stop lose in that it’s a limit point you set to your order when reached the order will be closed There are, however, two d ifferences: • •
There is no “trailing” point. The exit point must be set above the current market price, instead of below.
Figure 1 – Setting Stop loss and Take profit points int Crossed (double line1 , double line2) { static int last_direction = 0; static int current_direction = 0; if(line1>line2)current_direction = 1; //up if(line1
if(current_direction != last_direction) //changed { last_direction = current_direction; return (last_direction); } else { return (0); }
}
As I told you before, the idea behind our expert advisor is monitor the crossing of the short EMA and the long EMA lines. And getting the direction of the crossing (which line is above and which line is below) which will determine the type of the order (buy, sell, buy-close and sell-close). For this goal we have created the Crossed function. The Crossed function takes two double values as parameters and returns an integer. The first parameter is the value of the first line we want to monitor (the short EMA in our case) and the second parameter is the value of the second we want to (the long EMA). The function will monitor the two lines every time we call it by saving the direction of the two lines in static variables to remember their state between the repeated calls. • •
•
It will return 0 if there’s no change happened in the last directions saved. It will return 1 if the direction has changed (the lines crossed each others) and the first line is above the second line. It will return 2 if the direction has changed (the lines crossed each others) and the first line is below the second line.
You can use this function in your coming expert advisor to monitor any two lines and get the crossing direction.
Note:
Let’s see how did we write it?
int Crossed (double line1 , double line2)
The above line is the function declaration, it means we want to create Crossed function which takes two double data type parameters and returns an integer. When you call this function you have to pass to it two double parameters and it will return an integer to you. You have to declare the function before using (calling) it. The p lace of the function doesn't matter, I placed it above start() function, but you can place it anywhere else. static int last_direction = 0; static int current_direction = 0;
Here we declared two static integers to hold the current and the last direction of the two lines. We are going to use these variables (they are static variables which means they save their value between the repeated calls) to check if there’s a change in the di rection of the lines or not.
we have initialized them to 0 because we don’t want them to work in the first call to the function (if they worked in the first call the e xpert advisor will open an order as soon as we load it in the terminal). if (current_direction != last_direction) //changed In this line we compare the two static variables to check for changes between the last call of our function and the current call. If last_direction not equal current_direction that’s mean there’s a change happened in the direction. last_direction = current_direction; return (last_direction);
In this case (last_direction not equal current_direction) we have to reset our last_direction by assigning to it the value of the current_direction. And we will return the value of the last_direction. This value will be 1 if the first line is above the second line and 2 if the first line is below the second line. else { return (0); }
Else (last_direction is equal current_direction) there’s no change in the lines direction and we have to return 0. Our program will call this function in its start() function body and use the returned value to determine the appropriate action. In the coming part of this lesson we will know how did we call the function, and we will know a lot about the very important trading functions. To that day I hope you the best luck. I welcome very much the questions and the suggestions. See you Coders’ Guru 01-12-2005
MetaQuotes Language 4 MQL4 quick reference Account Information Array Functions Common functions Conversion functions Custom Indicator functions Date & Time functions File functions Global Variables functions Math & Trig Object functions Pre-defined Variables Standard Constants String functions Technical Indicator calls Trading functions Window functions
MQL4 quick reference About MetaQuotes Language 4 Syntax Data types Operations & Expressions Operators Functions Variables Preprocessor
About MetaQuotes Language 4
MetaQuotes Language 4 (MQL4) is a new built-in language for programming trading strategies. This language allows to create your own Expert Advisors that render the trade process management automatic and are perfectly suitable for implementing your own trade strategies. Also, with the help of MQL4 you can create your own Custom Indicators, Scripts and Libraries of functions. A large number of functions necessary for the analysis of the current and past quotations, the basic arithmetic and logic operations are included in MQL4 structure. There are also basic indicators built in and commands of order placement and control. The MetaEditor 4 text editor that highlights different constructions of MQL4 language is used for writing the program code. It helps users to orient in the expert system text quite easily. As an i nformation book for MQL4 language we use MetaQuotes Language Dictionary. A brief guide c ontains functions divided into categories, operations, reserved words, and other language constructions and allows finding the description of every element we use. Programs written in MetaQuotes Language 4 have different features and p urposes: Expert Advisors is a mechanical trade system (MTS) linked up to a certain plot. The Advisor can not only inform you about a possibility to strike bargains, but also can make deals on the trade account automatically and direct them right to the trade server. Like most trade systems, the terminal supports testing strategies on historical data with displaying on the chart the spots where trades come in and out. Custom Indicators are an analogue of a technical indicator. In other words, Custom Indicators allow to create technical indicators in addition to those already integrated into client terminal. Like built-in indicators, they cannot make deals automatically and are aimed only at implementing analytical functions. Scripts are programs intended for single execution of some actions. Unlike Expert Advisors, Scripts are not run tick wise and have no access to indicator functions. Libraries are user functions libraries where frequently used blocks of user programs are stored. •
•
•
•
Syntax Format
Comments Identifiers Reserved words
Format
Spaces, tabs, line feed/form feed symbols are used as separators. You can use any amount of such symbols instead of one. You should use tab symbols to enhance the readability of the text .
Comments
Multi line comments start with /* symbols and end with */ symbols. Such comments cannot be nested. Single comments start with // symbols, end with the symbol of a new line and c an be nested into multi line comments. Comments are allowed where blank spaces are possible and tolerate any number of spaces. Examples: // single comment /* multiline // nested single comment comment */
Identifiers
Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 31 characters. Symbols you can use: the numbers 0-9, Latin capital and small letters a-z, A-Z (recognized as different symbols), the symbol of underlining (_). The first symbol cannot be a number. The identifier must not coincide with any reserved word. Examples: NAME1 namel Total_5 Paper
Reserved words
The identifiers listed below are fixed reserved words. A certain action is assigned to each of them, and they cannot be used for other purposes: Data types
Memory classes Operators
Other
bool
extern
break
false
color
static
case
true
datetime
continue
double
default
int
else
string
for
void
if return switch while
Data types Data types overview Integer constants
Literal constants Boolean constants Floating-point number constants String constants Color constants Datetime constants
Data types overview
The main data types are: • • • • • • •
Integer (int) Boolean (bool) Literals (char) String (string) Floating-point number (double) Color (color) Datetime (datetime)
We need the Color and Datetime types only to facilitate visualization and entering those parameters that we set from expert advisor property tab or custom indicator "Input parameters" tab. The data of Color and Datetime types are represented as integer values. We use implicit type transformation. The priority of types at a transformation in ascending order is the following: int (bool,color,datetime); double; string;
Before operations (except for the assignment ones) are performed, the data have been transferred to the maximum precision type. Before assignment operations are performed, the data have been transferred to the integer type.
Integer constants Decimal: numbers from 0 to 9; Zero should not be the first number. Examples: 12, 111, -956 1007 Hexadecimal: numbers from 0 to 9, letters a-f or A-F to represent the values 10-15; they start with 0x or 0X. Examples: 0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7
Integer constants can assume values from -2147483648 to 2147483647. If a constant exceeds this range, the result will not be defined.
Literal constants
Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like '\x10' is a character constant of integer type. Some characters like a single quote ('), double quote (") a question mark (?), a reverse slash (\) and control characters can be represented as a combination of characters starting with a reverse slash (\) according to the table below: line feed horizontal tab carriage return reverse slash single quote double quote hexadecimal ASCII-code
NL (LF) \n HT \t CR \r \ \\ ' \' " \" hh \xhh
If a character different from those listed above follows the reverse slash, the result will not be defined.
Examples: int int int int
a b c d
= = = =
'A'; '$'; '©'; // code 0xA9 '\xAE'; // symbol code ®
Boolean constants
Boolean constants may have the value of true or false, numeric representation of them is 1 or 0 respectively. We can also use synonyms True and TRUE, False and FALSE. Examples: bool a = true; bool b = false; bool c = 1;
Floating-point number constants
Floating-point constants consist of an integer part, a dot (.) and a fractional part. The integer and the fractional parts are a succession of decimal numbers. An unimportant fractional part with the dot can be absent. Examples: double double double double
a b c d
= = = =
12.111; -956.1007; 0.0001; 16;
Floating-point constants can assume values from 2.2e-308 to 1.8e308. If a constant exceeds this range, the result will not be defined.
String constants
String constant is a succession of ASCII-code characters enclosed in double quotes: "Character constant". A string constant is an array of characters enclosed in quotes. It is of the string type. Each string constant, even if it is identical to another string constant, is saved in a separate memory space. If you need to insert a double quote (") into the line, you must place a reverse slash (\) before it. You can insert any special character constants into the line if they have a reverse slash (\) before them. The length of a string constant lies between 0 and 255 characters. If the string constant is longer, the superfluous characters on the right are rejected. Examples: "This is a character string" "Copyright symbol \t\xA9" "this line with LF symbol \n" "A" "1234567890" "0" "$"
Color constants
Color constants can be represented in three ways: by character representation; by integer representation; by name (for concrete Web colors only). Character representation consists of four parts representing numerical rate values of three main c olor components red, green, blue. The constant starts with the symbol C and is enclosed in single quotes. Numerical rate values of a color component lie in the range from 0 to 255. Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal number looks like 0x00BBGGRR where RR is the rate of the red color component, GG - of the green one and BB - of the blue one. Decimal constants are not directly reflected in RGB. They represent the decimal value of the hexadecimal integer representation. Specific colors reflect the so-called Web colors set. Examples: // symbol constants C'128,128,128' // gray
C'0x00,0x00,0xFF' // named color Red Yellow Black // integer-valued 0xFFFFFF 16777215 0x008000 32768
// blue
representation // white // white // green // green
Datetime constants
Datetime constants can be represented as a character line consisting of 6 parts for value of year, month, date, hour, minutes, and seconds. The constant is enclosed in simple quotes and starts with a D character. Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037. Examples: D'2004.01.01 00:00' D'1980.07.19 12:30:27' D'19.07.1980 12:30:27' D'19.07.1980 12' D'01.01.2004' D'12:30:27' D''
// New Year
//equal //equal //equal //equal
to to to to
D'1980.07.19 12:00:00' D'01.01.2004 00:00:00' D'[compilation date] 12:30:27' D'[compilation date] 00:00:00'
Operations & Expressions Expressions Arithmetical operations The operation of assignment Operations of relation Boolean operations Bitwise operations Other operations Precedence rules
Expressions
An expression consists of one or more operands and operation characters. An expression can be written in several lines. Example: a++; b = 10; x = (y*z)/w;
Note: An expression that ends with a semicolon is an operator.
Arithmetical operations Sum of values Difference of values Changing the operation sign Product of values Division quotient Division remainder Adding 1 to the variable value Subtracting 1 from the variable value
i = j + 2; i = j - 3; x = - x; z = 3 * x; i = j / 5; minutes = time % 60; i++; k--;
The operations of adding/subtracting 1 cannot be implemented in expressions. Example: int a=3; a++; int b=(a++)*3;
// valid expression // invalid expression
The operation of assignment
Note: The value of the expression that includes this operation is the value of the left operand following the bind character. Assigning the y value to the x variable Adding x to the y variable Subtracting x from the y variable Multiplying the y variable by x Dividing the y variable by x Module x value of y Logical shift of y representation to the right by x bit Logical shift of y representation to the left by x bit Bitwise operation AND Bitwise operation OR Bitwise operation exclusive OR
y y y y y y y y y y y
= x; += x; -= x; *= x; /= x; %= x; >>= x; <<= x; &= x; |= x; ^= x;
Note: There can be only one operation of assignment in the expression. You can implement bitwise operations with integer numbers only. The logical shift operation uses values of x less than 5 binary digits. The greater digits are rejected, so the shift is for the range of 0-31 bit. By %= operation a result sign i s equal to the sign of divided number.
Operations of relation
The logical value false is represented with an integer zero value, while the logical value true is represented with any value differing from zero. The value of expressions containing operations of relation or logical operations is 0 (false) or 1 (true). True True True True True True
if if if if if if
a a a a a a
equals b does not equal b is less than b is greater than b is less than or equals b is greater than or equals b
a a a a a a
== b; != b; < b; > b; <= b; >= b;
Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why it is necessary to subtract one from another, and the normalized outcome needs to be compared to null.
Boolean operations
The operand of negation NOT (!) must be of arithmetic type; the result equals 1 if the operand value is 0; the result equals 0 if the operand differs from 0. // True if a is false. if(!a) Print("not 'a'");
The logical operation OR (||) of values k and 1. The value k is checked first, the value 1 is checked only if k value is false. The value of this expression is true if the value of k or 1 is true. Example: if(xl) Print("out of range");
The logical operation AND (&&) of values x and y. The value x is checked first; the value y is checked only if k value
is true. The value of this expression is true if the values of both x and y are true. Example: if(p!=x && p>y) Print("true"); n++;
Bitwise operations
One's complement of values of variables. The value of the expression contains 1 in all digits where n contains 0; the value of the expression contains 0 in all digits where n contains 1. b = ~n;
Binary-coded representation of x is shifted to the right by y digits. The right shift is logical shift, that is the freed leftside bits will be filled with zeros. Example: x = x >> y;
The binary-coded representation of x is shifted to the right by y digits; the free digits on the right will be filled with zeroes. Example: x = x << y;
Bitwise operation AND of binary-coded x and y representations. The value of the expression contains 1 (true) in all digits where both x and y are not equal to zero; the value of the expression contains 0 (false) in all other digits. Example: b = ((x & y) != 0);
Bitwise operation OR of binary-coded x and y representations. The expression contains 1 in all digits where x and y not equals 0; the value of the expression contains 0 in all other digits. Example: b = x | y;
Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression contains 1 in all digits where x and y have different binary values; the value of the expression contains 0 in all other digits. Example: b = x ^ y;
Note: Bitwise operations are executed with integers only.
Other operations
Indexing. At addressing to i element of array, the value of the expression equals the value of the variable numbered as i. Example: array[i] = 3; //Assign the value of 3 to array element with index i. //Mind that the first array element //is described with the expression array [0].
The call of function with x1,x2,...,xn arguments. The expression accepts the value returned by the function. If the returned value is of the void type, you cannot place such function call on the right in the assignment operation. Mind that the expressions x1,x2,...,xn are surely executed in this order. Example: double SL=Ask-25*Point; double TP=Ask+25*Point; int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,TP, "My comment",123,0,Red);
The "comma" operation is executed from left to right. A pair of expressions separated by a comma is calculated from left to right with a subsequent deletion of the left expression value. All side e ffects of left expression calculation can appear before we calculate the right expression. The result type and value coincide with the type and value of the right expression.
Precedence rules
Each group of operations in the table has the same priority. The higher the priority is, the higher the position of the group in the table is. The execution order determines the grouping of operations and operands. () [] ! ~ * / % + << >> < <= > >= == != & ^ | && || = += -= *= /= %= >>= <<= &= |= ^= ,
Function call Array element selection Negation Bitwise negation Sign changing operation Multiplication Division Module division Addition Subtraction Left shift Right shift Less than Less than or equals Greater than Greater than or equals Equals Not equal Bitwise AND operation Bitwise exclusive OR Bitwise OR operation Logical AND Logical OR Assignment Assignment addition Assignment subtraction Assignment multiplication Assignment division Assignment module Assignment right shift Assignment left shift Assignment bitwise AND Assignment bitwise OR Assignment exclusive OR Comma
From left to right From left to right
From left to right
From left to right From left to right From left to right
From left to right From From From From From From
left to right left to right left to right left to right left to right right to left
From left to right
Use parentheses to change the execution order of the operations.
Operators Format and nesting Compound operator Expression operator Break operator Continue operator Return operator Conditional operator if Conditional operator if-else Switch operator Cycle operator while Cycle operator for
Format and nesting
Format. One operator can occupy one or several lines. Two or more operators can be located in the same line. Nesting. Execution order control operators (if, if-else, switch, while and for) can be nested into each other.
Compound operator
A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. The closing brace should not be followed by a semicolon (;). Example: if(x==0) { x=1; y=2; z=3; }
Expression operator
Any expression followed by a semicolon (;) is an operator. Here are some examples of expression operators: Assignment operator. Identifier=expression;
Example: x=3; y=x=3; // error
You can use an assignment operator in an expression only once. Function call operator Function_name(argument1,..., argumentN);
Example: fclose(file);
Null operator It consists of a semicolon (;) only. We use it to denote a null body of a control operator.
Break operator
A break; operator terminates the execution of the nearest nested outward operator switch, while or for. The control is given to the operator that follows the terminated one. One of the purposes of this operator is to finish the looping execution when a certain value is assigned to a variable. Example: // searching first zero element for(i=0;i
Continue operator
A continue; operator gives control to the beginning of the nearest outward cycle operator while or for, calling the next iteration. The purpose of this operator is opposite to that of break. Example: // summary of nonzero elements of array int func(int array[]) { int array_size=ArraySize(array);
int sum=0; for(int i=0;i
Return operator
A return; operator terminates the current function execution and returns the control to the calling program. A return(expression); operator terminates the current function execution and returns the control to the calling program together with the expression value. The operator expression is enclosed in parentheses. The expression should not contain an assignment operator. Example: return(x+y);
Conditional operator if if (expression) operator;
If the expression is true, the operator will be executed. If the expression is false, the c ontrol will be given to the expression following the operator. Example: if(a==x) temp*=3; temp=MathAbs(temp);
Conditional operator if-else if (expression) operator1 else operator2
If the expression is true, operator1 is executed and the control is given to the operator that follows operator2 (operator2 is not executed). If the expression is false, operator2 is executed. The "else" part of the "if" operator can be omitted. Thus, a divergence may appear in nested "if" operators with an omitted "else" part. If it happens, "else" addresses to the nearest previous operator "if" in the block that has no "else" part. Example: // The "else" part refers to the second "if" operator: if(x>1) if(y==2) z=5; else z=6; // The "else" part refers to the first "if" operator: if(x>l) { if(y==2) z=5; } else
{ z=6; } // Nested operators if(x=='a') { y=1; } else if(x=='b') { y=2; z=3; } else if(x=='c') { y = 4; } else { Print("ERROR"); }
Switch operator switch (expression) { case constant1: operators; break; case constant2: operators; break; ... default: operators; break; }
It compares the expression value with constants in al l variants of case and gives control to the operator that resembles the expression value. Each variant of the case can be marked with an integer or character constant or a constant expression. The constant expression must not include variables and function calls. Example: case 3+4: //valid case X+Y: //invalid
Operators connected with a default label are executed if none of the constants in case operators equals the expression value. The default variant is not obligatory final. If none of the constants resembles the expression value and the default variant is absent, no actions are executed. The keyword case and the constant are just labels and if operators are executed for some variant of case the program will further execute the operators of al l following variants until it hits a break operator. It allows linking one succession of operators with several variants. A constant expression is calculated during compilation. None of two constants in one switch operator can have the same values. Example: switch(x) { case 'A': Print("CASE A\n"); break; case 'B': case 'C': Print("CASE B or C\n"); break; default: Print("NOT A, B or C\n");
break; }
Cycle operator while while (expression) operator;
If the expression is true, the operator is executed till the expression becomes false. If the expression is false, the control will be given to the next operator. Note: An expression value has been defined before the operator is executed. Therefore, if the expression is false from the very beginning, the operator is not executed at all. Example: while(k
Cycle operator for for (expression1; expression2; expression3) operator;
Expression1 describes the initialization of the cycle. Expression2 is the cycle termination check. If it is true, the loop body operator will be executed, Expression3 is executed. The cycle is repeated until Expression2 becomes false. If it is not false, the cycle is terminated, and the control is given to the next operator. Expression3 is calculated after each iteration. The 'for' operator is equivalent to the following succession of operators: expression1; while (expression2) { operator; expression3; };
Example: for(x=1;x<=7;x++) Print(MathPower(x,2));
Any of the three or all three expressions can be absent in the FOR operator, but you should not omit the semicolons (;) that separate them. If Expression2 is omitted, it is considered constantly true. The FOR (;;) operator is a continuous cycle equivalent to the WHILE(l) operator. Each of the expressions 1 to 3 can consist of several expressions united by a comma operator ','. Example: // for(i=0,j=n-l;i
Functions Function definition Function call Special functions init(), deinit() and start()
Function definition
A function is defined by return value type declaration, by formal parameters and a compound operator (block) that describes actions the function executes. Example: double // type linfunc (double x, double a, double b) // function name and // parameters list { // nested operators return (a*x + b); // returned value }
The "return" operator can return the value of the expression included i nto this operator. In case of a necessity, the expression value assumes the type of function result. A function that does not return a value must be of "void" type. Example: void errmesg(string s) { Print("error: "+s); }
Function call function_name (x1,x2,...,xn)
Arguments (actual parameters) are transferred according to their value. Each expression x1,...,xn is calculated, and the value is passed to the function. The order of expressions calculation and the order of values loading are guaranteed. During the execution, the system checks the number and type of arguments given to the function. Such way of addressing to the function is called a value call. There is also another way: call by link. A function call is an expression that assumes the value returned by the function. This function type must correspond with the type of the returned value. The function can be declared or described in any part of the program: int somefunc() { double a=linfunc(0.3, 10.5, 8); } double linfunc(double x, double a, double b) { return (a*x + b); }
Special functions init(), deinit() and start()
Any program begins its work with the "init()" function. "Init()" function attached to charts is launched also after client terminal has started and in case of changing financial symbol and/or charts periodicity. Every program finishes its work with the "deinit()" function. "deinit()" function is launched also by client terminal shutdown, chart window closing, changing financial symbol and/or charts periodicity. When new quotations are received, the "start()" function of attached expert advisors and custom indicator programs is executed. If, when receiving new quotations, the "start()" function triggered on the previous quotations was performed, the next calling "start()" function is executed only after "return()" instruction. All new quotations received during the program execution are ignored by the program. Detaching of the program from charts, changing financial s ymbol and/or charts periodicity, charts closing and al so client terminal exiting interrupts execution of program. Execution of scripts does not depend on quotations coming.
Variables Definitions Defining local variables Static variables
Defining global variables Defining extern variables Initializing variables External function definition
Definitions
Definitions are used to define variables and to declare types of variables and functions defined somewhere else. A definition is not an operator. Variables must be declared before being used. Only constants can be used to initialize variables. The basic types are: • • • •
string - a string of characters; int - an integer; double - a floating-point number (double precision); bool - a boolean number "true" or "false".
Example: string int double bool
MessageBox; Orders; SymbolPrice; bLog;
The additional types are: • •
datetime is date and time, unsigned integer, containing seconds since 0 o'clock on January, 1, 1970. color - integer reflecting a collection of three color components.
The additional data types make sense only at the declaration of input data for more convenient their representation in a property sheet. Example: extern datetime tBegin_Data = D'2004.01.01 00:00'; extern color cModify_Color = C'0x44,0xB9,0xE6';
Arrays Array is the indexed sequence of the identical-type data. Example: int a[50]; //A one-dimensional array of 50 integers. double m[7][50]; //Two-dimensional array of seven arrays, //each of them consisting of 50 integers.
Only an integer can be an array index. No more than four-dimensional arrays can be declared.
Defining local variables
The variable declared inside any function is local. The scope of a local variable is limited to limits of the function inside which it is declared. The local variable can be initialized by outcome of any expression. Every call of function execute the initialization of local variables. Local variables are stored in memory area of corresponding function. Formal parameters Examples: void func(int x, double y, bool z) { ... }
Formal parameters are local. Scope is the block of the function. Formal parameters must have names differing from those of external variables and local variables defined within one function. In the block of the function to the formal parameters some values can be assigned. Formal parameters can be initialized by constants. In this case, the initializing value is considered as a default value. The parameters following the initialized parameter should be
initialized, as well. By calling this function the initialized parameters can be omitted, instead of them defaults will be substituted. Example: func(123, 0.5);
Parameters are passed by value. These are modifications of a corresponding local variable inside the called function will not be reflected in any way in the calling function. It is possible to pass arrays as parameters. However, for an array passed as parameter, it is impossible to change the array elements. There is a possibility to pass parameters by reference. In this case, modification of such parameters will be reflected on corresponded variables in the called function. To point, that the parameter is passed by reference, after a data type, it is necessary to put the modifier &. Example: void func(int& x, double& y, double& z[]) { ... }
Arrays also can be passed by reference, all modifications will be reflected in the initial array. The parameters that passed by reference, cannot be initialized by default values.
Static variables
The memory class "static" defines a static variable. The specifier "static" is declared before a data type. Example: { static int flag }
Static variables are constant ones since their values are not lost when the function is exited. Any variables in a block, except the formal parameters of the function, can be defined as static. The static variable can be initialized by corresponded type constant, as against a simple local variable which can be initialized by any expression. If there is no explicit initialization, the static variable is initialized with zero. Static variables are initialized only once before calling "init()" function. That is at exit from the function inside which the static variable is declared, the value of this variable being not lost.
Defining global variables
They are defined on the same level as functions, i.e. they are not local in any block. Example: int Global_flag; int start() { ... }
Scope of global variables is the whole program. Global variables are accessible from all functions defined in the program. They are initialized with zero if no other initial value is explicitly defined. The global variable can be initialized only by corresponded type constant. Initialization of global variables is made only once before execution of "init()" function. Note: it is not necessary to confuse the variables declared at a global l evel, to global variables of Client Terminal, access to which is carried out by GlobalVariable...() function.
Defining extern variables
The memory class "extern" defines an extern variable. The specifier "extern" is declared before a data type. Example: extern double InputParameter1 = 1.0; int init()
{ ... }
Extern variables define input data of the program, they are accessible from a property program sheet. It is not meaningful to define extern variables in scripts. Arrays cannot represent itself as extern variables.
Initializing variables
Any variable can be initialized during its definition. Any permanently located variable is initialized with zero (0) if no other initial value is explicitly defined. Global and static variables can be initialized only by constant of corresponded type. Local variables can be initialized by any expression, and not just a constant. Initialization of global and static variables is made only once. Initialization of local variables is made each time by call of corresponded functions. Basic types Examples: int mt = 1; // integer initialization // initialization floating-point number (double precision) double p = MarketInfo(Symbol(),MODE_POINT); // string initialization string s = "hello";
Arrays Example: int mta[6] = {1,4,9,16,25,36};
The list of array elements must be enclosed by curly braces. If the array size is defined, the values being not explicitly defined equal 0.
External function definition
The type of external functions defined in another component of a program must be explicitly defined. The absence of such a definition may result in errors during the compilation, assembling or execution of your program. While describing an external object, use the key word #import with the reference to the module. Examples: #import "user32.dll" int MessageBoxA(int hWnd ,string szText, string szCaption,int nType); int SendMessageA(int hWnd,int Msg,int wParam,int lParam); #import "lib.ex4" double round(double value); #import
Preprocessor Declaring of constant Controlling compilation Including files Importing functions and other modules
Declaring of constant
If the first character in a program line is #, it means that this line is a compiler command. Such a compiler command ends with a carriage-return character. #define identifier_value
The identifier of a constant obeys the same rules as variable names. The value can be of any type. Example: #define ABC
100
#define PI 0.314 #define COMPANY_NAME "MetaQuotes Software Corp."
The compiler will replace each occurrence of an identifier in your source code with the corresponding value.
Controlling compilation #property identifier_value
The list of predefined constant identifiers. Example: #property link #property copyright #property stacksize
"http://www.metaquotes.net" "MetaQuotes Software Corp." 1024
Constant
Type
Description
link
string
a link to the company website
copyright
string
the company name
stacksize
int
stack size
indicator_chart_window
void
show the indicator in the chart window
indicator_separate_window void
show the indicator in a separate window
indicator_buffers
int
the number of buffers for calculation, up to 8
indicator_minimum
int
the bottom border for the chart
indicator_maximum
int
the top border for the chart
indicator_colorN
color
the color for displaying line N, where N lies between 1 and 8
indicator_levelN
double
predefined level N for separate window custom indicator, where N lies between 1 and 8
show_confirm
void
before script run message box with confirmation appears
show_inputs
void
before script run its property sheet appears; disables show_confirm property
The compiler
will write the declared values to the settings of the executable module.
Including files
Note: The #include command line can be placed anywhere in the program, but usually all inclusions are placed at the beginning of the source code. #include
Example: #include
The preprocessor replaces this line with the content of the file win32.h. Angle brackets mean that the file win32.h will be taken from the default directory (usually, terminal_directory\experts\include). The current directory is not searched. #include "file_name" Example: #include "mylib.h"
The compiler replaces this line with the content of the file mylib.h. Since this name is enclosed in quotes, the search is performed in the current directory (where the main file of the source code is located). If the f ile is not found in the current directory, the error will be messaged.
Importing functions and other modules #import "file_name" func1(); func2();
#import
Example: #import "user32.dll" int MessageBoxA(int hWnd,string lpText,string lpCaption, int uType); int MessageBoxExA(int hWnd,string lpText,string lpCaption, int uType,int wLanguageId); #import "melib.ex4" #import "gdi32.dll" int GetDC(int hWnd); int ReleaseDC(int hWnd,int hDC); #import
Functions are imported from MQL4 compiled modules (*.ex4 files) and from operating system modules (*.dll files). In the latter case, the imported functions are also declared. A new #import command (it can be without parameters) finishes the description of imported functions.
Account Information AccountBalance() AccountCredit() AccountCompany() AccountCurrency() AccountEquity() AccountFreeMargin() AccountLeverage() AccountMargin() AccountName() AccountNumber() AccountProfit()
double AccountBalance() Returns balance value of the current account.
Sample Print("Account balance = ",AccountBalance());
double AccountCredit() Returns credit value of the current account.
Sample Print("Account number ", AccountCredit());
string AccountCompany() Returns the current account company name.
Sample Print("Account company name ", AccountCompany());
string AccountCurrency() Returns currency name of the current account.
Sample
Print("account currency is ", AccountCurrency());
double AccountEquity() Returns equity value of the current account.
Sample Print("Account equity = ",AccountEquity());
double AccountFreeMargin() Returns free margin value of the current account.
Sample Print("Account free margin = ",AccountFreeMargin());
int AccountLeverage() Returns leverage of the current account.
Sample Print("Account #",AccountNumber(), " leverage is ", AccountLeverage());
double AccountMargin() Returns margin value of the current account.
Sample Print("Account margin ", AccountMargin());
string AccountName() Returns the current account name.
Sample Print("Account name ", AccountName());
int AccountNumber() Returns the number of the current account.
Sample Print("account number ", AccountNumber()); double AccountProfit() Returns profit value of the current account .
Sample Print("Account profit ", AccountProfit());
Array Functions ArrayBsearch() ArrayCopy() ArrayCopyRates() ArrayCopySeries() ArrayDimension() ArrayGetAsSeries()
ArrayInitialize() ArrayIsSeries() ArrayMaximum() ArrayMinimum() ArrayRange() ArrayResize() ArraySetAsSeries() ArraySize() ArraySort()
int double array[], double value, int count=WHOLE_ARRAY, int start=0, ArrayBsearch( int direction=MODE_ASCEND) Returns the index of the first occurrence of a value in the first dimension of array if possible, or the nearest one, if the occurrence is not found. The function cannot be used with string arrays and serial numeric arrays. Note: Binary search processes only sorted arrays. To sort numeric arrays use ArraySort() functions.
Parameters array[]
-
The numeric array to search for.
value
-
The value to search for.
count
-
Count of elements to search for. By default, it searches in the whole array.
start
-
Starting index to search for. By default, the search starts on the first element.
direction
-
Search direction. It can be any of the following values: MODE_ASCEND searching in forward direction, MODE_DESCEND searching in the backward direction.
Sample datetime daytimes[]; int shift=10,dayshift; // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND); if(Period()
int object& dest[], object source[], int start_dest=0, int start_source=0, ArrayCopy( int count=WHOLE_ARRAY) Copies an array to another one. Arrays must be of the same type, but arrays with type double[], int[], datetime[], color[], and bool[] can be copied as arrays with same type. Returns the amount of copied elements.
Parameters dest[]
-
Destination array.
source[]
-
Source array.
start_dest
-
Starting index for the destination array. By default, start index is 0.
start_source
-
Starting index for the source array. By default, start index is 0.
count
-
The count of elements that should be copied. By default, it is WHOLE_ARRAY constant.
Sample double array1[][6]; double array2[10][6]; // fill array with some data ArrayCopyRates(array1); ArrayCopy(array2, array1,0,Bars-9,10); // now array2 has first 10 bars in the history
int ArrayCopyRates(double& dest_array[], string symbol=NULL, int timeframe=0) Copies rates to the two-dimensional array from chart RateInfo array, where second dimension has 6 elements: 0 - time, 1 - open, 2 - low, 3 - high, 4 - close, 5 - volume. Note: Usually retrieved array used to pass large blocks of data to the DLL functions.
Parameters dest_array[]
-
Reference to the two-dimensional destination numeric array.
symbol
-
symbol name, by default, current chart symbol name is used.
timeframe
-
Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values.
Sample double array1[][6]; ArrayCopyRates(array1,"EURUSD", PERIOD_H1); Print("Current bar ",TimeToStr(array1[0][0]),"Open", array1[0][1]);
int double& array[], int series_index, string symbol=NULL, ArrayCopySeries( int timeframe=0) Copies a series array to another one and returns the count of copied elements. Note: If series_index is MODE_TIME, the first parameter must be a datetime array.
Parameters array[]
-
Reference to the destination one-dimensional numeric array.
series_index
-
Series array identifier. It can be any of Series array identifiers enumeration values.
symbol
-
Symbol name, by default, the current chart symbol name is used.
timeframe
-
Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values.
Sample datetime daytimes[]; int shift=10,dayshift; // All the Time[] timeseries are sorted in descendant mode ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1); if(Time[shift]>=daytimes[0]) dayshift=0; else { dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND); if(Period()
int ArrayDimension(int array[]) Returns array rank (dimensions count).
Parameters array[]
-
array to retrieve dimensions count.
Sample int num_array[10][5]; int dim_size; dim_size=ArrayDimension(num_array); // dim_size is 2
bool ArrayGetAsSeries(object array[]) Returns true if array is organized as a series array (array elements indexed from last to first) otherwise return false.
Parameters array[]
-
Array to check.
Sample if(ArrayGetAsSeries(array1)==true) Print("array1 is indexed as a series array"); else Print("array1 is indexed normally (from left to right)");
int ArrayInitialize(double& array[], double value) Sets all elements of numeric array to the same value. Returns the count of initialized element. Note: It is useless to initialize index buffers in the custom indicator init() function.
Parameters array[]
-
Numeric array to be initialized.
value
-
New value to be set.
Sample //---- setting all elements of array to 2.1 double myarray[10]; ArrayInitialize(myarray,2.1);
bool ArrayIsSeries(object array[]) Returns true if the array checked is a series array (time,open,close,high,low, or volume).
Parameters array[]
-
Array to check.
Sample if(ArrayIsSeries(array1)==false) ArrayInitialize(array1,0); else { Print("Series array cannot be initialized!"); return(-1); }
int ArrayMaximum(double array[], int count=WHOLE_ARRAY, int start=0) Searches for elements with maximum value and returns its position.
Parameters array[]
-
The numeric array to search for.
count
-
Scans for the count of elements in the array.
start
-
Start searching on the start index.
Sample double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; int maxValueIdx=ArrayMaximum(num_array); Print("Max value = ", num_array[maxValueIdx]);
int ArrayMinimum(double array[], int count=WHOLE_ARRAY, int start=0) Searches for element with minimum value and returns its position.
Parameters
array[]
-
The numeric array to search for.
count
-
Scans for the count of elements in the array.
start
-
Start searching on the start index.
Sample double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9}; double minValueidx=ArrayMinimum(num_array); Print("Min value = ", num_array[minValueIdx]);
int ArrayRange(object array[], int range_index) Returns the count of elements in the indicated 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);
int ArrayResize(object& array[], int new_size) Sets new size to the first dimension. If success returns count of all elements contained in the array after resizing, otherwise, returns zero and array is not resized.
Parameters array[]
-
Array to resize.
new_size
-
New size for the first dimension.
Sample double array1[][4]; int element_count=ArrayResize(array, 20); // element count is 80 elements
bool ArraySetAsSeries(double& array[], bool set) Sets indexing order of the array like a series arrays, i.e. last element has zero index. Returns previous state.
Parameters array[]
-
The numeric array to set.
set
-
The Series flag to set (true) or drop (false).
Sample double macd_buffer[300]; double signal_buffer[300]; int i,limit=ArraySize(macd_buffer); ArraySetAsSeries(macd_buffer,true); for(i=0; i
int ArraySize(object array[]) Returns the count of elements contained in the array.
Parameters array[]
-
Array of any type.
Sample int count=ArraySize(array1); for(int i=0; i
int double& array[], int count=WHOLE_ARRAY, int start=0, ArraySort( int sort_dir=MODE_ASCEND) Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort().
Parameters array[]
-
The numeric array to sort.
count
-
Count of elements to sort.
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,MODE_DESCEND); // now array is sorted 9,6,4,3,1
Common functions Alert() ClientTerminalName() CompanyName() Comment() GetLastError() GetTickCount() HideTestIndicators() IsConnected() IsDemo() IsDllsAllowed() IsLibrariesAllowed() IsStopped() IsTesting() IsTradeAllowed() MarketInfo() MessageBox() Period() PlaySound() Print() RefreshRates() SendMail() ServerAddress() Sleep() SpeechText() Symbol() UninitializeReason()
void Alert(... ) Displays a dialog box containing the user-defined data. Parameters can be of any type. Arrays cannot be passed to the Alert function. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Comment() and Print() functions.
Parameters ...
-
Any values, separated by commas.
Sample if(Close[0]>SignalLevel) Alert("Close price coming ", Close[0],"!!!");
string ClientTerminalName() Returns Client Terminal Name.
Sample Print("Terminal name is ",ClientTerminalName());
string CompanyName() Returns Company name
Sample Print("Company name is ",CompanyName());
void Comment(... ) Prints some message to the left top corner of the chart. Parameters can be of any type. Arrays cannot be passed to the Comment() function. Arrays should be output elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Alert() and Print() functions.
Parameters ...
-
Any values, separated by commas.
Sample double free=AccountFreeMargin(); Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current time is ",TimeToStr(CurTime()));
int GetLastError() Returns last occurred error after an operation and sets internal last error value to zero.
Sample int err; int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN); if(handle<1) { err=GetLastError(); Print("error(",err,"): ",ErrorDescription(err)); return(0); }
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(); // do some hard calculation... Print("Calculation time is ", GetTickCount()-start, " milliseconds.");
void HideTestIndicators( bool hide) The function sets a flag hiding indicators called by the Expert Advisor. After the chart has been tested and opened the flagged indicators will not be drawn on the testing chart. Every indicator called will first be flagged with the current hiding flag.
Parameters hide
-
TRUE - if indicators must be hidden, otherwise, FALSE.
Sample HideTestIndicators(true);
bool IsConnected() Returns true if client terminal has opened connection to the server, otherwise returns false.
Sample if(!IsConnected()) { Print("Connection is broken!"); return(0); } // Expert body that need opened connection // ...
bool IsDemo() Returns true if expert runs on demo account, otherwise returns false.
Sample if(IsDemo()) Print("I am working on demo account"); else Print("I am working on real account");
bool IsDllsAllowed() Returns true if DLL function 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);
bool IsLibrariesAllowed() Returns true if 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. Experts cannot run."); return(0); } // expert body that calls external DLL functions somefunc();
bool IsStopped() Returns true if expert in the stopping state, otherwise returns false. This function can be used in the cycles to determine expert unloading.
Sample while(expr!=false) { if(IsStopped()==true) return(0); // long time procesing cycle // ... }
bool IsTesting() Returns true if expert runs in the testing mode, otherwise returns false.
Sample if(IsTesting()) Print("I am testing now");
bool IsTradeAllowed() Returns true if trade is allowed for the expert, otherwise returns false. See also IsDllsAllowed(), IsLibrariesAllowed().
Sample if(IsTradeAllowed()) Print("Trade allowed");
double MarketInfo(string symbol, int type) Returns value from Market watch window.
Parameters symbol
-
Instrument symbol.
type
-
Returning data type index. It can be any of Market information identifiers value.
Sample double var; var=MarketInfo("EURUSD",MODE_BID);
int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY) The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined
message and title, plus any combination of predefined If the function succeeds, the return value is one of the MessageBox return code values.
icons
and
push
buttons.
Parameters text
-
Optional text that contains the message message to be displayed. displayed.
caption
-
Optional text that contains the dialog dialog box title.If this parameter is is NULL, the title will be name of expert. expert.
flags
-
Specifies the contents and behavior of the dialog box.This optional parameter parameter can be a combination of flags from the following groups of flags.
Sample #include if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false) { int ret=MessageBox("ObjectCreate() fails with code "+GetLastError()+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION); if(ret==IDNO) return(false); } // continue
int Period() Returns the number of minutes defining the used period (chart timeframe).
Sample Print("Period Print("Period is ", Period());
void PlaySound(string void PlaySound( string filename) Function plays sound file. File must be located at the terminal_dir\sounds directory or its subdirectory.
Parameters filename
-
Sound file name.
Sample if(IsDemo()) if(IsDemo()) PlaySound("alert.wav"); PlaySound("alert.wav");
void Print(... void Print( ... ) Prints some message to the experts log. Parameters can be of any type. Arrays cannot be passed to the Print() function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. See also: Alert() and Comment() functions.
Parameters ...
-
Any values, separated by commas.
Sample Print("Account free margin is ", AccountFreeMargin()); Print("Current time is ", TimeToStr(CurTime())); double pi=3.141592653589793; 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]);
bool RefreshRates() Refreshing data in the built-in variables and series arrays. This function is used when expert advisor calculates for a long time and needs refreshing data. Returns true if data are refreshed, otherwise false.
Sample int ticket; while(true) { ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<=0) { int error=GetLastError(); error=GetLastError(); if(error==134) if(error==134) break; // not enough money if(error==135) if(error==13 5) RefreshRates(); RefreshRate s(); // prices changed break; } else { OrderPrint(); break; } //---- 10 seconds wait Sleep(10000); }
void SendMail(string void SendMail( string subject, string some_text) Sends mail to address set in the Tools->Options->EMail tab if enabled. Note: Posting e-mail can be denied or address can be empty.
Parameters subject
-
Subject text.
some_text
-
Mail body.
Sample double lastclose=Close[0]; lastclose=Close[0]; if(lastclose
string ServerAddress() Returns connected server address in form of a text string.
Sample Print("Server Print("Server address is ", ServerAddress()); ServerAddress());
void Sleep(int void Sleep( int milliseconds) The Sleep function suspends the execution of the current expert for a specified interval.
Parameters -
milliseconds
Sleeping interval in milliseconds.
Sample Sleep(5);
void SpeechText(string void SpeechText( string text, int lang_mode=SPEECH_ENGLISH) Computer speaks some text.
Parameters text
-
Speaking text.
lang_mode
-
SPEECH_ENGLISH (by default) or SPEECH_NATIVE values.
Sample double lastclose=Close[0]; lastclose=Close[0]; SpeechText("Price dropped down to "+DoubleToStr(lastclose));
string Symbol() Returns a text string with the name of the current financial instrument.
Sample int total=OrdersTotal(); total=OrdersTotal(); for(int pos=0;posOP_SELL || OrderSymbol()!=Symbol()) continue; // do some orders processing... }
int UninitializeReason() Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. Return values can be one of Uninitialize reason codes. codes.
Sample // this is example int deinit() { switch(UninitializeReason()) { case REASON_CHARTCLOSE: case REASON_REMOVE: REASON_REMOV E: CleanUp(); break; // clean up and free all expert's resources. case REASON_RECOMPILE: REASON_RECOMPILE: case REASON_CHARTCHANGE: REASON_CHARTCHANGE: case REASON_PARAMETERS: case REASON_ACCOUNT: REASON_ACCOU NT: StoreData(); break; // prepare to restart } //... }
Conversion functions CharToStr() DoubleToStr() NormalizeDouble() StrToDouble() StrToInteger() StrToTime() TimeToStr()
string CharToStr(int CharToStr(int char_code) Returns string with one symbol that have specified code
Parameters char_code
-
ASCII char code.
Sample string str="WORL" + CharToStr(44); // 44 is code for 'D' // resulting string will be WORLD
string DoubleToStr(double DoubleToStr(double value, int digits) Returns text string with the specified numerical value transformed into the specified precision format.
Parameters value
-
Numerical value.
digits
-
Precision format, number of digits digits after decimal point (0-8).
Sample string value=DoubleToStr(1.28473418, 5); // value is 1.28473
double NormalizeDouble( NormalizeDouble(double double value, int digits) Rounds floating point number to specified decimal places.
Parameters value
-
Floating point value.
digits
-
Precision format, number of digits digits after decimal point (0-8).
Sample double var1=0.123456789; var1=0.123456789; Print(NormalizeDouble(var1,5)); // output: 0.12346
double StrToDouble(string StrToDouble(string value) Converts string representation of number to type double.
Parameters value
-
String containing value in fixed number format.
Sample double var=StrToDouble("103.2812");
int StrToInteger(string StrToInteger(string value) Converts string representation of number to type integer.
Parameters value
-
String containing integer number.
Sample int var1=StrToInteger("1024");
datetime StrToTime(string StrToTime(string value) Converts string in the format "yyyy.mm.dd hh:mi" to type datetime.
Parameters value
-
String value value of date/time format such as "yyyy.mm.dd hh:mi".
Sample datetime var1; var1=StrToTime("2003.8 var1=StrToTime("2003.8.12 .12 17:35"); var1=StrToTime("17:35"); var1=StrToTi me("17:35"); // returns with current date var1=StrToTime("2003.8.12 var1=StrToTi me("2003.8.12"); "); // returns with midnight time "00:00" string TimeToStr(datetime TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES) Returns time as string in the format "yyyy.mm.dd hh:mi".
Parameters
value
-
Positive number number of of seconds from 00:00 January 1, 1970.
mode
-
Optional data output mode can be one or combination combination of: TIME_DATE get result in form "yyyy.mm.dd", TIME_MINUTES get result in form "hh:mi", TIME_SECONDS get result in form "hh:mi:ss".
Sample strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);
Custom Indicator functions IndicatorBuffers() IndicatorCounted() IndicatorDigits() IndicatorShortName() SetIndexArrow() SetIndexBuffer() SetIndexDrawBegin() SetIndexEmptyValue() SetIndexLabel() SetIndexShift() SetIndexStyle() SetLevelStyle() SetLevelValue()
void IndicatorBuffers(int count) void IndicatorBuffers( Allocates memory for buffers used for custom indicator calculations. Cannot be greater than 8 and less than indicator_buffers property. If custom indicator requires additional buffers for counting then use this function for pointing common buffers count.
Parameters count
-
Buffers count count to allocate. Should Should be be up to 8 buffers.
Sample #property indicator_separate_window #property indicator_buffers indicator_bu ffers 1 #property indicator_color1 Silver //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; SignalSMA=9; //---- indicator buffers double ind_buffer1[]; double ind_buffer2[]; double ind_buffer3[]; //+------------------------------------------------------------------+ //| Custom indicator initialization initializati on 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); }
int IndicatorCounted() Returns bars count that does not changed after last indicator launch. In most cases same count of index values do not need for recalculation. Used for optimizing calculations.
Sample int start() { int limit; 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--; limit=Bars-counted_bars; //---- main loop for(int i=0; i
void IndicatorDigits(int digits) Sets default precision format for indicators visualization.
Parameters digits
-
Precision format, number of digits after decimal point.
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); }
void IndicatorShortName(string name) Sets indicator short name for showing on the chart subwindow.
Parameters name
-
New short name.
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); }
void SetIndexArrow(int index, int code)
Sets arrow symbol for indicators that draws some lines as arrow.
Parameters index
-
Line index. Should be from 0 to 7.
code
-
Symbol code from Wingdings font or Array constants.
Sample SetIndexArrow(0, 217);
bool SetIndexBuffer(int index, double array[]) Sets buffer for calculating line. The indicated array bound with previously allocated custom indicator buffer. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters index
-
Line index. Should be from 0 to 7.
array[]
-
Array that stores calculated indicator values.
Sample double ExtBufferSilver[]; int init() { SetIndexBuffer(0, ExtBufferSilver); // set buffer for first line // ... }
void SetIndexDrawBegin(int index, int begin) Sets first bar from what index will be drawn. Index values before draw begin are not significant and does not drawn and not show in the DataWindow.
Parameters index
-
Line index. Should be from 0 to 7.
begin
-
First drawing bar position number.
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); }
void SetIndexEmptyValue(int index, double value) Sets drawing line empty value. By default, empty value line is EMPTY_VALUE. Empty values are not drawn and not show in the DataWindow.
Parameters index
-
Line index. Should be from 0 to 7.
value
-
New empty value.
Sample SetIndexEmptyValue(6,0.0001);
void SetIndexLabel(int index, string text) Sets drawing line description for showing in the DataWindow.
Parameters index
-
Line index. Should be from 0 to 7.
text
-
Label text. NULL means that index value does not show 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
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); }
void SetIndexShift(int index, int shift) Sets offset for drawing line. Line will be counted on the current bar, but will be drawn shifted.
Parameters index
-
Line index. Should be from 0 to 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); }
void int index, int type, int style=EMPTY, int width=EMPTY, SetIndexStyle( color clr=CLR_NONE) Sets new type, style, width and color for a given indicator line.
Parameters index
-
Line index. Should be from 0 to 7.
type
-
Shape style.Can be one of Drawing shape style enumeration.
style
-
Drawing style. Except STYLE_SOLID style all other styles valid when width is 1 pixel.Can be one of Shape style enumeration. EMPTY value indicates that style does not changed.
width
-
Line width. valid values - 1,2,3,4,5. EMPTY value indicates that width does not changed.
clr
-
Line color.
Sample SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red);
void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE) Function sets new style, width and color of indicator levels.
Parameters draw_style
-
Drawing style. Except for STYLE_SOLID, all other styles are valid if the width is 1 pixel.Can be one of Shape style constants.EMPTY value indicates that style will not be changed.
line_width
-
Line width. Valid values are 1,2,3,4,5. EMPTY value indicates that width will not be changed.
clr
-
Line color.
Sample //---- show levels as thick red lines SetLevelStyle(STYLE_SOLID,2,Red)
int SetLevelValue(int level, double value) Function sets a new value for the given indicator level.
Parameters level
-
Level index (0-31).
value
-
Value for the given indicator level.
Sample SetLevelValue(1,3.14);
Date & Time functions CurTime() Day() DayOfWeek() DayOfYear() Hour() LocalTime() Minute() Month() Seconds() TimeDay() TimeDayOfWeek() TimeDayOfYear() TimeHour() TimeMinute() TimeMonth() TimeSeconds() TimeYear() Year()
datetime CurTime() Returns the last known server time, number of seconds elapsed from 00:00 January 1, 1970.
Sample if(CurTime()-OrderOpenTime()<360) return(0);
int Day() Returns the current day of the month.
Sample if(Day()<5) return(0);
int DayOfWeek() Returns the current zero based day of the week (0-Sunday,1,2,3,4,5,6).
Sample // do not work on holidays. if(DayOfWeek()==0 || DayOfWeek()==6) return(0);
int DayOfYear() Returns the current day of the year (1-1 ja nuary,..,365(6) - 31 december).
Sample if(DayOfYear()==245) return(true);
int Hour() Returns current hour (0,1,2,..23)
Sample bool is_siesta=false; if(Hour()>=12 || Hour()<17) is_siesta=true;
datetime LocalTime() Returns local computer time, number of seconds elapsed from 00:00 January 1, 1970.
Sample if(LocalTime()-OrderOpenTime()<360) return(0);
int Minute() Returns current minute (0,1,2,..59).
Sample if(Minute()<=15) return("first quarter");
int Month() Returns current month as number (1-January,2,3,4,5,6,7,8,9,10,11,12).
Sample
if(Month()<=5) return("first half of year");
int Seconds() Returns current second (0,1,2,..59).
Sample if(Seconds()<=15) return(0);
int TimeDay(datetime date) Returns day of month (1 - 31) for specified date.
Parameters date
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int day=TimeDay(D'2003.12.31'); // day is 31
int TimeDayOfWeek(datetime date) Returns zero based day of week (0-Sunday,1,2,3,4,5,6) for specified date.
Parameters date
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int weekday=TimeDayOfWeek(D'2004.11.2'); // day is 2 - tuesday
int TimeDayOfYear(datetime date) Returns day (1-1 january,..,365(6) - 31 december) of ye ar for specified date.
Parameters date
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int day=TimeDayOfYear(CurTime());
int TimeHour(datetime time) Returns hour for specified time.
Parameters time
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int h=TimeHour(CurTime());
int TimeMinute(datetime time) Returns minute for specified time.
Parameters time
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int m=TimeMinute(CurTime());
int TimeMonth(datetime time) Returns month for specified time.
Parameters time
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int m=TimeMonth(CurTime());
int TimeSeconds(datetime time) Returns seconds after minute (0 – 59) for specified time.
Parameters time
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int m=TimeSeconds(CurTime());
int TimeYear(datetime time) Returns year for specified date. Return values can be in range 1970-2037.
Parameters time
-
Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample int y=TimeYear(CurTime());
int Year() Returns current year.
Sample // return if date before 1 May 2002 if(Year()==2002 && Month()<5) return(0);
File functions FileClose() FileDelete() FileFlush() FileIsEnding() FileIsLineEnding() FileOpen() FileOpenHistory() FileReadArray() FileReadDouble() FileReadInteger() FileReadNumber() FileReadString() FileSeek() FileSize() FileTell() FileWrite() FileWriteArray() FileWriteDouble() FileWriteInteger()
FileWriteString()
void FileClose(int handle) Closes file previously opened by FileOpen() functions.
Parameters handle
-
File handle, returned by FileOpen() functions
Sample int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0) { // working with file ... FileClose(handle); }
void FileClose(int handle) Closes file previously opened by FileOpen() functions.
Parameters handle
-
File handle, returned by FileOpen() functions
Sample int handle=FileOpen("filename", FILE_CSV|FILE_READ); if(handle>0) { // working with file ... FileClose(handle); }
void FileFlush(int handle) Flushes all data stored in the file buffer to disk.
Parameters handle
-
File handle, returned by FileOpen() functions.
Sample int bars_count=Bars; int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE); if(handle>0) { FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW"); for(int i=0;i
bool FileIsEnding(int handle) Returns logical true if file pointer is at the end of the file, otherwise returns false. To get the detailed error information, call GetLastError() function.
Parameters
handle
-
File handle, returned by FileOpen() functions.
Sample if(FileIsEnding(h1)) { FileClose(h1); return(false); }
bool FileIsLineEnding(int handle) For CSV file returns logical true if file pointer is at the end of the line, otherwise returns false. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
Sample if(FileIsLineEnding(h1)) { FileClose(h1); return(false); }
int FileOpen(string filename, int mode, int delimiter=';') Opens file for input and/or output. Returns a file handle for the opened file. If the function fails, the return value less than 1. To get the detailed error information, call GetLastError() function. Note: Files can be opened only from terminal_dir\experts\files directory and its subdirectories.
Parameters filename
-
File name, file may be with any extensions.
mode
-
Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter
-
Delimiter character for csv files. By default passed ';' symbol.
Sample int handle; handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';'); if(handle<1) { Print("File my_data.dat not found, the last error is ", GetLastError()); return(false); }
int FileOpenHistory(string filename, int mode, int delimiter=';') Opens file in the current history directory for input and/or output. Returns a file handle for the opened file. If the function fails, the return value less than 1. To get th e detailed error information, call GetLastError().
Parameters filename
-
File name, file may be with any extensions.
mode
-
Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter
-
Delimiter character for csv files. By default passed ';' symbol.
Sample int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE); if(handle<1) { Print("Cannot create file USDX240.HST"); return(false); }
// work with file // ... FileClose(handle);
int FileReadArray(int handle, object& array[], int start, int count) Reads the indicated count of elements from the binary file to array. Returns actual read elements count. To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a sufficient size.
Parameters handle
-
File handle, returned by FileOpen() function.
array[]
-
Array where data will be stored.
start
-
Storing start position into array.
count
-
Count of elements to read.
Sample int handle; double varray[10]; handle=FileOpen("filename.dat", FILE_BIN|FILE_READ); if(handle>0) { FileReadArray(handle, varray, 0, 10); FileClose(handle); }
int FileReadArray(int handle, object& array[], int start, int count) Reads the indicated count of elements from the binary file to array. Returns actual read elements count. To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a sufficient size.
Parameters handle
-
File handle, returned by FileOpen() function.
array[]
-
Array where data will be stored.
start
-
Storing start position into array.
count
-
Count of elements to read.
Sample int handle; double varray[10]; handle=FileOpen("filename.dat", FILE_BIN|FILE_READ); if(handle>0) { FileReadArray(handle, varray, 0, 10); FileClose(handle); }
int FileReadInteger(int handle, int size=LONG_VALUE) Read the integer from binary files from the current file position. Integer format size can be 1, 2 or 4 bytes length. If the format size is not specified system attempts to read 4 bytes length value. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
size
-
Format size. Can be CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) or LONG_VALUE(4 bytes).
Sample int handle; int value;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ); if(handle>0) { value=FileReadInteger(h1,2); FileClose(handle); }
double FileReadNumber(int handle) Read the number from the current file position to the delimiter. Only for CSV files. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
Sample int handle; int value; handle=FileOpen("filename.csv", FILE_CSV, ';'); if(handle>0) { value=FileReadNumber(handle); FileClose(handle); }
string FileReadString(int handle, int length=0) Read the string from the current file position. Applied to both CSV and binary files. For text files string will be read to the delimiter and for binary file string will be read for the count of characters indicated. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
length
-
Reading characters count.
Sample int handle; string str; handle=FileOpen("filename.csv", FILE_CSV|FILE_READ); if(handle>0) { str=FileReadString(handle); FileClose(handle); }
bool FileSeek(int handle, int offset, int origin) Moves the file pointer to a specified location. The FileSeek() function moves the file pointer associated with handle to a new location that is offset bytes from origin. The next operation on the file occurs at the new location. If successful, function returns TRUE. Otherwise, it returns FALSE. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() functions.
offset
-
Offset in bytes from origin.
origin
-
Initial position. Value can be one of this constants: SEEK_CUR - from current position, SEEK_SET - from begin, SEEK_END - from end of file.
Sample int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ, ';'); if(handle>0)
{ FileSeek(handle, 10, SEEK_SET); FileReadInteger(handle); FileClose(handle); handle=0; }
int FileSize(int handle) Returns file size in bytes. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
Sample int handle; int size; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); if(handle>0) { size=FileSize(handle); Print("my_table.dat size is ", size, " bytes"); FileClose(handle); }
int FileSize(int handle) Returns file size in bytes. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
Sample int handle; int size; handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ); if(handle>0) { size=FileSize(handle); Print("my_table.dat size is ", size, " bytes"); FileClose(handle); }
int FileWrite(int handle, ... ) Writes to the CSV file some values, delimiter inserted automatically. Returns the number of characters written, or a negative value if an error occurs. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
...
-
User data to write, separated with commas. Note: int and double types automatically converted to string,but color, datetime and bool types does not automatically converted and will be writen to file in it's as integers.
Sample int handle; datetime orderOpen=OrderOpenTime(); handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';'); if(handle>0) {
FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen)); FileClose(handle); }
int FileWriteArray(int FileWriteArray(int handle, object array[], int start, int count) Writes array to the binary file. Arrays of type int, bool, datetime and color will be written as 4 bytes integers. Arrays of type double will be written as 8 bytes floating point numbers. Arrays of string will be written as one string where elements will be divided by Carriage return and Line feed symbols (0D 0A). Returns the number of elements wrote, or a negative value if an error occurs. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
array[]
-
Array to write.
start
-
Starting index into array to write.
count
-
Count of elements to write.
Sample int handle; double BarOpenValues[10]; // copy first ten bars to the array for(int i=0;i<10; i++) BarOpenValues[i]=Open[i]; // writing array to the file handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle>0) { FileWriteArray(handle, FileWriteArray(handle, BarOpenValues, BarOpenValues, 3, 7); // writing last 7 elements FileClose(handle); }
int FileWriteDouble( FileWriteDouble(int int handle, double value, int size=DOUBLE_VALUE) Writes double value to the binary file. If size is FLOAT_VALUE, value will be written as 4 bytes floating point format, else will be written in 8 bytes floating point format. Returns actual written bytes count. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
value
-
Value to write.
size
-
Optional format flag. It can be any of the following values: DOUBLE_VALUE (8 bytes, default) FLOAT_VALUE (4 bytes).
Sample int handle; double var1=0.345; handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteDouble(h1, var1, DOUBLE_VALUE); //... FileClose(handle);
int FileWriteInteger( FileWriteInteger(int int handle, int value, int size=LONG_VALUE) Writes integer value to the binary file. If size is SHORT_VALUE, value will be written as 2 bytes integer, if size is CHAR_VALUE,
value will be written as 1 bytes integer and if size is LONG_VALUE, value will be written as 4 bytes integer. Returns actual written bytes count. To get the detailed error information, call GetLastError() function.
Parameters handle
-
File handle, returned by FileOpen() function.
value
-
Value to write.
size
-
Optional format flag. It can be any of the following values: CHAR_VALUE (1 byte), SHORT_VALUE (2 bytes), LONG_VALUE (4 bytes, default).
Sample int handle; int value=10; handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteInteger(handle, value, SHORT_VALUE); //... FileClose(handle);
int FileWriteString( FileWriteString(int int handle, string value, int length) Writes string to the binary file from current file position. Returns To get the detailed error information, call GetLastError() function.
actual
written
bytes
count.
Parameters handle
-
File handle, returned by FileOpen() function.
value
-
Text to write.
length
-
Counts of characters to write.
Sample int handle; string str="some string"; handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE); if(handle<1) { Print("can't open file error-",GetLastError()); return(0); } FileWriteString(h1, str, 8); FileClose(handle);
Global Variables functions GlobalVariableCheck() GlobalVariableDel() GlobalVariableGet() GlobalVariableSet() GlobalVariableSetOnCondition() GlobalVariablesDeleteAll()
bool GlobalVariableCheck( GlobalVariableCheck(string string name) Return logical true if global variable exists, otherwise returns false. To get the detailed error information, call GetLastError() function.
Parameters name
-
Global variable name.
Sample // check variable before use if(!GlobalVariableCheck("g1")) GlobalVariableSet("g1",1);
bool GlobalVariableDel( GlobalVariableDel(string string name) Deletes global variable. If the function succeeds, the return value will be true. If the function fails, the return value is false. To get the detailed error information, call GetLastError() GetLastError()..
Parameters name
-
Global variable name.
Sample // deleting global variable with name "gvar_1" GlobalVariableDel("gvar_1");
double GlobalVariableGet( GlobalVariableGet(string string name) Returns global variable value. To check function failure, check error information by calling GetLastError() GetLastError()..
Parameters name
-
Global variable name.
Sample double v1=GlobalVariableGet("g v1=GlobalVariableGet("g1"); 1"); //---- check function call result if(GetLastError()!=0) if(GetLastError()!=0) return(false); return(false); //---- continue processing
datetime GlobalVariableSet( GlobalVariableSet(string string name, double value) Sets global variable value. If it does not exist, the system creates a new variable. If the function succeeds, the return value is last access time. If the function fails, the return value is 0. To get the detailed error information, call GetLastError() GetLastError()..
Parameters name
-
Global variable name.
value
-
Numeric value to set.
Sample //---- try to set new value if(GlobalVariableSet("BarsTotal",Bars)==0) return(false); //---- continue processing bool GlobalVariableSetOnCondition(string name, double value, double check_value) Sets the new value of the global variable if the current value equals to the third parameter check_value . If there is no variable at all, the function function will return return false false and set the value of ERR_GLOBA ERR_GLOBAL_VAR L_VARIABLE IABLE_NOT_ _NOT_FOUN FOUND D constant constant to LastError. LastError. When successf successfully ully executed, the function function returns true, otherwise otherwise it does false. To receive receive the information information about the error, error, call GetLastError() function. The function can be used as a semaphore for the access to common resources.
Parameters name
-
Global variable name.
value
-
Numeric value to set.
check_value
-
Value to compare with the current global global variable value.
Sample int init() { //---- create global variable
GlobalVariableSet("DATAFILE_SEM",0); //... } int start() { //---- try to lock common resource while(!IsStopped()) { //---- locking if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break; //---- may be variable deleted? if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0); //---- sleeping Sleep(500); } //---- resource locked // ... do some work //---- unlock resource GlobalVariableSet("DATAFILE_SEM",0); }
void GlobalVariablesDeleteAll() void GlobalVariablesDeleteAll() Deletes all global variables. This function never fails.
Sample GlobalVariablesDeleteAll();
Math & Trig MathAbs() MathArccos() MathArcsin() MathArctan() MathCeil() MathCos() MathExp() MathFloor() MathLog() MathMax() MathMin() MathMod() MathPow() MathRand() MathRound() MathSin() MathSqrt() MathSrand() MathTan()
double MathAbs(double MathAbs(double value) Returns the absolute value (modulus) o f the specified numeric value.
Parameters value
Sample
-
Numeric value.
double dx=-3.141593, dy; // calc MathAbs dy=MathAbs(dx); Print("The absolute absolute value of ",dx," is ",dy); // Output: The absolute value of -3.141593 is 3.141593
double MathArccos(double MathArccos(double x) The MathArccos function returns the arccosine of x in the range 0 to π radians. If x is less than -1 or greater than 1, MathArccos returns an indefinite (same as a quiet NaN).
Parameters x
-
Value between -1 and 1 arc cosine of which should be calculated.
Sample double x=0.32696, y; y=asin(x); Print("Arcsine Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 0.326960=0.3 33085 //Output: Arccosine of 0.326960=1.237711
double MathArcsin(double MathArcsin(double x) The MathArcsin function returns the arcsine of x in the range -π/2 to π/2 radians. If x is less than -1 or greater than 1, arcsine returns an indefinite (same as a quiet NaN).
Parameters x
-
Value the arcsine of which which should be calculated
Sample double x=0.32696, y; y=MathArcsin(x); Print("Arcsine Print("Arcsine of ",x," = ",y); y=acos(x); Print("Arccosine Print("Arccosine of ",x," = ",y); //Output: Arcsine of 0.326960=0.333085 0.326960=0.3 33085 //Output: Arccosine of 0.326960=1.237711 double MathArctan(double MathArctan(double x) The MathArctan returns the arctangent of x . If x is 0, MathArctan returns 0. MathArctan returns a value in the range -π/2 to π/2 radians.
Parameters x
-
A number representing a tangent.
Sample double x=-862.42, y; y=MathArctan(x); Print("Arctangent of ",x," is ",y); //Output: Arctangent of -862.42 is -1.5696
double MathCeil(double MathCeil(double x) The MathCeil function returns a numeric value representing the smallest integer that is greater than or equal to x .
Parameters x
-
Numeric value.
Sample double y;
y=MathCeil(2.8); Print("The ceil of 2.8 is ",y); y=MathCeil(-2.8); Print("The ceil of -2.8 is ",y); /*Output: The ceil of 2.8 is 3 The ceil of -2.8 is -2*/
double MathCos(double value) Returns the cosine of the specified angle.
Parameters value
-
An angle, measured in radians.
Sample double pi=3.1415926535; double x, y; x=pi/2; y=MathSin(x); Print("MathSin(",x,") = ",y); y=MathCos(x); Print("MathCos(",x,") = ",y); //Output: MathSin(1.5708)=1 // MathCos(1.5708)=0
double MathExp(double d) Returns value the number e raised to the power d . On overflow, the function returns INF (infinite) and on underflow, MathExp returns 0.
Parameters d
-
A number specifying a power.
Sample double x=2.302585093,y; y=MathExp(x); Print("MathExp(",x,") = ",y); //Output: MathExp(2.3026)=10
double MathFloor(double x) The MathFloor function returns a numeric value representing the largest integer that is less than or equal to x .
Parameters x
-
Numeric value.
Sample double y; y=MathFloor(2.8); Print("The floor of 2.8 is ",y); y=MathFloor(-2.8); Print("The floor of -2.8 is ",y); /*Output: The floor of 2.8 is 2 The floor of -2.8 is -3*/
double MathLog(double x) The MathLog functions return the logarithm of x if successful. If x is negative, these functions return an indefinite (same as a
quiet NaN). If x is 0, they return INF (infinite).
Parameters x
-
Value whose logarithm is to be found.
Sample double x=9000.0,y; y=MathLog(x); Print("MathLog(",x,") = ", y); //Output: MathLog(9000)=9.10498
double MathMax(double value1, double value2) Returns maximum value of two numeric values.
Parameters value1
-
First numeric value.
value2
-
Second numeric value.
Sample double result=MathMax(1.08,Bid);
double MathMin(double value1, double value2) Returns minimum value of two numeric values.
Parameters value1
-
First numeric value.
value2
-
Second numeric value.
Sample double result=MathMin(1.08,Ask);
double MathMod(double value, double value2) Divides two numbers and returns only the remainder.
Parameters value
-
Dividend value.
value2
-
Divider value.
Sample double x=-10.0,y=3.0,z; z=MathMod(x,y); Print("The remainder of ",x," / ",y," is ",z); //Output: The remainder of -10 / 3 is -1
double MathPow(double base, double exponent) Returns the value of a base expression taken to a specified power.
Parameters base
-
Base value.
exponent
-
Exponent value.
Sample double x=2.0,y=3.0,z; z=MathPow(x,y); Printf(x," to the power of ",y," is ", z); //Output: 2 to the power of 3 is 8
int MathRand() The MathRand function returns a pseudorandom integer in the range 0 to 0x7fff (32767). Use the MathSrand function to seed the pseudorandom-number generator before calling rand.
Sample MathSrand(LocalTime()); // Display 10 numbers. for(int i=0;i<10;i++ ) Print("random value ", MathRand());
double MathRound(double value) Returns value rounded to the nearest integer of the specified numeric value.
Parameters value
-
Numeric value to round.
Sample double y=MathRound(2.8); Print("The round of 2.8 is ",y); y=MathRound(2.4); Print("The round of -2.4 is ",y); //Output: The round of 2.8 is 3 // The round of -2.4 is -2 double MathSin(double value) Returns the sine of the specified angle.
Parameters value
-
An angle, measured in radians.
Sample double pi=3.1415926535; double x, y; x=pi/2; y=MathSin(x); Print("MathSin(",x,") = ",y); y=MathCos(x); Print("MathCos(",x,") = ",y); //Output: MathSin(1.5708)=1 // MathCos(1.5708)=0
double MathSqrt(double x) The MathSqrt function returns the square-root of x . If x is negative, MathSqrt returns an indefinite (same as a quiet NaN).
Parameters x
-
Positive numeric value.
Sample double question=45.35, answer; answer=MathSqrt(question); if(question<0) Print("Error: MathSqrt returns ",answer," answer"); else Print("The square root of ",question," is ", answer); //Output: The square root of 45.35 is 6.73
void MathSrand(int seed) The MathSrand() function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. MathRand retrieves the
pseudorandom numbers that are generated. Calling MathRand before any call to MathSrand generates the same sequence as calling MathSrand with seed passed as 1.
Parameters seed
-
Seed for random-number generation.
Sample MathSrand(LocalTime()); // Display 10 numbers. for(int i=0;i<10;i++ ) Print("random value ", MathRand());
double MathTan(double x) MathTan returns the tangent of x . If x is greater than or equal to 263, or less than or equal to -263, a loss of significance in the result occurs, in which case the function returns an indefinite (same as a quiet NaN).
Parameters x
-
Angle in radians.
Sample double pi=3.1415926535; double x,y; x=MathTan(pi/4); Print("MathTan(",pi/4," = ",x); //Output: MathTan(0.7856)=1
Object functions ObjectCreate() ObjectDelete() ObjectDescription() ObjectFind() ObjectGet() ObjectGetFiboDescription() ObjectGetShiftByValue() ObjectGetValueByShift() ObjectGetVisibility() ObjectMove() ObjectName() ObjectsDeleteAll() ObjectSet() ObjectSetFiboDescription() ObjectSetText() ObjectSetVisibility() ObjectsRedraw ObjectsTotal() ObjectType()
bool string name, int type, int window, datetime time1, double price1, ObjectCreate( datetime time2=0, double price2=0, datetime time3=0, double price3=0) Create object with specified name, type and initial coordinates in the specified window. Count of coordinates related from object type (1-3). If the function succeeds, the return value will be true. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError(). For objects with type OBJ_LABEL first coordinate ignored. To set coordinate for label use ObjectSet() function to set OBJPROP_XDISTANCE and OBJPROP_YDISTANCE properties. Note: Coordinates must be passed with both part - time and price. For example: Object OBJ_VLINE required 1 coordinate part time . But function wants also the seconds part of coordinate price .
Parameters
name
-
Unique object name.
type
-
Object type. It can be any of the Object type enumeration values.
window
-
Window index where object will be added. Window index must be greater or equal to 0 and less than WindowsTotal().
time1
-
Time part of first point.
price1
-
Price part of first point.
time2
-
Time part of second point.
price2
-
Price part of second point.
time3
-
Time part of third point.
price3
-
Price part of third point.
Sample // new text object if(!ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)) { Print("error: can't create text_object! code #",GetLastError()); return(0); } // new label object if(!ObjectCreate("label_object", OBJ_LABEL, 0, 0, 0)) { Print("error: can't create label_object! code #",GetLastError()); return(0); } ObjectSet("label_object", OBJPROP_XDISTANCE, 200); ObjectSet("label_object", OBJPROP_YDISTANCE, 100);
bool ObjectDelete(string name) Deletes object with specified name. If the function succeeds, the return value will be true. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters name
-
Deleting object name.
Sample ObjectDelete("text_object");
string ObjectDescription(string name) Return object description. To get error information, call GetLastError() function.
Parameters name
-
Object name.
Sample // writing chart's object list to the file int handle, total; string obj_name,fname; // file name fname="objlist_"+Symbol(); handle=FileOpen(fname,FILE_CSV|FILE_WRITE); if(handle!=false) { total=ObjectsTotal(); for(int i=-;i
Parameters name
-
Object name.
index
-
Object property index. It can be any of the Object properties enumeration values.
Sample color oldColor=ObjectGet("hline12", OBJPROP_COLOR);
string ObjectGetFiboDescription(string name, int index) Function returns description of Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels never exceeds 32. To get the detailed error information, call GetLastError() function.
Parameters name
-
Object name.
index
-
Index of the Fibonacci level.
Sample #include ... string text; for(int i=0;i<32;i++) { text=ObjectGetFiboDescription(MyObjectName,i); //---- check. may be objects's level count less than 32 if(GetLastError()!=ERR_NO_ERROR) break; Print(MyObjectName,"level: ",i," description: ",text); }
int ObjectGetShiftByValue(string name, double value) Calculates and returns bar index for the indicated price. Calculated by first and second coordinate. Applied to trendlines. To get the detailed error information, call GetLastError() function.
Parameters name
-
Object name.
value
-
Price value.
Sample int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34);
double ObjectGetValueByShift(string name, int shift) Calculates and returns price value for the indicated bar. Calculated by first and second coordinate. Applied to trendlines. To get the detailed error information, call GetLastError() function.
Parameters name
-
Object name
shift
-
Bar index.
Sample double price=ObjectGetValueByShift("MyTrendLine#123", 11);
int ObjectGetVisibility(string name) Function returns flags of the object visibility on the chart. Value can be single or combined (bitwise addition) of object visibility constants.
Parameters name
-
Object name.
Sample // is object visible on the chart? if((ObjectGetVisibility()&OBJ_PERIOD_M5)!=0 && Period()==PERIOD_M5) { // working with object }
bool ObjectMove(string name, int point, datetime time1, double price1) Moves objects point on the chart. Objects can have from one to three points related to its type. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError().
Parameters name
-
Object name.
point
-
Coordinate index.
time1
-
New time value.
price1
-
New price value.
Sample ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345);
string ObjectName(int index) Returns object name by index.
Parameters index
-
Object index on the chart. Object index must be greater or equal to 0 and less than ObjectsTotal().
Sample int obj_total=ObjectsTotal(); string name; for(int i=0;i
int ObjectsDeleteAll(int window, int type=EMPTY) Removes all objects with specified type and on the specified subwindow of the chart. Returns removed objects count.
Parameters window
-
Window index from objects will be deleted. Window index must be greater or equal to 0 and less than WindowsTotal().
type
-
Optional object type to delete.It can be any of the Object type enumeration values or EMPTY constant to delete all objects with any types.
Sample
ObjectsDeleteAll(2, OBJ_HLINE); // removes all horizontal line objects from window 3 (index 2).
bool ObjectSet(string name, int index, double value) Changes named objects property with new value. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError().
Parameters name
-
Object name.
index
-
Object value index. It can be any of Object properties enumeration values.
value
-
New value for property.
Sample // moving first coord to last bar time ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]); // setting second fibo level ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234); // setting object visibility. object will be shown only on 15 minute and 1 hour charts ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 | OBJ_PERIOD_H1);
bool ObjectSetFiboDescription(string name, int index, string text) Function assigns a new description to a Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum amount of Fibonacci levels never exceeds 32. To get the detailed error information, call GetLastError() function.
Parameters name
-
Object name.
index
-
Index of the Fibonacci level (0-31).
text
-
New description to be assigned to the Fibonacci level.
Sample ObjectSetFiboDescription("MyFiboObject,2,"Second line");
bool string name, string text, int font_size, string font=NULL, ObjectSetText( color text_color=CLR_NONE) Sets object description. If the function succeeds, the return value will be true. If the function fails, the return value will be false. To get the detailed error information, call GetLastError() function.
Parameters name
-
Object name.
text
-
Some text.
font_size
-
Font size in points.
font
-
Font name.
text_color
-
Text color.
Sample ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green);
int ObjectSetVisibility(string name, int flag) Function sets new value to the object visibility property. Function returns previous value.
Parameters name
-
Object name.
flag
-
New value of the object visibility property. Value can be single or combined (bitwise addition) of object visibility constants.
Sample // The object will be shown on 1-hour charts only.
ObjectSetVisibility("MyObj1",OBJ_PERIOD_H1);
void ObjectsRedraw() Redraws all objects on the char.
Sample ObjectsRedraw();
int ObjectsTotal() Returns total count of objects on the chart.
Sample int obj_total=ObjectsTotal(); string name; for(int i=0;i
int ObjectType(string name) Returns Object type enumeration value.
Parameters name
-
Object name.
Sample if(ObjectType("line_object2")!=OBJ_HLINE) return(0);
Pre-defined Variables Ask Bars Bid Close Digits High Low Open Point Time Volume
double Ask
Ask price (the Buyer's price).
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) { OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point, "My order #2",3,D'2005.10.10 12:30',Red); return; }
int Bars
Number of bars on the chart.
int counter=1; for(int i=1;i<=Bars;i++) { Print(Close[i-1]); }
double Bid
Bid price (the Seller's price).
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point, "My order #2",3,D'2005.10.10 12:30',Red); return(0); }
double Close[]
Returns the closing price of the bar being referenced.
int handle, bars=Bars; handle=FileOpen("file.csv",FILE_CSV|FILE_WRITE,';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i
int Digits
Number of digits after decimal point for the current symbol.
Print(DoubleToStr(Close[i-1], Digits));
double High[]
Returns the highest price of the bar referenced.
int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i
double Low[]
Returns the lowest price of the bar referenced.
int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";"); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i
double Open[]
Returns the opening price of the bar referenced.
int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i
double Point
Point value for the current chart.
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,Red);
datetime Time[]
Open time of the bars. Datetime is the number of seconds elapsed from 00:00 January 1, 1 970.
int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // write data for(int i=0; i
double Volume[]
Returns the ticks count for the referenced bar.
int handle, bars=Bars; handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';'); if(handle>0) { // write table columns headers FileWrite(handle, "Time;Open;High;Low;Close;Volume"); // erite data for(int i=0; i
Standard Constants Applied price enumeration Drawing shape style enumeration Error codes Ichimoku Kinko Hyo modes enumeration Indicators line identifiers Market information identifiers MessageBox return codes MessageBox behavior flags Moving Average method enumeration Object properties enumeration Object type enumeration Object visibility enumeration Predefined Arrow codes enumeration Series array identifier Special constants Time frame enumeration Trade operation enumeration
Uninitialize reason codes Wingdings symbols Web colors table
Applied price enumeration
Applied price constants. It can be any of the following values: Constant
Value
Description
PRICE_CLOSE
0
Close price.
PRICE_OPEN
1
Open price.
PRICE_HIGH
2
High price.
PRICE_LOW
3
Low price.
PRICE_MEDIAN
4
Median price, (high+low)/2.
PRICE_TYPICAL
5
Typical price, (high+low+close)/3.
PRICE_WEIGHTED
6
Weighted close price, (high+low+close+close)/4.
Drawing shape style enumeration
Drawing shape style enumeration for SetIndexStyle() function. It can be any of the following values: Constant
Value
Description
DRAW_LINE
0
Drawing line.
DRAW_SECTION
1
Drawing sections.
DRAW_HISTOGRAM
2
Drawing histogram.
DRAW_ARROW
3
Drawing arrows (symbols).
DRAW_NONE
12
No drawing.
Drawing style. Valid when width=1. It can be any of the
following values: Constant
Value
Description
STYLE_SOLID
0
The pen is solid.
STYLE_DASH
1
The pen is dashed.
STYLE_DOT
2
The pen is dotted.
STYLE_DASHDOT
3
The pen has alternating dashes and dots.
STYLE_DASHDOTDOT 4
The pen has alternating dashes and double dots.
Error codes
The GetLastError() function return codes. Error code constants defined at stderror.mqh file. To print text messages use ErrorDescription() function defined at stdlib.mqh file. #include void SendMyMessage(string text) { int check; SendMail("some subject", text); check=GetLastError(); if(check!=ERR_NO_MQLERROR) Print("Cannot send message, error: ",ErrorDescription(check)); }
Error codes returned from trade server.
Constant
Value
Description
ERR_NO_ERROR
0
No error returned.
ERR_NO_RESULT
1
No error returned, but the result is unknown.
ERR_COMMON_ERROR
2
Common error.
ERR_INVALID_TRADE_PARAMETERS
3
Invalid trade parameters.
ERR_SERVER_BUSY
4
Trade server is busy.
ERR_OLD_VERSION
5
Old version of the client terminal.
ERR_NO_CONNECTION
6
No connection with trade server.
ERR_NOT_ENOUGH_RIGHTS
7
Not enough rights.
ERR_TOO_FREQUENT_REQUESTS
8
Too frequent requests.
ERR_MALFUNCTIONAL_TRADE
9
Malfunctional trade operation.
ERR_ACCOUNT_DISABLED
64
Account disabled.
ERR_INVALID_ACCOUNT
65
Invalid account.
ERR_TRADE_TIMEOUT
128
Trade timeout.
ERR_INVALID_PRICE
129
Invalid price.
ERR_INVALID_STOPS
130
Invalid stops.
ERR_INVALID_TRADE_VOLUME
131
Invalid trade volume.
ERR_MARKET_CLOSED
132
Market is closed.
ERR_TRADE_DISABLED
133
Trade is disabled.
ERR_NOT_ENOUGH_MONEY
134
Not enough money.
ERR_PRICE_CHANGED
135
Price changed.
ERR_OFF_QUOTES
136
Off quotes.
ERR_BROKER_BUSY
137
Broker is busy.
ERR_REQUOTE
138
Requote.
ERR_ORDER_LOCKED
139
Order is locked.
ERR_LONG_POSITIONS_ONLY_ALLOWED 140
Long positions only allowed.
ERR_TOO_MANY_REQUESTS
141
Too many requests.
ERR_TRADE_MODIFY_DENIED
145
Modification denied because order too close to market.
ERR_TRADE_CONTEXT_BUSY
146
Trade context is busy.
MQL4 run time error codes
Constant
Value
Description
ERR_NO_MQLERROR
4000
No error.
ERR_WRONG_FUNCTION_POINTER
4001
Wrong function pointer.
ERR_ARRAY_INDEX_OUT_OF_RANGE
4002
Array index is out of range.
ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK
4003
No memory for function call stack.
ERR_RECURSIVE_STACK_OVERFLOW
4004
Recursive stack overflow.
ERR_NOT_ENOUGH_STACK_FOR_PARAMETER
4005
Not enough stack for parameter.
ERR_NO_MEMORY_FOR_PARAMETER_STRING
4006
No memory for parameter string.
ERR_NO_MEMORY_FOR_TEMP_STRING
4007
No memory for temp string.
ERR_NOT_INITIALIZED_STRING
4008
Not initialized string.
ERR_NOT_INITIALIZED_ARRAYSTRING
4009
Not initialized string in array.
ERR_NO_MEMORY_FOR_ARRAYSTRING
4010
No memory for array string.
ERR_TOO_LONG_STRING
4011
Too long string.
ERR_REMAINDER_FROM_ZERO_DIVIDE
4012
Remainder from zero divide.
ERR_ZERO_DIVIDE
4013
Zero divide.
ERR_UNKNOWN_COMMAND
4014
Unknown command.
ERR_WRONG_JUMP
4015
Wrong jump (never generated error).
ERR_NOT_INITIALIZED_ARRAY
4016
Not initialized array.
ERR_DLL_CALLS_NOT_ALLOWED
4017
DLL calls are not allowed.
ERR_CANNOT_LOAD_LIBRARY
4018
Cannot load library.
ERR_CANNOT_CALL_FUNCTION
4019
Cannot call function.
ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED
4020
Expert function calls are not allowed.
ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021
Not enough memory for temp string returned from function.
ERR_SYSTEM_BUSY
4022
System is busy (never generated error).
ERR_INVALID_FUNCTION_PARAMETERS_COUNT
4050
Invalid function parameters count.
ERR_INVALID_FUNCTION_PARAMETER_VALUE
4051
Invalid function parameter value.
ERR_STRING_FUNCTION_INTERNAL_ERROR
4052
String function internal error.
ERR_SOME_ARRAY_ERROR
4053
Some array error.
ERR_INCORRECT_SERIES_ARRAY_USING
4054
Incorrect series array using.
ERR_CUSTOM_INDICATOR_ERROR
4055
Custom indicator error.
ERR_INCOMPATIBLE_ARRAYS
4056
Arrays are incompatible.
ERR_GLOBAL_VARIABLES_PROCESSING_ERROR
4057
Global variables processing error.
ERR_GLOBAL_VARIABLE_NOT_FOUND
4058
Global variable not found.
ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE
4059
Function is not allowed in testing mode.
ERR_FUNCTION_NOT_CONFIRMED
4060
Function is not confirmed.
ERR_SEND_MAIL_ERROR
4061
Send mail error.
ERR_STRING_PARAMETER_EXPECTED
4062
String parameter expected.
ERR_INTEGER_PARAMETER_EXPECTED
4063
Integer parameter expected.
ERR_DOUBLE_PARAMETER_EXPECTED
4064
Double parameter expected.
ERR_ARRAY_AS_PARAMETER_EXPECTED
4065
Array as parameter expected.
ERR_HISTORY_WILL_UPDATED
4066
Requested history data in updating state.
ERR_END_OF_FILE
4099
End of file.
ERR_SOME_FILE_ERROR
4100
Some file error.
ERR_WRONG_FILE_NAME
4101
Wrong file name.
ERR_TOO_MANY_OPENED_FILES
4102
Too many opened files.
ERR_CANNOT_OPEN_FILE
4103
Cannot open file.
Ichimoku Kinko Hyo modes enumeration
Ichimoku Kinko Hyo source It can be one of the following values: Constant
Value
of
data.
Used
in
iIchimoku()
indicators.
iMACD(),
iRVI()
and
iStochastic()
indicators.
Description
MODE_TENKANSEN
1
Tenkan-sen.
MODE_KIJUNSEN
2
Kijun-sen.
MODE_SENKOUSPANA 3
Senkou Span A.
MODE_SENKOUSPANB 4
Senkou Span B.
MODE_CHINKOUSPAN 5
Chinkou Span.
Indicators line identifiers
Indicator line identifiers used It can be one of the following values: Constant
Value
Description
MODE_MAIN
0
Base indicator line.
MODE_SIGNAL
1
Signal line.
Constant
Value
in
Indicator line identifiers used in iADX() indicator.
Description
MODE_MAIN
0
Base indicator line.
MODE_PLUSDI
1
+DI indicator line.
MODE_MINUSDI
2
-DI indicator line.
Value
Description
Indicator iEnvelopesOnArray(), iFractals() and iGator() indicators. Constant
MODE_UPPER
1
Upper line.
MODE_LOWER
2
Lower line.
line
identifiers
used
with
used
in
iBands(),
iEnvelopes(),
Market information identifiers
Market information identifiers, It can be any of the following values:
MarketInfo()
function.
Constant
Value
Description
MODE_LOW
1
Low day price.
MODE_HIGH
2
High day price.
MODE_TIME
5
The last incoming quotation time.
MODE_BID
9
Last incoming bid price.
MODE_ASK
10
Last incoming ask price.
MODE_POINT
11
Point size.
MODE_DIGITS
12
Digits after decimal point.
MODE_SPREAD
13
Spread value in points.
MODE_STOPLEVEL
14
Stop level in points.
MODE_LOTSIZE
15
Lot size in the base currency.
MODE_TICKVALUE
16
Tick value.
MODE_TICKSIZE
17
Tick size.
MODE_SWAPLONG
18
Swap of the long position.
MODE_SWAPSHORT
19
Swap of the short position.
MODE_STARTING
20
Market starting date (usually used for future markets).
MODE_EXPIRATION
21
Market expiration date (usually used for future markets).
MODE_TRADEALLOWED 22
Trade is allowed for the symbol.
MODE_MINLOT
22
The minimum lot size in points.
MODE_LOTSTEP
22
Step for changing lots in points.
MessageBox return codes
The MessageBox() function return codes. If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect. Note: MessageBox return codes defined in the WinUser32.mqh file Constant
Value
Description
IDOK
1
OK button was selected.
IDCANCEL
2
Cancel button was selected.
IDABORT
3
Abort button was selected.
IDRETRY
4
Retry button was selected.
IDIGNORE
5
Ignore button was selected.
IDYES
6
Yes button was selected.
IDNO
7
No button was selected.
IDTRYAGAIN
10
Try Again button was selected.
IDCONTINUE
11
Continue button was selected.
MessageBox behavior flags
The MessageBox function flags specify the contents and behavior of the dialog box. This value can be a combination of flags from the following groups of flags. Note: MessageBox return codes defined in the WinUser32.mqh file To indicate the buttons displayed in the message box, specify one of the following values.
Constant
Value
Description
MB_OK
0x00000000 The message box contains one push button: OK. This is the default.
MB_OKCANCEL
0x00000001 The message box contains two push buttons: OK and Cancel.
MB_ABORTRETRYIGNORE
0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore.
MB_YESNOCANCEL
0x00000003 The message box contains three push buttons: Yes, No, and Cancel.
MB_YESNO
0x00000004 The message box contains two push buttons: Yes and No.
MB_RETRYCANCEL
0x00000005 The message box contains two push buttons: Retry and Cancel.
MB_CANCELTRYCONTINUE 0x00000006
Windows 2000: The message box contains three push buttons: Cancel, Try Again, Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
To display an icon in the message box, specify one of the following values. Constant
Value
Description
MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND 0x00000010 A stop-sign icon appears in the message box. MB_ICONQUESTION
0x00000020 A question-mark icon appears in the message box.
MB_ICONEXCLAMATION, MB_ICONWARNING
0x00000030 An exclamation-point icon appears in the message box.
MB_ICONINFORMATION, MB_ICONASTERISK
0x00000040
An icon consisting of a lowercase letter i in a circle appears in the message box.
To indicate the default button, specify one of the following values. Constant
Value
Description
The first button is the default button. MB_DEFBUTTON1 is the default unless MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON1
0x00000000
MB_DEFBUTTON2
0x00000100 The second button is the default button.
MB_DEFBUTTON3
0x00000200 The third button is the default button.
MB_DEFBUTTON4
0x00000300 The fourth button is the default button.
Moving Average method enumeration
Moving Average calculation method. used with iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(), iMAOnArray(), iStdDev(), iStdDevOnArray(), iStochastic() indicators. It can be any of the following values: Constant
Value
Description
MODE_SMA
0
Simple moving average,
MODE_EMA
1
Exponential moving average,
MODE_SMMA
2
Smoothed moving average,
MODE_LWMA
3
Linear weighted moving average.
Object properties enumeration
Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values:
Constant
Value
Description
OBJPROP_TIME1
0
Datetime value to set/get first coordinate time part.
OBJPROP_PRICE1
1
Double value to set/get first coordinate price part.
OBJPROP_TIME2
2
Datetime value to set/get second coordinate time part.
OBJPROP_PRICE2
3
Double value to set/get second coordinate price part.
OBJPROP_TIME3
4
Datetime value to set/get third coordinate time part.
OBJPROP_PRICE3
5
Double value to set/get third coordinate price part.
OBJPROP_COLOR
6
Color value to set/get object color.
OBJPROP_STYLE
7
Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT, STYLE_DASHDOTDOT constants to set/get object line style.
OBJPROP_WIDTH
8
Integer value to set/get object line width. Can be from 1 to 5.
OBJPROP_BACK
9
Boolean value to set/get background drawing flag for object.
OBJPROP_RAY
10
Boolean value to set/get ray flag of object.
OBJPROP_ELLIPSE
11
Boolean value to set/get ellipse flag for fibo arcs.
OBJPROP_SCALE
12
Double value to set/get scale object property.
OBJPROP_ANGLE
13
Double value to set/get angle object property in degrees.
OBJPROP_ARROWCODE
14
Integer value or arrow enumeration to set/get arrow code object property.
OBJPROP_TIMEFRAMES
15
Value can be one or combination (bitwise addition) of object visibility constants to set/get timeframe object property.
OBJPROP_DEVIATION
16
Double value to set/get deviation property for Standard deviation objects.
OBJPROP_FONTSIZE
100
Integer value to set/get font size for text objects.
OBJPROP_CORNER
101
Integer value to set/get anchor corner property for label objects. Must be from 0-3.
OBJPROP_XDISTANCE
102
Integer value to set/get anchor X distance object property in pixels.
OBJPROP_YDISTANCE
103
Integer value is to set/get anchor Y distance object property in pixels.
OBJPROP_FIBOLEVELS
200
Integer value to set/get Fibonacci object level count. Can be from 0 to 32.
OBJPROP_FIRSTLEVEL+n
210
Fibonacci object level index, where n is level index to set/get. Can be from 0 to 31.
Object type enumeration
Object type identifier constants used with ObjectCreate(), ObjectsDeleteAll() and ObjectType() functions. It can be any of the following values: Objects can have 1-3 coordinates related to type.
Constant
Value
Description
OBJ_VLINE
0
Vertical line. Uses time part of first coordinate.
OBJ_HLINE
1
Horizontal line. Uses price part of first coordinate.
OBJ_TREND
2
Trend line. Uses 2 coordinates.
OBJ_TRENDBYANGLE
3
Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function.
OBJ_REGRESSION
4
Regression. Uses time parts of first two coordinates.
OBJ_CHANNEL
5
Channel. Uses 3 coordinates.
OBJ_STDDEVCHANNEL
6
Standard deviation channel. Uses time parts of first two coordinates.
OBJ_GANNLINE
7
Gann line. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNFAN
8
Gann fan. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNGRID
9
Gann grid. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_FIBO
10
Fibonacci retracement. Uses 2 coordinates.
OBJ_FIBOTIMES
11
Fibonacci time zones. Uses 2 coordinates.
OBJ_FIBOFAN
12
Fibonacci fan. Uses 2 coordinates.
OBJ_FIBOARC
13
Fibonacci arcs. Uses 2 coordinates.
OBJ_EXPANSION
14
Fibonacci expansions. Uses 3 coordinates.
OBJ_FIBOCHANNEL
15
Fibonacci channel. Uses 3 coordinates.
OBJ_RECTANGLE
16
Rectangle. Uses 2 coordinates.
OBJ_TRIANGLE
17
Triangle. Uses 3 coordinates.
OBJ_ELLIPSE
18
Ellipse. Uses 2 coordinates.
OBJ_PITCHFORK
19
Andrews pitchfork. Uses 3 coordinates.
OBJ_CYCLES
20
Cycles. Uses 2 coordinates.
OBJ_TEXT
21
Text. Uses 1 coordinate.
OBJ_ARROW
22
Arrows. Uses 1 coordinate.
OBJ_LABEL
23
Text label. Uses 1 coordinate in pixels.
Object visibility enumeration
Time frames where object may be shown. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property. Constant
Value
Description
OBJ_PERIOD_M1
0x0001 Object shown is only on 1-minute charts.
OBJ_PERIOD_M5
0x0002 Object shown is only on 5-minute charts.
OBJ_PERIOD_M15
0x0004 Object shown is only on 15-minute charts.
OBJ_PERIOD_M30
0x0008 Object shown is only on 30-minute charts.
OBJ_PERIOD_H1
0x0010 Object shown is only on 1-hour charts.
OBJ_PERIOD_H4
0x0020 Object shown is only on 4-hour charts.
OBJ_PERIOD_D1
0x0040 Object shown is only on daily charts.
OBJ_PERIOD_W1
0x0080 Object shown is only on weekly charts.
OBJ_PERIOD_MN1
0x0100 Object shown is only on monthly charts.
OBJ_ALL_PERIODS
0x01FF Object shown is on all timeframes.
NULL
0
Object shown is on all timeframes.
EMPTY
-1
Hidden object on all timeframes.
Predefined Arrow codes enumeration
Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values:
Constant
Value
Description
SYMBOL_THUMBSUP
67
Thumb up symbol ().
SYMBOL_THUMBSDOWN
68
Thumb down symbol ().
SYMBOL_ARROWUP
241
Arrow up symbol ().
SYMBOL_ARROWDOWN
242
Arrow down symbol ().
SYMBOL_STOPSIGN
251
Stop sign symbol ().
SYMBOL_CHECKSIGN
252
Check sign symbol ().
Special Arrow codes that exactly points to price and time.
It can be one of the following values: Constant
Value
Description
1
Upwards arrow with tip rightwards ( ↱).
2
Downwards arrow with tip rightwards ( ↳).
3
Left pointing triangle (◄).
4
En Dash symbol (–).
SYMBOL_LEFTPRICE
5
Left sided price label.
SYMBOL_RIGHTPRICE
6
Right sided price label.
Series array identifier
Series array identifier used It can be any of the following values: Constant
Value
with
ArrayCopySeries(),
Highest()
and
Lowest()
Description
MODE_OPEN
0
Open price.
MODE_LOW
1
Low price.
MODE_HIGH
2
High price.
MODE_CLOSE
3
Close price.
MODE_VOLUME
4
Volume, used in Lowest() and Highest() functions.
MODE_TIME
5
Bar open time, used in ArrayCopySeries() function.
Special constants
Special constants used to indicate parameters and variables states. It can be one of the following values: Constant
value
Description
NULL
0
Indicates empty state of the string.
EMPTY
-1
Indicates empty state of the parameter.
EMPTY_VALUE
0x7FFFFFFF Default custom indicator empty value.
CLR_NONE
0xFFFFFFFF Indicates empty state of colors.
WHOLE_ARRAY
0
Used with array functions. Indicates that all array elements will be processed.
Time frame enumeration
Time frame on the chart. It can be any of the following values:
functions.
Constant
Value
Description
PERIOD_M1
1
1 minute.
PERIOD_M5
5
5 minutes.
PERIOD_M15
15
15 minutes.
PERIOD_M30
30
30 minutes.
PERIOD_H1
60
1 hour.
PERIOD_H4
240
4 hour.
PERIOD_D1
1440
Daily.
PERIOD_W1
10080
Weekly.
PERIOD_MN1
43200
Monthly.
0 (zero)
0
Time frame used on the chart.
Trade operation enumeration
Operation type for the OrderSend() function. It can be any of the following values: Constant
Value
Description
OP_BUY
0
Buying position.
OP_SELL
1
Selling position.
OP_BUYLIMIT
2
Buy limit pending position.
OP_SELLLIMIT
3
Sell limit pending position.
OP_BUYSTOP
4
Buy stop pending position.
OP_SELLSTOP
5
Sell stop pending position.
Uninitialize reason codes
Uninitialize reason codes returned by UninitializeReason() function. It can be any one of the following values: Constant
Value
Description
REASON_REMOVE
1
Expert removed from chart.
REASON_RECOMPILE
2
Expert recompiled.
REASON_CHARTCHANGE 3
symbol or timeframe changed on the chart.
REASON_CHARTCLOSE
4
Chart closed.
REASON_PARAMETERS
5
Inputs parameters was changed by user.
REASON_ACCOUNT
6
Other account activated.
Wingdings symbols
Wingdings font symbols used with Arrow objects.
32
48 64 80 96
33 49 65 81 97
34 50 66 82 98
35 51 67 83 99
36 52 68 84 10 0
37
10 1
38 54 70 86 10 2
53 69 85
39 55 71 87 10 3
40 56 72 88 10 4
41 57 73 89 10 5
42 58 74 90 10 6
11 2
11 3
11 4
11 5
11 6
11 7
11 8
11 9
12 12 0 1
12 8
12 9
13 0
13 1
13 2
…
13 3
13 4
13 5
14 4
14 5
’
14 6
14 7
”
14 8
14 9
15 0
—
16 0
16 1
16 2
16 3
16 4
16 5
16 6
17 6
17 7
17 8
17 9
18 0
18 1
19 2
19 3
19 4
19 5
19 6
19 7
20 8
20 9
21 0
21 1
21 2
21 21 3 4
22 4
22 5
22 6
22 7
22 8
22 9
24 0
24 1
24 2
24 3
24 4
24 5
‘
“
43 59 75 91 10 7
44 60 76 92 10 8
45 61 77 93 10 9
46 62 78 94 11 0
47 63 79 95 11 1
12 2
12 3
12 4
12 5
12 6
12 7
13 8
13 9
14 0
14 1
14 2
14 3
15 1
15 15 15 2 3 4
15 5
15 6
15 7
15 8
15 9
16 7
16 8
16 9
17 0
17 1
17 2
- 17 3
17 4
17 5
18 2
18 3
18 4
18 5
18 6
18 7
18 8
18 9
19 0
19 1
19 8
20 20 20 19 9 0 1 2
20 3
20 4
20 5
20 6
20 7
21 5
13 6
21 7
21 8
21 9
22 0
22 1
22 2
22 3
23 0
23 23 1 2
23 3
23 4
23 5
23 6
23 7
23 8
23 9
24 6
24 9
25 0
25 1
25 2
25 3
25 4
25 5
24 7
21 6
‰13 7
24 8
Web colors table Black
DarkGreen
DarkSlateGray
Olive
Green
Teal
Navy
Purple
Maroon
Indigo
MidnightBlue
DarkBlue
DarkOliveGreen
SaddleBrown
ForestGreen
OliveDrab
SeaGreen
DarkGoldenrod
DarkSlateBlue
Sienna
MediumBlue
Brown
DarkTurquoise
DimGray
LightSeaGreen
DarkViolet
FireBrick
MediumVioletRed
MediumSeaGreen
Chocolate
Crimson
SteelBlue
Goldenrod
MediumSpringGreen
LawnGreen
CadetBlue
DarkOrchid
YellowGreen
LimeGreen
OrangeRed
DarkOrange
Orange
Gold
Yellow
Chartreuse
Lime
SpringGreen
Aqua
DeepSkyBlue
Blue
Magenta
Red
Gray
SlateGray
Peru
BlueViolet
LightSlateGray
DeepPink
MediumTurquoise
DodgerBlue
Turquoise
RoyalBlue
SlateBlue
DarkKhaki
IndianRed
MediumOrchid
GreenYellow
MediumAquamarine
DarkSeaGreen
Tomato
RosyBrown
Orchid
MediumPurple
PaleVioletRed
Coral
CornflowerBlue
DarkGray
DarkSalmon
BurlyWood
Salmon
Violet
LightCoral
SkyBlue
LightSalmon
Plum
Khaki
LightGreen
Aquamarine
Silver
LightSkyBlue
LightSteelBlue
LightBlue
PaleGreen
Thistle
PowderBlue
PaleGoldenrod
PaleTurquoise
LightGray
Wheat
NavajoWhite
Moccasin
LightPink
Gainsboro
PeachPuff
Pink
Bisque
LemonChiffon
Beige
AntiqueWhite
PapayaWhip
Cornsilk
LightYellow
LightCyan
Linen
Lavender
MistyRose
OldLace
WhiteSmoke
Seashell
Ivory
Honeydew
AliceBlue
LavenderBlush
MintCream
Snow
White
HotPink
SandyBrown MediumSlateBlue
Tan
LightGoldenRod BlanchedAlmond
String functions StringConcatenate() StringFind() StringGetChar() StringLen() StringSetChar() StringSubstr() StringTrimLeft() StringTrimRight() string StringConcatenate(... ) Writes data to the string and returns it. Parameters can be of any type. Arrays cannot be passed to the StringConcatenate() function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string convert it by TimeToStr() function. StringConcatenate() function work faster than concatenating strings by + operator. See also: Print(), Alert() and Comment() functions.
Parameters ...
-
Any values, separated by commas.
Sample string text; text=StringConcatenate("Account free margin is ", AccountFreeMargin(), "Current time is ", TimeToStr(CurTime())); // slow text="Account free margin is " + AccountFreeMargin() + "Current time is " + TimeToStr(CurTime()) Print(text);
int StringFind(string text, string matched_text, int start=0) Scans this string for the first match of a substring.
Parameters text
-
String to search for.
matched_text
-
String to search for.
start
-
Starting index in the string.
Sample string text="The quick brown dog jumps over the lazy fox"; int index=StringFind(text, "dog jumps", 0); if(index!=16) Print("oops!");
int StringGetChar(string text, int pos) Returns character (code) from specified position in the string.
Parameters text
-
String where character will be retrieved.
pos
-
Char zero based position in the string.
Sample int char_code=StringGetChar("abcdefgh", 3); // char code 'c' is 99
int StringLen(string text) Returns character count of a string.
Parameters text
-
String to calculate length.
Sample string str="some text"; if(StringLen(str)<5) return(0);
string StringSetChar(string text, int pos, int value) Returns string copy with changed character at the indicated position with new value.
Parameters text
-
String where character will be changed.
pos
-
Zero based character position in the string. Can be from 0 to StringLen()-1.
value
-
New char ASCII code.
Sample string str="abcdefgh"; string str1=StringSetChar(str, 3, 'D'); // str1 is "abcDefgh"
string StringSubstr(string text, int start, int count=EMPTY) Extracts a substring from text string, starting at The function returns a copy of the extracted substring if possible, otherwise returns empty string.
position
(zero-based).
Parameters text
-
String from substring will be extracted.
start
-
Substring starting index
count
-
Character count.
Sample string text="The quick brown dog jumps over the lazy fox"; string substr=StringSubstr(text, 4, 5); // subtracted string is "quick" word
string StringTrimLeft(string text) Call the function to trim leading white space characters from the string. StringTrimLeft removes new line, space, and tab characters. The function returns a copy of the trimmed string if possible, otherwise returns empty string. Returns new string with changes.
Parameters text
-
String to trim left.
Sample string str1=" Hello world "; string str2=StringTrimLeft(str); // after trimming the str2 variable will be "Hello World
"
string StringTrimRight(string text) Call the function to trim leading white space characters from the string. StringTrimRight removes new line, space, and tab characters. The function returns a copy of the trimmed string if possible, otherwise return empty string.
Parameters text
-
String to trim right.
Sample string str1=" Hello world "; string str2=StringTrimRight(str); // after trimming the str2 variable will be "
Technical Indicator calls Accelerator Oscillator - iAC() Accumulation/Distribution - iAD() Alligator - iAlligator() Average Directional Movement Index - iADX() Average True Range - iATR() Awesome Oscillator - iAO() Bears Power - iBearsPower() Bollinger Bands - iBands() Bollinger Bands on buffer - iBandsOnArray() Bulls Power - iBullsPower() Commodity Channel Index - iCCI() Commodity Channel Index on buffer - iCCIOnArray() Custom Indicator - iCustom() DeMarker - iDeMarker() Envelopes - iEnvelopes() Envelopes on buffer - iEnvelopesOnArray() Force Index - iForce()
Hello World"
Fractals - iFractals() Gator Oscillator - iGator() Ichimoku Kinko Hyo - iIchimoku() Market Facilitation Index (Bill Williams) - iBWMFI() Momentum - iMomentum() Momentum on buffer - iMomentumOnArray() Money Flow Index - iMFI() Moving Average - iMA() Moving Average on buffer - iMAOnArray() Moving Average of Oscillator - iOsMA() Moving Averages Convergence/Divergence - iMACD() On Balance Volume - iOBV() Parabolic SAR - iSAR() Relative Strength Index - iRSI() Relative Strength Index on buffer - iRSIOnArray() Relative Vigor Index - iRVI() Standard Deviation - iStdDev() Standard Deviation on buffer - iStdDevOnArray() Stochastic Oscillator - iStochastic() William's Percent Range - iWPR() iBars() iBarShift() iClose() iHigh() iLow() iOpen() iTime() iVolume() Highest() Lowest()
double iAC(string symbol, int timeframe, int shift) Calculates the Bill Williams' Accelerator/Decelerator oscillator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double result=iAC(NULL, 0, 1);
double iAD(string symbol, int timeframe, int shift) Calculates the Accumulation/Distribution indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double result=iAD(NULL, 0, 1);
double iAlligator(
string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift) Calculates the Bill Williams' Alligator and returns its value.
Parameters
symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
jaw_period
-
Jaw period.
jaw_shift
-
Jaw line shift.
teeth_period
-
Teeth period.
teeth_shift
-
Teeth line shift.
lips_period
-
Lips period.
lips_shift
-
Lips line shift.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
mode
-
Source of data. It can be any of the following values: MODE_GATORJAW - Gator Jaw (blue) balance line, MODE_GATORTEETH - Gator Teeth (red) balance line, MODE_GATORLIPS - Gator Lips (green) balance line.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double jaw_val=iAlligator(NULl, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_GATORJAW, 1);
double string symbol, int timeframe, int period, int applied_price, int mode, iADX( int shift) Calculates the Movement directional index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
mode
-
Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0)>iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0)) return(0);
double iATR(string symbol, int timeframe, int period, int shift) Calculates the Indicator of the average true range and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0);
double iAO(string symbol, int timeframe, int shift) Calculates the Bill Williams' Awesome oscillator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iAO(NULL, 0, 2);
double string symbol, int timeframe, int period, int applied_price, iBearsPower( int shift) Calculates the Bears Power indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iBearsPower(NULL, 0, 13,PRICE_CLOSE,0);
double string symbol, int timeframe, int period, int deviation, int bands_shift, iBands( int applied_price, int mode, int shift) Calculates the Bollinger bands indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
deviation
-
Deviation.
bands_shift
-
Bands shift.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
mode
-
Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0])
return(0);
double double array[], int total, int period, double deviation, iBandsOnArray( int bands_shift, int mode, int shift) Calculates the Bollinger bands indicator and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
period
-
Number of periods for calculation.
deviation
-
Deviation.
bands_shift
-
Bands shift.
mode
-
Series array identifier. It can be any of the Series array identifier enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iBands(ExtBuffer,total,2,0,MODE_LOWER,0)>Low[0]) return(0);
double string symbol, int timeframe, int period, int applied_price, iBullsPower( int shift) Calculates the Bulls Power indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iBullsPower(NULL, 0, 13,PRICE_CLOSE,0);
double iCCI(string symbol, int timeframe, int period, int applied_price, int shift) Calculates the Commodity channel index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iCCI(NULL,0,12,0)>iCCI(NULL,0,20,0)) return(0);
double iCCIOnArray(double array[], int total, int period, int shift) Calculates the Commodity channel index and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_OPEN, 0)) return(0);
double iCustom(string symbol, int timeframe, string name, ... , int mode, int shift) Calculates the Custom indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
name
-
Custom indicator compiled program name.
...
-
Parameters set (if needed).
mode
-
Line index. Can be from 0 to 7.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iCustom(NULL, 0, "SampleInd",13,1,0);
double iDeMarker(string symbol, int timeframe, int period, int shift) Calculates the DeMarker indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iDeMarker(NULL, 0, 13, 1);
double string symbol, int timeframe, int ma_period, int ma_method, iEnvelopes( int ma_shift, int applied_price, double deviation, int mode, int shift) Calculates the Envelopes indicator and returns its value.
Parameters
symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
ma_period
-
Number of periods for calculation.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
ma_shift
-
MA shift. Indicator line offset relate to the chart by timeframe.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
deviation
-
Deviation.
mode
-
Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iEnvelopes(NULL, 0, 13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0); double double array[], int total, int ma_period, int ma_method, iEnvelopesOnArray( int ma_shift, double deviation, int mode, int shift) Calculates the Envelopes indicator counted on buffer and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
ma_period
-
Number of periods for calculation.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
ma_shift
-
MA shift. Indicator line offset relate to the chart by timeframe.
deviation
-
Deviation.
mode
-
Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iEnvelopesOnArray(ExtBuffer, 0, 13, MODE_SMA, 0.2, MODE_UPPER,0 );
double string symbol, int timeframe, int period, int ma_method, iForce( int applied_price, int shift) Calculates the Force index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iForce(NULL, 0, 13,MODE_SMA,PRICE_CLOSE,0);
double iFractals(string symbol, int timeframe, int mode, int shift) Calculates the Fractals and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
mode
-
Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iFractals(NULL, 0, MODE_UPPER,0);
double iGator(
string symbol, int timeframe, int jaw_period, int jaw_shift, int teeth_period, int teeth_shift, int lips_period, int lips_shift, int ma_method, int applied_price, int mode, int shift)
Calculates the Gator Oscillator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
jaw_period
-
Jaw period.
jaw_shift
-
Jaw line shift.
teeth_period
-
Teeth period.
teeth_shift
-
Teeth line shift.
lips_period
-
Lips period.
lips_shift
-
Lips line shift.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
mode
-
Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double jaw_val=iGator(NULL, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN, MODE_UPPER, 1);
double string symbol, int timeframe, int tenkan_sen, int kijun_sen, iIchimoku( int senkou_span_b, int mode, int shift) Calculates the Ichimoku Kinko Hyo and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
tenkan_sen
-
Tenkan Sen.
kijun_sen
-
Kijun Sen.
senkou_span_b
-
Senkou SpanB.
mode
-
Source of data. It can be one of the Ichimoku Kinko Hyo mode enumeration.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double tenkan_sen=iIchimoku(NULL, 0, 9, 26, 52, MODE_TENKANSEN, 1);
double iBWMFI(string symbol, int timeframe, int shift) Calculates the Bill Williams Market Facilitation index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iBWMFI(NULL, 0, 0);
double string symbol, int timeframe, int period, int applied_price, iMomentum( int shift) Calculates the Momentum indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator.NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0))
return(0);
double iMomentumOnArray(double array[], int total, int period, int shift) Calculates the Momentum indicator counted on buffer and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,20,0)) return(0);
double iMFI(string symbol, int timeframe, int period, int shift) Calculates the Money flow index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0);
double string symbol, int timeframe, int period, int ma_shift, int ma_method, iMA( int applied_price, int shift) Calculates the Moving average indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
ma_shift
-
MA shift. Indicators line offset relate to the chart by timeframe.
ma_method
-
MA method. It can be any of the Moving Average method enumeration value.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);
double double array[], int total, int period, int ma_shift, int ma_method, iMAOnArray( int shift) Calculates the Moving average counted on buffer and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted. 0 means whole array.
period
-
Number of periods for calculation.
ma_shift
-
MA shift
ma_method
-
MA method. It can be any of the Moving Average method enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0); double macurrentslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,0);
double maprev=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,1); double maprevslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,1); //---if(maprev=macurrentslow) Alert("crossing up");
double string symbol, int timeframe, int fast_ema_period, int slow_ema_period, iOsMA( int signal_period, int applied_price, int shift) Calculates the Moving Average of Oscillator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
fast_ema_period
-
Number of periods for fast moving average calculation.
slow_ema_period
-
Nmber of periods for slow moving average calculation.
signal_period
-
Number of periods for signal moving average calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,0)) return(0);
double string symbol, int timeframe, int fast_ema_period, int slow_ema_period, iMACD( int signal_period, int applied_price, int mode, int shift) Calculates the Moving averages convergence/divergence and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
fast_ema_period
-
Number of periods for fast moving average calculation.
slow_ema_period
-
Number of periods for slow moving average calculation.
signal_period
-
Number of periods for signal moving average calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
mode
-
Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,M ODE_SIGNAL,0)) return(0);
double iOBV(string symbol, int timeframe, int applied_price, int shift) Calculates the On Balance Volume indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iOBV(NULL, 0, PRICE_CLOSE, 1);
double iSAR(string symbol, int timeframe, double step, double maximum, int shift) Calculates the Parabolic Sell and Reverse system and returns its value.
Parameters
symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
step
-
Increment, usually 0.02.
maximum
-
Maximum value, usually 0.2.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0);
double iRSI(string symbol, void timeframe, int period, int applied_price, int shift) Calculates the Relative strength index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>iRSI(NULL,0,14,PRICE_CLOSE,1))
return(0);
double iRSIOnArray(double array[], int total, int period, int shift) Calculates the Relative strength index counted on buffer and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iRSIOnBuffer(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1))
return(0);
double iRVI(string symbol, int timeframe, int period, int mode, int shift) Calculates the Relative Vigor index and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
mode
-
Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iRVI(NULL, 0, 10,MODE_MAIN,0);
double string symbol, int timeframe, int ma_period, int ma_method, int ma_shift, iStdDev( int applied_price, int shift) Calculates the Standard Deviation indicator and returns its value.
Parameters
symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
ma_period
-
MA period.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
ma_shift
-
MA shift.
applied_price
-
Applied price. It can be any of Applied price enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iStdDev(NULL,0,10,MODE_EMA,0,PRICE_CLOSE,0);
double double array[], int total, int ma_period, int ma_method, iStdDevOnArray( int ma_shift, int shift) Calculates the Standard Deviation counted on buffer and returns its value.
Parameters array[]
-
Array with data.
total
-
The number of items to be counted.
ma_period
-
MA period.
ma_method
-
MA method. It can be any of Moving Average method enumeration value.
ma_shift
-
iMA shift.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample double val=iStdDevOnArray(ExtBuffer,100,10,MODE_EMA,0,0);
double string symbol, int timeframe, int %Kperiod, int %Dperiod, int slowing, iStochastic( int method, int price_field, int mode, int shift) Calculates the Stochastic oscillator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
%Kperiod
-
%K line period.
%Dperiod
-
%D line period.
slowing
-
Slowing value.
method
-
MA method. It can be any of Moving Average method enumeration value.
price_field
-
Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close.
mode
-
Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_S MA,0,MODE_SIGNAL,0)) return(0);
double iWPR(string symbol, int timeframe, int period, int shift) Calculates the Larry William's percent range indicator and returns its value.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
period
-
Number of periods for calculation.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0);
int iBars(string symbol, int timeframe) Returns the number of bars on the specified chart.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
Sample Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1 is",iBars("EUROUSD",PERIOD_H1));
int iBarShift(string symbol, int timeframe, datetime time, bool exact=false) Search for bar by open time. The function returns bar shift with the open time specified. If the bar having the specified open time is absent the function will return, depending on the exact parameter, -1 or the nearest bar shift.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
time
-
value to find (bar's open time).
exact
-
Return mode when bar not found. false - iBarShift returns nearest. true - iBarShift returns -1.
Sample datetime some_time=D'2004.03.21 12:00'; int shift=iBarShift("EUROUSD",PERIOD_M1,some_time); Print("shift of bar with open time ",TimeToStr(some_time)," is ",shift);
double iClose(string symbol, int timeframe, int shift) Returns Close value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iHigh(string symbol, int timeframe, int shift) Returns High value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol on that data need to calculate indicator. NULL means current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iLow(string symbol, int timeframe, int shift) Returns Low value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iOpen(string symbol, int timeframe, int shift) Returns Open value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
datetime iTime(string symbol, int timeframe, int shift) Returns Time value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
double iVolume(string symbol, int timeframe, int shift) Returns Volume value for the bar of indicated symbol with timeframe and shift . If local history is empty (not loaded), function returns 0.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
shift
-
Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ", iOpen("USDCHF",PERIOD_H1,i),", ", iHigh("USDCHF",PERIOD_H1,i),", ", iLow("USDCHF",PERIOD_H1,i),", ", iClose("USDCHF",PERIOD_H1,i),", ", iVolume("USDCHF",PERIOD_H1,i));
int Highest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) Returns the shift of the maximum value over a specific number of periods depending on type.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
type
-
Series array identifier. It can be any of the Series array identifier enumeration values.
count
-
Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start
-
Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample double val; // calculating the highest value in the range from 5 element to 25 element // indicator charts symbol and indicator charts time frame val=High[Highest(NULL,0,MODE_HIGH,20,4)];
int Lowest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0) Returns the shift of the least value over a specific number of periods depending on type.
Parameters symbol
-
Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
type
-
Series array identifier. It can be any of Series array identifier enumeration values.
count
-
Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start
-
Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample double val=Low[Lowest(NULL,0,MODE_LOW,10,10)];
Trading functions HistoryTotal() OrderClose() OrderCloseBy() OrderClosePrice() OrderCloseTime() OrderComment() OrderCommission() OrderDelete() OrderExpiration() OrderLots() OrderMagicNumber() OrderModify() OrderOpenPrice() OrderOpenTime() OrderPrint() OrderProfit() OrderSelect() OrderSend() OrderStopLoss()
OrdersTotal() OrderSwap() OrderSymbol() OrderTakeProfit() OrderTicket() OrderType()
int HistoryTotal() Returns the number of closed orders in the account history loaded into the terminal. To get the detailed error information, call GetLastError() function.
Sample // retrieving info from trade history int i,hstTotal=HistoryTotal(); for(i=0;i
bool int ticket, double lots, double price, int slippage, OrderClose( color Color=CLR_NONE) Closes opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters ticket
-
Unique number of the order ticket.
lots
-
Number of lots.
price
-
Preferred closing price.
slippage
-
Value of the maximum price slippage in points.
Color
-
Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart.
Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) { OrderClose(order_id,1,Ask,3,Red); return(0); }
bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE) Closes opened order by another opposite opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters ticket
-
Unique number of the order ticket.
opposite
-
Unique number of the opposite order ticket.
Color
-
Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on the chart.
Sample if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) {
OrderCloseBy(order_id,opposite_id); return(0); }
double OrderClosePrice() Returns close price for Note: Order must be selected by OrderSelect() function.
the
currently
selected
order.
Sample if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Close price for the order ",ticket," = ",OrderClosePrice()); else Print("OrderSelect failed error code is",GetLastError());
datetime OrderCloseTime() Returns close time for the currently selected order. If order close time is not 0 then the order selected and has been closed and retrieved from the account history. Note: Order must be selected by OrderSelect() function.
Sample if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true) { datetime ctm=OrderOpenTime(); if(ctm>0) Print("Open time for the order 10 ", ctm); ctm=OrderCloseTime(); if(ctm>0) Print("Close time for the order 10 ", ctm); } else Print("OrderSelect failed error code is",GetLastError());
string OrderComment() Returns comment for Note: Order must be selected by OrderSelect() function.
the
selected
order.
Sample string comment; if(OrderSelect(10,SELECT_BY_TICKET)==false) { Print("OrderSelect failed error code is",GetLastError()); return(0); } comment = OrderComment(); // ...
double OrderCommission() Returns calculated commission Note: Order must be selected by OrderSelect() function.
for
the
currently
Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("Commission for the order 10 ",OrderCommission()); else Print("OrderSelect failed error code is",GetLastError());
selected
order.
bool OrderDelete(int ticket) Deletes previously opened pending order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters ticket
-
Unique number of the order ticket.
Sample if(Ask>var1) { OrderDelete(order_ticket); return(0); }
datetime OrderExpiration() Returns expiration date for Note: Order must be selected by OrderSelect() function.
the
selected
pending
order.
Sample if(OrderSelect(10, SELECT_BY_TICKET)==true) Print("Order expiration for the order #10 is ",OrderExpiration()); else Print("OrderSelect failed error code is",GetLastError());
double OrderLots() Returns lots value Note: Order must be selected by OrderSelect() function.
for
the
selected
order.
Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("lots for the order 10 ",OrderLots()); else Print("OrderSelect failed error code is",GetLastError());
int OrderMagicNumber() Returns magic number for Note: Order must be selected by OrderSelect() function.
the
currently
selected
order.
Sample if(OrderSelect(10,SELECT_BY_POS)==true) Print("Magic number for the order 10 ", OrderMagicNumber()); else Print("OrderSelect failed error code is",GetLastError());
bool int ticket, double price, double stoploss, double takeprofit, OrderModify( datetime expiration, color arrow_color=CLR_NONE) Modification of characteristics for the previously opened position or a pending order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters
ticket
-
Unique number of the order ticket.
price
-
New price (for pending orders only).
stoploss
-
New stoploss level.
takeprofit
-
New profit-taking level.
expiration
-
Order expiration server date/time (for pending orders only).
arrow_color
-
Arrow color of the pictogram on the chart.If the parameter is absent or has CLR_NONE value arrow will not be drawn on the chart.
Sample if(TrailingStop>0) { SelectOrder(12345,SELECT_BY_TICKET); if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()
double OrderOpenPrice() Returns open price for Note: Order must be selected by OrderSelect() function.
the
currently
selected
order.
selected
order.
Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("open price for the order 10 ",OrderOpenPrice()); else Print("OrderSelect failed error code is",GetLastError());
datetime OrderOpenTime() Returns open time for Note: Order must be selected by OrderSelect() function.
the
currently
Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("open time for the order 10 ",OrderOpenTime()); else Print("OrderSelect failed error code is",GetLastError());
void OrderPrint() Prints selected order data to Note: Order must be selected by OrderSelect() function.
the
log
for
the
selected
order.
Sample if(OrderSelect(10, SELECT_BY_TICKET)==true) OrderPrint(); else Print("OrderSelect failed error code is",GetLastError());
double OrderProfit() Returns profit
for
the
currently
selected
order.
Note: Order must be selected by OrderSelect() function.
Sample if(OrderSelect(10, SELECT_BY_POS)==true) Print("Profit for the order 10 ",OrderProfit()); else Print("OrderSelect failed error code is",GetLastError());
bool OrderSelect(int index, int select, int pool=MODE_TRADES) Selects order by index or ticket to further processing. If the function fails, the return value will be false. To get the extended error information, call GetLastError().
Parameters index
-
Order index or order ticket depending from second parameter.
select
-
Selecting flags. It can be any of the following values: SELECT_BY_POS - index in the order pool, SELECT_BY_TICKET - index is order ticket.
pool
-
Optional order pool index. Used when select parameter is SELECT_BY_POS.It can be any of the following values: MODE_TRADES (default)- order selected from trading pool(opened and pending orders), MODE_HISTORY - order selected from history pool (closed and canceled order).
Sample if(OrderSelect(12470, SELECT_BY_TICKET)==true) { Print("order #12470 open price is ", OrderOpenPrice()); Print("order #12470 close price is ", OrderClosePrice()); } else Print("OrderSelect failed error code is",GetLastError());
int string symbol, int cmd, double volume, double price, int slippage, OrderSend( double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE) Main function used to open a position or set a pending order. Returns ticket of the placed order or -1 if failed. To check error code use GetLastError() function.
Parameters symbol
-
Symbol for trading.
cmd
-
Operation type. It can be any of the Trade operation enumeration.
volume
-
Number of lots.
price
-
Preferred price of the trade.
slippage
-
Maximum price slippage for buy or sell orders.
stoploss
-
Stop loss level.
takeprofit
-
Take profit level.
comment
-
Order comment text. Last part of the comment may be changed by server.
magic
-
Order magic number. May be used as user defined identifier.
expiration
-
Order expiration time (for pending orders only).
arrow_color
-
Color of the opening arrow on the chart. If parameter is absent or has CLR_NONE value opening arrow is not drawn on the chart.
Sample int ticket; if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) { ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,Ask-25*Point,Ask+25*Point,"My #2",16384,0,Green); if(ticket<0) { Print("OrderSend failed with error #",GetLastError()); return(0);
order
} }
double OrderStopLoss() Returns stop loss value Note: Order must be selected by OrderSelect() function.
for
the
currently
selected
order.
Sample if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Stop loss value for the order 10 ", OrderStopLoss()); else Print("OrderSelect failed error code is",GetLastError());
int OrdersTotal() Returns market and pending orders count.
Sample int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"\t"); if(handle<0) return(0); // write header FileWrite(handle,"#","open price","open time","symbol","lots"); int total=OrdersTotal(); // write open orders for(int pos=0;pos
double OrderSwap() Returns swap value for Note: Order must be selected by OrderSelect() function.
the
currently
selected
order.
selected
order.
Sample if(OrderSelect(order_id, SELECT_BY_TICKET)==true) Print("Swap for the order #", order_id, " ",OrderSwap()); else Print("OrderSelect failed error code is",GetLastError());
string OrderSymbol() Returns the order symbol Note: Order must be selected by OrderSelect() function.
value
for
Sample if(OrderSelect(12, SELECT_BY_POS)==true) Print("symbol of order #", OrderTicket(), " is ", OrderSymbol()); else Print("OrderSelect failed error code is",GetLastError());
double OrderTakeProfit() Returns take profit
value
for
the
currently
selected
order.
Note: Order must be selected by OrderSelect() function.
Sample if(OrderSelect(12, SELECT_BY_POS)==true) Print("Order #",OrderTicket()," profit: ", OrderTakeProfit()); else Print("OrderSelect() 忮痦箅 铠栳牦 - ",GetLastError());
int OrderTicket() Returns ticket number for Note: Order must be selected by OrderSelect() function.
the
currently
selected
order.
Sample if(OrderSelect(12, SELECT_BY_POS)==true) order=OrderTicket(); else Print("OrderSelect failed error code is",GetLastError());
int OrderType() Returns order operation type for the currently OP_BUY OP_SELL OP_BUYLIMIT buy OP_BUYSTOP buy OP_SELLLIMIT sell OP_SELLSTOP sell Note: Order must be selected by OrderSelect() function.
selected
order.
It can buying selling
be
limit stop limit stop
Sample int order_type; if(OrderSelect(12, SELECT_BY_POS)==true) { order_type=OrderType(); // ... } else Print("OrderSelect() returned error - ",GetLastError());
Window functions BarsPerWindow() FirstVisibleBar() PriceOnDropped() TimeOnDropped() WindowFind() WindowHandle() WindowIsVisible WindowOnDropped() WindowsTotal() WindowXOnDropped() WindowYOnDropped()
int BarsPerWindow() Function returns the amount of bars visible on the chart.
Sample
any
of
pending pending pending pending
the
following
values: position, position, position, position, position, position.
// work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i
int FirstVisibleBar() Function returns index of the first visible bar.
Sample // work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i
int FirstVisibleBar() Function returns index of the first visible bar.
Sample // work with visible bars. int bars_count=BarsPerWindow(); int bar=FirstVisibleBar(); for(int i=0; i
datetime TimeOnDropped() Returns time part of dropped point where expert or script was dropped. This value is valid when expert or script dropped by mouse. Note: For custom indicators this value is undefined.
Sample double drop_price=PriceOnDropped(); datetime drop_time=TimeOnDropped(); //---- may be undefined (zero) if(drop_time>0) { ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price); ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time); }
int WindowFind(string name) If indicator with name found returns the window index containing specified indicator, otherwise Note: WindowFind() returns -1 if ñustom indicator searches itself when init() function works.
Parameters name
Sample
-
Indicator short name.
returns
-1.
int win_idx=WindowFind("MACD(12,26,9)");
int WindowHandle(string symbol, int timeframe) If chart of symbol and timeframe is currently opened returns the window handle, otherwise returns 0.
Parameters symbol
-
symbol name.
timeframe
-
Time frame. It can be any of Time frame enumeration values.
Sample int win_handle=WindowHandle("USDX",PERIOD_H1); if(win_handle!=0) Print("Window with USDX,H1 detected. Rates array will be copied immediately.");
bool WindowIsVisible(int index) Returns true if the chart subwindow is visible, otherwise returns false.
Parameters index
-
Chart subwindow index.
Sample int maywin=WindowFind("MyMACD"); if(maywin>-1 && WindowIsVisible(maywin)==true) Print("window of MyMACD is visible"); else Print("window of MyMACD not found or is not visible");
int WindowOnDropped() Returns window index where expert, custom indicator or script was dropped. This value is valid when expert, custom indicator or script dropped by mouse. Note: For custom indicators this index is undefined when init() function works and returning index is window index where custom indicator works (may be different from dropping window index, because custom indicator can create its own new window). See also WindowXOnDropped(), WindowYOnDropped()
Sample if(WindowOnDropped()!=0) { Print("Indicator 'MyIndicator' must be applied to main chart window!"); return(false); }
int WindowsTotal() Returns count of indicator windows on the chart (including main chart).
Sample Print("Windows count = ", WindowsTotal());
int WindowXOnDropped() Returns x-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped()
Sample Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());
int WindowYOnDropped() Returns y-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(), WindowOnDropped()
Sample Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());
Include Files //+------------------------------------------------------------------+ //| stderror.mqh | //| Copyright © 2004-2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ //---- errors returned from trade server #define ERR_NO_ERROR 0 #define ERR_NO_RESULT 1 #define ERR_COMMON_ERROR 2 #define ERR_INVALID_TRADE_PARAMETERS 3 #define ERR_SERVER_BUSY 4 #define ERR_OLD_VERSION 5 #define ERR_NO_CONNECTION 6 #define ERR_NOT_ENOUGH_RIGHTS 7 #define ERR_TOO_FREQUENT_REQUESTS 8 #define ERR_MALFUNCTIONAL_TRADE 9 #define ERR_ACCOUNT_DISABLED 64 #define ERR_INVALID_ACCOUNT 65 #define ERR_TRADE_TIMEOUT 128 #define ERR_INVALID_PRICE 129 #define ERR_INVALID_STOPS 130 #define ERR_INVALID_TRADE_VOLUME 131 #define ERR_MARKET_CLOSED 132 #define ERR_TRADE_DISABLED 133 #define ERR_NOT_ENOUGH_MONEY 134 #define ERR_PRICE_CHANGED 135 #define ERR_OFF_QUOTES 136 #define ERR_BROKER_BUSY 137 #define ERR_REQUOTE 138 #define ERR_ORDER_LOCKED 139 #define ERR_LONG_POSITIONS_ONLY_ALLOWED 140 #define ERR_TOO_MANY_REQUESTS 141 #define ERR_TRADE_MODIFY_DENIED 145 #define ERR_TRADE_CONTEXT_BUSY 146 //---- mql4 run time errors #define ERR_NO_MQLERROR 4000 #define ERR_WRONG_FUNCTION_POINTER 4001 #define ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 #define ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 #define ERR_RECURSIVE_STACK_OVERFLOW 4004 #define ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 #define ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 #define ERR_NO_MEMORY_FOR_TEMP_STRING 4007 #define ERR_NOT_INITIALIZED_STRING 4008 #define ERR_NOT_INITIALIZED_ARRAYSTRING 4009 #define ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 #define ERR_TOO_LONG_STRING 4011 #define ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 #define ERR_ZERO_DIVIDE 4013 #define ERR_UNKNOWN_COMMAND 4014 #define ERR_WRONG_JUMP 4015 #define ERR_NOT_INITIALIZED_ARRAY 4016 #define ERR_DLL_CALLS_NOT_ALLOWED 4017 #define ERR_CANNOT_LOAD_LIBRARY 4018 #define ERR_CANNOT_CALL_FUNCTION 4019
#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define
ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING ERR_SYSTEM_BUSY ERR_INVALID_FUNCTION_PARAMETERS_COUNT ERR_INVALID_FUNCTION_PARAMETER_VALUE ERR_STRING_FUNCTION_INTERNAL_ERROR ERR_SOME_ARRAY_ERROR ERR_INCORRECT_SERIES_ARRAY_USING ERR_CUSTOM_INDICATOR_ERROR ERR_INCOMPATIBLE_ARRAYS ERR_GLOBAL_VARIABLES_PROCESSING_ERROR ERR_GLOBAL_VARIABLE_NOT_FOUND ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE ERR_FUNCTION_NOT_CONFIRMED ERR_SEND_MAIL_ERROR ERR_STRING_PARAMETER_EXPECTED ERR_INTEGER_PARAMETER_EXPECTED ERR_DOUBLE_PARAMETER_EXPECTED ERR_ARRAY_AS_PARAMETER_EXPECTED ERR_HISTORY_WILL_UPDATED ERR_END_OF_FILE ERR_SOME_FILE_ERROR ERR_WRONG_FILE_NAME ERR_TOO_MANY_OPENED_FILES ERR_CANNOT_OPEN_FILE ERR_INCOMPATIBLE_ACCESS_TO_FILE ERR_NO_ORDER_SELECTED ERR_UNKNOWN_SYMBOL ERR_INVALID_PRICE_PARAM ERR_INVALID_TICKET ERR_TRADE_NOT_ALLOWED ERR_LONGS__NOT_ALLOWED ERR_SHORTS_NOT_ALLOWED ERR_OBJECT_ALREADY_EXISTS ERR_UNKNOWN_OBJECT_PROPERTY ERR_OBJECT_DOES_NOT_EXIST ERR_UNKNOWN_OBJECT_TYPE ERR_NO_OBJECT_NAME ERR_OBJECT_COORDINATES_ERROR ERR_NO_SPECIFIED_SUBWINDOW
4020 4021 4022 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4200 4201 4202 4203 4204 4205 4206
//+------------------------------------------------------------------+ //| stdlib.mqh | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #import "stdlib.ex4" string int bool string string
ErrorDescription(int error_code); RGB(int red_value,int green_value,int blue_value); CompareDoubles(double number1,double number2); DoubleToStrMorePrecision(double number,int precision); IntegerToHexString(int integer_number);
//+------------------------------------------------------------------+ //| WinUser32.mqh | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #define copyright "Copyright © 2004, MetaQuotes Software Corp." #define link "http://www.metaquotes.net/" #import "user32.dll" //---- messages
int SendMessageA(int hWnd,int Msg,int wParam,int lParam); int SendNotifyMessageA(int hWnd,int Msg,int wParam,int lParam); int PostMessageA(int hWnd,int Msg,int wParam,int lParam); void keybd_event(int bVk,int bScan,int dwFlags,int dwExtraInfo); void mouse_event(int dwFlags,int dx,int dy,int dwData,int dwExtraInfo); //---- windows int FindWindowA(string lpClassName ,string lpWindowName); int SetWindowTextA(int hWnd,string lpString); int GetWindowTextA(int hWnd,string lpString,int nMaxCount); int GetWindowTextLengthA(int hWnd); int GetWindow(int hWnd,int uCmd); int UpdateWindow(int hWnd); int EnableWindow(int hWnd,int bEnable); int DestroyWindow(int hWnd); int ShowWindow(int hWnd,int nCmdShow); int SetActiveWindow(int hWnd); int AnimateWindow(int hWnd,int dwTime,int dwFlags); int FlashWindow(int hWnd,int dwFlags /*bInvert*/); int CloseWindow(int hWnd); int MoveWindow(int hWnd,int X,int Y,int nWidth,int nHeight,int bRepaint); int SetWindowPos(int hWnd,int hWndInsertAfter ,int X,int Y,int cx,int cy,int uFlags); int IsWindowVisible(int hWnd); int IsIconic(int hWnd); int IsZoomed(int hWnd); int SetFocus(int hWnd); int GetFocus(); int GetActiveWindow(); int IsWindowEnabled(int hWnd); //---- miscelaneouse int MessageBoxA(int hWnd ,string lpText,string lpCaption,int uType); int MessageBoxExA(int hWnd ,string lpText,string lpCaption,int uType,int wLanguageId); int MessageBeep(int uType); int GetSystemMetrics(int nIndex); int ExitWindowsEx(int uFlags,int dwReserved); int SwapMouseButton(int fSwap); #import //---- Window Messages #define WM_NULL #define WM_CREATE #define WM_DESTROY #define WM_MOVE #define WM_SIZE #define WM_ACTIVATE #define WM_SETFOCUS #define WM_KILLFOCUS #define WM_ENABLE #define WM_SETREDRAW #define WM_SETTEXT #define WM_GETTEXT #define WM_GETTEXTLENGTH #define WM_PAINT #define WM_CLOSE #define WM_QUERYENDSESSION #define WM_QUIT #define WM_QUERYOPEN #define WM_ERASEBKGND #define WM_SYSCOLORCHANGE #define WM_ENDSESSION #define WM_SHOWWINDOW #define WM_WININICHANGE #define WM_SETTINGCHANGE #define WM_DEVMODECHANGE #define WM_ACTIVATEAPP
0x0000 0x0001 0x0002 0x0003 0x0005 0x0006 0x0007 0x0008 0x000A 0x000B 0x000C 0x000D 0x000E 0x000F 0x0010 0x0011 0x0012 0x0013 0x0014 0x0015 0x0016 0x0018 0x001A 0x001A // WM_WININICHANGE 0x001B 0x001C
#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define
WM_FONTCHANGE WM_TIMECHANGE WM_CANCELMODE WM_SETCURSOR WM_MOUSEACTIVATE WM_CHILDACTIVATE WM_QUEUESYNC WM_GETMINMAXINFO WM_PAINTICON WM_ICONERASEBKGND WM_NEXTDLGCTL WM_SPOOLERSTATUS WM_DRAWITEM WM_MEASUREITEM WM_DELETEITEM WM_VKEYTOITEM WM_CHARTOITEM WM_SETFONT WM_GETFONT WM_SETHOTKEY WM_GETHOTKEY WM_QUERYDRAGICON WM_COMPAREITEM WM_GETOBJECT WM_COMPACTING WM_WINDOWPOSCHANGING WM_WINDOWPOSCHANGED WM_COPYDATA WM_CANCELJOURNAL WM_NOTIFY WM_INPUTLANGCHANGEREQUEST WM_INPUTLANGCHANGE WM_TCARD WM_HELP WM_USERCHANGED WM_NOTIFYFORMAT WM_CONTEXTMENU WM_STYLECHANGING WM_STYLECHANGED WM_DISPLAYCHANGE WM_GETICON WM_SETICON WM_NCCREATE WM_NCDESTROY WM_NCCALCSIZE WM_NCHITTEST WM_NCPAINT WM_NCACTIVATE WM_GETDLGCODE WM_SYNCPAINT WM_NCMOUSEMOVE WM_NCLBUTTONDOWN WM_NCLBUTTONUP WM_NCLBUTTONDBLCLK WM_NCRBUTTONDOWN WM_NCRBUTTONUP WM_NCRBUTTONDBLCLK WM_NCMBUTTONDOWN WM_NCMBUTTONUP WM_NCMBUTTONDBLCLK WM_KEYFIRST WM_KEYDOWN WM_KEYUP WM_CHAR WM_DEADCHAR WM_SYSKEYDOWN WM_SYSKEYUP
0x001D 0x001E 0x001F 0x0020 0x0021 0x0022 0x0023 0x0024 0x0026 0x0027 0x0028 0x002A 0x002B 0x002C 0x002D 0x002E 0x002F 0x0030 0x0031 0x0032 0x0033 0x0037 0x0039 0x003D 0x0041 0x0046 0x0047 0x004A 0x004B 0x004E 0x0050 0x0051 0x0052 0x0053 0x0054 0x0055 0x007B 0x007C 0x007D 0x007E 0x007F 0x0080 0x0081 0x0082 0x0083 0x0084 0x0085 0x0086 0x0087 0x0088 0x00A0 0x00A1 0x00A2 0x00A3 0x00A4 0x00A5 0x00A6 0x00A7 0x00A8 0x00A9 0x0100 0x0100 0x0101 0x0102 0x0103 0x0104 0x0105
#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define
WM_SYSCHAR WM_SYSDEADCHAR WM_KEYLAST WM_INITDIALOG WM_COMMAND WM_SYSCOMMAND WM_TIMER WM_HSCROLL WM_VSCROLL WM_INITMENU WM_INITMENUPOPUP WM_MENUSELECT WM_MENUCHAR WM_ENTERIDLE WM_MENURBUTTONUP WM_MENUDRAG WM_MENUGETOBJECT WM_UNINITMENUPOPUP WM_MENUCOMMAND WM_CTLCOLORMSGBOX WM_CTLCOLOREDIT WM_CTLCOLORLISTBOX WM_CTLCOLORBTN WM_CTLCOLORDLG WM_CTLCOLORSCROLLBAR WM_CTLCOLORSTATIC WM_MOUSEFIRST WM_MOUSEMOVE WM_LBUTTONDOWN WM_LBUTTONUP WM_LBUTTONDBLCLK WM_RBUTTONDOWN WM_RBUTTONUP WM_RBUTTONDBLCLK WM_MBUTTONDOWN WM_MBUTTONUP WM_MBUTTONDBLCLK WM_PARENTNOTIFY WM_ENTERMENULOOP WM_EXITMENULOOP WM_NEXTMENU WM_SIZING WM_CAPTURECHANGED WM_MOVING WM_DEVICECHANGE WM_MDICREATE WM_MDIDESTROY WM_MDIACTIVATE WM_MDIRESTORE WM_MDINEXT WM_MDIMAXIMIZE WM_MDITILE WM_MDICASCADE WM_MDIICONARRANGE WM_MDIGETACTIVE WM_MDISETMENU WM_ENTERSIZEMOVE WM_EXITSIZEMOVE WM_DROPFILES WM_MDIREFRESHMENU WM_MOUSEHOVER WM_MOUSELEAVE WM_CUT WM_COPY WM_PASTE WM_CLEAR WM_UNDO
0x0106 0x0107 0x0108 0x0110 0x0111 0x0112 0x0113 0x0114 0x0115 0x0116 0x0117 0x011F 0x0120 0x0121 0x0122 0x0123 0x0124 0x0125 0x0126 0x0132 0x0133 0x0134 0x0135 0x0136 0x0137 0x0138 0x0200 0x0200 0x0201 0x0202 0x0203 0x0204 0x0205 0x0206 0x0207 0x0208 0x0209 0x0210 0x0211 0x0212 0x0213 0x0214 0x0215 0x0216 0x0219 0x0220 0x0221 0x0222 0x0223 0x0224 0x0225 0x0226 0x0227 0x0228 0x0229 0x0230 0x0231 0x0232 0x0233 0x0234 0x02A1 0x02A3 0x0300 0x0301 0x0302 0x0303 0x0304
#define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define #define
WM_RENDERFORMAT WM_RENDERALLFORMATS WM_DESTROYCLIPBOARD WM_DRAWCLIPBOARD WM_PAINTCLIPBOARD WM_VSCROLLCLIPBOARD WM_SIZECLIPBOARD WM_ASKCBFORMATNAME WM_CHANGECBCHAIN WM_HSCROLLCLIPBOARD WM_QUERYNEWPALETTE WM_PALETTEISCHANGING WM_PALETTECHANGED WM_HOTKEY WM_PRINT WM_PRINTCLIENT WM_HANDHELDFIRST WM_HANDHELDLAST WM_AFXFIRST WM_AFXLAST WM_PENWINFIRST WM_PENWINLAST WM_APP
0x0305 0x0306 0x0307 0x0308 0x0309 0x030A 0x030B 0x030C 0x030D 0x030E 0x030F 0x0310 0x0311 0x0312 0x0317 0x0318 0x0358 0x035F 0x0360 0x037F 0x0380 0x038F 0x8000
//---- keybd_event routines #define KEYEVENTF_EXTENDEDKEY #define KEYEVENTF_KEYUP //---- mouse_event routines #define MOUSEEVENTF_MOVE #define MOUSEEVENTF_LEFTDOWN #define MOUSEEVENTF_LEFTUP #define MOUSEEVENTF_RIGHTDOWN #define MOUSEEVENTF_RIGHTUP #define MOUSEEVENTF_MIDDLEDOWN #define MOUSEEVENTF_MIDDLEUP #define MOUSEEVENTF_WHEEL #define MOUSEEVENTF_ABSOLUTE
0x0001 0x0002 0x0004 0x0008 0x0010 0x0020 0x0040 0x0800 0x8000
//---- GetSystemMetrics() codes #define SM_CXSCREEN #define SM_CYSCREEN #define SM_CXVSCROLL #define SM_CYHSCROLL #define SM_CYCAPTION #define SM_CXBORDER #define SM_CYBORDER #define SM_CXDLGFRAME #define SM_CYDLGFRAME #define SM_CYVTHUMB #define SM_CXHTHUMB #define SM_CXICON #define SM_CYICON #define SM_CXCURSOR #define SM_CYCURSOR #define SM_CYMENU #define SM_CXFULLSCREEN #define SM_CYFULLSCREEN #define SM_CYKANJIWINDOW #define SM_MOUSEPRESENT #define SM_CYVSCROLL #define SM_CXHSCROLL #define SM_DEBUG #define SM_SWAPBUTTON #define SM_RESERVED1 #define SM_RESERVED2 #define SM_RESERVED3 #define SM_RESERVED4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
0x0001 0x0002 // // // // // // // // //
mouse move left button down left button up right button down right button up middle button down middle button up wheel button rolled absolute move
#define SM_CXMIN #define SM_CYMIN #define SM_CXSIZE #define SM_CYSIZE #define SM_CXFRAME #define SM_CYFRAME #define SM_CXMINTRACK #define SM_CYMINTRACK #define SM_CXDOUBLECLK #define SM_CYDOUBLECLK #define SM_CXICONSPACING #define SM_CYICONSPACING #define SM_MENUDROPALIGNMENT #define SM_PENWINDOWS #define SM_DBCSENABLED #define SM_CMOUSEBUTTONS #define SM_SECURE #define SM_CXEDGE #define SM_CYEDGE #define SM_CXMINSPACING #define SM_CYMINSPACING #define SM_CXSMICON #define SM_CYSMICON #define SM_CYSMCAPTION #define SM_CXSMSIZE #define SM_CYSMSIZE #define SM_CXMENUSIZE #define SM_CYMENUSIZE #define SM_ARRANGE #define SM_CXMINIMIZED #define SM_CYMINIMIZED #define SM_CXMAXTRACK #define SM_CYMAXTRACK #define SM_CXMAXIMIZED #define SM_CYMAXIMIZED #define SM_NETWORK #define SM_CLEANBOOT #define SM_CXDRAG #define SM_CYDRAG #define SM_SHOWSOUNDS #define SM_CXMENUCHECK GetMenuCheckMarkDimensions()! #define SM_CYMENUCHECK #define SM_SLOWMACHINE #define SM_MIDEASTENABLED #define SM_MOUSEWHEELPRESENT #define SM_XVIRTUALSCREEN #define SM_YVIRTUALSCREEN #define SM_CXVIRTUALSCREEN #define SM_CYVIRTUALSCREEN #define SM_CMONITORS #define SM_SAMEDISPLAYFORMAT
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 67 68 69 70 71 // Use instead of 72 73 74 75 76 77 78 79 80 81
//---- GetWindow() Constants #define GW_HWNDFIRST #define GW_HWNDLAST #define GW_HWNDNEXT #define GW_HWNDPREV #define GW_OWNER #define GW_CHILD
0 1 2 3 4 5
//---- AnimateWindow() Commands #define AW_HOR_POSITIVE #define AW_HOR_NEGATIVE #define AW_VER_POSITIVE #define AW_VER_NEGATIVE #define AW_CENTER
0x00000001 0x00000002 0x00000004 0x00000008 0x00000010
#define #define #define #define
AW_HIDE AW_ACTIVATE AW_SLIDE AW_BLEND
0x00010000 0x00020000 0x00040000 0x00080000
//---- MessageBox() Flags #define MB_OK #define MB_OKCANCEL #define MB_ABORTRETRYIGNORE #define MB_YESNOCANCEL #define MB_YESNO #define MB_RETRYCANCEL #define MB_ICONHAND #define MB_ICONQUESTION #define MB_ICONEXCLAMATION #define MB_ICONASTERISK #define MB_USERICON #define MB_ICONWARNING #define MB_ICONERROR #define MB_ICONINFORMATION #define MB_ICONSTOP #define MB_DEFBUTTON1 #define MB_DEFBUTTON2 #define MB_DEFBUTTON3 #define MB_DEFBUTTON4 #define MB_APPLMODAL #define MB_SYSTEMMODAL #define MB_TASKMODAL #define MB_HELP #define MB_NOFOCUS #define MB_SETFOREGROUND #define MB_DEFAULT_DESKTOP_ONLY #define MB_TOPMOST #define MB_RIGHT #define MB_RTLREADING //---- Dialog Box Command IDs #define IDOK #define IDCANCEL #define IDABORT #define IDRETRY #define IDIGNORE #define IDYES #define IDNO #define IDCLOSE #define IDHELP
0x00000000 0x00000001 0x00000002 0x00000003 0x00000004 0x00000005 0x00000010 0x00000020 0x00000030 0x00000040 0x00000080 MB_ICONEXCLAMATION MB_ICONHAND MB_ICONASTERISK MB_ICONHAND 0x00000000 0x00000100 0x00000200 0x00000300 0x00000000 0x00001000 0x00002000 0x00004000 // Help Button 0x00008000 0x00010000 0x00020000 0x00040000 0x00080000 0x00100000 1 2 3 4 5 6 7 8 9
//+------------------------------------------------------------------+
Scripts //+------------------------------------------------------------------+ //| Period_Converter.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net" #property show_inputs #include extern int ExtPeriodMultiplier=3; // new period multiplier factor int ExtHandle=-1; //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+
int start() { int i, start_pos, i_time, time0, last_fpos, periodseconds; double d_open, d_low, d_high, d_close, d_volume, last_volume; int hwnd=0,cnt=0; //---- History header int version=400; string c_copyright; string c_symbol=Symbol(); int i_period=Period()*ExtPeriodMultiplier; int i_digits=Digits; int i_unused[13]; //---ExtHandle=FileOpenHistory(c_symbol+i_period+".hst", FILE_BIN|FILE_WRITE); if(ExtHandle < 0) return(-1); //---- write history file header c_copyright="(C)opyright 2003, MetaQuotes Software Corp."; FileWriteInteger(ExtHandle, version, LONG_VALUE); FileWriteString(ExtHandle, c_copyright, 64); FileWriteString(ExtHandle, c_symbol, 12); FileWriteInteger(ExtHandle, i_period, LONG_VALUE); FileWriteInteger(ExtHandle, i_digits, LONG_VALUE); FileWriteInteger(ExtHandle, 0, LONG_VALUE); //timesign FileWriteInteger(ExtHandle, 0, LONG_VALUE); //last_sync FileWriteArray(ExtHandle, i_unused, 0, 13); //---- write history file periodseconds=i_period*60; start_pos=Bars-1; d_open=Open[start_pos]; d_low=Low[start_pos]; d_high=High[start_pos]; d_volume=Volume[start_pos]; //---- normalize open time i_time=Time[start_pos]/periodseconds; i_time*=periodseconds; for(i=start_pos-1;i>=0; i--) { time0=Time[i]; if(time0>=i_time+periodseconds || i==0) { if(i==0 && time0d_high) d_high=High[0]; d_close=Close[0]; } last_fpos=FileTell(ExtHandle); last_volume=Volume[i]; FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); FileFlush(ExtHandle); cnt++; if(time0>=i_time+periodseconds) { i_time=time0/periodseconds; i_time*=periodseconds; d_open=Open[i]; d_low=Low[i]; d_high=High[i]; d_close=Close[i]; d_volume=last_volume; }
} else { d_volume+=Volume[i]; if (Low[i]d_high) d_high=High[i]; d_close=Close[i]; } } FileFlush(ExtHandle); Print(cnt," record(s) written"); //---- collect incoming ticks int last_time=LocalTime()-5; while(true) { int cur_time=LocalTime(); //---- check for new rates if(RefreshRates()) { time0=Time[0]; FileSeek(ExtHandle,last_fpos,SEEK_SET); //---- is there current bar? if(time0d_high) d_high=High[0]; d_close=Close[0]; } else { //---- no, there is new bar d_volume+=Volume[1]-last_volume; if (Low[1]d_high) d_high=High[1]; //---- write previous bar remains FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); last_fpos=FileTell(ExtHandle); //---i_time=time0/periodseconds; i_time*=periodseconds; d_open=Open[0]; d_low=Low[0]; d_high=High[0]; d_close=Close[0]; d_volume=Volume[0]; last_volume=d_volume; } //---FileWriteInteger(ExtHandle, i_time, LONG_VALUE); FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE); FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE); FileFlush(ExtHandle); //---if(hwnd==0) { hwnd=WindowHandle(Symbol(),i_period); if(hwnd!=0) Print("Chart window detected");
} //---- refresh window not frequently than 1 time in 2 seconds if(hwnd!=0 && cur_time-last_time>=2) { PostMessageA(hwnd,WM_COMMAND,33324,0); last_time=cur_time; } } } //---return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { if(ExtHandle>=0) { FileClose(ExtHandle); ExtHandle=-1; } } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| rotate_text.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include string line_name="rotating_line"; string object_name1="rotating_text"; void init() { Print("point = ", Point," bars=",Bars); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name); ObjectDelete(object_name1); ObjectsRedraw(); } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2; int error,index,fontsize=10; double price,price1,price2; double angle=0.0; //---price2=High[10]+Point*10; ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2); index=20; ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100); ObjectSetText(object_name1, "rotating_text", fontsize); while(IsStopped()==false) { index++; price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point; error=GetLastError(); if(error!=0)
//
{ Print(object_name1," : ",ErrorDescription(error)); break; } ObjectMove(object_name1, 0, Time[index], price); ObjectSet(object_name1, OBJPROP_ANGLE, angle*2); ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize); ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0); double line_angle=360.0-angle; if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50); if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50); time2=ObjectGet(line_name,OBJPROP_TIME2); if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10]; else time2=Time[0]; ObjectSet(line_name, OBJPROP_TIME2, time2); ObjectSet(line_name, OBJPROP_ANGLE, line_angle); ObjectsRedraw(); angle+=3.0; if(angle>=360.0) angle=360.0-angle; fontsize++; if(fontsize>48) fontsize=6; Sleep(500); price1=ObjectGetValueByShift(line_name, index); if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=",price," price1=", price1); ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0)); ObjectsRedraw(); Sleep(5000); ObjectDelete(object_name1); } }
} return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include #include //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ", "Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1); //---int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<1) { int error=GetLastError(); Print("Error = ",ErrorDescription(error)); return; } //---OrderPrint();
return(0); } //+------------------------------------------------------------------+
Templates type=INDICATOR_ADVISOR description=Accelerator Oscilator separate_window=1 used_buffers=4 color=Green type=DRAW_HISTOGRAM color=Red type=DRAW_HISTOGRAM #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtGreenBuffer[]; double ExtRedBuffer[]; double ExtMABuffer[]; double ExtBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- indicator buffers mapping SetIndexBuffer(0, ExtGreenBuffer); SetIndexBuffer(1, ExtRedBuffer); SetIndexBuffer(2, ExtMABuffer); SetIndexBuffer(3, ExtBuffer); //---- drawing settings #indicators_init# //---IndicatorDigits(6); SetIndexDrawBegin(0,38); SetIndexDrawBegin(1,38); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AC"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i=0; i--) { current=ExtMABuffer[i]-ExtBuffer[i]; prev=ExtMABuffer[i+1]-ExtBuffer[i+1]; if(current>prev) up=true; if(current type=INDICATOR_ADVISOR description= used_buffers=3 name=JawsPeriod type=int value=13 name=JawsShift type=int value=8 name=TeethPeriod type=int value=8 name=TeethShift type=int value=5 name=LipsPeriod type=int value=5 name=LipsShift type=int value=3
color=Blue color=Red color=Lime #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtBlueBuffer[]; double ExtRedBuffer[]; double ExtLimeBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- 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 #indicators_init# //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit; 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--; limit=Bars-counted_bars; //---- main loop for(int i=0; i
//+------------------------------------------------------------------+ type=INDICATOR_ADVISOR description=Awesome Oscilator separate_window=1 used_buffers=3; color=Green type=DRAW_HISTOGRAM color=Red type=DRAW_HISTOGRAM #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtGreenBuffer[]; double ExtRedBuffer[]; double ExtMABuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- drawing settings #indicators_init# IndicatorDigits(5); SetIndexDrawBegin(0,34); SetIndexDrawBegin(1,34); //---- indicator buffers mapping SetIndexBuffer(0, ExtGreenBuffer); SetIndexBuffer(1, ExtRedBuffer); SetIndexBuffer(2, ExtMABuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AO"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- check for possible errors if(counted_bars<0) return(-1); //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i=0; i--)
{ current=ExtMABuffer[i]; prev=ExtMABuffer[i+1]; if(current>prev) up=true; if(current type=EXPERT_ADVISOR #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| expert initialization function | //+------------------------------------------------------------------+ int init() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0); } //+------------------------------------------------------------------+ //| expert start function | //+------------------------------------------------------------------+ int start() { //---//---return(0); } //+------------------------------------------------------------------+ type=INDICATOR_ADVISOR #header# #property copyright "#copyright#" #property link "#link#"
#indicator_properties# #extern_variables# #mapping_buffers# //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used# //---- indicators #indicators_init# //---return(0); } //+------------------------------------------------------------------+ //| Custor indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---//---return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { int counted_bars=IndicatorCounted(); //---//---return(0); } //+------------------------------------------------------------------+ type=INDICATOR_ADVISOR separate_window=1 used_buffers=2 type=int name=FastEMA value=12 type=int name=SlowEMA value=26 type=int name=SignalSMA value=9 color=Silver type=DRAW_HISTOGRAM color=Red #header# #property copyright "#copyright#"
#property link
"#link#"
#indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtSilverBuffer[]; double ExtRedBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- drawing settings #indicators_init# //---SetIndexDrawBegin(1,SignalSMA); IndicatorDigits(5); //---- indicator buffers mapping SetIndexBuffer(0, ExtSilverBuffer); SetIndexBuffer(1, ExtRedBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit; 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--; limit=Bars-counted_bars; //---- macd counted in the 1-st buffer for(int i=0; i type=INDICATOR_ADVISOR separate_window=1 used_buffers=3 name=FastEMA type=int value=12 name=SlowEMA type=int value=26
name=SignalSMA type=int value=9 type=DRAW_HISTOGRAM color=Silver #header# #property copyright "#copyright#" #property link "#link#" #indicator_properties# #extern_variables# #mapping_buffers# //---- indicator buffers double ExtSilverBuffer[]; double ExtMABuffer[]; double ExtBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { #buffers_used#; //---- drawing settings #indicators_init# //---SetIndexDrawBegin(0,SignalSMA); IndicatorDigits(6); //---- indicator buffers mapping SetIndexBuffer(0,ExtSilverBuffer); SetIndexBuffer(1,ExtMABuffer); SetIndexBuffer(2,ExtBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Average of Oscillator | //+------------------------------------------------------------------+ int start() { int limit; 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--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i
type=SCRIPT_ADVISOR #header# #property copyright "#copyright#" #property link "#link#" #extern_variables# //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { //---//---return(0); } //+------------------------------------------------------------------+
Library //+------------------------------------------------------------------+ //| stdlib.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property library /* int init() { Print("Init function defined as feature sample"); } int deinit() { Print("Deinit function defined as feature sample too"); } */ //+------------------------------------------------------------------+ //| return error description | //+------------------------------------------------------------------+ string ErrorDescription(int error_code) { string error_string; //---switch(error_code) { //---- codes returned from trade server case 0: case 1: error_string="no error"; break; case 2: error_string="common error"; break; case 3: error_string="invalid trade parameters"; break; case 4: error_string="trade server is busy"; break; case 5: error_string="old version of the client terminal"; break; case 6: error_string="no connection with trade server"; break; case 7: error_string="not enough rights"; break; case 8: error_string="too frequent requests";
break; case 9:
error_string="malfunctional trade operation";
case 64:
error_string="account disabled";
case 65:
error_string="invalid account";
break; break; break; case 128: error_string="trade timeout"; break; case 129: error_string="invalid price"; break; case 130: error_string="invalid stops"; break; case 131: error_string="invalid trade volume"; break; case 132: error_string="market is closed"; break; case 133: error_string="trade is disabled"; break; case 134: error_string="not enough money"; break; case 135: error_string="price changed"; break; case 136: error_string="off quotes"; break; case 137: error_string="broker is busy"; break; case 138: error_string="requote"; break; case 139: error_string="order is locked"; break; case 140: error_string="long positions only allowed"; break; case 141: error_string="too many requests"; break; case 145: error_string="modification denied because order too close to market"; break; case 146: error_string="trade context is busy"; break; //---- mql4 errors case 4000: error_string="no error"; break; case 4001: error_string="wrong function pointer"; break; case 4002: error_string="array index is out of range"; break; case 4003: error_string="no memory for function call stack"; break; case 4004: error_string="recursive stack overflow"; break; case 4005: error_string="not enough stack for parameter"; break; case 4006: error_string="no memory for parameter string"; break; case 4007: error_string="no memory for temp string"; break; case 4008: error_string="not initialized string"; break; case 4009: error_string="not initialized string in array"; break; case 4010: error_string="no memory for array\' string"; break; case 4011: error_string="too long string"; break; case 4012: error_string="remainder from zero divide"; break; case 4013: error_string="zero divide";
break; case 4014: error_string="unknown command"; break; case 4015: error_string="wrong jump (never generated error)"; break; case 4016: error_string="not initialized array"; break; case 4017: error_string="dll calls are not allowed"; break; case 4018: error_string="cannot load library"; break; case 4019: error_string="cannot call function"; break; case 4020: error_string="expert function calls are not allowed"; break; case function"; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break; case break;
4021: error_string="not enough memory for temp string returned from break; 4022: error_string="system is busy (never generated error)"; 4050: error_string="invalid function parameters count"; 4051: error_string="invalid function parameter value"; 4052: error_string="string function internal error"; 4053: error_string="some array error"; 4054: error_string="incorrect series array using"; 4055: error_string="custom indicator error"; 4056: error_string="arrays are incompatible"; 4057: error_string="global variables processing error"; 4058: error_string="global variable not found"; 4059: error_string="function is not allowed in testing mode"; 4060: error_string="function is not confirmed"; 4061: error_string="send mail error"; 4062: error_string="string parameter expected"; 4063: error_string="integer parameter expected"; 4064: error_string="double parameter expected"; 4065: error_string="array as parameter expected"; 4066: error_string="requested history data in update state"; 4099: error_string="end of file"; 4100: error_string="some file error"; 4101: error_string="wrong file name"; 4102: error_string="too many opened files"; 4103: error_string="cannot open file"; 4104: error_string="incompatible access to a file"; 4105: error_string="no order selected";
case 4106: error_string="unknown symbol"; break; case 4107: error_string="invalid price parameter for trade function"; break; case 4108: error_string="invalid ticket"; break; case 4109: error_string="trade is not allowed"; break; case 4110: error_string="longs are not allowed"; break; case 4111: error_string="shorts are not allowed"; break; case 4200: error_string="object is already exist"; break; case 4201: error_string="unknown object property"; break; case 4202: error_string="object is not exist"; break; case 4203: error_string="unknown object type"; break; case 4204: error_string="no object name"; break; case 4205: error_string="object coordinates error"; break; case 4206: error_string="no specified subwindow"; break; default:
error_string="unknown error";
} //---return(error_string); } //+------------------------------------------------------------------+ //| convert red, green and blue values to color | //+------------------------------------------------------------------+ int RGB(int red_value,int green_value,int blue_value) { //---- check parameters if(red_value<0) red_value=0; if(red_value>255) red_value=255; if(green_value<0) green_value=0; if(green_value>255) green_value=255; if(blue_value<0) blue_value=0; if(blue_value>255) blue_value=255; //---green_value<<=8; blue_value<<=16; return(red_value+green_value+blue_value); } //+------------------------------------------------------------------+ //| right comparison of 2 doubles | //+------------------------------------------------------------------+ bool CompareDoubles(double number1,double number2) { if(NormalizeDouble(number1-number2,8)==0) return(true); else return(false); } //+------------------------------------------------------------------+ //| up to 16 digits after decimal point | //+------------------------------------------------------------------+ string DoubleToStrMorePrecision(double number,int precision) { double rem,integer,integer2; double DecimalArray[17]={ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 1000000000000000.0,
10000000000000000.0 }; string intstring,remstring,retstring; bool isnegative=false; int rem2; //---if(precision<0) precision=0; if(precision>16) precision=16; //---double p=DecimalArray[precision]; if(number<0.0) { isnegative=true; number=-number; } integer=MathFloor(number); rem=MathRound((number-integer)*p); remstring=""; for(int i=0; i0) retstring=retstring+"."+remstring; return(retstring); } //+------------------------------------------------------------------+ //| convert integer to string contained input's hexadecimal notation | //+------------------------------------------------------------------+ string IntegerToHexString(int integer_number) { string hex_string="00000000"; int value, shift=28; // Print("Parameter for IntegerHexToString is ",integer_number); //---for(int i=0; i<8; i++) { value=(integer_number>>shift)&0x0F; if(value<10) hex_string=StringSetChar(hex_string, i, value+'0'); else hex_string=StringSetChar(hex_string, i, (value-10)+'A'); shift-=4; } //---return(hex_string); }
Indicators //+------------------------------------------------------------------+ //| CCI.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 LightSeaGreen //---- input parameters extern int CCIPeriod=14; //---- buffers double CCIBuffer[]; double RelBuffer[]; double DevBuffer[];
double MovBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 3 additional buffers are used for counting. IndicatorBuffers(4); SetIndexBuffer(1, RelBuffer); SetIndexBuffer(2, DevBuffer); SetIndexBuffer(3, MovBuffer); //---- indicator lines SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,CCIBuffer); //---- name for DataWindow and indicator subwindow label short_name="CCI("+CCIPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---SetIndexDrawBegin(0,CCIPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Commodity Channel Index | //+------------------------------------------------------------------+ int start() { int i,k,counted_bars=IndicatorCounted(); double price,sum,mul; if(Bars<=CCIPeriod) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=CCIPeriod;i++) CCIBuffer[Bars-i]=0.0; for(i=1;i<=CCIPeriod;i++) DevBuffer[Bars-i]=0.0; for(i=1;i<=CCIPeriod;i++) MovBuffer[Bars-i]=0.0; } //---- last counted bar will be recounted int limit=Bars-counted_bars; if(counted_bars>0) limit++; //---- moving average for(i=0; iCCIPeriod-1) i=Bars-counted_bars-1; mul=0.015/CCIPeriod; while(i>=0) { sum=0.0; k=i+CCIPeriod-1; while(k>=i) { price=(High[k]+Low[k]+Close[k])/3; sum+=MathAbs(price-MovBuffer[i]); k--; } DevBuffer[i]=sum*mul; i--; } i=Bars-CCIPeriod+1; if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1; while(i>=0) { price=(High[i]+Low[i]+Close[i])/3;
RelBuffer[i]=price-MovBuffer[i]; i--; } //---- cci counting i=Bars-CCIPeriod+1; if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1; while(i>=0) { if(DevBuffer[i]==0.0) CCIBuffer[i]=0.0; else CCIBuffer[i]=RelBuffer[i]/DevBuffer[i]; i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Ichimoku.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 7 #property indicator_color1 Red #property indicator_color2 Blue #property indicator_color3 SandyBrown #property indicator_color4 Thistle #property indicator_color5 Lime #property indicator_color6 SandyBrown #property indicator_color7 Thistle //---- input parameters extern int Tenkan=9; extern int Kijun=26; extern int Senkou=52; //---- buffers double Tenkan_Buffer[]; double Kijun_Buffer[]; double SpanA_Buffer[]; double SpanB_Buffer[]; double Chinkou_Buffer[]; double SpanA2_Buffer[]; double SpanB2_Buffer[]; //---int a_begin; //+------------------------------------------------------------------+ //| Custom indicator 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
SetIndexDrawBegin(2,Kijun+a_begin-1); SetIndexShift(2,Kijun); 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); 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); } //+------------------------------------------------------------------+ //| Ichimoku Kinko Hyo | //+------------------------------------------------------------------+ int start() { int i,k; int counted_bars=IndicatorCounted(); double high,low,price; //---if(Bars<=Tenkan || Bars<=Kijun || Bars<=Senkou) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=Tenkan;i++) Tenkan_Buffer[Bars-i]=0; for(i=1;i<=Kijun;i++) Kijun_Buffer[Bars-i]=0; for(i=1;i<=a_begin;i++) { SpanA_Buffer[Bars-i]=0; SpanA2_Buffer[Bars-i]=0; } for(i=1;i<=Senkou;i++) { SpanB_Buffer[Bars-i]=0; SpanB2_Buffer[Bars-i]=0; } } //---- Tenkan Sen i=Bars-Tenkan; if(counted_bars>Tenkan) i=Bars-counted_bars-1; while(i>=0) { high=High[i]; low=Low[i]; k=i-1+Tenkan; while(k>=i) { price=High[k]; if(highprice) low=price; k--; } Tenkan_Buffer[i]=(high+low)/2; i--; } //---- Kijun Sen i=Bars-Kijun; if(counted_bars>Kijun) i=Bars-counted_bars-1; while(i>=0) {
high=High[i]; low=Low[i]; k=i-1+Kijun; while(k>=i) { price=High[k]; if(highprice) low=price; k--; } Kijun_Buffer[i]=(high+low)/2; i--; } //---- Senkou Span A i=Bars-a_begin+1; if(counted_bars>a_begin-1) i=Bars-counted_bars-1; while(i>=0) { price=(Kijun_Buffer[i]+Tenkan_Buffer[i])/2; SpanA_Buffer[i]=price; SpanA2_Buffer[i]=price; i--; } //---- Senkou Span B i=Bars-Senkou; if(counted_bars>Senkou) i=Bars-counted_bars-1; while(i>=0) { high=High[i]; low=Low[i]; k=i-1+Senkou; while(k>=i) { price=High[k]; if(highprice) low=price; k--; } price=(high+low)/2; SpanB_Buffer[i]=price; SpanB2_Buffer[i]=price; i--; } //---- Chinkou Span i=Bars-1; if(counted_bars>1) i=Bars-counted_bars-1; while(i>=0) { Chinkou_Buffer[i]=Close[i]; i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom MACD.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 2 #property indicator_color1 Silver #property indicator_color2 Red //---- indicator parameters extern int FastEMA=12; extern int SlowEMA=26; extern int SignalSMA=9; //---- indicator buffers
double double
ind_buffer1[]; ind_buffer2[];
//+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- drawing settings SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3); SetIndexDrawBegin(1,SignalSMA); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+1); //---- indicator buffers mapping if(!SetIndexBuffer(0,ind_buffer1) && !SetIndexBuffer(1,ind_buffer2)) Print("cannot set indicator buffers!"); //---- name for DataWindow and indicator subwindow label IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")"); SetIndexLabel(0,"MACD"); SetIndexLabel(1,"Signal"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Moving Averages Convergence/Divergence | //+------------------------------------------------------------------+ int start() { int limit; 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--; limit=Bars-counted_bars; //---- macd counted in the 1-st buffer for(int i=0; i
SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,MomBuffer); //---- name for DataWindow and indicator subwindow label short_name="Mom("+MomPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---SetIndexDrawBegin(0,MomPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Momentum | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---if(Bars<=MomPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=MomPeriod;i++) MomBuffer[Bars-i]=0.0; //---i=Bars-MomPeriod-1; if(counted_bars>=MomPeriod) i=Bars-counted_bars-1; while(i>=0) { MomBuffer[i]=Close[i]*100/Close[i+MomPeriod]; i--; } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Custom Moving Average.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 1 #property indicator_color1 Red //---- indicator parameters extern int MA_Period=13; extern int MA_Shift=0; extern int MA_Method=0; //---- indicator buffers double ExtMapBuffer[]; //---int ExtCountedBars=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { int draw_begin; string short_name; //---- drawing settings SetIndexStyle(0,DRAW_LINE); SetIndexShift(0,MA_Shift); IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)); if(MA_Period<2) MA_Period=13; draw_begin=MA_Period-1; //---- indicator short name
switch(MA_Method) { case 1 : short_name="EMA("; draw_begin=0; break; case 2 : short_name="SMMA("; break; case 3 : short_name="LWMA("; break; default : MA_Method=0; short_name="SMA("; } IndicatorShortName(short_name+MA_Period+")"); SetIndexDrawBegin(0,draw_begin); //---- indicator buffers mapping SetIndexBuffer(0,ExtMapBuffer); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { if(Bars<=MA_Period) return(0); ExtCountedBars=IndicatorCounted(); //---- check for possible errors if (ExtCountedBars<0) return(-1); //---- last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--; //---switch(MA_Method) { case 0 : sma(); break; case 1 : ema(); break; case 2 : smma(); break; case 3 : lwma(); } //---- done return(0); } //+------------------------------------------------------------------+ //| Simple Moving Average | //+------------------------------------------------------------------+ void sma() { double sum=0; int i,pos=Bars-ExtCountedBars-1; //---- initial accumulation if(pos=0) { sum+=Close[pos]; ExtMapBuffer[pos]=sum/MA_Period; sum-=Close[pos+MA_Period-1]; pos--; } //---- zero initial bars if(ExtCountedBars<1) for(i=1;i
int pos=Bars-2; if(ExtCountedBars>2) pos=Bars-ExtCountedBars-1; //---- main calculation loop while(pos>=0) { if(pos==Bars-2) ExtMapBuffer[pos+1]=Close[pos+1]; ExtMapBuffer[pos]=Close[pos]*pr+ExtMapBuffer[pos+1]*(1-pr); pos--; } } //+------------------------------------------------------------------+ //| Smoothed Moving Average | //+------------------------------------------------------------------+ void smma() { double sum=0; int i,k,pos=Bars-ExtCountedBars+1; //---- main calculation loop pos=Bars-MA_Period; if(pos>Bars-ExtCountedBars) pos=Bars-ExtCountedBars; while(pos>=0) { if(pos==Bars-MA_Period) { //---- initial accumulation for(i=0,k=pos;i=0) { ExtMapBuffer[pos]=sum/weight; if(pos==0) break; pos--; i--; price=Close[pos]; sum=sum-lsum+price*MA_Period; lsum-=Close[i]; lsum+=price;
} //---- zero initial bars if(ExtCountedBars<1) for(i=1;i0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i
//---- main loop for(i=0; i
double ep,sar,price_low,price_high,price; int i,counted_bars=IndicatorCounted(); //---if(Bars<3) return(0); //---- initial settings i=Bars-2; if(counted_bars==0 || first) { first=false; dirlong=true; start=Step; last_high=-10000000.0; last_low=10000000.0; while(i>0) { save_lastreverse=i; price_low=Low[i]; if(last_low>price_low) last_low=price_low; price_high=High[i]; if(last_highHigh[i+1] && price_low>Low[i+1]) break; if(price_high=0) { price_low=Low[i]; price_high=High[i]; //--- check for reverse if(dirlong && price_lowSarBuffer[i+1]) { SaveLastReverse(i,false,start,last_low,price_high,ep,sar); start=Step; dirlong=true; ep=price_high; ep=price_high; last_high=price_high; last_high=price_high; SarBuffer[i]=last_low;
i--; continue; } //--price=SarBuffer[i+1]; sar=price+start*(ep-price); if(dirlong) { if(epprice) sar=price; price=Low[i+2]; if(sar>price) sar=price; if(sar>price_low) { SaveLastReverse(i,true,start,price_low,last_high,ep,sar); start=Step; dirlong=false; ep=price_low; last_low=price_low; SarBuffer[i]=last_high; i--; continue; } if(epprice_low if(ep>price_low && (start+Step)<=Maximum) (start+Step)<=Maximum) start+=Step; if(price_lowprice_low) { last_low=price_low; ep=price_low; } } SarBuffer[i]=sar; i--; } // sar=SarBuffer[0]; // price=iSAR(NULL,0,Step,Maximum,0); // if(sar!=price) if(sar!=pri ce) Print("custom=",sar," Print("cust om=",sar," SAR=",price," SAR=",price, " counted=",counted_bars); counted=",cou nted_bars); // if(sar==price) if(sar==pri ce) Print("custom=",sar," Print("cust om=",sar," SAR=",price," SAR=",price, " counted=",counted_bars); counted=",cou nted_bars); //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| RSI.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net http://www.m etaquotes.net/ / | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.n "http://www .metaquotes.net/" et/" #property indicator_separate_window
#property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int RSIPeriod=14; RSIPeriod=14; //---- buffers double RSIBuffer[]; double PosBuffer[]; double NegBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization initializati on function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(3); SetIndexBuffer(1,PosBuffer); SetIndexBuffer(2,NegBuffer); //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,RSIBuffer); //---- name for DataWindow and indicator subwindow label short_name="RSI("+RSIPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---SetIndexDrawBegin(0,RSIPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Relative Strength Index | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); double rel,negative,positive; //---if(Bars<=RSIPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=RSIPeriod;i++) RSIBuffer[Bars-i]=0.0; //---i=Bars-RSIPeriod-1; if(counted_bars>=RSIPeriod) i=Bars-counted_bars-1; while(i>=0) { double sumn=0.0,sump=0.0; if(i==Bars-RSIPeriod-1) { int k=Bars-2; //---- initial accumulation while(k>=i) { rel=Close[k]-Close[k+1]; if(rel>0) sump+=rel; else sumn-=rel; k--; } positive=sump/RSIPeriod; negative=sumn/RSIPeriod; } else { //---- smoothed moving average
rel=Close[i]-Close[i+1]; if(rel>0) sump=rel; else sumn=-rel; positive=(PosBuffer[i+1]*(RSIPeriod-1)+sump)/RSIPeriod; negative=(NegBuffer[i+1]*(RSIPeriod-1)+sumn)/RSIPeriod; } PosBuffer[i]=positive; NegBuffer[i]=negative; if(negative==0.0) RSIBuffer[i]=0.0; else RSIBuffer[i]=100.0-100.0/(1+positive/negative); i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Stochastic.mq4 Stochastic.mq 4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net http://www.m etaquotes.net/ / | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.n "http://www .metaquotes.net/" et/" #property indicator_separate_window #property indicator_minimum 0 #property indicator_maximum 100 #property indicator_buffers 2 #property indicator_color1 LightSeaGreen #property indicator_color2 Red //---- input parameters extern int KPeriod=5; extern int DPeriod=3; extern int Slowing=3; //---- buffers double MainBuffer[]; MainBuffer[]; double SignalBuffer[]; SignalBuffer[]; double HighesBuffer[]; HighesBuffer[]; double LowesBuffer[]; //---int draw_begin1=0; int draw_begin2=0; //+------------------------------------------------------------------+ //| Custom indicator initialization initializati on function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 2 additional buffers are used for counting. IndicatorBuffers(4); SetIndexBuffer(2, HighesBuffer); SetIndexBuffer(3, LowesBuffer); //---- indicator lines SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0, MainBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1, SignalBuffer); //---- name for DataWindow and indicator subwindow label short_name="Sto("+KPeriod+","+DPeriod+","+Slowing+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); SetIndexLabel(1,"Signal"); //---draw_begin1=KPeriod+Slowing; draw_begin2=draw_begin1+DPeriod; SetIndexDrawBegin(0,dra SetIndexDrawBegin(0,draw_begin1); w_begin1);
SetIndexDrawBegin(1,dra SetIndexDrawBegin(1,draw_begin2); w_begin2); //---return(0); } //+------------------------------------------------------------------+ //| Stochastic oscillator | //+------------------------------------------------------------------+ int start() { int i,k; int counted_bars=IndicatorCounted(); double price; //---if(Bars<=draw_begin2) return(0); //---- initial zero if(counted_bars<1) { for(i=1;i<=draw_begin1;i++) MainBuffer[Bars-i]=0; for(i=1;i<=draw_begin2;i++) SignalBuffer[Bars-i]=0; } //---- minimums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double min=1000000; k=i+KPeriod-1; while(k>=i) { price=Low[k]; if(min>price) min=price; k--; } LowesBuffer[i]=min; i--; } //---- maximums counting i=Bars-KPeriod; if(counted_bars>KPeriod) i=Bars-counted_bars-1; while(i>=0) { double max=-1000000; max=-1000000; k=i+KPeriod-1; while(k>=i) { price=High[k]; if(maxdraw_begin1) i=Bars-counted_bars-1; while(i>=0) { double sumlow=0.0; double sumhigh=0.0; for(k=(i+Slowing-1);k>=i;k--) { sumlow+=Close[k]-LowesBuffer[k]; sumhigh+=HighesBuffer[k]-LowesBuffer[k]; } if(sumhigh==0.0) MainBuffer[i]=100.0; else MainBuffer[i]=sumlow/sumhigh*100; i--;
} //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; int limit=Bars-counted_bars; //---- signal line is simple movimg average for(i=0; i=0; shift--) { val=Low[Lowest(NULL,0,MODE_LOW,ExtDepth,shift)]; if(val==lastlow) val=0.0; else { lastlow=val; if((Low[shift]-val)>(ExtDeviation*Point)) val=0.0;
else { for(back=1; back<=ExtBackstep; back++) { res=ExtMapBuffer[shift+back]; if((res!=0)&&(res>val)) ExtMapBuffer[shift+back]=0.0; } } } ExtMapBuffer[shift]=val; //--- high val=High[Highest(NULL,0,MODE_HIGH,ExtDepth,shift)]; if(val==lasthigh) val=0.0; else { lasthigh=val; if((val-High[shift])>(ExtDeviation*Point)) val=0.0; else { for(back=1; back<=ExtBackstep; back++) { res=ExtMapBuffer2[shift+back]; if((res!=0)&&(res=0; shift--) { curlow=ExtMapBuffer[shift]; curhigh=ExtMapBuffer2[shift]; if((curlow==0)&&(curhigh==0)) continue; //--if(curhigh!=0) { if(lasthigh>0) { if(lasthigh0) { if(lastlow>curlow) ExtMapBuffer[lastlowpos]=0; else ExtMapBuffer[shift]=0; } //--if((curlow
} lasthigh=-1; } } for(shift=Bars-1; shift>=0; shift--) { if(shift>=Bars-ExtDepth) ExtMapBuffer[shift]=0.0; else { res=ExtMapBuffer2[shift]; if(res!=0.0) ExtMapBuffer[shift]=res; } } } //+------------------------------------------------------------------+ //| Accelerator.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" //---- indicator settings #property indicator_separate_window #property indicator_buffers 3 #property indicator_color1 Black #property indicator_color2 Green #property indicator_color3 Red //---- indicator buffers double ExtBuffer0[]; double ExtBuffer1[]; double ExtBuffer2[]; double ExtBuffer3[]; double ExtBuffer4[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- 2 additional buffers are used for counting. IndicatorBuffers(5); //---- drawing settings SetIndexStyle(0,DRAW_NONE); SetIndexStyle(1,DRAW_HISTOGRAM); SetIndexStyle(2,DRAW_HISTOGRAM); IndicatorDigits(Digits+2); SetIndexDrawBegin(0,38); SetIndexDrawBegin(1,38); SetIndexDrawBegin(2,38); //---- 4 indicator buffers mapping SetIndexBuffer(0,ExtBuffer0); SetIndexBuffer(1,ExtBuffer1); SetIndexBuffer(2,ExtBuffer2); SetIndexBuffer(3,ExtBuffer3); SetIndexBuffer(4,ExtBuffer4); //---- name for DataWindow and indicator subwindow label IndicatorShortName("AC"); SetIndexLabel(1,NULL); SetIndexLabel(2,NULL); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Accelerator/Decelerator Oscillator | //+------------------------------------------------------------------+ int start()
{ int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd counted in the 1-st additional buffer for(int i=0; i=0; i--) { current=ExtBuffer3[i]-ExtBuffer4[i]; prev=ExtBuffer3[i+1]-ExtBuffer4[i+1]; if(current>prev) up=true; if(current
//---- indicator buffers SetIndexBuffer(0,ADXBuffer); SetIndexBuffer(1,PlusDiBuffer); SetIndexBuffer(2,MinusDiBuffer); SetIndexBuffer(3,PlusSdiBuffer); SetIndexBuffer(4,MinusSdiBuffer); SetIndexBuffer(5,TempBuffer); //---- name for DataWindow and indicator subwindow label IndicatorShortName("ADX("+ADXPeriod+")"); SetIndexLabel(0,"ADX"); SetIndexLabel(1,"+DI"); SetIndexLabel(2,"-DI"); //---SetIndexDrawBegin(0,ADXPeriod); SetIndexDrawBegin(1,ADXPeriod); SetIndexDrawBegin(2,ADXPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Average Directional Movement Index | //+------------------------------------------------------------------+ int start() { double pdm,mdm,tr; double price_high,price_low; int starti,i,counted_bars=IndicatorCounted(); //---i=Bars-2; PlusSdiBuffer[i+1]=0; MinusSdiBuffer[i+1]=0; if(counted_bars>=i) i=Bars-counted_bars-1; starti=i; //---while(i>=0) { price_low=Low[i]; price_high=High[i]; //---pdm=price_high-High[i+1]; mdm=Low[i+1]-price_low; if(pdm<0) pdm=0; // +DM if(mdm<0) mdm=0; // -DM if(pdm==mdm) { pdm=0; mdm=0; } else if(pdm0) counted_bars--; int limit=Bars-counted_bars; //---- apply EMA to +DI for(i=0; i<=limit; i++) PlusDiBuffer[i]=iMAOnArray(PlusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i); //---- apply EMA to -DI for(i=0; i<=limit; i++) MinusDiBuffer[i]=iMAOnArray(MinusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i);
//---- Directional Movement (DX) i=Bars-2; TempBuffer[i+1]=0; i=starti; while(i>=0) { double div=MathAbs(PlusDiBuffer[i]+MinusDiBuffer[i]); if(div==0.00) TempBuffer[i]=0; else TempBuffer[i]=100*(MathAbs(PlusDiBuffer[i]-MinusDiBuffer[i])/div); i--; } //---- ADX is exponential moving average on DX for(i=0; i
SetIndexLabel(1,"Gator Teeth"); SetIndexLabel(2,"Gator Lips"); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Bill Williams' Alligator | //+------------------------------------------------------------------+ int start() { int limit; 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--; limit=Bars-counted_bars; //---- main loop for(int i=0; i
IndicatorShortName("AO"); SetIndexLabel(1,NULL); SetIndexLabel(2,NULL); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Awesome Oscillator | //+------------------------------------------------------------------+ int start() { int limit; int counted_bars=IndicatorCounted(); double prev,current; //---- last counted bar will be recounted if(counted_bars>0) counted_bars--; limit=Bars-counted_bars; //---- macd for(int i=0; i=0; i--) { current=ExtBuffer0[i]; prev=ExtBuffer0[i+1]; if(current>prev) up=true; if(current
Samples Includes #import "ExpertSample.dll" int GetIntValue(int); double GetDoubleValue(double); string GetStringValue(string); double GetArrayItemValue(double arr[],int,int); bool SetArrayItemValue(double& arr[],int,int,double); double GetRatesItemValue(double rates[][6],int,int,int); int SortStringArray(string& arr[],int); int ProcessStringArray(string& arr[],int);
Samples Indicators //+------------------------------------------------------------------+ //| ATR.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link
"http://www.metaquotes.net/"
#property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 DodgerBlue //---- input parameters extern int AtrPeriod=14; //---- buffers double AtrBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); //---- indicator line SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,AtrBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="ATR("+AtrPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---SetIndexDrawBegin(0,AtrPeriod); //---return(0); } //+------------------------------------------------------------------+ //| Average True Range | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---if(Bars<=AtrPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=AtrPeriod;i++) AtrBuffer[Bars-i]=0.0; //---i=Bars-counted_bars-1; while(i>=0) { double high=High[i]; double low =Low[i]; if(i==Bars-1) TempBuffer[i]=high-low; else { double prevclose=Close[i+1]; TempBuffer[i]=MathMax(high,prevclose)-MathMin(low,prevclose); } i--; } //---if(counted_bars>0) counted_bars--; int limit=Bars-counted_bars; for(i=0; i
//| Bands.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_chart_window #property indicator_buffers 3 #property indicator_color1 LightSeaGreen #property indicator_color2 LightSeaGreen #property indicator_color3 LightSeaGreen //---- indicator parameters extern int BandsPeriod=20; extern int BandsShift=0; extern double BandsDeviations=2.0; //---- buffers double MovingBuffer[]; double UpperBuffer[]; double LowerBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { //---- indicators SetIndexStyle(0,DRAW_LINE); SetIndexBuffer(0,MovingBuffer); SetIndexStyle(1,DRAW_LINE); SetIndexBuffer(1,UpperBuffer); SetIndexStyle(2,DRAW_LINE); SetIndexBuffer(2,LowerBuffer); //---SetIndexDrawBegin(0,BandsPeriod+BandsShift); SetIndexDrawBegin(1,BandsPeriod+BandsShift); SetIndexDrawBegin(2,BandsPeriod+BandsShift); //---return(0); } //+------------------------------------------------------------------+ //| Bollinger Bands | //+------------------------------------------------------------------+ int start() { int i,k,counted_bars=IndicatorCounted(); double deviation; double sum,oldval,newres; //---if(Bars<=BandsPeriod) return(0); //---- initial zero if(counted_bars<1) for(i=1;i<=BandsPeriod;i++) { MovingBuffer[Bars-i]=EMPTY_VALUE; UpperBuffer[Bars-i]=EMPTY_VALUE; LowerBuffer[Bars-i]=EMPTY_VALUE; } //---int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; iBandsPeriod-1) i=Bars-counted_bars-1; while(i>=0) {
sum=0.0; k=i+BandsPeriod-1; oldval=MovingBuffer[i]; while(k>=i) { newres=Close[k]-oldval; sum+=newres*newres; k--; } deviation=BandsDeviations*MathSqrt(sum/BandsPeriod);; UpperBuffer[i]=oldval+deviation; LowerBuffer[i]=oldval-deviation; i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bears.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- input parameters extern int BearsPeriod=13; //---- buffers double BearsBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); IndicatorDigits(Digits); //---- indicator line SetIndexStyle(0,DRAW_HISTOGRAM); SetIndexBuffer(0,BearsBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="Bears("+BearsPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---return(0); } //+------------------------------------------------------------------+ //| Bears Power | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---if(Bars<=BearsPeriod) return(0); //---int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; i
TempBuffer[i]=iMA(NULL,0,BearsPeriod,0,MODE_EMA,PRICE_CLOSE,i); //---i=Bars-counted_bars-1; while(i>=0) { BearsBuffer[i]=Low[i]-TempBuffer[i]; i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Bulls.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property indicator_separate_window #property indicator_buffers 1 #property indicator_color1 Silver //---- input parameters extern int BullsPeriod=13; //---- buffers double BullsBuffer[]; double TempBuffer[]; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //+------------------------------------------------------------------+ int init() { string short_name; //---- 1 additional buffer used for counting. IndicatorBuffers(2); IndicatorDigits(Digits); //---- indicator line SetIndexStyle(0,DRAW_HISTOGRAM); SetIndexBuffer(0,BullsBuffer); SetIndexBuffer(1,TempBuffer); //---- name for DataWindow and indicator subwindow label short_name="Bulls("+BullsPeriod+")"; IndicatorShortName(short_name); SetIndexLabel(0,short_name); //---return(0); } //+------------------------------------------------------------------+ //| Bulls Power | //+------------------------------------------------------------------+ int start() { int i,counted_bars=IndicatorCounted(); //---if(Bars<=BullsPeriod) return(0); //---int limit=Bars-counted_bars; if(counted_bars>0) limit++; for(i=0; i=0) { BullsBuffer[i]=High[i]-TempBuffer[i];
i--; } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| Heiken Ashi.mq4 | //| Copyright c 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net | //+------------------------------------------------------------------+ //| For Heiken Ashi we recommend next chart settings ( press F8 or | //| select on menu 'Charts'->'Properties...'): | //| - On 'Color' Tab select 'Black' for 'Line Graph' | //| - On 'Common' Tab disable 'Chart on Foreground' checkbox and | //| select 'Line Chart' radiobutton | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net" #property indicator_chart_window #property indicator_buffers 4 #property indicator_color1 Red #property indicator_color2 White #property indicator_color3 Red #property indicator_color4 White //---- buffers double ExtMapBuffer1[]; double ExtMapBuffer2[]; double ExtMapBuffer3[]; double ExtMapBuffer4[]; //---int ExtCountedBars=0; //+------------------------------------------------------------------+ //| Custom indicator initialization function | //|------------------------------------------------------------------| int init() { //---- indicators SetIndexStyle(0,DRAW_HISTOGRAM, 0, 1, Red); SetIndexBuffer(0, ExtMapBuffer1); SetIndexStyle(1,DRAW_HISTOGRAM, 0, 1, White); SetIndexBuffer(1, ExtMapBuffer2); SetIndexStyle(2,DRAW_HISTOGRAM, 0, 3, Red); SetIndexBuffer(2, ExtMapBuffer3); SetIndexStyle(3,DRAW_HISTOGRAM, 0, 3, White); SetIndexBuffer(3, ExtMapBuffer4); //---SetIndexDrawBegin(0,10); SetIndexDrawBegin(1,10); SetIndexDrawBegin(2,10); SetIndexDrawBegin(3,10); //---- indicator buffers mapping SetIndexBuffer(0,ExtMapBuffer1); SetIndexBuffer(1,ExtMapBuffer2); SetIndexBuffer(2,ExtMapBuffer3); SetIndexBuffer(3,ExtMapBuffer4); //---- initialization done return(0); } //+------------------------------------------------------------------+ //| Custom indicator deinitialization function | //+------------------------------------------------------------------+ int deinit() { //---- TODO: add your code here
//---return(0); } //+------------------------------------------------------------------+ //| Custom indicator iteration function | //+------------------------------------------------------------------+ int start() { double haOpen, haHigh, haLow, haClose; if(Bars<=10) return(0); ExtCountedBars=IndicatorCounted(); //---- check for possible errors if (ExtCountedBars<0) return(-1); //---- last counted bar will be recounted if (ExtCountedBars>0) ExtCountedBars--; int pos=Bars-ExtCountedBars-1; while(pos>=0) { haOpen=(ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2; haClose=(Open[pos]+High[pos]+Low[pos]+Close[pos])/4; haHigh=MathMax(High[pos], MathMax(haOpen, haClose)); haLow=MathMin(Low[pos], MathMin(haOpen, haClose)); if (haOpen
Samples Scripts //+------------------------------------------------------------------+ //| close.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "close first market order if it is first in the list" | //+------------------------------------------------------------------+ int start() { bool result; double price; int cmd,error; //---if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES)) { cmd=OrderType(); //---- first order is buy or sell
if(cmd==OP_BUY || cmd==OP_SELL) { while(true) { if(cmd==OP_BUY) price=Bid; else price=Ask; result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE); if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); } else error=0; if(error==135) RefreshRates(); else break; } } } else Print( "Error when order select ", GetLastError()); //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| delete_pending.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "delete first pending order" | //+------------------------------------------------------------------+ int start() { bool result; int cmd,total; //---total=OrdersTotal(); //---for(int i=0; i
#property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "modify first market order" | //+------------------------------------------------------------------+ int start() { bool result; double stop_loss,point; int cmd,total; //---total=OrdersTotal(); point=MarketInfo(Symbol(),MODE_POINT); //---for(int i=0; i
total=OrdersTotal(); point=MarketInfo(Symbol(),MODE_POINT); //---for(int i=0; i string line_name="rotating_line"; string object_name1="rotating_text"; void init() { Print("point = ", Point," bars=",Bars); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ void deinit() { ObjectDelete(line_name); ObjectDelete(object_name1); ObjectsRedraw(); } //+------------------------------------------------------------------+ //| script program start function | //+------------------------------------------------------------------+ int start() { int time2; int error,index,fontsize=10; double price,price1,price2; double angle=0.0; //---price2=High[10]+Point*10; ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2);
index=20; ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100); ObjectSetText(object_name1, "rotating_text", fontsize); while(IsStopped()==false) { index++; price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point; error=GetLastError(); if(error!=0) { Print(object_name1," : ",ErrorDescription(error)); break; } ObjectMove(object_name1, 0, Time[index], price); ObjectSet(object_name1, OBJPROP_ANGLE, angle*2); ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize); ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0); double line_angle=360.0-angle; if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50); if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50); time2=ObjectGet(line_name,OBJPROP_TIME2); if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10]; else time2=Time[0]; ObjectSet(line_name, OBJPROP_TIME2, time2); ObjectSet(line_name, OBJPROP_ANGLE, line_angle); ObjectsRedraw(); angle+=3.0; if(angle>=360.0) angle=360.0-angle; fontsize++; if(fontsize>48) fontsize=6; Sleep(500); price1=ObjectGetValueByShift(line_name, index); if(GetLastError()==0) { if(MathAbs(price1-price) < Point*50) { Print("price=",price," price1=", price1); ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0)); ObjectsRedraw(); Sleep(5000); // ObjectDelete(object_name1); } } } return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| send_pending.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #property show_confirm //+------------------------------------------------------------------+ //| script "send pending order with expiration data" | //+------------------------------------------------------------------+ int start() { int ticket,expiration; double point; //---point=MarketInfo(Symbol(),MODE_POINT); expiration=CurTime()+PERIOD_D1*60;
//---while(true) { ticket=OrderSend(Symbol(),OP_SELLSTOP,1.0,Bid-100*point,0,0,0,"some comment",16384,expiration,Green); if(ticket<=0) Print("Error = ",GetLastError()); else { Print("ticket = ",ticket); break; } //---- 10 seconds wait Sleep(10000); } //---return(0); } //+------------------------------------------------------------------+ //+------------------------------------------------------------------+ //| trade.mq4 | //| Copyright © 2004, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2004, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include #include //+------------------------------------------------------------------+ //| script "trading for all money" | //+------------------------------------------------------------------+ int start() { //---if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ", "Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1); //---int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE); if(ticket<1) { int error=GetLastError(); Print("Error = ",ErrorDescription(error)); return; } //---OrderPrint(); return(0); } //+------------------------------------------------------------------+
Samples Program //+------------------------------------------------------------------+ //| ExportFunctions.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #property copyright "Copyright © 2005, MetaQuotes Software Corp." #property link "http://www.metaquotes.net/" #include #define TIME_INDEX 0 #define OPEN_INDEX 1 #define LOW_INDEX 2 #define HIGH_INDEX 3 #define CLOSE_INDEX 4 #define VOLUME_INDEX 5 //+------------------------------------------------------------------+
//| expert initialization function | //+------------------------------------------------------------------+ int init() { double ret,some_value=10.5; string sret; int cnt; string strarray[6]={ "first", "second", "third", "fourth", "fifth" }; //---- simple dll-functions call cnt=GetIntValue(some_value); Print("Returned value is ",cnt); ret=GetDoubleValue(some_value); Print("Returned value is ",ret); sret=GetStringValue("some string"); Print("Returned value is ",sret); //---cnt=SortStringArray(strarray,ArraySize(strarray)); for(int i=0; i
double double double double double double
TakeProfit = 50; Lots = 0.1; TrailingStop = 30; MACDOpenLevel=3; MACDCloseLevel=2; MATrendPeriod=26;
//+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { double MacdCurrent, MacdPrevious, SignalCurrent; double SignalPrevious, MaCurrent, MaPrevious; int cnt, ticket, total;
// // // // // //
initial data checks it is important to make sure that the expert works with a normal chart and the user did not make any mistakes setting external variables (Lots, StopLoss, TakeProfit, TrailingStop) in our case, we check TakeProfit on a chart of less than 100 bars if(Bars<100) { Print("bars less than 100"); return(0); } if(TakeProfit<10) { Print("TakeProfit less than 10"); return(0); // check TakeProfit } // to simplify the coding and speed up access // data are put into internal variables MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0); MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1); SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0); SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0); MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1); total=OrdersTotal(); if(total<1) { // no opened orders identified if(AccountFreeMargin()<(1000*Lots)) { Print("We have no money. Free Margin = ", AccountFreeMargin()); return(0); } // check for long position (BUY) possibility if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious(MACDOpenLevel*Point) && MaCurrent>MaPrevious) { ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd sample",16384,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()); return(0); } // check for short position (SELL) possibility if(MacdCurrent>0 && MacdCurrentSignalPrevious && MacdCurrent>(MACDOpenLevel*Point) && MaCurrent0) { if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice()); } else Print("Error opening SELL order : ",GetLastError()); return(0); } return(0); } // it is important to enter the market correctly, // but it is more important to exit it correctly... for(cnt=0;cnt
{ OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES); if(OrderType()<=OP_SELL && // check for opened position OrderSymbol()==Symbol()) // check for symbol { if(OrderType()==OP_BUY) // long position is opened { // should it be closed? if(MacdCurrent>0 && MacdCurrentSignalPrevious && MacdCurrent>(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position return(0); // exit } // check for trailing stop if(TrailingStop>0) { if(Bid-OrderOpenPrice()>Point*TrailingStop) { if(OrderStopLoss()SignalCurrent && MacdPrevious(MACDCloseLevel*Point)) { OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position return(0); // exit } // 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); } } } } } } return(0); } // the end. //+------------------------------------------------------------------+ //| Moving Average.mq4 | //| Copyright © 2005, MetaQuotes Software Corp. | //| http://www.metaquotes.net/ | //+------------------------------------------------------------------+ #define MAGICMA 20050610
extern double Lots = 0.1; extern double MaximumRisk = 0.02; extern double DecreaseFactor = 3; extern double MovingPeriod = 12; extern double MovingShift = 6; //+------------------------------------------------------------------+ //| Calculate open positions | //+------------------------------------------------------------------+ int CalculateCurrentOrders(string symbol) { int buys=0,sells=0; //---for(int i=0;i0) return(buys); else return(-sells); } //+------------------------------------------------------------------+ //| Calculate optimal lot size | //+------------------------------------------------------------------+ double LotsOptimized() { double lot=Lots; int orders=HistoryTotal(); // history orders total int losses=0; // number of losses orders without a break //---- select lot size lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1); //---- calcuulate number of losses orders without a break if(DecreaseFactor>0) { for(int i=orders-1;i>=0;i--) { if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; } if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue; //---if(OrderProfit()>0) break; if(OrderProfit()<0) losses++; } if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1); } //---- return lot size if(lot<0.1) lot=0.1; return(lot); } //+------------------------------------------------------------------+ //| Check for open order conditions | //+------------------------------------------------------------------+ void CheckForOpen() { double ma; int res; //---- go trading only for first tiks of new bar if(Volume[0]>1) return; //---- get Moving Average ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0); //---- sell conditions if(Open[1]>ma && Close[1]