Category Archives: Complete EasyLanguage Systems

Tracking Last EntryPrice While Pyramiding on Minute Bars

EasyLanguage’s EntryPrice Doesn’t Cut the Mustard

In writing the Hi-Res edition of Easing Into EasyLanguage I should have included this sample program.  I do point out the limitations of the EntryPrice keyword/function in the book.  But recently I was tasked to create a pyramiding scheme template that used minute bars and would initiate a position with N Shares and then pyramid up to three times by adding on N Shares at the last entry price + one 10 -Day ATR measure as the market moves in favor of the original position.  Here is an example of just such a trade.

Pyramid 3 Times After Initial Trade Entry. Where’s the EntryPrice?

EntryPrice only contains the original entry price.  So every time you add on a position, the EntryPrice doesn’t reflect this add on price.  I would like to be able to index into this keyword/function and extract any EntryPrice.  If you enter at the market, then you can keep track of entry prices because a market order is usually issued from an if-then construct:

//Here I can keep track of entry prices because I know
//exactly when and where they occur.

if c > c[1] and value1 > value2 then
begin
buy("MarketOrder") next bar at market;
lastEntryPrice = open of next bar;
end;
Last Entry Price tracking is easy if using Market Orders

But what if you are using a stop or limit order.  You don’t know ahead of time where one of these types of orders will hit up.  It could be the next bar or it could be five bars later or who knows.

AvgEntryPrice Makes Up for the Weakness of EntryPrice

AvgEntryPrice is a keyword/function that  returns the average of the entries when pyramiding.  Assume you buy at 42.00 and pyramid the same number of shares at 46.50 – AvgEntryPrice will be equal to (42.00 + 46.50) / 2 = 44.25.  With this information you can determine the two entry prices.  You already know the original price.  Take a look at this code.

// remember currentShares and avgEntryPrice ARE EasyLanguage Keywords/Functions
if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",totShorts," ",avgEntryPrice," ",entryPriceSums);
end;
end;
Calculating the true LastEntryPrice

Remember currentShares is a keyword/function and it is immediately updated when more shares are added or taken off.  CurShares is my own variable where I keep track of the prior  currentShares , so if currentShares (real number of shares) is greater than the prior curShares (currentShares) then I know 100%, a position has been pyramided as long the the mp stays the same.  If currentShares increases and mp stays constant, then you can figure out the last entry price where the pyramid takes place.  First you tick totShorts up by 1.  If currentShares > initShares, then you know you are pyramiding so

lastEntryPrice = totShorts * avgEntryPrice – entryPriceSums

Don’t believe me.  Let’s test it.  Remember original entry was 42.00 and the add on was at 46.50.  TotShorts now equals 2.

  1. Initial entryPrice = 42.00 so entryPriceSums is set to 42.00
  2. After pyramiding avgEntryPrice is set to 44.25
  3. lastEntryPrice = 2 * 44.25 – 42.00 = 46.50
  4. entryPriceSums is then set to 42.00 + 46.50 or 88.50

So every time you add on a position, then you flow through this logic and you can keep track of the actual last entry price even if it is via a limit or stop order.

But wait there is more.  This post is also a small glimpse into what I will be writing about in the Easing Into EasyLanguage:  Advanced Topics.  This system definitely falls into what I discussed in the Hi-Res Edition.  Here is where we tip over into Advanced Topics.  The next book is not about creating dialogs or trading apps using OOEL (object oriented EasyLanguage), but we do use some of those topics to do some rather complicated back testing things.

Now that we know how to calculate the lastEntryPrice wouldn’t it be really cool if we could keep track of all of the entryPrices during the pyramid stream.   If I have pyramided four times, I would like to know entryPrice 1, entryPrice 2, entryPrice 3 and entryPrice 4.

EntryPrice Vector

Dr. VectorLove or How I Learned to Stop Worrying and Love Objects

I have discussed vectors before but I really wanted to discuss them more.  Remember Vectors are just lists or arrays that don’t need all the maintenance.  Yes you have to create them which can be a pain, but once you learn and forget it twenty times it starts to sink in.  Or just keep referring back to this web page.


