# Pyramania Levels with 24-Hour Session – Free Code

## Easing Into EasyLanguage-DayTrade Edition [On SALE Now thru November]

EZ-DT Pyramania is a strategy I introduced in the Day Trade Edition.  The logic is rather simple – pyramid as the market moves through multiple levels during the trading day. – buy, buy, buy, dump or buy, dump, short, short, short, dump.  The distance between the levels is constant.  In the book, I showed an algorithm with a total of 6 levels with 7 edges.

Here the market opens @ 9:30 and the levels are instantly plotted and trades are executed as the market moves through the levels located above the open tick.  Over the weekend, I had a reader ask how he could modify the code to plot the levels on the 24-hour @ES session.  In the day session, I used the change in the date as the trigger for the calculation and plotting of the levels.  Here is the day session version.

``inputs:numSegments(6),numPlots(6);arrays: segmentBounds[](0);variables: j(0),loopCnt(0),segmentSize(0),avgRng(0);onceBegin	Array_SetMaxIndex(segmentBounds, numSegments);end;if d <> d[1] Then  // only works on the @ES.D or any .D sessionbegin	avgRng = average(range of data2,20);	segmentSize = avgRng/numSegments;	loopCnt = -1*numSegments/2;	for j = 0 to numSegments	begin		segmentBounds[j] = openD(0) + loopCnt * segmentSize;		loopCnt = loopCnt + 1;	end;end;//The following time constraint only works when all time stamps//are less than the end of day time stamp//This will not work when time = 1800 and endTime = 1700if t < calcTime(sessionEndTime(0,1),-barInterval) Thenbegin	if numPlots >= 1 then plot1(segmentBounds[0],"Level 0");	if numPlots >= 2 then plot2(segmentBounds[1],"Level 1");	if numPlots >= 3 then plot3(segmentBounds[2],"Level 2");	if numPlots >= 4 then plot4(segmentBounds[3],"Level 3");	if numPlots >= 5 then plot5(segmentBounds[4],"Level 4");	if numPlots >= 6 then plot6(segmentBounds[5],"Level 5");	if numPlots >= 7 then plot7(segmentBounds[6],"Level 6");//	plot8(segmentBounds[7],"Level 7");//	plot9(segmentBounds[8],"Level 8");end;``
Works great with @ES.D or any @**.D

I like this code because it exposes you to arrays, loops, and plotting multiple values.  You can fix this by modifying and adding some code.  I used the Trading Around Midnight blog post to get the code I needed to enable plotting around 0:00 hours.  Here is the updated code:

``inputs:numSegments(6),numPlots(6);arrays: segmentBounds[](0);variables: j(0),loopCnt(0),segmentSize(0),avgRng(0),startTime(0),endTime(0),endTimeOffset(0);onceBegin	Array_SetMaxIndex(segmentBounds, numSegments);end;startTime = sessionStartTime(0,1); endTime = sessionEndTime(0,1);//let TS tell you when the market opens - remember the//first time stamp is the open time + bar intervalif t = calcTime(sessionStartTime(0,1),barInterval) Thenbegin	avgRng = average(range of data2,20);	segmentSize = avgRng/numSegments;	loopCnt = -1*numSegments/2;	for j = 0 to numSegments	begin		segmentBounds[j] = open + loopCnt * segmentSize;		loopCnt = loopCnt + 1;	end;end;// if startTime > endTime then you know you are dealing with// timees that more than likely bridges midnight// if time is greater then 1700 (end time) then you must// subtract an offset so it makes sense - endTimeOffset// play with the math and it will come to youif startTime > endTime then begin 	endTimeOffset = 0; 	if t >= startTime+barInterval and t<= 2359 then		endTimeOffSet = 2400-endTime; end;if t-endTimeOffSet < endTime Thenbegin	if numPlots >= 1 then plot1(segmentBounds[0],"Level 0");	if numPlots >= 2 then plot2(segmentBounds[1],"Level 1");	if numPlots >= 3 then plot3(segmentBounds[2],"Level 2");	if numPlots >= 4 then plot4(segmentBounds[3],"Level 3");	if numPlots >= 5 then plot5(segmentBounds[4],"Level 4");	if numPlots >= 6 then plot6(segmentBounds[5],"Level 5");	if numPlots >= 7 then plot7(segmentBounds[6],"Level 6");//	plot8(segmentBounds[7],"Level 7");//	plot9(segmentBounds[8],"Level 8");end;``
Modification to plot data around midnight

Here I let TS tell me with the market opens and then use some simple math to make sure I can plot with the time is greater than and less than the end of day time.

Email me if you have the book and want to companion code to the strategy – georgeppruitt@gmail.com

# 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.

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 ThenBegin	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) Thenbegin	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!”

## Daily Bar Daytrade to 5 Minute Bars — Not So Easy!

Like in the previous post, I designed a simple optimization framework trying to determine the best day of the week to apply a long only volatility based open range break out algorithm on natural gas.  You might first ask why natural gas?  Its a good market that has seasonal tendencies that can actually be day-traded – there is enough volatility and volume.  Anyway, by simply slapping setExitOnClose at the end of your code turns your algorithm into one that exits every day at the settlement (fictional value that is derived via formula) price.  You can always use LIB (look inside bar) to help determine the magnitude of intraday swings and there respective chronological order.  But you are still getting out at the settlement price – which isn’t accurate.  However, if you are trying to get a set of parameters that gets you into the ballpark, then this is a very acceptable approach.  But you will always want to turn you daily bar strategy with LIB intro an intraday version for automation and accuracy purposes.

### Day of Week Analysis On Intraday Data

