You are on page 1of 56

THE TRADERS’ MAGAZINE SINCE 1982 www.traders.

com APRIL 2023

JUST IGNORE THEM


Undersampling the data
as a smoothing technique 8

REPATRIATION
Using the flow of foreign
investment money 14

MINING PATENT
DOCUMENTS
Looking for trading ideas 18

TRADING GLD IN THE AGE


OF ZERO COMMISSION
Trading rules you can use 22

INTERVIEW
John F. Ehlers 28

THE “DAY DROP”


PATTERN
Filtering trades with a
downtrend pattern 36

APRIL 2023
Subscribe Or Renew Today!
A subscription to Technical Analysis of Stocks & Commodities magazine
gets you so much more than just a magazine:

• Full access to our Digital Edition


The complete magazine as a PDF
you can download.

• Full access to our Digital Archives


Every article since 1982!

• Complete access to Working Money


The information you need to invest
smartly and successfully.

• Access to Traders.com Advantage


Ideas, insights, evaluations, tips
and techniques that can help you
trade smarter.

8999
1 year.........................
$

2 years.................... 149
$ 99

3 years.................... 199
$ 99

Or try our best value subscription:

PROFESSIONAL TRADERS’ STARTER KIT


5-year subscription to S&C magazine that includes everything above
PLUS a free* book, Charting The Stock Market: The Wyckoff Method,
$
29999
all for a price that saves you $150 off the year-by-year price! only around
*Shipping & handling charges apply for foreign orders. $$
5 a month!

Visit www.Traders.com to find out more!


Email: Circ@Traders.com • Phone: 206-938-0570 facebook.com/STOCKSandCOMMODITIES @STOCKSandCOMM
Can you imagine winning the
Stocks & Commodities Readers’ Choice
Award for 30 consecutive years?

Best Standalone
Analytical Software
in it’s price category
1993-2023

We can.

Get your free trial at MetaStock.com/TASC

This is neither a solicitation to buy or sell any type of financial instruments, nor intended as investment recommendations. All investment trading involves multiple substantial risks of monetary loss. Don’t
trade with money you can’t afford to lose. Trading is not suitable for everyone. Past performance, whether indicated by actual or hypothetical results or testimonials are no guarantee of future performance
or success. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFITS OR LOSSES SIMILAR TO THOSE SHOWN. IN FACT, THERE ARE FREQUENTLY SHARP DIFFERENCES
BETWEEN HYPOTHETICAL PERFORMANCE RESULTS OR TESTIMONIALS AND THE ACTUAL RESULTS SUBSEQUENTLY ACHIEVED BY ANY PARTICULAR TRADING PROGRAM. Furthermore, all internal and external
computer and software systems are not fail-safe. Have contingency plans in place for such occasions. MetaStock assumes no responsibility for errors, inaccuracies, or omissions in these materials, nor shall
it be liable for any special, indirect, incidental, or consequential damages, including without limitation losses, lost revenue, or lost profits, that may result from reliance upon the information presented.
CONTENTS APRIL 2023, VOLUME 41 NUMBER 5

6 Explore Your Options Raytheon. Kevin Davey interviewed


by Jay Kaeppel him to discuss his trading and
The Traders’ MagazineTM Got a question about options? analysis approach, his thoughts
on where quantitative financial
FEATURE ARTICLE analysis is heading, and his long
EDITORIAL
8 Just Ignore Them and meaningful contribution to
TIPS
editor@traders.com
by John F. Ehlers the fields of technical analysis and
Editor in Chief Jack K. Hutson
To avoid whipsaw trades, traders quantitative financial analysis.
Production Manager Karen E. Wasserman
smooth the market data to get
Graphic Designer Wayne Shaw
better and less-frequent trading 33 Market Rap
Webmaster Han J. Kim
signals. But smoothing filters have by Emilio Tomasini
Contributing Editors John Ehlers,
drawbacks, such as introducing lag. “Unserious” thoughts on serious
Anthony W. Warren, PhD.
Here is an effective solution, and topics in finance.
Contributing Writers Thomas Bulkowski, Martin
it’s simpler than you might expect.
Pring, Barbara Star, Markos Katsanos, Leslie N. 34 Futures For You
Masonson, Karl Montevirgen, Kevin Davey
14 Repatriation by Carley Garner
by Perry J. Kaufman Here’s how the futures market
Traders are always looking for really works.
OFFICE OF THE PUBLISHER
tradable patterns in the data. Here is
Publisher Jack K. Hutson
a pattern used by currency traders
36 The “Day Drop” Pattern
Industrial Engineer Jason K. Hutson by Andrea Unger
that you may not have heard of and
Project Engineer Sean M. Moore
that could provide an edge. Here is a price pattern you may
ADVERTISING SALES not have heard of that you can use
4757 California Ave. S.W. 18 Mining Patent Documents as a trade filter to improve system
Seattle, WA 98116-4499
For Trading Ideas performance. In this article, we’ll
206 660-8577 Fax 206 938-1307
advert@traders.com by Gregory Aharonian step through the process of writing
Did you know that patent some code to develop a trading
National Sales Manager Edward W. Schramm
documents can be a good source strategy, we’ll test adding some
ESchramm@traders.com
of trading ideas for stocks, options, rules and conditions—including
CIRCULATION
and bonds? Find out how you may the filtering of trades using this
Subscription & Order Service 1 800 832-4642
be able to find and use some of the price pattern—and we’ll review
1 206 938-0570 Fax 1 206 938-1307
information. the resulting system performance
circ@traders.com
metrics.
Subscription Manager Sean M. Moore
22 Trading GLD In The Age Of
WEBSITE Zero Commission, Part 1 42 Average True Range Breakouts
by Ken Calhoun
http://www.traders.com
by Massoud Metghalchi, PhD,
The ATR was originally designed
Staff members may be emailed using first initial and Linda A. Hayes, PhD
to indicate when daily ranges are
plus last name plus @traders.com
Come follow along on a quest to
increasing or decreasing. Here,
discover profitable trading rules you
we show you how you can use the
can use, based on a few technical
Author­i­za­tion to pho­to­copy items for inter­nal or per­sonal indicator to spot upside breakouts.
use, or the inter­nal or per­sonal use of spe­cific cli­ents, is granted indicators. In this two-article series
by Tech­ni­cal Anal­y­sis, Inc. for users reg­is­tered with the Cop­y­ focusing on two different markets, 54 Algo Q&A
we’ll conceptualize some strategies
right Clear­ance Cen­ter (CCC) Transactional Reporting Serv­ice,
pro­vided that the base fee of $1.00 per copy, plus 50¢ per by Kevin J. Davey
page is paid directly to CCC, 222 Rosewood Drive, Danvers, and technical trading rules, test Got a question about system or algo
MA 01923. Online: http://www.copyright.com. For those them, and then compare the results. trading?
Here in part 1, the focus is on
organ­iz­ a­tions that have been granted a photocopy license
by CCC, a sep­ar­ ate sys­tem of pay­ment has been arranged.
The fee code for users of the Transactional Reporting Serv­ice trading a popular gold market ETF.
is: 0738-3355/2023 $1.00 + 0.50. DEPARTMENTS
Sub­scrip­tions: USA: one year (13 issues) $89.99;
Magazines shipped outside the US require additional post­
INTERVIEW 41 Trade News
age as follows: Canada, US$15 per year; Europe, US$25.50 28 A Conversation With John Ehlers 44 Traders’ Tips
per year; all other countries US$39 per year. Sin­gle copies of by Kevin J. Davey 50 Advertisers’ Index
50 Editorial Resource Index
After four decades of providing
most past issues from the cur­rent year are avail­a­ble pre­paid
at $8 per copy. Prior years are avail­a­ble in book format (with­ 51 Futures Liquidity
out ads) or digitally from www.traders.com. USA funds only. products, services, and education 52 Classified Advertising
Washington state res­id ­ ents add sales tax for their locale. to traders through his company, 52 Traders’ Resource
MESA Software, John F. Ehlers
VISA, MasterCard, AmEx, and Discover accepted. Subscrip­ 53 Books For Traders
tion orders: 1 800 832-4642 or 1 206 938-0570.
Technical Analysis of Stocks & Commodities™, The has announced his retirement.
Traders’ Magazine™, is prepared from information believed Ehlers, a Contributing Editor to
Stocks & Commodities since
to be reliable but not guaranteed by us with­out further
verification, and does not purport to be complete. Opinions
expressed are subject to revision without notification. We nearly the magazine’s launch, is
are not offer­ing to buy or sell securities or commodities a pioneer in the use of cycles and
digital signal processing (DSP)
discussed. Technical Anal­ysis Inc., one or more of its officers,
and authors may have a position in the securities discussed
herein. technical analysis. Formerly, he
The names of products and services presented in this was an engineering fellow for
magazine are used only in an editorial fashion, and to the
benefit of the trademark owner, with no intention of infring­ This article is the basis for
n Cover: Victoria Novak/moxumbic/E-ART/ TIPS
ing on trademark rights. Traders’ Tips this month.
Shutterstock

Copyright © 2023 Technical Analysis, Inc. All rights reserved. Information in this publication must not be stored or reproduced in any form without written permission from the publisher. Technical Analysis of Stocks & Commodities™
(ISSN 0738–3355) is published monthly with a Bonus Issue in March for $89.99 per year by Technical Analysis, Inc., 4757 California Ave. S.W., Seattle, WA 98116–4499. Periodicals postage paid at Seattle, WA and at additional mailing
offices. Postmaster: Send address changes to Technical Analysis of Stocks & Commodities™ 4757 California Ave. S.W., Seattle, WA 98116–4499 U.S.A. Printed in the U.S.A.

4 • April 2023 • Technical Analysis of Stocks & Commodities


Simple. Worldwide.
Stock trading.

The IBKR GlobalTrader app makes it easy to trade


stocks worldwide. Open your account in minutes
and enjoy commission-free trading on US stocks and ETFs and access
over 80 stock markets in the US, Canada, Europe, and Asia.

The app is packed with powerful functionality, including:

Scan the globe for Trade in Deposit in your Free educational


undervalued stocks fractions local currency resources

Start your FREE TRIAL today.


Download your app by scanning the
QR code and put the world in the palm
of your hand.

Download on the App Store Get it on


for iPhone and iPad Google Play

ibkr.com/sc-trader

Interactive Brokers LLC - member NYSE, FINRA, SIPC.


Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations. 02-IB22-1530CH1522
Explore Your Options
GOT A QUESTION ABOUT OPTIONS?
Jay Kaeppel has over three decades of experience in the options markets. He
was a head trader for a CTA firm, an options trading software developer,
and was a portfolio manager for an investment management firm. He is
presently Senior Research Analyst for Sentimentrader.com. He is the author
of several books, including The Four Biggest Mistakes In Option Trading;
The Option Trader’s Guide To Probability, Volatility, And Timing; and
Seasonal Stock Market Trends. Send your questions or topic suggestions
to Jay Kaeppel at jay@sentimentrader.com. Selected questions will appear
in a future issue of S&C.
Jay Kaeppel

IRON CONDORS If you trade options close to the price it will expire in the money. While
What exactly is an iron condor? of the underlying, you can take in a this is not mathematically correct, it
An iron condor involves selling an lot of option premium, however, the does provide a reasonable estimate.
out-of-the-money call and put and odds are generally very high that the So a call option with a delta of 15 is
simultaneously buying another call underlying will move outside your thought to have a 15% probability
at a higher strike price and buying profit range. On the other hand, if you of expiring in-the-money (which is
another put at a lower strike price. trade options that are extremely far- bad for the option seller) and an 85%
The idea is to create a “profit range.” out-of-the-money, you have a higher probability of expiring out-of-the-
As long the underlying security price probability of the options expiring money (i.e., worthless).
remains within the profit range, the worthless, but your returns can be
trade will make money. In a perfect microscopic. Which expiration to use?
world, the underlying security stays Here too, we must consider the
within the profit range, all options An iron condor involves tradeoff. Selling longer-term options
expire worthless, and the trader keeps “selling premium,” and offer the potential to take in more
all the premium received when the option premium, however, they also
trade was entered.
the maximum profit is give the underlying security more
In choosing and trading an iron equal to the premium time to move out of the profit range.
condor, there are a variety of im- received when the In addition, the bulk of option time
portant factors to consider. Gener- trade is entered. decay occurs in the 30 days leading
ally speaking, they can be boiled up to expiration. If we go too far out
down to: While I’ve already stated that in time, we will have to wait a long
there are no correct answers, for the time before time decay really begins
• Which strike prices to trade? purposes of this piece, I am going to work in our favor.
• Which expiration to use? to lay out some example guidelines So, we will look for options with 15
• What to do if the underlying as follows: to 45 days left until expiration.
moves too far?
• Sell a call option with a delta of 15 Other factors to
The reality is that there are no or less and sell a put option with consider
“correct” answers to these questions. a delta of −15 or higher An iron condor involves “selling
The key is that your answers to • Buy a call option with a delta premium,” and the maximum profit
these questions comport with your between 5 and 10 and buy a put is equal to the premium received
own objectives regarding risk and option with a delta between −10 when the trade is entered. The higher
reward. and −5 implied option volatility is for the
underlying security, the more time
Which strike price to There is nothing magic about these premium there is built into the op-
trade? values. They are chosen to try to put tions, thus the higher the profit poten-
Ideally, you want the best tradeoff the odds of success in our favor. In tial. One word of caution, though. If
between potential return and the this case, we are looking at an options we limit our search only to securities
probability of achieving that return. delta as roughly the probability that presently trading at extremely high
6 • April 2023 • Technical Analysis of Stocks & Commodities
Explore Your Options

OPTIONSANALYSIS.COM
FIGURE 1: TRADE PARTICULARS, IRON CONDOR EXAMPLE. Iron condors involve selling an out-of-the-money call and put while simultaneously buying
another call at a higher strike price and buying another put at a lower strike price.

IV levels, we will
typically focus on
stocks making large
price swings (which
is causing the high
IV in the first place).
This is not what we
want when selling
an iron condor. So,
regarding IV, sim-
ply make sure that
IV is not at rock bot-
tom levels and that
there is some worth-
while premium to
be earned.
In a perfect world, FIGURE 2: RISK CURVES, IRON CONDOR. Here you see the risk curves for the example trade in Figure 1. The trade has 35 calendar
the stock in question days until option expiration. The maximum profit on the trade would be $60 or 13.6% of capital risked.
will remain in a
quiet trading range during the life of announcement prior to the expiration 2,000
an iron condor trade. Some traders date of the options you plan to trade. • No earnings announcement in the
argue that one way to accomplish Few things can cause a stock to make upcoming 45 days
this is to purposely look for stocks a surprisingly large move like an • IV rank > 15% (0% = IV at a
or indexes that are already mired in a earnings announcement. So they are two-year low, 100% = IV at a
trading range. This makes sense, but best avoided. two-year high)
again, a word of caution. No trading • Call and put sold are $10 to $14
range lasts forever, so if you trade a Scanning for iron condors away from underlying price
security that has been in an extended Using www.optionsanalysis.com, I • Difference between call and put
trading range, one could argue that scanned for iron condors using the strikes sold is $20 to $25
it is that much closer to the next following criteria on 12/16/2022:
breakout and big move. Example trade
It is also ideally preferable not to • Stocks with an average options The top trade using the scan described
trade an iron condor on a security bid/ask spread <= 2%
that has an upcoming earnings • Average daily option volume > Continued on page 21
April 2023 • Technical Analysis of Stocks & Commodities • 7
DIGITAL SIGNAL PROCESSING

Undersampling The Data As A Smoothing Technique

Just Ignore Them


To avoid whipsaw trades, traders smooth the market ponents in the spectrum are directly correlated with
data to get better and less-frequent trading signals. their wavelength. If you shorten the wavelength by
But smoothing filters have drawbacks, such as in- a factor of 2, then you can expect the cycle ampli-
troducing lag. Here is an effective solution, and it’s tude to be reduced to half amplitude. So, increasing
simpler than you might expect. the sampling rate necessarily leads to a lower gross

H
profit per trade because the data swings are less, all
igh-frequency components in the data other things being equal. When carried far enough,
spectra—that is, “noise” in the data or all transaction costs of slippage and commission can
the extra wiggles on the chart that distract exceed your average gross profit per trade.
from price direction—are the bane of trad- The bottom line is there is a “sweet spot” for sam-
ers because they often lead to whipsaw trades. The pling rate that depends on the trader’s technique.
usual approach is to reduce their effect on trading
rules through the use of smoothing filters, such as A new approach to smoothing
moving averages. In the past I have introduced more No matter the sampling rate, we still have to get rid of
effective smoothing filters, like the SuperSmoother those pesky high-frequency components. My radical
infinite impulse response (IIR) filter and the Hann proposal is this: Simply ignore them. But ignoring the
windowed finite impulse response (FIR) filter. high-frequency components doesn’t come for free.
I now propose to eliminate those high-frequency Sampled data is different from continuous data
components with a new approach. because its shortest possible wavelength has exactly
two samples per cycle. This is called the Nyquist
Data sampling rate frequency. Sampled data simply does not contain
Market data are sampled data. For example, using information whose wavelengths are shorter than that
daily data, we get only one sample per day. Regard- of the Nyquist frequency. Of course, those spectrum
less of whether that sample is the close representing components are still there in continuous data. The
the data for that day, the average of the high, low, sampling process handles those shorter wavelength
and close, or any other combination of available components by aliasing. That is, the shorter wave-
statistics. We still only get one sample per day. The length components are simply folded back into the
sample rate can be increased. For example, trad- observable spectrum.
ing intraday on 15-minute bars is not uncommon. Figure 1 illustrates the principle of aliasing, where the
There is a temptation to increase the sample rate cyan line is sampled every 1.25 cycles. The wavelength
VICTORIA NOVAK/MOXUMBIC/E-ART/SHUTTERSTOCK

further, using five-minute bars, one-minute bars, or of the cyan line is shorter than the Nyquist frequency,
even tick bars. The temptation is caused by confus- and so it appears that the signal is the blue line. The
ing resolution with accuracy. More intricate market samples exactly fit both the cyan and blue sine waves,
activity is revealed by the higher sampling rate, but but the blue line has a longer wavelength than the
the increased resolution doesn’t necessarily lead to Nyquist frequency. Thus, in this case, the observable
greater trading profits. The reason for this is that the spectrum component is the blue line because it is the
market data is fractal and has the spectral density of aliased version of the cyan line.
pink noise. That is, the amplitude of the cycle com-

by John F. Ehlers
April 2023 • Technical Analysis of Stocks & Commodities • 9
It is a workable approximation that the cycle amplitude is
halved every time the cycle spectrum component wave-
length is doubled. So, if we sample once every five days,
a five-day cycle period component is aliased back into our
observable spectrum at half amplitude, a 2.5-day period
component is aliased back into the observable spectrum
at one quarter amplitude, and so on. So, the aliased energy
falls off rapidly compared to the desired signal energy.
Further, market data is nonstationary and so the aliased
FIGURE 1: ALIASING. The principle of aliasing is demonstrated here. That is, signals energy does not fold back coherently. Rather, it is simply
become indistinguishable—or aliases of one another—when sampled. Here, the a little more noise added to the already noisy signal. The
cyan line is sampled every 1.25 cycles of the market data. The samples exactly fit end result is that aliasing is hardly noticed, as a practical
both the cyan and blue sine waves, but the blue line has a longer wavelength matter.
than the Nyquist frequency. In sampled data, as opposed to continuous data, the
shortest possible wavelength has exactly two samples per cycle.
Less lag
The undersampled data also undergoes a quantization
Market data is fractal lag that is half the quantization step size. (“Quantization”
The reason that we can ignore the high-frequency com- means to subdivide into small but measurable increments.)
ponents in market data is because market data is fractal. If daily data is sampled every five days, the induced lag is
2.5 days. This lag is much shorter than that of smoothing
filters that reject cyclic components longer than the Nyquist
rate (10 days) if we were using daily samples.
A practical application of smoothing by undersampling
Undersampling removes the high- is shown in Figure 2. The undersampled data is further
frequency components in price data. smoothed by a six-period Hann filter and a 12-period Hann
filter to be the equivalent of a double moving average. It is
Elimination of these components apparent that the high-frequency components in the data
is done with less lag than that of have been removed by the combination of undersampling
conventional smoothing filters. and Hann-windowed FIR filters.

