Category Archives: EasyLanguage Snippets

Converting A String Date To A Number – String Manipulation in EasyLanguage

EasyLanguage Includes a Powerful String Manipulation Library

I thought I would share this function.  I needed to convert a date string (not a number per se) like “20010115” or “2001/01/15” or “01/15/2001” or “2001-01-15” into a date that TradeStation would understand.  The function had to be flexible enough to accept the four different formats listed above.

String Functions

Most programming languages have functions that operate strictly on strings and so does EasyLanguage.  The most popular are:

  • Right String (rightStr) – returns N characters from the right side of the string.
  • Left String (leftStr) – returns N character starting from the left side of the string
  • Mid String (midStr) – returns the middle portion of a string starting at a specific place in the string and advance N characters
  • String Length (strLen) – returns the number of characters in the string
  • String To Number (strToNum) – converts the string to a numeric representation.  If the string has a character, this function will return 0
  • In String (inStr) – returns location of a sub string inside a larger string ( a substring can be just one character long)

Unpack the String

If the format is YYYYMMDD format then all you need to do is remove the dashes or slashes (if there are any) and then convert what is left over to a number.   But if the format is MM/DD/YYYY format then we are talking about a different animal.  So how can you determine if the date string is in this format?  First off you need to find out if the month/day/year separator is a slash or a dash.  This is how you do this:

whereIsAslash = inStr(dateString,”/”);
whereIsAdash = inStr(dateString,”-“);

If either is a non zero then you know there is a separator.  The next thing to do is locate the first “dash or slash” (the search character or string).  If it is located within the first four characters of the date string then you know its not a four digit year.  But, lets pretend the format is “12/14/2001” so if the first dash/slash is the 3rd character you can extract the month string by doing this:

firstSrchStrLoc = inStr(dateString,srchStr);
mnStr= leftStr(dateString,firstSrchStrLoc-1);

So if firstSrchStrLoc = 3 then we want to leftStr the date string and extract the first two characters and store them in mnStr.  We then store what’s left of the date string in tempStr by using rightStr:

strLength = strLen(dateString);

tempStr = rightStr(dateString,strLength-firstSrchStrLoc);

Here I pass dateString and the strLength-firstSrchStrLoc – so if the dateString is 10 characters long and the firstSrchStrLoc is 3, then we can create a tempstring by taking [10 -3  = 7 ] characters from right side of the string:

“12/14/2001” becomes “14/2001” – once that is done we can pull the first two characters from the tempStr and store those into the dyStr [day string.]  I do this by searching for the “/” and storing its location in srchStrLoc.  Once I have that location I can use that information and leftStr to get the value I need.   All that is left now is to use the srchStrLoc and the rightStr function.

srchStrLoc = inStr(tempStr,srchStr);
dyStr = leftStr(tempStr,srchStrLoc-1);
yrStr = rightStr(tempStr,strLen(tempStr)-srchStrLoc);

Now convert the strings to numbers and multiply their values accordingly.

DateSTrToYYYMMDD = strToNum(yrStr) X 10000-19000000 + strToNum(mnStr) X 100 + strToNum(dyStr)

To get the date into TS format I have to subtract 19000000 from the year.  Remember TS represents the date in YYYMMDD  format.

Now what do  you do if the date is in the right format but simply includes the dash or slash separators.  All you need to do here is loop through the string and copy all non dash or slash characters to a new string and then convert to a number.  Here is the loop:

        tempStr = "";
iCnt = 1;
While iCnt <= strLength
Begin
If midStr(dateString,iCnt,1) <> srchStr then
tempStr += midStr(dateString,iCnt,1);
iCnt+=1;
end;
tempDate = strToNum(tempStr);
DateStrToYYYMMDD = tempDate-19000000;

Here I use midStr to step through each character in the string.  MidStr requires a string and the starting point and how many characters you want returned from the string.  Notice I step through the string with iCnt and only ask for 1 character at a time.  If the character is not a dash or slash I concatenate tempStr with the non dash/slash character.  At the end of the While loop I simply strToNum the string and subtract 19000000.  That’s it!  Remember EasyLanguage is basically a full blown programming language with a unique set of functions that relate directly to trading.

Here is the function and testFunc caller.

STRINGFUNCANDFUNCCALLER

 

Implementing Finite State Machine Functionality with EasyLanguage (Last Trade Was Loser Filter a la Turtle)

Last Trade Was a Loser Filter – To Use or Not To Use

Premise

A major component of the Turtle algorithm was to skip the subsequent 20-day break out if the prior was a winner.  I guess Dennis believed the success/failure of a trade had an impact on the outcome of the subsequent trade.  I have written on how you can implement this in EasyLanguage in prior posts, but I have been getting some questions on implementing FSM in trading and thought this post could kill two birds with one stone: 1) provide a template that can be adapted to any LTL mechanism and 2) provide the code/structure of setting up a FSM using EasyLanguage’s Switch/Case structure.

Turtle Specific LTL Logic

The Turtle LTL logic states that a trade is a loser if a 2N loss occurs after entry.  N is basically an exponential-like moving average of TrueRange.  So if the market moves 2N against a long or short position and stops you out, you have a losing trade.  What makes the Turtle algorithm a little more difficult is that you can also exit on a new 10-day low/high depending on your position.  The 10-day trailing exit does not signify a loss.  Well at least in this post it doesn’t.  I have code that says any loss is a loss, but for this explanation let’s just stick to a 2N loss to determine a trade’s failure.

How To Monitor Trades When Skipping Some Of Them

This is another added layer of complexity.  You have to do your own trade accounting behind the scenes to determine if a losing trade occurs.  Because if you have a winning trade you skip the next trade and if you skip it how do you know if it would have been a winner or a loser.  You have to run a theoretical system in parallel with the actual system code.

Okay let’s start out assuming the last trade was a winner.  So we turn real trading off.  As the bars go by we look for a 20-Day high or low penetration.  Assume a new 20-Day high is put in and a long position is established at the prior 20-Day high.  At this point you calculate a 2N amount and subtract if from the theoretical entry price to obtain the theoretical exit price.  So you have a theoMP (marketPosition) and a theoEX (exit price.)  This task seems pretty simple, so you mov on and start looking for a day that either puts in a new 10-Day low or crosses below your theoEX price.  If a new 10-Day low is put in then you continue on looking for a new entry and a subsequent 2N loss.  If a 2N loss occurs, then you turn trading back on and continue monitoring the trades – turning trading off and then back on when necessary.  In the following code I use these variables:

  • state – 0: looking for an entry or 1: looking for an exit
  • lep – long entry price
  • sep– short entry price
  • seekLong – I am seeking a long position
  • seekShort – I am seeking a short position
  • theoMP – theoretical market position
  • theoEX – theoretical exit price
  • lxp – long exit price
  • sxp – short exit price

