Category Archives: EasyLanguage Indicator

Should you use a profit taking algorithm in your Trend Following system?

If letting profits run is key to the success of a trend following approach, is there a way to take profit without diminishing returns?

Most trend following approaches win less than 40% of the time.   So, the big profitable trades are what saves the day for this type of trading approach.  However, it is pure pain to simply sit there and watch a large profit erode, just because the criteria to exit the trade takes many days to be met.

Three methods to take a profit on a Trend Following algorithm

  1.  Simple profit objective – take a profit at a multiple of market risk.
  2.  Trail a stop (% of ATR) after a profit level (% of ATR) is achieved.
  3. Trail a stop (Donchian Channel) after a profit level (% of ATR) is achieved.

Use an input switch to determine which exit to incorporate

Inputs: initCapital(200000),rskAmt(.02),
useMoneyManagement(False),exitLen(13),
maxTradeLoss$(2500),
// the following allows the user to pick
// which exit to use
// 1: pure profit objective
// exit1ProfATRMult allows use to select
// amount of profit in terms of ATR
// 2: trailing stop 1 - the user can choose
// the treshhold amount in terms of ATR
// to be reached before trailing begins
// 3: trailing stop 2 - the user can chose
// the threshold amount in terms of ATR
// to be reached before tailing begins
whichExit(1),
exit1ProfATRMult(3),
exit2ThreshATRMult(2),exit2TrailATRMult(1),
exit3ThreshATRMult(2),exit3ChanDays(5);
Exit switch and the parameters needed for each switch.

The switch determines which exit to use later in the code.  Using inputs to allow the user to change via the interface also allows us to use an optimizer to search for the best combination of inputs.  I used MultiCharts Portfolio Trader to optimize across a basket of 21 diverse markets.  Here are the values I used for each exit switch.

MR = Market risk was defined as 2 X avgTrueRange(15).

  • Pure profit objective -Multiple from 2 to 10 in increments of 0.25.  Take profit at entryPrice + or – Profit Multiple X MR
  • Trailing stop using MR – Profit Thresh Multiple from 2 to 4 in increments of 0.1.  Trailing Stop Multiple from 1 to 4 in increments of 0.1.
  • Trailing stop using MR and Donchian Channel – Profit Thresh Multiple from 2 to 4 in increments of 0.1.  Donchian length from 3 to 10 days.

Complete strategy code incorporating exit switch.  This code is from Michael Covel’s 2005 Trend Following book (Covel, Michael. Trend Following: How Great Traders Make Millions in Up or Down Markets. FT Press, 2005.)  This strategy is highlighted in my latest installment in my Easing into EasyLanguage series – Trend Following edition.


vars:buyLevel(0),shortLevel(0),longExit(0),shortExit(0);

Inputs: initCapital(200000),rskAmt(.02),
useMoneyManagement(False),exitLen(13),
maxTradeLoss$(2500),whichExit(1),
exit1ProfATRMult(3),
exit2ThreshATRMult(2),exit2TrailATRMult(1),
exit3ThreshATRMult(2),exit3ChanDays(5);

Vars: marketRisk(0), workingCapital(0),
marketRisk1(0),marketRisk2(0),
numContracts1(0),numContracts2(0);

//Reinvest profits? - uncomment the first line and comment out the second
//workingCapital = Portfolio_Equity-Portfolio_OpenPositionProfit;
workingCapital = initCapital;


buyLevel = highest(High,89) + minMove/priceScale;
shortLevel = lowest(Low,89) - minMove/priceScale;
longExit = lowest(Low,exitLen) - minMove/priceScale;
shortExit = highest(High,exitLen) + minMove/priceScale;

marketRisk = avgTrueRange(15)*2*BigPointValue;
marketRisk1 =(buyLevel - longExit)*BigPointValue;
marketRisk2 =(shortExit - shortLevel)*BigPointValue;
marketRisk1 = minList(marketRisk,marketRisk1);
marketRisk2 = minList(marketRisk,marketRisk2);

numContracts1 = (workingCapital * rskAmt) /marketRisk1;
numContracts2 = (workingCapital * rskAmt) /marketRisk2;

if not(useMoneyManagement) then
begin
numContracts1 = 1;
numContracts2 =1;
end;

numContracts1 = maxList(numContracts1,intPortion(numContracts1)); {Round down to the nearest whole number}
numContracts2 = MaxList(numContracts2,intPortion(numContracts1));


if c < buyLevel then buy numContracts1 contracts next bar at buyLevel stop;
if c > shortLevel then Sellshort numContracts2 contracts next bar at shortLevel stop;

buytocover next bar at shortExit stop;
Sell next bar at longExit stop;

vars: marketRiskPoints(0);
marketRiskPoints = marketRisk/bigPointValue;
if marketPosition = 1 then
begin
if whichExit = 1 then
sell("Lxit-1") next bar at entryPrice + exit1ProfATRMult * marketRiskPoints limit;
if whichExit = 2 then
if maxcontractprofit > (exit2ThreshATRMult * marketRiskPoints ) * bigPointValue then
sell("Lxit-2") next bar at entryPrice + maxContractProfit/bigPointValue - exit2TrailATRMult*marketRiskPoints stop;
if whichExit = 3 then
if maxcontractprofit > (exit3ThreshATRMult * marketRiskPoints ) * bigPointValue then
sell("Lxit-3") next bar at lowest(l,exit3ChanDays) stop;
end;

