The Best Broker! 15 000 $ Welcome Bonus!
10 000$ welcome bonus!
The Best Binary Options Broker 2020!
Perfect For Beginners and Middle-Leveled Traders!
Free Demo Account.
Get Your Sign-Up Bonus Now!
Recommended Only For Experienced Traders!
How to Use a Moving Average to Buy Stocks
The moving average (MA) is a simple technical analysis tool that smooths out price data by creating a constantly updated average price. The average is taken over a specific period of time, like 10 days, 20 minutes, 30 weeks or any time period the trader chooses. There are advantages to using a moving average in your trading, as well as options on what type of moving average to use. Moving average strategies are also popular and can be tailored to any time frame, suiting both long-term investors and short-term traders.
- A moving average (MA) is a widely used technical indicator that smooths out price trends by filtering out the “noise” from random short-term price fluctuations.
- Moving averages can be constructed in several different ways, and employ different numbers of days for the averaging interval.
- The most common applications of moving averages are to identify trend direction and to determine support and resistance levels.
- When asset prices cross over their moving averages, it may generate a trading signal for technical traders.
- While moving averages are useful enough on their own, they also form the basis for other technical indicators such as the moving average convergence divergence (MACD).
Why Use a Moving Average
A moving average helps cut down the amount of “noise” on a price chart. Look at the direction of the moving average to get a basic idea of which way the price is moving. If it is angled up, the price is moving up (or was recently) overall; angled down, and the price is moving down overall; moving sideways, and the price is likely in a range.
A moving average can also act as support or resistance. In an uptrend, a 50-day, 100-day or 200-day moving average may act as a support level, as shown in the figure below. This is because the average acts like a floor (support), so the price bounces up off of it. In a downtrend, a moving average may act as resistance; like a ceiling, the price hits the level and then starts to drop again.
The price won’t always “respect” the moving average in this way. The price may run through it slightly or stop and reverse prior to reaching it.
As a general guideline, if the price is above a moving average, the trend is up. If the price is below a moving average, the trend is down. However, moving averages can have different lengths (discussed shortly), so one MA may indicate an uptrend while another MA indicates a downtrend.
Types of Moving Averages
A moving average can be calculated in different ways. A five-day simple moving average (SMA) adds up the five most recent daily closing prices and divides it by five to create a new average each day. Each average is connected to the next, creating the singular flowing line.
Another popular type of moving average is the exponential moving average (EMA). The calculation is more complex, as it applies more weighting to the most recent prices. If you plot a 50-day SMA and a 50-day EMA on the same chart, you’ll notice that the EMA reacts more quickly to price changes than the SMA does, due to the additional weighting on recent price data.
Charting software and trading platforms do the calculations, so no manual math is required to use a moving average.
One type of MA isn’t better than another. An EMA may work better in a stock or financial market for a time, and at other times, an SMA may work better. The time frame chosen for a moving average will also play a significant role in how effective it is (regardless of type).
Moving Average Length
Common moving average lengths are 10, 20, 50, 100 and 200. These lengths can be applied to any chart time frame (one minute, daily, weekly, etc.), depending on the trader’s time horizon.
The time frame or length you choose for a moving average, also called the “look back period,” can play a big role in how effective it is.
An MA with a short time frame will react much quicker to price changes than an MA with a long look back period. In the figure below, the 20-day moving average more closely tracks the actual price than the 100-day moving average does.
The 20-day may be of analytical benefit to a shorter-term trader since it follows the price more closely and therefore produces less “lag” than the longer-term moving average. A 100-day MA may be more beneficial to a longer-term trader.
Lag is the time it takes for a moving average to signal a potential reversal. Recall that, as a general guideline, when the price is above a moving average, the trend is considered up. So when the price drops below that moving average, it signals a potential reversal based on that MA. A 20-day moving average will provide many more “reversal” signals than a 100-day moving average.
A moving average can be any length: 15, 28, 89, etc. Adjusting the moving average so it provides more accurate signals on historical data may help create better future signals.
Trading Strategies – Crossovers
Crossovers are one of the main moving average strategies. The first type is a price crossover, which is when the price crosses above or below a moving average to signal a potential change in trend.
Another strategy is to apply two moving averages to a chart: one longer and one shorter. When the shorter-term MA crosses above the longer-term MA, it’s a buy signal, as it indicates that the trend is shifting up. This is known as a “golden cross.”
Meanwhile, when the shorter-term MA crosses below the longer-term MA, it’s a sell signal, as it indicates that the trend is shifting down. This is known as a “dead/death cross.”
Moving averages are calculated based on historical data, and nothing about the calculation is predictive in nature. Therefore, results using moving averages can be random. At times, the market seems to respect MA support/resistance and trade signals, and at other times, it shows these indicators no respect.
One major problem is that, if the price action becomes choppy, the price may swing back and forth, generating multiple trend reversal or trade signals. When this occurs, it’s best to step aside or utilize another indicator to help clarify the trend. The same thing can occur with MA crossovers when the MAs get “tangled up” for a period of time, triggering multiple losing trades.
Moving averages work quite well in strong trending conditions but poorly in choppy or ranging conditions. Adjusting the time frame can remedy this problem temporarily, although at some point, these issues are likely to occur regardless of the time frame chosen for the moving average(s).
The Bottom Line
A moving average simplifies price data by smoothing it out and creating one flowing line. This makes seeing the trend easier. Exponential moving averages react quicker to price changes than simple moving averages. In some cases, this may be good, and in others, it may cause false signals. Moving averages with a shorter look back period (20 days, for example) will also respond quicker to price changes than an average with a longer look back period (200 days).
Moving average crossovers are a popular strategy for both entries and exits. MAs can also highlight areas of potential support or resistance. While this may appear predictive, moving averages are always based on historical data and simply show the average price over a certain time period.
Investing using moving average, or any technique requires an investment account with a stockbroker. Investopedia’s list of the best online brokers is a great place to start your research on the broker that fits your needs the most.
Trading Moving Average Crossover Strategy
Hello, traders. Welcome to Day Trading Binary Options. In this lesson, you
will learn how to use moving-average crossovers to trade fast-paced
environments and scout the markets, as well as day trade end-of-day
expiration options. But first of all, let’s learn what a moving average is.
Well, moving averages are indicators that smooth price action and filter
out market noise. They are trend-following indicators and define the
current direction with a lag. Like its name implies, these indicators are
the average of price of a financial asset over a specific period of time.
For example, a [inaudible 00:42] moving average calculates the average
price in the last five periods. So on a 15-minute chart, a moving average
calculates each period as 15 minutes, one candle. This means that if you
plot the five-period moving average on a 15-minute chart, this moving
average will calculate the average of the last five periods or of the last
five 15-minute candles to draw the actual moving average on the chart.
There are two kinds of moving averages: a simple moving average and an
exponential moving average. The difference between them is simple, and it’s
that the calculation of the exponential moving average gives more weight to
the more recent prices. So the exponential moving average reacts faster to
price fluctuations. And of course, it’s up to you if you want to use the
simple moving average or the exponential moving average. But for this case,
or for these systems that we’re going to teach you, we are going to use the
exponential moving averages because we want to get as fast as we can in the
markets without actually losing, or without actually missing the move.
The more periods you choose to calculate the moving average, the more it
lags with price action. Here’s an example of the lagging factor. Here’s a
20-period moving average on a one-hour chart. As you can see, the 20-period
moving average goes very close to price and reacts with every time price
fluctuates. For example, you can see that when we were in a down-move, the
moving average was pointing down and was being drawn down. When we hit this
turning point and the price moved above the moving average, the moving
average quickly turned to the upside. Every time price corrected, the
moving average flattened a little bit, until we hit this period of range or
chopping it where the moving average is completely flat.
Unlike the 200-period moving average, that reacts very slowly to price. As
you can see here, this is the same one-hour chart. The only difference is
that we have plotted here the 200-period moving average. You can see that
because it uses the last 200 candles to calculate the actual indicator, it
lags so much more than the 20-period moving average. This is basically the
difference or the lagging factor that we were talking about in the previous
Well, the 200-period moving average is mostly used to calculate . . . not
to calculate, but to look for heavy areas of resistance and support and to
actually know if the market overall trend has changed. For the system or
the crossover system we will use, much faster moving averages because we
will be scalping or day trading, and we want to actually get in the move at
the bottom of it or at the top of it. If we are using a 200-period moving
average or a 100-period moving average, we will get very few signals, and
we will be late to the actual move. But let me go further and show you what
we actually mean.
Before we go any further, we actually want to show you that moving averages
can also act as support and resistance. A moving average can be used as
support or resistance in the up and downtrends. This is important for you
to learn because when we are using the crossover systems, you will see that
we will be trying to trade with the trend direction. Of course, if we hit a
turning point, we will be countered in trading. But when we are in a very
aggressive trending market, we are going to wait for directions, and then
trade with the direction of the market to make it easy on our trading.
The more periods you choose for your moving average, the more precise the
setups will be. Okay. So here’s an example of a 12-period moving average
acting as support and a 30-period moving average acting as resistance.
Here’s an example of a chart in a very aggressive up-move. As you can see,
we have plotted the 30-period moving average on it, and it acted as support
here once, twice, three times, and four times.
Here’s the same 30-period moving average, but in a very aggressive down-
move. You can see that we corrected to the upside and acted here and found
a resistance here and here. This can also be called resistance because
there are fake-outs. But for this lesson, we will focus on actual rejection
of the 30-period moving averages. This is important because as you can see
here, this is just one moving average, but you will see that when we
actually are learning how to use the crossover, these steep corrections or
deep corrections to the opposite side of the trend will give us nice
signals and nice crossovers to trade with the market direction. Of course,
you already know that trading with the market direction makes things a lot
easier than trying to find tops and bottoms.
But with this moving average crossover, you can actually counter-trend
trade if we hit a heavy [inaudible 07:07] of support or resistance, but
more of that on the following slides. So the moving average crossovers,
there are common ways to actually use this indicator. The idea here is to
use one moving average faster than the other. The faster moving average is
called the trigger. Why it’s called the trigger? Because when it actually
crosses over or crosses below the slower moving average, we get the trigger
to buy either calls or puts on the instrument that we are monitoring or
analyzing. So the length of the moving average in the system defines the
timeframe and expiration options for the system. This is very important.
If we are going to use faster moving averages and we choose to scalp the
market, we are going to analyze price action on the lower timeframes and
choose a lower expiration time. For example, if we use the 15 and 30-period
moving average, we will choose to day trade the hourly to end-of-day
expiration options, and this is an example. If we choose a much slower
moving average crossover system, like the 50 to 200-period moving average
crossover, we’ll be better off trading the weekly expiration options and
analyzing price action on the four-hour charts, because the 50 and 200-
period moving averages are used on a much slower environment.
Remember that the higher you go on the timeframes on your charting
platform, the less market noise you will have, so the less fluctuations and
the less crossovers you will have if you use much lower moving average
crossover systems on the higher timeframes. But these are just examples.
These are not the actual systems that we are going to learn.
In this lesson, we will teach you how to use two different systems. The
first system is the 15 and 30-moving average crossover on the hourly charts
for end-of-day expiration options, and this is basically what we are going
to do with the 15 to 30-minute . . . I’m sorry . . . with the 15 and 30-
period moving average crossovers. We are going to analyze the hourly chart
and choose to trade the end-of-day expiration options. But if you like to
be, if you’re not comfortable holding on a trade for an end-of-day
expiration, we will teach you a 7-11 AM moving average crossover on the
five-minute chart, that you can use to trade the 15-minute to the hourly
expiration options. Okay? Now, let’s go and let’s jump into the faster
moving average crossover system, which is the seven and 11-period moving
The general rules here are that the system is meant to be used in fast-
paced environments and lower timeframes for short trades. A bullish signal
is when the seven-moving average crosses above the 11-moving average, and a
bearish signal is when the seven-moving average crosses below the 11-moving
average. This is simple. We buy calls when we have a bullish signal, and we
buy puts when we have a bearish signal.
Remember that this system is meant to be used on the five-minute charts and
be traded with the 50-minute to hourly expiration options. Here’s an
example of a bullish signal, using the seven/11-period moving average
crossover. You can see right here that we have actually the black moving
average in the seven-period moving average, and the orange moving average
is the 11-period moving average.
When we have a crossover of these two moving averages, when the seven-
period moving average crosses above the 11-period moving average, we have a
signal to buy calls. Here, this is the five-minute Aussie/US dollar chart.
If you choose to trade a 50-minute expiration option right here after the
crossover, one, two, three, our option would have expired in the money, as
well as the hourly.
Here is an example of a bearish signal to buy puts on the US
dollar/Japanese yen five-minute chart. Even though we are in a steep up-
move, we have a turning point. Okay? When the seven-period moving average
crosses below the 11-period moving average, we have a signal to buy puts
and an hourly expiration option, as well as a 50-minute expiration option
would have expired. Both options would have expired in the money.
Now, the 15 to 30-period moving average crossover system. The general rules
are the same. I mean, with a difference that this system is meant to be
used in a slower environment and higher timeframes for day trades. A
bullish signal is when the 15-period moving average crosses above the 30-
period moving average, and a bearish signal is when the 15-period moving
average crosses below the 30-period moving average.
This system is meant to be used in the one-hour charts and should be traded
with end-of-day expiration options. This is because the moving average will
react slower to price. If you actually trade the 15-30-moving average
crossover system on the slower timeframes, you will get less reliable
setups, meaning that in lower timeframes and faster-paced environments you
might get the actual crossover once the move has already begun.
So when we are trading the lower timeframes and the lower expiration
options, we want to use a faster system to get at the beginning of the
move. If we are day trading, this 15-30-moving average crossover system is
excellent because if you use a faster crossover system on a higher
timeframe, you might get too many false signals. So this system is meant to
be used in the one-hour charts and should be traded with end-of-day
Here’s an example of the Aussie/US dollar one-hour chart. As you can see
here, we are in a steep up-move. We hit a head and shoulders, and when we
break with the neckline, we have actually a crossover right here, but we
wait for confirmation, the breakout of the neckline, of this head and
shoulders. When we break below this trend line or neckline, in this case,
we buy puts on the Aussie/US dollar for end-of-day expiration options. You
can see that we expire or the option expires in the money. Right here is
the actual trigger.
Here’s a cable one-hour chart. As you can see here, even though we are in a
very choppy market, we are making lower highs. Once we break with this
descending resistance and we have a bullish crossover right here, we can
trade end-of-day expiration options or buy end-of-day calls on cable with
this setup. As you can see, it is very important to use previous highs and
lows or previous support and resistance for confirmation of these setups. I
mean, you can certainly trade only the crossovers. But if you want to be
more accurate and if you want your winning ratio to be higher, you might as
well get confirmation from previous highs or previous lows or immediate
support and resistance, just as in this case.
Now, there’s some considerations that we’re going to go through before
going through the empty floor platform. Always use immediate support and
resistance levels to confirm the moves before you buy your options. You can
trade an end-of-day expiration option and still scalp the same instrument
with both systems.
Let’s say that you’re at the beginning of your trading session, and you are
analyzing the Euro/US dollar. At the beginning of the session, you find a
bullish crossover on the Euro/US dollar. So you buy an end-of-day
expiration option. But then again, you can always go to the five-minute
chart and plot the seven-11 system on it and scalp the same Euro/US dollar,
even though you have already bought an end-of-day expiration option with
the slower system. This means that you can actually use both systems on the
same financial instrument that you are trading.
Never trade MA crossovers in range and choppy markets, and this is a must.
This you need to understand and get inside your heads, because if you start
to trade moving average crossovers in ranging markets and choppy markets,
you are going to burn your money because you need trending market for the
moving average crossovers to work. If you actually use them in ranging
markets, you are going to be buying options with a lot of false signals. So
always wait for ranging markets.
Here’s how to know if we are in a ranging market or not. If price is below
the moving averages, we are in a bear market, and we are looking to buy
puts. If the price is above the moving averages, we are in a bull market
and looking to buy calls. In both cases, look for a correction, and then a
crossover with the direction of the trend. This means that if we are in an
uptrend, we are going to wait for a correction to the downside, and then
move to the upside with a moving average crossover or a bullish moving
average crossover for us to buy calls. If we are in a downtrend, we are
going to wait for a move to the upside, and then a continuation of the move
to the downside with a bearish moving average crossover for us to buy puts.
We can also trade turning points or what we call tops and bottoms. But when
we’re trading tops and bottoms, we look for confirmation on breaks from
previous highs or lows. I mean, for us to be able to counter-trend trade,
we need, of course, the moving average crossover of the system, and we need
price action to break with the previous structure, meaning that if we are
in an up-market, and we have hit a turning point and we get a crossover
signal, price needs to take out the previous lows and start making lower
lows. It’s the same case if we are in a down-market. If we are in a down-
move, and we have hit a turning point or a bottom and we get a bullish
moving average crossover, we need to wait for price to break with previous
highs or resistance before we can actually buy our calls.
Now, let’s go to the empty floor platform. Welcome back, traders. Here’s my
empty floor platform. We are going to analyze the GBP/USD one-hour chart
with the slower moving average crossover system and the Aussie/USD five-
minute chart with the faster moving average crossover system. Let’s start
with cable. This is how you actually insert the moving averages. You go to
your insert-indicator button. You choose moving average, and then you
actually just change the period of each moving average when you are
plotting them. In this case, we are going to use a 15-period moving
average, which is the orange moving average, and a 30-period moving
average, which is the black moving average.
As you can see here, what we’re going to use is previous areas of support
and resistance, and we have one right here. Okay? When we were in this
choppy market and we, of course, bottom or based right here. So when we hit
this area of support and make a double-bottom, we can know for sure that we
have hit a turning point. Okay?
When we have the moving average crossover, meaning that the faster or the
trigger moving average crosses above the slower moving average, we have, in
this case, a signal to buy calls and an end-of-day expiration option. We
have expired in the money. If we go backwards, let me just get rid of this
line. If we go backwards, let’s say here, here’s a good example of how to
use the moving average crossover when we are trading with the direction of
the trend. In this case, we are in a down-move. Right here, you can see
that we made a correction to the upside. Okay?
For this to be a truly turning point, not turning point but trend reversal,
we have to take out this previous low. In this case, we did, and we started
to move lower. When we get another crossover, bearish crossover in this
case, when the 15-period moving average crosses below the 30-period moving
average again, we have a signal to buy puts right here with the direction
of the trend. An end-of-day expiration option would have expired in the
In this case, we have a correction, but we do not get the moving average
crossovers. So we can’t trade this correction. Here, we hit a turning
point. Okay? You can see that it is actually a turning point because, in
this case, we are making lower highs. We have here another lower high,
another lower high, and lower highs right here. Okay?
When we actually take out the previous high right here, which is also an
area of previous support, we know that the trend has reversed. Right here,
when we get the moving average crossover, we have a signal to buy calls for
an end-of-day expiration option that would have expired in the money.
Remember that, in this case, we were trading around noon. So volatility was
very scarce. Well, for these moving average crossover systems to work, you
actually need to trade on very liquid markets or on trading hours. Okay? In
this case, we have another very interesting moving average crossover right
here, on a turning point. Okay? We tested this area three times. One, two,
three. When we broke with this low right here, we have another signal to
buy end-of-day expiration options with the faster moving average.
Since we have swift on the direction of the trend, we are now in a down-
move. Okay? Here, we have a correction to the upside. This is what we were
talking about, guys. We have a very deep correction to the upside. As you
can see, we actually had a moving average crossover, a bullish moving
average crossover. But because we are in a bearish market, we are not going
to trade it just yet. Okay? We are going to wait for it to continue to the
downside. When we have this moving average crossover, we have a signal
here. Well, this is the crossover and the actual buying put signal is here
for an end-of-day expiration option that you clearly see that expires in
Now, let’s go to the Aussie/US dollar five-minute chart. As you can see,
let me just thicken this out for you. As you can see here, when we get the
moving average crossovers in a faster-paced environment, we have to be
quick. Okay? Right here, we were actually making higher highs, higher lows,
and we were kind of making what looks like a triangle here. Okay, or a
When we break with these lows, it means that we have broken with this
structure. So look for the moving average crossover. When we get the moving
average crossover here, we can actually trade or buy puts in this currency
pair, for a 50-minute to hourly expiration option. You can see here, if you
buy puts right here, one, two, three, your option would have expired in the
money, as well as the hourly expiration option.
If you go further back, you can see that here we are in an up-move, and we
are making a correction to the downside. This is called a flag, guys. In an
up-move, sometimes price . . . Well, most of the times, price will correct
in a formation that is called a flag. This is the pole. The main move is
the pole. The correction is the flag. When we break with the flag right
here, we have a moving average crossover to get back on the overall move.
In this case, I would choose to trade an hourly expiration option, maybe a
30-minute expiration option, just because we are breaking with a very
strong continuation pattern. Okay? You can see that even the 50-minute
expiration option will have expired in the money. But to be a little more
certain that we are going to make money out of this trade, I would have
chosen a 30-minute to hourly expiration on this particular setup. This is
basically how you use these two systems that you just learned.
More About Adam
Adam is an experienced financial trader who writes about Forex trading, binary options, technical analysis and more.
Using Moving Average Cross-Over as strategy in cryptocurrency trading
A winning approach in bearish trends [2020–2020]
In trading, we often tend to rely upon over-complicated strategies that over promise gains and undermine risks. However, the key to find a balanced trading strategy is simplicity. In this article, we present a systematic back-testing of a well-known, simple yet profitable strategy called Moving Average Cross Over (MACO) in the trading of the top-18 cryptocurrencies. In our study, we screen for the best combination of short-term and long-term moving averages and we set the basis for a potentially automatic strategy. MACO with optimal parameters reports (a) more than 50% profit over investment in 10 out of 18 cryptocurrencies, (b) more than 100% USD return (no value loss) in 16 out of 18 cryptos and (c) better performance than “holding” in 17 out of 18 cases.
The MACO strategy
The moving average cross over trading strategy is fairly simple. We calculate two different moving averages (MA): one long and one short. The long one, or long-termed, represents the overall trend of the market: either bullish (when it goes up) or bearish (when it goes down). The short one, or short-termed, represents the more immediate price fluctuation and reacts quicker when the price changes. Now, when the fast MA crosses the slow MA we detect a potential change of trend. As traders, we can leverage the detected change of trend and buy when the trend becomes bullish, and sell when the trend becomes bearish. These concepts are represented in the following example for the BTC-USDT trading pair.
In the previous example, we buy when the fast MA goes over the slow MA (green area) and we sell when the fast MA goes under the slow MA (red area). So far so good.
MACO performance on successive trading windows
As we saw in the previous example, MACO is quite simple to apply in appearance. In practice is a little bit more complicated because we have to find a successful combination of lengths for the short and long moving averages. One way we can address this issue in retrospective is by trying all or a representative set of combinations and see which ones performed better on past data (a.k.a. back-testing).
There are different ways to assess the performance of each short/long MA combination. For this analysis, we have decided to take windows of 20 days (20*6 candles of 4h) and moving them along the time axis in jumps of 4 days (4*6 candles of 4h). For each window, we calculated:
(a) The return over investment following the aforementioned MACO strategy to buy and sell according to the cross-overs and the cross-unders, respectively.
(b) The return over investment by following a “holding” strategy, i.e. buying at the beginning of the window and selling in the end of the window.
The ratio between the two (MACO/holding) was computed for each window and for each combination of long-term MA (20, 30, 40, 50, 60, 70 candles of 4h) and and short-term MA (1, 2, 3, 4, 5, 6, 7, 8, 9 candles of 4h). The results for the BTC-USDT pair look like this:
The lines/simulations that go over 1 mean that MACO strategy was, for instance, 1.2 (20%) more profitable than just holding for that particular window. The legend on the right show all combinations of long/short MA (first parenthesis). The price of BTC is shown as reference.
Although all combinations of long/short MA seem to follow a similar pattern, there are clearly some winners and some losers. In order to discriminate the best strategy, we have calculated the area under the curve (AUC) above 1 (positive AUC) and the area under the curve below 1 (negative AUC). Finally, the profitability of a specific combination of MAs can be calculated as:
Total_AUC = MA _positive – MA_ negative
The Best Broker! 15 000 $ Welcome Bonus!
10 000$ welcome bonus!
The Best Binary Options Broker 2020!
Perfect For Beginners and Middle-Leveled Traders!
Free Demo Account.
Get Your Sign-Up Bonus Now!
Recommended Only For Experienced Traders!
A positive total AUC means that following the MACO strategy is better than holding on average. The winner combination of short/long MA with maximum total AUC is depicted in red. Individual total AUCs can be found on the legend.
Two final remarks. First, notice that each simulation or predicted return has an associated error bar. This is because, to make it more realistic, once the strategy tells us to buy or sell, we use a random price comprised between the open and close of the following candle. Additionally, for each buy/sell action we take into account a 0.1% commission.
Second, notice that no combination is particularly profitable during exponential growths such as the one that BTC experienced in late 2020. In these situations, holding is clearly the best strategy to follow. Notice, however, that when markets enter a side-ways or bearish trend, trading becomes a handy tool to maximize profits by hedging on downtrends. This becomes even more evident in the following plots shown in this article.
Screening profitable MACO long/short combinations among the top-18 cryptocurrencies
In this final analysis, we applied the techniques explained in the previous sections to the top 18 cryptocurrencies by volume in the Binance cryptocurrency exchange. In particular, we ran the previous analysis to detect the best and worst long/short MA combination and we ran 1000 different simulations following the MACO strategy to buy and sell cryptocurrency during the duration of one year using 4h candlesticks. These are the results:
From the plots we can conclude that MACO with optimal parameters yield:
(a) more than 50% profit over investment in 10 out of 18 cryptocurrencies,
(b) more than 100% USD return (no value loss) in 16 out of 18 cryptos (this means that trading is good to hedge funds in downtrends) and
(c) better performance than “holding” in 17 out of 18 cases.
Finally, the best performing cryptocurrency pair has been the ZRXBTC pair with over 800% on returns. Interestingly, the top 3 cryptocurrencies were also particularly profitable.
Conclusions and personal opinion
- Moving average cross over is a simple yet profitable strategy to follow.
- Using back-testing to see which was the profitable combination of long/short MA gives us a good idea on what worked in the past and what could work in the future, but with little guarantee.
- MACO strategy can be used to trade cryptocurrencies but would probably work optimally when in combination to other indicators. I personally use price action as confirming indicator.
- MACO seems to work quite well for the current top 3 cryptocurrencies (BTC, ETH, XRP).
- Trading with a solid strategy in hand is a good practice in all occasions except during meteoric and parabolic growths.
The Simple Moving Average (SMA) Crossover strategy for TradingView
Moving averages are a popular technical indicator. They smooth prices to reduce noise and see price action more clearly. That feature also makes them popular under trend followers. Let’s see how we can code a moving average-based trend-following strategy: the SMA Crossover strategy.
IN THIS ARTICLE:
# Trend following with the SMA Crossover strategy for TradingView
For his book Trend Following, Michael Covel (2006) researched the world’s best trend followers. The goal of trend following is simple: capture the majority of an up or down move for profit (Covel, 2006). How trend followers go about achieving that goal is, however, a bit different.
Where other trading styles speculate on trends or estimated support and resistance levels, trend followers only concern themselves with price. They define beforehand what price action defines a trend, and then open a position once they see a new trend emerge (Covel, 2006). This does make trend followers always miss the first part of the trend. And neither do they exit near the top. But that’s okay since they are able to catch the main move of big trends (Covel, 2006).
Typical trend-following strategies share several features (Covel, 2006). They detect major trends by looking at price changes. Profitable trades are kept until the trend changes to let profits run. Losing trades are closed at a predefined stop-loss level. And with position sizing losses are limited.
One trend-following strategy that Covel (2006) shares in his book is the SMA Crossover strategy. This strategy uses two moving averages: one that follows the short-term trend and another that reflects the market’s long-term trend. When the fast moving average crosses the slower one, the market is thought to change its long-term trend direction. Let’s take a closer look at the strategy’s trading rules.
# Trading rules of the SMA Crossover strategy
The SMA Crossover strategy has the following trading rules (Covel, 2006):
- Enter long:
- Go long (and reverse any open short position) with a market order the next day at the open when the 50-bar Simple Moving Average (SMA)crosses over the 100-period SMA.
- Exit long:
- Set a stop loss for the long position as follows: entry price – 4 times the 10-bar Average True Range (ATR).
- Enter short:
- Go short (and exit any open long position) with a market order the next day at the open when the 50-bar SMA crossed under the 100-bar SMA.
- Exit short:
- The stop loss for short positions is: entry price plus 4 times the 10-bar ATR.
- Position sizing:
- The initial risk for each position (difference between entry price and stop-loss price) is 2% of equity.
- The maximum exposure (that is, the margin to equity ratio) for a single position is 10% of equity.
The position sizes we trade with the SMA Crossover strategy are 2% of strategy’s equity. However, if markets gap beyond our stop prices, losses can be more. To limit excessive losses in those cases we restrict the size of each position to 10% of equity. That way we never trade a position that’s too big in relation to the strategy’s equity.
Covel’s (2006) profitable backtest was done on 15 years of daily data for various US futures, including currencies (British Pound, Japanese Yen, Euro), commodities (crude oil, gold, silver, corn, wheat), soft commodities (coffee, sugar), and financials (S&P 500, Nasdaq 100, T-Note 5yr).
# Program the SMA Crossover strategy for TradingView
Now let’s turn the above trading rules into a TradingView strategy script. An efficient way to do that is to use a template. That breaks up the task into smaller, easier-to-manage chunks. It also adds a bit of structure. And it makes it easier to start with a smaller part of the strategy instead of being confronted with an empty script.
This is the template that we’ll use for the SMA Crossover strategy:
If you want to follow along with the code discussion in this article, make a new strategy script in TradingView’s Pine Editor and paste in the above template. (Else jump to the end of the article where the entire strategy code is.)
For an idea of what the code we’re going to write does, here’s what the finished SMA Crossover strategy looks like:
Now let’s translate the above trading rules into a proper TradingView strategy script.
# Step 1: Define strategy settings and input options
In the first step we configure the strategy. We also make user-configurable settings so we can easily change the strategy’s parameters.
strategy() ‘”># Specify strategy settings with strategy()
So first we specify the strategy’s settings. We use the following code for that:
We define the script’s properties with the strategy() function. With the title argument we name the strategy. And with overlay set to true we have the strategy appear in the same chart area as the chart’s instrument.
Based on the strategy’s rules we disable pyramiding ( pyramiding=0 ). With initial_capital we give the script a starting capital of 100,000 in the currency of the chart’s instrument.
For transaction costs we use 4 currency ( commission_value=4 ) per single trade ( strategy.commission.cash_per_order ). And we estimate 2 ticks slippage for market and stop orders ( slippage=2 ). These costs are a bit high, but it’s safer to overestimate trading costs than to underestimate them.
input() ‘”># Make input options with input()
We make the strategy’s inputs with the input() function. That function makes a user-configurable option in the script’s settings and returns the current value of that setting. Here we store those values in variables to easily use them later on in the script.
The first two inputs we make are both integer input options ( type=integer ). We name them ‘Fast SMA Length’ and ‘Slow SMA Length’ and give them standard values of 50 ( defval=50 ) and 100 ( defval=100 ). We use these later on to calculate the moving averages.
# Create inputs for stop-loss
We also make two stop-loss inputs:
The ‘ATR Length’ integer input option specifies the number of bars that the Average True Range (ATR) calculates on. We have this option use 10 as its initial value.
The ‘Stop Offset Multiple’ floating-point input ( type=float ) specifies how many ATRs the stop is removed from the entry signal price. We set this option to a default value of 4.
# Make options for strategy’s position sizing
Then we make settings for the strategy’s position sizing:
With the ‘Use Position Sizing?’ true/false input option ( type=bool ) we can easily enable or disable the strategy’s position sizing. We enable the setting by default ( defval=true ), which makes the script use its position sizing algorithm. When disabled we simply trade 1 contract with each trade.
The ‘Max Position Risk %’ floating-point input ( type=float ) specifies how much strategy equity we want to risk on a single trade. That risk is based on the distance between the price and stop-loss level. Based on the strategy’s trading rules we use a default of 2% here ( defval=2 ).
With ‘Max Position Exposure %’ we specify how large the strategy’s position may be in relation to its equity. That prevents that the strategy trades big positions for when the computed stop is close to the entry price. We give this setting a default value of 10%.
The last input option, ‘Margin %’, estimates the margin percentage of the chart’s instrument. That value is what we use to determine the maximum position size. Since we cannot access the instrument’s margin with TradingView Pine code, we’ll have to estimate it ourselves. For a typical futures contract the margin rate ranges from 5 till 15% of total contract value (Kowalski, 2020). And so we use a default value of 10% here.
# Step 2: Calculate trading strategy values
Next we calculate the strategy’s data. We’ll have to determine the moving averages and Average True Range, figure out the strategy’s trade window, and calculate the position size.
# Calculate moving averages and ATR
So first we determine the moving averages and ATR:
The SMA Crossover strategy uses basic simple moving averages, and we compute those here with TradingView’s sma() function. The first sma() function call runs on closing prices ( close ) for fastMALen bars, the input variable we gave a default of 50 earlier. The second sma() call calculates the 100-bar SMA of closing prices with help of the slowMALen input variable.
We calculate the Average True Range (ATR) with TradingView’s atr() function. The length we use with atr() is set with atrLen , the input variable we set to 10 earlier.
# Determine strategy’s trade window
Then we compute when the strategy should trade:
The idea behind a ‘trade window’ is that the strategy goes flat when the backtest ends. That way we don’t have open positions in the performance report of the ‘Strategy Tester’ window.
For that we’ll have to figure out when the strategy should stop. One approach is to stop several days before the date and time of when we perform the backtest. By pausing the strategy several days earlier we give the script enough price bars to close open positions (and we also account for when the market is closed, like over the weekend).
And so we make a tradeWindow true/false variable here that checks if the opening time of each bar ( time ) is less than or equal to ( ) the current time ( timenow ) minus 86,400,000 times 3. That 86.4 million value corresponds to the number of milliseconds in a day, which we use here since both time and timenow also report time values in milliseconds. So by multiplying that value with 3 we in effect go back three days from the current date and time.
That means the tradeWindow variable is true when the script calculates on a price bar that happens before 3 days ago from the current time and date. And its value is false when the script processes a price bar less than 3 days from now.
# Calculate strategy’s position size
Next we calculate the strategy’s position size:
To calculate the position size we need two things: the amount of strategy equity we want to risk and the estimated risk per trade. Those two give us the computed position size, which we then compare with the maximum position. That way we don’t trade positions that are too big.
For the risk equity computation we first turn the maxRisk input variable to a percentage expressed as a floating-point value (so 10% becomes 0.10). For that we multiply the input variable with 0.01. Then we multiply with strategy.equity , a variable that returns the sum of the strategy’s initial capital, close trade profit, and open position profit (TradingView, n.d.).
For the risk per trade we multiply the 10-bar ATR ( atrValue ) with the stop offset input variable ( stopOffset ). That value matches how many ATRs the stop is away from the entry price. To turn that into a currency value we multiply with syminfo.pointvalue . That variable returns how much one point of price movement is worth. For the E-mini S&P 500 future, for instance, that variable returns 50. For crude oil futures we get 1,000 and for stocks 1.
Then we figure out the maximum position size. For that we first turn the maxExposure input variable (which holds a percentage) into its decimal equivalent. Then we multiply with strategy.equity . That gets us the percentage of equity to invest at most. We divide that value with the estimated margin requirement. We get that value when we multiply the ‘Margin %’ input option with the total contract value, which we get when we multiply the current price ( close ) with syminfo.pointvalue .
As an example, say we trade the E-mini S&P 500 future (ES) and its current price is 2,500. One point of price movement in ES is worth $50 or, put differently, the ES represents 50 times the S&P 500 index.
When our strategy has 1,000,000 worth of equity and the maximum exposure is 12.5%, then we can invest at most 125,000 in an ES position. If we guess the margin rate to be 15%, then we need 18,750 currency for a single ES contract (15% x $50 x 2,500).
So we can trade at most 6 contracts (125,000 / 18,750). When we trade more, our margin-to-equity ratio becomes too high.
Then we make the posSize variable and give it one of two values with TradingView’s conditional operator ( ?: ). Should the usePosSize input variable be false , then we use a default position size of 1 contract.
When usePosSize is true , we calculate the strategy’s position size. For that we divide riskEquity with riskTrade . We do that operation inside the floor() function. That rounds down the position size to the nearest integer. We also use the min() function to have the script choose the smallest of the position size and maximum position size. That way we don’t trade positions that are too big.
# Step 3: Code the long trading rules
Now we turn the strategy’s trading rules into TradingView code. We’ll start with the long side in this step, and cover the short code in step 4.
# Specify condition for long entry
First we code the enter long condition:
Here we make the enterLong variable. Its value depends on the combination of two true/false expressions. Since we combine those with the and logical operator, both have to be true before enterLong becomes true as well. If one or both are false , then the variable becomes false too.
The first expression is the crossover() function with the fastMA and slowMA variables. This way we monitor for when the 50-bar SMA crosses over the 100-bar simple moving average. When that happens, the crossover() function returns true here (and false otherwise).
The second expression is tradeWindow . We defined that variable earlier and set it to true when the script calculated on a price bar more than 3 days ago from the current date and time. By including tradeWindow in the enter long condition we only have the script trade up until that point in time.
# Define the long stop loss value
In this third step of coding a TradingView strategy we also figure out the long stop price. We use this code for that:
This first declares the longStop variable and gives it an initial floating-point value. With that default value our variable can hold decimal values (instead of just whole numbers).
Then we give the variable its actual value with the := operator. The value it gets depends on the enterLong variable. If that variable is true , the conditional operator ( ?: ) sets the long stop to close – (stopOffset * atrValue) . This calculates the initial stop value by subtracting a certain multiple ( stopOffset ) of the 10-bar ATR ( atrValue ) from the current price ( close ).
When enterLong is false , the conditional operator returns the previous bar value of longStop (so longStop ). This keeps the stop price at the same level as long as there is no new enter long signal.
# Step 4: Program the short trading conditions
Then we write the code for short positions.
# Determine the strategy’s enter short condition
First we implement the enter short condition:
There are two requirements before enterShort becomes true . The first is that the 50-bar SMA dropped below the 100-bar SMA. We evaluate that here with the crossunder() function and the fastMA and slowMA variables as arguments.
Next the tradeWindow variable has to be true . That happens when the script processes a price bar that’s more than 3 days before the current date and time. Should the bar’s time be later or when there’s no moving average crossunder, then the enterShort variable is false .
# Compute the short stop value
Then we calculate the short stop price:
This code is much like how we calculated the long stop. First we make the shortStop floating-point variable. Then we update that variable to its actual value with the := operator.
The value of shortStop depends on the enterShort variable. When that variable is true , we calculate the stop with close + (stopOffset * atrValue) . This sets the stop to a certain multiple ( stopOffset ) of the 10-bar Average True Range (ATR) ( atrValue ) above the current price ( close ).
Should enterShort be false , we use TradingView’s history referencing operator (  ) to fetch the previous bar value of shortStop . This keeps the stop at the same price for several bars, and we only update it when a new enter short signal happens.
# Step 5: Output the strategy’s data and visualise signals
Next we output the strategy’s data on the chart. That way we can easily verify that the strategy behaves like it should.
# Plot moving averages on the chart
First we display the simple moving averages:
We plot the SMAs with TradingView’s plot() function. The first plot() statement shows the 50-bar SMA ( series=fastMA ). We make this regular line plot appear in orange .
The second plot() function call displays the 100-bar SMA ( slowSMA ). That line appears in the teal colour. And with the linewidth argument set to 2 the line plot is a bit thicker than normal.
# Show stop prices on the chart
We also plot the strategy’s stop prices:
Here the plot() function shows again values on the chart. But this time we make a circles plot ( style=circles ). When we plot those values is also different: we don’t plot values on every bar, but only when there’s a long or short position.
To make that possible we set the series argument of plot() to a conditional value. In the first plot() statement we evaluate if the strategy.position_size variable is greater than ( > ) 0. That happens when the strategy is long (TradingView, n.d.). In that case we have TradingView’s conditional operator ( ?: ) return the long stop value ( longStop ).
When the script is not long we have that operator return na to disable plotting. This has the script only show the long stop prices when the strategy is actually long.
With the second plot() statement we also evaluate strategy.position_size . But this time we look if that variable is less than ( ) 0, which it is when the strategy is short (TradingView, n.d.). In that scenario we have the conditional operator ( ?: ) return the shortStop values (which are then plotted on the chart). Else that operator returns na to disable the circles plot.
# Step 6: Open a trading position with entry orders
With the strategy’s data computed and plotted it’s now time to do the actual trading. For that we first write the strategy logic that opens trades:
The first if statement checks whether the enterLong variable is true . That variable holds that value when the 50-bar SMA crossed over the 100-bar simple moving average. In that case we call the strategy.entry() function to open a long trade ( long=true ). We name that order ‘EL’ ( id=”EL” ). The order size is set with the posSize variable, which we earlier set to the calculate position size or a default value of 1.
With the second if statement we check whether the enterShort variable is true . When it is, the 50-bar SMA dropped below the 100-bar average. In that case we initiate a short trade ( long=false ). We name that order ‘ES’ and submit it for posSize contracts.
If there’s already a position open in the other direction, strategy.entry() automatically reverses that trade (TradingView, n.d.).
So if our strategy is long and the 50-bar SMA crosses below the 100-bar SMA, strategy.entry() turns that long position into a short trade. (The same goes for when the strategy is short and the long signal happens.)
# Step 7: Close market positions with exit orders
In this last step we write the strategy code that closes positions.
# Generate the strategy’s stop-loss orders
First we submit the stop-loss orders:
The first if statement checks whether the strategy is long, which is the case when strategy.position_size is bigger than 0. Then we call the strategy.exit() function to submit a stop order for the longStop price. We name that exit long order ‘XL’ ( id=”XL” ) and have it close the ‘EL’ entry order ( from_entry=”EL” ).
The second if statement looks if the strategy is short ( strategy.position_size ). In that case we call strategy.exit() to submit a stop order based on the shortStop prices. We name that exit short order ‘XS’ and have it close the ‘ES’ entry orders.
# Flatten strategy when backtest ends
We end the script with code that makes the strategy go flat at the end of the backtest period:
Here we execute the strategy.close_all() function. That function closes any open order with a market order when its when argument is true (TradingView, n.d.). Here we set that argument to not tradeWindow .
Earlier we set the tradeWindow variable to a true/false value. That value was based on if the script calculated on a price bar that happened more than 3 bars before the current date and time ( true ) or not ( false ). Since we want to close all orders after that point in time, we need a true value for strategy.close_all() once that time and date passes.
However, tradeWindow is false after that moment in time. And so we place the not logical operator before tradeWindow . That gets us a true value when tradeWindow is false and a false value when tradeWindow is true .
Since tradeWindow is false when the script calculates on a price bar within 3 bars of the current time and date, not before the variable gives us a true value in that case. And with that true value we have strategy.close_all() close any open position. That way the strategy goes flat at the backtest’s end. Since we also check tradeWindow before we open a trade, we don’t initiate new trades after that point in time.
# Performance of the SMA Crossover strategy for TradingView
Let’s start our performance review with a positive note. Like most trend-following strategies, the SMA Crossover strategy performs superb when prices trend in the same direction for a long time. Those market conditions have the strategy outperform with little transaction costs.
An example of that is the chart below, where the strategy booked a 500 point profit in the E-mini S&P 500 future:
Unfortunately, the SMA Crossover strategy also has its weaknesses. When for instance markets move sideways, the strategy’s performance suffers due to whipsaw trades. In those conditions the strategy loses money due to three reasons: trends that don’t start, trends that move in the ‘wrong’ direction, and trends that end too soon.
An example of that poor performance is the chart below, where the strategy had several losses in a row.
The results of a mini-backtest show below. These results are without position sizing. That way the strategy traded every signal it got, which also maximised the number of trades (and thus data) in the backtest report.
But as you can tell from the trades in the table below, there are just around 2.5 trades per year. That makes it near impossible to draw conclusions from these two backtests. And so further testing is needed.
|Performance metric||E-mini S&P 500 (ES)||Crude oil futures (CL)|
|Time frame||1 day||1 day|
|Avg win trade||$9,005||$9,441|
|Avg losing trade||-$3,888||-$3,801|
|Slippage||2 ticks||2 ticks|
# Ideas for improvement and new strategies
There’s definitely a need to improve the SMA Crossover strategy as the above backtest results show. Here are some ideas you might find valuable to explore further:
- One problem of the SMA Crossover strategy is how it takes to close trades. This happens because the moving averages have a length of 50 and 100 bars, which makes exit signals rather slow. That means losses are made worse because it takes some time before the exit signal happens. Perhaps a better idea is to use 50 and 100-bar SMAs for entries, but use shorter moving averages for exits. Or perhaps use a trailing stop-loss so that always a portion of open profit is ‘protected’.
- Covel (2006) shares in his book results from an optimisation, which show that optional values for the fast SMA are from 40 till 60 while the most profitable values for the slower average range from 100 till 120 bars. We can use these values as a starting point. But likely need to revisit and update them so that they fit the traded instrument and current market conditions.
- Like most trend-following strategies, the SMA Crossover strategy underperforms when market move sideways. If we can filter out those low-probability trades the strategy’s performance will improve considerably. Perhaps an ADX or Average True Range (ATR) filter can help pinpoint when the market goes from sideways to trending.
- The SMA Crossover strategy uses Simple Moving Averages (SMAs). Those calculate a straight average of the data, where each data point has the same weight. That, however, does not make these averages very responsive. Perhaps the strategy’s performance changes for the better when we use other moving averages, like an Exponential Moving Average (EMA).
- Other options to make the strategy better include risk management. We can, for example, use a maximum drawdown. Or limit the losing day streak. See the risk management category for more inspiration.
For strategies similar to the SMA Crossover, see the SMA Crossover Weekly (which trades weekly simple moving averages) and the SMA Crossover Pyramiding strategy, which scales into profitable positions.
Other trend-following strategies that also rely on moving averages are the Dual Moving Average strategy and the Triple Moving Average strategy.
# Full code: the SMA Crossover strategy for TradingView
The complete and final code of the SMA Crossover strategy shows below. See the discussion above for details about the code and an explanation.
See all TradingView example strategies for more trading ideas and other scripts to experiment with. There are also several TradingView example indicators, which give several trading ideas and show how to code them.
Covel, M.W. (2006). Trend Following: How Great Traders Make Millions in Up or Down Markets (2nd edition). Upper Saddle River, NJ: FT Press.
TradingView (n.d.). Pine Script Language Reference Manual. Retrieved on October 26, 2020, from https://www.tradingview.com/study-script-reference/
Last updated on June 7, 2020 (published November 16, 2020 ).
# Related TradingView tutorials
The Trend with Pattern Entry is a trend-following strategy that uses moving averages. But this TradingView strategy enters with countertrend signals.
The Bollinger Breakout strategy trades long and short breakouts based on a volatility channel. This TradingView strategy is based on the Bollinger bands.
Strong price momentum when the week starts may not last. The Wide-Range Midweek Reversal system is a TradingView strategy that fades early-week momentum.
The SMA Crossover Weekly strategy trades longs and shorts with two moving averages. This TradingView trend-following strategy uses weekly price data.
The Swing Trade Market Gaps is a countertrend TradingView strategy. It shorts up gaps and buys down gaps, and checks if the broad market also gaps.
Welcome on Kodify.net! This website aims to help people like you reduce their programming curve. I hope you find the articles helpful with your programming tasks.
Want to know more about me? Check out the about page.
See Kodify.net’s homepage to learn about other programming topics.
See all TradingView articles to learn about other topics.
The Best Broker! 15 000 $ Welcome Bonus!
10 000$ welcome bonus!
The Best Binary Options Broker 2020!
Perfect For Beginners and Middle-Leveled Traders!
Free Demo Account.
Get Your Sign-Up Bonus Now!
Recommended Only For Experienced Traders!