Indicators – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Thu, 11 Jul 2024 11:47:18 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg Indicators – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 Exploring Price-Time Filtering in Trading https://easylanguagemastery.com/indicators/exploring-price-time-filtering-in-trading/?utm_source=rss&utm_medium=rss&utm_campaign=exploring-price-time-filtering-in-trading https://easylanguagemastery.com/indicators/exploring-price-time-filtering-in-trading/#respond Mon, 15 Jul 2024 10:00:00 +0000 https://easylanguagemastery.com/?p=534623

The Price-Time Filter Indicator

It's essential to identify genuine market trends for consistent trading success. Many traders find distinguishing between random price fluctuations and real trading signals challenging, which can lead to missed opportunities or false entries. Today, we'll explore an intriguing technique called Price-Time Filtering, designed to filter out market noise and emphasize significant trends with greater clarity.

This article was inspired by Alfred François Tagher's insightful article, "Trend Identification By Price And Time Filtering," featured in the February 2024 issue of Stocks & Commodities magazine. In it, Tagher introduced the Price-Time Filtering technique. This method leverages the power of both price and time to identify trends, making it a robust tool for traders seeking to enhance their market analysis. When applied correctly, this method can provide a clearer picture of market movements and help traders make more informed decisions.

This article will delve into the price-time filtering technique and apply it to several future markets. By the end, we'll have a deeper understanding of how this technique works, its potential advantages, and how to incorporate it into your trading toolkit.

Practical Application of the Price-Time Filter

Imagine trying to listen to a piece of music in a noisy environment. In this scenario, you need some type of filter to remove the noise so you can hear the music more clearly. This is what your canceling headsets do.

In the trading world, price-time filtering isolates trends, allowing you to trade in the overall market direction. don't see the Price-Time filter as a signal generator to go long or short. Instead, it will help align trades with the prevailing market direction, reducing the risk of false signals and improving the consistency of trading results.

Well, that's the theory, anyway. I don't know if it will work, but that's what we're testing with this article.

Implementing the Price-Time Filter in EasyLanguage

Implementing the price-time filtering technique is straightforward with EasyLanguage for those using TradeStation or MultiCharts. Below, I provide code examples for the weekly timeframes, which I plan to focus on in this article. 

EasyLanguagee Code For Price-Time Filter:

{ Price-Time Filtering - Weekly }

Inputs: UpColor(Green), DnColor(Red);
Vars: WeekHi(0), WeekLo(0), WeekCl(0), PriorWeekHi(0), PriorWeekLo(0), Trend(0), WeekKnt(0);

{ Check for end of the week }
If (DayOfWeek(Date) < DayOfWeek(Date[1]) and DayOfWeek(Date[1]) <> 5) or (DayOfWeek(Date) = 5) then begin
If DayOfWeek(Date) = 5 then WeekCl = Close else WeekCl = Close[1];

If WeekCl > PriorWeekHi then Trend = +1;
If WeekCl < PriorWeekLo then Trend = -1;

PriorWeekHi = WeekHi;
PriorWeekLo = WeekLo;
WeekKnt = WeekKnt + 1;
end;

{ Reset weekly high and low }
If DayOfWeek(Date) < DayOfWeek(Date[1]) then begin
WeekHi = High;
WeekLo = Low;
end;

{ Update weekly high and low }
If High > WeekHi then WeekHi = High;
If Low < WeekLo then WeekLo = Low;

{ Plot the trend }
If WeekKnt > 1 then begin
If Trend = +1 then Plot1(High, "Week UP", UpColor);
If Trend = -1 then Plot1(Low, "Week DOWN", DnColor);
end;

Explanation

1. Inputs: These are user-defined parameters for the colors used in the plots.

2. Variables: These store the high, low, and close prices for the current and prior periods, as well as the trend direction and counters.

3. End of Period Check: The script checks if the current day is the week's or month's end and updates the trend accordingly.

4. High and Low Updates: The script continuously updates the highest and lowest prices observed throughout the period.

5. Plotting: The script plots the trend direction based on the evaluated conditions.

Below is an image of a PaintBar indicator using the Price-Time filter. Bearish trends are coloring the price bars red. Bullish trends are in green.

Price-Time Filter example

Price-Time Filter example

Testing the Price-Time Filter

I transformed the indicator into a simple trading strategy to evaluate the effectiveness of the Price-Time Filtering technique. This strategy will buy when the filter indicates an uptrend and sell short during a downtrend. By doing this, we can gauge how well the Price-Time Filter can identify and capitalize on trending markets.

Here's the plan:

  1. Strategy Setup:
    • We'll use the EasyLanguage code for the Price-Time Filtering indicator, which we've already discussed.
    • The strategy will enter a long position when the filter signals an uptrend and enter a short position when it signals a downtrend.
    • We'll be using the Weekly version of the Price-Time Filter.
  2. Testing Parameters:
    • We'll apply this strategy to several futures markets that represent a good basket of unique markets I trade, including:
      • Soybeans (S)
      • Euro Currency Futures (EC)
      • Crude Oil (CL)
      • S&P 500 (ES)
      • Gold (GC)
    • The testing will use daily bars to capture significant price movements over time.
    • We'll be using historical dates from 2000-2023. 
    • Slippage and commission will not be taken into account for this analysis.
  3. Performance Metrics:
    • We'll evaluate the strategies based on key performance metrics such as net profit, maximum drawdown, and net profit vs. maximum drawdown ratio.
    • Additionally, we'll analyze the average duration of trades to understand how long trends typically last.

By converting the Price-Time Filter into a simple strategy and testing it across different futures markets, I aim to provide you with actionable insights into its effectiveness. This practical approach will help you determine if this method can enhance your trading systems and improve your overall trading success. In the following sections, we'll dive into the results of these tests and draw meaningful conclusions to guide your trading decisions.

Price-Time Results

Now it's time to test this indicator on our markets. Below is a table with the results of apply the Price-Time strategy.

S

EC

CL

ES

GC

Net Profit

-31,687

$39,012

$157,480

$31,612

-$112,670

Profit Factor

0.89

1.12

1.36

1.36

1.09

0.79

Total Trades

216

216

200

222

254

Avg.Trade Net Profit

-$146

$180

$787

$142

-$443

Max Drawdown (Intra-Day)

$82,800

$49,056

$117,960

$74,412

$135,650

NP vs. DD

-0.3

0.7

1.3

0.4

-0.8

Some markets yield higher net profits than others which is expected. Soybeans and Gold do not perform well, whereas Crude Oil performs the best.

I couldn't help but notice that the Price-Time filter serves as a momentum or trend indicator. Thus, the markets with higher net profit are likely markets that have some trending characterisitic.

What if we were to invert the trading logic? We'll explore that in the next section.

Inverted Price-Time Results

In this case we're going to do the opposite of the original rules. That is, when we get a long signal, we're going to sell short. Why? We want to test the mean reversion characteristic of the market. We would expect to see results that are opposite of above. 

S

EC

CL

ES

GC

Net Profit

31,687

-$39,012

-$157,480

-$31,687

$112,670

Profit Factor

1.09

0.89

0.73

0.92

0.79

Total Trades

222

216

200

222

254

Avg.Trade Net Profit

$142

-$180

-$787

-$142

-$443

Max Drawdown (Intra-Day)

$74,412

$73,237

$266,450

$74,962

$88,090

NP vs. DD

0.4

-0.5

-0.6

-0.4

1.2

We can see that soybeans and gold do much better while the other market moves into negative territory. This tells me that Soybeans and Gold have mean reverting characteristics while the other markets have more trending characteristics. At least based on this indicator and this indicators hold times. We'll look at hold times in the final table. below.

Let's now create a table with the best results for each market.

Price-Time Best Results

In this table we're going to select the best performing side (Long, Short, or Both) and we'll select the best performing trading style (Trend Following or Mean Reversion)

S
Long MR

EC
Both TF

CL
Both TF

ES
Long MR

GC
Long MR

Net Profit

61,212

$39,012

$157,480

$87,950

$118,270

Profit Factor

1.61

1.12

1.36

1.54

1.71

Total Trades

108

216

200

111

127

Avg.Trade Net Profit

$566

$180

$787

$792

$931