if marketPosition = -1 then
begin
if whichExit = 1 then
buyToCover("Sxit-1") next bar at entryPrice - exit1ProfATRMult * marketRiskPoints limit;
if whichExit = 2 then
if maxcontractprofit > (exit2ThreshATRMult * marketRiskPoints ) * bigPointValue then
buyToCover("Sxit-2") next bar at entryPrice - maxContractProfit/bigPointValue + exit2TrailATRMult*marketRiskPoints stop;
if whichExit = 3 then
if maxcontractprofit > (exit3ThreshATRMult * marketRiskPoints ) * bigPointValue then
buyToCover("Sxit-3") next bar at highest(h,exit3ChanDays) stop;
end;

setStopLoss(maxTradeLoss$);

Here’s the fun code from the complete listing.

vars: marketRiskPoints(0);
marketRiskPoints = marketRisk/bigPointValue;
if marketPosition = 1 then
begin
if whichExit = 1 then
sell("Lxit-1") next bar at entryPrice + exit1ProfATRMult * marketRiskPoints limit;
if whichExit = 2 then
if maxContractProfit > (exit2ThreshATRMult * marketRiskPoints ) * bigPointValue then
sell("Lxit-2") next bar at entryPrice + maxContractProfit/bigPointValue - exit2TrailATRMult*marketRiskPoints stop;
if whichExit = 3 then
if maxContractProfit > (exit3ThreshATRMult * marketRiskPoints ) * bigPointValue then
sell("Lxit-3") next bar at lowest(l,exit3ChanDays) stop;
end;

if marketPosition = -1 then
begin
if whichExit = 1 then
buyToCover("Sxit-1") next bar at entryPrice - exit1ProfATRMult * marketRiskPoints limit;
if whichExit = 2 then
if maxContractProfit > (exit2ThreshATRMult * marketRiskPoints ) * bigPointValue then
buyToCover("Sxit-2") next bar at entryPrice - maxContractProfit/bigPointValue + exit2TrailATRMult*marketRiskPoints stop;
if whichExit = 3 then
if maxContractProfit > (exit3ThreshATRMult * marketRiskPoints ) * bigPointValue then
buyToCover("Sxit-3") next bar at highest(h,exit3ChanDays) stop;
end;

The first exit is rather simple – just get out on a limit order at a nice profit level.  The second and third exit mechanisms are a little more complicated.  The key variable in the code is the maxContractProfit keyword.  This value stores the highest level, from a long side perspective, reached during the life of the trade.  If max profit exceeds the exit2ThreshATRMult, then trail the apex by exit2TrailATRMult.  Let’s take a look at the math from a long side trade.

if maxContractProfit > (exit2ThreshATRMult * marketRiskPoints ) * bigPointValue

Since maxContractProfit is in dollar you must convert the exit2ThreshATRMult X marketRiskPoints into dollars as well.  If you review the full code listing you will see that I convert the dollar value, marketRisk, into points and store the value in marketRiskPoints.  The conversion to dollars is accomplished by multiplying the product by bigPointValue.

sell("Lxit-2") next bar at
entryPrice + maxContractProfit / bigPointValue - exit2TrailATRMult * marketRiskPoints stop;

I know this looks complicated, so let’s break it down.  Once I exceed a certain profit level, I calculate a trailing stop at the entryPrice plus the apex in price during the trade (maxContractProfit / bigPointValue) minus the exit2TrailATRMult X marketRiskPoints. If the price of the market keeps rising, so will the trailing stop.  That last statement is not necessarily true, since the trailing stop is based on market volatility in terms of the ATR.  If the market rises a slight amount, and the ATR increases more dramatically, then the trailing stop could actually move down.  This might be what you want.  Give the market more room in a noisier market.  What could you do to ratchet this stop?  Mind your dollars and your points in your calculations.

The third exit uses the same profit trigger, but simply installs an exit based on a shorter term Donchian channel.  This is a trailing stop too, but it utilizes a chart point to help define the exit price.

Results of the three exits

Exit 1 – Pure Profit Objective

Take a profit on a limit order once profit reaches a multiple of market risk aka 2 X ATR(15).

Pure profit object. Profit in terms of ATR or perceived market risk.

The profit objective that proved to be the best was using a multiple of 7.  A multiple of 10 basically negates the profit objective.   With this system several profit objective multiples seemed to work.

Exit – 2 – Profit Threshold and Trailing Stop in terms of ATR or market risk

Trail a stop a multiple of ATR after a multiple of ATR in profit is reached.

Trailing Stop using ATR
3-D view of parameters
3D view of parameter pairs

This strategy liked 3 multiples of ATR of profit before trailing and applying a multiple of 1.3 ATR as a stop.

Like I said in the video, watch out for 1.3 as you trailing amount multiple as it seems to be on a mountain ridge.

Exit – 3 – Profit Threshold in terms of ATR or market risk and a Donchain Channel trailing stop

Trail a stop using a Donchian Channel after a multiple of ATR in profit is reached.  Here was a profit level is reached, incorporate a tailing stop at the lowest low or the highest high of N days back.