Using elsystem.collections;

vars: Vector entryPriceVector(Null);

once Begin
entryPriceVector = new Vector;
end;
The Bare Minimum to Instantiate a Vector
  1. Type – “Using elsystem.collections; “
  2. Declare entryPriceVector as a Vector and set it equal to Null
  3. Use Once and instantiate entryPriceVector by using the keyword new < object type>;

A Vector is part of elsystem’s collection objects.  Take a look at this updated code,

if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceVector.push_back(lastEntryPrice);
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",entryPrice," ",entryPrice(1)," ",totShorts," ",avgEntryPrice," ",entryPriceSums," ",entryPriceVector.back() astype double," ",entryPriceVector.count asType int);
if not(entryPriceVector.empty()) then
begin
for m = 0 to entryPriceVector.count-1
begin
print(entryPriceVector.at(m) astype double);
end;
end;
end;
end;
LastEntryPrice and Pushing It onto the Vector and Then Printing Out the Vector

After the lastEntryPrice is calculated it is pushed onto the entryPriceVector using the function (method same thing but it is attached to the Vector class).push_back(lastEntryPrice);

entryPriceVector.push_back(lastEntryPrice);

So every time a new lastEntryPrice is calculated it is pushed onto the Vector at the back end.  Now if the entryPriceVector is not empty then we can print its contents by looping and indexing into the Vector.

if not(entryPriceVector.empty()) then
begin
     for m = 0 to entryPriceVector.count-1
     begin
          print(entryPriceVector.at(m) astype double);
     end;
end;
Looping through a Vector and Printing Out its Contents

Remember if you NOT a boolean value then it turns it to off/on or just the opposite of the boolean valueIf entryPriceVector is not empty then proceed.  entryPriceVector.count holds the number of values stuffed into the vectorYou can index into the Vector by using .at(m),  If you want to print out the value of the Vector .at(m), then you will need to typecast the Vector object as what ever it is holding.  We know we are pushing numbers with decimals (double type) onto the Vector so we know we can evaluate them as a double type.  Just remember you have to do this when printing out the values of the Vector.

Okay you can see where we moved into an Advanced Topics area with this code.  But it really becomes useful when trying to overcome some limitations of EasyLanguage.  Remember keep an eye open for Advanced Topics sometime in the Spring.

Easing Into EasyLanguage: Hi-Res Edition Now Available

Hi-Res Is Now Available

Easing Into EasyLanguage : The Hi-Res Edition

The Hi-Res Edition of Easing Into EasyLanguage

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 and sellShort 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 and buy 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

From Tutorial 21 – Put 2 Units on, Take Profit on 1 Unit, Pull Stop to Break Even on 2nd Unit

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.

No Execution Costs Included! Please read backtesting disclaimer.

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.

 

The Foundation Edition – First Book In Easing Into EasyLanguage

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.

The Cover of my latest book. The first in the series.

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!

Here is the link to buy the book now!

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.

If You Can’t Go Forward, Then Go Backward [Back To The Future]

Calculate MAE/MFE 30 Bars after A Signal

A very astute reader of this blog brought a snippet of code that looks like EasyLanguage and sort of behaves like it, but not exactly.  This code was presented on the exceptional blog of Quant Trader posted by Kahler Philipp.  He used some of the ideas from  Dave Bergstrom.

Equilla Programming Language

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.

 

 

 

 

 

Converting Method() To Function – MultiCharts

MultiCharts Doesn’t Support Methods

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?

Create A New Function – Call It DayOfWeekAnalysis

inputs: weekArray[n](numericArrayRef);

vars: mp(0);
var: tradeProfit(0);
mp = marketPosition;

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.

Function Properties – AutoDetect Selected

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.

array: weekArray[5](0);
vars: mp(0),newTrade(false);

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.

 

 

EasyLanguage Programming Workshop Part 1: 2D Array, Print Format, and Loops

