Genetic Optimizer for TradeStation

This program is to incredible improving of TradeStation abilities of design, testing and optimization of trading strategies.
We can offer the add-on for TradeStation (TradeStation Group, Inc.)
which realizes the advanced optimization methods based on Genetic Algorithms.
| Download demo
|How to Buy|
Ask here|
F.A.Q.|
EasyLanguage Code Converter|
The main advantages of TS Genetic Optimizer for
TradeStation:
- Speeding-up of optimization, fast convergence to optimal solution;
- Unlimited number of optimized parameters (up to 100 in the current version);
- Unlimited calculation of parameter’s accuracy;
- Usage of any complex optimization criteria (written in Easy Language), for example, considered
maximal drawdown, equity line shape, etc.;
- It is possible to give any constraints in optimization problem. For example, to reject
strategies which have too many trades or few trades or exceeds the given threshold for maximal
drawdown;
- Structural optimization ability that is building of complex strategy, automatically switched to
different assets and timeframes;
- Visualization of strategy testing results in sample (optimization data) and out of sample
(testing data) simultaneously.
- Ability to get a set of Trading Systems which are close to optimal (last population). They can
be composed as the trading system portfolio.
What are Genetic Algorithms
Genetic Algorithms has appeared recently. They combine the best characteristics of other
optimization methods such as speedy work that doesn’t depend on properties of optimization criteria
(like smoothness). They provide optimal solution on a vast domain.
The name Genetic Algorithms is connected with the fact that their work is similar to natural
selection in the Nature. Therefore it uses the Biology and Genetics terms like gene, chromosome,
fitness, population etc. in the description of Genetic Algorithms.
Genetic Algorithms work is similar to random sort out (Monte Carlo method). In contrast to Monte
Carlo method the search is led purposefully. The goal of Algorithm is to get some specimens
(population) with the best fitness (optimization criteria) values.
Work of Genetic Optimizer can be considered as the growth of the best population of Trading Systems
most adapted to the successful and stable functioning according to the given fitness criteria.
The Brand New approach to Trading System Design
The common approach to the trading system design is the following routine:
Begin (*)
Choose the parameters:
- Asset.
- Time Frame.
- Concept (trend following, patterns etc.).
- Formalization via indicators.
- Feasible sets of indicator’s parameters.
- Signal generation rules.
- Order types.
- Look through parameters in sample data.
- Estimation of parameters according to a criterion (Net Profit, Profit Factor etc.) to choose
the best parameters’ set.
- If the results of item 9 are satisfactory load out-of-sample data and testing the trading
system for the best parameters’ set.
- If the result of item 10 differs from the result of item 9 within acceptable bounds then go out
else go to (*).
End.
It is possible to include the additional parameters:
- Position size calculation.
- Asset share calculation, or Portfolio optimization.
In fact all steps are led by the random search except for item 8 where parameters’ values are
defined by enumeration of all possibilities. At the same time sorting is led by one of the
TradeStation performance criteria (Profit Factor for example). The cycle stops if the satisfactory
result is got. Using the algorithm man-hours are tremendous. The resulting trading system is hardly
optimal.
Following the principle “human should thinking, machine should working” we suggest replace the
above routine to the following:
- Choose the parameters:
- Admitted asset candidates.
- Possible time frames.
- Admitted concept set.
- possible indicator set by which admitted concepts can be formalized.
- Feasible sets of indicator’s parameters.
- Elementary rule set from which any signal can be generated.
- All possible orders with its parameters.
- Assign optimization criterion of any complexity and with any constraints.
- Set Genetic Algorithm parameters.
- Set out-of-sample data interval.
- Run TS GO Genetic Optimizer.
For a few minutes we shall get a set of optimal trading systems, according to our fitness
criterion, tested in out-of-sample data. All we need is to choose reasonable parameters’
bounds and meaningful optimization criterion.
System definition
The system concludes program with graphic interface assigned for examination parameters of received
Trading System population and program module which provides interaction of set of strategy elements
with genetic optimizer and written in Easy Language.
The Trading System population is saved in the file which user set.
Later on one can see the results using graphic interface.
The system gives you a chance to continue optimization from the moment you stopped. For example,
you can run optimization for 100 steps, look at the results, and then run for more 100 steps
starting from the last result.
Besides, you can re-count received population and continue your calculation in external changes,
For example, on the next bar. And all the members of population are optimized on the new bar. This
let you make more precise definition of parameters on each bar and therefore let you build adaptive
to market changes Trading System populations.
Program interface
To arrange the cycle by generations the default TradeStation optimizer is used. To do that one has
to define input parameter Gen (generation) in the strategy:
Input: Gen(1);
To start genetic optimization it is necessary to set optimization in TradeStation by this parameter
from 1 to required number of generations, for example, to 1000 (Format Strategy -> Inputs -> Edit
Input -> Optimize).
On the first bar we start Genetic Optimizer for a strategy where genes (optimization parameters)
and chromosomes (blocks of parameters) are defined. Besides, we get strategy parameter values from
the module of Genetic Optimizer.
On the last bar the fitness function is called which informs about the results of Genetic Optimizer
run. In accordance with the received values optimizer module changes current Trading System
population and defines the candidate for the new run.
List of Functions of Trade Smart Genetic
Optimizer
|
Function Description
|
TSGO Free Version
|
TSGO Version 1.4
|
Function: TS.GO.Start
Starts the optimization and sets the name
of file for current
population storage. This function always
should be called on the first
bar
|
Yes
|
Yes
|
Function: TS.GO.Mode Sets up
the
optimization mode
|
Mode only 0
|
All Mode
|
Function: TS.GO.Popul Sets up
the
size of population.
Size of population in version 1.4 is
limited from 10 to 1000
|
10 - 50
|
10 - 1000
|
Function: TS.GO.Gen Sets up new
gene or search of existing gene.
|
Yes
|
Yes
|
Function: TS.GO.Next Generates
new candidate of population or determines
the best candidate of
population.
|
Yes
|
Yes
|
Function: TS.GO.Finish Returns
the characteristics of the last run of
strategy.
|
Yes
|
Yes
|
Function: TS.GO.Error Returns
error code of performed function.
|
Yes
|
Yes
|
Function: TS.GO.Var Creates
users
variable.
|
Yes
|
Yes
|
Function: TS.GO.Get Gets value
of
gene or variable of user by “Name” from
sample number “Individ”.
|
Yes
|
Yes
|
Function: TS.GO.Set Sets new
value of users variable for current
sample of population.
|
Yes
|
Yes
|
Function: TS.GO.Fitness Informs
about results of executed run on
system.
|
Yes
|
Yes
|
Function: TS.GO.FreshBlood Sets
up value of factor "fresh
blood" in population.
|
Mode only 0
|
All Mode
|
Function: TS.GO.Stat This
function calculates different statistics
of system in EasyLanguage.
|
Yes
|
Yes
|
Function: TS.GO.ShowViewer
Show Viewer immediately.
|
Yes
|
Yes
|
|
Iteration Count
|
100
|
Not Limited
|
An example of simplest strategy
Consider the simplest strategy as example for demonstration Genetic Optimizer use.
The strategy is based on moving averages crossover, for which moving average periods are selected.
One pair is used for entry signals and another pair is used for exit signals. Besides, TradeStation
built-in signals for stop-loss and trailing stop value fitting are used.
| EasyLanguage: | {******************************************************************* Name: TS.GO.12.Ex1 Analysis Type: Strategy Description: Example Strategy for Genetic Optimizer v.1.4 or Higher without Out of Sample Example of simple trading system to show the possibilities of Genetic Optimizer for TradeStation. The system is based on 2 moving average crossover. Buy signal is generated when fast moving average crosses over slow moving average. Additionaly Stop-loss is included in the system. Used: TSGO12.dll Provided By: Trade Smart Research (c) Copyright 2001 - 2004 www.tsresearchgroup.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),DT(0),FA(0),PC(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.GO.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.GO.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.GO.Mode(ModeTSGO); R = TS.GO.Popul(Population); R = TS.GO.FreshBlood(FreshBlood); { Define User variables. } R = TS.GO.Var("NetProfit"); R = TS.GO.Var("PF"); R = TS.GO.Var("MaxIDD"); {***Sets up new chromosomes and new genes. Chromosome Parameters: TS.GO.Chrom(Name) Name – name of chromosome. Gene Parameters: TS.GO.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.GO.Chrom("Buy.Signal"); R = TS.GO.Gen("Buy.Signal.Len1",K,1,50,1); R = TS.GO.Gen("Buy.Signal.Len2",K,1,50,1); K = TS.GO.Chrom("Sell.Signal"); R = TS.GO.Gen("Sell.Signal.Len3",K,1,50,1); R = TS.GO.Gen("Sell.Signal.Len4",K,1,50,1); K = TS.GO.Chrom("StopLoss"); R = TS.GO.Gen("StopLoss.SL",K,1,1000,1); K = TS.GO.Chrom("DollarTraling"); R = TS.GO.Gen("DollarTraling.DT",K,1,1000,1); K = TS.GO.Chrom("PercentTraling"); R = TS.GO.Gen("PercentTraling.FA",K,1,1000,1); R = TS.GO.Gen("PercentTraling.PC",K,1,100,1); End; { The generation of a new candidate in the population } LastRun = TS.GO.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.GO.Get("Buy.Signal.Len1",Ind); Len2 = TS.GO.Get("Buy.Signal.Len2",Ind); Len3 = TS.GO.Get("Sell.Signal.Len3",Ind); Len4 = TS.GO.Get("Sell.Signal.Len4",Ind); SL = TS.GO.Get("StopLoss.SL",Ind); DT = TS.GO.Get("DollarTraling.DT",Ind); FA = TS.GO.Get("PercentTraling.FA",Ind); PC = TS.GO.Get("PercentTraling.PC",Ind); R = TS.GO.ShowViewer; End; { ---------------------------------------------------------------------- } { The basic strategy code. } { Set up the stop-loss and traling-stop parameter. } SetStopPosition; SetStopLoss(SL); SetDollarTrailing(DT); SetPercentTrailing(FA,PC); { 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; if Value3 cross below Value4 then Sell; { End the basic strategy code. } { ---------------------------------------------------------------------- } { Calculation an optimization criteria. The simplest criteria is used here. } Fitness = NetProfit + OpenPositionProfit; if LastBarOnChart Then Begin { Save user defined data. } R = TS.GO.Set("NetProfit",NetProfit); R = TS.GO.Set("PF",Iff(GrossLoss < 0,-GrossProfit/GrossLoss,0)); R = TS.GO.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. } R = TS.GO.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-2004 Trade Smart Research, Ltd. All rights reserved. www.tsresearchgroup.com ***** ***** Trade Smart Research reserves the right to modify or overwrite this analysis technique with each release. *****}
|
To start Genetic Optimizer it is necessary to apply a strategy to a graph and to set optimization
for parameter Gen from 1 to some large number with a step 1. The number defines how many
generations will passed. Usually it is from hundreds to thousands.
After the optimization start TradeStation alerts that input has a maximum value that is greater
then the current MaxBarsBack setting. Do not care, push “Continue” button.
During the work TradeStation computes its own optimization criterion parallel to Genetic Optimizer
that guided by a given fitness. Therefore optimal solution must not have the best TradeStation
criterion value.
The results of strategy testing
Below there are given the result of strategy testing on hourly and daily FOREX EURJPY bars. Maximal
number of generations was set 1111, so the same number of parameters combinations has been tested.
The total number of possible combinations that will have to test in standard TradeStation optimizer
is 6.25 * 1017. Genetic Optimizer spent for it about a minute.

Picture 1. The result of strategy testing on daily EURJPY bars in TS GO Viewer.
Here are shown some best Trading System copies from the last population. The best one from Picture
1 have the following parameters:
Len1 = 39
Len2 = 40
Len3 = 31
Len4 = 9
SL = 407
DT = 810
FA = 997
PC = 6
Below signals of the Trading System are shown.

Picture 2. The results on EURJPY (Daily).
It is tested on 1000 days.
Results are in pips.
Spread is 10 pips.
TradeStation Strategy Performance Report

Picture 2. The results on EURJPY (60 min.).
It is tested on 50 days.
Results are in pips.
Spread is 10 pips.
TradeStation Strategy Performance Report
Testing Out Of Sample
TO demonstrate optimization In Sample and testing Out Of Sample simultaneously we use the slightly
modified example of strategy above.
In the signal are add 2 input parameters, assign beginning and end of area, on which is conduct
optimization (In Sample). Beginning and end will be assign by the bar number, brushed off from the
last bar a graphics.
| EasyLanguage: | {******************************************************************* Name: TS.GO.12.Ex2 Analysis Type: Strategy Description: Example Strategy for Genetic Optimizer v.1.4 or Higher with Out of Sample Example of simple trading system to show the possibilities of Genetic Optimizer for TradeStation. The system is based on 2 moving average crossover. Buy signal is generated when fast moving average crosses over slow moving average. Additionaly Stop-loss is included in the system. Used: TSGO12.dll Provided By: Trade Smart Research (c) Copyright 2001 - 2004 www.tsresearchgroup.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"), Dstart(60000), {Day number from the end of data, start In Sample data} Dstop(0); {Day number from the end of data, end In Sample data} {For example - Dstop = 365 - OOS is 365 last days} { Declaration of variables } Vars: Len1(0),Len2(0),Len3(0),Len4(0),SL(0),DT(0),FA(0),PC(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.GO.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.GO.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.GO.Mode(ModeTSGO); R = TS.GO.Popul(Population); R = TS.GO.FreshBlood(FreshBlood); {***Sets up new chromosomes and new genes. Chromosome Parameters: TS.GO.Chrom(Name) Name – name of chromosome. Gene Parameters: TS.GO.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.GO.Chrom("Buy.Signal"); R = TS.GO.Gen("Buy.Signal.Len1",K,1,50,1); R = TS.GO.Gen("Buy.Signal.Len2",K,1,50,1); K = TS.GO.Chrom("Sell.Signal"); R = TS.GO.Gen("Sell.Signal.Len3",K,1,50,1); R = TS.GO.Gen("Sell.Signal.Len4",K,1,50,1); K = TS.GO.Chrom("StopLoss"); R = TS.GO.Gen("StopLoss.SL",K,1,1000,1); K = TS.GO.Chrom("DollarTraling"); R = TS.GO.Gen("DollarTraling.DT",K,1,1000,1); K = TS.GO.Chrom("PercentTraling"); R = TS.GO.Gen("PercentTraling.FA",K,1,1000,1); R = TS.GO.Gen("PercentTraling.PC",K,1,100,1); End; { The generation of a new candidate in the population } LastRun = TS.GO.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.GO.Get("Buy.Signal.Len1",Ind); Len2 = TS.GO.Get("Buy.Signal.Len2",Ind); Len3 = TS.GO.Get("Sell.Signal.Len3",Ind); Len4 = TS.GO.Get("Sell.Signal.Len4",Ind); SL = TS.GO.Get("StopLoss.SL",Ind); DT = TS.GO.Get("DollarTraling.DT",Ind); FA = TS.GO.Get("PercentTraling.FA",Ind); PC = TS.GO.Get("PercentTraling.PC",Ind); R = TS.GO.ShowViewer; End; { ---------------------------------------------------------------------- } { The basic strategy code. } { Set up the stop-loss and traling-stop parameter. } SetStopPosition; SetStopLoss(SL); SetDollarTrailing(DT); SetPercentTrailing(FA,PC); { 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; if Value3 cross below Value4 then Sell; { End the basic strategy code. } { ---------------------------------------------------------------------- } Var: Fitness1(0),Fitness2(0); { Compute fitness } Fitness = NetProfit + OpenPositionProfit; { Keep in mind the fitness value on the first bar In Sample, Paint vertical bar marked the OOS period beginning. } R = LastCalcJDate - DStart; if DateToJulian(Date[1]) < R and DateToJulian(Date) >= R then Begin Fitness1 = Fitness; R = TL_New(Date, Time, High, Date, Time, Low); TL_SetExtLeft (R, True); TL_SetExtRight(R, True); TL_SetColor(R, Blue); end; { Pass the fitness value on the last bar In Sample, Paint vertical bar marked the OOS period finish } R = LastCalcJDate - DStop; if DateToJulian(Date[1]) < R and DateToJulian(Date) >= R then Begin Fitness2 = Fitness; R = TS.GO.Fitness (Fitness - Fitness1); R = TL_New(Date, Time, High, Date, Time, Low); TL_SetExtLeft (R, True); TL_SetExtRight(R, True); TL_SetColor(R, Blue); end; {***** Copyright (c) 2001-2004 Trade Smart Research, Ltd. All rights reserved. www.tsresearchgroup.com ***** ***** Trade Smart Research reserves the right to modify or overwrite this analysis technique with each release. *****}
|
The Signal is the same as above except for the last block.
As optimization criterion we use Fitness value difference for the bar that located DStart bars to
the left from the last bar and for the bar that located DStop bars to the left from the last bar
in contrast to standard TradeStation optimizer. As a result bars from DStart to DStop are not used
in optimization. They are Out Of Sample.
Below there are shown signals of the Trading System. Vertical red bar in the center of the picture
separates data on In Sample (on the left) and Out of Sample (on the right).
Picture 3. The results Out Of Sample on EURJPY (60 min).
TradeStation Strategy Performance Report
It is tested on 50 days, length of area OOS - 10 days.
Results are in pips.
Spread is 10 pips.
| Download demo
|How to Buy|
Ask here|
F.A.Q.|
EasyLanguage Code Converter|
|