When you optimize the day of week on daily bars, the first bar of the week is usually Monday.  When testing with intraday bars on futures, the trading actually starts on Sunday evening.  If your daily bar analysis reveals the best day of week is Wedneday, then you must inform TradeStation to take the trade from the opening on Tuesday night through the close on Wenesday.  If you are executing a market order, then you just need to tell TradeStation to execute at Tuesday night’s open (1800 eastern standard time).  The TRICK to allow trading throughout the 24 hour session (1800 to 1700) on just a particular day of the week is to capture the day of the week on the first bar of the trading session.  Here is some bookkeeping you can take care of on the first bar of the trading session.

``if t = sessionstartTime(0,1) + barInterval ThenBegin		todaysOpen = o;	openDOW = dayOfWeek(d);	canBuy = False;	if openDOW = daysOfWeekToTrade then canBuy = True;	if canBuy and d[1] <> date of data2 then 	begin		canBuy = False;		print(d," turning off canBuy");	end;			if mp = 1 then curTradeDays = curTradeDays + 1;	if mp = 0 then curTradeDays = 0;	barsToday = 1;end;``
Bookkeeping on the first bar of trading session

Here, I check to see if the first bar’s time stamp is equal to the sessionStarttime + barInterval.  Remember TradeStation shows the close time of each bar as the time stamp.  If adding a barInterval to the opening time results in a non-time, then use the calcTime function ( 1800 + 60 = 1860 – a non-time.)   I first store the open of the session in my variable todaysOpen.  Why not just use openD(0).  Well openD(0) is great for sessions that don’t span midnight.  If they span midnight then the openD returns the open of the12:00 am bar.  Here is the output from August 9th with the open on August 8th at 1800.  The two other values are midnight on August 8th and August 7th.  So the openD, highD, lowD, and closeD functions involve the 24 hour clock and not the session.

```print(todaysOpen:5:5," ",openD(0):5:5," ",openD(1):5:5);

18:00  midnite[0]   midnite[1]
--------------------------------------
1230808 2.797        2.712      2.588

```

On the first bar of the trading session I also capture the day of the week.  The days of the week, using intraday data on a 24 hour session, range from Sunday to Thursday, instead of Monday thru Friday.  CanBuy is turned on if the day of week equals the input provided by the user.  When using daily bars and you optimize the day of the week, remember if you chose 2 or Tuesday you really mean Wednesday.  If today is Tuesday, then buy next bar at…  This will generate trades only on Wednesdays.  When testing on intraday data you do not need to make a modification for the day of week.  If the first bar of the trading session is Tuesday, then you will actually trade what is considered the Wednesday session that starts on Tuesday evening at 18:00.

Here is a quick trick to not trade on Holidays.  The daily bar does not include preempted sessions in its database, whereas intraday data does.  So, if at 18:00 the date of the prior bar does not match the date of the daily bar located in the Data2 slot, then you know that the prior day was preempted and you should not trade today.  In other words, Data2 is missing.  Remember, you only want to trade on days that are included in the daily bar database in your attempt to replicate the daily bar strategy.

```date             close   moving average
1230703.00 data2         2.57382 2.70300
1230704.00 missing data2 2.57382 2.70300 <-- no trade
1230705.00 data2         2.57485 2.65100 <-- matches```

## How to count the daily bars since entry.

Here again you need to do some bookkeeping.  If you are long on the first bar of the day, then you have been in the trade for at least a day.  If you are long on two first bars of the trading session, then you have been long for two days.  I use the variable, curTradeDays, to count the number of days we have been in the trade.  If on the first bar of the trading session we are flat, then I reset curTradeDays to zero.  Otherwise, I increment the variable and this only occurs once a day.  You can optimize the daysInTrade input, but for this post we are just interested in getting out at the close on the day of entry.

#### Controlling one entry per day.

We only want one long entry per day in an attempt to replicate the daily bar system.  There are several ways to do this, but comparing the current bar’s marketPosition to the prior bar’s value will inform you if a position has been transitioned from flat to long.  If the prior bar’s position if flat and the current bar is now long, then we can turn our canBuy off or to false.  If we get stopped out later and the market rallies again to our break out level, we will not execute at that level, because the trade directive will not be issued.  Why not use the entriesToday function?  Again midnight cause this function to reset.  Say you go long at 22:00 and you do not want to enter another position until the tomorrow at 18:00.  EntriesToday will forget you entered the long position at 22:00.

```1220726.00 2350.00 entries today 1.00
1220726.00 2355.00 entries today 1.00
1220727.00 0.00 entries today 0.00 < not true!```

#### Cannot execute on the first bar of the day – does it matter?

``	if canBuy and h > todaysOpen + volAmt *volMult then 	Begin 		print(d," first bar penetration ",value67," ",value68," ",(c - (todaysOpen + volAmt *volMult))*bigPointValue );		value67 = value67 + 1;		value68 = value68 + (c - (todaysOpen + volAmt *volMult))*bigPointValue;	end;``
Testing for penetration on first 5 minute bar of the day

By the end of the first bar of the day we know the open, high, low and close of the day thus far.  We can test to see if the high would have penetrated the break out level and also calculate the profit or loss of the trade.  In a back-test you will not miss this trade if the next bar’s open is still above the break out level.  If the next bar’s open is below the break out level, then you may have missed a fake out break out.   Again this is a rare event.

### The rest of the code in its entirety

