Tag Archives: Multicharts

Extend Data Mining to Actual Trading System

Data Mining May or May Not Link Causality

A study between ice cream sales and crime rate demonstrated a high level of correlation.  However, it would be illogical to assume that buying more ice cream leads to more crime.  There are just too many other factors and variables involved to draw a conclusion.  So, data mining with EasyLanguage may or may not lead to anything beneficial.  One thing is you cannot hang your hat completely on this type of research.  A reader of my books asked if there was evidence that pointed to the best time to enter and exit a day trade.  Is it better to enter in the morning or in the afternoon or are there multiple trading windows throughout the day?  I thought I would try to answer the question using TradeStation’s optimization capabilities.

If You Like the Theory and its EasyLanguage Code of this Blog Post – Check Out my New Book at Amazon.com

Get Your Copy Now!

Create a Search Space of Different Window Opening Times and Open Duration

My approach is just one of a few that can be used to help answer this question.  To cut down on time and the size of this blog we will only look at day trading the @ES.D from the long side.  The search space boundaries can be defined by when we open the trading window and how long we leave it open.  These two variables will be defined by inputs so we can access the optimization engine.  Here is how I did it with EasyLanguage code.

inputs: openWindowTime(930),openWindowOffset(5),windowDuration(60);
inputs: canBuy(True),canShort(True);



if t >= calcTime(openWindowTime,openWindowOffset) and t < calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if entriesToday(d) = 0 and canBuy Then
buy next bar at market;
if entriesToday(d) = 0 and canShort Then
sellshort next bar at market ;
end;

if t = calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if marketPosition = 1 then sell next bar at open;
if marketPosition =-1 then buyToCover next bar at open;
end;
setExitOnClose;
Optimize when to open and how long to leave open

The openWindowTime input is the basis from where we open the trading window.  We are working with the @ES.D with an open time of 9:30 AM eastern.  The openWindowOffset will be incremented in minutes equivalent to the data resolution of the chart, five minutes.  We will start by opening the window at 9:35 and leave it open for 60 minutes.  The next iteration in the optimization loop will open the window at 9:40 and keep it open for 60 minutes as well.  Here are the boundaries that I used to define our search space.

  • window opening times offset: 5 to 240 by 5 minutes
  • window opening duration: 60 to 240 by 5 minutes
Optimization Ranges for Window Open and Open Duration

A total of 1739 iterations will span our search space.   The results state that waiting for twenty minutes before buying and then exiting 190 minutes later, worked best.  But also entering 90 minutes after the open and exiting 4 hours later produced good results as well (no trade execution fee were utilized.)  Initially I was going to limit entry to once per day, but then I thought it might be worthwhile to enter a fresh position, if the first one is stopped out, or pyramid if it hasn’t.  I also thought, each entry should have its own protective stop amount.  Would entering later require a small stop – isn’t most of the volatility, on average, expressed during the early part of the day.

Results of different opening and duration times.

Build a Strategy that Takes on a Secondary Trade as a New Position or One that is Pyramided.

This is not a simple strategy.  It sounds simple and it requires just a few lines of code.  But there is a trick in assigning each entry with its own exit.  As you can see there is a potential for trade overlap.  You can get long 20 minutes after the open and then add on 70 minutes  (90 from the open) later.  If the first position hasn’t been stopped out, then you will pyramid at the second trade entry.  You have to tell TradeStation to allow this to happen.

Allow TradeStation to Pyramid up to 2 positions with different signals.

System Rules

  1. Enter long 20 minutes after open
  2. Enter long 90 minutes after open
  3. Exit 1st entry 190 minutes later or at a fixed $ stop loss
  4. Exit 2nd entry 240 minutes later or at a fixed $ stop loss
  5. Make sure you are out at the end of the day

Sounds pretty simple, but if you want to use different stop values for each entry, then the water gets very muddy.

AvgEntryPrice versus EntryPrice

Assume you enter long and then you add on another long position.  If you examine EntryPrice you will discover that it reflects the initial entry price only.   The built-in variable AvgEntryPrice will be updated with the average price between the two entries.  If you want to key off of the second entry price, then you will need to do a little math.

avgEntryPrice = (entry price 1 + entry price 2) / 2

or ap = (ep1 + ep2) /2

