Automated Trading Course - Part 1: Programming

Some people seem to be interested in a course about programming automated strategies, so I’ll post the first part of the course here over the next days. The first part is about learning programming in C, and covers variables, functions, branches, and loops. The second part will be about trading strategies, and cover trend trading, counter trend trading, optimizing, walk forward analysis, portfolio strategies, and money management. It uses some new trading algorithms such as frequency filters.

The course will go over about 2 weeks. The goal is to develop a portfolio strategy with a solid annual return of about 400% on capital. There might be a third part about using artificial intelligence, such a perceptrons and decision trees, but it’s not finished yet and comes at a later time.

The course is based on my half finished C trading tutorial. I hope from posting it here that I get some feedback about what is easy to understand and what not, so that I can improve the tutorial.

For the course you’ll need some program for running the script examples and testing the strategies. It’s called “Zorro” and you can download it for free from zorro-trader.com. We won’t use MT4 for this course, although MT4 also uses C for its Expert Advisors. There are several reasons: EA’s are more complicated and hard to learn for a beginner. MT4 lacks also some important features required for developing a profitable strategy, such as walk forward optimization. The third reason is that MT4 has a hidden feature called “Virtual Dealer Plugin”, which can be used by your broker to pocket a part of your profits. Therefore an MT4 EA had to be very good for getting into the profit zone on real trading. However when you’re through this course you’ll also have the basic knowledge to write an MT4 Expert Advisor if you want.

1 Like

Sounds interesting jcl; eagerly awaiting the next parts of the course.

Cheers

Already gone through Tuts 1,2,3 and 4… Started to study C on my own… You know you v got one student here already. Lets hit the road running mate.

Let’s start working. At first a little theory. The purpose of a [B]script [/B](or program) is telling the computer what to do under which circumstances. A script consists of [B]variables [/B]and [B]functions [/B]- in this first lesson let me explain variables. A variable is a place in your computer’s memory (just like a container) that is used to store numbers, text, or other information. Because you don’t want to have to remember where in the computer which variable is stored, any variable has a unique [B]name [/B]that’s used in the script. A few example script lines that define variables:

[B]var Price;
var PercentPerMonth = 1.5; // the monthly interest
int Days = 7;
string Wealth = “I am rich!”;
bool Winning = true; [/B]

These are a few short lines of code but we can use them to learn many new things:

► Every variable must be [B]defined [/B](programmers also say ‘[B]declared[/B]’) before being used. We have different variable types: [B]var [/B]for variables with decimals, like prices or rates; [B]int [/B]for variables that have no decimals, such as for counting something; [B]string [/B]for text; and [B]bool [/B]for a sort of ‘toggle switch’ that is either true or false. There are even more basic variable types, but in trading scripts you’ll normally encounter only these four. If you write this line in your script:

[B]Days = 3;
[/B]
and you haven’t defined the variable named Days before, you’ll get an error message. The only exception are variables that Zorro already knows because they are pre-defined in the compiler.

► Any variable can receive an initial value at start, but we aren’t forced to do that when the initial value does not matter. Example:

[B]int num_bars = 7;
var limit = 3.5[/B];

► We can add our own comments to the code. Every time it encounters two slashes //, Zorro will ignore the words that follow it, up to the end of the line. This way we can add useful information to our code:

[B]int bar_width; // the width of one bar in minutes[/B]

or we can temporarily disable a line in the script by placing two slashes in front of it. This is called “commenting out” a line, and while programming it is used so frequently that the script editor has two extra buttons for commenting out and commenting in.

► Every definition or any command in C needs to end with a semicolon. Many beginners forget to add “;” at the end of their lines of code, and this also leads to an error message - not in the line with the missing semicolon, but in the following line!

► Every variable name must start with either a letter or with an underscore _. Here are some valid variable names:

[B]var AlohA;
var _me_too;
var go42;
var Iamb19;
var _12345;[/B]

Now let’s take a look at some bad examples:

[B]var #ItoldYou;
var 1_for_all;
var 12345;[/B]

I’ll let you discover what is wrong in the definitions above.

► Variable names are case sensitive. This means that if we define an int this way:

[B]int MyTradePositions;[/B]

