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. Investing

    What's a Sensitivity Analysis?

    Sensitivity analysis is used in financial modeling to determine how one variable (the target variable) may be affected by changes in another variable (the input variable).
  3. 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.
  4. Financial Advisor

    Variable Annuities: The Pros and Cons

    Variable annuities are one of the most complicated financial instruments. Here is an in depth look at their pros and cons.
  5. Taxes

    Making Sense Of The Tax Code

    If tax rules and regulations are Greek to you, read on to learn how to decipher them.
  6. Retirement

    How a Variable Annuity Works After Retirement

    These investments can provide extra income after you retire. Here’s a guide to when and how you will receive the payout.
Frequently Asked Questions
  1. I'm about to retire. If I pay off my mortgage with after-tax money I have saved, I can save 6.5%. Should I do this?

    Only you and your financial advisor, family, accountant, etc. can answer the "should I?" question because there are many ...
  2. My wife and I both converted our Traditional IRAs to Roth IRAs over a decade ago and have invested the maximum allowed each year since. We're buying our first home soon. Do we both qualify for one-time, tax-free, $10,000 distributions?

    You and your spouse each qualify for a penalty-free distribution of up to $10,000 for the purchase, acquisition or construction ...
  3. Is a Thrift Savings Plan (TSP) a qualified retirement plan?

    Take advantage of the government's retirement plan for employees with the Thrift Savings Plan. As with a 401(k), contributions ...
  4. Who manages the assets in a Roth 401(k) account?

    Learn how to personally manage the assets in your Roth 401(k) plan and determine the best options available to help meet ...
Trading Center