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 not 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
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.
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.
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.
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 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.
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;
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.
A good portion of my readers use MultiCharts and the similarities between their PowerLanguage and EasyLanguage is almost indistinguishable. However, I came across a situation where one my clients was getting different values between an indicator function call and the actual plotted indicator when using Multi-Data.
Here is the code that didn’t seem to work, even though it was programmed correctly in TradeStation.
Value1 = DirMovement( H, L, C , Data1ADXLen, oDMIPlus1, oDMIMinus1, oDMI1, oADX1, oADXR1, oVolty1 ) ; Value2 = DirMovement( H of data2, L of data2, C of data2, Data2ADXLen, oDMIPlus2, oDMIMinus2, oDMI2, oADX2, oADXR2, oVolty2 );
Pretty simple – so what is the problem. Data aliasing was utilized in the Vars: section – this keeps the indicator from being calculated on the time frame of data1. Its only calculated on the data2 time frame – think of data1 being a 5 min. chart and data2 a 30 min. chart. I discovered that you have to also add data aliasing to not just the variables used in the indicator function but also to the function call itself. This line of code fixed the problem:
DirMovement( H of data2, L of data2, C of data2, Value2, oDMIPlus2, oDMIMinus2, oDMI2, oADX2, oADXR2, oVolty2 )data2;
Add data2 after the function call to tie it to data2.
See that! Just add Data2 to the end of the function call. This verifies in TradeStation and compiles in MC with no problems.
Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!
Get All Five Books in the Easing Into EasyLanguage Series - The Trend Following Edition is now Available!
Announcement – A Trend Following edition has been added to my Easing into EasyLanguage Series! This edition will be the fifth and final installment and will utilize concepts discussed in the Foundation editions. I will pay respect to the legends of Trend Following by replicating the essence of their algorithms. Learn about the most prominent form of algorithmic trading. But get geared up for it by reading the first four editions in the series now. Get your favorite QUANT the books they need!
The Foundation Edition. The first in the series.
This series includes five editions that covers the full spectrum of the EasyLanguage programming language. Fully compliant with TradeStation and mostly compliant with MultiCharts. Start out with the Foundation Edition. It is designed for the new user of EasyLanguage or for those you would like to have a refresher course. There are 13 tutorials ranging from creating Strategies to PaintBars. Learn how to create your own functions or apply stops and profit objectives. Ever wanted to know how to find an inside day that is also a Narrow Range 7 (NR7?) Now you can, and the best part is you get over 4 HOURS OF VIDEO INSTRUCTION – one for each tutorial.
Hi-Res Edition Cover
This book is ideal for those who have completed the Foundation Edition or have some experience with EasyLanguage, especially if you’re ready to take your programming skills to the next level. The Hi-Res Edition is designed for programmers who want to build intraday trading systems, incorporating trade management techniques like profit targets and stop losses. This edition bridges the gap between daily and intraday bar programming, making it easier to handle challenges like tracking the sequence of high and low prices within the trading day. Plus, enjoy 5 hours of video instruction to guide you through each tutorial.
Advanced Topics Cover
The Advanced Topics Edition delves into essential programming concepts within EasyLanguage, offering a focused approach to complex topics. This book covers arrays and fixed-length buffers, including methods for element management, extraction, and sorting. Explore finite state machines using the switch-case construct, text graphic manipulation to retrieve precise X and Y coordinates, and gain insights into seasonality with the Ruggiero/Barna Universal Seasonal and Sheldon Knight Seasonal methods. Additionally, learn to build EasyLanguage projects, integrate fundamental data like Commitment of Traders, and create multi-timeframe indicators for comprehensive analysis.
Get Day Trading Edition Today!
The Day Trading Edition complements the other books in the series, diving into the popular approach of day trading, where overnight risk is avoided (though daytime risk still applies!). Programming on high-resolution data, such as five- or one-minute bars, can be challenging, and this book provides guidance without claiming to be a “Holy Grail.” It’s not for ultra-high-frequency trading but rather for those interested in techniques like volatility-based breakouts, pyramiding, scaling out, and zone-based trading. Ideal for readers of the Foundation and Hi-Res editions or those with EasyLanguage experience, this book offers insights into algorithms that shaped the day trading industry.
Trend Following Cover.
For thirty-one years as the Director of Research at Futures Truth Magazine, I had the privilege of collaborating with renowned experts in technical analysis, including Fitschen, Stuckey, Ruggiero, Fox, and Waite. I gained invaluable insights as I watched their trend-following methods reach impressive peaks, face sharp declines, and ultimately rebound. From late 2014 to early 2020, I witnessed a dramatic downturn across the trend-following industry. Iconic systems like Aberration, CatScan, Andromeda, and Super Turtle—once thriving on robust trends of the 1990s through early 2010s—began to falter long before the pandemic. Since 2020 we have seen the familiar trends return. Get six hours of video instruction with this edition.
Pick up your copies today – e-Book or paperback format – at Amazon.com