Category Archives: Uncategorized

A Tribute to Murray and His Inter-Market Research

Murray Ruggiero’s Inter-Market Research

Well it’s been a year, this month, that Murray passed away.  I was fortunate to work with him on many of his projects and learned quite a bit about inter-market convergence and divergence.  Honestly, I wasn’t that into it, but you couldn’t argue with his results.  A strategy that he developed in the 1990s that compared the Bond market with silver really did stand the test of time.  He monitored this relationship over the years and watched in wane.  Murray replaced silver with $UTY.

The PHLX Utility Sector Index (UTY) is a market capitalization-weighted index composed of geographically diverse public utility stocks.

He wrote an article for EasyLanguage Mastery by Jeff Swanson where he discussed this relationship and the development of inter-market strategies and through statistical analysis proved that these relationships added real value.

I am currently writing Advanced Topics, the final book in my Easing Into EasyLanguage trilogy, and have been working with Murray’s research.  I am fortunate to have a complete collection of his Futures Magazine articles from the mid 1990s to the mid 2000s.  There is a quite a bit of inter-market stuff in his articles.  I wanted, as a tribute and to proffer up some neat code, to show the performance and code of his Bond and $UTY inter-market algorithm.

Here is a version that he published a few years ago updated through June 30, 2022 – no commission/slippage.

Murray’s Bond and $UTY inter-market Strategy

Not a bad equity curve.  To be fair to Murray he did notice the connection between $UTY and the bonds was changing over the past couple of year.  And this simple stop and reverse system doesn’t  have a protective stop.   But it wouldn’t look much different with one, because the system looks at momentum of the primary  data and momentum of the secondary data and if they are in synch (either positively or negatively correlated – selected by the algo) an order is fired off.  If you simply just add a protective stop, and the momentum of the data are in synch, the strategy will just re-enter on the next bar.  However, the equity curve just made a new high  recently.  It has got on the wrong side of the Fed raising rates.  One could argue that this invisible hand has toppled the apple cart and this inter-market relationship has been rendered meaningless.

Murray had evolved his inter-market analysis to include state transitions.  He not only looked at the current momentum, but also at where the momentum had been.  He assigned the transitions of the momentum for the primary and secondary markets a value from one to four and he felt this state transition helped overcome some of the coupling/decoupling of the inter-market relationship.

However,  I wanted to test Murray’s simple strategy with a fixed $ stop and force the primary market to move from positive to negative or negative to positive territory while the secondary market is in the correct relationship.  Here is an updated equity curve.

George’s Adaptation and using a $4500 stop loss

This equity curve was developed  by using a $4500 stop loss.  Because I changed the order triggers, I reoptimized the length of the momentum calculations for the primary and secondary markets.  This curve is only better in the category of maximum draw down.  Shouldn’t we give Murray a chance and reoptimize his momentum length calculations too!  You bet.

Murray Length Optimizations

These metrics were sorted by Max Intraday Draw down.  The numbers did improve, but look at the Max Losing Trade value.  Murray’s later technology,  his State Systems, were a great improvement over this basic system.  Here is my optimization using a slightly different entry technique and a $4500 protective stop.

Standing on the Shoulders of a Giant

This system, using Murray’s overall research, achieved a better Max Draw Down and a much better Max Losing Trade.   Here is my code using the template that Murray provided in his articles in Futures Magazine and EasyLanguage Mastery.

 

// Code by Murray Ruggiero
// adapted by George Pruitt

Inputs: InterSet(2),LSB(0),Type(1),LenTr(4),LenInt(4),Relate(0);
Vars: MarkInd(0),InterInd(0);

If Type=0 Then
Begin
InterInd=Close of Data(InterSet)-CLose[LenInt] of Data(InterSet);
MarkInd=CLose-CLose[LenTr];
end;

If Type=1 Then
Begin
InterInd=Close of Data(InterSet)-Average(CLose of Data(InterSet),LenInt);
MarkInd=CLose-Average(CLose,LenTr);
end;

if Relate=1 then
begin
If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy("GO--Long") Next Bar at open;
If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short("GO--Shrt") Next Bar at open;

end;
if Relate=0 then begin
If InterInd<0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy Next Bar at open;
If InterInd>0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short Next Bar at open;
end;

Here the user can actually include more than two data streams on the chart.  The InterSet input allows the user to choose or optimize the secondary market data stream.  Momentum is defined by two types:

  • Type 0:  Intermarket or secondary momentum simply calculated by close of data(2) – close[LenInt] of date(2) and primary momentum calculated by close – close[LenTr]
  • Type 1:   Intermarket or secondary momentum  calculated by close of data(2) – average( close of data2, LenInt)  and primary momentum calculated by close – average(close, LenTr)

The user can also input what type of Relationship: 1 for positive correlation and 0 for negative correlation.  This template can be used to dig deeper into other market relationships.

George’s Modification

I simply forced the primary market to CROSS below/above 0 to initiate a new trade as long the secondary market was pointing in the right direction.

	If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then 
Buy("GO--Long") Next Bar at open;
If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short("GO--Shrt") Next Bar at open;
Using the keyword CROSSES

This was a one STATE transition and also allowed a protective stop to be used without the strategy automatically re-entering the trade in the same direction.

Thank You Murray – we sure do miss you!

Murray loved to share his research and would want us to carry on with it.  I will write one or two blogs a year in tribute to Murray and his invaluable research.

Super Trend Indicator in EasyLanguage

SuperTrend Indicator – What Is It?

SuperTrend is a trading strategy and indicator all built into one entity.  There are a couple of versions floating around out there.  MultiCharts and Sierra Chart both have slightly different flavors of this combo approach.

Ratcheting Trailing Stop Paradigm

This indic/strat falls into this category of algorithm.  The indicator never moves away from your current position like a parabolic stop or chandelier exit.  I used the code that was disclosed on Futures.io or formerly known as BigMikesTrading blog.   This version differs from the original SuperTrend which used average true range.  I like Big Mike’s version so it will discussed here.

Big Mike’s Math

