# On the Subject of Data Mining with EasyLanguage

## When Mining for Data, Make Sure You Have Accurate Data

Take a look at these results with no execution costs.

These results were derived by applying a simple algorithm to the natural gas futures for the past 15 or so years.  I wanted to see if there was a day of the week that produced the best results with the following entry and exit techniques:

• Long entries only
• Open range break out using a fraction of the N-day average range.
• Buy in the direction of the moving average.
• Yesterdays close must be above the X-day moving average of closing prices.
•  Yesterday must have a wider range than a fractional multiple of the average range.
• A fixed \$stop and \$profit used to exit trades.
• Other exits
• Exit at low of prior day.
• Exit at the close of today – so a day trade.

Here is a list of the parameters that can be optimized:

• daysOfWeekToTrade(1) : 1 – Monday, 2 – Tuesday…
• mavLen(20): moving average calculation length.
• volLen(10):  moving average calculation length for range.
• volMult(0.25): average range multiplier to determine break out/
• volComp(.5):  yesterday’s range must be greater than this percentage.
• stopLoss(500): stop loss in \$
• profitTarget(1000): profit objective in \$
• daysInTrade(0): 0 get out at end of day.
• llLookBack(2): pattern derived stop value – use the lowest low of N-days or the stop loss in \$, whichever is closer.

Here is the code:

``inputs: daysOfWeekToTrade(1),mavLen(20),volLen(10),volMult(0.25),volComp(.5),stopLoss(500),profitTarget(1000),daysInTrade(0),llLookBack(2);if dayOfWeek(d) = daysOfWeekToTrade ThenBegin	if close > average(c,mavLen) and range > average(range,volLen)*volComp then 		buy("DMDailyBuy") next bar at open of tomorrow + average(range,volLen)*volMult stop;end;if daysInTrade = 0 then setExitOnClose;sell("LLxit") next bar at lowest(l,llLookBack) stop;if marketPosition = 1 thenbegin	if barsSinceEntry = daysInTrade then sell("DaysXit") next bar at open;end;setStopLoss(stopLoss);setProfitTarget(profitTarget);``

### Why Is This Algorithm Wrong?  It’s Not It’s the Data!

The algorithm, speaking in terms of logic, is accurate. The data is wrong.  You cannot test the exit technology of this algorithm with just four data points per day – open, high, low, and close.  If this simple algorithm cannot be tested, then what can you test on a daily bar basis accurately?

• Long or short entry, but not both.
• If the algorithm can enter both long and short, you need to know what occurred first.  Doesn’t matter if you enter via stop or limit orders.  Using a stop order for both, then you need to know if the high occurred first and got you long, and then later the low and got you short.  Or just the opposite.  You can test, with the benefit of hindsight, if only one of the orders would have been elected.  If only one is elected, then you can proceed.  If both then no-go.  You must be able to use future leak to determine if only one of the orders were fillable.  TS-18 allows future leak BTW.  I say that like it’s a good thing!
• L or S position from either a market or stop, and a profit objective.
• If a long position is entered above the open, via a stop, and then the market moves even higher, you can get out on a sell limit for a profit.
• Same goes for the short side, but you need to know the magnitude of the low price in relation to the open.
• L or S position from either a market or limit and a protective stop.
• If short position is entered above the open, via a limit order, and the market moves even higher, you can exit the short position at a loss via a buy stop order.
• Same goes for the long side, but you need to know the magnitude of the high in relation to the open.
• Long pyramid on multiple higher stop or lower limit orders, but not both.
• The market opens and then sells off. You can go long on a limit order below the open, then you go long another unit below the original limit price and so on…
• The market opens and rallies.  You can go long on a stop order above the open, then you can go long another unit above the original stop price and so on…
• Short pyramid on multiple lower stop or higher limit orders.
• Same as long entries but in opposite direction.

Can’t you look at the relationships of the open to low and open to high and close to high and close to low and determine which occurred first, the high or the low of the day.  You can, but there is no guarantee.  And you can’t determine the magnitude of intraday day swings.  Assume the market opens and immediately moves down and gets you short via a stop order.  And from looking at a daily chart, it looks like the market never turned around, so you would assume you had a profit going into the close.  But in fact, after the market opened and moved down, it rallied back to the open enough to trigger a protective stop you had working.

The entry technique of this strategy is perfectly fine.  It is only buying in the direction of a breakout.  The problems arise when you apply a profit objective and a stop loss and a pattern-based stop and a market on close order.    After buying did the market pull back to get you stopped out before moving up to get you out at profit objective?  Did the market move up and then down to the prior lowest low of N days and then back up to get you long?  Or just the opposite? In futures, the settlement price is calculated with a formula.  You are always exiting at the settlement price with an MOC or setExitOnClose directive (daily bar basis.)

