Australia Forex Broker
Trade with an
Australian regulated
company!
Forex Expert Advisor
Forex Expert Advisor
Live Account Testing
Forex Video Tutorials
Forex Education
Video Tutorials
Forex Platform - MetaTrader 4 How to Guide
Forex Platform
MT4 User Guide

MQL4 Programming

Variables – An Overview

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

A string variable is used for text usually. For example, to ask the user for his or her first name.

A Boolean variable is used when the variable can be either true / false or yes / no.

An integer is just a whole number.

A double is also a number but with a higher precision (decimals). The price of the EURUSD would be stored in a "double" variable. The number of periods to use in you Moving Average would be stored as an int. The name of the user would be stored as a string.

Declaring Variables

Before you can use a variable you need to "declare" it.

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 will not be part of the code. It is recommend to add lots of comments to your code has it helps you or anyone would will read the code understand what is going on.

Also you may have notice the names of the variables, MOST programming languages are case sensitive. If I declared int number; And then tried to use, Number , it would NOT know that you want the value of number and will most likely return an error message. Also you cannot use a space in the name and more often than not special characters are not recommended.

Variable Initialization

It is recommended initializing a variable when declaring it. When declaring a variable you are holding a piece of memory from the computer to store a value. However that memory spot might be "NOT EMPTY" and have some random value. To avoid any issues it is recommended to 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

"IF THEN ELSE" is a conditional statement that allows us to modify the behavior of our program if specific "conditions" occur.

There are 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 next line of 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 for your < condition > are:

Greater Than in pseudo code is >
Less Than in pseudo code is <
Equal in pseudo code is ==
Not Equal in pseudo code is !=
Greater or Equal in pseudo code is >=
Less or Equal in pseudo code is <=
Let's say you wanted to create a program in which the user inputs 2 numbers and the program tells you with one is greater. This example will include input-> for each input by the end user 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

This example will show you how to create a program in which the user inputs 3 numbers and your program 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

You will notice that we created a 4th variable called Z to store in memory which of A or B was the greatest. Another, more efficient way to do the same thing:

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

Exercise:

Using pseudo code, create a program where the end user inputs 3 numbers A B and C and have the program return each number from the lowest to the highest. Try to write the 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;

//---- Variable Declare and Init

input-> A, B, C;

//---- Here we would take the inputs

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;

//---- Here is our logic

END

AND OR

You can combine multiple conditions by using AND and OR. Let's say we are writing a program that assigns grade to students. We input a grade and the program tells us whether it is an A, B, C, D or F and whether the student passed or failed. This code is not optimal but it was done on purpose.

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"

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

Spend some time thinking about this line:

IF ( X != "D" AND X != "F" ) THEN Y = "PASS"

Most beginners would probably have written this:

IF ( X == "A" OR X == "B" OR X == "C" ) THEN Y = "PASS"

Try to keep your code as small and as clean as possible. One way to keep a piece of code clean is to try to remember that == and != are available.

Looking at the code above, we see that our program has to go through a lot of steps before it is completed. Let's run through it one line at the time.

Input -> Score : Well let's say the score was 82.

The program will set the variables and then check the first IF statement. The result is false, so we go ahead to the next IF statement and this time it is true. We set our variables and we are done checking for the grade. However with the way the program is written it still will check to see if the score is a C or a D or an F. To make your program faster, better and easier to fix you need to skip unneeded steps.

The first option is to use ELSE IF

This is how the code might look if you used ELSE IF:

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

This code should execute faster because once it found the grade it does not check for the other conditions.

NESTED IF Statements

Nested IF statements are where many mistakes are made. They need to be setup properly and a small mistake in the syntax will modify the meaning of your code. For our pseudo code we will use indents to show nested IF statements.

For example:

IF < CONDITION > THEN

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 to terminate an IF statement, in pseudo code we write END IF to terminate the most recent IF statement.

Loops