The math for this indicator utilizes volatility in the terms of the distance the market has travelled over the past N days.  This is determined by calculating the highest high of the last N days/bars and then subtracting the lowest low of last N days/bars.   Let’s call this the highLowRange.  The next calculation is an exponential moving average of the highLowRange.  This value will define the market volatility.   Exponential moving averages of the last strength days/bars highs and lows are then calculated and divided by two – giving a midpoint.  The volatility measure (multiplied my mult) is then added to this midpoint to calculate an upper band.  A lower band is formed by subtracting the volatility measure X mult from the midpoint.

Upper or Lower Channel?

If the closing price penetrates the upper channel and the close is also above the highest high of strength days/bars back (offset by one of course) then the trend will flip to UP.  When the trend is UP,  then the Lower Channel is plotted.  Once the trend flips to DN, the upper channel will be plotted.  If the trend is UP the lower channel will either rise with the market or stay put.  The same goes for a DN trend – hence the ratcheting.  Here is a graphic of the indicator on CL.

Super Trend by Bike Mike

If you plan on using an customized indicator in a strategy it is always best to build the calculations inside a function.  The function then can be used in either an indicator or a strategy.

Function Name: SuperTrend_BM

Function Type: Series – we will need to access prior variable values

SuperTrend_BM Function Code:

//SuperTrend from Big Mike now futures.io

inputs:
length(NumericSimple), mult(NumericSimple), strength(NumericSimple), STrend(NumericRef);

vars:
highLowRange(0),
xAvgRng(0),
xAvg(0),
dn(0),
up(0),
trend(1),
trendDN(False),
trendUP(False),
ST(0);

highLowRange = Highest(high, length) - Lowest(low, length);

xAvgRng = XAverage(highLowRange, length);

xAvg = (XAverage(high, Strength) + XAverage(low, Strength))/2;

up = xAvg + mult * xAvgRng;
dn = xAvg - mult * xAvgRng;

if c > up[1] and c > Highest(High, strength)[1] then
trend = 1
else
if c < dn[1] and c < Lowest(Low, Strength)[1] then
trend = -1;

//did trend flip?
trendDN = False;
trendUP = False;

if trend < 0 and trend[1] > 0 then
trendDN = True;
if trend > 0 and trend[1] < 0 then
trendUP = True;

//ratcheting mechanism
if trend > 0 then dn = maxList(dn,dn[1]);
if trend < 0 then up = minList(up,up[1]);

// if trend dir. changes then assign
// up and down appropriately
if trendUP then
up = xAvg + mult * xAvgRng;
if trendDN then
dn = xAvg - mult * xAvgRng;

if trend = 1 then
ST = dn
else
ST = up;

STrend = trend;

SuperTrend_BM = ST;
SuperTrend ala Big Mike

The Inputs to the Function

The original SuperTrend did include the Strength input.  This input is a Donchian like signal.  Not only does the price need to close above/below the upper/lower channel but also the close must be above/below the appropriate Donchian Channels to flip the trend,  Also notice we are using a numericRef as the type for STrend.  This is done because we need the function to return two values:  trend direction and the upper or lower channel value.  The appropriate channel value is assigned to the function name and STrend contains the Trend Direction.

A Function Driver in the Form of an Indicator

A function is a sub-program and must be called to be utilized.   Here is the indicator code that will plot the values of the function using: length(9), mult(1), strength(9).

// SuperTrend indicator
// March 25 2010
// Big Mike https://www.bigmiketrading.com
inputs:
length(9), mult(1), strength(9);

vars:
strend(0),
st(0);

st = SuperTrend_BM(length, mult,strength,strend);

if strend = 1 then Plot1(st,"SuperTrendUP");
if strend = -1 then Plot2(st,"SuperTrendDN");
Function Drive in the form of an Indicator

 

This should be a fun indicator to play with in the development of a trend following approach.   My version of Big Mike’s code is a little different as I wanted the variable names to be a little more descriptive.

Update Feb 28 2022

I forgot to mention that you will need to make sure your plot lines don’t automatically connect.

Plot Style Setting

Can You Do This with Just One Plot1?

An astute reader brought it to my attention that we could get away with a single plot and he was right.  The reason I initially used two plot was to enable the user to chose his/her own plot colors by using the Format dialog.

//if strend = 1 then Plot1(st,"SuperTrendUP");
//if strend = -1 then Plot2(st,"SuperTrendDN");

if strend = 1 then SetPlotColor(1,red);
if strend = -1 then SetPlotColor(1,green);

Plot1(st,"SuperTrend_BM");
Method to just use one Plot1

Tracking Last EntryPrice While Pyramiding on Minute Bars

EasyLanguage’s EntryPrice Doesn’t Cut the Mustard

In writing the Hi-Res edition of Easing Into EasyLanguage I should have included this sample program.  I do point out the limitations of the EntryPrice keyword/function in the book.  But recently I was tasked to create a pyramiding scheme template that used minute bars and would initiate a position with N Shares and then pyramid up to three times by adding on N Shares at the last entry price + one 10 -Day ATR measure as the market moves in favor of the original position.  Here is an example of just such a trade.

Pyramid 3 Times After Initial Trade Entry. Where’s the EntryPrice?

EntryPrice only contains the original entry price.  So every time you add on a position, the EntryPrice doesn’t reflect this add on price.  I would like to be able to index into this keyword/function and extract any EntryPrice.  If you enter at the market, then you can keep track of entry prices because a market order is usually issued from an if-then construct:

//Here I can keep track of entry prices because I know
//exactly when and where they occur.

if c > c[1] and value1 > value2 then
begin
buy("MarketOrder") next bar at market;
lastEntryPrice = open of next bar;
end;
Last Entry Price tracking is easy if using Market Orders

But what if you are using a stop or limit order.  You don’t know ahead of time where one of these types of orders will hit up.  It could be the next bar or it could be five bars later or who knows.

AvgEntryPrice Makes Up for the Weakness of EntryPrice

