Before the days of OOEL and more advanced data structures, such as vectors, you had to work with multidimensional arrays.
The problem with arrays is you have to do all the housekeeping whereas with vectors the housekeeping is handled internally. Yes, vectors in many cases would be the most efficient approach, but if you are already using Multi-D arrays, then mixing the two could become confusing. So stick with the arrays for now and progress into vectors at your leisure.
Recreate the CCI indicator with Multi-D Array
This exercise is for demonstration purposes only as the existing CCI function works just fine. However, when you are trying out something new or in this case an application of a different data structure (array) its always great to check your results against a known entity. If your program replicates the known entity, then you know that you are close to a solution. The CCI function accesses data via the globalHigh, Low and Close data streams and then applies a mathematical formula to derive a result. <
Derive Your Function First
Create the function first by prototyping what the function will need in the formal parameter list (funciton header). The first thing the function will need is the data – here is what it will look like.
OHLCArray[1,1] =1210903.00 // DATE
OHLCArray[1,2] = 4420.25 // OPEN
OHLCArray[1,3] = 4490.25 // HIGH
OHLCArray[1,4] = 4410.25 // LOW
OHLCArray[1,5] = 4480.75 // CLOSE
OHLCArray[2,1] =1210904.00 // DATE
OHLCArray[2,2] = 4470.25 // OPEN
OHLCArray[2,3] = 4490.25 // HIGH
OHLCArray[2,4] = 4420.25 // LOW
OHLCArray[2,5] = 4440.75 // CLOSE
Visualize 2-D Array as a Table
Column 1
Column 2
Column 3
Column 4
Column 5
1210903
44202.25
4490.25
4410.25
4480.75
1210904
4470.25
4490.25
4420.25
4440.76
The CCI function is only concerned with H, L, C and that data is in columns 3, 4, 5. If you know the structure of the array before you program the function, then you now which columns or fields you will need to access. If you don’t know the structure beforehand , then that information would need to be passed into the function as well. Let us assume we know the structure. Part of the housekeeping that I mentioned earlier was keeping track of the current row where the latest data is being stored. This “index” plus the length of the CCI indicator is the last two things we will need to know to do a proper calculation.
CCI_2D Function Formal Parameter List
// This function needs data, current data row, and length // Notice how I declare the OHLCArray using the dummy X and Y // Variable - this just tells TradeStation to expect 2-D array // ------------------ // | | // * * inputs: OHLCArray[x,y](numericArray), currentRow(numericSimple), length(numericSimple); // *** // ||| //---------------------------- // Also notice I tell TradeStation that the array is of type numeric // We are not changing the array but if we were, then the type would be // numericArrayRef - the actual location in memory not just a copy
CCI_2D Formal Parameter List
2-D Array Must Run Parallels with Actual Data
The rest of the function expects the data to be just like the H, L, C built-in data – so there cannot be gaps. This is very important when you pack the data and you will see this in the function driver code a.k.a an indicator. The data needs to align with the bars. Now if you are using large arrays this can slow things down a bit. You can also shuffle the array and keep the array size to a minimum and I will post how to do this in a post later this week. The CCI doesn’t care about the order of the H,L,C as long as the last N element is the latest values.
if AvgDev = 0 then CCI_2D = 0 else CCI_2D = ( value1 + value2 + value3 - Mean ) / ( .015 * AvgDev ) ;
CCI-2D Function
This function could be streamlined, but I wanted to show you how to access the different data values with the currentRow variable and columns 3, 4, and 5. I extract these data and store them in Values variables. Notice the highlighted line where I check to make sure there are enough rows to handle the calculation. If you try to access data before row #1, then you will get an out of bounds error and a halt to program execution.
Notice lines 16 and 17 where I am plotting both function results – my CCI_2D and CCI. Also notice how I increment numRows on each bar – this is the housekeeping that keeps that array synched with the chart. In the following graphic I use 14 for CCI_2D and 9 for the built-in CCI.
Now the following graphic uses the same length parameters for both functions. Why did just one line show up?
Make Your Unique Coding Replicate a Known Entity – If You Can
Here is where your programming is graded. The replication of the CCI using a 2-D Array instead of the built-in H, L, C data streams, if programmed correctly, should create the exact same results and it does, hence the one line. Big Deal right! Why did I go through all this to do something that was already done? Great programming is not supposed to re-invent the wheel. And we just did exactly that. But read between the lines here. We validated code that packed a 2-D array with data and then passed it to a function that then accessed the data correctly and applied a known formula and compared it to a known entity. So now you have re-usable code for passing a 2-D array to a function. All you have to do is use the template and modify the calculations. Re-inventing the wheel is A-Okay if you are using it as a tool for validation.
Hello to All! I just published the first book in this series. It is the Foundation Edition and is designed for the new user of EasyLanguage or for those you would like to have a refresher course. There are 13 total tutorials ranging from creating Strategies to PaintBars. Learn how to create your own functions or apply stops and profit objectives. Ever wanted to know how to find an inside day that is also a Narrow Range 7 (NR7?) Now you can, and the best part is you get over 4 HOURS OF VIDEO INSTRUCTION – one for each tutorial. Each video is created by yours truly and Beau my trustworthy canine companion. I go over every line of code to really bring home the concepts that are laid out in each tutorial. All source code is available too, and if you have TradeStation, so are the workspaces. Plus you can always email George for any questions. george.p.pruitt@gmail.com.
If you like the information on my blog, but find the programming code a little daunting, then go back and build a solid foundation with the Foundation Edition. It starts easy but moves up the Learning Curve at comfortable pace. On sale now for $24.95 at Amazon.com. I am planning on having two more advanced books in the series. The second book, specifically designed for intraday trading and day-trading, will be available this winter. And the third book, Advanced Topics, will be available next spring.
Pick up your copy today – e-Book or Paperback format!
Let me know if you buy either format and I will send you a PDF of the source code – just need proof of purchase. With the PDF you can copy and paste the code. After you buy the book come back here to the Easing Into EasyLanguage Page and download the ELD and workspaces.
The theory behind the code is quite interesting and I haven’t gotten into it thoroughly, but will do so in the next few days. The code was derived from Trade-Signal’s Equilla Programming Language. I looked at the website and it seems to leans heavily on an EasyLanguage like syntax, but unlike EZLang allows you to incorporate indicators right in the Strategy. It also allows you, and I might be wrong, to move forward in time from a point in the past quite easily. The code basically was fed a signal (+1,0,-1) and based on this value progressively moved forward one bar at a time (over a certain time period) and calculated the MAE and MFE (max. adverse/favorable excursion for each bar. The cumulative MAE/MFE were then stored in a BIN for each bar. At the end of the data, a chart of the ratio between the MAE and MFE was plotted.
EasyLanguage Version
I tried to replicate the code to the best of my ability by going back in time and recording a trading signal and then moving Back to The Future thirty bars, in this case, to calculated and store the MAE/MFE in the BINS.
Simple Moving Average Cross Over Test
After 100 bars, I looked back 30 bars to determine if the price was either greater than or less than the 21 day moving average. Let’s assume the close was greater than the 21 day moving average 30 days ago, I then kept going backward until this was not the case. In other words I found the bar that crossed the moving average. It could have been 5 or 18 or whatever bars further back. I stored that close and then started moving forward calculating the MAE/MFE by keeping track of the Highest Close and Lowest Close made during 30 bar holding period. You will see the calculation in the code. Every time I got a signal I accumulated the results of the calculations for each bar in the walk forward period. At the end of the chart or test I divided each bars MFE by its MAE and plotted the results. A table was also created in the Print Log. This code is barely beta, so let me know if you see any apparent errors in logic or calculations.
inputs: ilb(30); //ilb - initial lookback vars: lb(0),signal(0),btf(0),mf(0),ma(0),hh(0),ll(99999999),arrCnt(0),numSigs(0); arrays : mfe[40](0),mae[40](0); lb = ilb; if barNumber > 100 then begin signal = iff(c[ilb] > average(c[ilb],21),1,-1); // print(d," signal ",signal," ",ilb); if signal <> signal[1] then begin numSigs = numSigs + 1; // keep track of number of signals // print("Inside loop ", date[ilb]," ",c[ilb]," ",average(c[ilb],21)); if signal = 1 then // loop further back to get cross over begin // print("Inside signal = 1 ",date[lb]," ",c[lb]," ",average(c[lb],21)); while c[lb] > average(c[lb],21) begin lb = lb + 1; end; // print("lb = ",lb); end;
if signal = -1 then // loop further back to get cross over begin // print("Inside signal = -1 ",date[lb]," ",c[lb]," ",average(c[lb],21)); while c[lb] < average(c[lb],21) begin lb = lb + 1; end; end; lb = lb - 1;
hh = 0; ll = 999999999;
arrCnt = 0; for btf = lb downto (lb - ilb) //btf BACK TO FUTURE INDEX begin mf=0; ma=0; hh=maxList(c[btf],hh); // print("inside inner loop ",btf," hh ",hh," **arrCnt ",arrCnt); ll=minList(c[btf],ll); if signal>0 then begin mf=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // mf long signal ma=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // ma long signal end; if signal<0 then begin ma=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // ma after short signal mf=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // mf after short signal end; // print(btf," signal ",signal," mf ",mf:0:5," ma ",ma:0:5," hh ",hh," ll ",ll," close[lb] ",c[lb]); mfe[arrCnt]=mfe[arrCnt]+absValue(signal)*mf; mae[arrCnt]=mae[arrCnt]+absValue(signal)*ma; arrCnt = arrCnt + 1; end; end; end;
if lastBarOnChart then begin print(" ** MFE / MAE ** "); for arrCnt = 1 to 30 begin print("Bar # ",arrCnt:1:0," mfe / mae ",(mfe[arrCnt]/mae[arrCnt]):0:5); end;
for arrCnt = 30 downto 1 begin plot1[arrCnt](mfe[31-arrCnt]/mae[31-arrCnt]," mfe/mae "); end; end;
Back to The Future - going backward then forward
Here is an output at the end of a test on Crude Oil
** MFE / MAE ** Bar # 1 mfe / mae 0.79828 Bar # 2 mfe / mae 0.81267 Bar # 3 mfe / mae 0.82771 Bar # 4 mfe / mae 0.86606 Bar # 5 mfe / mae 0.87927 Bar # 6 mfe / mae 0.90274 Bar # 7 mfe / mae 0.93169 Bar # 8 mfe / mae 0.97254 Bar # 9 mfe / mae 1.01002 Bar # 10 mfe / mae 1.03290 Bar # 11 mfe / mae 1.01329 Bar # 12 mfe / mae 1.01195 Bar # 13 mfe / mae 0.99963 Bar # 14 mfe / mae 1.01301 Bar # 15 mfe / mae 1.00513 Bar # 16 mfe / mae 1.00576 Bar # 17 mfe / mae 1.00814 Bar # 18 mfe / mae 1.00958 Bar # 19 mfe / mae 1.02738 Bar # 20 mfe / mae 1.01948 Bar # 21 mfe / mae 1.01208 Bar # 22 mfe / mae 1.02229 Bar # 23 mfe / mae 1.02481 Bar # 24 mfe / mae 1.00820 Bar # 25 mfe / mae 1.00119 Bar # 26 mfe / mae 0.99822 Bar # 27 mfe / mae 1.01343 Bar # 28 mfe / mae 1.00919 Bar # 29 mfe / mae 0.99960 Bar # 30 mfe / mae 0.99915
Ratio Values over 30 Bins
Using Arrays for Bins
When newcomers start to program EasyLanguage and encounter arrays it sometimes scares them away. They are really easy and in many cases necessary to complete a project. In this code I used two 40 element or bins arrays MFE and MAE. I only use the first 30 of the bins to store my information. You can change this to 30 if you like, and when you start using a fixed array it is best to define them with the exact number you need, so that TradeStation will tell you if you step out of bounds (assign value to a bin outside the length of the array). To learn more about arrays just search my blog. The cool thing about arrays is you control what data goes in and what you do with that data afterwards. Anyways play with the code, and I will be back with a more thorough explanation of the theory behind it.
Methods are wonderful tools that are just like functions, but you can put them right into your Analysis Technique and they can share the variables that are defined outside the Method. Here is an example that I have posted previously. Note: This was in response to a question I got on Jeff Swanson’s EasyLanguage Mastery Facebook Group.
{'(' Expected line 10, column 12 } //the t in tradeProfit. // var: double tradeProfit;
vars: mp(0); array: weekArray[5](0);
method void dayOfWeekAnalysis() {method definition} var: double tradeProfit; begin If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue; If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue; weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit; end;
Buy next bar at highest(high,9)[1] stop; Sellshort next bar at lowest(low,9)[1] stop;
mp = marketPosition; if mp <> mp[1] then dayOfWeekAnalysis(); If lastBarOnChart then Begin print("Monday ",weekArray[1]); print("Tuesday ",weekArray[2]); print("Wednesday ",weekArray[3]); print("Thursday ",weekArray[4]); print("Friday ",weekArray[5]); end;
PowerEditor Cannot Handle Method Syntax
Convert Method to External Function
Sounds easy enough – just remove Method and copy code and put into a new function. This method keeps track of Day Of Week Analysis. So what is the function going to return? It needs to return the performance metrics for Monday, Tuesday, Wednesday, Thursday and Friday. That is five values so you can’t simply assign the Function Name a single value – right?
tradeProfit = -999999999; If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue; If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue; if tradeProfit <> -999999999 then weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit; print(d," ",mp," ",mp[1]," ",dayOfWeek(entryDate(1)),tradeProfit," ",entryDate," ",entryDate(1)," ",entryPrice(0)," ",entryPrice(1));
DayOfWeekAnalysis = 1;
Simple Function - What's the Big Deal
Looks pretty simple and straight forward. Take a look at the first line of code. Notice how I inform the function to expect an array of [n] length to passed to it. Also notice I am not passing by value but by reference. Value versus reference – huge difference. Value is a scalar value such as 5, True or a string. When you pass by reference you are actually passing a pointer to actual location in computer memory – once you change it – it stays changed and that is what we want to do. When you pass a variable to an indicator function you are simple passing a value that is not modified within the body of the function. If you want a function to modify and return more than one value you can pass the variable and catch it as a numericRef. TradeStation has a great explanation of multiple output functions.
Multiple Output Function per EasyLanguage
Some built-in functions need to return more than a single value and do this by using one or more output parameters within the parameter list. Built-in multiple output functions typically preface the parameter name with an ‘o’ to indicate that it is an output parameter used to return a value. These are also known as ‘input-output’ parameters because they are declared within a function as a ‘ref’ type of input (i.e. NumericRef, TrueFalseRef, etc.) which allows it output a value, by reference, to a variable in the EasyLanguage code calling the function.
I personally don’t follow the “O” prefacing, but if it helps you program then go for it.
Series Function – What Is It And Why Do I Need to Worry About It?
A series function is a specialized function that refers to a previous function value within its calculations. In addition, series functions update their value on every bar even if the function call is placed within a conditional structure that may not be true on a given bar. Because a series function automatically stores its own previous values and executes on every bar, it allows you to write function calculations that may be more streamlined than if you had to manage all of the resources yourself. However, it’s a good idea to understand how this might affect the performance of your EasyLanguage code.
Seems complicated, but it really isn’t. It all boils down to SCOPE – not the mouthwash. See when you call a function all the variables inside that function are local to that particular function – in other words it doesn’t have a memory. If it changes a value in the first call to the function, it has amnesia so the next time you call the function it forgets what it did just prior – unless its a series function. Then it remembers. This is why I can do this:
If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue; If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
I Can Refer to Prior Values - It Has A Memory
Did you notice TradeProfit = -99999999 and then if it changes then I accumulate it in the correct Day Bin. If I didn’t check for this then the values in the Day Bin would be accumulated with the values returned by EntryPrice and ExitPrice functions. Remember this function is called on every bar even if you don’t call it. I could have tested if a trade occurred and passed this information to the function and then have the function access the EntryPrice and ExitPrice values. This is up to your individual taste of style. One more parameter for readability, or one less parameter for perhaps efficiency?
This Is A Special Function – Array Manipulator and Series Type
When you program a function like this the EasyLanguage Dev. Environment can determine what type of function you are using. But if you need to change it you can. Simply right click inside the editor and select Properites.
How Do You Call Such a “Special” Function?
The first thing you need to do is declare the array that you will be passing to the function. Use the keyword Array and put the number of elements it will hold and then declare the values of each element. Here I create a 5 element array and assign each element zero. Here is the function wrapper.
Buy next bar at highest(high,9)[1] stop; Sellshort next bar at lowest(low,9)[1] stop; mp = marketPosition; newTrade = False; //if mp <> mp[1] then newTrade = true;
value1 = dayOfWeekAnalysis(weekArray); If lastBarOnChart then Begin print("Monday ",weekArray[1]); print("Tuesday ",weekArray[2]); print("Wednesday ",weekArray[3]); print("Thursday ",weekArray[4]); print("Friday ",weekArray[5]); end;
Wrapper Function - Notice I only Pass the Array to the Function
Okay that’s how you convert a Method from EasyLanguage into a Function. Functions are more re-uasable, but methods are easier. But if you can’t use a method you now know how to convert one that uses Array Manipulation and us a “Series” type.
Since this is part 1 we are just going to go over a very simple system: SAR (stop and reverse) at highest/lowest high/low for past 20 days.
A 2D Array in EasyLanguage is Immutable
Meaning that once you create an array all of the data types must be the same. In a Python list you can have integers, strings, objects whatever. In C and its derivatives you also have a a data structure (a thing that stores related data) know as a Structure or Struct. We can mimic a structure in EL by using a 2 dimensional array. An array is just a list of values that can be referenced by an index.
array[1] = 3.14
array[2] = 42
array[3] = 2.71828
A 2 day array is similar but it looks like a table
array[1,1], array[1,2], array[1,3]
array[2,1], array[2,2], array[2,3]
The first number in the pair is the row and the second is the column. So a 2D array can be very large table with many rows and columns. The column can also be referred to as a field in the table. To help use a table you can actually give your fields names. Here is a table structure that I created to store trade information.
trdEntryPrice (0) – column zero – yes we can have a 0 col. and row
trdEntryDate(1)
trdExitPrice (2)
trdExitDate(3)
trdID(4)
trdPos(5)
trdProfit(6)
trdCumuProfit(7)
So when I refer to tradeStruct[0, trdEntryPrice] I am referring to the first column in the first row.
This how you define a 2D array and its associate fields.
In EasyLanguage You are Poised at the Close of a Yesterday’s Bar
This paradigm allows you to sneak a peek at tomorrow’s open tick but that is it. You can’t really cheat, but it also limits your creativity and makes things more difficult to program when all you want is an accurate backtest. I will go into detail, if I haven’t already in an earlier post, the difference of sitting on Yesterday’s close verus sitting on Today’s close with retroactive trading powers. Since we are only storing trade information when can use hindsight to gather the information we need.
Buy tomorrow at highest(h,20) stop;
SellShort tomorrow at lowest(l,20) stop;
These are the order directives that we will be using to execute our strategy. We can also run a Shadow System, with the benefit of hindsight, to see where we entered long/short and at what prices. I call it a Shadow because its all the trades reflected back one bar. All we need to do is offset the highest and lowest calculations by 1 and compare the values to today’s highs and lows to determine trade entry. We must also test the open if a gap occurred and we would have been filled at the open. Now this code gets a bit hairy, but stick with it.
if mPos <> 1 then begin if h >= stb1 then begin if mPos < 0 then // close existing short position begin mEntryPrice = tradeStruct[numTrades,trdEntryPrice]; mExitPrice = maxList(o,stb1); tradeStruct[numTrades,trdExitPrice] = mExitPrice; tradeStruct[numTrades,trdExitDate] = date; mProfit = (mEntryPrice - mExitPrice) * bigPointValue - mCommSlipp; cumuProfit += mProfit; tradeStruct[numTrades,trdCumuProfit] = cumuProfit; tradeStruct[numTrades,trdProfit] = mProfit; print(d+19000000:8:0," shrtExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0); print("-------------------------------------------------------------------------"); end; numTrades +=1; mEntryPrice = maxList(o,stb1); tradeStruct[numTrades,trdID] = 1; tradeStruct[numTrades,trdPOS] = 1; tradeStruct[numTrades,trdEntryPrice] = mEntryPrice; tradeStruct[numTrades,trdEntryDate] = date; mPos = 1; print(d+19000000:8:0," longEntry ",mEntryPrice:4:5); end; end; if mPos <>-1 then begin if l <= sts1 then begin if mPos > 0 then // close existing long position begin mEntryPrice = tradeStruct[numTrades,trdEntryPrice]; mExitPrice = minList(o,sts1); tradeStruct[numTrades,trdExitPrice] = mExitPrice; tradeStruct[numTrades,trdExitDate] = date; mProfit = (mExitPrice - mEntryPrice ) * bigPointValue - mCommSlipp; cumuProfit += mProfit; tradeStruct[numTrades,trdCumuProfit] = cumuProfit; tradeStruct[numTrades,trdProfit] = mProfit; print(d+19000000:8:0," longExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0); print("---------------------------------------------------------------------"); end; numTrades +=1; mEntryPrice =minList(o,sts1); tradeStruct[numTrades,trdID] = 2; tradeStruct[numTrades,trdPOS] =-1; tradeStruct[numTrades,trdEntryPrice] = mEntryPrice; tradeStruct[numTrades,trdEntryDate] = date; mPos = -1; print(d+19000000:8:0," ShortEntry ",mEntryPrice:4:5); end; end;
Shadow System - Generic forany SAR System
Notice I have stb and stb1. The only difference between the two calculations is one is displaced a day. I use the stb and sts in the EL trade directives. I use stb1 and sts1 in the Shadow System code. I guarantee this snippet of code is in every backtesting platform out there.
All the variables that start with the letter m, such as mEntryPrice, mExitPrice deal with the Shadow System. Theyare not derived from TradeStation’s back testing engine only our logic. Lets look at the first part of just one side of the Shadow System:
if mPos <> 1 then begin if h >= stb1 then begin if mPos < 0 then // close existing short position begin mEntryPrice = tradeStruct[numTrades,trdEntryPrice]; mExitPrice = maxList(o,stb1); tradeStruct[numTrades,trdExitPrice] = mExitPrice; tradeStruct[numTrades,trdExitDate] = date; mProfit = (mEntryPrice - mExitPrice) * bigPointValue - mCommSlipp; cumuProfit += mProfit; tradeStruct[numTrades,trdCumuProfit] = cumuProfit; tradeStruct[numTrades,trdProfit] = mProfit; print(d+19000000:8:0," shrtExit ",mEntryPrice:4:5," ",mExitPrice:4:5," ",mProfit:6:0," ",cumuProfit:7:0); print("-------------------------------------------------------------------------"); end;
mPos and mEntryPrice and mExitPrice belong to the Shadow System
if mPos <> 1 then the Shadow Systems [SS] is not long. So we test today’s high against stb1 and if its greater then we know a long position was put on. But what if mPos = -1 [short], then we need to calculate the exit and the trade profit and the cumulative trade profit. If mPos = -1 then we know a short position is on and we can access its particulars from the tradeStruct 2D array. mEntryPrice = tradeStruct[numTrades,trdEntryPrice]. We can gather the other necessary information from the tradeStruct [remember this is just a table with fields spelled out for us.] Once we get the information we need we then need to stuff our calculations back into the Structure or table so we can regurgitate later. We stuff date in to the following fields trdExitPrice, trdExitDate, trdProfit and trdCumuProfit in the table.
Formatted Print: mEntryPrice:4:5
Notice in the code how I follow the print out of variables with :8:0 or :4:5? I am telling TradeStation to use either 0 or 5 decimal places. The date doesn’t need decimals but prices do. So I format that so that they will line up really pretty like.
Now that I take care of liquidating an existing position all I need to do is increment the number of trades and stuff the new trade information into the Structure.
The same goes for the short entry and long exit side of things. Just review the code. I print out the trades as we go along through the history of crude. All the while stuffing the table.
If LastBarOnChart -> Regurgitate
On the last bar of the chart we know exactly how many trades have been executed because we were keeping track of them in the Shadow System. So it is very easy to loop from 0 to numTrades.
if lastBarOnChart then begin print("Trade History"); for arrIndx = 1 to numTrades begin value20 = tradeStruct[arrIndx,trdEntryDate]; value21 = tradeStruct[arrIndx,trdEntryPrice]; value22 = tradeStruct[arrIndx,trdExitDate]; value23 = tradeStruct[arrIndx,trdExitPrice]; value24 = tradeStruct[arrIndx,trdID]; value25 = tradeStruct[arrIndx,trdProfit]; value26 = tradeStruct[arrIndx,trdCumuProfit];
print("---------------------------------------------------------------------"); if value24 = 1 then begin string1 = buyStr; string2 = sellStr; end; if value24 = 2 then begin string1 = shortStr; string2 = coverStr; end; print(value20+19000000:8:0,string1,value21:4:5," ",value22+19000000:8:0,string2, value23:4:5," ",value25:6:0," ",value26:7:0); end; end;
Add 19000000 to Dates for easy Translation
Since all trade information is stored in the Structure or Table then pulling the information out using our Field Descriptors is very easy. Notice I used EL built-in valueXX to store table information. I did this to make the print statements a lot shorter. I could have just used tradeStruct[arrIndx, trdEntry] or whatever was needed to provide the right information, but the lines would be hard to read. To translate EL date to a normal looking data just add 19,000,000 [without commas].
If you format your PrintLog to a monospaced font your out put should look like this.
Why Would We Want to Save Trade Information?
The answer to this question will be answered in Part 2. Email me with any other questions…..
Why Can’t I Just Test with Daily Bars and Use Look-Inside Bar?
Good question. You can’t because it doesn’t work accurately all of the time. I just default to using 5 minute or less bars whenever I need to. A large portion of short term, including day trade, systems need to know the intra day market movements to know which orders were filled accurately. It would be great if you could just flip a switch and convert a daily bar system to an intraday system and Look Inside Bar(LIB) is theoretically that switch. Here I will prove that switch doesn’t always work.
Daily Bar System
Buy next bar at open of the day plus 20% of the 5 day average range
SellShort next at open of the day minus 20% of the 5 day average range
If long take a profit at one 5 day average range above entryPrice
If short take a profit at one 5 day average range below entryPrice
If long get out at a loss at 1/2 a 5 day average range below entryPrice
If short get out at a loss at 1/2 a 5 day average range above entry price
Simplified Daily Bar DayTrade System using ES.D Daily
Looks great with just the one hiccup: Bot @ 3846.75 and the Shorted @ 3834.75 and then took nearly 30 handles of profit.
Now let’s see what really happened.
Intraday Code to Control Entry Time and Number of Longs and Shorts
Not an accurate representation so let’s take this really simple system and apply it to intraday data. Approaching this from a logical perspective with limited knowledge about TradeStation you might come up with this seemingly valid solution. Working on the long side first.
//First Attempt
if d <> d[1] then value1 = .2 * average(Range of data2,5); value2 = value1 * 5; if t > sess1startTime then buy next bar at opend(0) + value1 stop; setProfitTarget(value2*bigPointValue); setStopLoss(value2/2*bigPointValue); setExitOnClose;
First Simple Attempt
This looks very similar to the daily bar system. I cheated a little by using
if d <> d[1] then value1 = .2 * average(Range of data2,5);
Here I am only calculating the average once a day instead of on each 5 minute bar. Makes things quicker. Also I used
if t > sess1StartTime then buy next bar at openD(0) + value1 stop;
I did that because if you did this:
buy next bar at open of next bar + value1 stop;
You would get this:
That should do it for the long side, right?
So now we have to monitor when we can place a trade and monitor the number of long and short entries.
How does this look!
So here is the code. You will notice the added complexity. The important things to know is how to control when an entry is allowed and how to count the number of long and short entries. I use the built-in keyword/function totalTrades to keep track of entries/exits and marketPosition to keep track of the type of entry.
Take a look at the code and you can see how the daily bar system is somewhat embedded in the code. But remember you have to take into account that you are stepping through every 5 minute bar and things change from one bar to the next.
if d <> d[1] then begin curTotTrades = totalTrades; value1 = .2 * average(Range of data2,5); value2 = value1 * 5; buysToday = 0; shortsToday = 0; tradeZoneTime = False; end;
mp = marketPosition;
if totalTrades > curTotTrades then begin if mp <> mp[1] then begin if mp[1] = 1 then buysToday = buysToday + 1; if mp[1] = -1 then shortsToday = shortsToday + 1; end; if mp[1] = -1 then print(d," ",t," ",mp," ",mp[1]," ",shortsToday); curTotTrades = totalTrades; end; if t > sess1StartTime and t < sess1EndTime then tradeZoneTime = True;
if tradeZoneTime and buysToday = 0 and mp <> 1 then buy next bar at opend(0) + value1 stop;
if tradeZoneTime and shortsToday = 0 and mp <> -1 then sellShort next bar at opend(0) - value1 stop;
Proper Code to Replicate the Daily Bar System with Accuracy
Here’s a few trade examples to prove our code works.
Okay the code worked but did the system?
Conclusion
If you need to know what occurred first – a high or a low in a move then you must use intraday data. If you want to have multiple entries then of course your only alternative is intraday data. This little bit of code can get you started converting your daily bar systems to intraday data and can be a framework to develop your own day trading/or swing systems.
Can I Prototype A Short Term System with Daily Data?
You can of course use Daily Bars for fast system prototyping. When the daily bar system was tested with LIB turned on, it came close to the same results as the more accurately programmed intraday system. So you can prototype to determine if a system has a chance. Our core concept buyt a break out, short a break out, take profits and losses and have no overnight exposure sounds good theoretically. And if you only allow 2 entries in opposite directions on a daily bar you can determine if there is something there.
A Dr. Jekyll and Mr. Hyde Scenario
While playing around with this I did some prototyping of a daily bar system and created this equity curve. I mistakenly did not allow any losses – only took profits and re-entered long.
Venalicius Cave! Don’t take a loser you and will reap the benefits. The chart says so – so its got to be true – I know right?
The same chart from a different perspective.
Moral of the Story – always look at your detailed Equity Curve. This curve is very close to a simple buy and hold strategy. Maybe a little better.
I was recently testing the idea of a short term VBO strategy on the ES utilizing very tight stops. I wanted to see if using a tight ATR stop in concert with the entry day’s low (for buys) would cut down on losses after a break out. In other words, if the break out doesn’t go as anticipated get out and wait for the next signal. With the benefit of hindsight in writing this post, I certainly felt like my exit mechanism was what was going to make or break this system. In turns out that all pre conceived notions should be thrown out when volatility enters the picture.
System Description
If 14 ADX < 20 get ready to trade
Buy 1 ATR above the midPoint of the past 4 closing prices
Place an initial stop at 1 ATR and a Profit Objective of 1 ATR
Trail the stop up to the prior day’s low if it is greater than entryPrice – 1 ATR initially, and then trail if a higher low is established
Wait 3 bars to Re-Enter after going flat – Reversals allowed
That’s it. Basically wait for a trendless period and buy on the bulge and then get it out if it doesn’t materialize. I knew I could improve the system by optimizing the parameters but I felt I was in the ball park. My hypothesis was that the system would fail because of the tight stops. I felt the ADX trigger was OK and the BO level would get in on a short burst. Just from past experience I knew that using the prior day’s price extremes as a stop usually doesn’t fair that well.
Without commission the initial test was a loser: -$1K and -$20K draw down over the past ten years. I thought I would test my hypothesis by optimizing a majority of the parameters:
ADX Len
ADX Trigger Value
ATR Len
ATR BO multiplier
ATR Multiplier for Trade Risk
ATR Multiplier for Profit Objective
Number of bars to trail the stop – used lowest lows for longs
Results
As you can probably figure, I had to use the Genetic Optimizer to get the job done. Over a billion different permutations. In the end here is what the computer pushed out using the best set of parameters.
Optimization Report – The Best of the Best
ADX – Does it Really Matter?
Take a look at the chart – the ADX is mostly in Trigger territory – does it really matter?
A Chart is Worth a 1000 Words
What does this chart tell us?
Was the parameter selection biased by the heightened level of volatility? The system has performed on the parameter set very well over the past two or three years. But should you use this parameter set going into the future – volatility will eventually settle down.
Now using my experience in trading I would have selected a different parameter set. Here are my biased results going into the initial programming. I would use a wider stop for sure, but I would have used the generic ADX values.
I would have used 14 ADX Len with a 20 trigger and risk 1 to make 3 and use a wider trailing stop. With trend neutral break out algorithms, it seems you have to be in the game all of the time. The ADX was supposed to capture zones that predicated break out moves, but the ADX didn’t help out at all. Wider stops helped but it was the ADX values that really changed the complexion of the system. Also the number of bars to wait after going flat had a large impact as well. During low volatility you can be somewhat picky with trades but when volatility increases you gots to be in the game. – no ADX filtering and no delay in re-Entry. Surprise, surprise!
Alogorithm Code
Here is the code – some neat stuff here if you are just learning EL. Notice how I anchor some of the indicator based variables by indexing them by barsSinceEntry. Drop me a note if you see something wrong or want a little further explanation.
If mp <> 1 and adx(adxLen) < adxTrig and BSE > reEntryDelay and open of next bar < BBO then buy next bar at BBO stop; If mp <>-1 and adx(adxLen) < adxTrig AND BSE > reEntryDelay AND open of next bar > SBO then sellshort next bar at SBO stop;
If mp = 1 and mp[1] <> 1 then Begin trailLongStop = entryPrice - tradeRisk; end;
If mp = -1 and mp[1] <> -1 then Begin trailShortStop = entryPrice + tradeRisk; end;
if mp = 1 then sell("L-init-loss") next bar at entryPrice - tradeRisk[barsSinceEntry] stop; if mp = -1 then buyToCover("S-init-loss") next bar at entryPrice + tradeRisk[barsSinceEntry] stop;
if mp = 1 then begin sell("L-ATR-prof") next bar at entryPrice + tradeProf[barsSinceEntry] limit; trailLongStop = maxList(trailLongStop,lowest(l,posMovTrailNumBars)); sell("L-TL-Stop") next bar at trailLongStop stop; end; if mp =-1 then begin buyToCover("S-ATR-prof") next bar at entryPrice -tradeProf[barsSinceEntry] limit; trailShortStop = minList(trailShortStop,highest(h,posMovTrailNumBars)); // print(d, " Short and trailStop is : ",trailShortStop); buyToCover("S-TL-Stop") next bar at trailShortStop stop; end;
EasyLanguage Includes a Powerful String Manipulation Library
I thought I would share this function. I needed to convert a date string (not a number per se) like “20010115” or “2001/01/15” or “01/15/2001” or “2001-01-15” into a date that TradeStation would understand. The function had to be flexible enough to accept the four different formats listed above.
String Functions
Most programming languages have functions that operate strictly on strings and so does EasyLanguage. The most popular are:
Right String (rightStr) – returns N characters from the right side of the string.
Left String (leftStr) – returns N character starting from the left side of the string
Mid String (midStr) – returns the middle portion of a string starting at a specific place in the string and advance N characters
String Length (strLen) – returns the number of characters in the string
String To Number (strToNum) – converts the string to a numeric representation. If the string has a character, this function will return 0
In String (inStr) – returns location of a sub string inside a larger string ( a substring can be just one character long)
Unpack the String
If the format is YYYYMMDD format then all you need to do is remove the dashes or slashes (if there are any) and then convert what is left over to a number. But if the format is MM/DD/YYYY format then we are talking about a different animal. So how can you determine if the date string is in this format? First off you need to find out if the month/day/year separator is a slash or a dash. This is how you do this:
If either is a non zero then you know there is a separator. The next thing to do is locate the first “dash or slash” (the search character or string). If it is located within the first four characters of the date string then you know its not a four digit year. But, lets pretend the format is “12/14/2001” so if the first dash/slash is the 3rd character you can extract the month string by doing this:
So if firstSrchStrLoc = 3 then we want to leftStr the date string and extract the first two characters and store them in mnStr. We then store what’s left of the date string in tempStr by using rightStr:
Here I pass dateString and the strLength-firstSrchStrLoc – so if the dateString is 10 characters long and the firstSrchStrLoc is 3, then we can create a tempstring by taking [10 -3 = 7 ] characters from right side of the string:
“12/14/2001” becomes “14/2001” – once that is done we can pull the first two characters from the tempStr and store those into the dyStr [day string.] I do this by searching for the “/” and storing its location in srchStrLoc. Once I have that location I can use that information and leftStr to get the value I need. All that is left now is to use the srchStrLoc and the rightStr function.
Now convert the strings to numbers and multiply their values accordingly.
DateSTrToYYYMMDD = strToNum(yrStr) X 10000-19000000 + strToNum(mnStr) X 100 + strToNum(dyStr)
To get the date into TS format I have to subtract 19000000 from the year. Remember TS represents the date in YYYMMDD format.
Now what do you do if the date is in the right format but simply includes the dash or slash separators. All you need to do here is loop through the string and copy all non dash or slash characters to a new string and then convert to a number. Here is the loop:
tempStr = ""; iCnt = 1; While iCnt <= strLength Begin If midStr(dateString,iCnt,1) <> srchStr then tempStr += midStr(dateString,iCnt,1); iCnt+=1; end; tempDate = strToNum(tempStr); DateStrToYYYMMDD = tempDate-19000000;
Here I use midStr to step through each character in the string. MidStr requires a string and the starting point and how many characters you want returned from the string. Notice I step through the string with iCnt and only ask for 1 character at a time. If the character is not a dash or slash I concatenate tempStr with the non dash/slash character. At the end of the While loop I simply strToNum the string and subtract 19000000. That’s it! Remember EasyLanguage is basically a full blown programming language with a unique set of functions that relate directly to trading.
I have seen a plethora of posts on the Turtle trading strategies where the rules and code are provided. The codes range from a mere Donchian breakout to a fairly close representation. Without dynamic portfolio feedback its rather impossible to program the portfolio constraints as explained by Curtis Faith in his well received “Way Of The Turtle.” But the other components can be programmed rather closely to Curtis’ descriptions. I wanted to provide this code in a concise manner to illustrate some of EasyLanguage’s esoteric constructs and some neat shortcuts. First of all let’s take a look at how the system has performed on Crude for the past 15 years.
If a market trends, the Turtle will catch it. Look how the market rallied in 2007 and immediately snapped back in 2008, and look at how the Turtle caught the moves – impressive. But see how the system stops working in congestion. It did take a small portion of the 2014 move down and has done a great job of catching the pandemic collapse and bounce. In my last post, I programmed the LTL (Last Trader Loser) function to determine the success/failure of the Turtle System 1 entry. I modified it slightly for this post and used it in concert with Turtle System 2 Entry and the 1/2N AddOn pyramid trade to get as close as possible to the core of the Turtle Entry/Exit logic.
Can Your Program This – sure you CAN!
I will provide the ELD so you can review at your leisure, but here are the important pieces of the code that you might not be able to derive without a lot of programming experience.
If mp[1] <> mp and mp <> 0 then begin if mp = 1 then begin origEntry = entryPrice; origEntryName = "Sys1Long"; If ltl = False and h >= lep1[1] then origEntryName = "Sys2Long"; end; if mp =-1 then begin origEntry = entryPrice; origEntryName = "Sys1Short"; If ltl = False and l <= sep1[1] then origEntryName = "Sys2Short"; end; end;
Keeping Track Of Last Entry Signal Price and Name
This code determines if the current market position is not flat and is different than the prior bar’s market position. If this is the case then a new trade has been executed. This information is needed so that you know which exit to apply without having to forcibly tie them together using EasyLanguage’s from Entry keywords. Here I just need to know the name of the entry. The entryPrice is the entryPrice. Here I know if the LTL is false, and the entryPrice is equal to or greater/less than (based on current market position) than System 2 entry levels, then I know that System 2 got us into the trade.
If mp = 1 and origEntryName = "Sys1Long" then Sell currentShares shares next bar at lxp stop; If mp =-1 and origEntryName = "Sys1Short" then buyToCover currentShares shares next bar at sxp stop;
//55 bar component - no contingency here If mp = 0 and ltl = False then buy("55BBO") next bar at lep1 stop; If mp = 1 and origEntryName = "Sys2Long" then sell("55BBO-Lx") currentShares shares next bar at lxp1 stop;
If mp = 0 and ltl = False then sellShort("55SBO") next bar at sep1 stop; If mp =-1 and origEntryName = "Sys2Short" then buyToCover("55SBO-Sx") currentShares shares next bar at sxp1 stop;
Entries and Exits
The key to this logic is the keywords currentShares shares. This code tells TradeStation to liquidate all the current shares or contracts at the stop levels. You could use currentContractscontracts if you are more comfortable with futures vernacular.
AddOn Pyramiding Signal Logic
Before you can pyramid you must turn it on in the Strategy Properties.
If mp = 1 and currentShares < 4 then buy("AddonBuy") next bar at entryPrice + (currentShares * .5*NValue) stop; If mp =-1 and currentShares < 4 then sellShort("AddonShort") next bar at entryPrice - (currentShares * .5*NValue) stop;
This logic adds positions on from the original entryPrice in increments of 1/2N. The description for this logic is a little fuzzy. Is the N value the ATR reading when the first contract was put on or is it dynamically recalculated? I erred on the side of caution and used the N when the first contract was put on. So to calculate the AddOn long entries you simply take the original entryPrice and add the currentShares * .5N. So if currentShares is 1, then the next pyramid level would be entryPrice + 1* .5N. If currentShares is 2 ,then entryPrice + 2* .5N and so on an so forth. The 2N stop trails from the latest entryPrice. So if you put on 4 contracts (specified in Curtis’ book), then the trailing exit would be 2N from where you added the 4th contract. Here is the code for that.
Liquidate All Contracts at Last Entry – 2N
vars: lastEntryPrice(0); If cs <= 1 then lastEntryPrice = entryPrice; If cs > 1 and cs > cs[1] and mp = 1 then lastEntryPrice = entryPrice + ((currentShares-1) * .5*NValue); If cs > 1 and cs > cs[1] and mp =-1 then lastEntryPrice = entryPrice - ((currentShares-1) * .5*NValue);
//If mp = -1 then print(d," ",lastEntryPrice," ",NValue);
If mp = 1 then sell("2NLongLoss") currentShares shares next bar at lastEntryPrice-2*NValue stop; If mp =-1 then buyToCover("2NShrtLoss") currentShares shares next bar at lastEntryPrice+2*NValue Stop;
Calculate Last EntryPrice and Go From There
I introduce a new variable here: cs. CS stands for currentShares and I keep track of it from bar to bar. If currentShares or cs is less than or equal to1 I know that the last entryPrice was the original entryPrice. Things get a little more complicated when you start adding positions – initially I couldn’t remember if EasyLanguage’s entryPrice contained the last entryPrice or the original – turns out it is the original – good to know. So, if currentShares is greater than one and the current bar’s currentShares is greater than the prior bar’s currentShares, then I know I added on another contract and therefore must update lastEntryPrice. LastEntryPrice is calculated by taking the original entryPrice and adding (currentShares-1) * .5N. Now this is the theoretical entryPrice, because I don’t take into consideration slippage on entry. You could make this adjustment. So, once I know the lastEntryPrice I can determine 2N from that price.
Getting Out At 2N Trailing Stop
If mp = 1 then sell("2NLongLoss") currentShares shares next bar at lastEntryPrice-2*NValue stop; If mp =-1 then buyToCover("2NShrtLoss") currentShares shares next bar at lastEntryPrice+2*NValue Stop;
Get Out At LastEntryPrice +/-2N
That’s all of the nifty code. Below is the function and ELD for my implementation of the Turtle dual entry system. You will see some rather sophisticated code when it comes to System 1 Entry and this is because of these scenarios:
What if you are theoretically short and are theoretically stopped out for a true loser and you can enter on the same bar into a long trade.
What if you are theoretically short and the reversal point would result in a losing trade. You wouldn’t record the loser in time to enter the long position at the reversal point.
What if you are really short and the reversal point would results in a true loser, then you would want to allow the reversal at that point
There are probably some other scenarios, but I think I covered all bases. Just let me know if that’s not the case. What I did to validate the entries was I programmed a 20/10 day breakout/failure with a 2N stop and then went through the list and deleted the trades that followed a non 2N loss (10 bar exit for a loss or a win.) Then I made sure those trades were not in the output of the complete system. There was quite a bit of trial and error. If you see a mistake, like I said, just let me know.
Remember I published the results of different permutations of this strategy incorporating dynamic portfolio feedback at my other site www.trendfollowingsystems.com. These results reflect the a fairly close portfolio that Curtis suggests in his book.
Last Trade Was a Loser Filter – To Use or Not To Use
Premise
A major component of the Turtle algorithm was to skip the subsequent 20-day break out if the prior was a winner. I guess Dennis believed the success/failure of a trade had an impact on the outcome of the subsequent trade. I have written on how you can implement this in EasyLanguage in prior posts, but I have been getting some questions on implementing FSM in trading and thought this post could kill two birds with one stone: 1) provide a template that can be adapted to any LTL mechanism and 2) provide the code/structure of setting up a FSM using EasyLanguage’s Switch/Case structure.
Turtle Specific LTL Logic
The Turtle LTL logic states that a trade is a loser if a 2N loss occurs after entry. N is basically an exponential-like moving average of TrueRange. So if the market moves 2N against a long or short position and stops you out, you have a losing trade. What makes the Turtle algorithm a little more difficult is that you can also exit on a new 10-day low/high depending on your position. The 10-day trailing exit does not signify a loss. Well at least in this post it doesn’t. I have code that says any loss is a loss, but for this explanation let’s just stick to a 2N loss to determine a trade’s failure.
How To Monitor Trades When Skipping Some Of Them
This is another added layer of complexity. You have to do your own trade accounting behind the scenes to determine if a losing trade occurs. Because if you have a winning trade you skip the next trade and if you skip it how do you know if it would have been a winner or a loser. You have to run a theoretical system in parallel with the actual system code.
Okay let’s start out assuming the last trade was a winner. So we turn real trading off. As the bars go by we look for a 20-Day high or low penetration. Assume a new 20-Day high is put in and a long position is established at the prior 20-Day high. At this point you calculate a 2N amount and subtract if from the theoretical entry price to obtain the theoretical exit price. So you have a theoMP (marketPosition) and a theoEX (exit price.) This task seems pretty simple, so you mov on and start looking for a day that either puts in a new 10-Day low or crosses below your theoEX price. If a new 10-Day low is put in then you continue on looking for a new entry and a subsequent 2N loss. If a 2N loss occurs, then you turn trading back on and continue monitoring the trades – turning trading off and then back on when necessary. In the following code I use these variables:
state – 0: looking for an entry or 1: looking for an exit
lep – long entry price
sep– short entry price
seekLong – I am seeking a long position
seekShort – I am seeking a short position
theoMP – theoretical market position
theoEX – theoretical exit price
lxp – long exit price
sxp – short exit price
Let’s jump into the Switch/Case structure when state = 0:
Switch(state) Begin Case 0: lep = highest(h[1],20) + minMove/priceScale; sep = lowest(l[1],20) - minMove/priceScale; If seekLong and h >= lep then begin theoMP = 1; theoEX = maxList(lep,o) - 2 * atr; // print(d," entered long >> exit at ",theoEX," ",atr); end; If seekShort and l <= sep then begin theoMP = -1; theoEX = minList(sep,o) + 2 * atr; end; If theoMP <> 0 then begin state = 1; cantExitToday = True; end;
State 0 (Finite State Set Up)
The Switch/Case is a must have structure in any programming language. What really blows my mind is that Python doesn’t have it. They claim its redundant to an if-then structure and it is but its so much easier to read and implement. Basically you use the Switch statement and a variable name and based on the value of the variable it will flow to whatever case the variable equates to. Here we are looking at state 0. In the CASE: 0 structure the computer calculates the lep and sep values – long and short entry levels. If you are flat then you are seeking a long or a short position. If the high or low of the bar penetrates it respective trigger levels then theoMP is set to 1 for long or -1 for short. TheoEX is then calculated based on the atr value on the day of entry. If theoMP is set to either a 1 or -1, then we know a trade has just been triggered. The Finite State Machine then switches gears to State 1. Since State = 1 the next Case statement is immediately evaluated. I don’t want to exit on the same bar as I entered (wide bars can enter and exit during volatile times) I use a variable cantExitToday. This variable delays the Case 1: evaluation by one bar.
State = 1 code:
Case 1: If not(cantExitToday) then begin lxp = maxList(theoEX,lowest(l[1],10)-minMove/priceScale); sxp = minList(theoEX,highest(h[1],10)+minMove/priceScale); If theoMP = 1 and l <= lxp then begin theoMP = 0; seekLong = False; if lxp <= theoEX then ltl = True Else ltl = False; end; If theoMP =-1 and h >= sxp then begin theoMP = 0; seekShort = False; if sxp >= theoEX then ltl = True else ltl = False; end; If theoMP = 0 then state = 0; end; cantExitToday = False; end;
State = 1 (Switching Gears)
Once we have a theoretical position, then we only examine the code in the Case 1: module. On the subsequent bar after entry, the lxp and sxp (long exit and short exit prices) are calculated. Notice these values use maxList or minList to determine whichever is closer to the current market action – the 2N stop or the lowest/highest low/high for the past 10-days. Lxp and sxp are assigned whichever is closer. Each bar’s high or low is compared to these values. If theoMP = 1 then the low is compared to lxp. If the low crosses below lxp, then things are set into motion. The theoMP is immediately set to 0 and seekLong is turned to False. If lxp <= a 2N loss then ltl (last trade loser) is set to true. If not, then ltl is set to False. If theoMP = 0 then we assume a flat position and switch the FSM back to State 0 and start looking for a new trade. The ltl variable is then used in the code to allow a real trade to occur.
Strategy Incorporates Our FSM Output
vars:N(0),mp(0),NLossAmt(0); If barNumber = 1 then n = avgTrueRange(20); if barNumber > 1 then n = (n*19 + trueRange)/20;
If useLTLFilter then Begin if ltl then buy next bar at highest(h,20) + minMove/priceScale stop; if ltl then sellShort next bar at lowest(l,20) -minMove/priceScale stop; end Else Begin buy next bar at highest(h,20) + minMove/priceScale stop; sellShort next bar at lowest(l,20) -minMove/priceScale stop; end;
mp = marketPosition;
If mp <> 0 and mp[1] <> mp then NLossAmt = 2 * n;
If mp = 1 then Begin Sell("LL10-LX") next bar at lowest(l,10) - minMove/priceScale stop; Sell("2NLS-LX") next bar at entryPrice - NLossAmt stop; end; If mp =-1 then Begin buyToCover("HH10-SX") next bar at highest(h,10) + minMove/priceScale stop; buyToCover("2NLS-SX") next bar at entryPrice + NLossAmt stop; end;
Strategy Code Using ltl filter
This code basically replicates what we did in the FSM, but places real orders based on the fact that the Last Trade Was A Loser (ltl.)
Does It Work – Only Trade After a 2N-Loss
Without Filter on the last 10-years in Crude Oil
With Filter on the last 10-years in Crude Oil
I have programmed this into my TradingSimula-18 software and will show a portfolio performance with this filter a little later at www.trendfollowingsystems.com.
I had to do some fancy footwork with some of the code due to the fact you can exit and then re-enter on the same bar. In the next post on this blog I will so you those machinations . With this template you should be able to recreate any last trade was a loser mechanism and see if it can help out with your own trading algorithms. Shoot me an email with any questions.
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!
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.
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.
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.
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.
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