Max Drawdown (Intra-Day)

$32,100

$49,056

$117,960

$40,462

$67,300

NP vs. DD

1.9

0.8

1.3

2.1

1.7

Avg. Bars in Trades

31

36

39

47

29

The weakest market is the Euro Currency Futures. The Price-Time filter does not hold some potential when using the mean reversion version of the indicator.  

The Crude Oil market does best in terms of net profit while talking both  long and short trades, with our filter acting as a trend-following indicator. See the image below for example trades. Click on the image for a larger version.

Price-Time Chart of Crude Oil With Trades

Price-Time Chart of Crude Oil With Trades

The remaining markets (Soybeans, S&P 500, Gold) all do well on the long side, with our filter acting as a mean reverting indicator.

What have we learned?

We have discovered which trading style (mean reversion or trend following) may work well for each market and which side of the market we should trade (long, short, or both).

This can be valuable information! We now have some critical information if we wish to start building trading systems on the daily timeframes for these markets.

Remember, depending on the market, the average holding time for these trades is between 29 days (GC) and 47 days (ES). So, the characteristics we're measuring in this study must unfold over several weeks.

How could you use this indicator?

As stated earlier, the Price-Time filter is not meant to generate trading signals. We used it to perform our market study this way, but it's better as a filter. 

For example, you might use this indicator on the ES market to activate your trading model and start looking for long trades. 

I did not explore the monthly signals in this study. However, the code can be modified to use the monthly closing price to produce an even longer-term filter, which presents a promising avenue for future studies. You will find that code in the original article, requiring a subscription to Technical Analysis For Stocks & Commodities magazine. I recommend the publication highly.

Lastly, if you trade intraday strategies, use this filter on a daily chart to filter which direction you should be trading on your 60-minute chart. This is another idea worth testing.

]]>
https://easylanguagemastery.com/indicators/exploring-price-time-filtering-in-trading/feed/ 0
A Better Regime Filter: True Range Adjusted Exponential Moving Average https://easylanguagemastery.com/indicators/a-better-regime-filter-true-range-adjusted-exponential-moving-average/?utm_source=rss&utm_medium=rss&utm_campaign=a-better-regime-filter-true-range-adjusted-exponential-moving-average https://easylanguagemastery.com/indicators/a-better-regime-filter-true-range-adjusted-exponential-moving-average/#comments Mon, 17 Jul 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532612

As an aspiring algorithmic trader, you're stepping into a realm where the mastery of various trading indicators can significantly enhance your trading decisions. One such powerful tool that deserves your attention is the True Range Adjusted Exponential Moving Average (TRAdj EMA) .

The TRAdj EMA is not just another trading indicator. It distinguishes itself from traditional moving averages by integrating volatility into its calculation, providing a more responsive indicator to market trends. This unique feature makes it an invaluable tool for algorithmic traders, especially those trading in volatile markets.

This article dives deep into the TRAdj EMA, exploring its calculation, application, and performance in trading scenarios. Our discussion is inspired by the article "True Range Adjusted Exponential Moving Average" by Vitali Apirine, found in the January 2023 issue of Stocks & Commodities magazine.

Whether you're a novice trader looking to expand your toolkit or an experienced trader keen to explore new strategies, understanding the TRAdj EMA could be a helpful tool in your arsenal. And here at EasyLanguage Mastery, we're committed to helping you master such powerful tools through our comprehensive System Development Master Class. 

Lets get going!

Understanding the True Range Adjusted Exponential Moving Average

The TRAdj EMA is a unique trading indicator that goes beyond the traditional moving averages. It's a trend-following indicator that adjusts for a market's volatility, making it a valuable tool for traders operating in volatile markets.

At its core, the TRAdj EMA incorporates the concept of 'true range,' a measure of volatility introduced by J. Welles Wilder. The true range is the greatest of the following: 

  • the current high less the current low,
  • the absolute value of the recent high less the previous close and
  • the absolute value of the current low less the previous close.

By integrating this measure of volatility, the TRAdj EMA provides a more accurate and responsive representation of market trends. At least, that's the theory!

Moreover, by using TRAdj EMA with different lengths, traders can define turning points and filter price movements more effectively.

Understanding the TRAdj EMA is the first step towards leveraging its power in your trading strategy as we delve deeper into its calculation and application in the following sections. The main point of this article will be to test the TRAdj EMA indicator to see if it can help use build strategies. In short, is this indicator useful to us?

Calculating the True Range Adjusted Exponential Moving Average

Calculating the True Range Adjusted Exponential Moving Average (TRAdj EMA) may seem complex at first glance, but it's quite straightforward once you understand the components involved.

Let's break it down step by step.

The TRAdj EMA is calculated using the formula: 

 TRAdj EMA = Prior TRAdj EMA + MLTP * (1+TRAdj*MLTP_TRAdj) * (Price − Prior TRAdj EMA). 

  • The multiplier (MLTP) is calculated as 2 / (Time periods + 1). This multiplier gives more weight to recent prices, making the TRAdj EMA more responsive to recent price changes.
  • The true range (TR) is calculated as the greatest of the following: current high less the current low, the absolute value of the current high less the previous close, and the absolute value of the current low less the previous close.
  • The True Range Adjustment (TRAdj) is calculated as (Current TR − Minimum TR) / (Maximum TR − Minimum TR). The TRAdj fluctuates between 0 and 1, and it's then multiplied by MLTP_TRAdj, which can vary from 5 to 10.

OK that was a bit complex for my taste! I think I followed that but no worries if you don't. Then it comes to these indicators we're going to focus on the practical side of things and test if this indicator can be helpful to us. Can it help us build winning trading systems.

In the next section, we'll explore how to apply this powerful indicator in your trading strategy.

Applying the True Range Adjusted Exponential Moving Average in Trading

Now that we understand what the True Range Adjusted Exponential Moving Average (TRAdj EMA) is and how it's calculated let's explore how to apply it in your trading strategy.

The True Range Adjusted Exponential Moving Average (TRAdj EMA) offers two possible applications for building trading systems.

1. Trend Identification: The TRAdj EMA can be used with an exponential moving average of the same length to help identify the overall trend. TRAdj EMAs with different lengths can define turning points and filter price movements. For instance, the 200-day EMA and TRAdj EMA(200,200,10) captured the 2000–2003 bear market.

Pictured below is the daily chart of the E-mini S&P. The redline is the TRAdj EMA, and the thicker dark blue line is a 200 EMA. When the TRAdj EMA crosses below the EMA that would be a bearish signal. When the TRAdj EMA crosses above the EMA that would be a bullish signal. We can see how these two indicatommmrs defined the most recent bearish action starting and 2022 and ending in 2023.

True Range Email Trend Example

TRAdj EMA Trend Example

2. Signal Generation: Moreover, the TRAdj EMA can be used to generate buy and sell signals based on crossovers with the price or another moving average. A bullish crossover, where the TRAdj EMA crosses above the price or another moving average, can be seen as a buy signal. On the other hand, a bearish crossover, where the TRAdj EMA crosses below the price or another moving average, can be seen as a sell signal.

True Range Trade Example

TRAdj EMA Trade Example

It's important to remember that, like all trading indicators, the TRAdj EMA should not be used in isolation. It's most effective when used in conjunction with other technical analysis tools and market indicators. In the next section, we'll put the TRAdj EMA to the test and see how it performs in different trading scenarios.

Trend Testing the TRAdj EMA

I'm most interested in how this indicator may work as a trend filter. I often use the 200-bar simple moving average to define bullish and bearish regimes. For example, if the current price is above the 200-day SMA, I consider the market in a bullish regime. On the other hand, if it's below the 200-day SMA, it's in a bearish regime. Can this indicator do better? This test can easily be coded using EasyLanguage. 

I coded a switch in EasyLanguage to switch between calculating a bullish or bearish regime usng my 200-bar SMA vs the new 200-bar TRAdj EMA. For this test I open a long trade during a bullish regime and sell short during a bearish regime. Then I used TradeStation optimization feature to optimize over the two different options.  I did not account for slippage or commissions. I tested from 2006 through June of 2023.

Here is the code:

inputs:
SMAorTRAdjEMA(0) {0-traditional 1-TRAdjEMA},
Periods(20),
Pds(20),
Mltp(5);

