Ask Mr. EasyLanguage: A Study in Price Action

By Samuel K. Tennis aka “Mr. EasyLanguage”

There was a price pattern (pivot formation) made rather famous by Kent Calhoun a decade or two ago called the 5VBTP (Five Vertical Bar Trading Pattern). As he explains, he did not create it, he just named it and defined some rules. Mr. Pat Raffalovich and myself have each worked, jointly and separately, with Mr. Calhoun over the years. For this example of coding a Price Action SetUp and Trigger I am going to borrow just a portion of what I learned from Mr. Calhoun.

The basic pattern we are going to explore consists of a four bar setup and a fifth bar which will either Trigger our entry or cancel the pattern. Hold up your left hand and the four fingers demonstrate the bar pattern. The high of one bar ago is the highest high of the four bars. The fourth bar (the zero or current bar in EasyLanguage) can have a lower low then the previous bar, or be an inside bar, either way.

se_SetUp  = High [01]  > High [00] and  // High of one bar ago is greater than the High of the current bar
            High [01]  > High [02] and  // High of one bar ago is greater than the High of two bars ago
            High [01]  > High [03] ;    // High of one bar ago is greater than the High of three bars ago

The Trigger Price will be the Lowest Low of the two most recent bars, the setup bar and the pivot bar itself, minus zero or more ticks. A tick on EasyLanguage can be referenced using the KeyWork “Point” or “Points” but you will see that I have a “skt_OneTick” User Function which I use primarily to remove the micro pip when on a ForEx chart, so that need not distract you any further at this time.

if  se_SetUp  then  se_Price  = se_Trigger - se_Points ; // Order price is x-ticks below the Lowest Low of the two most recent setup bars

Now, once we have a SetUp we wait for price action to confirm or cancel it. A single tick higher than our pivot high patter and we are off to the races again, looking for a new pattern to form.

The code I am providing is only a portion, as I mentioned, of the whole methodology but this is enough to give us something to work with. The first study, a “proof of concept” is named “Ask Mr. EZL, Price Action #1”. On my workspace I applied the study to both Data1 (Daily) and Data2 (Weekly), as a test, and if you try this you will discover that TradeStation has an error in it’s display when you offset Data2 back a bar as I do to mark the SetUp Bar to mark the Pivot Bar. It Paints one daily bar ago, instead of one weekly bar ago. Oops! So I just hide Data2 usually.

In the study I am painting the SetUp Bar (Plot 1 & 2), there are Color Inputs provided, marking the entry price with a small cross (Plots 3 & 4)and plotting a large point (dot) when a fill occurs (Plots 5 & 6). That just happened to tbe the order I applied the plots as I developed and tested the code.

Once I had everything debugged and validated for accuracy I saved the Study as “Ask Mr. EZL, Price Action #2”, created two User Functions and removed all the now unnecessary declarations and code. The reason for the User Function is two fold. First, by putting all the logic possible in the function(s) I only have one place to make adjustments instead of having to change the Study and the Strategy. The second, and most important reason for this example, is so I can say

le_SetUp_d2  = MrEZL_PriceAction_LE (le_Ticks, le_Price_d2, ShowCmtry) of Data2 ;

and by adding just those few extra characters get a second time frame for analysis! We really do not care much, at this time, about the Price value for Data2, just about the SetUp, though the price will tell us if it is cancelled, but our Data1 / Daily should be cancelled LONG before the Data2 / Weekly can!

This is not intended to be a profitable strategy but a demonstration of SetUp and Trigger using Price Action. I write EasyLanguage code while Murray develops profitable trading systems!

To begin exploring this powerful concept, please request this free code using the form to the right.

Channel Breakout TradeStation Code

Let’s consider multi-timeframe analysis within TradeStation:

Inputs: LELen(20),SELen(20),LXLen(20),SXLen(20);
Vars: HighLE(0,data2);
HighLE=Highest(High of data2,LELen) of data2+Minmove;
LowSE=Lowest(Low of data2,SELen) of data2-minmove;
HighSX=Highest(High of data2,SXLen) of data2+minmove;
LowLX=Lowest(Low of data2,LXLen) of data2-minmove;
If High>=HighLE then Buy next bar at market;
If Low<=LowSE then Sell short next bar at market;
If High>=HighSX then Buy to cover next bar at market;
If Low<=LowLX then Sell next bar at market;

This is a simple channel breakout which gets in using market orders on intra-day bars. We use daily bars on data 2. We want to make sure that our variables which are used to get the highest high and lowest low are tied to roll on a daily timeframe. This requires a two step process. First, we declare the variable as being tied to roll on data2. Second, we not only get the highest high of data2, but we also add the “of data2” outside of the () of the function. This makes the resulting expression roll the same as the timeframe of data 2.

Download the channel breakout code by using the form to the right (make sure and keep the channel breakout checkbox selected). You can import this code and use the 9.1 workspace to see how this concept works.

Free code for the Empirical Mode Decomposition Indicator