### No Biggie – I Will Just Test with LIB (Look Inside Bar.  That should fix it, right?

It definitely will increase accuracy, because you can see the intraday movements that make up the daily bar.  So, your entries and exits should be executed more accurately.  But you are still getting out at the settlement price which does not exist.  Here are the results from using LIB with 5-minute bar resolution.

### We Know the Weakness, But What Can We Do?

Test on a 5-minute bar as Data1 and daily as Data2.  This concept is what my Hi-Res Edition of Easing Into EasyLanguage is all about.  Here the results of using a higher resolution data and exiting on the last tick of the trading day – a known quantity.

These results validate the LIB results, right?  Not 100%, but very close.  Perhaps this run makes more money because the settlement price on the particular days that the system entered a trade was perhaps lower than the last tick.  In other words, when exiting at the end of the day, the last tick was more often higher than the settlement price.

In my next post, I will go over the details of developing an intraday system to replicate (as close as possible) a simple daily bar-based day trading system.  Like the one we have here.

# Extend Data Mining to Actual Trading System

## Data Mining May or May Not Link Causality

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

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

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

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

``inputs: openWindowTime(930),openWindowOffset(5),windowDuration(60);inputs: canBuy(True),canShort(True);if t >= calcTime(openWindowTime,openWindowOffset) and t < calcTime(openWindowTime,openWindowOffset+windowDuration) ThenBegin	if entriesToday(d) = 0 and canBuy Then		buy next bar at market;	if entriesToday(d) = 0 and canShort Then		sellshort next bar at market ;end;if t = calcTime(openWindowTime,openWindowOffset+windowDuration) ThenBegin	if marketPosition = 1 then sell next bar at open;	if marketPosition =-1 then buyToCover next bar at open;end;setExitOnClose;``
Optimize when to open and how long to leave open

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

• window opening times offset: 5 to 240 by 5 minutes
• window opening duration: 60 to 240 by 5 minutes

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

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

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

#### System Rules

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

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

##### AvgEntryPrice versus EntryPrice

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

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

or ap = (ep1 + ep2) /2

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

``if time = calcTime(openTime,entryTime1Offset) then 	buy("1st buy") next bar at open;	if time = calcTime(openTime,entryTime2Offset) then 	buy("2nd buy") next bar at open;if time = calcTime(openTime,entryTime1Offset + exitTime1Offset) then 	sell("1st exit") from entry("1st buy") next bar at open;if time = calcTime(openTime,entryTime2Offset + exitTime2Offset) then 	sell("2nd exit") from entry("2nd buy") next bar at open;if mp = 1 ThenBegin	value1 = avgEntryPrice;	if currentShares = 2 then value1 = avgEntryPrice*2 - entryPrice;	sell("1st loss") from entry("1st buy") next bar at entryPrice - stopLoss1/bigPointValue stop;	sell("2nd loss") from entry("2nd buy") next bar at value1 - stopLoss2/bigPointValue stop;end;if mp = 1 and t = openTime + barInterval then sell("oops") next bar at open;``
Entry and Exit Directives Code

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

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

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

1. Increase data resolution and hope for an intervening bar
2. Force the second loss to occur on the subsequent trading bar after entry.  This means you will not be stopped out on the bar of entry but will have to wait five minutes or whatever bar interval you are working with.

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

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

``filter1 = True;filter2 = True;if filtNum1 = 1 then	filter1 = close of data2 > close[1] of data2;if filtNum1 = 2 Then	filter1 = close of data2 < close[1] of data2;if filtNum1 = 3 Then	filter1 = close of data2 > open of data2;if filtNum1 = 4 Then	filter1 = close of data2 < open of data2;if filtNum1 = 5 Then	filter1 = close of data2 > (h data2 + l data2 + c data2)/3;if filtNum1 = 6 Then	filter1 = close of data2 < (h data2 + l data2 + c data2)/3;if filtNum1 = 7 Then	filter1 = openD(0) > close data2;if filtNum1 = 8 Then	filter1 = openD(0) < close data2;	if filtNum2 = 1 Then	filter2 = trueRange data2 < avgTrueRange(10) data2;if filtNum2 = 2 Then	filter2 = trueRange data2 > avgTrueRange(10) data2;if filtNum2 = 3 Then	filter2 = range data2 = lowest(range data2,4);if filtNum2 = 4 Then	filter2 = range data2 = highest(range data2,4);``
Filter1 and Filter2 - filter1 looks for a pattern and filter2 seeks range compression/expansion.

## Let’s Search – And Away We Go

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

### Best Total Profit

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

### Best W:L Ratio and Respectable Avg. Trade

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

## Did We Find the Holy Grail?  Gosh No!

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

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

# Learn Pyramiding, Scaling In or Out, Camarilla, Break Out and Clear Out techniques in day trading environment.