variables:
mySMA(0),
myEMA(0),
TRAdjEMA( 0 );

TRAdjEMA = True_Range_EMA( Periods, Pds, Mltp );
MyEMA = Xaverage(Close, Periods);

mySMA = average(Close,Periods);

if ( SMAorTRAdjEMA = 1 ) Then
Begin
   if ( TRAdjEMA >= MyEMA ) then buy next bar at market;
   if ( TRAdjEMA < MyEMA ) then sellshort next bar at market;
End
Else Begin
   if ( Close >= mySMA ) then buy next bar at market;
   if ( Close < mySMA ) then sellshort next bar at market;
End;

E-mini S&P Trend Results

SMA

TRAdj EMA

Net Profit

$68,867

$37,812

Profit Factor

1.36

1.28

Total Trades

149

28

Avg.Trade Net Profit

$462

$1,350

Max Drawdown

$59,337

$88,987

NPDD

1.16

0.61

The SMA captures more profit. That's clear. It also produces a smaller drawdown. This is good. But look at the number of trades. The standard SMA regime filter has 149 trades vs the 28 with the TRAdj EMA. What does this mean? The standard SMA regime filter has a lot more whipsaws as seen below.

SMA vs True Trend EMA

SMA vs TRAdj EMA

The image on the left is the standard SMA regime filter. As the price bounces above and below the 200-period simple moving average, several trades occur. Contrast that with the TRAdj EMA on the right-hand side. This cleanly calls the bear regime's end and a bull regime's start.

In short, the SMA will capture more profit but at the cost of many more trades. The TRAdj EMA will be more selective, capturing the major trend. We can see this in the number of trades and the average profit per trade.

So, which one is better? That depends. The standard SMA regime filter will react quicker but at the cost of more false signals. On the other hand, the TRAdj EMA is more efficient at calling the major trends. I like that. Both indicators will still have value, but I could see why the TRAdj EMA may work well as a regime filter.

Trend Results for Other Markets

Crude Oil

SMA

TRAdj EMA

Net Profit

$95,560

$138,170

Profit Factor

1.38

2.48

Total Trades

192

25

Avg.Trade Net Profit

$497

$5,526

Max Drawdown

$119,320

$120,240

NPDD

.80

1.15

Soy Beans

SMA

TRAdj EMA

Net Profit

$72,087

$46,000

Profit Factor

1.71

1.98

Total Trades

150

20

Avg.Trade Net Profit

$480

$2,300

Max Drawdown

$38,000

$31,112

NPDD

1.90

1.48

Euro Futures

SMA

TRAdj EMA

Net Profit

$107,700

$59,413

Profit Factor

1.85

1.88

Total Trades

139

26

Avg.Trade Net Profit

$774

$2,285

Max Drawdown

$49,368

$77,350

NPDD

2.18

0.77

As a trend filter it looks like the TRAdj EMA does well. It's consistently taking fewer trades and generating more profit per trade. I take this as a sign of defining the major trend better than the popular 200-bar simple moving average. It really reduces the number of false signals (whipsaws).

What do you think? Post your thoughts or questions in the comments below this post.

As I wrap up this post, I did not even test the TRAdj EMA as a signal for opening trades. That will be for another post.

Conclusion

In conclusion, the True Range Adjusted Exponential Moving Average (TRAdj EMA) presents a compelling alternative to the traditional Simple Moving Average (SMA) as a regime filter. While the SMA may capture more profit and produce a smaller drawdown, it also results in more trades, indicating more whipsaws. On the other hand, the TRAdj EMA is more selective, capturing the major trends with fewer trades, thus increasing the average profit per trade.

The choice between the two depends on the trader's strategy and risk tolerance. The SMA will react quicker but at the cost of more false signals, while the TRAdj EMA is more efficient at calling the major trends. Both indicators have their value and can be powerful tools in your toolbox. I plan to use TRAdj EMA and SMA in my strategy development process.

This exploration of the TRAdj EMA underscores the importance of understanding and experimenting with different trading indicators. As we've seen, even a slight adjustment to a traditional indicator can significantly impact trading outcomes.

As we've seen, the True Range Adjusted Exponential Moving Average (TRAdj EMA) is a powerful tool that can significantly enhance your trading strategy. But mastering this tool requires more than just understanding its calculation and application. It requires hands-on experience, guided learning, and the opportunity to apply your knowledge in real-world trading scenarios. That's where System Development Master Class comes in.

My System Development Master Class is a comprehensive 90-day program designed to fast-track your journey to becoming a profitable system trader. We focus on teaching you to code in EasyLanguage, build and validate trading systems, and deploy those strategies to the live market. Join our System Development Master Class today and take a giant leap forward in your trading career.

Remember, the key to successful trading lies not just in the tools you use, but also in the strategies you develop and your understanding of these tools.

Happy trading!

]]>
https://easylanguagemastery.com/indicators/a-better-regime-filter-true-range-adjusted-exponential-moving-average/feed/ 6
Capture The Big Moves! (Updated 2023) https://easylanguagemastery.com/indicators/capture-the-big-moves/?utm_source=rss&utm_medium=rss&utm_campaign=capture-the-big-moves https://easylanguagemastery.com/indicators/capture-the-big-moves/#comments Mon, 03 Jul 2023 10:00:00 +0000 http://systemtradersuccess.com/?p=153

Wouldn’t it be great to have an indicator that will help tell you when you are in a major bull or bear market? Imagine if you had a clear signal to exit the market on January 19, 2008 before the major market crash. Then the same indicator told you when to get back into the market on August 15, 2009. Such an indicator would have also gotten you out of the market during the dot-com crash on November 11, 2000. Well, this indicator I’m going to talk about does just that.

Below you will also find the EasyLanguage code for this indicator. This major trend indicator was inspired by an article entitled, Combining RSI With RSI” by Peter Konner, and it appeared in the January 2011 issue of Technical Analysis of Stocks and Commodities.

How It Works

We will start with a well-known indicator: the Relative Strength Indicator (RSI). The goal is to identify major bull market and bear market regimes. In his article, Peter does this by simply using an RSI indicator on a weekly chart and identifying two unique thresholds. Peter noticed that during bull markets, the RSI rarely goes below the value of 40.

On the other hand, during a bear market, the RSI rarely rises above the value of 60. Thus, when the RSI crosses these thresholds, you can determine the beginning and end of bull/bear markets.

For example, in the bear market during the financial crisis of 2008, the weekly RSI indicator did not rise above 60 until August of 2009. This signaled the start of a new bull trend. The next bear trend will be signaled when the weekly RSI falls below 40.

With these simple rules, you can determine bull and bear markets for the S&P cash index market.

  • Bull Markets RSI Often Above 60
  • Bear Markets RSI Often Below 40

The two images below display a weekly chart. Below the price is a second pane with a 12-period RSI. Why a 12-period RSI? I chose that number because it represents a quarter of a year of trading if you figure four weeks in a month. There was nothing optimized about this number. It just seemed to be a logical starting point. Other lookback values will produce very similar results.

In the image below (click to enlarge), you will see the RSI signal stays above the 40 level during the strong bull market of the 1990s.

In the image below (click to enlarge) you will see the RSI signal stays below the 60 level during the strong bear market in the financial crisis of 2007-2009.

As you can see the RSI appears to do a fairly decent job of dividing the market into bull and bear regimes. You will also notice the RSI indicator paints red when it goes below 40, and only returns to a light blue when it rises above 60. It is these critical thresholds which highlight a significant turning point in the market that may be occurring.

Testing Lookback Periods

I’m curious to see how well this strategy holds up over various lookback periods. A strategy should be robust enough to produce solid results over different lookback periods. To test this aspect of the strategy, I will use TradeStation’s optimization feature to optimize the lookback period over the values 2-24.

The first chart is the lookback period (x-axis) vs. the net profit (y-axis).

Lookback Period vs Net Profit

The above chart shows rising profit as the lookback period increased from 2 to 10. Then the growth slows down. You can make a case for a stable region between 9 and 24; the midpoint is about 16. Feel free to experiment on your own and pick a different value. The main point here is this: all the values produce positive results, and a wide range of values at the upper end of our scale generate excellent results. This makes me believe that this indicator is robust in signaling significant market changes.