We are offering Free code for the Empirical Mode Decomposition Indicator (EMD) free TradeStation code helps identify whether a market is in a cycle or trend mode. This indicator is discussed in the article titled “Empirical Mode Decomposition” in the March 2010 Issue of Stocks and Commodities magazine, by John F. Ehlers and Ric Way. For reference, here is a link to the original article. It is a strongly recommended read for anyone interested in TradeStation indicators.

According to the article, when the Trend Component rises above the Average Peaks, the market is in an uptrend. When it is below the Average Valleys, the market is in a downtrend. Finally, when it’s between the two, the market is in cycle mode.

The EMD indicator has 4 optional components: the Bandpass Filter (or cycle component), the Trend Component, the Average Peaks, and the Average Valleys. The inputs include price, period, delta, and fraction. The price defaults to (High + Low) / 2. The period should reflect the cycle period (or frequency) of the market being studied and defaults to 20 bars. The delta should be set to half the bandwidth with common values of 0.1 to 0.5. The fraction is the fraction of the average peaks and valleys used to display the upper and lower limits for the trend component. This value is subjective and can be adjusted to fit your trading style. For swing trades that prefer to trade in cycle mode, a larger fraction might be used such as 0.25.

It’s worth noting that the code contained within the original article will not compile as-is due to the fact that the names of the variables and inputs are now keywords within TradeStation.

We have created a strategy using this indicator. The rules are listed below:

  1. Go long when the Mean of the Empirical indicator crosses over the upper band (AvgPeak)
  2. Exit long when the Mean crosses down under the upper band
  3. Go short when the Mean crosses under the lower band (AvgValley)
  4. Exit short when the Mean crosses over the lower band

When testing this strategy it seems that for many markets it works better from 2009 forward.

Let’s now look at this system on a very good trending market: crude oil. We will use 12 years of daily data using TradeStation’s continuous contract from July 14, 2003 to July 10, 2015. We will use 25.00 slippage and commission. The strategy (system) is JEhlers_Empirical. Shown below are the parameters we are using for crude oil continuous default contract daily data for 12 years in TradeStation.

J. Ehlers Article 1
Click on the image above to see it in full size.

Let’s now look at the results:

J. Ehlers Article 2
Click on the image above to see it in full size.

The results look good but the drawdown is too big. There is something here though in terms of picking up trend mode and direction. Taking a look at the equity curve, we can see that it does much better after 2008. This is not only true of this system for crude but also other markets like the E-Mini Futures. One question that must be investigated now is why?

J. Ehlers Article 3
Click on the image above to see it in full size.

This system at times has big equity curve givebacks. For example, note the long trade in the center of the chart. It becomes a losing trade but had 10,000 in open equity before it gave it back. We also see that on the short trade we gave back 15,000 off the bottom.

J. Ehlers Article 4
Click on the image above to see it in full size.

If we look at this system results recently, it has been almost perfect. We gave a few dollars back on the last long trade but it was still profitable and we did get out near the bottom on the recent bear market move.

J. Ehlers Article 5
Click on the image above to see it in full size.




Development of Intermarket Trading Systems

In my past article, Intermarket Is Fundamentally Sound, I covered some of the basic premises and history of intermarket trading systems. While the previous entry was more theoretical, this article is more practical. Indeed, I will be discussing how intermarket analysis can be used to generate mechanical signals. I will also walk you through the process I followed in developing and improving my own intermarket analysis mechanical trading methods.

First Generation Intermarket Trading Systems

Let’s begin our study by taking a look at what I call the “first generation” intermarket systems. These basically used intermarket forces as a filter. Our analysis will be done as follows: futures will use one lot and be compared with some market. For example, we will use Treasury bonds and compare utility stocks to the DJ Bond index. Measures like CARG are controlled by account size and sizing. If we are not trading a portfolio then sizing to normalize risk volatility is not needed and it simplifies our results. If we do this analysis on stocks or ETFs as the markets we are trading, then we need to look at these calculations because dollar analysis is meaningless as it depends when gains occur. In futures, it’s always the same dollar value per point, except for major contract changes like 1997 in the S&P500.

Our first generation system is very simple and is as follows:

Sub IntermarketDummy(SLen,Relate)
    Dim IntOsc As BarArray
    IntOsc=Close Of independent1-Average(Close Of independent1,SLen,0)
    If Relate=1 Then
        If IntOsc>0 Then Buy("",1,0,Day,Market)
        If IntOsc<0 Then Sell("",1,0,Day,Market)
    End If
    If Relate<>1 Then
        If IntOsc<0 Then Buy("",1,0,Day,Market)
        If IntOsc>0 Then Sell("",1,0,Day,Market)
    End If
End Sub

If you’re wondering how this trading model code was generated, you’ll be interested to know it’s based upon the free Intermarket Divergence TradeStation Tool. You can download a free copy here.

Let’s now look at our first example. We will use the UTY (Philadelphia electrical utility average) and trade U.S. thirty year treasury bonds (24 hour session, continuous contract). Utility stocks are positively correlated so relate = 1. We will use $50 for slippage and commission, and optimize the moving average lookback value from 2-30 in steps of 1, using the date range 09/22/1987 to 04/10/2015.

