Dollar Cost Averaging Algorithm – Buy X amount every other Monday!
I am not going to get into this controversial approach to trading. But in many cases, you have to do this because of the limitations of your retirement plan. Hey if you get free matching dough, then what can you say.
Check this out!
Buy $1000 worth of shares every other Monday. INTC
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then begin toggle = not(toggle); if toggle then buy dollarInvestment/close shares next bar at open; end;
Toggle every other Monday ON
Here I use a Boolean typed variable – toggle. Whenever it is the first day of the week, turn the toggle on or off. Its new state becomes the opposite if its old state. On-Off-On-Off – buy whenever the toggle is On or True. See how I determined if it was the first day of the week; whenever tomorrow’s day of the week is less than today’s day of the week, we must be in a new week. Monday = 1 and Friday = 5.
Allow partial liquidation on certain days of the year.
Here I use arrays to set up a few days to liquidate a fractional part of the entire holdings.
value1 = d + 19000000; if sellDates[cnt] = value1 then begin sell sellAmounts[cnt]/close shares total next bar at open; cnt = cnt + 1; end;
Notice the word TOTAL in the order directive.
You can use this as reference on how to declare an array and assign the elements an initial value. Initially, sellDates is an array that contains 20 zeros, and sellAmounts is an array that contains 20 zeros as well. Load these arrays with the dates and the dollar amounts that want to execute a partial liquidation. Be careful with using Easylanguage’s Date. It is in the form YYYMMDD – todays date December 28, 2023, would be represented by 1231228. All you need to do is add 19000000 to Date to get YYYYMMDD format. You could use a function to help out here, but why. When the d + 19000000 equals the first date in the sellDates[1] array, then a market sell order to sell sellAmounts[1]/close shares total is issued. The array index cnt is incremented. Notice the order directive.
sell X sharestotal next bar at market;
If you don’t use the keyword total, then all the shares will be liquidated.
To create a complete equity curve, you will want to liquidate all the shares at some date near the end of the chart. This is used as input as well as the amount of dollars to invest each time.
//Demonstation of Dollar Cost Averaging //Buy $1000 shares every two weeks //Then liquidate a specific $amount on certain days //of the year
value1 = d + 19000000; if sellDates[cnt] = value1 then begin sell sellAmounts[cnt]/close shares total next bar at open; cnt = cnt + 1; end;
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then begin toggle = not(toggle); if toggle then buy dollarInvestment/close shares next bar at open; end;
if d + 19000000 = settleDate Then sell next bar at open;
A cool looking chart.
A chart with all the entries and exits.
Allow Pyramiding
Turn Pyramding On. You will want to allow up to X entries in the same direction regardless of the order directive.
Working with Data2
I work with many charts that have a minute bar chart as Data1 and a daily bar as Data2. And always forget the difference between:
Close of Data2 and Close[1] of Data2
24 hour regular session used here 1231214 1705 first bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231214 1710 second bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231215 1555 next to last bar of day - close of data2 4774.00 close[1] of data2 4760.75 1231215 1600 last bar of day - close of data2 4768.00 close[1] of data2 4774.00
Up to the last bar of the current trading day the open, high, low, close of data2 will reflect the prior day’s values. On the last bar of the trading day – these values will be updated with today’s values.
Learn how to constrain trading between a Start and End Time – not so “easy-peasy”
Why waste time on this?
Is Time > StartTime and Time <= EndTime then… Right?
This is definitely valid when EndTime > StartTime. But what happens when EndTime < StartTime. Meaning that you start trading yesterday, prior to midnight, and end trading after midnight (today.) Many readers of my blog know I have addressed this issue before and created some simple equations to help facilitate trading around midnight. The lines of code I have presented work most of the time. Remember when the ES used to close at 4:15 and re-open at 4:30 eastern? As of late June 2021, this gap in time has been removed. The ES now trades between 4:15 and 4:30 continuously. I discovered a little bug in my code for this small gap when I was optimizing a “get out time.” I wanted to create a user function that uses the latest session start and end times and build a small database of valid times for the 24-hour markets. Close to 24 hours – most markets will close for an hour. With this small database you can test your time to see if it is a valid time. The construction of this database will require a little TIME math and require the use of arrays and loops. It is a good tutorial. However, it is not perfect. If you optimize time and you want to get out at 4:20 in 2020 on the ES, then you still run into the problem of this time not being valid. This requires a small workaround. Going forward with automated trading, this function might be useful. Most markets trade around the midnight hour – I think meats might be the exception.
Time Based Math
How many 5-minute bars are between 18:00 (prior day) and 17:00 (today)? We can do this in our heads 23 hours X (60 minutes / 5 minutes) or 23 X 12 = 276 bars. But we need to tell the computer how to do this and we also should allow users to use times that include minutes such as 18:55 to 14:25. Here’s the math – btw you may have a simpler approach.
Using startTime of 18:55 and endTime of 14:25.
Calculate the difference in hours and minutes from startTime to midnight and then in terms of minutes only.
timeDiffInHrsMins = 2360 – 1855 = 505 or 5 hours and 5 minutes. We use a little short cut hear. 23 hours and 60 minutes is the same as 2400 or midnight.
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100). This looks much more complicated than it really is because we are using two helper functions – intPortion and mod:
) intPortion – returns the whole number from a fraction. If we divide 505/100 we get 5.05 and if we truncate the decimal we get 5 hours.
) mod – returns the modulus or remainder from a division operation. I use this function a lot. Mod(505/100) gives 5 minutes.
) Five hours * 60 minutes + Five minutes = 305 minutes.
Calculate the difference in hours and minutes from midnight to endTime and then in terms of minutes only.
timeDiffInHrsMins = endTime – 0 = 1425 or 14 hours and 25 minutes. We don’t need to use our little, short cut here since we are simply subtracting zero. I left the zero in the calculation to denote midnight.
timeDiffInMinutes = timeDiffInMinutes + intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100). This is the same calculation as before, but we are adding the result to the number of minutes derived from the startTime to midnight.
) intPortion – returns the whole number from a fraction. If we divide 1425/100, we get 14.05 and if we truncate the decimal, we get 14.
) mod – returns the modulus or remainder from a division operation. I use this function a lot. Mod(1425/100) gives 25.
) 14* 60 + 25 = 865 minutes.
) Now add 305 minutes to 865. This gives us a total of 1165 minutes between the start and end times.
Now divide the timeDiffInMinutes by the barInterval. This gives 1165 minutes/5 minutes or 233 five-minute bars.
Build Database of all potential time stamps between start and end time
We now have all the ingredients to build are simple array-based database. Don’t let the word array scare you away. Follow the logic and you will see how easy it is to use them. First, we will create the database of all the time stamps between the regular session start and end times of the data on the chart. We will use the same time-based math (and a little more) to create this benchmark database. Check out the following code.
// You could use static arrays // reserve enough room for 24 hours of minute bars // 24 * 60 = 1440 // arrays: theoTimes[1440](0),validTimes[1440](0); // syntax - arrayName[size](0) - the zero sets all elements to zero // this seems like over kill because we don't know what // bar interval or time span the user will be using
// these arrays are dynamic // we dimension or reserve space for just what we need arrays: theoTimes[](0),validTimes[](0);
// Create a database of all times stamps that potentiall could // occur
// Now set the dimension of the array by using the following // function and the number of bars we calculated for the entire // regular session Array_setmaxindex(theoTimes,numBarsInCompleteSession); // Load the array from start time to end time // We know the start time and we know the number of X-min bars // loop from 1 to numBarsInCompleteSession and // use timeSum as the each and every time stamp // To get to the end of our journey we must use Time Based Math again. timeSum = startTime; for arrayIndex = 1 to numBarsInCompleteSession Begin timeSum = timeSum + barInterval; if mod(timeSum,100) = 60 Then timeSum = timeSum - 60 + 100; // 1860 - becomes 1900 if timeSum = 2400 Then timeSum = 0; // 2400 becomes 0000 theoTimes[arrayIndex] = timeSum;
print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]); end;
Create a dynamic array with all possible time stamps
This is a simple looping mechanism that continually adds the barInterval to timeSum until numBarsInCompleteSession are exhausted. Reade about the difference between static and dynamic arrays in the code, please. Here’s how it works with a session start time of 1800:
theoTimes[01] = 1800 + 5 = 1805 theoTimes[02] = 1805 + 5 = 1810 theoTimes[04] = 1810 + 5 = 1815 theoTimes[05] = 1815 + 5 = 1820 theoTimes[06] = 1820 + 5 = 1830 ... //whoops - need more time based math 1860 is not valid theoTimes[12] = 1855 + 5 = 1860
Insert bar stamps into our theoTimes array
More time-based math
Our loop hit a snag when we came up with 1860 as a valid time. We all know that 1860 is really 1900. We need to intervene when this occurs. All we need to do is use our modulus function again to extract the minutes from our time.
If mod(timeSum,100) = 60 then timeSum = timeSum – 60 + 100. Her we remove the sixty minutes from the time and add an hour to it.
1860 – 60 + 100 = 1900 // a valid time stamp
That should fix everything right? What about this:
2400 is okay in Military Time but not in TradeStation
This is a simple fix with. All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.
Build a database on our custom time frame.
Basically, do the same thing, but use the user’s choice of start and end times.
//calculate the number of barInterval bars in the //user defined session numBarsInSession = timeDiffInMinutes/barInterval;
Array_setmaxindex(validTimes,numBarsInSession);
startTimeStamp = calcTime(startTime,barInterval);
timeSum = startTime; for arrayIndex = 1 to numBarsInSession Begin timeSum = timeSum + barInterval; if mod(timeSum,100) = 60 Then timeSum = timeSum - 60 + 100; if timeSum = 2400 Then timeSum = 0; validTimes[arrayIndex] = timeSum; // print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession); end;
Create another database using the time frame chose by the user
Don’t allow weird times!
Good programmers don’t allow extraneous values to bomb their functions. TRY and CATCH the erroneous input before proceeding. If we have a database of all possible time stamps, shouldn’t we use it to validate the user entry? Of course, we should.
//Are the users startTime and endTime valid //bar time stamps? Loop through all the times //and validate the times.
for arrayIndex = 1 to numBarsInCompleteSession begin if startTimeStamp = theoTimes[arrayIndex] then validStartTime = True; if endTime = theoTimes[arrayIndex] Then validEndTime = True; end;
Validate user's input.
Once we determine if both time inputs are valid, then we can determine if the any bar’s time stamp during a back-test is a valid time.
if validStartTime = false or validEndTime = false Then error = True;
//Okay to check for bar time stamps against our //database - only go through the loop until we //validate the time - break out when time is found //in database. CanTradeThisTime is the name of the function. //It returns either True or False
if error = False Then Begin for arrayIndex = 1 to numBarsInSession Begin if t = validTimes[arrayIndex] Then begin CanTradeThisTime = True; break; end; end; end;
This portion of the code is executed on every bar of the back-test.
Once and only Once!
The code that creates the theoretical and user defined time stamp database is only done on the very first bar of the chart. Also, the validation of the user’s input in only done once as well. This is accomplished by encasing this code inside a Once – begin – end.
Now this code will test any time stamp against the current regular session. If you run a test prior to June 2021, you will get a theoretical database that includes a 4:20, 4:25, and 4:30 on the ES futures. However, in actuality these bar stamps did not exist in the data. This might cause a problem when working with a start or end time prior to June 2021, that falls in this range.
Function Name: CanTradeThisTime
Complete code:
// Function to determine if time is in acceptable // set of times inputs: startTime(numericSimple),endTime(numericSimple);
if startTime <= endTime Then Begin timeDiffInHrsMins = (intPortion(endTime/100) - 1)*100 + mod(endTime,100) + 60 - startTime; timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100); end;
numBarsInSession = timeDiffInMinutes/barInterval;
Array_setmaxindex(validTimes,numBarsInSession);
startTimeStamp = calcTime(startTime,barInterval);
timeSum = startTime; for arrayIndex = 1 to numBarsInSession Begin timeSum = timeSum + barInterval; if mod(timeSum,100) = 60 Then timeSum = timeSum - 60 + 100; if timeSum = 2400 Then timeSum = 0; validTimes[arrayIndex] = timeSum; print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession); end; for arrayIndex = 1 to numBarsInCompleteSession begin if startTimeStamp = theoTimes[arrayIndex] then validStartTime = True; if endTime = theoTimes[arrayIndex] Then validEndTime = True; end; end;
if validStartTime = False or validEndTime = false Then error = True;
if error = False Then Begin for arrayIndex = 1 to numBarsInSession Begin if t = validTimes[arrayIndex] Then begin CanTradeThisTime = True; break; end; end; end;
Complete CanTradeThisTime function code
Sandbox Strategy function driver
inputs: startTime(1800),endTime(1500);
if canTradeThisTime(startTime,endTime) Then if d = 1231206 or d = 1231207 then print(d," ",t," can trade this time");
I hope you find this useful. Remember to purchase by Easing into EasyLanguage books at amazon.com. The DayTrade edition is still on sale. Email me with any question or suggestions or bugs or anything else.
Daily Bar Daytrade to 5 Minute Bars — Not So Easy!
Like in the previous post, I designed a simple optimization framework trying to determine the best day of the week to apply a long onlyvolatility based open range break out algorithm on natural gas. You might first ask why natural gas? Its a good market that has seasonal tendencies that can actually be day-traded – there is enough volatility and volume. Anyway, by simply slapping setExitOnClose at the end of your code turns your algorithm into one that exits every day at the settlement (fictional value that is derived via formula) price. You can always use LIB (look inside bar) to help determine the magnitude of intraday swings and there respective chronological order. But you are still getting out at the settlement price – which isn’t accurate. However, if you are trying to get a set of parameters that gets you into the ballpark, then this is a very acceptable approach. But you will always want to turn you daily bar strategy with LIB intro an intraday version for automation and accuracy purposes.
Day of Week Analysis On Intraday Data
When you optimize the day of week on daily bars, the first bar of the week is usually Monday. When testing with intraday bars on futures, the trading actually starts on Sunday evening. If your daily bar analysis reveals the best day of week is Wedneday, then you must inform TradeStation to take the trade from the opening on Tuesday night through the close on Wenesday. If you are executing a market order, then you just need to tell TradeStation to execute at Tuesday night’s open (1800 eastern standard time). The TRICK to allow trading throughout the 24 hour session (1800 to 1700) on just a particular day of the week is to capture the day of the week on the first bar of the trading session. Here is some bookkeeping you can take care of on the first bar of the trading session.
if t = sessionstartTime(0,1) + barInterval Then Begin
todaysOpen = o; openDOW = dayOfWeek(d); canBuy = False; if openDOW = daysOfWeekToTrade then canBuy = True; if canBuy and d[1] <> date of data2 then begin canBuy = False; print(d," turning off canBuy"); end;
if mp = 1 then curTradeDays = curTradeDays + 1; if mp = 0 then curTradeDays = 0; barsToday = 1; end;
Bookkeeping on the first bar of trading session
Here, I check to see if the first bar’s time stamp is equal to the sessionStarttime + barInterval. Remember TradeStation shows the close time of each bar as the time stamp. If adding a barInterval to the opening time results in a non-time, then use the calcTime function ( 1800 + 60 = 1860 – a non-time.) I first store the open of the session in my variable todaysOpen. Why not just use openD(0). Well openD(0) is great for sessions that don’t span midnight. If they span midnight then the openD returns the open of the12:00 am bar. Here is the output from August 9th with the open on August 8th at 1800. The two other values are midnight on August 8th and August 7th. So the openD, highD, lowD, and closeD functions involve the 24 hour clock and not the session.
On the first bar of the trading session I also capture the day of the week. The days of the week, using intraday data on a 24 hour session, range from Sunday to Thursday, instead of Monday thru Friday. CanBuy is turned on if the day of week equals the input provided by the user. When using daily bars and you optimize the day of the week, remember if you chose 2 or Tuesday you really mean Wednesday. If today is Tuesday, then buy next bar at… This will generate trades only on Wednesdays. When testing on intraday data you do not need to make a modification for the day of week. If the first bar of the trading session is Tuesday, then you will actually trade what is considered the Wednesday session that starts on Tuesday evening at 18:00.
What About Holidays?
Here is a quick trick to not trade on Holidays. The daily bar does not include preempted sessions in its database, whereas intraday data does. So, if at 18:00 the date of the prior bar does not match the date of the daily bar located in the Data2 slot, then you know that the prior day was preempted and you should not trade today. In other words, Data2 is missing. Remember, you only want to trade on days that are included in the daily bar database in your attempt to replicate the daily bar strategy.
date close moving average
1230703.00 data2 2.57382 2.70300
1230704.00 missing data2 2.57382 2.70300 <-- no trade
1230705.00 data2 2.57485 2.65100 <-- matches
How to count the daily bars since entry.
Here again you need to do some bookkeeping. If you are long on the first bar of the day, then you have been in the trade for at least a day. If you are long on two first bars of the trading session, then you have been long for two days. I use the variable, curTradeDays, to count the number of days we have been in the trade. If on the first bar of the trading session we are flat, then I reset curTradeDays to zero. Otherwise, I increment the variable and this only occurs once a day. You can optimize the daysInTrade input, but for this post we are just interested in getting out at the close on the day of entry.
Controlling one entry per day.
We only want one long entry per day in an attempt to replicate the daily bar system. There are several ways to do this, but comparing the current bar’s marketPosition to the prior bar’s value will inform you if a position has been transitioned from flat to long. If the prior bar’s position if flat and the current bar is now long, then we can turn our canBuy off or to false. If we get stopped out later and the market rallies again to our break out level, we will not execute at that level, because the trade directive will not be issued. Why not use the entriesToday function? Again midnight cause this function to reset. Say you go long at 22:00 and you do not want to enter another position until the tomorrow at 18:00. EntriesToday will forget you entered the long position at 22:00.
Cannot execute on the first bar of the day – does it matter?
Since this is an open range break out, we need to know what the open is prior to our break out calculation. Could the break out level be penetrated on the first 5 minute bar? Sure, but I bet it is rare. I tested this and it only occurred 4 or 5 times. In a back-test, if this occurs and the subsequent bar’s open is still above the break out level, TradeStation will convert the stop order to a market order and you will buy the open of the 2nd five minute bar. In real time trading, you must tell TradeStation to wait until the end of the first 5 minute bar before issuing the trade directive to replicate your back testing. If this is an issue, you can test with 5 minute bars, but execute on 1 minute bars. In other words, have your testing chart and an additional execution chart. Skipping the first 5 minute bar may be advantageous. Many times you will get a surge at the open and then the market falls back. By the time the first 5 minute bar concludes the market may be trading back below your break out level. You might bypass the bulge. But your still in the game. Here is how you can test the significance of this event.
if canBuy and h > todaysOpen + volAmt *volMult then Begin print(d," first bar penetration ",value67," ",value68," ",(c - (todaysOpen + volAmt *volMult))*bigPointValue ); value67 = value67 + 1; value68 = value68 + (c - (todaysOpen + volAmt *volMult))*bigPointValue; end;
Testing for penetration on first 5 minute bar of the day
By the end of the first bar of the day we know the open, high, low and close of the day thus far. We can test to see if the high would have penetrated the break out level and also calculate the profit or loss of the trade. In a back-test you will not miss this trade if the next bar’s open is still above the break out level. If the next bar’s open is below the break out level, then you may have missed a fake out break out. Again this is a rare event.
if t = sessionstartTime(0,1) + barInterval Then Begin todaysOpen = o; openDOW = dayOfWeek(d); canBuy = False; if openDOW = daysOfWeekToTrade then canBuy = True; if canBuy and d[1] <> date of data2 then begin canBuy = False; end;
if mp = 1 then curTradeDays =curTradeDays + 1; if mp = 0 then curTradeDays = 0; barsToday = 1;
volAmt = average(range of data2,volLen); movAvg = average(c,mavLen) of data2; if canBuy and h > todaysOpen + volAmt *volMult then Begin print(d," first bar penetration ",value67," ",value68," ",(c - (todaysOpen + volAmt *volMult))*bigPointValue ); value67 = value67 + 1; value68 = value68 + (c - (todaysOpen + volAmt *volMult))*bigPointValue; end; end;
if mp[1] = 0 and mp = 1 and canBuy then canBuy = False;
if canBuy and t <> sessionEndTime(0,1) Then Begin if barsToday > 1 and close of data2 > movAvg and range of data2 > volAmt * volComp then buy("DMIntraBuy") next bar at todaysOpen + volAmt *volMult stop; end; barsToday = barsToday + 1;
if daysInTrade = 0 then setExitOnClose;
sell("LLxit") next bar at lowest(l of data2,llLookBack) stop; if mp = 1 and daysInTrade > 0 then begin if curTradeDays = daysInTrade then sell("DaysXit") next bar at open; end;
Intrday system that replicates a daily bar day trader
We are using the setStopLoss and setProfitTarget functions in this code. But remember, if your continuous contract goes negative, then these functions will not work properly.
This type of programming is tricky, because you must use tricks to get EasyLanguage to do what you want it to do. You must experiment, debug, and program ideas to test the limitations of EasyLanguage to hone your craft.
OptimizeDaysOfWeek = False; if optimizeNumber > 0 and optimizeNumber < 32 Then Begin currDOWStr = midStr(daysOfWeek,dayOfWeek(d),1); if inStr(dowArr[optimizeNumber],currDOWStr) <> 0 Then OptimizeDaysOfWeek = True; end;
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:
Williams Awesome Oscillator
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.
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 then sellShort next bar at open;
if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= osRatio Then buy next bar at open;
Trade Directives
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.
Too few trades!
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 wide 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.
Exiting while conditions to short are still turned on!
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 then Begin if mavDiff[1] < 0 then canBuy = False; if mavDiff[1] > 0 then canShort = False; end;
totTrades = totalTrades;
Watch for a change in totalTrades.
If we were long yesterday and totalTrades (builtin keyword/function) increases above my own totTrades, then we know a trade was closed out – a long trade that is. A closed out short position is handled in the same manner. What about when yesterday’s position is flat and totalTrades increases. This means an entry and exit occurred on the current bar. You have to investigate whether the position was either long or short. I know I can only go long when mavDiff is less than zero and can only go short when mavDiff is greater than zero. So, all you need to do is investigate yesterday’s mavDiff to help you determine what position was entered and exited on the same day. After you determine if an exit occurred, you need to update totTrades with totalTrades. Once you determine an exit occurred you turn canBuy or canShort off. They can only be turned back on after N bars have transpired since they were turned off. I use my own barsSince function to help determine this.
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;
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 then Begin 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 then sellShort next bar at open;
if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= shortOSRatio Then buy next bar at open;
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.
if month(d) <> month(d[1]) Then Begin weekCnt = 1; end;
if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Then begin 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.
Indicator in Histogram form representing the Week of MonthSome months are spread across SIX weeks.
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.
The concept of Scope when it comes to a programming language can get very confusing very quickly. If you are new to programming and you think Scope is a mouthwash, no worries here. I will give a full explanation of Scope in terms of programming with the help of ChatGPT. Its response is italicized.
In Python, the scope of a variable refers to the region of the program where that variable can be accessed or referenced. There are two types of scopes in Python: global scope and local scope.
Here’s an example that demonstrates the concept of scope in Python:
# global variable x = 10
def my_func(): # local variable y = 5 print("x inside my_func:", x) # x is accessed from the global scope print("y inside my_func:", y) # y is accessed from the local scope
my_func()
print("x outside my_func:", x) # x is accessed from the global scope print("y outside my_func:") # y is not defined in the global scope, so this will raise a NameError
Example of Scope as demonstrated by Chat-GPT
In this example, we define a global variable x with a value of 10.
We then define a function my_func that has a local variable y with a value of 5. Inside the function, we print the values of x and y. The variable x is accessed from the global scope, which means it can be referenced from anywhere in the program.
The variable y, on the other hand, is only accessible within the function, which is the local scope. Outside the function, we print the value of x again, which is still accessible from the global scope. However, when we try to print the value of y, we get a NameError because y is not defined in the global scope.
Okay that was pretty formal. In simpler terms, a variable declared inside a function can only be seen inside that function, unless it is declared globally. Another thing about Scope, is that the variables have amnesia. Once you step out of the function the variable forgets what it was, and you can’t refer to its prior value upon return to the function.
Unless you are an EasyLanguage function. Scope is still constrained by an EasyLanguage function, because it is a separate piece of code held within the library of Analysis Techniques. Most of the time you can’t see what’s in the function unless you open it with the ELEditor. However, the variables that are defined inside the function do not suffer from amnesia. If you need to refer to a prior value of a locally declared variable, you can. This type of function is what EasyLanguage calls a Serial function. The only downside to this function is it slows processing down quite a bit.
Okay. To make a long story short I wanted to show the magic of EasyLanguage function that I have been working with on a project. This project includes some of Ehlers’ cycle analysis functions. The one I am going to discuss today is the HighRoof function – don’t worry I am not going to go into detail of what this function does. If you want to know just GOOGLE it or ask ChatGPT. I developed a strategy that used the function on the last 25 days of closing price data. I then turned around and fed the output of the first pass of the HighRoof function right back into the HighRoof function. Something similar to embedding functions.
doubleSmooth = average(average(c,20),20);
Sort of like a double smoothed moving average. After I did this, I started thinking does the function remember the data from its respective call? The first pass used closing price data, so its variables and their history should be in terms of price data. The second pass used the cyclical movements data that was output by the initial call to the HighRoof function. Everything turned out fine, the function remembered the correct data. Or seemed like it did. This is how you learn about any programming language – pull out your SandBox and do some testing. First off, here is my conversion of Ehlers’ HighRoof function in EasyLanguage.
This function requires just two inputs – the data (with a history) and a simple length or cut period. The first input is of type numericSeries and the second input is of type numericSimple. You will see the following line of code
This code prints out the last three historic values of the HighPass variable for each function call. I am calling the function twice for each bar of data in the Crude Oil futures continuous contract.
Starting at the top of the output you will see that on 1230206 the function was called twice with two different sets of data. As you can see the output of the first two lines is of a different magnitude. The first line is approximately an order or magnitude of 10 of the second line. If you go to lines 3 and 4 you will see the highPass[1] of lines 1 and 2 moves to highPass[2] and then onto highPass[3]. I think what happens internally is for every call on per bar basis, the variables for each function call are pushed into a queue in memory. The queue continues to grow for whatever length is necessary and then either maintained or truncated at some later time.
Why Is This So Cool?
In many languages the encapsulation of data with the function requires additional programming. The EasyLanguage function could be seen as an “object” like in object-oriented programming. You just don’t know you are doing it. EasyLanguage takes care of a lot of the behind-the-scenes data management. To do the same thing in Python you would need to create a class of Ehlers Roof that maintain historic data in class members and the calculations would be accomplished by a class method. In the case of calling the function twice, you would instantiate two classes from the template and each class would act independent of each other.
One last nugget of information. If you are going to be working with trigonometric functions such as Cosine, Sine or Tangent, make sure your arguments are in degrees not radians. In Python, you must use radians.
Complete Strategy based on Sheldon Knight and William Brower Research
In my Easing Into EasyLanguage: Hi-Res Edition, I discuss the famous statistician and trader Sheldon Knight and his K-DATA Time Line. This time line enumerated each day of the year using the following nomenclature:
First Monday in December = 1stMonDec
Second Friday in April = 2ndFriApr
Third Wednesday in March = 3rdWedMar
This enumeration or encoding was used to determine if a certain week of the month and the day of week held any seasonality tendencies. If you trade index futures you are probably familiar with Triple Witching Days.
Four times a year, contracts for stock options, stock index options, and stock index futures all expire on the same day, resulting in much higher volumes and price volatility. While the stock market may seem foreign and complicated to many people, it is definitely not “witchy”, however, it does have what is known as “triple witching days.”
Triple witching, typically, occurs on the third Friday of the last month in the quarter. That means the third Friday in March, June, September, and December. In 2022, triple witching Friday are March 18, June 17, September 16, and December 16
Other days of certain months also carry significance. Some days, such as the first Friday of every month (employment situation), carry even more significance. In 1996, Bill Brower wrote an excellent article in Technical Analysis of Stocks and Commodities. The title of the article was The S&P 500 Seasonal Day Trade. In this article, Bill devised 8 very simple day trade patterns and then filtered them with the Day of Week in Month. Here are the eight patterns as he laid them out in the article.
Pattern 1: If tomorrow’s open minus 30 points is greater than today’s close, then buy at market.
Pattern 2: If tomorrow’s open plus 30 points is less than today’s close, then buy at market.
Pattern 3: If tomorrow’s open minus 30 points is greater than today’s close, then sell short at market.
Pattern 4: If tomorrow’s open plus 30 points is less than today’s close, then sell short at market.
Pattern 5: If tomorrow’s open plus 10 points is less than today’s low, then buy at market.
Pattern 6: If tomorrow’s open minus 20 points is greater than today’s high, then sell short at today’s close stop.
Pattern 7: If tomorrow’s open minus 40 points is greater than today’s close, then buy at today’s low limit.
Pattern 8: If tomorrow’s open plus 70 points is less than today’s close, then sell short at today’s high limit.
This article was written nearly 27 years ago when 30 points meant something in the S&P futures contract. The S&P was trading around the 600.00 level. Today the e-mini S&P 500 (big S&P replacement) is trading near 4000.00 and has been higher. So 30, 40 or 70 points doesn’t make sense. To bring the patterns up to date, I decided to use a percentage of ATR in place of a single point. If today’s range equals 112.00 handles or in terms of points 11200 and we use 5%, then the basis would equate to 11200 = 560 points or 5.6 handles. In the day of the article the range was around 6 handles or 600 points. So. I think using 1% or 5% of ATR could replace Bill’s point values. Bill’s syntax was a little different than the way I would have described the patterns. I would have used this language to describe Pattern1 – If tomorrow’s open is greater than today’s close plus 30 points, then buy at market – its easy to see we are looking for a gap open greater than 30 points here. Remember there is more than one way to program an idea. Let’s stick with Bills syntax.
10 points = 1 X (Mult) X ATR
20 points = 2 X (Mult) X ATR
30 points = 3 X (Mult) X ATR
40 points = 4 X (Mult) X ATR
50 points = 5 X (Mult) X ATR
70 points =7 X (Mult) X ATR
We can play around with the Mult to see if we can simulate similar levels back in 1996.
// atrMult will be a small percentage like 0.01 or 0.05 atrVal = avgTrueRange(atrLen) * atrMult;
//original patterns //use IFF function to either returne a 1 or a 0 //1 pattern is true or 0 it is false
The Day of Week In A Month is represented by a two digit number. The first digit is the week rank and the second number is day of the week. I thought this to be very clever, so I decided to program it. I approached it from a couple of different angles and I actually coded an encoding method that included the week rank, day of week, and month (1stWedJan) in my Hi-Res Edition. Bill’s version didn’t need to be as sophisticated and since I decided to use TradeStation’s optimization capabilities I didn’t need to create a data structure to store any data. Take a look at the code and see if it makes a little bit of sense.
newMonth = False; newMonth = dayOfMonth(d of tomorrow) < dayOfMonth(d of today); atrVal = avgTrueRange(atrLen) * atrMult; if newMonth then begin startTrading = True; monCnt = 0; tueCnt = 0; wedCnt = 0; thuCnt = 0; friCnt = 0; weekCnt = 1; end;
if not(newMonth) and dayOfWeek(d of tomorrow) < dayOfWeek(d of today) then weekCnt +=1;
dayOfWeekInMonth = weekCnt * 10 + dayOfWeek(d of tomorrow);
Simple formula to week rank and DOW
NewMonth is set to false on every bar. If tomorrow’s day of month is less than today’s day of month, then we know we have a new month and newMonth is set to true. If we have a new month, then several things take place: reinitialize the code that counts the number Mondays, Tuesdays, Wednesdays, Thursdays and Fridays to 0 (not used for this application but can be used later,) and set the week count weekCnt to 1. If its not a new month and the day of week of tomorrow is less than the day of the week today (Monday = 1 and Friday = 5, if tomorrow is less than today (1 < 5)) then we must have a new week on tomorrow’s bar. To encode the day of week in month as a two digit number is quite easy – just multiply the week rank (or count) by 10 and add the day of week (1-Monday, 2-Tuesday,…) So the third Wednesday would be equal to 3X10+3 or 33.
Use Optimization to Step Through 8 Patterns and 25 Day of Week in Month Enumerations
Stepping through the 8 patterns is a no brainer. However, stepping through the 25 possible DowInAMonth codes or enumerations is another story. Many times you can use an equation based on the iterative process of going from 1 to 25. I played around with this using the modulus function, but decided to use the Switch-Case construct instead. This is a perfect example of replacing math with computer code. Check this out.
switch(dowInMonthInc) begin case 1 to 5: value2 = mod(dowInMonthInc,6); value3 = 10; case 6 to 10: value2 = mod(dowInMonthInc-5,6); value3 = 20; case 11 to 15: value2 = mod(dowInMonthInc-10,6); value3 = 30; case 16 to 20: value2 = mod(dowInMonthInc-15,6); value3 = 40; case 21 to 25: value2 = mod(dowInMonthInc-20,6); value3 = 50; end;
Switch-Case to Step across 25 Enumerations
Here we are switching on the input (dowInMonthInc). Remember this value will go from 1 to 25 in increments of 1. What is really neat about EasyLanguage’s implementation of the Switch-Case is that it can handle ranges. If the dowInMonthInc turns out to be 4 it will fall within the first case block (case 1 to 5). Here we know that if this value is less than 6, then we are in the first week so I set the first number in the two digit dayOfWeekInMonth representation to 1. This is accomplished by setting value3 to 10. Now you need to extract the day of the week from the 1 to 25 loop. If the dowInMonthInc is less than 6, then all you need to do is use the modulus function and the value 6.
mod(1,6) = 1
mod(2,6) = 2
mod(3,6) = 3
This works great when the increment value is less than 6. Remember:
1 –> 11 (first Monday)
2 –> 12 (first Tuesday)
3 –> 13 (first Wednesday)
…
…
6 –> 21 (second Monday)
7 –> 22 (second Tuesday).
So, you have to get a little creative with your code. Assume the iterative value is 8. We need to get 8 to equal 23 (second Wednesday). This value falls into the second case, so Value3 = 20 the second week of the month. That is easy enough. Now we need to extract the day of week – remember this is just one solution, I guarantee there are are many.
mod(dowInMonthInc – 5, 6) – does it work?
value2 = mod(8-5,6) = 3 -> value3 = value1 + value2 -> value3 = 23. It worked. Do you see the pattern below.
case 6 to 10 – mod(dowInMonthInc – 5, 6)
case 11 to 15 – mod(dowInMonthInc – 10, 6)
case 16 to 20- mod(dowInMonthInc – 15, 6)
case 21 to25 – mod(dowInMonthInc – 20, 6)
Save Optimization Report as Text and Open with Excel
Here are the settings that I used to create the following report. If you do the math that is a total of 200 iterations.
Seasonal Day Trader Settings
I opened the Optimization Report and saved as text. Excel had no problem opening it.
Optimization results output to Excel and cleaned up.
I created the third column by translating the second column into our week of month and day of week vernacular. These results were applied to 20 years of ES.D (day session data.) The best result was Pattern #3 applied to the third Friday of the month (35.) Remember the 15th DowInMonthInc equals the third (3) Friday (5). The top patterns predominately occurred on a Thursday or Friday.
switch(dowInMonthInc) begin case 1 to 5: value2 = mod(dowInMonthInc,6); value3 = 10; case 6 to 10: value2 = mod(dowInMonthInc-5,6); value3 = 20; case 11 to 15: value2 = mod(dowInMonthInc-10,6); value3 = 30; case 16 to 20: value2 = mod(dowInMonthInc-15,6); value3 = 40; case 21 to 25: value2 = mod(dowInMonthInc-20,6); value3 = 50; end;
if value1 = dayOfWeekInMonth then begin if patternNum = 1 and patt1 = 1 then buy("Patt1") next bar at open; if patternNum = 2 and patt2 = 1 then buy("Patt2") next bar at open; if patternNum = 3 and patt3 = 1 then sellShort("Patt3") next bar at open; if patternNum = 4 and patt4 = 1 then sellShort("Patt4") next bar at open; if patternNum = 5 and patt5 = 1 then buy("Patt5") next bar at low limit; if patternNum = 6 and patt6 = 1 then sellShort("Patt6") next bar at close stop; if patternNum = 7 and patt7 = 1 then buy("Patt7") next bar at low limit; if patternNum = 8 and patt8 = 1 then sellShort("Patt8") next bar at high stop; end;
setExitOnClose;
The Full Monty of the ES-Seasonal-Day Trade
I think this could provide a means to much more in-depth analysis. I think the Patterns could be changed up. I would like to thank William (Bill) Brower for his excellent article, The S&P Seasonal Day Trade in Stocks and Commodities, August 1996 Issue, V.14:7 (333-337). The article is copyright by Technical Analysis Inc. For those not familiar with Stocks and Commodities check them out at https://store.traders.com/
Please email me with any questions or anything I just got plain wrong. George
I had to wrap up Part -1 rather quickly and probably didn’t get my ideas across, completely. Here is what we did in Part – 1.
used my function to locate the First Notice Date in crude
used the same function to print out exact EasyLanguage syntax
chose to roll eight days before FND and had the function print out pure EasyLanguage
the output created array assignments and loaded the calculated roll points in YYYMMDD format into the array
visually inspected non-adjusted continuous contracts that were spliced eight days before FND
appended dates in the array to match roll points, as illustrated by the dip in open interest
Step 6 from above is very important, because you want to make sure you are out of a position on the correct rollover date. If you are not, then you will absorb the discount between the contracts into your profit/loss when you exit the trade.
Step 2 – Create the code that executes the rollover trades
Here is the code that handles the rollover trades.
// If in a position and date + 1900000 (convert TS date format to YYYYMMDD), // then exit long or short on the current bar's close and then re-enter // on the next bar's open
if d+19000000 = rollArr[arrCnt] then begin condition1 = true; arrCnt = arrCnt + 1; if marketPosition = 1 then begin sell("LongRollExit") this bar on close; buy("LongRollEntry") next bar at open; end; if marketPosition = -1 then begin buyToCover("ShrtRollExit") this bar on close; sellShort("ShrtRollEntry") next bar at open; end;
end;
Code to rollover open position
This code gets us out of an open position during the transition from the old contract to the new contract. Remember our function created and loaded the rollArr for us with the appropriate dates. This simulation is the best we can do – in reality we would exit/enter at the same time in the two different contracts. Waiting until the open of the next bar introduces slippage. However, in the long run this slippage cost may wash out.
Step 3 – Create a trading system with entries and exits
The system will be a simple Donchian where you enter on the close when the bar’s high/low penetrates the highest/lowest low of the past 40 bars. If you are long, then you will exit on the close of the bar whose low is less than the lowest low of the past 20 bars. If short, get out on the close of the bar that is greater than the highest high of the past twenty bars. The first test will show the result of using an adjusted continuous contract rolling 8 days prior to FND
Nice Trade. Around August 2014
This test will use the exact same data to generate the signals, but execution will take place on a non-adjusted continuous contract with rollovers. Here data2 is the adjusted continuous contract and data1 is the non-adjusted.
Same Trade but with rollovers
Still a very nice trade, but in reality you would have to endure six rollover trades and the associated execution costs.
Conclusion
Here is the mechanism of the rollover trade.
Roll out of old contract and roll into new contract
And now the performance results using $30 for round turn execution costs.
No-Rollovers
No Rollovers?
Now with rollovers
Many more trades with the rollovers!
The results are very close, if you take into consideration the additional execution costs. Since TradeStation is not built around the concept of rollovers, many of the trade metrics are not accurate. Metrics such as average trade, percent wins, average win/loss and max Trade Drawdown will not reflect the pure algorithm based entries and exits. These metrics take into consideration the entries and exits promulgated by the rollovers. The first trade graphic where the short was held for several months should be considered 1 entry and 1 exit. The rollovers should be executed in real time, but the performance metrics should ignore these intermediary trades.
I will test these rollovers with different algorithms, and see if we still get similar results, and will post them later. As you can see, testing on non-adjusted data with rollovers is no simple task. Email me if you would like to see some of the code I used in this post.
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.
You can choose type of trigger – (3) Dynamic or (4) Time based.
I am getting ahead of myself, because we can simply use the default @CL data to derive the rollover dates (almost.) Crude oil is one of those weird markets where LTD (last trade days) occurs before FND (first notice day.) Most markets will give you a notice before they back up a huge truck and dump a 1000 barrels of oil at your front door. With crude you have to be Johnny on the spot! Rollover is just a headache when trading futures, but it can be very expensive headache if you don’t get out in time. Some markets are cash settled so rollover isn’t that important, but others result in delivery of the commodity. Most clearing firms will help you unwind an expired contract for a small fee (well relatively small.) In the good old days your full service broker would give you heads up. They would call you and say, “George you have to get out of that Sept. crude pronto!” Some firms would automatically liquidate the offending contract on your behalf – which sounds nice but it could cost you. Over my 30 year history of trading futures I was caught a few times in the delivery process. You can determine these FND and LTD from the CME website. Here is the expiration description for crude futures.
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;
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.
Actual data I simulated rollovers with.
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 Open Interest Valley is the rollover date.
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.
Using an adjusted continuous contract you would not see these trades.
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.
Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!
Get All Five Books in the Easing Into EasyLanguage Series - The Trend Following Edition is now Available!
Announcement – A Trend Following edition has been added to my Easing into EasyLanguage Series! This edition will be the fifth and final installment and will utilize concepts discussed in the Foundation editions. I will pay respect to the legends of Trend Following by replicating the essence of their algorithms. Learn about the most prominent form of algorithmic trading. But get geared up for it by reading the first four editions in the series now. Get your favorite QUANT the books they need!
The Foundation Edition. The first in the series.
This series includes five editions that covers the full spectrum of the EasyLanguage programming language. Fully compliant with TradeStation and mostly compliant with MultiCharts. Start out with the Foundation Edition. It is designed for the new user of EasyLanguage or for those you would like to have a refresher course. There are 13 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.
Hi-Res Edition Cover
This book is ideal for those who have completed the Foundation Edition or have some experience with EasyLanguage, especially if you’re ready to take your programming skills to the next level. The Hi-Res Edition is designed for programmers who want to build intraday trading systems, incorporating trade management techniques like profit targets and stop losses. This edition bridges the gap between daily and intraday bar programming, making it easier to handle challenges like tracking the sequence of high and low prices within the trading day. Plus, enjoy 5 hours of video instruction to guide you through each tutorial.
Advanced Topics Cover
The Advanced Topics Edition delves into essential programming concepts within EasyLanguage, offering a focused approach to complex topics. This book covers arrays and fixed-length buffers, including methods for element management, extraction, and sorting. Explore finite state machines using the switch-case construct, text graphic manipulation to retrieve precise X and Y coordinates, and gain insights into seasonality with the Ruggiero/Barna Universal Seasonal and Sheldon Knight Seasonal methods. Additionally, learn to build EasyLanguage projects, integrate fundamental data like Commitment of Traders, and create multi-timeframe indicators for comprehensive analysis.
Get Day Trading Edition Today!
The Day Trading Edition complements the other books in the series, diving into the popular approach of day trading, where overnight risk is avoided (though daytime risk still applies!). Programming on high-resolution data, such as five- or one-minute bars, can be challenging, and this book provides guidance without claiming to be a “Holy Grail.” It’s not for ultra-high-frequency trading but rather for those interested in techniques like volatility-based breakouts, pyramiding, scaling out, and zone-based trading. Ideal for readers of the Foundation and Hi-Res editions or those with EasyLanguage experience, this book offers insights into algorithms that shaped the day trading industry.
Trend Following Cover.
For thirty-one years as the Director of Research at Futures Truth Magazine, I had the privilege of collaborating with renowned experts in technical analysis, including Fitschen, Stuckey, Ruggiero, Fox, and Waite. I gained invaluable insights as I watched their trend-following methods reach impressive peaks, face sharp declines, and ultimately rebound. From late 2014 to early 2020, I witnessed a dramatic downturn across the trend-following industry. Iconic systems like Aberration, CatScan, Andromeda, and Super Turtle—once thriving on robust trends of the 1990s through early 2010s—began to falter long before the pandemic. Since 2020 we have seen the familiar trends return. Get six hours of video instruction with this edition.
Pick up your copies today – e-Book or paperback format – at Amazon.com