Testing Environment

I decided to test the strategy on the S&P cash index going back to 1960. The following assumptions were made:

  • Starting account size of $100,000.
  • Dates tested are from 1960 through August 2020.
  • The number of shares traded will be based on volatility estimation and risking no more than $5,000 per trade.
  • Volatility is estimated with a three times 20-week 40 ATR calculation. This is done to normalize the amount of risk per trade.
  • The P&L is not accumulated to the starting equity.
  • There are no deductions for commissions and slippage.
  • No stops were used.

Results

Applying this to the S&P cash index we get the following overall results.

CaptureBigMovesPerformance_2022_06_13

Capture Big Moves Performance 2022-06-13

Notice the short side loses money. I would guess this tells us over the life of the market, there is a strong upside bias. Below is the equity curve.

Capture Big Moves EQ Graph 2022-06-13

Capture Big Moves EQ Graph 2022-06-13

Using this indicator, we come up with the following turning points for significant bull and bear markets for the US indices. The blowup of the dot-com bubble happened in 2000, and we got out on October 14, 2000. The indicator then told us to go long on May 10, 2003. We then ride this all the way up to the financial crisis getting out of the market on January 12, 2008. Then on June 15, 2009, we went long. Overall, not too bad!

Does It Work Today?

Here is what the strategy looks like when applied to the price chart over the past few years. I also painted the price bars based on the RSI signal. Light blue price bars mean we are in a bull market, and red price bars represent a bear market.

Capture The Big Moves Recent Current Signal 2023-06-29

Capture The Big Moves Recent Current Signal 2023-06-29

The price action of 2019 and 2020 (Covid-19 Event) saw a sharp selloff, resulting in this indicator reacting slowly from a Bull-to-Bear transition. So, this strategy lost money on the long side and short side. Classic whipsaw behavior.

Will these sudden sell-offs and sharp rebounds continue into the future? I really don't know. But let's look at the most recent sell signal in 2022.

Sell Signal March 5, 2022

This signal resulted in booking a profit from the long trade. At the time of this writing in June of 2022, this looks like a reasonable exit point if the market continues to fall over the coming months. But we don't know what will happen at this point.

Buy Signal June 16, 2023

This signal resultsed in a loss on the short side. The downturn in the market which triggered and sell signal that started on March 5, 2022 turned out to be rather shallow.

Capture The Big Moves Recent Signals 2023-06-29

Capture The Big Moves Recent Signals 2023-06-29

How can this be used in your trading?

Perhaps you can use this as a basis for a long-term swing strategy. For example, maybe this is an indicator to let you know when to go long or liquidate your long positions within your 401(k) and other retirement accounts.

Keep in mind that short trades are not profitable. In my opinion, you're better off stepping aside during these short times. That is, close long positions and move to cash without attempting to short. Nothing wrong with being on the sidelines.

The strength of such a system is not in how much money you can make compared to buying and holding. The strength is avoiding drawdowns and providing a mechanism to start buying back into the market, so you don't miss the next bull market.

Or perhaps if you are a discretionary trader, you can use this to focus on taking trades in the primary direction of the indicator. Maybe when the RSI indicator signals a bull market, you may want to view this as another confirmation or green light to pursue whatever investment strategy you prefer. I thought it was an exciting and novel way to look at the RSI indicator.

Of course, we only have 59 signals since 1960. This is hardly a representative sample if we are talking about statistics. However, given the robust nature of the lookback period and the rising equity curve since 1960, this indicator may be worth keeping an eye on.

Where Are We Now?


Bull Market Signal Since June 16, 2023


Recent market behavior as we go into the Summer of 2023 is signaling Bull Market. The signal was triggered on the week of June 16, 2023What do you think? Is a new bull marketing forming? Will it last?


]]>
https://easylanguagemastery.com/indicators/capture-the-big-moves/feed/ 27
EasyLanguage to Determine Week of Month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/?utm_source=rss&utm_medium=rss&utm_campaign=easylanguage-to-determine-week-of-month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/#respond Mon, 22 May 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532499

Week Of Month
I could be wrong, but I couldn’t find this functionality in EasyLanguage. I was testing a strategy that didn’t want to trade a specific week of the month. If it’s not built-in, then it must be created. I coded this functionality in Sheldon Knight’s Seasonality indicator but wanted to create a simplified universal version. I may have run into one little snag. Before discussing the snag, here is a Series function that returns my theoretical week of the month.

vars: weekCnt(0),cnt(0);
vars: newMonth(False),functionSeed(False);

if month(d) <> month(d[1]) Then
Begin
weekCnt = 1;
end;

if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Then
begin
weekCnt = weekCnt + 1;
end;
if weekCnt = 1 and dayofMonth(d) = 2 and dayOfWeek(D) = Sunday Then
print("Saturday was first day of month"," ",d);

WeekOfMonth = weekCnt;

Series Function to Return Week Rank


This function is of type Series because it has to remember the prior output of the function call – weekCnt.  This function is simple as it will not provide the week count accurately (at the very beginning of a test) until a new month is encountered in your data.  It needs a ramp up (at least 30 days of daily or intraday data) to get to that new month.  I could have used a while loop the first time the function was called and worked my way back in time to the beginning of the month and along the way calculate the week of the month.  I decided against that, because if you are using tick data then that would be a bunch of loops and TradeStation can get caught in an infinite loop very easily.

This code is rather straightforward.  If the today’s month is not equal to yesterday’s month, then weekCnt is set to one.  Makes sense, right.  The first day of the month should be the first week of the month.  I then compare the day of week of today against the day of week of yesterday.  If today’s day of week is less than the prior day’s day of week, then it must be a Sunday (futures markets open Sunday night to start the week) or Monday (Sunday = 0 and Monday = 1 and Friday = 5.)  If this occurs and today’s month is the same as yesterday’s month, weekCnt is incremented.  Why did I check for the month?  What if the first trading day was a Sunday or Monday?  Without the month comparison I would immediately increment weekCnt and that would be wrong.  That is all there is to it?  Or is it?  Notice I put some debug code in the function code.

Is There a Snag?

April 2023 started the month on Saturday which is the last day of the week, but it falls in the first week of the month.  The sun rises on Sunday and it falls in the second week of the month.  If you think about my code, this is the first trading day of the month for futures:

month(April 2nd) = April or 4

month(March 31st) = March or 3

They do not equal so weekCnt is set to 1.  The first trading day of the month is Sunday or DOW=0 and the prior trading day is Friday or DOW=5.  WeekCnt is NOT incremented because month(D) doesn’t equal month(D[1]).  Should WeekCnt be incremented?  On a calendar basis it should, but on a trading calendar maybe not.  If you are searching for the first occurrence of a certain day of week, then my code will work for you.  On April 2nd, 2023, it is the second week of the month, but it is the first Sunday of April.

Thoughts???  Here are a couple of screenshots of interest.

Indicator in Histogram form representing the Week of Month

Some months are spread across SIX weeks.

This function is an example of where we let the data tell us what to do.  I am sure there is calendar functions, in other languages, that can extract information from just the date.  However, I like to extract from what is actually going to be traded.

Email me if you have any questions, concerns, criticism, or a better mouse trap.

>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/feed/ 0
Bull Flag on futures markets? https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/?utm_source=rss&utm_medium=rss&utm_campaign=bull-flag-on-futures-markets https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/#comments Mon, 08 May 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532389

Recently someone asked on an Easylanguage forum if anyone had coded a Bull flag / Bear flag pattern recognition to use on a futures index strategy. I realized that I did not know the pattern, so I went and looked for it.

Bull flag pattern

A bull flag is a technical chart pattern that is often used by traders to identify potential bullish market movements. The pattern is characterized by a strong upward move, followed by a period of consolidation, or “flag,” that is usually parallel to the trendline of the initial move.

The bull flag pattern is considered a continuation pattern, as it indicates that the current bullish trend will likely continue after the consolidation period. This can be a valuable signal for traders looking to enter long positions or add to existing ones.

The pattern typically forms after a strong upward move, which is known as the “flagpole.” This initial move can be caused by a number of factors, such as positive earnings reports, strong economic data, or other market-moving news. During the consolidation period, the price of the security will generally move sideways, forming a “flag” shape on the chart.

