Previous: Functions

Workshop 3: Branches and Loops

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 if - else branching; its associated code would look like this:

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

You will use "if" 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 "if" statement:

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

or

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

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

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
}

The instructions placed inside the "else" part are executed only if "some condition" 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 2000 or 3000 because only one of the branches will be executed (income = 2000 or income = 3000, 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 "if" and many branches of which only one is executed.

By the way, have you notices how we indented the lines after the "if" and between the winged brackets? The C language does not care how you indent lines or if you write a command on the same or on a new line, but we do that for clarity. The code reads easier if dependent lines are indented. However, if we want we can write it also like this:

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

or even

if(my_age > 65) income = 2000; else income = 3000;

Let's draw some conclusions:

► "if" 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 "else", 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 "else" 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.

indentation and lines are not needed for the language, but make code easier readable.

You'll be mastering these 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 var named profit which receives an initial value of 50, and an if statement. If profit is greater than 100, 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 "myscript3.c" in the Strategy folder, select and
[Test] it:

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

function main()
{
  var profit = slider(3,50,0,200,"Profit",0);
  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 "Profit". Move it all the way to the right, so that 200 appears in the small window, and click [Test] again:

What happened? The slider() function put its return value - which is the value from the bottom slider - into the profit variable, and thus the if(..) 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). 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 100 or below. You can now imagine how we can use the sliders for adjusting variables for our strategies.

Now let's assume that you want to do something only when two different conditions are fulfilled. Try the following program:

function main()
{
  var profit = slider(3,50,0,200,"Profit",0);
  var loss = slider(2,25,0,200,"Loss",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. That means both conditions must be true for the combination to be true. There is also an "or" keyword when only one of the conditions needs be true.**

Now, I'm giving you three important tips for avoiding coding mistakes in expressions and comparisons.

Have you noted the use of parentheses around (profit > 50) and (loss == 0)? We know from school mathematics that in a mathematical equation, the expressions in the parentheses are solved first. (1+2)*3 is not the same as 1 + (2*3) - 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. That was the first tip.

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

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

will set loss to zero instead of comparing loss 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!

if(a == 3) // correct
{
    // do_some_stuff
}

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

You can avoid this mistake is 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:

if(0 == loss) // correct
    ...

If you then accidentally put a single '=' instead of '==', the computer 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 '==' comparison with care when comparing var variables. If a computer calculates a mathematical expression, the result is usually inaccurate due to the limited floating point precision. Instead of 2, the square root of 4 might be 2.000001 or 1.999997. If you then compare it with 2, the comparison will come out false. Generally when comparing values with many decimals. such as prices, it's highly unlikely that two such values will be ever exactly equal. Normally you'll only use 'greater' or 'smaller' comparisons (< or >) with var variables. This problem does not affect int variables, as they have no decimals and can indeed be exactly equal.

Expressions

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:

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

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

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

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: Loops.

While loops

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:

while (my_money < 1000000)
    trade(my_money);

The while statement has the same syntax as the if statement. There is some expression - in this case the condition that the variable my_money is less than a million - and a command that is executed when the expression is true. However, in the case of an if statement, the program whould then go on with executing the next command afterwards. In the case of a while 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 "loop" is called so because the program runs in a circle. Here's the basic form of the while loop:

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

or

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

Note that whatever the commands do, they must somehow affect the while 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()
{
  int n = 0; 
  while(n < 10) { 
    n = n + 1;
    printf("%i ",n);
  }
} 

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

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.

And there's more...

We are now at the end of the three basic workshops that teach general programming. In the next workshops we'll begin with developing trade 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, structs, classes, or the Windows API. lite-C also supports some elements from C++, the 'big brother' of C - such as methods or function overloading.

If you want, you can learn 'real' programming beyond the scope of trade strategies. Buy a C book or go through a free online C tutorial, such as Sam's Teach Yourself C in 24 Hours. You can also join the Gamestudio community that uses Zorro's lite-C language for programming small or large computer games. Check out how a 'real' C program looks like: open and run the script Mandelbrot. 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.

Next: Trend Trading


** C/C++ programmers might wonder why they have to use and and or instead of the familiar operators && and ||. Don't worry, all C operators work as before, we're just using easier-to-memorize operators for beginner's sake.

Further reading: ► if, for, slider