Using Donchian Channel as trailing stop.
3-D view of parameters
3D view of parameters for Exit 3.

Conclusion

The core strategy is just an 89-day Donchian Channel for entry and a 13-Day Donchian Channel for exit.  The existing exit is a trailing exit and after I wrote this lengthy post, I started to think that a different strategy might be more appropriate.  However, as you can see from the contour charts, using a trailing stop that is closer than a 13-day Donchian might be more productive.   From this analysis you would be led to believe the ATR based profit and exit triggers (Exit #2) is superior.  But this may not be the case for all strategies.  I will leave this up to you to decide.  Here is the benchmark performance analysis with just the core logic.

Core logic results.

If you like this type of explanation and code, make sure you check at my latest book at amazon.com.  Easing into EasyLanguage – Trend Following Edition.

How to Fix the Fixed Fractional Position Size

The Fixed Fractional position sizing scheme is the most popular, so why does it need fixed?

Problems solved with Fixed Fractional:

  1. Efficient usage of trading capital
  2. Trade size normalization between different futures contracts
  3. Trade size normalization across different market environments

These are very good reasons why you should use positions sizing.  Problem #2 doesn’t apply if you are only trading one market.  This sounds idyllic, right?  It solves these two problems, but it introduces a rather bothersome side effect – huge draw down.  Well, huge draw down in absolute terms.  Draw downs when using a fixed fractional approach are proportional to the prior run up.  If you make a ton of money on a prior trade, then your position sizing reflects that big blip in the equity curve.  So, if you have a large loser following a large winner, the draw down will be a function of the run up.  In most cases, a winning trading system using fixed fractional position sizing will scale profit up as well as draw down.  A professional money manager will look at the profit to draw down ratio instead of the absolute draw down value.  The efficient use of capital will reflect a smaller position size after a draw down, so that is good right?  It is unless you believe in a Martingale betting algorithm – double up on losses and halve winners.  Are we just stuck with large “absolute” draw downs when using this size scheme?

Possible solutions to fixing Fixed Fractional (FF)

The first thing you can do is risk less than the industry standard 2% per trade.  Using 1% will cause equity to grow at a slower rate and also reduce the inevitable draw down.  But this doesn’t really solve the problem as we are giving up the upside.  And that might be okay with you.  Profit will increase and you are using an algorithm for size normalization.  In this blog I am going to propose a trading equity adjustment feature while using FF.  What if we act like money managers, and you should even if you are trading your own personal money, and at the end of the year or month we take a little off the table (theoretically – we are not removing funds from the account just from the position sizing calculation) that is if there is any extra on the table.  This way we are getting the benefit of FF while removing a portion of the compounding effect, which reduces our allocation for the next time interval.  How do you program such a thing?  Well first off let’s code up the FF scheme.

positionSize = round((tradingCapital * riskPerTrade) / (avgTrueRange(30)*bigPointValue),0);

Nothing new here.  Simply multiply tradingCapital by the riskPerTrade (1 or 2%) and then divide by a formula that defines current and inherent market risk.  This is where you can become very creative.  You could risk the distance between entry and exit if you know those values ahead of time or you can use a value in terms of the current market.  Here I have chosen the 30-day average true range.  This value gives a value that predicts the market movement into the future.  However, this value only gives the expected market movement for a short period of time into the future.  You could us a multiplier since you will probably remain in a trade for more than a few days – that is if you are trying to capture the trend.  In my experiment I just use one as my multiplier.

Capture and store the prior year/month NetProfit

When I come up with a trading idea I usually just jump in and program it.  I don’t usually take time to see if Easy Language already provides a solution for my problem.   Many hours have been used to reinvent the wheel, which isn’t always a bad thing.  So, I try to take time and search the functions to see if the wheel already exists.  This time it looks like I need to create the wheel.  I will show the code first and then explain afterward.

inputs: useAllocateYearly(True),useAllocateMonthly(False),initCapital(100000),removePerProfit(0.50),riskPerTrade(0.01);
vars: tradingCapital(0),prevNetProfit(0),tradingCapitalAdjustment(0);
vars: oLRSlope(0),oLRAngle(0),oLRIntercept(0), oLRValueRaw(0),mp(0);
arrays: yearProfit[250](0),snapShotNetProfit[250](0);vars: ypIndex(0);


once
begin
tradingCapital = initCapital;
end;

if useAllocateYearly then
begin
value1 = year(d);
value2 = year(d[1]);
end;

if useAllocateMonthly then //remember make sure your array is 12XNumYears
begin
value1 = month(d);
value2 = month(d[1]);
end;

if useAllocateYearly or useAllocateMonthly then
begin
if value1 <> value2 then
begin
if ypIndex > 0 then
yearProfit[ypIndex] = prevNetProfit - snapShotNetProfit[ypIndex-1]
else
yearProfit[ypIndex] = prevNetProfit;

snapShotNetProfit[ypIndex] = prevNetProfit;
tradingCapitalAdjustment = yearProfit[ypIndex];
if yearProfit[ypIndex] > 0 then
tradingCapitalAdjustment = yearProfit[ypIndex] * (1-removePerProfit);
tradingCapital = tradingCapital + tradingCapitalAdjustment;
print(d,",",netProfit,",",yearProfit[ypIndex],",",tradingCapitalAdjustment,",",tradingCapital);
ypIndex +=1;
end;
end
else
tradingCapital = initCapital + netProfit;
Capture either the prior years or months net profit

I wanted to test the idea of profit retention on a monthly and yearly basis to see if it made a difference.  I also wanted to just use the vanilla version of FF.  The use of Arrays may not be necessary, but I didn’t know ahead of time.  When you program on the fly, which is also called “ad hoc” programming you create first and then refine later.  Many times, the “ad hoc” version turns out to be the best approach but may not be the most efficient.  Like writing a book, many times your code needs revisions.  When applying a study or strategy that uses dates to a chart, you don’t know exactly when the data starts so you always need to assume you are starting in the middle of a year.   If you are storing yearly data into an array, make sure you dimension you array sufficiently.  You will need 12X the number of years as the size you need to dimension your array if you want to store monthly data.

 


//250 element array will contain more than 20 years of monthly data
//You could increase these if you like just to be safe
arrays: yearProfit[250](0),snapShotNetProfit[250](0);
//Remember you dimension you arrray variable first and then
//Pass it a value that you want to initiate all the values
//in the array to equal
vars: ypIndex(0);
Dimension and Initiate Your Arrays

The first thing we need to do is capture the beginning of the year or month.  We can do this by using the year and month function.  If the current month or year value is not the same as the prior day’s month or year value, then we know we crossed the respective timeline boundary.  We are using two arrays, snapShotNetProfit and yearProfit (to save time I use this array to store monthlty values as well, when that option is chosen) and a single array index ypIndex.  If we have crossed the time boundary, the first thing we need to do is capture the EasyLanguage function NetProfit’s value.  NetProfit keeps track of the cumulative closed out trade profits and losses. Going forward in this description I am going to refer to a yearly reallocation.  If it’s the first year, the ypIndex will be zero, and in turn the first year’s profit will be the same as netProfit.  We store netProfit in the yearProfit array at the ypIndex location.  Since we are in a new year, we take a snapshot of netProfit and store it in the snapShotNetProfit array at the same ypIndex location.  You will notice I use the variable prevNetProfit in the code for netProfit.  Here is where the devil is in the details.  Since we are comparing today’s year value with yesterday’s year value and when they are different, we are already inside the new year, so we need to know yesterday’s netProfit.   Before you say it, you can’t pass netProfit a variable for prior values; you know like netProfit(1) or netProfit[1] – this is a function that has no historic values, but you can record the prior day’s value by using our own prevNetProfit  variable.  Now we need to calculate the tradingCapitalAdjustment.  The first thing we do is assign the variable the value held in  yearProfit[ypIndex].  We then test the yearProfit[ypIndex] value to see if it is positive.  If it is, then we multiply it by (1-removePerProfit).  If you want to take 75% of the prior year’s profit off the table, then you would multiply the prior year’s profit by 25%.  Let’s say you make $10,000 and you want to remove $7,500, then all you do is multiply $10,000 by 25%.  If the prior year’s netProfit is a loss, then this value flows directly through the code to the position sizing calculation (auto deallocation on a losing year).   If not, the adjusted profit portion of funds are deallocated in the position sizing equation.

The next time we encounter a new year, then we know this is the second year in our data stream, so we need to subtract last year’s snapshot of netProfit (or prevNetProfit) from the current netProfit.  This will give us the change in the yearly net profit.  We stuff this information into the yearProfit array.  The snapShotNetProfit is stuffed with the current prevNetProfit.  ypIndex is incremented every time we encounter a new yearNotice how I increment the ypIndex – it is incremented after all the calculations in the new year.  The tradingCapitalAdjustment is then calculated with the latest information.

Here is a table of how the tradingCapital and profit retention adjustment are calculated.  A yearly profit adjustment only takes place after a profitable year.  A losing year passes without adjustment.

All tests were carried out on the trend friendly crude oil futures with no execution costs from 2006 thru 2/28/2204.

See how money is removed from the allocation model after winning years.

Here are some optimization tests with 75% profit retention on yearly and monthly intervals.

Yearly First-

Yearly retention with no stop loss or break-even levels.

Now Monthly-

Monthly retention with no stop loss or break-even levels.

What if we didn’t reallocate on any specific interval?

Huge drawdowns with very little change in total profit.

Add some trade management into the mix.

Here we optimize a protective stop and a break-even level to see if we can juice the results.  All the trade management is on a position basis.

200K with No Reallocating with $14k and $8.5 stop/break-even levels [ranked by Profit Factor]
No position sizing and no reallocation with $5K and $10K stop/break-even levels

200K and monthly reallocating with $7K and $5.5K stop/break-even levels [BEST PROFIT FACTOR]
200K and monthly reallocating with $7K and $8.5K stop/break-even levels [2ND BEST PROFIT FACTOR]

Are we really using our capital in the most efficient manner?

If we retain profit, should we remove some of the loss form the position sizing engine as well.  All the tests I performed retained profit from the position size calculations.  I let the loss go full bore into the calculation.  This is a very risk averse approach.  Why don’t I retain 25% of losses and deduct that amount from the yearly loss and feed that into the position sizing engine.  This will be less risk averse – let’s see what it does.

Not as good.  But I could spend a week working different permutations and optimization sessions.

Are you wondering what Trend Following System I was using as the foundation of this strategy?  I used EasyLanguage’s Linear Regression function to create buy and short levels.  Here is the very simple code.

Value1 = LinearReg (Close, 60, 1, oLRSlope, oLRAngle, oLRIntercept, oLRValueRaw);

Value2 = oLRSlope;

Value3 = oLRAngle;

Value4 = oLRIntercept;

Value5 = oLRValueRaw;


//Basically I am buying/shorting on the change of the linear regression slope
//Also I have a volatility filter but it really isn't used
If value2 >=0 and value2[1] < 0 and avgTrueRange(30)*bigPointValue < 10000 then
buy positionSize contracts next bar at market;
If value2 <=0 and value2[1] > 0 and avgTrueRange(30)*bigPointValue < 10000 then
sellShort positionSize contracts next bar at market;

mp = marketPosition;

//I also have incorporated a 3XATR(30) disaster stop
if mp = 1 and c <= entryPrice - 3 * avgTrueRange(30) then sell next bar at market;
if mp = -1 and c >= entryPrice + 3 * avgTrueRange(30) then buyToCover next bar at market

If you want to see some more Trend Following models and their codes in EasyLanguage and TS-18 Python check out my TrendFollowing Guide and Kit.

Pyramania Levels with 24-Hour Session – Free Code

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

Get Your Copy Now!  On sale now for thru the end of 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.

Pyramania of @ES.D

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);
once
Begin
Array_SetMaxIndex(segmentBounds, numSegments);
end;

