# MultiCharts Doesn’t Support Methods

Methods are wonderful tools that are just like functions, but you can put them right into your Analysis Technique and they can share the variables that are defined outside the Method.  Here is an example that I have posted previously.  Note:  This was in response to a question I got on Jeff Swanson’s EasyLanguage Mastery Facebook Group.

``````{'('  Expected line 10, column 12  }

vars: mp(0);
array: weekArray[5](0);

method void dayOfWeekAnalysis()   {method definition}
begin
If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
end;

Buy next bar at highest(high,9)[1] stop;
Sellshort next bar at lowest(low,9)[1] stop;

mp = marketPosition;
if mp <> mp[1] then dayOfWeekAnalysis();
If lastBarOnChart then
Begin
print("Monday ",weekArray[1]);
print("Tuesday ",weekArray[2]);
print("Wednesday ",weekArray[3]);
print("Thursday ",weekArray[4]);
print("Friday ",weekArray[5]);
end;``````
PowerEditor Cannot Handle Method Syntax

## Convert Method to External Function

Sounds easy enough – just remove Method and copy code and put into a new function.  This method keeps track of Day Of Week Analysis.  So what is the function going to return?  It needs to return the performance metrics for Monday, Tuesday, Wednesday, Thursday and Friday.  That is five values so you can’t simply  assign the Function Name a single value – right?

### Create A New Function – Call It DayOfWeekAnalysis

``````inputs: weekArray[n](numericArrayRef);

vars: mp(0);
mp = marketPosition;

If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
print(d," ",mp," ",mp[1]," ",dayOfWeek(entryDate(1)),tradeProfit," ",entryDate," ",entryDate(1)," ",entryPrice(0)," ",entryPrice(1));

DayOfWeekAnalysis = 1;``````
Simple Function - What's the Big Deal

Looks pretty simple and straight forward.  Take a look at the first line of code.  Notice how I inform the function to expect an array of [n] length to passed to it.  Also notice I am not passing by value but by reference.  Value versus reference – huge difference.  Value is a scalar value such as 5, True or a string.  When you pass by reference you are actually passing a pointer to actual location in computer memory – once you change it – it stays changed and that is what we want to do.  When you pass a variable to an indicator function you are simple passing a value that is not modified within the body of the function.  If you want a function to modify and return more than one value you can pass the variable and catch it as a numericRef.  TradeStation has a great explanation of multiple output functions.

### Multiple Output Function per EasyLanguage

Some built-in functions need to return more than a single value and do this by using one or more output parameters within the parameter list.  Built-in multiple output functions typically preface the parameter name with an ‘o’ to indicate that it is an output parameter used to return a value.  These are also known as ‘input-output’ parameters because they are declared within a function as a ‘ref’ type of  input (i.e. NumericRef, TrueFalseRef, etc.) which allows it output a value, by reference, to a variable in the EasyLanguage code calling the function.

I personally don’t follow the “O” prefacing, but if it helps you program then go for it.

### Series Function – What Is It And Why Do I Need to Worry About It?

A series function is a specialized function that refers to a previous function value within its calculations.  In addition, series functions update their value on every bar even if the function call is placed within a conditional structure that may not be true on a given bar.  Because a series function automatically stores its own previous values and executes on every bar, it allows you to write function calculations that may be more streamlined than if you had to manage all of the resources yourself.  However, it’s a good idea to understand how this might affect the performance of your EasyLanguage code.

Seems complicated, but it really isn’t.  It all boils down to SCOPE – not the mouthwash.  See when you call a function all the variables inside that function are local to that particular function – in other words it doesn’t have a memory.  If it changes a value in the first call to the function, it has amnesia so the next time you call the function it forgets what it did just prior – unless its a series function.  Then it remembers.  This is why I can do this:

`````` 	If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;``````
I Can Refer to Prior Values - It Has A Memory

Did you notice TradeProfit = -99999999 and then if it changes then I accumulate it in the correct Day Bin.  If I didn’t check for this then the values in the Day Bin would be accumulated with the values returned by EntryPrice and ExitPrice functions.  Remember this function is called on every bar even if you don’t call it.  I could have tested if a trade occurred and passed this information to the function and then have the function access the EntryPrice and ExitPrice values.  This is up to your individual taste of style.  One more parameter for readability, or one less parameter for perhaps efficiency?

### This Is A Special Function – Array Manipulator and Series Type

When you program a function like this the EasyLanguage Dev. Environment can determine what type of function you are using.  But if you need to change it you can.  Simply right click inside the editor and select Properites.

### How Do You Call Such a “Special”  Function?

The first thing you need to do is declare the array that you will be passing to the function.  Use the keyword Array and put the number of elements it will hold and then declare the values of each element.  Here I create a 5 element array and assign each element zero.  Here is the function wrapper.

``````array: weekArray[5](0);

Buy next bar at highest(high,9)[1] stop;
Sellshort next bar at lowest(low,9)[1] stop;
mp = marketPosition;
//if mp <> mp[1] then newTrade = true;

value1 = dayOfWeekAnalysis(weekArray);
If lastBarOnChart then
Begin
print("Monday ",weekArray[1]);
print("Tuesday ",weekArray[2]);
print("Wednesday ",weekArray[3]);
print("Thursday ",weekArray[4]);
print("Friday ",weekArray[5]);
end;``````
Wrapper Function - Notice I only Pass the Array to the Function

Okay that’s how you convert a Method from EasyLanguage into a Function.  Functions are more re-uasable, but methods are easier.  But if you can’t use a method you now know how to convert one that uses Array Manipulation and us a “Series” type.

# Storing Trades for Later Use in a 2D Array

Since this is part 1 we are just going to go over a very simple system:  SAR (stop and reverse) at highest/lowest high/low for past 20 days.

## A 2D Array in EasyLanguage is Immutable

Meaning that once you create an array all of the data types must be the same.  In a Python list you can have integers, strings, objects whatever.   In C and its derivatives you also have a a data structure (a thing that stores related data) know as a Structure or Struct.  We can mimic a structure in EL by using a 2 dimensional array.  An array is just a list of values that can be referenced by an index.

array[1] = 3.14

array[2] = 42

array[3] = 2.71828

A 2 day array is similar but it looks like a table

array[1,1], array[1,2], array[1,3]

array[2,1], array[2,2], array[2,3]

The first number in the pair is the row and the second is the column.  So a 2D array can be very large table with many rows and columns.  The column can also be referred to as a field in the table.  To help use a table you can actually give your fields names.  Here is a table structure that I created to store trade information.

1. trdEntryPrice (0) – column zero – yes we can have a 0 col. and row
2. trdEntryDate(1)
3. trdExitPrice (2)
4. trdExitDate(3)
5. trdID(4)
6. trdPos(5)
7. trdProfit(6)
8. trdCumuProfit(7)

So when I refer to tradeStruct[0, trdEntryPrice] I am referring to the first column in the first row.

This how you define a 2D array and its associate fields.

``````arrays: tradeStruct[10000,7](0);

vars: trdEntryPrice (0),
trdEntryDate(1),
trdExitPrice (2),
trdExitDate(3),
trdID(4),
trdPos(5),
trdProfit(6),
trdCumuProfit(7);``````
2D array and its Fields

## In EasyLanguage You are Poised at the Close of a Yesterday’s Bar

