Category Archives: Complete EasyLanguage Systems

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.

Buy in November, Sell in May Strategy Framework

Thanks to Jeff Swanson for the basis of this post

I like to post something educational at least once a month.  Sometimes, it’s difficult to come up with stuff to write about.  Jeff really got me thinking with his Buy November… post.  Check out his post “Riding the Market Waves:  How to Surf Seasonal Trends to Trading Success.”  Hopefully you have read his post and now have returned.  As you know, the gist of his post was to buy in November and sell in May.  Jeff was gracious enough to provide analysis, source and suggestions for improvement for this base strategy.

Why Change Jeff’s Code to a Framework?

I found Jeff’s post most intriguing, so the first think I start thinking about is how could I optimize the buy and sell months, a max loss, the three entry filters that he provided and in addition add a sell short option.  If you have read my books, you know I like to develop frameworks for further research when I program an algorithm or strategy.  Here is how I developed the framework:

  1. Optimize the entry month from January to December or 1 to 12.
  2. Optimize the exit month from January to December or 1 to 12.
  3. Optimize to go long or go short or 1 to 2 (to go short any number other than 1 really).
input: startMonth(11),endMonth(5),
longOrShort(1),


currentMonth = Month(Date of tomorrow);
If currentMonth = startMonth and mp = 0 and entriesThisMonth = 0 Then
begin
// a trade can only occur if canBuy is True - start month is active as
// long as the filtering allows it. Until the filter is in alignment
// keep looking for a trading during the ENTIRE startMonth
if longOrShort = 1 and canBuy then
entriesThisMonth = 1;
if longOrShort = 1 and canBuy then
buy("Buy Month") iShares contracts next bar at market;
if longOrShort <> 1 and canShort then
sellShort("Short Month") iShares contracts next bar at market;
if longOrShort = -1 and canShort then
entriesThisMonth = 1;
end;

if CurrentMonth = endMonth Then
begin
if longOrShort = 1 then
sell("L-xit Month") currentShares contracts next bar at market
else
buyToCover("S-xit Month") currentShares contracts next bar at market;
end;

if mp = 1 then
sell("l-xitMM") next bar at entryPrice - maxTradeRisk/bigPointValue stop;
if mp =-1 then
buyToCover("s-xitMM") next bar at entryPrice + maxTradeRisk/bigPointValue stop;
Snippet of the bones with extra flavor to enter and exit on certain months

You can see that I have provided the three inputs:

  1. startMonth
  2. endMonth
  3. longOrShort

I get the currentMonth by peeking at the date of tomorrow and passing this date to the month function.  If tomorrow is the first day of the month that I want to enter a long or short and the current market position (mp), and entriesThisMonth = 0, then a long or short position will be initiated.  If the filters I describe a little later allow it, I know that I will be executing a trade tomorrow, and I can go ahead assign a 1 to entries this month.  Why do I do this?  Just wait and you will see.   Long entries depend on the variable longOrShort being equal to 1 and the toggle canBuy set to True.  What is canBuy.  Just wait and you will see.  The sell short is similar, but conversely longOrShort needs to not equal 1.  In addition, canShort needs to be true too.

If the currentMonth = endMonth, then based on the market position a sell or a buy to cover will be executed.

How to add filters to Determine canBuy and canShort

inputs: 
useMACDFilter(1), MACDFast(9), MACDSlow(26), MACDAvgLen(9), MACDLevel(0),
useMAFilter(0), MALength(30),
useRSIFilter(0), RSILength(14), RSILevel(50)

RSIVal = rsi(close,RSILength);
MAVal = xAverage(close,MALength);
MACDVal = macd(close,MACDFast,MACDSlow);
MACDAvg = xAverage(MACDVal,MACDAvgLen);

if useMACDFilter = 1 then
begin
canBuy = MACDVal > MACDLevel;
canShort = MACDVal < MACDLevel;
end;

if useMAFilter = 1 then
begin
canBuy = close > MAVal and canBuy;
canShort = close < MAVal and canShort;
end;

if useRSIFilter = 1 then
begin
canBuy = RSIVal > RSILevel and canBuy;
canShort = RSIVal < RSILevel and canShort;
end;
Calculate Filter Components and then test them

You cannot optimize a True to False toggle, but you can optimize 0 for off and 1 for on.  Here the useFilterName inputs are initially set to 0 or off.  Each filter indicator has respective inputs so that the filters can be calculated with the user’s input.  If the filters are equal to one, then a test to turn canBuy and canShort to on or off is laid out in the code.  Each test depends on either the state of price compared to the indicator value, or the indicator’s relationship to a user defined level or value.

Will this code test all the combination of the filters?

Yes!  F1 is Filter 1 and F2 is Filter 2 and F3 is Filter 3.  By optimizing each filter from 0 to 1, you will span this search space.

  • F1 = On; F2 = Off; F3 = Off
  • F1 = On; F2 = On; F3 = Off
  • F1 = On; F2 = On; F3 = On
  • F1 = Off; F2 = On; F3 = Off
  • F1 = Off; F2 = On; F3 = On
  • F1 = Off; F2 = Off: F3 = On
  • F1 = On; F2 = Off; F3 = On

You will notice I initially set canBuy and canShort to True and then turn them off if an offending filter occurs.  Notice how I AND the results for Filter 2 and Filter 3 with canBuy or canShort.  Doing this allows me to cascade the filter combinations.  I do want to test when all filters are in alignment.  In other words, they must all be True to initiate a position.

Should the Filters be Active During the Entire Entry Month?

What if the first day of the month arrives and you can’t initiate a trade due to a conflict of one of the filters.  Should we allow a trade later in the entry month if the filters align properly?  If we are testing 25 years of history and allow for entry later on in the month, we could definitely generate as close to 25 trades as possible.   This line of code keeps the potential of a trade open for the entire month.


// only set entriesThisMonth to true
// when all the stars align - might enter a long
// trade on the last day of the month

if longOrShort = 1 and canBuy then
entriesThisMonth = 1;
Keep the entire start month active

Some Tricky Code

I wanted to allow a money management exit on a contract basis.  I had to devise some code that would not allow me to reenter the startMonth if I got stopped out prematurely in the startMonth (the same month as entry.)

if entriesThisMonth = 1 and monthOfTomorrow <> startMonth then
entriesThisMonth = 0;
This code resets entriesThisMonth

If a position is initiated, I know entriesThisMonth will be set to one.  If I enter into another month that is not the startMonth then entriesThisMonth is set to 0.  This prevents reentry in case we get stopped out in the same month we initially enter a position.  In other words, entriesThisMonth stays one until a new month is observed.  And we can’t enter when entriesThisMonth is equal to one.

Full Code

input: startMonth(11),endMonth(5),
longOrShort(1),
useMACDFilter(1),MACDFast(9),MACDSlow(26),MACDAvgLen(9),MACDLevel(0),
useMAFilter(0),MALength(30),
useRSIFilter(0),RSILength(14),RSILevel(50),
startAccountSize(100000),
marketRiskLen(30),
riskPerTrade(5000),
maxTradeRisk(5000);