if d <> d[1] Then // only works on the @ES.D or any .D session
begin
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 = 1700
if t < calcTime(sessionEndTime(0,1),-barInterval) Then
begin
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);

once
Begin
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 interval
if t = calcTime(sessionStartTime(0,1),barInterval) Then
begin
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 you
if startTime > endTime then
begin
endTimeOffset = 0;
if t >= startTime+barInterval and t<= 2359 then
endTimeOffSet = 2400-endTime;
end;
if t-endTimeOffSet < endTime Then
begin
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.

Plots from 18:05 through midnight until 17:00 the next day.

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

 

 

 

 

The Day Trading Edition of Easing Into EasyLanguage Now Available!

Learn Pyramiding, Scaling In or Out, Camarilla, Break Out and Clear Out techniques in day trading environment.

Get Your Copy Now!
  • Chapter 1 – Open Range Break Out and other Sundries
  • Chapter 2 – Improving Our ORBO with Pattern Recognition
  • Chapter 3 – Time based Breakout
  • Chapter 4 – Trading After the Lunch Break
  • Chapter 5 – Extending Our Break Out Technology With Pyramiding and Scaling Out
  • Chapter 6 – Scaling Out of Pyramided and multiple Positions
  • Chapter 7 – Pyramania
  • Chapter 8 – Introduction to Zone Trading with the Camarilla
  • Chapter 9 – Day Trading Templates Appendix