First Example Optimization

In our first simple model, we can see that the results are not very good. Only one set of parameters (the top set) made any money on the short side (how do you know this?). In the bond market, due to the strong upward bias, most systems do not make any money on the short side. Does the use of UTY in this way predict bonds? In order to figure out this question, we would need to compare to a standard sample. This will be a simple price crossover system which we will then do a Z-test to see if UTY is predictive. Our standard system which is a bogey test is as follows:

Sub InterBogeyDummy(SLen)
    Dim IntOsc As BarArray
    If IntOsc>0 Then Buy("",1,0,Day,Market)
    If IntOsc<0 Then Sell("",1,0,Day,Market)
End Sub

We will use the same date range. We will also optimize over the same date range and use the same values for the moving average 2-30. Finally, we are also using $50.00 slippage and commission, as we did before.

Standard Results

We can obviously see that using UTY was a big improvement to our results even though the results of the basic intermarket system are not that good. Albeit it’s extremely obvious just by glancing at the two tables that using UTY did certainly help, I will walk through the Z-test to show this fact. Indeed, it is always important to run statistical analyses on your systems to confirm that they are really performing better than we could expect just by chance. We did not run in sample and out of sample tests because our only goal here was to show that UTY was predictive of Treasury bonds.

The Z-Test

The goal of constructing a statistical distribution is to compare some observed phenomena with another observed phenomena, and see if they are the same or different. The Z-test is an easy way to compare two types of distributions and determine, with some quantifiable degree of certainty, that they are different.

The Z-test makes use of one of the fundamental tenants of statistical theory:

The error in the mean is calculated by dividing the dispersion by the square root of the number of data points.

The error in the mean can be thought of as a measure of how reliable a mean value is. The more samples you have the more reliable the mean is. However, this reliability is directly related to the square root of the number of samples that you have. If you wanted to improve the reliability by a factor of 10, for example, you would have to get 100 times the number of samples. This can be difficult to do sometimes!

Comparing two sample means is easy. To find the difference of the two sample means in units of sample mean error, use the following formula:


But for comparing two samples directly, one needs to compute the Z statistic in the following manner:



  • X1 is the mean value of sample one
  • X2 is the mean value of sample two
  • σx1 is the standard deviation of sample one divided by the square root of the number of data points
  • σx2 is the standard deviation of sample two divided by the square root of the number of data points

Here is a specific example of the Z-test application (in very simple, non-trading terms):

Eugene vs. Seattle rainfall comparison over 25 years (so N = number of samples = 25):

Rainfall example

So far this example:

  • X1 = 51.5
  • X2 = 39.5
  • X1 – X2 = 12
  • σx1 = 1.6
  • σx2 = 1.4
  • sqrt of σx12 + σx22 = sqrt(1.62 + 1.42) = sqrt(2.56 + 1.96) = 2.1

Therefore, the Z statistic is 12/2.1 = 6 which means there is a highly significant difference between these two distributions. This means it really does rain significantly more in Eugene than in Seattle.

You can verify these numbers by using the Z-test tool (comparing two means) accessible from the statistical tools area.

Probability	z value	
0.25	        0.7	* this is often used in in power calculations power=0.75, β=0.25
0.2	        0.85	* this is often used in in power calculations power=0.8, β=0.2
0.1	        1.29	
0.05	        1.65	* this is often used for testing statistical significant p<0.05
0.025	        1.96	* this is often used to define the 95% confidence interval (2.5% each side)
0.01	        2.33	
0.005	        2.58	

Standard Distribution

Now that we’ve taken a look at the non-trading example, let’s walk through our trading example that we had earlier. We will look at the net profit column and see if they come from a different distribution.

In a perfect world, we would like to see Z of at least 1.65 but in the trading world with all the noise and small samples, Z values are often not this high. The worst thing we can do is make a type II error.

For reference, a type II error occurs when you accept the null hypothesis when it is false. In this case, it would be concluding that there are no significant differences between the two samples when they actually are different. In trading, this is tantamount to having a statistically good system and throwing it away because you don’t see that due to an error in the calculations!

We will do our calculations as follows. We will optimize across a range of parameters and will drop the lowest 10% and the top 10% rounded up. Let’s consider these to be potential outliers. We will then use the results from above, with 30 combinations for both. We will drop the best two and the worst two for both sets of data.

Our results are as follows:

Average Bogey	              -$60,671.8
Std deviation Bogey	        69072.74
Intermarket Average	       $111,670.8
Intermarket Std deviation	50652.47
Ave Diff	               $172,342.5
sqr of std deviation	        85654.63
Z-test	                        2.012063

This is significant at the 97.8% level. Put another way, we can say with 97.8% certainty that using UTY does help us predict and trade the 30-year bonds.

We also want to see if we have a probability that the system is going to be profitable. The way to do that is to compare the average net profit over the optimization space to the standard deviation of that space. We want a ratio of at least 1.0 for the system to be considered stable with positive expectations over the space. In our case, the ratio is 2.20 which is a good sign!