``inputs: daysOfWeekToTrade(1),mavLen(20),volLen(10),volMult(0.25),volComp(.5),stopLoss(500),profitTarget(1000),daysInTrade(0),llLookBack(2);vars: todaysOpen(0),curTradeDays(0),mp(0),barsToday(0),openDOW(0),canBuy(False),volAmt(0),movAvg(0);mp = marketPosition;if t = sessionstartTime(0,1) + barInterval ThenBegin		todaysOpen = o;	openDOW = dayOfWeek(d);	canBuy = False;	if openDOW = daysOfWeekToTrade then canBuy = True;		if canBuy and d[1] <> date of data2 then 	begin		canBuy = False;	end;			if mp = 1 then curTradeDays =curTradeDays + 1;	if mp = 0 then curTradeDays = 0;	barsToday = 1; 		volAmt = average(range of data2,volLen);	movAvg = average(c,mavLen) of data2;	if canBuy and h > todaysOpen + volAmt *volMult then 	Begin 		print(d," first bar penetration ",value67," ",value68," ",(c - (todaysOpen + volAmt *volMult))*bigPointValue );		value67 = value67 + 1;		value68 = value68 + (c - (todaysOpen + volAmt *volMult))*bigPointValue;	end;end;if mp[1] = 0 and mp = 1 and canBuy then canBuy = False;if canBuy and t <> sessionEndTime(0,1) ThenBegin	if barsToday > 1 and 	close of data2 > movAvg and 	range of data2 > volAmt * volComp then 		 buy("DMIntraBuy") next bar at todaysOpen + volAmt *volMult stop;end;barsToday = barsToday + 1;if daysInTrade = 0 then 	setExitOnClose;	sell("LLxit") next bar at lowest(l of data2,llLookBack) stop;if mp = 1 and daysInTrade > 0 thenbegin	if curTradeDays = daysInTrade then sell("DaysXit") next bar at open;end;setStopLoss(stopLoss);setProfitTarget(profitTarget);``
Intrday system that replicates a daily bar day trader

We are using the setStopLoss and setProfitTarget functions in this code.  But remember, if your continuous contract goes negative, then these functions will not work properly.

This type of programming is tricky, because you must use tricks to get EasyLanguage to do what you want it to do.  You must experiment, debug, and program ideas to test the limitations of EasyLanguage to hone your craft.

# On the Subject of Data Mining with EasyLanguage

## When Mining for Data, Make Sure You Have Accurate Data

Take a look at these results with no execution costs.

These results were derived by applying a simple algorithm to the natural gas futures for the past 15 or so years.  I wanted to see if there was a day of the week that produced the best results with the following entry and exit techniques:

• Long entries only
• Open range break out using a fraction of the N-day average range.
• Buy in the direction of the moving average.
• Yesterdays close must be above the X-day moving average of closing prices.
•  Yesterday must have a wider range than a fractional multiple of the average range.
• A fixed \$stop and \$profit used to exit trades.
• Other exits
• Exit at low of prior day.
• Exit at the close of today – so a day trade.

Here is a list of the parameters that can be optimized:

• daysOfWeekToTrade(1) : 1 – Monday, 2 – Tuesday…
• mavLen(20): moving average calculation length.
• volLen(10):  moving average calculation length for range.
• volMult(0.25): average range multiplier to determine break out/
• volComp(.5):  yesterday’s range must be greater than this percentage.
• stopLoss(500): stop loss in \$
• profitTarget(1000): profit objective in \$
• daysInTrade(0): 0 get out at end of day.
• llLookBack(2): pattern derived stop value – use the lowest low of N-days or the stop loss in \$, whichever is closer.

Here is the code:

``inputs: daysOfWeekToTrade(1),mavLen(20),volLen(10),volMult(0.25),volComp(.5),stopLoss(500),profitTarget(1000),daysInTrade(0),llLookBack(2);if dayOfWeek(d) = daysOfWeekToTrade ThenBegin	if close > average(c,mavLen) and range > average(range,volLen)*volComp then 		buy("DMDailyBuy") next bar at open of tomorrow + average(range,volLen)*volMult stop;end;if daysInTrade = 0 then setExitOnClose;sell("LLxit") next bar at lowest(l,llLookBack) stop;if marketPosition = 1 thenbegin	if barsSinceEntry = daysInTrade then sell("DaysXit") next bar at open;end;setStopLoss(stopLoss);setProfitTarget(profitTarget);``

### Why Is This Algorithm Wrong?  It’s Not It’s the Data!

The algorithm, speaking in terms of logic, is accurate. The data is wrong.  You cannot test the exit technology of this algorithm with just four data points per day – open, high, low, and close.  If this simple algorithm cannot be tested, then what can you test on a daily bar basis accurately?

• Long or short entry, but not both.
• If the algorithm can enter both long and short, you need to know what occurred first.  Doesn’t matter if you enter via stop or limit orders.  Using a stop order for both, then you need to know if the high occurred first and got you long, and then later the low and got you short.  Or just the opposite.  You can test, with the benefit of hindsight, if only one of the orders would have been elected.  If only one is elected, then you can proceed.  If both then no-go.  You must be able to use future leak to determine if only one of the orders were fillable.  TS-18 allows future leak BTW.  I say that like it’s a good thing!
• L or S position from either a market or stop, and a profit objective.
• If a long position is entered above the open, via a stop, and then the market moves even higher, you can get out on a sell limit for a profit.
• Same goes for the short side, but you need to know the magnitude of the low price in relation to the open.
• L or S position from either a market or limit and a protective stop.
• If short position is entered above the open, via a limit order, and the market moves even higher, you can exit the short position at a loss via a buy stop order.
• Same goes for the long side, but you need to know the magnitude of the high in relation to the open.
• Long pyramid on multiple higher stop or lower limit orders, but not both.
• The market opens and then sells off. You can go long on a limit order below the open, then you go long another unit below the original limit price and so on…
• The market opens and rallies.  You can go long on a stop order above the open, then you can go long another unit above the original stop price and so on…
• Short pyramid on multiple lower stop or higher limit orders.
• Same as long entries but in opposite direction.

