Trading Systems Coding: The Coding Process
  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

Trading Systems Coding: The Coding Process

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

  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
  1. Indicator

    Indicators are statistics used to measure current conditions ...
  2. Intraday Momentum Index (IMI)

    A technical indicator that combines aspects of candlestick analysis ...
  3. Money Flow Index - MFI

    A momentum indicator that uses a stock’s price and volume to ...
  4. OsMA

    An abbreviation for Oscillator - Moving Average. OsMA is used ...
  5. Triple Exponential Average - TRIX

    A momentum indicator used by technical traders that shows the ...
  6. Hybrid Indicator

    A technical indicator that combines core elements of chart analysis ...
  1. How do quant traders build the relative strength index (RSI) into their algorithms?

    Learn how quantitative traders build the relative strength index (RSI) into their algorithms. Explore how automated trading ... Read Answer >>
  2. How do you know where on the oscillator you should make a purchase or sale?

    Learn more about oscillator indicators, technical momentum measures that are used by traders to predict potential market ... Read Answer >>
  3. How do I Implement a Forex Strategy when spotting a Sanku (Three Gaps) Pattern?

    Understand the significance of the sanku candlestick pattern, and learn a forex trading strategy to employ when recognizing ... Read Answer >>
  4. How effective is creating trade entries after spotting a Tri-Star pattern?

    Learn about the tri-star pattern and how to use corroborating reversal signals from other technical indicators to build effective ... Read Answer >>
  5. What are the most popular forms of technical analysis?

    Technical analysis approaches the market by studying price and volume. It yields radically different insights and conjectures ... Read Answer >>
  6. What are the most common market indicators forex traders follow?

    Learn the most common technical indicators that forex traders and currency market analysts utilize to predict likely market ... Read Answer >>

You May Also Like

Hot Definitions
  1. Keynesian Economics

    An economic theory of total spending in the economy and its effects on output and inflation. Keynesian economics was developed ...
  2. Society for Worldwide Interbank Financial Telecommunications ...

    A member-owned cooperative that provides safe and secure financial transactions for its members. Established in 1973, the ...
  3. Generally Accepted Accounting Principles - GAAP

    The common set of accounting principles, standards and procedures that companies use to compile their financial statements. ...
  4. DuPont Analysis

    A method of performance measurement that was started by the DuPont Corporation in the 1920s. With this method, assets are ...
  5. Call Option

    An agreement that gives an investor the right (but not the obligation) to buy a stock, bond, commodity, or other instrument ...
  6. Economies Of Scale

    Economies of scale is the cost advantage that arises with increased output of a product. Economies of scale arise because ...
Trading Center