Sometimes you need to repeat a set of actions until you get the desired outcome. For example I want my robot to continue cleaning until my 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 not be practical. So instead we use "repeating structures", more commonly called Loops. There are a few different type of loops but we will only talk about the While loop and the For loop.

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 an UNKNOWN AMOUNT OF TIMES. Let's say I want to count how many hits it takes for me to break a box. I don't know how many times I need to hit, maybe 3 this time maybe 5 next run, maybe more...

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; There are a number of different ways that line can be written:

First option

Count += 1; //-- Could be Count += 32; So it is not limited to incrementing by 1.
In the same vein you can use *= or /= or -=

Review:

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;
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 poorly written it will cause your program hang and crash.

Let's 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

This says, initialize the Count variable to be equal to zero. Then check to see if it is greater than -50 if not then add 1 to Count until it is. Well no matter how much you add to the variable Count it will never be less than -50 and your program will never stop.

The For Loop

The For Loop A For loop is most often used when the code within the loop needs to be repeated for an KNOWN AMOUNT OF TIMES. Let's say I want to see how fast a computer really is and I want it 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

Code:

Syntax:

FOR(< Init/condition >; < condition > ;< increment> )

REPEAT [ACTION]

Let's decompose the following line:

For( int i = 0; i < 1000; i++ )

int i = 0;

Here we are just declaring an int variable called i and initializing it to zero. On a side note, you will find that some programming language do not allow you to 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;

If I is less than 1000 do the loop...

i++

This tells the loop to increment the value of i by one. Again i++ is the same as i = i +1;

Another way of writing the same exact loop is:

For( int i = 1000; i > 0; i-- )

Intro to MT4 Programming

MetaTrader 4 has a powerful programming language called MQL4. It is similar to C and you can write and use custom DLL's. With the MQL4 language it is easy to open a trade, close a trade, access any data available on the platform and more. There are hundreds of these functions/items available so make sure to use the search and help often.

Meta-Editor

To access the MQL4 editor, click on Tools > MetaQuotes Language Editor from the platform. This program is really similar to a text editor, in fact it is one.

The first thing to note is the MQL Navigator. It is the fifth icon from the left on the toolbar and looks like a dictionary. The navigator by default is docked on the right side of the window, and has 3 tabs at the bottom Files, Dictionary and Search. You can find the definition of many of the functions and items here. This saves you the need to remember every function name or syntax.

The first tab (Files) is a simple browser of your MT4 tools folder. You could use it, for example, to open an indicator you programmed in the past. Instead of clicking on File, Open and then browsing through your many folders, you can quickly open an indicator, script or expert from this Files tab.

The second tab (Dictionary) is an index of built in functions, and best of all it is categorized. This is sometimes faster than a search.

The third tab is Search. Type in a keyword press enter and the program will look for matching functions or items.

Once you have found a function, you can then double click on the item to get more information.

Example:

Double on the search result item called "AccountNumber()"

This will open the Tool Box if it isn't already open. On the left is a list of related function. The toolbar at the top is very much like a browser toolbar. And at the bottom you will see tabs for Errors, Find in Files, Online Library, and Help.

The content of the Help page should read:

int AccountNumber()

To return the number of the current account you could use:

Print ("account number ", AccountNumber());

The "int" tells you the type of the value the function returns. Therefore if you want to store this data in a variable you would write:

int MyAccount = AccountNumber();

This window also gives you an example on how to use the function. This may help you understand how a function is supposed to be used.

MT4 Basic Guidelines

1) MQL4 is case sensitive

int, double, string and bool are all case sensitive. All MQL4 functions are also case sensitive. The same rule applies for if, for, while, else and others.

MyAccount is not the same thing as myaccount.

2) Statement Termination

Each action/statement should be terminated by a semicolon.
For example:

if( MyAccount != 0 )

{

Print("Not Connected");

MyAccount = AccountNumber();

Count +=1;

Etc ...

}