Using this formula and simple algebra we can arrive at ep2 using this formula:  ep2 = 2*ap – ep1.  Since we already know ep1 and ap, ep2 is easy to get to.  We will need this information and also the functionality of from entry.  You tie entries and exits together with the keywords from entry.  Here are the entry and exit trade directives.

if time = calcTime(openTime,entryTime1Offset) then 
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;


if time = calcTime(openTime,entryTime1Offset + exitTime1Offset) then
sell("1st exit") from entry("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset + exitTime2Offset) then
sell("2nd exit") from entry("2nd buy") next bar at open;

if mp = 1 Then
Begin
value1 = avgEntryPrice;
if currentShares = 2 then value1 = avgEntryPrice*2 - entryPrice;
sell("1st loss") from entry("1st buy") next bar at entryPrice - stopLoss1/bigPointValue stop;
sell("2nd loss") from entry("2nd buy") next bar at value1 - stopLoss2/bigPointValue stop;
end;

if mp = 1 and t = openTime + barInterval then sell("oops") next bar at open;
Entry and Exit Directives Code

The trade entry directives are rather simple, but you must use the calcTime function to arrive at the correct entry and exit times.  Here we are using the benchmark, openTime and the offsets of entryTime1Offset and entryTime2Offset.  This function adds (or subtracts if the offset is negative) the offset to the benchmark.  This takes care of when the trading windows open, but you must add the entry1TimeOffset to exit1TimeOffset to calculate the duration the trading window is to remain open.  This goes for the second entry window as well.

Now let’s look at the exit directives.  Notice how I exit the 1st buy entry with the code from entry (“1st buy”).  This ties the entry and exit directives together.  This is pretty much straightforward as well.  The tricky part arrives when we try to apply different money management stops to each entry.  Exiting from the 1st buy requires us to simply subtract the $ in terms of points from entryPrice.  We must use our new equation to derive the 2nd entry price when two contracts are concurrent.   But what if we get stopped out of the first position prior to entering the second position?  Should we continue using the formula.  No.  We need to fall back to entryPrice or avgEntryPrice:  when only one contract or unit is in play, these two variables are equal.  We initially assign the variable value1 to the avgEntryPrice and only use our formula when currentShares = 2.  This code will work a majority of the time.  But take a look at this trade:

Didn’t have an intervening bar to update the 2nd entry price. The first entry price was used as the basis to calculate the stop loss!

This is an anomaly, but anomalies can add up.  What happened is we added the second position and the market moved down very quickly – too quickly for the correct entry price to be updated.  The stop out (2nd loss) was elected by using the 1st entry price, not the second.  You can fix this with the following two solutions:

  1. Increase data resolution and hope for an intervening bar
  2. Force the second loss to occur on the subsequent trading bar after entry.  This means you will not be stopped out on the bar of entry but will have to wait five minutes or whatever bar interval you are working with.
Fixed – just told TS to place the order at the close of the bar where we were filled!

OK – Now How Do We Make this a Viable Trading System

If you refer back to the optimization results you will notice that the average trade (before execution costs) was around $31.  Keep in mind we were trading every day.  This is just the beginning of your research – did we find a technical advantage?  No.  We just found out that you can enter and exit at different times of the trading day, and you can expect a positive outcome.  Are there better times to enter and exit?  YES.  You can’t trade this approach without adding some technical analysis – a reason to enter based on observable patterns.  This process is called FILTERING.   Maybe you should only enter after range compression.  Or after the market closed up on the prior day, or if the market was an NR4 (narrow range 4.)  I have added all these filters so you can iterate across them all using the optimization engine.  Take a look:

filter1 = True;
filter2 = True;

if filtNum1 = 1 then
filter1 = close of data2 > close[1] of data2;
if filtNum1 = 2 Then
filter1 = close of data2 < close[1] of data2;
if filtNum1 = 3 Then
filter1 = close of data2 > open of data2;
if filtNum1 = 4 Then
filter1 = close of data2 < open of data2;
if filtNum1 = 5 Then
filter1 = close of data2 > (h data2 + l data2 + c data2)/3;
if filtNum1 = 6 Then
filter1 = close of data2 < (h data2 + l data2 + c data2)/3;
if filtNum1 = 7 Then
filter1 = openD(0) > close data2;
if filtNum1 = 8 Then
filter1 = openD(0) < close data2;

if filtNum2 = 1 Then
filter2 = trueRange data2 < avgTrueRange(10) data2;
if filtNum2 = 2 Then
filter2 = trueRange data2 > avgTrueRange(10) data2;
if filtNum2 = 3 Then
filter2 = range data2 = lowest(range data2,4);
if filtNum2 = 4 Then
filter2 = range data2 = highest(range data2,4);
Filter1 and Filter2 - filter1 looks for a pattern and filter2 seeks range compression/expansion.

Let’s Search – And Away We Go

I will optimize across the different patterns and range analysis and different $ stops for each entry (1st and 2nd.)

Optimize across patterns and volatility and protective stops for 1st and 2nd entries.

Best Total Profit

Trade when today’s open is greater than yesterday’s close and don’t worry about the volatility.  Use $550 for the first entry and $600 for the second.

Best W:L Ratio and Respectable Avg. Trade

This curve was created  by waiting for yesterday’s close to be below the prior day’s and yesterday being an NR4 (narrow range 4).  And using a $500 protective stop for both the 1st and 2nd entries.

Did We Find the Holy Grail?  Gosh No!

This post served two purposes.  One, how to set up a framework for data mining and two, create code that can handle things that aren’t apparently obvious – entryPrice versus avgEntryPrice!

if filter1 and filter2 Then
begin
if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;
end;
Incorporating Filter1 and Filter2 in the Entry Logic

 

Converting Method() To Function – MultiCharts

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  }
//the t in tradeProfit. // var: double tradeProfit;

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