Let’s jump into the Switch/Case structure when state = 0:

	Switch(state)
Begin
Case 0:
lep = highest(h[1],20) + minMove/priceScale;
sep = lowest(l[1],20) - minMove/priceScale;
If seekLong and h >= lep then
begin
theoMP = 1;
theoEX = maxList(lep,o) - 2 * atr;
// print(d," entered long >> exit at ",theoEX," ",atr);
end;
If seekShort and l <= sep then
begin
theoMP = -1;
theoEX = minList(sep,o) + 2 * atr;
end;
If theoMP <> 0 then
begin
state = 1;
cantExitToday = True;
end;
State 0 (Finite State Set Up)

The Switch/Case is a must have structure in any programming language.  What really blows my mind is that Python doesn’t have it.  They claim its redundant to an if-then structure and it is but its so much easier to read and implement.  Basically you use the Switch statement and a variable name and based on the value of the variable it will flow to whatever case the variable equates to.  Here we are looking at state 0.  In the CASE: 0  structure the computer calculates the lep and sep values – long and short entry levels.  If you are flat then you are seeking a long or a short position.  If the high or low of the bar penetrates it respective trigger levels then theoMP is set to 1 for long or -1 for short.  TheoEX is then calculated based on the atr value on the day of entry.  If theoMP is set to either a 1 or -1, then we know a trade has just been triggered.  The Finite State Machine then switches gears to State 1.  Since State = 1 the next Case statement is immediately evaluated.  I don’t want to exit on the same bar as I entered (wide bars can enter and exit during volatile times) I use a variable cantExitToday.  This variable delays the Case 1: evaluation by one bar.

State = 1 code:

		Case 1:
If not(cantExitToday) then
begin
lxp = maxList(theoEX,lowest(l[1],10)-minMove/priceScale);
sxp = minList(theoEX,highest(h[1],10)+minMove/priceScale);
If theoMP = 1 and l <= lxp then
begin
theoMP = 0;
seekLong = False;
if lxp <= theoEX then
ltl = True
Else
ltl = False;
end;
If theoMP =-1 and h >= sxp then
begin
theoMP = 0;
seekShort = False;
if sxp >= theoEX then
ltl = True
else
ltl = False;
end;
If theoMP = 0 then state = 0;
end;
cantExitToday = False;
end;
State = 1 (Switching Gears)

Once we have a theoretical position, then we only examine the code in the Case 1: module.  On the subsequent bar after entry, the lxp and sxp (long exit and short exit prices) are calculated.  Notice these values use maxList or minList to determine whichever is closer to the current market action – the 2N stop or the lowest/highest low/high for the past 10-daysLxp and sxp are assigned whichever is closer.  Each bar’s high or low is compared to these values.  If theoMP = 1 then the low is compared to lxp.  If the low crosses below lxp, then things are set into motion.  The theoMP is immediately set to  0 and seekLong is turned to False.  If lxp <= a 2N loss then ltl (last trade loser) is set to true.  If not, then ltl is set to False.   If theoMP = 0 then we assume a flat position and switch the FSM back to State 0 and start looking for a new trade.  The ltl variable is then used in the code to allow a real trade to occur.

Strategy Incorporates Our FSM Output

vars:N(0),mp(0),NLossAmt(0);
If barNumber = 1 then n = avgTrueRange(20);
if barNumber > 1 then n = (n*19 + trueRange)/20;

If useLTLFilter then
Begin
if ltl then buy next bar at highest(h,20) + minMove/priceScale stop;
if ltl then sellShort next bar at lowest(l,20) -minMove/priceScale stop;
end
Else
Begin
buy next bar at highest(h,20) + minMove/priceScale stop;
sellShort next bar at lowest(l,20) -minMove/priceScale stop;
end;

mp = marketPosition;

If mp <> 0 and mp[1] <> mp then NLossAmt = 2 * n;

If mp = 1 then
Begin
Sell("LL10-LX") next bar at lowest(l,10) - minMove/priceScale stop;
Sell("2NLS-LX") next bar at entryPrice - NLossAmt stop;
end;
If mp =-1 then
Begin
buyToCover("HH10-SX") next bar at highest(h,10) + minMove/priceScale stop;
buyToCover("2NLS-SX") next bar at entryPrice + NLossAmt stop;
end;
Strategy Code Using ltl filter

This code basically replicates what we did in the FSM, but places real orders based on the fact that the Last Trade Was A Loser (ltl.)

Does It Work – Only Trade After a 2N-Loss

Last Trade Loser In Action

Without Filter on the last 10-years in Crude Oil

With Filter on the last 10-years in Crude Oil

I have programmed this into my TradingSimula-18 software and will show a portfolio performance with this filter a little later at www.trendfollowingsystems.com.

I had to do some fancy footwork with some of the code due to the fact you can exit and then re-enter on the same bar.  In the next post on this blog I will so you those machinations .  With this template you should be able to recreate any last trade was a loser mechanism and see if it can help out with your own trading algorithms.  Shoot me an email with any questions.

 

 

 

Ratio Adjusted versus Point Adjusted Contracts in TradeStation Part 2

Thomas Stridsman quote from  his “Trading Systems That Work Book”

The benefits of the RAD contract also become evident when you want to put together a multimarket portfolio…For now we only state that the percentage based calculations do not take into consideration how many contracts you’re trading and, therefore, give each market an equal weighting in the portfolio.

The Stridsman Function I presented in the last post can be used to help normalize a portfolio of different markets.  Here is a two market portfolio (SP – 250price and JY -125Kprice contract sizes) on a PAD contract.

1-Contract SP and JY on PAD data

Here is the performance of the same portfolio on a RAD contract.

Equal rating of SP and JY on RAD data

 