In our next installment, I will discuss how I developed the intermarket divergence concept.

If you would like more information on the tool I use to create these types of trading models, you can learn more here.

Intermarket Analysis is Fundamentally Sound

Intermarket analysis is a powerful tool that a trader can use to get an edge on the market. This type of analysis can be thought of as a type of instantaneous, fundamental analysis, which if done correctly, is a form of arbitrage. In this series of articles, we will show how and why intermarket analysis is predictive. It has a long history, having been used by traders since the 60s, but it became popular when John Murphy published his first intermarket analysis book entitled “Intermarket Technical Analysis Trading Strategies for the Global Stock, Bond, Commodity, and Currency Markets”.

Basic Premises of Intermarket Work

In this series of articles, I will be using a general framework outline. This will help illustrate the direction in which we’ll be going. I will then outline the specific relationships that will be the focus of these articles. There are an infinite number of relationships that exist between markets, but our discussions will be limited to those that I have found most useful and that I believe carry the most significance. After completion of the overview, we will begin our study of intermarket analysis using the events of 1987 as a case study of these types of relationships.

I’d like to present some general guidelines:

  • All markets are interrelated. This means that no markets ever move in isolation.
  • Intermarket work provides important background data.
  • Intermarket work uses external, as opposed to internal, data.
  • Technical analysis is the preferred vehicle.
  • Intermarket relationships are not only for futures, but also for stocks, ETFs, and various indices or sectors.
  • We will first try to understand the premise behind a relationship. This means viewing it visually on a chart and then developing mechanical signals based on this relationship.

These premises form the basis of intermarket analysis. If it can be shown that all markets – financial ones, non-financial ones, domestic markets, global markets, and so on – are interrelated, and that each one of these components is simply a part of a greater whole, then it becomes clear that focusing one’s attention on only one market leaves a great possibility of missing vital directional clues. Indeed, understanding the sum of the markets is the key to understanding each part of the market. Market analysis, when limited to one market only, often leaves the analyst in doubt. Technical analysis can tell an important story about a common stock or a futures contract. However, these technical readings are uncertain and can generate false positive signals. Understanding the relationship between multiple markets is truly what can provide critical information as to market direction. When in doubt, look to related markets for clues! Stated another way, the secret is to demonstrate that intermarket relationships exist, why they exist, and how they can be incorporated into our technical work to predict future price moments. Our goal is to show how these interrelationships can be thought of as fundamental and really a form of statistical arbitrage.

Intermarket Analysis as Context Clues

Intermarket analysis provides contextual clues about the market we are trading. When we only use technical analytic techniques on a market (think indicators such as RSI, MACD, etc.), we only have that information to use for our trading decisions. The idea of intermarket work is to go beyond this level and judge the market context for this technical analysis.

Concepts are sometimes best illustrated by example. Suppose your research shows that two markets usually trend in opposite directions, such as Treasury bonds and the Commodity Research Bureau Index or Silver. Suppose further that a separate analysis of the top markets provides a bullish outlook for both at the same time. Since those are two conclusions, arrived at through separate analysis techniques, the analyst might wish to go back and re-examine the individual conclusions. Intermarket analysis helps us avoid what might seemingly be good technical analyses on paper, by providing a broader picture of the markets. As we will see later, this will be key to forecasting future trends.

Indeed, there will be times when the usual intermarket relationships aren’t visible or simply are temporarily out of line. How do we resolve these potential conflicts? That is, how do we resolve when intermarket analysis does not match up with technical analysis? There are times when strong trends or true fundamentals in markets exist and these will override the influence of intermarket correlations.

Coming back to our previous example, getting bullish readings for two markets that normally don’t trend together is a sign that one of the markets is giving false readings. Our goal then in intermarket analysis is to find markets which lead the market we are trading. In addition, we need to understand when these relationships temporarily stop working due to strong trends or fundamental analysis.

By doing intermarket analysis, a trader nets two things. First is a warning signal at market turning points and also instantaneous fundamental analysis. Many intermarket relationships are predictive because they are fundamentally linked. One such example is crude oil and oil exploration stocks. Thinking about it logically, if oil exploration stock earnings are expected to outperform, then these stocks will be bullish because oil prices are expected to be higher. In turn, this is bullish for crude oil futures.

In this series of articles, my goal is to show that in general there are predictive intermarket relationships, and also discuss when these might fail. Finally, I’ll be concluding by explaining when intermarket analysis is not reliable because other controlling factors are overpowering.

The Role of the Business Cycle

Understanding the economic rationale that binds commodities, bonds, and the stock market requires some discussion of the business cycle and what happens during periods of expansion and recession. For example, the bond market is considered an excellent leading indicator of the U.S. economy. A rising bond market comes before economic strength. A weak bond market usually provides a leading indication of an economic downturn (although the lead times can be quite long). The stock market benefits from economic expansion and weakens during times of economic recession.

