Documents
Resources
Learning Center
Upload
Plans & pricing Sign in
Sign Out

TSD_Manual

VIEWS: 6 PAGES: 55

									Trade System Designer
       User’s Manual
        Version 0.20


    www.tradesystemdesigner.com
                                         Table of Contents
1.     Introduction _________________________________________________________________ 2
2.     An Overview of Trade System Designer ___________________________________________ 3
     2.1.       TSD.dll _______________________________________________________________________ 3
     2.2.       TSDOptimizer.exe ______________________________________________________________ 3
     2.3.       TSDTrader.exe_________________________________________________________________ 4
     2.4.       Systems _______________________________________________________________________ 5
3.     The five minute Lua primer_____________________________________________________ 6
     3.1.       Comments: ____________________________________________________________________ 6
     3.2.       Identifiers: ____________________________________________________________________ 6
     3.3.       Keywords: ____________________________________________________________________ 7
     3.4.       Types: ________________________________________________________________________ 7
     3.5.       Operators: ____________________________________________________________________ 7
     3.6.       Visibility of variables: ___________________________________________________________ 8
4.     TSDOptimizer________________________________________________________________ 9
     4.1.       Main Tab _____________________________________________________________________ 9
       4.1.1.     Menus _____________________________________________________________________________ 10
       4.1.2.     Optimization ________________________________________________________________________ 12
       4.1.3.     VCR Functionality ___________________________________________________________________ 14
     4.2.       Security Settings Tab___________________________________________________________ 15
     4.3.       Analysis Tab__________________________________________________________________ 16
     4.4.       Global Settings Tab ____________________________________________________________ 17
     4.5.       DLL Info Tab_________________________________________________________________ 18
     4.6.       Price Graph __________________________________________________________________ 19
     4.7.       Tick Price Graph ______________________________________________________________ 20
5.     Creating a MetaStock Indicator ________________________________________________ 21
     5.1.       TSD Demo_TrendLines6 _______________________________________________________ 22
     5.2.       What could go wrong? _________________________________________________________ 23
6.     TSD’s Extensions to the Lua Language __________________________________________ 24
     6.1.       Variable Types ________________________________________________________________ 24
       6.1.1.     DataArray __________________________________________________________________________ 24
       6.1.2.     UserVar____________________________________________________________________________ 29
     6.2.       New Functions ________________________________________________________________ 30
7.     A Dissection of SystemDemo_MACrossover.lua ___________________________________ 31
Appendix A – Indicator functions ___________________________________________________ 33
Appendix B – SystemDemo_MACrossover.lua_________________________________________ 51



                                                       1
1. Introduction
Trade System Designer (TSD) is a system which enables the design and implementation of highly
customizable Expert Advisors (EA) and Indicators for MetaStock. The MetaStock Developer’s Kit is
not required to develop these systems.

TSD is written in C/C++ and uses the embedded scripting language Lua (www.lua.org) to execute
your custom code. While developing an EA or Indicator, the Lua code may be modified and saved
without closing TSDOptimizer, and the changes will take effect immediately.

The indicators built in to TSD come from the open-source library TA-LIB (http://www.ta-lib.org).

SQLite (www.sqlite.org) is used to store persistant settings, customizable to each security. This
allows your code to be optimized for each security, as well as timeframe (the settings for 30 minute
AUDUSD are separate from the settings for daily AUDUSD).




                           TSDOptimizer         (via network)    TSDTrader          FXCM




   MetaStock                 TSD DLL                  Settings
                                                      Files


                             User’s Lua
                             code

Figure 1 - TSD Map




                                                  2
2. An Overview of Trade System Designer
TSD consists of two separate executables, several Lua files, and one MetaStock DLL:

FileName                         Installation Location
TSD.dll                          PF\ \Equis\MetaStock\External Function DLLs
TSDOptimizer.exe                 PF\Trade System Designer
TSDTrader.exe                    PF\ Trade System Designer
SystemDemo_*.lua                 DS\UserName\ Application Data\Trade System Designer
TrailingStops.lua                DS\UserName\ Application Data\Trade System Designer
Utilities.lua                    DS\UserName\ Application Data\Trade System Designer
Note: PF = The computer’s “Program Files” directory
       DS = The computer’s “Documents and Settings” directory

During the execution of a TSD Expert or Indicator, a database file will be created for each System in
the directory “DS\UserName\ Application Data\Trade System Designer”. This one file will contain
all the settings for all securities for that System.


2.1. TSD.dll

TSD.dll is loaded by MetaStock to execute your custom Systems. There are only three functions
visible to MetaStock from TSD: Execute, and GetIndicator, and SetIndicator.

Execute runs your System and produces all the output. It returns no indicators or data back to
MetaStock. GetIndicator is used to retrieve all the indicators after Execute has run. Each indicator
has its own name (ie. “BearTrendTarget”) assigned by the System (your program). SetIndicator may
be used to push indicators from MetaStock into your System.

Therefore, to create an EA, only a few lines of code are needed in MetaStock.
Detailed instructions for use are provided in section 5 “Creating a MetaStock Indicator” of this
manual.


2.2. TSDOptimizer.exe

TSDOptimizer is a very powerful front-end to the DLL to allow development and optimization
outside of the MetaStock environment. It consists of four main windows: the Program window, the
Security Data window, the Tick Data window, and the Optimizing window. When first started, the
Tick Data and Optimizing windows are not displayed. The Program and Optimizing windows are a
fixed size, but the Security Data and Tick Data windows are resizable.

Using TSDOptimizer, new Systems can be tested right down to the tick, using the VCR capability to
“play” the data through the System one bar or tick at a time. This can be important to verify that a
system doesn’t “cheat” by changing past entries and exits. This type of cheating is not obvious when
testing an entire range of data at once, because only the final results will be displayed.

                                                   3
2.3. TSDTrader.exe

NOTE:
TSDTrader is not considered complete enough for shipping at this time. It will be included in a
future release of TSD.

TSDTrader will automatically place trades with an online broker. It communicates with TSD.dll
while MetaStock is running to determine the status of the securities, and places the order as each
status changes.

TSDTrader supports multiple accounts and multiple securities simultaneously.

At the moment, the only vendor supported is FXCM.




Figure 2 - TSDTrader




                                                  4
2.4. Systems

A System is one or more indicators with or without an EA. When MetaStock calls TSD’s Execute
function, all indicators and the EA are computed and the results are retained for future GetIndicator
calls.

From a programming point of view, a System consists of one or more Lua files, with one being
named SystemXXX.lua, where XXX is a descriptive term for that system. For example, the Moving
Average Crossing demo System’s file is named SystemDemo_MACrossing.lua. TSDOptimizer will
search the user’s directory for all Lua files beginning with “System” and add them to its System
menu, after removing “System” from the name. So, SystemDemo_MACrossing will show up as
“Demo_MACrossing” in the menu. This is also how MetaStock will refer to the system.

Furthermore, notice the name of the file starts with “System”. This is a requirement of all System
files. The name of the function within that file is the same as the file name:
SystemDemo_MACrossover. This is also a requirement. Other files that have reusable code (used in
multiple Systems) may be named anything, and their function names do not have to match the file
names. For example the file “TrailingStops.lua” has the functions “TrailingStopsInit” and
“TrailingStops” in it. These functions may be used by any System, but do not show up in
TSDOptimizer’s menu and are not directly callable by MetaStock.




                                                   5
3. The five minute Lua primer
This section is aimed mainly at experienced programmers unfamiliar with the Lua language. It
covers just the basic syntax so that the later discussions can be understood. There is no attempt at
teaching Lua or programming in general in this manual.

For more in-depth coverage of the Lua language, the book “Programming in Lua” by Roberto
Ierusalimschy is recommended. The Lua web site (www.lua.org) also has documentation and
tutorials available.


3.1. Comments:
Comments embedded in the code are ignored during execution. They are there as notes to the
programmer. There are two types of comments in Lua, the single-line comment, and the multi-line
(block) comment.

The single-line comment starts with two dashes (minus symbols): --
The following line is a comment:

-- This is a comment

Comments can also be placed at the end of a line of code:

currentBarTime = thisBarTime -- Set the value of currentBarTime

The block comment starts with --[[ and ends with ]] (or --]]). The following is a block
comment:

--[[ This is a comment.
     Continued comment.
     Even more comment.
]]


3.2. Identifiers:
An identifier (variable) can be named by any string of letters, digits, and underscores which do not
begin with a number. The identifier startLoop10 is valid, but 3StartLoop is not. They are
case sensitive, so startLoop, StartLoop, and startloop are three different identifiers.




                                                   6
3.3. Keywords:
The following are keywords reserved by Lua, and cannot be used otherwise:

and, break, do, else, elseif, end, false, for, function, if, in,
local, nil, not, or, repeat, return, then, true, until, while.


3.4. Types:
      Warning, geek talk ahead! If you are not a programmer and the explanation below means
      nothing to you, it’s fine. Just remember that you don’t have to tell a variable that it’s a number
      or text or a DataArray. It just knows.

Lua is a dynamically typed language: there are no explicit types. Each identifier remembers its own
type. The types built into Lua are: nil, boolean, number, string, userdata, function, thread, and table.

When writing programs for TSD, typically only boolean, number, string and the additional TSD types
DataArray and UserVar are needed. The rest can safely be ignored.


3.5. Operators:
The following are relational operators in Lua:
<     Less than
>     Greater than
<=    Less than or equal to
>=    Greater than or equal to
==    Equals (does one variable equals another?)
~=    Not equals

The following are logical operators in Lua:
and, or, not

The assignment operator is a single equals sign: = (Sets one variable equal to another)

Be careful not to mix “==” for “=” when testing for equality:

-- Incorrect!
if (variable1 = variable2) then
    doSomething
end

-- Correct!
if (variable1 == variable2) then
    doSomething
end




                                                    7
3.6. Visibility of variables:
All variables in Lua are global by default, unless explicitly declared local or passed as parameters to a
function.

Global variables may be used anywhere within the same program, even across files.
Local variables are limited in scope to the block in which it was declared. To declare a variable as
local, simply precede the variable name with the keyword local:

function TestFunction()
    -- loopCount is visible outside the while loop,
    -- but not outside this function
    local loopCount = 0

      while loopCount < 10 do
          -- tempVariable1 is visible globally, even outside this function
          tempVariable1 = 500
          -- tempVariable2 is visible only within this while loop
          local tempVariable2 = 100
      end
