Strategy Coding Tutorial

A script describes the trading rules of a strategy in code - a sort of simplified language. Theoretically, there could be other ways to define trading rules, for instance with a visual strategy builder, or by entering formulas in a spreadsheet program. Unfortunately, this way only rather primitive strategies can be created, with no real success chance in today's financial markets. All known successful automated strategies are programmed or scripted, and underwent a solid development, optimization, and test process.

The disadvantage of script is obviously that you have to learn the script language. You do not need to dive deep into programming, but a certain learning process can't be avoided. If you want to be successful with algorithmic trading, you're competing with traders that already know coding and statistics. Code illiteracy would put you at a large disadvantage in this game.

A simple strategy script, coded in the language C, looks as shown below. This strategy uses two simple moving averages (SMA) with 30 and 100 bars time period, places a stop at 10 pip distance, and buys a long or short position when the faster average crosses over or under the slower average:

function run()
{
  vars Close = series(priceClose());
  vars SMA100 = series(SMA(Close,100));
  vars SMA30 = series(SMA(Close,30));


  if(crossOver(SMA30,SMA100))
    enterLong();
  if(crossUnder(SMA30,SMA100))
    enterShort();
}

C is used for strategy scripts because it's the fastest high-level language and most software today is written in C or C++. For the same reason, most trade platforms use C or a C variant for automated trading. The first 3 workshops will give you an introduction into formulating simple tasks in C code - also called coding. The next 4 workshops are about developing and optimizing trading strategies. For testing the examples, you can use the free Zorro platform (if you don't have Zorro yet, get it from zorro-project.com). The 7 workshops are an excerpt of the much more detailed and comprehensive strategy development course in the Black Book. For going even deeper into the matter, enter the online course that can be found on the Zorro download page. When you need further help with coding a particular strategy, contact our development service.

Zorro gives you the choice to develop strategy scripts either in lite-C, a 'lightweight' version of the C programming language, or in 'full' C++ using a professional development system such as Microsoft Visual Studio. If you're new to programming, start with lite-C. The 'lite' just means it contains a framework that hides the complex stuff - API calls, pointers, structs, etc. - that is difficult to beginners. lite-C was originally developed for the computer game company Atari for controlling the artificial intelligence of actors in computer games. As you can imagine, a language powerful enough to control simultaneously ten thousands of actors in a virtual world, and at the same time easy enough to be used by computer gamers for the behavior of their agents, is an excellent choice for trading strategies. Once familiar with C, you can use your programming knowledge not only for C based trading strategies. Since most languages have a similar structure, you'll also be able to at least understand code in Python, Pascal, or Tradestation's EasyLanguage, even though the latter generates a variable not with var x = 7, but with Vars: x(7).

If you already know C, you can skip the first 3 workshops. If you already know interpreter languages like R or Python, you'll notice soon that a compiled language like C has a crucial advantage for trading system development: It is much faster. A script in C will need only a few seconds for a high-resolution backtest. The same script in Python would need hours.

Here's our curriculum:

Although the strategies in this tutorial are profitable in the backtests, they are meant for educational purposes only and are designed for simplicity, not for maximizing profit and minimizing risk. For trading with real money, better develop your own strategies.

Workshop 1: Variables

A script (or program) is a list of instructions in plain text format that tell the computer what to do under which circumstances. It consists of two types of objects, variables and functions. A variable is used to store numbers, text, or other information. It must be defined before it can be used, like this:

var Price;
int Days = 7;
string Wealth = "I am rich!";
bool Winning = true;

Variables can have different types for different purposes, such as var (or double) for prices, vars for a time series, int for counting, or string for text. You can find details about the different types here. Any variable can receive an initial value at start.

We can add comments to explain our code, using two slashes. Example:

int bar_width; // the width of one bar in minutes

Often we temporarily disable a line in the script by placing two slashes in front of it. This is called "commenting out" a line, and is used so frequently in programming 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. If you forget to add ";" at the end of the line of code, you'll see an error message - not for the line with the missing semicolon, but for the following line!

The first script

Start Zorro, select Workshop1 in the Script dropdown menu, then press [Edit]. The strategy script editor opens up and shows you this script:

// Tutorial Workshop 1: Variables
////////////////////////////////////////

function main()
{
  var a = 1;
  var b = 2;
  var c;

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

The script begins with a comment (the lines beginning with //). Then we have a function named main - everything that happens in a program is inside a function. In the next lines we can see that three variables a, b, c are defined. The action happens in the following line:

c = a + b;

This is a command (also called instruction) to the computer to add the content of the variables a and b, and store the result in the variable c. The last line is also a command, used for displaying the content of c in the message window:

printf("Result = %.f",c);

Now press [Test] on Zorro's panel and watch the script running.

Workshop 2: Functions

Functions are 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, if required. The body of the function is written inside a pair of winged brackets { }. The body consists of one or more lines of C code that end with a semicolon. Programmers usually indent the code in the function body by some spaces or a tab, for making clear that it is inside something.

Zorro follows the convention to use lowercase names for functions (except for indicators, such as EMA), 'CamelCase' names for variables, and UPPERCASE names for predefined numbers. An example of a function that computes the number of days spent by me (or you) on Earth:

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);
}

Enter this code in a new empty script, and save it (File / Save As) into the Strategy folder under a name like Myscript.c (don't forget the ".c" at the end - it means that this file contains C code). You should now find Myscript in the Script scrollbox. When you now select it and click [Test], you 'll get an error message "No main or run function!".

If a function is named main, it will automatically start when we start the script. The function named run is special to Zorro; it normally contains our trade strategy and is automatically run once for every bar 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.

So enter a main function at the end of the script:

function main()
{
   compute_days();
}

This code 'calls' (meaning it executes) our compute_days function. For calling a function, we write its name followed by a pair of parenthesis and then we end the line of code with a semicolon. Write the code for your functions first and and the code that calls them later. The computer reads code from the top of the script down to the bottom, line by line. Don't call or refer to something that was not defined before, or else you will get an error message.

You will anyway encounter compiler errors frequently when you write scripts - even experienced programmers make little mistakes all the time. Sometimes it's a forgotten definition, sometimes a missing semicolon or bracket. Get used to compiler errors and don't be helpless when you see one. The computer (usually) tells you what's wrong and at which line in the script, so you won't need rocket science for fixing it.

Passing variables to and from functions

A function can also get variables or values from the calling function, use them for its calculation, and give the resulting value back in return. Example:

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

The var age between the parentheses is for passing a value to the function. This is our new script with passing variables to and from functions:

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);
}

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. Check out the printf function in the manual.

When a function returns a var, we can just place a call to 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::

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

 !!  Important tip when you call functions in your code that return something. Do not forget the parentheses - especially when the parameter list is empty! In C, an function name without parentheses means the address of that function in the computer memory. add_numbers and add_numbers() are both valid and won't give an error message in the code! But they are something entirely different.

Workshop 3: Branches and Loops

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 simplest 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
} else {
    // execute one or several commands that are placed inside these curly brackets
}

A practical example:

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

When you click [Test] to run that script, 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. You can see that the result is now different. The slider() function has 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 bigger than 100. You can see details of the slider function in the manual.

While loops

An example of a "while loop":

while(my_money < 1000000)
    trade(my_money);

The while statement has the same syntax as the if statement. A "loop" is called so because the program runs in a circle. Here's the form of a while loop:

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

Whatever those commands do, they must somehow affect the while condition, because when the condition never changes, we have an "infinite loop" that never ends! 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 basic workshops that teach general programming. A more in-depth introduction can be found in the Black Book. And we haven't touched yet concepts such as macros, pointers, arrays, structs, classes, or the Windows API. You can learn 'real' programming beyond the scope of trade strategies with a C book or a free online C tutorial, such as Sam's Teach Yourself C in 24 Hours. You can also join the Gamestudio community that uses the lite-C language for programming small or large computer games. Check out how a 'real' C program looks like: open and run the included 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 can be a lot more fun even without earning money with it.

In the next workshops we'll begin developing trade strategies; you've already learned all basic programming stuff that you'll need for those lessons.

 

Next: Trading


Further reading: ► Variables. Expressions. Functions, return, printf. if, for, slider.