CODE FOR UNDERSAMPLED DOUBLE MOVING AVERAGE, IN EASYLANGUAGE


The high-frequency components in the market data, period Hann filter and a 12-period Hann filter to be the
which contribute to noisiness to the data, can be effec- equivalent of a double moving average.
tively removed by a combination of undersampling and The Hann filter referenced here is written as a function,
Hann-windowed finite impulse response (FIR) filters. and that function is provided in the next sidebar titled
This code samples the data every five bars, effectively. “Code For $Hann Function, In EasyLanguage.”
This undersampled data is further smoothed by a six-
{ Sample = Sample[1];
Undersampled Double MA Indicator
(c) 2022 John F. Ehlers //Sample every five days
} If CurrentBar / 5 = IntPortion(CurrentBar / 5) Then Sample =
Close;
Inputs:
Fast Length(6), //Find Fast Average using Hann FIR filter
Slow Length(12); FastAvg = $Hann(Sample, FastLength);
//Find Slow Average using Hann FIR filter
Vars: SlowAvg = $Hann(Sample, SlowLength);
Sample(0),
Fasting(0), Plot1(FastAvg, "", magenta, 6, 6);
Slowing(0); Plot2(SlowAvg, "", blue, 6, 6);

10 • April 2023 • Technical Analysis of Stocks & Commodities


TRADESTATION
FIGURE 2: SMOOTHING BY UNDERSAMPLING (DAILY MARKET DATA). The data is sampled here every five bars, effectively. The undersampled data are
further smoothed by a six-period Hann filter and a 12-period Hann filter to be the equivalent of a double moving average. The high-frequency components in the
data are removed by the combination of undersampling and Hann-windowed FIR filters. You can see that the two moving averages, the blue and indigo lines,
are very smooth.

Implementing the concept naming of the function is important.


EasyLanguage code to produce the double MA indicator Intraday data can also be smoothed by undersampling.
is given in the sidebar, “Code For Undersampled Double The method to do this is described with reference to the
Moving Average, in EasyLanguage.” sidebar, “Code For Undersampled Intraday Double Mov-
The sampled value is the same as the previous sampled
value except when the integer portion of the current bar
divided by 5 is exactly equal to the current bar divided
by 5. In this case, the sampled value is assigned the value The market data is fractal
of the closing price. Thus, the data is effectively sampled and has the spectral density
every five bars. The Hann filter is written as a function,
and the function is given in the sidebar, “Code For $Hann of pink noise.
Function, In EasyLanguage.” Note that the dollar sign in

CODE FOR $HANN FUNCTION, IN EASYLANGUAGE


The Hann filter is written here as a function, referenced sign in naming of the function is important.
in the code elsewhere in this article. Note that the dollar

{ coef(0),
Function: Hann Windowed Lowpass FIR Filter Filt(0);
(c) 2021-2022 John F. Ehlers
} Filt = 0;
coef = 0;
Inputs: For count = 1 to Length Begin
Price(numericseries), Filt = Filt + (1 - Cosine(360*count / (Length +
Length(numericsimple); 1)))*Price[count - 1];
coef = coef + (1 - Cosine(360*count / (Length + 1)));
Vars: End;
count(0), If coef <> 0 Then $Hann = Filt / coef;

April 2023 • Technical Analysis of Stocks & Commodities • 11


FIGURE 3: SMOOTHING BY UNDERSAMPLING (INTRADAY MARKET DATA). The undersampling technique can also be used for intraday data, as demonstrated
here. The data is sampled here every four bars, effectively. Because opening gaps are removed from the data and the gap removal is cumulative, the intraday under-
sampled data is offset from prices.

ing Average, In EasyLanguage.” Intraday data for index


futures is available as a “day session” that runs from 6:30
More intricate market activity am to 1:15 pm Pacific Time (you will need to adjust for
is revealed by the higher your time zone). I have assumed 15-minute bars are used,
sampling rate, but the increased so the first bar of the day is 645. At the close of the first
resolution doesn’t necessarily bar of the day, the gap value is computed as the differ-
lead to greater trading profits. ence of the closing price and the previous value of degap.

Continued on page 43

CODE FOR UNDERSAMPLED INTRADAY DOUBLE MOVING AVERAGE, IN EASYLANGUAGE


The technique of smoothing data by undersampling the data. The code to do that is provided here. The data is
data can be applied to intraday data as well as to daily sampled here every four bars, effectively.

{ If Time = 645 Then Begin


Undersampled Intraday Double MA Indicator Gap = Close - Degap[1];
(c) 2022 John F. Ehlers Degap = Close - Gap;
} End;
If Time = 800 or Time = 900 or Time = 1000 or Time = 1100
Inputs: or Time = 1200 or Time = 1315 Then Degap = Close - Gap;
BegDate(1221117),
FastLength(20), If Date < BegDate Then Degap = Close;
SlowLength(40);
//Find Fast Average using Hann FIR filter
Vars: FastAvg = $Hann(Degap, FastLength);
Gap(0),
Degap(0), //Find Slow Average using Hann FIR filter
FastAvg(0), SlowAvg = $Hann(Degap, SlowLength);
SlowAvg(0);
Plot1(FastAvg, "", magenta, 6, 6);
Degap = Degap[1]; Plot2(SlowAvg, "", blue, 6, 6)

12 • April 2023 • Technical Analysis of Stocks & Commodities


thinkorswim : ®

a dynamic suite of
trading platforms
designed for every
kind of trader.

From the advanced tools of thinkorswim® desktop to the streamlined interface of thinkorswim
web to the convenience of thinkorswim mobile, thinkorswim offers a range of trading
experiences for a range of trading needs. So no matter where you are on your trading journey
or how you like to trade, the thinkorswim suite of trading platforms is designed for you.

Scan the QR code to learn more

All investing involves risks, including loss of principal. TD Ameritrade, Inc., member FINRA/SIPC, a subsidiary of The Charles Schwab Corporation.
© 2022 Charles Schwab & Co., Inc. All rights reserved.
Using The Flow Of Foreign Investment Money

Repatriation
Traders are always looking for tradable patterns in the 4. Seasonal trades in stocks recognize that some com-
data. Here is a pattern used by currency traders that you panies, such as travel and leisure, profit from more
may not have heard of and that could provide an edge. activity during the summer and winter holidays.
5. Volume is highest near the open and close, and

By
by Perry J. Kaufman lowest in the middle of the day.

now, we know that the stock market is Traders also mine data looking for new patterns, or
a complex vehicle for investing. Each patterns that persist for only a short time based on the
person or institution has their own reason current economic conditions. Investors react differently
for buying and selling and their own in bull markets than in bear markets.
timing. Yet viewed as a bigger picture,
there are patterns that emerge that traders have been Repatriation
able to exploit. The patterns can be either technical or There is a pattern that is rarely recognized except by
fundamental, or both. For example: currency traders, and it is called repatriation. It is the
flow of foreign investment money back to the country
1. “Taylor’s 3-Day Trade” looks for reversals after of origin.
three days of price moves in one direction. re·pa·tri·a·tion | rēιpātrēιāSH(ə)n, rēιpatrēιāSH(ə)n |
PANUWATCCN/SHUTTERSTOCK

2. “Up on Monday, down on Tuesday” recognizes that noun


market analysis over the weekend results in larger 1. the return of someone to their own country.
moves on Monday that are moderated on Tuesday. “the voluntary repatriation of refugees”
3. Seasonal trades in agriculture capitalizes on plant- 2. the sending of money back to one’s own country.
ing and harvest patterns. “the repatriation of profits by foreign investors”
14 • April 2023 • Technical Analysis of Stocks & Commodities
FUTURES TRADING

FIGURE 1: SAMPLE PROGRAM OUTPUT. Here you see monthly returns of the euro currency futures (CU) when the S&P closed higher three days before the end
of the month. Cells with zero correspond to months in which the S&P closed lower.