The curve shapes are similar but look at the total profit and the nearly $125K draw down.  I was trying to replicate Thomas’ research so this data is from Jan. 1990 to Dec. 1999.  A time period where the price of the SP increased 3 FOLD!  Initially you would start trading 1 JY to 2 SP but by the time it was over you would be trading nearly 3 JY to 1 SP.  Had you traded at this allocation the PAD numbers would be nearly $240K in profit.  Now this change occurred through time so the percentage approach is applied continuously.  Also the RAD data allows for a somewhat “unrealistic” reinvestment or compounding mechanism.  Its unrealistic because you can’t trade a partial futures contract.  But it does give you a glimpse of the potential.  The PAD test does not show reinvestment of profit.  I have code for that if you want to research that a little bit more.  Remember everything is in terms of Dec. 31 1999 dollars.  That is another beauty of the RAD contract.

Another Stridsman Quote

Now, wait a minute, you say, those results are purely hypothetical.  How can I place all the trades in the same market at presumably the same point in time?  Well, you can’t, so that is a good and valid question; but let me ask you, can you place any of these trades for real, no matter, how you do it?  No, of course not.  They all represent foregone opportunities.  Isn’t it better then to at least place them hypothetically in today’s marketplace to get a feel for what might happen today, rather in a ten-year-old market situation to get a feel for how the situation was back then?  I think wall can agree that it is better to know what might happen today, rather than what happened ten years ago.

That is a very good point.  However, convenience and time is import and when developing an algorithm.  And most platforms, including my TS-18, are geared toward PAD data.  However TS-18 can look at the entire portfolio balance and all the market data for each market up to that point in time and can adjust/normalize based on portfolio and data metrics.  However, I will add a percentage module a little later, but I would definitely use the StridsmanFunc that I presented in the last post to validate/verify your algorithm in today’s market place if using TradeStation.

Email me if you want the ELD of the function.

Ratio Adjusted versus Pointed Adjusted Contracts in TradeStation – Part 1

If you play around with TradeStation’s custom futures capabilities you will discover you can create different adjusted continuous contracts.  Take a look at this picture:

Panama vs Ratio Adjusted

Both charts look the same and the trades enter and exit at the same locations in relation to the respective price charts.   However, take a look at the Price Scale on the right and the following pictures.

As you can see from the P/L from each trade list there is a big difference.  The top list is using RAD and the second is the generally accepted Panama Adjusted Data (PAD.)  Ratio adjusted data takes the percentage difference between the expiring contract and the new contract and propagates the value throughout the entire back history.  This is different than the PAD we have all used, where the actual point difference is propagated.  These two forms of adjustment have their own pros and cons but many industry leaders prefer the RAD.  I will go over a little bit of the theory in my next post, but in the mean time I will direct you to Thomas Stridsman’s excellent work on the subject in his book, “Trading Systems That Work – Building and Evaluating Effective Trading Systems”.

Here is another look at draw down metrics between the two formats.

RAD V PAD DrawDown

Who would want to trade a system on 1 contract of crude and have a $174K draw down?  Well you can’t look at it like that.  Back in 2008 crude was trading at $100 X 1000 = $100,000 a contract.  Today May 11th 2020 it is around $25,000.  So a drawdown of $44K back then would be more like $176K in today’s terms.  In my next post I will go over the theory of  RAD, but for right now you just need to basically ignore TradeStation’s built in performance metrics and use this function that I developed in most part by looking at Thomas’ book.

//Name this function StridsmanFunc1

Vars: FName(""), offset(1),TotTr(0), Prof(0), CumProf(1), ETop(1), TopBar(0), Toplnt(0),BotBar(0), Botlnt(0), EBot(1), EDraw(1), TradeStr2( "" );
Arrays: tradesPerArr[1000](0),drawDownArr[1000](0);
Vars: myEntryPrice(0),myEntryDate(0),myMarketPosition(0),myExitDate(0),myExitPrice(0);
If CurrentBar = 1 Then
Begin
FName = "C:\Temp\" + LeftStr(GetSymbolName, 3) + ".csv";
FileDelete(FName);
TradeStr2 = "E Date" + "," + "Position" + "," + "E Price" + "," + "X Date" +"," + "X Price" + "," + "Profit" + "," + "Cum. prof." + "," + "E-Top" + "," +"E-Bottom" + "," + "Flat time" + "," + "Run up" + "," + "Drawdown" +NewLine;
FileAppend(FName, TradeStr2);
End;
TotTr = TotalTrades;
If TotTr > TotTr[1] or (lastBarOnChart and marketPosition <> 0) Then
Begin

if TotTr > TotTr[1] then
begin
if (EntryPrice(1) <> 0) then Prof = 1 + PositionProfit(1)/(EntryPrice(1) * BigPointValue);
End
else
begin
Value99 = iff(marketPosition = 1,c - entryPrice, entryPrice - c);
Prof = 1 + (Value99*bigPointValue) /(Entryprice *BigPointValue);
// print(d," StridsmanFunc1 ",Value99," ",Prof," ",(Value99*bigPointValue) /(Entryprice *BigPointValue):5:4);
TotTr = totTr + 1;
end;
tradesPerArr[TotTr] = Prof - 1;
CumProf = CumProf * Prof;
ETop = MaxList(ETop, CumProf);
If ETop > ETop[1] Then
Begin
TopBar = CurrentBar;
EBot = ETop;
End;

EBot = MinList(EBot, CumProf);

If EBot<EBot[1] Then BotBar = CurrentBar;

Toplnt = CurrentBar - TopBar;

Botlnt = CurrentBar - BotBar;

if ETop <> 0 then EDraw = CumProf / ETop;

drawDownArr[TotTr] = (EDraw - 1);

myEntryDate = EntryDate(1);
myMarketPosition = MarketPosition(1);
myEntryPrice = EntryPrice(1);
myExitDate = ExitDate(1);
myExitPrice = ExitPrice(1);
If lastBarOnChart and marketPosition <> 0 then
Begin
myEntryDate = EntryDate(0);
myMarketPosition = MarketPosition(0);
myEntryPrice = EntryPrice(0);
myExitDate = d;
myExitPrice =c;
end;
TradeStr2 = NumToStr(myEntryDate, 0) + "," +NumToStr(myMarketPosition, 0) + "," + NumToStr(myEntryPrice, 2) + ","
+ NumToStr(myExitDate, 0) + "," + NumToStr(myExitPrice, 2) + ","+ NumToStr((Prof - 1) * 100, 2) + "," + NumToStr((CumProf - 1) *100, 2) + ","
+ NumToStr((ETop - 1) * 100, 2) + "," + NumToStr((EBot - 1) * 100, 2) + "," + NumToStr(Toplnt, 0) + "," + NumToStr(Botlnt, 0) + "," + NumToStr((EDraw - 1) * 100, 2) +
NewLine;