AvgEntryPrice is a keyword/function that  returns the average of the entries when pyramiding.  Assume you buy at 42.00 and pyramid the same number of shares at 46.50 – AvgEntryPrice will be equal to (42.00 + 46.50) / 2 = 44.25.  With this information you can determine the two entry prices.  You already know the original price.  Take a look at this code.

// remember currentShares and avgEntryPrice ARE EasyLanguage Keywords/Functions
if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",totShorts," ",avgEntryPrice," ",entryPriceSums);
end;
end;
Calculating the true LastEntryPrice

Remember currentShares is a keyword/function and it is immediately updated when more shares are added or taken off.  CurShares is my own variable where I keep track of the prior  currentShares , so if currentShares (real number of shares) is greater than the prior curShares (currentShares) then I know 100%, a position has been pyramided as long the the mp stays the same.  If currentShares increases and mp stays constant, then you can figure out the last entry price where the pyramid takes place.  First you tick totShorts up by 1.  If currentShares > initShares, then you know you are pyramiding so

lastEntryPrice = totShorts * avgEntryPrice – entryPriceSums

Don’t believe me.  Let’s test it.  Remember original entry was 42.00 and the add on was at 46.50.  TotShorts now equals 2.

  1. Initial entryPrice = 42.00 so entryPriceSums is set to 42.00
  2. After pyramiding avgEntryPrice is set to 44.25
  3. lastEntryPrice = 2 * 44.25 – 42.00 = 46.50
  4. entryPriceSums is then set to 42.00 + 46.50 or 88.50

So every time you add on a position, then you flow through this logic and you can keep track of the actual last entry price even if it is via a limit or stop order.

But wait there is more.  This post is also a small glimpse into what I will be writing about in the Easing Into EasyLanguage:  Advanced Topics.  This system definitely falls into what I discussed in the Hi-Res Edition.  Here is where we tip over into Advanced Topics.  The next book is not about creating dialogs or trading apps using OOEL (object oriented EasyLanguage), but we do use some of those topics to do some rather complicated back testing things.

Now that we know how to calculate the lastEntryPrice wouldn’t it be really cool if we could keep track of all of the entryPrices during the pyramid stream.   If I have pyramided four times, I would like to know entryPrice 1, entryPrice 2, entryPrice 3 and entryPrice 4.

EntryPrice Vector

Dr. VectorLove or How I Learned to Stop Worrying and Love Objects

I have discussed vectors before but I really wanted to discuss them more.  Remember Vectors are just lists or arrays that don’t need all the maintenance.  Yes you have to create them which can be a pain, but once you learn and forget it twenty times it starts to sink in.  Or just keep referring back to this web page.


Using elsystem.collections;

vars: Vector entryPriceVector(Null);

once Begin
entryPriceVector = new Vector;
end;
The Bare Minimum to Instantiate a Vector
  1. Type – “Using elsystem.collections; “
  2. Declare entryPriceVector as a Vector and set it equal to Null
  3. Use Once and instantiate entryPriceVector by using the keyword new < object type>;

A Vector is part of elsystem’s collection objects.  Take a look at this updated code,

if mp[1] = mp and mp = -1 and currentShares > curShares then
begin
totShorts = totShorts + 1;
if currentShares > initShares then
begin
lastEntryPrice = totShorts * avgEntryPrice - entryPriceSums;
entryPriceVector.push_back(lastEntryPrice);
entryPriceSums = entryPriceSums + lastEntryPrice;
print(d," Short addon ",lastEntryPrice," ",entryPrice," ",entryPrice(1)," ",totShorts," ",avgEntryPrice," ",entryPriceSums," ",entryPriceVector.back() astype double," ",entryPriceVector.count asType int);
if not(entryPriceVector.empty()) then
begin
for m = 0 to entryPriceVector.count-1
begin
print(entryPriceVector.at(m) astype double);
end;
end;
end;
end;
LastEntryPrice and Pushing It onto the Vector and Then Printing Out the Vector

After the lastEntryPrice is calculated it is pushed onto the entryPriceVector using the function (method same thing but it is attached to the Vector class).push_back(lastEntryPrice);

entryPriceVector.push_back(lastEntryPrice);

So every time a new lastEntryPrice is calculated it is pushed onto the Vector at the back end.  Now if the entryPriceVector is not empty then we can print its contents by looping and indexing into the Vector.

if not(entryPriceVector.empty()) then
begin
     for m = 0 to entryPriceVector.count-1
     begin
          print(entryPriceVector.at(m) astype double);
     end;
end;
Looping through a Vector and Printing Out its Contents

Remember if you NOT a boolean value then it turns it to off/on or just the opposite of the boolean valueIf entryPriceVector is not empty then proceed.  entryPriceVector.count holds the number of values stuffed into the vectorYou can index into the Vector by using .at(m),  If you want to print out the value of the Vector .at(m), then you will need to typecast the Vector object as what ever it is holding.  We know we are pushing numbers with decimals (double type) onto the Vector so we know we can evaluate them as a double type.  Just remember you have to do this when printing out the values of the Vector.

Okay you can see where we moved into an Advanced Topics area with this code.  But it really becomes useful when trying to overcome some limitations of EasyLanguage.  Remember keep an eye open for Advanced Topics sometime in the Spring.

Easing Into EasyLanguage: Hi-Res Edition Now Available

Hi-Res Is Now Available

Easing Into EasyLanguage : The Hi-Res Edition

The Hi-Res Edition of Easing Into EasyLanguage

This is my second book in the Easing Into EasyLanguage [EZNGN2EZLANG] series of books.  Here are the table of contents.

Contents

  •  Introduction
  • About Website Computer Code and Fonts In Print Version
  • Using EasyLanguage to Program on Minute Intervals?
  • Tutorial 14 – Why Do I Need to Use Intraday Data
  • Tutorial 15 – An Algorithm Template that Uses Minute Bars to Trade a Daily Bar Scheme
  • Tutorial 16 – Using Data2 as a Daily Bar
  • Tutorial 17 – Let’s Day Trade!
  • Tutorial 18 – Moving From Discrete Day-Trade Strategy to a Framework
  • Tutorial 19 – Day-Trading Continued: Volatility Based Open Range Break Out with Pattern Recognition
  • Tutorial 20 – Pyramiding with Camarilla
  • Tutorial 21 – Programming a Scale Out Scheme
  • Tutorial 22- Crawling Like A Bug on a Five Minute Chart
  • Tutorial 23 – Templates For Further Research
  • Appendix A-Source Code
  • Appendix B-Links to Video Instruction