method void dayOfWeekAnalysis() {method definition}
var: double tradeProfit;
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;
weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit;
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);
var: tradeProfit(0);
mp = marketPosition;

tradeProfit = -999999999;
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;
if tradeProfit <> -999999999 then
weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit;
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.

Function Properties – AutoDetect Selected

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);
vars: mp(0),newTrade(false);

Buy next bar at highest(high,9)[1] stop;
Sellshort next bar at lowest(low,9)[1] stop;
mp = marketPosition;
newTrade = False;
//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.

 

 

Daily Bar Ratcheting Stop and Conditional Optimization

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:

Opimization space

And here are the results:

Optimization 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.

Converting A String Date To A Number – String Manipulation in EasyLanguage

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,”/”);
whereIsAdash = 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

 

Turn of the Month Trading Strategy [Stock Indices Only]

The System

This system has been around for several years.  Its based on the belief that fund managers start pouring money into the market near the end of the month and this creates momentum that lasts for just a few days.  The original system states to enter the market on the close of the last bar of the day if the its above a certain moving average value.  In the Jaekle and Tomasini book, the authors describe such a trading system.  Its quite simple, enter on the close of the month if its greater than X-Day moving average and exit either 4 days later or if during the trade the closing price drops below the X-Day moving average.

EasyLanguage or Multi-Charts Version

Determining the end of the month should be quite easy -right?  Well if you want to use EasyLanguage on TradeStation and I think on Multi-Charts you can’t sneak a peek at the next bar’s open to determine if the current bar is the last bar of the month.  You can try, but you will receive an error message that you can’t mix this bar on close with next bar.  In other words you can’t take action on today’s close if tomorrow’s bar is the first day of the month.  This is designed, I think, to prevent from future leak or cheating.  In TradeStation the shift from backtesting to trading is designed to be a no brainer, but this does provide some obstacles when you only want to do a backtest.

LDOM function – last day of month for past 15 years or so

So I had to create a LastDayOfMonth function.  At first I thought if the day of the month is the 31st then it is definitely the last bar of the month.  And this is the case no matter what.  And if its the 30th then its the last day of the month too if the month is April, June, Sept, and November.  But what happens if the last day of the month falls on a weekend.  Then if its the 28th and its a Friday and the month is blah, blah, blah.  What about February?  To save time here is the code:

Inputs: movAvgPeriods(50);
vars: endOfMonth(false),theDayOfWeek(0),theMonth(0),theDayOfMonth(0),isLeapYear(False);

endOfMonth = false;
theDayOfWeek = dayOfWeek(date);
theMonth = month(date);
theDayOfMonth = dayOfMonth(date);
isLeapYear = mod(year(d),4) = 0;

// 29th of the month and a Friday
if theDayOfMonth = 29 and theDayOfWeek = 5 then
endOfMonth = True;
// 30th of the month and a Friday
if theDayOfMonth = 30 and theDayOfWeek = 5 then
endOfMonth = True;
// 31st of the month
if theDayOfMonth = 31 then
endOfMonth = True;
// 30th of the month and April, June, Sept, or Nov
if theDayOfMonth = 30 and (theMonth=4 or theMonth=6 or theMonth=9 or theMonth=11) then
endOfMonth = True;
// 28th of the month and February and not leap year
if theDayOfMonth = 28 and theMonth = 2 and not(isLeapYear) then
endOfMonth = True;
// 29th of the month and February and a leap year or 28th, 27th and a Friday
if theMonth = 2 and isLeapYear then
Begin
If theDayOfMonth = 29 or ((theDayOfMonth = 28 or theDayOfMonth = 27) and theDayOfWeek = 5) then
endOfMonth = True;
end;
// 28th of the month and Friday and April, June, Sept, or Nov
if theDayOfMonth = 28 and (theMonth = 4 or theMonth = 6 or
theMonth = 9 or theMonth =11) and theDayOfWeek = 5 then
endOfMonth = True;
// 27th, 28th of Feb and Friday
if theMonth = 2 and theDayOfWeek = 5 and theDayOfMonth = 27 then
endOfMonth = True;
// 26th of Feb and Friday and not LeapYear
if theMonth = 2 and theDayOfWeek = 5 and theDayOfMonth = 26 and not(isLeapYear) then
endOfMonth = True;
// Memorial day adjustment
If theMonth = 5 and theDayOfWeek = 5 and theDayOfMonth = 28 then
endOfMonth = True;
//Easter 2013 adjustment
If theMonth = 3 and year(d) = 113 and theDayOfMonth = 28 then
endOfMonth = True;
//Easter 2018 adjustment
If theMonth = 3 and year(d) = 118 and theDayOfMonth = 29 then
endOfMonth = True;

if endOfMonth and c > average(c,movAvgPeriods) then
Buy("BuyDay") this bar on close;

If C <average(c,movAvgPeriods) then
Sell("MovAvgExit") this bar on close;
If BarsSinceEntry=4 then
Sell("4days") this bar on close;
Last Day Of Month Function and Strategy

All the code is generic except for the hard code for days that are a consequence of Good Friday.

All this code because I couldn’t sneak a peek at the date of tomorrow.  Here are the results of trading the ES futures sans execution costs for the past 15 years.

Last Day Of Month Buy If C > 50 Day Mavg

What if it did the easy way and executed the open of the first bar of the month.

If c > average(c,50) and month(d) <> month(d of tomorrow) then 
buy next bar at open;

If barsSinceEntry >=3 then
sell next bar at open;

If marketPosition = 1 and c < average(c,50) then
sell next bar at open;
Buy First Day Of Month
First Day of Month If C > 50 Day Mavg

The results aren’t as good but it sure was easier to program.

TradingSimula-18 Version

Since you can use daily bars we can test this with my TradingSimula-18 Python platform.  And we will execute on the close of the month.  Here is the snippet of code that you have to concern yourself with.  Here I am using Sublime Text and utilizing their text collapsing tool to hide non-user code:

Small Snippet of TS-18 Code

This was easy to program in TS-18 because I do allow Future Leak – in other words I will let you sneak a peek at tomorrow’s values and make a decision today.  Now many people might say this is a huge boo-boo, but with great power comes great responsibility.  If you go in with eyes wide open, then you will only use the data to make things easier or even doable, but without cheating.  Because you are only going to cheat yourself.  Its in your best interest do follow the rules.  Here is the line that let’s you leak into the future.

If isNewMonth(myDate[curBar+1])

The curBar is today and curBar+1 is tomorrow.  So I am saying if tomorrow is the first day of the month then buy today’s close.  Here you are leaking into the future but not taking advantage of it.  We all know if today is the last day of the month, but try explaining that to a computer.  You saw the EasyLanguage code.  So things are made easier with future leak, but not taking advantage of .

Here is a quick video of running the TS-18 Module of 4 different markets.