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.
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.
I opened the Optimization Report and saved as text. Excel had no problem opening it.
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
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.
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.
And now the performance results using $30 for round turn execution costs.
No-Rollovers
Now with 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.
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.
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.
Illustrating Difference Between Data Aliasing and Not Data Aliasing
If you have a higher resolution as Data 1 (5 minute in this case) than Data 2 (15 minute), then you must use Data Aliasing if you are going to use a variable to represent a price or a function output. With out Data Aliasing all data references are in terms of Data 1. When the 15 minute bar closes then the current [0] and one bar back[ 1] will be correct – going back further in time will reflect correct data. During the 15 minute bar only the last value [0] will show the correct reading of the last completed 15 minute bar. Once you tie the variable to its correct time frame variableName(0, Data2), you can then reference historic bars in the same fashion as if it were Data1. This includes price references and function output values.
Check this chart out and see if it makes sense to you. I dedicate a portion of a Tutorial on Data Aliasing in my latest book due out next week – Easing Into EasyLanguage – Advanced Topics.
Quickly Analyze Market Metrics with Gradient Based Shading
This is a simple indicator but it does involve some semi-advanced topics. Just to let you know I am working on the third book in the Easing Into EasyLanguage series. If you haven’t check out the first two, you might just want to head over to amazon and check those out. This topic falls in the spectrum of the ideas that I will be covering in the Advanced Topics edition. Also to let you know I just published the 2nd Edition of Trend Following Systems: A DIY Project – Batteries Included. Check this out if you want to learn some Python and also see some pretty cool Trend Following algorithms – I include EasyLanguage too!
The code that follows demonstrates how to shade between plots and adjust gradient in terms of the RSI reading. I compiled this with MultiCharts, so I assume it will work there too – just let me know if it doesnt. I found this code somewhere on the web when researching shading. If I knew the original author I would definitely give full credit. The code is rather simple, setting up the chart is just slightly more difficult. The Keltner Channel was used to define the shading boundaries. You could have just as easily used Bollinger Bands or anything that provided a range around the market. Here’s the code.
Basically all this math is doing is keeping the RSI reading within the bounds of the Keltner Upper and Lower Channels. You want a high RSI reading to be near the Upper Channel and a low RSI reading to be near the Lower Channel. You can change up the formula to make more sense.
I have worked with computer graphics for many years and this is really a very neat formula. The generic formula to constrain a value within a boundary is;
Here you take the LowerBand and add the percentage of the MyRSI/100 times the range. This works too. But the original formula scales or intensifies the RSI reading so you get much wider gradient spectrum. The AVG is used as the center of gravity and the RSI is converted in terms of the middle 50 line. A positive number, anything > 50, is then scaled higher in the range and a negative number, anything < 50 is scaled lower in the range. In other words it makes a prettier and more informative picture.
Returns a specific color from a user defined gradient color range, such as Blue to White
Inputs:
dValue = value being passed-in that is within the specified Min/Max range of values
dMin = Starting value for the gradient range, where the nFromColor is displayed
dMax = Ending value for the gradient range, where the nToColor is displayed
nFromColor = Starting color of the gradient
nToColor = Ending color of the gradient
Since the gradient shading will cover up your bars you will need to plot the bars as well.
Chart SetUp
Don’t Forget To Fade Out Your Data Chart
That’s it. Like I stated earlier – I will be including things like this in the Advanced Topics edition. I should have it wrapped sometime in July or August.
SuperTrend is a trading strategy and indicator all built into one entity. There are a couple of versions floating around out there. MultiCharts and Sierra Chart both have slightly different flavors of this combo approach.
Ratcheting Trailing Stop Paradigm
This indic/strat falls into this category of algorithm. The indicator never moves away from your current position like a parabolic stop or chandelier exit. I used the code that was disclosed on Futures.io or formerly known as BigMikesTrading blog. This version differs from the original SuperTrend which used average true range. I like Big Mike’s version so it will discussed here.
Big Mike’s Math
The math for this indicator utilizes volatility in the terms of the distance the market has travelled over the past N days. This is determined by calculating the highest high of the last N days/bars and then subtracting the lowest low of last Ndays/bars. Let’s call this the highLowRange. The next calculation is an exponential moving average of the highLowRange. This value will define the market volatility. Exponential moving averages of the last strength days/bars highs and lows are then calculated and divided by two – giving a midpoint. The volatility measure (multiplied my mult) is then added to this midpoint to calculate an upper band. A lower band is formed by subtracting the volatility measure X mult from the midpoint.
Upper or Lower Channel?
If the closing price penetrates the upper channel and the close is also above the highest high of strength days/bars back (offset by one of course) then the trend will flip to UP. When the trend is UP, then the Lower Channel is plotted. Once the trend flips to DN, the upper channel will be plotted. If the trend is UP the lower channel will either rise with the market or stay put. The same goes for a DN trend – hence the ratcheting. Here is a graphic of the indicator on CL.
If you plan on using an customized indicator in a strategy it is always best to build the calculations inside a function. The function then can be used in either an indicator or a strategy.
Function Name: SuperTrend_BM
Function Type: Series – we will need to access prior variable values
if trend < 0 and trend[1] > 0 then trendDN = True; if trend > 0 and trend[1] < 0 then trendUP = True;
//ratcheting mechanism if trend > 0 then dn = maxList(dn,dn[1]); if trend < 0 then up = minList(up,up[1]);
// if trend dir. changes then assign // up and down appropriately if trendUP then up = xAvg + mult * xAvgRng; if trendDN then dn = xAvg - mult * xAvgRng;
if trend = 1 then ST = dn else ST = up;
STrend = trend;
SuperTrend_BM = ST;
SuperTrend ala Big Mike
The Inputs to the Function
The original SuperTrend did include the Strength input. This input is a Donchian like signal. Not only does the price need to close above/below the upper/lower channel but also the close must be above/below the appropriate Donchian Channels to flip the trend, Also notice we are using a numericRef as the type for STrend. This is done because we need the function to return two values: trend direction and the upper or lower channel value. The appropriate channel value is assigned to the function name and STrend contains the Trend Direction.
A Function Driver in the Form of an Indicator
A function is a sub-program and must be called to be utilized. Here is the indicator code that will plot the values of the function using: length(9), mult(1), strength(9).
// SuperTrend indicator // March 25 2010 // Big Mike https://www.bigmiketrading.com inputs: length(9), mult(1), strength(9);
vars: strend(0), st(0);
st = SuperTrend_BM(length, mult,strength,strend);
if strend = 1 then Plot1(st,"SuperTrendUP"); if strend = -1 then Plot2(st,"SuperTrendDN");
Function Drive in the form of an Indicator
This should be a fun indicator to play with in the development of a trend following approach. My version of Big Mike’s code is a little different as I wanted the variable names to be a little more descriptive.
Update Feb 28 2022
I forgot to mention that you will need to make sure your plot lines don’t automatically connect.
Can You Do This with Just One Plot1?
An astute reader brought it to my attention that we could get away with a single plot and he was right. The reason I initially used two plot was to enable the user to chose his/her own plot colors by using the Format dialog.
//if strend = 1 then Plot1(st,"SuperTrendUP"); //if strend = -1 then Plot2(st,"SuperTrendDN");
if strend = 1 then SetPlotColor(1,red); if strend = -1 then SetPlotColor(1,green);
This is my second book in the Easing Into EasyLanguage [EZNGN2EZLANG] series of books. Here are the table of contents.
Contents
Introduction
About Website Computer Code and Fonts In Print Version
Using EasyLanguage to Program on Minute Intervals?
Tutorial 14 – Why Do I Need to Use Intraday Data
Tutorial 15 – An Algorithm Template that Uses Minute Bars to Trade a Daily Bar Scheme
Tutorial 16 – Using Data2 as a Daily Bar
Tutorial 17 – Let’s Day Trade!
Tutorial 18 – Moving From Discrete Day-Trade Strategy to a Framework
Tutorial 19 – Day-Trading Continued: Volatility Based Open Range Break Out with Pattern Recognition
Tutorial 20 – Pyramiding with Camarilla
Tutorial 21 – Programming a Scale Out Scheme
Tutorial 22- Crawling Like A Bug on a Five Minute Chart
Tutorial 23 – Templates For Further Research
Appendix A-Source Code
Appendix B-Links to Video Instruction
I have included five hours of video instruction which is included via links in the book and in the supplemental resource download.
What’s In This Book
If you are not a Trend Follower, then in most cases, you will not be able to properly or accurately code and backtest your trading algorithm without the use of higher resolution data (minute bars). A very large portion of the consulting I have done over the years has dealt with converting a daily bar system to one that uses intraday data such as a 5-minute bar. Coding a daily bar system is much more simple than taking the same concept and adding it to a higher resolution (Hi-Res) chart. If you use a 100 day moving average and you apply it to a 5-minute chart you get a 100 five minute bar moving average – a big difference.
Why Do I Need To Use Hi-Res Data?
If all you need to do is calculate a single entry or exit on a daily basis and can manually execute the trades, then you can stick with daily bars. Many of the famous Trend-Following systems such as Turtle, Aberration, Aberration Plus, Andromeda, and many others fall into this category. Most CTAs use these types of systems and spend most of their efforts on accurate execution and portfolio management. These systems, until the genesis of the COVID pandemic, have struggled for many years. Some of the biggest and brightest futures fund managers had to shut their doors due to their lagging performance and elevated levels of risk in comparison to the stock market. However, if you need to know the ebb and flow of the intraday market movement to determine accurate trade entry, then intraday data is an absolute necessity. Also, if you want to automate, Hi-Res data will help too! Here is an example of a strategy that would need to know what occurs first in chronological order.
Example of a Simple Algorithm that Needs Intraday Data
If the market closes above the prior day’s close, then buy the open of the next day plus 20% of today’s range andsellShort the open of the next day minus 40% of today’s range. Use a protective stop of $500 and a profit objective of $750. If the market closes below the prior day’s close then sellShort the open of the next day minus 20% of today’s range andbuy the open of the next day plus 40% of todays range. The same trade management of profit and loss is applied as well. From the low resolution of a daily bar the computer cannot determine if the market moves up 20% or down 40% first. So the computer cannot accurately determine if a long or short is established first. And to add insult to injury, if the computer could determine the initial position accurately from a daily bar, it still couldn’t determine if the position is liquidated via a profit or a loss if both conditions could have occurred.
What About “Look Inside Bar”?
There is evidence that if the bar closes near the high and the open near the low of a daily bar, then there is a higher probability that the low was made first. And the opposite is true as well. If the market opens near the middle of the bar, then all bets are off. When real money is in play you can’t count on this type of probability or the lack thereof . TradeStation allows you to use your daily bar scheme and then Look Inside Bar to see the overall ebb and flow of the intraday movement. This function allows you to drill down to one minute bars, if you like. This helps a lot, but it still doesn’t allow you to make intraday decisions, because you are making trading decisions from the close of the prior day.
if c > c[1] then begin buy next day at open of next day + 0.2 * range stop; sellShort next day at open of next day - 0.4 * range stop; end;
setProfitTarget(750); setStopLoss(500);
Next Day Order Placement
Using setProfitTarget and setStopLoss helps increase testing accuracy, but shouldn’t you really test on a 5-minute bar just to be on the safe side.
DayTrading in Most Cases Needs Hi-Res Data
If I say buy tomorrow at open of next day and use a setStopLoss(500), then I don’t need Hi-Res data. I execute the open which is the first time stamp in the chronological order of the day. Getting stopped out will happen later and any adverse move from the open that equates to $500 will liquidate the position or the position will be liquidated at the end of the day.
However, if I say buy the high of the first 30 minutes and use the low of the first 30 minutes as my stop loss and take profits if the position is profitable an hour later or at $750, then intraday data is absolute necessity. Most day trading systems need to react to what the market offers up and only slightly relies on longer term daily bar indicators.
If Intraday Data is So Important then Why ” The Foundation Edition?”
You must learn to crawl before you can walk. And many traders don’t care about the intraday action – all they care about is where the market closed and how much money should be allocated to a given trade or position. Or how an open position needs to be managed. The concepts and constructs of EasyLanguage must be learned first from a daily bar framework before a new EL programmer can understand how to use that knowledge on a five minute bar. You cannot just jump into a five minute bar framework and start programming accurately unless you are a programmer from the start or you have a sound Foundation in EasyLanguage.
Excerpt from Hi-Res Edition
Here is an example of a simple and very popular day trading scheme. Buy 2 units on a break out and take profits on 1 unit at X dollars. Pull stop on 2nd unit to breakeven to provide a free trade. Take profit on 2nd unit or get out at the end of the day.
Conceptually this is easy to see on the chart and to understand. But programming this is not so easy. The code and video for this algorithm is from Tutorial 21 in the Hi-Res edition.
Here are the results of the algorithm on a 5 minute ES.D chart going back five years. Remember these results are the result of data mining. Make sure you understand the limitations of back-testing. You can read those here.
There are a total of 10 Tutorials and over 5 hours of Video Instruction included. If you want to expand your programming capabilities to include intraday algorithm development, including day trading, then get your copy today.
How important is a day of week analysis? Many pundits would of course state that it is very important, especially when dealing with a day trading algorithm. Others would disagree. With the increase in market efficiency maybe this study is not as important as it once was, but it is another peformance metric that can be used with others.
I am currently working on the second book in the Easing into EasyLanguage trilogy (Hi-Res Edition) and I am including this in one of the tutorials on developing a day trading template. The book, like this post, will focus on intraday data such as 5 or less minute bars. I hope to have the book finalized in late November. If you haven’t purchased the Foundation Edition and like this presentation, I would suggest picking a copy up – especially if you are new to EasyLanguage. The code for this analysis is quite simple, but it is pretty cool and can be re-used.
Day Trading Algorithms Make Things Much More Simple
When you enter and exit on the same day and you don’t need to wrap around a 00:00 (midnight) time stamp, things such as this simple snippet of code are very easy to create. The EasyLanguage built-in functions work as you would expect as well. And obtaining the first bar of the day is ultra simple. The idea here is to have five variables, one for each day of the week, and accumulate the profit that is made on each day, and at the end of the run print out the results. Three things must be known on the first bar of the new trading day to accomplish this task:
were trades taken yesterday?
how much profit was made or lost?
what was yesterday – M, T, W, R, or F?
Two Reserved Words and One Function Are Used: Total Trades, NetProfit and the DayOfWeek function.
The reserved word TotalTrades keeps track of when a trade is closed out. The second reserved word, NetProfit keeps track of total profit everytime a trade is closed out. Along with the DayOfWeek(D[1]) function you can capture all the information you need for this analysis. Here is the code. I will show it first and then explain it afterwards.
if date <> date[1] then begin myBarCount = 0; buysToday = 0;sellsToday = 0; zatr = avgTrueRange(atrLen) of data2; if totalTrades > totTrades then begin Print(d," ",t," trade out ",dayOfWeek(d[1])," ",netProfit); switch(dayOfWeek(date[1])) begin Case 1: MProf = MProf + (netProfit - begDayEquity); Case 2: TProf = TProf + (netProfit - begDayEquity); Case 3: WProf = WProf + (netProfit - begDayEquity); Case 4: RProf = RProf + (netProfit - begDayEquity); Case 5: FProf = FProf + (netProfit - begDayEquity); Default: Value1 = Value1 + 1; end; begDayEquity = netProfit; totTrades = totalTrades; end; end;
Snippet To Handle DofW Analysis on DayTrading Algorithm
Code Explanation – Switch and Case
I have used the Switch – Case construct in some of my prior posts and I can’t emphasize enough how awesome it is, and how you can cut down on the use of if – thens. This snippet only takes place on the first bar of the trading day. Since we are using day sessions we can simply compare today’s date to the prior bar’s date, and if they are different then you know you are sitting on the first intraday bar of the day. After some initial housekeeping, the first if – then checks to see if trade(s) were closed out yesterday. If totalTrades is greater than my user defined totTrades, then something happened yesterday. My totTrades is updated to totalTrades after I am done with my calculations. The switch keys off of the DayOfWeek function. Remember you should account for every possible outcome of the variable inside the switch expression. In the case of the DayOfWeek function when know:
Monday
Tuesday
Wednesday
Thursday
Friday
Notice I am passing Date[1] into the function, because I want to know the day of the week of yesterday. After the Switch and its associated expression you have a Begin statement. Each outcome of the expression is preceded withthe keyword Case followed by a colon (:). Any code associated with each distinct result of the expression is sandwiched between Case keywords. So if the day of week of yesterday is 1 or Monday then MProf accumulates the change in the current NetProfit and the begDayEquity (beginning of the yesterday’s NetProfit) variable. So, if the equity at the beginning of yesterday was $10,000 and there was a closed out trade and the current NetProfit is $10,500 then $500 was made by the end of the day yesterday. This exact calculation is used for each day of the week and stored in the appropriate day of the week variable:
MProf – Monday
TProf – Tuesday
WProf – Wednesday
RProf – Thursday
FProf – Friday
You might ask why RProf for Thursday? Well, we have already used TProf for Tuesday and Thursday contains an “R”. This is just my way of doing it, but you will find this often in code dealing with days of the week. Every Switch should account for every possible outcome of the expression its keying off of. Many times you can’t always know ahead of time all the possible outcomes, so a Default case should be used as an exception. It is not necessary and it will not kick an error message if its not there. However, its just good programming to account for everything. Once the Switch is concluded begDayEquity and totTrades are updated for use the following day.
Here is the code that prints out the results of the DayOfWeek Analysis
if d = 1211027 and t = 1100 then begin print(d," DOW Analysis "); print("Monday : ",MProf); print("Tuesday : ",TProf); print("Wednesday : ",WProf); print("Thursday : ",RProf); print("Friday : ",FProf);
end;
Printing The Results of DofW Analysis
The printout occurs on October 27, 2021 at 11 AM. Here is my analysis of a day trading algorithm I am working on, tested over the last two years on 5 minute bars of the @ES.D
Looks like it does. These results were derived from one of the Tutorials in The Hi-Res edition of EZ-NG-N2-EZ-LANG trilogy. I should have it availabe at Amazon some time in late November. Of course if you have any questions just email me @ george.p.pruitt@gmail.com.
Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!
Take Advantage of George's Black Friday Special until Christmas
George Pruitt’s Easing into EasyLangauge – Academy
A video-based approach to teaching EasyLanguage. Learn at your own pace.
Module #1
and Pattern Smasher 2024 too!
From the creator of the bestselling Easing into EasyLanguage series comes his latest project – Easing into EasyLanguage Academy. In this introductory course, George shows you to program a George Taylor Technique into a day trading system. You will start with a blank slate and learn everything you need to take advantage of Taylor’s Buy and Short – day techniques. Give the gift the keeps on giving – knowledge.
Can You Program This Trading Strategy?
Imagine this: On a buy day, you want to:
Enter: Place a buy order for tomorrow if the market:
Trades a certain amount below today’s low, and
Then travels back up to today’s low.
Protect: Use a protective stop at tomorrow’s low (before the buy stop is triggered).
Risk Manage: If the entry and exit levels are too large, limit your risk to a predefined amount.
Profit Secure: When a specific profit level is reached, implement a ratcheting trailing stop to lock in a percentage of the maximum open trade equity.
Time Manage: If still in the trade at a specific time of day, exit the position.
PURCHASE NOW AND GET PATTERN SMASHER 2024 FOR FREE!
Learn how to do this and then pick intelligent and robust paremeter sets.s
Get the Pattern Smasher Cheat Code to create this strategy. This is a 4 Pattern relationship based on the last three day’s closing relationships. You can learn more at George’s Digital Store.