FileAppend(FName, TradeStr2);
End;
vars: tradeStr3(""),
ii(0),avgTrade(0),avgTrade$(0),cumProf$(0),trdSum(0),
stdDevTrade(0),stdDevTrade$(0),
profFactor(0),winTrades(0),lossTrades(0),perWins(0),perLosers(0),
largestWin(0),largestWin$(0),largestLoss(0),largestLoss$(0),avgProf(0),avgProf$(0),
winSum(0),lossSum(0),avgWin(0),avgWin$(0),avgLoss(0),avgLoss$(0),maxDD(0),maxDD$(0),cumProfit(0),cumProfit$(0);

If lastBarOnChart then
begin
stdDevTrade = standardDevArray(tradesPerArr,TotTr,1);
stdDevTrade$ = stdDevTrade*c*bigPointValue;
For ii = 1 to TotTr
Begin
trdSum = trdSum + tradesPerArr[ii];
// print(d," ",ii," ",tradesPerArr[ii]);
If tradesPerArr[ii] > 0 then
begin
winTrades = winTrades + 1;
winSum = winSum + tradesPerArr[ii];
end;
If tradesPerArr[ii] <=0 then
begin
lossTrades = lossTrades + 1;
lossSum = lossSum + tradesPerArr[ii];
end;
If tradesPerArr[ii] > largestWin then
begin
largestWin = tradesPerArr[ii];
// print("LargestWin Found ",largestWin);
end;
If tradesPerArr[ii] < largestLoss then largestLoss = tradesPerArr[ii];
If drawDownArr[ii] < maxDD then maxDD = drawDownArr[ii];
end;
// print("TradeSum: ",trdSum);
if TotTr <> 0 then avgTrade = trdSum/TotTr;
avgTrade$ = avgTrade*c*bigPointValue;
largestWin = largestWin;
largestLoss = largestLoss;
largestWin$ = largestWin*c*bigPointValue;
largestLoss$ = largestLoss*c*bigPointValue;
if TotTr <> 0 then perWins = winTrades/TotTr;
if TotTr <> 0 then perLosers = lossTrades/TotTr;
If winTrades <> 0 then avgWin = winSum / winTrades;
avgWin$ = avgWin*c*bigPointValue;
if lossTrades <> 0 then avgLoss= lossSum / lossTrades;
avgLoss$ = avgLoss*c*bigPointValue;
maxDD$ = maxDD *c*bigPointValue;
if lossTrades <>0 and avgLoss$ <> 0 then profFactor = (winTrades*avgWin$)/(lossTrades*avgLoss$);
CumProf = cumProf - 1;
CumProf$ = cumProf*c*bigPointValue;

TradeStr3 = "Total Trades,,"+NumToStr(TotTr,0)+",Num. Winners,"+NumToStr(winTrades,0)+","+NumToStr(perWins,3)+", Num. Losses,"+NumToStr(lossTrades,0)+","+NumToStr(perLosers,3)+NewLine+
"Profit Factor,,"+NumToStr(profFactor,3)+",Largest Win ,"+NumToStr(largestWin,3)+","+NumToStr(largestWin$,0)+",Largest Loss,"+NumToStr(largestLoss,3)+","+NumToStr(largestLoss$,0)+NewLine+
"Avg Profit,"+NumToStr(avgTrade,3)+","+NumToSTr(avgTrade$,0)+",Avg Win,"+NumToStr(avgWin,3)+","+NumToStr(avgWin$,0)+",Avg Loss,"+NumToStr(avgLoss,3)+","+NumToStr(avgLoss$,0)+NewLine+
"Std. Dev,"+NumToStr(stdDevTrade,3)+","+NumToStr(stdDevTrade$,0)+",Cum Profit,"+NumToStr(cumProf,3)+","+NumToStr(cumProf$,3)+",Draw Down,"+numToStr(maxDD,3)+","+numToStr(maxDD$,0)+NewLine;
FileAppend(FName, TradeStr3);
{ Print("Total Trades ",totalTrades," Num. Winners ",winTrades," ",perWins," Num. Losses ",lossTrades," ",perLosers);
Print("Profit Factor ",profFactor," Largest Win ",largestWin:5:2," ",largestWin$," Largest Loss ",largestLoss:5:2," ",largestLoss$);
Print("Avg Profit ",avgTrade," ",avgTrade$," Avg Win ",avgWin," ",avgWin$," Avg Loss ",avgLoss," ",avgLoss$);
Print("St Dev ",stdDevTrade," ",stdDevTrade$," Cum Profit ",cumProf," ",cumProf$," Drawdown ",maxDD," ",maxDD$);}


end;



StridsmanFunc1 = 1;
Conversion of Performance Metrics to Percentages Instead of $Dollars

This function will out put a file that looks like this.  Go ahead and play with the code – all you have to do is call the function from within an existing strategy that you are working with.  In part two I will go over the code and explain what its doing and how arrays and strings were used to archive the trade history and print out this nifty table.

Stridsman Function Output.

In this output if you treat the return from each trade as a function of the entry price and accumulate the returns you can convert the value to today’s current market price of the underlying.  In this case a 15 -year test going through the end of last year, ended up making almost $70K.

RAD TradeStation Metrics:

Profit $350K – Draw Down $140K

PAD TradeStation Metrics:

Profit $89K – Draw Down $45K

Stridsman Func on RAD:

Profit $70K – Draw Down $48K

At this point you can definitely determine that the typical RAD/TS metrics are not all that usuable.  The PAD/TS results look very similar to RAD/StridsmanFunc results.  Stay tuned for my next post and I will hopefully explain why RAD/StridsmanFunc is probably the most accurate performance metrics of the three.

Testing Keith Fitschen’s Bar Scoring with Pattern Smasher

Keith’s Book

Thanks to MJ for planting the seed for this post.  If you were one of the lucky ones to get Keith’s “Building Reliable Trading SystemsTradable Strategies that Perform as They Backtest and Meet Your Risk-Reward Goals”  book by John Wiley 2013 at the list price of $75 count yourself lucky.  The book sells for a multiple of that on Amazon.com.  Is there anything earth shattering in the book you might ask?  I wouldn’t necessarily say that, but there are some very well thought out and researched topics that most traders would find of interest.

Bar Scoring

In his book Keith discusses the concept of bar-scoring.  In Keith’s words, “Bar-scoring is an objective way to classify an instrument’s movement potential every bar.  The two parts of the bar-scoring are the criterion and the resultant profit X days hence.”  Keith provides several bar scoring techniques, but I highlight just one.