3) IF-THEN, IF THEN ELSE setup

You need to use French brackets for IF-THEN and IF THEN ELSE functions.
The specific syntax for MQL4 is:

If( condition)

{

code;

}

For example:

if( A > B)

{

X = A;

}

else

{

X = B;

}

4) Loop Setup

You need to use French brackets for Loop setups.

The While loop:

while( Done == False )

{

Print("not done");

Done = .... ;

}

The For loop:

for( int i= 0; i < 1000 ; i++)

{

Count++; Print( Count );

}

Writing Basic MetaTrader 4 (MT4) Indicators

Indicators are representations of the price data that trader use to help them make decisions. The data we will be working with is the Open, High, Low, Close and Volume (if available). The representation of the indicator is made across a time line; therefore you will need to use a loop. Make sure to always setup your loop properly and also make sure to use a FOR loop as much as possible.

First Step

Open the MetaEditor and click on File > New, select indicator in the popup window and click on Next. In the name field you would input the name of your MetaTrader indicator. Enter the author copyright info and website info if you choose to and then click on Next and then click on finish. This will present you with a blank template for your indicator.

The header should look like this:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

You will note these lines are preceded by //. They are comments and could be removed if you chose to. If you want to add an additional copyright or license statement you can add it here.

# Property - The next items you should see are:

#property copyright "Copyright © 2009, Your Copyright Information" #property link

www.yourwebsite.com

These were generated by the wizard when you created the new indicator. You can also update these if you need to. Items preceded by #property are controls for the indicators standard options/behavior.

The most common property settings available:

#property indicator_chart_window

#property indicator_separate_window

#property indicator_color1 to #property indicator_color8

#property indicator_level1 to #property indicator_level8

#property indicator_style1 to #property indicator_style8

#property indicator_levelcolor

#property indicator_levelstyle

#property indicator_levelwidth

#property indicator_maximum

#property indicator_minimum

#property indicator_buffers

#property indicator_chart_window and #property indicator_separate_window will determine whether your indicator will plot in the same window as the price chart or in a separate window.

If we keep the indicator in the same window, this is what the top of the code looks like:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

The color, level, style properties are used to define the "style" of the indicator and or levels. However if you set these as properties then the user won't be able to change any of these settings which is not usually a good idea.

For example if you wrote:

#property indicator_color1 Red

The MetaTrader indicator would be red. The user won't be able to change it to another color even though the platform allows you to select from a wide panel of colors. This same theory applies to width, style and levels.

#property indicator_maximum and #property indicator_minimum are used when you want to create an indicator in a separate window and you want to control the indicators window scale. For example in the case of an oscillator you would want to fix the range from 0 to 100 and you would add the following lines to your indicator.

#property indicator_maximum 100.0

#property indicator_minimum 0.0

You can see we used 100.0 and not 100. There is not really any difference but if you enter double values as doubles you will recognize them right away. Often people define and declare variables as integer variables but use them as double variables. To write a value in its right form helps you spot these types of mistakes quickly.

The #property indicator_buffers is, simply put, the amount of "lines" your indicator will display. You are limited to 8 output buffers, 8 lines. Internally, you can use as many buffers as you want but you can only display 8 of them.

If your indicator has one line you would write the following line:

#property indicator_buffers 1

If you wanted to create the MACD Traditional indicator, which has 2 moving averages and 1 histogram then you would need to use:

#property indicator_buffers 3

If you don't set this to 3 then you will be unable display 3 items in your indicator.

Now your MT4 indicator code looks like this:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

The next step is to define the buffers. To do this you will write:

double OutPut[];

Just like a variable you need to define the type, here you are using double. Then select a name, in this case OutPut. The [] is to define it as an array.

An array is a "list" of values for a variables. It is a multidimensional variable.

