Here is some code I have been working on. I will go into detail on the code a little later. But this is how you monitor re-entering at a better price after taking a profit. The problem with taking profits on longer term trend following systems is that the logic that got you into the position is probably still true and you will notice your algorithm will re-enter in the same direction. So you need to inform your algorithm not to re-enter until a certain condition is met. In this example, I only re-enter at a better price if the condition that got me into the trade is still valid.
Okay let’s see how I was able to add some eloquence to the brute force approach to this pyramiding algorithm. The original code included multiple entry directives and a ton of hard coded numerical values. So let me show you how I was able to refine the logic/code and in doing so make it much more flexible. We might lose a little bit of the readability, but we can compensate by using extra commentary.
First off, let’s add flexibility by employing input variables. In this case, we need to inform the algorithm the distance from the open to add additional positions and the max number of entries allowed for the day.
Now we need to set somethings up for the first bar of the day. Comparing the date of today with the date of yesterday is a good way to do this.
Here is a neat way to keep track of the number of entries as they occur throughout the trading day. Remember the function EntriesToday(date) will not provide the information we need.
If the last bar’s mp is not equal to the current bar’s mp then and mp is not equal to zero then we know we have added on another entry. Okay now let’s think about eliminating the “brute force” approach.
Instead of placing multiple order entry directives I only want to use one with a variable stop level. This stop level will be guided by the variable SellMult. We start the day with a wacky sell stop level and then calculate it based on the SellMult variable and PyramidDistance input.
So on the first bar of the day the sellStop = openD(0) – sellMult * pyramidDistance or sellStop = openD(0) – 1 * 5. Or 5 handles below the open. Note you an change the pyramidDistance input and make it three to match the previous examples.
Ok, we need to tell the computer to turn off the ability to place orders if one of two things happens: 1) we have reached the maxDailyEntries or 2) time >= sess1EndTime. You could make the time to stop entering trades an input as well. If neither criteria applies then place an order to sellShort at our sellStop level. If price goes below our sell stop level then we know we have been filled and the new sellStop level needs to be recalculated. See how we use a calculation to adapt the stop level with a single order placement directive? This is where the eloquence comes into play. QED.
Now you code the opposite side and then see if you can make money (hypothetically speaking of course) with it. If you think about it, why does this not work. And the not so obvious reason is that it trades too much. Other than trading too much it makes perfect sense – buy or sell by taking a nibbles at the market. If the market takes off then take a big bite. The execution costs of the nibbles are just way too great. So we need to think of a filtering process to determine when it is either better to buy or sell or when to trade at all. Good Luck with this ES [emini S&P ]day trading algorithm!
Sorry for the delay in getting this up on the web. Here is the flip side of the pyramiding day trade scheme from the buy side perspective. I simply flipped the rules. In some cases, to keep the programming a little cleaner I like to keep the buy and sellShort logic in two separate strategies. So with this chart make sure you insert both strategies.
And here is the code:
Check out the latest video on Pyramiding.
Here is the finalized tutorial on building the pyramiding ES-day-trade system that was presented in the last post.
I will admit this video should be half as long as the end result. I get a bit long-winded. However, I think there are some good pointers that should save you some time when programming a similar system.
Here is the final code from the video:
What we learned here:
- can’t use entriesToday(date) to determine last entry price
- must use logic to not issue an order to execute on the first bar of the next day
- mp = marketPosition * currentContracts is powerful stuff!
In the next few days, I will publish the long side version of this code and also a more eloquent approach to the programming that will allow for future modifications and flexibility.
Let me know how it works out for you.
Take this code and add some filters to prevent trading every day or a filter to only allow long entries!
Would you like to learn how to do this? Check back over the next few days and I will show you to do it. Warning: its not straightforward as it seems – some tricks are involved. Remember to sign up for email notifications of new posts.
UPDATE: I have recorded an introductory webcast on how to program this pyramiding scheme. This webcast is Part 1 and illustrates how to brainstorm and start thinking/programming about a problem. Part 1 introduces some concepts that show how you can use and adapt some of EasyLanguage built-in reserved words and functions. I start from the perspective of a somewhat beginning EasyLanguage programmer – one that knows enough to maybe not get the problem solved, but at least get the ball rolling. The final code may not look anything like the code I present in Part 1. However it is sometimes important to go down the wrong trail so that you can learn the limitations of a programming language. Once you know the limitations, you can go about programming workarounds and fixes. I hope you enjoy Part 1 I should have Part 2 up soon. Don’t be too critical, this is really the first webcast I have recorded. You’ll notice I repeat myself and I refer to one function input as a subscript. Check it out: https://youtu.be/ip-DyyKpOTo
I had a request recently to publish the EasyLanguage code for my Dynamic Moving Average system. This system tries to solve the problem of using an appropriate length moving average that will keep you out of the chop. The adaptive engine utilizes market volatility and increases moving average lengths as volatility increases and decreases moving average lengths as volatility decreases. Its had some success, but the adaptive engine has not truly solved the problem. The logic is pretty straightforward and can be modified to use different types of adaptive engines.
This concept may be considered advanced and only used by pure programmers, but that is not the case at all. A Hash Table is simply a table that is indexed by a function. The function acts like the post office – it sends the data to the correct slot in the table. I utilized this data structure because I wanted to know the closing prices for the past fifteen years for the “1stThuJan” (first Thursday of January.) This, of course, would require some programming and I could simply store the values in an array. However, what if I wanted to know the closing prices for the “3rdFriMar?” I would have to spend more time and re-code, right? What if I changed my mind again. Instead, as we programmers often do, I wanted to be able to pull the data for any instance of “Week, Day Of Week, Month.” This is where a table structure comes in handy. With this table, I can query it and find out the average yearly closing prices for the “1stMonSep” or the “4thFriJuly” or the “3rdWedApr ” on a rolling year by year basis. Why would you want this you might ask? Would it be helpful to know the price change from the “2ndMonMar” to the subsequent “2ndMonMar” on a rolling basis? What if the average price change is 10%. You could use this information to make sure you always buy on this particular day. That is if you believe in this form of analysis.
Here’s how I created a table that stores the closing prices for the past 15 years for each entry in the table. Remember each row value only comes up once a year. You only have one “1stMonJan” in a calendar year. So the first part of the problem was simple, create a table that can store the closing prices with all the different combinations like the “1stTueJan” for the past fifteen years. The second part of creating the post office like function that places the correct closing price in the right row was a little more difficult, but not much. Here’s how I did it.
As I said earlier, a Hash Table is a very simple concept and very useful as well! For some of you out there, I just want to make sure that you know that I am not talking about a device to keep your cannabis off of the floor;-) All kidding aside, go ahead and take a look at the table below. Notice how it stores the closing prices of all the possible occurrences of Week, Day Of Week, Month. Column 1 is the key or Hash Index value. You will need this key to unlock the data for that particular row. Column 2 shows the number of years that the data was collected. Column 3 and on are the closing prices for that particular day across the years. Once you have the data collected you can do anything your heart desires with it.
|Table Index||Num. Years||Close 1||Close 2||Close 3||Close 4||Close 5||Close 6|
Sounds cool – so let’s do it!
Step 1: Calculate the size of the table.
Each month consists of 4.25 weeks (52/12). Because of this, you can have up to five occurrences of any given day of the week inside of a month – five Mondays, Tuesdays, etc., So we must build the table big enough to handle five complete weeks for each month. Since there are 5 days in a week and 5 weeks in a month (not really but plan on it) and 12 months in a year, the table must contain at least 300 rows ( 5 X 5 X 12.) Since we don’t know how many years of data that we might want to collect we could make the arrays dynamic, but I want to keep things simple so I will reserve space for 100 years. Overkill?
Step 2: Use measurements from Step 1 to construct the container and create an addressing function.
The container is easy just dimension a 2-d array. A 2-d array is a table whereas a 1-d array is a list. A spreadsheet is an example of a 2-d array. Just make the table big enough to hold the data. Remember the key component to the Hash Table is not what it can hold, but the ability to quickly reference the data. Just like your home, we need to create a unique address for each of the three hundred rows so the right mail, er data can be delivered or stored. This is really quite simple – we know we need a distinctive address and we know we need 300 of them. Like the table above we can create a unique address in the form of “1stMonJan.” This is a nine character string. This string can easily represent the 300 different addresses. We start with “1stMonJan” and end with “5thFriDec.” These values most consist of only nine characters. I could have done the same thing using an integer value to represent each address. “1stMonJan” could also be represented with 10101. The “3rdFriDec” would be 30512. I liked the string approach because the addresses are instantly recognizable with little or no translation. So we need to get to typing, right? Always remember if you are doing something redundant a computer can do the chore and do it quicker. Just a quick note here. I designed the table ahead of time with the values in column 1 already filled in. I could have done it more dynamically, but creating a data structure and filling in as much information before can save time on the programming side.
Instead of typing each unique address into the table, let’s let the computer do it for us. Remember, Easylanguage has some cool string manipulation tools and with a little bit of cleverness, you can create the 300 unique addresses in one fell swoop. The following code creates an array (list) of all of the possible combinations of “Week, Day Of Week, Month.” There are 100 lines of code here, don’t freak out! It’s mostly redundant. I used a Finite State Machine and Easylanguage’s Switch – Case programming structure. So you are learning about Hash Tables, Hash Indices, Finite State Machines, and Switch-Case programming in one post. And here, all you want is a winning trading system. Well, they are hard to come by and you need as many tools at your disposal to unlock the Holy Grail. This is just one way to come up with the address values.
Here is a brief overview of this code. The switch statement requires matching case statements. In this machine, there are 6 different states. Based on whatever the current state happens to be, the computer executes that block of code. If the state is 1, then the block of code encapsulated with case(1) is executed. All other code is ignored. I start building the array by executing all of the “1st”‘s in January – “1stMonJan, 1stTueJan, 1stWedJan, 1stThuJan, and 1stFriJan.” The nine character strings are built using concatenation. In Easylanguage and most other languages you can add strings together: “Cat” + “Dog” = “CatDog.” So I take the string “1st” + “Mon” + “Jan” to form the string “1stMonJan.” I store the three characters for the day of the week and the three characters for the month in simple arrays. After the fifth “1st”, I transition to state 2 and start working on all the “2nd”‘s. Eventually the machine switches into 6th gear, er uh I mean state. If month count is less than twelve, we gear down all the way back down to state 1 and start the process again for the month of February. The machine finally turns off after month counter exceeds 12. The Hash Index is completed; we have a unique address for the 300 rows. In Part 2 I will show how to map the Hash Index onto the Hash Table and how to store the necessary information. Finally, we will create an indicator using the data pulled from the table.
Or this one?
Obviously the first one. Even though it had a substantial draw down late in the test. What if I told you that the exact same system logic generated both curves? Here is the EasyLanguage code for this simple system.
This algorithm relies heavily on needing to know which occurred first: the high or the low of the day. The second chart tells the true story because it looks inside the daily bar to see what really happened. The first chart uses an algorithm to try to determine which happened first and applies this to the trades. In some instances, the market looks like it opens then has a slight pull back and then goes up all day. As a result the system buys and holds the trade through the close and onto the next day, but in reality the market opens, goes up and triggers a long entry, then retraces and you get stopped out. What was a nice winner turns into a bad loss. Here is an example of what might have happened during a few trades:
Nice flow – sold, bought, sold, bought, sold again and finally a nice profit. But this is what really happened:
Sold, bought, reversed short on same day and stopped out on same day. Then sold and reversed long on same day and finally sold and took profit. TradeStation’s Look Inside Bar feature helps out when your system needs to know the exact path the market made during the day. In many cases, simply clicking this feature to on will take care of most of your testing needs. However, this simple algorithm needs to place or replace orders based on what happens during the course of the day. With daily bars you are sitting on the close of the prior day spouting off orders. So once the new day starts all of your orders are set. You can’t see this initially on the surface, because it seems the algorithm is so simple. Here is another consequence of day bar testing when the intra-day market movement is paramount:
Here the computer is doing exactly what you told it! Sell short and then take a profit and sell short 25% of the ATR below the open. Well once the system exited the short it realized it was well below the sell entry point so it immediately goes short at the exact same price (remember TS doesn’t allow stop limit orders). You told the computer that you wanted to be short if the market moves a certain amount below the open. These were the orders that were place on yesterday’s close This may not be exactly what you wanted, right? You probably wanted to take the profit and then wait for the next day to enter a new trade. Even if you did want to still be short after the profit level was obtained you wouldn’t want to exit and then reenter at the same price (practically impossible) and be levied a round-turn slip and commission. You could fiddle around with the code and try to make it work, but I guarantee you that a system like this can only be tested properly on intra-day data. Let’s drop down to a lower time frame, program the system and see what the real results look like:
Looks very similar to the daily bar chart with Look Inside Bar turned on. However, it is different. If you wan’t to gauge a systems potential with a quick program, then go ahead and test on daily bars with LIB turned on. If it shows promise, then invest the time and program the intra-day version just to validate your results. What do you mean spend the time? Can’t you simply turn your chart from daily bars to five minute bars and be done with it. Unfortunately no! You have to switch paradigms and this requires quite a bit more programming. Here is our simple system now in EasyLanguage:
Here is a validation that Look Inside Bar does work:
This is the trade from June 1st. Scroll back up to the second chart where LIB is turned on.
Camarilla – A group of confidential, often scheming advisers; a cabal.
An attentive reader of this blog, Walter Baker, found some typos in my code. I have corrected them in the code section – if you have used this code make sure you copy and paste the code in its entirety into your EasyLanguage editor and replace your prior version.
I wanted to elaborate on the original version of Camarilla. The one that users have been downloading from this website is pure reversion version. The Camarilla Equation was by created by Nick Scott, a bond day trader, in 1989. The equation uses just yesterday’s price action to project eight support/resistance price levels onto today’s trading action. These levels, or advisers, as the name of the equation suggests provides the necessary overlay to help predict turning points as well as break outs. Going through many charts with the Camarilla indicator overlay it is surprising how many times the market does in fact turn at one of these eight price levels. The equations that generate the support/resistance levels are mathematically simple:
Resistance #4 = Close + Range * 1.1 / 2;
Resistance #3 = Close + Range * 1.1/4;
Resistance #2 = Close + Range * 1.1/6;
Resistance #1 = Close + Range * 1.1/12;
Support #1 = Close – Range * 1.1/12;
Support #2 = Close – Range * 1.1/6;
Support #3 = Close – Range * 1.1/4;
Support #4 = Close – Range * 1.1/2;
The core theory behind the equation and levels is that prices have a tendency to revert to the mean. Day trading the stock indices would be easy if price broke out and continued in that direction throughout the rest of the day. We all know that “trend days” occur very infrequently on a day trade basis; most of the time the indices just chop around without any general direction. This is where the Camarilla can be effective. Take a look at the following chart [ ES 5-minute day session] where the indicator is overlaid. and how the strategy was able to take advantage of the market’s indecisiveness. This particular example shows the counter-trend nature of the Camarilla. The original Camarilla looked at where the market opened to make a trading decision. The chart below is an adapted version of the one I send out when one registers on for the download. I thought it would be a good idea to show the original that incorporates a break out along with the counter trend mechanism. I will go over the code in the next post. You can copy the code below and paste directly into you EasyLanguage editor.
Original Camarilla rules:
- If market opens between R3 and R4 go with the break out of R4. This is the long break out part of the strategy.
- If market opens between R3 and S3 then counter trend trade at the R3 level. In other words, sell short at R3. If the market moves down, then buy S3. As you can see this is the mean reversion portion of the strategy.
- If market open between S3 and S4 go with the break out of S4 – the short break out method.
- Stops are placed in the following manner:
- If long from a R4 break-out, then place stop at R3.
- If short from a S4 break-out, then place stop at S3.
- If long from a R3 countertrend, then place stop at R4.
- If short from a S3 countertrend, then place stop at S4.
- Profit objectives can be placed at opposite resistance/support levels:
- If short from a R3 countertrend, then take profits at S1, S2, or S3.
- If long from a S3 countertrend, then take profits at R1, R2, or R3.
Profit objectives for all trades can be a dollar, percent of price of ATR multiple.
Well it happened again. I had four analysis techniques open in my TradeStation Development Environment and my TS crashed and when I went back to work after restarting they were all garbage. The easiest way to back up your code is to have NotePad open and while working on your EasyLanguage copy and past your code into a NotePad file. Do this in stages and if you like you can keep different revisions. If you don’t want to keep revisions just select all and replace with the code you are copying from the TDE. Make sure you copy your final changes so that you can archive this in a separate folder and store it on your computer, flash drive or the cloud. Remember TradeStation stores your analysis techniques in one big library glob. If that glob gets corrupted and you don’t back up your TradeStation periodically, then you run a chance of losing all of your hard work. So definitely back up TradeStation automatically using their software and also back up your coding in a NotePad file.