Traders typically look for a breakout above the resistance level of the flag to confirm the continuation of the bullish trend. Additionally, traders may use a stop-loss order below the support level of the flag to protect their position in case the trend does not continue.

Bull flag in quantitative trading

We can get as fancy as we want with Easylenguage, but I wanted to take a straightforward approach:

Flagpole: Two simple moving average (SMA).

  • Bullish flagpole SMA based on the low price, and current SMA bigger than the previous two SMA´s.
  • Bearish flagpole SMA based on the high price, and current SMA lover then the previous two SMA´s.

Breakout: RSI2 that breaks over limit on the direction on the trend.

Exits: Stop loss and profit target.

Long and Shorts: The ability to test only long, only short or both.  

Charting Software: Tradestation 10.0

Code development: Easylenguage 10

Research platform: https://tradesq.net/

Bull Flag on futures markets? –Easylanguage code

Let’s see how it works on a chart:

Long entries on Bull flag on a @CL 1440m chart

Short entries on bear flag on a @CL 1440m chart

Its not perfect “flag” shape, but the concept of entering after the breakout of the retracement works pretty well.

Now that we have the code and the strategy let’s see if it would work in future markets. For the study, Tradesq will test it for us on 43 Future markets and 11 timeframes in a matter of hours. Can you imagine how much time would take to perform the test manually?

Results

We have many edges on currencies, energies, grains, Indexes, and interest sectors.

Results filtered by (NP/DD>4, Number of trades above 200)

Let’s have a look at Some results from every sector.

30Yr Bonds(@US) 240min

Heating Oil(@HO) 360min

British Pound(@BP) 240min

Spring Wheat(@MW) 360min

Nasdaq(@NQ) 30min

Note: All results include trading costs, Slippage and Commission.

Conclusion

I don’t know if the code developed will resolve the poster question on the Bull Bear Flag pattern, but certainly did find really good edges.

The study was intended to show how we can start from a simple idea and use tools like Tradesq and Easylanguage / Powerlanguage to build strategies. As a result, we found firm edges through five (5) different future market sectors. 

It does not mean this are strategies ready to trade, additional filters and robustness tests must be applied, but is a terrific starting point.

>>By Juan Fernando Gómez From blog.tradesq.net  Email: jgomezv2@jgomezv2

]]>
https://easylanguagemastery.com/indicators/bull-flag-on-futures-markets/feed/ 5
Understanding the Relationship Between Stocks & Bonds https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/?utm_source=rss&utm_medium=rss&utm_campaign=understanding-relationship-stocks-bonds https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/#comments Mon, 24 Apr 2023 10:00:50 +0000 http://systemtradersuccess.com/?p=6825

Intermarket Analysis is the comparison of potentially related markets. For example:

  • S&P500 and 30 Year Treasury Bonds
  • 30 Year Treasury Bonds and Gold
  • S&P500 and Japanese Yen
  • Shanghai Composite Index and Aussie Dollar, etc.

The problem with using TradeStation for any Intermarket Analysis is the dreaded “You may not mix symbols with different delays in the same window” error code. That’s exactly what you’ll get if you try to add 30 Year Treasury Bond Futures (symbol US) to an Emini chart (symbol ES). The problem arises because the data comes from two different exchanges – CBOT for Bonds and CME for the Emini. TradeStation says:

Using ETFs for Intermarket Analysis

Tradestation limitation TradeStation does not allow you to plot two symbols in the same chart window when the amount of delay for the data is different. For example, one is delayed and one is real-time, or both are delayed but the exchanges providing the symbols’ data delay by different amounts of time. Otherwise, during the market session, you would see last prices on the current bar that are asynchronous (i.e. not simultaneous).
There are various ways around the problem – most of them quite complex and involving exchanging data between charts. However, I have found an easier solution. Read on for some tricks of the trade and useful equities vs. bonds indicators.

The solution to the problem is to find market symbols from the same exchange. With the explosion in the number of Exchange Traded Funds (ETFs) it is usually possible to find ones that track the underlying markets you are interested in.

For the Emini the obvious choice is the SPDR (symbol SPY) ETF traded on the AMEX exchange. For the Bond market the best choice is the iShares Lehman 20+ Year Treasury Bond ETF (symbol TLT), also traded on the AMEX exchange.

In the left panel of the chart above, daily data for the SPY and TLT symbols have been plotted quite happily on the same chart. However, in the right panel you get the dreaded “mix symbols” error code when plotting the ES and US symbols.

Are the Emini and Bond Markets Correlated?

The answer is sometimes yes and sometimes no. Correlation between the two markets can go as high as +60% (correlated) or a low as -60% (negatively correlated). You can add the in-built TradeStation correlation indicator on a chart of SPY and TLT to see this for yourself.

There are 2 opposing factors that drive the Bond and Stock markets at different times:

  • Interest rates might be falling and causing Bond prices to rise. The stock market might view the lower interest rates as encouraging for the economy and respond with higher stock prices. Alternatively, rising interest rates will cause Bond prices to fall and the stock market might view the tightening as negative for the economy and stock prices. In these cases correlation between the two markets is positive as they are moving in sync.
  • Stocks and Bonds are also alternative investment vehicles. If the stock market is rising strongly it might encourage Bond investors to cash out and put their money in the stock market and thereby cause Bond prices to fall. Alternatively, if there is a stock market panic investors might rush for the safety of Bonds and push Bond prices up. In these cases the two markets are negatively correlated as they are moving in opposite directions.

Measuring Differences Between the Emini and Bond Markets

With SPY and TLT plotted on the same chart we can compare price movements. A popular oscillator is shown in the screen grab above. In this case a ratio of SPY and TLT is calculated and this value is compared to a moving average of the ratio.

I prefer to use another measure of relative price movement. The screen grab below shows TradeStation EasyLanguage code for my Bond Oscillator. Instead of using the ratio of SPY and TLT prices it calculates the difference in percentage movement. This indicator is more like a momentum indicator.

The two indicators are comparead below. The Bond Oscillator (momentum type) is shown above and the Spread Oscillator (moving average type) is shown below. As you can see, the Bond Oscillator generates more defined turning points and is easier to trade.

The chart below shows the Bond Oscillator added to a 3 year chart of daily SPY prices. Spikes (up and down) in the oscillator show periods when the SPY is over or under-valued against Bonds. These periods can persist for some time – more so on the upside than the downside. To illustrate this a PaintBar has been added to highlight periods when the Bond Oscillator is above +5 (shown as white bars) and below -5 (shown as red bars).

Rather than use extreme readings on the Bond Oscillator to enter trades, it is safer to wait until the Oscillator crosses the zero line after an extreme reading. This prevents entering the trades too early.

Another trick I have found using this indicator is to wait for an extreme Oscillator reading and then look for a large daily move in the opposite direction in the Bond market. For example, Bonds are in a down trend, the Bond Oscillator goes above +5 and then Bonds have a one-day large up move. This pattern is signaling that professionals are taking profits at stock market highs and reaching for the safety of Bonds, hence driving Bond prices higher.

TradeStation EasyLanguage code for the PaintBar is shown in the screen grab below.

Bond Market Turning Points and the Emini

The last series of Bond Intermarket indicators are designed to highlight market turning points. I have found that there is a tendency for the Emini to lag the Bond market by approximately 20 days. To illustrate this point check out the chart below.

The SPY (Emini equivalent) is shown in the top of the chart and below it is TLT (Bond market equivalent) with closing prices shifted by 20 days. The red vertical lines show how turning points in the two markets (one delayed by 20 days) often line up. The neat thing about this analysis is that the Bond market turning points are known well in advance.

As an aside, this 20 day delay is also the reason I use 20 days as the look back period in the previous two indicators, Spread Oscillator and Bond Oscillator.

The chart below shows the state of the current Bond market (mid April 2007). A vertical line has been added showing where prices were 20 days ago. As you can see, since then the Bond market has declined steeply. If the 20 day relationship holds we may well see another turning point in the stock market. Only time will tell.