end




                                                   8
        4. TSDOptimizer
        TSDOptimizer is a stand-alone program, and does not require MetaStock to run. It is this program
        that is used to create and debug new Systems and Indicators.

        There are three separate windows that make up TSDOptimizer:
           • the program window, as seen in Figure 3
           • the price graph, as seen in Figure 10
           • the tick price graph, as seen in Figure 11

        The tick price graph is not initially displayed at program start up. It is shown by clicking the “Show
        Ticks” button on TSDOptimizer’s main page.


        4.1. Main Tab

    A




B
                                C
                                                                                                      H


                                                                                                                 I

                                                                             G
                        E

                                                F
D
                  K         L                                                                             J
                                                                                     M
        Figure 3 – TSDOptimizer’s main page



        The title bar of the main program window displays the program name, the version number, and the
        currently selected System.

        A. Menus
           There are several menus available. See section 4.1.1 for details.
        B. Tabs
           Each tab displays a new page on TSDOptimizer. Each tab is described seperately in this chapter.
        C. Securities



                                                           9
   This is a list box which displays all available securities according to the time interval chosen, the
   data type (historical or MetaStock), and the Data Cache Path (set on the Global Settings tab).
   Clicking on one of the securities in the list will select and display it.
D. Zoom Buttons
   These buttons will cause the price display to zoom in and out.
         • “+” zooms in by one level
         • “++” zooms in as far as possible
         • “-“ zooms out by one level
         • “--“ zooms out as far as possible (displays the entire time range)
E. Price Bar Information
   This grid displays the details of the price bar the cursor (thin green line) is currently over on the
   price display. This will update in real-time as the cursor is moved over the price display.
F. UserVar values
   This grid displays all the UserVars’ values defined for the current System. Because these values
   are constant throughout the entire time frame, they will not change as the cursor moves over the
   price display. ProcessStartTick and ProcessStopTick are the begin and end indexes selected by
   clicking on the price display. See the description for “J” below.
G. DataArray values
   This grid displays the values for all the DataArrays used in the System at the cursor index. These
   values will update in real-time as the cursor is moved over the price display.
H. Detailed trade history
   Here a complete list of every trade made in the selected time frame is displayed, along with
   summary data. The numbers in parenthesis in the summary data refers to the trade number in the
   list.
I. VCR playback functionality
   This is a set of controls which start and control the playback of data one bar or tick at a time. See
   section 4.1.3 for more details.
J. Set Start and Stop indexes
   When checked, left-clicking on the price window will set the start index, and right-clicking will
   set the end index.
K. Edit System Button
   Opens the current System in the specified text editor (text editor setting on Global Settings tab).
L. Clipboard Button
   Copies all the UserVar values to the clipboard for easy pasting into a text document or
   spreadsheet.
M. Optimize Button
   This will begin the Optimize process for the selected security, during the selected time frame.
   See section 4.1.2 for more details.


4.1.1. Menus
•   System
       Choose which System to work with. This list is loaded at program start-up, so if a new
       System is created while working with TSDOptimizer, it will have to be restarted to have it
       listed here.
•   Display



                                                   10
        Lists all the DataArrays available to be displayed on the graph. Several other parameters may
        also be turned on and off here, such as price/volume data, buy/sell/stop/exit signals, trend
        lines, and the grids.
•   Data Type
        There are two data formats TSD can work with: Historical or MetaStock. Historical data is
        imported from text files using the “Convert Historical Data” tool (see the Tools menu).
        MetaStock data is readable in its native format.
•   Interval
        Time interval to work with (1 minute, 5 minute…).
•   Optimization
        There are several options that may be changed when doing optimizations. See section 4.1.2
        for details regarding Optimization.
        Price Only
            The metric used in comparing one optimization run against another is strictly profit. The
            higher profit run is the winner.
        Profit Count
            The metric used in comparing one optimization against another is a combination of the
            number of profitable trades, the number of losing trades, and total profit.
        Quick Optimization
            Do a four-pass optimization versus a 20 pass. Quick optimization is fine to use for
            Analysis and while developing a new System. Use full optimization only after design is
            finished and ideal values are needed for real-time use.
        Weighted
            When active, a weighting will be applied to the profits of each trade, putting more weight
            at later dates.
        Restart on Shift
            When set, the Begin and End optimization values will be used as a sliding window, with
            Min and Max as the extremes allowed. This can allow finer detail for a variable that may
            change ranges over time. For instance, the price range for USDCHF was high in the year
            2000 and began tapering off to about half its range today (according to the TrueRange
            indicator). Therefore, the Min and Max of an optimization variable could cover the entire
            range, with the Begin and End covering a smaller range. This smaller range would shift
            over time from the upper end of Min/Max to the lower end as time went on. This works
            by allowing the Optimization algorithm to shift the Begin/End window when the best
            value is at one end or the other of Begin/End.
•   Options
        General program options:
    Candlesticks
        Display price data as candlesticks if checked. Displayed as bars if not checked.
•   Tools
        Miscellaneous tools.
        Convert Historical Data
                 Opens a dialog box enabling the importing of historical data from a text file.




                                                  11
4.1.2. Optimization
                                       B                          C           D         E


                                      F                               G           H         I




A




                                                                          M
    J
                             K                L


Figure 4 – The Optimizing dialog

Because the number of variations in UserVars can add up quickly (there are over 1014 combinations
of UserVars for the test shown in Figure 4), not every combination of UserVars can be tested.
Therefore, several passes are done, each with a different “starting point” and optimization method.
For each pass, every UserVar (one at a time) has its value run from its Begin value to its End value,
and the one that produces the best output is saved. This process runs until no improvement in the
overall score is made, then the next starting point is executed the same way.

Each pass differs from the others by the starting index of each UserVar, and its method of
optimization. The methods differ by the direction (top to bottom vs. bottom to top) of optimization
and whether an improved score causes a restart (from the first UserVar).

If the “Quick Optimization” menu item is checked, only four passes will be done. Otherwise, twenty
passess will occur, being much more time consuming, but also more complete.




                                                  12
The dialog box is set up as multiple rows of fields, one for each UserVar from your code. The top
row is overall progress information, not tied to a single UserVar.

   A. UserVars
      Each of these rows is one of the UserVars set for optimization in your code. There can be a
      maximum of 17 UserVars optimized per System.
   B. Progress Bars
      Gives a visual indication of where the current value of the UserVar lies in respect to the
      Begin/End range. If the bar is consistantly at one end or the other, the Begin/End range may
      need to be shifted.
   C. Best Value Index
      This column shows the index for each UserVar which produced the best output for the current
      run. The format is best/count where “best” is the best index and “count” is the total number
      of tests (highest index) for this UserVar. The higher “count” is, the more tests per run are
      required, so it is best to keep this number as low as possible.
   D. Best Value this pass
      This column is the best value for the current pass. It is the value of the UserVar at the “best”
      index in column C.
   E. Best Value overall
      Here the best value for all passes is shown for each UserVar. This will be the number used
      for this UserVar when all passes are complete.
   F. Pass Completion visual indicator
      This progress bar shows visually how many passes have occurred out of the total number of
      passes.
   G. Pass Completion number
      This box shows numerically how many passes have occurred vs. the total number of passes.
   H. Best Score this pass
      The best score for the current pass is shown here. If this number is greater than the number in
      I (see below), then this pass will become the best overall pass.
   I. Best Score overall
      This is the best overall score, the score of the UserVar values shown in the same column.
   J. Beep on Completion
      Optimizing can take quite a while, depending on how many UserVars there are, how many
      steps per UserVar, and how many price bars have been selected for optimization. Checking
      this box will cause a beep to sound when the process is complete.
   K. Pause
      Pauses the Optimization process. Optimizing can take close to 100% of the computer’s CPU
      time, so pause the process if you need to do something else with the computer. Press again to
      resume.
   L. Cancel
      Stops the Optimization process and closes the dialog.
   M. Security Name
      Lists the security currently being optimized




                                                 13
4.1.3. VCR Functionality

                    C     D E
            B
A

    F                              G


                                   H
Inactive                                 Active, but paused

Figure 5 – The VCR controls

The VCR on the Main tab allows the security data to be “played” one bar or tick at a time at varying
speeds, in forward or reverse direction. The main purpose of this is to verify that a System is not
cheating by changing signals in the past. As the data is played through the VCR, the price graph is
constantly updated, keeping the most current bar visible at the right-hand side of the graph. This will
allow and changed signals (added or dropped) to become obvious, as they will appear or disappear in
the “past”.

If the Tick Data window is shown, and the Ticks checkbox (B) is checked, a blue cursor line will
appear on the tick graph, indicating the current data position. Also, the current price bar on the main
price graph will have its Open/High/Low/Close values set appropriately for the current tick position.
This will give an accurate tick-by-tick playback of the data through your System. The Tick Data
window does not have to be shown to use the Ticks functionality of the VCR; it will work the same if
it is not shown.

The data played through the VCR will begin wherever the current Start Cursor is located, and end at
the Stop Cursor. To set these cursors, check the “Set Start/Stop” checkbox, then left-click on the
price graph to set the Start Cursor and right-click to set the Stop Cursor. A thick green line will
appear at both the Start and Stop Cursors as a visual indicator. If no Start and Stop Cursors are set,
the entire data set will be used.

To begin VCR playback, simply press the Play button (A). Nothing happens. This is because the
Speed control (F) is set to its default in the middle, which is a speed of zero. Moving this control to
the right will speed up the playback in forward time, and moving it to the left will speed it up in
reverse time. Using the Speed control, you can easily move forward and backward in time at varying
speeds. The farther away from the center, the faster the playback in that direction.

To pause playback at any time, press the Pause button (C). Pressing the Pause button will activate
the two Step buttons, (D) and (E). While paused, you can single-step through the data using these
buttons to go forward (E) and reverse (D). If the Ticks checkbox is set, the data will move one tick at
a time, otherwise, it will move one data bar at a time.

The Progress Bar (G) is a visual indicator of the current playback (price bar) location. The Progress
Bar (H) is a visual indicator of the distance through the current price bar. It is only valid when
playing back Tick data.

                                                  14
    4.2. Security Settings Tab



                                                                                                               D




A


                                                              C                                                E