Keith broke these patterns down into the relationship of the close to the open, and close in the upper half of the range; close greater than the open and close in the lower half of the range.  He extended the total number of types to 8 by adding the relationship of the close of the bar to yesterdays bar.

The PatternSmasher code can run through a binary representation

for each pattern and test holding the position for an optimizable number of days.  It can also check for long and short positions.  The original Pattern Smasher code used a for-loop to create patterns that were then compared to the real life facsimile.  In this code it was easier to just manually define the patterns and assign them the binary string.

if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+++";
Manual Pattern Designations

Please check my code for any errors.  Here I go through the 8 different relationships and assign them to a Patter String.  “-+++”  represents pattern number (7 ) or type (7 + 1 = 8 – my strings start out at 0).  You can then optimize the test pattern and if the test pattern matches the actual pattern, then the Pattern Smasher takes the trade  on the opening of the next bar and holds it for the number of days you specify.  You an also designate long and short positions in the code.  Here I optimized the 8 patterns going long and short and holding from 1-4 days.

Here is the equity curve!  Remember these are Hypothetical Results with $0 commission/slippage and historic performance is not necessarily indicative of future results.  Educational purposes only!  This is tested on ES.D

Play around with the code and let me know if you find any errors or any improvements.

input: patternTests(8),orbAmount(0.20),LorS(1),holdDays(0),atrAvgLen(10),enterNextBarAtOpen(true);

var: patternTest(""),patternString(""),tempString("");
var: iCnt(0),jCnt(0);
array: patternBitChanger[4](0);

{written by George Pruitt -- copyright 2019 by George Pruitt
This will test a 4 day pattern based on the open to close
relationship. A plus represents a close greater than its
open, whereas a minus represents a close less than its open.
The default pattern is set to pattern 14 +++- (1110 binary).
You can optimize the different patterns by optimizing the
patternTests input from 1 to 16 and the orbAmount from .01 to
whatever you like. Same goes for the hold days, but in this
case you optimize start at zero. The LorS input can be
optimized from 1 to 2 with 1 being buy and 2 being sellshort.}

patternString = "";
patternTest = "";

patternBitChanger[0] = 0;
patternBitChanger[1] = 0;
patternBitChanger[2] = 0;
patternBitChanger[3] = 0;

value1 = patternTests - 1;


//example patternTests = 0 -- > 0000
//example patternTests = 1 -- > 0001
//example patternTests = 2 -- > 0010
//example patternTests = 3 -- > 0011
//example patternTests = 4 -- > 0100
//example patternTests = 5 -- > 0101
//example patternTests = 6 -- > 0110
//example patternTests = 7 -- > 0111

if(value1 >= 0) then
begin

if(mod(value1,2) = 1) or value1 = 1 then patternBitChanger[0] = 1;
value2 = value1 - patternBitChanger[0] * 1;

if(value2 >= 7) then begin
patternBitChanger[3] = 1;
value2 = value2 - 8;
end;

if(value2 >= 4) then begin
patternBitChanger[2] = 1;
value2 = value2 - 4;
end;
if(value2 = 2) then patternBitChanger[1] = 1;
end;

for iCnt = 3 downto 0 begin
if(patternBitChanger[iCnt] = 1) then
begin
patternTest = patternTest + "+";
end
else
begin
patternTest = patternTest + "-";
end;
end;

patternString = "";

if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+++";


if(barNumber = 1) then print(elDateToString(date)," pattern ",patternTest," ",patternTests-1);
if(patternString = patternTest) then
begin

// print(date," ",patternString," ",patternTest); //uncomment this and you can print out the pattern
if (enterNextBarAtOpen) then
begin
if(LorS = 2) then SellShort("PatternSell") next bar on open;
if(LorS = 1) then buy("PatternBuy") next bar at open;
end
else
begin
if(LorS = 2) then SellShort("PatternSellBO") next bar at open of tomorrow - avgTrueRange(atrAvgLen) * orbAmount stop;
if(LorS = 1) then buy("PatternBuyBO") next bar at open of tomorrow + avgTrueRange(atrAvgLen) * orbAmount stop;
end;


end;

if(holdDays = 0 ) then setExitonClose;
if(holdDays > 0) then
begin
if(barsSinceEntry = holdDays and LorS = 2) then BuyToCover("xbarLExit") next bar at open;
if(barsSinceEntry = holdDays and LorS = 1) then Sell("xbarSExit") next bar at open;
end;
Bar Scoring Testing Template

MULTI-TIME FRAME – KEEPING TRACK OF DISCRETE TIME FRAMES

Just a quick post here.  I was asked how to keep track of the opening price for each time frame from our original Multi-Time Frame indicator and I was answering the question when I thought about modifying the indicator.  This version keeps track of each discrete time frame.  The original simply looked back a multiple of the base chart to gather the highest highs and lowest lows and then would do a simple calculation to determine the trend.  So let’s say its 1430 on a five-minute bar and you are looking back at time frame 2.  All I did was get the highest high and lowest low two bars back and stored that information as the high and low of time frame 2.  Time frame 3 simply looked back three bars to gather that information.  However if you tried to compare these values to a 10-minute or 15-minute chart they would not match.

In this version, I use the modulus function to determine the demarcation of each time frame.  If I hit the border of the time frame I reset the open, high, low and carry that value over until I hit the next demarcation.  All the while collecting the highest highs and lowest lows.  In this model, I am working my way from left to right instead of right to left.  And in doing so each time frame is discrete.

Let me know which version you like best.

 

Inputs:tf1Mult(2),tf2Mult(3),tf3Mult(4),tf4Mult(5);



vars: mtf1h(0),mtf1l(0),mtf1o(0),mtf1c(0),mtf1pvt(0),diff1(0),
mtf2h(0),mtf2l(0),mtf2o(0),mtf2c(0),mtf2pvt(0),diff2(0),
mtf3h(0),mtf3l(0),mtf3o(0),mtf3c(0),mtf3pvt(0),diff3(0),
mtf4h(0),mtf4l(0),mtf4o(0),mtf4c(0),mtf4pvt(0),diff4(0),
mtf0pvt(0),diff0(0);

If barNumber = 1 then
Begin
mtf1o = o;
mtf2o = o;
mtf3o = o;
mtf4o = o;
end;


If barNumber > 1 then
Begin