I have included five hours of video instruction which is included via links in the book and in the supplemental resource download.

What’s In This Book

If you are not a Trend Follower, then in most cases, you will not be able to properly or accurately code and backtest your trading algorithm without the use of higher resolution  data  (minute bars).  A very large portion of the consulting I have done over the years has  dealt with converting a daily bar system to one that uses intraday data such as a 5-minute bar.  Coding a daily bar system is much more simple than taking the same concept and adding it to a higher resolution (Hi-Res) chart.  If you use a 100 day moving average and you apply it to a 5-minute chart you get a 100 five minute bar moving average – a big difference.

Why Do I Need To Use Hi-Res Data?

If all you need to do is calculate a single entry or exit on a daily basis and can manually execute the trades, then you can stick with daily bars.  Many of the famous Trend-Following systems such as Turtle, Aberration,  Aberration Plus,  Andromeda,  and many others fall into this category.  Most CTAs use these types of systems and spend most of their efforts on accurate execution and portfolio management.   These systems, until the genesis of the COVID pandemic, have struggled for many years.  Some of the biggest and brightest futures fund managers had to shut their doors due to their lagging performance and elevated levels of risk in comparison to the stock market.  However, if you need to know the ebb and flow of the intraday market movement to determine accurate trade entry, then intraday data is an absolute necessity.   Also, if you want to automate, Hi-Res data will help too!   Here is an example of a strategy that would need to know what occurs first in chronological order.

Example of a Simple  Algorithm that Needs Intraday Data

If the market closes above the prior day’s close, then  buy the open of the next day plus 20% of today’s range and sellShort the open of the next day minus 40% of today’s range.  Use a protective stop of $500 and a profit objective of $750.  If the market closes below the prior day’s close then sellShort the open of the next day minus 20% of today’s range and buy the open of the next day plus 40% of todays range.  The same trade management of profit and loss is applied as well.  From the low resolution of a daily bar the computer cannot determine if the market moves up 20% or down 40% first.  So the computer cannot accurately determine if a long or short is established first.  And to add insult to injury, if the computer could determine the initial position accurately from a daily bar, it still couldn’t determine if the position is liquidated via a profit or a loss if both conditions could have occurred.

What About “Look Inside Bar”?

There is evidence that if the bar closes near the high and the open near the low of a daily bar, then there is a higher probability that the low was made first.  And the opposite is true as well.  If the market opens near the middle of the bar, then all bets are off.  When real money is in play you can’t count on this type of probability or the lack thereof .  TradeStation allows you to use your daily bar scheme and then Look Inside Bar to see the overall ebb and flow of the intraday movement.  This function allows you to drill down to one minute bars, if you like.  This helps a lot, but it still doesn’t allow you to make intraday decisions, because you are making trading decisions from the close of the prior day.

if c > c[1] then 
begin
buy next day at open of next day + 0.2 * range stop;
sellShort next day at open of next day - 0.4 * range stop;
end;

setProfitTarget(750);
setStopLoss(500);
Next Day Order Placement

Using setProfitTarget and setStopLoss helps increase testing accuracy, but shouldn’t you really test on a 5-minute bar just to be on the safe side.

DayTrading in Most Cases Needs Hi-Res Data

If I say buy tomorrow at open of next day and use a setStopLoss(500), then I don’t need Hi-Res data.  I execute the open which is the first time stamp in the chronological order of the day.  Getting stopped out will happen later and any adverse move from the open that  equates to $500 will liquidate the position or the position will be liquidated at the end of the day.

However, if I say buy the high of the first 30 minutes and use the low of the first 30 minutes as my stop loss and take profits if the position is profitable an hour later or at $750, then intraday data is absolute necessity.  Most day trading systems need to react to what the market offers up and only slightly relies on longer term daily bar indicators.

If Intraday Data is So Important then Why ” The Foundation Edition?”

You must learn to crawl before you can walk.  And many traders don’t care about the intraday action – all they care about is where the market closed and how much money should be allocated to a given trade or position.  Or how an open position needs to be managed.  The concepts and constructs of EasyLanguage must be learned first from a daily bar framework before a new EL programmer can understand how to use that knowledge on a five minute bar.  You cannot just jump into a five minute bar framework and start programming accurately unless you are a programmer from the start or you have a sound Foundation in EasyLanguage.

Excerpt from Hi-Res Edition

From Tutorial 21 – Put 2 Units on, Take Profit on 1 Unit, Pull Stop to Break Even on 2nd Unit

Here is an example of a simple and very popular day trading scheme.  Buy 2 units on a break out and take profits on 1 unit at X dollars.  Pull stop on 2nd unit to breakeven to provide a free trade.  Take profit on 2nd unit or get out at the end of the day.

Conceptually this is easy to see on the chart and to understand.  But programming this is not so easy.  The code and video for this algorithm is  from Tutorial 21 in the Hi-Res edition.

Here are the results of the algorithm on a 5 minute ES.D chart going back five years.  Remember these results are the result of data mining.  Make sure you understand the limitations of back-testing.  You can read those here.

No Execution Costs Included! Please read backtesting disclaimer.

There are a total of 10 Tutorials and over 5 hours of Video Instruction included.  If you want to expand your programming capabilities to include intraday algorithm development, including day trading, then get your copy today.

 

Updated Code That Works With Midnight Time Stamp

Updated Code for the Midnight Hour

UPDATE: October 12, 2023.  I found an error in the code.  I will comment it out and show you the correction.   Copy and paste can get you into trouble.

I was working with some code for my latest book – Easing Into EasyLanguage – The Hi-Res Edition and streamlined some code from an old post.