Both bonds and stocks are considered leading indicators of the economy. They usually turn down prior to a recession and bottom out after the economy is well into a recession. However, turns in the bond market usually occur first. Going back through the last 80 years, every major downturn in the stock market has either come after or at the same time as a major downturn in the bond market. During the last six recessions bonds have bottomed out an average of almost four months prior to bottoms in the stock market. During the postwar era stocks have begun to turn down an average of six months prior to the onset of a recession and have begun to turn up about six months prior to the end of a recession.

Tops in the bond market, which usually give earlier warnings of an impending recession, are generally associated with rising commodity markets. Conversely, during a recession falling commodity markets are usually associated with a bottom in the bond market. Therefore, movements in the commodity markets also play an important role in the analysis of bonds and stocks. I made the point about the relationship between bonds and stocks since world war two because all of these tops in bonds were caused by inflation. The problem is when disinflationary forces cause these issues then bonds do not top when the stock market turns down.

Focusing on the Dollar

Discussions so far have turned on the how the commodity markets affect the bond market and how the bond market affects stocks. The activity in the U.S. dollar plays an important role in the intermarket picture as well. Most market participants would agree with the general statement that a rising dollar is bullish for bonds and stocks and that a falling dollar is bearish for bonds and stocks. However, it’s not as simple as that. The U.S. dollar hit a major top in 1985 and dropped all the way to January 1988. For a large part of that time, bonds and stocks rose as the dollar weakened. Clearly, there must be something missing in this analysis.

The impact of the dollar on the bond and the stock markets is not a direct one but an indirect one. The impact of the dollar on bonds and stocks must be understood from the standpoint of the dollar’s impact on inflation, which brings us back to the commodity markets. Commodity prices in dollars are bullish as the dollar falls, so as the dollar fall the US goods are cheaper overseas and that good for US international companies. One big problem in using the dollar to price commodities is that this can sometime hide a bull or bear market because of the strength in trend of the dollar. For example, currently in 2015, gold is in a bull market against world currencies but a bear market against the dollar.

Intermarket Analysis in Action

John Murphy’s books used chart analysis to show the case for intermarket relationships. John used the crash of 1987 to show how all the markets truly are interrelated. This is where my research on intermarket analysis began in 1992. Let’s focus now on some of that 1987 crash analysis.

Market Peaked in August of 1987

We first begin by looking at the correlation of the 30 year Treasury bonds to the S&P500. We can see bonds peaked in February 1987 (the chart on the bottom) and the market peaked in August of 1987 (the top chart). The sell-off in bonds foreshadowed the crash by about six months.

Flight to Safety

Looking at the markets after the crash, we see that bonds begin to rally substantially. This reflects a flight to safety – investors took cash out of equities and stocks and put it in Treasuries. In general, bond prices are positively correlated to the S&P 500 whereas yields are negatively correlated. This has been true since 1971 when the U.S. went completely off the gold standard. When a black swan event occurs (like the crash of 1987), the relationship between bonds and stocks inverts. You can see how the 30 year treasury leads stocks. Now, could we have predicted the move in the thirty year treasury?

Eurodollar Contract Peaked in September of 1986

The answer is quite simple: yes. The Eurodollar contract peaked in September of 1986 while the thirty year Treasury peaked in February of 1987. The Eurodollar is a futures contract that is tied to short term rates (90 days) so we can see the rise in short term rates. This led the collapse of long term rates by about 5-6 months. We now see two interrelated pieces based on intermarket analysis.

Copper Futures During the Period of February to August 1987

This is a chart of Eurodollar futures (the top chart), gold futures (the middle chart), and copper futures (the bottom chart) during the period of February to August 1987. We can see that Eurodollars sold off as gold rallied and also as copper rallied. Gold and copper topped just as Eurodollars bottomed. During the mid-2000s going into the crash of 2008, Eurodollar rates became pinned near zero and this messed up the relationship between Eurodollars and bonds. Thus, we might perceive gold and copper as being correlated to inflation rates – future interest rates based on current inflation plus future perceived inflation plus a risk premium.

Intermarket Relationship Between Eurodollars and Bonds to Break Down

The fact the short term interest rates were pinned at 0 caused the intermarket relationship between Eurodollars and treasury bonds to break down.

Intermarket Relationship Between Eurodollars

We can see how the classic relationship between the S&P500 and Treasury bonds inverted during the financial crisis and for a year or so after.

Intermarket Relationships Between 2007 and 2009

Above, we can see intermarket relationships between 2007 and 2009 for the S&P 500 as the traded market on top. Thirty year Treasury bond futures are the middle chart and the dollar index is the bottom chart. The market peaked in 2007 and bonds were generally flat, but in a very slight uptrend during 2008. During this time the dollar bottomed and then began a strong rally in August 2008. During this time, the stock market entered a normal bear market (down about 20%), and we were in a recession already, but not in a crisis. The dollar rallying during this bear market broke the market completely and the 20% selloff turned into over 50% by the March 2009 bottom. The dollar rallied over 15% in five months and bonds re-entered a bull market rally – over 20% in three months. This was due to the financial crisis and fears of disinflation. A strong dollar can cause disinflation (fewer people can afford U.S. goods and services so prices must adjust downwards) which is dangerous to corporate profits and can cause major bear markets. Disinflation was the main problem during the depression and Japanese crisis over the past 25 years.

