Tag Archives: EasyLanguage

Can You Turn Failure into Success?

Have You Ever Wondered If You Just Reversed the Logic?

You have been there before. What you thought was a great trading idea turns out to be a big flop. We have all developed these types of algorithms. Then it hits you, just flip the logic and in turn the equity curve. Hold your horses! First off you have to make sure it’s not just the execution costs that is hammering the equity curve into oblivion. When testing a fresh trading idea, it is best to keep execution costs to zero. This way if your idea is a good one, but is simply backward, then you have a chance of creating something good out of something bad. I was playing around with a mean reversion day trading algorithm (on the @ES.D – day session of the mini S&P 500) that created the following equity curve.  Remember to read the disclaimer concerning hypothetical performance before proceeding reading the rest of this blog.  It is located under the DISCLAIMER – REAMDE! tab.  By reading the rest of this blog post it implies that you understand the limitations of hypothetical back testing and simulated analysis.

The pandemic created a strong mean reversion environment. In the initial stage of this research, I did not set the executions costs – they defaulted to zero. My idea was to buy below the open after the market moved down from the high of the day a certain percentage of price. Since I was going to be buying as the market was moving down, I was willing to use a wide stop to see if I could hold on to the falling knife. Short entries were just the opposite -sell short above the open after the market rallied a certain percentage of price. I wanted to enter on a hiccup. Once the market moved down a certain range from the high of the day, I wanted to enter on a stop at the high of the prior bar. I figured if the price penetrated the high of the prior five-minute bar in a down move, then it would signal an eventual rotation in the market. Again, I was just throwing pasta against the wall to see what would stick. I even came up with a really neat name for the algorithm the Rubber Band system – stretch just far enough and the market is bound to slam back. Well, there wasn’t any pasta sticking. Or was there? If I flipped the equity curve 180 degrees, then I would have a darned good strategy. All it would take is to reverse the signals, sell short when I was buying and buy when I was selling short. Instead of a mean reversion scheme, this would turn into a momentum-based strategy.

Here are the original rules.

maxCloseMinusOpen = maxList(close - todaysOpen,maxCloseMinusOpen);
maxOpenMinusClose = maxList(todaysOpen - close,maxOpenMinusClose);

if c < todaysOpen and todaysOpen-c = maxOpenMinusClose and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canBuy = True;
if c > todaysOpen and c- todaysOpen = maxCloseMinusOpen and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canShort = True;
Guts of the complete failure.

Here I measure the maximum distance from the highest close above the open and the lowest close below the open.  The distance between the two points is the range between the highest and lowest closing price of the current day.  If the close is less than today’s open, and the range between the extremes of the highest close and lowest close of the trading day is greater than stretchPercent, then an order directive to buy the next bar at the current bar’s high is issued.  The order is alive until it is filled, or the day expires.  Selling short uses the same calculations but requires the close of the current bar to be above the open.   The stretchPercent was set to 1 percent and the protective stop was set to a wide $2,000.  As you can see from the equity curve, this plan did not work except for the time span of the pandemic.  Could you optimize the strategy and make it a winning system.  Definitely.  But the 1 percent and $2000 stop seemed very logical to me.  Since we are comparing the range of the data to a fixed price of the data, then we don’t need to worry about the continuous contract distortion.  Maybe we would have to, if the market price was straddling zero.  Anyways, here is a strategy using the same entry technique, but reversed, with some intelligent trade filtering.  I figured a profit objective might be beneficial, because the stop was hit several times during the original test.

$2K was hit often!
Using some trade filtering and stop loss and profit objective on the reversal of the original strategy.

If you like the following code, make sure you check out my books at Amazon.com.  This type of code is used the Hi-Res and Day-Trading editions of the Easing_Into_Easylanguage series.

input: stretchPercent(0.01),stopLoss(1000),takeProfit(1000),
dontTradeBefore(930),dontTradeBeforeOffset(5),
dontTradeAfter(1500),dontTradeAfterOffset(5),
rangeCompressionPercent(0.75);

vars: buysToday(0),shortsToday(0),mp(0),atr(0),canBuy(False),canShort(False),canTrade(False);
vars: todaysOpen(0),maxCloseMinusOpen(0),maxOpenMinusClose(0);
if t = sessionStartTime(0,1)+barInterval Then
Begin
todaysOpen = open;
maxCloseMinusOpen = 0;
maxOpenMinusClose = 0;
buysToday = 0;
shortsToday = 0;
canTrade = False;
atr = avgTrueRange(20) of data2;
if trueRange of data2 < atr * rangeCompressionPercent Then
canTrade = True;
canBuy = False;
canShort = False;

end;

mp = marketPosition;

