# George’s EasyLanguage BarsSince Function – How Many Bars Since?

Have you ever wondered how many bars have transpired since a certain condition was met?  Some platforms provide this capability:

If ExitFlag and (c crosses above average within 3 bars) then

TradeStation provides the MRO (Most Recent Occurrence) function that provides a very similar capability.  The only problem with this function is that it returns a -1 if the criteria are not met within the user provided lookback window.  If you say:

myBarsSinceCond = MRO(c crosses average(c,200),20,1) < 3

And c hasn’t crossed the 200-day moving average within the past twenty days the condition is still set to true because the function returns a -1.

I have created a function named BarsSince and you can set the false value to any value you wish.  In the aforementioned example, you would want the function to return a large number so the function would provide the correct solution.  Here’s how I did it:

``inputs: 	Test( truefalseseries ), 	Length( numericsimple ), 	Instance( numericsimple ) , { 0 < Instance <= Length}	FalseReturnValue(numericsimple); {Return value if not found in length window}	 value1 = RecentOcc( Test, Length, Instance, 1 ) ;If value1 = -1 then 	BarsSince = FalseReturnValueElse	BarsSince = value1;``

And here’s a strategy that uses the function:

``inputs: profTarg\$(2000),protStop\$(1000),rsiOBVal(60),rsiOSVal(40),slowAvgLen(100),fastAvgLen(9),rsiLen(14),barsSinceMax(3);Value1 = BarsSince(rsi(c,rsiLen) crosses above rsiOSVal,rsiLen,1,999);Value2 = BarsSince(rsi(c,rsiLen) crosses below rsiOBVal,rsiLen,1,999);If c > average(c, slowAvgLen) and c < average(c,fastAvgLen) and Value1 <barsSinceMax then buy next bar at open;If c < average(c, slowAvgLen) and c > average(c,fastAvgLen) and Value2 <barsSinceMax then sellshort next bar at open;setStopLoss(protStop\$);setProfitTarget(profTarg\$)``

The function requires four arguments:

1. The condition that is being tested [e.g.  rsi > crosses above 30]
2. The lookback window [rsiLen – 14 bars in this case]
3. Which occurrence [1 – most recent; 2- next most recent; etc…]
4. False return value [999 in this case; if condition is not met in time]

## A Simple Mean Reversion Using the Function:

Here are the results of this simple system utilizing the function.

### Optimization Results:

I came up with this curve through a Genetic Optimization:

The BarsSince function adds flexibility or fuzziness when you want to test a condition but want to allow it to have a day (bar) or two tolerance.  In a more in-depth analysis, the best results very rarely occurred on the day the RSI crossed a boundary.   Email me with questions of course.

# 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] thenBegin	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 thenBegin 	longExitPoint = entryPrice - longStopAmt;	sell("L-Exit") next bar at longExitPoint stop;end;If marketposition = -1 thenBegin	shortExitPoint = entryPrice + shortStopAmt;	buyToCover("S-Exit") next bar at shortExitPoint stop;end;If marketPosition = 1 and maxContractProfit/bigPointValue >= longThreshAmt thenBegin	longTrailLevel = maxList(highest(h,barsSinceEntry) - longTrailAmt,longTrailLevel);	sell("TrailSell") next bar at longTrailLevel stop;end;If marketPosition = -1 and maxContractProfit/bigPointValue >= shortThreshAmt thenBegin	shortTrailLevel = minList(lowest(l,barsSinceEntry) + shortTrailAmt,ShortTraillevel);	buyToCover("TrailCover") next bar at shortTrailLevel stop;end;SetExitOnClose;``

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.