|
User Guide Genetic Optimizer v.2.0 for TradeStation (Omega Research)
What You Can Do In Genetic Optimizer v.2.0 for TradeStation (TSG2).
TSG2 is an add-on dll library for TradeStation (TradeStation Securities, Inc) and set of functions on EasyLanguage that allows to speed up optimization.
Here are some links to help you become familiar with this powerful and flexible optimization application.
|
|
Introduction
TSG2 contains a dll library with functions for genetic optimization and analysis, which are being referred to in the strategy code, created on EasyLanguage in TradeStation. To analyse the optimization and see the results you can use the program Report Viewer, which is in the installation box. To convert market strategies into strategies for genetic optimization, use the program EasyLanguage Code Converter, which also is in the set.
TSG2 uses an original algorithm that is much faster than typical genetic algorithms.
A big advantage of TSG2 is the possibility to use the optimization criterions (fitness) that are written in EasyLanguage and the usage of different linear and nonlinear limitations that are tied to optimization system. |
|
Awards
The program Genetic Optimizer for TradeStation got the 1st place in the category "Add-on Dynamic Link Library/Function" by user votes on the international conference TradeStation World Conference & Expo 2005, that took place in Las Vegas, USA. |
|
Features
View the list below to learn about what’s new in this version.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
System Requirements
Minimum System Requirements:
Operating System:Windows NT/2000/XP/2003/Vista User Access Level:Administrator Software:Omega Research ProSuite 2000i or TradeStation 6.x/7.x/8.x Processor:1500 MHz Pentium IV or better RAM:512 MB (1024 MB RAM is recommended) Hard Drive:65 MB free space Monitor:1024x768 monitor resolution or higher
|
|
Installation and Activation
The installation of TSG2 is in TSG2Setup.exe, that you can download on the homepage of Products Control Center:
To enter you will have to input the access parameters, which are: **************************************************************************** Registration e-mail: Password: **************************************************************************** that you will obtain by purchasing the program. Then follow the instructions on our site and download and activate products. You will find the description of the activation process of our software here: http://reg.tsresearch.com/client/products/help/
After activation, import TSG2 Function, Signals and Strategy into EasyLanguage Power Editor or TradeStation. |
|
Genetic Optimization
|
|
Genetic Algorithms
GENETIC ALGORITHMS It is the modeling of natural selection.
Some time ago people noticed that some processes in nature are very effectively arranged. Algorithms in question are based on natural selection in wild nature.
Genetic Algorithms are adaptive methods of extremum seeking. Recently they were frequently used for solving optimization tasks. They are based on imitation of evolution in wild nature: biological populations evolve during some time, obeying the natural selection law discovered by Charles Darvin and only the fittest survive. Genetic algorithms imitate this process and they are able to solve real tasks if they are properly encoded.
Basic principles of GA’s were formulated by Holland (Holland, 1975) and are described in many papers. In contrast to the natural evolution GA’s model only those processes in populations that are essential for the evolution. Which processes are essential for evolution and which are not is still an open question for the researchers.
Scheme of genetic algorithm work:
|
|
Genetic Optimizer Terms
|
|
Gene – it is one of the system’s parameters which could be optimized. Type of moving average, averaging period or some parameter or coefficient of the digital filter, for example, etc. |
|
Chromosome – it is a group of genes (parameters) that have logical connection with each other, parameters of one type of input or one signal. This group participates in crossover as a whole, i.e. it is a set of parameters which can migrate between specimens as a whole. Thus successful combinations of genes have better chances to survive and reproduce. It is appropriate to combine connected parameters (of one signal for instance) into one chromosome. |
|
Fitness - criterion of profit or suitability of specimen, the criterion function. It is some value that is connected with the specific trading system. By the means of fitness we report to genetic optimizer how much we are satisfied with that trading system. The greater it is – the better is the specimen. In simplest case it can be NetProfit or ProfitFactor, as in original optimization used in TradeStation for example, but we suppose that it is not correct. Results obtained with use of such simple criterions hardly can be stable. In our case user defines himself what is "vitality" of specimen (trading system). In fact, one can get a trading system that will show stable results in future only due to proper choice of optimization criterion. |
|
Population – it is a group of survived till present moment best specimen selected by best fitness. Usually trading systems are built in such a way that "population" consists of most "vital", stable systems. |
|
Crossover – it is a replacement of genes to analogous ones from another specimen or replacement of chromosome to analogous from another specimen of population. |
|
Mutation – it is a random change of some genes (parameters of system). |
|
Principle of operation
The genetic optimization in TradeStation with TSG2 is done the same way as the optimization of any other system, with the single difference that in this case it’s not the parameters of the system that are optimized but a variable of TSG2’s function "Gen" from 1, to the needed amount of iterations, e.g., 1000. The step for this is always 1. In other words, the built–in optimizer TradeStation is used only as an iteration counter and as an initializer for TSG2 functions.
After initialization, TSG2 assigns values to variables from the value range needed for optimization. Then the system is tested on the inputted range of historical data.
After finishing each run on the inputted range of historical data the system hands over the calculated values of criterion of optimality (fitness) to TSG2.
Based on the results, TSG2 forms the current population out of the best met exemplars and forms a new set of parameters for testing by crossbreeding them.
On every iteration the system is ran on the data we’re interested in, every time with new values of the variables we’re optimizing. After that, the fitness is compared to fitnesses we already have from other exemplars.
If it is better than the previous one, it "pushes" the "weaker" exemplar out, if it’s worse than the ones we already have, it’s taken out of the population. Further on, we start looking for a new exemplar (change the parameters of the system), until the needed amount of iterations, inputted in the variable "Gen" at the beginning of the optimization is gone through.
With this, you don’t have to go through a large number of iterations, even in complicated systems with big amounts of variables. E.g. the evaluation of coefficients of a linear digital filter of 100th order at the accuracy of coefficient rating 0.01 can take going through 10300 combinations of parameters. Not even the most powerful supercomputer couldn’t possibly do this, neither could all existing computers if ran simultaneously.
Still, with the help of TSG2 you can find an acceptable decision even in about ten minutes even on a home PC. |
|
Getting Started
|
|
Strategy adoptions
To work with TSG2, initial strategy should be changed. Please, have a look at an example of a strategy:
TS.G2. SIMPLE This strategy is analogous to TS.GO.12.PRO. There is only one criterion of optimality (fitness) defined. All strategies of the previous version TSGO are compatible with the new version TSG2, you just need to rename the functions, e.g., previously it was TS.GO.Mode, in the new version it should be TS.G2.Mode.
TS.G2.MULTI This strategy is also analogous to TS.G2.SIMPLE and to TS.GO.12.PRO, but instead of one criterion of optimality in this strategy optimization is done with many criterions.
TS.G2.INCLUDE In this strategy optimization takes place with many criterions, but external signals are used with the help of IncludeSignal.
It is commented in the text of program.
To make the adoption of code easier you can download "Code Converter for Trade Smart Genetic Optimizer" http://tsresearch.com/download/free_download/converter/
You can find the description of it's usage here: http://tsresearch.com/support/online_help/genetic/converter/ The main idea of strategy adoption is the following.
1. Inputs of initial strategy should be set as Variables.
2. Entry parameters of optimization should be added. It's necessary to set Inputs: Gen(1); - counter of strategy runs. Other parameters can be fixed in the text of strategy.
3. Initial User Inputs are described as genes and Name of Gen is set. Starting and ending values and step should be set. Step can also be = 0.
4. Genes are combined in chromosomes. There can be several chromosomes in TSG2. Chromosomes allow TSG2 to understand structure of system that is being optimized. Connected genes should be combined into one chromosome for example all parameters of one type. You can also combine all genes into one chromosome, it will work but will slow down the optimization. Description of genes and chromosomes and settings of parameters should be done on the first bar when Gen = 1.
5. Every time on the first bar of function LastRun = TS.G2.Next(Gen); generation of new candidate is started. Then values of new candidates are selected and saved as variables that were Inputs in initial strategy. To read values of genes the function Len1 = TS.G2.Get("Buy.Signal.Len1",Ind); is used. First parameter of a gene is the name of a gene. The second parameter can be 0. The value > 0 is used in only in some cases when choosing sample from population by it's number.
6. The code of initial system follows without any changes.
7. When code of initial system is added, EasyLanguage code of criterion calculation should be added (fitness) and finally code that calls the function on the last bar R = TS.G2.Fitness(Fitness); That tells TSG2 the result of run.
8. When optimization is completed TSG2 will show the best candidate. We will see the best candidate on the chart of TradeStation.
|
|
Example strategy
The system is based on 2 moving average crossovers. Buy signal is generated when the fast moving average crosses over the slower moving average. Additionaly Stop-loss is included in the system. It is a very simple system and we don't recommend trading it but it is very useful to understand the principles of genetic optimization. To do optimization in usual way all parameters will be tested.
That would include: K = TS.G2.Chrom("Buy.Signal"); R = TS.G2.Gen("Buy.Signal.Len1",K,1,50,1); -- 1 to 50, together 50 R = TS.G2.Gen("Buy.Signal.Len2",K,1,50,1); -- 1 to 50, together 50
K = TS.G2.Chrom("Sell.Signal"); R = TS.G2.Gen("Sell.Signal.Len3",K,1,50,1); -- 1 to 50, together 50 R = TS.G2.Gen("Sell.Signal.Len4",K,1,50,1); -- 1 to 50, together 50
K = TS.G2.Chrom("StopLoss"); R = TS.G2.Gen("StopLoss.SL",K,100,1000,100); -- 100 to 1000, together 11
All together: = 50 x 50 x 50 x 50 x 11 = 68.75 million tests
TS GO finds acceptable solution with ~1000 tests. The use of our new function FreshBlood slows down the search, but raises the chance to find a global maximum. FreshBlood imitates the use of a large population.
It's obvious that using new technological possibilities it's easy to lower the time needed for searching solutions. The new version of Genetic Optimizer v.2.0 for TradeStation supports up to 1000 genes (!), that allow to solve tasks that wouldn't be possible with other methods.
EasyLanguage:
{******************************************************************* Name: TS.G2.SIMPLE Analysis Type: Strategy Description: Example Strategy for Genetic Optimizer v.2.x Example of simple trading system to show the possibilities of Genetic Optimizer for TradeStation. The system is based on 2 moving average crossovers. Buy signal is generated when fast moving average crosses over slow moving average. Additionaly Stop-loss is included in the system. Used: TSG2.dll Provided By: Trade Smart Research (c) Copyright 2001 - 2007 www.tsresearch.com *******************************************************************}
Inputs: Gen(1), {Gen - input parameter, that assigns the number of generations. Optimize in TradeStation with "Start = 1" and "Inc = 1"} ShowInd(1), {ShowInd - number of individual in population to show} ModeTSGO(0), Population(50), FreshBlood(0), MyReportName("MySystem1");
{ Declaration of variables } Vars: Len1(0),Len2(0),Len3(0),Len4(0),SL(0), Fitness(0),LastRun(0),R(0),K(0),Ind(0);
{ ---------------------------------------------------------------------- } { The Genetic Optimizer initialization and the definition of genes }
If CurrentBar = 1 Then Begin
{ This block runs on every run of strategy on the first bar.
The function TS.G2.Start is called having the Parameter that defines filename for milestones. All the tunings of an optimizer and current population are stored in the file, that allows to continue an optimization after break, or to draw the input/output signals after the opening the TradeStation workspace with the strategy. It is possible to open this file in graphic interface for viewing population.}
R = TS.G2.Start(MyReportName + "(" + GetSymbolName + ").rgo");
{ This block runs when the optimization is starting for the first bar only. }
If Gen = 1 Then Begin
{ The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example. }
R = TS.G2.Mode(ModeTSGO); R = TS.G2.Popul(Population); R = TS.G2.FreshBlood(FreshBlood);
{ Define User variables. }
R = TS.G2.Var("NetProfit"); R = TS.G2.Var("PF"); R = TS.G2.Var("MaxIDD");
{***Sets up new chromosomes and new genes. Chromosome Parameters: TS.G2.Chrom(Name) Name – name of chromosome. Gene Parameters: TS.G2.Gen(Name,Chrom,Min,Max,Incr) Name – name of gene. Chrom – number of chromosome that contains gene (if 0 then gene doesn’t participate in mutations, it’s fixed). Min – minimal value of gene. Max – maximal value of gene. Incr – value increase (step), if = 0 then any values in set range can be used.***}
K = TS.G2.Chrom("Buy.Signal"); R = TS.G2.Gen("Buy.Signal.Len1",K,1,50,1); R = TS.G2.Gen("Buy.Signal.Len2",K,1,50,1);
K = TS.G2.Chrom("Sell.Signal"); R = TS.G2.Gen("Sell.Signal.Len3",K,1,50,1); R = TS.G2.Gen("Sell.Signal.Len4",K,1,50,1);
K = TS.G2.Chrom("StopLoss"); R = TS.G2.Gen("StopLoss.SL",K,100,1000,100);
End;
{ The generation of a new candidate in the population }
LastRun = TS.G2.Next(Gen);
{ If this is the last path, shows results for Ind = ShowInd; Else get the next candidate Ind = 0; }
Ind = Iff(LastRun = 1,ShowInd,0);
{ Get values of genes for choosen candidate. }
Len1 = TS.G2.Get("Buy.Signal.Len1",Ind); Len2 = TS.G2.Get("Buy.Signal.Len2",Ind); Len3 = TS.G2.Get("Sell.Signal.Len3",Ind); Len4 = TS.G2.Get("Sell.Signal.Len4",Ind); SL = TS.G2.Get("StopLoss.SL" ,Ind); R = TS.G2.ShowViewer; End;
{ ---------------------------------------------------------------------- } { The basic strategy code. }
{ Set up the stop-loss parameter. }
SetStopPosition; SetStopLoss(SL);
{ The Moving Averages Calculation. }
Value1 = AverageFC(C,Len1); Value2 = AverageFC(C,Len2); Value3 = AverageFC(C,Len3); Value4 = AverageFC(C,Len4);
{ Generation of signals by moving averages crossover. According to the signal, short positions are reversed to long positions and vise versa. Besides, positions can be stopped by stop-loss and trailing-stop orders. }
if Value1 cross over Value2 then Buy This Bar ; if Value3 cross below Value4 then Sell This Bar ;
{ End the basic strategy code. } { ---------------------------------------------------------------------- }
{ Calculation an optimization criteria. The simplest criteria is used here. }
R = TS.G2.Stat;
if LastBarOnChart Then Begin
{ Save user defined data. }
R = TS.G2.Set("NetProfit",NetProfit); R = TS.G2.Set("PF",Iff(GrossLoss < 0,-GrossProfit/GrossLoss,0)); R = TS.G2.Set("MaxIDD",MaxIDDrawDown);
{ A fitness value is passed to the genetic optimizer on the last bar. If the candidates are included in the current population depends on the result of run. }
Fitness = TS.G2.Get("%T_Test",0); R = TS.G2.Fitness(Fitness);
{ One can look at all tested variants, assigning a print of the gene values for each generation. In PowerEditor in debug window to the debugger.}
{print(Gen,Fitness,Len1,Len2,Len3,Len4,SL,DT,FA,PC);} end;
{***** Copyright (c) 2001-2007 Trade Smart Research, Ltd. All rights reserved. www.tsresearch.com ***** ***** Trade Smart Research reserves the right to modify or overwrite this analysis technique with each release. *****}
|
|
Start example Strategy
After importing TSG2 Function, run TradeStation or Omega Research ProSuite, create Tradestation Chart and insert example Strategy.
Select Input parameter "Gen" and start optimize from 1 by step 1 to number of runs (for example 99) and run the optimization.
TSG2 will perform optimization of other parameters automatically and after completing the process it will present the optimization report.
To see the current population during optimization and the last population when optimization is finished you can use Reports Viewer:
You can start it from menu "Start" Windows ("...\Program files\TradeSmart\TSG2\TSG2.exe"). Besides that you can run it by double-clicking on the report file of optimization (file .rg2) and when starting or finishing optimization. By default reports of optimization are placed in the folder …\Program Files\TradeSmart\TSG2\Reports\ You can set any folder where it will be saved.
|
|
User interface
The results of optimizations performed by TSG2 are saved in a report file *.rg2 and can be viewed and analysed with the program Report Viewer, which is included in the installation package. The graphic interface of Report Viewer is a common window, in which several separate windows for every new testing system, that has it’s own name, are opened. You can run Report Viewer automatically at the start of optimization with a call to the function TS.G2.ShowViewer. With the help of Report Viewer you can analyse the data of exemplars, create all kinds of graphics and export data to a CSV format.
|
|
Report Viewer
Files for Report Viewer are saved automatically after the optimization is done. You can open the Data Sheet window for every report file, in which you’ll find columns, that show parameters that were optimized and statistics of system work, ordered up, and also numbers of subjects and their fitness in the order of dieing.
The background in the Data Sheet window has different colors, depending of the type of data assigned by the TS.G2.Criterion function.
Criterions by which minimum is searched TS.G2.Criterion(Name,-1), background color – yellow. Criterions by which maximum is searched TS.G2.Criterion(Name,2), background color – blue.
All other variables, that aren’t defined as criterions are shown on a white background.
During optimization, in the Date Sheet window you can observe changes of current system’s exemplars in on-line mode.
The version TSG2 allows you to see dynamics of changes and the interaction of any parameters between each other or with system statistics during the process of optimization with the help of additionally included diagrams and histograms. Generally, this gives you additional advantages in modeling and testing market systems.
|
|
Graphs
Using Report Viewer you can make graphics for data analysis, make diagrams and histograms. To make a histogram or diagram you have to right-click on the needed column in Data Sheet and choose what type of graphic you want.
Diagrams and histograms can be set up. You can choose parameters for viewing them and color schemes in menu. The actual values of your chosen parameters are also shown in diagrams and histograms.
The first number in brackets in the picture above is the average value of all individuals of the population in the column, the second number is their standard deviation. Values of the variable Z are shown in color. The minimum value of Z is shown in one color, e.g., green and these circles are on the bottom. The maximum value of Z is shown in another color, e.g., red and these circles are shown on the top.
The graphics sizes and positions are automatically saved on closing Report Viewer. When you open an earlier saved report, the data is automatically shown the way you last left it.
|
|
Function Description
The call to dll functions is made with the help of other functions, written in Easy Language. All functions used for work with TSG2 start with TS.G2.*** and end with the name of the function.
All functions of TSG2 can be relatively split into three groups: Optimization’s parameter input; Describing the exemplar’s structure; Managing the optimization process;
Note: Every previous signal works correctly with version TSG2 v2.x You just need to change TSGO to TSG2 in function names.
|
|
Optimizations Parameters
Optimization parameter input functions are referred to only one time on the first step of the optimizers work and in the very beginning of the system’s code. These functions define the optimization’s mode, population’s size and optimization’s method.
|
|
TS.G2.Mode(ModeGO)
Sets up the optimization mode.
Parameters: ModeGO – optimization mode. 0 – deletes old population and begins optimization from empty population. 1 – recalculates old population and continues optimization. 2 – continues optimization without recalculation of old population.
Returned values: 1 – successful completion. -1 – wrong number of mode.
Usage Example: EasyLanguage: { This block runs when the optimization is starting for the first bar only. }
If Gen = 1 Then Begin
{The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example.}
Value1 = TS.G2.Mode(0); End;
Function Code: EasyLanguage: Inputs: ModeGO(NumericSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Set_Mode",int; TS.G2.Mode = GO_Set_Mode(ModeGO);
|
|
TS.G2.Popul(NPop)
Sets up the size of population. Size of population in current version is limited from to an amount of 10 to 1000.
Parameters: NPop –size of population.
Returned values: 1 – successful completion. -1 – wrong size of population.
Usage Example: EasyLanguage: { This block runs when the optimization is starting for the first bar only. }
If Gen = 1 Then Begin
{The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example.}
Value1 = TS.G2.Popul(50); End;
Function Code: EasyLanguage: Inputs: NPop(NumericSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Set_Population",int; TS.G2.Popul = GO_Set_Population(NPop);
|
|
TS.G2.Method (Method)
Optimization method. (For version TSG2 v 2.x and higher) Has 1 parameter. Values = 0, 1, 2.
Parameters: 0 – The method, used in version TSGO v1.5 and older – searching maximum by one parameter. Using this method you have to input the criterion of optimization (fitness) with the function TS.G2.Fitness.
1 – A method to search for the best of the best exemplars by many criterions simultaneously. In this method systems with best (highest or lowest) criterion values are considered to be good. See description of the function TS.G2.Criterion for further details. Basically, this is a usual search for the best exemplar by many criterions.This method gives results, which are close to the Paretto method.
2 – Method Minimax. A method to seek for the best exemplar of the worst by one parameter. In this method the exemplar that is the best by its worst parameter is considered to be the best. A search for the maximum in the weakest parameter of the copy.
In methods 1 and 2, optimization criterions are announced with the function TS.G2.Criterion, values are entered with the function TS.G2.Set.
Attention: The function TS.G2.Fitness is called as the last in the signal’s code. By using optimization methods 1 or 2 their parameter values are ignored.
Usage Example: EasyLanguage: { This block runs when the optimization is starting for the first bar only. }
If Gen = 1 Then Begin
{The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example.}
Value1 = TS.G2.Method(1); End;
Function Code: EasyLanguage: Inputs: MethodGO(NumericSimple); DefineDLLFunc: "TSG2.dll", int, "GO_Set_Method",int;
TS.G2.Method = GO_Set_Method(MethodGO);
|
|
TS.G2.FreshBlood(FB_factor)
Sets up value of factor "fresh blood" in population. This function increases effective size of population prohibiting possibilities of leader’s domination and giving chance to other candidates. Thus optimization is accelerated using varying genes bank and avoiding over fitting the system.
Parameters: FB_factor – value of factor. =0 – function is turned off, work is same as it was in previous version. >0 – additional mixing of population is turned on, typical value is 1. Returned values: 1 – normal completion. -1 – wrong value of parameter (<0).
Usage Example: It’s not necessary to include FreshBlood, optimizator works correctly anyway with population 1000. FreshBlood increases effective size of population. When FreshBlood > 0 some good samples are avoided from population and some bad samples are left. This way some kind of variety is left in population as it is in a big population. FreshBlood tries to avoid curve fitting using emulation of fitness. Unfortunately this method only decreases possibility of curve fitting. FreshBlood > 0 increases range of search and decreases speed.
EasyLanguage: If Gen = 1 Then Begin { The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example. }
R = TS.G2.Mode(0); R = TS.G2.Popul(50); R = TS.G2.FreshBlood(3); End;
Function Code: EasyLanguage:
Inputs: FB_factor(NumericSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Set_FreshBlood",float; TS.G2.FreshBlood = GO_Set_FreshBlood(FB_factor);
|
|
Exemplar Structure
Functions to describe an exemplar’s structure, create signal structure with setting parameters and conditions of genetic optimization.
|
|
TS.G2.Gen(Name,Chrom,Min,Max,Incr)
Sets up new gene or search of existing gene.
Parameters: Name – name of gene. Chrom – number of chromosome that contains gene (if equal to 0 then gene doesn’t participate in mutations, it’s fixed). Min – minimal value of gene. Max – maximal value of gene. Incr – value increase (step), if = 0 then any values in set range can be used.
Returned values: >0 – number of found or created genes. -1 – wrong name of gene (for example it is blank). -2 – array of genes overloaded (in new version max. number of genes = 1000). -3 – wrong number of chromosome (<0 or chromosome is not defined).
Usage Example: EasyLanguage: If Gen = 1 Then Begin
{ The description of 5 genes is as follows. The First parameter - a gene number. If it's zero, generate gene number. The Second parameter - a chromosome number that the gene belongs to. The Third parameter - a minimum parameter value. The Fourth parameter - a maximum parameter value. The Fifth parameter - an increment of the parameter. It is possible to assign 0. Sixth parameter - a name of the gene, one can use it as a commentary in the graphic interface. }
K = TS.G2.Chrom("Buy.Signal"); R = TS.G2.Gen("Len1",K,1,50,1); R = TS.G2.Gen("Len2",K,1,50,1);
K = TS.G2.Chrom("Sell.Signal"); R = TS.G2.Gen("Len3",K,1,50,1); R = TS.G2.Gen("Len4",K,1,50,1);
K = TS.G2.Chrom("StopLoss"); R = TS.G2.Gen("SL",K,100,1000,100); End;
Function Code: EasyLanguage: Inputs: GName(StringSimple), Chrom(NumericSimple), Min(NumericSimple), Max(NumericSimple), Incr(NumericSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Def_Gen",int,int,float,float,float,LPSTR; TS.G2.Gen = GO_Def_Gen(0,Chrom,Min,Max,Incr,GName);
|
|
TS.G2.Chrom(Name)
Sets up new chromosome or search of existing chromosome.
Parameters: Sets up new chromosome or search of existing chromosome.
Parameters: Name – name of chromosome.
Returned values: >0 – number of found or created chromosomes. -1 – wrong name of chromosome (for example it is blank). -2 – array of chromosomes is overloaded (in new version max. number of chromosomes is equal to 1000). Usage Example:
EasyLanguage: If Gen = 1 Then Begin
{ The description of 5 genes is as follows. The First parameter - a gene number. If it's zero, generate gene number. The Second parameter - a chromosome number that the gene belongs to. The Third parameter - a minimum parameter value. The Fourth parameter - a maximum parameter value. The Fifth parameter - an increment of the parameter. It is possible to assign 0. Sixth parameter - a name of the gene, one can use it as a commentary in the graphic interface. }
K = TS.G2.Chrom("Buy.Signal"); R = TS.G2.Gen("Len1",K,1,50,1); R = TS.G2.Gen("Len2",K,1,50,1);
K = TS.G2.Chrom("Sell.Signal"); R = TS.G2.Gen("Len3",K,1,50,1); R = TS.G2.Gen("Len4",K,1,50,1);
K = TS.G2.Chrom("StopLoss"); R = TS.G2.Gen("SL",K,100,1000,100); End;
Function Code: EasyLanguage: Inputs: Name(StringSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Def_Chrom",LPSTR; TS.G2.Chrom = GO_Def_Chrom(Name);
|
|
TS.G2.Var(Name)
Creates user’s variable. Variable is tied to sample of population and allows to keep and choose user data. This data is displayed in viewer together with gene values and can be extracted into Excel for further analysis. Also they can be used for transferring data among functions in one strategy. Usage of this function is not necessary because variable is created automatically on attempt to write in it. This function can be used to reserve order of variables (order of columns in viewer).
Parameters: Name – name of users variable.
Returned values: >0 – number of gene where variable is written. -1 – wrong name of variable (for example it is blank). -2 – table of genes and variables is overloaded (it’s size in current version is 1000).
Usage Example: EasyLanguage: If Gen = 1 Then Begin
{ The initializing of optimizer determination of genes and the population regime is executed (see the description of functions). We start optimizer with empty population in a given example. }
R = TS.G2.Mode(0); R = TS.G2.Popul(50); R = TS.G2.FreshBlood(3);
{ Define User variables. }
R = TS.G2.Var("NetProfit"); R = TS.G2.Var("PF"); R = TS.G2.Var("MaxIDD"); End;
Function Code: EasyLanguage: Inputs: Name(StringSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Def_Gen",int,int,float,float,float,LPSTR; TS.G2.Var = GO_Def_Gen(0,0,0,0,0,Name);
|
|
TS.G2.Criterion(Name,Type)
Announces the variable "Name" as an optimization criterion. Is used at function’s values TS.G2.Method = 1 or 2. Parameters: Name – criterion name; Type – way of criterion usage: 0 – ignore criterion; +1 – look for maximum of criterion; -1 – look for minimum of criterion;
Usage example: A criterion’s value is entered with the function TS.G2.Set (Name,Val). Variable Val in TS.G2.Set can be anything, e.g., NetProfit, MaxIDDrawDown, Totaltrades. When using several criterions you are able to input any combinations of system searching by your needed criterions. E.g. with maximum NetProfit, minimum MaxDrawDown and maximum Profit Factor etc. The amount of criterions is only limited to the total amount of an exemplar’s variables – 1000. At a large number of criterions, like a few hundreds, the time taken to generate a new exemplar is going to increase. It is possible to create criterions any time during the run. The only thing important is that it must have it’s value assigned to it before the call to the function TS.G2.Fitness(0) is made.
EasyLanguage: if CurrentBar = 1 Then Begin R = TS.G2.Method(1); R = TS.G2.Criterion("NetProfit",1); R = TS.G2.Criterion("MaxDD",1); R = TS.G2.Criterion("PF",1); End;
Function Code: Easy Language: Inputs: Name(StringSimple),Val(NumericSimple); DefineDLLFunc: "TSG2.dll", int, "GO_Set_Criterion",LPSTR,int;
TS.G2.Criterion = GO_Set_Criterion(Name,Val);
|
|
Optimization Control
|
|
TS.G2.Start(FileName)
Starts the optimization and sets the name of file for current population storage. This function always should be called on the first bar.
Parameters: FileName – name of the file for current population storage. If special folder is not set then the file will be created in Reports folder (for example: ...\ProgramFiles\TradeSmart\TSG2\Reports ).
Return of value: 1 – successful completion. -1 – error creating a new file or opening an indicated file.
Usage Example: EasyLanguage: If CurrentBar = 1 Then Begin
Value1 =TS.G2.Start("MyName");
End;
Function Code: EasyLanguage: Inputs: FName(StringSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Start",LPSTR; TS.G2.Start = GO_Start(FName);
|
|
TS.GO.ShowViewer
Show Viewer immediately. No Parameters.
Usage Example: EasyLanguage: If CurrentBar = 1 Then Begin Value1 =TS.G2.ShowViewer; End;
Function Code: EasyLanguage: DefineDLLFunc: "TSG2.dll", int, "GO_Show_Viewer";
|
|
TS.G2.Next(Generation)
Generates new candidate of population or determines the best candidate of population. The end of optimization (final run on strategy) is determined by the value of parameter "Generation" <= than value in previous run.
Parameters: Generation – number of generation. It should be growing value.
Returned values: 1 – last run of strategy after finishing optimization. The best sample of population will be marked. 0 – instant run of optimization. Instant candidate of population is generated.
Usage Example: EasyLanguage: Input: ShowInd(1); Var:LastRun (0),Ind(0); { The generation of a new candidate in the population } LastRun = TS.G2.Next(Gen); { If this is the last path, shows results for Ind = ShowInd; Else get the next candidate Ind = 0; } Ind = Iff(LastRun = 1,ShowInd,0);
Function Code: EasyLanguage: Inputs: Generation(NumericSimple);
DefineDLLFunc: "TSG2.dll", int, "GO_Next",int; TS.G2.Next = GO_Next(Generation);
|
|
TS.G2.Get(Name,Individ)
Gets value of gene or variable of user by "Name" from sample number "Individ".
Parameters: Name – name of gene or users variable. For reading value of fitness, fixed name "Fitness" is used. Individ – number of sample in population from which value of gene is read. 1 - the best sample. 2 - next sample. 0 - special value. During optimization data of regular candidate of population is returned but at the last run data of best candidate is returned.
Returned values: Value of gene or parameter of user is returned. Error codes (can be obtained with function TS.G2.Error): 1 - normal completion. -1 - wrong name of gene (it is blank or missing). -2 - wrong number of sample (< 0 or > size of population).
Usage Example: EasyLanguage:
If Gen = 1 Then Begin { Get values of genes for choosen candidate. }
Len1 = TS.G2.Get("Len1",Ind); Len2 = TS.G2.Get("Len2",Ind); Len3 = TS.G2.Get("Len3",Ind); Len4 = TS.G2.Get("Len4",Ind); SL = TS.G2.Get("SL" ,Ind); End;
Function Code: EasyLanguage: Inputs: Name(StringSimple),Individ(NumericSimple); DefineDLLFunc: "TSG2.dll", float, "GO_Get_Gen",LPSTR,int; TS.G2.Get = GO_Get_Gen(Name,Individ);
|
|
TS.G2.Set(Name,Val)
Sets new value of users variable for current sample of population. This function should be called after function TS.G2.Next and before TS.G2.Fitness.
Parameters: Name – name of users variable. Val – written value.
Returned values: >0 – normal completion. Number of gene is returned. -1 – wrong name of variable (for example it is blank). -2 – table of genes or variables is overloaded (it’s size in current version is 1000).
Usage Example: EasyLanguage: if LastBarOnChart Then Begin { Save user defined data. } R = TS.G2.Set("NetProfit",NetProfit); R = TS.G2.Set("PF",Iff(GrossLoss < 0,-GrossProfit/GrossLoss,0)); R = TS.G2.Set("MaxIDD",MaxIDDrawDown); End;
Function Code: EasyLanguage: Inputs: Name(StringSimple),Val(NumericSimple); DefineDLLFunc: "TSG2.dll", int, "GO_Set_Gen",LPSTR,float; TS.G2.Set = GO_Set_Gen(Name,Val);
|
|
TS.G2.Finish
Returns the indication of the last run of strategy.
No parameters.
Returned values: 1 – the last run of strategy after finishing optimization. 0 – instant run of optimization.
Usage Example: EasyLanguage: Value1 = TS.G2.Finish;
Function Code: EasyLanguage: DefineDLLFunc: "TSG2.dll", int, "GO_IsFinish"; TS.G2.Finish = GO_IsFinish;
|
|
TS.G2.Default("VarName",DefValue)
Sets default value of exemplar’s variable. If this function is not called, 0 is considered to be the default value. A call to the function TS.G2.Default allows you to change this. Default values are used when creating a new exemplar. At this point all exemplar’s variables are assigned their default values and new ones are generated for their genes.
Parameters: "VarName" – the variable’s name, that you are creating the default value for; DefValue – default value.
No returned values:
Usage Example: EasyLanguage: R = TS.G2.Default("MyVariable",-1);
Function Code: EasyLanguage: Inputs: Name(StringSimple),Val(NumericSimple); DefineDLLFunc: "TSG2.dll", float, "GO_Set_Default",LPSTR,float; TS.G2.Default = GO_Set_Default(Name,Val);
|
|
TS.G2.BadIndividual
Marks the exemplar currently being tested as bad. This exemplar will not be added to the population and will not influence any heirs.
No parameters. No returned values.
Usage Example: EasyLanguage: If MaxIDDrawDown < -10000 Then R = TS.G2.BadIndividual;
Function Code: EasyLanguage: DefineDLLFunc: "TSG2.dll", int, "GO_Set_Constrain"; TS.G2.BadIndividual = GO_Set_Constrain;
|
|
TS.G2.Fitness(Fitness)
Informs about results of executed run on system. When optimizing with one criterion (TS.G2.Method(0)) the parameter Fitness transfers the criterion’s optimization value. When optimizing by many criterions the parameter is ignored. Software uses the following assumption – negative value of Fitness is bad, so these samples are not included in population.
Parameters: Fitness – value of optimization criterion following the results of system.
Returned values: 1 – successful completion.
Usage Example: EasyLanguage: { A fitness value is passed to the genetic optimizer on the last bar. If the candidates are included in the current population depends on the result of run. }
Fitness = NetProfit + OpenPositionProfit; R = TS.G2.Fitness(Fitness);
Function Code: EasyLanguage: Inputs: Fitness(NumericSimple); DefineDLLFunc: "TSG2.dll", int, "GO_Fitness",float; TS.G2.Fitness = GO_Fitness(Fitness);
|
|
TS.G2.Error
Returns error code of performed function.
No parameters. Returned values: >0 – normal completion. =0 – normal completion, special case. <0 – code of error.
Usage Example: EasyLanguage: If TS.G2.Error < 0 Then { Your condition };
Function Code: EasyLanguage: DefineDLLFunc: "TSG2.dll", int, "GO_Error"; TS.G2.Error = GO_Error;
|
|
TS.G2.Stat
This function calculates different statistics of system in EasyLanguage. Obtained statistical results are saved in GO file in users variables. They are tied to current testing sample. It’s possible: * to see them in Report Viewer, * extract them in Excel for analysis, * use them as fitness in optimization, * they can be viewed as built in fitness.
No parameters.
Returned values: 1 – successful completion.
Usage Example: EasyLanguage: { Call of functions for statistics calculation } { Should be called on every bar }
R = TS.G2.Stat; if LastBarOnChart Then Begin { Selection of calculated t_Test for current sample}
Fitness = TS.G2.Get("%T_Test",0);
{ Transmiting of fitness } R = TS.G2.Fitness(Fitness);
Function Code: EasyLanguage:
Vars: MP(0),TotTr(0),Winners(0),ConsecWin(0),MaxConsecWin(0),ConsecLoss(0), WinLoss2(0),WinLoss1(0),MaxWinner(0),SumWin(0),Losers(0),MaxConsecLoss(0), MaxLoser(0),SumLoss(0),ChPos(0),CumProf(1),EqTop(0),TopBar(0),EqBot(0), TopInt(0),FlatTime(0),DD(0),MaxDD(0),AvgTrade(0),DevTrade(0),t_Test(0),Pf(0); Vars: R(0); Array: Prof[10000](0);
MP = MarketPosition; TotTr = MinList(10000,TotalTrades);
if MP <> MP[1] and MP[1] <> 0 then begin Prof[TotTr] = MP[1] * (ExitPrice(1) - EntryPrice(1)) / EntryPrice(1); if Prof[TotTr] > 0 then begin Winners = Winners + 1; ConsecWin = ConsecWin + 1; MaxConsecWin = MaxList(MaxConsecWin, ConsecWin); ConsecLoss = 0; WinLoss2 = WinLoss1; WinLoss1 = 1; Condition1 = true; MaxWinner = MaxList(MaxWinner, Prof[TotTr]); SumWin = SumWin + Prof[TotTr]; end else begin Losers = TotTr - Winners; ConsecLoss = ConsecLoss + 1; MaxConsecLoss = MaxList(MaxConsecLoss, ConsecLoss); ConsecWin = 0; WinLoss2 = WinLoss1; WinLoss1 = -1; Condition1 = true; MaxLoser = MinList(MaxLoser, Prof[TotTr]); SumLoss = SumLoss + Prof[TotTr]; end; if Condition1 then if WinLoss1 <> WinLoss2 then ChPos = ChPos + 1; CumProf = CumProf * (1 + Prof[TotTr]); EqTop = MaxList(EqTop, CumProf); if EqTop > EqTop[1] then begin TopBar = CurrentBar; EqBot = EqTop; end; EqBot = MinList(EqBot, CumProf); TopInt = CurrentBar - TopBar; FlatTime = MaxList(TopInt, FlatTime); if EqTop > 0 then DD = (CumProf/EqTop - 1); MaxDD = MinList(MaxDD, DD); AvgTrade = Average_a(Prof, TotTr); If TotTr > 1 then DevTrade = StdDevS_a(Prof, TotTr); t_Test = Iff(DevTrade > 0, AvgTrade / DevTrade * SquareRoot(TotTr), 0);
Pf = Iff(GrossLoss < 0,-(GrossProfit - LargestWinTrade)/GrossLoss,0); R = TS.GO.Set("NetProfit",NetProfit); R = TS.GO.Set("PF",Pf); R = TS.GO.Set("MaxDD",MaxIDDrawDown); R = TS.GO.Set("Trades",TotalTrades); R = TS.GO.Set("PercentProfit",PercentProfit); R = TS.GO.Set("MaxWin",LargestWinTrade); R = TS.GO.Set("MaxLoss",LargestLosTrade); R = TS.GO.Set("Winners",Winners); R = TS.GO.Set("Losers",Losers); R = TS.GO.Set("MaxConsecWin",MaxConsecWin); R = TS.GO.Set("MaxConsecLoss",MaxConsecLoss); R = TS.GO.Set("ChPos",ChPos); R = TS.GO.Set("%MaxWin",MaxWinner*100); R = TS.GO.Set("%SumWin",SumWin*100); R = TS.GO.Set("%MaxLoss",MaxLoser*100); R = TS.GO.Set("%SumLoss",SumLoss*100); R = TS.GO.Set("%CumProf",CumProf*100); R = TS.GO.Set("%MaxDD",MaxDD*100); R = TS.GO.Set("%AvgTrade",AvgTrade*100); R = TS.GO.Set("%DevTrade",DevTrade*100); R = TS.GO.Set("%T_Test",t_Test); end; TS.G2.Stat = 1;
|