and then we use it later in our code this way:

[B]mytradepositions = 5; // or
Mytradepositions = 5; // or
MYTRADEPOSITIONS = 5;[/B]

Zorro will not accept it.

► You can define several variables in one line. This saves lines and keeps your code short. Example:

[B]var momentum, strength, score;
int width = 7, height = 14, depth = 20;[/B]

► Finally, the variables should have significant names. While it is possible to define a pile of variables that look like this:

[B]var x32;
var a125;
var h_34_5;
var _z34187;[/B]

it isn’t a good idea to do it this way. You will have problems trying to remember what these variables do if you look at your script a few weeks later. If you want to show your script to other people, they will have a hard time trying to figure what you wanted to do with your code.

Tomorrow we’ll write a little example script that does something with variables.

Please don’t hesitate to ask here if something is unclear or bad explained.

Hi,
It is Jonathon is it not?

You should introduce yourself. Let ppl know you are not some crazy 15 year old kid :slight_smile:

BTW, the Zorro manual is a good read. I like the part about indicators. Totally agree some of the most commonly used indicators have no provable benefit in trading. True believers will keep on using them though.

Hi goldylox - I’m not Jonathon, but I posted about myself in the “Introduce” forum some time ago. I have a mathematical background, you might find some of my stuff on the net when you google my real name, Johann Christian Lotter. But it does not matter who I am - I think it’s the content that matters. Thanks for the kind words about the Zorro manual.

-Back to the course. Today we’ll write our first script. You’ll need to download Zorro now from zorro-trader.com if you haven’t done so already. After installation, start it and you’ll see this:

Click the [Script] scrollbox, go all the way down and select [New Script]. A text editor will now open. Type in the following:

function main()
{
  var a,b,c;

  a = 1;
  b = 2;
  c = a + b;
  printf("Result = %.f",c);
}

Now, select [Save As] in the [File] menu of the text editor, and save it under a name like “myfirstscript.c” in the “Strategy” subfolder of your Zorro installation. When you now click Zorro’s [Script] scrollbox again, the name “myfirstscript” should appear among the other scripts. Select it, press [Test] on Zorro’s panel, and watch what happens in its message window.

If you did anything right, you should now see a message like “Result = 3”. Otherwise, please complain here.

Now, edit the numbers in the a and b lines and replace them with

a = 5;
b = 12;

Save the edited script (File / Save or [Ctrl-S]), then press [Test] again. Tell us if your result is different than 17.

That was our first program. Starting to make sense of this, isn’t it? It looks like c is the sum of a and b; try to type several values for a and b and you will convince yourself. Now let’s take a look at the piece of script that transforms Zorro in a sort of simple calculator.

function main()
{

}

The script starts with a function named main - everything that happens in a program is inside the winged brackets { } of a function. But we’ll come to functions tomorrow. Here we concentrate on variables, and the next lines should already be familiar from what I said above:

var a,b,c;

We can see that the 3 variables a, b, c are defined, just as described above. The following lines are commands:

a = 5;
b = 12;

The variables here get a content; they are set to 5 and 12. Now the following line is the core of our script:

c = a + b;

This line of C code appears to be simple too; it makes c equal to the sum of a and b. It is a command to the computer to add the content of the variables a and b and store the result in the variable c. Commands are lines in the code that do something, usually with variables.

The last line is also a command, used for displaying c in the message window:

printf(“Result = %.f”,c);

Let’s make a small experiment. Find the line of code c = a + b; in the editor, and then replace the “+” by a “*”, the ‘times’ character, so that the line now reads:

c = a * b;

Save the script, then press the [Test] button again. Does the result make sense?

You have now mastered the basics of lite-C. Zorro has multiplied 5 by 12, displaying the correct result: 60. I know it’s not yet a trade strategy what we’re doing here, but we’re going somewhere! So now we know how to add and multiply values; we can use “-” to subtract two numbers or “/” to divide them. We could replace the line that does the c = a * b; calculation with much more complex expressions…

But we’ll save that for the next lessons. Enough for today.

Please let me know if something was unclear or hard to understand.


Code



Done.

Tut 2 tonight?

this looks interesting I will follow this. Zoro looks interesting also I will check that out for sure.

Ok, this lesson will teach you interesting things about functions. Once you got variables and functions, you have a basic understanding of how a script works.

What are these functions, anyway? Let’s see a small example:

function add_numbers( )
{
  var a, b, c;
  a = 3; 
  b = 5;
  c = a + b;
}

Do you see what I see? A function is nothing more than a collection of C commands that are executed by the computer one after the other. Let’s see some properties for these functions:

► A function is normally defined using the word [B]function [/B]followed by the name of the function and a pair of parentheses B[/B]. The parentheses are used to pass additional variables to the function; we’ll learn about that later. In our case we don’t pass any variables, so they are empty.

► The [B]body [/B]of the function (its list of commands) must be written inside a pair of winged brackets [B]{ }[/B]. The body consists of one or more lines of lite-C code that end with a semicolon. For clarity, programmers usually indent the code in the function body by some spaces or a tab, for making clear that it is inside something.

► The names used for the functions follow the same naming convention as for variables. You shouldn’t use the same name for a variable and a function; this will lead to errors.

If you can read this tutorial I hope that you know your age, too. Not in years, but in days! What, you don’t know it? Ok, so let’s try to write a function that computes the number of days spent by me (or you) on Earth.

I know how to start! I write the keyword [B]function [/B]and then the name of the function; let’s name it compute_days:

[B]function compute_days()
{[/B]

I haven’t forgotten the parenthesis after the name of the function and I have added the first curly bracket!

We will use some variables, so we’d better define them now:

[B]var my_age = 33; // your age (in years) goes here
var days_a_year = 365.25;[/B]

Nothing new so far, right? We have defined two [B]var [/B]variables and they have received initial values, because I know my age in years and I also know that every year has about [B]365.25[/B] days. Now comes the scary part: how will I be able to tell the computer to compute the number of days? How would I do it with a pocket calculator? I would enter something like this:

[B]33 * 365.25 =[/B]

Now let’s take a look at our variables; if I replace [B]33[/B] with [B]my_age [/B]and [B]365.25 [/B]with [B]days_a_year[/B], I will get something like this:

[B]number_of_days = my_age * days_a_year;[/B]

Ok, so our function should end like this:

[B]var number_of_days = my_age * days_a_year;
printf(“I am %.f days old!”,number_of_days);
}[/B]

I have remembered to add the second curly bracket, so now the body of the function is enclosed by the two required curly brackets. I am really curious to see if this function works, so let’s test it. Fire up Zorro, and then select [New Script] in the Script list. Wait until the editor opens. Then copy and paste the lines below into the editor window. Select the entire script below with your mouse, right click and choose Copy (or hit [Ctrl-C]), switch to the editor, right click into the empty window named “script1”, then choose Paste:

function compute_days()
{
  var my_age = 33;
  var days_a_year = 365.25;
  var number_of_days = my_age * days_a_year;
  printf("I am %.f days old!",number_of_days);
}

The code looks pretty simple, doesn’t it? We already know how to work with those variables, we know how to add comments… So let’s save it (File / Save As) into the Strategy folder of the Zorro installation, under a name like [B]myscript2.c[/B]. Don’t forget the “[B].c[/B]” at the end - it means that this file contains C code.

If you did everything right, you should now find [B]myscript2[/B] in the Script list. Select it. Time to [Test] our script:

Does this error message mean that a script always need a [B]main()[/B] or [B]run()[/B] function? Yes, main is a predefined function name. If a function is named [B]main[/B], it will automatically run when we start our script. The function named [B]run [/B]is special to Zorro; it contains our trade strategy and is automatically run once for every time period. If a script has neither a [B]main [/B]nor a [B]run [/B]function, Zorro assumes that you made a mistake and will give you this error message.

Now, let’s enter a main function at the end of the script:

function main()
{
  compute_days();
}

The way I see it, this code ‘[B]calls[/B]’ (meaning it starts) our [B]compute_days [/B]function. Ok, now that we are here let’s see how we call a function: we write its name followed by a pair of parenthesis and then we end the line of code with a semicolon. Sounds logical, doesn’t it?

Important tip: write the lines of code for your functions first and call them later. The computer reads the code the same way you read a book: it starts with the top of the script page and goes down to the bottom, reading the code line by line. If I would write my script the other way around, like this:

function main()
{
  compute_days();
}

function compute_days()
{
  ... 
}

the computer will say: oh, that’s function [B]main[/B]. I know function [B]main[/B]; I need to run it every time. What does it say now? [B]compute_days()[/B]. What’s with this function? I don’t know it yet! I don’t know what it wants from me. I’m going to display an error message and I will take the rest of the day off:

Don’t forget to define your functions first, otherwise the computer will complain when you try to use it.

Tomorrow we’ll look into functions more closely. Please complain here when something didn’t work or was unclear.

so far so good - I’ve got about 2 yrs c++ college credits - so this stuff is ‘basic’ for me - but I will follow along - and may even participate - as I am working an ea in .mq4 – - but may be fun to try it here as well.
Keep up the nice work - and pace –
I recommend any ‘users’ out there - - write each of these code pieces like 9 times - and try different things with them - examples I guess -
if you figured out how many days old you are - - – -go ahead and figure out how many seconds that is? or even better - how many weeks? stuff like that - - - don’t expect yourself to ‘get it’ until you KNOW you know.

A short summary of the new things we’ve learned yesterday :

► We define functions by writing “[B]function name(…) { … }[/B]” in the script.

► If a function has the name [B]main [/B]or [B]run[/B], it is automatically executed. All other functions must be called from an already-running function to be executed.

But that’s not all what a a function can do. It can also get variables from the calling function, and give the value of a variable back in return. Let’s see an example of a function that gets and returns variables.

var compute_days(var age)
{
  return age * 356.25;
}

For a function to return the value of a variable, just write the variable - or the arithmetic expression that calculates the value - behind a [B]return [/B]command. The function then gives that value back to from where it was called.

You did notice that we defined this function not with the keyword “[B]function[/B]”, but with “[B]var[/B]”? But is [B]var [/B]not a variable definition? Yes, but when a function is expected to return something, it is just defined with the type of the returned variable. So if a function returns a variable of type [B]int[/B], define it with [B]int[/B]; if it returns a [B]var[/B], define it with [B]var[/B]. Still, the computer knows from the B[/B] parentheses that this is a function definition and no variable definition.

If a function expects variables, place them together with their type in the function definition between those parentheses. If there are several variables, separate them with commas. When you then call that function, just put the values of the variables you want to pass to the function between the parentheses. The function will then use those variables just as any other variable for computing a result.

If a function returns something, you can just place a call to that function instead of the variable that it returns. This sounds sort of complicated? Let’s try it right away with our new compute_days function. This is our new script:

var compute_days(var age)
{
  return age * 365.25;
}
 
function main()
{
  var my_age = 33;
  var number_of_days = compute_days(my_age);
  printf("I am %.f days old!",number_of_days);
}

We’ve just set our [B]number_of_days [/B]variable direct from the returned value by [B]compute_days(my_age)[/B]. This makes our code shorter and more elegant! Still, the result is the same:

Now what is this mysterious [B]printf(…)[/B]? It has parentheses attached, so it’s obviously also a function that we call for displaying our result. However we have nowhere defined this function; it is a function that is already “built-in” in C. Just as the built-in variables that we mentioned in the last workshop, there are also many functions already built in the script language.

The [B]“I am %.f days old!”,number_of_days[/B] are the two variables that we pass to the printf function. The first variable is a [B]string[/B], used for displaying some text: [B]“I am %.f days old!”[/B]. The second variable is a [B]var[/B]: [B]number_of_days[/B]. Variables passed to functions are separated by commas. You can read details about the [B]printf [/B]function in the Zorro manual: Click [Help], then navigate to “Script functions / Input/Output / printf”.

For the moment we just need to know that the strange [B]"%.f[/B]" in the string is a placeholder. It means: the function inserts here the value - with no decimals - of the [B]var [/B]that is passed to the function. So, if [B]number_of_days [/B]has the value [B]12045[/B], our printf function will print [B]“I am 12045 days old!”[/B].

We can make our code even shorter. Remember, if a function returns a [B]var[/B], we can just place a call of this function in stead of the [B]var[/B] itself - even inside the parentheses of another function. We’ll save one variable and one line of script this way. Programmers do such shortcuts all the time because they are lazy and prefer to type as less code as possible:

function main()
{
  var my_age = 33;
  printf("I am %.f days old!",compute_days(my_age));
}

Enough for today. The next workshop will teach us how a script can make decisions (called ‘branches’ in computerish). Being able to decide something is important for trading. So we’re now going in huge steps towards writing our own trade strategy.

Please let me know if something was unclear with passing variables to and from functions.

For this and the next lesson, you’ll need a slightly newer Zorro, as the version from the Beta Release had two small bugs that affected the slider set-up and the chart display. There’s a patch available. Go to the Zorro forum and download the 0.99.4 patch from the “Starting with Zorro” section.

Today we’ll learn how a program makes decisions. If my bills grow bigger than $3000, I need to find a new job, else I will keep my existing job.

Yes, my brain is still working ok, thank you for asking. That was just an example of an [B]if - else branch[/B]; its associated code would look like this:

if(my_bills > 3000)
  find_new_job();
else
  keep_old_job();

You will use “[B]if[/B]” statements when you want your script to make decisions - meaning that it behaves differently depending on some conditions, like user input, a random number, the result of a mathematical operation, a crossing of two indicators, etc. Here’s the basic form of the “[B]if[/B]” statement:

[B]if(some condition is true)
do_something(); // execute this command (a single command!)[/B]

or

[B]if(some condition is true)
{
// execute one or several commands that are placed inside the curly brackets
}[/B]

A more complex form of the “if” instruction is listed below:

[B]if(some condition is true)
{
// execute one or several commands that are placed inside the curly brackets
} else {
// execute one or several commands that are placed inside these curly brackets
}[/B]

The instructions placed inside the “[B]else[/B]” part are executed only if “[B]some condition[/B]” is not true. Here’s a practical example:

if (my_age > 65)
  income = 2000;
else // age less than or equal to 65?
  income = 3000;

It is pretty clear that income can be either [B]2000 [/B]or [B]3000 [/B]because only one of the branches will be executed ([B]income = 2000[/B] or [B]income = 3000[/B], not both). The conditional parts of the code are called “branches” because several nested if instructions can look like a tree with the root at the first “[B]if[/B]” and many branches of which only one is executed.

Let’s draw some conclusions:

► “[B]if[/B]” branching statements start with the if keyword followed by a pair of parentheses;
► the parentheses contain a comparison, or any other expression (“some condition”) that can be true or false;
► if the expression is true, the following instruction or the set of instructions placed inside the first pair of curly brackets is executed;
► if the expression is false and we don’t use “[B]else[/B]”, the set of instructions placed between the curly brackets is skipped (it isn’t executed);
► if the expression is false and we are using the “[B]else[/B]” branch as well, the set of instructions placed inside the first pair of curly brackets is skipped, and the set of instructions placed inside the second pair of curly brackets is executed.

You’ll be mastering these branching techniques in no time, trust me! Let’s write the following script :

function main()
{
  var profit = 50;
  if(profit > 100)
    printf("Enough!");
  else
    printf("Not enough!");
}

The code doesn’t look that complicated; we have defined a [B]var [/B]named [B]profit [/B]which receives an initial value of [B]50[/B], and an [B]if [/B]statement. If [B]profit [/B]is greater than [B]100[/B], we have enough, otherwise not. We can omit the if / else pairs of curly brackets mentioned above when their content consists of a single line of code.

Create a new script - you have learned in the last workshops how to do that - paste the content, save it as “[B]myscript3.c[/B]” in the Strategy folder, select and [Test] it:

Now let’s try something else. Modify the code by editing the marked line:

function main()
{
  var profit = slider(3,50,0,200,"Profit",0); // <= modify this line!
  if(profit > 100)
    printf("Enough!");
  else
    printf("Not enough!");
}

When you now click [Test] to run the script again, you’ll notice that the bottom slider gets the label “[B]Profit[/B]”. Move it all the way to the right, so that [B]200[/B] appears in the small window, and click [Test] again:

What happened? The [B]slider()[/B] function put its return value - which is the value from the bottom slider - into the [B]profit [/B]variable, and thus the [B]if(…)[/B] condition became true as the value was now bigger than 100. We can make an educated guess how the slider function works: It gets six variables - the slider number (3), the initial value (50), the right and left borders (0 and 200), the name of the slider (“Profit”), and a tooltip (here 0, i.e. not used). You can find a detailed description of this function in the Zorro help file. Put the slider to the right again and verify that the program now prints “Not enough!” when you click [Test] with the slider value at [B]100 [/B]or below. You can now imagine how we can use the sliders for adjusting variables for our strategies.

We’re now almost through with the programming part. One last lesson tomorrow and then we’ll start writing our first trade robot. Please mention here if something was unclear so far.

A little more about [B]if[/B] statements. Let’s assume that you want to do something only when two different conditions are fulfilled. Try the following program:

function main()
{
  var loss = slider(2,25,0,200,"Loss",0);
  var profit = slider(3,50,0,200,"Profit",0);
  if((profit > 50) and (loss == 0))
    printf("Enough!");
  else
    printf("Not enough!");
}

Now two sliders are involved. How do you need to set them for the “Enough!” condition? We leave this as a little puzzle to the reader… but we’ve learned that we can combine two conditions using the “and” keyword. There is also an “or” keyword when one or the other condition needs be true. (C/C#C++ programmers might wonder why they have to use [B]and[/B] and [B]or [/B]instead of the familiar operators [B]&&[/B] and [B]||[/B]. Don’t worry, all C operators work as before, we’re just using easier-to-memorize operators in lite-C for beginner’s sake.)

Now, I’m giving you three important tips for avoiding coding mistakes. Here’s the first one. Have you noted the use of parentheses around [B](profit > 50)[/B] and [B](loss == 0)[/B]? We know from school mathematics that in a mathematical equation, the expressions in the parentheses are solved first. B3[/B] is not the same as [B]1+(23)[/B] - this is true in mathematics and also in a programming language. Always use parentheses to make sure that the program calculates in the same order that we want… and make sure that you have as many opening as closing parentheses! A missing parentheses at the end of a line is one of the most frequent reasons of compiler error messages. The computer will usually complain about an error in the following line because it’s there looking for the missing parenthesis.

What’s with that “[B]loss == 0[/B]” in the first new line of code? Is the double equals sign a typing error? No, it isn’t. Whenever you compare two expressions ([B]loss [/B]and [B]0 [/B]in the example above) you have to use “[B]==[/B]” instead of “[B]=[/B]”, because a line of code that looks like this:

[B]if(loss = 0)
{
// do some stuff
}[/B]

will set [B]loss [/B]to zero instead of comparing [B]loss [/B]with zero! This is one of the most frequent mistakes; even an experienced programmer might set a variable to a certain value by mistake, instead of comparing it with that value. Using one instead of two equality signs for comparing two expressions is a very frequent mistake. Don’t forget this!

[B]if (a == 3) // correct
{
// do_some_stuff
}

if (a = 3) // wrong!
{
// do_some_stuff
}[/B]

You can avoid this mistake if you make it a habit to put the constant value on the left side of a comparison and the variable on the right side. The loss comparison statement would look this way:

[B]if(0 == loss) // correct
… [/B]

If you then accidentally put a single ‘[B]=[/B]’ instead of ‘[B]==[/B]’, Zorro will report an error because it knows that 0 can’t be set to a different value. That was the second tip.

The third tip is that you should use the ‘[B]==[/B]’ comparison with care. When you calculate a [B]var[/B] variable in a complicated mathematical [B]expression[/B], the result is usually inaccurate. Instead of [B]2[/B], it might be [B]2.00001[/B] or [B]1.99997[/B]. This is due to the limited precision of variables in a computer. When you then compare it with 2, the comparison always comes out false - so better use ‘greater’ or ‘smaller’ comparisons (< or >) when working with [B]var[/B] variables. This problem does not affect [B]int [/B]variables.

We’ve talked a lot about expressions, but what is an expression? An (arithmetic) expression is a sequence of variables, numbers, operators, etc that are linked together. You can have simple expressions that look like the one below:

[B]if (indicator > 50) // simple expression inside the parenthesis
{
// do something
}[/B]

Or you can have arbitrary complicated expressions that are a combination of sub-expressions:

[B]if((factor1*indicator1 > 50) and (indicator2 < 35) and (volatility < 10)) // more complicated expression
{
// do something
}[/B]

You can combine as many expressions as you want, using parentheses, just like in the example above. The same rules from your math classes apply here, too. Sadly, you have to know some basic math if you want to be a good trader.

Now that you know everything about if statements, let me just talk a little about a statement that seems quite similar to if, but introduces a new concept in the programming language: [B]Loops[/B].

While I have less than a million, I must continue trading.

That was just an example of a “while loop”. In code it would look like this:

[B]while (my_money < 1000000)
trade(my_money);[/B]

The [B]while [/B]statement has the same syntax as the [B]if [/B]statement. There is some expression - in this case the condition that the variable [B]my_money [/B]is less than a million - and a command that is executed when the expression is true. However, in the case of an [B]if [/B]statement, the program whould then go on with executing the next command afterwards. In the case of a [B]while [/B]statement, the program “jumps back” to the while condition and tests it again. If it’s still true, the command is executed again. And the while condition is then tested again. And so on. This process is repeated until the while expression eventually comes out false, or until eternity, whichever happens first.

A “[B]loop[/B]” is called so because the program runs in a circle. Here’s the basic form of the while loop:

[B]while (some condition is true)
do_something(); // execute this command repeatedly until the condition becomes false [/B]

or

[B]while (some condition is true)
{
// execute all commands inside the curly brackets repeatedly until the condition becomes false
}[/B]

Note that whatever the commands do, they must somehow affect the [B]while [/B]condition, because when the condition never changes, we have an “infinite loop” that never ends!

Here’s a practical example of a while loop. Run this in Zorro:

function main()
{
  var n = 0; 
  while(n < 10) { 
    n = n + 1;
    printf("%.f ",n);
  }
}

This little program adds [B]1 [/B]to the variable [B]n[/B], prints the variable to the message window, and repeats this until [B]n [/B]is [B]10[/B].

Loops are very useful when something has to be done repeatedly. For instance, when we want to execute the same trade algorithm several times, each time with a different asset. This way we can create a strategy that trades with a portfolio of assets.

We are now at the end of the first part of the course. In the next part we’ll begin with developing real trading strategies; you’ve already learned all programming stuff that you’ll need for those lessons. But there’s far more to programming - we haven’t touched yet concepts such as macros, pointers, arrays, or the Windows API. lite-C also supports some elements from C++, the ‘big brother’ of C - such as classes or function overloading. If you want, you can continue on your own with online C tutorials. You can also visit the Gamestudio community that uses Zorro’s lite-C language for programming small or large computer games.

If you want to look at some ‘real’ C program, run the script [B]Mandelbrot[/B]. It has nothing to do with trading and you will probably not understand yet much of the code inside. It is a normal Windows graphics program. Don’t worry, trading strategies won’t be this complicated - it just shows that programming has a lot more depth and can be a lot more fun even without earning money with it. :wink:


A lil error before getting it right.


Progress

So I am curious about 2 things - - oh by the way keep it up this is good stuff.
I’ve ---- out a couple spots from your first post - - – what do you mean by Virtual Dealer plugin and How can it take part of my profits?
Secondly - -
I have this fear - - that I create an nice EA that generates profits - - and for some reason - - someone hacks my pc and gets my code - - how likely is this?

The Virtual Dealer Plugin is a MT4 / MT5 feature that reduces the profits of your trades with a variety of methods. For instance, it adds artificial slippage, and it early triggers your stop loss. This happens in a way that you normally won’t notice it - you’ll just wonder why you’re frequently losing. The broker can determine through the plugin settings how many pips he wants to take from your profits. It won’t only affect your EAs, but also manual trading. You can see here what your broker can do with your trades:

As to the issue of hacking your PC however, this is normally not easy. If your EA is so good that hacking your PC would be worth it, you’ll be probably already so rich that it won’t matter to you. :wink:

The second part of the course starts here:

http://forums.babypips.com/expert-advisors-automated-trading/47032-automated-trading-course-part-2-strategy-design.html

any updates, jcl365?