If you’re interested in following turning points in the Bond market you can use the indicator below to plot these vertical lines. The indicator allows multiple vertical lines of different frequencies to be plotted. Just vary the inputs NumLines (number of vertical lines) and Period (20 days, etc.). Make sure there’s enough back history in the chart to plot the lines though – if you ask for two 200 day lines and only have 300 days of history on the chart, the indicator won’t work!

I hope this article on Intermarket Analysis and equities versus bonds was helpful to you. You can download the indicator code used in this analysis.

— By Barry Taylor from Emini Watch

]]>
https://easylanguagemastery.com/indicators/understanding-relationship-stocks-bonds/feed/ 1
Does the Hammer-Hangman Pattern work on Futures markets? https://easylanguagemastery.com/indicators/does-the-hammer-hangman-pattern-work-on-futures-markets/?utm_source=rss&utm_medium=rss&utm_campaign=does-the-hammer-hangman-pattern-work-on-futures-markets https://easylanguagemastery.com/indicators/does-the-hammer-hangman-pattern-work-on-futures-markets/#respond Mon, 13 Mar 2023 10:00:45 +0000 https://easylanguagemastery.com/?p=532180

Table of Contents

  • A Tradesq Case Study
  • How to use it
  • Some examples
    • Nasdaq(@NQ) 180min:
    • VIX(@VX) 15min
    • Wheat(@W) 480min
    • High Grade Copper(@HG) 240m
  • Conclusion
  • A Tradesq Case Study

    I want to see that the simple pattern called Hammer or Hanging man works in future markets, but before beginning the test let’s see what the pattern is all about:

    Definition: Source https://www.thinkmarkets.com/

    How to use it

    Short trades: Hammer Pattern and Close are higher than the open. 

    Long trades: Hammer Pattern and Close is lower than the open.

    Now that we understand what a hammer pattern is, lets code in TradeStation Easylenguage the signals, the easiest way to do it, is to look at the resources that TradeStation already has: 

    Within the Prebuilt Studies, ShowMe Section, we can find: C_Hammer_HangingMan

    And it will show us every hammer (Green and Red dots) on the chart:

    Let’s have a look at the code that TradeStation has already developed:

    As we can see, there is already a function called C_Hammer_HangingManso let’s take advantage and proceed to create our code and implement the entry signals:

    Consideration for creating the code:

    • Ability to choose Long only, short only, or both.
    • Random Stop Loss and Profit Target exits.

    Let’s check that our code is working correctly: (Red dot should be a short entry and the green dot a long entry)

    We are ready to upload the code into Tradesq and select all 43 futures markets, the 11 timeframes, and the inputs range we want to test.

    Let’s see the results:

    We have many edges in the currencyenergygrainsindex, and metals sectors.

    Some examples

    Nasdaq(@NQ) 180min:

    VIX(@VX) 15min

    Wheat(@W) 480min

    High Grade Copper(@HG) 240m

    Note: All results include trading costs, slippage and commission.

    Conclusion

    This test used a really simple pattern with some random Profit Target and Stop losses, and was only intended to find good edges on the futures markets. Using Tradesq saved us a lot of time and effort in selecting the best results, which found edges on five (5) different sectors of the futures markets. It does not mean these are strategies ready to trade. Additional filters and robustness tests must be applied, but it is a terrific starting point. 

    >> Juan Fernando Gomez from blog.tradesq.net

    ]]>
    https://easylanguagemastery.com/indicators/does-the-hammer-hangman-pattern-work-on-futures-markets/feed/ 0
    Can Yet Another Improved RSI Boost Your Trading? https://easylanguagemastery.com/indicators/can-yet-another-improved-rsi-boost-your-trading/?utm_source=rss&utm_medium=rss&utm_campaign=can-yet-another-improved-rsi-boost-your-trading https://easylanguagemastery.com/indicators/can-yet-another-improved-rsi-boost-your-trading/#comments Tue, 19 Apr 2022 16:21:58 +0000 https://easylanguagemastery.com/?p=528001

    In the January 2022 issue of Technical Analysis of Stocks & Commodities magazine, we're presented with another indicator created by John Ehlers.

    Can this new trading indicator help us make more profitable trades?

    Let's find out!

    In this article, we're going to test this new indicator across several markets and timeframes to see if it can be used to build profitable trading systems.

    The article in question is, "(Yet Another) Improved RSI", which is found in the January 2022 issue. I'm not going to get into the details of the code or the theory behind John's math. You can read the article and download the code if you have a subscription to Technical Analysis of Stocks & Commodities magazine. I've been a subscriber for over 10 years and still recommend it.

    The article's main thrust is that this new RSI-based indicator (RSIH) is better than the original RSI because it's a lot smoother. Thus we should reduce whipsaws. FYI: The "H" in the indicator name stands for "Hann window," which is a mathematical concept that I certainly don't understand. 

    Below is an image of a price chart with the classic RSI indicator (upper pane) and the enhanced RSI with Hann windowing to become the RSIH (lower pane). The RSIH has a zero mean and is smoother than the classic RSI.

    Ehler's RSIH vs RSI

    Ehler's RSIH vs RSI. The classic RSI indicator (upper pane) and the enhanced RSI with Hann windowing to become the RSIH (lower pane). Image provided by Technical Analysis of Stocks & Commodities magazine.

    You'll notice the HRSI indicator has a horizon line at zero. This is the critical line that generates buy and sell signals. A long trade happens when the HRSI crosses above the zero line. A shoring signal occurs when it crosses below the zero line.

    Testing Long/Short/Both

    I updated the code provided by Technical Analysis of Stocks & Commodities magazine to test long and short independently and combined. I added an input value called LSB (long, short, both). As an input, I can use TradeStation's optimization feature to optimize the values of -1 to 1 in steps of 1.

    I'm not concerned about testing this new RSI against the traditional RSI. I want to see if this new indicator will work across different markets and timeframes. If it does, I can add it to my collection of indicators for consideration when building strategies.

    Testing Across Different Markets & Timeframes

    I'm going to use Tradesq to test across all available futures markets and time frames. Tradesq is an online tool that will allow you to test your code, and many popular futures markets and across 8 intraday timeframes. You can read more about Tradesq in the article, "How I Trade Like A Hedge Fund.

    Futures markets tested include: AD, BD, BO, BP, C, CC, CD, CL, CT, DX, EMD, ES, EU, FV, GC, GF, HE, HG, HO, JPY, KC, KW, LB, LE, MW, NG, NQ, OJ, PA, PL, RB, RR, RTY, S, SB, SF, SI, SM, TY, US, W, XG, YM.

    The timeframes tested include:

    • Daily
    • 1,440-minute
    • 600-minute
    • 360-minute
    • 240-minute
    • 180-minute
    • 120-minute
    • 60-minute

    I had Tradesq vary the lookback period from 5-60 in steps of 5. I also carried the LSB input from -1 to 1 in steps of 1 so I could test long and short trades independently and together.

    Best Performing Markets & Timeframes

    I took the results from Tradesq and loaded it into a spreadsheet to find the best performing markets. What defines the best performing markets? Good question.

    When Tradesq has completed all backtests it generates a table of the results. This table lists the markets tested and all time frames. See the image below.

    This table lists the number of "edges" found for each strategy based upon timeframe.

    This RSIH Edge Table does not display all the results from the backtest. Instead it's showing you filtered results. The filter applied to the backtest required that a backtest must...

    • Minimum number of trades 100
    • Minimum PnL: $5000
    • Minimum R2: .55
    • Minimum NP vs DD: 1.5

    These values may seem too low, and I would agree. Remember, we're testing an indicator, not a trading strategy. I would not expect a single indicator to create stellar results. I'm just looking for OK results knowing that this indicator would be combined with other indicators, price patterns, and filters to make a final system. In short, I'm just looking for an OK performance.

    Notice also in the RSIH Edge Table there are numbers in each cell. These represent the successful run that's passed the filter requirements. Remember, we tested different lookback periods. We also tested long trades only, short trades only, and both. These are our different runs.

    When a particular run passes the filter, this is called an "edge." The higher edges mean more backtests in that specific category passed the filter. So, many edges show that more backtest produced passing results. The different input values (our lookback period, for example) had a passing performance. 

    From these results I simply pick the top markets which have the highest "edges".

    1. HO (Heating Oil). This looks good on the daily chart and the 240-minute, 360-minute, 480-minute, and 600-minute intraday charts. It also appears that both long and short trades are viable so, be sure to test both.
    2. DB (Euro Bund). This held up on the daily chart and across several intraday timeframes including 120-minute, 180-minute, 240-minute, 360-minute 480-minute, and 600-minute. There is a clear bias to taking long trades only.
    3. YM (E-mini DOW). Surprisingly this looks best on a 180-minute chart. There is a long side bias, of course. 

    Below are equity curve of some of the better examples from the top three markets. Notice these equity curves are all based upon intraday charts with slippage and commissions deducted. In the description below each graph will find the net profit vs. drawdown metric (NPDD).

    RSIH YM 180m

    RSIH YM 180m - NPDD 2.9

    RSIH YM 180m

    RSIH HO 180m - NPDD 5.9

    RSIH DB 240m

    RSIH DB 240m - NPDD 2.9

    What Can This Be Used For?

    Overall, I don't think this particular indicator holds much of an edge. Only a handful of promising results stood out in all the markets and timeframes.

    This indicator should not be used as a stand-alone system. Like nearly all indicators, you can't just create a trading system from them. Some of the equity curves look like they almost could be trading systems. Instead, I would attempt to combine the RSIH with other indicators or filters. So, based on the Tradesq results, the RSIH could be the start of a trading system for the most promising markets and timeframes.

    Another option is to use this indicator as a possible regime filter to divide the market between bullish and bearish. I'll be adding the RSIH to my library of regime filters that I will use when I build strategies.

    ]]>
    https://easylanguagemastery.com/indicators/can-yet-another-improved-rsi-boost-your-trading/feed/ 6
    The Oscillator Indicator. Does It Work? https://easylanguagemastery.com/indicators/testing-an-oscillator-trading-indicator/?utm_source=rss&utm_medium=rss&utm_campaign=testing-an-oscillator-trading-indicator https://easylanguagemastery.com/indicators/testing-an-oscillator-trading-indicator/#comments Mon, 11 Oct 2021 10:00:00 +0000 https://easylanguagemastery.com/?p=26222

    I recently watched the video, "Oscillator Trading Indicator!, a trading system for all assets!", on the StatOasis channel. It's a simple trading concept based upon an oscillator indicator. When I see videos like this, I'm very skeptical. Most of what you see on YouTube will not work. Thus, it's time to put this concept to the test! 

    This article will duplicate the recommended trading method on the S&P futures market. Then I'll expand the trading idea to different markets and modify the strategy. Please watch the video for a solid overview of the indicator and trading strategy.

    Let's get going!

    The Indicator

    The baseline strategy is straightforward. First, you calculate two simple moving averages. The first is based upon the close. The second is based upon the open.

    We are looking for a trending market based upon the simple moving average of the close being higher than the simple moving average of the open. Makes sense. A rising market will likely have a higher closing price than the open.

    openSMA = average( Open, smaPeriod );
    closeSMA = average( Close, smaPeriod );
    BullishOscilator = closeSMA > openSMA;

    Adding A Trend Filter

    The YouTube host then recommends a trend filter to only take trades in the direction of the trend. This was accomplished by using two simple moving averages.

    longTrend1 = average( close, 100 ) > average( close, 100 )[1] and
       average( close, 100 )[1] > average( close, 100 )[2] and
       average( close, 100 )[2] > average( close, 100 )[3];
    longTrend2 = average( close, 100 ) > average( close, 100 )[10];

    You can see longTrend1 is bullish when the 100-period simple moving average has three consecutive higher values. The longTrend2 is bullish when the 100-period simple moving average is higher than itself 100 bars ago.

    The Baseline Strategy

    The baseline strategy code is below. You'll see that a profit target and stop-loss value are based upon the true average range. In this case, the 20-period moving average.

    Input:
    StopFactor(5),
    ProfitFactor(10),
    smaPeriod(9);

    Variables:
    BullishOscilator(False),
    longTrend1(False),
    longTrend2(False),
    StopLoss$(0),
    Target$(0),ATR(0),
    openSMA(0),
    closeSMA(0);

    openSMA = average( Open, smaPeriod );
    closeSMA = average( Close, smaPeriod );
    BullishOscilator = closeSMA > openSMA;
    longTrend1 = average( close, 100 ) > average( close, 100 )[1] and   average( close, 100 )[1] > average( close, 100 )[2] and average( close, 100 )[2] > average( close, 100 )[3];

    longTrend2 = average( close, 100 ) > average( close, 100 )[10];

    if BullishOscilator and longTrend1 and longTrend2 then
       Buy("LE") next bar at market;If ( MP <> 0 ) then
       Begin
          ATR = average( truerange,20 );
          StopLoss$ = round2fraction( ATR * Bigpointvalue * StopFactor );
          Target$ = round2fraction( ATR * Bigpointvalue * ProfitFactor );        
          Setstoploss(StopLoss$);
          Setprofittarget( Target$ );
       End;

    Trading Environment

    I will test the baseline code on the 60-minute E-mini S&P (@ES) market from 2007. Below are the assumptions used to generate the backtest:

    •  Starting account size of $50,000.
    •  Dates tested are from January 1, 2007 through January 29, 2021.
    • Trading 1 Contract.
    • $30 deducted for slippage and commissions per round trip.
    oscillator Indicator trades

    Click on image to enlarge

    Baseline Results

    In the YouTube video, the results looked decent. That's not too unexpected, as we're building a long-only strategy for the S&P, with a considerable upside bias. In particular, the upside bias has been strong for the past 10 years or so. Within the actual results from QuantOasis, they only test this strategy from 2009. I went back further and got this:

    oscillator Indicator EQ curve

    I marked the year 2009 in the graph above to show you when QuantOasis started their backtest. You can see it was right at the low point. Since 2009 the equity graph has been moving up. So, the original historical period may be a little deceiving. But since 2009, this strategy is doing really well.

    Average Profit Per Trade: $233 Net Profit vs Drawdown: 2.1 Annual Rate of Return: 7.57% Max Intraday Drawdown: $44,756.

    Removing Profit Target

    I also don't like that we have a profit target that is equal to the stop loss. That is, we're using 10 times the 20-period ATR. I want to let my profits run. I'm going to modify the code to exit a trade when one of the trend filters is no longer bullish.

    oscillator Indicator removing profit target

    Well, that did not help at all.

    Buying On Pull-Back

    In this test, I'm going to buy when the oscillator is bearish. I'll do this by taking trades when the closing SMA is less than the open SMA.

    openSMA = average( Open, smaPeriod );closeSMA = average( Close, smaPeriod );BullishOscilator = closeSMA < openSMA;
    oscillator Indicator buying on pull back

    These simple modifications did not show any improvement. Not to say you can't improve this strategy on the S&P but, you'll have to dig deeper.

    What About Other Stock Index Markets?

    Let's go back to the original code and test it on Mini DOW (YM) and Mini Nasdaq (NQ) markets. Slippage and commissions are deducted.

    oscillator Indicator on NQ

    @NQ

    oscillator Indicator on YM

    @YM

    We can see the NQ only performs well (very well!) over the most recent years. However, most of the time, you see the equity curve is hovering around the zero line. The YM market looks rather similar to ES. Overall, the stock index markets that I trade look similar. That is, the strategy has worked well for the last few years.

    What About Other Markets?

    Let's take a quick look at several other futures markets to get a feel for how this baseline strategy may work. Slippage and commission are taken into account.

    oscillator Indicator on US

    @US

    oscillator Indicator  on LH

    @LH

    oscillator Indicator on GC

    @GC

    oscillator Indicator EC

    @EC

    Conclusion

    With this simple test, we can't demonstrate that using this particular oscillator as the foundation of a strategy is not great. Sure, there is much more you could test, such as different timeframes, profit targets, stops, and other filters. But I like to see better performance without adding much to the basic idea. I don't see that in this case. The exception seems to be the stock index markets. Maybe. If you wanted to test this oscillator strategy idea, I would start with the stock index markets. Don't forget to try different intraday timeframes.

    If you want to learn to code in EasyLanguage so you can test trading ideas, just like we did in this article, then join me in the Coder Edition of my System Development Master Class.

    ]]>
    https://easylanguagemastery.com/indicators/testing-an-oscillator-trading-indicator/feed/ 5
    Can A Price Pattern Beat an Indicator? https://easylanguagemastery.com/indicators/price-pattern-or-indicator/?utm_source=rss&utm_medium=rss&utm_campaign=price-pattern-or-indicator https://easylanguagemastery.com/indicators/price-pattern-or-indicator/#comments Mon, 27 Sep 2021 10:00:16 +0000 http://systemtradersuccess.com/?p=7696

    I've seen people use simple price action patterns in place of inicators. For example,  Larry Connors and Cesar Alvarez really popularized the 2-period RSI. It works really well when createing mean-reversion strategies on the stock index markets. However, can you find a simple price pattern that will work just as well?

    Here is an idea, losing streaks, as an indicaor. For example, a two-day losing streak indicator simply buys the market after two consecutive losing days. Lets put it to the test. I’m going to focus on a longer term study of this indicator within the future’s market (ES). Free EasyLanguage code will be provided at the conclusion of this article.

    Mean Reversion

    As a reminder, the traditional two-period RSI indicator (RSI(2)) is an indicator we have used many times on this website. So I will not spend much time talking about it within this article. Overall, it’s primarily used on the stock index markets such as the S&P, as a method to determine an entry point for a mean reverting trading models. You can read more about the RSI(2) indicator and the trading models built from it by reviewing these articles:

    Two-Day Losing Streak Indicator

    I’m going to use EasyLanguage in order to build a strategy to test the effectiveness of this indicator. Again, the indicator simply highlights when the market has two consecutive losing days. To build this simple indicator I’m going to assume that a losing day is defined when the market closes below its open. We sell our position when we have just the opposite condition, a two-day winning streak.

    The trading rules provided in the original article are:

    • Buy at the open of next day if 2-Day Losing Streak
    • Sell at the open of next day if 2-Day Winning Streak

    The EasyLanguage code for the basic strategy will look something like this:

    Variables:
    BuySignal(false),
    SellSignal(false);
    BuySignal = ( Close < Open ) And ( Close[1] < Open[1] );
    SellSignal = ( Close > Open ) And ( Close[1] > Open[1] );
    If ( BuySignal ) then Buy("LE") next bar at market;
    If ( SellSignal ) then Sell("LX") next bar at market;

    Testing Environment

    Because you, the reader might want to build a trading model based upon this indicator, I’m going to break the historical data into two portions. An in-sample portion and out-of-sample portion. I will perform my testing for this article on the in-sample portion only. Thus, when I’m finished with my testing we’ll still have a good amount of data which can be used for out-of-sample testing.

    Before getting into the details of the results, let me say this: All the tests within this article are going to use the following assumptions:

    • Starting account size of $25,000
    • In-sample dates are from 1998 through December 31, 2012
    • One contract was traded per signal
    • $30 was deducted per round-trip for slippage and commissions

    Baseline Results

    Below is the baseline results over our in-sample historical segment. The maximum drawdown is a percentage of our starting equity, which is $25,000. Keep in mind that this study has no stops, thus some positions will hold through some very deep pullbacks before exiting. Again, we are testing the performance of an indicator at this point – not a trading model.

    Losing Streak

    Baseline

    Net Profit

    $25,800

    Profit Factor

    1.17

    Total Trades

    300

    %Winners

    63%

    Avg.Trade Net Profit

    $86.00

    Annual Rate of Return

    4.89%

    Max Drawdown(Intraday)

    79%

    Longer Losing Streak

    The first thing that I noticed in a two-day losing streak may not be deep enough. Two-day pullbacks are somewhat common. As pointed out in the original article, over the past few years a two-day pullback has been a great pattern. Market pullbacks have been shallow and these shallow pullbacks have been great entry points. But what about helping to ensure this indicator will work under different conditions?  Testing three or four days consecutive losing days may generate more profitable and/or tradable results.

    For past experience I know, in general, deeper pullbacks may provide a better profit vs risk. That is, the generated signals will be fewer in number but will also provide better rewards. So I modified the code and generated the following results based upon the number of days required in the losing streak before opening a new position. During this testing I did not modify the exit rules. They remained the same with two consecutive winning days acting as the exit trigger.

    Losing Streak

    Baseline

    3 Days

    4 Days

    Net Profit

    $25,800

    $32,290

    $31,925

    Profit Factor

    1.17

    1.37

    1.83

    Total Trades

    300

    177

    85

    % Winners

    63%

    64%

    71%

    Avg.Trade Net Profit

    $86.00

    $182.43

    $375.59

    Annual Rate of Return

    4.89%

    5.72%

    5.67%

    Max Drawdown (Intraday)

    79%

    66%

    64%

    As expected we see the number of trades decreases and the average profit per trade increases as we increase the number of losing days. Deeper pullbacks happen less often, but have larger payouts. The four-day losing streak has only 85 trades so I’m going to use the three-day losing streak during the remainder of my testing. This is a good compromise as a three-day pullback does appear to eliminate many shallow and unproductive pullbacks. Below is the equity graph for the three-day losing streak.

    Bull/Bear Regime Filter

    The next characteristic to explore is the difference between a bull and bear market. I’ll divide the market into two regimes based upon a 200-day simple moving average. The market will be “bullish” when price is trading above the 200-day SMA. The market will be “bearish” when price is below this moving average. Below is the results of the indicator in each of these regimes.

    Losing Streak Regime Streak

    Bull Only

    Bear Only

    Net Profit

    $14,542

    $29,530

    Profit Factor

    1.39

    1.57

    Total Trades

    94

    94

    % Winners

    69%

    62%

    Avg.Trade Net Profit

    $154.71

    $314.15

    Annual Rate of Return

    3.16%

    5.38%

    Max Drawdown (Intraday)

    54%

    73%

    Surprisingly, at least to me, we see better performance with the bear market. Overall, both the bull and bear regimes are profitable. The bear regime does suffer from larger drawdowns but it also has the biggest rewards. Notice that both regimes also have the same number of trades. I checked this a couple of times and it does appear to be correct. Given this result, I will not include a regime filter as we test our final modification I wish to test.

    5-Day SMA Exit

    The 5-Day SMA Exit closes a position once price closes above a 5-day simple moving average. This exit is often used with the RSI(2) system and it’s worth testing here as well. Below are the results of this test vs our baseline. As a reminder, the Baseline column represents the 3-day losing streak with a 2-day exit.

    Losing Streak Exit Test

    Baseline

    SMA Exit

    Net Profit

    $32,290

    $43,475

    Profit Factor

    1.37

    1.68

    Total Trades

    177

    205

    % Winners

    64%

    67%

    Avg.Trade Net Profit

    $182.43

    $212.07

    Annual Rate of Return

    5.72%

    6.95%

    Max Drawdown (Intraday)

    66%

    30%

    The power of a good exit! By changing the exit to our 5-day simple moving average we have significantly improved the performance. All metrics have improved. Notice the significant reduction in drawdown. This is huge.

    So how does this hold up against the 2-period RSI indicator? Let’s see…

    RSI(2) vs Losing Streak

    Below is the results of using a two-period RSI with a threshold of 10 vs our 3-day losing streak. Both methods exit when price crosses the 5-day SMA.

    Losing Streak vs RSI(2)

    Baseline

    RSI(2)

    Net Profit

    Cell

    $45,960

    Profit Factor

    1.68

    1.68

    Total Trades

    205

    183

    % Winners

    67%

    68%

    Avg.Trade Net Profit

    $212.07

    $251.15

    Annual Rate of Return

    6.95%

    7.19%

    Max Drawdown (Intraday)

    30%

    68%

    So which one is better? They are very similar in most of the metrics. The maximum drawdown is a lot higher with the RSI(2) system. Again, neither of these tests utilize a stop.

    Overall, these are very interesting results. It looks like a simple price pattern could be used as an effective replacement for a short-term indicator. I encourage you to perform your own testing to see if this simple price pattern indicator could be used in your own trading. Maybe you can test what happens if you combine the price pattern with the RSI.  Below you will find the EasyLanguage code for code used in this study.

    ]]>
    https://easylanguagemastery.com/indicators/price-pattern-or-indicator/feed/ 3