Can’t you look at the relationships of the open to low and open to high and close to high and close to low and determine which occurred first, the high or the low of the day.  You can, but there is no guarantee.  And you can’t determine the magnitude of intraday day swings.  Assume the market opens and immediately moves down and gets you short via a stop order.  And from looking at a daily chart, it looks like the market never turned around, so you would assume you had a profit going into the close.  But in fact, after the market opened and moved down, it rallied back to the open enough to trigger a protective stop you had working.

The entry technique of this strategy is perfectly fine.  It is only buying in the direction of a breakout.  The problems arise when you apply a profit objective and a stop loss and a pattern-based stop and a market on close order.    After buying did the market pull back to get you stopped out before moving up to get you out at profit objective?  Did the market move up and then down to the prior lowest low of N days and then back up to get you long?  Or just the opposite? In futures, the settlement price is calculated with a formula.  You are always exiting at the settlement price with an MOC or setExitOnClose directive (daily bar basis.)

### No Biggie – I Will Just Test with LIB (Look Inside Bar.  That should fix it, right?

It definitely will increase accuracy, because you can see the intraday movements that make up the daily bar.  So, your entries and exits should be executed more accurately.  But you are still getting out at the settlement price which does not exist.  Here are the results from using LIB with 5-minute bar resolution.

### We Know the Weakness, But What Can We Do?

Test on a 5-minute bar as Data1 and daily as Data2.  This concept is what my Hi-Res Edition of Easing Into EasyLanguage is all about.  Here the results of using a higher resolution data and exiting on the last tick of the trading day – a known quantity.

These results validate the LIB results, right?  Not 100%, but very close.  Perhaps this run makes more money because the settlement price on the particular days that the system entered a trade was perhaps lower than the last tick.  In other words, when exiting at the end of the day, the last tick was more often higher than the settlement price.

In my next post, I will go over the details of developing an intraday system to replicate (as close as possible) a simple daily bar-based day trading system.  Like the one we have here.

# 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

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

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.

### 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.

#### 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 ThenBegin	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:

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.

## 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.)

### 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 Thenbegin	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

# Williams Awesome Oscillator Indicator and Strategy

## Awesome Oscillator

This is a very simple yet telling analysis.  Here is the EasyLanguage:

``[LegacyColorValue = true];                     Vars:oscVal(0),mavDiff(0);                    mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);Plot3( 0, "ZeroLine" ) ;if currentbar>=1 then	if oscVal>oscVal[1] then plot1(mavDiff,"+AO")	else plot2(mavDiff,"-AO")``
Williams Awesome Oscillator Source Code

And here is what it looks like:

The code reveals a value that oscillates around 0.  First calculate the difference between the 5-day moving average of the daily midPoint (H+ L)/2 and the 34-day moving average of the midPoint.    A positive value informs us that the market is in a bullish stance whereas a negative represents a bearish tone.  Basically, the positive value is simply stating the shorter-term moving average is above the longer term and vice versa. The second step in the indicator calculation is to subtract the 5-day moving average of the differences from the current difference.  If the second calculation is greater than the prior day’s calculation, then plot the original calculation value as green (AO+).  If it is less (A0-), then paint the first calculation red.  The color signifies the momentum between the current and the five-day smoothed value.

## Awesome Indicator Strategy

``mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);                                     mp = marketPosition;mavUp = countIf(mavDiff > 0,30);mavDn = countIf(mavDiff < 0,30);value1 = countIf(oscVal > oscVal[1],10);oscRatio = value1/10*100;``
The beginning of an AO based Strategy

Here I am using the very handy countIf function.  This function will tell you how many times a Boolean comparison is true out of the last N days.  Her I use the function twice, but I could have replaced the second function call with mavDn = 30 – mavUp.  So, I am counting the number of occurrences of when the mavDiff is positive and negative over the past 30-days.  I also count the number of times the oscVal is greater than the prior oscVal.  In other words, I am counting the number of green bars.  I create a ratio between green bars and 10.  If there are six green bars, then the ratio equals 60% This indicates that the ratio of red bars would be 40%.  Based on these readings you can create trade entry directives.

``if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= obRatio thensellShort next bar at open;if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= osRatio Thenbuy next bar at open;       ``

If the number of readings out of the last 30 days is greater than numBarsAbove and mavDiff is of a certain magnitude and the oscillator ratio is greater than buyOSCRatio, then you can go short on the next open.  Here we are looking for the market to converge.  When these conditions are met then I think the market is overbought.  You can see how I set up the long entries.  As you can see from the chart it does a pretty good job.  Optimizing the parameters on the crude oil futures yielded this equity curve.

Not bad, but not statistically significant either.  One way to generate more trades is to install some trade management such as protective stop and profit objective.

Using a wide protective stop and large profit objective tripled the number of trades.  Don’t know if it is any better, but total performance was not derived from just a couple of trades.  When you are working with a strategy like this and overlay trade management you will often run into this situation.

Here we either get stopped out or take a profit and immediately reenter the market.  This occurs when the conditions are still met to short when we exit a trade.  The fix for this is to determine when an exit has occurred and force the entry trigger to toggle off.  But you have to figure out how to turn the trigger back on.  I reset the triggers based on the number of days since the triggers were turned off – a simple fix for this post.  If you want to play with this strategy, you will probably need a better trigger reset.