A Chart from Chapter 8 – Camarilla Equation

Take a look at this function that spans the entire search space of all the combinations of the days of the week.

inputs: optimizeNumber(numericSimple);
arrays: dowArr[31]("");
vars: currDOWStr(""),daysOfWeek("MTWRF");

//Once
//begin
print(d," ",t," assigning list ");
dowArr[1]="MTWRF";dowArr[2]="MTWR";
dowArr[3]="MTWF";dowArr[4]="MTRF";
dowArr[5]="MWRF";dowArr[6]="TWRF";
dowArr[7]="MTW";dowArr[8]="MTR";
dowArr[9]="MTF";dowArr[10]="MWR";
dowArr[11]="MWF";dowArr[12]="MRF";
dowArr[13]="TWR";dowArr[14]="TWF";
dowArr[15]="TRF";dowArr[16]="WRF";
dowArr[17]="MT";dowArr[18]="MW";
dowArr[19]="MR";dowArr[20]="MF";
dowArr[21]="TW";dowArr[22]="TR";
dowArr[23]="TF";dowArr[24]="WR";
dowArr[25]="WF";dowArr[26]="RF";
dowArr[27]="M";dowArr[28]="T";
dowArr[29]="W";dowArr[30]="R";
dowArr[31]="F";
//end;

OptimizeDaysOfWeek = False;
if optimizeNumber > 0 and optimizeNumber < 32 Then
Begin
currDOWStr = midStr(daysOfWeek,dayOfWeek(d),1);
if inStr(dowArr[optimizeNumber],currDOWStr) <> 0 Then
OptimizeDaysOfWeek = True;
end;
All The Permutations of the Days of the Week

 

Trade after the Lunch Break in Apple

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:

Williams Awesome Oscillator

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 then
sellShort next bar at open;

if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= osRatio Then
buy next bar at open;
Trade Directives

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.

Too few trades!

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

Exiting while conditions to short are still turned on!

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 then
Begin
if mavDiff[1] < 0 then canBuy = False;
if mavDiff[1] > 0 then canShort = False;
end;

totTrades = totalTrades;
Watch for a change in totalTrades.

If we were long yesterday and totalTrades (builtin keyword/function) increases above my own totTrades, then we know a trade was closed out – a long trade that is.  A closed out short position is handled in the same manner.  What about when yesterday’s position is flat and totalTrades increases.  This means an entry and exit occurred on the current bar.  You have to investigate whether the position was either long or short.  I know I can only go long when mavDiff is less than zero and can only go short when mavDiff is greater than zero.  So, all you need to do is investigate yesterday’s mavDiff  to help you determine what position was entered and exited on the same day.  After you determine if an exit occurred, you need to update totTrades with totalTrades.  Once you determine an exit occurred you turn canBuy or canShort off.  They can only be turned back on after N bars have transpired since they were turned off.   I use my own barsSince function to help determine this.

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 then
Begin
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 then
sellShort next bar at open;

if canBuy and mavDn > numBarsBelow and mavDiff < -1*minDiffAmt and oscRatio <= shortOSRatio Then
buy next bar at open;

totTrades = totalTrades;
Inputs used to generate the equity curve.

Reentry of Long at better price

How to reenter at a better price after a stop loss

A reader of this blog wanted to know how he could reenter a position at a better price if the first attempt turned out to be a loser.  Here I am working with 5 minute bars, but the concepts work for daily bars too.  The daily bar is quite a bit easier to program.

ES.D Day Trade using 30 minute Break Out

Here we are going to wait for the first 30 minutes to develop a channel at the highest high and the lowest low of the first 30 minutes.  After the first 30 minutes and before 12:00 pm eastern, we will place a buy stop at the upper channel.  The initial stop for this initial entry will be the lower channel.  If we get stopped out, then we will reenter long at the midpoint between the upper and lower channel.  The exit for this second entry will be the lower channel minus the width of the upper and lower channel.

Here are some pix.  It kinda, sorta worked here – well the code worked perfectly.   The initial thrust blew through the top channel and then immediately consolidated, distributed and crashed through the bottom channel.  The bulls wanted another go at it, so they pushed it halfway to the midpoint and then immediately the bears came in and played tug of war.  In the end the bulls won out.

Initial Break Out Failed. But 2nd Entry made a little.

Here the bulls had initial control and then the bears, and then the bulls and finally the bears tipped the canoe over.

We gave it the old college try didn’t we fellas.

This type of logic can be applied to any daytrade or swing trade algorithm.  Here is the code for the strategy.

//working with 5 minute bars here
//should work with any time frame

input:startTradeTime(0930),numOfBarsHHLL(6),stopTradeTime(1200),maxLongEntriesToday(2);
vars: startTime(0),endTime(0),
barCountToday(0),totTrades(0),mp(0),longEntriesToday(0),
periodHigh(-99999999),periodLow(99999999);

startTime = sessionStartTime(0,1);
endTime = sessionStartTime(0,1);


if t = calcTime(startTime,barInterval) Then
begin
periodHigh = -99999999;
periodLow = 99999999;
barCountToday = 1;
totTrades = totalTrades;
end;

if barCountToday <= numOfBarsHHLL Then
Begin
periodHigh = maxList(periodHigh,h);
periodLow = minList(periodLow,l);
end;

barCountToday = barCountToday + 1;

longEntriesToday = totalTrades - totTrades;

mp = marketPosition;
if t <= stopTradeTime and barCountToday > numOfBarsHHLL Then
Begin
if longEntriesToday = 0 then
buy("InitBreakOut") next bar at periodHigh + minMove/priceScale stop;
if longEntriesToday = 1 Then
buy("BetterBuy") next bar at (periodHigh+periodLow)/2 stop;
end;

if mp = 1 then
if longEntriesToday = 0 then sell("InitXit") next bar at periodLow stop;
if longEntriesToday = 1 then sell("2ndXit") next bar at periodLow - (periodHigh - periodLow) stop;

SetExitOnClose;

The key concepts here are the time constraints and how I count bars to calculate the first 30 – minute channel.  I have had problems with EasyLanguages’s entriesToday function, so I like how I did it here much better.  On the first bar of the day, I set my variable totTrades to EasyLanguages built-in totalTrades (notice the difference in the spelling!)  The keyword TotalTrades is immediately updated when a trade is closed out.  So, I simply subtract my totTrades (the total number of trades at the beginning of the day) from totalTrades.  If totalTrades  is incremented (a trade is closed out) then the difference between the two variables is 1.  I assign the difference of these two values to longEntriesToday.  If longEntriesToday = 1, then I know I have entered long and have been stopped out.  I then say, OK let’s get back long at a better price – the midpoint.  I use the longEntriesToday variable again to determine which exit to use.  With any luck the initial momentum that got us long initially will work its way back into the market for another shot.

It’s Easy to Create  a Strategy Based Indicator

Once you develop a strategy, the indicator that plots entry and exit levels is very easy to derive.  You have already done the math – just plot the values.  Check this out.

//working with 5 minute bars here
//should work with any time frame

input:startTradeTime(0930),numOfBarsHHLL(6);
vars: startTime(0),endTime(0),
barCountToday(0),periodHigh(-99999999),periodLow(99999999);

startTime = sessionStartTime(0,1);
endTime = sessionStartTime(0,1);


if t = calcTime(startTime,barInterval) Then
begin
periodHigh = -99999999;
periodLow = 99999999;
barCountToday = 1;
end;

if barCountToday <= numOfBarsHHLL Then
Begin
periodHigh = maxList(periodHigh,h);
periodLow = minList(periodLow,l);
end;

if barCountToday < numOfBarsHHLL Then
begin
noPlot(1);
noPlot(2);
noPlot(3);
noPlot(4);
End
Else
begin
plot1(periodHigh,"top");
plot2((periodHigh+periodLow)/2,"mid");
plot3(periodLow,"bot");
plot4(periodLow - (periodHigh - periodLow),"2bot");
end;

barCountToday = barCountToday + 1;

So, that’s how you do it.  You can use this code as a foundation for any system that wants to try and reenter at a better price.  You can also use this code to develop your own time based break out strategy.  In my new book, Easing Into EasyLanguage – the Daytrade Edition I will discuss topics very similar to this post.

 

 

 

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.

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 open

if d+19000000 = rollArr[arrCnt] then
begin
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

Nice Trade. Around August 2014

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.

Same Trade but with rollovers

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.

Roll out of old contract and roll into new contract

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

No-Rollovers

No Rollovers?

Now with rollovers

Many more trades with the 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.

Can Futures Traders Trust Continuous Contracts? [Part – 1]

 Well You Have To, Don’t You?

When I worked at Futures Truth, we tested everything with our Excalibur software.  This software used individual contract data and loaded the entire history (well, the part we maintained) of each contract into memory and executed rollovers at a certain time of the month.  Excalibur had its limitations as certain futures contracts had very short histories and rollover dates had to be predetermined – in other words, they were undynamic.  Over the years, we fixed the short history problem by creating a dynamic continuous contract going back in time for the number of days required for a calculation.  We also fixed the database with more appropriate rollover frequency and dates.  So in the end, the software simulated what I had expected from trading real futures contracts.  This software was originally written in Fortran and for the Macintosh.  It also had limitations on portfolio analysis as it worked its way across the portfolio, one complete market at a time.   Even with all these limitations, I truly thought that the returns more closely mirrored what a trader might see in real time.  Today, there aren’t many, if any, simulation platforms that test on individual contracts.  The main reasons for this are the complexity of the software, and the database management.  However, if you are willing to do the work, you can get close to testing on individual contract data with EasyLanguage.

Step 1 – Get the rollover dates

This is critical as the dates will be used to roll out of one contract and into another.  In this post, I will test a simple strategy on the crude futures.  I picked crude because it rolls every month.   Some data vendors use a specific date to roll contracts, such as Pinnacle data.  In real time trading, I did this as well.  We had a calendar for each month, and we would mark the rollover dates for all markets traded at the beginning of each month.  Crude was rolled on the 11th or 12th of the prior month to expiration.  So, if we were trading the September 2022 contract, we would roll on August 11th.  A single order (rollover spread) was placed to sell (if long) the September contract and buy the October contract at the market simultaneously.  Sometimes we would leg into the rollover by executing two separate orders – in hopes of getting better execution.  I have never been able to find a historic database of when TradeStation performs its rollovers.  When you use the default @CL symbol, you allow TradeStation to use a formula to determine the best time to perform a rollover.  This was probably based on volume and open interest.  TradeStation does allow you to pick several different rollover triggers when using their continuous data.

You can choose type of trigger – (3) Dynamic or (4) Time based.

I am getting ahead of myself, because we can simply use the default @CL data to derive the rollover dates (almost.)  Crude oil is one of those weird markets where LTD (last trade days) occurs before FND (first notice day.)  Most markets will give you a notice before they back up a huge truck and dump a 1000 barrels of oil at your front door.   With crude you have to be Johnny on the spot!  Rollover is just a headache when trading futures, but it can be very expensive headache if you don’t get out in time.  Some markets are cash settled so rollover isn’t that important, but others result in delivery of the commodity.  Most clearing firms will help you unwind an expired contract for a small fee (well relatively small.)  In the good old days your full service broker would give you heads up.  They would call you and say, “George you have to get out of that Sept. crude pronto!”  Some firms would automatically liquidate the offending contract on your behalf – which sounds nice but it could cost you.  Over my 30 year history of trading futures I was caught a few times in the delivery process.   You can determine these FND and LTD from the CME website.  Here is the expiration description for crude futures.

Trading terminates 3 business day before the 25th calendar day of the month prior to the contract month. If the 25th calendar day is not a business day, trading terminates 4 business days before the 25th calendar day of the month prior to the contract month.

You can look this up on your favorite broker’s website or the handy calendars they send out at Christmas.  Based on this description, the Sept. 2022 Crude contract would expire on August 20th and here’s why

  • August 25 is Tuesday
  • August 24 is Monday- DAY1
  • August 21 is Friday – DAY2
  • August 20 is Thursday – DAY3

This is the beauty of a well oiled machine or exchange.  The FND will occur exactly as described.  All you need to do is get all the calendars for the past ten years and find the 25th of the month and count back three business days.  Or if the 25 falls on a weekend count back four business days.  Boy that would be chore, would it not?  Luckily, we can have the data and an  EasyLanguage script do this for us.  Take a look at this code and see if it makes any sense to you.

Case "@CL":
If dayOfMonth(date) = 25 and firstMonthPrint = false then
begin
print(date[3]+19000000:8:0);
firstMonthPrint = true;
end;
If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then
begin
print(date[4]+19000000:8:0);
firstMonthPrint = true;
end;
Code to printout all the FND of crude oil.

