Data Aliasing with Minute Bars

Why It Is Important to Connect Variables with Correct Time Frame

I had a question about data aliasing from a reader of this blog.  Here is the debug code I used in the form of an Indicator.

//vars: myCloseData1(0),myCloseData2(0),
// myRSIData1(0),myRSIData2(0);

vars: myCloseData1(0),myCloseData2(0,data2),
myRSIData1(0),myRSIData2(0,data2);


myCloseData1 = close of data1;
myCloseData2 = close of data2;

myRSIData1 = rsi(close of data1,14);
myRSIData2 = rsi(close of data2,14);


Print(d," ",t," --------------- ");

print(" myCloseData1[0]: ",myCloseData1[0]," myCloseData2[0]: ",myCloseData2[0]);
print(" myCloseData1[1]: ",myCloseData1[1]," myCloseData2[1]: ",myCloseData2[1]);
print(" myCloseData1[2]: ",myCloseData1[2]," myCloseData2[2]: ",myCloseData2[2]);
print(" myCloseData1[3]: ",myCloseData1[3]," myCloseData2[3]: ",myCloseData2[3]);

print(" myRSIData1[0]: ",myRSIData1[0]," myRSIData2[0]: ",myRSIData2[0]);
print(" myRSIData1[1]: ",myRSIData1[1]," myRSIData2[1]: ",myRSIData2[1]);
print(" myRSIData1[2]: ",myRSIData1[2]," myRSIData1[2]: ",myRSIData2[2]);
print(" myRSIData1[3]: ",myRSIData1[3]," myRSIData1[3]: ",myRSIData2[3]);
Illustrating Difference Between Data Aliasing and Not Data Aliasing

If you have a higher resolution as Data 1 (5 minute in this case) than Data 2 (15 minute), then you must use Data Aliasing if you are going to use a variable to represent a price or a function output.  With out Data Aliasing all data references are in terms of Data 1.  When the 15 minute bar closes then the current [0] and one bar back[ 1] will be correct – going back further in time will reflect correct data.  During the 15 minute bar only the last value [0] will show the correct reading of the last completed 15 minute bar.  Once you tie the variable to its correct time frame variableName(0, Data2), you can then reference historic bars in the same fashion as if it were Data1.  This includes price references and function output values.

Check this chart out and see if it makes sense to you.  I dedicate a portion of a Tutorial on Data Aliasing in my latest book due out next week – Easing Into EasyLanguage – Advanced Topics.

Difference between using Data Aliasing and Not using Data Aliasing

A Tribute to Murray and His Inter-Market Research

Murray Ruggiero’s Inter-Market Research

Well it’s been a year, this month, that Murray passed away.  I was fortunate to work with him on many of his projects and learned quite a bit about inter-market convergence and divergence.  Honestly, I wasn’t that into it, but you couldn’t argue with his results.  A strategy that he developed in the 1990s that compared the Bond market with silver really did stand the test of time.  He monitored this relationship over the years and watched in wane.  Murray replaced silver with $UTY.

The PHLX Utility Sector Index (UTY) is a market capitalization-weighted index composed of geographically diverse public utility stocks.

He wrote an article for EasyLanguage Mastery by Jeff Swanson where he discussed this relationship and the development of inter-market strategies and through statistical analysis proved that these relationships added real value.

I am currently writing Advanced Topics, the final book in my Easing Into EasyLanguage trilogy, and have been working with Murray’s research.  I am fortunate to have a complete collection of his Futures Magazine articles from the mid 1990s to the mid 2000s.  There is a quite a bit of inter-market stuff in his articles.  I wanted, as a tribute and to proffer up some neat code, to show the performance and code of his Bond and $UTY inter-market algorithm.

Here is a version that he published a few years ago updated through June 30, 2022 – no commission/slippage.

Murray’s Bond and $UTY inter-market Strategy

Not a bad equity curve.  To be fair to Murray he did notice the connection between $UTY and the bonds was changing over the past couple of year.  And this simple stop and reverse system doesn’t  have a protective stop.   But it wouldn’t look much different with one, because the system looks at momentum of the primary  data and momentum of the secondary data and if they are in synch (either positively or negatively correlated – selected by the algo) an order is fired off.  If you simply just add a protective stop, and the momentum of the data are in synch, the strategy will just re-enter on the next bar.  However, the equity curve just made a new high  recently.  It has got on the wrong side of the Fed raising rates.  One could argue that this invisible hand has toppled the apple cart and this inter-market relationship has been rendered meaningless.

Murray had evolved his inter-market analysis to include state transitions.  He not only looked at the current momentum, but also at where the momentum had been.  He assigned the transitions of the momentum for the primary and secondary markets a value from one to four and he felt this state transition helped overcome some of the coupling/decoupling of the inter-market relationship.

However,  I wanted to test Murray’s simple strategy with a fixed $ stop and force the primary market to move from positive to negative or negative to positive territory while the secondary market is in the correct relationship.  Here is an updated equity curve.

George’s Adaptation and using a $4500 stop loss

This equity curve was developed  by using a $4500 stop loss.  Because I changed the order triggers, I reoptimized the length of the momentum calculations for the primary and secondary markets.  This curve is only better in the category of maximum draw down.  Shouldn’t we give Murray a chance and reoptimize his momentum length calculations too!  You bet.

Murray Length Optimizations

These metrics were sorted by Max Intraday Draw down.  The numbers did improve, but look at the Max Losing Trade value.  Murray’s later technology,  his State Systems, were a great improvement over this basic system.  Here is my optimization using a slightly different entry technique and a $4500 protective stop.

Standing on the Shoulders of a Giant

This system, using Murray’s overall research, achieved a better Max Draw Down and a much better Max Losing Trade.   Here is my code using the template that Murray provided in his articles in Futures Magazine and EasyLanguage Mastery.

 

// Code by Murray Ruggiero
// adapted by George Pruitt

Inputs: InterSet(2),LSB(0),Type(1),LenTr(4),LenInt(4),Relate(0);
Vars: MarkInd(0),InterInd(0);

If Type=0 Then
Begin
InterInd=Close of Data(InterSet)-CLose[LenInt] of Data(InterSet);
MarkInd=CLose-CLose[LenTr];
end;

If Type=1 Then
Begin
InterInd=Close of Data(InterSet)-Average(CLose of Data(InterSet),LenInt);
MarkInd=CLose-Average(CLose,LenTr);
end;

if Relate=1 then
begin
If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy("GO--Long") Next Bar at open;
If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short("GO--Shrt") Next Bar at open;

end;
if Relate=0 then begin
If InterInd<0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy Next Bar at open;
If InterInd>0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short Next Bar at open;
end;

Here the user can actually include more than two data streams on the chart.  The InterSet input allows the user to choose or optimize the secondary market data stream.  Momentum is defined by two types:

  • Type 0:  Intermarket or secondary momentum simply calculated by close of data(2) – close[LenInt] of date(2) and primary momentum calculated by close – close[LenTr]
  • Type 1:   Intermarket or secondary momentum  calculated by close of data(2) – average( close of data2, LenInt)  and primary momentum calculated by close – average(close, LenTr)

The user can also input what type of Relationship: 1 for positive correlation and 0 for negative correlation.  This template can be used to dig deeper into other market relationships.

George’s Modification

I simply forced the primary market to CROSS below/above 0 to initiate a new trade as long the secondary market was pointing in the right direction.

	If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then 
Buy("GO--Long") Next Bar at open;
If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short("GO--Shrt") Next Bar at open;
Using the keyword CROSSES

This was a one STATE transition and also allowed a protective stop to be used without the strategy automatically re-entering the trade in the same direction.

Thank You Murray – we sure do miss you!

Murray loved to share his research and would want us to carry on with it.  I will write one or two blogs a year in tribute to Murray and his invaluable research.

Using Gradient to Shade Between Plots

Quickly Analyze Market Metrics with Gradient Based Shading

This is a simple indicator but it does involve some semi-advanced topics.  Just to let you know I am working on the third book in the Easing Into EasyLanguage series.  If you haven’t check out the first two, you might just want to head over to amazon and check those out.  This topic falls in the spectrum of the ideas that I will be covering in the Advanced Topics edition.  Also to let you know I just published the 2nd Edition of Trend Following Systems: A DIY Project – Batteries Included.  Check this out if you want to learn some Python and also see some pretty cool Trend Following algorithms – I include EasyLanguage too!

Shading Between Keltner Channels with RSI Intensity

The code that follows demonstrates how to shade between plots and adjust gradient in terms of the RSI reading.  I compiled this with MultiCharts, so I assume it will work there too – just let me know if it doesnt.  I found this code somewhere on the web when researching shading.  If I knew the original author I would definitely give full credit.   The code is rather simple, setting up the chart is just slightly more difficult.  The Keltner Channel was used to define the shading boundaries.  You could have just as easily used Bollinger Bands or anything that provided a range around the market.  Here’s the code.

inputs:  KeltnerLength( 90 ), KeltnerWid( 5 ), RSILength( 14 ), overbought( 70 ), oversold( 30 ); 
var: Avg( 0 ), Shift( 0 ), LowerBand( 0 ), UpperBand( 0 ), MyRSI( 0 ) ;

// Keltner

Avg = AverageFC( c, KeltnerLength ) ;
Shift = KeltnerWid * AvgTrueRange( Keltnerlength ) ;
UpperBand = Avg + Shift ;
LowerBand = Avg - Shift ;

Plot11( UpperBand, "UpperBand" ) ;
Plot12( LowerBand, "LowerBand" ) ;
Plot13( Avg, "MidLine" ) ;

// RSI

MyRSI = xaverage(RSI( c, RSILength ), 7) ;

var: projrsi(0);

// Get projected RSI in terms of the Upper and Lower Bands

projrsi = Avg + .01 * (UpperBand - LowerBand) * (MyRSI - 50) * 2.5;
if false then plot14( projrsi, "RSI" );

// Gradient background

var: barspacing( getappinfo( aibarspacing ) );
var: gradcolr(0);
// Remember how to use the IFF function?
gradcolr = iff( MyRSI > 50, GradientColor( projrsi, Avg, UpperBand, black, red),
GradientColor(projrsi, LowerBand, Avg, green, black) );

plot91( UpperBand, "ugrad", gradcolr, default, barspacing);
plot92( LowerBand, "lgrad");

// Show Bar - increase transparency of data to 100% so
// shading does not overlap the bar charts

plot4( c, "c");
plot5( h, "h");
plot6( l, "l");
Code to Shade with Gradient Based on a RSI Reading

That is a little bit of code that does a lot of work.  Here are the key lines and their explanations.

projrsi = Avg + .01 * (UpperBand – LowerBand) * (MyRSI – 50) * 2.5;

Remember the RSI outputs values between 0 and 100 – oscillates.  Assume RSI is in oversold territory at 24.

UpperBand = 16273 and LowerBand = 15023 and Avg = 15648

Let’s do the math:

  1. projrsi = 15468 + 0.01 * (16273 – 15023) * (24 – 50) * 2.5
  2. projrsi = 15468 + 0.01 * 1250  * – 26 * 2.5
  3. projrsi = 15468 + 12.5 * -65
  4. projrsi = 15468 – 165
  5. projrsi = 15308

Basically all this math is doing is keeping the RSI reading within the bounds of the Keltner Upper and Lower Channels.  You want a high RSI reading to be near the Upper Channel and a low RSI reading to be near the Lower Channel.   You can change up the formula to make more sense.

projrsi = Avg + (MyRSI – 50)/100 * (UpperBand – LowerBand) * 2.5

I have worked with computer graphics for many years and this is really a very neat formula.  The generic formula to constrain a value within a boundary is;

projrsi = LowerBand + (MyRSI / 100) * (UpperBand – LowerBand)

Here you take the LowerBand and add the percentage of the MyRSI/100 times the range.  This works too.  But the original formula scales or intensifies the RSI reading so you get much wider gradient spectrum.  The AVG is used as the center of gravity and the RSI is converted in terms of the middle 50 line.  A positive number, anything > 50, is then scaled higher in the range and a negative number, anything < 50 is scaled lower in the range.  In other words it makes a prettier and more informative picture.

The other important line in the code is

gradcolr = iff( MyRSI > 50, GradientColor( projrsi, Avg, UpperBand, black, red),
GradientColor(projrsi, LowerBand, Avg, green, black) );

This code uses the IFF function which basically replicates this

If MyRSI > 50 then

     gradColor = GradientColor(projrsi, Avg, UpperBand, black, red)

else

gradColor = GradientColor(projrsi,Avg,LowerBand,green,black);

GradientColor Function

GradientColor( dValue, dMin, dMax, nFromColor, nToColor )

Return

Returns a specific color from a user defined gradient color range, such as Blue to White

Inputs:

  • dValue = value being passed-in that is within the specified Min/Max range of values
  • dMin = Starting value for the gradient range, where the nFromColor is displayed
  • dMax = Ending value for the gradient range, where the nToColor is displayed
  •  nFromColor = Starting color of the gradient
  • nToColor = Ending color of the gradient

Since the gradient shading will cover up your bars you will need to plot the bars as well.

Chart SetUp

The close should be POINT and the other inputs LINES.

Don’t Forget To Fade Out Your Data Chart

That’s it.  Like I stated earlier – I will be including things like this in the Advanced Topics edition.  I should have it wrapped sometime in July or August.

 

Using EXCEL VBA to Combine Equity Curves from TradeStation

A Poor Man’s Equity Curve Merger

Sometimes you just want to create a combined equity curve of several markets and for one reason or another you don’t want to use Maestro.  This post will show you an indicator that you can insert into your TradeStation chart/strategies that will output monthly cumulative equity readings.  After that I refresh my VBA skills a little bit by creating a VBA Macro/Script that will take the output and parse it into a table where the different months are the rows and the different market EOM equities, for those months, will be the columns.  Then all the rows will be summed and then finally a chart will be produced.  I will zip the Exel .xlsm and include it at the end of this post.

Part 1:  Output Monthly Data to Print Log

You can determine the end of the month by comparing the current month of the date and the month of the prior date.  If they are different, then you know you are sitting on the first trading day of the new month.  You can then reach back and access the total equity as of yesterday.  If you want you can also track the change in month equity.  Here is the indicator code in EasyLanguage.

// Non plotting indicator that needs to be applied to 
// a chart that also has a strategy applied
// one that produces a number of trades

vars: monthlyEqu(0),priorMonthEqu(0);
vars: totalEquity(0);


if month(date) <> month(date[1]) then
begin
monthlyEqu = totalEquity[1] - priorMonthEqu;
priorMonthEqu = totalEquity[1];
print(getSymbolName,",",month(date[1]):2:0,"-",year(date[1])+1900:4:0,",",monthlyEqu,",",totalEquity);
end;
totalEquity = i_ClosedEquity;
Indicator that exports the EOM equity values

The interesting part of this code is the print statement.  You can use the month and year  functions to extract the respective values from the date bar array.  I use a formatted print to export the month and year without decimals.  Remember 2021 in TradeStation is represented by 121 and all you have to do is add 1900 to get a more comfortable value.  The month output is formatted with :2:0 and the year with :4:0.  The first value in the format notation informs  the computer to allow at least 2 or 4 values for the month  and the year respectively.  The second value following the second colon informs the computer that you do not want any decimals values (:0).  Next insert the indicator into all the charts in your workspace.  Here’s a snippet of the output on one market.  I tested this on six markets and this data was the output generated.  Some of the markets were interspersed and that is okay.  You may have a few months of @EC and then a few months of @JY and then @EC again.

@EC, 7-2008,-5106.24,-5106.24
@EC, 8-2008, 0.00,-5106.24
@EC, 9-2008, 0.00,-5106.24
@EC,10-2008, 0.00,-5106.24
@EC,11-2008, 0.00,-5106.24
@EC,12-2008,25156.26,20050.02
@EC, 1-2009, 0.00,20050.02
@EC, 2-2009, 0.00,20050.02
@EC, 3-2009, 0.00,20050.02
@EC, 4-2009, 0.00,20050.02
@EC, 5-2009, 0.00,20050.02
@EC, 6-2009, 0.00,20050.02
@EC, 7-2009, 0.00,20050.02
@EC, 8-2009, 0.00,20050.02
@EC, 9-2009, 0.00,20050.02
@EC,10-2009, 0.00,20050.02
@EC,11-2009, 0.00,20050.02
@EC,12-2009,7737.51,27787.53
@EC, 1-2010, 0.00,27787.53
@EC, 2-2010, 0.00,27787.53
@EC, 3-2010, 0.00,27787.53
@EC, 4-2010, 0.00,27787.53
@EC, 5-2010, 0.00,27787.53
@EC, 6-2010, 0.00,27787.53
@EC, 7-2010, 0.00,27787.53
@EC, 8-2010, 0.00,27787.53
@EC, 9-2010,6018.76,33806.29
Indicator output

Part 2: Getting the Data into Excel

If you use this post’s EXCEL workbook with the macro you may need to tell EXCEL to forget any formatting that might already be inside the workbook.  Open my workbook and beware that it will inform/warn you that a macro is located inside and that it could be dangerous.  If you want to go ahead and enable the macro go ahead.  On Sheet1 click in A1 and place the letter “G”.  Then goto the Data Menu and then the Data Tools section of the ribbon and click Text to Columns.  A dialog will open and ask you they type of file that best describes your data.  Click the Delimited radio button and then next.  You should see a dialog like this one.

Clear Any Left Over Formatting

Now copy all of the data from the Print-Log and paste it into Column A.  If all goes right everything will be dumped in the appropriate rows and in a single column.

The fields will be dumped into a single column

First select column A and  go back to the Data Menu and the Data Tools on the Ribbon.  Select Delimited and hit next,  Choose comma because we used commas to separate our values.  Click Next again.  Eventually you will get to this dialog.

Make sure you use Date [MDY] for the second column of data.
If you chose Date format for column 2 with MDY, then it will be imported into the appropriate column in a date format.  This makes charting easier.  If all goes well then you will have four columns of data –  a column for Symbol, Date, Delta-EOM and EOM.  Select column B and right click and select Format Cells.

Clean Up column B by formatting cells and customizing the date format

Once you format the B column in the form of  MM-YYYY you will have a date like 9-2007, 10-2007, 11-2007…

Running the VBA Macro/Script

On the Ribbon in EXCEL goto the Developer Tab.  If you don’t see it then you will need to install it.  Just GOOGLE it and follow their instructions.  Once on the Develop Tab goto the Code category and click the Visual Basic Icon.  Your VBA IDE will open and should like very similar to this.

VBA IDE [integrated development environment]
If all goes according to plan after you hit the green Arrow for the Run command your spreadsheet should like similar to this.

EOM table with Months as Rows and Individual Market EOMs as columns

The Date column will be needed to be reformatted again as Date with Custom MM-YYYY format.  Now copy the table by highlighting the columns and rows including the headings and then goto to Insert Menu and select the Charts category.  

This is what you should get.

Merged Equity on Closed Trade Basis

This is the output of the SuperTurtle Trading system tested on the currency sector from 2007 to the present.

VBA Code

I have become very spoiled using Python as it does many things for you by simply calling a function.  This code took my longer to develop than I thought it would, because I had to back to the really old school of programming (really wanted to see if I could do this from scratch) to get this done.  You could of course eliminate some of my code by calling spread sheet functions from within EXCEL.  I went ahead and did it the brute force way just to see if I could do it.

Sub combineEquityFromTS()

'read data from columns
'symbol, date, monthlyEquity, cumulativeEquity - format
'create arrays to hold each column of data
'use nested loops to do all the work
'brute force coding, no objects - just like we did in the 80s

Dim symbol(1250) As String
Dim symbolHeadings(20) As String
Dim myDate(1250) As Long
Dim monthlyEquity(1250) As Double
Dim cumulativeEquity(1250) As Double

'read the data from the cells
dataCnt = 1
Do While Cells(dataCnt, 1) <> ""
symbol(dataCnt) = Cells(dataCnt, 1)
myDate(dataCnt) = Cells(dataCnt, 2)
monthlyEquity(dataCnt) = Cells(dataCnt, 3)
cumulativeEquity(dataCnt) = Cells(dataCnt, 4)
dataCnt = dataCnt + 1
Loop
dataCnt = dataCnt - 1

'get distinct symbolNames and use as headers
symbolHeadings(1) = symbol(1)
numSymbolheadings = 1
For i = 2 To dataCnt - 1
If symbol(i) <> symbol(i + 1) Then
newSymbol = True
For j = 1 To numSymbolheadings
If symbol(i + 1) = symbolHeadings(j) Then
newSymbol = False
End If
Next j
If newSymbol = True Then
numSymbolheadings = numSymbolheadings + 1
symbolHeadings(numSymbolheadings) = symbol(i + 1)
End If
End If
Next i

'Remove duplicate months in date array
'have just one column of month end dates

Cells(2, 7) = myDate(1)
dispRow = 2
numMonths = 1
i = 1
Do While i <= dataCnt
foundDate = False
For j = 1 To numMonths
If myDate(i) = Cells(j + 1, 7) Then
foundDate = True
End If
Next j
If foundDate = False Then
numMonths = numMonths + 1
Cells(numMonths + 1, 7) = myDate(i)
End If
i = i + 1
Loop
'put symbols across top of table
'put "date" and "cumulative" column headings in proper
'locations too

Cells(1, 7) = "Date"
For i = 1 To numSymbolheadings
Cells(1, 7 + i) = symbolHeadings(i)
Next i

numSymbols = numSymbolheadings
Cells(1, 7 + numSymbols + 1) = "Cumulative"
'now distribute the monthly returns in their proper
'slots in the table
dispRow = 2
dispCol = 7
For i = 1 To numSymbols
For j = 2 To numMonths + 1
For k = 1 To dataCnt
foundDate = False
If symbol(k) = symbolHeadings(i) And myDate(k) = Cells(j, 7) Then
Cells(dispRow, dispCol + i) = cumulativeEquity(k)
dispRow = dispRow + 1
Exit For
End If
'for later use
'If j > 1 Then
' If symbol(k) = symbolHeadings(i) And myDate(k) < Cells(j, 7) And myDate(k) > Cells(j - 1, 7) Then
' dispRow = dispRow + 1
' End If
'End If
Next k
Next j
dispRow = 2
Next i
'now accumulate across table and then down
For i = 1 To numMonths
cumulative = 0
For j = 1 To numSymbols
cumulative = cumulative + Cells(i + 1, j + 7)
Next j
Cells(i + 1, 7 + numSymbols + 1) = cumulative
Next i
End Sub

This a throwback to the 80s BASIC on many of the family computers of that era.  If you are new to VBA you can access cell values by using the keyword Cells and the row and column that points to the data.   The first thing you do is create a Module named combineEquityFromTS and in doing so it will create a Sub combineEquityFromTS() header and a End Sub footer.  All of your code will be squeezed between these two statements.  This code is ad hoc because I just sat down and started coding without much forethought.  

Use DIM to Dimension an Arrays

I like to read the date from the cells into arrays so I can manipulate the data internally.  Here I create five arrays and then loop through column one until there is no longer any data.  The appropriate arrays are filled with their respective data from each row.

Dimension and Load Arrays

Once the data is in arrays we can start do parse it.  The first thing I want is to get the symbolHeadings or markets.  I know the first row has a symbol name so I go ahead and put that into the symbolHeadings array.  I kept track of the number of rows in the data with the variable dataCnt.  Here I use  nested loops to work my way down the data and keep track of new symbols as I encounter them.  If the symbol changes values, I then check my list of stored symbolHeadings and if the new symbol is not in the list I add it.

Parse different symbols from all data

Since all the currencies will have the same month values I wanted to compress all the months into a single discrete month list.  This isn’t really all that necessary since we could have just prefilled the worksheet with monthly date values going back to 2007.  This algorithm is similar to the one that is used to extract the different symbols.  Except this time, just for giggles, I used a Do While Loop.

Squash Monthly List Down

As well as getting values from cells you can also put values into them.  Here I run through the list of markets and put them into Cells(1, 7+i).  When working with cells you need to make sure you get the offset correct.  Here I wanted to put the market names in Row A and Columns: H, I, J, K, L, M.

  • Column H = 8
  • Column I = 9
  • Column J = 10
  • Column K =11
  • Column L = 12
  • Column M = 13
Put Markets as Column Headers

Cells are two dimensional arrays.  However if you are going to use what is on the worksheet make sure you are referencing the correct data.  Here I introduce dispRow and dispCol as the anchor points where the data I need to reference starts out.

Three nested loops – Whopee.

Here I first parse through each symbol and extract the EOM value that matches the symbol name and month-year value.  So if I am working on @EC and I need the EOM for 07-2010, I fist loop through the month date values and compare the symbol AND myDate (looped through with another for-loop) with the month date values.  If they are the same then I dump the value in the array on to the spreadsheet.  And yes I should have used this:

For j = dispRow to numMonths-1

Instead of –

For j = 2 to numMonths-1

Keeping arrays in alignment with Cells can be difficult.  I have a hybrid approach here.  I will clean this up later and stick just with arrays and only use Cells to extract and place data.  The last thing you need to do is sum each row up and store that value in the Cumulative column.

Across and then Down to sum accumulated monthly returns

Conclusion

This was another post where we relied on another application to help us achieve our objective.   If you are new to EXCEL VBA (working with algorithms that generate trades) you can find out more in my Ultimate Algorithmic Trading System Toolbox book.  Even if you don’t get the book this post should get you started on the right track.

Excel Workbooks – One Empty with Macro and one Filled With this Post Data.

 

Super Trend Indicator in EasyLanguage

SuperTrend Indicator – What Is It?

SuperTrend is a trading strategy and indicator all built into one entity.  There are a couple of versions floating around out there.  MultiCharts and Sierra Chart both have slightly different flavors of this combo approach.

Ratcheting Trailing Stop Paradigm

This indic/strat falls into this category of algorithm.  The indicator never moves away from your current position like a parabolic stop or chandelier exit.  I used the code that was disclosed on Futures.io or formerly known as BigMikesTrading blog.   This version differs from the original SuperTrend which used average true range.  I like Big Mike’s version so it will discussed here.

Big Mike’s Math

The math for this indicator utilizes volatility in the terms of the distance the market has travelled over the past N days.  This is determined by calculating the highest high of the last N days/bars and then subtracting the lowest low of last N days/bars.   Let’s call this the highLowRange.  The next calculation is an exponential moving average of the highLowRange.  This value will define the market volatility.   Exponential moving averages of the last strength days/bars highs and lows are then calculated and divided by two – giving a midpoint.  The volatility measure (multiplied my mult) is then added to this midpoint to calculate an upper band.  A lower band is formed by subtracting the volatility measure X mult from the midpoint.

Upper or Lower Channel?

If the closing price penetrates the upper channel and the close is also above the highest high of strength days/bars back (offset by one of course) then the trend will flip to UP.  When the trend is UP,  then the Lower Channel is plotted.  Once the trend flips to DN, the upper channel will be plotted.  If the trend is UP the lower channel will either rise with the market or stay put.  The same goes for a DN trend – hence the ratcheting.  Here is a graphic of the indicator on CL.

Super Trend by Bike Mike

If you plan on using an customized indicator in a strategy it is always best to build the calculations inside a function.  The function then can be used in either an indicator or a strategy.

Function Name: SuperTrend_BM

Function Type: Series – we will need to access prior variable values

SuperTrend_BM Function Code:

//SuperTrend from Big Mike now futures.io

inputs:
length(NumericSimple), mult(NumericSimple), strength(NumericSimple), STrend(NumericRef);

vars:
highLowRange(0),
xAvgRng(0),
xAvg(0),
dn(0),
up(0),
trend(1),
trendDN(False),
trendUP(False),
ST(0);

highLowRange = Highest(high, length) - Lowest(low, length);

xAvgRng = XAverage(highLowRange, length);

xAvg = (XAverage(high, Strength) + XAverage(low, Strength))/2;

up = xAvg + mult * xAvgRng;
dn = xAvg - mult * xAvgRng;

if c > up[1] and c > Highest(High, strength)[1] then
trend = 1
else
if c < dn[1] and c < Lowest(Low, Strength)[1] then
trend = -1;

//did trend flip?
trendDN = False;
trendUP = False;

if trend < 0 and trend[1] > 0 then
trendDN = True;
if trend > 0 and trend[1] < 0 then
trendUP = True;

//ratcheting mechanism
if trend > 0 then dn = maxList(dn,dn[1]);
if trend < 0 then up = minList(up,up[1]);

// if trend dir. changes then assign
// up and down appropriately
if trendUP then
up = xAvg + mult * xAvgRng;
if trendDN then
dn = xAvg - mult * xAvgRng;

if trend = 1 then
ST = dn
else
ST = up;

STrend = trend;

SuperTrend_BM = ST;
SuperTrend ala Big Mike

The Inputs to the Function

The original SuperTrend did include the Strength input.  This input is a Donchian like signal.  Not only does the price need to close above/below the upper/lower channel but also the close must be above/below the appropriate Donchian Channels to flip the trend,  Also notice we are using a numericRef as the type for STrend.  This is done because we need the function to return two values:  trend direction and the upper or lower channel value.  The appropriate channel value is assigned to the function name and STrend contains the Trend Direction.

A Function Driver in the Form of an Indicator

A function is a sub-program and must be called to be utilized.   Here is the indicator code that will plot the values of the function using: length(9), mult(1), strength(9).

// SuperTrend indicator
// March 25 2010
// Big Mike https://www.bigmiketrading.com
inputs:
length(9), mult(1), strength(9);

vars:
strend(0),
st(0);

st = SuperTrend_BM(length, mult,strength,strend);

if strend = 1 then Plot1(st,"SuperTrendUP");
if strend = -1 then Plot2(st,"SuperTrendDN");
Function Drive in the form of an Indicator

 

This should be a fun indicator to play with in the development of a trend following approach.   My version of Big Mike’s code is a little different as I wanted the variable names to be a little more descriptive.

Update Feb 28 2022

I forgot to mention that you will need to make sure your plot lines don’t automatically connect.

Plot Style Setting

Can You Do This with Just One Plot1?

An astute reader brought it to my attention that we could get away with a single plot and he was right.  The reason I initially used two plot was to enable the user to chose his/her own plot colors by using the Format dialog.

//if strend = 1 then Plot1(st,"SuperTrendUP");
//if strend = -1 then Plot2(st,"SuperTrendDN");

if strend = 1 then SetPlotColor(1,red);
if strend = -1 then SetPlotColor(1,green);

Plot1(st,"SuperTrend_BM");
Method to just use one Plot1

Tracking Last EntryPrice While Pyramiding on Minute Bars

EasyLanguage’s EntryPrice Doesn’t Cut the Mustard

In writing the Hi-Res edition of Easing Into EasyLanguage I should have included this sample program.  I do point out the limitations of the EntryPrice keyword/function in the book.  But recently I was tasked to create a pyramiding scheme template that used minute bars and would initiate a position with N Shares and then pyramid up to three times by adding on N Shares at the last entry price + one 10 -Day ATR measure as the market moves in favor of the original position.  Here is an example of just such a trade.

Pyramid 3 Times After Initial Trade Entry. Where’s the EntryPrice?

EntryPrice only contains the original entry price.  So every time you add on a position, the EntryPrice doesn’t reflect this add on price.  I would like to be able to index into this keyword/function and extract any EntryPrice.  If you enter at the market, then you can keep track of entry prices because a market order is usually issued from an if-then construct:

//Here I can keep track of entry prices because I know
//exactly when and where they occur.

if c > c[1] and value1 > value2 then
begin
buy("MarketOrder") next bar at market;
lastEntryPrice = open of next bar;
end;
Last Entry Price tracking is easy if using Market Orders

But what if you are using a stop or limit order.  You don’t know ahead of time where one of these types of orders will hit up.  It could be the next bar or it could be five bars later or who knows.

AvgEntryPrice Makes Up for the Weakness of EntryPrice

AvgEntryPrice is a keyword/function that  returns the average of the entries when pyramiding.  Assume you buy at 42.00 and pyramid the same number of shares at 46.50 – AvgEntryPrice will be equal to (42.00 + 46.50) / 2 = 44.25.  With this information you can determine the two entry prices.  You already know the original price.  Take a look at this code.

// remember currentShares and avgEntryPrice ARE EasyLanguage Keywords/Functions
if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",totShorts," ",avgEntryPrice," ",entryPriceSums);
end;
end;
Calculating the true LastEntryPrice

Remember currentShares is a keyword/function and it is immediately updated when more shares are added or taken off.  CurShares is my own variable where I keep track of the prior  currentShares , so if currentShares (real number of shares) is greater than the prior curShares (currentShares) then I know 100%, a position has been pyramided as long the the mp stays the same.  If currentShares increases and mp stays constant, then you can figure out the last entry price where the pyramid takes place.  First you tick totShorts up by 1.  If currentShares > initShares, then you know you are pyramiding so

lastEntryPrice = totShorts * avgEntryPrice – entryPriceSums

Don’t believe me.  Let’s test it.  Remember original entry was 42.00 and the add on was at 46.50.  TotShorts now equals 2.

  1. Initial entryPrice = 42.00 so entryPriceSums is set to 42.00
  2. After pyramiding avgEntryPrice is set to 44.25
  3. lastEntryPrice = 2 * 44.25 – 42.00 = 46.50
  4. entryPriceSums is then set to 42.00 + 46.50 or 88.50

So every time you add on a position, then you flow through this logic and you can keep track of the actual last entry price even if it is via a limit or stop order.

But wait there is more.  This post is also a small glimpse into what I will be writing about in the Easing Into EasyLanguage:  Advanced Topics.  This system definitely falls into what I discussed in the Hi-Res Edition.  Here is where we tip over into Advanced Topics.  The next book is not about creating dialogs or trading apps using OOEL (object oriented EasyLanguage), but we do use some of those topics to do some rather complicated back testing things.

Now that we know how to calculate the lastEntryPrice wouldn’t it be really cool if we could keep track of all of the entryPrices during the pyramid stream.   If I have pyramided four times, I would like to know entryPrice 1, entryPrice 2, entryPrice 3 and entryPrice 4.

EntryPrice Vector

Dr. VectorLove or How I Learned to Stop Worrying and Love Objects

I have discussed vectors before but I really wanted to discuss them more.  Remember Vectors are just lists or arrays that don’t need all the maintenance.  Yes you have to create them which can be a pain, but once you learn and forget it twenty times it starts to sink in.  Or just keep referring back to this web page.


Using elsystem.collections;

vars: Vector entryPriceVector(Null);

once Begin
entryPriceVector = new Vector;
end;
The Bare Minimum to Instantiate a Vector
  1. Type – “Using elsystem.collections; “
  2. Declare entryPriceVector as a Vector and set it equal to Null
  3. Use Once and instantiate entryPriceVector by using the keyword new < object type>;

A Vector is part of elsystem’s collection objects.  Take a look at this updated code,

if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceVector.push_back(lastEntryPrice);
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",entryPrice," ",entryPrice(1)," ",totShorts," ",avgEntryPrice," ",entryPriceSums," ",entryPriceVector.back() astype double," ",entryPriceVector.count asType int);
if not(entryPriceVector.empty()) then
begin
for m = 0 to entryPriceVector.count-1
begin
print(entryPriceVector.at(m) astype double);
end;
end;
end;
end;
LastEntryPrice and Pushing It onto the Vector and Then Printing Out the Vector

After the lastEntryPrice is calculated it is pushed onto the entryPriceVector using the function (method same thing but it is attached to the Vector class).push_back(lastEntryPrice);

entryPriceVector.push_back(lastEntryPrice);

So every time a new lastEntryPrice is calculated it is pushed onto the Vector at the back end.  Now if the entryPriceVector is not empty then we can print its contents by looping and indexing into the Vector.

if not(entryPriceVector.empty()) then
begin
     for m = 0 to entryPriceVector.count-1
     begin
          print(entryPriceVector.at(m) astype double);
     end;
end;
Looping through a Vector and Printing Out its Contents

Remember if you NOT a boolean value then it turns it to off/on or just the opposite of the boolean valueIf entryPriceVector is not empty then proceed.  entryPriceVector.count holds the number of values stuffed into the vectorYou can index into the Vector by using .at(m),  If you want to print out the value of the Vector .at(m), then you will need to typecast the Vector object as what ever it is holding.  We know we are pushing numbers with decimals (double type) onto the Vector so we know we can evaluate them as a double type.  Just remember you have to do this when printing out the values of the Vector.

Okay you can see where we moved into an Advanced Topics area with this code.  But it really becomes useful when trying to overcome some limitations of EasyLanguage.  Remember keep an eye open for Advanced Topics sometime in the Spring.

Another Good Year For Trend Following

Take a Look at the Last Two Years

Simple Donchian on a one contract basis.  $100 Commission/slippage.  Tested from 2000 thru December 31, 2021.  Do you see why most trend followers failed after the 2008 monstrous year.   Many funds caught the 2008 move and more funds were added soon thereafter.  Promises of similar performance came to fruition in 2011.  This kept much of the “new money” on the board.  However, reality set in and weak handed funds left for greener pastures.  Those that stuck it out were rewarded in 2014.  The trend drought of 2014 -2019 eroded most of the confidence in managed futures.  The rationalization that limited resources would eventually rise in price sounded good initially, but then fell on deaf ears after months of draw down.  Well known CTAs and hedge funds shut their doors forever.   The long awaited promise of 2008 came in the form of a pandemic – but it was too late.   Maybe now the deluge that ended the drought will persevere (hopefully not in the form of a pandemic) into the future.  Prices do not need to rise endlessly, but they need to move one direction or another without many hiccups.   

Simple Donchian Caught Most of the Commodities Up Moves

Which Sectors Pushed this Curve through the Roof

These reports were generated by my Python based Trading Simula-18 using Pinnacle continuous data – rollover triggered by date.  This is my new sector analysis report where I graph the last four years performance.  The tabular data is for the entire 21 year history.  The best sectors were energy, grains, financials and metals.  Lumber was extraordinary

Sector Analysis Report
################################################
Currency -------------------------------------
BN -28012 44681
SN -26925 55337
AN 6560 34350
DX 16284 24387
FN 67463 31737
JN -22212 50362
CN -25355 44110
------------------------------------------------
Totals: -12198 141445
------------------------------------------------
Currency Last 4 Years ---------------------
|
||| |
||||||
| ||||||||
| |||||||||
| ||||||||||
|||||||||||||
||||||||||||||
|||||||||||||| |
|||||||||||||||||||
||||||||||||||||||||| |
|||||||||||||||||||||| | |
|||||||||||||||||||||| | |
|||||||||||||||||||||| | || | | |
------------------------------------------------ 0
||||||||||||||||||||||||| ||| |||| ||| |
||||||||||||||||||||||||| |||| |||||||||||
||||||||||||||||||||||||| | |||| ||||||||||||
||||||||||||||||||||||||||| |||||||||||||||||
|||||||||||||||||||||||||||| ||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Energies -------------------------------------
ZU 180750 38330
ZH 155696 85541
ZN 70630 74400
ZB 131874 66651
------------------------------------------------
Totals: 538951 154434
------------------------------------------------
Energies Last 4 Years ---------------------
| |
|| || ||
||| || |||
| ||||||||||
| |||||||||||
||| |||||||||||
|||| | ||||||||||||
||||||| ||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
|||||||||||||||||||||
| || |||||||||||||||||||||
|| || |||||||||||||||||||||
|| |||| |||||||||||||||||||||
||||||||| ||||||||||||||||||||||
| |||||||||| |||||||||||||||||||||||
|| || |||||||||||||||||||||||||||||||||||||
|||||| |||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Metals -------------------------------------
ZG -17070 43540
ZI 68395 146885
ZK 101888 29475
ZP 82885 27600
ZA 174955 83910
------------------------------------------------
Totals: 411052 166703
------------------------------------------------
Metals Last 4 Years ---------------------
|
| | |
|| || |
|| |||| |||
| ||| | |||||||||
|| |||||||||||||||||
|| |||||||||||||||||||
|||||||||||||||||||||||
|||||||||||||||||||||||
|||||||||||||||||||||||
| | ||||||||||||||||||||||||
||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||
|| |||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||
|| |||||||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Grains -------------------------------------
ZS 79175 20312
ZW -43438 51975
ZC 5238 26688
ZL 13248 24588
ZM 29860 28810
------------------------------------------------
Totals: 84083 88850
------------------------------------------------
Grains Last 4 Years ---------------------
|
|
||
||
|||||||||
|||||||||||
|||||||||||
|||||||||||
||||||||||||
| ||||||||||||
| | ||||||||||||
| || ||| ||||||||||||
||||| ||||| |||||||||||||
|||||||||||| |||||||||||||
|||||||||||| ||| | |||||||||||||
||||||||||||| ||||||| || ||||||||||||||
|||||||||||||||||||||||||||| ||||||||||||||
|||||||||||||||||||||||||||||| |||||||||||||||
||||||||||||||||||||||||||||||| |||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Financials -------------------------------------
US 35991 24959
TY -350 29175
TU 1473 23969
EC 4700 9650
------------------------------------------------
Totals: 41813 56453
------------------------------------------------
Financials Last 4 Years ---------------------
| | ||||
||| | |||||
||| | || ||||||
||||| ||||||||||
|||||| ||||||||||
|||||||| ||||||||||
|||||||| ||||||||||
||||||||| |||||||||||
||||||||||||||||||||||
| ||||||||||||||||||||||
| ||||||||||||||||||||||
| | ||||||||||||||||||||||
| | || ||||||||||||||||||||||
|| |||||| |||||||||||||||||||||||
||| |||||||||||||||||||||||||||||||
|||| || | |||||||||||||||||||||||||||||||
||||| |||| |||||||||||||||||||||||||||||||
||||||| ||||||||||||||||||||||||||||||||||||
|||||||| ||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Softs -------------------------------------
SB 25927 15035
KC -49775 94069
CC -72140 76660
CT 16785 45470
Lumber 218513 51745
JO 2588 15760
------------------------------------------------
Totals: 141898 128540
------------------------------------------------
Softs Last 4 Years ---------------------
| ||
||||
|||||
|||||
||||||
| ||||||
||||||||
||||||||
||||||||
||||||||
------------------------------------------------ 0
| | |||||||||
| | ||||||||||
||||||||||||||||
||||||||||||||||
|||||||||||||||||
|||||||||||||||||
|| | ||||||||||||||||||
| ||||||||||| | |||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------
################################################
Meats -------------------------------------
ZT -29940 57680
ZZ 38480 15080
ZF 18413 57550
------------------------------------------------
Totals: 26952 66515
------------------------------------------------
Meats Last 4 Years ---------------------
| ||
| || ||
|| | || ||
||| | || ||
||||||||| ||||
| |||||||||| ||||
| | ||||||||||| |||||
| | ||||||||||| |||||| |
| || |||||||||||||||||| |
| ||| | |||||||||||||||||||||
|| ||| | |||||||||||||||||||||
|||||| || | ||||||||||||||||||||| |
|||||| || |||||||||||||||||||||||| |
|||||| || ||||||||||||||||||||||||||
|||||||| | || ||||||||||||||||||||||||||
|||||||| | ||| ||||||||||||||||||||||||||
|||||||||| | |||||||||||||||||||||||||||||||
||||||||||| | |||||||||||||||||||||||||||||||
|||||||||||| || ||||||||||||||||||||||||||||||||
||||||||||||||||||||||||||||||||||||||||||||||||
2018--------2019--------2020--------2021--------

How Do You Program this in Python

Here is the module for TS-18.  There is a little extra code to keep track of sectors in case you want to limit sector exposure.  However, this code takes every trade on a one contract basis.  This code reflects my latest version of TS-18, which will be released shortly.

#  Define Long, Short, ExitLong and ExitShort Levels - mind your indentations
buyLevel = highest(myHigh,40,curBar,1)
shortLevel = lowest(myLow,40,curBar,1)
longExit = lowest(myLow,20,curBar,1)
shortExit = highest(myHigh,20,curBar,1)
ATR = sAverage(myTrueRange,30,curBar,1)
stopAmt = 2000/myBPV

ATR = sAverage(myTrueRange,30,curBar,1)

posSize = 1
mmLxit = 99999999
mmSxit = -99999999
if mp == 1 : mmLxit = entryPrice[-1] - stopAmt
if mp ==-1 : mmSxit = entryPrice[-1] + stopAmt



# Long Exit
if mp == 1 and myLow[curBar] <= mmLxit and mmLxit > longExit and barsSinceEntry > 1:
price = min(myOpen[curBar],mmLxit)
tradeName = "LxitMM"
numShares = curShares
exitPosition(price, curShares, tradeName, sysMarkDict)
unPackDict(sysMarkDict)
# Long Exit
if mp == 1 and myLow[curBar] <= longExit and barsSinceEntry > 1:
price = min(myOpen[curBar],longExit)
tradeName = "Lxit"
numShares = curShares
exitPosition(price, curShares, tradeName, sysMarkDict)
unPackDict(sysMarkDict)
# Short Exit
if mp == -1 and myHigh[curBar] >= shortExit and barsSinceEntry > 1:
price = max(myOpen[curBar],shortExit)
tradeName = "Sxit"
numShares = curShares
exitPosition(price, curShares, tradeName, sysMarkDict)
unPackDict(sysMarkDict)
# Short Exit
if mp == -1 and myHigh[curBar] >= entryPrice[-1] + stopAmt and barsSinceEntry > 1:
price = max(myOpen[curBar],entryPrice[-1] + stopAmt)
tradeName = "SxitMM"
numShares = curShares
exitPosition(price, curShares, tradeName,sysMarkDict)
unPackDict(sysMarkDict)
# Long Entry
if myHigh[curBar] >= buyLevel and mp !=1:
price = max(myOpen[curBar],buyLevel)
tradeName = "Simple Buy"
numShares = posSize
enterLongPosition(price,numShares,tradeName,sysMarkDict)
unPackDict(sysMarkDict)
# Short Entry
if myLow[curBar] <= shortLevel and mp !=-1 :
price = min(myOpen[curBar],shortLevel)
if mp == 0 : sectorTradesTodayList[curSector] +=1
tradeName = "Simple Sell"
numShares = posSize
enterShortPosition(price, numShares, tradeName, sysMarkDict)
unPackDict(sysMarkDict)
Python within Trading Simula-18

Easing Into EasyLanguage: Hi-Res Edition Now Available

Hi-Res Is Now Available

Easing Into EasyLanguage : The Hi-Res Edition

The Hi-Res Edition of Easing Into EasyLanguage

This is my second book in the Easing Into EasyLanguage [EZNGN2EZLANG] series of books.  Here are the table of contents.

Contents

  •  Introduction
  • About Website Computer Code and Fonts In Print Version
  • Using EasyLanguage to Program on Minute Intervals?
  • Tutorial 14 – Why Do I Need to Use Intraday Data
  • Tutorial 15 – An Algorithm Template that Uses Minute Bars to Trade a Daily Bar Scheme
  • Tutorial 16 – Using Data2 as a Daily Bar
  • Tutorial 17 – Let’s Day Trade!
  • Tutorial 18 – Moving From Discrete Day-Trade Strategy to a Framework
  • Tutorial 19 – Day-Trading Continued: Volatility Based Open Range Break Out with Pattern Recognition
  • Tutorial 20 – Pyramiding with Camarilla
  • Tutorial 21 – Programming a Scale Out Scheme
  • Tutorial 22- Crawling Like A Bug on a Five Minute Chart
  • Tutorial 23 – Templates For Further Research
  • Appendix A-Source Code
  • Appendix B-Links to Video Instruction

I have included five hours of video instruction which is included via links in the book and in the supplemental resource download.

What’s In This Book

If you are not a Trend Follower, then in most cases, you will not be able to properly or accurately code and backtest your trading algorithm without the use of higher resolution  data  (minute bars).  A very large portion of the consulting I have done over the years has  dealt with converting a daily bar system to one that uses intraday data such as a 5-minute bar.  Coding a daily bar system is much more simple than taking the same concept and adding it to a higher resolution (Hi-Res) chart.  If you use a 100 day moving average and you apply it to a 5-minute chart you get a 100 five minute bar moving average – a big difference.

Why Do I Need To Use Hi-Res Data?

If all you need to do is calculate a single entry or exit on a daily basis and can manually execute the trades, then you can stick with daily bars.  Many of the famous Trend-Following systems such as Turtle, Aberration,  Aberration Plus,  Andromeda,  and many others fall into this category.  Most CTAs use these types of systems and spend most of their efforts on accurate execution and portfolio management.   These systems, until the genesis of the COVID pandemic, have struggled for many years.  Some of the biggest and brightest futures fund managers had to shut their doors due to their lagging performance and elevated levels of risk in comparison to the stock market.  However, if you need to know the ebb and flow of the intraday market movement to determine accurate trade entry, then intraday data is an absolute necessity.   Also, if you want to automate, Hi-Res data will help too!   Here is an example of a strategy that would need to know what occurs first in chronological order.

Example of a Simple  Algorithm that Needs Intraday Data

If the market closes above the prior day’s close, then  buy the open of the next day plus 20% of today’s range and sellShort the open of the next day minus 40% of today’s range.  Use a protective stop of $500 and a profit objective of $750.  If the market closes below the prior day’s close then sellShort the open of the next day minus 20% of today’s range and buy the open of the next day plus 40% of todays range.  The same trade management of profit and loss is applied as well.  From the low resolution of a daily bar the computer cannot determine if the market moves up 20% or down 40% first.  So the computer cannot accurately determine if a long or short is established first.  And to add insult to injury, if the computer could determine the initial position accurately from a daily bar, it still couldn’t determine if the position is liquidated via a profit or a loss if both conditions could have occurred.

What About “Look Inside Bar”?

There is evidence that if the bar closes near the high and the open near the low of a daily bar, then there is a higher probability that the low was made first.  And the opposite is true as well.  If the market opens near the middle of the bar, then all bets are off.  When real money is in play you can’t count on this type of probability or the lack thereof .  TradeStation allows you to use your daily bar scheme and then Look Inside Bar to see the overall ebb and flow of the intraday movement.  This function allows you to drill down to one minute bars, if you like.  This helps a lot, but it still doesn’t allow you to make intraday decisions, because you are making trading decisions from the close of the prior day.

if c > c[1] then 
begin
buy next day at open of next day + 0.2 * range stop;
sellShort next day at open of next day - 0.4 * range stop;
end;

setProfitTarget(750);
setStopLoss(500);
Next Day Order Placement

Using setProfitTarget and setStopLoss helps increase testing accuracy, but shouldn’t you really test on a 5-minute bar just to be on the safe side.

DayTrading in Most Cases Needs Hi-Res Data

If I say buy tomorrow at open of next day and use a setStopLoss(500), then I don’t need Hi-Res data.  I execute the open which is the first time stamp in the chronological order of the day.  Getting stopped out will happen later and any adverse move from the open that  equates to $500 will liquidate the position or the position will be liquidated at the end of the day.

However, if I say buy the high of the first 30 minutes and use the low of the first 30 minutes as my stop loss and take profits if the position is profitable an hour later or at $750, then intraday data is absolute necessity.  Most day trading systems need to react to what the market offers up and only slightly relies on longer term daily bar indicators.

If Intraday Data is So Important then Why ” The Foundation Edition?”

You must learn to crawl before you can walk.  And many traders don’t care about the intraday action – all they care about is where the market closed and how much money should be allocated to a given trade or position.  Or how an open position needs to be managed.  The concepts and constructs of EasyLanguage must be learned first from a daily bar framework before a new EL programmer can understand how to use that knowledge on a five minute bar.  You cannot just jump into a five minute bar framework and start programming accurately unless you are a programmer from the start or you have a sound Foundation in EasyLanguage.

Excerpt from Hi-Res Edition

From Tutorial 21 – Put 2 Units on, Take Profit on 1 Unit, Pull Stop to Break Even on 2nd Unit

Here is an example of a simple and very popular day trading scheme.  Buy 2 units on a break out and take profits on 1 unit at X dollars.  Pull stop on 2nd unit to breakeven to provide a free trade.  Take profit on 2nd unit or get out at the end of the day.

Conceptually this is easy to see on the chart and to understand.  But programming this is not so easy.  The code and video for this algorithm is  from Tutorial 21 in the Hi-Res edition.

Here are the results of the algorithm on a 5 minute ES.D chart going back five years.  Remember these results are the result of data mining.  Make sure you understand the limitations of back-testing.  You can read those here.

No Execution Costs Included! Please read backtesting disclaimer.

There are a total of 10 Tutorials and over 5 hours of Video Instruction included.  If you want to expand your programming capabilities to include intraday algorithm development, including day trading, then get your copy today.

 

Updated Code That Works With Midnight Time Stamp

Updated Code for the Midnight Hour

UPDATE: October 12, 2023.  I found an error in the code.  I will comment it out and show you the correction.   Copy and paste can get you into trouble.

I was working with some code for my latest book – Easing Into EasyLanguage – The Hi-Res Edition and streamlined some code from an old post.

startTime = sessionStartTime(0,1); 
//endTime = sessionStartTime(0,1); WRONG!
endTime = sessionEndTime(0,1);

if startTime > endTime then
begin
endTimeOffset = 0;
if t >= startTime+barInterval and t<= 2359 then endTimeOffSet = 2400-endTime;
end;

if t-endTimeOffSet < endTime then
begin
...
...
...
...
end.
Updated Code That Works with 0000 Time Stamp
24 Hour Session

Now you can carve out times to trade that bridge the midnight hour.  You just need to use the above code for when the your StartTime is greater than your EndTime.

So if you want to trade from 20:00 to 05:00 (8 PM to 5 AM) then just use this code and it will work every time.

I wanted to make sure I did a post for November to keep my record alive and to let you know I am wrapping up the Hi-Res edition and will be on the bookshelves before Christmas – I hope.

 

 

EasyLanguage Code for Day of Week Analysis with Day Trading Algo

D of W Analysis

How important is a day of week analysis?  Many pundits would of course state that it is very important, especially when dealing with a day trading algorithm.   Others would disagree.  With the increase in market efficiency maybe this study is not as important as it once was, but it is another peformance metric that can be used with others.

I am currently working on the second book in the Easing into EasyLanguage trilogy (Hi-Res Edition) and I am including this in one of the tutorials on developing a day trading template.  The book, like this post, will focus on intraday data such as 5 or less minute bars.  I hope to have the book finalized in late November.  If you haven’t purchased the Foundation Edition and like this presentation, I would suggest picking a copy up – especially if you are new to EasyLanguage.  The code for this analysis is quite simple, but it is pretty cool and can be re-used.

Day Trading Algorithms Make Things Much More Simple

When you enter and exit on the same day and you don’t need to wrap around a 00:00 (midnight) time stamp, things such as this simple snippet of code are very easy to create.  The EasyLanguage built-in functions work as you would expect as well.  And obtaining the first bar of the day is ultra simple.  The idea here is to have five variables, one for each day of the week, and accumulate the profit that is made on each day, and at the end of the run print out the results.  Three things must be known on the first bar of the new trading day to accomplish this task:

  1. were trades taken yesterday?
  2. how much profit was made or lost?
  3. what was yesterday – M, T, W, R, or F?

Two Reserved Words and One Function  Are Used:  Total Trades, NetProfit and the DayOfWeek function.

The reserved word TotalTrades keeps track of when a trade is closed out.  The second reserved word, NetProfit keeps track of total profit everytime a trade is closed out.  Along with the DayOfWeek(D[1]) function you can capture all the information you need for this analysis.  Here is the code.  I will show it first and then explain it afterwards.

	if date <> date[1] then
begin
myBarCount = 0;
buysToday = 0;sellsToday = 0;
zatr = avgTrueRange(atrLen) of data2;
if totalTrades > totTrades then
begin
Print(d," ",t," trade out ",dayOfWeek(d[1])," ",netProfit);
switch(dayOfWeek(date[1]))
begin
Case 1: MProf = MProf + (netProfit - begDayEquity);
Case 2: TProf = TProf + (netProfit - begDayEquity);
Case 3: WProf = WProf + (netProfit - begDayEquity);
Case 4: RProf = RProf + (netProfit - begDayEquity);
Case 5: FProf = FProf + (netProfit - begDayEquity);
Default: Value1 = Value1 + 1;
end;
begDayEquity = netProfit;
totTrades = totalTrades;
end;
end;
Snippet To Handle DofW Analysis on DayTrading Algorithm

 Code Explanation – Switch and Case

I have used the Switch –  Case construct in some of my prior posts and I can’t emphasize enough how awesome it is, and how you can cut down on the use of if – thens.  This snippet only takes place on the first bar of the trading day.  Since we are using day sessions we can simply compare today’s date to the prior bar’s date, and if they are different then you know you are sitting on the first  intraday bar of the day.    After some initial housekeeping, the first if – then checks to see if trade(s) were closed out yesterday.  If totalTrades is greater than my user defined totTrades, then something happened yesterday.  My totTrades is updated to totalTrades after I am done with my calculations.  The switch keys off of the DayOfWeek function.  Remember you should account for every possible outcome of the variable inside the switch expression.  In the case of the DayOfWeek function when know:

  1. Monday
  2. Tuesday
  3. Wednesday
  4. Thursday
  5. Friday

Notice I am passing Date[1] into the function, because I want to know the day of the week of yesterday.  After the Switch and its associated expression you have a Begin statement.  Each outcome of the expression is preceded withthe keyword Case followed by a colon (:).  Any code associated with each distinct result of the expression is sandwiched between Case keywords.  So if the day of week of yesterday is 1 or Monday then MProf accumulates the change in the current NetProfit and the begDayEquity (beginning of the yesterday’s NetProfit) variable.  So, if the equity at the beginning of yesterday was $10,000 and there was a closed out trade and the current NetProfit is $10,500 then $500 was made by the end of the day yesterday.  This exact calculation is used for each day of the week and stored in the appropriate day of the week variable:

  • MProf – Monday
  • TProf – Tuesday
  • WProf – Wednesday
  • RProf – Thursday
  • FProf – Friday

You might ask why RProf for Thursday?  Well, we have already used TProf for Tuesday and Thursday contains an “R”.  This is just my way of doing it, but you will find this often in code dealing with days of the week.  Every Switch should account for every possible outcome of the expression its keying off of.  Many times you can’t always know ahead of time all the possible outcomes, so a Default case should be used as an exception.  It is not necessary and it will not kick an error message if its not there.  However, its just good programming to account for everything.    Once the Switch is concluded begDayEquity and totTrades are updated for use the following day.

Here is the code that prints out the results of the DayOfWeek Analysis

if d = 1211027 and t = 1100 then
begin
print(d," DOW Analysis ");
print("Monday : ",MProf);
print("Tuesday : ",TProf);
print("Wednesday : ",WProf);
print("Thursday : ",RProf);
print("Friday : ",FProf);

end;
Printing The Results of DofW Analysis

The  printout occurs on October 27, 2021 at 11 AM.  Here is my analysis of a day trading algorithm I am working  on, tested over the last two years on 5 minute bars of the @ES.D

Monday    : 9225.00
Tuesday : 7375.00
Wednesday : 5175.00
Thursday : -1150.00
Friday : 9862.50
Resuts of around $30,000

Does This Agree with Strategy Performance Report?

This System Will Be Published in the Hi-Res Edition of Easing into EasyLanguage Trilogy

Looks like it does.  These results were derived from one of the Tutorials in The Hi-Res edition of EZ-NG-N2-EZ-LANG trilogy.  I should have it availabe at Amazon some time in late November.    Of course if you have any questions just email me @ george.p.pruitt@gmail.com.

 

Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!