It doesn’t seem as though there should be a pattern to tion on the close two days before the end of the month
that flow because investors enter and exit the markets and exit on the close of the month. We hold the trade
every day for any number of reasons. But there is a pat- for only two days.
tern driven by large non-U.S. investment firms. It goes
this way: Selecting higher S&P returns
The program allows you to test the day on which you
When foreign money is invested in the U.S. stock market, measure the index returns, then enter on the close of that
and that market is profitable for the current month, they day. We use the close of the third day back to allow the
repatriate those profits at the end of the month. trade to be held for two full days.
It also allows you to set a filter for the index returns.
We can recognize when this occurs by measuring That is, you may want to capture the currency returns
the returns of the S&P, the NASDAQ, or the small-cap if the S&P is positive by any amount on the third day
index. If they are profitable above a certain return, then before the month-end. But we also want to see what hap-
the currencies of the foreign investors will be stronger pens if we are more selective. Do the returns improve if
on the last day of the month because they need to buy we require the S&P to close higher by 1% or 2%? The
those currencies to repatriate the funds. To move money higher our threshold, the fewer the cases.
from the U.S. back to, for example, Europe, they need Figure 1 shows the table produced by the program
to sell the dollar and buy the euro. That goes for other using three days back and any S&P positive return. The
currencies as well. cells with zero correspond to months in which the S&P
We don’t know which parts of the U.S. market have closed lower.
been targets of foreign investments, so we will look at Figure 2 shows the monthly returns of the S&P–euro
all three stock indexes mentioned above. combination using S&P return filters of 0%, 1%, and 2%.
It shows that either a 1% or 2% filter is an improvement
A program to test the theory over no filter.
I wrote a program on my own platform so that I could
test multiple index and currency markets at one time. In
sidebar “Repatriation Pattern Trade, In EasyLanguage When foreign money is invested
Code,” you will find a program that allows you to test in the US stock market, and the
one combination at a time. US stock market is profitable
You enter the equity index market as data2 and the for the current month, they
currency as data1. We are interested in the profits from
the currency if the index market has returned greater
repatriate those profits at the
than some percent as of two days before the end of the end of the month.
month. We then take a long currency/short dollar posi-
April 2023 • Technical Analysis of Stocks & Commodities • 15
REPATRIATION PATTERN TRADE, IN EASYLANGUAGE CODE
This code allows you measure the returns of an equity totalmonth[ix] = totalmonth[ix] + months[ix];
index and test for a potential currency trade to enter two totalPL = totalPL + months[ix];
days before the end of the month. The code allows you // monthly PL
to set a threshold for the index returns to filter trades. print(File("c:\TradeStation\Repatriation_
Currency data is entered as data1 and equity index data Monthly_$PL.csv"),
is entered data2. year(date[1])+1900:4:0,",", ix:2:0, ",",
totalPL:8:4);
months[ix] = 0;
// PJK Repatriation end;
// Copyright 2022-2023, P J Kaufman. All rights reserved. nyears = nyears + 1;
// This program uses futures only end;
// data1 = currency // new year begins
// data2 = equity index k = 0;
end;
inputs: daysbeforemonthend(2), minreturn(0.02);
vars: endofmonth(0), pendofmonth(0), indexreturn(0), // calculate last month returns from end of prior to
cmonth(0), pmonth(0), // n days before this end
ix(0), k(0), size(0), ATR(0), investment(25000), nyears(0), if pendofmonth = 0 then
totalPL(0), indexreturn = 0
priordate(0), newdate(0), savecmonth(0); else
array: months[12](0), totalmonth[12](0); indexreturn = close[daysbeforemonthend] of
data2/pendofmonth - 1;
once begin
// Writes an ASCII file with a name created from the data months[pmonth] = 0;
// series if indexreturn >= minreturn then begin
print(File("c:\TradeStation\Repatriation_Table.csv"),
"Year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,No // currency returns only last day of month
v,Dec"); ATR = AvgTrueRange(20);
for ix = 1 to 12 begin if ATR <> 0 then
months[ix] = 0; size = investment/(ATR*bigpointvalue)
end; else
k = 0; size = 0;
print(File("c:\TradeStation\Repatriation_Monthly_$PL. months[pmonth] = 100.*(close[1]/
csv"),"Year,Month,$PL"); close[daysbeforemonthend] - 1);
end; end;
cmonth = month(date); k = k + 1;
pmonth = month(date[1]);
// if end of data output final records
// if month changes, process if lastbaronchart and cmonth = pmonth then begin
if cmonth <> pmonth and cmonth <> savecmonth and print(File("c:\TradeStation\Repatriation_Table.csv"
currentbar > 1 then begin ),year(date[1])+1900:4:0,",",
savecmonth = cmonth; months[1]:8:4,",",months[2]:8:4,",", months[3]:8:4,",",months
pendofmonth = endofmonth; {index} [4]:8:4,",",
priordate = newdate; months[5]:8:4,",",months[6]:8:4,",",months[7]:8:
endofmonth = close[1] of data2; {index} 4,",",months[8]:8:4,",",
newdate = date[1]; months[9]:8:4,",",months[10]:8:4,",",months[11]:
8:4,",",months[12]:8:4);
// if end of year then print and clear arrays
if pmonth = 12 then begin print(File("c:\TradeStation\Repatriation_Table.
print(File("c:\TradeStation\Repatriation_Table.csv") csv"),"Total,", totalmonth[1]:8:4,",",
,year(date[1])+1900:4:0,",", totalmonth[2]:8:4,",", totalmonth[3]:8:4,",",totalmonth[4]:8:
months[1]:8:4,",",months[2]:8:4,",",months[3]:8: 4,","
4,",",months[4]:8:4,",", ,totalmonth[5]:8:4,",",totalmonth[6]:8:4, ",",to-
months[5]:8:4,",",months[6]:8:4,",",months[7]:8: talmonth[7]:8:4,",",
4,",",months[8]:8:4,",", totalmonth[8]:8:4,",",totalmonth[9]:8:4,",",total
months[9]:8:4,",",months[10]:8:4,",",months[11]: month[10]:8:4,",",
8:4,",",months[12]:8:4); totalmonth[11]:8:4,",",totalmonth[12]:8:4);
end;
for ix = 1 to 12 begin

16 • April 2023 • Technical Analysis of Stocks & Commodities


FIGURE 2: S&P–EURO (ES–CU), FILTERING TRADES.Do the returns improve FIGURE 4: NASDAQ AND EURO FUTURES. Is the repatriation pattern stronger
if we require the S&P to close higher by 1% or 2%? This shows the monthly returns for a market with stronger returns? Returns in the Nasdaq 100 have been stronger
of the S&P–euro combination using trade filters based on the S&P closing 0%, than the S&P, so foreign investment may be more attracted to this market. This
1%, and 2% higher for the month. The filters improve the performance. test of the euro when Nasdaq returns are better than 2% shows that euro futures
returns tend to be better using Nasdaq futures than S&P futures.

FIGURE 3: TESTING THE REPATRIATION PREMISE. Is the observed month-


end pattern in currency values correlated to positive stock market profits for FIGURE 5: NASDAQ AND BRITISH POUND FUTURES. Currency moves only
the month, or does the month-end currency pattern occur for some other occur when enough volume is transacted. This test of the British pound when
reason? Changing the filter on the equity index return measurements to include NASDAQ returns are better than 2% shows this approach also works for the
negative equity index returns can help answer the question. This graph shows British pound.
euro returns when the S&P monthly returns were greater than −10%. Returns
seen here run about 5%, with an erratic pattern, compared to 15% when index the same test as before. In Figure 4, euro returns are bet-
returns are positive for the month. ter using Nasdaq futures than S&P futures.
Currency moves will only occur when enough volume
Do we get the same pattern without is transacted. The European community is likely to be
regard to S&P returns? the largest investment pool outside of the U.S. But what
Every system developer needs to ask whether they have about the U.K.? A lot of money moves through England.
discovered something special, or whether the euro al-
ways rallies at the end of the month. Either one can be Continued on page 21
traded, but if the euro rallies anyway, we have not found
anything special.
Figure 3 shows the euro returns for any month in
which the S&P closed with a return greater than −10%. We are interested in the profits
Returns are about 5% compared to 15%, with an erratic from the currency if the index
pattern.
market has returns greater than
NASDAQ some percent as of two days
Returns in the NASDAQ 100 have been stronger than before the end of the month.
the S&P, so we might expect foreign investors to be more
heavily allocated there. We can confirm that by running
April 2023 • Technical Analysis of Stocks & Commodities • 17
On The Coattails Of The Inventors

Mining Patent Documents


For Trading Ideas
Did you know that patent documents can be a good To find unique ideas, we might try turning to lesser-
source of trading ideas for stocks, options, and bonds? known or lesser-used resources. I will share with you here
It may be an opportunity to gain a trading edge from one resource I’ve found to be a rich source of ideas.
publicly available information. Find out how you may
be able to find and use some of the information. Patents
Patents are a government-issued legal right, a quasi-

G
by Gregory Aharonian law, to protect your invention. Patents prohibit other
people or other companies from using your invention,
ood traders are always looking for an edge where your invention is either something new or is an
in their trading and are always looking for improvement on existing techniques. (Note that patents
new trading techniques to harness. Profitable are not a right for you to use your invention, since actual
strategies must be able to exploit something implementation of your invention may be subject to
that probabilistically puts you at a slight ad- various laws and regulations.) If you hold a patent on a
vantage over the other side of the trade. An “edge” might particular invention, and if someone uses that invention
come from your own market observations, or something without licensing your invention or without outright
you read, or ideas you may pick up in an online trading- buying your patent from you, then legally you can sue
TIERNEYMJ/SHUTTERSTOCK

related forum. Of course, if an idea becomes too popular them for patent infringement. In some cases (such as has
and is used by too many trading strategies, the edge it occurred with some cellphone patents and drug patents),
provided could fade. So we must always be in the hunt the penalties for patent infringement have been in the
for new ideas. billions of dollars.
18 • April 2023 • Technical Analysis of Stocks & Commodities
TRADING TECHNIQUES

A good introduction to the US patent system can be found new inventions. So the point of this article is that you
in the book Patent It Yourself by David Pressman. can get some ideas and inspiration from what others are
In the United States, the patent system is overseen by thinking and developing, and you may be able to take
the US Patent and Trademark Office (USPTO, www. a germ of an idea and make it your own, for your own
uspto.gov). This site also gives a thorough overview of personal use, which could give you a unique edge. After
what patents are and the basic process for obtaining one. all, it is commonplace for companies today to stay abreast
Other countries may have their own patent offices. of what their competitors are doing and to keep moving
forward with their own progress by studying others’
Finding trading ideas products, developments, successes, and failures, and also
For many decades, business methods have been patent- researching their patents (both to avoid infringement
able. One type of business method that is patentable is and to work toward distinguishing their own product
trading techniques for use in the financial markets. Inter- offerings).
estingly and somewhat controversially, one requirement Second, understand that patent offices are not experts
for obtaining a patent is to give a detailed description of in the technology for which they are examining patent
your invention, which serves to identify and distinguish applications. So patent offices such as the USPTO won’t
your patent or invention from other patents or inventions. really know if a particular invention actually works or
These descriptions can be a rich source of ideas for trad- not. They are only trying to gauge whether the invention
ing strategies and trading techniques. By browsing the described is adequately unique to be patentable.
documents, you may be able to glean a few good trading Third, patents do not provide a highly detailed descrip-
ideas from work that others are doing in the field. tion of the invention. A patent filing serves to briefly
To be clear, I am not proposing the replication, imple- describe and identify an invention; it is intentionally
mentation, and distribution of another’s patented inven- not a how-to manual on how to use or implement an
tion. Patents are a form of intellectual property and as invention. However, it still may contain enough food
such they are someone else’s property. Technically, it for thought for you to think about how you might use
is the implementation of the idea (such as in a process, some of the ingredients yourself, and you may be able
a machine, a manufactured item, a composition, or a to add some of the ingredients you come across into
design) that is patented. your own recipe.
I will also say that points two and three, which on the
Browsing the databases face of it seem like drawbacks, actually have a benefit
Patent offices maintain public databases of the patents for traders: The fact that patent documents lack complete
issued in their country. The USPTO’s database is at details of an invention or may represent something never
www.uspto.gov/patft. Since such databases are mostly actually undertaken means that it won’t be a widely
designed for insiders, they are not the easiest to use, and known idea or product. Again, a widely used idea could
they only include patents for their own country. I find dilute an edge, whereas a vague idea about something or
that an easier-to-use and more comprehensive patent da- an obscure ingredient could help you yourself to create
tabase is offered by Google, available at: https://patents. something unique that no one else is using and that will
google.com. This site allows you to search on keywords give you an edge.
of interest to start exploring. A fourth note is about timelines. Patents generally
last 20 years from when they were filed, with some ex-
Caveats and notes tensions. A check of the USPTO database can help tell
There are several caveats and characteristics about patents you whether a patent is still in force, or whether it has
to note for some more background. lapsed. Some inventions for which the patent on it has
First, given that the whole point of having a formal expired and was not renewed or extended can fall into
system of patenting is to protect inventions and the the public domain. Ideas that are in the public domain
implementation of ideas, it is illegal and improper to use can usually be more freely used (but could also be more
a patented invention without going through the proper widely used).
steps to license or buy the rights to it, as I already stated. A fifth note: Sometimes, you will see multiple patents
An important purpose of patents is to make it worthwhile filed for one invention. Given that it is likely a company
for people and companies to invest in the research and spent a significant amount of money (in the tens of thou-
development necessary to bring their ideas to market. sands of dollars or more) to prepare and file so many
This is what makes it possible for us all to benefit from patent applications for one invention, this can indicate
April 2023 • Technical Analysis of Stocks & Commodities • 19
the inventor believes their invention is something “hot”
and they want rock-solid legal protection for it. While
it’s interesting to see what “hot” or important ideas are Patent documents can be
being developed in the field, again, ideas garnering a lot
of attention or being put into service in many ways may
an interesting source of
in the end suffer from dilution and lead to less unique ideas and inspiration.
trading ideas for you.
A final caveat has to do with if you are considering
patenting your own idea. If this article inspires you to https://patents.google.com/patent/US20140289096A1/en
consider patenting your own trading idea or invention, I
would suggest avoiding that route, especially if you are “Asset analysis according to the required yield method”
a retail trader. One reason is that generally, the protec- (Note: this one has some good math in it)
tion of patents stops at national borders. And financial U.S. Patent Application 2010/042553 (abandoned in 2012)
markets today are global in nature. So while a patent- https://patents.google.com/patent/US20100042553A1/en
holder could potentially sue to stop someone else from
using their idea within their own borders, or possibly “Method and device for evaluating stock exchange
within other countries that have mutual agreements in rates”:
place, you would not be able to do much about use of Austrian Patent AT501028 (abandoned in 2011)
your idea outside your border. And again, gaining an https://patents.google.com/patent/AT501028B1/en
edge can mean having a unique approach.
“System and methods for detecting advance earning
Examples insider information”:
One public benefit of the patent system is that patent U.S. Patent Application 2017/236201 (abandoned in 2019)
applications that have been abandoned for more than https://patents.google.com/patent/US20170236201A1/en
two years are in the public domain. Furthermore, issued
patents that have been abandoned/expired for more than “Market microstructure data method and appliance”
six years are completely in the public domain and are (includes mathematical formulas):
not generally subject to litigation concerning infringe- U.S. Patent Application 2014/149273 (abandoned in 2015)
ment, meaning if you first start using techniques in an https://patents.google.com/patent/US20140149273A1/en
abandoned/expired patent six years or more after it was
abandoned/expired, you theoretically can’t be sued for Those are some examples I found that I think contain
damages for using it. some very good ideas. You may wish to explore the
Following are some examples of links to abandoned/ database for yourself according to your own interests.
expired technical analysis–related patents whose tech- To begin, go to the Google Patents site and you’ll see a
niques would now be considered in the public domain. simple search box. Enter a term having to do with the
And here is an interesting side note about the patents markets. Entering “technical analysis” plus “stocks” and
in these links: While many academic writings in the “options” returns over 1,800 search results. Peruse the
finance realm are written in support of the efficient mar- results and see if any seem to match your interests. You
ket hypothesis (that is, with the premise that there can may find, for example, a description of a trend trading
be no successful trading systems), all of the following system, or example equations being incorporated into
patents are for inventions in support of the inefficient an algorithm, or even some example output that could
market hypothesis. be examined. It can be educational.
Or you could try searching on the term “interest
“Method for creating and valuing financial instruments rates.” Interest rate predictions are hugely important in
linked to average credit spreads”: the financial world, and you’ll see some of the research
U.S. Patent Application 2006/143099 (abandoned in 2008) being done in this area.
https://patents.google.com/patent/US20060143099A1/en Or try “Black-Scholes,” the well-known model used
in options trading. The search results suggest there are
“System/method for providing [graphical] share assess- over 2,000 patents around the world describing improve-
ment data with compound quality analysis”:
U.S. Patent Application 2014/289096 (abandoned in 2016) Continued on page 41
20 • April 2023 • Technical Analysis of Stocks & Commodities
Explore Your Options
KAEPPEL/OPTIONS cay will begin in earnest soon)
Continued from page 7 • The amount a trader must put The idea that a trader
up to trade a 1-lot is $440—this can “set it and forget
involved using options on Elec- also represents the maximum
tronic Arts (EA). With EA trading dollar risk
it” with an iron condor
at $121.74, the legs are: • The maximum profit on the is misguided.
trade is $60, or 13.6% of capital
• Buy 1 Jan20 2023 140 call @ risked the simplest terms possible, the trader
$0.19 • The maximum profit will be real- must formulate a contingency plan
• Sell 1 Jan20 2023 135 call @ ized if the trade is held until expi- regarding what they will do if the
$0.45 ration and EA is between $109.40 underlying security approaches one
• Sell 1 Jan 20 2023 110 put @ and $135.60 at that time of the short strikes. Unfortunately, the
$0.72 range of possible actions is beyond the
• Buy 1 Jan 20 2023 105 put @ Managing the trade scope of this article. But in general, if
$0.38 If the underlying stock doesn’t wan- one of the short strikes is threatened,
der too far, there isn’t really anything most traders will attempt to adjust the
The trade particulars and the risk that needs to be done. The main original position to reset the reward-
curves for this trade appear in Figures problem with an iron condor is that to-risk ratio more favorably.
1 and 2. the risk on both the upside and the
downside is generally much larger
Things to note: than the profit potential. So the idea
• This trade has 35 calendar days that a trader can “set it and forget it”
until option expiration (so time de- with an iron condor is misguided. In

KAUFMAN/REPATRIATION
Continued from page 17
We then take a long currency/
short dollar position on the
Figure 5 shows that this approach also works for the
British pound when Nasdaq returns more than 2%.
close two days before the end
of the month and exit on the
are These reTUrns good enoUgh? close of the month.
We are looking at about 15% return over 12 years. That’s
not a lot. However, it is earned by being in the market only
24 days each year. In addition, futures can be leveraged. and Learn To Trade (2022). For questions or comments,
Currency futures can be leveraged a lot. please go to www.kaufmansignals.com.
The benefit of this approach is that it is very different
from other trading methods, and it has less exposure to The code given in this article is available in the Article
price shocks. If you are only in the market 24 of 252 Code section of our website, Traders.com.
days, you have reduced your exposure by 90%.
You have also gained another view of why prices FUrTher reading
move. Kaufman, Perry J. [2022]. Learn To Trade, Amazon.
[2020]. Trading Systems and Methods, 6th Edi-
Perry J. Kaufman is a trader and financial engineer. tion, Wiley.
He is the author of many books on trading and market [2020]. Kaufman Constructs Trading Systems
analysis, including the sixth edition (2020) of Trading (print and ebook editions), Amazon.
Systems and Methods (with the first edition published in ‡TradeStation
1978 as a seminal book in the field of technical analysis), ‡See Editorial Resource Index
as well as Kaufman Constructs Trading Systems (2020),
April 2023 • Technical Analysis of Stocks & Commodities • 21
Long-Term And Short-Term Trading Of An ETF

Trading GLD In The Age Of


Zero Commission
Part 1

Come follow along on a quest to discover profitable provide some trading strategy rules for ETFs related to
trading rules you can use, based on a few technical gold and silver, based on the same technique. In response
indicators. In this two-article series focusing on two dif- to those requests, we set out to devise some possible
ferent markets, we’ll conceptualize some strategies and trading strategy rules that could beat a buy-and-hold
technical trading rules, test them, and then compare the strategy for SLV and GLD, the popular ETFs related to
results. Here in part 1, the focus is on trading a popular the silver and gold markets.
gold market ETF. Here in this article, we will analyze some possible
technical trading rules for GLD. Then, in part 2, to appear
by Massoud Metghalchi, PhD, in an upcoming issue of this magazine, we will analyze
and Linda A. Hayes, PhD some possible technical trading rules for SLV.

In
the September 2022 issue of Technical SPDR Gold Shares ETF (GLD)
Analysis of Stocks & Commodities, I and GLD is symbol for the SPDR Gold Shares ETF that
coauthor Peggy Cloninger presented an owns gold bullion and began trading on November 18,
OLIVIER LE MOAL/SHUTTERSTOCK

article on trading the natural gas ETF UNG 2004. This ETF allows investors to participate in the
(“Trading Natural Gas Using UNG”). In the gold market without having to take actual delivery of
article, we used a Coppock indicator that gold. GLD is designed to closely mimic the price of gold
we had revised and updated. After that article came out, minus the fund’s fees and expenses. This ETF can easily
some readers wrote to us and asked us if we could also be bought and sold via stock brokerage firms.
22 • April 2023 • Technical Analysis of Stocks & Commodities
TRADING STRATEGIES

Figure 1 shows a chart


of GLD from its incep-
tion.
To investigate trading
rules that could outper-
form a buy-and-hold
(B&H) strategy for GLD,
we will use both monthly
data and daily data (from
Yahoo Finance) and will
explore applying the

STOCKCHARTS.COM
revised Coppock indi-
cator plus a dozen other
technical indicators such FIGURE 1: SPDR GOLD SHARES ETF (GLD). The popular SPDR Gold Shares ETF GLD began trading on November 18, 2004
as the relative strength and is designed to closely mimic the price of gold minus the fund’s fees and expenses.
index (RSI), moving
average convergence/ Chance of Losing in the Stock Market
divergence (MACD),%D of stochastic (%D), moving 100%
averages (MAs), and a few others. Then, we will provide
the best results from the technical trading rules tested. 75%
Chance of Loss

Finally, we will compare those results with the risk and


50%
return of a B&H strategy.

MINDFULLYINVESTING.COM
25%
Long-term analysis
In the long term, we use the rate function in Microsoft 0%
Excel to estimate the geometric return of the B&H 0 5 10
Years Invested
15 20
strategy as follows:
FIGURE 2: WEALTH RISK OVER VARIOUS TIME HORIZONS. Many assets
tend to appreciate in the long run, as does the stock market in general. The risk
B&H return = Rate (N, PMT, −PV, FV) associated with wealth (not periodic returns) for the S&P 500 after 15 years of
= 5.95% Eq.1 buying and holding the S&P 500 is almost zero.

where N = number of periods, or 15.33 years, PMT is zero, A trader following strategy 1, long/money, will buy
PV is the closing price of GLD on 6/1/2007 or $64.27 the GLD ETF when the trading rule emits a buy signal.
when technical trading estimation starts, and FV is the When the rule emits a sell signal, the trader will sell
closing price of GLD on 10/1/2022 or $155.99. GLD and invest the funds in TLT.
Note that although the GLD ETF started trading in A trader following strategy 2, long/short, will buy GLD
November 2004, because of the estimation of a moving when the trading rule emits a buy signal and short GLD
average of 30 months, our start of technical trading when the rule emits a sell signal.
analysis is 6/1/2007, since the use of MA30 requires 30 For strategy 3, leverage/money, a trader will buy GLD
months of averaging the GLD price. on leverage and invest in TLT when the rule emits a sell
We will design the technical trading rules in com-
bination with a few strategies to beat the return of the
B&H strategy, which was 5.95%. The four strategies are
similar to the strategies we discussed in the September
To investigate trading rules that
2022 article on natural gas, namely: could outperform a buy-and-hold
strategy for GLD, we will explore
Strategies applying the revised Coppock
1. Long/money indicator plus a dozen other
2. Long/short
3. Leverage/money, and
technical indicators.
4. Leverage/short
April 2023 • Technical Analysis of Stocks & Commodities • 23
signal. The return for buy days for this strategy will be Coppock Trading Rule
two times the GLD return minus the TLT return. Rule
Strategy 1 Strategy 2 Strategy 3 Strategy 4
Finally, for strategy 4, leverage/short, a trader will buy Monthly
0.63% 0.48% 1.15% 0.99%
GLD on leverage when the rule emits a buy signal and average
short GLD when the rule emits a sell signal. Annual
7.91% 5.87% 14.74% 12.57%
return
We use TLT, iShares Treasury bond ETF, as a proxy Rule 10-Month MA > 30-Month MA
for returns on invested funds for strategies 1 and 3 and a Monthly
borrowing rate for strategies 3 and 4 when a trader buys average
0.64% 0.33% 1.15% 0.84%
GLD on leverage. Annual
7.94% 3.98% 14.81% 10.60%
return
Assessing risk Rule 30-Month MA Is Increasing
Monthly
Our approach to risk is very different from most literature average
0.62% 0.77% 1.12% 1.26%
on risk/return trade-offs. In the long run, the risk for a Annual
7.72% 9.66% 14.33% 16.39%
trader’s wealth is almost zero. For example, the risk as- return
sociated with wealth (not periodic returns) for the S&P FIGURE 3: LONG-TERM TECHNICAL TRADING RULES FOR GLD, 6/1/2007–
500 after 15 years of buying and holding the S&P 500 is 10/1/2022. Here are the three long-term technical trading rules that showed
almost zero as can be seen by the chart in Figure 2. the best results in the tests, in combination with the four long/short strategies.
Given that in the long run most assets such as precious These long-term trading rules are based on monthly data for GLD. You can see
that the results from these three best trading rules are very similar. Compare
metals do not lose their value and the risk of a negative
to the annual return of 5.95% for the buy & hold approach.
return after 15 years is close to zero, we only look at the
returns of various trading rules that can beat the B&H
return. In the short run, when we use daily data, we Next we’ll explain each of these three rules and how
compare both the risks and returns of various trading they were combined with each of the four strategies
rules with the risk and return of the B&H strategy. For discussed earlier.
the long term, we look at returns only, since after 15
years, the value of an asset such as gold would be above Trading rule 1: Coppock trading rule
its price 15 years ago. Let’s start with the trading rule based on the Coppock in-
dicator. We estimate the Coppock indicator as follows:
Calculating annual returns
For our tests on our long-term trading rules, we will es- Coppock = EMA10 of [ROC (14 months GLD price)
timate annual returns based on the following formula: + ROC (11 months of GLD price)] Eq. 3

Annual return = EXP (average monthly where EMA10 is the exponential moving average of 10
return * 12) −1 Eq. 2 months, and ROC [14] and ROC [11] are the 14 months
and 11 months rates of change of the closing price of
The “annual return” in equation 2 is based on the geo- GLD.
metric compounding of the monthly average returns. A trader following this Coppock trading rule with
“EXP” is the Excel function for “exponential.” strategy 1 will buy GLD if Coppock is greater than
zero and will stay invested in GLD till the Coppock
The trading rules indicator becomes zero or less than zero; at this time,
In the table in Figure 3, we present the three long-term the trader will sell all GLD and invest the funds in TLT.
trading rules that had the best results in our test. Our This will be repeated for the entire period of 6/1/2007 to
long-term trading rules are based on monthly data (a 10/21/2022, implying a total of seven in and out trades of
total of 185 months or observations) for GLD. You can GLD for the entire period, or 0.45 trades per year. Since
see that the results from these three best trading rules the transaction costs of trading GLD are zero, we have
are very similar. The three trading rules are: not considered transaction costs.
A trader following this Coppock trading rule with
1. Coppock indicator trading rule strategy 2 will buy GLD when the rule emits a buy
2. 10-month moving average > 30-month moving signal (Coppock >0), and will short GLD when the rule
average emits a sell signal.
3. 30-month moving average is increasing For strategy 3, when the Coppock trading rule emits a
24 • April 2023 • Technical Analysis of Stocks & Commodities
buy signal, the trader borrows at the money market rate All trades for the above three trading rules are made
and doubles (50% margin) investment in GLD. When the on the last day of each month. We assume that on the
rule emits a sell signal (Coppock <0), the trader parks last day of each month, a few minutes before the market
the funds in TLT. closes, a trader can estimate the GLD price that will
This rule with strategy 4 implies buying GLD on trigger a buy or sell signal and will initiate a conditional
margin when the rule emits a buy signal and shorting limit order just before the market closes at the end of
GLD when the rule emits a sell signal. each month. If a trader cannot estimate the GLD price
For the Coppock trading rule, strategies 2 and 4 are that triggers a buy/sell signal at the close of the month,
inferior to strategies 1 and 3, implying shorting GLD is the trader can initiate the buy/sell order the next day at
not a good idea for the Coppock trading rule. The returns the open. Placing the order on the open the next day
of strategies 1 and 3 are 7.91% and 14.74%, respectively, would not change our results. Also, it would eliminate
and these returns should be compared with the B&H the non-synchronicity bias.
return of equation 1, or 5.95%. In conclusion, for long-term trading, the trader may
perform better by using one of our three trading rules
Trading rule 2: MA10>MA30 with strategy 1 (low risk) or strategy 3 (high risk) rather
The second-best long-term trading rule from Figure 3 than buying and holding GLD for the long term.
is MA10>MA30. For this trading rule combined with
strategy 1, a trader will buy GLD if the 10-month mov- Short-term analysis
ing average is above the 30-month moving average, and From Yahoo Finance, we’ll use the daily closing price of
otherwise, will park the funds in TLT. GLD and TLT from 11/19/2004 to 10/10/2022. Since the
Strategy 2 is similar to strategy 1 except when the rule estimation of MA200 days requires data from previous
emits a sell signal, the trader will short GLD. Strategies days, all estimations and technical trading are done from
3 and 4 are similar to strategies 1 and 2 except when 9/16/2005 to 10/10/2022, which is 4,296 days of daily
the rule emits a buy signal, the trader will buy GLD on prices. We estimate various statistics as follows:
margin.
Once again, as with the previous trading rule, strategies Daily return = Log (Pt / Pt-1) Eq. 4
2 and 4 are inferior to strategies 1 and 3, implying that
it is better to park the funds in TLT rather than shorting Annual return = EXP (average daily returns
GLD when this rule emits a sell signal. * 260) −1
The average annual returns for this trading rule used
with strategies 1 and 3 are 7.94% and 14.81%, better than σA = σd * √365 Eq. 5
the B&H of 5.95%. This trading rule implies six trades
in and out of GLD for the entire period.
where σA and σd are the annual and daily standard devia-
Trading rule 3: 30-month MA is increasing tion (SD) of daily returns of GLD according to equation 4.
The third best long-term trading rule from Figure 3 is “EXP” is the Excel function for “exponential.”
when the 30-month MA is increasing, a trader will buy
GLD if MA30 of GLD is going up, and otherwise (that The trading rules
is, when MA30 is going down), the trader will be out of For exploring short-term trading rules, we analyzed
GLD, either buying TLT (strategies 1 and 3) or shorting
GLD (strategies 2 and 4).
The annual average returns for this trading rule com- Given that in the long run most
bined with the four strategies are 7.72%, 9.66%, 14.33%,
and 16.39%, respectively. These long-term annual returns
assets like precious metals do not
should be compared with the B&H return of 5.95%. lose their value and the risk of a
negative return after 15 years is
Conclusions close to zero, we only look at the
Given that leverage usually increases risk, a trader with returns of various trading rules
a low tolerance for risk should apply these trading rules
with strategy 1. Traders with a higher tolerance toward that can beat the B&H return.
risk could use one of these three rules with strategy 3.
April 2023 • Technical Analysis of Stocks & Commodities • 25
a dozen technical indicators generated by % D of Stochastic Indicator Is Increasing
TraderCode software. Here, we’ll discuss the Rule
Strategy 1 Strategy 2 Strategy 3 Strategy 4 B&H
best technical trading rules with combinations Annual
12.79% 1.35% 26.69% 13.84% 7.49%
of the above four strategies found from our return
test. We will also compare the risk-return of Annual SD 19.34% 21.85% 32.80% 34.37% 21.85%
the best trading rules and strategies with the Reward/
0.66 0.06 0.81 0.40 0.34
Risk
risk-return of buying and holding GLD.
Rule RSI > 30 B&H
In the table in Figure 4, we present the three Annual
best models from our tests. They are: return
9.37% 9.04% 19.11% 18.75% 7.49%
Annual SD 21.47 21.84 43.40% 43.59% 21.85%
1. %D of stochastic indicator is increas- Reward/
0.44 0.41 0.44 0.43 0.34
ing Risk
2. RSI >30 Rule 150-Day MA Increasing B&H
3. 150-day MA is increasing Annual
return
9.04% 6.49% 18.39% 15.62% 7.49%
Annual SD 20.09% 21.85% 36.66% 37.65% 21.85%
Trading rule 1: %D of stochastic indicator Reward/
is increasing Risk
0.45 0.30 0.50 0.41 0.34
The best trading rule from Figure 4, combined FIGURE 4: SHORT-TERM TECHNICAL TRADING RULES FOR GLD, 9/16/2005 TO
with strategy 1, means that the trader buys 10/10/2022. To come up with some possible technical trading rules for shorter-term trading,
GLD if the %D of the 14-day slow stochastic a dozen technical indicators were explored. The three best trading rules from the test are
(MA3 of %K) is increasing. The trader stays shown here, in combination with the four long/short strategies. Also shown is the risk-return
of the trading rules and strategies compared with the risk-return of buy & hold for GLD.
invested in GLD until %D starts to decrease.
Notes: SD stands for standard deviation, and annual return is based on the formula [EXP (Daily
At that point, the trader sells GLD and parks average*260) −1]. EXP is the Excel function for “exponential.” %D is the slow stochastic.
the funds in TLT. This will be repeated for
the entire period of 9/16/2005 to 10/10/2022,
implying a total of 138 in and outs in GLD over the 17.07 Trading rule 2: RSI >30
years, or an annual average of 8.09 trades per year. Since The second-best short-term trading rule for GLD from
the transaction costs of trading GLD are zero, we have Figure 4 implies buying GLD if the 14-period relative
not considered the transaction costs. strength index (RSI) is above 30.
The annual returns of this trading rule combined with A trader following this rule with strategy 1 will buy
strategies 1 and 3 are 12.79% and 26.69%, respectively, GLD if RSI is above 30 and will stay invested until RSI
compared to the B&H annual return of 7.49%. The risks goes below 30; at that time, the trader will sell GLD and
of this trading rule with strategies 1 and 3 are 19.34% park the funds in TLT for strategy 1, or, for strategy 2,
and 32.80%, respectively. will short GLD. This rule with strategies 3 and 4 is
These risks should be compared with the risk of the similar to strategies 1 and 2 except that when the rule
B&H strategy of 21.85%. Thus, trading rule 1 with strat- emits a buy signal, the trader buys GLD on margin.
egy 1 has a higher return and a bit lower risk than the For this RSI trading rule combined with each of the
B&H strategy. Trading rule 1 with strategy 3 provides four strategies, the reward-to-risk ratios are higher than
very high returns and also higher risk, so it’s a good the reward-to-risk ratio of B&H. This RSI trading rule
choice for risk-tolerant traders. The reward/risk ratio combined with strategy 1 is appropriate for traders with
(annual return divided by annual SD) of this rule with a low risk tolerance, with strategy 2 for traders with a
both strategies 1 and 3 are much higher than the reward/ medium risk tolerance, and with strategies 3 and 4 for
risk ratio of the B&H. traders with a high risk tolerance.
This trading rule with strategies 1 and 3 are superior This rule combined with strategy 1 has an annual return
to strategies 2 and 4, implying that when the rule emits of 9.37%. Note that if we change RSI>30 to RSI>31 or
a sell signal, it is better to park the funds in TLT rather RSI>29, the annual return for this rule with strategy 1
than short GLD. remains unchanged at 9.37% for RSI>31, and becomes
This rule combined with strategy 1 is appropriate 8.49% for RSI>29.
for traders with a low tolerance for risk, while the rule
combined with strategy 3 is appropriate for traders with Trading rule 3: 150-day MA is increasing
a high tolerance to risk. In the third-best trading model, when the 150-day MA
26 • April 2023 • Technical Analysis of Stocks & Commodities
is increasing, a trader will buy GLD and Sub-Period 1: 2/27/2007 to 3/28/2014
stay invested in GLD as long as MA150 is Strategy 1 Strategy 2 Strategy 3 Strategy 4 GLD (B&H)
increasing, and otherwise will be out of GLD. Annual
22.62% 2.59% 47.29% 23.24% 12.99%
For this trading rule, strategies 2 and 4 are return
inferior to strategies 1 and 3, implying that Annual SD 21.55% 25.83% 38.81% 41.39% 25.82%
when the rule emits a sell signal, it is better Reward/
1.05 0.10 1.22 0.56 0.50
Risk
for traders to park funds in TLT rather than
Sub-Period 2: 3/29/2014 to 10/10/2022 GLD (B&H)
shorting GLD. Annual
This trading rule with strategy 1 has return
3.76% 0.15% 8.90% 5.11% 2.72%
an annual return of 9.04%, annual SD of Annual SD 16.83% 16.98% 25.39% 25.49% 16.97%
20.09%, and reward to risk of 0.45, all better Reward/
0.22 0.01 0.35 0.20 0.16
than the B&H strategy for GLD. A similar Risk
conclusion can be made about this rule with FIGURE 5: ARE THE TRADING RULES ROBUST? To help ensure the trading rules are robust
strategy 3. and aren’t just the result of “data snooping,” which can introduce bias into an evaluation, the
This MA trading rule combined with strat- sample test period was divided into two equal sub-periods and the test was rerun Shown
here are test results for just one of the technical trading rules (that is, the “increasing %D”
egy 1 is appropriate for traders with a low
rule), combined with each of the four strategies. As can be seen, the trading rule and strategy
risk tolerance and combined with strategy 3 combinations that beat the reward/risk ratio of the B&H strategy in the entire sample also beat
for traders with a high risk tolerance. the B&H strategy in each sub-period, suggesting the trading rule is robust.
Notes: SD stands for standard deviation; annual return is based on the formula [EXP (Daily
Order placement average*260) −1] where EXP is the Excel function for “exponential.”
All trades for the above three rules are made
at the end of each day. A few minutes before the market In addition, we did the same robustness check for the
closes, a trader can estimate the GLD price that will trigger other two trading rules from Figure 3 and found similar
a buy or sell signal and initiate a conditional limit order results: The trading rules and strategies that beat the
just before the market closes at the end of each day. If a B&H reward/risk ratio in the entire sample also did so
trader cannot estimate the GLD price that triggers a buy/ in each sub-period. (We can provide the returns of the
sell signal at the close of the day, the trader can initiate other two trading rules upon reader request.)
the buy/sell order the next day at the open.
Conclusions
Robustness and “data snooping” GLD is an exchange-traded fund that holds gold bullion
One method to check that the results are robust and not for investors. Traders can buy and sell the fund at leading
a result of data snooping is to divide the entire sample brokerage firms just like for any other ETF, and it has a
period into sub-periods. very good trading volume.
(“Data snooping” is making inferences about the results In this study, we suggest technical trading rules that
when in reality the results could be due to chance. The could beat the B&H strategy both in the short run and
more combinations of variables you test, the likelihood in the long run.
grows.) For long-term traders, we suggest three technical trad-
If the results in each sub-period are similar to the re- ing rules, shown in Figure 3, based on monthly data, that
sults over the entire period, we can conclude with high can be combined with the four long/short approaches
confidence that our methodology is robust, and our results discussed earlier and that indicate better performance
are not the result of data snooping.
In the table in Figure 5, we provide the results for the Continued on page 55
technical trading rule of “%D increasing” for each sub-
period. The two equal sub-periods are from 9/16/2005 to
3/28/2014 and 3/29/2014 to 10/10/2022, implying 2,147
days for sub-period 1 and 2,149 days for sub-period 2. In this study, we’ve suggested
As can be seen in the table, the trading rules and strate- technical trading rules that could
gies that beat the reward/risk ratio of the B&H strategy beat the B&H strategy both in the
in the entire sample also beat the B&H strategy in each
sub-period. Therefore, we can reasonably conclude our
short run and in the long run.
trading rules are robust.
April 2023 • Technical Analysis of Stocks & Commodities • 27
INTERVIEW

Market Technician, Trader, Quantitative Analyst, Educator

A Conversation
With John Ehlers
After four decades of providing products, services, and education to trad-
ers through his company, MESA Software, John F. Ehlers has announced
his retirement. We congratulate him on his long and successful career.
He has been a Contributing Editor to Technical Analysis of Stocks &
Commodities since 1983, a year following the magazine’s launch. He
has written more than 100 articles for the magazine, more than any other
contributor. Ehlers is a pioneer in the use of cycles and digital signal
processing (DSP) technical analysis. He launched MESA Software in the
early 1980s after developing the technique of maximum entropy spectral
analysis as applied to trading and market analysis. MESA Software has
focused on offering algorithmic trading strategies that adapt to different
markets and market conditions.
Traders and technical analysts have benefitted from the research,
tutorials, tools, software, and insights he has provided via his writings,
his products, his speaking engagements, and through the annual semi-
nars he offered through 2022, in which he would share some of his life’s
work on analyzing market data. He continues to contribute articles to
this magazine based on his ongoing, latest research. In this issue, you At its core, trading is an
will find an article in which he presents a practical and effective way to art. But success is simply
smooth market data.
Prior to launching MESA Software, he was a Senior Engineering Fel-
a matter of statistics. By
low with Raytheon and worked on special projects including SkyLab. It using technology, one has
was during his time there that he started to become interested in studying a much higher probability
market data and cycle analysis. of success.
Ehlers can be reached through his website at MESAsoftware.com.
Stocks & Commodities Contributing Writer and “Algo Trading”
columnist Kevin J. Davey interviewed John Ehlers via email in January 2023 to discuss his trading and analysis
approach, his thoughts on where quantitative financial analysis is heading, and his long and meaningful contri-
bution to the fields of technical analysis and quantitative financial analysis.

John, your contributions stand out to you, and why? themselves an immense amount of
over the years to the To me, the importance of an article time simply by avoiding volatility
trading community are is directly related to my contribution when trying to improve market tim-
immense and far reach- to technical analysis. So, I think ers. Instead, they can use volatility
ing. That makes it tough my best article was “A Technical to establish amplitude thresholds to
for someone new to algorithmic Description Of Market Data For improve the probability of a trade
trading, or new to your material, Traders,” which appeared in the May being successful.
to actually benefit from your great 2021 issue of S&C. I also established that the signal
work. So let’s start with the archives In that article, I proved that vola- information in the data is analogous
of this magazine. Out of the 100+ tility is orthogonal (that is, uncor- to frequency modulation or phase
articles you have written for Stocks related) to market timing signals. modulation of a radio wave. The
& Commodities, which one or two Astute strategy developers can save implication of this relationship is
28 • April 2023 • Technical Analysis of Stocks & Commodities
that band-limiting filters can recover short position at the top
trading information with greater ac- of that swing. It is easy
curacy than conventional technical to add a volatility rule to Astute strategy developers
indicators. apparently improve the can save themselves an
It is common knowledge that percent winners or profit immense amount of time
market data are fractal and the factor in historical test-
statistical shape of the market spec- ing. What I have proven is simply by avoiding volatility
trum is pink noise. That means the that such a rule is illusory, when trying to improve
amplitude swings of the frequency and a resulting strategy market timers.
components are in direct proportion will be less robust in out-
to their wavelength, which makes of-sample applications.
the measurement of cycles very dif- Swing trade timing rules
ficult. In fact, cycles are ephemeral should be solely dependent upon the varies with time. Therefore, a walk-
and measurement shows them to be position of the phasor. forward-type procedure is advised
all over the place. Therefore, it is I don’t think Bollinger Bands to get the best strategy performance
just not practical to use measured should be used for swing trading for from the filters.
frequency as a parameter to tune several reasons, mostly because of
filters or indicators. computational lag. Bollinger Bands Let’s say I am a brand-new algo/
I also like “Predictive And Suc- first require a moving average from systematic trader. What would be
cessful Indicators” in the January which to compute the standard devia- the best path for a newbie to start
2014 issue because I introduced the tion. The lag of a moving average utilizing your research and material
SuperSmoother and highpass filters is approximately half the average into their own trading?
there. length, and that alone is enough to Nothing can replace preparation.
I introduced the bandpass filter make the swing trade timing signals First of all, my approach embraces
in “The Bandpass Indicator” in the ineffective. swing, or reversion to the mean, trad-
September 1994 issue. ing. I do this because the algorithmic
I introduced the Hann-windowed In the other articles you mentioned, approach offers a better chance of
FIR (finite impulse response) smooth- filters are introduced. As a best having a higher probability of win-
ing filter in “Windowing” in the practice, do you recommend the ning trades. Trend trading typically
September 2021 issue. trader first analyze the market offers a higher probability of a larger
data with these indicators and profit factor. If you want to be a trend
There is definitely a lot to absorb filters to see if they can be tuned trader, about all my techniques will
in those articles. In the first article to the particular market, or would provide are smoothing filters.
you reference, you mention how you rather people just incorporate If you embrace swing trading, read
volatility is uncorrelated to market the filters in strategies they are all that has been written and apply
timing signals. Can you expand developing? the concepts to your own particular
upon that a bit? For example, I think of the market as a “blackbox market and style of trading. Don’t
are you saying that Bollinger system” when using digital signal avoid studying DSP because it ap-
Bands—which give signals and use processing (DSP). Such a system has pears to be too difficult. Thoroughly
standard deviation as a volatility an input, and output, and a transfer test your strategy for robustness. Now
measure for the upper and lower response linking the two. A system your work is done. When it comes to
bands—can be improved upon or transfer response is often charac- trading, just turn on the computer and
modified by encompassing the ideas terized by its response to an input let it process the trades for you. Don’t
in that article of yours? If so, can impulse function. My research shows override your algorithm. In fact, don’t
you briefly explain? that the system response of the market even look at the trades until they are
I want to underscore that I am is broadly described as the combina- closed. That way you can maintain
referring to swing, or reversion to tion of a highpass filter and a low- your sanity and quality of life.
the mean, style of trading. With that pass filter, forming a relatively wide
style, a trader is attempting to enter passband of spectral components. Excellent points, both on the proper
a long position at the bottom of the Since the market is nonstationary, use of your work and on how to test
cyclic swing and exit or reverse to a the particular tuning of these filters and ultimately execute a strategy.
April 2023 • Technical Analysis of Stocks & Commodities • 29
Sorry for the sidetrack axis). Suppose the data consistently
question. Please continue had a frequency less than 0.05 and
I think this is a profound with new algo trader your trading rules provided strate-
tips. gies that couldn’t miss for weeks
overview of DSP applied to Another tip is to ma- at a time. Then, the data shifts and
trading: Market data are nipulate the data to create now you can’t get a winning trade
fractal and has a pink noise tradable events. Since to save your life. What happened?
spectrum. the data are fractal, the The answer is in the phase response.
spectrum component Successful trades occurred when the
amplitudes are in direct filter phase response was near +90
proportion to their wave- degrees. But when the data shifted
That said, what are the two or three length. Taking a simple difference to a frequency larger than 0.05, the
best tips you’d offer to brand-new of successive data samples creates filter phase response was near -90
algo/systematic traders? a filter whose amplitude outputs are degrees. Thus, the data shift caused
The most important aspect of inversely proportional to wavelength. a 180-degree phase reversal for the
algo trading is “keep it simple.” A Thus, the difference flattens the data information provided to the trad-
trading strategy absolutely has to be spectrum amplitudes. Then, the infor- ing rules and the trading rules are
dirt-simple to be robust in all market mation can be recovered by applying a therefore dead wrong in the second
conditions. One can see an immense smoothing filter to flattened spectrum case. This illustrates how important
interaction between tunable inputs data. Differencing sampled data is phase response is to a successful
when optimizing a strategy. Those analogous to taking the derivative in algorithmic strategy.
same interactions are present when calculus and smoothing is analogous
the fixed parameters are presented to integration in calculus. Therefore, Your material is math and science
with the variable market data. So my by simply applying the two inverse intensive (no surprise, considering
rule is to use only one, or at most two, mathematical operations, one can your rocket science background!).
tunable parameters when developing create a nearly matched filter for Your answer to the above question
a strategy. trading. There are different combi- is a great example of that. Here is
nations of filters and indicators that a two-part question: First, can you
With limiting yourself to two approximate the frequency response recommend a good book for people
tunable parameters, are you also of a matched filter. starting out with digital signal
including any stop-losses or profit The third tip is to expand analysis processing, maybe that focuses
targets in your strategy, as most into the frequency and phase domain. more on concepts as opposed to
traders do? If those values are also Most traders are familiar with the the detailed math? Next, how
optimized or tuned, then you could squiggly lines of indicators in the can non-math-inclined traders
have four parameters total. Or, do time domain. Those squiggly lines best utilize your work in digital
you mean a limit of two total for the have a direct representation in the fre- signal processing to help them be
whole strategy? quency domain as well. The chart in a successful trader?
I would prefer to not use stop-loss Figure 1 of the
rules in my strategies because the amplitude and
stop-loss interferes with the perfor- phase response
mance of the trading rules. Having of a relatively
said this, I am not completely oblivi- narrow band
ous to real-world considerations. So bandpass fil-
my strategies include stop-losses that ter illustrates
are merely disaster stops. They are my point. The
set on the basis that they are rarely green line is
hit, and therefore have minimum the amplitude
interaction with my trading rules. response (left
Therefore, I don’t count a disaster axis). The blue
stop as a tunable parameter. line is the phase FIGURE 1: AMPLITUDE AND PHASE RESPONSE OF A RELATIVELY NARROW
response (right BAND BANDPASS FILTER
30 • April 2023 • Technical Analysis of Stocks & Commodities
DSP is a relatively complicated opposite mathematical
subject, requiring advanced math- function—taking the in-
ematics. But the necessity to mini- tegral of the band-limited My approach embraces swing,
mize computational lag in trading signal. Integration is the or reversion to the mean,
applications means that only a tiny equivalent of summa- trading. I do this because the
fraction of the entire DSP subject is tion and summation is
used. I would advise traders not to the basically the same
algorithmic approach offers
try to learn all about DSP, but to just as lowpass filtering. The a better chance of having a
get a general understanding of the result of using the two op- higher probability of winning
concepts. So, rather than recommend- posite calculus operations trades. Trend trading typically
ing a book, traders can read my DSP is an approximation to a offers a higher probability of a
tutorial at https://www.mesasoftware. statistically matched filter
com/DSPTutorial.htm or review the in the frequency domain. larger profit factor.
tutorial found at www.micromodeler. This matched filter can be
com/dsp. tuned using combinations
Just don’t be intimidated by tech- of highpass and lowpass filters. on risk, and that means that losses are
nology. Learning a little bit about DSP I know the concept is difficult for inevitable. But taking a loss in real
is a whole lot easier than memoriz- traders to get their mind around, but money is a lot different than looking at
ing a bunch of patterns or trying to once you master the concept, the rest drawdown on a hypothetical histori-
understand the relationship between of the application of DSP is just tun- cal study. Taking a loss is tough, and
price and volume. One key feature of ing simple filters. a trader must be prepared for it.
DSP is that it exploits the duality of All of this also means that an im-
the time domain and the frequency Over the years, you have seen portant key to successful trading is to
domain. That is, the characteristics of many successful and unsuccessful do thorough research before trading
the squiggly lines in the time domain traders. What do you think is the is begun. The research involves not
can be explained in terms of filters most important key to successful only the probability of success of the
in the frequency domain. trading? selected strategy, but also the impact
I think this is a profound overview Without question, the single most of the losses.
of DSP applied to trading: Market important key to successful trading
data are fractal and has a pink is money management. It is simple. For those wanting to learn more
noise spectrum. That means that the You have to have enough capital to about your money management
amplitude of the cyclic component stay in the game. That means a suc- thoughts and practices, can you
swings are in direct proportion to cessful trader needs to understand expand upon how you perform
their wavelength. A reasonable ap- his capability to absorb losses. This money management, or point
proximation is that the cyclic swing capability includes both financial and readers to an article or book chapter
amplitudes increase at the rate of 6 psychological aspects. you wrote on the topic?
dB per octave. Since the spectrum On the financial side, a trader’s ac- Money management is not my
components do not have equal ampli- count must be sufficiently capitalized forte. I think the primary objective
tude, cyclic analysis is possible only to fully implement the strategy being of money management is to stay
if the spectrum is equalized. The followed. In trading futures, that alive so you can trade another day.
spectrum can be equalized by taking capability means having a respect So I simply approach the subject with
a simple difference of successive data for the effect margin can have on the the question of how many consecu-
samples, which is approximately the downside. If you get a margin call, it tive losers can I afford to take. That
same as taking a derivative in calcu- is impossible to continue following number, times the average loss per
lus. The derivative has a frequency your strategy without the influx of trade and initial margin, is the amount
response of −6 dB per octave, which more capital. of capital I must have to trade. I use
provides the equalization. The result On the emotional side, traders must ten consecutive losers as my rule
of taking the difference is a band- realize that their role in the market is because the probability of this event
limited signal (that is, an oscillator). to provide capital so that producers is vanishingly small.
The information in the band-limited and consumers can mitigate their
signal can be recovered by using the risks. That means the trader is taking I find it very interesting that a
April 2023 • Technical Analysis of Stocks & Commodities • 31
ing is synonymous with a cycles tutorial and a DSP tutorial,
curve fitting. So, if you as well as many of the more recent
Without question, the like curve fitting you will technical articles I have written.
single most important key love AI. No matter how
you slice it, AI is pattern Thank you John, not just for this
to successful trading is matching on steroids. interview, but for all the work
money management. Technology will bring you’ve contributed to trading over
more sophistication to the the years. Your legacy in trading (or
art of trading. Successful should I say “lagacy”) will last for
“numbers” guy like yourself, with traders will be forced to decades to come.
so much research into DSP for acquire skills in signal processing and
trading, highlights the importance probabilities of outcomes. Traders of Kevin J. Davey may be reached at
of emotions and psychology for tomorrow probably will become the kdavey@kjtradingsystems.com.
good trading. Do you have anything ones we call quants today.
(books, articles) that you have Further reading
written or read that have really Do you think retail traders who Ehlers, John F. [2013]. Cycle Ana-
helped you emotionally? do not embrace these advanced lytics For Traders, John Wiley
Nope. The numbers protect you concepts will be able to succeed? & Sons.
against emotions. You just have to Of course retail traders can succeed [2001]. Rocket Science For
understand that losses are part of without quant skills because, at its Traders, John Wiley & Sons.
trading. You must also respect lever- core, trading is an art. But success [1994]. “The Bandpass In-
age when trading futures. One way of is simply a matter of statistics. By dicator,” Technical Analysis of
sidestepping many emotions is to put using technology, one has a much Stocks & Commodities, Volume
your computer on autotrade and don’t higher probability of success. It takes 12: September.
even look at the results until the end a mountain of experience to be a [2014]. “Predictive And Suc-
of the day or end of the week. successful seat-of-the-pants trader cessful Indicators,” Technical
using skills that are nearly impos- Analysis of Stocks & Commodi-
For many years you have been sible to quantify, and many traders ties, Volume 32: January.
at the forefront of incorporating burn out before they acquire those [2021]. “A Technical Descrip-
advanced concepts like digital skills. Then there is the emotional tion Of Market Data For Traders,”
signal processing into trading. What and psychological aspect of trading. Technical Analysis of Stocks &
advanced concepts do you think will Without technology, trading losses Commodities, Volume 39: May.
dominate trading the next 10–20 are closely linked to personal fail- [2021]. “Windowing,” Tech-
years? Machine learning, artificial ure because the trader blames the nical Analysis of Stocks &
intelligence, etc. losses on bad decisions. Then, the Commodities, Volume 39: Sep-
I am fond of saying that artifi- sense of failure ultimately leads to tember.
cial intelligence is better than real abandonment of trading altogether. Montevirgen Karl [2019]. “Market
ignorance—but not by much. Com- On the other hand, knowing that the Data Insights With John Ehlers,”
puters are really, really dumb. They probability of losses is just part of the interview, Technical Analysis of
have no capacity to draw inferences. game, traders using technology avoid Stocks & Commodities, Volume
Anyone who has done even a little the personal involvement. So, using 37: September.
programming knows that computers technology improves the probability Gopalakrishnan, Jayanthi [2004].
are perversely literal. Computers can of success. “John F. Ehlers of MESA,” in-
make blazingly fast calculations and terview, Technical Analysis of
have a semi-infinite memory, which Now that you are wrapping up a long Stocks & Commodities, Volume
makes them ideal for tasks like pat- and successful career, will traders 22: January.
tern matching. Pattern matching is still be able to access your website, • https://www.mesasoftware.com/
useful for applications like facial rec- software, and work? DSPTutorial.htm
ognition, voice recognition, or even I am keeping my website https://me- • www.micromodeler.com/dsp
making estimates of the best chess sasoftware.com active as a resource
moves. In trading, pattern match- for algorithmic traders. It contains
32 • April 2023 • Technical Analysis of Stocks & Commodities
MARKET RAP
THE WORLD OF RETAIL TRADING
Emilio Tomasini is an adjunct professor of corporate finance at the
University of Bologna in Italy and is a professional trader. He has au-
dited over 5,000 accounts of traders during 13 years of a real-money
trading competition, giving him unique insights into what helps a retail
trader to succeed. He has expertise in technical analysis and trading
Emilio Tomasini
system design. In this column, he shares his sometimes “unserious”
thoughts on serious topics in finance. In his writings, he hopes to help the retail trader better understand the leap
from unprofitable to profitable trader, firmly believing that the right answers can come only if the right questions
are asked. At his website at www.emiliotomasini.com, he offers some of his expertise in a free video course.

LOOK TO EXPLOIT PRICING AND As with most collectors, I often trading—price inefficiencies.
MARKET INEFFICIENCIES find myself surfing maniacally in Looking for price inefficiencies in
(Or, How I Apply Trading Method- the online public auctions all around stock and futures trading is a difficult
ologies To Antiques On Ebay) the world, mostly on eBay, in the concept, so I’ll use helmet-collecting
Being a trader is a kind of obsession. continual hunt for the lucky punch. as an example, a simpler topic.
But oftentimes, the skills involved in In trading, however, we know that On eBay, a pricing inefficiency
trading give you a way to understand “lucky punches” do not exist—it’s only can occur when a seller does not
realities in life that go beyond most price patterns that exist, and we know know the true value of the item. But
people’s comprehension of them. that patterns tend to repeat. A good nowadays, with so much information
I want to make an admission, even trader is somebody who consciously online everywhere and the transpar-
though it could very well have great (systematic trader) or unconsciously ency it brings, it seldom happens that
consequences for my professional (discretionary trader) is able to identify somebody would list an item for sale
career in the financial industry: I am such patterns in the market’s action without first researching comparable
an eBay buyer. and is able to profit from them. items for sale. It only takes a few clicks
That is to say, beyond being a trader to look at similar items already listed
in the financial markets, I am also a The skills involved to see what the seller is asking.
collector. My object of affection is with trading give you In theory, the law of the unique price
military helmets. I really appreciated applies so that all the same helmets
a recent online lecture by Aswath
a way to understand will have the same price in the mar-
Damodaran, a real guru in corporate realities in life that go ketplace. But in reality, discrepancies
evaluation and a professor at New beyond most people’s occur, and not all information is
York University. In the lecture, he in- comprehension of them. known, so mispricing may occur.
cluded “arts and antiques” among the Here’s an example from my eBay
assets that he considers to be in good When I am surfing on eBay and experience. One time I saw a col-
company with real estate, bonds, stock the other public online auctions, I am lection of helmets for sale that were
shares, and so on. Antique military always wondering what the statistical described as all replicas. There were
helmets are in the “militaria” category pattern is that I am looking for. In almost 100 helmets in the collection,
of the antiques sector, and military other words, what pattern will allow in the German WWII style, presum-
helmets represent a large part of this me to build a valuable helmet collec- ably all copies and fakes, or there were
category. I won’t go on too much about tion while paying less than the price some doubts about their originality; in
it. However, Professor Damodaran’s that other collectors would pay? To any case, not real antiques. A serious
lecture inspired me to think about accomplish that, I know it can’t just antiques collector would pass right
and write about some of the pricing be a matter of me being interested in over this listing dismissively, not be-
mechanisms and tendencies that I see this item or that item. So what is this ing interested in putting out money
at play in both the online antiques pattern that drives me in this marvel- for reproductions or inauthentic or
auction marketplaces like eBay and ous hunt for helmets and makes my fake items. However, in examin-
the financial markets. There are les- collection valuable? ing the collection more closely, I
sons from the eBay marketplace that It turns out to be the same thing that
traders can benefit from. traders look for in stock and futures Continued on page 35
April 2023 • Technical Analysis of Stocks & Commodities • 33
Futures For You
INSIDE THE FUTURES WORLD
Want to find out how the futures markets really work? Carley Garner is
the senior strategist for DeCarley Trading, a division of Zaner, where she
also works as a broker. She has written five books on futures and options
trading, with the latest being Trading Commodity Options...With Creativ-
ity (July 2020), as well as A Trader’s First Book On Commodities (third
edition, October 2017) and Higher Probability Commodity Trading (July
2016). Garner also authors widely distributed e-newsletters; for a free
subscription, visit www.DeCarleyTrading.com. To submit a question, email
her at info@carleygarnertrading.com or via www.DeCarleyTrading.com.
Selected questions will appear in a future issue of S&C.
Carley Garner

COMMODITY SPECULATORS anybody; further, trends end quickly speculators.


Do commodity speculators distort and spectacularly, leaving a lot of Although it comes with baggage,
prices and ultimately hurt producers bag holders, including end-users, giving speculators access to open
and consumers? producers, and even speculators. and, ideally, free markets enables
During commodity bull markets, In reality, speculators can contribute individuals and businesses to hedge
without fail, the discussion of whether to runaway prices in the short run, their price risk. By definition,
speculators are doing more harm than but the math has to make sense for hedging price risk is the practice
good to the price discovery process consumers and producers in the long of strategically using financial
arises. Ironically, this topic never run. Reversion to practical pricing is a instruments or market strategies to
materializes in a commodity bear self-correcting mechanism built into offset the risk of any adverse price
market. The answer to this question commodity markets. Also, runaway movements. To illustrate, a corn
involves quite a bit of a gray area commodity trends work in both farmer who has planted but has not yet
and is not without bias depending directions. While bull markets might harvested his crop might want to lock
on what part of the commodity result in higher prices than would in the price of corn to ensure he can
chain one might be a part of. For profit from his business operations.
instance, consumers paying high After all, the price of corn at the
prices at the pump might not have The assumption is time of planting and budgeting rarely
the same view on market speculation producers and retailers matches the price in the fall when the
as a commodity producer due to are price gouging, but crop is harvested. The farmer can lock
differences in experience and a lack of in many cases, they are in his price by selling a corn futures
understanding of the pricing process. contract at the current market price;
As consumers, we tend to get upset
struggling to merely as time goes on, the futures position
about paying higher prices, but we survive; the same can makes money if corn drops, but
don’t always fully comprehend why be said for speculators. his cash crop loses money. On the
prices are higher. The assumption contrary, if corn prices increase, his
is producers and retailers are price have occurred without a speculative futures hedge will lose money, and
gouging, but in many cases, they buying frenzy, bear markets tend to the cash crop will gain in value. The
are struggling to merely survive; the see prices depressed to lower levels goal isn’t to make money on one or
same can be said for speculators. as speculators liquidate or sell short a the other after the time of the hedge;
The media needs a villain, and commodity in hopes of profiting from it is merely to remove the risk of price
speculators fit the bill when market lower prices. It might not seem like it change in the underlying asset.
prices are temporarily distorted. in real-time, but in the end, the impact Pull up a chart of lumber futures
They operate on the assumption that of the two phenomena on consumers if you want to know what the
speculators are making money on (and producers) likely cancels each commodity markets might look like
the backs of society. Yet, the reality other out. In the meantime, as prices without speculators. Despite being a
is an overwhelming percentage of fluctuate between extreme highs staple in the day-to-day lives of most
speculators lose money. A market and lows, market pricing is likely global inhabitants, lumber futures,
trend doesn’t guarantee profits for more stable than it would be without the instrument created to facilitate
34 • April 2023 • Technical Analysis of Stocks & Commodities
Futures For You
price discovery and hedging, are 2021 after suffering a 50% correc-
among the least liquid listed on tion along the way! At the time of Speculators can distort
US futures exchanges. The result the writing of this piece, lumber prices at times, but
is painful slippage upon entering was valued near $400, but the route a lack of speculation
and exiting futures, and especially from $1,700 to $400 was plagued
options, due to wide spreads between with volatility. For example, after the
arguably leads to
the bid (the price you can sell at) and initial decline from $1,700, lumber more market volatility
the ask (the price you can buy at). futures managed to rally from $450 and, therefore, even
The lack of liquidity is the direct to $1,475 before retreating lower into more dramatic price
result of a shortage of speculator the $300s. Seeing the difficulties such distortions.
market participation; if there were price swings have on home builders
more speculators buying and selling and other end users doesn’t take of speculation arguably leads to more
lumber futures, price discovery would much imagination. Similarly, new market volatility and, therefore, even
be less painful, more civilized, and home buyers and those attempting more dramatic price distortions.
more efficient than we see in today’s home improvement projects in recent Despite the drawbacks of speculation
marketplace. years have been on an emotional and in commodity markets, they are
For those who missed the lumber financial roller-coaster. minimal in comparison to those that
frenzy headlines, the price of lumber In conclusion, price discovery come with removing speculation
bottomed out during the spring of perfection and fully efficient markets from the marketplace.
2020 Covid shutdowns near $250 don’t exist in the short run. Speculators

MARKET RAP
and peaked near $1,700 in May of can distort prices at times, but a lack

TOMASINI/MARKET RAP helmet characteristics and I became


Continued from page 33 excited—this helmet could be a good In trading, we know
find. Finally I got to speak to the that “lucky punches” do
found—relying on my expertise in seller over the phone and learned the
the subject matter—two helmets story of the helmet. The seller usu-
not exist—it’s only price
that were originals, and I purchased ally deals in electric guitars and he patterns that exist, and
them at a fraction of the price of what traded an electric guitar that he had we know that patterns
these antiques would normally cost. been unable to sell to someone for tend to repeat.
The seller hadn’t taken the time to the helmet who wanted an electric
appraise every item individually in guitar for their nephew to play. The in the long run. My collection is
the collection, deemed not worthy of seller’s history on eBay bore out treasured by me and it also grows in
his time and expense to do so. the story. I snapped up the helmet, value. And knowing that I’ve made
Two factors helped make this a suc- which turned out to be an ultra-rare smart purchases makes me happy! It
cessful trade for me: some hastiness WWII helmet. So my bargain was feels more worthwhile to do if I don’t
or inattention on the part of the seller, gained from lack of knowledge on the just take the easy way to acquire ev-
and my own extensive knowledge of part of the seller, poor presentation erything. I put research into it.
this category of objects. of the goods for sale, and my own If you are a buyer or collector in
Here’s another example. Once I patience and persistence. It was not something, a takeaway from this story
found a helmet on auction for a tenth for any lack of price discovery in the might be the following: Don’t just
of its likely true market price. But marketplace. look for your dream purchase; look
the pictures in the listing were dark Someone reading this may argue for price inefficiencies. The same
and blurry and there was little and there’s a difference between invest- holds true for the stock market: Don’t
incorrect information in the listing. ing and collecting, in that an investor fall in love with a stock “for richer or
Since I am such a passionate buyer, I looks for appreciation of assets while poorer, for better or worse.” Instead,
took the time and initiative to contact a collector may just be looking for a look for price inefficiencies.
the seller for more details. With more sense of fulfillment. But I would say
photos I could start to make out the the two can easily go hand in hand
April 2023 • Technical Analysis of Stocks & Commodities • 35
Filtering Trades With A Downtrend Pattern

The “Day Drop” Pattern


Here is a price pattern you may not have heard of that What is “day drop”?
you can use as a trade filter to improve system perfor- A daily bar is called a “day drop” (DDr) when its closing
mance. In this article, we’ll step through the process of is at the lower end of the trading range. This downtrend
writing some code to develop a trading strategy, we’ll configuration is more robust the closer the closing price
test adding some rules and conditions—including the is to the session lows.
filtering of trades using this price pattern—and we’ll Figure 1 helps to explain this concept.
review the resulting system performance metrics. This diagram shows that the “daily close” is very close
to the “daily low,” and yesterday’s session closed with a
by Andrea Unger very low value compared to the whole day’s range.

U
In other words, the DDr tells us that the strength of
se price patterns in a trading system? Yes, but the sellers pushed the market down to close the session
never as a starting point. near the lows reached.
At Unger Academy, we teach when and how To check if yesterday’s close was near the session’s
to apply price patterns to different trading ap- low, we’ll use the following code:
proaches. In this article, we’ll discuss the “day
drop”—a downtrend filter that we’ll apply to (closeS(1)-lowS(1)) < DayDropValue*(highS(1)-lowS(1))
a well-diversified basket of instruments, and
VJOM/SHUTTERSTOCK

then test with a real strategy on the most liquid market where the parameter DayDropValue can take on a value
in the world, the S&P 500. between 0 and 1 and tells us the degree of strength of
our DDr: the smaller the DayDropValue, the stronger the
36 • April 2023 • Technical Analysis of Stocks & Commodities
PRICE PATTERNS

FIGURE 2: DAY DROP VALUE SET TO 35% OF THE DAY’S RANGE. In this
example, the DayDropValue is set to 0.35, which provides a reference value
FIGURE 1: THE DAY DROP PRICE PATTERN. A daily bar is called a “day drop” of 35% of the range. There will be a DDr only if yesterday’s closing price was
(DDr) when its closing is at the lower end of the trading range. Here, the daily below this value.
close is very close to the daily low, and yesterday’s session closed with a very
low value compared to the whole day’s range.

downward trend of the last session.


If this line of code is associated with a Boolean variable,
it can take the value true or false depending on whether
the inequality in the line of code above occurred or not. In
other words, the variable will be true or false depending
on whether there was a DDr yesterday or not.
To better illustrate the concept, let’s look at two ex-
amples (Figures 2 and 3).
In the first example (Figure 2), we set a DayDropValue
FIGURE 3: DAY DROP VALUE SET TO 15% OF THE DAY’S RANGE. In this
= 0.35, which, if we put it in our formula, gives us a refer- example, the DayDropValue is set to 0.15, which provides a reference level of
ence value of 35% of the range, so it isn’t too strict. 15% of the range. This parameter is therefore much more restrictive than that
As seen in Figure 2, there will be a DDr only if yes- in Figure 2. Again here, there will be a DDr if yesterday’s closing price is below
terday’s closing price was below this value. this level.
In the second example (Figure 3), we’ve set a Day-
DropValue = 0.15, which gives a reference level of 15%
of the range and is therefore much more restrictive. if (closeS(1)-lowS(1)) < DayDropValue*(highS(1)-lowS(1)) then
As before, we’ll have a DDr if yesterday’s closing price begin
is below this level. countDDr = countDDr+1;
end;
How well can it filter?
We’ve established that the lower the DayDropValue, the countsession=countsession+1;
more selective our filtering will be. Let’s now look at the print(File("C:\test.txt"),datereadable," ",countDDr,"
extent to which DDr can filter, using some simple code ",countsession);
(in PowerLanguage for MultiCharts) that calculates on
daily bars the percentage of occurrences on different Basically, we count all the DDrs that a market has
markets since 2008:

input: DayDropValue(0);
var: countDDr(0), countsession(0),
A daily bar is called a “day
dateInDateTimeFormat(0), datereadable(""); drop” (DDr) when its closing
is at the lower end of the
dateInDateTimeFormat = ELDateToDateTime(date); trading range.
datereadable = FormatDate("dd-MM-yyyy", dateInDate-
TimeFormat);
April 2023 • Technical Analysis of Stocks & Commodities • 37
produced and relate them to
the total number of sessions, countsession countDDr countDDr countDDr
all of which while evaluating
different DayDropValues.
As we all know, as the Day-
DropValue decreases, we’ll
have fewer DDrs; if we use FIGURE 4: FILTERING BY DAY DROP PATTERN. From this table, we see that using a DayDropValue between 15%
this pattern to filter our market and 25% leads to significant filtering.
entries, the number of trades
will be set proportional to the
DayDropValue.

The first test with several instruments


From the table in Figure 4, we see that a DayDropValue
FIGURE 5: TESTING THE FILTER ON A BASKET OF INSTRUMENTS. A Day-
between 15% and 25% already leads to significant filter-
DropValue of 20% was used on a basket of instruments with good results.
ing; therefore, to test DDr on a basket of instruments, we
decide to use a DayDropValue of 20%. setexitonclose;
For the first test, we’ll consider a basket consisting of if stoploss>0 then setstoploss(stoploss);
@ES, @CL, @EC, @GC, and @US futures and apply
the simple strategy shown below to each instrument, with From the results in Figure 5, we can safely say that the
15-minute timeframes and data from 2008 to today. @ES provided the best answer. We, therefore, decided to
The system takes long positions only and enters the create an ad-hoc strategy for this underlying.
market every time there was a DDr in the previous ses-
sion. It then closes the position at the end of the session Let’s develop a simple strategy for
or when the stop-loss of $1,750 is reached, which I chose the mini S&P 500 futures
as an intermediate value between $1,500 and $2,000. Let’s take the code used in the previous section and
test whether adding a time filter on the entries would
input: DayDropValue(0.2), stoploss(1750); improve the system’s performance. To do this, we add
var: daydrop(false), slb(false), MP(0), oktrade(false); the two inputs, myday1 and myday2, to choose only two
weekly trading sessions. This strategy was initially coded
slb=sessionlastbar; in 2017, and based on the data available at the time, I
MP=marketposition; had decided to set myday1 = 2 and myday2 = 4, allow-
ing only the second and fourth sessions of the week to
if slb[1] then begin enter the market.
daydrop = (closeS(1)-lowS(1))<DayDropValue*(highS(1)- We add this new time condition to our code, which
lowS(1)); will change as shown below:
oktrade = true;
end; input: DayDropValue(0.2), stoploss(1750), myday1(2), my-
day2(4);
if oktrade and daydrop then buy next bar market; var: daydrop(false), slb(false), MP(0), oktrade(false), my-
if MP<>MP[1] and MP=1 then oktrade=false; dow(0);

slb=sessionlastbar;
MP=marketposition;

The “day drop” tells us that the if slb[1] then begin


strength of the sellers pushed mydow = dayofweek(d)+1;
the market down to close the daydrop = (closeS(1)-lowS(1))<DayDropValue*(highS(1)-
session near the lows reached. lowS(1));
oktrade = true;
end;
38 • April 2023 • Technical Analysis of Stocks & Commodities
if oktrade and daydrop and (mydow = myday1 or mydow =
myday2) then buy next bar market;
if MP<>MP[1] and MP=1 then oktrade=false; FIGURE 6: TIME FILTER—DAY OF WEEK. Does adding a time filter on the
entries improve the system’s performance? This test allowed the system to enter
setexitonclose; the market on only the second and fourth sessions of the week. The results are
if stoploss>0 then setstoploss(stoploss); shown here. While net profit decreased, drawdown improved and the profit
per average trade increased.
obtaining the new results shown in the table in Figure
6.
The NetProfit of the system has decreased significantly,
FIGURE 7: TIME FILTER—HOUR OF ENTRY. An additional condition was
but this is because we only trade on 2 of the 5 available
tested to enter the market right after midnight as the time of entry for the trades.
days per week; however, the Max DD has halved, and The resulting metrics are shown here. While most metrics are unchanged from
the average trade has increased from $146 to $197. We, the previous iteration of the system in Figure 6, drawdown is reduced.
therefore, decide to keep the chosen time filter.
The S&P 500 futures session starts at 5:00 pm (exchange
time) and ends at 4:00 pm the next day, and given how
the code is set up, we’ll enter the market at the beginning FIGURE 8: LENGTHENING TIME IN TRADE. Could the system’s performance
of the Tuesday and Thursday sessions. However, while be improved by giving the trades more time to develop? This test allowed the
testing in 2017, it occurred to me that starting trading at trades to remain open for up to 4 trading sessions. The results are shown here.
midnight (exchange time) would be beneficial to the sys- You can see that changing from intraday to multiday trading saw an increase
tem, so let us change the single line highlighted in yellow in drawdown, but net profit increased by more than 60% and the average
in the code above with the following instruction: trade rose by about 80%.

if daydrop and Time<1500 and (mydow = myday1 or mydow MaxDays>0 then begin
= myday2) and oktrade then buy next bar market; if Time>=1530 and Time<1600 then sell next bar market;
end;
We’ve inserted an additional condition (Time<1500),
which will allow us to trade on Tuesday and Thursday By optimizing MaxDays with the data available dur-
starting at 0:00 (exchange time); in other words, we’ll ing the initial development, I found leaving the trades
enter the first bar shortly after the stroke of midnight. open up to a maximum of 4 sessions beneficial. So let’s
With the introduction of this new time window, we’ll get set MaxDays=4 and observe the new results, seen in
the metrics shown in Figure 7. Figure 8.
The number of trades hasn’t changed, as we’ve only The change of strategy from intraday to multiday has
moved our entries forward by a few hours. The NetProfit had a substantial impact on the system: we’ve indeed seen
has remained almost the same (and so has the average an increase in Max DD, but NetProfit has increased by
trade), but we have significantly reduced the Max DD more than 60%, and the average trade has risen by about
of the strategy. 80%, reaching an excellent level for the instrument on
which we’re trading.
Can we improve the system further? Can we go even further? The strategy is very simple
We trade intraday, so we close every trade at the end of
the session. What would happen if we gave the trades
more time to develop? To answer this question, let’s enter
a new MaxDays input and a new DaysInTrade variable Let’s now look at the extent to
and replace the exit command setexitonclose with the which DDr can filter, using some
last 4 lines in the following code:
simple code that calculates on
input: MaxDays(0); daily bars the percentage of
var: DaysInTrade(0), occurrences on different markets
since 2008.
if MP<>MP[1] and MP<>0 then DaysInTrade=1;
if marketposition<>0 and DaysInTrade>=MaxDays and
April 2023 • Technical Analysis of Stocks & Commodities • 39
and already gives us excellent metrics; adding special
conditions could improve it, but it would also increase
the risk of overfitting. FIGURE 9: ADDING A TAKE-PROFIT. Would adding a take-profit improve
We, therefore, decided not to introduce any additional drawdown? The results of the test are shown here. The Max DD is indeed
entry rules but only see if using a take-profit could help lowered. Meanwhile, the net profit and average trade are improved, making
us contain the Max DD of the system. the take-profit a good addition to the strategy.
The results shown in Figure 9 are the results after in-
troducing a take-profit of $4,000. As you can see, we’ve
lowered the Max DD while increasing the NetProfit and
average trade, so we’re satisfied with this choice.

Final remarks and insights


We’ve used DDr as a trading filter to trade only long
positions on the @ES, and this pattern has proven to
be very effective. We’ve achieved good results already
with the first system, which led us to develop a complete
strategy suitable for our portfolio.
The final system has few conditions, which convinces
us of the robustness of the strategy. The equity curve
shown in Figure 10 from 2008 to today, covering more
than five years of out-of-sample data, shows that when
the world’s most important stock index was exposed to
significant shocks, our strategy continued its path very

MULTICHARTS
smoothly.

Andrea Unger is a full-time professional trader, president FIGURE10:EQUITY CURVE FOR RESULTING EXAMPLE TRADING SYSTEM.
of The Unger Academy, and author of The Unger Method. The hypothetical equity curve is shown here for the trading strategy result-
He is a four-time World Trading Champion (2008, 2009, ing from using the rules and conditions discussed in this article for trading
2010, and 2012), an honorary member of SIAT (Italian long-only positions on the emini S&P 500 contract (ES). The equity curve is
Society of Technical Analysis, a branch of IFTA), and based on data from 2008 to the present, covering more than five years of
speaks throughout Europe, America, Australia, and out-of-sample data.
Asia. He may be reached at Andrea@UngerAcademy.
com. The Unger Academy provides services to traders,
including individuals, to help them improve their ap-
proach to trading (more information can be found at We’ve used DDr as a trading
https://autc.pro/tasc3). filter to trade only long
The code given in this article is available in the Article positions on the @ES, and this
Code section of our website, Traders.com. pattern has proven to be very
effective.
Further reading
Unger, Andrea [2021]. The Successful Trader’s Guide To
Money Management: Proven Strategies, Applications,
And Management Techniques, Wiley Trading. Filter,” Technical Analysis of Stocks & Commodities,
[2021]. The Unger Method: The Winning Strategy Volume 41: February.
Of The 4-Time World Trading Champion, The Boss
Books. ‡MultiCharts
[2022]. “Filters On The Test Bench,” Technical ‡See Editorial Resource Index
Analysis of Stocks & Commodities, Volume 40:
November.
[2023]. “The Outside Bar: A Rare And Powerful
40 • April 2023 • Technical Analysis of Stocks & Commodities
CMT SYMPOSIUM APRIL 26–29, 2023, explore first principles of the markets have occurred in the markets and in
50-YEAR ANNIVERSARY OF and the utility of technical analysis the world over the past 50 years.
CMT ASSOCIATION in any investment-selection model. Today, the CMT serves more than
The 2023 CMT Association Sympo- Attendees can expand their profes- 10,000 members and candidates, with
sium will be held in New York City sional network and gain new skills monthly educational meetings and
on April 26–28, 2023. This year’s that they can take back to their firms, guest speakers, an annual award to
symposium will celebrate the 50-year their clients, and their portfolios. recognize outstanding contributions
history of the CMT Association and The cost to attend ranges from to the field, and national and inter-
the history of the industry during this $1,499 to $1,899 for CMT Associa- national chapters. The association
period, with a focus on the evolution tion members or $1,649 to $2,049 offers rigorous credentialing, profes-
of technical analysis. for nonmembers. sional ethics standards, and continu-
The symposium will bring together CMTAssociation.org/events/symposium ing education requirements.
a diverse array of speakers across This year’s symposium will honor
different asset classes and arenas of 50-year history of the CMT the heritage and innovation of those
the financial industry. Sessions will Association who contributed to the field over
address the ETF ecosystem, market The CMT Association was formed to the years, all while the association
volatility variation, cross-asset cor- advance the discipline of technical strives to cultivate the community
relations, data visualization methods, analysis and advocate for association for the future.
decision theory, and machine learning members industry-wide. The asso- CMTAssociation.org
algorithms. The sessions are designed ciation, formerly called the Market
to give attendees an understanding of Technicians Association, formed
the forces at play when asset prices in the late 1960s when a group of
and valuations diverge. equity research analysts recognized
This year’s symposium will include the unwarranted gap between funda-
a celebration of several legends in the mental and technical analysts. They
field of technical analysis on the floor wanted to stand up for professional
of the New York Stock Exchange on recognition of technical analysts. The
Thursday evening. organization has sought to elevate
This annual event is an opportunity investors’ skills for mitigating market
for portfolio managers, registered risk and maximizing return in capital
investment advisers, asset allocators, markets. This mission continues to
strategists, traders, and analysts to this day despite all the changes that

AHARONIAN/PATENTS of ideas and inspiration, and in addition, the documents


Continued from page 20 may be little-used. Given that basic patent information
is publicly available, it is a resource worth mastering.
ments to the Black-Scholes model, where individuals or
companies are working to develop new and more profit- Gregory Aharonian is founder of KukaXoco Finance. He
able ways to calculate options prices, going beyond the has two decades of experience consulting in patent and
traditional models. intellectual property law in the US insurance industry.
You will find that some patents relate to highly technical He can be reached at greg.aharonian@kukaxoco.org.
developments while others are simpler. Some patent fil-
ings include some of the mathematics behind an idea. fUrther reaDinG & resoUrCes
Pressman, David [1985]. Patent It Yourself, Nolo
ConCLUsion Press.
You don’t have to be an inventor and formally use the US Patent and Trademark Office, www.uspto.gov
patent system to benefit from patent information. Patent Google Patents, https://patents.google.com
documents can provide a little education on developments
in the field of trading and can be an interesting source
April 2023 • Technical Analysis of Stocks & Commodities • 41
TRADING ON MOMENTUM

Pivot Leading Indicator

Average True Range Breakouts


The ATR was originally designed Reversal after down- Step 1: Visually scan for charts
to indicate when daily ranges are trend: ATR in action that have had multiweek ATR
increasing or decreasing. Here, we You can see the reversal of the red downtrends and are starting to
show you how you can use the indica- ATR line at the bottom of Figure 1, a pivot back up.
tor to spot upside breakouts. chart of Coinbase Global Inc. (COIN)
on January 3, 2023. Shortly after it Step 2: Next, wait until you see three
by Ken Calhoun pivoted and started going back up, or more uptrending days in the stock

T
price action in COIN soon followed. or ETF chart you’re trading.
he problem with many This is a rare, valuable lead indicator
indicators is that they are setup. Once you see the red ATR line Step 3: Use an initial stop-loss of
lagging, which is too late trend up for three or more days, you no further than $2 under your entry.
for active traders. The could enter for a strong uptrending Once you do enter, you can scale in
strategy I will discuss breakout. every several days, as long as the
here produces trading signals ahead trend remains intact to the upside.
of time. The strategy is based on a Step-by-step action plan
simple 14-step average true range Here’s how you can start using this Step 4: Keep an eye on the slope of
(ATR) indicator. strategy: the line of the ATR; once it starts

eSIGNAL

FIGURE 1: TRADING THE ATR REVERSAL, COIN. This shows an example of buying the pivot as price action goes up. The reversal in the red ATR line can be seen
at the bottom of the chart; price soon followed.
42 • April 2023 • Technical Analysis of Stocks & Commodities
to pivot back downwards, then con-
sider exiting your position. Using ATR to spot upside breakouts in this strategy
is different, because it combines trend direction
Why this technique works along with an increase in average true ranges.
The ATR was originally designed
to indicate when daily ranges are
increasing or decreasing. Using it to Trade management tips Ken Calhoun moderates a popular
spot upside breakouts in this strategy As usual, we can use this momentum live trading room for active traders.
is different, because it combines trend strategy to add to winning positions He is the founder of TradeMastery.
direction along with an increase in by scaling in every few days, as long com, an interactive webinar site
average true ranges. This built-in as price keeps trending up. Exit using for active traders, and is a UCLA
combination can be even more effec- typical signals, such as the shooting alumnus.
tive than classic ATR signals. star seen on February 5 in the chart
in Figure 1.

EHLERS/JUST IGNORE THEM However, care should be taken not to get carried away
Continued from page 12 and start folding desired signals back onto the observable
spectrum.
Then, that gap value is mathematically removed from
every sample during the day. This technique removes the John Ehlers, a Contributing Editor to STOCKS & COM-
opening price gap from the overnight period and provides MODITIES, is a pioneer in the use of cycles and DSP (digital
a more continuous function for analysis. The sampling signal processing) technical analysis. After four decades
is conducted only on the hour and at the session closing of dedication to advancing the field of digital signal pro-
time. Otherwise, the previous value of degap is held. So cessing and offering products and services to traders, he
the data is effectively sampled every four bars. The little is retiring from the company he founded, MESA Software.
jitter in the sampling clock due to the time offset of the An interview with him highlighting some of his important
first and last bar of the day doesn’t matter much because research and developments in quantitative and technical
the data are not coherent. analysis appears elsewhere in this issue. Ehlers can be
The beginning date for the indicator is provided as an reached through his website at MESAsoftware.com.
input. This is required because the impact of the opening
gap is cumulative, and the degapped undersampled data The code given in this article is available in the Article
can drift from the absolute values of the prices. Code section of our website, Traders.com.
Just to demonstrate the smoothing process of undersam-
pling, a double moving average type indicator is shown in See our Traders’ Tips section beginning on page 44
Figure 3, using Hann windowed FIR filters. for implementation of John Ehlers technique in various
technical analysis programs and trading platforms. Ac-
conclusion companying program code can be found in the Traders’
I have shown that undersampling removes the high- Tips area at Traders.com.
frequency components in price data. Elimination of these
components is done with less lag than that of conventional fuRtheR Reading
smoothing filters. Quantization lag is only half the under- Ehlers, John F. [2014]. “Predictive And Successful Indica-
sampling step size. This magic is possible because the tors,” Technical Analysis of StockS & commoditieS,
market data is fractal, so the aliased components have a Volume 32: January.
small amplitude relative to the desired signal components. Ehlers, John F. [2021]. “Windowing,” Technical Analysis
Further, the folding of the aliased component into the of StockS & commoditieS, Volume 39: September.
observable spectrum is performed noncoherently.
Undersampling can also be applied to intraday data,
removing the overnight gap openings as well.
The degree of undersampling is designer’s choice.
April 2023 • Technical Analysis of Stocks & Commodities • 43
The focus of Trad- • 
Traders.com  S&C Magazine 
ers’ Tips this month is Traders’ Tips
John F. Ehlers’ article in
this issue, “Just Ignore At Traders.com you can also right-click on any chart
Them: Undersampling to open it in a new tab or window and view the chart
The Data As A Smooth- at a much larger size.
ing Technique.” Here,
we present the April The Traders’ Tips section is provided to help readers
2023 Traders’ Tips code implement a selected technique from an article in this
with possible implementations in various software. issue or another recent issue. The entries here are con-
The code for the following Traders’ Tips selections is tributed by software developers or programmers for
posted here: software that is capable of customization.

inputs:
Price( numericseries ),
Length( numericsimple );
F TRADESTATION: APRIL 2023 TRADERS’ TIPS CODE
In his article in this issue, “Just Ignore Them: Undersampling variables:
The Data As A Smoothing Technique,” John Ehlers explains Count( 0 ),
that data smoothing is often used as a means to help avoid Coef( 0 ),
trading whipsaws. While this can result in fewer trading Filt( 0 );
signals, it can also result in a lag in those trading signals. Filt = 0;
In the article, Ehlers describes how undersampling coupled Coef = 0;
with Hann-windowed finite impulse response (FIR) filters
can be used to remove high-frequency components in price for Count = 1 to Length
data, resulting in less lag than that of traditional smoothing begin
Filt = Filt + (1 - Cosine(360 * Count / (Length +
filters. 1))) * Price[Count - 1];
Coef = Coef +
Function: $Hann (1 - Cosine(360 * Count / (Length + 1)));
end;
{
TASC APR 2023 if Coef <> 0 Then
Function: Hann Windowed Lowpass FIR Filter $Hann = Filt / Coef;
(c) 2021-2022 John F. Ehlers
} Indicator: Undersampled Double MA

{
TASC APR 2023
Undersampled Double MA Indicator
(c) 2022 John F. Ehlers
}

inputs:
FastLength( 6 ),
SlowLength( 12 );

variables:
Sample( 0 ),
FastAvg( 0 ),
SlowAvg( 0 );

Sample = Sample[1];

//Sample every five days


if CurrentBar / 5 = IntPortion(CurrentBar / 5) then
Sample = Close;
FIGURE 1: TRADESTATION. This TradeStation daily chart of the S&P 500 ETF //Find Fast Average using Hann FIR filter
SPY shows a portion of 2022 and 2023 with the undersampled double MA indi- FastAvg = $Hann(Sample, FastLength);
cator applied. A fast length of 6 is used and a slow length of 12 is used. The fast //Find Slow Average using Hann FIR filter
SlowAvg = $Hann(Sample, SlowLength);
average is shown in magenta and the slow average is shown in blue.
44 • April 2023 • Technical Analysis of Stocks & Commodities
Plot1(FastAvg, "FastAvg");
Plot2(SlowAvg, "SlowAvg");

Indicator: Undersampled Intraday Double MA

{
TASC APR 2023
Undersampled Intraday Double MA Indicator
(c) 2022 John F. Ehlers
}

inputs:
BegDate( 1221117 ),
FastLength( 20 ),
SlowLength( 40 );

variables: FIGURE 2: WEALTH-LAB. This sample chart demonstrates a 6- and 12-period Hann filter
Gap(0 ), (5-period undersampled) on the daily chart of the emini S&P 500 futures (ES=F). Data provided
Degap( 0 ),
by Yahoo! Finance.
FastAvg( 0 ),
SlowAvg( 0 );
Degap = Degap[1]; various tools in Wealth-Lab such as Building Blocks (to cre-
ate no-code trading strategies), the Indicator Profiler (which
if Time = 645 then tells how much of an edge an indicator provides), or our
begin Strategy Optimizer.
Gap = Close - Degap[1];
Degap = Close - Gap; With Wealth-Lab’s ability to combine different indicators
end; in a GUI wizard, Hann filters can even be used as a “smooth-
er” to your favorite indicator like MFI, RSI, or momentum.
if Time = 800 or Time = 900 The techniques, common to moving average interpretation,
or Time = 1000 or Time = 1100 apply here as well.
or Time = 1200 or Time = 1315 then
Degap = Close - Gap; Prototyping a trading system, including complex ideas,
doesn’t take much effort with the Building Blocks feature. If
if Date < BegDate then you’re not familiar with Wealth-Lab, our web-based back-
Degap = Close; testing engine is free to use. Create a system (for example,
//Find Fast Average using Hann FIR filter applying the Hann filter to a price or indicator of choice) in
FastAvg = $Hann(Degap, FastLength);
//Find Slow Average using Hann FIR filter its user-friendly interface and run backtests of your strategy
SlowAvg = $Hann(Degap, SlowLength); right in the browser. As a natural next step, your strategy
becomes instantly available in the Wealth-Lab desktop ap-
Plot1(FastAvg, "Fast Avg"); plication for in-depth use. And if the strategy turns out to be
Plot2(SlowAvg, "Slow Avg"); good enough, you could choose to publish it for the benefit
of the Wealth-Lab community of members. Strategies pub-
A sample chart is shown in Figure 1.
lished by community members can be found at https://www.
This article is for informational purposes. No type of
wealth-lab.com/Strategy/PublishedStrategies.
trading or investment recommendation, advice, or strategy —Gene Geren (Eugene)
is being made, given, or in any manner provided by TradeS- Wealth-Lab team
tation Securities or its affiliates. www.wealth-lab.com
—John Robinson
TradeStation Securities, Inc.
www.TradeStation.com

F NINJATRADER: APRIL 2023 TRADERS’ TIPS CODE


The smoothing technique that John Ehlers presents in his
article in this issue, “Just Ignore Them,” using undersampling
F WEALTH-LAB: APRIL 2023 TRADERS’ TIPS CODE and Hann windowing is available for download from the
In his article “Just Ignore Them” in this issue, John Ehlers following links for NinjaTrader 8 and for NinjaTrader 7:
suggests a smoothing method by undersampling the data and
using Hann windowing. NinjaTrader 8: www.ninjatrader.com/SC/April2023SCNT8.zip
NinjaTrader 7: www.ninjatrader.com/SC/April2023SCNT7.zip
The Hann indicator is ready for use in Wealth-Lab 8, al-
lowing the user to choose whether to apply undersampling Once the file is downloaded, you can import the indicator
to the data or leave it as is. You can apply it equally using into NinjaTrader 8 from within the control center by select-
April 2023 • Technical Analysis of Stocks & Commodities • 45
ing Tools → Import → NinjaScript Add-On and then
selecting the downloaded file for NinjaTrader 8. To im-
port into NinjaTrader 7, from within the control cen-
ter window, select the menu File → Utilities → Import
NinjaScript and select the downloaded file.
You can review the indicator’s source code in Nin-
jaTrader 8 by selecting the menu New → NinjaScript
Editor → Indicators from within the control center
window and selecting the file you wish to examine. You
can review the indicator’s source code in NinjaTrader
7 by selecting the menu Tools → Edit NinjaScript →
Indicator from within the control center window and
selecting the file to examine.
NinjaScript uses compiled DLLs that run native, not
interpreted, which provides you with the highest per-
formance possible.
A sample chart displaying the double moving aver-
age as discussed in Ehlers’ article is shown in Figure
3. FIGURE 3: NINJATRADER. This shows an example of the undersampled double
—Chelsea Bell moving average on a daily chart of the emini ES, 11/15/2022 to 2/10/2023.
NinjaTrader, LLC
www.ninjatrader.com
hann (float source, int length) =>
float PIx2 = math.pi * 2.0, filt = 0.0, coef = 0.0
for count = 1 to length
float w = 1.0-math.cos(PIx2*count / (length + 1.0))
filt += w * nz(source[count - 1])
F TRADINGVIEW: APRIL 2023 TRADERS’ TIPS CODE
coef += w
Here is TradingView Pine Script code implementing the float hann = coef != 0.0 ? filt / coef : na
undersampled double moving average indicator described hann
in the article in this issue by John Ehlers, titled “Just
Ignore Them: Undersampling The Data As A Smoothing // @function Undersampled Double Moving Average.
// @param length int . Length period.
Technique.”
// @param samplePeriod int . Sampling period.
// @param source float . Data source.
// TASC Issue: April 2023 - Vol. 41, Issue 5
// @returns float.
// Article: Undersampling The Data As A Smoothing Tech-
udma (int length = 6,
nique.
int samplePeriod = 5,
//. Just Ignore Them.
float source = close
// Article By: John F. Ehlers
) =>
// Language: TradingView's Pine Script™ v5
float sample = sampledSource(samplePeriod, source)
// Provided By: PineCoders, for tradingview.com
//find average using Hann FIR filter:
float result = hann(sample, length)
//@version=5
string title = 'TASC 2023.04 Undersampled Double MA'
string stitle = 'UDMA'
indicator(title, stitle, true)

// @function Samples a source every period of bars.


// @param period int . Period of sampling.
// @param source float . Data source.
// @returns float.
sampledSource (int period = 5, float source = close) =>
var float sample = source
// sample every period:
if bar_index % period == 0
sample := source
sample

// @function Hann Windowed Lowpass FIR Filter.


// @param source float . Data source.
// @param length int . Length period.
// @returns float.
FIGURE 4: TRADINGVIEW. This daily TradingView chart of the S&P 500 index dem-
onstrates the undersampled double moving average (5,6,12).
46 • April 2023 • Technical Analysis of Stocks & Commodities
result

int samplePeriod = input.int( 5, 'Sampling period:',


1)
int fastLength = input.int( 6, 'Fast period:', 1)
int slowLength = input.int(12, 'Slow period:', 1)

float fast = udma(fastLength, samplePeriod)


float slow = udma(slowLength, samplePeriod)

plot(fast, 'Fast UDMA', color.red, 4)


plot(slow, 'Slow UDMA', color.navy, 4)

The indicator is available on TradingView


from the PineCodersTASC account at:
https://www.tradingview.com/u/PineCoders
TASC/#published-scripts.
An example chart is shown in Figure 4.
—PineCoders, for TradingView FIGURE 5: NEUROSHELL TRADER. This NeuroShell Trader chart demonstrates the undersampled
www.TradingView.com intraday double moving average indicator.

F NEUROSHELL TRADER: APRIL 2023 modities section of the NeuroShell Trader free technical
TRADERS’ TIPS CODE support website to download a copy of this or any previous
Using undersampling of the data as a smoothing Traders’ Tips.
technique, as described by John Ehlers in his article in —Ward Systems Group, Inc.
this issue, “Just Ignore Them,” can be easily implemented sales@wardsystems.com
www.neuroshell.com
in NeuroShell Trader by combining some of NeuroShell
Trader’s 800+ indicators. To implement the undersampled
intraday double MA indicator, select “new indicator” from
the insert menu, and use the indicator wizard to set up the F THE ZORRO PROJECT: APRIL 2023 TRADERS’
following indicators: TIPS CODE
All smoothing indicators, such as the simple
Gap Sub(DayOpen(Date,Open,0),DayClose(Date,Close,1)) moving average (SMA) or lowpass filter, trade more lag for
CumGap CumSum( IfThenElse(A not equal B(Momentum( more smoothing. In this issue’s article “Just Ignore Them,”
Gap, 1), 0), Gap, 0) ,0) John Ehlers suggests undersampling the price curves for
PriceSub(Close, CumGap)
SampleFreq 4 achieving a better compromise between smoothness and
Degap SelectiveAvg(Price,A=B(Remainder(CumSum(Ad lag. We can check that out by applying a Hann filter to the
d2(1,0),0), SampleFreq),0),1) original price curve and a five-fold undersampled curve.
FastAvg Hann(Degap, 20) The C code for the Hann filter, from Ehlers’ article, is:
SlowAvg Hann(Degap, 40)
var Hann(vars Data,int Length)
Note that Ehlers’ Hann filter indicator is created using {
NeuroShell Trader’s ability to call external dynamic linked var Filt = 0, Coeff = 0;
libraries (DLLs). After moving the Hann filter code given in int i;
for(i=1; i<=Length; i++) {
the article to your preferred compiler and creating a DLL, Filt += (1-cos(2*PI*i/(Length+1)))*Data[i-1];
you can insert the resulting indicator as follows: Coeff += 1-cos(2*PI*i/(Length+1));
}
1. Select “new indicator” from the insert menu. return Filt/fix0(Coeff );
2. Choose the External Program & Library Calls }
category.
The fix0 function in the denominator has the purpose of
3. Select the appropriate External DLL Call indicator.
working around division-by-zero issues. We will now apply
4. Set up the parameters to match your DLL.
the Hann filter to the undersampled SPY price curve:
5. Select the finished button.
void run()
Figure 5 demonstrates the undersampled intraday double {
moving average indicator.. StartDate = 20220101;
Users of NeuroShell Trader can go to the Stocks & Com- EndDate = 20221231;
BarPeriod = 1440;

April 2023 • Technical Analysis of Stocks & Commodities • 47


set(PLOTNOW);
asset("SPY");

vars Samples = series();


if(Init || Bar%5 == 0)
Samples[0] = priceC(0);
else
Samples[0] = Samples[1];

plot("Hann6",Hann(Samples,6),LINE,MAGENTA);
plot("Hann12",Hann(Samples,12),LINE,BLUE);
plot("Hann",Hann(seriesC(),12),0,DARKGREEN);
}

The resulting chart is shown in Figure 6. The blue


line is the Hann filter of the undersampled curve with FIGURE 6: ZORRO PROJECT. This chart of the daily SPY applies a Hann filter to the
period 12, and magenta line with period 6. For com- original price curve and a five-fold undersampled curve. The blue line is the Hann filter
parison, we’ve added the Hann filter output from the of the undersampled curve with period 12, and magenta line with period 6. The Hann
original curve (green). You can see that the green line filter output from the original curve is shown in green for comparison. You can see that
has less lag but is also less smooth. the green line has less lag but is also less smooth.
A test script for the Hann indicator and undersam-
pling can be downloaded from the 2022 script reposi- that this is simply a case of “source data misalignment. ” It
tory on https://financial-hacker.com. The Zorro platform can turns out that which bar we use to start the sampling and bar
be downloaded from https://zorro-project.com. counting matters. Ehlers’ sampling started with a different
—Petra Volkova bar.
The Zorro Project by oP group Germany
The formulas in this spreadsheet default the starting bar
https://zorro-project.com
of the count to be the most recent bar available (right-most
bar on the chart). But the misalignment problem could be the
same if my count started with the oldest bar available.
F EXCEL: APRIL 2023 TRADERS’ TIPS CODE To adjust the relative starting bar, I introduced an “inter-
In his article in this issue, “Just Ignore Them: Undersampling val offset” in the user controls area. A non-zero “interval
The Data As A Smoothing Technique,” John Ehlers presents offset” value shifts the logical starting bar to the right. With
an interesting approach to reducing the impact of noise in the a sampling interval of 5, valid offset values are 0 through 4.
data (high-frequency components) by way of undersampling Under the covers, higher offset values logically wrap back
the data and taking advantage of the resulting aliasing. into 0 through 4 via a modulo calculation based on the sam-
We can replicate his technique in Excel by using a two- pling interval value.
step computation: An interval offset of 3 produced a chart (Figure 9) that is a
near match to Ehlers’ Figure 2. It was interesting to observe
1: Undersample the data by collecting sample values a set the changes of the fast and slow shapes and crossovers as I
number of bars apart. Then propagate this value forward cycled through the possible interval offset values.
as the sample value for the intervening bars until the next Determining the starting bar for the sampling process be-
sample bar (Figure 7). comes particularly important as new data bars become avail-

2: Compute two weighted


averages of the sample
values using different-length
Hann weighting profiles
(Figure 8).

A careful observer will


notice that the fast and slow
Hann plots presented here do
not quite match Figure 2 in
Ehlers’ article in this issue.
This difference really stands FIGURE 7: EXCEL. To replicate the smoothing technique presented in John Ehlers’ article in this issue, the first step, illus-
out in the right-most 12 or so trated here, is to undersample the data by collecting sample values a set number of bars apart, then propagate this value
bars. After researching this forward as the sample value for the intervening bars until the next sample bar. Here, the closing price value is sampled
difference a bit, I determined every 5 bars, with the value carried forward until the next sample bar.
48 • April 2023 • Technical Analysis of Stocks & Commodities
In Figure 10, I stepped 7
days forward in time without
changing the interval off-
set. Here, the fast and slow
shapes of the right-most bars
look very similar to Figure 7.
(Changing the interval offset
to “4” restored the picture.)
With a sampling interval
of 5, the fast and slow shapes
for mid-plot bars will ex-
FIGURE 8: EXCEL. The next step in Excel is to compute two weighted averages of the sample values using different- hibit a repeating cycle every
length Hann weighting profiles. Here, Hann 6 and Hann 12 averages are used. fifth new bar. This is similar
to what we observed as we
cycled the interval offset
value.
A possible solution would
be to specify a particular
bar date as an anchor for
the sampling interval rather
than an interval offset. And
you might need to keep track
of that date for each symbol
you look at.
To download this spread-
FIGURE 9: EXCEL. Here, an interval offset is chosen (of “3”) to match Figure 2 in John Ehlers’ article in this issue. sheet: The spreadsheet file
for this Traders’ Tip can be
downloaded from www.trad-
ers.com in the Traders’ Tips
area. To successfully down-
load it, follow these steps:

• Right-click on the link


to the Excel file, then
• Select “save target as”
to place a copy of the
spreadsheet file on your
FIGURE 10: EXCEL. Seven days into the future, the fast and slow once again look similar to Figure 1 in John Ehlers’ article hard drive.
in this issue. —Ron McAllister
Excel and VBA programmer
able and older bars drop out of the calculation and charting rpmac_xltt@sprynet.com
window over time.

YOUR ONLINE RESOURCE


FOR TECHNICAL ANALYSIS

Join us on Facebook at www.facebook.com/STOCKSandCOMMODITIES


Follow us on Twitter @STOCKSandCOMM

April 2023 • Technical Analysis of Stocks & Commodities • 49


Free Information From Advertisers
Advertiser Page Advertiser Page How to reach us
For questions, address changes, or
Brokerages Software ordering information for Technical
Interactive Brokers 5 MetaStock 3 Analysis of Stocks & Commodities
ibkr.com/sc-trader MetaStock.com/TASC magazine and its online publications:
Ninjatrader 56 Ninjatrader 56 Toll-free 800 832-4642
ninjatrader.com ninjatrader.com (800-Technical) or:
206 938-0570.
TD Ameritrade 13 Websites
tdameritrade.com Email us at:
Stocks & Commodities 2 circ@traders.com.
Store.Traders.com, Traders.com
Publications Or write to us at:
Stocks & Commodities 2 4757 California Ave. SW,
Store.Traders.com, Traders.com Seattle, WA 98116-4499.
Do your magazines arrive tattered
and torn? Polybagging of magazines
(domestic delivery) is available for
Editorial Resource Index $6/year.
Single back issues from the current
OptionsAnalysis.com. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 NeuroShell Trader (Ward Systems Group) .. . . . . . . . . . 47
year (subject to availability) are $8
TradeStation.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 The Zorro Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 prepaid. Subscribers have access to
our digital archive of all past articles.
www.uspto.gov.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Microsoft Excel. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Individual articles can be purchased
patents.google.com. . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 ChatGPT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 from the Online Store at our website,
Traders.com.
StockCharts.com. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Editorial feedback
MindfullyInvesting.com.. . . . . . . . . . . . . . . . . . . . . . . 23
We always want to know more about
MultiCharts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 the needs of our readers: What kinds of
articles would you like to see more of?
eSignal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
What do you find useful? Address your
Wealth-Lab.com .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 written questions and comments to edi-
tor@traders.com or to: Editor, Stocks
NinjaTrader. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
& Commodities, 4757 California Ave
TradingView. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 SW, Seattle, WA 98116-4499. Sorry, we
cannot perform research on individual
financial questions not related to this
For more information about our advertisers, go to Traders.com/reader where magazine and we cannot respond to
you will find the alphabetized list of this month’s advertisers. For reference, the all mail. Letters or emails containing
list is also printed above along with the corresponding page number for each ad. questions or information that other
Just follow the simple directions below and the advertisers will get your requests readers may enjoy or that relate to
the same day! our articles or technical analysis top-
ics may be published in our Letters to
Step 1: Go to Traders.com/reader and S&C column.
scroll through the list of our current month’s Join us on Facebook at
advertisers.Click the box for each adver- www.facebook.com/
tiser you’d like to hear from. At the bottom STOCKSandCOMMODITIES
of the list, click Continue when finished.
Follow us on Twitter
Step 2: Fill out your contact information @STOCKSandCOMM
and click Send Request. Your request will
To receive information on the products and services listed in the Editorial
then be sent to the advertisers you selected. and Advertisers’ Indexes, go to: Traders.com/reader. These indexes are
And that’s it! published solely as a convenience. While every effort is made to maintain
accuracy, last-minute changes may result in omissions or errors.

50 • April 2023 • Technical Analysis of Stocks & Commodities


FUTURES LIQUIDITY

T
rading liquidity is often over- very high volumes. The greatest number three-year period. Thus, all numbers in
looked as a key technical of dots indicates the greatest activity; this column have an equal dollar value.
measurement in the analysis futures with one or no dots show little Columns indicating percent margin
and selection of commodity activity and are therefore less desirable and effective percent margin provide
futures. The following explains how to for speculators. a helpful comparison for traders who
read the futures liquidity chart pub- Courtesy of CBOT wish to place their margin money ef-
lished by Technical Analysis of Stocks ficiently. The effective percent margin
& Commodities every month. is determined by dividing the margin
value ($) by the three-year price range of
Commodity futures contract dollar value, and then multiply-
The futures liquidity chart shown be- ing by one hundred.
low is intended to rank publicly traded
futures contracts in order of liquidity. Stocks
Relative contract liquidity is indicated Trading liquidity has a significant ef-
by the number of dots on the right-hand fect on the change in price of a secu-
side of the chart. rity. Theoretically, trading activity can
This liquidity ranking is produced by serve as a proxy for trading liquidity
multiplying contract point value times All futures listed are weighted equally and equals the total volume for a given
the maximum conceivable price motion under “contracts to trade for equal dol- period expressed as a percentage of the
(based on the past three years’ historical lar profit.” This is done by multiplying total number of shares outstanding. This
data) times the contract’s open interest contract value times the maximum pos- value can be thought of as the turnover
times a factor (usually 1 to 4) for low or sible change in price observed in the last rate of a firm’s shares outstanding.

Trading Liquidity: Futures


Contracts to
Effective
Commodity Futures Exchange % Margin Trade for Equal Relative Contract Liquidity
% Margin Dollar Profit
S&P 500 E-Mini (Mar ’23) CME 5.8 12.7 2 • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • >>>
Ultra T-Bond (Mar ’23) CBOT 5.3 6.4 2 • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • •>
10-Year T-Note (Mar ’23) CBOT 1.9 7.3 7 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••>
30-Year T-Bond (Mar ’23) CBOT 3.7 6.8 3 ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Soybean Meal (May ’23) CBOT 0.9 2.1 2 ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Soybean (May ’23) CBOT 2.4 5 3 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Russell 2000 E-Mini (Mar ’23) CME 3.3 6.7 2 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
5-Year T-Note (Mar ’23) CBOT 1.3 7.4 10 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Crude Oil WTI (Apr ’23) NYMEX 9.6 6.3 2 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Ultra 10-Year T-Note (Mar ’23) CBOT 2.6 6.8 4 •••••••••••••••••••••••••••••••••••••••••••••••••••••••••
Nasdaq 100 E-Mini (Mar ’23) CME 7.1 15.6 2 ••••••••••••••••••••••••••••••••••••••••••••
2-Year T-Note (Mar ’23) CBOT 0.5 6.3 11 ••••••••••••••••••••••••••••••••••••••
Corn (May ’23) CBOT 7 12.9 11 ••••••••••••••••••••••••••••••••
3-Month Eurodollar (Mar ’23) CME 0.2 4.4 16 •••••••••••••••••••••••••••
3-Month SOFR (Mar ’23) CME 0.2 4.4 16 ••••••••••••••••••••••••••
Euro FX (Mar ’23) CME 2.2 13.4 9 ••••••••••••••••••••••••••
Natural Gas (Apr ’23) NYMEX 20 6.5 3 •••••••••••••••••••••••••
Gold (Apr ’23) COMEX 4.4 21.5 5 •••••••••••••••••••
Wheat (May ’23) CBOT 8.8 9.8 6 ••••••••••••••
Gasoline RBOB (Apr ’23) NYMEX 7.8 9.1 2 •••••••••••••
S&P 500 VIX (Mar ’23) CFE 54.7 19.6 3 •••••••••••••
Sugar #11 (May ’23) ICE/US 6.5 11.7 15 •••••••••••••
30-Day Fed Funds (Apr ’23) CBOT 0.1 2.7 10 •••••••••••
ULSD NY Harbor (Apr ’23) NYMEX 11.1 12 2 •••••••••••
Dow Futures Mini (Mar ’23) CBOT 8 17.5 3 ••••••••••
Live Cattle (Apr ’23) CME 2.7 5.2 6 •••••••••
Japanese Yen (Mar ’23) CME 4.4 13.4 6 ••••••••
Coffee (May ’23) ICE/US 10.4 20.4 5 ••••••
Cotton #2 (May ’23) ICE/US 12 13.1 5 ••••••
British Pound (Mar ’23) CME 4.1 22 14 ••••
Hard Red Wheat (May ’23) KCBT 8 13.1 7 ••••
High Grade Copper (Mar ’23) COMEX 6.2 12.7 4 ••• CBOT Chicago Board of Trade, Division of CME
Lean Hogs (Apr ’23) CME 5.6 9.8 10 ••• CFE CBOE Futures Exchange
Mexican Peso (Mar ’23) CME 5.3 18 24 ••• CME Chicago Mercantile Exchange
Palladium (Jun ’23) NYMEX 16 11.9 1 ••• COMEX Commodity Exchange, Inc. CME Group
Australian Dollar (Mar ’23) CME 3.2 17 15 •• ICE-EU Intercontinental Exchange-Futures—Europe
Canadian Dollar (Mar ’23) CME 2.1 16.1 21 •• ICE-US Intercontinental Exchange-Futures—US
Canola (May ’23) ICE/CA 6.9 14.3 24 •• KCBT Kansas City Board of Trade
Cocoa (May ’23) ICE/US 5.7 24 30 •• MGEX Minneapolis Grain Exchange
Crude Oil Brent (F) (Apr ’23) NYMEX 9 11.1 3 •• NYMEX New York Mercantile Exchange
Platinum (Apr ’23) NYMEX 7.4 17.6 10 ••
Silver (Mar ’23) COMEX 8.8 19.5 4 •• 2304
Trading Liquidity: Futures is a reference chart for speculators. It compares markets “Relative Contract Liquidity” places commodities in descending order according to
according to their per-contract potential for profit and how easily contracts can be bought how easily all of their contracts can be traded. Commodities at the top of the list are easi-
or sold (i.e., trading liquidity). Each is a proportional measure and is meaningful only est to buy and sell; commodities at the bottom of the list are the most difficult. “Relative
when compared to others in the same column. Contract Liquidity” is the number of contracts to trade times total open interest times a
The number in the “Contracts to Trade for Equal Dollar Profit” column shows how volume factor, which is the greater of:
many contracts of one commodity must be traded to obtain the same potential return In volume
as another commodity. Contracts to Trade = (Tick $ value) x (3-year Maximum Price 1 or exp –2
In 5000
Excursion).

April 2023 • Technical Analysis of Stocks & Commodities • 51


ADVISORY SERVICES SOFTWARE CLASSIFIED

Yes, You Can Cash In On Chaos! Certified


Chaos Traders Courses teach you how.
Learn to earn at http://moneytide.com?r=s TO ADVERTISE CONTACT:
EMini MoonTide Hotline up 252 months in a row
http://daytradingforecasts.com?r=s Ed Schramm
ESchramm@traders.com • (206) 660 8577

TRADERS'
RESOURCE

TOP 10 VIEWED forex brokerages


LINKS
Foreign exchange traders have
more choices than ever in their Product Company
ongoing search for speed,
pricing efficiency, and good 1. Interactive Brokers Interactive Brokers
accounting when it comes to
forex brokerages. First, you 2. NinjaTrader Brokerage NinjaTrader Group, LLC
must find a forex brokerage
that handles your particular 3. Striker Securities, Inc. Striker Securities
currency cross or pair. You should also look at
margin requirements/leverage, and whether the 4. Robbins Trading Company Robbins Trading Company
broker offers a mini account. With a little research,
5. Dallas Commodity Company, Inc. Dallas Commodity Company, Inc.
you will be able to find a forex brokerage targeted
on your interest. 6. AGN Futures AGN Futures
Your first question might be, “How fast can I
execute an order?” Test out a demo account offered 7. FXCM Forex Capital Markets LLC
by the brokerage. This gives you the opportunity to
see if the prices on the screen are actually honored 8. TradeStation TradeStation
and the speed at which your order gets executed.
A forex brokerage’s ability to provide market 9. GFF Brokers Global Futures & Forex, Inc.
statistics, hedging activity reports, and other such
information may be critical to your trading and 10. TradeView Forex TradeView Ltd.
investing decisions.
These are the 10 Forex Brokerage listings clicked on most often on the Traders’ Resource website,
For more complete information, see the Traders’ in order of clicks received. This is not an editorial rating or ranking. For more information on spe-
Resource area at our website, Traders.com. cific products and services, try checking store.Traders.com for archived S&C product reviews.

TRADERS’ RESOURCE AT TRADERS.COM


Traders’ Resource is available at our website where you’ll Resource link. Then follow the Brokerages category link,
not only find the brokerages listing, but also numerous or use the search feature to find products or services with
other categories, such as data services, seminars, hardware, specific attributes in this or other categories.
software, and trading systems. Just click on the Traders’

The information in Traders’ Resource is the most accurate at the time of posting and is subject to change. Because the vendors posting to Traders’ Resource are responsible for their own listing, Technical Analysis, Inc. declines any and all
liability for any representations made by the businesses and individuals listed. Nor can Technical Analysis, Inc. endorse any business or individual listed on Traders’ Resource. Technical Analysis, Inc. makes no warranties, express or implied,
as to the accuracy and reliability of claims herein. You agree to release Technical Analysis, Inc., together with its respective employees, agents, officers, directors and shareholders, from any and all liability and obligations whatsoever in
connection with or arising from your use of Traders’ Resource. If at any time you are not happy with the information posted to Traders’ Resource or object to any material within Traders’ Resource, your sole remedy is to cease using it. This
list is updated frequently. If you are aware of a business that should be listed, please email us at Editor@Traders.com.

52 • April 2023 • Technical Analysis of Stocks & Commodities


The following selection of book descriptions represents a sampling of recent book technical indicators to be adaptable to different
releases in the investing field. Books described here may be from some of the major markets and different market conditions. The
book publishers as well as some independent book publishers. These are not critical author states that successful trading isn’t about
reviews or editorial evaluations, but rather a brief look at the book marketplace to luck or gaming talent, but rather, it’s about being
help keep readers up to date on new or recent book offerings. a keen observer of market price patterns. She
writes that successful traders do their homework by
researching the markets and properly backtesting
The Breakout Trading Revolution: One technical algorithm trading systems. Traders can learn to identify the patterns
Proven Trading Formula, Endless Strate- that repeat in different ways and in different forms and can trade on these
gies, And How To Attain Ultimate Trading patterns and trends. The author has spent years studying time series behavior
Freedom (175 pages, October 2022, softcover of stocks, stock indexes futures, currencies, and commodities futures, and has
978-981-18-5241-1, ebook 978-981-18-5240- been testing and refining systems according to different markets’ behaviors.
4), by Tomáš Nesnidal, published by Better She has written several articles for S&C, including “Trading Trends With The
Trader, Pte. Ltd. Tomas Nesnidal has been a Bollinger Bands Z-Test” (March 2006) and “The Adjustable-Bands Z-Test”
full-time trader for over 11 years, specializing (December 2011), found in the article archives at Traders.com.
in breakout strategies. He is cofounder of Better Amazon.com
Trader Academy and host of the “Systems On The
Road” podcast. In 2017, he launched a hedge Build Your Wealth And Keep Your Health (156
fund specializing in breakout trading techniques. Today he manages portfolios pages, softcover $12.95, ebook $7.99, 2022, ISBN
for institutional clients while also seeking to help individual traders achieve 978-1506907987) by Dan Geller, PhD, indepen-
trading success. This book tells how he learned his craft and he shares what dently published using First Design Publishing.
he found to be the keys to success for him. He presents the mindset shift he This book explains how independent investors
made that opened up new possibilities for him, how he came to specialize in can invest with better predictability to stop los-
one approach to streamline all his trading efforts, and how he developed an ing sleep over their portfolio. The author writes
automated, algorithmic approach to trading. He then goes on to share the that most investors make investment decisions
breakout trading approach he developed, which he considers his formula for based on what their instincts or emotions are
success. He uses this approach to build breakout strategies for any market. telling them to do, which are often wrong. The
Finally in the book, the author interviews some of his most successful past book discusses how investors’ anxiety naturally
students to have them describe how they were able to learn and implement increases during periods of market volatility, causing them to default to their
the process, with numerous case studies provided. The book includes discus- instinctive-response mode as a survival mechanism, leading to impulsive
sion of indicators, filters, time parameters, exits, lessons from losses, and decision-making. He presents what he feels is a more sound investing approach
sample breakout strategies. It also includes sample code to help the reader that can help investors improve their investment outcomes, based on using
get started developing and testing their own breakout strategies, and includes an analytical approach. Geller is a behavioral economist and the book reflects
example strategies for different markets, with backtests and forward analysis research from the field of behavioral economics and finance on how people
as a demonstration for what the reader can expect when developing their make investment decisions. The author states his goal is to use the principles
own strategies. Also included is a model workbook with exercises and best of decision science to help people reduce their anxiety over money.
practices for implementing the breakout model, and a video that walks the FirstEditionDesignPublishing.com
investor through how to cross-validate breakout strategies.
www.TheBreakoutTradingRevolution.com J.K. Lasser’s Your Income Tax 2023: For Prepar-
ing Your 2022 Tax Return (928 pages, hardcover
Algorithm Trading 101: Trading Made Simple $26.95 ISBN 978-1-394-15768-6, ebook $16 ISBN
For Everyone, second edition (217 pages, 2022, 978-1-394-15770-9, December 2022) by J.K.
ISBN 979-8704070009) by Jacinta Chan, PhD, Lasser, published by Wiley. This guide offers
independently published using Amazon Digital hands-on practical advice for anyone getting ready
Services LLC. This is a guide to building algorithmic to file their personal tax return in the US for the
trading models that could help decipher market 2022 calendar year. It includes information about
patterns and detect trends in today’s rapidly changes to the 2022 US tax code, worksheets and
changing markets. The author holds that trad- forms to use for filing taxes, and advice on how to maximize credits and
ers need a proven statistical trading edge that deductions, with the goal of helping people to understand how to legally
generates net profitable returns in the long run. keep as much money as possible. The latest edition discusses recent US tax
This edition discusses how this statistical trading court decisions and IRS rulings that affect deductions and credits. It includes
edge can be built into a do-it-yourself algorithmic technical trading model. tax-planning strategies for saving money, and tips on filing tax returns.
The book begins at ground level introducing the concepts, then builds on that Wiley.com
with technical analysis and mechanical trading systems, and finishes with algo
trading systems. The author discusses creating hybrid trading models that make
use of the best combination of neural network and moving average–based
April 2023 • Technical Analysis of Stocks & Commodities • 53
Algo Q&A
ALGORITHMIC TRADING
Have a question about system or algo trading? Kevin J. Davey has over
30 years of system trading experience. Kevin is a full-time trader, and also
teaches and consults via his Strategy Factory online workshop (https://
kjtradingsystems.com). He is the author of five bestselling trading books,
including “Building Winning Algorithmic Trading Systems” and his latest
book “Algo Trading Cheat Codes.” Send your questions or topic suggestions
to Kevin Davey at kdavey@kjtradingsystems.com. Selected questions will
appear in a future issue of S&C.
Kevin J. Davey

CHATGPT trading algorithm, and it is written in strategy. Maybe one day it will. And
Everyone is talking about ChatGPT my requested language, TradeStation it certainly could create a profitable
for algo trading. Can you explain EasyLanguage. The code actually strategy by chance.
how that might go? verifies in TradeStation, So this is a So, at least right now, ChatGPT
ChatGPT seems to be today’s working strategy. Nice! is not the answer to developing
hot topic in many fields, including That said, just because I asked it profitable algo strategies. But it
algorithmic trading. For those of you for a “good” (meaning profitable) could be a useful tool for the trader’s
who do not know, ChatGPT is an strategy, that doesn’t mean it actually toolbox. Here’s how:
artificial intelligence (AI) tool that is good. In fact, I tested this strategy
was recently released to the public with various markets, and as is, 1. ChatGPT can write code for
(https://openai.com/blog/chatgpt). without any code changes, it generally many trading platform languag-
You ask it a question and ChatGPT loses money. es. For a new programmer, this
will provide an answer. As we will In other words, ChatGPT is smart, can make it very useful. Simply
see, it will not always be the right but not that smart. It does not know give it general instructions such
answer, but it will be an answer. how to create a profitable trading as “provide me breakout strategy
The possibilities for ChatGPT are
endless. High school and college
students have found it to be a great
tool for writing papers and essays,
although that is not really ethical.
Website content creators now have a
quicker way to write in-depth articles.
Many fields are being affected by Chat
GPT—but what about trading?
I decided to give ChatGPT a try
recently. I asked it to give me a good
algo for trading. Figure 1 shows what
it provided.
At first glance, this is pretty
impressive. ChatGPT gave me a

In other words, it
can be a great source
of inspiration, and
most algo traders are
continually looking for
CHATGPT

new strategies. FIGURE 1: CHATGPT-PRODUCED STRATEGY. Here is the response I received from ChatGPT when I
requested it to come up with a good algo strategy for trading.
54 • April 2023 • Technical Analysis of Stocks & Commodities
Algo Q&A
code for NinjaTrader 8” and it 1. It frequently has coding mis-
could provide a good start. takes, which will take time for Given the current status
2. The tool can provide new trading an inexperienced programmer of ChatGPT, I don’t see it
ideas. Prompts like “provide a to debug. eliminating the need for
simple mean reversion strategy” 2. It does not test or validate any
might give the user a whole new code it provides; the trader still algo traders to properly
strategy or group of strategies to has to test the strategy with actual test and validate their
try. In other words, it can be a market data. models.
great source of inspiration, and 3. As more traders utilize it, any
most algo traders are continually good trading ideas the tool comes
looking for new strategies. up with will quickly be shared this tool to experiment and try new ap-
3. ChatGPT can translate from one amongst users—possibly render- proaches out. I suspect as I get better
trading programming language ing the idea ineffective. at asking ChatGPT questions, it will
to another. If you have, for ex- provide better trading strategies. For
ample, NinjaTrader code, you Given the current status of Chat- anyone interested, I’ll be document-
might be able to have ChatGPT GPT, I don’t see it eliminating the ing my ongoing ChatGPT tests on
turn it into, say, EasyLanguage need for algo traders to properly test my YouTube Channel: https://www.
code for use in TradeStation. and validate their models. But at the youtube.com/@AlgoTradingWith-
same time, I do see it making pro- KevinDavey (Playlist “ChatGPT”).
All those good aspects notwith- gramming easier, and also providing
standing, ChatGPT, in its current fresh ideas for a trader to test.
form, is limited for algo traders: For my own trading, I plan on using

METGHALCHI & HAYES/GLD at Metghalchim@uhv.edu.


Continued from page 27 Linda Hayes, PhD, is a professor of marketing at the
University of Houston-Victoria College of Business.

than B&H. FURTHER READING


In addition, for short-term traders, we provide in Figure Metghalchi, Massoud, and Peggy A. Cloninger [2022].
4 another three technical trading rules combined with “Trading Natural Gas Using UNG,” Technical
the four strategies (the long/short approaches discussed Analysis of StockS & commoditieS, Volume 40:
earlier) that in our tests beat the risk-adjusted performance September.
of the B&H strategy. Coppock, E. [1962]. “The Madness Of Crowds,” Bar-
Generally, traders with a low tolerance toward risk ron’s, October 15, 1962.
could choose to combine one of these trading rules with Steiner, Karl, “Investing Over Time,” Mindfully Invest-
strategy 1, and traders with a high tolerance toward risk ing: Using Mindfulness To Make Better Investing
could choose to combine one of these trading rules with Decisions, https://www.mindfullyinvesting.com/
strategy 3. articles/8-investing-over-time
‡TraderCode, ‡StockCharts.com
Massoud Metghalchi, PhD, is a professor of finance at ‡See Editorial Resource Index
the University of Houston-Victoria. He may be reached

YOUR ONLINE RESOURCE


FOR TECHNICAL ANALYSIS
Join us on Facebook at www.facebook.com/STOCKSandCOMMODITIES
Follow us on Twitter @STOCKSandCOMM

April 2023 • Technical Analysis of Stocks & Commodities • 55


We are honored to be recognized as a
top trading software provider in the
Readers’ Choice Awards.

WINNER: Stand Alone Analytical Software $$$

Thank you to all who voted for NinjaTrader’s industry


leading platform & brokerage services.
Futures, foreign currency and options trading contains substantial risk and is not for every
investor. Only risk capital should be used for trading and only those with sufficient risk capital
should consider trading.

ninjatrader.com

You might also like