Condition1 = mod((barNumber+1),tf1Mult) = 0;
Condition2 = mod((barNumber+1),tf2Mult) = 0;
Condition3 = mod((barNumber+1),tf3Mult) = 0;
Condition4 = mod((barNumber+1),tf4Mult) = 0;

mtf1h = iff(not(condition1[1]),maxList(high,mtf1h[1]),high);
mtf1l = iff(not(condition1[1]),minList(low,mtf1l[1]),low);
mtf1o = iff(condition1[1],open,mtf1o[1]);
mtf1c = close;


mtf0pvt = (close + high + low) / 3;
diff0 = close - mtf0pvt;

mtf2h = iff(not(condition2[1]),maxList(high,mtf2h[1]),high);
mtf2l = iff(not(condition2[1]),minList(low,mtf2l[1]),low);
mtf2o = iff(condition2[1],open,mtf2o[1]);
mtf2c = close;


mtf1pvt = (mtf1h+mtf1l+mtf1c) / 3;
diff1 = mtf1c - mtf1pvt;

mtf2pvt = (mtf2h+mtf2l+mtf2c) / 3;
diff2 = mtf2c - mtf2pvt;

mtf3h = iff(not(condition3[1]),maxList(high,mtf3h[1]),high);
mtf3l = iff(not(condition3[1]),minList(low,mtf3l[1]),low);
mtf3o = iff(condition3[1],open,mtf3o[1]);
mtf3c = close;

mtf3pvt = (mtf3h+mtf3l+mtf3c) / 3;
diff3 = mtf3c - mtf3pvt;

mtf4h = iff(not(condition4[1]),maxList(high,mtf4h[1]),high);
mtf4l = iff(not(condition4[1]),minList(low,mtf4l[1]),low);
mtf4o = iff(condition4[1],open,mtf4o[1]);
mtf4c = close;

mtf4pvt = (mtf4h+mtf4l+mtf4c) / 3;
diff4 = mtf4c - mtf4pvt;


Condition10 = diff0 > 0;
Condition11 = diff1 > 0;
Condition12 = diff2 > 0;
Condition13 = diff3 > 0;
Condition14 = diff4 > 0;

If condition10 then setPlotColor(1,Green) else SetPlotColor(1,Red);
If condition11 then setPlotColor(2,Green) else SetPlotColor(2,Red);
If condition12 then setPlotColor(3,Green) else SetPlotColor(3,Red);
If condition13 then setPlotColor(4,Green) else SetPlotColor(4,Red);
If condition14 then setPlotColor(5,Green) else SetPlotColor(5,Red);

condition6 = condition10 and condition11 and condition12 and condition13 and condition14;
Condition7 = not(condition10) and not(condition11) and not(condition12) and not(condition13) and not(condition14);

If condition6 then setPlotColor(7,Green);
If condition7 then setPlotColor(7,Red);

If condition6 or condition7 then plot7(7,"trend");

Plot6(5,"line");
Plot1(4,"t1");
Plot2(3,"t2");
Plot3(2,"t3");
Plot4(1,"t4");
Plot5(0,"t5");

end;
Multi-Time Frame with Discrete Time Frames

Using a Dictionary to Create a Trading System

Dictionary Recap

Last month’s post on using the elcollections dictionary was a little thin so I wanted to elaborate on it and also develop a trading system around the best patterns that are stored in the dictionary.  The concept of the dictionary exists in most programming languages and almost all the time uses the (key)–>value model.  Just like a regular dictionary a word or a key has a unique definition or value.  In the last post, we stored the cumulative 3-day rate of return in keys that looked like “+ + – –” or “+ – – +“.  We will build off this and create a trading system that finds the best pattern historically based on average return.  Since its rather difficult to store serial data in a Dictionary I chose to use Wilder’s smoothing average function.

Ideally, I Would Have Liked to Use a Nested Dictionary

Initially, I played around with the idea of the pattern key pointing to another dictionary that contained not only the cumulative return but also the frequency that each pattern hit up.  A dictionary is designed to have  unique key–> to one value paradigm.  Remember the keys are strings.  I wanted to have unique key–> to multiple values. And you can do this but it’s rather complicated.  If someone wants to do this and share, that would be great.  AndroidMarvin has written an excellent manual on OOEL and it can be found on the TradeStation forums.  

Ended Up Using A Dictionary With 2*Keys Plus an Array

So I didn’t want to take the time to figure out the nested dictionary approach or a vector of dictionaries – it gets deep quick.  So following the dictionary paradigm I came up with the idea that words have synonyms and those definitions are related to the original word.  So in addition to having keys like “+ + – -” or “- – + -” I added keys like “0”, “1” or “15”.  For every  + or – key string there exists a parallel key like “0” or “15”.  Here is what it looks like:

–  –  –  –  = “0”
– – – + = “1”
– – + – = “2”

You can probably see the pattern here.  Every “+” represents a 1 and every “0” represent 0 in a binary-based numbering system.  In the + or – key I store the last value of Wilders average and in the numeric string equivalent, I store the frequency of the pattern.

Converting String Keys to Numbers [Back and Forth]

To use this pattern mapping I had to be able to convert the “++–” to a number and then to a string.  I used the numeric string representation as a dictionary key and the number as an index into an array that store the pattern frequency.  Here is the method I used for this conversion.  Remember a method is just a function local to the analysis technique it is written.

//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;
String Pattern to Number

This is a simple method that parses the string from left to right and if there is a “+” it is raised to the power(2,idx) where idx is the location of “+” in the string.  So “+  +  –  –  ” turns out to be 8 + 4 + 0 + 0 or 12.

Once I retrieve the number I used it to index into my array and increment the frequency count by one.  And then store the frequency count in the correct slot in the dictionary.

patternNumber = convertPatternString2Num(patternString); 
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
Store Value In Array and Dictionary

Calculating Wilder’s Average Return and Storing in Dictionary

Once I have stored an instance of each pattern [16] and the frequency of each pattern[16] I calculate the average return of each pattern and store that in the dictionary as well.