vars: currentMonth(0),mp(0),iShares(0),entriesThisMonth(0),monthOfTomorrow(0),
RSIVal(0),MAVal(0),MACDVal(0),MACDAvg(0),canBuy(True),canShort(True);

mp = marketPosition;
iShares = riskPerTrade/bigPointValue/avgTrueRange(marketRiskLen);

RSIVal = rsi(close,RSILength);
MAVal = xAverage(close,MALength);
MACDVal = macd(close,MACDFast,MACDSlow);
MACDAvg = xAverage(MACDVal,MACDAvgLen);

canBuy = True;
canShort = True;

mp = marketPosition;

monthOfTomorrow = month(date of tomorrow);

if entriesThisMonth = 1 and monthOfTomorrow <> startMonth then
entriesThisMonth = 0;

if useMACDFilter = 1 then
begin
canBuy = MACDVal > MACDLevel;
canShort = MACDVal < MACDLevel;
end;

if useMAFilter = 1 then
begin
canBuy = close > MAVal and canBuy;
canShort = close < MAVal and canShort;
end;

if useRSIFilter = 1 then
begin
canBuy = RSIVal > RSILevel and canBuy;
canShort = RSIVal < RSILevel and canShort;
end;

currentMonth = Month(Date of tomorrow);
//print(d," ",currentMonth," ",startMonth," ",entriesThisMonth);
If currentMonth = startMonth and mp = 0 and entriesThisMonth = 0 Then
begin
// print(d," ",currentMonth," ",canBuy);
if longOrShort = 1 and canBuy then
entriesThisMonth = 1;
if longOrShort = 1 and canBuy then
buy("Buy Month") iShares contracts next bar at market;
if longOrShort <> 1 and canShort then
sellShort("Short Month") iShares contracts next bar at market;
if longOrShort = -1 and canShort then
entriesThisMonth = 1;
end;

if CurrentMonth = endMonth Then
begin
if longOrShort = 1 then
sell("L-xit Month") currentShares contracts next bar at market
else
buyToCover("S-xit Month") currentShares contracts next bar at market;
end;

if mp = 1 then
sell("l-xitMM") next bar at entryPrice - maxTradeRisk/bigPointValue stop;
if mp =-1 then
buyToCover("s-xitMM") next bar at entryPrice + maxTradeRisk/bigPointValue stop;
Complete Code Framework

Here is the best equity curve I uncovered when I optimized the startMonth from 1 to 12 and the endMonth from 1 to 12 and the maxTradeRisk per contract and the three entry filters.  Entering in November when the moving average filter aligns and exiting on the first day of August and risking $5,500 per contract produced this equity curve.

Enter November get out the beginning of August

The test returned what would basically be similar to a buy and hold scenario; the difference being you only hold the trade between seven and eight months of the year and risk only $5,500 per contract.  If you get stopped out, you wait until November to get back in – whenever the moving average filter allows.  Net profit to draw down ratio is north of 4.0.

Last Comment

If I optimize from 1 to 12 for the start month and 1 to 12 for end month, will this not cause an error?  What if the two values equal?  I mean I can’t enter and exit in the same month – a one-day trade?  You could make the code smarter, but it doesn’t matter.  As a user you will know better than to use the same number and the optimizer will test the combination with the same number, but the results will fall off the table.   In this case, error trapping doesn’t prevent a necessarily unwanted or dangerous scenario.

Prune Your Trend Following Algorithm

Multiple trading decisions based on “logic” may not add to the bottom line

In this post, I will present a trend following system that uses four exit techniques.  These techniques are based on experience and also logic.  The problem with using multiple exit techniques is that it is difficult to see the synergy that is generated from all the moving parts.  Pruning your algorithm may help cut down on invisible redundancy and opportunities to over curve fit.  The trading strategy I will be presenting will use a very popular entry technique overlaid with trade risk compression.

Entry logic

Long:

Criteria #1:  Penetration of the closing price above an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2:  The mid-band or moving average must be increasing for the past three consecutive days.

Criteria #3: The trade risk (1.5X standard deviation) must be less than 3 X average true range for the past twenty days and also must be less than $4,500.

Risk is initially defined by the standard deviation of the market but is then compared to $4,500. If the trade risk is less than $4,500, then a trade is entered. I am allowing the market movement to define risk, but I am putting a ceiling on it if necessary.

Short:

Criteria #1:  Penetration of the closing price below an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2:  The mid-band or moving average must be decreasing for the past three consecutive days.

Criteria #3:  Same as criteria #3 on the long side

Exit Logic

Exit #1:  Like any Bollinger Band strategy, the mid band or moving average is the initial exit point.  This exit must be included in this particular strategy, because it allows exits at profitable levels and works synergistically with the entry technique.

Exit #2:  Fixed $ stop loss ($3,000)

Exit #3:  The mid-band must be decreasing for three consecutive days and today’s close must be below the entry price.

Exit #4:  Todays true range must be greater than 3X average true range for the past twenty days, and today’s close is below yesterday’s, and yesterday’s close must be below the prior days.

Here is the logic of exits #2 through exit #4.  With longer term trend following system, risk can increase quickly during a trade and capping the maximum loss to $3,000 can help in extreme situations.  If the mid-band starts to move down for three consecutive days and the trade is underwater, then the trade probably should be aborted.  If you have a very wide bar and the market has closed twice against the trade, there is a good chance the trade should be aborted.

Short exits use the same logic but in reverse.  The close must close below the midband, or a $3,000 maximum loss, or three bars where each moving average is greater than the one before, or a wide bar and two consecutive up closes.

Here is the logic in PowerLanguage/EasyLanguage that includes the which exit seletor.

[LegacyColorValue = true]; 
Inputs: maxEntryRisk$(4500),maxNATRLossMult(3),maxTradeLoss$(3000),
indicLen(85),numStdDevs(1.5),highVolMult(3),whichExit(7);

Vars: upperBand(0), lowerBand(0),slopeUp(False),slopeDn(False),
largeAtr(0),sma(0),
initialRisk(0),tradeRisk(0),
longLoss(0),shortLoss(0),permString("");

upperBand = bollingerBand(close,indicLen,numStdDevs);
lowerBand = bollingerBand(close,indicLen,-numStdDevs);
largeATR = highVolMult*(AvgTrueRange(20));

sma = average(close,indicLen);

slopeUp = sma>sma[1] and sma[1]>sma[2] and sma[2]>sma[3];
slopeDn = sma<sma[1] and sma[1]<sma[2] and sma[2]<sma[3];

initialRisk = AvgTrueRange(20);
largeATR = highVolMult * initialRisk;
tradeRisk = (upperBand - sma);
// 3 objects in our permutations
// exit 1, exit 2, exit 3
// perm # exit #
// 1 1
// 2 1,2
// 3 1,3
// 4 2
// 5 2,3
// 6 3
// 7 1,2,3