• Chapter 1 – Open Range Break Out and other Sundries
• Chapter 2 – Improving Our ORBO with Pattern Recognition
• Chapter 3 – Time based Breakout
• Chapter 4 – Trading After the Lunch Break
• Chapter 5 – Extending Our Break Out Technology With Pyramiding and Scaling Out
• Chapter 6 – Scaling Out of Pyramided and multiple Positions
• Chapter 7 – Pyramania
• Chapter 8 – Introduction to Zone Trading with the Camarilla
• Chapter 9 – Day Trading Templates Appendix

## Take a look at this function that spans the entire search space of all the combinations of the days of the week.

``inputs: optimizeNumber(numericSimple);arrays: dowArr[31]("");vars: currDOWStr(""),daysOfWeek("MTWRF");//Once//begin	print(d," ",t," assigning list ");	dowArr[1]="MTWRF";dowArr[2]="MTWR";	dowArr[3]="MTWF";dowArr[4]="MTRF";	dowArr[5]="MWRF";dowArr[6]="TWRF";	dowArr[7]="MTW";dowArr[8]="MTR";	dowArr[9]="MTF";dowArr[10]="MWR";	dowArr[11]="MWF";dowArr[12]="MRF";	dowArr[13]="TWR";dowArr[14]="TWF";	dowArr[15]="TRF";dowArr[16]="WRF";	dowArr[17]="MT";dowArr[18]="MW";	dowArr[19]="MR";dowArr[20]="MF";	dowArr[21]="TW";dowArr[22]="TR";	dowArr[23]="TF";dowArr[24]="WR";	dowArr[25]="WF";dowArr[26]="RF";	dowArr[27]="M";dowArr[28]="T";	dowArr[29]="W";dowArr[30]="R";	dowArr[31]="F";//end;OptimizeDaysOfWeek = False;if optimizeNumber > 0 and optimizeNumber < 32 ThenBegin	currDOWStr = midStr(daysOfWeek,dayOfWeek(d),1);	if inStr(dowArr[optimizeNumber],currDOWStr) <> 0 Then		OptimizeDaysOfWeek = True;end;``
All The Permutations of the Days of the Week

# Williams Awesome Oscillator Indicator and Strategy

## Awesome Oscillator

This is a very simple yet telling analysis.  Here is the EasyLanguage:

``[LegacyColorValue = true];                     Vars:oscVal(0),mavDiff(0);                    mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);Plot3( 0, "ZeroLine" ) ;if currentbar>=1 then	if oscVal>oscVal[1] then plot1(mavDiff,"+AO")	else plot2(mavDiff,"-AO")``
Williams Awesome Oscillator Source Code

And here is what it looks like:

The code reveals a value that oscillates around 0.  First calculate the difference between the 5-day moving average of the daily midPoint (H+ L)/2 and the 34-day moving average of the midPoint.    A positive value informs us that the market is in a bullish stance whereas a negative represents a bearish tone.  Basically, the positive value is simply stating the shorter-term moving average is above the longer term and vice versa. The second step in the indicator calculation is to subtract the 5-day moving average of the differences from the current difference.  If the second calculation is greater than the prior day’s calculation, then plot the original calculation value as green (AO+).  If it is less (A0-), then paint the first calculation red.  The color signifies the momentum between the current and the five-day smoothed value.

## Awesome Indicator Strategy

``mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);                                     mp = marketPosition;mavUp = countIf(mavDiff > 0,30);mavDn = countIf(mavDiff < 0,30);value1 = countIf(oscVal > oscVal[1],10);oscRatio = value1/10*100;``
The beginning of an AO based Strategy

Here I am using the very handy countIf function.  This function will tell you how many times a Boolean comparison is true out of the last N days.  Her I use the function twice, but I could have replaced the second function call with mavDn = 30 – mavUp.  So, I am counting the number of occurrences of when the mavDiff is positive and negative over the past 30-days.  I also count the number of times the oscVal is greater than the prior oscVal.  In other words, I am counting the number of green bars.  I create a ratio between green bars and 10.  If there are six green bars, then the ratio equals 60% This indicates that the ratio of red bars would be 40%.  Based on these readings you can create trade entry directives.

``if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= obRatio thensellShort next bar at open;if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= osRatio Thenbuy next bar at open;       ``

If the number of readings out of the last 30 days is greater than numBarsAbove and mavDiff is of a certain magnitude and the oscillator ratio is greater than buyOSCRatio, then you can go short on the next open.  Here we are looking for the market to converge.  When these conditions are met then I think the market is overbought.  You can see how I set up the long entries.  As you can see from the chart it does a pretty good job.  Optimizing the parameters on the crude oil futures yielded this equity curve.

Not bad, but not statistically significant either.  One way to generate more trades is to install some trade management such as protective stop and profit objective.

Using a wide protective stop and large profit objective tripled the number of trades.  Don’t know if it is any better, but total performance was not derived from just a couple of trades.  When you are working with a strategy like this and overlay trade management you will often run into this situation.

Here we either get stopped out or take a profit and immediately reenter the market.  This occurs when the conditions are still met to short when we exit a trade.  The fix for this is to determine when an exit has occurred and force the entry trigger to toggle off.  But you have to figure out how to turn the trigger back on.  I reset the triggers based on the number of days since the triggers were turned off – a simple fix for this post.  If you want to play with this strategy, you will probably need a better trigger reset.

I am using the setStopLoss and setProfitTarget functionality via their own strategies – Stop Loss and Profit Target.  These functions allow exit on the same as entry, which can be useful.  Since we are executing on the open of the bar, the market could definitely move either in the direction of the stop or the profit.  Since we are using wide values, the probability of both would be minimal.  So how do you determine when you have exited a trade.  You could look the current bar’s marketPosition and compare it with the prior bar’s value, but this doesn’t work 100% of the time.  We could be flat at yesterday’s close, enter long on today’s open and get stopped out during the day and yesterday’s marketPosition would be flat and today’s marketPosition would be flat as well.  It would be as if nothing occurred when in fact it did.

Take a look at this code and see if it makes sense to you.

``if mp[1] = 1 and totalTrades > totTrades then	canBuy = False;		if mp[1] = -1 and totalTrades > totTrades then 	canShort = False;if mp[1] = 0 and totalTrades > totTrades thenBegin	if mavDiff[1] < 0 then canBuy = False;		if mavDiff[1] > 0 then canShort = False;end;totTrades = totalTrades;``
Watch for a change in totalTrades.

``if  not(canBuy) Then	if barsSince(canBuy=True,100,1,0) = 6 then		canBuy = True;if  not(canShort) Then	if barsSince(canShort=True,100,1,0) = 6 then		canShort = True;``

Complete strategy code:

``inputs:numBarsAbove(10),numBarsBelow(10),buyOSCRatio(60),shortOSRatio(40),minDiffAmt(2),numBarsTrigReset(6);Vars:canBuy(True),canShort(True),mp(0),totTrades(0),oscVal(0),mavDiff(0),oscRatio(0),mavUp(0),mavDn(0),stopLoss\$(1000);	                    mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);                                     mp = marketPosition;mavUp = countIf(mavDiff > 0,30);mavDn = countIf(mavDiff < 0,30);value1 = countIf(oscVal > oscVal[1],10);oscRatio = value1/10*100; if  not(canBuy) Then	if barsSince(canBuy=True,100,1,0) = numBarsTrigReset then		canBuy = True;if  not(canShort) Then	if barsSince(canShort=True,100,1,0) = numBarsTrigReset then		canShort = True;if mp[1] = 1 and totalTrades > totTrades then	canBuy = False;		if mp[1] = -1 and totalTrades > totTrades then 	canShort = False;if mp[1] = 0 and totalTrades > totTrades thenBegin	if mavDiff[1] < 0 then canBuy = False;		if mavDiff[1] > 0 then canShort = False;end;if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= buyOSCRatio thensellShort next bar at open;if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= shortOSRatio Thenbuy next bar at open;       		totTrades = totalTrades;                           ``

# Week Of Month

I could be wrong, but I couldn’t find this functionality in EasyLanguage.  I was testing a strategy that didn’t want to trade a specific week of the month.   If it’s not built-in, then it must be created.   I coded this functionality in Sheldon Knight’s Seasonality indicator but wanted to create a simplified universal version.  I may have run into one little snag.  Before discussing the snag, here is a Series function that returns my theoretical week of the month.

``vars: weekCnt(0),cnt(0);vars: newMonth(False),functionSeed(False);if month(d) <> month(d[1]) ThenBegin	weekCnt = 1;end;if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Thenbegin	weekCnt = weekCnt + 1;end;if weekCnt = 1 and dayofMonth(d) = 2 and dayOfWeek(D) = Sunday Then	print("Saturday was first day of month"," ",d);WeekOfMonth = weekCnt;``
Series Function to Return Week Rank

This function is of type Series because it has to remember the prior output of the function call – weekCnt.  This function is simple as it will not provide the week count accurately (at the very beginning of a test) until a new month is encountered in your data.  It needs a ramp up (at least 30 days of daily or intraday data) to get to that new month.  I could have used a while loop the first time the function was called and worked my way back in time to the beginning of the month and along the way calculate the week of the month.  I decided against that, because if you are using tick data then that would be a bunch of loops and TradeStation can get caught in an infinite loop very easily.