A basic example is when you try to pay your children for getting better grades. You will say if you get an A, I will give you $10. If you get a B then $5, and so on. You could represent this with the following table:

A  B  C  D  E
$10  $5  $1  $0.25  $0
Using the above table you would say:

OutPut[A] = 10.0;

OutPut[B] = 5.0;

OutPut[C] = 1.0;

OutPut[D] = 0.0;

OutPut[E] = 0.25;

For your indicator, you would need to "OutPut" the value of you indicator for each bar on your chart. So your table would be like this:

Bar0  Bar1  Bar2  Bar3  Bar4
Indicatorvalue0  Indicatorvalue1  Indicatorvalue2  Indicatorvalue3  Indicatorvalue4
Inputs:

In MQL4 it is easy to create inputs for the end user. You will simply add extern before your variable declaration. If you are writing a basic moving average indicator (not using the built-in iMA function) you would need to know the number of periods from the end user. Remember, periods are an integer so you will write:

extern int Periods = 10;

Or you could write:

extern bool IsItTrue = true;

extern double Value = 0.0;

extern string UserName = "Patrick Nouvion";

MetaTrader's language also has specific variable types such as color so you could also write:

extern color VarColor = Red;

Make sure to use only inputs that are needed. If you have a lot on inputs it is a good idea to separate them with "dummy" variables. Here is the input section for an expert advisor for an example:

extern bool CLOSE_ALL_ORDERS = false;

//extern bool AUTO_RENEW = false;

extern string INITIAL_ORDERS = "Initial Orders";

extern double EURUSD_LONG = 0.0; extern double GBPUSD_LONG = 0.0; extern double USDCHF_LONG = 0.0; extern double USDJPY_LONG = 0.0;

extern string PENDING_ORDERS = "Pending Orders";

extern double EURUSD_LOTS_TO_TRADE = 0.0; extern double __EURUSD_BUY_RATE = 0.0; extern double __EURUSD_SELL_RATE = 0.0; extern double GBPUSD_LOTS_TO_TRADE = 0.0;

extern double __GBPUSD_BUY_RATE = 0.0; extern double __GBPUSD_SELL_RATE = 0.0; extern double USDCHF_LOTS_TO_TRADE = 0.0; extern double __USDCHF_BUY_RATE = 0.0;

extern double __USDCHF_SELL_RATE = 0.0; extern double USDJPY_LOTS_TO_TRADE = 0.0;extern double __USDJPY_BUY_RATE = 0.0; extern double __USDJPY_SELL_RATE = 0.0;

extern string OPTIONS = "Options";

extern double PROFIT_TARGET = 0; extern double TRAIL_START = 0; extern double TRAIL = 0; extern bool EMAIL_ALERTS = false;

Notice the string variables that will help separate all the different inputs and which will not be used anywhere else in the code.

Now your code should look like this:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

double OutPut[];

extern int Periods = 10;

Let's take a quick break to look at the rest of the code that was automatically added into the default template. As you can see, the indicator requires 3 sections Init (); Deinit(); and Start();

You can call functions and those functions can return a value. In the case of an indicator or expert advisor in MetaTrader 4 you are expected to run 3 functions. Init(); Start(); Deinit(); in this order. It does not matter the order you put these into the code because MetaTrader will call the function in the right order regardless. You could write Start(); Deinit(); Init(); or Init();Deinit();Start(); but MetaTrader expects to find the 3 functions and it expects each of these function to return a value.

INIT ()

The code for init when you create a new MetaTrader indicator is:

int init()

{

return(0);

}

In essence this function must return an int and right now it returns 0.
To help you understand how functions are defined and what they are expected to do, here are a few examples:

bool ReturnZero () { return(true); }

double ReturnValue() { return(0.0);}

return(0) means everything ran fine without error, and -1 means there was an error. MetaTrader will first run through the init function, if in the end init returns 0 the program will assume everything went fine and will then run through the start function. If init returns -1 then MetaTrader will stop running the indicator. Remember, init is always called first. init is called when you apply an indicator, update the inputs, change the periodicity of the chart or change the symbol of the chart. init is only run one time and that is it.