I am using the setStopLoss and setProfitTarget functionality via their own strategies – Stop Loss and Profit Target.  These functions allow exit on the same as entry, which can be useful.  Since we are executing on the open of the bar, the market could definitely move either in the direction of the stop or the profit.  Since we are using wide values, the probability of both would be minimal.  So how do you determine when you have exited a trade.  You could look the current bar’s marketPosition and compare it with the prior bar’s value, but this doesn’t work 100% of the time.  We could be flat at yesterday’s close, enter long on today’s open and get stopped out during the day and yesterday’s marketPosition would be flat and today’s marketPosition would be flat as well.  It would be as if nothing occurred when in fact it did.

Take a look at this code and see if it makes sense to you.

``if mp[1] = 1 and totalTrades > totTrades then	canBuy = False;		if mp[1] = -1 and totalTrades > totTrades then 	canShort = False;if mp[1] = 0 and totalTrades > totTrades thenBegin	if mavDiff[1] < 0 then canBuy = False;		if mavDiff[1] > 0 then canShort = False;end;totTrades = totalTrades;``
Watch for a change in totalTrades.

``if  not(canBuy) Then	if barsSince(canBuy=True,100,1,0) = 6 then		canBuy = True;if  not(canShort) Then	if barsSince(canShort=True,100,1,0) = 6 then		canShort = True;``

Complete strategy code:

``inputs:numBarsAbove(10),numBarsBelow(10),buyOSCRatio(60),shortOSRatio(40),minDiffAmt(2),numBarsTrigReset(6);Vars:canBuy(True),canShort(True),mp(0),totTrades(0),oscVal(0),mavDiff(0),oscRatio(0),mavUp(0),mavDn(0),stopLoss\$(1000);	                    mavDiff= Average((h+l)/2,5)-Average((h+l)/2,34);oscVal = mavDiff - average(mavDiff,5);                                     mp = marketPosition;mavUp = countIf(mavDiff > 0,30);mavDn = countIf(mavDiff < 0,30);value1 = countIf(oscVal > oscVal[1],10);oscRatio = value1/10*100; if  not(canBuy) Then	if barsSince(canBuy=True,100,1,0) = numBarsTrigReset then		canBuy = True;if  not(canShort) Then	if barsSince(canShort=True,100,1,0) = numBarsTrigReset then		canShort = True;if mp[1] = 1 and totalTrades > totTrades then	canBuy = False;		if mp[1] = -1 and totalTrades > totTrades then 	canShort = False;if mp[1] = 0 and totalTrades > totTrades thenBegin	if mavDiff[1] < 0 then canBuy = False;		if mavDiff[1] > 0 then canShort = False;end;if canShort and mavUp > numBarsAbove and mavDiff > minDiffAmt and oscRatio >= buyOSCRatio thensellShort next bar at open;if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= shortOSRatio Thenbuy next bar at open;       		totTrades = totalTrades;                           ``

# 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 variablex = 10def 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 scopemy_func()print("x outside my_func:", x)  # x is accessed from the global scopeprint("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 barsnumTimesCalled = 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.601230206.00 numTimesCalled  494.00 highPass[1]   -0.05 highPass[2]   -0.02 highPass[3]   -0.061230207.00 numTimesCalled  495.00 highPass[1]   -0.38 highPass[2]   -0.78 highPass[3]   -0.511230207.00 numTimesCalled  495.00 highPass[1]    0.04 highPass[2]   -0.05 highPass[3]   -0.021230208.00 numTimesCalled  496.00 highPass[1]    0.31 highPass[2]   -0.38 highPass[3]   -0.781230208.00 numTimesCalled  496.00 highPass[1]    0.16 highPass[2]    0.04 highPass[3]   -0.051230209.00 numTimesCalled  497.00 highPass[1]    0.49 highPass[2]    0.31 highPass[3]   -0.381230209.00 numTimesCalled  497.00 highPass[1]    0.15 highPass[2]    0.16 highPass[3]    0.041230210.00 numTimesCalled  498.00 highPass[1]    0.30 highPass[2]    0.49 highPass[3]    0.311230210.00 numTimesCalled  498.00 highPass[1]    0.07 highPass[2]    0.15 highPass[3]    0.161230213.00 numTimesCalled  499.00 highPass[1]    0.52 highPass[2]    0.30 highPass[3]    0.491230213.00 numTimesCalled  499.00 highPass[1]    0.08 highPass[2]    0.07 highPass[3]    0.151230214.00 numTimesCalled  500.00 highPass[1]    0.44 highPass[2]    0.52 highPass[3]    0.301230214.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.

# Have you discovered a seasonal tendency but can’t figure out how to test it?

Are there certain times of the year when a commodity increases in price and then recedes?  In many markets this is the case.  Crude oil seems to go up during the summer months and then chills out in the fall.  It will rise once again when winter hits.  Early spring might show another price decline.  Have you done your homework and recorded certain dates of the year to buy/sell and short/buyToCover.  Have you tried to apply these dates to a historical back test and just couldn’t figure it out?  In this post I am going to show how you can use arrays and loops to cycle through the days in your seasonal database (database might be too strong of a term here) and apply long and short entries at the appropriate times during the past twenty years of daily bar data.

## Build the Quasi-Database with Arrays

If you are new to EasyLanguage  you may not yet know what arrays are or you might just simply be scared of them.  Now worries here!  Most people bypass arrays because they don’t know how to declare them, and if they get passed that, how to manipulate them to squeeze out the data they need. You may not be aware of it, but if you have programmed in EasyLanguage the least bit, then you have already used arrays.  Check this out:

``if high > high[1] and low > low[1] andaverage(c,30) > average(c,30)[1] thenbuy next bar at open``

In reality the keywords high and low are really arrays.  They are lists that contain the entire history of the high and low prices of the data that is plotted on the chart.  And just like with declared arrays, you index these keywords to get historic data.  the HIGH[1] means the high of yesterday and the HIGH[2] means the high of the prior day.   EasyLanguage handles the management of these array-like structures.  In other words, you don’t need to keep track of the indexing – you know the [1] or [2] stuff.  The declaration of an array is ultra-simple once you do it a few times.  In our code we are going to use four arrays:

2. SellShort array
3. Sell array

Each of these arrays will contain the month and day of month when a trade is to be entered or exited.  Why not the year?  We want to keep things simple and buy/short the same time every year to see if there is truly a seasonal tendency.  The first thing we need to do is declare the four arrays and then fill them up.

``// use the keyword arrays and : semicolon// next give each array a name and specify the// max number of elements that each array can hold// the [100] part.  Each array needs to be initialized // and we do this by placing a zero (0) in parenthesesarrays: buyDates[100](0),sellDates[100](0),      shortDates[100](0),buyToCoverDates[100](0);// next you want the arrays that go together to have the same// index value - take a look at thisbuyDates[1] = 0415;sellDates[1] = 0515;buyDates[2] = 0605;sellDates[2] = 0830;shortDates[1] = 0915;buyToCoverDates[1] = 1130;shortDates[2] = 0215;buyToCoverDates[2] = 0330;// note the buyDates[1] has a matching sellDates[1]//          buyDates[2] has a matching sellDates[2]// -- and --// shortDates[1] has a matching buyToCoverDates[1]// shortDates[2] has a matching buyToCoverDates[2]``

Our simple database has been declared, initialized and populated.  This seasonal strategy will buy on:

• April 15th and Exit on May 15th
• June 5th and Exit on August 30th

It will sellShort on:

• September 15th and Cover on November 30th
• February 15th and Cover on March 30th

You could use this template and follow the pattern to add more dates to your database.  Just make sure nothing overlaps.

Now, each chart has N dates of history plotted from the left to right.  TradeStation starts out the test from the earliest date to the last date.  It does this by looping one day at a time.  The first thing we need to do is convert the bar date (TradeStation represents dates in a weird format – YYYMMDD – Jan 30, 2022 is represented by the number 1220130 – don’t ask why!!) to a format like the data that is stored in our arrays.   Fortunately, we don’t have to deal with the year and EasyLanguage provides two functions to help us out.

• Month(Date) = the month (1-12) of the current bar
• DayOfMonth(Date) = the day of the month of the current bar

All we need to do is use these functions to convert the current bar’s date into terms of our database, and then test that converted date against our database.  Take a look:

``//convert the date into our own terms//say the date is December 12//the month function returns 12 and the day of month returns 12// 12*100 + 12 = 1212 --> MMDD - just waht we need//notice I look at the date of tomorrow because I want to take//action on the open of tomorrow.currentMMDD = month(d of tomorrow)*100 + dayOfMonth(d of tomorrow);//You might need to study this a little bit - but I am looping through each//array to determine if a trade needs to be entered.//Long Seasonal Entries togglebuyNow = False;for n = 1 to numBuyDatesBegin	if currentMMDD[1] < buyDates[n]  and currentMMDD >= buyDates[n]   Then	Begin		buyNow = True;	end;end;//Short Seasonal Entries toggleshortNow = False;for n = 1 to numshortDatesBegin	if currentMMDD[1] < shortDates[n] and currentMMDD >= shortDates[n] Then	Begin		shortNow = True;	end;end;``
Date conversion and looping thru Database

This code might look a little daunting, but it really isn’t.  The first for-loop starts at 1 and goes through the number of buyDates.  The index variable is the letter n. The loop starts at 1 and goes to 2 in increments of 1.  Study the structure of the for-loop and let me know if you have any questions.  What do you think this code is doing.

``if currentMMDD[1] < buyDates[n] andcurrentMMDD >= buyDates[n] Then``

As you know the 15th of any month may fall on a weekend.  This code basically says, ” Okay if today is less than the buyDate and tomorrow is equal to or greater than buyDate, then tommorrow is either going to be the exact day of the month or the first day of the subsequent week (the day of month fell on a weekend.)  If tomorrow is a trade date, then a conditional buyNow is set to True.  Further down in the logic the trade directive is issued if buyNow is set to True.

### Total of 4 loops – 2 for each long/short entry and 2 for each long/short exit.

Here is the rest of the code:

``inputs: dollarProfit(5000),dollarLoss(3000);arrays: buyDates[100](0),sellDates[100](0),      shortDates[100](0),buyToCoverDates[100](0);       vars: n(0),mp(0),currentMMDD(0), 	   numBuyDates(0),numshortDates(0), 	   numSellDates(0),numBuyToCoverDates(0); 	    vars: buyNow(False),shortNow(False),       sellNow(False),buyToCoverNow(False);      // fill the arrays with dates - remember we are not pyramiding here//  use mmdd formatbuyDates[1] = 0415;sellDates[1] = 0515;buyDates[2] = 0605;sellDates[2] = 0830;numBuyDates = 2;numSellDates = 2;shortDates[1] = 0915;buyToCoverDates[1] = 1130;shortDates[2] = 0215;buyToCoverDates[2] = 0330;numshortDates = 2;numbuyToCoverDates = 2;mp = marketPosition;currentMMDD = month(d of tomorrow)*100 + dayOfMonth(d of tomorrow);//Long Seasonal Entries togglebuyNow = False;for n = 1 to numBuyDatesBegin	if currentMMDD[1] < buyDates[n]  and currentMMDD >= buyDates[n]   Then	Begin		buyNow = True;	end;end;//Short Seasonal Entries toggleshortNow = False;for n = 1 to numshortDatesBegin	if currentMMDD[1] < shortDates[n] and currentMMDD >= shortDates[n] Then	Begin		shortNow = True;	end;end;//Long Seasonal Exits togglesellNow = False;if mp = 1 ThenBegin	for n = 1 to numSellDates	Begin		if currentMMDD[1] < sellDates[n] and currentMMDD >= sellDates[n] Then		Begin			sellNow = True;		end;	end;end;//Short Seasonal Exits togglebuyToCoverNow = False;if mp = -1 ThenBegin	for n = 1 to numBuyToCoverDates	Begin		if currentMMDD[1] < buyToCoverDates[n] and currentMMDD >= buyToCoverDates[n] Then		Begin			buyToCoverNow = True;		end;	end;end;// Long entry executionif buyNow = True thenbegin	buy("Seas-Buy") next bar at open;end;// Long exit executionif mp = 1 thenbegin	if sellNow then	begin		sell("Long Exit") next bar at open;	end;end;// Short entry executionif shortNow thenbegin	sellShort("Seas-Short") next bar at open;end;// short exit executionif mp = -1 thenbegin	if buyToCoverNow then	begin		buyToCover("short Exit") next bar at open;	end;end; 	setStopLoss(dollarLoss);setProfitTarget(dollarProfit);``
Complete Seasonal Template EasyLanguage Code

Does it work?  It does – please take my word for it.  IYou can email me with any questions.  However, TS 10 just crashed on me and is wanting to update, but I need to kill all the processes before it can do a successful update.  Remember to always export your new code to an external location.  I will post an example on Monday Jan 30th.

# The Clear Out Pattern

This pattern has been around for many years, and is still useful today in a day trading scheme.  The pattern is quite simple:  if today’s high exceeds yesterday’s high by a certain amount, then sell short as the market moves back through yesterday’s high.  There are certain components of yesterday’s daily bar that are significant to day traders – the high, the low, the close and the day traders’ pivot.  Yesterday’s high is considered a level of resistance and is often tested.  Many times the market has just enough momentum to carry through this resistance level, but eventually peters out and then the bears will jump in and push the market down even more.  The opposite is true when the bulls take over near the support level of yesterday’s low.  Here is an example of Clear Out short and buy.

## How Do You Program this Simple Pattern?

The programming of this strategy is rather simple, if you are day trading.  The key components are toggles that track the high and low of the day as the market penetrate the prior day’s high and low.  Once the toggles are flipped on, then order directives can be placed.  A max. trade stop loss can easily be installed via the SetStopLoss(500) function.  You will also want to limit the number of entries, because in a congestive phase, this pattern could fire off multiple times.   Once you intuitively program this,  you will almost certainly run into an issue where a simple “trick” will bail you out.   Remember the code does exactly what you tell it to do. Take a look at these trades.

### Okay – Can you rely on a 5 minute bar then?

Five minute bar data has been the staple of day trading systems for many years.  However, if you want to test “bang-bang” algorithms you are probably better off dropping down to a N-seconds bar.  However, this strategy as a whole is not “bang-bang” so with a little trick you can get more accurate entries and exits.

### How Does the Trick Affect Performance?

Here are the results over the past four months on different time frame resolutions.

10 seconds bar would be the most accurate if slippage is acceptable.  And that is a big assumption on “bang-bang” days.

The one minute bar is close but September is substantially off.  Probably some “bang-bang” action.

This is close to the 10-second bar result.  Fast market or “bang-bang” trades were reduced or eliminated with the “trick”.

Surprisingly, the 5 minute bar without the “Trick” resembles the 10 seconds results.  But we know this is not accurate as trades are fired off in a manner that goes against reality.

The two following table shows the impact of a \$15 RT comm./slipp. per trade charge.

## Okay, Now That We Have That Figured Out How Do You Limit Trading After a Daily Max. Loss

Another concept I wanted to cover was limiting trades after a certain loss level was suffered on a daily basis.  In the code, I only wanted to enter trades as long as the max. daily loss was less than or equal to \$1,000   A fixed stop of \$500 on a per trade basis was utilized as well.  So, if you suffered two max. stop losses right off the bat (\$1,000), you could still take one more trade.  Now if you had a \$500 winner and two \$500 losses you could still take another trade.

If you are going to trade a system, you better trade it systematically!

## Now Onto the Code

``//Illustrate trade stoppage after a certain loss has been//experienced and creating realistic stop orders.inputs: maxDailyLoss(1000),startTime(0935);inputs: clrOutBuyPer(.10),clrOutShortPer(.10);vars: coBuy(False),coShort(False),canTrade(0);vars: beginOfDayProfit(0),beginOfDayTotTrades(0),mp(0);if t = startTime thenbegin	coBuy = False;	coShort = False;	beginOfDayProfit = netProfit;	beginOfDayTotTrades = totalTrades;end;canTrade = iff(t >=startTime and t < sess1EndTime,1,0);if  t >= startTime and h > highD(1) + clrOutBuyPer*(highD(1)-lowD(1)) thenbegin	coShort = True;end;if  t >= startTime and l < lowD(1) - clrOutShortPer*(highD(1)-lowD(1)) thenbegin	coBuy = True;end;mp = marketPosition;if canTrade = 1 and coShort and netProfit >= beginOfDayProfit - maxDailyLoss andc > highD(1) - minMove/priceScale then	 sellShort next bar at highD(1) - minMove/priceScale stop;	 if mp = -1 then // toggle to turn off coShort - must wait for set upbegin	coShort = False;end;if canTrade = 1 and coBuy and netProfit >= beginOfDayProfit - maxDailyLoss andc <  lowD(1) + minMove/priceScale then	buy next bar at lowD(1) + minMove/priceScale stop;	if mp = 1 thenbegin	coBuy = False;end;setStopLoss(500);setExitOnClose;``
Strategy in its Entirety