if whichExit = 1 then permString = "1";
if whichExit = 2 then permString = "1,2";
if whichExit = 3 then permString = "1,3";
if whichExit = 4 then permString = "2";
if whichExit = 5 then permString = "2,3";
if whichExit = 6 then permString = "3";
if whichExit = 7 then permString = "1,2,3";



{Long Entry:}
If (MarketPosition = 0) and
Close crosses above upperBand and slopeUp and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Buy ("LE") Next Bar at Market;
End;


{Short Entry:}

If (MarketPosition = 0) and slopeDn and
Close crosses below lowerBand and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Sell Short ("SE") Next Bar at Market;
End;


{Long Exits:}

if marketPosition = 1 Then
Begin
longLoss = initialRisk * maxNATRLossMult;
longLoss = minList(longLoss,maxTradeLoss$/bigPointValue);

If Close < sma then
Sell ("LX Stop") Next Bar at Market;;

if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;

if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;
end;

{Short Exit:}

If (MarketPosition = -1) Then
Begin

shortLoss = initialRisk * maxNATRLossMult;
shortLoss = minList(shortLoss,maxTradeLoss$/bigPointValue);
if Close > sma then
Buy to Cover ("SX Stop") Next Bar at Market;

if inStr(permString,"1") > 0 then
buyToCover("SX MaxL") next bar at entryPrice + shortLoss stop;

if inStr(permString,"2") > 0 then
If sma > sma[1] and sma[1] > sma[2] and sma[2] > sma[3] and close > entryPrice then
Buy to Cover ("SX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeAtr and close > close[1] and close[1] > close[2] then
Buy to Cover ("SX ATR") Next Bar at Market;
end;
Trend following with exit selector

Please note that I modified the code from my original by forcing the close to cross above or below the Bollinger Bands.  There is a slight chance that one of the exits could get you out of a trade outside of the bands, and this could potentially cause and automatic re-entry in the same direction at the same price.  Forcing a crossing, makes sure the market is currently within the bands’ boundaries.

This code has an input that will allow the user to select which combination of exits to use.

Since we have three exits, and we want to evaluate all the combinations of each exit separately, taken two of the exits and finally all the exits, we will need to rely on a combinatorial table.    In long form, here are the combinations:

3 objects in our combinations of exit 1, exit 2, exit 3

  • one  – 1
  • two  – 1,2
  • three  –  1,3
  • four –  2
  • five  – 2,3
  • six –  3
  • seven  –  1,2,3

There are a total of seven different combinations. Given the small set, we can effectively hard-code this using string manipulation to create a combinatorial table. For larger sets, you may find my post on the Pattern Smasher beneficial. A robust programming language like Easy/PowerLanguage offers extensive libraries for string manipulation. The inStr string function, for instance, identifies the starting position of a substring within a larger string. When keyed to the whichExit input, I can dynamically recreate the various combinations using string values.

  1. if whichExit = 1 then permString = “1”
  2. if whichExit = 2 then permString= “1,2”
  3. if whichExit = 3 then permString = “1,2,3”
  4.  etc…

As I optimize from one to seven, permString will dynamically change its value, representing different rows in the table. For my exit logic, I simply check if the enumerated string value corresponding to each exit is present within the string.

	if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;
if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;
Using inStr to see if the current whichExit input applies

When permString = “1,2,3” then all exits are used.  If permString = “1,2”, then only the first two exits are utilized.  Now all we need to do is optimize whichExit from 1 to 7.  Let’s see what happens:

Combination of all three exits

The best combination of exits was “3”.  Remember 3 is the permString  that = “1,3” – this combination includes the money management loss exit, and the wide bar against position exit.  It only slightly improved overall profitability instead of using all the exits – combo #7.  In reality, just using the max loss stop wouldn’t be a bad way to go either.  Occam uses his razor to shave away unnecessary complexities again!

If you like this code, you should check out the Summer Special at my digital store. I showcase over ten more trend-following algorithms with different entry and exit logic constructs.  These other algorithms are derived from the best Trend Following “Masters” of the twentieth century.  IMHO!

Here is a video you can watch that goes over the core of this trading strategy.

 

Multi-Agents and the Power of the Series Function

Jeff Swanson wrote a great post on multi-agent trading a few years ago.

Jeff created a simple mean reversion system and then created two derivatives that culminated in three systems (or three agents.)  Using Murray Ruggiero’s Equity Curve Feedback, he was able to poll which system was doing the best, synthetically, and execute the strategy that showed the best performance.   If memory serves, picking the highflyer turned out to be the way to go.  Jeff had just touched the surface of Murray’s tool. but it definitely did the job.  Murray contracted me to fix some problems with the ECF tool and I did, but the tool is just way too cumbersome, resource hungry and requires a somewhat higher level of EasyLanguage knowledge to be universally applicable.  I was doing similar research in the area of polling multiple strategies and picking the best, just like Jeff did, and just executing that one system, when I thought about this post.  Traders do this all the time.  They have multiple strategies in the pipeline and monitor the performance and if one is head and shoulders better than what they are currently trading, they will switch systems.  This was one of the side benefits of the ECF tool.

What is an agent

An agent is any trading system that produces a positive expectancy.  Using multiple agents in a polling process allows a trader to go with the strategy that is currently performing the best.  This sounds reasonable, but there are pitfalls.  You could always be behind the curve – picking the best system right before it has its draw down.  Agents can be similar, or they can be totally different types of systems.  I am going to follow in Jeff’s footsteps and create three agents with the same DNA.  Here is what I call the AgentSpawner strategy.

inputs: movAvgLen(200),numDownDays(3),numDaysInTrade(2),stopLoss(5000);


value1 = countIf(c < c[1],numDownDays);
if c > average(c,movAvgLen) and value1 = numDownDays then
buy next bar at open;
if barsSinceEntry = numDaysInTrade then
sell next bar at open;
if marketPosition = 1 then sell next bar at entryPrice - stopLoss/bigPointValue stop;
Use this template and optimize inputs to spawn new agents

This code trades in the direction of the longer-term moving average and waits for a pull back on N consecutive down closes.  I am using the neat function countIF. This function counts the number of times the conditional test occurs in the last N bars.  If I want to know the number of times I have had a down close in the last 3 days, I can use this function like this.

Value1 = countIF(c<c[1],3);

// this is what the function doues
// 1.) todays close < yesterdays close + 1
// 2.) yesterdays close < prior days close + 2
// 3.) day before yesterdays close < prior cays close + 3

// If value3 = 3 then I know I had three conscecutive down
// closes. If value3 is less than three then I did not.

If the close is greater than the longer-term moving average and I have N consecutive down closings, then I buy the next bar at the open.  I use a wide protective stop and get out after X bars since entry.  Remember EasyLanguage does not count the day of entry in its barsSinceEntry calculation.  I am not using the built-in setStopLoss as I don’t want to get stopped out on the day of entry.  In real trading, you may want to do this, but for testing purposes my tracking algorithm was not this sophisticated.  I spawned three agents with the following properties.

	Case 1: //Agent 1
movAvgLen = 200;
numDownDays = 2;
numDaysInTrade = 15;
stopLoss = 7500;
Case 2: //Agent 2
movAvgLen = 140;
numDownDays = 3;
numDaysInTrade = 9;
stopLoss = 2500;
Case 3: //Agent 3
movAvgLen = 160;
numDownDays = 3;
numDaysInTrade = 15;
stopLoss = 2500;

System Tracking Algorithm

This is why I love copy-paste programming.  This can be difficult if you don’t know your EasyLanguage or how TradeStation processes the bars of data.  Get educated by checking my books out at amazon.com – that is if you have not already.  This code is a very simplistic approach for keeping track of a system’s trades and its equity.

value4 = countIf(c<c[1],4);
value3 = countIf(c<c[1],3);
value2 = countIf(c<c[1],2);
//Agent #1 tracking algorithm
if sys1Signal<> 1 and c[1] > average(c[1],160) and value2[1] = 2 then
begin
sys1Signal = 1;
sys1BarCount = -1;
sys1TradePrice = open;
sys1LExit = open - 7500/bigPointValue;
end;
if sys1Signal = 1 then
begin
sys1BarCount+=1;
if low < sys1LExit and sys1BarCount > 0 then
begin
sys1TradePrice = sys1LExit;
sys1Signal = 0;
end;
if sys1BarCount = 16 and sys1Signal = 1 then
begin
sys1TradePrice = open;
sys1Signal = 0;
end;
end;
Yes, this looks a little hairy, but it really is simple stuff

I am pretending to be TradeStation here.  First, I need to test to see if Agent#1 entered into a long position.  If the close of yesterday is greater than the moving average, inclusive of yesterdays close, and there has been two consecutive down closes, then I know a trade should have been entered on todays open.  EasyLanguage’s next bar paardigm cannot be utilized here.  Remember I am not generating signals, I am just seeing if today’s (not tomorrows or the next bars) trading action triggered a signal and if so, I need to determine the entry/exit price.  I am gathering this information so I can feed it into a series function.  If a trade is triggered, I set four variables:

  1. sys1Signal – 1 for long, -1 for short, and 0 for flat.
  2. sys1BarCount – set to a -1 because I immediately increment.
  3. sys1TradePrice – at what price did I enter or exit
  4. sys1LExit – set this to our stop loss level

If I am theoretically long, remember we are just tracking here, then I need to test, starting with the following day, if the low of the day is below our stop loss level and if it is I need to reset two variables:

  1. sys1TradePrice – where did I get out
  2. sys1Signal – set to 0 for a flat position

If not stopped out, then I start counting the number of bars sys1Signal is equal to 1.  If sys1BarCount = 16, then I get out at the open by resetting the following variables:

  1. sys1TradePrice = open
  2. sys1Signal = 0

If you look back at the properties for Agent#1 you will see I get out after 15 days, not 16.  Here is where the next bar paradigm can make it confusing.  The AgentSpawner strategy says to sell next bar at open when barsSinceEntry = 15.  The next bar after 15 is 16, so we store the open of the 16th bar as our trade price.

Now copy and paste the code into a nice editor such as NotePad++ or NotePad and replace the string sys1 with sys2.  Copy the code from NotePad++ into your EasyLanguage editor.  Now back to NotePad++ and replace sys2 with sys3.  Copy that code into the EL edition too.  Now all you need to do is change the different properties for each agent and you will have three tracking modules.

The Power of the EasyLanguage Series Function

The vanilla version of EasyLanguage has object-oriented nuances that you may not see right off the bat.  In my opinion, a series function is like a class.  Before I get started, let me explain what I mean by series.  All EasyLanguage function are of three types.

  1. simple – like a Bollinger band calculation
  2. series – like we are talking about here
  3. auto-detect – the interpreter/compiler decides

The series function has a memory for the variables that are used within the function.  Take a look at this.

input: funcID(string),seed(numericSimple);

vars: count(0);
if barNumber = 1 then // on first bar seed count
count = seed;
count = count+1;
print(d," ",funcID," ", count);
SeriesFunctionTest = count;
Count is class-like member

On the first bar of the function call – remember it will be called on each bar in the chart, the function variable count is assigned seed. Seed will be ignored on subsequent bars.   What makes this magical is that no matter how many times you call the function on the same bar it remembers the internal variables on somewhat of a hierarchical basis (each call remembers its own stuff.)  It like a class in that it gets instantiated on the very first call.  Meaning if you call it three times on the first bar of the data, you will have three distinct internal variable memories.  Take a look at my sandbox function driver and its output.

result = SeriesFunctionTest("Call #1",50);
result = SeriesFunctionTest("Call #2",5);
result = SeriesFunctionTest("Call #3",100);

//outPut

1170407.00 Call #1 51.00 //first bar 51 = seed + count + 1
1170407.00 Call #2 6.00 //first bar 6 = seed + count + 1
1170407.00 Call #3 101.00 //first bar 101 = seed + count + 1

1170410.00 Call #1 52.00 // second bar it remembered count was 51
1170410.00 Call #2 7.00 // second bar it remembered count was 6
1170410.00 Call #3 102.00 // second bar it remembered count was 101

1170411.00 Call #1 53.00 // you have a unique function values that
1170411.00 Call #2 8.00 // were instantiated on the first bar
1170411.00 Call #3 103.00 // of the test.

1170412.00 Call #1 54.00
1170412.00 Call #2 9.00
1170412.00 Call #3 104.00
Series functions rock - but they are resource hungry

Why is this important?

I have created a PLSimulator function that keeps track of the three agent’s performance.  I need the profit or loss to stick with each function and then also add or subtract from it.  This is a neat function.  Remember if you like this stuff buy my books at Amazon.com.

//ProfitLoss Simulator
Inputs: signal(numericseries),tradePrice(numericSimple),orderType(numericSimple),useOte(Truefalse);
Vars:dmode(0),LEPrice(-99999),LXPrice(-99999),SEPrice(-99999),SXPrice(-99999);
vars: GProfit(0),OpenProfit(0);
vars: modTradePrice(0);

vars: printOutTrades(True);

modTradePrice = tradePrice;

if orderType = 1 then // stop order
begin
if signal = 1 or (signal = 0 and signal[1] = - 1) then
modTradePrice = maxList(open,modTradePrice);
if signal = -1 or (signal = 0 and signal[1] = 1) then
modTradePrice = minList(open,modTradePrice);
end;

if orderType = 2 then // limit order
begin
if signal = 1 or (signal = 0 and signal[1] = - 1) then
modTradePrice = minList(open,modTradePrice);
if signal = -1 or (signal = 0 and signal[1] = 1) then
modTradePrice = maxList(open,modTradePrice);
end;
if orderType = 3 then // market order
begin
modTradePrice = open;
end;

If Signal[0]=1 And (Signal[1]=-1 Or Signal[1]=0) Then
begin
LEPrice=modTradePrice;
SXPrice = -999999;
condition1 = false;
If Signal[1]=-1 Then
begin
SXPrice=modTradePrice;
GProfit=(SEPrice-SXPrice)+GProfit;
condition1 = True;
End;
if not(condition1) then
if printOutTrades then Print(d," L:Entry ",LEPrice)
else
if printOutTrades then Print(d," L:Entry ",LEPrice," ",(SEPrice-SXPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);
End;
{('***********************************************}
If Signal[0]=-1 And (Signal[1]=1 Or Signal[1]=0) Then
begin
SEPrice=modTradePrice;
LXPrice = 999999;
condition1 = false;
If Signal[1]=1 Then
begin
condition1 = True;
LXPrice=modTradePrice;
GProfit=(LXPrice-LEPrice)+GProfit;
End;
if not(condition1) then
if printOutTrades then Print(d," S:Entry ",SEPrice)
else
if printOutTrades then Print(d," L:Exit ",LXPrice," ",(LXPrice-LEPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);

End;
If Signal[0]=0 And Signal[1]=-1 Then
begin
SXPrice = modTradePrice;
GProfit=(SEPrice-SXPrice)+GProfit;
if printOutTrades then Print(d," S:Exit ",SXPrice," ",(SEPrice-SXPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);

end;
If Signal[0]=0 And Signal[1]=1 Then
begin
LXPrice = modTradePrice;
GProfit=(LXPrice-LEPrice)+GProfit;
if printOutTrades then Print(d," L:Exit ",LXPrice," ",(LXPrice-LEPrice)*bigPointValue:8:2," ",GProfit*bigPointValue:9:2);

end;

If Signal[1]=1 And useOte=True Then
begin
OpenProfit=(Close[1]-LEPrice);
End;
If Signal[1]=-1 and useOte=True Then
begin
OpenProfit=(SEPrice-Close[1]);
End;
If Signal[1]=0 Or useOte=False Then
begin
OpenProfit=0;
End;

PLSimulator=(GProfit+OpenProfit)*bigpointvalue;
Simulate profit and loss and more importantly keep track of it

Feed tracker algorithm data into the function

Your information must be properly assigned to get this to work.  First, I show how to get the information into the function.  The function does all the work and returns the equity.  I then determine the best agent by looking at the ROC over the past thirty days of equity for each agent and pick the very best.  I then trade the very best.  This is a very quick application of the function.  I will have a more sophisticated function, something akin to Murray’s ECF but with much less overhead and more strategy templates.

sys1Equity = PLSimulator(sys1Signal,sys1TradePrice,1,True);
sys2Equity = PLSimulator(sys2Signal,sys2TradePrice,1,True);
sys3Equity = PLSimulator(sys3Signal,sys3TradePrice,1,True);


vars: multiAgent(0);

value1 = maxList(sys1Equity-sys1Equity[30],sys2Equity-sys2Equity[30],sys3Equity-sys3Equity[30]);
multiAgent = 1;
if sys2Equity-sys2Equity[30] = value1 then multiAgent = 2;
if sys3Equity-sys3Equity[30] = value1 then multiAgent = 3;


{print(d," ",sys1Equity-sys1Equity[30]," ",sys1Equity);
print(d," ",sys2Equity-sys2Equity[30]," ",sys2Equity);
print(d," ",sys3Equity-sys3Equity[30]," ",sys2Equity);}
print(d," MultiAgent ",multiAgent);

//system parameters
vars: movAvgLen(200),numDownDays(3),numDaysInTrade(2),stopLoss(5000);
Switch ( multiAgent )
Begin
Case 1:
movAvgLen = 200;
numDownDays = 2;
numDaysInTrade = 15;
stopLoss = 7500;
Case 2:
movAvgLen = 140;
numDownDays = 3;
numDaysInTrade = 9;
stopLoss = 2500;
Case 3:
movAvgLen = 160;
numDownDays = 3;
numDaysInTrade = 15;
stopLoss = 2500;
End;
// Actual system execution
value1 = countIf(c < c[1],numDownDays);

if multiAgent <> multiAgent[1] then print(d," ---->multiagent trans ");

if c > average(c,movAvgLen) and value1 = numDownDays then
begin
if multiAgent = 1 then buy("Sys1") next bar at open;
if multiAgent = 2 then buy("Sys2") next bar at open;
if multiAgent = 3 then buy("Sys3") next bar at open;
end;
if barsSinceEntry >= numDaysInTrade then
sell next bar at open;
if marketPosition = 1 then sell next bar at entryPrice - stopLoss/bigPointValue stop;
Cool usage of a switch-case and agent determination

If this seems over your head…

Get one of my books are check out Jeff Swanson’s course.  EasyLanguage has so many little nuggets that can help you define your algorithm into an actionable strategy.  You will never know how your strategy will work until your program it (properly) and back test it.  And then potentially improve it with optimization.

Multi-Agent Results

 

 

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.

How To Test and Optimize Turn of the Month Seasonality

Historical evidence suggests a potential seasonal pattern around the end of the month in the markets.

If you have been involved with the markets for even a short period of time, you have heard about this trade.  Buy N days prior to the end of the month and then exit M days after the end of the month.  This is a simple test to perform if you have a way to determine the N and the M in the algorithm.  You could always buy on the 24th of the month, but the 24th of the month may not equal N days prior to the end of the month. 

Simple approach that doesn’t always work – buy the 24th of the month and exit the 5th of the following month.

if dayOfMonth(d) = 24 then buy next bar at open;

if marketPosition = 1 and dayOfMonth(d) = 5 then sell next bar at open;

Before we get into a little better coding of this algorithm, let’s see the numbers.  The first graph is trading one contract of the ES futures once a month – no execution fees were applied.  The same goes for the US bond futures chart that follows.  Before reading further please read this.

CFTC-required risk disclosure for hypothetical results:

Hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program.

One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk in actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all of which can adversely affect actual trading results.
Buying N days before EOM and Selling M days after EOM
Ditto!

No Pain No Gain

Looking into the maw of draw down and seeing the jagged and long teeth.

Draw down as a percentage of account value.
Ditto2

The bonds had more frequent draw down but not so deep.  These teeth can cause a lot of pain.

Well, George what is the N and M?

I should have done M days before and N days after to maintain alphabetic order, but here you go.

ES: N = 6 AND M = 6

US: N =10 AND M = 1

How did you do this?

Some testing platforms have built-in seasonality tools, but, and I could be wrong I didn’t find what I needed in the TradeStation function library.  So, I built my own.

A TradingDaysLeftInMonth function had to be created.  This function is a broad swipe at attempting to determining this value.  It’s not very smart because it doesn’t take HOLIDAYS into consideration.  But for a quick analysis it is fine.  How does one design such a function?  First off, what do we know to help provide information that might be useful?  We know how many days are in each month (again this function isn’t smart enough to take into consideration leap years) and we know what day of the week each trading day belongs to.  We have this function DayOfWeek(Date) already in EasyLanguage.  And we know the DayOfMonth(Date) (built-in too!) With these three tidbits of information, we should be able to come up with a useful function.   Not to mention a little programming knowledge.  I was working on a Python project when I was thinking of this function, so I decided to prototype it there.  No worries, the algorithm can be easily translated to EasyLanguage. And yes, I could have used my concept of a Sandbox to prototype in EasyLanguage as wellRemember a sandbox is a playground where you can quickly test a snippet of code.  Using the ONCE keyword, you can quickly throw some generic EasyLanguage together sans trade directives and mate it to a chart and get to the nuts and bolts quickly.  I personally like having an indicator and a strategy sandbox.  Here is a generic snippet of code where we assume the day of month is the 16th and it is a Monday ( 2 – 1 for Sunday thru 7 for Saturday) and there are 31 days in whatever month.

currentDayOfWeek = 2;
currentDayOfMonth = 16;
loopDOW = currentDayOfWeek;
daysInMonth = 31
#create the calender for the remaining month
tdToEOM=0; #total days to EOM
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1; #start back on Monday
Create a synthetic calendar from the current day of month

I just absolutely love the simplicity of Python.  When I am prototyping for EasyLanguage, I put a semicolon at the end of each line.  Python doesn’t care.  Here is the output from this snippet of code.

Cur>Day    DOWDay  DaysLeftAccum.
-----------------------------------
16 2 1 Monday
17 3 2 Tuesday
18 4 3 Wednesday
19 5 4 Thursday
20 6 5 Friday
21 7 5 Saturday
22 1 5 Sunday
23 2 6 Monday
24 3 7 Tuesday
25 4 8 Wednesday
26 5 9 Thursday
27 6 10 Friday
28 7 10 Saturday
28 1 10 Sunday
30 2 11 Monday
31 3 12 Tuesday

On Monday 16th there were 12 Trading Days Left In Month Inclusive
Output of Python Snippet - use in EZLang.

I start out with the current day of the month, 16 and loop through the rest of the days of the month.  Whenever I encounter a Sunday (1) or a Saturday (7) I do not increment tdToEOM, else I do increment.  

Here is how the function works on a chart.  Remember in TradeStation I am placing a market order for the NEXT BAR.

Counting the days until the EOM

This snippet of code is the heart of the function, but you must make in generic for any day of any month.  Here it is in EasyLanguage – you will see the similarity between the Python snippet and its corresponding EasyLanguage.

array: monthDays[12](0);

monthDays[1] = 31;
monthDays[2] = 28;
monthDays[3] = 31;
monthDays[4] = 30;
monthDays[5] = 31;
monthDays[6] = 30;
monthDays[7] = 31;
monthDays[8] = 31;
monthDays[9] = 30;
monthDays[10] = 31;
monthDays[11] = 30;
monthDays[12] = 31;

vars: curDayOfMonth(0),curDayOfWeek(0),loopDOW(0),tdToEOM(0),j(0);

curDayOfWeek = dayOfWeek(d);
curDayOfMonth = dayOfMonth(d);

{Python prototype
tdToEOM=0;
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1;
}

loopDOW = curDayOfWeek+1;
tdToEOM=0;

for j = curDayOfMonth to monthDays[month(d)]
begin
if loopDOW <> 1 and loopDOW <> 7 then
tdToEOM +=1; // tdToEOM = tdToEOM + 1;
loopDOW +=1;
if loopDOW > 7 then loopDOW = 1;
end;
TradingDaysLeftInMonth = tdToEOM;
EasyLanguage Function : TradingDaysLeftInMonth

I used arrays to store the number of days in each month.  You might find a better method.  Once I get the day of the month and the day of the week I get to work.  EasyLanguage uses a 0 for Sunday so to be compliant with the Python function I add a 1 to it.  I then loop from the current day of month through monthDays[month(d)].  Remember month(d) returns the month number [1…12].  A perfect index into my array.  That is all there is to it.  The code is simple, but the concept requires a little thinking.  Okay, now that we have the tools for data mining, let’s do some.  I did this by creating the following strategy (the same strategy that create the original equity curves.)

inputs: numDaysBeforeEOM(8),numDaysAfterEOM(10),movingAvgLen(100);
inputs: stopLossAmount(1500),profitTargetAmount(4000);

vars: TDLM(0),TDIM(0);

TDLM = tradingDaysLeftInMonth;
TDIM = tradingDayOfMonth;

if c >= average(c,movingAvgLen) and TDLM = numDaysBeforeEOM then
begin
buy("Buy B4 EOM") next bar at open;
end;

if marketPosition = 1 and barsSinceEntry > 3 then
begin
if TDIM = numDaysAfterEOM then
begin
sell("Sell TDOM") next bar at open;
end;
end;
setStopLoss(stopLossAmount);
setProfitTarget(profitTargetAmount);
EasyLanguage function driver in form of Strategy

A complete strategy has trade management and an entry and an exit.  In this case, I added an additional feature – a trend detector in the form of a longer-term moving average.  Let’s see if we can improve the trading system.  Thank goodness for Genetic Optimization.  Here is the @ES market.

Get your Pick ready to mine!

Smoothed the equity curve – took the big draw down out.

Genetically MODIFIED – Data Mining at its best!

Here are the parameters:

Did not like the moving average. Wide stop and wide profit objective. Days to EOM and after EOM stayed the same.

Bond System:

Bond market results.

If you like this type of programming check out my books at Amazon.com.  I have books on Python and of course EasyLanguage.  I quickly assembled a YouTube video discussing this post here.

Conclusion – there is something here, no doubt.  But it can be a risky proposition.  It definitely could provide fodder for the basis of a more complete trading system.

George’s Amazon Page

 

Happy New Year and some code tidbits

Dollar Cost Averaging Algorithm – Buy X amount every other Monday!

I am not going to get into this controversial approach to trading.  But in many cases, you have to do this because of the limitations of your retirement plan.  Hey if you get free matching dough, then what can you say.

Check this out!

Buy $1000 worth of shares every other Monday. INTC
if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then
begin
toggle = not(toggle);
if toggle then buy dollarInvestment/close shares next bar at open;
end;
Toggle every other Monday ON

Here I use a Boolean typed variable – toggle.   Whenever it is the first day of the week, turn the toggle on or off.  Its new state becomes the opposite if its old state.  On-Off-On-Off – buy whenever the toggle is On or True.  See how I determined if it was the first day of the week; whenever tomorrow’s day of the week is less than today’s day of the week, we must be in a new week.  Monday = 1 and Friday = 5.

Allow partial liquidation on certain days of the year.

Here I use arrays to set up a few days to liquidate a fractional part of the entire holdings.

arrays: sellDates[20](0),sellAmounts[20](0);
//make sure you use valid dates
sellDates[0] = 20220103;sellAmounts[0] = 5000;
sellDates[1] = 20220601;sellAmounts[1] = 5000;
sellDates[2] = 20230104;sellAmounts[2] = 8000;
sellDates[3] = 20230601;sellAmounts[3] = 8000;

value1 = d + 19000000;
if sellDates[cnt] = value1 then
begin
sell sellAmounts[cnt]/close shares total next bar at open;
cnt = cnt + 1;
end;
Notice the word TOTAL in the order directive.

You can use this as reference on how to declare an array and assign the elements an initial value.  Initially, sellDates is an array that contains 20 zeros, and sellAmounts is an array that contains 20 zeros as well.  Load these arrays with the dates and the dollar amounts that want to execute a partial liquidation.  Be careful with using Easylanguage’s Date.  It is in the form YYYMMDD – todays date December 28, 2023, would be represented by 1231228.  All you need to do is add 19000000 to Date to get YYYYMMDD format.  You could use a function to help out here, but why.  When the d + 19000000 equals the first date in the sellDates[1] array, then a market sell order to sell sellAmounts[1]/close shares total is issued.  The array index cnt is incremented.  Notice the order directive.

sell X shares total next bar at market;

If you don’t use the keyword total, then all the shares will be liquidated.

To create a complete equity curve, you will want to liquidate all the shares at some date near the end of the chart.  This is used as input as well as the amount of dollars to invest each time.

//Demonstation of Dollar Cost Averaging
//Buy $1000 shares every two weeks
//Then liquidate a specific $amount on certain days
//of the year

vars: toggle(False),cnt(0);
inputs: settleDate(20231205),dollarInvestment(1000);
arrays: sellDates[20](0),sellAmounts[20](0);
//make sure you use valid dates
sellDates[0] = 20220103;sellAmounts[0] = 5000;
sellDates[1] = 20220601;sellAmounts[1] = 5000;
sellDates[2] = 20230104;sellAmounts[2] = 8000;
sellDates[3] = 20230601;sellAmounts[3] = 8000;

value1 = d + 19000000;
if sellDates[cnt] = value1 then
begin
sell sellAmounts[cnt]/close shares total next bar at open;
cnt = cnt + 1;
end;

if dayOfWeek(d of tomorrow)< dayOfWeek(d) Then
begin
toggle = not(toggle);
if toggle then buy dollarInvestment/close shares next bar at open;
end;

if d + 19000000 = settleDate Then
sell next bar at open;

A cool looking chart.

A chart with all the entries and exits.

Allow Pyramiding

Turn Pyramding On. You will want to allow up to X entries in the same direction regardless of the order directive.

Working with Data2

I work with many charts that have a minute bar chart as Data1 and a daily bar as Data2.  And always forget the difference between:

Close of Data2 and Close[1] of Data2

24 hour regular session used here
1231214 1705 first bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231214 1710 second bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231215 1555 next to last bar of day - close of data2 4774.00 close[1] of data2 4760.75
1231215 1600 last bar of day - close of data2 4768.00 close[1] of data2 4774.00

Up to the last bar of the current trading day the open, high, low, close of data2 will reflect the prior day’s values.  On the last bar of the trading day – these values will be updated with today’s values.

Hope these tidbits help you out.  Happy New Years!

Warmest regards,

George

A Timely Function in EasyLanguage

Learn how to constrain trading between a Start and End Time – not so “easy-peasy”

Why waste time on this?

Is Time > StartTime and Time <= EndTime then…  Right?

This is definitely valid when EndTime > StartTime.  But what happens when EndTime < StartTime.  Meaning that you start trading yesterday, prior to midnight, and end trading after midnight (today.)  Many readers of my blog know I have addressed this issue before and created some simple equations to help facilitate trading around midnight.  The lines of code I have presented work most of the time.  Remember when the ES used to close at 4:15 and re-open at 4:30 eastern?   As of late June 2021, this gap in time has been removed.  The ES now trades between 4:15 and 4:30 continuously.   I discovered a little bug in my code for this small gap when I was optimizing a “get out time.”   I wanted to create a user function that uses the latest session start and end times and build a small database of valid times for the 24-hour markets.  Close to 24 hours – most markets will close for an hour.  With this small database you can test your time to see if it is a valid time.  The construction of this database will require a little TIME math and require the use of arrays and loops.  It is a good tutorial.  However, it is not perfect.  If you optimize time and you want to get out at 4:20 in 2020 on the ES, then you still run into the problem of this time not being valid.  This requires a small workaround.  Going forward with automated trading, this function might be useful.  Most markets trade around the midnight hour – I think meats might be the exception.

Time Based Math

How many 5-minute bars are between 18:00 (prior day) and 17:00 (today)?  We can do this in our heads 23 hours X (60 minutes / 5 minutes) or 23 X 12 = 276 bars.  But we need to tell the computer how to do this and we also should allow users to use times that include minutes such as 18:55 to 14:25. Here’s the math – btw you may have a simpler approach.

Using startTime of 18:55 and endTime of 14:25.

  1. Calculate the difference in hours and minutes from startTime to midnight and then in terms of minutes only.
    1. timeDiffInHrsMins = 2360 – 1855 = 505 or 5 hours and 5 minutes.  We use a little short cut hear.  23 hours and 60 minutes is the same as 2400 or midnight.
    2. timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This looks much more complicated than it really is because we are using two helper functions – intPortion and mod:
      1. ) intPortion – returns the whole number from a fraction.  If we divide 505/100 we get 5.05 and if we truncate the decimal we get 5 hours.
      2. ) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(505/100) gives 5 minutes.
      3. ) Five hours * 60 minutes + Five minutes = 305 minutes.
  2. Calculate the difference in hours and minutes from midnight to endTime and then in terms of minutes only.
    1. timeDiffInHrsMins = endTime – 0 = 1425 or 14 hours and 25 minutes.  We don’t need to use our little, short cut here since we are simply subtracting zero.  I left the zero in the calculation to denote midnight.
    2. timeDiffInMinutes = timeDiffInMinutes + intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This is the same calculation as before, but we are adding the result to the number of minutes derived from the startTime to midnight.  
      1. ) intPortion – returns the whole number from a fraction.  If we divide 1425/100, we get 14.05 and if we truncate the decimal, we get 14.
      2. ) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(1425/100) gives 25.
      3. ) 14* 60 + 25 = 865 minutes.
      4. ) Now add 305 minutes to 865.  This gives us a total of 1165 minutes between the start and end times.
    3. Now divide the timeDiffInMinutes by the barInterval.  This gives 1165 minutes/5 minutes or 233 five-minute bars.

Build Database of all potential time stamps between start and end time

We now have all the ingredients to build are simple array-based database.  Don’t let the word array scare you away.  Follow the logic and you will see how easy it is to use them.   First, we will create the database of all the time stamps between the regular session start and end times of the data on the chart.  We will use the same time-based math (and a little more) to create this benchmark database.  Check out the following code.

// You could use static arrays
// reserve enough room for 24 hours of minute bars
// 24 * 60 = 1440
// arrays: theoTimes[1440](0),validTimes[1440](0);
// syntax - arrayName[size](0) - the zero sets all elements to zero
// this seems like over kill because we don't know what
// bar interval or time span the user will be using

// these arrays are dynamic
// we dimension or reserve space for just what we need
arrays: theoTimes[](0),validTimes[](0);

// Create a database of all times stamps that potentiall could
// occur

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

// Now set the dimension of the array by using the following
// function and the number of bars we calculated for the entire
// regular session
Array_setmaxindex(theoTimes,numBarsInCompleteSession);
// Load the array from start time to end time
// We know the start time and we know the number of X-min bars
// loop from 1 to numBarsInCompleteSession and
// use timeSum as the each and every time stamp
// To get to the end of our journey we must use Time Based Math again.
timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100; // 1860 - becomes 1900
if timeSum = 2400 Then
timeSum = 0; // 2400 becomes 0000
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;
Create a dynamic array with all possible time stamps

This is a simple looping mechanism that continually adds the barInterval to timeSum until numBarsInCompleteSession are exhausted.  Reade about the difference between static and dynamic arrays in the code, please.  Here’s how it works with a session start time of 1800:

theoTimes[01] = 1800 + 5 = 1805
theoTimes[02] = 1805 + 5 = 1810
theoTimes[04] = 1810 + 5 = 1815
theoTimes[05] = 1815 + 5 = 1820
theoTimes[06] = 1820 + 5 = 1830
...
//whoops - need more time based math 1860 is not valid
theoTimes[12] = 1855 + 5 = 1860
Insert bar stamps into our theoTimes array

More time-based math

Our loop hit a snag when we came up with 1860 as a valid time.  We all know that 1860 is really 1900.  We need to intervene when this occurs.  All we need to do is use our modulus function again to extract the minutes from our time.

If mod(timeSum,100) = 60 then timeSum = timeSum – 60 + 100.  Her we remove the sixty minutes from the time and add an hour to it.

1860 – 60 + 100 = 1900 // a valid time stamp

That should fix everything right?  What about this:

theoTimes[69] = 2340 + 5 = 2345
theoTimes[70] = 2345 + 5 = 2350
theoTimes[71] = 2350 + 5 = 2355
theoTimes[72] = 2355 + 5 = 2400 // whoops
2400 is okay in Military Time but not in TradeStation

This is a simple fix with.  All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.

Build a database on our custom time frame.

Basically, do the same thing, but use the user’s choice of start and end times.

	//calculate the number of barInterval bars in the
//user defined session
numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
// print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;
Create another database using the time frame chose by the user

Don’t allow weird times!

Good programmers don’t allow extraneous values to bomb their functions.  TRY and CATCH the erroneous input before proceeding.  If we have a database of all possible time stamps, shouldn’t we use it to validate the user entry?  Of course, we should.

//Are the users startTime and endTime valid
//bar time stamps? Loop through all the times
//and validate the times.

for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;
Validate user's input.

Once we determine if both time inputs are valid, then we can determine if the any bar’s time stamp during a back-test is a valid time.

if validStartTime = false or validEndTime = false Then
error = True;


//Okay to check for bar time stamps against our
//database - only go through the loop until we
//validate the time - break out when time is found
//in database. CanTradeThisTime is the name of the function.
//It returns either True or False

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;
This portion of the code is executed on every bar of the back-test.

Once and only Once!

The code that creates the theoretical and user defined time stamp database is only done on the very first bar of the chart.  Also, the validation of the user’s input in only done once as well.  This is accomplished by encasing this code inside a Once – begin – end.

Now this code will test any time stamp against the current regular session.  If you run a test prior to June 2021, you will get a theoretical database that includes a 4:20, 4:25, and 4:30 on the ES futures.  However, in actuality these bar stamps did not exist in the data.  This might cause a problem when working with a start or end time prior to June 2021, that falls in this range.

Function Name:  CanTradeThisTime

Complete code:

//  Function to determine if time is in acceptable
// set of times
inputs: startTime(numericSimple),endTime(numericSimple);

vars: sessStartTime(0),sessEndTime(0),
startTimeStamp(0),timeSum(0),timeDiffInHrsMins(0),timeDiffInMinutes(0),
validStartTime(False), validEndTime(False);

vars: error(False),arrayIndex(0),
numBarsInSession(0),numBarsInCompleteSession(0);

arrays: theoTimes[](0),validTimes[](0);
vars: arrCnt(0),seed(0);

canTradeThisTime = false;

once
Begin

sessStartTime = sessionStartTime(0,1);
sessEndTime = sessionEndTime(0,1);

if sessStartTime > sessEndTime Then
Begin
timeDiffInHrsMins = 2360 - sessStartTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);

timeDiffInHrsMins = sessEndTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if sessStartTime <= sessEndTime Then
Begin
timeDiffInHrsMins = (intPortion(sessEndTime/100) - 1)*100 + mod(sessEndTime,100) + 60 - sessEndTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(theoTimes,numBarsInCompleteSession);

timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;

if startTime > endTime Then
Begin
timeDiffInHrsMins = 2360 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
timeDiffInHrsMins = endTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if startTime <= endTime Then
Begin
timeDiffInHrsMins = (intPortion(endTime/100) - 1)*100 + mod(endTime,100) + 60 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;
for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;
end;

if validStartTime = False or validEndTime = false Then
error = True;

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;
Complete CanTradeThisTime function code

Sandbox Strategy function driver

inputs: startTime(1800),endTime(1500);

if canTradeThisTime(startTime,endTime) Then
if d = 1231206 or d = 1231207 then
print(d," ",t," can trade this time");

I hope you find this useful.  Remember to purchase by Easing into EasyLanguage books at amazon.com.  The DayTrade edition is still on sale.  Email me with any question or suggestions or bugs or anything else.

 

 

Can You Turn Failure into Success?

Have You Ever Wondered If You Just Reversed the Logic?

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

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

Here are the original rules.

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

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

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

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

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

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

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

end;

mp = marketPosition;

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

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

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


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


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

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

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

Replicating Daily Bar Daytrade with Intraday Data – EasyLanguage

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 Then
Begin

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.

What About Holidays?

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?

Since this is an open range break out, we need to know what the open is prior to our break out calculation.  Could the break out level be penetrated on the first 5 minute bar?  Sure, but I bet it is rare.  I tested this and it only occurred 4 or 5 times.  In a back-test, if this occurs and the subsequent bar’s open is still above the break out level, TradeStation will convert the stop order to a market order and you will buy the open of the 2nd five minute bar.  In real time trading, you must tell TradeStation to wait until the end of the first 5 minute bar before issuing the trade directive to replicate your back testing.  If this is an issue, you can test with 5 minute bars, but execute on 1 minute bars.  In other words, have your testing chart and an additional execution chart.  Skipping the first 5 minute bar may be advantageous.  Many times you will get a surge at the open and then the market falls back.  By the time the first 5 minute bar concludes the market may be trading back below your break out level.  You might bypass the bulge. But your still in the game.  Here is how you can test the significance of this event.

	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 Then
Begin
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) Then
Begin
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 then
begin
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.