At this stage you could actually compile the code. If we remove all the comments and unnecessary characters the code could look like:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

double OutPut[];

extern int Periods = 10;

int init() { return(0); }

int deinit() { return(0); }

int start() { return(0); }

However init() is where you need to define a few things about your indicator such as color, style. You can also add a few fail safes, copyright protection or expiration time here.

For this example if you wanted to make sure traders use positive Periods only, you would write:

Int init()

{

if( Periods <= 0 )

{

Alert("Invalid Periods");

return(-1);

}

return(0);

}

This says "if the input for the Periods is less than our equal to 0 return an error and stop running the indicator".

Now you will need to set your buffer index using SetIndexBuffer()

If your indicator uses multiple buffers, you will have an index to know which one to modify and how to modify it.

SetIndexBuffer(0, OutPut);

If your buffer was define as MyBuffer[], you would then write:

SetIndexBuffer(0, MyBuffer);

Note, you don't type the [] ... Also note that all is zero based, the first buffer is 0, the second buffer would be 1, etc ... This is very important to remember.

Now you will set a color and style using built in functions. Make sure to check the dictionary to learn all that is available to you. Here you will use the SetIndexStyle() function. The reason is that using this function in init versus using the property functions allows the end user to modify the style of the indicators using the MetaTrader 4 platform.

SetIndexStyle( 0, DRAW_LINE, STYLE_SOLID, 1, Red);

0 here represent your Buffer index, since you have only one buffer ( OutPut ) and that its index value was 0 you entered 0.

The 1 is for the width of the line. If we wanted a histogram we would have used DRAW_HISTOGRAM. STYLE_SOLID could have been STYLE_DOT or STYLE_DASH.

You should also define when your indicator should start to plot. In the case of a moving average, you won't get to plot any data until you have had at least a "periods" worth of data. If you entered periods = 10 then you would need 10 bars/records before you will be able to calculate your average for the first time. For this reason you would write the following line:

SetIndexDrawBegin(0, Periods );

0 refers to the buffer id. "Periods" is our external input...

Here is what your code looks like now:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

//---- BUFFER

double OutPut[];

//---- INPUT(S)

extern int Periods = 10;

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

//+ INIT |

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

int init()

{

//---- ERROR TRAPS

if( Periods <= 0 ) { Alert("Invalid Periods"); return(-1); }

//---- INDICATOR STYLE

SetIndexBuffer(0, OutPut);

SetIndexStyle( 0, DRAW_LINE, STYLE_SOLID, 1, Red);

SetIndexDrawBegin(0, Periods );

//----

return(0);

}

deinit()

deinit() can be really useful. It is used to tell the platform what to do when the MetaTrader indicator is removed. For example, you created some objects on your chart during the init() phase. In the deinit() phase you would make sure to clean up these object and delete them.

The basic deinit code:

int deinit() { return(0); }

start()

You will need to set an array and a "for loop" so that your MetaTrader 4 indicator will plot across the chart properly. So your first action is to prepare the "for loop". In order to do this, you will need to define how many bars/records you have on your chart.

For this example, your deinit code will be:

int deinit() { return(0); }

//---- Find MaxRecords

int counted_bars=IndicatorCounted();

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

if(counted_bars>0) { counted_bars--; }

int MaxRecords = Bars-counted_bars;

MaxRecords is the accurate count of bars / records on a given chart. With this information, you can now setup a loop:

//---- Find MaxRecords

int counted_bars=IndicatorCounted();

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

if(counted_bars>0) { counted_bars--; }

int MaxRecords = Bars-counted_bars;

for( int i = 0; i < MaxRecords ; i++ )

{

...

}

//----

return(0);

}