B



    Figure 6 – Security Settings tab of TSDOptimizer

    The Settings tab of TSDOptimizer allows the manual editing of individual settings. All the settings
    listed on this page are stored in the System’s database file, named the same as the System’s script file
    with “.db” (for DataBase) instead as “.lua” as an extension.

        A. This grid lists all the Optimization Settings for all the different securities. The cursor may be
           placed in any of the white-background fields to edit the value. The left column lists the name
           of the security, which is composed of the symbol, the periodicity (D for daily, I for Intraday),
           and the interval (0 for daily, 30 for 30 minute…). Each optimization setting consists of
           several fields, listed across the top of the grid:
               • Begin – value to begin optimization.
               • End – value to end optimization.
               • Incr – increment value, added to the current value on each optimization pass.
               • Min – minimum value. Used when the optimization option “Restart on Shift” is true.
               • Max – maximum value. Used when the optimization option “Restart on Shift” is true.
        B. This grid lists all the current (Active) settings for each of the securities. These values may be
           manually edited here.
        C. The Save Settings button does what it says; it saves all the settings from both grids to the
           System’s database. If this button is not pressed before changing tabs, all the changes made in
           either of the grids will be discarded.
        D. This Clipboard button will copy all the Optimization Settings values and names to the
           clipboard to allow easy pasting into a text file or spreadsheet.
        E. This Clipboard button will copy all the Active Settings values and names to the clipboard to
           allow easy pasting into a text file or spreadsheet.



                                                       15
4.3. Analysis Tab




Figure 7 – Analysis tab of TSDOptimizer

The Analysis system of TSDOptimizer allows for an excellent back/forward testing of a System. It is
a multi-phase operation which optimizes a section of data, then applies the results of that
optimization to the next section of data in time.

In other words, with the settings of 12 and 6 as shown in the figure above, an optimization will occur
for a 12 day window, then the following 6 days will be tested with those optimized values, and the
results saved to the grid (and a text file for later viewing). This process will continue from the start
date specified until the end of data is reached (or the optimization process is cancelled), sliding the
optimization window forward for each test. This should give a good indication of how the System
will act in real time.

Clicking on any cell in the grid will load the settings for that test and make the analyzed section of
data visible in the Price Display.

The grid is compressed horizontally to allow the most data to be on the screen at once. Hovering the
mouse over any of the cells in the top row will display the full name of that column. The columns
may also be resized manually to increase the width of any column.




                                                   16
4.4. Global Settings Tab




Figure 8 – Global Settings tab of TSDOptimizer




                                                 17
        4.5. DLL Info Tab




                      A                    B
                                                                                   C




D



    E

        Figure 9 – DLL Info tab of TSDOptimizer

        This page lists all the DLLs (addons for MetaStock) that have been installed. Clicking on the DLL
        name in the list (A) will display its available functions in (B). Clicking on one of these functions in
        (B) will list that function’s arguments in grid (C). The details about the DLL and function will be
        listed in the text boxes (D). A sample of how to call this function will be generated and displayed in
        the text box (E). This may be copied and pasted into your code.

        Note that Custom Strings (type Custom) listed as arguments will be referred to by their String ID in
        the function call. So for the “Signals” function shown above, to use the “ExitLong” string as a
        parameter, a “2” will be passed as the last parameter to the function.

        The firstValid and lastValid indexes will be returned by the function.

        firstValid, lastValid = ExecuteDLLFunc(securityData, returnDA, "BBS", "Signals", 0.1, 2)

        No details regarding how to use a specific DLL or its functions can be given. Refer to the
        documentation that came with the addon for instructions on how to use its functions.




                                                           18
    4.6. Price Graph
                                                                                             E



                     A


         C
                                                                                                                 H
                                   F
                                                                                                 D

                                                                     G




                                                                                                                 I
                                                                                                         J
B




    Figure 10 – Price graph of TSDOptimizer
                                                                                                     K
    The name of the currently selected security and its symbol are listed on the title bar of the Price
    Graph.

    Every time your System makes an entry or exit, a graphic is displayed on the graph, showing the
    exact entry/exit point:
    Short entry symbol
    Long entry symbol
    Exit with profit symbol
    Exit with loss symbol

    A.   The names of all the displayed Indicators in the price area, in the same color as that Indicator.
    B.   The names of all the displayed Indicators in the Indicator area, in the same color as that Indicator.
    C.   The Start Cursor
    D.   The Stop Cursor
    E.   The total profits obtained over the time range between the Start and Stop Cursors.
    F.   The price data and Indicators.
    G.   The Cursor (moves with the mouse).
    H.   The price grid with scale.
    I.   The Indicator scale.
    J.   Zoom buttons (identical to the ones on the Main Tab).
    K.   Scroll bar, used for scrolling the data left and right.



                                                        19
4.7. Tick Price Graph

If real data is found (imported from historical data), the graph will be black. If not, fake tick data will
be generated automatically and displayed as red.

Fake data is generated by using the actual bar’s open, high, low, and close. It starts at the open, picks
a direction randomly (up or down) and moves in that direction until it reaches the high/low. Then it
reverses direction and continues until it reaches the other extreme. After hitting the bar’s high and
low, it will head toward the close and remain near the close value until the end of the time frame (100
ticks per bar), where it will be forced to close at the actual close value.




Figure 11 – Tick price graph showing real historical tick data




Figure 12 – Tick price graph showing generated, fake data




                                                        20
5.     Creating a MetaStock Indicator
In the lines below, “MACrossover” is the name of the user’s System. “BuySignals”, “SellSignals”,
and “BearTrendTarget” are custom indicators created within MACrossover.
In the Symbols tab, add the following:
Name: Execute
ExtFml("TSD.Execute", "MACrossover");
Name: Buy Signals
If(ExtFml("TSD.GetIndicator", "MACrossover", "BuySignals"), 1, 0);
Name: Sell Signals
If(ExtFml("TSD.GetIndicator", "MACrossover", "SellSignals"), 1, 0);

Indicators are created similarly:
ExtFml("TSD.GetIndicator", "MACrossover", "BearTrendTarget");

All TSD Indicators are created within a TSD System. In this explanation, the file
SystemDemo_MACrossover.lua will be used to demonstrate how to create a MetaStock indicator.

First, a note regarding MetaStock’s handling of Indicators and Expert Advisors. In MetaStock, when
opening a security, or when new data has arrived (in real-time versions), Indicators are always
evaluated before Expert Advisors, and the Indicators are evaluated in the order in which they were
placed on the chart. Therefore, the first Indicator placed on the chart must be the System’s Execute
function, which will call the System’s main function (“SystemDemo_MACrossover” in this example)
to create and evaluate all the Indicators for that System.

To create the Execute indicator within MetaStock, create a new indicator via the Indicator Builder
and name it the System name followed by “Execute”, for example “TSD D_MACrossover Execute”.

In the body of the indicator, TSD’s Execute function is called with the System name:
ExtFml("TSD.Execute", "Demo_MACrossover");

Close the Indicator Editor and place this Indicator on your chart first, before adding any other TSD
indicators.

Now, back in the file SystemDemo_MACrossover.lua, the indicator will be stored in a TSD
DataArray (see section 6.1.1 for details of the DataArray type), so the first thing to do is to create it:
  enterPriceDA = DataArray.Create(securityData, "EnterPrice", true, false)

The DataArray “enterPriceDA” was created with the name “EnterPrice”. The “true, false”
parameters tell TSDOptimizer that it will be available to graph, and will be plotted over the price data
(not in the Indicator area of the graph).

The range of the newly created DataArray is automatically set to the same as the range of the Open
data for that security. This may be changed if needed by calling DataArray.SetRange (see the section
on DataArrays for details).

After creating the DataArray, the values must be filled in. The System function has a loop which
processes every data bar individually:

                                                    21
  for dataIndex = startIndex + 1, endIndex do
  end

Everything in between the “for” and the “end” will be executed once per data bar, with the variable
dataIndex incrementing from startIndex + 1 to endIndex inclusively. The following line fills in the
data for enterPriceDA:
     DataArray.SetValue(securityData, enterPriceDA, dataIndex, enterPrice)

This sets the value of the element of enterPriceDA at location dataIndex to the value of enterPrice,
which was set prior to this line.

So now we have a DataArray named “EnterPrice” with valid data which spans the entire range of the
price data. To display this indicator within MetaStock, create a new indicator via the Indicator
Builder and name it something which includes the System name and the Indicator name, for example
“TSD D_MACrossover EnterPrice”. Because every indicator is specific to different Systems, a
separate indicator is required for each System. In other words, the “EnterPrice” indicator is different
for the “Demo_MACrossover” System and the “Demo_ADX” System.

In the body of the indicator, TSD’s GetIndicator function is called with the System name and
DataArray name:

ExtFml("TSD.GetIndicator", "Demo_MACrossover", "EnterPrice");

Close the Indicator Editor and the new Indicator may now be plotted in MetaStock.

To summarize, in MetaStock, first create an “Execute” indicator, then create all the “GetIndicator”
indicators needed. When applying any TSD indicators to a chart, always drop the “Execute”
indicator on the chart first, followed by the rest of them in any order.


5.1. TSD Demo_TrendLines6
To run the demo System Demo_TrendLines6 in MetaStock, first create an Indicator named “TSD
Demo_TrendLines6” and copy the following code into it:

ExtFml("TSD.Execute", "Demo_TrendLines6");
ExtFml("TSD.GetIndicator", "Demo_TrendLines6", "StopPrice");
ExtFml("TSD.GetFirstTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");

                                                  22
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "High");
ExtFml("TSD.GetFirstTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");
ExtFml("TSD.GetNextTrendLine", "Demo_TrendLines6", "Low");

Next, create an Expert Advisor named “TSD Demo_TrendLines6” and create the following Signals
within it:

Signal "Buy Signals":
If(ExtFml("TSD.GetIndicator", "Demo_TrendLines6", "BuySignals"), 1, 0);

Signal "Sell Signals":
If(ExtFml("TSD.GetIndicator", "Demo_TrendLines6", "SellSignals"), 1, 0);

Signal "Stop Signals":
If(ExtFml("TSD.GetIndicator", "Demo_TrendLines6", "StopSignals"), 1, 0);

Signal "Exit Signals":
If(ExtFml("TSD.GetIndicator", "Demo_TrendLines6", "ExitSignals"), 1, 0);

The template “TSD Demo TrendLines6” (installed by TSD) may then be used to open securities in
MetaStock.