We can see that intermarket analysis is a powerful tool. However, relationships are not always perfectly constant and must be taken into context. Now that we have discussed this overview, the next part in this series will show how intermarket analysis can be used to develop actual trading systems (strategies) which are 100% mechanical. We will see both the strength and the weaknesses of these systems even though they are profitable and reliable. This will help us understand how we can use these simple models in context and, combined with other advanced market technologies, we can create a new generation of financial models.

If you would like more information on the tool I use to create these types of trading models, you can learn more here.

Free Code to Fix TradeStation’s 2D Sort

During a recent project, I needed to sort a 2D array so I used the built-in 2D array sort which is included within TradeStation. The documentation for TradeStation’s 2D Sort is as follows:

Sort2DArray(PriceArray, Size1, Size2, HiLo)

At first glance this appeared to be a relatively simple function. The parameters were straightforward as you simply provided PriceArray – the name of the array to sort – the first and second dimension sizes to sort upon (as represented by Size1 and Size2, respectively) and HiLo which is either a 1 to sort descending or a -1 to sort ascending.

Upon using this function, the order of values of the two-dimensional array specified by PriceArray are changed. The function itself returns 1.

To perform a descending sort of a user-declared 2D array, one might do the following:

Array: myArray[30,4](0);
... assign the values to the array ...
Value1 = Sort2DArray(myArray, 30, 4, 1);

I thought this would be easy but it was not. I could not get my code to work, no matter how hard I tried. I discussed this issue with my friend, Sam Tennis (who is also a TradeStation expert available on this site). He confirmed to me that the sort was not working as described. First the array is defined as column then row in the function (that is it references the Y axis before the X axis) not row then column (X, Y) co-ordinate system that is used everywhere else. In addition, I found that my array was also getting corrupted.

Sam was nice enough to supply a new sorting function to me. I am allowed to share this function as free TradeStation code on this site so long as you (and I) don’t remove Sam’s copyright information. This function is even more expandable as you can sort both 2D and 3D arrays just by changing the parameter.

The function is available as free TradeStation code by filling out the form on the right (not only can you get this code but you can get a plethora of other code as well)!

For an example of how to use skt_2D_Sort in your own indicator, check out the following example indicator:

*Consts: Size1 (05),
        Size2 (02) ;
Arrays: Array_In [Size1, Size2] (0.00) ;
Inputs: Sort_Rows               (05),  // How many of the Rows are in use (to be sorted)?
        Base_Val                (00),  // Use the zero element or not?  Input 00 or 01
        Sort_Col                (01),  // which column holds the sort value
        Sort_Dir               (+01) ; // +01 for Descending, -01 for Ascending
Dummy  = skt_2D_Sort (Array_In, Sort_Rows, Base_Val, Sort_Col, Sort_Dir);

Inputs: My_Index (01),  // Find Strategy #1
        My_Rank  (01) ; // Find most profitable

Consts: Max_Rows (05),
        Max_Cols (02),
        sub_Val  (01),  // the key value to be sorted
        sub_Ndx  (02) ; // the index back to original source
Arrays: myArray [max_Rows, Max_Cols] (0) ;
Vars  : Dummy    (00),
        Loop     (00),
        Str      (""),
        Index    (00),
        Rank     (00) ;

if  Barnumber <= 01 and BarStatus (01)  = 02 then begin

myArray [01,01]=1.5;
myArray [01,02]=1;
myArray [02,01]=5.5;
myArray [02,02]=5;
myArray [03,01]=2.5;
myArray [03,02]=2;
myArray [04,01]=3.5;
myArray [04,02]=3;
myArray [05,01]=4.5;
myArray [05,02]=4;

if  LastBarOnChart then begin
// Print (Date:6:0, ", ", Time:5:0) ;
 // Str  = "" ;
 // for Loop  = 01 to Max_Rows begin
//  Str  = Str + "#" + NumToStr (Loop, 00) + " " + 
// NumToStr (myArray [Loop, 01], 02) + ", " + 
// NumToStr (myArray [Loop, 02], 00) + NewLine ;
//  end ;
//  Print ("Pre :", NewLine, Str) ;

//  Value1  = MAR_OrdinalRank (myArray, 05, Ranking) ;
  Dummy  = skt_2D_Sort    (myArray, 05, 01, 01, +01 {, TRUE}) ;
  Index  = MAR_Find_Index (myArray, my_Index) ;
  Rank   = MAR_Find_Rank  (myArray, my_Rank) ;

  Plot1 (Index, "Index", Default, Default, Default) ;
  Plot2 ( Rank, " Rank", Default, Default, Default) ;
end ;

Custom Programming Services provided by:

                 Samuel K. Tennis
                    PO Box 1984
         Ft. Walton Beach, Florida  32549
          voice :  1(850) 243-5105
          cell  :  1(850) 582-7342
          fax   :  1(510) 743-8274

          AIM   : SKTennis
          GMail : SKTennis
          Yahoo : SamuelKTennis