if mp = 1 and mp <> mp[1] then buysToday +=1;
if mp =-1 and mp <> mp[1] then shortsToday +=1;

maxCloseMinusOpen = maxList(close - todaysOpen,maxCloseMinusOpen);
maxOpenMinusClose = maxList(todaysOpen - close,maxOpenMinusClose);

if c < todaysOpen and todaysOpen-c = maxOpenMinusClose and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canShort = True;
if c > todaysOpen and c- todaysOpen = maxCloseMinusOpen and
(maxCloseMinusOpen + maxOpenMinusClose)/c >= stretchPercent Then
canBuy = True;


if canTrade and t >= calcTime(dontTradeBefore,dontTradeBeforeOffset) and
t < calcTime(dontTradeAfter,dontTradeAfterOffset) and t < sessionEndTime(0,1) Then
begin
if shortsToday = 0 and canShort = True Then
sellshort next bar at l stop;
if buysToday = 0 and canBuy = True Then
buy next bar at h stop;
end;


setExitOnClose;
setStopLoss(stopLoss);
setProfitTarget(takeProfit);
The anti Rubber Band Strategy

Trade filtering was obtained by limiting the duration during the trading day that a trade could take place.  It’s usually wise to wait a few minutes after the open and a few minutes prior to the close to issue trade directives.  Also, range compression of the prior day seems to help in many cases.  Or at least not range expansion.   I only allow one long entry or one short or both during the trading day – two entries only!  Read the code and let me know if you have any questions.  This is a good framework for other areas of research.  Limiting entries using the mp variable is a neat technique that you can use elsewhere.

And as always let me know if you see any bugs in the code.  Like Donnie Knuth says, “Beware of bugs in the above code; I have only proved it correct, not tried it!”

Extend Data Mining to Actual Trading System

Data Mining May or May Not Link Causality

A study between ice cream sales and crime rate demonstrated a high level of correlation.  However, it would be illogical to assume that buying more ice cream leads to more crime.  There are just too many other factors and variables involved to draw a conclusion.  So, data mining with EasyLanguage may or may not lead to anything beneficial.  One thing is you cannot hang your hat completely on this type of research.  A reader of my books asked if there was evidence that pointed to the best time to enter and exit a day trade.  Is it better to enter in the morning or in the afternoon or are there multiple trading windows throughout the day?  I thought I would try to answer the question using TradeStation’s optimization capabilities.

If You Like the Theory and its EasyLanguage Code of this Blog Post – Check Out my New Book at Amazon.com

Get Your Copy Now!

Create a Search Space of Different Window Opening Times and Open Duration

My approach is just one of a few that can be used to help answer this question.  To cut down on time and the size of this blog we will only look at day trading the @ES.D from the long side.  The search space boundaries can be defined by when we open the trading window and how long we leave it open.  These two variables will be defined by inputs so we can access the optimization engine.  Here is how I did it with EasyLanguage code.

inputs: openWindowTime(930),openWindowOffset(5),windowDuration(60);
inputs: canBuy(True),canShort(True);



if t >= calcTime(openWindowTime,openWindowOffset) and t < calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if entriesToday(d) = 0 and canBuy Then
buy next bar at market;
if entriesToday(d) = 0 and canShort Then
sellshort next bar at market ;
end;

if t = calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if marketPosition = 1 then sell next bar at open;
if marketPosition =-1 then buyToCover next bar at open;
end;
setExitOnClose;
Optimize when to open and how long to leave open

The openWindowTime input is the basis from where we open the trading window.  We are working with the @ES.D with an open time of 9:30 AM eastern.  The openWindowOffset will be incremented in minutes equivalent to the data resolution of the chart, five minutes.  We will start by opening the window at 9:35 and leave it open for 60 minutes.  The next iteration in the optimization loop will open the window at 9:40 and keep it open for 60 minutes as well.  Here are the boundaries that I used to define our search space.

  • window opening times offset: 5 to 240 by 5 minutes
  • window opening duration: 60 to 240 by 5 minutes
Optimization Ranges for Window Open and Open Duration

A total of 1739 iterations will span our search space.   The results state that waiting for twenty minutes before buying and then exiting 190 minutes later, worked best.  But also entering 90 minutes after the open and exiting 4 hours later produced good results as well (no trade execution fee were utilized.)  Initially I was going to limit entry to once per day, but then I thought it might be worthwhile to enter a fresh position, if the first one is stopped out, or pyramid if it hasn’t.  I also thought, each entry should have its own protective stop amount.  Would entering later require a small stop – isn’t most of the volatility, on average, expressed during the early part of the day.

Results of different opening and duration times.

Build a Strategy that Takes on a Secondary Trade as a New Position or One that is Pyramided.