startTime = sessionStartTime(0,1); 
//endTime = sessionStartTime(0,1); WRONG!
endTime = sessionEndTime(0,1);

if startTime > endTime then
begin
endTimeOffset = 0;
if t >= startTime+barInterval and t<= 2359 then endTimeOffSet = 2400-endTime;
end;

if t-endTimeOffSet < endTime then
begin
...
...
...
...
end.
Updated Code That Works with 0000 Time Stamp
24 Hour Session

Now you can carve out times to trade that bridge the midnight hour.  You just need to use the above code for when the your StartTime is greater than your EndTime.

So if you want to trade from 20:00 to 05:00 (8 PM to 5 AM) then just use this code and it will work every time.

I wanted to make sure I did a post for November to keep my record alive and to let you know I am wrapping up the Hi-Res edition and will be on the bookshelves before Christmas – I hope.

 

 

Passing and Accessing Multidimensional Array in a Function

Before the days of OOEL and more advanced data structures, such as vectors, you had to work with multidimensional arrays.

The problem with arrays is you have to do all the housekeeping whereas with vectors the housekeeping is handled internally.  Yes, vectors in many cases would be the most efficient approach, but if you are already using Multi-D arrays, then mixing the two could become confusing.  So stick with the arrays for now and progress into vectors at your leisure.

Recreate the CCI indicator with Multi-D Array

This exercise is for demonstration purposes only as the existing CCI function works just fine.  However, when you are trying out something new  or in this case an application of a different data structure (array) its always great to check your results against a known entity.  If your program replicates the known entity, then you know that you are close to a solution.  The CCI function accesses data via the global High, Low and Close data streams and then applies a mathematical formula to derive a result. <

Derive Your Function First

Create the function first by prototyping what the function will need in the formal parameter list (funciton header).   The first thing the function will need is the data – here is what it will look like.

  • OHLCArray[1,1] =  1210903.00 // DATE
  • OHLCArray[1,2] =    4420.25 // OPEN
  • OHLCArray[1,3] =    4490.25 // HIGH
  • OHLCArray[1,4] =    4410.25 // LOW
  • OHLCArray[1,5] =    4480.75 // CLOSE
  • OHLCArray[2,1] =  1210904.00 // DATE
  • OHLCArray[2,2] =    4470.25 // OPEN
  • OHLCArray[2,3] =    4490.25 // HIGH
  • OHLCArray[2,4] =    4420.25 // LOW
  • OHLCArray[2,5] =    4440.75 // CLOSE

Visualize 2-D Array as a Table

Column 1 Column 2 Column 3 Column 4 Column 5
1210903 44202.25 4490.25 4410.25 4480.75
1210904 4470.25 4490.25 4420.25 4440.76
The CCI function is only concerned with H, L, C and that data is in columns 3, 4, 5.  If you know the structure of the array before you program the function, then you now which columns or fields you will need to access.  If you don’t know the structure beforehand , then that information would need to be passed into the function as well.   Let us assume we know the structure.  Part of the housekeeping that I mentioned earlier was keeping track of the current row where the latest data is being stored.  This “index” plus the length of the CCI indicator is the last two things we will need to know to do a proper calculation.

CCI_2D Function Formal Parameter List

// This function needs data, current data row, and length
// Notice how I declare the OHLCArray using the dummy X and Y
// Variable - this just tells TradeStation to expect 2-D array
// ------------------
// | |
// * *
inputs: OHLCArray[x,y](numericArray), currentRow(numericSimple), length(numericSimple);
// ***
// |||
//----------------------------
// Also notice I tell TradeStation that the array is of type numeric
// We are not changing the array but if we were, then the type would be
// numericArrayRef - the actual location in memory not just a copy
CCI_2D Formal Parameter List

2-D Array Must Run Parallels with Actual Data

The rest of the function expects the data to be just like the H, L, C built-in data – so there cannot be gaps.  This is very important when you pack the data and  you will see this in the function driver code a.k.a an indicator. The data needs to align with the bars.  Now if you are using large arrays this can slow things down a bit.  You can also shuffle the array and keep the array size to a minimum and I will post how to do this in a post later this week.  The CCI doesn’t care about the order of the H,L,C as long as the last N element is the latest values.

variables: 	
Mean( 0 ),sum1(0),sum2(0),
AvgDev( 0 ),rowNum(0),
Counter( 0 ) ;


AvgDev = 0 ;
if currentRow > length then // make sure enough rows
begin

sum1 = 0;
sum2 = 0;
for rowNum = currentRow - (length-1) to currentRow
begin
value1 = OHLCArray[rowNum,3];
value2 = OHLCArray[rowNum,4];
value3 = OHLCArray[rowNum,5];
sum1 = sum1 + value1 + value2 + value3;
end;
//Mean = Average( H + L + C, Length ) ; { don't have to divide H+L+C by 3, cancels out }
Mean = sum1/length;
print(d," Mean ",mean," ",mean/3);

for rowNum = currentRow - (length-1) to currentRow
begin
value1 = OHLCArray[rowNum,3];
value2 = OHLCArray[rowNum,4];
value3 = OHLCArray[rowNum,5];
sum2 = sum2 + AbsValue((value1 + value2 + value3) - Mean);
end ;
// AvgDev = AvgDev + AbsValue( ( H + L + C )[Counter] - Mean ) ;
AvgDev = sum2 / Length ;
print(d," avgDev ",AvgDev," ",AvgDev/3);

value1 = OHLCArray[currentRow,3];
value2 = OHLCArray[currentRow,4];
value3 = OHLCArray[currentRow,5];
end;

if AvgDev = 0 then
CCI_2D = 0
else
CCI_2D = ( value1 + value2 + value3 - Mean ) / ( .015 * AvgDev ) ;
CCI-2D Function
This function could be streamlined, but I wanted to show you how to access the different data values with the currentRow variable and columns 3, 4, and 5.  I extract these data and store them in Values variables.  Notice the highlighted line where I check to make sure there are enough rows to handle the calculation.  If you try to access data before row #1, then you will get an out of bounds error and a halt to program execution.

