1. Trading Systems Coding: Introduction
  2. Trading Systems Coding: System Design
  3. Trading Systems Coding: The Coding Stage
  4. Trading Systems Coding: The Coding Process
  5. Trading Systems Coding: Testing, Troubleshooting and Optimizing
  6. Trading Systems Coding: Using Your System
  7. Trading Systems Coding: Conclusion

By Justin Kuepper
Contact Justin

By now you should have a design in hand as well as a basic idea of what the code looks like. In this section, we'll take a more in-depth look at how a program is created. After reading this section, you should be able to understand basic program structure and be able to convert your design to code!

An Overview
There are two basic parts to a program:

  • Variables - These are items that hold data. This can be data that you collect from the user, or any other data.
  • Statements - These form the core of the program. Statements manipulate the data to get results that can be converted to actions.
In addition to these core components, there are also several optional components:
  • Functions - These are simply collections of related statements that can be used to perform a specific task. For example, a function telling you when to buy might include a statement to check whether you have enough money, a statement to determine whether it meets your criteria and a statement to place the order. A function combines these, allowing you to simply call on the function instead of rewriting these statements each time you want to buy.
  • Arrays - These are simply data structures that hold similar data and enable you to access and manipulate the data more efficiently.
A Look at Variables
Variables are simply objects that you define to hold data. You may recall from the previous section that we used three variables: MATrendPeriod, MaCurrent and MaPrior. MATrendPeriod held a number that defined how many days we would use in our moving average calculation; MaCurrent held a number representing the current moving average; and MaPrior held a number representing the prior moving average.

Creating a Variable
You can use almost any name you want when naming a variable. The only exception is a list of ''restricted words'' that you are not allowed to use because the names are already used by other parts of the program. You can find your trading program's list of restricted words in the program's documentation. In general, names should describe the data being held. For example, notice that we used MaCurrent to define the current moving average.

After you have created a name, you must declare and define the variable. Declaring a variable tells the computer what type of data it is, and tells it to make space for that data. Defining the variable is where actual data is assigned, or added, to the variable. Let's take a look at these processes:

1. Declaring a Variable

In MetaTrader, variables are declared automatically when you assign information to them. In other programs, you may have to declare a variable, which is typically done using the following format:

<data type> <variable name>;

The two types of data are numbers and text, but these are broken down into more groups like integers (whole numbers), double (large numbers), float (decimal numbers), string (text), and others depending on the program you are using. For example, the following code will declare numberOfDays as an integer:

Int numberOfDays;

2. Defining a Variable
After your variable has been declared, the computer has created space for it. Now, all you have to do is add actual data to that space. This can be done in two ways: you can either define a set amount, or you can perform a calculation to obtain a value, which you then assign to the variable.

In MetaTrader, you can add set data using the following format:

Defines: <variable name>(<set amount>);

In other programs, set data is often assigned simply using the equals sign:

<variable name> = <set amount>;

If you want to perform a calculation to obtain data to assign to the variable, then you simply assign the variable to the calculation:

<variable name> = <calculation>;

For example, to set a 20-day moving average in MetaTrader, we use the following code:

<variable name> = iMA(20,MODE_SMA,0);

Note that the iMA(20,MODE_SMA,0) portion of the code is the calculation. The format for this calculation was developed by MetaTrader and will differ if you are using another trading program. To find these calculations, you must consult your trading program's documentation, which usually contains a list of all available calculations.

3. Using Variables

Once declared and defined, variables can be used anywhere else within the program to represent the data they contain. To do this, simple type the name of the variable in place of the data. For example, if MATrendPeriod contains the number of days we want a moving average calculated for, we can use it to replace the 20 in our example above:

<variable name> = iMA(MATrendPeriod, MODE_SMA, 0);

There are two advantages to using variables as opposed to just the data: (1) you can change the data in one place, and (2) the result of an entire calculation can be contained within one variable.

A Look at Statements
Statements are the core of any program - they contain all of the commands that manipulate data to make decisions. Here we will take a look at several of the most common types of statements and how they can be used.

If you have designed a complex trading system, it may take a lot of code to implement your rules; therefore, it would be prudent to insert comments in your code to help yourself understand it in the future, and to help out anyone with whom you may share your code. Almost all trading applications share a similar method for creating comments:

Single Line Comments:

//<your comment here>

Multi-Line Comments:

/* <comment line one>
<comment line two>
<comment line three> */

2. The 'If' Statement
This is the statement you will use most when coding a trading system. This statement lets you create scenarios as we did in the design portion of this tutorial. You may have also noticed that this was the only statement we used in the example program we created. This type of statement is implemented using the following format:

Standard If/Then:

If <condition> Then <action>;

Standard If/Else:

If <condition> Then <action> Else <action>;

So, for example:

If accountBalance < 200 then Exit;

Note that the conditional part of the 'If' statement is constructed using the following:

<object one> <condition> <object two>

The condition can be:

· Greater Than (>)
· Less Than (<)
· Equal To (=). Note that one '=' assigns, two '==' returns either true or false.

3. The While Loop
This loop is commonly used to tell the computer to continue doing something while a certain condition is true or false. So, for example, maybe you want to have the trading system keep a position open while your account is above a certain balance, but close it if it ever falls below that balance. These statements are created using the following format:

While <condition> <action>;

4. The Exit and/or End Statement
An 'Exit' or 'End' statement is used to indicate to the computer that your program will be ending at that particular point. Typically, this is done using:


These are usually placed in the 'If' statements if that statement is executed so that the computer doesn't continue to look at the rest of the 'If' statements.

Trading System Implementation
Note that different trading applications will differ slightly in how they implement statements. For example, in some trading applications, the 'If' statement is constructed by using:

If (<condition>, <then do this>, <else do this>);

Meanwhile, other applications may split up this code into two parts:

If (<condition>) { <then do this> } else { <else do this> };

We can see that the same idea is present, but the implementation differs. It is important to consult your trading application's documentation, or application programming interface (API), to determine what differences exist.

Putting It All Together
Now you should have an idea of the different components that can be used when coding your trading system. All that remains to be done is to put everything together. To do this, simply take your design document and determine the following:

  • What variables will I have to define?
    • Calculations à Moving averages, RSI, MACD, etc.
    • Set Amounts à Time periods, deposit amounts, risk percentages, etc.
  • What statements will I have to make?
    • Convert your rules to the proper statements using the above guides.
Once you know this, all you need to do is piece together all of the parts. The standard structure for a program is:


Now you should have a basic idea of how to put your trading system into code. Be sure to consult your trading application's documentation often, as it may contain pre-built calculations that you can use, code examples and much more that can help you to better understand the specifics. In the next part of this tutorial, we'll take a look at testing your new program both technically (to find errors in the code) and theoretically (to find errors in your logic).

Trading Systems Coding: Testing, Troubleshooting and Optimizing
Related Articles
  1. Investing

    Stock and Flow Variables Explained: A Closer Look at Apple

    The difference between stock and flow variables is an essential concept in finance and economics. We illustrate with financial statements from Apple Inc.
  2. Insights

    Understanding Regression

    Regression is a statistical analysis that attempts to predict the effect of one or more variables on another variable.
  3. Financial Advisor

    Variable Annuity Basics

    Find out how variable annuities can help you plan for retirement by offering the returns of the stock market with the guarantee of insurance.
  4. Trading

    Trading Systems Coding

    Automate your trades by translating your strategy into a language your computer can implement in this hands-free approach to investing.
  5. Retirement

    Variable Annuities: The Do-It-Yourself Pension Plan

    Variable annuities can cost more than mutual funds, but that might be worth the protection they can add to your retirement.
  6. Financial Advisor

    Variable Vs. Variable Universal Life Insurance

    Do you know why you might need one policy versus the other? Read on to find out.
Frequently Asked Questions
  1. What's considered to be a good debt-to-income (DTI) ratio?

    Your debt-to-income ratio helps lenders determine your credit worthiness. Find out how to calculate your score and how to ...
  2. What is the difference between a loan and a line of credit?

    Learn to differentiate between lines of credit and standard loans, and determine when you are likely to use each method of ...
  3. What does a Chief Financial Officer (CFO) do?

    A CFO is responsible for accurate reporting of a company's financial information, investing the company's money and identifying ...
  4. How did George Soros break the Bank of England?

    George Soros pocketed $1 billion by betting against the British pound, cementing his reputation as the premier currency speculator ...
Trading Center