5.2. What could go wrong?
Q. In TSDOptimizer, my System has only one entry per exit. There are never two entries before an
exit. However, in MetaStock, there may be multiple entries before an exit occurs.
A. TSDOptimizer will show exits that occur on the same bar as an entry. MetaStock, however, will
only show a single Symbol per data bar. Therefore, an exit is probably occurring in the same bar as
the entry and just not displaying in MetaStock.




                                                 23
6. TSD’s Extensions to the Lua Language
TSD provides two new variable types along with numerous new functions.
Every function must pass the variable “securityData” back, which was originally passed in to the
System.


6.1. Variable Types
6.1.1. DataArray
A DataArray corresponds strongly to a MetaStock Indicator. It is an array of float values, one for
each bar of data. At the start of a System’s execution, all DataArrays are cleared to zeroes. When the
MetaStock exported function GetIndicator is called, the array of floats is returned as the data.

There are several functions implemented by the DataArray:
   • DataArray.Create
   • DataArray.Clear
   • DataArray.Get
   • DataArray.SetValue
   • DataArray.GetValue
   • DataArray.SetColor
   • DataArray.SetEnumValue
   • DataArray.Size
   • DataArray.SetRange
   • DataArray.GetRange
   • DataArray.SetAllRanges
   • DataArray.Add
   • DataArray.Subtract
   • DataArray.Multiply
   • DataArray.Divide
   • DataArray.Min
   • DataArray.Max


Create                     Create a new DataArray
             Definition:   array = DataArray.Create(securityData, arrayName, display,
                           indicatorArea)
          Parameters:      arrayName         Text name given to the DataArray.
                           display           Should this DataArray be available to display
                                             on the graph (true or false).
                           indicatorArea     Valid only if display = true. Should this
                                             DataArray be placed in the indicator area of the
                                             graph (true or false).
              Returns:     array             The new DataArray.
             Example:      fastMoveDA = DataArray.Create(securityData,
                           “FastMov”, true, false)

                                                 24
Get                        Retrieves an existing DataArray by name
             Definition:   array = DataArray.Get(securityData, arrayName)
           Parameters:     arrayName         Name of the DataArray to clear.
              Returns:     array             The DataArray corresponding to arrayName.
             Example:      fastMovDA = DataArray.Get(securityData,
                           “FastMov”)


Clear                      Clear a DataArray (set all values to zero)
             Definition:   DataArray.Clear(securityData, arrayName)
           Parameters:     dataArray         DataArray to clear.
              Returns:     nil
             Example:      DataArray.Clear(securityData, fastMovDA)


SetValue                   Set an element of a DataArray
             Definition:   DataArray.SetValue(securityData, dataArray, dataIndex,
                           newValue)
           Parameters:     dataArray        DataArray to set the value of.
                           dataIndex        Index of item to be changed.
                           newValue         New value of item to be changed.
               Returns:    nil
              Example:     DataArray.SetValue(securityData, enterPriceDA,
                           100, 1.50)


GetValue                   Get an element of a DataArray
             Definition:   value = DataArray.GetValue(securityData, dataArray, dataIndex)
           Parameters:     dataArray         DataArray to retrieve value from.
                           dataIndex         Index of item to be changed.
               Returns:    theValue          The value of item to be at dataIndex.
              Example:     enterPrice = DataArray.GetValue(securityData,
                           enterPriceDA, 100)


SetColor                   Set the color of the Indicator displayed by TSDOptimizer
             Definition:   DataArray.SetColor(securityData, dataArray, color)
           Parameters:     dataArray          DataArray to set color of.
                           color              Color for the indicator by name (see Utilities.lua
                                              for a list of color names).
               Returns:    nil
              Example:     DataArray.SetColor(securityData, enterPriceDA,
                           “Green”)


SetEnumValue               Set the enumeration value to displayed in TSDOptimizer’s

                                                25
                      DataArray debug grid.
          Definition: DataArray.SetEnumValue(securityData, dataArray, enumValue,
                      enumName)
        Parameters: dataArray         DataArray to set enumeration value.
                      enumValue       Value which is to have a text name.
                      enumName        Name of the value.
           Returns: nil
          Example: DataArray.SetEnumValue(securityData,
                      buySignalsDA, 0, “None”)


Size                     Retrieve the maximum size of a DataArray
          Definition:    maxSize = DataArray.Size(securityData)
        Parameters:      None
           Returns:      maxSize          The max number of elements of any DataArray.
          Example:       maxSize = DataArray.Size(securityData)


SetRange                 Set the valid range of a DataArray
           Definition:   DataArray.SetRange(securityData, dataArray, startIndex,
                         endIndex)
        Parameters:      dataArray         DataArray to set range.
                         startIndex        first valid index for the DataArray
                         endIndex          last valid index for the DataArray
            Returns:     nil
           Example:      DataArray.SetRange(securityData, enterPriceDA,
                         100, 1000)


GetRange              Get the valid range of a DataArray
          Definition: DataArray.GetRange (securityData, dataArray)
        Parameters: dataArray           DataArray to set color of.
           Returns: firstValid,         The first and last valid (inclusive) indices of the
                      lastValid         DataArray.
          Example: firstValidMA, lastValidMA =
                      DataArray.GetRange(securityData, fastMovDA)


SetAllRanges          Set the valid range of all DataArrays for the System
          Definition: DataArray.SetAllRanges(securityData, startIndex, endIndex)
        Parameters: startIndex          first valid index for all DataArrays
                      endIndex          last valid index for all DataArrays
           Returns: nil
          Example: DataArray.SetAllRanges(securityData, 100, 1000)


Add                      Either adds a number to a DataArray OR adds one DataArray
                         to another.

                                            26
             Definition: DataArray.Add(securityData, dataArrayOut, dataArrayIn, number)
                         OR
                         DataArray.Add(securityData, dataArrayOut, dataArrayIn1,
                         dataArrayIn2)
           Parameters: dataArrayOut          DataArray to receive sum. May be the same
                                             as dataArrayIn.
                         dataArrayIn         Source DataArray to have a number added to.
                         number              Constant number to add to every element of
                                             dataArrayIn.
                         dataArrayIn1        One of two DataArrays to add together.
                         dataArrayIn2        The second DataArray to be summed.
              Returns: nil
             Example: DataArray.Add(securityData, destDA, fastMovDA,
                         10)
                         This adds 10 to each element of fastMovDA, effectively shifting
                         the array up by 10.
                         destDA = fastMovDA + 10

                           DataArray.Add(securityData, destDA, fastMovDA,
                           slowMovDA)
                           This adds each element of fastMovDA to slowMovDA and places
                           the result into destDA.
                           destDA = fastMovDA + slowMovDA


Subtract                   Either subtracts a number from a DataArray OR add one
                           DataArray to another.
             Definition:   DataArray.Subtract(securityData, dataArrayOut, dataArrayIn,
                           number)
                           OR
                           DataArray.Subtract (securityData, dataArrayOut, dataArrayIn1,
                           dataArrayIn2)
           Parameters:     dataArrayOut        DataArray to receive result. May be the same
                                               as dataArrayIn.
                           dataArrayIn         Source DataArray to have a number subtracted
                                               from.
                           number              Constant number to subtract from every
                                               element of dataArrayIn.
                           dataArrayIn1        One of two DataArrays to add together.
                           dataArrayIn2        The second DataArray to be summed.
              Returns:     nil
             Example:      DataArray.Subtract(securityData, destDA,
                           fastMovDA, 10)
                           This adds 10 to each element of fastMovDA, effectively shifting
                           the array up by 10.
                           (destDA = fastMovDA - 10)

                           DataArray.Subtract(securityData, destDA,

                                               27
                           fastMovDA, slowMovDA)
                           This subtracts each element of slowMovDA from fastMovDA and
                           places the result into destDA.
                           destDA = fastMovDA - slowMovDA


Multiply                   Either multiplies a DataArray by a number OR multiplies one
                           DataArray with another.
             Definition:   DataArray.Multiply(securityData, dataArrayOut, dataArrayIn,
                           number)
                           OR
                           DataArray.Multiply(securityData, dataArrayOut, dataArrayIn1,
                           dataArrayIn2)
           Parameters:     dataArrayOut        DataArray to receive product. May be the
                                               same as dataArrayIn.
                           dataArrayIn         Source DataArray to have a number multiplied
                                               with.
                           number              Constant number to multiply with every element
                                               of dataArrayIn.
                           dataArrayIn1        One of two DataArrays to be multiplied
                                               together.
                           dataArrayIn2        The second DataArray to be multiplied.
              Returns:     nil
             Example:      DataArray.Multiply(securityData, destDA,
                           fastMovDA, 10)
                           This multiplies element of fastMovDA by 10.
                           destDA = fastMovDA * 10

                           DataArray.Multiply(securityData, destDA,
                           fastMovDA, slowMovDA)
                           This multiplies each element of fastMovDA by slowMovDA and
                           places the result into destDA.
                           destDA = fastMovDA * slowMovDA


Divide                   Either divides a DataArray by a number OR divides one
                         DataArray with another.
             Definition: DataArray.Divide(securityData, dataArrayOut, dataArrayIn,
                         number)
                         OR
                         DataArray.Divide(securityData, dataArrayOut, dataArrayIn1,
                         dataArrayIn2)
           Parameters: dataArrayOut        DataArray to receive product. May be the
                                           same as dataArrayIn.
                         dataArrayIn       Source DataArray to be divided by the number.
                         number            Constant number to divide by every element of
                                           dataArrayIn.
                         dataArrayIn1      The dividend; the array that gets divided by

                                               28
                                         datatArrayIn2.
                       dataArrayIn2      The divisor; the array that divides dataArrayIn1.
              Returns: nil
             Example: DataArray.Divide(securityData, destDA, fastMovDA,
                       10)
                       This divides element of fastMovDA by 10.
                       destDA = fastMovDA / 10

                          DataArray.Divide(securityData, destDA, fastMovDA,
                          slowMovDA)
                          This divides each element of fastMovDA by slowMovDA and
                          places the result into destDA.
                          destDA = fastMovDA / slowMovDA




6.1.2. UserVar
A UserVar is a container for a numeric variable which is saved in that System’s database, so it is
persistant, and is unique to each security. Its value may be optimized via TSDOptimizer, but does
not have to be.