Function Driver in the form of an Indicator

array: OHLCArray[5000,5](0);
Inputs: CCI2DLen(14),CCILen(14);

vars: numRows(0),myCCI(0),regCCI(0);

numRows = numRows + 1;
OHLCArray[numRows,1] = d;
OHLCArray[numRows,2] = o;
OHLCArray[numRows,3] = h;
OHLCArray[numRows,4] = l;
OHLCArray[numRows,5] = c;

myCCI = CCI_2D(OHLCArray,numRows,14);
regCCI = CCI(14);

plot1(myCCI," CCI_2D ");
plot2(regCCI," CCI ");
CCI-2D Indicator

Notice lines 16 and 17 where I am plotting both function results – my CCI_2D and CCI.   Also notice how I increment numRows on each bar – this is the housekeeping that keeps that array synched with the chart.  In the following graphic I use 14 for CCI_2D and 9 for the built-in CCI.

Two CCI functions with different Lengths

Now the following graphic uses the same length parameters for both functions.  Why did just one line show up?

Both CCI Functions with same Lengths – were did second line go to?

Make Your Unique Coding Replicate a Known Entity – If You Can

 

Here is where your programming is graded.  The replication of the CCI using a 2-D Array instead of the built-in H, L, C data streams, if programmed correctly, should create the exact same results and it does, hence the one line.  Big Deal right!  Why did I go through all this to do something that was already done?  Great programming is not supposed to re-invent the wheel.  And we just did exactly that.  But read between the lines here.   We validated code that packed a 2-D array with data and then passed it to a function that then accessed the data correctly and applied a known formula and compared it to a known entity.  So now you have re-usable code for passing a 2-D array to a function.  All you have to do is use the template and modify the calculations.  Re-inventing the wheel is A-Okay if you are using it as a tool for validation.

The Foundation Edition – First Book In Easing Into EasyLanguage

Hello to All!  I just published the first book in this series.  It is the Foundation Edition and is designed for the new user of EasyLanguage or for those you would like to have a refresher course.  There are 13 total 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.  Each video is created by yours truly and Beau my trustworthy canine companion.  I go over every line of code to really bring home the concepts that are laid out in each tutorial.  All source code is available too, and if you have TradeStation, so are the workspaces.  Plus you can always email George for any questions.  george.p.pruitt@gmail.com.

The Cover of my latest book. The first in the series.

If you like the information on my blog, but find the programming code a little daunting, then go back and build a solid foundation with the Foundation Edition.  It starts easy but moves up the Learning Curve at comfortable pace.  On sale now for $24.95 at Amazon.com.  I am planning on having two more advanced books in the series.  The second book, specifically designed for intraday trading and day-trading, will be available this winter.  And the third book, Advanced Topics, will be available next spring.

Pick up your copy today – e-Book or Paperback format!

Here is the link to buy the book now!

Let me know if you buy either format  and I will send you a PDF of the source code – just need proof of purchase.  With the  PDF you can copy and paste the code.  After you buy the book come back here to the Easing Into EasyLanguage Page and download  the ELD and workspaces.

If You Can’t Go Forward, Then Go Backward [Back To The Future]

Calculate MAE/MFE 30 Bars after A Signal

A very astute reader of this blog brought a snippet of code that looks like EasyLanguage and sort of behaves like it, but not exactly.  This code was presented on the exceptional blog of Quant Trader posted by Kahler Philipp.  He used some of the ideas from  Dave Bergstrom.

Equilla Programming Language