Storing Trades for Later Use in a 2D Array

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.

  1. trdEntryPrice (0) – column zero – yes we can have a 0 col. and row
  2. trdEntryDate(1)
  3. trdExitPrice (2)
  4. trdExitDate(3)
  5. trdID(4)
  6. trdPos(5)
  7. trdProfit(6)
  8. 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.

arrays: tradeStruct[10000,7](0);

vars: trdEntryPrice (0),
trdEntryDate(1),
trdExitPrice (2),
trdExitDate(3),
trdID(4),
trdPos(5),
trdProfit(6),
trdCumuProfit(7);
2D array and its 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.

Shadow System

stb = highest(h,20);
sts = lowest(l,20);
stb1 = highest(h[1],20);
sts1 = lowest(l[1],20);

buy("Sys-L") 1 contract next bar at stb stop;
sellShort("Sys-S") 1 contract next bar at sts stop;

mp = marketPosition*currentContracts;
totTrds = totalTrades;

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 arraymEntryPrice = 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.

		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);

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.

 

PrintLog OutPut

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 Do I Need to Test with Intraday Data

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
  • Allow only 1 long and 1 short entry per day
  • Get out at the end of the day

Simple Code for the System

value1 = .2 * average(Range,5);
value2 = value1 * 5;

Buy next bar at open of next bar + value1 stop;
sellShort next bar at open of next bar - value1 stop;

setProfitTarget(value2*bigPointValue);
setStopLoss(value2/2*bigPointValue);
setExitOnClose;
Simplified Daily Bar DayTrade System using ES.D Daily
Daily Bar Using 5 min Look Inside Bar

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.

What Really Happened – Bot – Shorted – Stopped Out

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:

Cannot Sneak a Peek with Data2

That should do it for the long side, right?

Didn’t work quite 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!

Correct Execution!

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.

vars: buysToday(0),shortsToday(0),curTotTrades(0),mp(0),tradeZoneTime(False);


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;

setProfitTarget(value2*bigPointValue);
setStopLoss(value2/2*bigPointValue);
setExitOnClose;
Proper Code to Replicate the Daily Bar System with Accuracy

Here’s a few trade examples to prove our code works.

Looks Right!

Okay the code worked but did the system?

Uh? NO!

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.

Wow! Awesome! Holy Grail Uncovered. Venalicius Cave!

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.

You Start and End at the Same Place. But What A Ride. Yikes!

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.

Daily Bar Ratcheting Stop and Conditional Optimization

Happy New Year!  My First Post of 2021!

In this post I simply wanted to convert the intraday ratcheting stop mechanism that I previously posted into a daily bar mechanism.  Well that got me thinking of how many different values could be used as the amount to ratchet.  I came up with three:

I have had requests for the EasyLanguage in an ELD – so here it is – just click on the link and unZip.

RATCHETINGSTOPWSWITCH

Ratcheting Schemes

  • ATR of N days
  • Fixed $ Amount
  • Percentage of Standard Deviation of 20 Days

So this was going to be a great start to a post, because I was going to incorporate one of my favorite programming constructs : Switch-Case.  After doing the program I thought wouldn’t it be really cool to be able to optimize over each scheme the ratchet and trail multiplier as well as the values that might go into each scheme.

In scheme one I wanted to optimize the N days for the ATR calculation.  In scheme two I wanted to optimize the $ amount and the scheme three the percentage of a 20 day standard deviation.  I could do a stepwise optimization and run three independent optimizations – one for each scheme.  Why not just do one global optimization you might ask?  You could but it would be a waste of computer time and then you would have to sift through the results.  Huh?  Why?  Here is a typical optimization loop:

Scheme Ratchet Mult Trigger Mult Parameter 1
1 : ATR 1 1 ATR (2)
2 : $ Amt 1 1 ATR (2)
3 : % of Dev. Amt 1 1 ATR (2)
1 : ATR 2 1 ATR (2)
2 : $ Amt 2 1 ATR (2)