You need to capture the NetProfit sometime during the day before trading commences.  This block does just that.

``if t = startTime thenbegin	coBuy = False;	coShort = False;	beginOfDayProfit = netProfit;	beginOfDayTotTrades = totalTrades;end;``
Snippet that captures NetProfit at start of day

Now all you need to do is compare the current netProfit (EL keyword) to the beginOfDayProfit (user variable)If the current netProfit >= beginOfDayProfit – maxDailyLoss (notice I programmed greater than or equal to), then proceed with the next trade.  The rest of the logic is pretty self explanatory, but to drive the point home, here is how I make sure a proper stop order is placed.

``if canTrade = 1 and coShort and netProfit >= beginOfDayProfit - maxDailyLoss andc > highD(1) - minMove/priceScale then	 sellShort next bar at highD(1) - minMove/priceScale stop;	 if mp = -1 then // toggle to turn off coShort - must wait for set upbegin	coShort = False;end;``
Notice how I use the current bars Close - C and How I toggle coShort to False

## If You Like This – Make Sure You Get My Hi-Res Edition of Easing Into EasyLanguage

This is a typical project I discuss in the second book in the Easing Into EasyLanguage Trilogy.  I have held over the BLACK FRIDAY special, and it will stay in effect through December 31st.  Hurry, and take advantage of the savings.  If you see any mistakes, or just want to ask me a question, or have a comment, just shoot me an email.

# Can Futures Traders Trust Continuous Contracts? [Part – 2]

## Recap from Part -1

I had to wrap up Part -1 rather quickly and probably didn’t get my ideas across, completely.  Here is what we did in Part – 1.

1. used my function to locate the First Notice Date in crude
2. used the same function to print out exact EasyLanguage syntax
3. chose to roll eight days before FND and had the function print out pure EasyLanguage
4. the output created array assignments and loaded the calculated roll points in YYYMMDD format into the array
5.  visually inspected non-adjusted continuous contracts that were spliced eight days before FND
6. appended dates in the array to match roll points, as illustrated by the dip in open interest

Step 6 from above is very important, because you want to make sure you are out of a position on the correct rollover date.  If you are not, then you will absorb the discount between the contracts into your profit/loss when you exit the trade.

## Step 2 – Create the code that executes the rollover trades

Here is the code that handles the rollover trades.

``............rollArr[118]=20220314;rollArr[119]=20220411;rollArr[120]=20220512;rollArr[121]=20220613;rollArr[122]=20220712;rollArr[123]=20220812;//  If in a position and date + 1900000 (convert TS date format to YYYYMMDD),//  then exit long or short on the current bar's close and then re-enter//  on the next bar's openif d+19000000 = rollArr[arrCnt] thenbegin	condition1 = true; 	arrCnt = arrCnt + 1;	if marketPosition = 1 then	begin		sell("LongRollExit") this bar on close;		buy("LongRollEntry") next bar at open;	end;	if marketPosition = -1 then	begin		buyToCover("ShrtRollExit") this bar on close;		sellShort("ShrtRollEntry") next bar at open;	end;	end;``
Code to rollover open position

This code gets us out of an open position during the transition from the old contract to the new contract.  Remember our function created and loaded the rollArr for us with the appropriate dates.  This simulation is the best we can do – in reality we would exit/enter at the same time in the two different contracts.  Waiting until the open of the next bar introduces slippage.  However, in the long run this slippage cost may wash out.

## Step 3 – Create a trading system with entries and exits

The system will be a simple Donchian where you enter on the close when the bar’s high/low penetrates the highest/lowest low of the past 40 bars.  If you are long, then you will exit on the close of the bar whose low is less than the lowest low of the past 20 bars.  If short, get out on the close of the bar that is greater than the highest high of the past twenty bars.  The first test will show the result of using an adjusted continuous contract rolling 8 days prior to FND

This test will use the exact same data to generate the signals, but execution will take place on a non-adjusted continuous contract with rollovers.  Here data2 is the adjusted continuous contract and data1 is the non-adjusted.

Still a very nice trade, but in reality you would have to endure six rollover trades and the associated execution costs.

## Conclusion

Here is the mechanism of the rollover trade.

And now the performance results using \$30 for round turn execution costs.

### Now with rollovers

The results are very close, if you take into consideration the additional execution costs.  Since TradeStation is not built around the concept of rollovers, many of the trade metrics are not accurate.  Metrics such as average trade, percent wins, average win/loss and max Trade Drawdown will not reflect the pure algorithm based entries and exits.  These metrics take into consideration the entries and exits promulgated by the rollovers.  The first trade graphic where the short was held for several months should be considered 1 entry and 1 exit.  The rollovers should be executed in real time, but the performance metrics should ignore these intermediary trades.

I will test these rollovers with different algorithms, and see if we still get similar results, and will post them later.  As you can see, testing on non-adjusted data with rollovers is no simple task.  Email me if you would like to see some of the code I used in this post.