I have created a tool to print out the FND or LTD of any commodity futures by examining the date.  In this example, I am using a Switch-Case to determine what logic is applied to the chart symbol.  If the chart symbol is @CL, I look to see if the 25th of the month exists and if it does, I print the date 3 days prior out.  If today’s day of month is greater than 25 and the prior day’s day of month is less than 25, I know the 25th occurred on a weekend and I must print out the date four bars prior.  These dates are FN dates and cannot be used as is to simulate a rollover. You had best be out before the FND to prevent the delivery process.   Pinnacle Date rolls the crude on the 11th day of the prior month for its crude continuous contracts.  I aimed for this day of the month with my logic.  If the FND normally fell on the 22nd of the month, then I should back up either 9 or 10 business days to get near the 11th of the month.   Also I wanted to use the output directly in an EasyLanguage strategy so I modified my output to be exact EasyLanguage.

Case "@CL":
If dayOfMonth(date) = 25 and firstMonthPrint = false then
begin
value1 = value1 + 1;
print("rollArr[",value1:1:0,"]=",date[9]+19000000:8:0,";");
firstMonthPrint = true;
end;
If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then
begin
value1 = value1 + 1;
print("rollArr[",value1:1:0,"]=",date[10]+19000000:8:0,";");
// print(date[4]+19000000:8:0);
firstMonthPrint = true;
end;


// example of output

rollArr[103]=20210312;
rollArr[104]=20210412;
rollArr[105]=20210512;
rollArr[106]=20210614;
rollArr[107]=20210712;
rollArr[108]=20210812;
rollArr[109]=20210913;
rollArr[110]=20211012;
rollArr[111]=20211111;
rollArr[112]=20211210;
rollArr[113]=20220111;
rollArr[114]=20220211;
rollArr[115]=20220314;
rollArr[116]=20220411;
rollArr[117]=20220512;
rollArr[118]=20220610;
rollArr[119]=20220712;
rollArr[120]=20220812;
Code to print our 9 or 10 bars prior to FND in actual EasyLanguage

Now. that I had the theoretical rollover dates for my analysis I had to make sure the data that I was going to use matched up exactly.  As you saw before, you can pick the rollover date for your chart data.   And you can also determine the discount to add or subtract to all prior data points based on the difference between the closing prices at the rollover point.  I played around with the number of days prior to FND and selected non adjusted for the smoothing of prior data.

Actual data I simulated rollovers with.

How did I determine 8 days Prior to First Notice Date?  I plotted different data using a different number of days prior and determined 8 provided a sweet spot between the old and new contract data’s open interest.  Can you see the rollover points in the following chart?  Ignore the trades – these were a beta test.

The Open Interest Valley is the rollover date.

The dates where the open interest creates a valley aligned very closely with the dates I printed out using my FND date finder function.  To be safe, I compared the dates and fixed my array data to match the chart exactly.  Here are two rollover trades – now these are correct.

Using an adjusted continuous contract you would not see these trades.

This post turned out to be a little longer than I thought, so I will post the results of using an adjusted continuous contract with no rollovers, and the results using non-adjusted concatenated contracts with rollovers.  The strategy will be a simple 40/20 bar Donchian entry/exit.  You maybe surprised by the results – stay tuned.

Advanced Topics Edition of Easing Into EasyLanguage – NOW AVAILABLE!

Advanced Edition is now Available

Advanced Topics Cover

The last book in the Easing Into EasyLanguage Series has finally been put to bed.  Unlike the first two books in the series, where the major focus and objective was to introduce basic programming ideas to help get  new EasyLanguages users up to speed, this edition introduces more Advanced topics and the code to develop and program them.

Buy this book to learn how to overcome the obstacles that may be holding you back from developing your ideal Analysis Technique. This book could be thousands of pages long because the number of topics could be infinite. The subjects covered in this edition provide a great cross-section of knowledge that can be used further down the road. The tutorials will cover subjects such as:

  • Arrays – single and multiple dimensions
  • Functions – creation and communicating via Passed by Value and Passed by Reference
  • Finite State Machine – implemented via the Switch-Case programming construct
  • String Manipulation – construction and deconstruction of strings using EasyLanguage functions
  • Hash Table and Hash Index – a data structure(s) that contains unique addresses of bins that can contain N records
  • Using Hash Tables – accessing and storing data related to unique Tokens
  • Token Generation – an individual instance of a type of symbol
  • Seasonality – in depth analysis of the Ruggiero/Barna and Sheldon Knight Universal Seasonal data
  • File Manipulation – creating, deleting and writing to external files
  • Using Projects – organizing Analysis Techniques by grouping support functions and code into a single entity
  • Text Graphic Objects – extracting text from a chart and storing the object information in arrays for later development into a strategy
  • Commitment of Traders Report – TradeStation only (not MultiChart compatible) code. Converting the COT indicator and using the FundValue functionality to develop a trading strategy
  • Multiple Time Frame based indicator – use five discrete time frames and pump the data into a single indicator – “traffic stop light” feel

Once you become a programmer, of any language, you must continually work on honing your craft.  This book shows you how to use your knowledge as building blocks to complete some really cool and advanced topics.

Take a look at this video: