Vous êtes sur la page 1sur 10

Introduction to MT4 Programming - Patrick Nouvion

Page 1 of 10

PRO 1010 | Intro to Programming - Patrick Nouvion

Introduction to Programming

Pre Requisite - This class should be taken before anyone should attempt to learn ho
your own tools with MT3 or MT4. If you are familiar with programming already you m
class.

MT4 has a much more flexible and extensive library. If you are familiar with Visual Basic, M
easier for you to pick up. If you come from a C based background, MT4 is your best choice

This is not intended to be a full fledge introduction to programming, but we will cover a
information that you will need for the more specific classes. Please make sure you spend m
trying to understand and follow the logic than try to get the right answer. The truth is, in
programming, there is not just one right solution. Everyone has their own style and appro
logic problems and that is fine, keep your own style just make sure you understand
doing. I do believe anyone can learn this if they put the effort required and do not give up
obstacle

Introduction

We all know what a computer is but let me give a slightly different description.
general purpose machines, I want to emphasize the word machines. Lets agree that a c
just an overgrown calculator. If it were not for the programs we use to control it, a
be quite useless.

So first and most important thing to learn and anchor in your head is that a computer is n
intelligent. A monkey is a gazillion times smarter than a computer, a computer only does w
told to do. Now keep this in mind as well, if a program you run makes mistakes, you
responsible for those mistakes. Own up to it, lets not be like those tennis players who kee
their racket after a bad shot.

However a computer is extremely powerful, because amongst other things it can do tons o
calculations a lot faster than we can. So how do we tell this machine what we want it to do
write programs, in some ways a program acts as a translator. There are many different
languages ( C, Visual Basic, Pascal, Delphi etc ) and their goal has always been to
communication between us humans and the machines. Unless you want to write
language programs which would not be practical ( nor easy for that matter ), you have to
compromise between English and Computer Speak.

For now our programming language will be what people call pseudo code, which means th
write our programs in plain English. The reason is because more often than not people will
the syntax and specific commands of a given programming language without learning the
programming concepts they need. Think of it as a kid who knows 3*2=6 but does
why ... He will get good grades until the problem he has to solve was not in his text book.

Algorithm

Programs or algorithms in computer science are a specific, finite set of instructions used to
problem or perform a function. A good example is a cooking recipe; let me point out tha
find many examples on the back of products you purchase everyday. Take a bottle of sham
the back and you will see the following:
Shake well
Shampoo
Rinse Thoroughly

Second important concept is that algorithms are the blue print for your programs
task in building a program is to write the algorithm for that program. Sure you can build a
without a blue print but chances are it is not a good idea Now to go back to our first imp
lesson (a computer is just a machine ), what do you think would happen if I made a
using the shampoo algorithm cited above, loaded it into a robot and ran it? Take the time
about it for a second

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 2 of 10

Well what would happen is the robot would shake well, shampoo, rinse then shake well, sh
rinse etc It would NEVER stop, it would not know to quit after washing its hair
even know there was no shampoo left, etc ... If you had sent a 5 year old wash his hair an
no shampoo left in the bottle he would come back and say Hey, we are out of shampoo! I
my hair. The kid would wash his hair once and then know to stop. Kids have common sen
computer does not

So your algorithm has to be very detailed and it needs to be finite. When writing algorithm
you to always start on the first line with START and finish is with END.
Here is your first assignment:

Take 5 or 10 minutes and write an algorithm in plain English to cook Mac and cheese. Aga
about right or wrong

Whatever you wrote is most likely a good answer but lets have a look at this version below
Here is a possible answer:
START
Find Milk and Butter and Kraft box
If found continue
else send kid to the store
Find Pot in cup board
If found continue else ask wife to help find it
Find Stove
If found continue
else order pizza
Check for an available burner
If available continue
else make avail
Turn Stove on to high
Find Water
If found continue
else order pizza
Put Water in pot
Make sure that the stove is hot
if hot continue
else check that it is plugged in
else call repair man and order pizza
Place pot on burner
if you have salt add a pinch of salt
if not continue
if you have pepper add a pinch of pepper
if not continue
while water is not boiling wait
open Kraft box
add the macaroni from box to pot
wait 8 minutes
while waiting, if pot over boils turn heat down and blow on it
Find colander
Drain macaroni in colander
return to pot
add contents of cheese packet
add butter
add 1 Tablespoon milk
stir to combine
if too thick add 1 Tablespoon milk; if not, eat
END
The Kraft Mac and Cheese exercise was done for 2 reasons:

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 3 of 10

1) now, most likely, you realize all that you would have forgotten should you have program
robot to cook your yellow death. Hopefully you understand that a few fail safe were need
do we have what we need to even get started) and that you might not have though of it if
first write the algorithm.

Also it is up to you to decide how complex you want your program to be. But if we take th
of checking for basic needs before we get started you could write a simple version:
Code:
If no milk or no Kraft or no pot or no whatever, then call pizza guy
Or you could go a little further
Code:
If no milk or no kraft or no pat or no whatever then go to store etc ...

2) You may or may not have noticed but each step could be a program of its own. I could
program call CheckFridgeForItems that will check to see a specific product is in my fridge.
my "CookMacnCheese" program call on that other "subprogram" when I need it. These sub
are called subroutines.
The idea is that it is easier to create 100 small programs than one enormous and gigantic
that has thousands of line of codes. Especially when you have to debug or update
our Mac and cheese we could have:
Code:
Program cook MacNCheese:
- call subroutine CheckForItems //--- We make sure we have the goods :)
- call subroutine PreparePot //---- We get our pot, water salt etc
- call subroutine StoveAndBoil
etc ...

Variables
From Wikipedia:

Quote: " In computer programming, variables are usually represented by alphanumeric st


variable can be thought of as a place to store a value in computer memory.

More precisely, a variable binds (associates) a name (sometimes called an identifier) with
location; a value in turn is stored as a data object in that location so that the object can be
later via the variable, much like referring to someone by name. Variables in computer prog
are analogous to variables in mathematics. Put in another way, an object could exist witho
bound to a variable, but without such a referent, it would be inaccessible from code. This
analogous to calling out a person whose name is not known, and expecting a reply from hi
Why do/should we use variables?
Variables for Inputs

Let's imagine a program where I want to find out if a number is greater than another num
this I need inputs from the user, since I do not know these inputs I will need to use
my program.
Input->A,B
If(A>B) OutPut->A Else OutPut ->B

Now my program is written using variable A and B that I can have the user define. So I do
to know or wait for the input values to write my program.
Variables for Flexibility

Let's say I wrote this great money making expert advisor and I found that when Price mov
1.1610 * 3.0 ) then I have a very good buy signal. And for arguments sake let's imagine I
calculation
( Pi * 1.1610 * 3.0 ) appears in my program over a hundred times.

Now after a few months the market as changed and after much backtesting I find out that
0.820 * 2.7 ) is a better value.

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 4 of 10

I now have to update my code every time it appears , over 100 times . Instead I could hav
variable called Calculation. For example:
Calculation = ( Pi * 1.1610 * 3.0 );

then every where in my program use the word ( variable name ) Calculation instead of ( P
3.0 ).

Some may think well I can do find/replace and get it fixed pretty quickly. Sure you could b
not seeing the big picture. When your programs start to be fairly complex, you will end up
tons of these calculations that should be variables.
Variables for Performance

If we take the example above you see that we end up calculating the value ( Pi * 1.1610 *
hundred times, where we only needed to calculate it once and store it in a variable. Now c
( Pie * 1.1610 * 3.0 ) a hundred times is not a big deal but you will often have access
that are resource intensive and you should always try to call them as little as you can.
Variable Types

There are different variable types ... The most common and the ones we care about are "S
"Integers", "Doubles", "Booleans".

A string variable is used for text usually. Let's say for example I created an input to ask t
his or her first name.

A Boolean variable is used when the variable can be either true or false. For example I cr
input asking the user if he or she is having a good day. The answer will be yes or no, true
1 and 0.
An integer is just a plain integer, think whole numbers only

A double is also a number but with a higher precision. Think decimals. Now why would yo
double instead of an integer? Lets imagine I create a variable called A and defined it as an
user inputs 1.2153 the program will only retain 1 (though it most likely will give you an er
double variable add more precision to your number and therefore uses more computer res
an integer variable.

The price of the EURUSD would be stored in a "double" variable. The number of periods to
Moving Average would be stored as an int. The name of the user would be stored

Alright so now we need to learn how to declare and initialize a variable. Each programming
has its own syntax but it is usually fairly similar. Also keep in mind we are using pseudo co
Declare Variables

Before you can use a variable you need to "declare" it. You could think of it as making a ph
reservation at a restaurant. "I need a table for 4 people at 8:30 for the under Joe Smith"
program, hold me an integer under the name Joe Smith"

If you go to the restaurant without making a reservation first and ask them to look up you
what will happen? They won't find it and therefore won't have a table ready for
programs and variables...
Code:
Syntax:
[variable Type] [Variable Name];
You declare a variable by writing the type, then the name followed by a semicolon.
int number; // This is an integer variable called number.
double prICE; // this is a double variable called prICE.
string Name; // This is a string variable called Name.
bool ISTRUE; // This is a boolean variable called ISTRUE.

In most programming languages anything after // becomes a comment of the code and wi
part of the code. It is recommend to add lots of comments to your code has it helps you o
would will read the code understand what is going on.

Also you may have notice the names of the variables, MOST programming languages are c
sensitive. If I declared int number; And then tried to use, Number , it would NOT know tha

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 5 of 10

the value of number and will most likely return an error message. Also you can not use a s
name and more often than not special characters are not recommended.
Variable Initialization

It is recommended to initialize a variable when declaring it. When declaring a variable you
a piece of memory from the computer to store a value. However that memory spot you ju
maybe "NOT EMPTY" and have some random value. To avoid any weird bug it is recomme
assign a value to a variable during its declaration. For example:
int number = 0;
double prICE = 25.6812;
string Name = "Patrick";
bool ISTRUE = true;
Notice the "" around Patrick, this is for string variables only.

IF THEN ELSE

So now that we have covered variables, let's overview "IF THEN ELSE" conditional stateme
allows us to modify the behavior of our program if specific conditions occur.
There is different ways you can use this:
Code:
Syntax
IF< CONDITION >THEN [ACTION A]ELSE[ACTION B];
Code:
Syntax
IF< CONDITION > THEN [ACTION A]

By default if no ELSE is specified the program will continue to run and will evaluate the nex
code.
For example in plain English I could write:
IF it is raining THEN we will cancel our soccer game ELSE we will play at 2 PM
The operators you can use for your < condition > are:
Greater Than in pseudo code we will write >
Less Than in pseudo code we will write <
Equal in pseudo code we will write ==
Not Equal in pseudo code we will write !=
Greater or Equal in pseudo code we will write >=
Less or Equal in pseudo code we will write <=

At the start of the program we declare our variable but what comes next. Next is your logi
say we wanted to create a program in which the user inputs 2 numbers and our program t
with one is greater. Also for the purpose of learning I will type input-> for each input by th
and output-> to show what the program would return/display.
START
//---- Variable Declare and Init
Int NumberOne = 0;
Int NumberTwo = 0;
//---- Here we would take the inputs
Input-> NumberOne; Input-> NumberTwo;
//---- Here is our logic
IF NumberOne > NumberTwo
THEN Output -> NumberOne
ELSE Output -> NumberTwo;
//---- End of Program
END

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 6 of 10

Now lets say we wanted to create a program in which the user inputs 3 numbers and our
tells you which one was the greatest...
START
//---- Variable Declare and Init
Int A = 0; Int B = 0; Int C = 0; Int Z = 0;
//---- Here we would take the inputs
input-> A, B, C;
//---- Here is our logic
IF A > B THEN Z = A ELSE Z = B;
IF Z > C THEN Output -> Z
ELSE Output -> C;
//---- End of Program
END

Now look at the program and you will notice that I had to create a 4th variable called Z to
memory which of A or B was the greatest. I hope it makes sense and make sure to spend
looking at the code, go through it like the computer would and understand what
with A = 5 and B = 1 then reverse the values. Once understood the code above and it is a
look at this updated code below and take the time to go through it.
START
//---- Variable Declare and Init
Int A = 0; Int B = 0; Int C = 0;
//---- Here we would take the inputs
input-> A, B, C;
//---- Here is our logic
IF A > B THEN B = A;
IF B > C THEN Output -> B
ELSE Output -> C;
//---- End of Program
END

Did you see that I assigned one variable's value to another variable. Once I know which of
greatest I don't need to remember the values and therefore can reuse one of the variable
some resources and make the code easier to read. Make sure you understand how I got
variable before continuing

Homework:

Using pseudo code to write your program, create a program where the end user inputs 3 n
and C and have the program return each number from the lowest to the highest.

It is important you try to do this exercise, now once you are done and have your solution.
your code and count how many variables you have? Chances are you have over 4 variable
to write the same program using only 4 variables and 3 IF statements
Answer:
START
//---- Variable Declare and Init
Int A = 0; Int B = 0;
Int C = 0; Int X = 0;
//---- Here we would take the inputs
input-> A, B, C;
//---- Here is our logic
IF A > B THEN X=A; A=B; B=X;
IF A > C THEN X=A; A=C; C=X;
IF B > C THEN X=B; B=C; C=X;
Output-> A,B,C;
//---- End of Program
END

Now I can combine multiple conditions by using AND and OR. Let's say we are writing a pr
assigns grade to students. We input a grade and the program tells us whether it is an A, B
and whether the student passed or failed. Code is not optimal and I'm doing it this way on
START
//---- Variable Declare and Init

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 7 of 10

Int Score = 0;
String X = Error; String Y = Error;
//---- Here we would take the inputs
input-> Score;
//---- Here is our logic
IF (Score >= 90 AND score <= 100) THEN X = "A"
IF (Score >= 80 AND score < 90 ) THEN X = "B"
IF (Score >= 70 AND score < 80 ) THEN X = "C"
IF (Score >= 60 AND score < 70 ) THEN X = "D"
IF (Score >= 50 AND score < 60 ) THEN X = "F"
IF ( X == "D" OR X == "F" ) THEN Y = "FAIL"
IF ( X != "D" AND X != "F" ) THEN Y = "PASS"
Output-> X,Y;
//---- End of Program
END

So hopefully this shows you how to combine condition and how to use the items presented
want you to spend some time thinking about this line:
IF ( X != "D" AND X != "F" ) THEN Y = "PASS"
Most beginners would probably have written this line such as :
IF ( X == "A" OR X == "B" OR X == "C" ) THEN Y = "PASS"

Now a lot of programmers tend to write out everything step by step ... Try to keep your
and as clean as possible. One way to keep a piece of code clean is to try to remember that
are available.

If we look at the code we see that our program has to go through a lot of steps before it is
Let's run through it one line at the time.
Input -> Score : Well let's say my score was 82.

The program will set my variables and then check the first if statement. The result is false
ahead to the next if statement and this time it is true so we set our variables and quite ho
are pretty much done checking for the grade.

However with the way our program is written it still will check to see if my score is a C or a
To make your program faster, better and easier to fix you need to skip unneeded steps.
The first option is to use ELSE IF let's take our code and update it:
START
//---- Variable Declare and Init
Int Score = 0;
String X = Error; String Y = Error;
//---- Here we would take the inputs
input-> Score;
//---- Here is our logic
IF (Score >= 90 AND Score <= 100) THEN X = "A"
ELSE IF (Score >= 80 AND Score < 90 ) THEN X = "B"
ELSE IF (Score >= 70 AND Score < 80 ) THEN X = "C"
ELSE IF (Score >= 60 AND Score < 70 ) THEN X = "D"
ELSE THEN X = "F"
IF ( X == "D" OR X == "F" ) THEN Y = "FAIL"
ELSE THEN Y = "PASS"
Output-> X,Y;
//---- End of Program
END

Now let's run though the code again ... hopefully you see that this code will execute faster
once it found the grade it does not check for the other conditions. There is one more that
but that is not our goal right now.

Lets have a look at NESTED IF statement. This is where most mistakes are made. They n
setup properly and a small mistake in the syntax will modify the meaning of your code. Fo
pseudo code we will use indents to show nested IF statements.
For example:
IF < CONDITION > THEN

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 8 of 10

IF< CONDITION > THEN [ACTION A]


ELSE [ACTION B]
END IF
ELSE [ACTION C]
END IF

When you start learning with a specific programming language make sure to recognize how
terminate an IF statement, in pseudo code we write END IF to terminate the most recent I
statement. In any case always be careful when writing nested IFs'. But if you take the nex
you will have plenty of opportunities to experience this first hand.
There are only a few more concepts for you to learn, we are almost done.

Loops

The reason why a computer is such great tool is because it is good at repeating the same
over and over and over and over. It does not get tired, it does not make mistake, and it is
way we have been writing our programs so far was very linear and it is fine but sometimes
to repeat a set of actions until you get the desired outcome. For example I want my robot
car is clean How do I say until in programming?

I could write a program that checks 10 times whether the car is clean or not but it would n
job and it is not practical. So instead we use repeating structures, more commonly called
There are a few different type of loops but we will only talk about the While loop and the
In the example of the car we would use:
Loop Start
While( Car Not Clean )
Clean Car
Loop End
The While Loop

A While Loop is most often used when the code within the loop needs to be repeated for a
UNKNOWN AMOUNT OF TIMES. Lets say I want to count how many hits it takes for me
box. I dont know how many times I need to hit, maybe 3 this time maybe 5 next run, ma
So I would write:
START
//---- Variable Declare and Init
Int Count = 0;
//---- Here is our logic
Loop Start
While( The box is not broken )
Count = Count + 1;
Loop End
Output-> Count;
//---- End of Program
END
Code:
Syntax:
WHILE < CONDITION IS TRUE > REPEAT [ACTION]

You will also notice the Count = Count + 1; And for those wondering yes most programmi
will let you do this. Briefly let me show should the different ways I can write the above line
First option
Count += 1; //-- Could be Count += 32; So it is not limited to 1.
In the same vein I can do *= or /= or -=
To make sure we are on the page.
A = A / 10; is the same as A /= 10;
A = A * 10; is the same as A *= 10;
A = A 10; is the same as A -= 10;
A = A + 10; is the same as A += 10;

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 9 of 10

Second option
Count++ ; //-- This increments Count by 1
I can also write Count--; // This would decrement Count by 1.

The While Loop is the more dangerous of the loops, because if badly written it will cause
program hang and crash.
Lets look at this program:
START
//---- Variable Declare and Init
Int Count = 0;
//---- Here is our logic
Loop Start
While( Count > -50 )
Count = Count + 1;
Loop End
Output-> Count;
//---- End of Program
END

So Im saying, initialize the Count variable to be equal to zero. Then check to see if it is gr
50 if not then add 1 to Count until it is. Well no matter how much you add to the variable
never be less than -50 and your program will never stop. Try to avoid using While
possible, even though it may look easier to use at first Try a For loop.

The For Loop A For loop is most often used when the code within the loop needs to be rep
an KNOWN AMOUNT OF TIMES. Lets say I want to see how fast a computer really is an
to calculate a complex math formula 1000 times.
So I would write:
( In our example the complex math formula is : 43876439182/3720193473412)
START
//---- Variable Declare and Init
double Value = 0.0;
//---- Here is our logic
Loop Start
For( int i = 0; i < 1000; i++ )
Value = 43876439182/3720193473412;
Loop End
Output-> Value;
//---- End of Program
END

When you write your first program you should write some silly math calculation that took y
to solve and have your program loop through it thousands of times just so you can realize
can do it.
Code:
Syntax:
FOR(< Init/condition >; < condition > ;< increment> )
REPEAT [ACTION]
Now it looks scary but it is not. Chances are you noticed this line in my previous code:
For( int i = 0; i < 1000; i++ )
Lets decompose it:
int i = 0;

Here Im just declaring an int variable called i and initializing it to zero. I could if I wanted
1000; Also on a different note, you will find that some programming language do not allow
declare a variable there so I could have declared i with my other variables and then write:
For( i = 0; i < 1000; i++ )
i < 1000; T
his part is pretty strait forward, if i is less than 1000 do the loop

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Introduction to MT4 Programming - Patrick Nouvion

Page 10 of 10

i++

Here I just tell my loop to increment the value of i by one. Again i++ is the same as i = i +
look at the code again, hopefully you see that, with each iteration the value of i increases
it finally reaches 1000.
Another way of writing the same exact loop is:
For( int i = 1000; i > 0; i-- )

This version has its uses obviously, and you will find out why when you start dealing with
will not cover arrays here because their structure too often depends on the language and i
to explain in real programming code.

This is the end of our Intro to programming class I hope you liked it. Make sure to take eit
MT3 or MT4 Classes

http://www.ibfx.com/ibfxu/catalog/programming/pro1010.aspx

30-08-2009

Vous aimerez peut-être aussi