Notice when we switch schemes the Parameter 1 doesn’t make sense.  When we switch to $ Amt we want to use a $ Value as Parameter 1 and not ATR.  So we could do a bunch of optimizations across non sensical values, but that wouldn’t really make a lot of sense.  Why not do a conditional optimization?  In other words, optimize only across a certain parameter range based on which scheme is currently being used.  I knew there wasn’t an overlay available to use using standard EasyLanguage but I thought maybe OOP,  and there is an optimization API that is quite powerful.  The only problem is that it was very complicated and I don’t know if I could get it to work exactly the way I wanted.

EasyLanguage is almost a full blown programming language.  So should I not be able to distill this conditional optimization down to something that I could do with such a powerful programming language?  And the answer is yes and its not that complicated.  Well at least for me it wasn’t but for beginners probably.  But to become a successful programmer you have to step outside your comfort zones, so I am going to not only explain the Switch/Case construct (I have done this in earlier posts)  but incorporate some array stuff.

When performing conditional optimization there are really just a few things you have to predefine:

  1. Scheme Based Optimization Parameters
  2. Exact Same Number of Iterations for each Scheme [starting point and increment value]
  3. Complete Search Space
  4. Total Number of Iterations
  5. Staying inside the bounds of your Search Space

Here are the optimization range per scheme:

  • Scheme #1 – optimize number of days in ATR calculation – starting at 10 days and incrementing by 2 days
  • Scheme #2 – optimize $ amounts – starting at $250 and incrementing by $100
  • Scheme #3 – optimize percent of 20 Bar standard deviation – starting at 0,25 and incrementing by 0.25

I also wanted to optimize the ratchet and target multiplier.  Here is the base code for the daily bar ratcheting system with three different schemes.  Entries are based on penetration of 20 bar highest/lowest close.

inputs: 
ratchetMult(2),trailMult(2),
volBase(True),volCalcLen(20),
dollarBase(False),dollarAmt(250),
devBase(False),devAmt(0.25);


vars:longMult(0),shortMult(0);
vars:ratchetAmt(0),trailAmt(0);
vars:stb(0),sts(0),mp(0);
vars:lep(0),sep(0);



if volBase then
begin
ratchetAmt = avgTrueRange(volCalcLen) * ratchetMult;
trailAmt = avgTrueRange(volCalcLen) * trailMult;
end;
if dollarBase then
begin
ratchetAmt =dollarAmt/bigPointValue * ratchetMult;
trailAmt = dollarAmt/bigPointValue * trailMult;
end;
if devBase then
begin
ratchetAmt = stddev(c,20) * devAmt * ratchetMult;
trailAmt = stddev(c,20) * devAmt * trailMult;
end;


if c crosses over highest(c[1],20) then buy next bar at open;
if c crosses under lowest(c[1],20) then sellshort next bar at open;

mp = marketPosition;
if mp <> 0 and mp[1] <> mp then
begin
longMult = 0;
shortMult = 0;
end;


If mp = 1 then lep = entryPrice;
If mp =-1 then sep = entryPrice;


// Okay initially you want a X point stop and then pull the stop up
// or down once price exceeds a multiple of Y points
// longMult keeps track of the number of Y point multiples of profit
// always key off of lep(LONG ENTRY POINT)
// notice how I used + 1 to determine profit
// and - 1 to determine stop level

If mp = 1 then
Begin
If h >= lep + (longMult + 1) * ratchetAmt then longMult = longMult + 1;
Sell("LongTrail") next bar at (lep + (longMult - 1) * trailAmt) stop;
end;

If mp = -1 then
Begin
If l <= sep - (shortMult + 1) * ratchetAmt then shortMult = shortMult + 1;
buyToCover("ShortTrail") next bar (sep - (shortMult - 1) * trailAmt) stop;
end;
Daily Bar Ratchet System

This code is fairly simple.  The intriguing inputs are:

  • volBase [True of False] and  volCalcLen [numeric Value]
  • dollarBase [True of False] and  dollarAmt [numeric Value]
  • devBase [True of False] and devAmt [numeric Value]