This is not a simple strategy.  It sounds simple and it requires just a few lines of code.  But there is a trick in assigning each entry with its own exit.  As you can see there is a potential for trade overlap.  You can get long 20 minutes after the open and then add on 70 minutes  (90 from the open) later.  If the first position hasn’t been stopped out, then you will pyramid at the second trade entry.  You have to tell TradeStation to allow this to happen.

Allow TradeStation to Pyramid up to 2 positions with different signals.

System Rules

  1. Enter long 20 minutes after open
  2. Enter long 90 minutes after open
  3. Exit 1st entry 190 minutes later or at a fixed $ stop loss
  4. Exit 2nd entry 240 minutes later or at a fixed $ stop loss
  5. Make sure you are out at the end of the day

Sounds pretty simple, but if you want to use different stop values for each entry, then the water gets very muddy.

AvgEntryPrice versus EntryPrice

Assume you enter long and then you add on another long position.  If you examine EntryPrice you will discover that it reflects the initial entry price only.   The built-in variable AvgEntryPrice will be updated with the average price between the two entries.  If you want to key off of the second entry price, then you will need to do a little math.

avgEntryPrice = (entry price 1 + entry price 2) / 2

or ap = (ep1 + ep2) /2

Using this formula and simple algebra we can arrive at ep2 using this formula:  ep2 = 2*ap – ep1.  Since we already know ep1 and ap, ep2 is easy to get to.  We will need this information and also the functionality of from entry.  You tie entries and exits together with the keywords from entry.  Here are the entry and exit trade directives.

if time = calcTime(openTime,entryTime1Offset) then 
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;