This code is rather straightforward.  If the today’s month is not equal to yesterday’s month, then weekCnt is set to one.  Makes sense, right.  The first day of the month should be the first week of the month.  I then compare the day of week of today against the day of week of yesterday.  If today’s day of week is less than the prior day’s day of week, then it must be a Sunday (futures markets open Sunday night to start the week) or Monday (Sunday = 0 and Monday = 1 and Friday = 5.)  If this occurs and today’s month is the same as yesterday’s month, weekCnt is incremented.  Why did I check for the month?  What if the first trading day was a Sunday or Monday?  Without the month comparison I would immediately increment weekCnt and that would be wrong.  That is all there is to it?  Or is it?  Notice I put some debug code in the function code.

## Is There a Snag?

April 2023 started the month on Saturday which is the last day of the week, but it falls in the first week of the month.  The sun rises on Sunday and it falls in the second week of the month.  If you think about my code, this is the first trading day of the month for futures:

month(April 2nd) = April or 4

month(March 31st) = March or 3

They do not equal so weekCnt is set to 1.  The first trading day of the month is Sunday or DOW=0 and the prior trading day is Friday or DOW=5.  WeekCnt is NOT incremented because month(D) doesn’t equal month(D[1]).  Should WeekCnt be incremented?  On a calendar basis it should, but on a trading calendar maybe not.  If you are searching for the first occurrence of a certain day of week, then my code will work for you.  On April 2nd, 2023, it is the second week of the month, but it is the first Sunday of April.

Thoughts???  Here are a couple of screenshots of interest.

This function is an example of where we let the data tell us what to do.  I am sure there is calendar functions, in other languages, that can extract information from just the date.  However, I like to extract from what is actually going to be traded.

Email me if you have any questions, concerns, criticism, or a better mouse trap.

# Reentry of Long at better price

## How to reenter at a better price after a stop loss

A reader of this blog wanted to know how he could reenter a position at a better price if the first attempt turned out to be a loser.  Here I am working with 5 minute bars, but the concepts work for daily bars too.  The daily bar is quite a bit easier to program.

### ES.D Day Trade using 30 minute Break Out

Here we are going to wait for the first 30 minutes to develop a channel at the highest high and the lowest low of the first 30 minutes.  After the first 30 minutes and before 12:00 pm eastern, we will place a buy stop at the upper channel.  The initial stop for this initial entry will be the lower channel.  If we get stopped out, then we will reenter long at the midpoint between the upper and lower channel.  The exit for this second entry will be the lower channel minus the width of the upper and lower channel.

Here are some pix.  It kinda, sorta worked here – well the code worked perfectly.   The initial thrust blew through the top channel and then immediately consolidated, distributed and crashed through the bottom channel.  The bulls wanted another go at it, so they pushed it halfway to the midpoint and then immediately the bears came in and played tug of war.  In the end the bulls won out.

Here the bulls had initial control and then the bears, and then the bulls and finally the bears tipped the canoe over.

This type of logic can be applied to any daytrade or swing trade algorithm.  Here is the code for the strategy.

``//working with 5 minute bars here//should work with any time frameinput:startTradeTime(0930),numOfBarsHHLL(6),stopTradeTime(1200),maxLongEntriesToday(2);vars: startTime(0),endTime(0),barCountToday(0),totTrades(0),mp(0),longEntriesToday(0),periodHigh(-99999999),periodLow(99999999);startTime = sessionStartTime(0,1); endTime = sessionStartTime(0,1); if t = calcTime(startTime,barInterval) Thenbegin	periodHigh = -99999999;	periodLow = 99999999;	barCountToday = 1;	totTrades = totalTrades;end;if barCountToday <= numOfBarsHHLL ThenBegin	periodHigh = maxList(periodHigh,h);	periodLow = minList(periodLow,l);end;barCountToday = barCountToday + 1;longEntriesToday = totalTrades - totTrades;mp = marketPosition;if t <= stopTradeTime and barCountToday > numOfBarsHHLL ThenBegin	if longEntriesToday = 0 then 		buy("InitBreakOut") next bar at periodHigh + minMove/priceScale stop;	if longEntriesToday = 1 Then		buy("BetterBuy") next bar at (periodHigh+periodLow)/2 stop;end;if mp = 1 then	if longEntriesToday = 0 then sell("InitXit") next bar at periodLow stop;	if longEntriesToday = 1 then sell("2ndXit") next bar at periodLow - (periodHigh - periodLow) stop;SetExitOnClose;	``

The key concepts here are the time constraints and how I count bars to calculate the first 30 – minute channel.  I have had problems with EasyLanguages’s entriesToday function, so I like how I did it here much better.  On the first bar of the day, I set my variable totTrades to EasyLanguages built-in totalTrades (notice the difference in the spelling!)  The keyword TotalTrades is immediately updated when a trade is closed out.  So, I simply subtract my totTrades (the total number of trades at the beginning of the day) from totalTrades.  If totalTrades  is incremented (a trade is closed out) then the difference between the two variables is 1.  I assign the difference of these two values to longEntriesToday.  If longEntriesToday = 1, then I know I have entered long and have been stopped out.  I then say, OK let’s get back long at a better price – the midpoint.  I use the longEntriesToday variable again to determine which exit to use.  With any luck the initial momentum that got us long initially will work its way back into the market for another shot.

## It’s Easy to Create  a Strategy Based Indicator

Once you develop a strategy, the indicator that plots entry and exit levels is very easy to derive.  You have already done the math – just plot the values.  Check this out.

``//working with 5 minute bars here//should work with any time frameinput:startTradeTime(0930),numOfBarsHHLL(6);vars: startTime(0),endTime(0),barCountToday(0),periodHigh(-99999999),periodLow(99999999);startTime = sessionStartTime(0,1); endTime = sessionStartTime(0,1); if t = calcTime(startTime,barInterval) Thenbegin	periodHigh = -99999999;	periodLow = 99999999;	barCountToday = 1;end;if barCountToday <= numOfBarsHHLL ThenBegin	periodHigh = maxList(periodHigh,h);	periodLow = minList(periodLow,l);end;if barCountToday < numOfBarsHHLL Thenbegin	noPlot(1);	noPlot(2);	noPlot(3);	noPlot(4);EndElsebegin	plot1(periodHigh,"top");	plot2((periodHigh+periodLow)/2,"mid");	plot3(periodLow,"bot");	plot4(periodLow - (periodHigh - periodLow),"2bot");end;barCountToday = barCountToday + 1;``

So, that’s how you do it.  You can use this code as a foundation for any system that wants to try and reenter at a better price.  You can also use this code to develop your own time based break out strategy.  In my new book, Easing Into EasyLanguage – the Daytrade Edition I will discuss topics very similar to this post.

# The Clear Out Pattern

This pattern has been around for many years, and is still useful today in a day trading scheme.  The pattern is quite simple:  if today’s high exceeds yesterday’s high by a certain amount, then sell short as the market moves back through yesterday’s high.  There are certain components of yesterday’s daily bar that are significant to day traders – the high, the low, the close and the day traders’ pivot.  Yesterday’s high is considered a level of resistance and is often tested.  Many times the market has just enough momentum to carry through this resistance level, but eventually peters out and then the bears will jump in and push the market down even more.  The opposite is true when the bulls take over near the support level of yesterday’s low.  Here is an example of Clear Out short and buy.

## How Do You Program this Simple Pattern?

The programming of this strategy is rather simple, if you are day trading.  The key components are toggles that track the high and low of the day as the market penetrate the prior day’s high and low.  Once the toggles are flipped on, then order directives can be placed.  A max. trade stop loss can easily be installed via the SetStopLoss(500) function.  You will also want to limit the number of entries, because in a congestive phase, this pattern could fire off multiple times.   Once you intuitively program this,  you will almost certainly run into an issue where a simple “trick” will bail you out.   Remember the code does exactly what you tell it to do. Take a look at these trades.

### Okay – Can you rely on a 5 minute bar then?

Five minute bar data has been the staple of day trading systems for many years.  However, if you want to test “bang-bang” algorithms you are probably better off dropping down to a N-seconds bar.  However, this strategy as a whole is not “bang-bang” so with a little trick you can get more accurate entries and exits.

### How Does the Trick Affect Performance?

Here are the results over the past four months on different time frame resolutions.

10 seconds bar would be the most accurate if slippage is acceptable.  And that is a big assumption on “bang-bang” days.

The one minute bar is close but September is substantially off.  Probably some “bang-bang” action.

This is close to the 10-second bar result.  Fast market or “bang-bang” trades were reduced or eliminated with the “trick”.

Surprisingly, the 5 minute bar without the “Trick” resembles the 10 seconds results.  But we know this is not accurate as trades are fired off in a manner that goes against reality.

The two following table shows the impact of a \$15 RT comm./slipp. per trade charge.

## Okay, Now That We Have That Figured Out How Do You Limit Trading After a Daily Max. Loss

Another concept I wanted to cover was limiting trades after a certain loss level was suffered on a daily basis.  In the code, I only wanted to enter trades as long as the max. daily loss was less than or equal to \$1,000   A fixed stop of \$500 on a per trade basis was utilized as well.  So, if you suffered two max. stop losses right off the bat (\$1,000), you could still take one more trade.  Now if you had a \$500 winner and two \$500 losses you could still take another trade.

If you are going to trade a system, you better trade it systematically!

## Now Onto the Code