Note, debugging comments have been removed from this article for space reasons.

This indicator calls 2 other functions which I have included
Index = MAR_Find_Index (myArray, my_Index) ;
Rank = MAR_Find_Rank (myArray, my_Rank) ;

MAR_Find_Index gives us a unique identifier to put in column 2. MAR_Find_Rank returns the sorted value. The My_Rank variable returns the offset in the array. In our case we used 1 which returns the highest value and 2 returns the second highest.

Check out this unique and awesome free TradeStation code by filling out the form on the right!

EquityCurve: Plotting Statistics from Your Strategy

When developing a strategy within TradeStation, many times it is important to plot how the system is performing in order to visually see ways in which it can be improved. TradeStation has built-in functions that allow you to plot various statistical measures of your system from an indicator. These are known as the I_XXXX reserved words. An indicator can use these to obtain strategy performance information. Most strategy-only performance-related reserved words can be replicated in an indicator using a combination of the I_XXXX reserved words:

I_OpenEquity (in an indicator) = NetProfit + OpenPositionProfit
                                 (in a strategy)
I_ClosedEquity (in an indicator) = NetProfit (in a strategy)
I_OpenEquity – I_ClosedEquity (in an indicator) = OpenPositionProfit 
                                                  (in a strategy)

Here are all the I_ reserved words:


These indicators can be helpful in better understanding your system. However, they cannot be used to filter the system in any way.=For example, you cannot use them to filter out trades when the equity curve crosses below its moving average. These measures are based on the real system results. If you want to do something like filtering the system using the equity curve this requires a shadow system which monitors a unfiltered copy of the rules equity and we can see the real trades based on filtered version. It’s simple to use these functions in an indicator. Look at the simple example below:

Inputs: ELen(40);
Vars: CurEquity(0), AveEquity(0);
Vars: AlertCond(FALSE);
CurEquity = I_openequity;
Plot1(CurEquity, "Plot1" );

AveEquity = Average(CurEquity,ELen);
Plot2(AveEquity, "Plot2" );

AlertCond =CurEquity < AveEquity;
if Condition1 then
	Alert( "Not Safe To Trade" );

Let’s see how this looks on a chart:


You can see that for about a dozen trades the current cycle equity stays below the moving average. This is because intermarket trades have serial dependencies due to decoupling between the traded market and the intermarket. Equity curve filters are a good tools for trading using intermarket analysis.

Please check out this product – EquityCurve – as well as my other free TradeStation code by filling out the form on the right!

Improving the Moving Average Crossover

By: Jeff Swanson (Visit his site, System Trader Success)

Let’s take a look at a simple moving average crossover system and see if we can improve it. Specifically, can we improve the moving average system’s performance by reducing the number of whipsaws during those dreaded range bound markets? Whipsaws occur when a market moves from a trending mode to a consolidation mode. During this consolidation mode the system gets whipsawed from long to short creating a string of losing trades. Long trades suddenly reverse hitting your stop. Likewise for short trades. These ‘false signals’ can destroy your equity curve. In this article I’m going to present two simple methods to improve the simple moving average crossover system. These ideas can easily be implemented into your trading systems and may provide a great starting point for a trend following system.

Baseline System

Our baseline system will consist of two simple moving averages (SMA) executed on a daily chart of the Euro futures. I’m picking the Euro because it has demonstrated solid trending characteristics as opposed to the stock index markets which tend to be mean reverting. If you will recall, signals are generated when a faster moving average (trigger SMA or trigger line) crosses a slower moving average (slow SMA or slow line).

Slow SMA 50 period
Trigger SMA 3 period

Go Long when trigger crosses above Slow SMA
Go Short when trigger crosses under Slow SMA

Dates Tested: May 2001 – September 30, 2013
Commissions & Slippage: $30 deducted per trade
Number of Contracts: 1

For those using TradeStation the Baseline System was created by inserting two strategies into the chart that were provided by TradeStation. Below are the two strategies. The first one controls the long entry (LE) rules and the second one controls the short entry (SE) rules. You can see the input fields contain the three and the fifty for the two different periods for our moving averages. Buy using these provided strategies you can build a moving average crossover strategy within seconds without any coding skills.


 Baseline System Equity Curve

Baseline EQ Curve

These two simple rules produce a trading system that is actually profitable over the long term. This is a testimate to the trending characteristics of the Euro futures market. However, there are periods of large drawdowns and long periods where no new equity highs are created. It’s not likely anyone would actually trade this with real money. The image below shows a recent period from 2011 when the Euro entered a consolidation phase during the summer months of June through August. During this time our Baseline System produced a string of eight consecutive losing trades.

Whipsaw Summer 2011


Improvement #1: Delayed Entry