The UserVar itself is not a number; it is a holder for a number. Call UserVar.GetValue to retrieve the
actual number.

   •   UserVar.Create
   •   UserVar.Get
   •   UserVar.SetValue
   •   UserVar.GetValue
   •   UserVar.SetOptimizeRange
   •   UserVar.SetAsExitVar

Create                  Create a new UserVar, or load an existing one.
            Definition: UserVar.Create(securityData, defaultValue, optBegin, optEnd,
                        optInc, decPlaces, display, shouldOptimize, minValue, maxValue)
          Parameters: defaultValue         Initial value used before any optimization
                        optBegin           Value to start optimization with
                        optEnd             Value to end optimization with
                        optInc             Increment value for optimization
                        decPlaces          Decimal places to display on Settings page
                        display            Display this UserVar on Settings page?
                        shouldOptimize     Include this UserVar in optimizations?
                        minValue           Minimum value for optimization (used when
                                           “Restart on Shift” is on)
                        maxValue           Maximum value for optimization (used when
                                           “Restart on Shift” is on)
             Returns: new UserVar

                                                 29
            Example: UserVar.Create(securityData, "MovPeriodFast", 10,
                     6, 12, 1, 0, true, true, 6, 50)



UserVar.Get(securityData, varName)
UserVar.SetValue(securityData, varName, userVar)
UserVar.GetValue(securityData, userVar)
UserVar.SetOptimizeRange(securityData, userVar, begin, end, increment, shouldOptimize)



6.2. New Functions
ExecuteDLLFunc(securityData, returnedArray, dllName, functionName, …)

CreateTrendLines(securityData, upperLinesDA, lowerLinesDA, minTrendLength, maxTrendLength,
maxExtendBars, minPeaksForTrend, maxNegativeSlope, maxPositiveSlope, offset,
penetrationMultiplier, peakRetrace)




                                              30
7. A Dissection of SystemDemo_MACrossover.lua
The shipped version of SystemDemo_MACrossover.lua may change slightly from when this chapter
was written, so please refer to Appendix B – SystemDemo_MACrossover.lua for the listing of the
source file discussed here.

Line(s)    Description
1          Loads the file “Utilities.lua” to make its functions available to our System.
2          Loads the file “TrailingStops.lua” to make its functions available to our System.
5 – 23     A block comment detailing the UserVar.Create and DataArray.Create functions.
27 – 29    Line comments describing the System.

31         Beginning of the function SystemDemo_MACrossover. The variable “securityData” is
           passed in from TSD.
32         Calls the function RetrieveStandardVars from Utilities.lua. This function sets some
           common variables and retrieves the price DataArrays.
33         Calls the function TrailingStopsInit from TrailingStops.lua, which prepares TrailingStops
           for usage.
36         This is the creation of a UserVar, “fastMovPeriodUV”. We assign the name
           “FastMovPeriod” to this and apply a default value of 10. The two “true”s at the end
           indicate that this is an optimizable variable and should be shown on the Settings tab of
           TSDOptimizer. The optimization will begin at value 6, end at 20, increment by 2, and 0
           decimal places will be displayed on the Settings page.
37 – 39    Creation of other UserVars.
42         Creation of the DataArray “enterPriceDA”, given the TSD name “EnterPrice”, and
           making it available to be graphed in the indicator area of TSD.
43 – 47    Creation of several other DataArrays.
50 – 55    Here the color of the previously created DataArrays are set. This only applies to usage
           within TSD. It does not set the colors for MetaStock.
58         The actual value of fastMovPeriod is retrieved from its UserVar.
59         The value of mediumMovPeriod is retrieved from its UserVar and added to
           fastMovPeriod. Adding it to fastMovPeriod ensures that the medium period is always
           greater than the fast period.
60 – 61    Setting of two more UserVar values.
65         The function ExecuteIndicator is called to calculate the moving average (MA) for the
           fastMovPeriod, with the results stored in the DataArray fastMovDA. The price field
           “open” is used as the input to the function, and an exponential MA (MAType_EMA) is
           calculated from that.
66         The MA for the medium period is calculated and stored in mediumMovDA.
67         The MA for the slow period is calculated and stored in slowMovDA. Since the slow MA
           will have the largest delay in its valid index, the begin and end values are saved.
71         startIndex is calculated from the largest of the two values “firstValid” (set in
           RetrieveStandardVars) and “firstValidMA” (set by the function ExecuteIndicator in line
           67 of this file).
72         endIndex is calculated from the smallest of the two values lastValid and lastValidMA.
74 – 76    Initialization of a few variables to be used within the loop.
80         Beginning of the main loop. It will step through each data bar, starting at (startIndex +

                                                31
          1) and going through endIndex.
82        Retrieve the value of the open price field and place it in the variable open0. The zero at
          the end is a convention to indicate that the data is from the current dataIndex.
84        Get the value of the fast MA at the current dataIndex.
86        Get the value of the fast MA from the previous dataIndex (the previous price bar).
87 – 90   Retrieve more values from various DataArrays.
93        Calculate the difference between the medium MA and the slow MA for the current price
          bar (dataIndex).
94        Calculate the difference between the medium MA and the slow MA for the previous
          price bar.
97        Set the value of the DataArray crossoverDA to crossOver0 calculated in line 93.
100 – 104 The test conditions for a new long entry.
               • currentSignal ~= SIGNAL_BUY : The System is not currently in a long position,
                   it is either in a short position, or not in a position at all.
               • crossOver0 > crossoverMin : The distance between the medium MA and the long
                   MA must be greater than crossoverMin.
               • crossOver0 > crossOver1 : The distance between the medium MA and the long
                   MA must be getting larger (the current value is greater than the previous value).
               • fastMovValue0 > fastMoveValue1 : The fast MA must be increasing in value.
               • mediumMovValue0 > mediumMovValue1 : the medium MA must be increasing.
106       Save the value of our entry. This System always enters on a new open.
108       Set the current value of buySignalsDA to the entry price. The TrailingStops function
          will handle the actual entry.
121       The end of the “if” statement started at line 100.
112 – 116 The test conditions for a new short entry. Same logic as the long entry, but reversed in
          direction.
118       Saving the entry value.
120       Set the sellSignalsDA value, which will cause TrailingStops to enter a new short trade.
121       End of the if statement.
124       Call the function TrailingStops, which will enter new trades when appropriate, and will
          exit trades when stops or profit targets are hit.
129       Get the current value from exitSignalsDA. If this value is not zero, a trade was exited on
          this bar with a profit.
130       Get the current value from stopSignalsDA. If this value is not zero, a trade was exited on
          this bar with a loss.
133 – 137 If either exit0 or are non-zero, set exitPrice to that new value. exitPrice is a combination
          of exit0 and stop0: it’s the price of last exit, profit or loss.
140       Set the value of enterPriceDA to the last entry price (either long or short). This
          DataArray is an indicator which may be displayed on the graph as a visual indicator of
          entries.
141       Set the value of exitPriceDA to the last exit price (profit or loss). This DataArray is an
          indicator which may be displayed on the graph as a visual indicator of exits.
143       The end of the for loop.
144       The end of the function SystemDemo_MACrossover.




                                                 32
Appendix A – Indicator functions
These indicators were implemented by the open source library TA-LIB, which can be found at
http://www.ta-lib.org.

For detailed descriptions and discussions of each of the indicators, please refer to the TADOC web
site at http://tadoc.org.

All the function calls for the Indicators have two common parameters: securityData and the
Indicator’s name. These will not be listed in the Parameters sections.

Every indicator function returns that indicator’s firstValid and lastValid:
firstValidADX, lastValidADX = ExecuteIndicator(securityData, "ADX", outputDA, 20)

The parameter type “maType” refers to a Moving Average Type. These are defined in the file
“Utilities.lua” and may be any of the following:
   • MAType_SMA               -- Simple Moving Average
   • MAType_EMA               -- Exponential Moving Average
   • MAType_WMA               -- Weighted Moving Average
   • MAType_DEMA              -- Double Exponential Moving Average
   • MAType_TEMA              -- Triple Exponential Moving Average
   • MAType_TRIMA             -- Triangular Moving Average
   • MAType_KAMA              -- Kaufman Adaptive Moving Average
   • MAType_MAMA              -- MESA Adaptive Moving Average
   • MAType_T3                -- Triple Exponential Moving Average

So any parameter listed as “maType” or a variation such as “maTypeSlowK” is to be replaced with
one of the above definitions, or by a variable set to one of the above definitions. For instance:

       maTypePPO = MAType_EMA
       fastPeriod = 10
       slowPeriod = 20
       ExecuteIndicator(securityData, "PPO", outputDA, openDA, fastPeriod, slowPeriod,
       maTypePPO)

The 60 or so candlestick (pattern matching) functions are not listed below. They all follow one of
two styles:
   • ExecuteIndicator(securityData, "CDL2Crows", outputDA)
   • ExecuteIndicator(securityData, "CDLAbandonedBaby", outputDA, penetration)

Penetration is the percentage of penetration of a candle within another candle and may range from
zero to 3e+37.

See the lua file SystemDemo_Indicators.lua for a complete list of all the indicators available, with an
example for each.



                                                  33
AD                  Accumulation/Distribution Line
          Example: ExecuteIndicator(securityData, "AD", outputDA)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.


ADOsc               Accumulation/Distribution Oscillator
          Example: ExecuteIndicator(securityData, "ADOsc", outputDA, fastPeriod,
                    slowPeriod)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    fastPeriod       Number of periods for the fast MA.
                                     range = 2 to 100000
                    slowPeriod       Number of periods for the slow MA.
                                     range = 2 to 100000