//Calculate the percentage change after the displaced pattern hits
Value1 = (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
// print("Initiating: ",patternDict[patternString] astype double);
end;
(pAvg * (N-1) + return) / N

When you extract a value from a collection you must us an identifier to expresses its data type or you will get an error message : patternDict[patternString] holds a double value {a real number}  as well as patternDict[patternStringNum] – so I have to use the keyword asType.  Once I do my calculation I ram the new value right back into the dictionary in the exact same slot.  If the pattern string is not in the dictionary (first time), then the Else statement inserts the initial three-day rate of return.

Sort Through All of The Patterns and Find the Best!

The values in a dictionary are stored in alphabetic order and the string patterns are arranged in the first 16 keys.  So I loop through those first sixteen keys and extract the highest return value as the “best pattern.”

//  get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
// print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
Extract Best Pattern From All History

If Today’s Pattern Matches the Best Then Take the Trade

// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Does Today Match the Best Pattern?

If today matches the best pattern then buy and cover after the second day.

Conclusion

I didn’t know if this code was worth proffering up but I decided to posit it because it contained a plethora of programming concepts: dictionary, method, string manipulation, and array.  I am sure there is a much better way to write this code but at least this gets the point across.

Contents of Dictionary at End of Run

++++    0.06
+++- -0.08
++-+ 0.12
++-- -0.18
+-++ 0.08
+-+- 0.40
+--+ -0.46
+--- 0.34
-+++ 0.20
-++- 0.10
-+-+ 0.23
-+-- 0.31
--++ 0.02
--+- 0.07
---+ 0.22
---- 0.46
0.00 103.00
1.00 128.00
10.00 167.00
11.00 182.00
12.00 146.00
13.00 168.00
14.00 163.00
15.00 212.00
2.00 157.00
3.00 133.00
4.00 143.00
5.00 181.00
6.00 151.00
7.00 163.00
8.00 128.00
9.00 161.00
Contents of Dictionary

Example of Trades

Pattern Dictionary System

 

Code in Universum

//Dictionary based trading sytem
//Store pattern return
//Store pattern frequency
// by George Pruitt
Using elsystem.collections;

vars: string keystring("");
vars: dictionary patternDict(NULL),vector index(null), vector values(null);
array: patternCountArray[100](0);

input: patternTests(8);

var: patternTest(""),tempString(""),patternString(""),patternStringNum("");
var: patternNumber(0);
var: iCnt(0),jCnt(0);
//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;


once begin
clearprintlog;
patternDict = new dictionary;
index = new vector;
values = new vector;
end;

//Convert 4 day pattern displaced by 2 days
patternString = "";
for iCnt = 5 downto 2
begin
if(close[iCnt]> close[iCnt+1]) then
begin
patternString = patternString + "+";
end
else
begin
patternString = patternString + "-";
end;
end;

//What is the current 4 day pattern
vars: currPattString("");
currPattString = "";

for iCnt = 3 downto 0
begin
if(close[iCnt]> close[iCnt+1]) then
begin
currPattString = currPattString + "+";
end
else
begin
currPattString = currPattString + "-";
end;
end;

//Get displaced pattern number
patternNumber = convertPatternString2Num(patternString);
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
//Calculate the percentage change after the displaced pattern hits
Value1 = (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
// print("Initiating: ",patternDict[patternString] astype double);
end;
// get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
// print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Pattern Dictionary Part II

 

 

 

Using A Dictionary to Store Chart Patterns in EasyLanguage

Dictionary – Another Cool Collection Object

The dictionary object in EasyLanguage works just like a real dictionary.  It stores values that referenced by a key.  In a real-life dictionary, the keys would be words and the values would be the definitions of those words.

An Introduction

This little bit of code just barely skims the surface of the dictionary object, but it gives enough to get a nice introduction to such a powerful tool.  I am piggybacking off of my Pattern Smasher code here, so you might recognize some of it.

Object Delcaration

Like any of the objects in EasyLanguage a dictionary must be declared initially.

Using elsystem.collections; 
vars: dictionary patternDict(NULL),vector index(null), vector values(null);
input: patternTests(8);
var: patternTest(""),tempString(""),patternString("");
var: iCnt(0),jCnt(0);

once begin
clearprintlog;
patternDict = new dictionary;
index = new vector;
values = new vector;
end;
Declaring Objects

Here I tell the editor that I am going to be using the elsystem.collections and then a declare/define a dictionary named patterDict and two vectors:  index and values.  In the Once block, I create instances of the three objects.  This is boilerplate stuff for object instantiation.

 

for iCnt = 5 downto 2
begin
if(close[iCnt]> close[iCnt+1]) then
begin
patternString = patternString + "+";
end
else
begin
patternString = patternString + "-";
end;
end;

If patternString = "+++-" then Value99 = value99 + (c - c[2])/c[2];

if patternDict.Contains(patternString) then
Begin
// print("Found pattern: ",patternString," 3-day return is: ", (c - c[2])/c[2]);
patternDict[patternString] = patternDict[patternString] astype double + (c - c[2])/c[2];
end
Else
patternDict[patternString] = (c - c[2])/c[2];
Build the Pattern String and Then Store It

 

The keys that index into the dictionary are strings.  In this very simple example, I want to examine all of the different combinations of the last four-bar closing prices.   Once the pattern hits up I want to accumulate the percentage change over the past three days and store that value in the location pointed to by the patternString key.

Notice how I displace the loop by three days (5-2 insteat of 3-0)?  I do this so I can compare the close at the end of the pattern with today’s close, hence gathering the percentage change.  Also, notice that I test to make sure there is an entry in the dictionary with the specific key string.  If there wasn’t already an entry with the key and I tried to reference the value I would get an error message – “unable to cast null object.”

Once I store the keys and values I can regurgitate the entire dictionary very simply.  The keys and values are stored as vectors.  I can simply assign these components of the dictionary to the two vectors I instantiated earlier.

If lastBarOnChart and patternDict.Count > 0 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
For iCnt = 0 to patternDict.Count-1
Begin
print(index[iCnt] astype string," ",values[iCnt] astype double);
end;
print("Value99 : ",value99:8:4);
end;
Printing Out the Dictionary

And then I can simply index into the vectors to print out their contents.  I will add some more commentary on this post a little later this week.  I hope you find this useful.  And remember this will not work with MultiCharts.

Multi-Time Frame – Using Built-in Indicators and Multi Data Charts

A reader of this blog wanted to be able to use different time frames and some built-in indicators and output the information in a similar fashion as I did in the original MTF post.  There are numerous ways to program this but the two easiest are to use data structures such as arrays or vectors or use TradeStation’s own multi data inputs.  The more complicated of the two would be to use arrays and stay compliant with Multicharts.  Or in that same vein use vectors and not stay compliant with Multicharts.  I chose, for this post, the down and dirty yet compliant method.  [NOTE HERE! When I started this post I didn’t realize it was going to take the turn I ended up with.  Read thoroughly before playing around with the code to see that it is what you are really, really looking for.]  I created a multi data chart with five-time frames: 5,10,15,30 and 60 minutes.  I then hid data2 thru data5.  I created an MTF indicator that plots the relationship of the five time frames applied to the ADX indicator with length 14.  If the ADX > 20 then the plot will be green else it will be red.  If all plots align, then the composite plot will reflect the alignment color.

Using the MTF indicator with ADX
{EasyLanguage MultiTime Frame Indicator)
written by George Pruitt - copyright 2019 by George Pruitt
}


Inputs:adxLen(14),adxTrendVall(20);

vars: adxData1(0),adxData2(0),adxData3(0),adxData4(0),adxData5(0);


If barNumber > 1 then
Begin

adxData1 = adx(adxLen) of data1;
adxData2 = adx(adxLen) of data2;
adxData3 = adx(adxLen) of data3;
adxData4 = adx(adxLen) of data4;
adxData5 = adx(adxLen) of data5;

Condition10 = adxData1 > adxTrendVall;
Condition11 = adxData2 > adxTrendVall;
Condition12 = adxData3 > adxTrendVall;
Condition13 = adxData4 > adxTrendVall;
Condition14 = adxData5 > adxTrendVall;

If condition10 then setPlotColor(1,Green) else SetPlotColor(1,Red);
If condition11 then setPlotColor(2,Green) else SetPlotColor(2,Red);
If condition12 then setPlotColor(3,Green) else SetPlotColor(3,Red);
If condition13 then setPlotColor(4,Green) else SetPlotColor(4,Red);
If condition14 then setPlotColor(5,Green) else SetPlotColor(5,Red);

condition6 = condition10 and condition11 and condition12 and condition13 and condition14;
Condition7 = not(condition10) and not(condition11) and not(condition12) and not(condition13) and not(condition14);

If condition6 then setPlotColor(7,Green);
If condition7 then setPlotColor(7,Red);

If condition6 or condition7 then plot7(7,"trend");

Plot6(5,"line");
Plot1(4,"t1");
Plot2(3,"t2");
Plot3(2,"t3");
Plot4(1,"t4");
Plot5(0,"t5");

end;
MTF with 5 data streams and ADX

This code is very similar to the original MTF indicator, but here I simply pass a pointer to the different time frames to the ADX function.  Since the ADX function only requires a length input I had assumed I could use the following format to get the result for each individual time frame:

adxData1 = adx(14) of data1;

adxData2 = adx(14) of data2;

This assumption worked out.

But are we really getting what we really, really want?  I might be putting too much thought into this but of the five-time frame indicator dots, only the 5-minute will change on a 5-minute basis.  The 10-min dot will stay the same for two 5-min bars.  The dots will reflect the closing of the PRIOR time frame and the current 5-min bar is ignored in the calculation.  This may be what you want, I will leave that up to you.  Here is an illustration of the delay in the different time frames.

So when you look at each dot color remember to say to yourself – this is the result of the prior respective time frame’s closing price.  You can say to yourself, “Okay this is the ADX of the current 5-minute bar and this is the ADX of the prior 10-minute close and this is the ADX of the prior 15 minutes close and so on and so on.   We all know that the last 5 minutes will change all of the time frames closing tick, but it may or may not change the price extremes of those larger time frames.   I will show you how to do this in the next post.   If you want to see the impact of the last 5- minutes, then you must build your bars internally and dynamically.

 

Calculating Position Size with Optimal F

I had a reader of the blog ask how to use Optimal F.  That was really a great question.  A few posts back I provided the OptimalFGeo function but didn’t demonstrate on how to use it for allocation purposes.  In this post, I will do just that.

I Have Optimal F – Now What?

From Ralph Vince’s book, “Portfolio Management Formulas”, he states: “Once the highest f is found, it can readily be turned into a dollar amount by dividing the biggest loss by the negative optimal f.  For example, if our biggest loss is $100 and our optimal f is 0.25, then -$100/ 0.25 = $400.  In other words, we should bet 1 unit for every $400 we have in our stake.”

Convert Optimal F to dollars and then to number of shares

In my example strategy, I start out with an initial capital of $50,000 and allow reinvestment of profit or loss.  The protective stop is set as 3 X ATR(10).  A fixed $2000 profit objective is also utilized.  The conversion form Optimal F to position size is illustrated by the following lines of code:

//keep track of biggest loss
biggestLoss = minList(positionProfit(1),biggestLoss);
//calculate the Optimal F with last 10 trades.
OptF = OptimalFGeo(10);
//reinvest profit or loss
risk$ = initCapital$ + netProfit;
//convert Optimal F to $$$
if OptF <> 0 then numShares = risk$ / (biggestLoss / (-1*OptF));
Code snippet - Optimal F to Position Size
  1. Keep track of biggest loss
  2. Calculate optimal F with OptimalFGeo function – minimum 10 trades
  3. Calculate Risk$ by adding InitCapital to current NetProfit (Easylanguage keyword)
  4. Calculate position size by dividing Risk$  by the quotient of biggest loss and (-1) Optimal F

I applied the Optimal F position sizing to a simple mean reversion algorithm where you buy on a break out in the direction of the 50-day moving average after a lower low occurs.

Code listing:

vars: numShares(0),initCapital$(50000),biggestLoss(0),OptF(0),risk$(0);


//keep track of biggest loss
biggestLoss = minList(positionProfit(1),biggestLoss);
//calculate the Optimal F with last 10 trades.
OptF = OptimalFGeo(10);
//reinvest profit or loss
risk$ = initCapital$ + netProfit;
//convert Optimal F to $$$
if OptF <> 0 then numShares = risk$ / (biggestLoss / (-1*OptF));
numShares = maxList(1,numShares);
//if Optf <> 0 then print(d," ",t," ",risk$ / (biggestLoss / (-1*OptF))," ",biggestLoss," ",optF);

if c > average(c,50) and low < low[1] then Buy numShares shares next bar at open + .25* range stop;

setStopPosition;
setProfitTarget(2000);

setStopLoss(3*avgTrueRange(10)*bigPointValue);
Strategy Using Optimal F

I have included the results below.  At one time during the testing the number of contracts jumped up to 23.  That is 23 mini Nasdaq futures ($20 * 7,300) * 23.  That’s a lot of leverage and risk.  Optimal doesn’t  always mean the best risk mitigation.  Please let me know if you find any errors in the code or in the logic.

 

Here is the ELD that incorporates the Strategy and the Function.USINGOPTIMALF