if time = calcTime(openTime,entryTime1Offset + exitTime1Offset) then
sell("1st exit") from entry("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset + exitTime2Offset) then
sell("2nd exit") from entry("2nd buy") next bar at open;

if mp = 1 Then
Begin
value1 = avgEntryPrice;
if currentShares = 2 then value1 = avgEntryPrice*2 - entryPrice;
sell("1st loss") from entry("1st buy") next bar at entryPrice - stopLoss1/bigPointValue stop;
sell("2nd loss") from entry("2nd buy") next bar at value1 - stopLoss2/bigPointValue stop;
end;

if mp = 1 and t = openTime + barInterval then sell("oops") next bar at open;
Entry and Exit Directives Code

The trade entry directives are rather simple, but you must use the calcTime function to arrive at the correct entry and exit times.  Here we are using the benchmark, openTime and the offsets of entryTime1Offset and entryTime2Offset.  This function adds (or subtracts if the offset is negative) the offset to the benchmark.  This takes care of when the trading windows open, but you must add the entry1TimeOffset to exit1TimeOffset to calculate the duration the trading window is to remain open.  This goes for the second entry window as well.

Now let’s look at the exit directives.  Notice how I exit the 1st buy entry with the code from entry (“1st buy”).  This ties the entry and exit directives together.  This is pretty much straightforward as well.  The tricky part arrives when we try to apply different money management stops to each entry.  Exiting from the 1st buy requires us to simply subtract the $ in terms of points from entryPrice.  We must use our new equation to derive the 2nd entry price when two contracts are concurrent.   But what if we get stopped out of the first position prior to entering the second position?  Should we continue using the formula.  No.  We need to fall back to entryPrice or avgEntryPrice:  when only one contract or unit is in play, these two variables are equal.  We initially assign the variable value1 to the avgEntryPrice and only use our formula when currentShares = 2.  This code will work a majority of the time.  But take a look at this trade:

Didn’t have an intervening bar to update the 2nd entry price. The first entry price was used as the basis to calculate the stop loss!

This is an anomaly, but anomalies can add up.  What happened is we added the second position and the market moved down very quickly – too quickly for the correct entry price to be updated.  The stop out (2nd loss) was elected by using the 1st entry price, not the second.  You can fix this with the following two solutions:

  1. Increase data resolution and hope for an intervening bar
  2. Force the second loss to occur on the subsequent trading bar after entry.  This means you will not be stopped out on the bar of entry but will have to wait five minutes or whatever bar interval you are working with.
Fixed – just told TS to place the order at the close of the bar where we were filled!

OK – Now How Do We Make this a Viable Trading System

If you refer back to the optimization results you will notice that the average trade (before execution costs) was around $31.  Keep in mind we were trading every day.  This is just the beginning of your research – did we find a technical advantage?  No.  We just found out that you can enter and exit at different times of the trading day, and you can expect a positive outcome.  Are there better times to enter and exit?  YES.  You can’t trade this approach without adding some technical analysis – a reason to enter based on observable patterns.  This process is called FILTERING.   Maybe you should only enter after range compression.  Or after the market closed up on the prior day, or if the market was an NR4 (narrow range 4.)  I have added all these filters so you can iterate across them all using the optimization engine.  Take a look:

filter1 = True;
filter2 = True;

if filtNum1 = 1 then
filter1 = close of data2 > close[1] of data2;
if filtNum1 = 2 Then
filter1 = close of data2 < close[1] of data2;
if filtNum1 = 3 Then
filter1 = close of data2 > open of data2;
if filtNum1 = 4 Then
filter1 = close of data2 < open of data2;
if filtNum1 = 5 Then
filter1 = close of data2 > (h data2 + l data2 + c data2)/3;
if filtNum1 = 6 Then
filter1 = close of data2 < (h data2 + l data2 + c data2)/3;
if filtNum1 = 7 Then
filter1 = openD(0) > close data2;
if filtNum1 = 8 Then
filter1 = openD(0) < close data2;

if filtNum2 = 1 Then
filter2 = trueRange data2 < avgTrueRange(10) data2;
if filtNum2 = 2 Then
filter2 = trueRange data2 > avgTrueRange(10) data2;
if filtNum2 = 3 Then
filter2 = range data2 = lowest(range data2,4);
if filtNum2 = 4 Then
filter2 = range data2 = highest(range data2,4);
Filter1 and Filter2 - filter1 looks for a pattern and filter2 seeks range compression/expansion.

Let’s Search – And Away We Go

I will optimize across the different patterns and range analysis and different $ stops for each entry (1st and 2nd.)

Optimize across patterns and volatility and protective stops for 1st and 2nd entries.

Best Total Profit

Trade when today’s open is greater than yesterday’s close and don’t worry about the volatility.  Use $550 for the first entry and $600 for the second.

Best W:L Ratio and Respectable Avg. Trade

This curve was created  by waiting for yesterday’s close to be below the prior day’s and yesterday being an NR4 (narrow range 4).  And using a $500 protective stop for both the 1st and 2nd entries.

Did We Find the Holy Grail?  Gosh No!

This post served two purposes.  One, how to set up a framework for data mining and two, create code that can handle things that aren’t apparently obvious – entryPrice versus avgEntryPrice!

if filter1 and filter2 Then
begin
if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;
end;
Incorporating Filter1 and Filter2 in the Entry Logic

 

EasyLanguage to Determine Week Of Month

Week Of Month

I could be wrong, but I couldn’t find this functionality in EasyLanguage.  I was testing a strategy that didn’t want to trade a specific week of the month.   If it’s not built-in, then it must be created.   I coded this functionality in Sheldon Knight’s Seasonality indicator but wanted to create a simplified universal version.  I may have run into one little snag.  Before discussing the snag, here is a Series function that returns my theoretical week of the month.

 

vars: weekCnt(0),cnt(0);
vars: newMonth(False),functionSeed(False);

if month(d) <> month(d[1]) Then
Begin
weekCnt = 1;
end;

if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Then
begin
weekCnt = weekCnt + 1;
end;
if weekCnt = 1 and dayofMonth(d) = 2 and dayOfWeek(D) = Sunday Then
print("Saturday was first day of month"," ",d);

WeekOfMonth = weekCnt;
Series Function to Return Week Rank

This function is of type Series because it has to remember the prior output of the function call – weekCnt.  This function is simple as it will not provide the week count accurately (at the very beginning of a test) until a new month is encountered in your data.  It needs a ramp up (at least 30 days of daily or intraday data) to get to that new month.  I could have used a while loop the first time the function was called and worked my way back in time to the beginning of the month and along the way calculate the week of the month.  I decided against that, because if you are using tick data then that would be a bunch of loops and TradeStation can get caught in an infinite loop very easily.

This code is rather straightforward.  If the today’s month is not equal to yesterday’s month, then weekCnt is set to one.  Makes sense, right.  The first day of the month should be the first week of the month.  I then compare the day of week of today against the day of week of yesterday.  If today’s day of week is less than the prior day’s day of week, then it must be a Sunday (futures markets open Sunday night to start the week) or Monday (Sunday = 0 and Monday = 1 and Friday = 5.)  If this occurs and today’s month is the same as yesterday’s month, weekCnt is incremented.  Why did I check for the month?  What if the first trading day was a Sunday or Monday?  Without the month comparison I would immediately increment weekCnt and that would be wrong.  That is all there is to it?  Or is it?  Notice I put some debug code in the function code.

Is There a Snag?

April 2023 started the month on Saturday which is the last day of the week, but it falls in the first week of the month.  The sun rises on Sunday and it falls in the second week of the month.  If you think about my code, this is the first trading day of the month for futures:

month(April 2nd) = April or 4

month(March 31st) = March or 3

They do not equal so weekCnt is set to 1.  The first trading day of the month is Sunday or DOW=0 and the prior trading day is Friday or DOW=5.  WeekCnt is NOT incremented because month(D) doesn’t equal month(D[1]).  Should WeekCnt be incremented?  On a calendar basis it should, but on a trading calendar maybe not.  If you are searching for the first occurrence of a certain day of week, then my code will work for you.  On April 2nd, 2023, it is the second week of the month, but it is the first Sunday of April.

Thoughts???  Here are a couple of screenshots of interest.

Indicator in Histogram form representing the Week of Month
Some months are spread across SIX weeks.

This function is an example of where we let the data tell us what to do.  I am sure there is calendar functions, in other languages, that can extract information from just the date.  However, I like to extract from what is actually going to be traded.

Email me if you have any questions, concerns, criticism, or a better mouse trap.

The EasyLanguage Function: A Thing of Beauty

The concept of Scope when it comes to a programming language can get very confusing very quickly. If you are new to programming and you think Scope is a mouthwash, no worries here. I will give a full explanation of Scope in terms of programming with the help of ChatGPT. Its response is italicized.

I recently chatted with ChatGPT about Scope in terms of the Python programing language.

In Python, the scope of a variable refers to the region of the program where that variable can be accessed or referenced. There are two types of scopes in Python: global scope and local scope.

Here’s an example that demonstrates the concept of scope in Python:

# global variable
x = 10

def my_func():
# local variable
y = 5
print("x inside my_func:", x) # x is accessed from the global scope
print("y inside my_func:", y) # y is accessed from the local scope

my_func()

print("x outside my_func:", x) # x is accessed from the global scope
print("y outside my_func:") # y is not defined in the global scope, so this will raise a NameError
Example of Scope as demonstrated by Chat-GPT

In this example, we define a global variable x with a value of 10.

We then define a function my_func that has a local variable y with a value of 5. Inside the function, we print the values of x and y. The variable x is accessed from the global scope, which means it can be referenced from anywhere in the program.

The variable y, on the other hand, is only accessible within the function, which is the local scope. Outside the function, we print the value of x again, which is still accessible from the global scope. However, when we try to print the value of y, we get a NameError because y is not defined in the global scope.

Okay that was pretty formal. In simpler terms, a variable declared inside a function can only be seen inside that function, unless it is declared globally. Another thing about Scope, is that the variables have amnesia. Once you step out of the function the variable forgets what it was, and you can’t refer to its prior value upon return to the function.

Unless you are an EasyLanguage function. Scope is still constrained by an EasyLanguage function, because it is a separate piece of code held within the library of Analysis Techniques. Most of the time you can’t see what’s in the function unless you open it with the ELEditor. However, the variables that are defined inside the function do not suffer from amnesia. If you need to refer to a prior value of a locally declared variable, you can. This type of function is what EasyLanguage calls a Serial function. The only downside to this function is it slows processing down quite a bit.

Okay. To make a long story short I wanted to show the magic of EasyLanguage function that I have been working with on a project. This project includes some of Ehlers’ cycle analysis functions. The one I am going to discuss today is the HighRoof function – don’t worry I am not going to go into detail of what this function does. If you want to know just GOOGLE it or ask ChatGPT. I developed a strategy that used the function on the last 25 days of closing price data. I then turned around and fed the output of the first pass of the HighRoof function right back into the HighRoof function. Something similar to embedding functions.

doubleSmooth = average(average(c,20),20);

Sort of like a double smoothed moving average. After I did this, I started thinking does the function remember the data from its respective call? The first pass used closing price data, so its variables and their history should be in terms of price data. The second pass used the cyclical movements data that was output by the initial call to the HighRoof function. Everything turned out fine, the function remembered the correct data. Or seemed like it did. This is how you learn about any programming language – pull out your SandBox and do some testing. First off, here is my conversion of Ehlers’ HighRoof function in EasyLanguage.

//Ehlers HiRoof
Inputs: dataSeries(numericseries),cutPeriod(Numeric);

Vars: a1(0), b1(0), c1(0), c2(0), c3(0), Filt(0), Filt2(0),
alpha1(0),oneMinusAlpha1(0), highPass(0),myhp(0),degrees(0);
Vars: numTimesCalled(0);

//Highpass filter cyclic components whose periods are shorter than 48 bars

numTimesCalled = numTimesCalled + 1;

print(d," numTimesCalled ",numTimesCalled," highPass[1] ",highPass[1]," highPass[2] ",highPass[2]," highPass[3] ",highPass[3]);
degrees = .707*360 / CutPeriod;

alpha1 = (Cosine(degrees) + Sine(degrees) - 1) / Cosine(degrees);

oneMinusAlpha1 = 1-alpha1;

highPass = square(oneMinusAlpha1/2)*(dataSeries-2*dataSeries[1]+dataSeries[2]) +
2*(oneMinusAlpha1)*highPass[1]-square(oneMinusAlpha1)*highPass[2];



EhlersHighRoof=highPass;
Ehlers High Roof Function

This function requires just two inputs – the data (with a history) and a simple length or cut period. The first input is of type numericSeries and the second input is of type numericSimple. You will see the following line of code

 print(d," numTimesCalled ",numTimesCalled," highPass[1] ",highPass[1]," highPass[2] ",highPass[2]," highPass[3] ",highPass[3]);

This code prints out the last three historic values of the HighPass variable for each function call. I am calling the function twice for each bar of data in the Crude Oil futures continuous contract.

1230206.00 numTimesCalled  494.00 highPass[1]   -0.78 highPass[2]   -0.51 highPass[3]   -0.60
1230206.00 numTimesCalled 494.00 highPass[1] -0.05 highPass[2] -0.02 highPass[3] -0.06
1230207.00 numTimesCalled 495.00 highPass[1] -0.38 highPass[2] -0.78 highPass[3] -0.51
1230207.00 numTimesCalled 495.00 highPass[1] 0.04 highPass[2] -0.05 highPass[3] -0.02
1230208.00 numTimesCalled 496.00 highPass[1] 0.31 highPass[2] -0.38 highPass[3] -0.78
1230208.00 numTimesCalled 496.00 highPass[1] 0.16 highPass[2] 0.04 highPass[3] -0.05
1230209.00 numTimesCalled 497.00 highPass[1] 0.49 highPass[2] 0.31 highPass[3] -0.38
1230209.00 numTimesCalled 497.00 highPass[1] 0.15 highPass[2] 0.16 highPass[3] 0.04
1230210.00 numTimesCalled 498.00 highPass[1] 0.30 highPass[2] 0.49 highPass[3] 0.31
1230210.00 numTimesCalled 498.00 highPass[1] 0.07 highPass[2] 0.15 highPass[3] 0.16
1230213.00 numTimesCalled 499.00 highPass[1] 0.52 highPass[2] 0.30 highPass[3] 0.49
1230213.00 numTimesCalled 499.00 highPass[1] 0.08 highPass[2] 0.07 highPass[3] 0.15
1230214.00 numTimesCalled 500.00 highPass[1] 0.44 highPass[2] 0.52 highPass[3] 0.30
1230214.00 numTimesCalled 500.00 highPass[1] 0.04 highPass[2] 0.08 highPass[3] 0.07
Output of calling HighRoof twice per bar

Starting at the top of the output you will see that on 1230206 the function was called twice with two different sets of data. As you can see the output of the first two lines is of a different magnitude. The first line is approximately an order or magnitude of 10 of the second line. If you go to lines 3 and 4 you will see the highPass[1] of lines 1 and 2 moves to highPass[2] and then onto highPass[3]. I think what happens internally is for every call on per bar basis, the variables for each function call are pushed into a queue in memory. The queue continues to grow for whatever length is necessary and then either maintained or truncated at some later time.

Why Is This So Cool?

In many languages the encapsulation of data with the function requires additional programming. The EasyLanguage function could be seen as an “object” like in object-oriented programming. You just don’t know you are doing it. EasyLanguage takes care of a lot of the behind-the-scenes data management. To do the same thing in Python you would need to create a class of Ehlers Roof that maintain historic data in class members and the calculations would be accomplished by a class method. In the case of calling the function twice, you would instantiate two classes from the template and each class would act independent of each other.

Here is my SandBox for Indicator


Value1 = EhlersHighRoof(close,25);
plot1(Value1,"EhlersHiRoof");
Value2 = EhlersHighRoof(value1,25);
plot2(Value2,"EhlersHiRoof2");
Sandbox Playground for Ehlers Function

 

One last nugget of information. If you are going to be working with trigonometric functions such as Cosine, Sine or Tangent, make sure your arguments are in degrees not radians. In Python, you must use radians.

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.

Highly Illogical – Best Guess Doesn’t Match Reality

An ES Break-Out System with Unexpected Parameters

I was recently testing the idea of a short term VBO strategy on the ES utilizing very tight stops.  I wanted to see if using a tight ATR stop in concert with the entry day’s low (for buys) would cut down on losses after a break out.  In other words, if the break out doesn’t go as anticipated get out and wait for the next signal.  With the benefit of hindsight in writing this post, I certainly felt like my exit mechanism was what was going to make or break this system.  In turns out that all pre conceived notions should be thrown out when volatility enters the picture.

System Description

  • If 14 ADX < 20 get ready to trade
  • Buy 1 ATR above the midPoint of the past 4 closing prices
  • Place an initial stop at 1 ATR and a Profit Objective of 1 ATR
  • Trail the stop up to the prior day’s low if it is greater than entryPrice – 1 ATR initially, and then trail if a higher low is established
  • Wait 3 bars to Re-Enter after going flat – Reversals allowed

That’s it.  Basically wait for a trendless period and buy on the bulge and then get it out if it doesn’t materialize.  I knew I could improve the system by optimizing the parameters but I felt I was in the ball park.  My hypothesis was that the system would fail because of the tight stops.  I felt the ADX trigger was OK and the BO level would get in on a short burst.  Just from past experience I knew that using the prior day’s price extremes as a stop usually doesn’t fair that well.

Without commission the initial test was a loser: -$1K and -$20K draw down over the past ten years.  I thought I would test my hypothesis by optimizing a majority of the parameters:

  • ADX Len
  • ADX Trigger Value
  • ATR Len
  • ATR BO multiplier
  • ATR Multiplier for Trade Risk
  • ATR Multiplier for Profit Objective
  • Number of bars to trail the stop – used lowest lows for longs

Results

As you can probably figure, I  had to use the Genetic Optimizer to get the job done.  Over a billion different permutations.  In the end here is what the computer pushed out using the best set of parameters.

No Commission or Slippage – Genetic Optimized Parameter Selection

Optimization Report – The Best of the Best

Top Parameters – notice the Wide Stop Initially and the Trailing Stop Look-Back and also the Profit Multiplier – but what really sticks out is the ADX inputs

ADX – Does it Really Matter?

Take a look at the chart – the ADX is mostly in Trigger territory – does it really matter?

A Chart is Worth a 1000 Words

What does this chart tell us?

70% of Profit was made in last 40 trades

Was the parameter selection biased by the heightened level of volatility?  The system has performed on the parameter set very well over the past two or three years.  But should you use this parameter set going into the future – volatility will eventually settle down.

Now using my experience in trading I would have selected a different parameter set.   Here are my biased results going into the initial programming.  I would use a wider stop for sure, but I would have used the generic ADX values.

George’s More Common Sense Parameter Selection – wow big difference

I would have used 14 ADX Len with a 20 trigger and risk 1 to make 3 and use a wider trailing stop.  With trend neutral break out algorithms, it seems you have to be in the game all of the time.  The ADX was supposed to capture zones that predicated break out moves, but the ADX didn’t help out at all.  Wider stops helped but it was the ADX values that really changed the complexion of the system.  Also the number of bars to wait after going flat had a large impact as well.  During low volatility you can be somewhat picky with trades but when volatility increases you gots to be in the game. – no ADX filtering and no delay in re-Entry.  Surprise, surprise!

Alogorithm Code

Here is the code – some neat stuff here if you are just learning EL.  Notice how I anchor some of the indicator based variables by indexing them by barsSinceEntry.  Drop me a note if you see something wrong or want a little further explanation.

Inputs: adxLen(14),adxTrig(25),atrLen(10),atrBOMult(1),atrRiskMult(1),atrProfMult(2),midPtNumBar(3),posMovTrailNumBars(2),reEntryDelay(3);
vars: mp(0),trailLongStop(0),trailShortStop(0),BSE(999),entryBar(0),tradeRisk(0),tradeProf(0);
vars: BBO(0),SBO(0),ATR(0),totTrades(0);

mp = marketPosition;
totTrades = totalTrades;
BSE = barsSinceExit(1);
If totTrades <> totTrades[1] then BSE = 0;
If totalTrades = 0 then BSE = 99;


ATR = avgTrueRange(atrLen);

SBO = midPoint(c,midPtNumBar) - ATR * atrBOMult;
BBO = midPoint(c,midPtNumBar) + ATR * atrBOMult;

tradeRisk = ATR * atrRiskMult;
tradeProf = ATR * atrProfMult;

If mp <> 1 and adx(adxLen) < adxTrig and BSE > reEntryDelay and open of next bar < BBO then buy next bar at BBO stop;
If mp <>-1 and adx(adxLen) < adxTrig AND BSE > reEntryDelay AND open of next bar > SBO then sellshort next bar at SBO stop;

If mp = 1 and mp[1] <> 1 then
Begin
trailLongStop = entryPrice - tradeRisk;
end;

If mp = -1 and mp[1] <> -1 then
Begin
trailShortStop = entryPrice + tradeRisk;
end;

if mp = 1 then sell("L-init-loss") next bar at entryPrice - tradeRisk[barsSinceEntry] stop;
if mp = -1 then buyToCover("S-init-loss") next bar at entryPrice + tradeRisk[barsSinceEntry] stop;


if mp = 1 then
begin
sell("L-ATR-prof") next bar at entryPrice + tradeProf[barsSinceEntry] limit;
trailLongStop = maxList(trailLongStop,lowest(l,posMovTrailNumBars));
sell("L-TL-Stop") next bar at trailLongStop stop;
end;
if mp =-1 then
begin
buyToCover("S-ATR-prof") next bar at entryPrice -tradeProf[barsSinceEntry] limit;
trailShortStop = minList(trailShortStop,highest(h,posMovTrailNumBars));
// print(d, " Short and trailStop is : ",trailShortStop);
buyToCover("S-TL-Stop") next bar at trailShortStop stop;
end;

Converting A String Date To A Number – String Manipulation in EasyLanguage

EasyLanguage Includes a Powerful String Manipulation Library

I thought I would share this function.  I needed to convert a date string (not a number per se) like “20010115” or “2001/01/15” or “01/15/2001” or “2001-01-15” into a date that TradeStation would understand.  The function had to be flexible enough to accept the four different formats listed above.

String Functions

Most programming languages have functions that operate strictly on strings and so does EasyLanguage.  The most popular are:

  • Right String (rightStr) – returns N characters from the right side of the string.
  • Left String (leftStr) – returns N character starting from the left side of the string
  • Mid String (midStr) – returns the middle portion of a string starting at a specific place in the string and advance N characters
  • String Length (strLen) – returns the number of characters in the string
  • String To Number (strToNum) – converts the string to a numeric representation.  If the string has a character, this function will return 0
  • In String (inStr) – returns location of a sub string inside a larger string ( a substring can be just one character long)

Unpack the String

If the format is YYYYMMDD format then all you need to do is remove the dashes or slashes (if there are any) and then convert what is left over to a number.   But if the format is MM/DD/YYYY format then we are talking about a different animal.  So how can you determine if the date string is in this format?  First off you need to find out if the month/day/year separator is a slash or a dash.  This is how you do this:

whereIsAslash = inStr(dateString,”/”);
whereIsAdash = inStr(dateString,”-“);

If either is a non zero then you know there is a separator.  The next thing to do is locate the first “dash or slash” (the search character or string).  If it is located within the first four characters of the date string then you know its not a four digit year.  But, lets pretend the format is “12/14/2001” so if the first dash/slash is the 3rd character you can extract the month string by doing this:

firstSrchStrLoc = inStr(dateString,srchStr);
mnStr= leftStr(dateString,firstSrchStrLoc-1);

So if firstSrchStrLoc = 3 then we want to leftStr the date string and extract the first two characters and store them in mnStr.  We then store what’s left of the date string in tempStr by using rightStr:

strLength = strLen(dateString);

tempStr = rightStr(dateString,strLength-firstSrchStrLoc);

Here I pass dateString and the strLength-firstSrchStrLoc – so if the dateString is 10 characters long and the firstSrchStrLoc is 3, then we can create a tempstring by taking [10 -3  = 7 ] characters from right side of the string:

“12/14/2001” becomes “14/2001” – once that is done we can pull the first two characters from the tempStr and store those into the dyStr [day string.]  I do this by searching for the “/” and storing its location in srchStrLoc.  Once I have that location I can use that information and leftStr to get the value I need.   All that is left now is to use the srchStrLoc and the rightStr function.

srchStrLoc = inStr(tempStr,srchStr);
dyStr = leftStr(tempStr,srchStrLoc-1);
yrStr = rightStr(tempStr,strLen(tempStr)-srchStrLoc);

Now convert the strings to numbers and multiply their values accordingly.

DateSTrToYYYMMDD = strToNum(yrStr) X 10000-19000000 + strToNum(mnStr) X 100 + strToNum(dyStr)

To get the date into TS format I have to subtract 19000000 from the year.  Remember TS represents the date in YYYMMDD  format.

Now what do  you do if the date is in the right format but simply includes the dash or slash separators.  All you need to do here is loop through the string and copy all non dash or slash characters to a new string and then convert to a number.  Here is the loop:

        tempStr = "";
iCnt = 1;
While iCnt <= strLength
Begin
If midStr(dateString,iCnt,1) <> srchStr then
tempStr += midStr(dateString,iCnt,1);
iCnt+=1;
end;
tempDate = strToNum(tempStr);
DateStrToYYYMMDD = tempDate-19000000;

Here I use midStr to step through each character in the string.  MidStr requires a string and the starting point and how many characters you want returned from the string.  Notice I step through the string with iCnt and only ask for 1 character at a time.  If the character is not a dash or slash I concatenate tempStr with the non dash/slash character.  At the end of the While loop I simply strToNum the string and subtract 19000000.  That’s it!  Remember EasyLanguage is basically a full blown programming language with a unique set of functions that relate directly to trading.

Here is the function and testFunc caller.

STRINGFUNCANDFUNCCALLER

 

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