With this entry method we are going to delay our entry into the market after the trigger line crosses the slow SMA. So, when the trigger line crosses the slow SMA we do not open our position right away. We delay for several bars. Let’s say we wait for 15 bars after the cross occurs. On the tenth bar after the signal we see if price is still above the slow SMA (for a long entry) and enter at the open of the 11th. If price is below our slow SMA we don’t open a new position. By doing this we eliminate some whipsaws at the expense of entering the trade later than the original SMA cross. The idea behind this method is if a new bull market is about to start, price should not fall back below the slow SMA. In short, it’s another way to measure the amount of conviction for the next market phase. However, we will keep the exit the same. When an EMA cross occurs we always close our open position. We only apply the delay when opening a new position.

EntryDelay EQ Curve

The equity curve with our delayed entry actually moves the entire equity curve above the zero line. Fewer trades are taken and we reduce the total net profit.  The equity curve also appears a little less jagged implying a slightly more smoother climb up. Below is an image showing the whipsaw summer time period in 2011. You will notice we have reduced the number of whipsaws from eight to zero.

 Whipsaw Summer 2011


Improvement #2: Trading Bands

Unlike the standard moving average crossover where the trigger line must simply cross the slow SMA, our trigger line must now demonstrate conviction by crossing beyond the slow SMA. For example, picture another band above the slow SMA that is 1 ATR above the slow SMA. In order to open a new long position we require the trigger line to penetrate that ATR band above the slow line. Now picture another band that is one ATR below the SMA. This band represents our short trigger when we open a short position. We hope to eliminate some whipsaws by delaying our entry and forcing the market to show us some strength.

Some of you may have already noticed that what we have is a Keltner Channel. A Keltner Channel is nothing more than a moving average (slow SMA) with an upper band X number of ATRs above and below the slow SMA. The upper and lower bands act as the trigger to enter either a long position or a short position. The bands adapt to expanding volatility requiring more price conviction to initiate a new position. Likewise, these bands contract during lower volatility times. Thus, the entry and exit rules are more dynamic to a changing market than a simple moving average crossover.

KeltnerChannel EQ Curve

The equity graph does not look too much different than our baseline  system. The entire equity curve spends less time near the zero line and there are fewer trades. Below is the same time period showing the Band System has reduced the number of false signals from eight to two. This is a great improvement over the Baseline System.

Whipsaw Summer 2011 



Each of the two methods improved the results of the original Baseline System. Looking at the table below we can see performance statistics such as profit factor, percent winners and average trade net profit all increased. The Keltner produced the best overall statistics. We certainly don’t have a trading system that is tradable with real money, but we accomplished our mission. We reduced the number of whipsaws with our Delayed Entry System and Band Entry System. You can see this by looking at the number of trades taken by each system and the percent winning trades.


More Ideas

You can take this research in all types of directions. Here two more ideas.

Delay With Time Decay – Markets switch between trending and non-trending as we all know. Often you will notice a string of whipsaws on a moving average crossover system right after a great winning trade was closed. The market apparently is now morphing to a range bound market and will likely do this for sometime. However, as the days or weeks wear on the likelihood of a breakout probably increases. Thus maybe we can reduce the delay amount as time goes by. After the close of a successful trade we begin looking for the next cross with our default X bar delay. The market remains range bound and produces several false signals over the weeks but our system does not take any new signals. During these false signals our delay counter is reset but let’s not always reset it to X. Every day or every week we reduce our X day delay by one. We do this because we believe as time goes by a breakout becomes more likely. However, we never reduce X to reach zero or lower. In fact, we may never want to go much lower than 5 or so.

Trend Filter – In a previous article I used rsRank or a 200-period SMA as a trend indicator to help determine the bigger picture for the Euro. In other words, are we within a bullish or bearish market? Maybe only taking long trades during a bull market or taking short trades during a bear market would improve results. This would be an interesting and simple test to perform. I would love to hear your results.

Be sure to leave  a comment below. I would love to hear any ideas or results from your own testing!

Intermarket Divergence Basic

This free TradeStation code is a simplified version of Murray Ruggiero Jr.’s Intermarket Divergence Pro software. This utility was designed to explore intermarket relationships. While the paid version of this tool supports more relationships and more advanced features, this program allows people to begin to explore the world of intermarket analysis and better understand it’s power.

Standard correlation between markets are not useful if our goal is to either predict future prices or generate profitable signals because current correlation does not tell us anything about future prices. A methodology we developed originally developed in the mid 1990’s called intermarket divergence allows us to gauge the predictive power of an intermarket relationship and produce 100% objective signals.

To begin exploring this powerful concept, please request this free code using the form to the right.

Pivot Point Zone Free Code

The latest free TradeStation code that Murray Ruggiero has posted on this site is a shell of a classic intra-day system that is based on pivot point zones. Included within the zip file are two strategies. The first one, called “-Zones” is a simple intra-day zone system which we can either trade all classic patterns or test one at a time. The second system is called “ZoneArticlePartB” and lets us test five different patterns. It also lets us store the zone we are in on each bar of the day using 45 minute bars on the ES day session. Using this second system, you can print the course of the market through the zones all day and see if you can find a predictive pattern that you can use to determine trade outcomes.

[Read more…]