ADX                 Directional Movement - Average Index
          Example: ExecuteIndicator(securityData, "ADX", outputDA, period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    period           Number of periods.
                                     range = 2 to 100000


ADXR                Directional Movement - Average Index Rating
          Example: ExecuteIndicator(securityData, "ADXR", outputDA, period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    period           Number of periods.
                                     range = 2 to 100000


APO                 Price Oscillator - Absolute
          Example: ExecuteIndicator(securityData, "APO", outputDA, sourceDA,
                    fastPeriod, slowPeriod, maType)
        Parameters: outputDA           Data Array receiving the output from the
                                       indicator.
                    sourceDA           Data Array used as input to the function.
                    fastPeriod         Number of periods for the fast MA.
                                       range = 2 to 100000
                    slowPeriod         Number of periods for the slow MA.
                                       range = 2 to 100000
                    maType             The type of Moving Average to use.


Aroon              Aroon
          Example: ExecuteIndicator(securityData, "Aroon", output1DA, output2DA,

                                          34
                     period)
         Parameters: output1DA          Data Array receiving the output from the
                                        indicator.
                      output2DA         Data Array receiving the output from the
                                        indicator.
                      period            Number of periods.
                                        range = 2 to 100000


AroonOsc             Aroon Oscillator
           Example: ExecuteIndicator(securityData, "AroonOsc", outputDA, period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     period           Number of periods.
                                      range = 2 to 100000


ATR                  Average True Range
           Example: ExecuteIndicator(securityData, "ATR", outputDA, period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     period           Number of periods.
                                      range = 2 to 100000


AvgPrice             Average Price
           Example: ExecuteIndicator(securityData, "AvgPrice", outputDA)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.


BBands               Bollinger Bands
           Example: ExecuteIndicator(securityData, "BBands", output1DA, output2DA,
                     output3DA, sourceDA, period, devUp, devDown, maType)
         Parameters: output1DA        Data Array receiving the Upper output.
                     output2DA        Data Array receiving the Middle output.
                     output3DA        Data Array receiving the Lower output.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000
                     devUp            Deviation multiplier for upper band.
                     devDown          Deviation multiplier for lower band.
                     maType           The type of Moving Average to use.


Beta                Beta Coefficient
           Example: ExecuteIndicator(securityData, "Beta", outputDA, source1DA,
                    source2DA, period)

                                          35
         Parameters: outputDA           Data Array receiving the output from the
                                        indicator.
                      source1DA         Data Array used as input to the function.
                      source2DA         Data Array used as input to the function.
                      period            Number of periods.
                                        range = 2 to 100000


BOP                  Balance of Power
           Example: ExecuteIndicator(securityData, "BOP", outputDA)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.


CCI                  Commodity Channel Index
           Example: ExecuteIndicator(securityData, "CCI", outputDA, period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     period           Number of periods.
                                      range = 2 to 100000


CMO                  Chande Momentum Oscillator
           Example: ExecuteIndicator(securityData, "APO", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


Correl               Pearson Product Momentum Corr. Coeff.
           Example: ExecuteIndicator(securityData, "APO", outputDA, source1DA,
                     source2DA, period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     source1DA        Data Array used as input to the function.
                     source2DA        Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


DEMA                 Double Exponential Moving Average
           Example: ExecuteIndicator(securityData, "DEMA", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.

                                          36
                       sourceDA          Data Array used as input to the function.
                       period            Number of periods.
                                         range = 2 to 100000


DX                    Directional Movement - Index
            Example: ExecuteIndicator(securityData, "DX", outputDA, period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      period           Number of periods.
                                       range = 2 to 100000


EMA                   Exponential Moving Average
            Example: ExecuteIndicator(securityData, "EMA", outputDA, sourceDA,
                      period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      sourceDA         Data Array used as input to the function.
                      period           Number of periods.
                                       range = 2 to 100000


HT_DCPeriod       Hilbert Transform - Dominant Cycle Period
         Example: ExecuteIndicator(securityData, "HT_DCPeriod", outputDA,
                  sourceDA)
      Parameters: outputDA          Data Array receiving the output from the
                                    indicator.
                  sourceDA          Data Array used as input to the function.


HT_DCPhase        Hilbert Transform - Dominant Cycle Phase
         Example: ExecuteIndicator(securityData, "HT_DCPhase", outputDA,
                  sourceDA)
      Parameters: outputDA          Data Array receiving the output from the
                                    indicator.
                  sourceDA          Data Array used as input to the function.


HT_Phasor             Hilbert Transform - In-Phase Indicator
            Example: ExecuteIndicator(securityData, "HT_Phasor", output1DA,
                      output2DA, sourceDA)
          Parameters: output1DA        Data Array receiving the InPhase output.
                      output2DA        Data Array receiving the Quadrature output.
                      sourceDA         Data Array used as input to the function.


HT_Sine                Hilbert Transform - Sinewave Indicator

                                           37
          Example: ExecuteIndicator(securityData, "HT_Sine", output1DA, output2DA,
                    sourceDA)
        Parameters: output1DA        Data Array receiving the Sine output.
                    output2DA        Data Array receiving the LeadSine output.
                    sourceDA         Data Array used as input to the function.


HT_TrendLine       Hilbert Transform - Instantaneous Trendline
          Example: ExecuteIndicator(securityData, "HT_TrendLine", outputDA,
                   sourceDA)
       Parameters: outputDA          Data Array receiving the output from the
                                     indicator.
                   sourceDA          Data Array used as input to the function.


HT_TrendMode       Hilbert Transform - Market Mode
         Example: ExecuteIndicator(securityData, "HT_TrendMode", outputDA,
                   sourceDA)
       Parameters: outputDA         Data Array receiving the output from the
                                    indicator.
                   sourceDA         Data Array used as input to the function.


KAMA                Kaufman's Adaptative Moving Average
          Example: ExecuteIndicator(securityData, "KAMA", outputDA, sourceDA,
                    period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    sourceDA         Data Array used as input to the function.
                    period           Number of periods.
                                     range = 2 to 100000


LinearReg           Linear Regression
          Example: ExecuteIndicator(securityData, "LinearReg", outputDA, sourceDA,
                    period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    sourceDA         Data Array used as input to the function.
                    period           Number of periods.
                                     range = 2 to 100000


LinearReg_Angle     Linear Regression Angle
          Example: ExecuteIndicator(securityData, "LinearReg_Angle", outputDA,
                    sourceDA, period)
        Parameters: outputDA          Data Array receiving the output from the
                                      indicator.

                                          38
                      sourceDA         Data Array used as input to the function.
                      period           Number of periods.
                                       range = 2 to 100000


LinearReg_Intercept Linear Regression Intercept
          Example: ExecuteIndicator(securityData, "LinearReg_Intercept", outputDA,
                    sourceDA, period)
        Parameters: outputDA          Data Array receiving the output from the
                                      indicator.
                    sourceDA          Data Array used as input to the function.
                    period            Number of periods.
                                      range = 2 to 100000


LinearReg_Slope     Linear Regression Slope
          Example: ExecuteIndicator(securityData, "LinearReg_Slope", outputDA,
                    sourceDA, period)
        Parameters: outputDA          Data Array receiving the output from the
                                      indicator.
                    sourceDA          Data Array used as input to the function.
                    period            Number of periods.
                                      range = 2 to 100000


MA                  Any Moving Average
          Example: ExecuteIndicator(securityData, "LinearReg_Slope", outputDA,
                    sourceDA, period)
        Parameters: outputDA          Data Array receiving the output from the
                                      indicator.
                    sourceDA          Data Array used as input to the function.
                    period            Number of periods.
                                      range = 2 to 100000
                    maType            The type of Moving Average to use.


MACD                Moving Average Convergence/Divergence
          Example: ExecuteIndicator(securityData, "MACD", output1DA, output2DA,
                    output3DA, sourceDA, fastPeriod, slowPeriod, signalPeriod)
        Parameters: output1DA        Data Array receiving the MACD output.
                    output2DA        Data Array receiving the Signal output.
                    output3DA        Data Array receiving the Histogram output.
                    sourceDA         Data Array used as input to the function.
                    fastPeriod       Number of periods.
                                     range = 2 to 100000
                    slowPeriod       Number of periods.
                                     range = 2 to 100000
                    signalPeriod     Number of periods.

                                         39
                                      range = 2 to 100000


MACDExt            MACD with controllable MA type
         Example: ExecuteIndicator(securityData, "MACDExt", output1DA,
                   output2DA, output3DA, sourceDA, fastPeriod, maTypeFast,
                   slowPeriod, maTypeSlow, signalPeriod, maTypeSignal)
       Parameters: output1DA         Data Array receiving the MACD output.
                   output2DA         Data Array receiving the Signal output.
                   output3DA         Data Array receiving the Histogram output.
                   sourceDA          Data Array used as input to the function.
                   fastPeriod        Number of periods.
                                     range = 2 to 100000
                   maTypeFast        The type of Moving Average to use for the Fast
                                     MA.
                   slowPeriod        Number of periods.
                                     range = 2 to 100000
                   maTypeSlow        The type of Moving Average to use for the Slow
                                     MA.
                   signalPeriod      Number of periods.
                                     range = 2 to 100000
                   maTypeSignal      The type of Moving Average to use for the
                                     Signal MA.


MACDFix            Moving Average Convergence/Divergence Fix 12/26
         Example: ExecuteIndicator(securityData, "MACDFix", output1DA,
                   output2DA, output3DA, sourceDA, signalPeriod)
       Parameters: output1DA         Data Array receiving the MACD output.
                   output2DA         Data Array receiving the Signal output.
                   output3DA         Data Array receiving the Histogram output.
                   sourceDA          Data Array used as input to the function.
                   signalPeriod      Number of periods.
                                     range = 2 to 100000


MAMA               MESA Adaptive Moving Average
         Example: ExecuteIndicator(securityData, "MAMA", output1DA, output2DA,
                   sourceDA, fastLimit, slowLimit)
       Parameters: output1DA         Data Array receiving the MAMA output.
                   output2DA         Data Array receiving the FAMA output.
                   sourceDA          Data Array used as input to the function.
                   fastLimit         Upper limit use in the adaptive algorithm.
                                     range = 0.01 to 0.99
                   slowLimit         Lower limit use in the adaptive algorithm.
                                     range = 0.01 to 0.99



                                        40
Max                    Highest value over a specified period
             Example: ExecuteIndicator(securityData, "Max", outputDA, sourceDA,
                       period)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       sourceDA         Data Array used as input to the function.
                       period           Number of periods.
                                        range = 2 to 100000


MaxIndex               Index of highest value over a specified period
             Example: ExecuteIndicator(securityData, "MaxIndex", outputDA, sourceDA,
                       period)
           Parameters: outputDA          Data Array receiving the output from the
                                         indicator.
                       sourceDA          Data Array used as input to the function.
                       period            Number of periods.
                                         range = 2 to 100000


MedPrice               Median Price
             Example: ExecuteIndicator(securityData, "MedPrice", outputDA, source1DA,
                       source2DA)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       source1DA        High Data Array used as input to the function.
                       source2DA        Low Data Array used as input to the function.


MFI                    Money Flow Index
             Example: ExecuteIndicator(securityData, "MFI", outputDA, period)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       period           Number of periods.
                                        range = 2 to 100000


MidPoint               MidPoint
             Example: ExecuteIndicator(securityData, "MidPoint", outputDA, sourceDA,
                       period)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       sourceDA         Data Array used as input to the function.
                       period           Number of periods.
                                        range = 2 to 100000


MidPrice                MidPrice

                                            41
           Example: ExecuteIndicator(securityData, "MidPrice", outputDA, source1DA,
                     source2DA, period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     source1DA        High Data Array used as input to the function.
                     source2DA        Low Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


Min                  Lowest value over a specified period
           Example: ExecuteIndicator(securityData, "Min", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


MinIndex             Index of lowest value over a specified period
           Example: ExecuteIndicator(securityData, "MinIndex", outputDA, sourceDA,
                     period)
         Parameters: outputDA          Data Array receiving the output from the
                                       indicator.
                     sourceDA          Data Array used as input to the function.
                     period            Number of periods.
                                       range = 2 to 100000


MinMax               Lowest and highest values over a specified period
           Example: ExecuteIndicator(securityData, "MinMax", output1DA, output2DA,
                     sourceDA, period)
         Parameters: output1DA         Data Array receiving the Min output.
                     output2DA         Data Array receiving the Max output.
                     sourceDA          Data Array used as input to the function.
                     period            Number of periods.
                                       range = 2 to 100000


MinMaxIndex         Indexes of lowest and highest values over a specified period
          Example: ExecuteIndicator(securityData, "MinMaxIndex", output1DA,
                    output2DA, sourceDA, period)
        Parameters: output1DA        Data Array receiving the Min Index output.
                    output2DA        Data Array receiving the Max Index output.
                    sourceDA         Data Array used as input to the function.
                    period           Number of periods.
                                     range = 2 to 100000

                                          42
Minus_DI              Directional Indicator (-DI)
            Example: ExecuteIndicator(securityData, "Minus_DI", outputDA, period)
          Parameters: outputDA          Data Array receiving the output from the
                                        indicator.
                      period            Number of periods.
                                        range = 2 to 100000


Minus_DM              Directional Movement (-DM)
            Example: ExecuteIndicator(securityData, "Minus_DM", outputDA, period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      period           Number of periods.
                                       range = 2 to 100000


MOM                   Momentum (price-prevPrice)
            Example: ExecuteIndicator(securityData, "MOM", outputDA, sourceDA,
                      period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      sourceDA         Data Array used as input to the function.
                      period           Number of periods.
                                       range = 2 to 100000


NATR                  Normalized Average True Range
            Example: ExecuteIndicator(securityData, "NATR", outputDA, period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      period           Number of periods.
                                       range = 2 to 100000


OBV                   On Balance Volume
            Example: ExecuteIndicator(securityData, "OBV", outputDA)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      sourceDA         Data Array used as input to the function.


Plus_DI               Directional Indicator (+DI)
            Example: ExecuteIndicator(securityData, "Plus_DI", outputDA, period)
          Parameters: outputDA          Data Array receiving the output from the
                                        indicator.
                      period            Number of periods.

                                           43
                                          range = 2 to 100000


Plus_DM               Directional Movement (+DM)
            Example: ExecuteIndicator(securityData, "Plus_DM", outputDA, period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      period           Number of periods.
                                       range = 2 to 100000


PPO                   Price Oscillator - Percentage
            Example: ExecuteIndicator(securityData, "PPO", outputDA, sourceDA,
                      fastPeriod, slowPeriod, maType)
          Parameters: outputDA           Data Array receiving the output from the
                                         indicator.
                      sourceDA           Data Array used as input to the function.
                      fastPeriod         Number of periods.
                                         range = 2 to 100000
                      slowPeriod         Number of periods.
                                         range = 2 to 100000
                      maType             The type of Moving Average to use.


ROC                   Rate-Of-Change : ((price/prevPrice)-1)*100
            Example: ExecuteIndicator(securityData, "ROC", outputDA, sourceDA,
                      period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      sourceDA         Data Array used as input to the function.
                      period           Number of periods.
                                       range = 2 to 100000


ROCP                  Rate-Of-Change : (price-prevPrice)/prevPrice
            Example: ExecuteIndicator(securityData, "ROCP", outputDA, sourceDA,
                      period)
          Parameters: outputDA         Data Array receiving the output from the
                                       indicator.
                      sourceDA         Data Array used as input to the function.
                      period           Number of periods.
                                       range = 2 to 100000


ROCR                  Rate-Of-Change : (price/prevPrice)
            Example: ExecuteIndicator(securityData, "ROCR", outputDA, sourceDA,
                      period)
          Parameters: outputDA         Data Array receiving the output from the

                                            44
                                         indicator.
                      sourceDA           Data Array used as input to the function.
                      period             Number of periods.
                                         range = 2 to 100000


ROCR100              Rate-Of-Change : (price/prevPrice)*100
           Example: ExecuteIndicator(securityData, "ROCR100", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


RSI                  Relative Strength Index
           Example: ExecuteIndicator(securityData, "RSI", outputDA, sourceDA,
                     period)
         Parameters: outputDA          Data Array receiving the output from the
                                       indicator.
                     sourceDA          Data Array used as input to the function.
                     period            Number of periods.
                                       range = 2 to 100000


SAR                  Parabolic SAR
           Example: ExecuteIndicator(securityData, "SAR", outputDA, sourceHighDA,
                     sourceLowDA, acceleration, maximum)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceHighDA     Data Array used as input to the function.
                     sourceLowDA      Data Array used as input to the function.
                     acceleration     Acceleration factor.
                                      range = 0 to 3e+37
                     maximum          Acceleration factor maximum value.
                                      range = 0 to 3e+37


SARExt               Parabolic SAR - Extended
           Example: ExecuteIndicator(securityData, "SARExt", outputDA,
                     sourceHighDA, sourceLowDA, startValue, offsetOnReverse,
                     accInitLong, accLong, accMaxLong, accInitShort, accShort,
                     accMaxShort)
         Parameters: outputDA          Data Array receiving the output from the
                                       indicator.
                     sourceHighDA      Data Array used as input to the function.
                     sourceLowDA       Data Array used as input to the function.

                                           45
                      startValue      Start value and direction.
                                      0 for Auto, >0 for Long, <0 for Short
                                      range = -3e+37 to 3e+37
                      offsetOnReverse Percent offset added/removed to initial stop on
                                      short/long reversal
                                      range = 0 to 3e+37
                      accInitLong     Acceleration Factor initial value for the Long
                                      direction.
                                      range = 0 to 3e+37
                      accLong         Acceleration Factor for the Long direction.
                                      range = 0 to 3e+37
                      accMaxLong      Acceleration Factor maximum value for the
                                      Long direction.
                                      range = 0 to 3e+37
                      accInitShort    Acceleration Factor initial value for the Short
                                      direction.
                                      range = 0 to 3e+37
                      accShort        Acceleration Factor for the Short direction.
                                      range = 0 to 3e+37
                      accMaxShort     Acceleration Factor maximum value for the
                                      Short direction.
                                      range = 0 to 3e+37


SMA                  Simple Moving Average
           Example: ExecuteIndicator(securityData, "SMA", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


StdDev               Standard Deviation
           Example: ExecuteIndicator(securityData, "StdDev", outputDA, sourceDA,
                     period, deviations)
         Parameters: outputDA            Data Array receiving the output from the
                                         indicator.
                     sourceDA            Data Array used as input to the function.
                     period              Number of periods.
                                         range = 2 to 100000
                     deviations          Number of deviations.
                                         range = -3e+37 to 3e+37


Stoch               Stochastic Oscillator Slow
           Example: ExecuteIndicator(securityData, "Stoch", output1DA, output2DA,

                                          46
                     fastPeriodK, slowPeriodK, maTypeSlowK, slowPeriodD,
                     maTypeSlowD)
         Parameters: output1DA         Data Array receiving the Slow K output.
                     output2DA         Data Array receiving the Slow D output.
                     fastPeriodK       Number of periods for the Fast-K line.
                                       range = 1 to 100000
                     slowPeriodK       Smoothing for the Slow-K line (usually 3).
                                       range = 1 to 100000
                     maTypeSlowK       The type of Moving Average for Slow-K.
                     slowPeriodD       Smoothing for the Slow-D line.
                                       range = 1 to 100000
                     maTypeSlowD       The type of Moving Average for Slow-D.


StochF               Stochastic Oscillator Fast
           Example: ExecuteIndicator(securityData, "StochF", output1DA, output2DA,
                     fastPeriodK, fastPeriodD, maTypeFastD)
         Parameters: output1DA          Data Array receiving the Fast K output.
                     output2DA          Data Array receiving the Fast D output.
                     fastPeriodK        Number of periods for the Fast-K line.
                                        range = 1 to 100000
                     fastPeriodD        Smoothing for the Fast-D line (usually 3).
                                        range = 1 to 100000
                     maTypeFastD        The type of Moving Average for Fast-D.


StochRSI             Stochastic RSI
           Example: ExecuteIndicator(securityData, "StochF", output1DA, output2DA,
                     sourceDA, fastPeriodK, fastPeriodD, maTypeFastD)
         Parameters: output1DA         Data Array receiving the Fast K output.
                     output2DA         Data Array receiving the Fast D output.
                     sourceDA          Data Array used as input to the function.
                     fastPeriodK       Number of periods for the Fast-K line.
                                       range = 1 to 100000
                     fastPeriodD       Smoothing for the Fast-D line (usually 3).
                                       range = 1 to 100000
                     maTypeFastD       The type of Moving Average for Fast-D.


Sum                  Summation
           Example: ExecuteIndicator(securityData, "Sum", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


                                           47
T3                   Triple Exponential Moving Average
           Example: ExecuteIndicator(securityData, "T3", outputDA, sourceDA, period,
                     vFactor)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000
                     vFactor          Volume Factor.
                                      range = 0.0 to 1.0


TEMA                 Triple Exponential Moving Average
           Example: ExecuteIndicator(securityData, "TEMA", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


TRange               True Range
           Example: ExecuteIndicator(securityData, "TRange", outputDA)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.


TriMA                Triangular Moving Average
           Example: ExecuteIndicator(securityData, "TriMA", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


TRIX                 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
           Example: ExecuteIndicator(securityData, "TRIX", outputDA, sourceDA,
                     period)
         Parameters: outputDA         Data Array receiving the output from the
                                      indicator.
                     sourceDA         Data Array used as input to the function.
                     period           Number of periods.
                                      range = 2 to 100000


                                          48
TSF                    Time Series Forecast
             Example: ExecuteIndicator(securityData, "TSF", outputDA, sourceDA,
                       period)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       sourceDA         Data Array used as input to the function.
                       period           Number of periods.
                                        range = 2 to 100000


TypPrice               Typical Price
             Example: ExecuteIndicator(securityData, "TypPrice", outputDA)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.


UltOsc                 Ultimate Oscillator
             Example: ExecuteIndicator(securityData, "UltOsc", outputDA, period1,
                       period2, period3)
           Parameters: outputDA          Data Array receiving the output from the
                                         indicator.
                       period1           Number of periods.
                                         range = 1 to 100000
                       period2           Number of periods.
                                         range = 1 to 100000
                       period3           Number of periods.
                                         range = 1 to 100000


Var                    Variance
             Example: ExecuteIndicator(securityData, "Var", outputDA, sourceDA, period,
                       deviations)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.
                       sourceDA         Data Array used as input to the function.
                       period           Number of periods.
                                        range = 1 to 100000
                       deviations       Number of deviations.
                                        range = -3e+37 to 3e+37


WClPrice               Weighted Close
             Example: ExecuteIndicator(securityData, "WCIPrice", outputDA)
           Parameters: outputDA         Data Array receiving the output from the
                                        indicator.



                                            49
WillR               Williams %R
          Example: ExecuteIndicator(securityData, "TriMA", outputDA, period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    period           Number of periods.
                                     range = 2 to 100000


WMA                 Weighted Moving Average
          Example: ExecuteIndicator(securityData, "WMA", outputDA, sourceDA,
                    period)
        Parameters: outputDA         Data Array receiving the output from the
                                     indicator.
                    sourceDA         Data Array used as input to the function.
                    period           Number of periods.
                                     range = 2 to 100000




                                         50
      Appendix B – SystemDemo_MACrossover.lua
1.     require "Utilities"
2.     require "TrailingStops"
3.
4.
5.     --[[ UserVar.Create() parameters:
6.                    securityData
7.                    Variable Name
8.                    Default Value
9.                    OptimizeBegin
10.                   OptimizeEnd
11.                   OptimizeIncrement
12.                   # of decimal places to display
13.                   Display variable on Settings page?
14.                   Should this variable be optimized?
15.                   OptimizeMin
16.                   OptimizeMax
17.
18.         DataArray.Create() parameters:
19.                    securityData
20.                    Array Name
21.                    Should be displayed on Graph?
22.                    Display in Indicator area of Graph?
23.    ]]
24.
25.
26.
27.    -- This demo enters long whenever the medium MA is above the slow MA, and enters short when
28.    -- the medium MA is below the slow, and the fast MA is moving in the proper direction.
29.    -- Generally not a profitable system.
30.
31.    function SystemDemo_MACrossover(securityData)
32.      RetrieveStandardVars(securityData) -- Do some common setup.
33.      TrailingStopsInit(securityData) -- Set up our TrailingStops function.
34.
35.       -- Get all our stored UserVariables from the database.
36.       fastMovPeriodUV = UserVar.Create(securityData, "FastMovPeriod", 10, 6, 20, 2, 0, true, true, 6,
       20)
37.       mediumMovPeriodUV = UserVar.Create(securityData, "MediumMovPeriod", 5, 5, 50, 5, 0, true,
       true, 5, 50)
38.       slowMovPeriodUV = UserVar.Create(securityData, "SlowMovPeriod", 5, 5, 50, 5, 0, true, true,
       5, 50)
39.       crossoverMinUV = UserVar.Create(securityData, "CrossoverMin", 0.0005, 0.0001, 0.0010,
       0.0001, 4, true, true, 0.0001, 0.0010)


                                                      51
40.
41.     -- Create out DataArrays (holders for the Indicators)
42.     enterPriceDA = DataArray.Create(securityData, "EnterPrice", true, false)
43.     exitPriceDA = DataArray.Create(securityData, "ExitPrice", true, false)
44.     fastMovDA = DataArray.Create(securityData, "FastMov", true, false)
45.     mediumMovDA = DataArray.Create(securityData, "MediumMov", true, false)
46.     slowMovDA = DataArray.Create(securityData, "SlowMov", true, false)
47.     crossoverDA = DataArray.Create(securityData, "Crossover", true, true)
48.
49.     -- Set the colors of the various Indicators.
50.     DataArray.SetColor(securityData, enterPriceDA, "Green")
51.     DataArray.SetColor(securityData, exitPriceDA, "Red")
52.     DataArray.SetColor(securityData, fastMovDA, "Red")
53.     DataArray.SetColor(securityData, mediumMovDA, "LightBlue")
54.     DataArray.SetColor(securityData, slowMovDA, "Blue")
55.     DataArray.SetColor(securityData, crossoverDA, "Blue")
56.
57.     -- Get the values of our UserVars
58.     fastMovPeriod = UserVar.GetValue(securityData, fastMovPeriodUV)
59.     mediumMovPeriod = UserVar.GetValue(securityData, mediumMovPeriodUV) + fastMovPeriod
60.     slowMovPeriod = UserVar.GetValue(securityData, slowMovPeriodUV) + mediumMovPeriod
61.     crossoverMin = UserVar.GetValue(securityData, crossoverMinUV)
62.
63.      -- Calculate the Moving Averages (MA).
64.      -- The MAType parameters may be changed to any other MA type available (see Utilities.lua)
65.      ExecuteIndicator(securityData, "MA", fastMovDA, openDA, fastMovPeriod, MAType_EMA)
66.      ExecuteIndicator(securityData, "MA", mediumMovDA, openDA, mediumMovPeriod,
      MAType_EMA)
67.      firstValidMA, lastValidMA = ExecuteIndicator(securityData, "MA", slowMovDA, openDA,
      slowMovPeriod, MAType_EMA)
68.
69.     -- Adjust our start and end indices according to the slowest MA.
70.     -- firstValid and lastValid are set in the function RetrieveStandardVars.
71.     startIndex = math.max(firstValid, firstValidMA)
72.     endIndex = math.min(lastValid, lastValidMA)
73.
74.     currentSignal = SIGNAL_NONE;
75.     enterPrice = 0
76.     exitPrice = 0
77.
78.     -- Process each price bar one at a time.
79.     -- Start at (startIndex + 1) because we look back in time by one bar (fastMovValue1...)
80.     for dataIndex = startIndex + 1, endIndex do
81.        -- open0 is the current bar's open price
82.        open0 = DataArray.GetValue(securityData, openDA, dataIndex)
83.        -- fastMovValue0 is the current bar's fast MA



                                                      52
84.    fastMovValue0 = DataArray.GetValue(securityData, fastMovDA, dataIndex)
85.    -- fastMovValue1 is the previous bar's fast MA
86.    fastMovValue1 = DataArray.GetValue(securityData, fastMovDA, dataIndex - 1)
87.    mediumMovValue0 = DataArray.GetValue(securityData, mediumMovDA, dataIndex)
88.    mediumMovValue1 = DataArray.GetValue(securityData, mediumMovDA, dataIndex - 1)
89.    slowMovValue0 = DataArray.GetValue(securityData, slowMovDA, dataIndex)
90.    slowMovValue1 = DataArray.GetValue(securityData, slowMovDA, dataIndex - 1)
91.
92.    -- crossOver0 is the distance between this bar's medium MA and slow MA.
93.    crossOver0 = mediumMovValue0 - slowMovValue0
94.    crossOver1 = mediumMovValue1 - slowMovValue1
95.
96.    -- Set the value of our CrossOver Indicator to crossOver0 for this price bar.
97.    DataArray.SetValue(securityData, crossoverDA, dataIndex, crossOver0)
98.
99.    -- If we're not already in a long position, test if we should enter one.
100.   if (currentSignal ~= SIGNAL_BUY) and
101.      (crossOver0 > crossoverMin) and
102.      (crossOver0 > crossOver1) and
103.      (fastMovValue0 > fastMovValue1) and
104.      (mediumMovValue0 > mediumMovValue1) then
105.
106.     enterPrice = open0      -- Enter at this bar's open price
107.     -- Create a long entry. Handled by the TrailingStops function.
108.     DataArray.SetValue(securityData, buySignalsDA, dataIndex, -enterPrice)
109.   end
110.
111.   -- If we're not already in a short position, test if we should enter one.
112.   if (currentSignal ~= SIGNAL_SELL) and
113.      (crossOver0 < -crossoverMin) and
114.      (crossOver0 < crossOver1) and
115.      (fastMovValue0 < fastMovValue1) and
116.      (mediumMovValue0 < mediumMovValue1) then
117.
118.     enterPrice = open0      -- Enter at this bar's open price
119.     -- Create a short entry. Handled by the TrailingStops function.
120.     DataArray.SetValue(securityData, sellSignalsDA, dataIndex, -enterPrice)
121.   end
122.
123.   -- The function TrailingStops will set the variable currentSignal to the proper value.
124.   TrailingStops(securityData, dataIndex)
125.
126.   -- If TrailingStops caused an exit, then exit0 or stop0 will be non-zero.
127.   -- If exit0 ~= 0, we exited with a profit.
128.   -- If stop0 ~= 0, we exited with a loss.
129.   exit0 = DataArray.GetValue(securityData, exitSignalsDA, dataIndex)



                                                    53
130.     stop0 = DataArray.GetValue(securityData, stopSignalsDA, dataIndex)
131.
132.     -- If we exited on this price bar, save the exit price for display to the user.
133.     if exit0 ~= 0 then
134.        exitPrice = exit0
135.     elseif stop0 ~= 0 then
136.        exitPrice = stop0
137.     end
138.
139.     -- Save the enterPrice and exitPrice to a DataArray (Indicator) for display to the user.
140.     DataArray.SetValue(securityData, enterPriceDA, dataIndex, enterPrice)
141.     DataArray.SetValue(securityData, exitPriceDA, dataIndex, exitPrice)
142.
143.   end -- for dataIndex = startIndex + 1, endIndex do
144. end -- function




                                                      54

								
To top