The theory behind the code is quite interesting and I haven’t gotten into it thoroughly, but will do so in the next few days.  The code was derived from Trade-Signal’s Equilla Programming Language.  I looked at the website and it seems to leans heavily on an EasyLanguage like syntax, but unlike EZLang allows you to incorporate indicators right in the Strategy.  It also allows you, and I might be wrong, to move forward in time from a point in the past quite easily.  The code basically was fed a signal (+1,0,-1) and based on this value progressively moved forward one bar at a time  (over a certain time period) and calculated the MAE and MFE (max. adverse/favorable excursion for each bar.  The cumulative MAE/MFE were then stored in a BIN for each bar.  At the end of the data, a chart of the ratio between the MAE and MFE was plotted.

EasyLanguage Version

I tried to replicate the code to the best of my ability by going back in time and recording a trading signal and then moving Back to The Future thirty bars, in this case, to calculated and store the MAE/MFE in the BINS.

Simple Moving Average Cross Over Test

After 100 bars, I looked back 30 bars to determine if the price was either greater than or less than the 21 day moving average.   Let’s assume the close was greater than the 21 day moving average 30 days ago, I then kept going backward until this was not the case.  In other words I found the bar that crossed the moving average.  It could have been 5 or 18 or whatever bars further back.  I stored that close and then started moving forward calculating the MAE/MFE by keeping track of the Highest Close and Lowest Close made during 30 bar holding period.  You will see the calculation in the code.  Every time I got a signal I accumulated the results of the calculations for each bar in the walk forward period.  At the end of the chart or test I divided each bars MFE by its MAE and plotted the results.  A table was also created in the Print Log.  This code is barely beta, so let me know if you see any apparent errors in logic or calculations.


inputs: ilb(30); //ilb - initial lookback
vars: lb(0),signal(0),btf(0),mf(0),ma(0),hh(0),ll(99999999),arrCnt(0),numSigs(0);
arrays : mfe[40](0),mae[40](0);
lb = ilb;
if barNumber > 100 then
begin
signal = iff(c[ilb] > average(c[ilb],21),1,-1);
// print(d," signal ",signal," ",ilb);
if signal <> signal[1] then
begin
numSigs = numSigs + 1; // keep track of number of signals
// print("Inside loop ", date[ilb]," ",c[ilb]," ",average(c[ilb],21));
if signal = 1 then // loop further back to get cross over
begin
// print("Inside signal = 1 ",date[lb]," ",c[lb]," ",average(c[lb],21));
while c[lb] > average(c[lb],21)
begin
lb = lb + 1;
end;
// print("lb = ",lb);
end;

if signal = -1 then // loop further back to get cross over
begin
// print("Inside signal = -1 ",date[lb]," ",c[lb]," ",average(c[lb],21));
while c[lb] < average(c[lb],21)
begin
lb = lb + 1;
end;
end;
lb = lb - 1;

hh = 0;
ll = 999999999;

arrCnt = 0;
for btf = lb downto (lb - ilb) //btf BACK TO FUTURE INDEX
begin
mf=0;
ma=0;
hh=maxList(c[btf],hh);
// print("inside inner loop ",btf," hh ",hh," **arrCnt ",arrCnt);
ll=minList(c[btf],ll);
if signal>0 then
begin
mf=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // mf long signal
ma=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // ma long signal
end;
if signal<0 then begin
ma=iff(hh>c[lb],(hh-c[lb])/c[lb],0); // ma after short signal
mf=iff(ll<c[lb],(c[lb]-ll)/c[lb],0); // mf after short signal
end;
// print(btf," signal ",signal," mf ",mf:0:5," ma ",ma:0:5," hh ",hh," ll ",ll," close[lb] ",c[lb]);
mfe[arrCnt]=mfe[arrCnt]+absValue(signal)*mf;
mae[arrCnt]=mae[arrCnt]+absValue(signal)*ma;
arrCnt = arrCnt + 1;
end;
end;
end;

if lastBarOnChart then
begin
print(" ** MFE / MAE ** ");
for arrCnt = 1 to 30
begin
print("Bar # ",arrCnt:1:0," mfe / mae ",(mfe[arrCnt]/mae[arrCnt]):0:5);
end;

for arrCnt = 30 downto 1
begin
plot1[arrCnt](mfe[31-arrCnt]/mae[31-arrCnt]," mfe/mae ");
end;
end;
Back to The Future - going backward then forward

Here is an output at the end of a test on Crude Oil

 ** MFE / MAE ** 
Bar # 1 mfe / mae 0.79828
Bar # 2 mfe / mae 0.81267
Bar # 3 mfe / mae 0.82771
Bar # 4 mfe / mae 0.86606
Bar # 5 mfe / mae 0.87927
Bar # 6 mfe / mae 0.90274
Bar # 7 mfe / mae 0.93169
Bar # 8 mfe / mae 0.97254
Bar # 9 mfe / mae 1.01002
Bar # 10 mfe / mae 1.03290
Bar # 11 mfe / mae 1.01329
Bar # 12 mfe / mae 1.01195
Bar # 13 mfe / mae 0.99963
Bar # 14 mfe / mae 1.01301
Bar # 15 mfe / mae 1.00513
Bar # 16 mfe / mae 1.00576
Bar # 17 mfe / mae 1.00814
Bar # 18 mfe / mae 1.00958
Bar # 19 mfe / mae 1.02738
Bar # 20 mfe / mae 1.01948
Bar # 21 mfe / mae 1.01208
Bar # 22 mfe / mae 1.02229
Bar # 23 mfe / mae 1.02481
Bar # 24 mfe / mae 1.00820
Bar # 25 mfe / mae 1.00119
Bar # 26 mfe / mae 0.99822
Bar # 27 mfe / mae 1.01343
Bar # 28 mfe / mae 1.00919
Bar # 29 mfe / mae 0.99960
Bar # 30 mfe / mae 0.99915
Ratio Values over 30 Bins

Using Arrays for Bins

When  newcomers  start to program EasyLanguage and encounter arrays it sometimes scares them away.  They are really easy and in many cases necessary to complete a project.  In this code I used two 40 element or bins arrays MFE and MAE.  I only use the first 30 of the bins to store my information.  You can change this to 30 if you like, and when you start using a fixed array it is best to define them with the exact number you need, so that TradeStation will tell you if you step out of bounds (assign value to a bin outside the length of the array).  To learn more about arrays just search my blog.  The cool thing about arrays is  you control what data goes in and what you do with that data afterwards.  Anyways play with the code, and I will be back with a more thorough explanation of the theory behind it.

 

 

 

 

 

Murray Ruggiero

Goodbye my old friend!

I first spoke to Murray in 1989 when he worked with Promise Land Technologies – an AI company that improved trading signals and I worked at Futures Truth.  He went from there to form his own companies and become an editor of Futures Magazine.  He developed one of the best back testing platforms available today – TraderStudio.  His dream was to compete with TradeStation and in his last days he saw a beta version of his software – 64 bit – and real time that could run his concepts of a trading session and a trading plan.  The session was simply a singular algorithm whereas the plan was an overlay that could manage multiple sessions and utilize complex money management schemes.  All this while collecting real time minute data.  So congratulations my friend – you damn well did it!

I-Master

Murray co-developed this phenomena that caught the attention of almost all Futures Brokers in the late 90s and early 00s.  When this system waded into the market you could see the wave it created.  It became over traded but boy did it have a run.

Intermarket Convergence/Divergence

This concept did not catch on until Murray started focusing on it.  He turned it into an art form and most of his focus was spent on uncovering the relationships between different markets and different derivatives.  I can say that he become the leading expert in this field.

Futures Magazine

If you can get your hands on his collection of articles, I would definitely advise doing so.  He touched on so many topics and explained them thoroughly.  Futures was fortunate to have him onboard.

Family

He was always talking about his family and how much he cared for them.  Murray was a workaholic – no doubt, but he was always there whenever they needed him.

Friends

I can’t list them all.  He knew everybody.  All the legends and all of them recognized him for his intelligence and innate market sense.

Legacy

Murray will be missed for being a good man – in every possible way.  That is truly the best compliment I can pay his memory.   His ideas will live on for sure, but we will all miss out on the great ideas he was yet to dream up.

Murray – thank you!

 

 

Converting Method() To Function – MultiCharts

MultiCharts Doesn’t Support Methods

Methods are wonderful tools that are just like functions, but you can put them right into your Analysis Technique and they can share the variables that are defined outside the Method.  Here is an example that I have posted previously.  Note:  This was in response to a question I got on Jeff Swanson’s EasyLanguage Mastery Facebook Group.

{'('  Expected line 10, column 12  }
//the t in tradeProfit. // var: double tradeProfit;

vars: mp(0);
array: weekArray[5](0);



method void dayOfWeekAnalysis() {method definition}
var: double tradeProfit;
begin
If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit;
end;

Buy next bar at highest(high,9)[1] stop;
Sellshort next bar at lowest(low,9)[1] stop;

mp = marketPosition;
if mp <> mp[1] then dayOfWeekAnalysis();
If lastBarOnChart then
Begin
print("Monday ",weekArray[1]);
print("Tuesday ",weekArray[2]);
print("Wednesday ",weekArray[3]);
print("Thursday ",weekArray[4]);
print("Friday ",weekArray[5]);
end;
PowerEditor Cannot Handle Method Syntax

Convert Method to External Function

Sounds easy enough – just remove Method and copy code and put into a new function.  This method keeps track of Day Of Week Analysis.  So what is the function going to return?  It needs to return the performance metrics for Monday, Tuesday, Wednesday, Thursday and Friday.  That is five values so you can’t simply  assign the Function Name a single value – right?

Create A New Function – Call It DayOfWeekAnalysis

inputs: weekArray[n](numericArrayRef);

vars: mp(0);
var: tradeProfit(0);
mp = marketPosition;

tradeProfit = -999999999;
If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
if tradeProfit <> -999999999 then
weekArray[dayOfWeek(entryDate(1))] = weekArray[dayOfWeek(entryDate(1))] + tradeProfit;
print(d," ",mp," ",mp[1]," ",dayOfWeek(entryDate(1)),tradeProfit," ",entryDate," ",entryDate(1)," ",entryPrice(0)," ",entryPrice(1));

DayOfWeekAnalysis = 1;
Simple Function - What's the Big Deal

Looks pretty simple and straight forward.  Take a look at the first line of code.  Notice how I inform the function to expect an array of [n] length to passed to it.  Also notice I am not passing by value but by reference.  Value versus reference – huge difference.  Value is a scalar value such as 5, True or a string.  When you pass by reference you are actually passing a pointer to actual location in computer memory – once you change it – it stays changed and that is what we want to do.  When you pass a variable to an indicator function you are simple passing a value that is not modified within the body of the function.  If you want a function to modify and return more than one value you can pass the variable and catch it as a numericRef.  TradeStation has a great explanation of multiple output functions.

Multiple Output Function per EasyLanguage

Some built-in functions need to return more than a single value and do this by using one or more output parameters within the parameter list.  Built-in multiple output functions typically preface the parameter name with an ‘o’ to indicate that it is an output parameter used to return a value.  These are also known as ‘input-output’ parameters because they are declared within a function as a ‘ref’ type of  input (i.e. NumericRef, TrueFalseRef, etc.) which allows it output a value, by reference, to a variable in the EasyLanguage code calling the function.

I personally don’t follow the “O” prefacing, but if it helps you program then go for it.

Series Function – What Is It And Why Do I Need to Worry About It?

A series function is a specialized function that refers to a previous function value within its calculations.  In addition, series functions update their value on every bar even if the function call is placed within a conditional structure that may not be true on a given bar.  Because a series function automatically stores its own previous values and executes on every bar, it allows you to write function calculations that may be more streamlined than if you had to manage all of the resources yourself.  However, it’s a good idea to understand how this might affect the performance of your EasyLanguage code.

Seems complicated, but it really isn’t.  It all boils down to SCOPE – not the mouthwash.  See when you call a function all the variables inside that function are local to that particular function – in other words it doesn’t have a memory.  If it changes a value in the first call to the function, it has amnesia so the next time you call the function it forgets what it did just prior – unless its a series function.  Then it remembers.  This is why I can do this:

 	If mp = 1 and mp[1] = -1 then tradeProfit = (entryPrice(1) - entryPrice(0))*bigPointValue;
If mp = -1 and mp[1] = 1 then tradeProfit = (entryPrice(0) - entryPrice(1))*bigPointValue;
I Can Refer to Prior Values - It Has A Memory

Did you notice TradeProfit = -99999999 and then if it changes then I accumulate it in the correct Day Bin.  If I didn’t check for this then the values in the Day Bin would be accumulated with the values returned by EntryPrice and ExitPrice functions.  Remember this function is called on every bar even if you don’t call it.  I could have tested if a trade occurred and passed this information to the function and then have the function access the EntryPrice and ExitPrice values.  This is up to your individual taste of style.  One more parameter for readability, or one less parameter for perhaps efficiency?

This Is A Special Function – Array Manipulator and Series Type

When you program a function like this the EasyLanguage Dev. Environment can determine what type of function you are using.  But if you need to change it you can.  Simply right click inside the editor and select Properites.

Function Properties – AutoDetect Selected

How Do You Call Such a “Special”  Function?

The first thing you need to do is declare the array that you will be passing to the function.  Use the keyword Array and put the number of elements it will hold and then declare the values of each element.  Here I create a 5 element array and assign each element zero.  Here is the function wrapper.

array: weekArray[5](0);
vars: mp(0),newTrade(false);

Buy next bar at highest(high,9)[1] stop;
Sellshort next bar at lowest(low,9)[1] stop;
mp = marketPosition;
newTrade = False;
//if mp <> mp[1] then newTrade = true;

value1 = dayOfWeekAnalysis(weekArray);
If lastBarOnChart then
Begin
print("Monday ",weekArray[1]);
print("Tuesday ",weekArray[2]);
print("Wednesday ",weekArray[3]);
print("Thursday ",weekArray[4]);
print("Friday ",weekArray[5]);
end;
Wrapper Function - Notice I only Pass the Array to the Function

Okay that’s how you convert a Method from EasyLanguage into a Function.  Functions are more re-uasable, but methods are easier.  But if you can’t use a method you now know how to convert one that uses Array Manipulation and us a “Series” type.