If volBase is true then you use the parameters that go along with that scheme.  The same goes for the other schemes.  So when you run this you would turn one scheme on at a time and set the parameters accordingly.  if I wanted to use dollarBase(True) then I would set the dollarAmt to a $ value.  The ratcheting mechanism is the same as it was in the prior post so I refer you back to that one for further explanation.

So this was a pretty straightforward strategy.  Let us plan out our optimization search space based on the different ranges for each scheme.  Since each scheme uses a different calculation we can’t simply optimize across all of the different ranges – one is days, and the other two are dollars and percentages.

Enumerate

We know how to make TradeStation loop based on the range of a value.  If you want to optimize from $250 to $1000 in steps of $250, you know this involves [$1000 – $250] / $250 + 1 or 3 + 1 or 4 interations.   Four loops will cover this entire search space.  Let’s examine the search space for each scheme:

  • ATR Scheme: start at 10 bars and end at 40 by steps of 2 or [40-10]/2 + 1 = 16
  • $ Amount Scheme: start at $250 and since we have to have 16 iterations [remember # of iterations have to be the same for each scheme] what can we do to use this information?  Well if we start $250 and step by $100 we cover the search space $250, $350, $450, $550…$1,750.  $250 + 15 x 250.  15 because $250 is iteration 1.
  • Percentage StdDev Scheme:  start at 0.25 and end at 0.25 + 15 x 0.25  = 4

So we enumerate 16 iterations to a different value.  The easiest way to do this is to create a map.  I know this seems to be getting hairy but it really isn’t.  The map will be defined as an array with 16 elements.  The array will be filled with the search space based on which scheme is currently being tested.  Take a look at this code where I show how to define an array of 16 elements and introduce my Switch/Case construct.

array: optVals[16](0);

switch(switchMode)
begin
case 1:
startPoint = 10; // vol based
increment = 2;
case 2:
startPoint = 250/bigPointValue; // $ based
increment = 100/bigPointValue;
case 3:
startPoint = 0.25; //standard dev
increment = 0.25*minMove/priceScale;
default:
startPoint = 1;
increment = 1;
end;

vars: cnt(0),loopCnt(0);
once
begin
for cnt = 1 to 16
begin
optVals[cnt] = startPoint + (cnt-1) * increment;
end;
end
Set Up Complete Search Space for all Three Schemes

This code creates a 16 element array, optVals, and assigns 0 to each element.  SwitchMode goes from 1 to 3.

  • if switchMode is 1: ATR scheme [case: 1] the startPoint is set to 10 and increment is set to 2
  • if switchMode is 2: $ Amt scheme [case: 2] the startPoint is set to $250 and increment is set to $100
  • if switchMode is 3: Percentage of StdDev [case: 3] the startPoint is set to 0.25 and the increment is set to 0.25

Once these two values are set the following 15 values can be spawned by the these two.  A for loop is great for populating our search space.  Notice I wrap this code with ONCE – remember ONCE  is only executed at the very beginning of each iteration or run.

once
begin
   for cnt = 1 to 16
   begin
     optVals[cnt] = startPoint + (cnt-1) * increment;
   end;
end

Based on startPoint and increment the entire search space is filled out.  Now all you have to do is extract this information stored in the array based on the iteration number.

Switch(switchMode) 
Begin
Case 1:
ratchetAmt = avgTrueRange(optVals[optLoops]) * ratchetMult;
trailAmt = avgTrueRange(optVals[optLoops]) * trailMult;
Case 2:
ratchetAmt =optVals[optLoops] * ratchetMult;
trailAmt = optVals[optLoops] * trailMult;
Case 3:
ratchetAmt =stddev(c,20) * optVals[optLoops] * ratchetMult;
trailAmt = stddev(c,20) * optVals[optLoops] * trailMult;
Default:
ratchetAmt = avgTrueRange(optVals[optLoops]) * ratchetMult;
trailAmt = avgTrueRange(optVals[optLoops]) * trailMult;
end;


if c crosses over highest(c[1],20) then buy next bar at open;
if c crosses under lowest(c[1],20) then sellshort next bar at open;

mp = marketPosition;
if mp <> 0 and mp[1] <> mp then
begin
longMult = 0;
shortMult = 0;
end;


If mp = 1 then lep = entryPrice;
If mp =-1 then sep = entryPrice;


// Okay initially you want a X point stop and then pull the stop up
// or down once price exceeds a multiple of Y points
// longMult keeps track of the number of Y point multiples of profit
// always key off of lep(LONG ENTRY POINT)
// notice how I used + 1 to determine profit
// and - 1 to determine stop level

If mp = 1 then
Begin
If h >= lep + (longMult + 1) * ratchetAmt then longMult = longMult + 1;
Sell("LongTrail") next bar at (lep + (longMult - 1) * trailAmt) stop;
end;

If mp = -1 then
Begin
If l <= sep - (shortMult + 1) * ratchetAmt then shortMult = shortMult + 1;
buyToCover("ShortTrail") next bar (sep - (shortMult - 1) * trailAmt) stop;
end;
Extract Search Space Values and Rest of Code

Switch(switchMode)
Begin
Case 1:
  ratchetAmt = avgTrueRange(optVals[optLoops])ratchetMult;
  trailAmt = avgTrueRange(optVals[optLoops]) trailMult;
Case 2:
  ratchetAmt =optVals[optLoops] * ratchetMult;
  trailAmt = optVals[optLoops] * trailMult;
Case 3:
  ratchetAmt =stddev(c,20)optVals[optLoops]
ratchetMult;
  trailAmt = stddev(c,20) * optVals[optLoops] * trailMult;

Notice how the optVals are indexed by optLoops.  So the only variable that is optimized is the optLoops and it spans 1 through 16.  This is the power of enumerations – each number represents a different thing and this is how you can control which variables are optimized in terms of another optimized variable.   Here is my optimization specifications:

Opimization space

And here are the results:

Optimization Results

The best combination was scheme 1 [N-day ATR Calculation] using a 2 Mult Ratchet and 1 Mult Trail Trigger.  The best N-day was optVals[2] for this scheme.  What in the world is this value?  Well you will need to back engineer a little bit here.  The starting point for this scheme was 10 and the increment was 2 so if optVals[1] =10 then optVals[2] = 12 or ATR(12).    You can also print out a map of the search spaces.

vars: cnt(0),loopCnt(0);
once
begin
loopCnt = loopCnt + 1;
// print(switchMode," : ",d," ",startPoint);
// print(" ",loopCnt:2:0," --------------------");
for cnt = 1 to 16
begin
optVals[cnt] = startPoint + (cnt-1) * increment;
// print(cnt," ",optVals[cnt]," ",cnt-1);
end;
end;
  Scheme 1
--------------------
1.00 10.00 0.00 10 days
2.00 12.00 1.00
3.00 14.00 2.00
4.00 16.00 3.00
5.00 18.00 4.00
6.00 20.00 5.00
7.00 22.00 6.00
8.00 24.00 7.00
9.00 26.00 8.00
10.00 28.00 9.00
11.00 30.00 10.00
12.00 32.00 11.00
13.00 34.00 12.00
14.00 36.00 13.00
15.00 38.00 14.00
16.00 40.00 15.00

Scheme2
--------------------
1.00 5.00 0.00 $ 250
2.00 7.00 1.00 $ 350
3.00 9.00 2.00 $ 400
4.00 11.00 3.00 $ ---
5.00 13.00 4.00
6.00 15.00 5.00
7.00 17.00 6.00
8.00 19.00 7.00
9.00 21.00 8.00
10.00 23.00 9.00
11.00 25.00 10.00
12.00 27.00 11.00
13.00 29.00 12.00
14.00 31.00 13.00
15.00 33.00 14.00
16.00 35.00 15.00 $1750

Scheme 3
--------------------
1.00 0.25 0.00 25 % stdDev
2.00 0.50 1.00
3.00 0.75 2.00
4.00 1.00 3.00
5.00 1.25 4.00
6.00 1.50 5.00
7.00 1.75 6.00
8.00 2.00 7.00
9.00 2.25 8.00
10.00 2.50 9.00
11.00 2.75 10.00
12.00 3.00 11.00
13.00 3.25 12.00
14.00 3.50 13.00
15.00 3.75 14.00
16.00 4.00 15.00

This was a elaborate post so please email me with questions.  I wanted to demonstrate that we can accomplish very sophisticated things with just the pure and raw EasyLanguage which is a programming language itself.

A Simple Break Out Algorithm Demonstrating Time Optimization

What is Better:  30, 60, or 120 Minute Break-Out on ES.D

Here is a simple tutorial you can use as a foundation to build a potentially profitable day trading system.  Here we wait N minutes after the open and then buy the high of the day or short the low of the day and apply a protective stop and profit objective.  The time increment can be optimized to see what time frame is best to use.  You can also optimize the stop loss and profit objective – this system gets out at the end of the day.  This system can be applied to any .D data stream in TradeStation or Multicharts.

Logic Description

  1. get open time
  2. get close time
  3. get N time increment
    1. 15 – first 15 minute of day
    2. 30 – first 30 minute of day
    3. 60 – first hour of day
  4. get High and Low of day
  5. place stop orders at high and low of day – no entries late in day
  6. calculate buy and short entries – only allow one each*
  7. apply stop loss
  8. apply profit objective
  9. get out at end of day if not exits have occurred

Optimization Results [From 15 to 120 by 5 minutes] on @ES.D 5 Minute Chart – Over Last Two Years

Optimization of Time: Look How the # Trades Decrease as the Time Increment Increases

Simple Orbo EasyLanguage

I threw this together rather quickly in a response to a reader’s question.  Let me know if you see a bug or two.  Remember once you gather your stops you must allow the order to be issued on every subsequent bar of the trading day.  The trading day is defined to be the time between timeIncrement and endTradeMinB4Close.  Notice how I used the EL function calcTime to calculate time using either a +positive or -negative input.  I want to sample the high/low of the day at timeIncrement and want to trade up until endTradeMinB4Close time.  I use the HighD and LowD functions to extract the high and low of the day up to that point.  Since I am using a tight stop relative to today’s volatility you will see more than 1 buy or 1 short occurring.  This happens when entry/exit occurs on the same bar and MP is not updated accordingly.  Somewhere  hidden in this tome of a blog you will see a solution for this.  If you don’t want to search I will repost it tomorrow.


//Optimizing Time to determine a simple break out
//Only works on .D data streams
Inputs: timeIncrement(15),endTradeMinB4Close(-15),stopLoss$(500),profTarg$(1000);

vars: firstBarTime(0),lastBarTime(0),buyStop(0),shortStop(0),
calcStopTime(0),quitTradeTime(0),buysToday(0),shortsToday(0),mp(0);

firstBarTime = sessionStartTime(0,1);
lastBarTime = sessionEndTime(0,1);

calcStopTime = calcTime(firstBarTime,timeIncrement);
quitTradeTime = calcTime(lastBarTime,endTradeMinB4Close);



If time = calcStopTime then
begin
buyStop = HighD(0);
shortStop = LowD(0);
buysToday = 0;
shortsToday = 0;
End;

if time >= calcStopTime and time < quitTradeTime then
begin
if buysToday = 0 then Buy next bar at buyStop stop;
if shortsToday = 0 then Sell short next bar at shortStop stop;
end;

mp = marketPosition;

If mp = 1 then buysToday = 1;
If mp = -1 then shortsToday = 1;

SetStopLoss(stopLoss$);
setProfitTarget(profTarg$);
setExitOnClose;
Orbo EasyLanguage Code

 

 

 

The Complete Turtle EasyLanguage [Well About as Close as You Can Get]

The Complete Turtle EasyLanguage – Almost!

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.

Turtle Performance on Crude 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!

Can You Program This?

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 currentContracts contracts 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.

Turn Pyramiding ON
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.

TURTLELTLFUNCTEST