Automated Trading Course - Part 1: Programming

Discussion in 'Automated Trading' started by jcl, Sep 8, 2012.

  1. u wan to learn hw to automate an algo that prints money every 3 hours.

    So u wait here. I will spoon feed and teach you and everyone else !!! U wait.. wait..
     
    #21     Sep 10, 2012
  2. What's the %.f for?




     
    #22     Sep 10, 2012
  3. jcl

    jcl

    The %.f in the printf function is a placeholder. In the printed text, it is replaced by the content of a var passed to that function. We'll come to the printf function tomorrow. For today, we'll look into functions in general. 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:

    Code:
    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 function followed by the name of the function and a pair of parentheses (). 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 body of the function (its list of commands) must be written inside a pair of winged brackets { }. 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 function and then the name of the function; let's name it compute_days:

    function compute_days()
    {


    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:

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


    Nothing new so far, right? We have defined two var variables and they have received initial values, because I know my age in years and I also know that every year has about 365.25 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:

    33 * 365.25 =

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

    number_of_days = my_age * days_a_year;

    Ok, so our function should end like this:

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


    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:

    Code:
    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 myscript2.c. Don't forget the ".c" at the end - it means that this file contains C code.

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

    [​IMG]

    Does this error message mean that a script always need a main() or run() function? Yes, main is a predefined function name. If a function is named main, it will automatically run when we start our script. The function named run is special to Zorro; it contains our trade strategy and is automatically run once for every time period. If a script has neither a main nor a run 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:

    Code:
    function main()
    {
      compute_days();
    }
    The way I see it, this code 'calls' (meaning it starts) our compute_days 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?

    [​IMG]

    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:

    Code:
    function main()
    {
      compute_days();
    }
    
    function compute_days()
    {
      ... 
    }
    the computer will say: oh, that's function main. I know function main; I need to run it every time. What does it say now? compute_days(). 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'll take the rest of the day off.

    [​IMG]

    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.
     
    #23     Sep 10, 2012
  4. as a C# programmer myself, you're doing a great job in explaining basic c programming.
     
    #24     Sep 10, 2012
  5. jcl

    jcl

    Thanks! A short summary of the new things we've learned yesterday :

    ► We define functions by writing "function name(...) { ... }" in the script.

    ► If a function has the name main or run, 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.

    Code:
    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 return 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 "function", but with "var"? But is var 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 int, define it with int; if it returns a var, define it with var. Still, the computer knows from the (..) 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:

    Code:
    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 number_of_days variable direct from the returned value by compute_days(my_age). This makes our code shorter and more elegant! Still, the result is the same:

    [​IMG]


    Now what is this mysterious printf(..)? 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 "I am %.f days old!",number_of_days are the two variables that we pass to the printf function. The first variable is a string, used for displaying some text: "I am %.f days old!". The second variable is a var: number_of_days. Variables passed to functions are separated by commas. You can read details about the printf 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 "%.f" in the string is a placeholder. It means: the function inserts here the value - with no decimals - of the var that is passed to the function. So, if number_of_days has the value 12045, our printf function will print "I am 12045 days old!".

    We can make our code even shorter. Remember, if a function returns a var, we can just place a call of this function in stead of the var 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:

    Code:
    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 first trade strategy.

    Please let me know if something was unclear with passing variables to and from functions.
     
    #25     Sep 11, 2012
  6. Daal

    Daal

    OP, which compiler are you using?
     
    #26     Sep 11, 2012
  7. jcl

    jcl

    lite-C.
     
    #27     Sep 11, 2012
  8. jcl

    jcl

    For this and the next lesson, you'll need a slightly newer Zorro, as the version from the downloaded beta release had two small bugs that affected the slider set-up and the chart display. There's a patch available. Please go to the Zorro website (google for "Zorro Trading Automaton"), and download the 0.99.4 patch from the "Starting with Zorro" section of the user forum.

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

    Code:
    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:

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

    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.

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

    Code:
    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:

    [​IMG]

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

    Code:
    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 "Profit". Move it all the way to the left, so that 200 appears in the small window on the right, and click [Test] again:

    [​IMG]

    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). 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 100 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 automated trade strategy. Please mention here if something was unclear so far.
     
    #28     Sep 12, 2012
  9. jcl

    jcl

    I just noticed that while copying the stuff from another forum, some conversion software has inserted a couple '*' characters in the last two code examples. So make sure to delete the '*' when you copy/paste the examples to Zorro.
     
    #29     Sep 12, 2012
  10. Humpy

    Humpy

    Sounds good
     
    #30     Sep 12, 2012