If you would like to check that everything is working, you could OutPut the Close value for a test. Change your loop to this:

for( int i = 0; i < MaxRecords ; i++ )

{

OutPut[i] = Close[i];

}

Your code should look like:

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

//---- BUFFER

double OutPut[];

//---- INPUT(S)

extern int Periods = 10;

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

//+ INIT |

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

int init()

{

//---- ERROR TRAPS

if( Periods <= 0 ) { Alert("Invalid Periods"); return(-1); }

//---- INDICATOR STYLE

SetIndexBuffer(0, OutPut);

SetIndexStyle( 0, DRAW_LINE, STYLE_SOLID, 1, Red);

SetIndexDrawBegin(0, Periods );

//----

return(0);

}

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

//+ DEINIT |

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

int deinit() { return(0); }

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

//+ START |

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

int start()

{

//---- Find MaxRecords

int counted_bars=IndicatorCounted();

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

if(counted_bars>0) { counted_bars--; }

int MaxRecords = Bars-counted_bars;

for( int i = 0; i < MaxRecords ; i++ )

{

OutPut[i] = Close[i];

}

//----

return(0);

}

Compile your code and open the platform. You can now apply your indicator on a chart. If your loop is set up properly, it should plot the close as a thin red line.

Now you need to program the value it outputs.

You could use:

for( int i = 0; i < MaxRecords ; i++ )

{

OutPut[i] = Close[i];

}

i will start at 0 and increment till it reaches MaxRecords. On the first run i is equal to 0. 0 is the most current bar and our loop will do:

OutPut[0] = Close[0];

Which means your most current OutPut value is equal to the Close most current value.

The next run i will be equal to 1. 1 is the bar before the most current bar and our loop will do:

OutPut[1] = Close[1];

A moving average of the close is the sum of the close for x periods divided by x. First you will need to sum up the Close value. For this you need another loop inside your loop.

double Sum = 0.0;

for( int k = 0; k < Periods; k++ )

{

Sum += Close[i+k];

}

Here you defined sum as a variable to store the total. Then you run a loop using the Periods input that was defined by the user. You not only defined sum but also set it to 0.0. This also resets it to 0.0 with each run.

A common mistake and something that is sometimes hard for people to understand is the Close[i+k]

Because you are using a loop inside of another loop, you need to add both iterators to get the right value. If you did not add i to k then our program would always use the most current values since k starts at 0.
Now you need to divide Sum by periods and set out output.

Now you need to divide Sum by periods and set out output.

OutPut[i] = Sum/Periods;

You should now have your moving average indicator.
Here is how your final code should look.

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

//| Your Indicator Name

//| Copyright © 2009, Your Copyright Information|

//| www.yourwebsite.com |

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

#property copyright "Copyright © 2009, Your Copyright Information"

#property link "www.yourwebsite.com"

#property indicator_chart_window

#property indicator_buffers 1

//---- BUFFER

double OutPut[];

//---- INPUT(S)

extern int Periods = 10;

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

//+ INIT |

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

int init()

{

//---- ERROR TRAPS

if( Periods <= 0 ) { Alert("Invalid Periods"); return(-1); }

//---- INDICATOR STYLE

SetIndexBuffer(0, OutPut);

SetIndexStyle( 0, DRAW_LINE, STYLE_SOLID, 1, Red);

SetIndexDrawBegin(0, Periods );

//----

return(0);

}

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

//+ DEINIT |

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

int deinit() { return(0); }

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

//+ START |

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

int start()

{

//---- Find MaxRecords

int counted_bars=IndicatorCounted();

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

if(counted_bars>0) { counted_bars--; }

int MaxRecords = Bars-counted_bars;

for( int i = 0; i < MaxRecords ; i++ )

{

double Sum = 0.0;

for( int k = 0; k < Periods; k++ )

{

Sum += Close[i+k];

}

OutPut[i] = Sum/Periods ;

}

//----

return(0);

}