Category Archives: Free EasyLanguage

Trading the Equity Curve – Part 1 of N?

Only Trade the Best Segments of the Equity Curve – Cut Out Drawdown and Take Advantage of Run Ups! Really?

Equity curve feedback has been around for many years and seems highly logical, but one can’t get an industry-wide agreement on its benefit.  The main problem is to know when to turn trading off and then back on as you track the equity curve.  The most popular approach is to use a moving average of the equity curve to signal system participation.   When the equity curve moves below 30, 60, or 90 period-moving average of equity, then just turn it off and wait until the curve crosses back above the average.  This approach will be investigated in Part 2 of this series.  Another approach is to stop trading once the curve enters a drawdown that exceeds a certain level and then start back up once the equity curve recovers.  In this post, this method will be investigated.

Programmers Perspective

How do you go about programming this tool to start with.  There are probably multiple ways of accomplishing this task, but the two I have most often observed were the two pass process and the inline simultaneous tracking of the synthetic and actual equity curves.  The two pass process generates an unadulterated equity curve and stores the equity and trades either in memory or in a file.  The second part of the process monitors the external equity curve along with the external trades synchronously and while trading is turned on, the trades are executed as they occur chronologically.  When trading is turned off, the synthetic equity curve and trades are processed along the way.   The second method is to create, which I have coined (maybe others too!), a synthetic equity curve and synthetic trades.  I have done this in my TradingSimula_18 software by creating a SynthTrade Class.  This class contains all the properties of every trade and in turn can use this information to create a synthetic equity curve.  The synthetic equity curve and trades are untouched by the real time trading.

Start Simple

The creation of an equity curve monitor and processor is best started using a very simple system.  One market algorithm that enters and exits on different dates, where pyramiding and scaling in or out are not allowed.  The first algorithm that I tested was a mean reversion system where you buy after two consecutive down closes followed by an up close and then waiting one day.  Since I tested the ES over the past 10 years you can assume the trend is up. I must admit that the day delay was a mistake on my behalf.  I was experimenting with a four bar pattern and somehow forgot to look at the prior day’s action.  Since this is an experiment it is OK!

if marketPosition <> 1 and 
(c[2] < c[3] and c[3] < c[4] and c[1]  > =  c[2]) then
buy next bar at open;

//The exit is just as simple -
//get out after four days (includeing entry bar) on the next bars open - no stops or profit objectives.  

If barsSinceEntry > 2 then sell next bar at open;
Simple Strategy to test Synthetic Trading Engine

Here is the unadulterated equity curve using $0 for execution costs.

Non adjusted equity curve of our simple mean reversion system. Wait for a pull back and then a rally before entering.

The Retrace and Recover Method

In this initial experiment, trading is suspended once you reach a draw down of 10% from the peak of the equity curve and then resumes trading once a rally of 15% of the subsequent valley.  Here is an intriguing graphic.

Green means ON. Red means OFF. The lower curve is the resultant curve.

I did this analysis by hand with Excel and it is best case scenario.  Meaning that when trading is turned back on any current synthetic position is immediately executed in the real world.  This experiment resulted in nearly the same drawdown but a large drop in overall equity curve growth – $75K.

Put the Synthetic Equity Curve Engine to the Test

Now that I had the confirmed results of the experiment, I used them as the benchmark against my TS-18 Synthetic Trade Engine.  But before I installed the Equity Curve algorithm, I needed to make sure my synthetic trades lined up exactly with the real equity curve.  The synthetic curve should align 100% with the real equity curve.  If it doesn’t, then there is a problem.  This is another reason to start with a simple trading strategy.

Take a look here where I print out the Synthetic Equity curve on  a daily basis and compare it with the end result of the analysis.

Synth. matches Reality

Now let’s see if it worked.

Testing with Synth. Equity Curve Trading Turned ON!

The equity curves are very similar.  However, there is a difference and this is caused by how one re-enters after trading is turned back on.  In this version I tested waiting for a new trade signal which might take a few days.  You could re-enter in three different ways:

  1. Automatically enter synthetic position on the next bar’s open
  2. Wait for a new trade signal
  3. Enter immediately if you can get in at a better price

Using the 10% Ret. and 15% Rec. algorithm didn’t help at all.  What if we test 10% and 10%.

10% Ret. and 10% Rec.

Now that performed better – more profit and less draw down.  Now that I have the synthetic engine working on simple algorithms we can do all sorts of equity curve analysis.  In the next installment in this series I will make sure the TS-18 Synthetic Engine can handle more complicated entry and exit algorithms.  I have already tested a simple longer term trend following strategy on a medium sized portfolio and the synthetic engine worked fine.  The retracement/recovery algorithm at 10%/15% did not work and I will go into the “whys” in my next post.

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

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.

 

Passing and Accessing Multidimensional Array in a Function

Before the days of OOEL and more advanced data structures, such as vectors, you had to work with multidimensional arrays.

The problem with arrays is you have to do all the housekeeping whereas with vectors the housekeeping is handled internally.  Yes, vectors in many cases would be the most efficient approach, but if you are already using Multi-D arrays, then mixing the two could become confusing.  So stick with the arrays for now and progress into vectors at your leisure.

Recreate the CCI indicator with Multi-D Array

This exercise is for demonstration purposes only as the existing CCI function works just fine.  However, when you are trying out something new  or in this case an application of a different data structure (array) its always great to check your results against a known entity.  If your program replicates the known entity, then you know that you are close to a solution.  The CCI function accesses data via the global High, Low and Close data streams and then applies a mathematical formula to derive a result. <

Derive Your Function First

Create the function first by prototyping what the function will need in the formal parameter list (funciton header).   The first thing the function will need is the data – here is what it will look like.

  • OHLCArray[1,1] =  1210903.00 // DATE
  • OHLCArray[1,2] =    4420.25 // OPEN
  • OHLCArray[1,3] =    4490.25 // HIGH
  • OHLCArray[1,4] =    4410.25 // LOW
  • OHLCArray[1,5] =    4480.75 // CLOSE
  • OHLCArray[2,1] =  1210904.00 // DATE
  • OHLCArray[2,2] =    4470.25 // OPEN
  • OHLCArray[2,3] =    4490.25 // HIGH
  • OHLCArray[2,4] =    4420.25 // LOW
  • OHLCArray[2,5] =    4440.75 // CLOSE

Visualize 2-D Array as a Table

Column 1 Column 2 Column 3 Column 4 Column 5
1210903 44202.25 4490.25 4410.25 4480.75
1210904 4470.25 4490.25 4420.25 4440.76
The CCI function is only concerned with H, L, C and that data is in columns 3, 4, 5.  If you know the structure of the array before you program the function, then you now which columns or fields you will need to access.  If you don’t know the structure beforehand , then that information would need to be passed into the function as well.   Let us assume we know the structure.  Part of the housekeeping that I mentioned earlier was keeping track of the current row where the latest data is being stored.  This “index” plus the length of the CCI indicator is the last two things we will need to know to do a proper calculation.

CCI_2D Function Formal Parameter List

// This function needs data, current data row, and length
// Notice how I declare the OHLCArray using the dummy X and Y
// Variable - this just tells TradeStation to expect 2-D array
// ------------------
// | |
// * *
inputs: OHLCArray[x,y](numericArray), currentRow(numericSimple), length(numericSimple);
// ***
// |||
//----------------------------
// Also notice I tell TradeStation that the array is of type numeric
// We are not changing the array but if we were, then the type would be
// numericArrayRef - the actual location in memory not just a copy
CCI_2D Formal Parameter List

2-D Array Must Run Parallels with Actual Data

The rest of the function expects the data to be just like the H, L, C built-in data – so there cannot be gaps.  This is very important when you pack the data and  you will see this in the function driver code a.k.a an indicator. The data needs to align with the bars.  Now if you are using large arrays this can slow things down a bit.  You can also shuffle the array and keep the array size to a minimum and I will post how to do this in a post later this week.  The CCI doesn’t care about the order of the H,L,C as long as the last N element is the latest values.

variables: 	
Mean( 0 ),sum1(0),sum2(0),
AvgDev( 0 ),rowNum(0),
Counter( 0 ) ;


AvgDev = 0 ;
if currentRow > length then // make sure enough rows
begin

sum1 = 0;
sum2 = 0;
for rowNum = currentRow - (length-1) to currentRow
begin
value1 = OHLCArray[rowNum,3];
value2 = OHLCArray[rowNum,4];
value3 = OHLCArray[rowNum,5];
sum1 = sum1 + value1 + value2 + value3;
end;
//Mean = Average( H + L + C, Length ) ; { don't have to divide H+L+C by 3, cancels out }
Mean = sum1/length;
print(d," Mean ",mean," ",mean/3);

for rowNum = currentRow - (length-1) to currentRow
begin
value1 = OHLCArray[rowNum,3];
value2 = OHLCArray[rowNum,4];
value3 = OHLCArray[rowNum,5];
sum2 = sum2 + AbsValue((value1 + value2 + value3) - Mean);
end ;
// AvgDev = AvgDev + AbsValue( ( H + L + C )[Counter] - Mean ) ;
AvgDev = sum2 / Length ;
print(d," avgDev ",AvgDev," ",AvgDev/3);

value1 = OHLCArray[currentRow,3];
value2 = OHLCArray[currentRow,4];
value3 = OHLCArray[currentRow,5];
end;

if AvgDev = 0 then
CCI_2D = 0
else
CCI_2D = ( value1 + value2 + value3 - Mean ) / ( .015 * AvgDev ) ;
CCI-2D Function
This function could be streamlined, but I wanted to show you how to access the different data values with the currentRow variable and columns 3, 4, and 5.  I extract these data and store them in Values variables.  Notice the highlighted line where I check to make sure there are enough rows to handle the calculation.  If you try to access data before row #1, then you will get an out of bounds error and a halt to program execution.

Function Driver in the form of an Indicator

array: OHLCArray[5000,5](0);
Inputs: CCI2DLen(14),CCILen(14);

vars: numRows(0),myCCI(0),regCCI(0);

numRows = numRows + 1;
OHLCArray[numRows,1] = d;
OHLCArray[numRows,2] = o;
OHLCArray[numRows,3] = h;
OHLCArray[numRows,4] = l;
OHLCArray[numRows,5] = c;

myCCI = CCI_2D(OHLCArray,numRows,14);
regCCI = CCI(14);

plot1(myCCI," CCI_2D ");
plot2(regCCI," CCI ");
CCI-2D Indicator

Notice lines 16 and 17 where I am plotting both function results – my CCI_2D and CCI.   Also notice how I increment numRows on each bar – this is the housekeeping that keeps that array synched with the chart.  In the following graphic I use 14 for CCI_2D and 9 for the built-in CCI.

Two CCI functions with different Lengths

Now the following graphic uses the same length parameters for both functions.  Why did just one line show up?

Both CCI Functions with same Lengths – were did second line go to?

Make Your Unique Coding Replicate a Known Entity – If You Can

 

Here is where your programming is graded.  The replication of the CCI using a 2-D Array instead of the built-in H, L, C data streams, if programmed correctly, should create the exact same results and it does, hence the one line.  Big Deal right!  Why did I go through all this to do something that was already done?  Great programming is not supposed to re-invent the wheel.  And we just did exactly that.  But read between the lines here.   We validated code that packed a 2-D array with data and then passed it to a function that then accessed the data correctly and applied a known formula and compared it to a known entity.  So now you have re-usable code for passing a 2-D array to a function.  All you have to do is use the template and modify the calculations.  Re-inventing the wheel is A-Okay if you are using it as a tool for validation.

The Foundation Edition – First Book In Easing Into EasyLanguage

Hello to All!  I just published the first book in this series.  It is the Foundation Edition and is designed for the new user of EasyLanguage or for those you would like to have a refresher course.  There are 13 total tutorials ranging from creating Strategies to PaintBars.  Learn how to create your own functions or apply stops and profit objectives.  Ever wanted to know how to find an inside day that is also a Narrow Range 7 (NR7?)  Now you can, and the best part is you get over 4 HOURS OF VIDEO INSTRUCTION – one for each tutorial.  Each video is created by yours truly and Beau my trustworthy canine companion.  I go over every line of code to really bring home the concepts that are laid out in each tutorial.  All source code is available too, and if you have TradeStation, so are the workspaces.  Plus you can always email George for any questions.  george.p.pruitt@gmail.com.

The Cover of my latest book. The first in the series.

If you like the information on my blog, but find the programming code a little daunting, then go back and build a solid foundation with the Foundation Edition.  It starts easy but moves up the Learning Curve at comfortable pace.  On sale now for $24.95 at Amazon.com.  I am planning on having two more advanced books in the series.  The second book, specifically designed for intraday trading and day-trading, will be available this winter.  And the third book, Advanced Topics, will be available next spring.

Pick up your copy today – e-Book or Paperback format!

Here is the link to buy the book now!

Let me know if you buy either format  and I will send you a PDF of the source code – just need proof of purchase.  With the  PDF you can copy and paste the code.  After you buy the book come back here to the Easing Into EasyLanguage Page and download  the ELD and workspaces.

If You Can’t Go Forward, Then Go Backward [Back To The Future]

Calculate MAE/MFE 30 Bars after A Signal

A very astute reader of this blog brought a snippet of code that looks like EasyLanguage and sort of behaves like it, but not exactly.  This code was presented on the exceptional blog of Quant Trader posted by Kahler Philipp.  He used some of the ideas from  Dave Bergstrom.

Equilla Programming Language

The theory behind the code is quite interesting and I haven’t gotten into it thoroughly, but will do so in the next few days.  The code was derived from Trade-Signal’s Equilla Programming Language.  I looked at the website and it seems to leans heavily on an EasyLanguage like syntax, but unlike EZLang allows you to incorporate indicators right in the Strategy.  It also allows you, and I might be wrong, to move forward in time from a point in the past quite easily.  The code basically was fed a signal (+1,0,-1) and based on this value progressively moved forward one bar at a time  (over a certain time period) and calculated the MAE and MFE (max. adverse/favorable excursion for each bar.  The cumulative MAE/MFE were then stored in a BIN for each bar.  At the end of the data, a chart of the ratio between the MAE and MFE was plotted.

EasyLanguage Version

I tried to replicate the code to the best of my ability by going back in time and recording a trading signal and then moving Back to The Future thirty bars, in this case, to calculated and store the MAE/MFE in the BINS.

Simple Moving Average Cross Over Test

After 100 bars, I looked back 30 bars to determine if the price was either greater than or less than the 21 day moving average.   Let’s assume the close was greater than the 21 day moving average 30 days ago, I then kept going backward until this was not the case.  In other words I found the bar that crossed the moving average.  It could have been 5 or 18 or whatever bars further back.  I stored that close and then started moving forward calculating the MAE/MFE by keeping track of the Highest Close and Lowest Close made during 30 bar holding period.  You will see the calculation in the code.  Every time I got a signal I accumulated the results of the calculations for each bar in the walk forward period.  At the end of the chart or test I divided each bars MFE by its MAE and plotted the results.  A table was also created in the Print Log.  This code is barely beta, so let me know if you see any apparent errors in logic or calculations.


inputs: ilb(30); //ilb - initial lookback
vars: lb(0),signal(0),btf(0),mf(0),ma(0),hh(0),ll(99999999),arrCnt(0),numSigs(0);
arrays : mfe[40](0),mae[40](0);
lb = ilb;
if barNumber > 100 then
begin
signal = iff(c[ilb] > average(c[ilb],21),1,-1);
// print(d," signal ",signal," ",ilb);
if signal <> signal[1] then
begin
numSigs = numSigs + 1; // keep track of number of signals
// print("Inside loop ", date[ilb]," ",c[ilb]," ",average(c[ilb],21));
if signal = 1 then // loop further back to get cross over
begin
// print("Inside signal = 1 ",date[lb]," ",c[lb]," ",average(c[lb],21));
while c[lb] > average(c[lb],21)
begin
lb = lb + 1;
end;
// print("lb = ",lb);
end;

if signal = -1 then // loop further back to get cross over
begin
// print("Inside signal = -1 ",date[lb]," ",c[lb]," ",average(c[lb],21));
while c[lb] < average(c[lb],21)
begin
lb = lb + 1;
end;
end;
lb = lb - 1;

hh = 0;
ll = 999999999;

arrCnt = 0;
for btf = lb downto (lb - ilb) //btf BACK TO FUTURE INDEX
begin
mf=0;
ma=0;
hh=maxList(c[btf],hh);
// print("inside inner loop ",btf," hh ",hh," **arrCnt ",arrCnt);
ll=minList(c[btf],ll);
if signal>0 then
begin
mf=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // mf long signal
ma=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // ma long signal
end;
if signal<0 then begin
ma=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // ma after short signal
mf=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // mf after short signal
end;
// print(btf," signal ",signal," mf ",mf:0:5," ma ",ma:0:5," hh ",hh," ll ",ll," close[lb] ",c[lb]);
mfe[arrCnt]=mfe[arrCnt]+absValue(signal)*mf;
mae[arrCnt]=mae[arrCnt]+absValue(signal)*ma;
arrCnt = arrCnt + 1;
end;
end;
end;

if lastBarOnChart then
begin
print(" ** MFE / MAE ** ");
for arrCnt = 1 to 30
begin
print("Bar # ",arrCnt:1:0," mfe / mae ",(mfe[arrCnt]/mae[arrCnt]):0:5);
end;

for arrCnt = 30 downto 1
begin
plot1[arrCnt](mfe[31-arrCnt]/mae[31-arrCnt]," mfe/mae ");
end;
end;
Back to The Future - going backward then forward

Here is an output at the end of a test on Crude Oil

 ** MFE / MAE ** 
Bar # 1 mfe / mae 0.79828
Bar # 2 mfe / mae 0.81267
Bar # 3 mfe / mae 0.82771
Bar # 4 mfe / mae 0.86606
Bar # 5 mfe / mae 0.87927
Bar # 6 mfe / mae 0.90274
Bar # 7 mfe / mae 0.93169
Bar # 8 mfe / mae 0.97254
Bar # 9 mfe / mae 1.01002
Bar # 10 mfe / mae 1.03290
Bar # 11 mfe / mae 1.01329
Bar # 12 mfe / mae 1.01195
Bar # 13 mfe / mae 0.99963
Bar # 14 mfe / mae 1.01301
Bar # 15 mfe / mae 1.00513
Bar # 16 mfe / mae 1.00576
Bar # 17 mfe / mae 1.00814
Bar # 18 mfe / mae 1.00958
Bar # 19 mfe / mae 1.02738
Bar # 20 mfe / mae 1.01948
Bar # 21 mfe / mae 1.01208
Bar # 22 mfe / mae 1.02229
Bar # 23 mfe / mae 1.02481
Bar # 24 mfe / mae 1.00820
Bar # 25 mfe / mae 1.00119
Bar # 26 mfe / mae 0.99822
Bar # 27 mfe / mae 1.01343
Bar # 28 mfe / mae 1.00919
Bar # 29 mfe / mae 0.99960
Bar # 30 mfe / mae 0.99915
Ratio Values over 30 Bins

Using Arrays for Bins

When  newcomers  start to program EasyLanguage and encounter arrays it sometimes scares them away.  They are really easy and in many cases necessary to complete a project.  In this code I used two 40 element or bins arrays MFE and MAE.  I only use the first 30 of the bins to store my information.  You can change this to 30 if you like, and when you start using a fixed array it is best to define them with the exact number you need, so that TradeStation will tell you if you step out of bounds (assign value to a bin outside the length of the array).  To learn more about arrays just search my blog.  The cool thing about arrays is  you control what data goes in and what you do with that data afterwards.  Anyways play with the code, and I will be back with a more thorough explanation of the theory behind it.