``//Illustrate trade stoppage after a certain loss has been//experienced and creating realistic stop orders.inputs: maxDailyLoss(1000),startTime(0935);inputs: clrOutBuyPer(.10),clrOutShortPer(.10);vars: coBuy(False),coShort(False),canTrade(0);vars: beginOfDayProfit(0),beginOfDayTotTrades(0),mp(0);if t = startTime thenbegin	coBuy = False;	coShort = False;	beginOfDayProfit = netProfit;	beginOfDayTotTrades = totalTrades;end;canTrade = iff(t >=startTime and t < sess1EndTime,1,0);if  t >= startTime and h > highD(1) + clrOutBuyPer*(highD(1)-lowD(1)) thenbegin	coShort = True;end;if  t >= startTime and l < lowD(1) - clrOutShortPer*(highD(1)-lowD(1)) thenbegin	coBuy = True;end;mp = marketPosition;if canTrade = 1 and coShort and netProfit >= beginOfDayProfit - maxDailyLoss andc > highD(1) - minMove/priceScale then	 sellShort next bar at highD(1) - minMove/priceScale stop;	 if mp = -1 then // toggle to turn off coShort - must wait for set upbegin	coShort = False;end;if canTrade = 1 and coBuy and netProfit >= beginOfDayProfit - maxDailyLoss andc <  lowD(1) + minMove/priceScale then	buy next bar at lowD(1) + minMove/priceScale stop;	if mp = 1 thenbegin	coBuy = False;end;setStopLoss(500);setExitOnClose;``
Strategy in its Entirety

You need to capture the NetProfit sometime during the day before trading commences.  This block does just that.

``if t = startTime thenbegin	coBuy = False;	coShort = False;	beginOfDayProfit = netProfit;	beginOfDayTotTrades = totalTrades;end;``
Snippet that captures NetProfit at start of day

Now all you need to do is compare the current netProfit (EL keyword) to the beginOfDayProfit (user variable)If the current netProfit >= beginOfDayProfit – maxDailyLoss (notice I programmed greater than or equal to), then proceed with the next trade.  The rest of the logic is pretty self explanatory, but to drive the point home, here is how I make sure a proper stop order is placed.

``if canTrade = 1 and coShort and netProfit >= beginOfDayProfit - maxDailyLoss andc > highD(1) - minMove/priceScale then	 sellShort next bar at highD(1) - minMove/priceScale stop;	 if mp = -1 then // toggle to turn off coShort - must wait for set upbegin	coShort = False;end;``
Notice how I use the current bars Close - C and How I toggle coShort to False

## If You Like This – Make Sure You Get My Hi-Res Edition of Easing Into EasyLanguage

This is a typical project I discuss in the second book in the Easing Into EasyLanguage Trilogy.  I have held over the BLACK FRIDAY special, and it will stay in effect through December 31st.  Hurry, and take advantage of the savings.  If you see any mistakes, or just want to ask me a question, or have a comment, just shoot me an email.

# Can Futures Traders Trust Continuous Contracts? [Part – 1]

## Well You Have To, Don’t You?

When I worked at Futures Truth, we tested everything with our Excalibur software.  This software used individual contract data and loaded the entire history (well, the part we maintained) of each contract into memory and executed rollovers at a certain time of the month.  Excalibur had its limitations as certain futures contracts had very short histories and rollover dates had to be predetermined – in other words, they were undynamic.  Over the years, we fixed the short history problem by creating a dynamic continuous contract going back in time for the number of days required for a calculation.  We also fixed the database with more appropriate rollover frequency and dates.  So in the end, the software simulated what I had expected from trading real futures contracts.  This software was originally written in Fortran and for the Macintosh.  It also had limitations on portfolio analysis as it worked its way across the portfolio, one complete market at a time.   Even with all these limitations, I truly thought that the returns more closely mirrored what a trader might see in real time.  Today, there aren’t many, if any, simulation platforms that test on individual contracts.  The main reasons for this are the complexity of the software, and the database management.  However, if you are willing to do the work, you can get close to testing on individual contract data with EasyLanguage.

## Step 1 – Get the rollover dates

This is critical as the dates will be used to roll out of one contract and into another.  In this post, I will test a simple strategy on the crude futures.  I picked crude because it rolls every month.   Some data vendors use a specific date to roll contracts, such as Pinnacle data.  In real time trading, I did this as well.  We had a calendar for each month, and we would mark the rollover dates for all markets traded at the beginning of each month.  Crude was rolled on the 11th or 12th of the prior month to expiration.  So, if we were trading the September 2022 contract, we would roll on August 11th.  A single order (rollover spread) was placed to sell (if long) the September contract and buy the October contract at the market simultaneously.  Sometimes we would leg into the rollover by executing two separate orders – in hopes of getting better execution.  I have never been able to find a historic database of when TradeStation performs its rollovers.  When you use the default @CL symbol, you allow TradeStation to use a formula to determine the best time to perform a rollover.  This was probably based on volume and open interest.  TradeStation does allow you to pick several different rollover triggers when using their continuous data.

Trading terminates 3 business day before the 25th calendar day of the month prior to the contract month. If the 25th calendar day is not a business day, trading terminates 4 business days before the 25th calendar day of the month prior to the contract month.

You can look this up on your favorite broker’s website or the handy calendars they send out at Christmas.  Based on this description, the Sept. 2022 Crude contract would expire on August 20th and here’s why

• August 25 is Tuesday
• August 24 is Monday- DAY1
• August 21 is Friday – DAY2
• August 20 is Thursday – DAY3

This is the beauty of a well oiled machine or exchange.  The FND will occur exactly as described.  All you need to do is get all the calendars for the past ten years and find the 25th of the month and count back three business days.  Or if the 25 falls on a weekend count back four business days.  Boy that would be chore, would it not?  Luckily, we can have the data and an  EasyLanguage script do this for us.  Take a look at this code and see if it makes any sense to you.

``Case "@CL":	If dayOfMonth(date) = 25 and firstMonthPrint = false then	begin		print(date[3]+19000000:8:0);		firstMonthPrint = true;	end;	If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then	begin		print(date[4]+19000000:8:0);		firstMonthPrint = true;	end;``
Code to printout all the FND of crude oil.

I have created a tool to print out the FND or LTD of any commodity futures by examining the date.  In this example, I am using a Switch-Case to determine what logic is applied to the chart symbol.  If the chart symbol is @CL, I look to see if the 25th of the month exists and if it does, I print the date 3 days prior out.  If today’s day of month is greater than 25 and the prior day’s day of month is less than 25, I know the 25th occurred on a weekend and I must print out the date four bars prior.  These dates are FN dates and cannot be used as is to simulate a rollover. You had best be out before the FND to prevent the delivery process.   Pinnacle Date rolls the crude on the 11th day of the prior month for its crude continuous contracts.  I aimed for this day of the month with my logic.  If the FND normally fell on the 22nd of the month, then I should back up either 9 or 10 business days to get near the 11th of the month.   Also I wanted to use the output directly in an EasyLanguage strategy so I modified my output to be exact EasyLanguage.

``Case "@CL":	If dayOfMonth(date) = 25 and firstMonthPrint = false then 	begin	value1 = value1 + 1;		print("rollArr[",value1:1:0,"]=",date[9]+19000000:8:0,";");		firstMonthPrint = true;	end;	If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then	begin		value1 = value1 + 1;		print("rollArr[",value1:1:0,"]=",date[10]+19000000:8:0,";");//		print(date[4]+19000000:8:0);		firstMonthPrint = true;	end;// example of outputrollArr[103]=20210312;rollArr[104]=20210412;rollArr[105]=20210512;rollArr[106]=20210614;rollArr[107]=20210712;rollArr[108]=20210812;rollArr[109]=20210913;rollArr[110]=20211012;rollArr[111]=20211111;rollArr[112]=20211210;rollArr[113]=20220111;rollArr[114]=20220211;rollArr[115]=20220314;rollArr[116]=20220411;rollArr[117]=20220512;rollArr[118]=20220610;rollArr[119]=20220712;rollArr[120]=20220812;``
Code to print our 9 or 10 bars prior to FND in actual EasyLanguage

Now. that I had the theoretical rollover dates for my analysis I had to make sure the data that I was going to use matched up exactly.  As you saw before, you can pick the rollover date for your chart data.   And you can also determine the discount to add or subtract to all prior data points based on the difference between the closing prices at the rollover point.  I played around with the number of days prior to FND and selected non adjusted for the smoothing of prior data.

How did I determine 8 days Prior to First Notice Date?  I plotted different data using a different number of days prior and determined 8 provided a sweet spot between the old and new contract data’s open interest.  Can you see the rollover points in the following chart?  Ignore the trades – these were a beta test.

The dates where the open interest creates a valley aligned very closely with the dates I printed out using my FND date finder function.  To be safe, I compared the dates and fixed my array data to match the chart exactly.  Here are two rollover trades – now these are correct.

This post turned out to be a little longer than I thought, so I will post the results of using an adjusted continuous contract with no rollovers, and the results using non-adjusted concatenated contracts with rollovers.  The strategy will be a simple 40/20 bar Donchian entry/exit.  You maybe surprised by the results – stay tuned.

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

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.

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.

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.

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 PruittInputs: 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 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 tradesvars: monthlyEqu(0),priorMonthEqu(0);vars: totalEquity(0);if month(date) <> month(date[1]) thenbegin    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.

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.

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.

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.

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.

If all goes according to plan after you hit the green Arrow for the Run command your spreadsheet should like similar to this.

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.

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

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.

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.

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

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.

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