This paradigm allows you to sneak a peek at tomorrow’s open tick but that is it.  You can’t really cheat, but it also limits your creativity and makes things more difficult to program when all you want is an accurate backtest.   I will go into detail, if I haven’t already in an earlier post, the difference of sitting on Yesterday’s close verus sitting on Today’s close with retroactive trading powers.  Since we are only storing trade information when can use hindsight to gather the information we need.

SellShort tomorrow at lowest(l,20) stop;

These are the order directives that we will be using to execute our strategy.  We can also run a Shadow System, with the benefit of hindsight, to see where we entered long/short and at what prices. I call it a Shadow because its all the trades reflected back one bar.   All we need to do is offset the highest and lowest calculations by 1 and compare the values to today’s highs and lows to determine trade entry.  We must also test the open if a gap occurred and we would have been filled at the open.  Now this code gets a bit hairy, but stick with it.

``````stb = highest(h,20);
sts = lowest(l,20);
stb1 = highest(h[1],20);
sts1 = lowest(l[1],20);

buy("Sys-L") 1 contract next bar at stb stop;
sellShort("Sys-S") 1 contract next bar at sts stop;

mp = marketPosition*currentContracts;

if mPos <> 1 then
begin
if h >= stb1 then
begin
if mPos < 0 then // close existing short position
begin
mExitPrice = maxList(o,stb1);
mProfit = (mEntryPrice - mExitPrice) * bigPointValue - mCommSlipp;
cumuProfit += mProfit;
print(d+19000000:8:0," shrtExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0);
print("-------------------------------------------------------------------------");
end;
mEntryPrice = maxList(o,stb1);
mPos = 1;
print(d+19000000:8:0," longEntry ",mEntryPrice:4:5);
end;
end;
if mPos <>-1 then
begin
if l <= sts1 then
begin
if mPos > 0 then // close existing long position
begin
mExitPrice = minList(o,sts1);
mProfit = (mExitPrice - mEntryPrice ) * bigPointValue - mCommSlipp;
cumuProfit += mProfit;
print(d+19000000:8:0," longExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0);
print("---------------------------------------------------------------------");
end;
mEntryPrice =minList(o,sts1);
mPos = -1;
print(d+19000000:8:0," ShortEntry ",mEntryPrice:4:5);
end;
end;``````
Shadow System - Generic forany SAR System

Notice I have stb and stb1.  The only difference between the two calculations is one is displaced a day.  I use the stb and sts in the EL trade directives.  I use stb1 and sts1 in the Shadow System code.  I guarantee this snippet of code is in every backtesting platform out there.

All the variables that start with the letter m, such as mEntryPrice, mExitPrice deal with the Shadow System.  Theyare not derived from TradeStation’s back testing engine only our logic.  Lets look at the first part of just one side of the Shadow System:

``````if mPos <> 1 then
begin
if h >= stb1 then
begin
if mPos < 0 then // close existing short position
begin
mExitPrice = maxList(o,stb1);
mProfit = (mEntryPrice - mExitPrice) * bigPointValue - mCommSlipp;
cumuProfit += mProfit;
print(d+19000000:8:0," shrtExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0);
print("-------------------------------------------------------------------------");
end;	``````

### mPos and mEntryPrice and mExitPrice belong to the Shadow System

if mPos <> 1 then the Shadow Systems [SS] is not long.  So we test today’s high against stb1 and if its greater then we know a long position was put on.  But what if mPos = -1 [short], then we need to calculate the exit and the trade profit and the cumulative trade profit.  If mPos = -1 then we know a short position is on and we can access its particulars from the tradeStruct 2D arraymEntryPrice = tradeStruct[numTrades,trdEntryPrice].  We can gather the other necessary information from the tradeStruct [remember this is just a table with fields spelled out for us.]  Once we get the information we need we then need to stuff our calculations back into the Structure or table so we can regurgitate later.  We stuff date in to the following fields trdExitPrice, trdExitDate, trdProfit and trdCumuProfit in the table.

### Formatted Print: mEntryPrice:4:5

Notice in the code how I follow the print out of variables with :8:0 or :4:5?  I am telling TradeStation to use either 0 or 5 decimal places.  The date doesn’t need decimals but prices do.  So I format that so that they will line up really pretty like.

Now that I take care of liquidating an existing position all I need to do is increment the number of trades and stuff the new trade information into the Structure.

``````		numTrades +=1;
mEntryPrice = maxList(o,stb1);
mPos = 1;
print(d+19000000:8:0," longEntry ",mEntryPrice:4:5);``````

The same goes for the short entry and long exit side of things.  Just review the code.  I print out the trades as we go along through the history of crude.  All the while stuffing the table.

## If LastBarOnChart -> Regurgitate

On the last bar of the chart we know exactly how many trades have been executed because we were keeping track of them in the Shadow System.  So it is very easy to loop from 0 to numTrades.

``````if lastBarOnChart then
begin
for arrIndx = 1 to numTrades
begin

print("---------------------------------------------------------------------");
if value24 = 1 then
begin
string2 = sellStr;
end;
if value24 = 2 then
begin
string1 = shortStr;
string2 = coverStr;
end;
print(value20+19000000:8:0,string1,value21:4:5," ",value22+19000000:8:0,string2,
value23:4:5," ",value25:6:0," ",value26:7:0);
end;
end;``````

#### Add 19000000 to Dates for easy Translation

Since all trade information is stored in the Structure or Table then pulling the information out using our Field Descriptors is very easy.  Notice I used EL built-in valueXX to store table information.  I did this to make the print statements a lot shorter.  I could have just used tradeStruct[arrIndx, trdEntry] or whatever was needed to provide the right information, but the lines would be hard to read.  To translate EL date to a normal looking data just add 19,000,000 [without commas].

If you format your PrintLog to a monospaced font your out put should look like this.

## Why Would We Want to Save Trade Information?

The answer to this question will be answered in Part 2.  Email me with any other questions…..

# Why Can’t I Just Test with Daily Bars and Use Look-Inside Bar?

Good question.  You can’t because it doesn’t work accurately all of the time.   I just default to using 5 minute or less bars whenever I need to.  A large portion of short term, including day trade, systems need to know the intra day market movements to know which orders were filled accurately.  It would be great if you could just flip a switch and convert a daily bar system to an intraday system and Look Inside Bar(LIB) is theoretically that switch.  Here I will prove that switch doesn’t always work.

## Daily Bar System

• Buy next bar at open of the day plus 20% of the 5 day average range
• SellShort next at open of the day minus 20% of the 5 day average range
• If long take a profit at one 5 day average range above entryPrice
• If short take a profit at one 5 day average range below entryPrice
• If long get out at a loss at 1/2 a 5 day average range below entryPrice
• If short get out at a loss at 1/2 a 5 day average range above entry price
• Allow only 1 long and 1 short entry per day
• Get out at the end of the day

### Simple Code for the System

``````value1 = .2 * average(Range,5);
value2 = value1 * 5;

Buy next bar at open of next bar + value1 stop;
sellShort next bar at open of next bar - value1 stop;

setProfitTarget(value2*bigPointValue);
setStopLoss(value2/2*bigPointValue);
setExitOnClose;``````
Simplified Daily Bar DayTrade System using ES.D Daily

Looks great with just the one hiccup:  Bot @ 3846.75 and the Shorted @ 3834.75 and then took nearly 30 handles of profit.

Now let’s see what really happened.

### Intraday Code to Control Entry Time and Number of Longs and Shorts

Not an accurate representation so let’s take this really simple system and apply it to intraday data.  Approaching this from a logical perspective with limited knowledge about TradeStation you might come up with this seemingly valid solution.  Working on the long side first.

``````//First Attempt

if d <> d[1] then value1 = .2 * average(Range of data2,5);
value2 = value1 * 5;
if t > sess1startTime then buy next bar at opend(0) + value1 stop;
setProfitTarget(value2*bigPointValue);
setStopLoss(value2/2*bigPointValue);
setExitOnClose;``````
First Simple Attempt

This looks very similar to the daily bar system.  I cheated a little by using

if d <> d[1] then value1 = .2 * average(Range of data2,5);

Here I am only calculating the average once a day instead of on each 5 minute bar.  Makes things quicker.  Also I used

if t > sess1StartTime then buy next bar at openD(0) + value1 stop;

I did that because if you did this:

buy next bar at open of next bar + value1 stop;

You would get this:

That should do it for the long side, right?

So now we have to monitor when we can place a trade and monitor the number of long and short entries.

How does this look!

So here is the code.  You will notice the added complexity.  The important things to know is how to control when an entry is allowed and how to count the number of long and short entries.  I use the built-in keyword/function totalTrades to keep track of entries/exits and marketPosition to keep track of the type of entry.

Take a look at the code and you can see how the daily bar system is somewhat embedded in the code.  But remember you have to take into account that you are stepping through every 5 minute bar and things change from one bar to the next.

``````vars: buysToday(0),shortsToday(0),curTotTrades(0),mp(0),tradeZoneTime(False);

if d <> d[1] then
begin
value1 = .2 * average(Range of data2,5);
value2 = value1 * 5;
shortsToday = 0;
end;

mp = marketPosition;

begin
if mp <> mp[1] then
begin
if mp[1] = -1 then shortsToday = shortsToday + 1;
end;
if mp[1] = -1 then print(d," ",t," ",mp," ",mp[1]," ",shortsToday);
end;
if t > sess1StartTime and t < sess1EndTime then tradeZoneTime = True;

buy next bar at opend(0) + value1 stop;

if tradeZoneTime and  shortsToday = 0 and mp <> -1 then
sellShort next bar at opend(0) - value1 stop;

setProfitTarget(value2*bigPointValue);
setStopLoss(value2/2*bigPointValue);
setExitOnClose;``````
Proper Code to Replicate the Daily Bar System with Accuracy

Here’s a few trade examples to prove our code works.

Okay the code worked but did the system?

## Conclusion

If you need to know what occurred first – a high or a low in a move then you must use intraday data.  If you want to have multiple entries then of course your only alternative is intraday data.   This little bit of code can get you started converting your daily bar systems to intraday data and can be a framework to develop your own day trading/or swing systems.

### Can I Prototype A Short Term System with Daily Data?

You can of course use Daily Bars for fast system prototyping.  When the daily bar system was tested with LIB turned on, it came close to the same results as the more accurately programmed intraday system.  So you can prototype to determine if a system has a chance.  Our core concept buyt a break out, short a break out, take profits and losses and have no overnight exposure sounds good theoretically.  And if you only allow 2 entries in opposite directions on a daily bar you can determine if there is something there.

### A Dr. Jekyll and Mr. Hyde Scenario

While playing around with this I did some prototyping of a daily bar system and created this equity curve.  I mistakenly did not allow any losses – only took profits and re-entered long.

Venalicius Cave!  Don’t take a loser you and will reap the benefits.  The chart says so – so its got to be true – I know right?

The same chart from a different perspective.

Moral of the Story – always look at your detailed Equity Curve.  This curve is very close to a simple buy and hold strategy.   Maybe a little better.

# Happy New Year!  My First Post of 2021!

In this post I simply wanted to convert the intraday ratcheting stop mechanism that I previously posted into a daily bar mechanism.  Well that got me thinking of how many different values could be used as the amount to ratchet.  I came up with three:

I have had requests for the EasyLanguage in an ELD – so here it is – just click on the link and unZip.

RATCHETINGSTOPWSWITCH

## Ratcheting Schemes

• ATR of N days
• Fixed \$ Amount
• Percentage of Standard Deviation of 20 Days

So this was going to be a great start to a post, because I was going to incorporate one of my favorite programming constructs : Switch-Case.  After doing the program I thought wouldn’t it be really cool to be able to optimize over each scheme the ratchet and trail multiplier as well as the values that might go into each scheme.

In scheme one I wanted to optimize the N days for the ATR calculation.  In scheme two I wanted to optimize the \$ amount and the scheme three the percentage of a 20 day standard deviation.  I could do a stepwise optimization and run three independent optimizations – one for each scheme.  Why not just do one global optimization you might ask?  You could but it would be a waste of computer time and then you would have to sift through the results.  Huh?  Why?  Here is a typical optimization loop:

 Scheme Ratchet Mult Trigger Mult Parameter 1 1 : ATR 1 1 ATR (2) 2 : \$ Amt 1 1 ATR (2) 3 : % of Dev. Amt 1 1 ATR (2) 1 : ATR 2 1 ATR (2) 2 : \$ Amt 2 1 ATR (2)

Notice when we switch schemes the Parameter 1 doesn’t make sense.  When we switch to \$ Amt we want to use a \$ Value as Parameter 1 and not ATR.  So we could do a bunch of optimizations across non sensical values, but that wouldn’t really make a lot of sense.  Why not do a conditional optimization?  In other words, optimize only across a certain parameter range based on which scheme is currently being used.  I knew there wasn’t an overlay available to use using standard EasyLanguage but I thought maybe OOP,  and there is an optimization API that is quite powerful.  The only problem is that it was very complicated and I don’t know if I could get it to work exactly the way I wanted.

EasyLanguage is almost a full blown programming language.  So should I not be able to distill this conditional optimization down to something that I could do with such a powerful programming language?  And the answer is yes and its not that complicated.  Well at least for me it wasn’t but for beginners probably.  But to become a successful programmer you have to step outside your comfort zones, so I am going to not only explain the Switch/Case construct (I have done this in earlier posts)  but incorporate some array stuff.

When performing conditional optimization there are really just a few things you have to predefine:

1. Scheme Based Optimization Parameters
2. Exact Same Number of Iterations for each Scheme [starting point and increment value]
3. Complete Search Space
4. Total Number of Iterations
5. Staying inside the bounds of your Search Space

Here are the optimization range per scheme:

• Scheme #1 – optimize number of days in ATR calculation – starting at 10 days and incrementing by 2 days
• Scheme #2 – optimize \$ amounts – starting at \$250 and incrementing by \$100
• Scheme #3 – optimize percent of 20 Bar standard deviation – starting at 0,25 and incrementing by 0.25

I also wanted to optimize the ratchet and target multiplier.  Here is the base code for the daily bar ratcheting system with three different schemes.  Entries are based on penetration of 20 bar highest/lowest close.

``````inputs:
ratchetMult(2),trailMult(2),
volBase(True),volCalcLen(20),
dollarBase(False),dollarAmt(250),
devBase(False),devAmt(0.25);

vars:longMult(0),shortMult(0);
vars:ratchetAmt(0),trailAmt(0);
vars:stb(0),sts(0),mp(0);
vars:lep(0),sep(0);

if volBase then
begin
ratchetAmt = avgTrueRange(volCalcLen) * ratchetMult;
trailAmt = avgTrueRange(volCalcLen) * trailMult;
end;
if dollarBase then
begin
ratchetAmt =dollarAmt/bigPointValue * ratchetMult;
trailAmt = dollarAmt/bigPointValue * trailMult;
end;
if devBase then
begin
ratchetAmt = stddev(c,20) * devAmt * ratchetMult;
trailAmt = stddev(c,20) * devAmt * trailMult;
end;

if c crosses over highest(c[1],20) then buy next bar at open;
if c crosses under lowest(c[1],20) then sellshort next bar at open;

mp = marketPosition;
if mp <> 0 and mp[1] <> mp then
begin
longMult = 0;
shortMult = 0;
end;

If mp = 1 then lep = entryPrice;
If mp =-1 then sep = entryPrice;

// Okay initially you want a X point stop and then pull the stop up
// or down once price exceeds a multiple of Y points
// longMult keeps track of the number of Y point multiples of profit
// always key off of lep(LONG ENTRY POINT)
// notice how I used + 1 to determine profit
// and -  1 to determine stop level

If mp = 1 then
Begin
If h >= lep + (longMult + 1) * ratchetAmt then	longMult = longMult + 1;
Sell("LongTrail") next bar at (lep + (longMult - 1) *  trailAmt) stop;
end;

If mp = -1 then
Begin
If l <= sep - (shortMult + 1) * ratchetAmt then	shortMult = shortMult + 1;
buyToCover("ShortTrail") next bar (sep - (shortMult - 1) *  trailAmt) stop;
end;``````
Daily Bar Ratchet System

This code is fairly simple.  The intriguing inputs are:

• volBase [True of False] and  volCalcLen [numeric Value]
• dollarBase [True of False] and  dollarAmt [numeric Value]
• devBase [True of False] and devAmt [numeric Value]

If volBase is true then you use the parameters that go along with that scheme.  The same goes for the other schemes.  So when you run this you would turn one scheme on at a time and set the parameters accordingly.  if I wanted to use dollarBase(True) then I would set the dollarAmt to a \$ value.  The ratcheting mechanism is the same as it was in the prior post so I refer you back to that one for further explanation.

So this was a pretty straightforward strategy.  Let us plan out our optimization search space based on the different ranges for each scheme.  Since each scheme uses a different calculation we can’t simply optimize across all of the different ranges – one is days, and the other two are dollars and percentages.

## Enumerate

We know how to make TradeStation loop based on the range of a value.  If you want to optimize from \$250 to \$1000 in steps of \$250, you know this involves [\$1000 – \$250] / \$250 + 1 or 3 + 1 or 4 interations.   Four loops will cover this entire search space.  Let’s examine the search space for each scheme:

• ATR Scheme: start at 10 bars and end at 40 by steps of 2 or [40-10]/2 + 1 = 16
• \$ Amount Scheme: start at \$250 and since we have to have 16 iterations [remember # of iterations have to be the same for each scheme] what can we do to use this information?  Well if we start \$250 and step by \$100 we cover the search space \$250, \$350, \$450, \$550…\$1,750.  \$250 + 15 x 250.  15 because \$250 is iteration 1.
• Percentage StdDev Scheme:  start at 0.25 and end at 0.25 + 15 x 0.25  = 4

So we enumerate 16 iterations to a different value.  The easiest way to do this is to create a map.  I know this seems to be getting hairy but it really isn’t.  The map will be defined as an array with 16 elements.  The array will be filled with the search space based on which scheme is currently being tested.  Take a look at this code where I show how to define an array of 16 elements and introduce my Switch/Case construct.

``````array: optVals[16](0);

switch(switchMode)
begin
case 1:
startPoint = 10; // vol based
increment = 2;
case 2:
startPoint = 250/bigPointValue; // \$ based
increment = 100/bigPointValue;
case 3:
startPoint = 0.25; //standard dev
increment = 0.25*minMove/priceScale;
default:
startPoint = 1;
increment = 1;
end;

vars: cnt(0),loopCnt(0);
once
begin
for cnt = 1 to 16
begin
optVals[cnt] = startPoint + (cnt-1) * increment;
end;
end``````
Set Up Complete Search Space for all Three Schemes

This code creates a 16 element array, optVals, and assigns 0 to each element.  SwitchMode goes from 1 to 3.

• if switchMode is 1: ATR scheme [case: 1] the startPoint is set to 10 and increment is set to 2
• if switchMode is 2: \$ Amt scheme [case: 2] the startPoint is set to \$250 and increment is set to \$100
• if switchMode is 3: Percentage of StdDev [case: 3] the startPoint is set to 0.25 and the increment is set to 0.25

Once these two values are set the following 15 values can be spawned by the these two.  A for loop is great for populating our search space.  Notice I wrap this code with ONCE – remember ONCE  is only executed at the very beginning of each iteration or run.

once
begin
for cnt = 1 to 16
begin
optVals[cnt] = startPoint + (cnt-1) * increment;
end;
end

Based on startPoint and increment the entire search space is filled out.  Now all you have to do is extract this information stored in the array based on the iteration number.

``````Switch(switchMode)
Begin
Case 1:
ratchetAmt = avgTrueRange(optVals[optLoops]) * ratchetMult;
trailAmt = avgTrueRange(optVals[optLoops]) * trailMult;
Case 2:
ratchetAmt =optVals[optLoops] * ratchetMult;
trailAmt = optVals[optLoops] * trailMult;
Case 3:
ratchetAmt =stddev(c,20) * optVals[optLoops] * ratchetMult;
trailAmt = stddev(c,20) * optVals[optLoops] * trailMult;
Default:
ratchetAmt = avgTrueRange(optVals[optLoops]) * ratchetMult;
trailAmt = avgTrueRange(optVals[optLoops]) * trailMult;
end;

if c crosses over highest(c[1],20) then buy next bar at open;
if c crosses under lowest(c[1],20) then sellshort next bar at open;

mp = marketPosition;
if mp <> 0 and mp[1] <> mp then
begin
longMult = 0;
shortMult = 0;
end;

If mp = 1 then lep = entryPrice;
If mp =-1 then sep = entryPrice;

// Okay initially you want a X point stop and then pull the stop up
// or down once price exceeds a multiple of Y points
// longMult keeps track of the number of Y point multiples of profit
// always key off of lep(LONG ENTRY POINT)
// notice how I used + 1 to determine profit
// and -  1 to determine stop level

If mp = 1 then
Begin
If h >= lep + (longMult + 1) * ratchetAmt then longMult = longMult + 1;
Sell("LongTrail") next bar at (lep + (longMult - 1) *  trailAmt) stop;
end;

If mp = -1 then
Begin
If l <= sep - (shortMult + 1) * ratchetAmt then	shortMult = shortMult + 1;
buyToCover("ShortTrail") next bar (sep - (shortMult - 1) *  trailAmt) stop;
end;``````
Extract Search Space Values and Rest of Code

Switch(switchMode)
Begin
Case 1:
ratchetAmt = avgTrueRange(optVals[optLoops])ratchetMult;
trailAmt = avgTrueRange(optVals[optLoops]) trailMult;
Case 2:
ratchetAmt =optVals[optLoops] * ratchetMult;
trailAmt = optVals[optLoops] * trailMult;
Case 3:
ratchetAmt =stddev(c,20)optVals[optLoops]
ratchetMult;
trailAmt = stddev(c,20) * optVals[optLoops] * trailMult;

Notice how the optVals are indexed by optLoops.  So the only variable that is optimized is the optLoops and it spans 1 through 16.  This is the power of enumerations – each number represents a different thing and this is how you can control which variables are optimized in terms of another optimized variable.   Here is my optimization specifications:

And here are the results:

The best combination was scheme 1 [N-day ATR Calculation] using a 2 Mult Ratchet and 1 Mult Trail Trigger.  The best N-day was optVals[2] for this scheme.  What in the world is this value?  Well you will need to back engineer a little bit here.  The starting point for this scheme was 10 and the increment was 2 so if optVals[1] =10 then optVals[2] = 12 or ATR(12).    You can also print out a map of the search spaces.

``````vars: cnt(0),loopCnt(0);
once
begin
loopCnt = loopCnt + 1;
//	print(switchMode," : ",d," ",startPoint);
//	print("  ",loopCnt:2:0,"  --------------------");
for cnt = 1 to 16
begin
optVals[cnt] = startPoint + (cnt-1) * increment;
//		print(cnt," ",optVals[cnt]," ",cnt-1);
end;
end;	``````
``````  Scheme 1
--------------------
1.00   10.00    0.00 10 days
2.00   12.00    1.00
3.00   14.00    2.00
4.00   16.00    3.00
5.00   18.00    4.00
6.00   20.00    5.00
7.00   22.00    6.00
8.00   24.00    7.00
9.00   26.00    8.00
10.00   28.00    9.00
11.00   30.00   10.00
12.00   32.00   11.00
13.00   34.00   12.00
14.00   36.00   13.00
15.00   38.00   14.00
16.00   40.00   15.00

Scheme2
--------------------
1.00    5.00    0.00 \$ 250
2.00    7.00    1.00 \$ 350
3.00    9.00    2.00 \$ 400
4.00   11.00    3.00 \$ ---
5.00   13.00    4.00
6.00   15.00    5.00
7.00   17.00    6.00
8.00   19.00    7.00
9.00   21.00    8.00
10.00   23.00    9.00
11.00   25.00   10.00
12.00   27.00   11.00
13.00   29.00   12.00
14.00   31.00   13.00
15.00   33.00   14.00
16.00   35.00   15.00 \$1750

Scheme 3
--------------------
1.00    0.25    0.00 25 % stdDev
2.00    0.50    1.00
3.00    0.75    2.00
4.00    1.00    3.00
5.00    1.25    4.00
6.00    1.50    5.00
7.00    1.75    6.00
8.00    2.00    7.00
9.00    2.25    8.00
10.00    2.50    9.00
11.00    2.75   10.00
12.00    3.00   11.00
13.00    3.25   12.00
14.00    3.50   13.00
15.00    3.75   14.00
16.00    4.00   15.00``````

This was a elaborate post so please email me with questions.  I wanted to demonstrate that we can accomplish very sophisticated things with just the pure and raw EasyLanguage which is a programming language itself.

# An ES Break-Out System with Unexpected Parameters

I was recently testing the idea of a short term VBO strategy on the ES utilizing very tight stops.  I wanted to see if using a tight ATR stop in concert with the entry day’s low (for buys) would cut down on losses after a break out.  In other words, if the break out doesn’t go as anticipated get out and wait for the next signal.  With the benefit of hindsight in writing this post, I certainly felt like my exit mechanism was what was going to make or break this system.  In turns out that all pre conceived notions should be thrown out when volatility enters the picture.

## System Description

• Buy 1 ATR above the midPoint of the past 4 closing prices
• Place an initial stop at 1 ATR and a Profit Objective of 1 ATR
• Trail the stop up to the prior day’s low if it is greater than entryPrice – 1 ATR initially, and then trail if a higher low is established
• Wait 3 bars to Re-Enter after going flat – Reversals allowed

That’s it.  Basically wait for a trendless period and buy on the bulge and then get it out if it doesn’t materialize.  I knew I could improve the system by optimizing the parameters but I felt I was in the ball park.  My hypothesis was that the system would fail because of the tight stops.  I felt the ADX trigger was OK and the BO level would get in on a short burst.  Just from past experience I knew that using the prior day’s price extremes as a stop usually doesn’t fair that well.

Without commission the initial test was a loser: -\$1K and -\$20K draw down over the past ten years.  I thought I would test my hypothesis by optimizing a majority of the parameters:

• ATR Len
• ATR BO multiplier
• ATR Multiplier for Trade Risk
• ATR Multiplier for Profit Objective
• Number of bars to trail the stop – used lowest lows for longs

## Results

As you can probably figure, I  had to use the Genetic Optimizer to get the job done.  Over a billion different permutations.  In the end here is what the computer pushed out using the best set of parameters.

## ADX – Does it Really Matter?

Take a look at the chart – the ADX is mostly in Trigger territory – does it really matter?

## A Chart is Worth a 1000 Words

What does this chart tell us?

Was the parameter selection biased by the heightened level of volatility?  The system has performed on the parameter set very well over the past two or three years.  But should you use this parameter set going into the future – volatility will eventually settle down.

Now using my experience in trading I would have selected a different parameter set.   Here are my biased results going into the initial programming.  I would use a wider stop for sure, but I would have used the generic ADX values.

I would have used 14 ADX Len with a 20 trigger and risk 1 to make 3 and use a wider trailing stop.  With trend neutral break out algorithms, it seems you have to be in the game all of the time.  The ADX was supposed to capture zones that predicated break out moves, but the ADX didn’t help out at all.  Wider stops helped but it was the ADX values that really changed the complexion of the system.  Also the number of bars to wait after going flat had a large impact as well.  During low volatility you can be somewhat picky with trades but when volatility increases you gots to be in the game. – no ADX filtering and no delay in re-Entry.  Surprise, surprise!

## Alogorithm Code

Here is the code – some neat stuff here if you are just learning EL.  Notice how I anchor some of the indicator based variables by indexing them by barsSinceEntry.  Drop me a note if you see something wrong or want a little further explanation.

``````Inputs: adxLen(14),adxTrig(25),atrLen(10),atrBOMult(1),atrRiskMult(1),atrProfMult(2),midPtNumBar(3),posMovTrailNumBars(2),reEntryDelay(3);

mp = marketPosition;
If totalTrades = 0 then BSE = 99;

ATR = avgTrueRange(atrLen);

SBO = midPoint(c,midPtNumBar) - ATR * atrBOMult;
BBO = midPoint(c,midPtNumBar) + ATR * atrBOMult;

If mp <> 1 and adx(adxLen) < adxTrig and BSE > reEntryDelay and open of next bar < BBO then buy next bar at BBO stop;
If mp <>-1 and adx(adxLen) < adxTrig AND BSE > reEntryDelay AND open of next bar > SBO then sellshort next bar at SBO stop;

If mp = 1 and mp[1] <> 1 then
Begin
end;

If mp = -1 and mp[1] <> -1 then
Begin
end;

if mp = 1 then sell("L-init-loss") next bar at entryPrice - tradeRisk[barsSinceEntry] stop;

if mp = 1 then
begin
trailLongStop = maxList(trailLongStop,lowest(l,posMovTrailNumBars));
sell("L-TL-Stop") next bar at trailLongStop stop;
end;
if mp =-1 then
begin
trailShortStop = minList(trailShortStop,highest(h,posMovTrailNumBars));
//	print(d, " Short and trailStop is : ",trailShortStop);
buyToCover("S-TL-Stop") next bar at trailShortStop stop;
end;``````

# EasyLanguage Includes a Powerful String Manipulation Library

I thought I would share this function.  I needed to convert a date string (not a number per se) like “20010115” or “2001/01/15” or “01/15/2001” or “2001-01-15” into a date that TradeStation would understand.  The function had to be flexible enough to accept the four different formats listed above.

## String Functions

Most programming languages have functions that operate strictly on strings and so does EasyLanguage.  The most popular are:

• Right String (rightStr) – returns N characters from the right side of the string.
• Left String (leftStr) – returns N character starting from the left side of the string
• Mid String (midStr) – returns the middle portion of a string starting at a specific place in the string and advance N characters
• String Length (strLen) – returns the number of characters in the string
• String To Number (strToNum) – converts the string to a numeric representation.  If the string has a character, this function will return 0
• In String (inStr) – returns location of a sub string inside a larger string ( a substring can be just one character long)

## Unpack the String

If the format is YYYYMMDD format then all you need to do is remove the dashes or slashes (if there are any) and then convert what is left over to a number.   But if the format is MM/DD/YYYY format then we are talking about a different animal.  So how can you determine if the date string is in this format?  First off you need to find out if the month/day/year separator is a slash or a dash.  This is how you do this:

whereIsAslash = inStr(dateString,”/”);

If either is a non zero then you know there is a separator.  The next thing to do is locate the first “dash or slash” (the search character or string).  If it is located within the first four characters of the date string then you know its not a four digit year.  But, lets pretend the format is “12/14/2001” so if the first dash/slash is the 3rd character you can extract the month string by doing this:

firstSrchStrLoc = inStr(dateString,srchStr);
mnStr= leftStr(dateString,firstSrchStrLoc-1);

So if firstSrchStrLoc = 3 then we want to leftStr the date string and extract the first two characters and store them in mnStr.  We then store what’s left of the date string in tempStr by using rightStr:

strLength = strLen(dateString);

tempStr = rightStr(dateString,strLength-firstSrchStrLoc);

Here I pass dateString and the strLength-firstSrchStrLoc – so if the dateString is 10 characters long and the firstSrchStrLoc is 3, then we can create a tempstring by taking [10 -3  = 7 ] characters from right side of the string:

“12/14/2001” becomes “14/2001” – once that is done we can pull the first two characters from the tempStr and store those into the dyStr [day string.]  I do this by searching for the “/” and storing its location in srchStrLoc.  Once I have that location I can use that information and leftStr to get the value I need.   All that is left now is to use the srchStrLoc and the rightStr function.

srchStrLoc = inStr(tempStr,srchStr);
dyStr = leftStr(tempStr,srchStrLoc-1);
yrStr = rightStr(tempStr,strLen(tempStr)-srchStrLoc);

Now convert the strings to numbers and multiply their values accordingly.

DateSTrToYYYMMDD = strToNum(yrStr) X 10000-19000000 + strToNum(mnStr) X 100 + strToNum(dyStr)

To get the date into TS format I have to subtract 19000000 from the year.  Remember TS represents the date in YYYMMDD  format.

Now what do  you do if the date is in the right format but simply includes the dash or slash separators.  All you need to do here is loop through the string and copy all non dash or slash characters to a new string and then convert to a number.  Here is the loop:

``````        tempStr = "";
iCnt = 1;
While iCnt <= strLength
Begin
If midStr(dateString,iCnt,1) <> srchStr then
tempStr += midStr(dateString,iCnt,1);
iCnt+=1;
end;
tempDate = strToNum(tempStr);
DateStrToYYYMMDD = tempDate-19000000;``````

Here I use midStr to step through each character in the string.  MidStr requires a string and the starting point and how many characters you want returned from the string.  Notice I step through the string with iCnt and only ask for 1 character at a time.  If the character is not a dash or slash I concatenate tempStr with the non dash/slash character.  At the end of the While loop I simply strToNum the string and subtract 19000000.  That’s it!  Remember EasyLanguage is basically a full blown programming language with a unique set of functions that relate directly to trading.

Here is the function and testFunc caller.

STRINGFUNCANDFUNCCALLER

# Thomas Stridsman quote from  his “Trading Systems That Work Book”

The benefits of the RAD contract also become evident when you want to put together a multimarket portfolio…For now we only state that the percentage based calculations do not take into consideration how many contracts you’re trading and, therefore, give each market an equal weighting in the portfolio.

The Stridsman Function I presented in the last post can be used to help normalize a portfolio of different markets.  Here is a two market portfolio (SP – 250price and JY -125Kprice contract sizes) on a PAD contract.

Here is the performance of the same portfolio on a RAD contract.

The curve shapes are similar but look at the total profit and the nearly \$125K draw down.  I was trying to replicate Thomas’ research so this data is from Jan. 1990 to Dec. 1999.  A time period where the price of the SP increased 3 FOLD!  Initially you would start trading 1 JY to 2 SP but by the time it was over you would be trading nearly 3 JY to 1 SP.  Had you traded at this allocation the PAD numbers would be nearly \$240K in profit.  Now this change occurred through time so the percentage approach is applied continuously.  Also the RAD data allows for a somewhat “unrealistic” reinvestment or compounding mechanism.  Its unrealistic because you can’t trade a partial futures contract.  But it does give you a glimpse of the potential.  The PAD test does not show reinvestment of profit.  I have code for that if you want to research that a little bit more.  Remember everything is in terms of Dec. 31 1999 dollars.  That is another beauty of the RAD contract.

## Another Stridsman Quote

Now, wait a minute, you say, those results are purely hypothetical.  How can I place all the trades in the same market at presumably the same point in time?  Well, you can’t, so that is a good and valid question; but let me ask you, can you place any of these trades for real, no matter, how you do it?  No, of course not.  They all represent foregone opportunities.  Isn’t it better then to at least place them hypothetically in today’s marketplace to get a feel for what might happen today, rather in a ten-year-old market situation to get a feel for how the situation was back then?  I think wall can agree that it is better to know what might happen today, rather than what happened ten years ago.

That is a very good point.  However, convenience and time is import and when developing an algorithm.  And most platforms, including my TS-18, are geared toward PAD data.  However TS-18 can look at the entire portfolio balance and all the market data for each market up to that point in time and can adjust/normalize based on portfolio and data metrics.  However, I will add a percentage module a little later, but I would definitely use the StridsmanFunc that I presented in the last post to validate/verify your algorithm in today’s market place if using TradeStation.

Email me if you want the ELD of the function.

If you play around with TradeStation’s custom futures capabilities you will discover you can create different adjusted continuous contracts.  Take a look at this picture:

Both charts look the same and the trades enter and exit at the same locations in relation to the respective price charts.   However, take a look at the Price Scale on the right and the following pictures.

Here is another look at draw down metrics between the two formats.

Who would want to trade a system on 1 contract of crude and have a \$174K draw down?  Well you can’t look at it like that.  Back in 2008 crude was trading at \$100 X 1000 = \$100,000 a contract.  Today May 11th 2020 it is around \$25,000.  So a drawdown of \$44K back then would be more like \$176K in today’s terms.  In my next post I will go over the theory of  RAD, but for right now you just need to basically ignore TradeStation’s built in performance metrics and use this function that I developed in most part by looking at Thomas’ book.

``````//Name this function StridsmanFunc1

Vars: FName(""), offset(1),TotTr(0), Prof(0), CumProf(1), ETop(1), TopBar(0), Toplnt(0),BotBar(0), Botlnt(0), EBot(1), EDraw(1), TradeStr2( "" );
Vars: myEntryPrice(0),myEntryDate(0),myMarketPosition(0),myExitDate(0),myExitPrice(0);
If CurrentBar = 1 Then
Begin
FName = "C:\Temp\" + LeftStr(GetSymbolName, 3) + ".csv";
FileDelete(FName);
TradeStr2 = "E Date" + "," + "Position" + "," + "E Price" + "," + "X Date" +"," + "X Price" + "," + "Profit" + "," + "Cum. prof." + "," + "E-Top" + "," +"E-Bottom" + "," + "Flat time" + "," + "Run up" + "," + "Drawdown" +NewLine;
End;
If TotTr > TotTr[1] or (lastBarOnChart and marketPosition <> 0) Then
Begin

if TotTr > TotTr[1] then
begin
if (EntryPrice(1) <> 0) then Prof = 1 + PositionProfit(1)/(EntryPrice(1) * BigPointValue);
End
else
begin
Value99 = iff(marketPosition = 1,c - entryPrice, entryPrice - c);
Prof = 1 + (Value99*bigPointValue) /(Entryprice *BigPointValue);
//		print(d," StridsmanFunc1 ",Value99," ",Prof," ",(Value99*bigPointValue) /(Entryprice *BigPointValue):5:4);
TotTr = totTr + 1;
end;
CumProf = CumProf * Prof;
ETop = MaxList(ETop, CumProf);
If ETop > ETop[1] Then
Begin
TopBar = CurrentBar;
EBot = ETop;
End;

EBot = MinList(EBot, CumProf);

If EBot<EBot[1] Then BotBar = CurrentBar;

Toplnt = CurrentBar - TopBar;

Botlnt = CurrentBar - BotBar;

if ETop <> 0 then EDraw = CumProf / ETop;

drawDownArr[TotTr] = (EDraw - 1);

myEntryDate = EntryDate(1);
myMarketPosition = MarketPosition(1);
myEntryPrice = EntryPrice(1);
myExitDate = ExitDate(1);
myExitPrice = ExitPrice(1);
If lastBarOnChart and marketPosition <> 0 then
Begin
myEntryDate = EntryDate(0);
myMarketPosition = MarketPosition(0);
myEntryPrice = EntryPrice(0);
myExitDate = d;
myExitPrice =c;
end;
TradeStr2 = NumToStr(myEntryDate, 0) + "," +NumToStr(myMarketPosition, 0) + "," + NumToStr(myEntryPrice, 2) + ","
+ NumToStr(myExitDate, 0) + "," + NumToStr(myExitPrice, 2) + ","+ NumToStr((Prof - 1) * 100, 2) + "," + NumToStr((CumProf - 1) *100, 2) + ","
+ NumToStr((ETop - 1) * 100, 2) + "," + NumToStr((EBot - 1) * 100, 2) + "," + NumToStr(Toplnt, 0) + "," + NumToStr(Botlnt, 0) + "," + NumToStr((EDraw - 1) * 100, 2) +
NewLine;

End;
largestWin(0),largestWin\$(0),largestLoss(0),largestLoss\$(0),avgProf(0),avgProf\$(0),
winSum(0),lossSum(0),avgWin(0),avgWin\$(0),avgLoss(0),avgLoss\$(0),maxDD(0),maxDD\$(0),cumProfit(0),cumProfit\$(0);

If lastBarOnChart then
begin
For ii = 1 to TotTr
Begin
begin
end;
begin
end;
begin
//   		print("LargestWin Found ",largestWin);
end;
If drawDownArr[ii] < maxDD then maxDD = drawDownArr[ii];
end;
if TotTr <> 0 then avgTrade = trdSum/TotTr;
largestWin = largestWin;
largestLoss = largestLoss;
largestWin\$ = largestWin*c*bigPointValue;
largestLoss\$ = largestLoss*c*bigPointValue;
if TotTr <> 0 then perWins = winTrades/TotTr;
if TotTr <> 0 then perLosers = lossTrades/TotTr;
avgWin\$ = avgWin*c*bigPointValue;
avgLoss\$ = avgLoss*c*bigPointValue;
maxDD\$ = maxDD *c*bigPointValue;
CumProf = cumProf - 1;
CumProf\$ = cumProf*c*bigPointValue;

"Profit Factor,,"+NumToStr(profFactor,3)+",Largest Win ,"+NumToStr(largestWin,3)+","+NumToStr(largestWin\$,0)+",Largest Loss,"+NumToStr(largestLoss,3)+","+NumToStr(largestLoss\$,0)+NewLine+
Print("Profit Factor ",profFactor," Largest Win   ",largestWin:5:2," ",largestWin\$," Largest Loss ",largestLoss:5:2," ",largestLoss\$);
Print("Avg Profit ",avgTrade," ",avgTrade\$," Avg Win ",avgWin," ",avgWin\$," Avg Loss ",avgLoss," ",avgLoss\$);

end;

StridsmanFunc1 = 1;``````
Conversion of Performance Metrics to Percentages Instead of \$Dollars

This function will out put a file that looks like this.  Go ahead and play with the code – all you have to do is call the function from within an existing strategy that you are working with.  In part two I will go over the code and explain what its doing and how arrays and strings were used to archive the trade history and print out this nifty table.

In this output if you treat the return from each trade as a function of the entry price and accumulate the returns you can convert the value to today’s current market price of the underlying.  In this case a 15 -year test going through the end of last year, ended up making almost \$70K.

Profit \$350K – Draw Down \$140K

Profit \$89K – Draw Down \$45K

Profit \$70K – Draw Down \$48K

At this point you can definitely determine that the typical RAD/TS metrics are not all that usuable.  The PAD/TS results look very similar to RAD/StridsmanFunc results.  Stay tuned for my next post and I will hopefully explain why RAD/StridsmanFunc is probably the most accurate performance metrics of the three.

# Using a Dictionary to Create a Trading System

## Dictionary Recap

Last month’s post on using the elcollections dictionary was a little thin so I wanted to elaborate on it and also develop a trading system around the best patterns that are stored in the dictionary.  The concept of the dictionary exists in most programming languages and almost all the time uses the (key)–>value model.  Just like a regular dictionary a word or a key has a unique definition or value.  In the last post, we stored the cumulative 3-day rate of return in keys that looked like “+ + – –” or “+ – – +“.  We will build off this and create a trading system that finds the best pattern historically based on average return.  Since its rather difficult to store serial data in a Dictionary I chose to use Wilder’s smoothing average function.

## Ideally, I Would Have Liked to Use a Nested Dictionary

Initially, I played around with the idea of the pattern key pointing to another dictionary that contained not only the cumulative return but also the frequency that each pattern hit up.  A dictionary is designed to have  unique key–> to one value paradigm.  Remember the keys are strings.  I wanted to have unique key–> to multiple values. And you can do this but it’s rather complicated.  If someone wants to do this and share, that would be great.  AndroidMarvin has written an excellent manual on OOEL and it can be found on the TradeStation forums.

## Ended Up Using A Dictionary With 2*Keys Plus an Array

So I didn’t want to take the time to figure out the nested dictionary approach or a vector of dictionaries – it gets deep quick.  So following the dictionary paradigm I came up with the idea that words have synonyms and those definitions are related to the original word.  So in addition to having keys like “+ + – -” or “- – + -” I added keys like “0”, “1” or “15”.  For every  + or – key string there exists a parallel key like “0” or “15”.  Here is what it looks like:

 –  –  –  – = “0” – – – + = “1” – – + – = “2”

You can probably see the pattern here.  Every “+” represents a 1 and every “0” represent 0 in a binary-based numbering system.  In the + or – key I store the last value of Wilders average and in the numeric string equivalent, I store the frequency of the pattern.

## Converting String Keys to Numbers [Back and Forth]

To use this pattern mapping I had to be able to convert the “++–” to a number and then to a string.  I used the numeric string representation as a dictionary key and the number as an index into an array that store the pattern frequency.  Here is the method I used for this conversion.  Remember a method is just a function local to the analysis technique it is written.

``````//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;``````
String Pattern to Number

This is a simple method that parses the string from left to right and if there is a “+” it is raised to the power(2,idx) where idx is the location of “+” in the string.  So “+  +  –  –  ” turns out to be 8 + 4 + 0 + 0 or 12.

Once I retrieve the number I used it to index into my array and increment the frequency count by one.  And then store the frequency count in the correct slot in the dictionary.

``````patternNumber = convertPatternString2Num(patternString);
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;``````
Store Value In Array and Dictionary

## Calculating Wilder’s Average Return and Storing in Dictionary

Once I have stored an instance of each pattern [16] and the frequency of each pattern[16] I calculate the average return of each pattern and store that in the dictionary as well.

``````//Calculate the percentage change after the displaced pattern hits
Value1 =  (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
//	print("Initiating: ",patternDict[patternString] astype double);
end;``````
(pAvg * (N-1) + return) / N

When you extract a value from a collection you must us an identifier to expresses its data type or you will get an error message : patternDict[patternString] holds a double value {a real number}  as well as patternDict[patternStringNum] – so I have to use the keyword asType.  Once I do my calculation I ram the new value right back into the dictionary in the exact same slot.  If the pattern string is not in the dictionary (first time), then the Else statement inserts the initial three-day rate of return.

## Sort Through All of The Patterns and Find the Best!

The values in a dictionary are stored in alphabetic order and the string patterns are arranged in the first 16 keys.  So I loop through those first sixteen keys and extract the highest return value as the “best pattern.”

``````//  get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
//	print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;``````
Extract Best Pattern From All History

If Today’s Pattern Matches the Best Then Take the Trade

``````// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;``````
Does Today Match the Best Pattern?

If today matches the best pattern then buy and cover after the second day.

## Conclusion

I didn’t know if this code was worth proffering up but I decided to posit it because it contained a plethora of programming concepts: dictionary, method, string manipulation, and array.  I am sure there is a much better way to write this code but at least this gets the point across.

## Contents of Dictionary at End of Run

``````++++    0.06
+++-   -0.08
++-+    0.12
++--   -0.18
+-++    0.08
+-+-    0.40
+--+   -0.46
+---    0.34
-+++    0.20
-++-    0.10
-+-+    0.23
-+--    0.31
--++    0.02
--+-    0.07
---+    0.22
----    0.46
0.00  103.00
1.00  128.00
10.00  167.00
11.00  182.00
12.00  146.00
13.00  168.00
14.00  163.00
15.00  212.00
2.00  157.00
3.00  133.00
4.00  143.00
5.00  181.00
6.00  151.00
7.00  163.00
8.00  128.00
9.00  161.00``````
Contents of Dictionary

## Code in Universum

``````//Dictionary based trading sytem
//Store pattern return
//Store pattern frequency
// by George Pruitt
Using elsystem.collections;

vars: string keystring("");
vars: dictionary patternDict(NULL),vector index(null), vector values(null);
array: patternCountArray[100](0);

input: patternTests(8);

var: patternTest(""),tempString(""),patternString(""),patternStringNum("");
var: patternNumber(0);
var: iCnt(0),jCnt(0);
//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;

once begin
clearprintlog;
patternDict = new dictionary;
index = new vector;
values = new vector;
end;

//Convert 4 day pattern displaced by 2 days
patternString = "";
for iCnt = 5 downto 2
begin
if(close[iCnt]> close[iCnt+1]) then
begin
patternString = patternString + "+";
end
else
begin
patternString = patternString + "-";
end;
end;

//What is the current 4 day pattern
vars: currPattString("");
currPattString = "";

for iCnt = 3 downto 0
begin
if(close[iCnt]> close[iCnt+1]) then
begin
currPattString = currPattString + "+";
end
else
begin
currPattString = currPattString + "-";
end;
end;

//Get displaced pattern number
patternNumber = convertPatternString2Num(patternString);
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
//Calculate the percentage change after the displaced pattern hits
Value1 =  (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
//	print("Initiating: ",patternDict[patternString] astype double);
end;
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
//	print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;``````
Pattern Dictionary Part II

# Multi-Time Frame – Using Built-in Indicators and Multi Data Charts

A reader of this blog wanted to be able to use different time frames and some built-in indicators and output the information in a similar fashion as I did in the original MTF post.  There are numerous ways to program this but the two easiest are to use data structures such as arrays or vectors or use TradeStation’s own multi data inputs.  The more complicated of the two would be to use arrays and stay compliant with Multicharts.  Or in that same vein use vectors and not stay compliant with Multicharts.  I chose, for this post, the down and dirty yet compliant method.  [NOTE HERE! When I started this post I didn’t realize it was going to take the turn I ended up with.  Read thoroughly before playing around with the code to see that it is what you are really, really looking for.]  I created a multi data chart with five-time frames: 5,10,15,30 and 60 minutes.  I then hid data2 thru data5.  I created an MTF indicator that plots the relationship of the five time frames applied to the ADX indicator with length 14.  If the ADX > 20 then the plot will be green else it will be red.  If all plots align, then the composite plot will reflect the alignment color.

``````{EasyLanguage MultiTime Frame Indicator)
written by George Pruitt - copyright 2019 by George Pruitt
}

If barNumber > 1 then
Begin

If condition10 then setPlotColor(1,Green) else SetPlotColor(1,Red);
If condition11 then setPlotColor(2,Green) else SetPlotColor(2,Red);
If condition12 then setPlotColor(3,Green) else SetPlotColor(3,Red);
If condition13 then setPlotColor(4,Green) else SetPlotColor(4,Red);
If condition14 then setPlotColor(5,Green) else SetPlotColor(5,Red);

condition6 = condition10 and condition11 and condition12 and condition13 and condition14;
Condition7 = not(condition10) and not(condition11) and not(condition12) and not(condition13) and not(condition14);

If condition6 then setPlotColor(7,Green);
If condition7 then setPlotColor(7,Red);

If condition6 or condition7 then plot7(7,"trend");

Plot6(5,"line");
Plot1(4,"t1");
Plot2(3,"t2");
Plot3(2,"t3");
Plot4(1,"t4");
Plot5(0,"t5");

end;``````
MTF with 5 data streams and ADX

This code is very similar to the original MTF indicator, but here I simply pass a pointer to the different time frames to the ADX function.  Since the ADX function only requires a length input I had assumed I could use the following format to get the result for each individual time frame: