Category Archives: Must Know

An ES Day Trading Model Explained – Part 2

This is a continuation post or Part 2 of the development of the ES day trading system with EasyLanguage.

If you can understand this model you can basically program any of your day trading ideas.

Inputs Again:

First I want to revisit our list of inputs and make a couple of changes before proceeding.

inputs: volCalcLen(10),orboBuyPer(.2),orboSellPer(.2); 
inputs: volStopPer(.7),Stop$(500); 
inputs: volThreshPer(.3),ProfThresh$(250);
inputs: volTrailPer(.2),Trail$(200);
inputs: endTradingTime(1500);
Modification to our inputs

If we want to optimize these values then we can’t use the keyword bigPointValue in the input variable default value.  So I removed them – also I added an input endTradingTime(1500).  I wanted to cut off our trading at a given time – no use entering a trade five minutes prior to the closing.

Disengage the Vol or $Dollar Trade Management:

I may have muddied the waters a little with having volatility and $ values simultaneously.  You can use either for the initial protective stop, profit threshold, and trailing stop amount.  You can disengage them by using large values.  If you want to ignore all the $ inputs just add a couple of 00 to each of the values:

Stop$(50000), ProfThres$(25000),Trail$(50000)

If you want to ignore the volatility trade management stops just put a large number in front of the decimal.

volStopPer(9.7), volThreshPer(9.3), volTrailPer(9.2)

If you make either set large then the algorithm will use the values closest to the current market price.

Computations:

Let’s now take a look at the computations that are done on the first bar of the day:

If d <> d[1] then
Begin
	rangeSum = 0.0;  // range calculation for entry
	For iCnt = 1 to volCalcLen
	Begin
		rangeSum = rangeSum + (highD(iCnt) - lowD(iCnt));
	end;
	vol = rangeSum/volCalcLen;
	buyPoint =  openD(0) + vol*orboBuyPer; 
	sellPoint = openD(0) - vol*orboSellPer; 
	
	longStopAmt = vol * volStopPer; 
	longStopAmt = minList(longStopAmt,Stop$/bigPointValue);
	
	shortStopAmt = vol *volStopPer; 
	shortStopAmt = minList(shortStopAmt,Stop$/bigPointValue);

	longThreshAmt = vol  * volThreshPer;
	longThreshAmt = minList(longThreshAmt,ProfThresh$/bigPointValue);
	
	shortThreshAmt = vol * volThreshPer;
	shortThreshAmt = minList(shortThreshAmt,ProfThresh$/bigPointValue);
	
	longTrailAmt = vol * volTrailPer;
	longTrailAmt = minList(longTrailAmt,Trail$/bigPointValue);
	
	shortTrailAmt = vol * volTrailPer;
	shortTrailAmt = minList(shortTrailAmt,Trail$/bigPointValue);
	
	longTrailLevel = 0;
	shortTrailLevel = 999999;
	buysToday = 0;
	shortsToday = 0;
end;
Once a day computations

I determine it is the first bar of the day by comparing the current 5-minute bar’s date stamp to the prior 5-minute bar’s date stamp.  If they are not the same then you have the first bar of the day.  The first thing I do is calculate the volatility of the current market by using a for-loop to accumulate the day ranges for the past volCalcLen days.  I start the iterative process using the iCnt index and going from 1 back in time to volCalcLen.  I use iCnt to index into the function calls HighD and LowD.  Indexing is not really the right word here – that is more appropriate when working with arrays.  HighD and LowD are functions and we are passing the values 1 to volCalcLen into the functions and summing their output.  When you do this you will get a warning “A series function should not be called more than once with a given set of parameters.”  Sounds scary but it seems to work just fine.  If you don’t do this then you have to include a daily bar on the chart.  I like to keep things as simple as possible.   Once I sum up the daily ranges I then divide by volCalcLen to get the average range over the few days.  All of the vol based variables will use this value.

Entries:

Entry is based off a move away from the opening in terms of volatility.  If we use 0.2 (twenty percent) as orboBuyPer then the algorithm will buy on a stop 20% of the average range above the open tick.  Sell short is just the opposite.   We further calculate the longStopAmt as a function of vol and a pure $ amount.  I am using the minList function to determine the smaller of the two values  .This is how I disengage either the vol value or the $ value.  The other variables are also calculated just once a day: shortStopAmt, longThreshAmt, shortThreshAmt, longTrailAmt, shortTrailAmt. You could calculate every bar but that would be inefficient. I am also resetting four values at the beginning of the day:  longTrailLevel, shortTrailLevel, buysToday and shortsToday.

 

The Mighty MP:

mp = marketPosition;

If mp = 1 and mp[1] <> 1 then buysToday = buysToday + 1;
If mp = -1 and mp[1] <> -1 then shortsToday = shortsToday + 1;
MarketPosition monitoring and determining Buys/Shorts Today

I like using a variable to store each bar’s marketPosition.  In this case I am using MP.  By aliasing the marketPosition function call to a variable allows us to do this:

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

This little line does a bunch of stuff.  If the current bar’s position is 1 and the prior bars position is not one then we know we have just entered a long position.  So every time this happens throughout the day the buysToday is incremented.  ShortsToday works just the same.  Pitfall warning:  If you strategy enters and exits on the same bar then this functionality will not work!  Neither will the call to the marketPosition function.  It will look like nothing happened.  If you need to keep track of the number of trades make sure you can only enter or exit on different bars.  If you stuff is so tight then drop down to a 1 minute or tick bar.

Controlling the Nmber of Buys/Shorts for the Day:

if time < endTradingTime and buysToday < 1 then Buy("ORBo-B") next bar at buyPoint stop;
if time < endTradingTime and shortsToday < 1 then Sellshort("ORBo-S") next bar at sellPoint stop;	  

	
If marketposition = 1 then
Begin 
	longExitPoint = entryPrice - longStopAmt;
	sell("L-Exit") next bar at longExitPoint stop;
end;

If marketposition = -1 then
Begin
	shortExitPoint = entryPrice + shortStopAmt;
	buyToCover("S-Exit") next bar at shortExitPoint stop;
end;

If marketPosition = 1 and maxContractProfit/bigPointValue >= longThreshAmt then
Begin
	longTrailLevel = maxList(highest(h,barsSinceEntry) - longTrailAmt,longTrailLevel);
	sell("TrailSell") next bar at longTrailLevel stop;
end;

If marketPosition = -1 and maxContractProfit/bigPointValue >= shortThreshAmt then
Begin
	shortTrailLevel = minList(lowest(l,barsSinceEntry) + shortTrailAmt,ShortTraillevel);
	buyToCover("TrailCover") next bar at shortTrailLevel stop;
end;


SetExitOnClose;
Controlled trade directives

Notice how I am controlling the trade directives using the if statements.  I only want to enter a long position when the time is right and I haven’t already entered a long position for the day.  If you don’t control the trade directives, then these orders are placed on every bar, in our case every 5-minutes.  If you have pyramiding turned off then once you are long the buy directive is ignored.  This is an important concept – let’s say you just want to buy and short only one time per day trade session.  If you don’t control this directive, then it will fire off an order every five minutes.    You don’t want this -at least I hope you don’t.

So controlling the time and number of entries is paramount.  If you don’t control the time of entry then the day can arrive at the last bar of the day and fire off an order for the opening of the next day.  A big no, no !

Put To Work:

Here are the inputs I used to generate the trades in the graphic that follows.

Not Doing Exactly What You Want:

Here is what most day traders are looking for.   I made a comment on the chart – make sure you read it – it is another pitfall.

The trailing stop had to wait for the bar to complete to determine if the profit reached the threshold.  A little slippage here.  You can overcome this if you use the BuiltIn Percent Trailing Strategy or by using the SetPercentTrailing function call.

However, you lose the ability to really customize your algorithms by using the builtin functionalility.  You could drop down to a one minute bar and probably get out nearer your trailing stop amount.

Download the ELD:

Here you go!

GEODAYTRADERV1.01

An ES Day Trading Model Explained – Part 1

Open Range BreakOut with Trade Management

How difficult is it to program a day trading system using an open range break out, protective stop and a trailing stop?  Let’s see.  I started working on this and it got a little more detailed than I wanted so I have now split it up into two posts.  Part 2 will follow very soon.

What inputs do we need?  How about the number of days used in the volatility calculation?  What percentage of the volatility from the open do you want to buy or sell?  Should we have a different value for buys and sells?  Do we want to use a volatility based protective stop or a fixed dollar?  How about a trailing stop?  Should we wait to get to a certain profit level before engaging the trailing stop?  Should it also be based on volatility or fixed dollar amt?  How much should we trail – again an amount of volatility or fixed dollar?

Proposed inputs:

inputs: volCalcLen(10), orboBuyPer(.2), orboSellPer(.2), volStopPer(.7), $Stop(500), volProfThreshPer(.5), $ProfThresh(250),volTrailPer(.2),$Trail(200);

That should do it for the inputs – we can change later if necessary.

Possible pitfalls:

This is where I will save you some time.  If we use an open range break out entry we must limit the number of entries or TradeStation will continue to execute as long as the price is above our buy level.  You might ask, “That’s what we want -right?”  What if we use a tight stop and we get stopped out of our first position.  Do you want to buy again later in the day?  What if we use a trailing stop and we get out of the market above the buy level.  What will TradeStation do?  It will follow your exact instructions and buy again if you don’t control the number of allowed entries.  Do you want to carry the buy and sell stops overnight for execution on the open of the next day – probably not!  So we not only need to control the number of entries buy we also need to control the time period we can enter a trade.

Calculations:

We need to determine the volatility and a good way do this is calculating the average range over the past N days.   There are two ways to do this: 1) incorporate a daily chart as data2 and use a built-in function for the calculation or 2) use a for-loop and use the built-in functions HighD and LowD and just use one data feed.   Both have their drawbacks.  The first is you need to have a multi-data chart and the second you get a warning that you shouldn’t put a series function call inside the body of a for-loop.   I have done it both ways and I prefer to deal with the warning – so far it has worked out nicely – so let’s go with a single data chart.

Building the code:

Inputs:

Since we are combining a volatility and fixed $ amount in our trade management, you will need to set either the vol or dollar amounts to a high value to disable them.  You can use both but I am taking the smaller of the respective values.

inputs: volCalcLen(10),orboBuyPer(.2),orboSellPer(.2); 
inputs: volStopPer(.7),$Stop(500/bigPointValue); 
inputs: volThreshPer(.5),$ProfThresh(250/bigPointValue);
inputs: volTrailPer(.2),$Trail(200/bigPointValue);
Inputs We Will Need - Can Changer Later

Variables:

vars:vol(0),buyPoint(0),sellPoint(0),
	longStopAmt(0),shortStopAmt(0),longExitPoint(0),shortExitPoint(0),
	longThreshAmt(0),shortThreshAmt(0),
	longTrailAmt(0),shortTrailAmt(0),
	longTrailLevel(0),shortTrailLevel(0),
	hiSinceLong(0),loSinceShort(0),mp(0),
	rangeSum(0),iCnt(0),
	buysToday(0),shortsToday(0)
Variables That We Might Need

Once A Day Calculations:

Since we will be working with five-minute bars we don’t want to do daily calculations on each bar.  If we do it will slow down the process.  So let’s do these calculation on the first bar of the day only.

If d <> d[1] then
Begin
	rangeSum = 0.0;  // range calculation for entry
	For iCnt = 1 to volCalcLen
	Begin
		rangeSum = rangeSum + (highD(iCnt) - lowD(iCnt));
	end;
	vol = rangeSum/volCalcLen;
	buyPoint =  openD(0) + vol*orboBuyPer; 
	sellPoint = openD(0) - vol*orboSellPer; 
	
	longStopAmt = vol * volStopPer; 
	longStopAmt = minList(longStopAmt,Stop$);
	
	shortStopAmt = vol *volStopPer; 
	shortStopAmt = minList(shortStopAmt,Stop$);

	longThreshAmt = vol  * volThreshPer;
	longThreshAmt = minList(longThreshAmt,ProfThresh$);
	
	shortThreshAmt = vol * volThreshPer;
	shortThreshAmt = minList(shortThreshAmt,ProfThresh$);
	
	longTrailAmt = vol * volTrailPer;
	longTrailAmt = minList(longTrailAmt,Trail$);
	
	shortTrailAmt = vol * volTrailPer;
	shortTrailAmt = minList(shortTrailAmt,Trail$);
	
	longTrailLevel = 0;
	shortTrailLevel = 999999;
	buysToday = 0;
	shortsToday = 0;
end;
Do These Just Once A Day

 

For All of You Who Don’t Want To Wait – Beta Version Is Available Below:

In my next post, I will dissect the following code for a better understanding.  Sorry I just ran out of time.

inputs: volCalcLen(10),orboBuyPer(.2),orboSellPer(.2); 
inputs: volStopPer(.7),Stop$(500/bigPointValue); 
inputs: volThreshPer(.3),ProfThresh$(250/bigPointValue);
inputs: volTrailPer(.2),Trail$(200/bigPointValue);


vars:vol(0),buyPoint(0),sellPoint(0),
	longStopAmt(0),shortStopAmt(0),longExitPoint(0),shortExitPoint(0),
	longThreshAmt(0),shortThreshAmt(0),
	longTrailAmt(0),shortTrailAmt(0),
	longTrailLevel(0),shortTrailLevel(0),
	hiSinceLong(0),loSinceShort(0),mp(0),
	rangeSum(0),iCnt(0),
	buysToday(0),shortsToday(0);

If d <> d[1] then
Begin
	rangeSum = 0.0;  // range calculation for entry
	For iCnt = 1 to volCalcLen
	Begin
		rangeSum = rangeSum + (highD(iCnt) - lowD(iCnt));
	end;
	vol = rangeSum/volCalcLen;
	buyPoint =  openD(0) + vol*orboBuyPer; 
	sellPoint = openD(0) - vol*orboSellPer; 
	
	longStopAmt = vol * volStopPer; 
	longStopAmt = minList(longStopAmt,Stop$);
	
	shortStopAmt = vol *volStopPer; 
	shortStopAmt = minList(shortStopAmt,Stop$);

	longThreshAmt = vol  * volThreshPer;
	longThreshAmt = minList(longThreshAmt,ProfThresh$);
	
	shortThreshAmt = vol * volThreshPer;
	shortThreshAmt = minList(shortThreshAmt,ProfThresh$);
	
	longTrailAmt = vol * volTrailPer;
	longTrailAmt = minList(longTrailAmt,Trail$);
	
	shortTrailAmt = vol * volTrailPer;
	shortTrailAmt = minList(shortTrailAmt,Trail$);
	
	longTrailLevel = 0;
	shortTrailLevel = 999999;
	buysToday = 0;
	shortsToday = 0;
end;

mp = marketPosition;

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

if time < sessionendTime(0,1) and buysToday < 1 then Buy("ORBo-B") next bar at buyPoint stop;
if time < sessionendTime(0,1) and shortsToday < 1 then Sellshort("ORBo-S") next bar at sellPoint stop;	  

	
If marketposition = 1 then
Begin 
	longExitPoint = entryPrice - longStopAmt;
	sell("L-Exit") next bar at longExitPoint stop;
end;

If marketposition = -1 then
Begin
	shortExitPoint = entryPrice + shortStopAmt;
	buyToCover("S-Exit") next bar at shortExitPoint stop;
end;

If marketPosition = 1 and maxContractProfit/bigPointValue >= longThreshAmt then
Begin
	longTrailLevel = maxList(highest(h,barsSinceEntry) - longTrailAmt,longTrailLevel);
	sell("TrailSell") next bar at longTrailLevel stop;
end;

If marketPosition = -1 and maxContractProfit/bigPointValue >= shortThreshAmt then
Begin
	shortTrailLevel = minList(lowest(l,barsSinceEntry) + shortTrailAmt,ShortTraillevel);
	buyToCover("TrailCover") next bar at shortTrailLevel stop;
end;


SetExitOnClose;
Beta Version - I will clean up later and post it

 

EasyLanguage Code for Optimal F (Multi-Charts and VBA too!)

Optimal F in EasyLanguage for TradeStation and MultiCharts

Here is the code for the Optimal F calculation.  For a really good explanation of Optimal F I refer you to Ralph Vince’s Book Portfolio Management FORMULAS.  We had programmed this years ago for our Excalibur software and I was surprised the EasyLanguage code was really all that accessible on the internet.  Finding the optimal f is found through an iterative process or in programmers terms a loop.  The code is really quite simple and I put it into a Function.  I decided to create this function because I wanted to demonstrate the ideas from my last post on how a function can store variable and array data.  Plus this code should be readily available somewhere out there.

//OptimalFGeo by George Pruitt
//My interpretation Sept. 2018
//www.georgepruitt.com
//georgeppruitt@gmail.com

input: minNumTrades(numericSimple);
vars: totalTradesCount(0),tradeCnt(0);
array: tradesArray[500](0);

vars: iCnt(00),jCnt(00),grandTot(0),highI(0);
vars: optF(0.0),gMean(0.0),fVal(0.0),HPR(0.0),TWR(0.0),hiTWR(0.0);
vars: biggestLoser(0.0),gat(0.0);

totalTradesCount = totalTrades;
If totalTradesCount > totalTradesCount[1] then
begin
	tradeCnt = tradeCnt + 1; 
	tradesArray[tradeCnt] = positionProfit(1);
end;

// Taken from my Fortran library - GPP and Vince Book PMF

optF = 0.0;
gMean = 1.00;
gat   = 0.00;
//Only calculate if new trade
IF(tradeCnt>minNumTrades and totalTradesCount > totalTradesCount[1]) then 
Begin
	biggestLoser = 0;
	grandTot = 0;
	For iCnt = 1 to tradeCnt //get the biggest loser
	begin
   		grandTot = grandTot + tradesArray[iCnt];
   		IF(tradesArray[iCnt]<biggestLoser) then biggestLoser = tradesArray[iCnt];
	end;
//	print(grandTot," ",biggestLoser);
	IF({grandTot > 0 and} biggestLoser <0) then 
	begin
//		print("Inside TWR Calculations");
		highI = 0;
		hiTWR = 0.0;
		for iCnt = 1 to 100
		begin
			fVal = .01 * iCnt;
			TWR = 1.0;
			for jCnt = 1 to tradeCnt // calculate the Terminal Wealth Relative
			begin
    			HPR = 1. + (fVal * (-1*tradesArray[jCnt]) / biggestLoser);
    			TWR = TWR * HPR;
 //   			print(fVal," ",iCnt," " ,jCnt," Trades ",tradesArray[jCnt]," HPR ",HPR:6:4," TWR : ",TWR:6:4," hiTWR",hiTWR:6:4," bl ",biggestLoser);
			end;
//			print(iCnt," ",TWR," ",hiTWR);
			IF(TWR>hiTWR) THEN
			begin
    			hiTWR = TWR;
    			optF = fVal;    	// assign optF to fVal in case its the correct one		
			end
			else
    			break;                     //highest f found - stop looping
		end;		
		If (TWR <= hiTWR or optF >= 0.999999) then
		begin
			TWR  = hiTWR;
			OptimalFGeo = optF;  //assign optF to the name of the function
		end;	
		gmean = power(TWR,(1.0 / tradeCnt));
		
		if(optF<>0) then GAT   = (gMean - 1.0) * (biggestLoser / -(optF));		
		print(d," gmean ",gmean:6:4," ",GAT:6:4);  // I calculate the GMEAN and GeoAvgTrade
	end;
end;
Optimal F Calculation by Ralph Vince code by George Pruitt

VBA version of Optimal F

For those of you who have a list of trades and want to see how this works in Excel here is the VBA code:

Sub OptimalF()

    Dim tradesArray(1000) As Double
    i = 0
    biggestLoser = 0#
    Do While (Cells(3 + i, 1) <> "")
        tradesArray(i) = Cells(3 + i, 1)
        If tradesArray(i) < bigLoser Then biggestLoser = tradesArray(i)
        i = i + 1
    Loop
    tradeCnt = i - 1
    highI = 0
    hiTWR = 0#
    rc = 3
    For fVal = 0.01 To 1 Step 0.01
        TWR = 1#
        For jCnt = 0 To tradeCnt
            HPR = 1# + (fVal * (-1 * tradesArray(jCnt)) / biggestLoser)
            TWR = TWR * HPR
            Cells(rc, 5) = jCnt
            Cells(rc, 6) = tradesArray(jCnt)
            Cells(rc, 7) = HPR
            Cells(rc, 8) = TWR
            rc = rc + 1
        Next jCnt
        Cells(rc, 9) = fVal
        Cells(rc, 10) = TWR
        rc = rc + 1

        If (TWR > hiTWR) Then
            hiTWR = TWR
            optF = fVal
        Else
            Exit For
        End If

    Next fVal
    If (TWR <= hiTWR Or optF >= 0.999999) Then
        TWR = hiTWR
        OptimalFGeo = optF
    End If
    Cells(rc, 8) = "Opt f"
    Cells(rc, 9) = optF
    rc = rc + 1
    gMean = TWR ^ (1# / (tradeCnt + 1))
    If (optF <> 0) Then GAT = (gMean - 1#) * (biggestLoser / -(optF))
    Cells(rc, 8) = "Geo Mean"
    Cells(rc, 9) = gMean
    rc = rc + 1
    Cells(rc, 8) = "Geo Avg Trade"
    Cells(rc, 9) = GAT

End Sub
VBA code for Optimal F

I will attach the eld and .xlsm file a little later.

 

 

 

Function Variable Data Survives Between Calls

Function Variable Data Survives from One Call to the Next – A Pretty Nifty Tool in EasyLanguage!

Creating a function that can store data and then have that data survive on successive function calls without having to pass information back and forth is really a cool and powerful tool in EasyLanguage.  In most programming languages, the variables defined in a function are local to that particular bit of code and once program execution exits the function, then the data is destroyed.  There are two exceptions (in other languages) that come to mind – if the variable is passed back and forth via their addresses, then the data can be maintained or if the variable is global in scope to the function and the calling program.  EasyLanguage prevents you from having to do this and this can definitely save on headaches.  I wrote a function that defines an array that will hold a list of trades.  Once the number of trades reaches a certain level, I then calculate a moving average of the last 10 trades.  The average is then passed back to the calling strategy.  Here is the simple code to the function.

 

{Function Name:   StoreTradesFunc by George Pruitt}
{Function to Calculate the average trade for past N trades.
 ----------------------------------------------------------
 Function remembers the current trade count in tradeCnt.
 It also remembers the values in the array tradesArray.
 It does this between function calls. 
 Values - simple and array - undoubtedly are global to the function}
 
input: avgTradeCalcLen(numericSimple);
vars: totalTradesCount(0),tradeCnt(0);
array: tradesArray[500](0);

totalTradesCount = totalTrades;
If totalTradesCount > totalTradesCount[1] then
begin
	tradeCnt = tradeCnt + 1;
	tradesArray[tradeCnt] = positionProfit(1);
//	print("Storing data ",tradesArray[tradeCnt]," ",tradeCnt);
end;

If totalTrades > avgTradeCalcLen then
begin
	Value2 = 0;
	For value1 = totalTrades downTo totalTrades - avgTradeCalcLen
	begin
		Value2 = value2 + tradesArray[value1];
	end;
	print("Sum of last 10 Trades: ",value2);
	StoreTradesFunc = value2/avgTradeCalcLen;
end;
Store A List of Trades in a Function

I call this function on every bar (daily would be best but you could do it on intra-day basis) and it polls the function/keyword totalTrades to see if a new trade has occurred.  If one has, then the variable tradeCnt is incremented and the trade result is inserted into the tradesArray array by using the tradeCnt as the array index.  When you come back into the function from the next bar of data tradeCnt and tradesArray are still there for you and most importantly still intactIn other words there values are held static until you change them and remembered.  This really comes in handy when you want to store all the trades in an array and then do some type of calculation on the trades and then have that information readily available for use in the strategy.  My example just provides the average trade for the past ten trades.  But you could do some really exotic things like Optimal F.  The thing to remember is once you define a variable or an array in a function and start dumping stuff in them, the stuff will be remembered throughout the life of the simulation.  The function data and variables are encapsulated to just the function scope – meaning I can’t access tradesArray outside of the function.  One last note – notice how I was able to determine a new trade had occurred.  I assigned the result of totalTrades to my own variable totalTradesCount and then compared the value to the prior bar’s value.  If the values were different than I knew a new trade had just completed.

Anatomy Of Mean Reversion in EasyLanguage

Look at this equity curve:

As long as you are in a bull market buying dips can be very consistent and profitable.  But you want to use some type of entry signal and trade management other than just buying a dip and selling a rally.  Here is the anatomy of a mean reversion trading algorithm that might introduce some code that you aren’t familiar.  Scroll through the code and I will  summarize below.

inputs: mavlen(200),rsiLen(2),rsiBuyVal(20),rsiSellVal(80),holdPeriod(5),stopLoss$(4500);
vars: iCnt(0),dontCatchFallingKnife(false),meanRevBuy(false),meanRevSell(false),consecUpClose(2),consecDnClose(2);

Condition1 = c > average(c,mavLen);

Condition2 = rsi(c,rsiLen) < rsiBuyVal;
Condition3 = rsi(c,rsiLen) > rsiSellVal;


Value1 = 0;
Value2 = 0;

For iCnt = 0 to consecUpClose - 1 
Begin
	value1 = value1 + iff(c[iCnt] > c[iCnt+1],1,0);
end;

For iCnt = 0 to consecDnClose - 1 
Begin
	Value2 = value2 + iff(c[iCnt] < c[iCnt+1],1,0);
end;

dontCatchFallingKnife = absValue(C - c[1]) < avgTrueRange(10)*2.0;

meanRevBuy = condition1 and condition2 and dontCatchFallingKnife;
meanRevSell =  not(condition1) and condition3 and dontCatchFallingKnife;

If meanRevBuy then buy this bar on close;
If marketPosition = 1 and condition1 and value1 >= consecUpClose then sell("ConsecUpCls") this bar on close;

If meanRevSell then sellShort this bar on close;
If marketPosition = -1 and not(condition1) and value2 >= consecDnClose then buyToCover this bar close;

setStopLoss(stopLoss$);


If barsSinceEntry = holdPeriod then
Begin
	if marketPosition = 1 and not(meanRevBuy) then sell this bar on close;
	if marketPosition =-1 and not(meanRevSell) then buytocover this bar on close;
end;
Mean Reversion System

I am using a very short term RSI indicator, a la Connors, to initiate long trades.  Basically when the 2 period RSI dips below 30 and the close is above the 200-day moving average I will buy only if I am not buying “a falling knife.”  In February several Mean Reversion algos kept buying as the market fell and eventually got stopped out with large losses.  Had they held on they probably would have been OK.  Here I don’t buy if the absolute price difference between today’s close and yesterday’s is greater than 2 X the ten day average true range.  Stay away from too much “VOL.”

Once a trade is put on I use the following logic to keep track of consecutive closing relationships:

For iCnt = 0 to consecUpClose - 1 
Begin
	value1 = value1 + iff(c[iCnt] > c[iCnt+1],1,0);
end;
Using the IFF function in EasyLanguage

Here I am using the IFF function to compare today’s close with the prior day’s.  iCnt is a loop counter that goes from 0 to 1. IFF checks the comparison and if it’s true it returns the first value after the comparison and if false it returns the last value.  Here if I have two consecutive up closes value1 accumulates to 2.  If I am long and I have two up closes I get out.  With this template you can easily change this by modifying the input:  consecUpClose.  Trade management also includes a protective stop and a time based exit.  If six days transpire without two up closes then the system gets out – if the market can’t muster two positive closes, then its probably not going to go anywhere.  The thing with mean reversion, more so with other types of systems, is the use or non use of a protective stop.  Wide stops are really best, because you are betting on the market to revert.  Look at the discrepancy of results using different stop levels on this system:

Here an $1,800 stop only cut the max draw down by $1,575.  But it came at a cost of $17K in profit.  Stops, in the case of Mean Reversion, are really used for the comfort of the trader.

This code has the major components necessary to create a complete trading system.  Play around with the code and see if you can come up with a better entry mechanism.

Making Trading Decisions on Current Month’s Profit/Loss

Keeping track of intra-month profit or loss

In real time trading I have noticed that once you reach a certain loss for the month its best, sometimes, to circle the wagons and quit trading until the beginning of the next month.  This concept works best for very short term or day trade algorithms, as its very easy to get started back up.  You can do this with Trend Following, but you must build a logical and replicable process for re-entering existing positions.  Let’s assume a trading algorithm whose averaging losing month is $1500 and you are currently down $2000 – what are the chances that you will revert to the mean or draw down further?  Probably 50/50.  Who knows you might turn around and actually make money by month’s end.  If you review a track record of a hedge fund manager, trader, or algorithm and they show a bar chart of monthly returns and there sticking out like a sore thumb is a big down bar, that kind of makes you think that could happen again.  If you can control the monthly downside without sacrificing the existing Profit:DrawDown ratio, then why not do it.

Sample Code To Monitor IntraMonth $P/L

if month(date) <> month(date[1]) then
Begin
	begMonthProf = netProfit; 
	print(d," ",t," ",begMonthProf);
	canTrade = true;
end;
Capture Beginning Of Month Net Profit

Here I am comparing the month of the current bar against the month of the prior bar.  If they are not equal, then we have a new month.  Store the netProfit in the variable begMonthProf.  All you have to do is compare the current bar’s netProfit to begMonthProf and make a decision.  Here is some code:

Making a Trading Decision Based on Monthly $P/L

		If dayOfMonth(date) > 15 and begMonthProf - netProfit >= intraMonthMaxLoss then canTrade = false;
If Down MaxLoss for Month and Past Mid-Month - Quit Trading

If the day of the month is greater than 15 (month half over) and the difference between the current netProfit and begMonthProfit is greater than a negative intraMonthMaxLoss then quit trading for the month.  Only turn it back on the first bar of the next month.  See how this works for your algos.

How to Keep Track of BuysToday and SellsToday

The Useful MP

We all know how to use the reserved word/function MarketPosition – right?  Brief summary if not – use MarketPosition to see what your current position is: -1 for short, +1 for long and 0 for flat.  MarketPosition acts like a function because you can index it to see what you position was prior to the current position – all you need to do is pass a parameter for the number of positions ago.  If you pass it a one (MarketPosition(1)) then it will return the your prior position.  If you define a variable such as MP you can store each bars MarketPosition and this can come in handy.

mp = marketPosition;

If mp[1] <> 1 and mp = 1 then buysToday = buysToday + 1;
If mp[1] <> -1 and mp = -1 then sellsToday = sellsToday + 1;
Keeping Track of Buy and Sell Entries on Daily Basis

The code compares prior bar’s MP value with the current bar’s.   If there is a change in the value, then the current market position has changed.   Going from not 1 to 1 indicates a new long position.  Going from not -1 to -1 implies a new short.  If the criteria is met, then the buysToday or sellsToday counters are incremented.  If you want to keep the number of buys or sells to a certain level, let’s say once or twice,  you can incorporate this into your code.

If  time >= startTradeTime and t < endTradeTime and 
	buysToday < 1 and 
	rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If  time >= startTradeTime and t < endTradeTime and 
	sellsToday < 1 and 
	rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;
Using MP to Keep Track of BuysToday and SellsToday

This logic will work most of the time, but it depends on the robustness of the builtin MarketPosition function Look how this logic fails in the following chart:

I didn't want entries in the same direction per day!
I only wanted 1 short entry per day!

MarketPosition Failure

Failure in the sense that the algorithm shorted twice in the same day.  Notice on the first trade how the profit objective was hit on the very next bar.  The problem with MarketPosition is that it only updates at the end of the bar one bar after the entry.  So MarketPosition stays 0 during the duration of this trade.  If MarketPosition doesn’t change then my counter won’t work.  TradeStation should update MarketPosition at the end of the entry bar.  Alas it doesn’t work this way.  I figured a way around it though.  I will push the code out and explain it later in more detail.

Input: rsiLen(14),rsiBuyVal(30),rsiShortVal(70),profitObj$(250),protStop$(300),startTradeTime(940),endTradeTime(1430);

Vars: mp(0),buysToday(0),sellsToday(0),startOfDayNetProfit(0);

If d <> d[1] then
Begin
	buysToday = 0;
	sellsToday = 0;
	startOfDayNetProfit = netProfit;
end;

{mp = marketPosition;

If mp[1] <> 1 and mp = 1 then buysToday = buysToday + 1;
If mp[1] <> -1 and mp = -1 then sellsToday = sellsToday + 1;}

If entriesToday(date) > buysToday + sellsToday then 
Begin
	If marketPosition = 1 then buysToday = buysToday + 1;
	If marketPosition =-1 then sellsToday = sellsToday + 1;
	If marketPosition = 0 then
	Begin
		if netProfit > startOfDayNetProfit then
		begin
			if exitPrice(1) > entryPrice(1) then buysToday = buysToday + 1;
			If exitPrice(1) < entryPrice(1) then sellsToday = sellsToday + 1;
		end;;
		if netProfit < startOfDayNetProfit then
		Begin
			if exitPrice(1) < entryPrice(1) then buysToday = buysToday + 1;
			If exitPrice(1) > entryPrice(1) then sellsToday = sellsToday + 1;
		end;
	end;
	print(d," ",t," ",buysToday," ",sellsToday);
end;

If  time >= startTradeTime and t < endTradeTime and 
	buysToday < 1 and 
	rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If  time >= startTradeTime and t < endTradeTime and 
	sellsToday < 1 and 
	rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;

SetProfittarget(profitObj$);
SetStopLoss(protStop$);

SetExitOnClose;
A Better Buy and Short Entries Counter

TradeStation does update EntriesToday at the end of the bar so you can use this keyword/function to help keep count of the different type of entries.  If MP is 0 and EntriesToday increments then you know an entry and an exit has occurred (takes care of the MarketPosition snafu) – all you need to do is determine if the entry was a buy or a sell.  NetProfit is also updated when a trade is closed.   I establish the StartOfDayNetProfit on the first bar of the day (line 9 in the code) and then examine EntriesToday and if NetProfit increased or decreased.  EntryPrice and ExitPrice are also updated at the end of the bar so I can also use them to extract the information I need.   Since MarketPosition is 0  I have to pass 1 to the EntryPrice and ExitPrice functions – prior position’s prices.  From there I can determine if a Long/Short entry occurred.  This seems like a lot of work for what you get out of it, but if you are controlling risk by limiting the number of trades (exposure) then an accurate count is so very important.

An alternative is to test on a higher resolution of data – say 1 minute bars.  In doing this you give a buffer to the MarketPosition function – more bars to catch up.

 

Pyramiding and then Scaling Out at Different Price Levels – EasyLanguage

TOTAL, TOTAL, TOTAL – an important keyword

I just learned something new!  I guess I never programmed a strategy that pyramided at different price levels and scaled out at different price levels.

Initially I thought no problem.  But I couldn’t get it to work – I tried everything and then I came across the keyword Total and then I remembered.  If you don’t specify Total in you exit directives then the entire position is liquidated.  Unless you are putting all your positions on at one time – like I did in my last post.   So remember if you are scaling out of a pyramid position use Total in your logic.

vars: maxPosSize(2);

If currentContracts < maxPosSize - 1 and c > average(c,50) and c = lowest(c,3) then buy("L3Close") 1 contract this bar on close;
If currentContracts < maxPosSize and c > average(c,50) and c = lowest(c,4) then buy("L4Close") 1 contract this bar on close;


If currentContracts = 2 and c = highest(c,5) then sell 1 contract total this bar on close;
If currentContracts = 1 and c = highest(c,10) then sell 1 contract total this bar on close;
Scaling Out Of Pyramid

Why you have to use the Total I don’t know.  You specify the number of contracts in the directive and that is sufficient if you aren’t pyramiding.  The pyramiding throws a “monkey wrench” in to the works.