Uploaded by abalduina

Automated Trading: Create Profitable Trading Robots

advertisement
Table of Contents
Introduction
Chapter 1: Which software will we use?
Chapter 2: Making an account
Chapter 3: Your first automated trade in less than 15 minutes!
Chapter 4: How to create a profitable trading robot
Chapter 5: Tradingview features, basic price information and most used
indicators explained
Chapter 6: Trading strategies
Chapter 7: Creating your first trend following strategy
Chapter 8: Automating our first trend following strategy
Chapter 9: Creating your first mean reversion strategy
Chapter 10: Automating our first mean reversion strategy.
Chapter 11: How to determine whether a strategy is profitable?
Chapter 12: Checklist for evaluating strategies
Chapter 13: Common pitfalls of trading systems
Chapter 14: Simple improvements of strategies
Chapter 15: Going over the checklist for a mean reversion strategy and
improving the strategy
Chapter 16: Proof of what is possible and tips of a 2-year automated trading
journey.
Chapter 17: Backtesting and trade automation software compared
Chapter 18: Conclusion
Chapter 19: Free scripts
Introduction
Like many new traders you are probably interested in trading because of the
money that can be made. Of course, trading can make you a fortune, but is a
difficult skill to master. According to statistics of Oanda, a large broker,
approximately 73.8% of retail traders lose money. So it is a challenge to become
one of the profitable retail traders.
To trade well, you need to trade actively when the markets are live. If you’re like
me you are working full-time, which makes trading during the daytime is an
illusion. You can’t trade while you are at work and trading markets that are open
in the evening is not for everyone. I spent a fair share of my time trying to trade
in the evening hours but soon found out that it wasn’t for me. I rather spend time
with my family and friends or doing things I like. Although I liked the fact that it
can make you extra money, I wasn’t able and willing to do keep doing it
consistently. I was looking for a solution to this problem and soon stumbled
upon the subject of automated trading. Automated trading would be the perfect
solution to the aforementioned problems.
Soon I set out on a journey to create automated trading systems and after several
years of experience, I want to share my knowledge with you. This book is
devoted to people like me, working a job, with limited capital to trade, and who
like to spend time with the family or doing the things you love.
You might also have heard about trading robots, and several objections for
creating a profitable one come to your mind. I can probably guess some of those,
as I have had the same experience. I address the most common thoughts below.
“You need a lot of money to start trading”
This certainly is not the case. A lot of brokers allow you to trade with very little
capital. Although you need to trade brokers that offer contracts for difference.
Because they often offer more leverage. I use Oanda. With Oanda, the smallest
needed amount of capital to trade is approximately 170 dollars. I started a
challenge to let one of my automated systems trade 168 dollars and see how
much money can be made. This is perfectly possible in a short timeframe I’ve
been able to almost double the initial investment.
“Creating a trading robot is hard”
I also thought that creating a trading robot is very difficult. I thought you would
need years of coding experience to be able to create one. This however is not the
case. You don’t need to code anything, to place an automated trade, which you
will discover in chapter 3. In this chapter, you will create your first automated
trade in less than 15 minutes. It is that simple!
“You can’t beat the smart boys at wall street”
This was the thought I had to struggle with most. The boys at wall street all seem
to be so smart. They trade with more money, have better equipment, and can
spend all their working hours developing new trading strategies. But every
benefit comes with a certain cost. I discovered that you and I have an enormous
advantage over the smart boys at wall street. They have to trade in a very
different and hard way. Because they operate enormous sums of money. Making
it impossible to get in and out of a trade quickly. Just imagine you would need to
close a position worth 100 million dollars. The order is so big, that not 1 buyer
will buy the 100 million dollars at once. The 100 million dollars will be bought
up by multiple buyers, which leads to a slightly worse prices per trade. For
instance, 10 million is sold at 3000, the next 10 million is sold at 2999, the next
10 million is sold at 2998, and so on. Just imagine what it would do to your
trading if each time you tried to buy or sell a position, the price got worse.
To deal with this issue the smart boys can get rid of their position with limit
orders instead of with market orders. The difference is that you specify that you
only want to buy or sell for a specific price. Let’s reuse the previous example. If
you want to sell at 3000 with a limit order, you will only sell the position to
buyers, who want to buy it for 3000. Your likely to sell your position when the
market is falling and you want to secure your profit. There are not a lot of buyers
who want to pay 3000 dollars. Which probably leaves your limit order partly
filled. You might only have sold 10 million dollars of the 100 million dollars. Let
that sink in.
In contrast however we as small traders can sell or buy a position for
approximately the same price as the market. We could have sold our trade for
2999.9 dollars. The smart boys at wall street thus need to develop strategies that
can cope with these issues. Which is very difficult. They need to come up with
all sorts of risk management, generally need larger average winning sizes, and
they need to stay in positions longer. All these criteria increase the risk of a
trading strategy and/or greatly influence the trading strategy’s return.
This is complicated in itself, but is furthermore complicated by the people that
invest their money with the trading firm. If the trading firm loses a little bit of
money, let’s say 5%, a lot of investors will take their money out of the account,
because of fear to lose more. This way the possibility of making the lost money
back is off the table. Limiting the trading done by the smart boys at wall street
even more.
You don’t have these limitations. Your orders will be filled immediately at
almost the same price, making it possible to operate a strategy with small
average trades, limiting the time you spend in a trade and thus limiting your risk.
Furthermore, you don’t have to deal with investors that take money away with
small losses that can happen. Just be sure to trade with money you can lose.
When your portfolio is a bit down, you can always recover. When you take the
money out, this option is taken off the table.
“Developing a trading strategy is difficult”
Developing a profitable trading system is not easy, but it is easier than creating a
discretionary trading strategy. A discretionary trading strategy is how almost all
traders trade. They see a certain price, pattern, or have a feeling for the security
and take a trade. But how can you be sure your strategy is profitable in the long
run? You can’t because the strategy’s trading rules are not specific enough so
that taking a trade or not is up to debate. If however, you have very specific
trading rules your trading is likely to be influenced by emotions. Sometimes you
keep a position to short and sometimes too long. All these acts influence your
trading strategy greatly and ultimately determine whether your profitable or not.
With automated strategies, the trading rules are always the same and are always
executed in the same way. Therefore the strategy’s performance is equal to the
strategy which we developed and tested. Which makes the performance of the
strategy much better. Moreover, we can test years of data making it much more
likely that the strategy will perform well and will keep performing well. Creating
a profitable automated strategy is in my opinion easier than becoming profitable
when trading based on emotions.
To begin automated trading, you need to develop a trading strategy. Luckily
automated trading is heavily documented. Great minds have created and tested
several trading strategies that have very specific rules that a computer can
follow. Scientific papers have tested these strategies and several of these
strategies seem to be profitable. With some slight alterations, you might have a
profitable trading strategy in less than a month.
“A trading system needs to be difficult to beat the smart boys at
wall street and the market”
As discussed in a prior statement you have a massive advantage as opposed to
the smart boys at wall street. They need to develop very refined trading
strategies to be able to profit while keeping their risk at a minimum. A simple
goal that you can manage to complete is to beat the market. Which is very
feasible and can be done with very simple strategies. One strategy that can beat
the S&P500 from 2000 to now buys a position based on one rule. When you
discover this I’m certain that you know that it is possible and doesn’t have to be
sophisticated at all.
But why doesn’t every retail traders use these, you might ask. Because so many
traders can’t follow these simple trading rules. They try to improve the strategy
based on their emotions or because they believe the news will have a major
influence. This in turn is often detrimental to the strategy’s performance. As an
automated trader, you won’t suffer these problems. Just be sure to keep running
the trading robot, and the robot will execute the trades perfectly, increasing the
probability of the past strategy’s results will be more or less the same in the
future.
I hope I’ve convinced you to get started, because it is possible! This book is for
you, trying hard to make a better living. I will teach you all that I know, and I am
confident that you soon will be able to create a profitable trading robot.
Appreciation notes
First of all, I would like to send my appreciation to Tradingview for offering
such a great platform. I’m a massive fan and I hope this e-book inspires others to
use this great platform as well.
I would also like to thank my girlfriend for putting up with all my talk about
trading in the past few years.
Note:
Any decisions you make regarding automated trading are your own. Your
responsible for your own trading performance.
Chapter 1: Which software will we use?
We will create our trading robot with the help of Tradingview. Tradingview is a
platform that offers intuitive charting, backtesting, and trade automation. A lot of
traders use the software since it is so easy to use and has many different
functionalities. I have worked with several different platforms, but Tradingview
is my personal favorite.
This guide is for inexperienced and experienced traders that want to create a
profitable trading robot. You will create your first automated trade in less than 15
minutes. If you click the url below, and if you do choose to go with an upgraded
plan, you'll get up to 30 dollar, which is equal to 2 free months.
https://www.tradingview.com/gopro/?share_your_love=moneytreesolutionss
Chapter 2: Making an account
If you don’t have a Tradingview account, you can easily open a free account.
Just follow this link to open a free account in Tradingview and click the “join for
free” box on the top right hand of the screen.
Then all you need to do is enter your signup details, and you’re ready to go in a
matter of seconds!
The free account in Tradingview gives you the following features:
Access to charts and all indicators, 1 chart per layout, 1 alert, 3 indicators per
chart, 1 indicator template, 1 watchlist, Screener timeframes: Daily, Weekly,
Monthly
The free account comes with occasional ads, which is acceptable. If you want to
get rid of these ads, you could upgrade to a paid subscription. Or you could just
do what I have done myself. I use a free version without ads, due to the use of
add-block for chrome and I use a paid version for the Trading robot, because we
will need multiple alerts and more data.
Chapter 3: Your first automated trade in less than 15
minutes!
Most traders think that creating a trading robot is hard. They think that you need
years of coding experience, before you can place your first automated trade. In
this chapter, you will create your first automated trade with no coding at all in
under 15 minutes. Sounds too good to be true right? Well, let’s try it out. I’ve
written a tutorial with pictures on how to do it. Follow this tutorial carefully, if
an error occurred, go back to the steps. You probably made a minor mistake.
Let’s get started!
Installation of tools
First of all, you need to work with google chrome as your browser. When you
have google chrome, we search in the google chrome web store for Autoview.
Autoview is an extension that will convert an alert in Tradingview to an order for
the exchanges you work with. Download the Autoview extension, by pressing
the blue button. When you have successfully downloaded the extension the
Autoview extension will appear in the top right corner of chrome. See picture
below.
Click on the Autoview icon in the top right corner of chrome. Now the settings
menu will appear. As is shown in the picture below. Click on change settings
button.
Now a new webpage will appear. We are now in the Autoview settings. See
picture below.
On this webpage, click on permissions on the left side of the screen. We need to
give Autoview permission to trade on a specific exchange.
Here you can see how many exchanges they support. They are always adding
exchanges and I think more will be added soon. For now, we want to automate
our first trade. In my opinion, the creation of an account on BitMEX testnet is
the fastest. So click on the button next to BitMEX testnet. When you’ve done
that it should appear as 2 green buttons. As it automatically also permits the
regular BitMEX exchange.
Now we will need to create a Bitmex testnet account to trade. Head over to
testnet.bitmex.com and register. See the picture below.
Great job, you have now created a BitMEX testnet account. Now we need to
give Autoview permission to place automated trades on BitMEX. Click on API
at the top of the screen in the middle.
Then this screen will appear on the left side of the screen, click on API key
management.
Set the key permissions to “order” and create the API key and save the ID and
key somewhere. This API will enable Autoview to place trades on BitMEX
testnet. Save the ID and the secret generated somewhere, I like to save this info
in a word file on my computer.
Now we will return to Autoview, we can do this by clicking the Autoview
security at the top right of the screen and click settings. Under exchanges on the
left side of the screen click on BitMEX testnet.
Now scroll up and right on the top of the screen click on add account. Now you
will see that you need an API ID and API secret key. You have just created on
BitMEX testnet. Copy and paste the info in the appropriate box. Afterward, click
test account. This will test whether Autoview can place trades on BitMEX
testnet. If you have done this correctly, the button will change to save account.
Click on this button. Autoview is now connected to BitMEX testnet.
Now enable Autoview to connect to Tradingview by selecting the Autoview icon
at the top right of the screen. Now click on Tradingview just above the change
settings button. When you click on this you will be taken to Tradingview.com
and Autoview will automatically have access to Tradingview.
First automated trade in 2 minutes
Now on Tradingview, we will create our first automated trade on BitMEX
testnet. We will open the xbtusd chart of BitMEX on Tradingview. Now we will
create an alert by selecting the clock at the right side of the screen.
Select create alert.
We want to test whether Autoview is working. Thus we select a condition that is
currently true, so that an alert is fired. Soon you will learn that you have created
your first trading strategy. The conditions are specified in the alert. Take a long
trade when the price of bitcoin is more than 1.
We change crossing to greater than, the value is set to 1. And we set the options
of the alert to every time. Furthermore, in the message box below we delete the
message and insert the text below. This is the syntax for trading. We specify the
exchange BitMEX testnet, e=bitmextestnet. We specify what side of the market
we want to trade, b=long. We select how much of the capital we have we want to
trade, 1=98%, we select which order type, we want our order to fill immediately
so we choose market.
e=bitmextestnet s=xbtusd b=long q=98% t=markete=bitmextestnet s=xbtusd
b=long q=98% t=market
Now we press save
Quickly head to BitMEX and see your first automated trade magically appear.
Great job! You have just placed your first automated trade. Moreover, you did
this at an incredible pace without any coding! I’m proud of you. Now you know
how to place automated trades!
Although the ability to place automated trades is great, it is not yet enough to be
profitable in the market. In the chapters onwards we will focus on creating a
profitable strategy for your trading robot to trade. You will discover how to
create trading strategies, you will discover how to evaluate whether a trading
strategy is profitable, you will discover tips, tricks, and common pitfalls in the
creation of profitable trading robots and much more.
Chapter 4: How to create a profitable trading robot
The ultimate goal is to create a profitable trading robot. But what is a trading
robot exactly, how does it work and why would you want to create one?
A trading robot executes trades automatically based on the rules you have
specified. In the example you’ve just completed, you created a trading robot that
trades bitcoin on BitMEX testnet. The criteria you have specified is to take a
long trade when the price of Bitcoin is larger than 1 dollar. Once the criteria
you’ve specified are met, the trading robot takes a trade. This is a very simple
strategy but, is it is a great start for creating more advanced automated trades.
The only thing you will need to change is the conditions for taking a trade, the
automated trade will just work the same.
Advantages of automated trading
The advantages of a trading robot are numerous, but the key advantages are:
- A trading robot is always watching the market and can work 24/7.
- A trading robot doesn’t have any emotions and always executes trades
according to the trading rules.
- A trading robots statistical edge in the market can be inferred with much more
ease than with discretionary trading. Giving you much more certainty whether
your strategy will be profitable or not.
- Lastly, a trading robot’s strategy can be tested against vast amounts of data,
which would take a discretionary trading strategy several years of testing.
Opposed to common belief creating a trading robot is simple. As I have shown
you in the previous chapter it is possible to create an automated trade in less than
15 minutes. The hardest part is not automating your strategy but creating a
profitable trading strategy. But this also applies to manual trading. When you
trade by hand you also need a profitable strategy. So in my opinion creating an
automated strategy is the best thing to do.
Although creating a profitable strategy is a challenge, there is a lot of literature
regarding this topic. The great advantage of literature regarding automated
strategies is that you can easily test the effectiveness yourself and the results are
crystal clear. Opposed to trying to trade a trading guru’s strategy by hand trading
a strategy by hand, who will tell you that you didn’t execute their strategy
perfectly, but don’t show you how they would have traded.
I get a lot of ideas for the creation of strategies by reading scientific papers
regarding automated trading. In these papers some of the smartest people in the
world have shared their automated strategies performance and trading rules in
detail. You just have to pick one that is promising and with some slight
alterations, you will have a strategy in no time. Then it is up to you to tweak the
strategies, to make them profitable.
Before you will try to create your trading strategy you will discover firs discover
the basics of price information and the most used indicators. Afterwards you will
learn the basics of trading strategies and later you will automate two of these
strategies. Furthermore I will share a checklist to evaluate a strategies
performance and will teach you a few tricks that can improve a strategies
performance greatly.
Although some of the strategies I will share are pretty good, it is not guaranteed
that the strategies are profitable. With some slight alterations and trading
knowledge, you might be able to make them profitable, but I do have to say that
nothing is guaranteed.
Chapter 5: Tradingview features, basic price
information and most used indicators explained
Tradingview features
A: Drawing tools
On the left toolbar you will find all drawing tools, such as trend lines, text zones,
Fibonacci extensions, retracements and much more. The toolbar has 18 items,
which we will discuss from top to bottom.
Profile details: here you can see your profile and profile setting. You can also
switch to dark mode
Cursor: different types of cursors
Trend lines: all types of trend lines, horizontal, regular and even regression trend
lines (tip you can chart an horizontal line with the alt + h short key combination
Schiff pitchforks, Gann and Fibonacci tools: many different options to chart
Geometric shapes
Annotation tools
Patterns: such as ABCD or head and shoulder patterns, with these you will
experience the powerful drawing tools Tradingview offers
Trade prediction: This is a tool you will use much if you want to test your
discretionary trading strategy, we will discuss these options in chapter 8
Icons: A whole range of icons that can be inserted on your chart
Measure: if you press shift you can also measure price changes in percentages
and points
Zoom function: zoom in or out on the chart
Magnet: This tool is very useful while using the charting tool. It will help you
chart elements to open, high, low and close candles (OHLC). You can try it out,
it works like a magnet to these OHLC candles. You can choose a weak or a
strong magnet, my personal favorite is the strong magnet mode.
Stay in drawing mode: this buttons keeps you in drawing mode
Lock all drawing tools: this will lock all drawing tools to the chart. So they
cannot be moved or deleted
Hide/show drawing tools: with this button you can hide all drawing tools on the
chart, or make them visible at once
Remove: with this button you can choose to remove all drawing tool, all
indicators or both.
Favorites: this buttons will show a toolbar on the chart with all your favorites.
Object tree: here you can see all the objects that are on the charts. This makes it
possible to carefully delete some charting elements, while keeping others.
B: timeframes, chart type and layouts
On the upper toolbar you will find time frames, chart types, layouts and much
more. The toolbar has 17 items, which we will discuss from left to right.
Security: in this box you can select the security of the asset you want to look at.
Since there are so many options Tradingview has several filters, you can select
stocks, futures, forex, CFD, cryptocurrency, index and economy. Furthermore
you can also filter the securities of an exchange, this is a feature I use
frequently. To select the specific asset charts of the broker I use.
Timeframes: Here you can select the timeframe. You can have several favorite
timeframes, which makes them more easily accessible. I have made the 1m,
30m, 3h and D timeframes favorites, such that I can easily switch between them.
Chart type: There are many different options to choose from, but the options are
more limited when using a free account. Renko charts for instance are not
available on intraday timeframes when you have a free account.
Compare: You can add another asset to the chart. The asset will appear as a line
chart. For instance you can chart the S&P 500 to the chart of Apple stocks. This
allows you to compare the price swings of Apple with the S&P 500.
Indicators: This is one of the most important buttons. There are so many
indicators to choose from. In the search box you can search the indicator you
would like to use, just like you would do in Google. Moreover you have a quick
selection menu on the left in which you can select Favorites, Built-in functions
by Tradingview, the public library, your own scripts and volume profiles. You
can also chart strategies which actually are visualized backtest on the chart. You
can easily see whether a script is a study script or a strategy script. Because
strategies have a red and green arrow behind them.
Financials: Tradingview has recently added fundamental data. They have all sort
of income statements, balance sheet, cashflows and ratios available. This allows
you to compare certain changes in fundamental data with the data on the chart.
Indicator templates: Predefined indicator templates.
Alerts: a very useful option which we will discuss in chapter 9
Replay: Personally I have used this feature a lot in practicing trading, back when
it was still available on a free account. This feature allows you to replay time.
You can select a moment back in time and it will look like all events still need to
unfold. This can be very useful in testing your discretionary trading strategy and
will be discussed in chapter 8.
Undo: As you know it
Redo: As you know it
Layout: This menu will allow you to select a number of chart lay-outs. You can
for instance have a split screen, in which the same stock is charted with different
timeframes. Or have several stocks in one overview. Unfortunately this feature is
only available for the paid versions.
Save chart total look and feel: This is a feature in which you can save the chart
look and feel. I have saved the chart look and feel I use often. This is especially
useful when you are experimenting with chart indicators, since it allow you to
select your favorite chart look and feel in an instant.
Chart properties: Many chart settings can be adjusted. You can for instance
adjust the color of candles, show session breaks and much more.
Fullscreen: As you know it
Snapshot: Allows you to printscreen your chart
Publish chart: Allows you to publish and share your chart ideas with the world.
C: Custom watchlist, alerts and hot stocks
On the right toolbar you will find your custom watchlist, alerts, hot stocks and
much more. The toolbar has 12 items, which we will discuss from top to bottom.
Watchlist, details and news: watchlists are a great feature. You can create a list of
all the securities you want to keep track off. With the free account you can create
one watch list. With the paid version you can get more watch list. Allowing you
to create for instance a watchlist for stocks for long positions, stocks for short
positions, crypto and much more. Details and news keeps you updated on what
news events are out for the particular security your currently looking at.
Alerts: This button will open a window with all your past and present alerts. The
free account only allows 1 alert.
Data window: Provides you with specific data of all the OHLC values,
percentage change and your plotted values for the current security and
timeframe.
Hotlist: Contains the main movers on the markets, usually those with high
percentage changes and volume gainers.
Calendar: A calendar for all the economic events.
My ideas: A list of your own published ideas.
Public chats: List of all ideas being posted on Tradingview. With chats
Private chats: Your own private chats are stored here.
Ideas stream: List of all ideas being posted on Tradingview
Notifications: Get notified about changes to your profile. Such as new followers,
when your mentioned in an idea of chat or when someone comments your idea.
Order panel: If you connect to your own broker via Tradingview, you can find
your order parameters.
Depth of market: This feature is usually known as the order book. This feature is
not supported by all brokers.
D: Stock screener, pine editor and strategy tester
Stock screener: In this section you can screen the stocks you would like to trade
by adjusting the filters. You can do this for stocks, crypto and forex. When
filtering securities, you can also choose the timeframe and market. A great guide
to stock screening is provided by Warrior trader. I have used this as a source of
inspiration for my own stock screener criteria in Tradingview.
Text notes: This allows you take notes.
Pine editor: allows you to program your own indicators and strategies, which we
delve into much more in chapter 5, 6, 7 and 9. This is my favorite feature of
Tradingview because it allows for so much flexibility in charting and the pine
editor also allows you to backtest trading strategies.
Strategy tester: This shows the return of your trading strategy and much more
detailed information, such as individual trades taken, the drawdown, gross profit,
gross loss, percentage gains and much more.
Trading panel: Depending on your broker you might be able to connect to your
broker. If this is possible, you can trade securities your broker provides in the
Tradingview charting environment, which is great!
E: basic chart information
In this panel the price information, indicators, graphs and drawings are plotted.
There are different options when charting price information. The one used most
often is the candlestick chart.
A single candlestick provides you with four pieces of information about the price
action of a security. It provides the high of the timeframe, the low of the
timeframe, the open of the timeframe, and the close of the timeframe. The center
of the candle, the part between the open and close, is called the body. The lines
that go up to the high and down to the low are called the upper and lower candle
wicks, or shadows. The candlestick tells us that price has moved to the highs and
lows of the candle before moving to the closing price. On a daily time frame,
each candlestick represents one day of trading. On a 5-minute timeframe, each
candlestick represents 5 minutes of trading. Charts can be set to any timeframe
you like, but the timeframes used most often are, 5-minute, 15-minute, 1 hour, 4
hour and daily timeframes. Due to the information a candlestick provides, we
can conclude the market sentiment based on the shape of the candle.
For instance, A Doji candlestick has a very small candle body, meaning the open
price and the close price are nearly the same. We can infer from this candlestick
shape that there is a momentary standoff between buyers and sellers. If the
candle occurs on heavy volume it tells us there is a battle at that price.
Sometimes a Doji will also have a long upper or lower candlewick. This tells us
the price suddenly moved up or down, but quickly returned to the same price as
the open. This means the move was not sustained. In general, Doji candles
represent some degree of indecision in the market. Some traders even take trades
based on certain candlestick patterns, such as a Doji candlestick. Since I don’t
trade set-ups based on candlestick patterns I would recommend you to watch
some tutorials of trading based on these candles sticks patterns as it will teach
you a great deal about market sentiment and overall price patterns. Which can be
used in the creation of different strategies.
Popular Tradingview features
Tradinview app on mobile
I often use the Tradingview mobile app. It is a great add on to your desktop
Tradingview experience. The use of a watchlist is essential in the mobile
environment. Because it will allow you to quickly switch between the securities
you want to monitor and trade. I feel that adding chart indicators and drawing
tools is a bit of a hassle on such a small screen. Therefore I would recommend to
make your chart look and feel ready in advance and then use your mobile
Tradingview app for looking at the chart and taking trades on the fly.
Indicators
Among the popular features, indicators are my personal favorite. There is a wide
range of built-in indicators available. One of my favorite indicators is a moving
average which you can see as a blue line in the figure below.
A moving average is determined by taking the average price of a price
information point from the last several candles of a specific timeframe. You can
choose the type of price information, the timeframe, and how many candles are
taken into account. You can choose between 4 different types of price
information, the open, high, low, or close price of a candle. Moreover, you can
also choose on which timeframe you do the calculation. Most traders use a 30
minute, 1 hour, 4hour, or a daily timeframe. Furthermore, you can choose how
many candle prices you want your moving average to take into account. In this
example, the blue line is the average close price of the last 9 candles at a certain
point in time. If we calculate the current 9 candle moving average of this chart,
we would calculate the average close prices of the 9 previous candles. Each new
candle this calculation is performed and plotted on the chart, so you get several
data points. Traditionally the moving average is charted as a line. The line
connects these data points, the line is much easier visible than each data point
separately.
Chapter 6: Trading strategies
All trading strategies can be divided into two types, namely, trend following
strategies and mean reversion strategies. When I made this discovery my
understanding of trading strategies improved greatly. Moreover, this discovery
also increased my ability to improve and create new strategies. I hope you will
experience this as well.
Trend following strategies
The basic assumption of trend following is that most profit in the market can be
made when the market makes a big move and the profits made during these
times are larger than when the market is stagnant or makes small moves. This
assumption has several implications for the typical performance of these
strategies. Trend following strategies have less winning trades than losing trades
because the market is only making big moves a small portion of the time.
Therefore most trend following strategies only win 30% of the trades. However,
if a big move occurs they will hit a homerun. Therefore these strategies typically
have a large profit factor. The profit factor is determined by dividing the average
winning trade by the average losing trade. Trend following strategies often have
a large profit factor, meaning they on average have big winners and small losers.
The profit factor and the percentage of trades the strategy wins are two key
principles you will need to understand. Based on these two metrics we can
determine whether a strategy is profitable or not. The figure and table below
show the relationship between the profit factor and winning percentage to play
even.
Winning percentage
25%
33%
40%
50%
60%
75%
Minimum profitfactor
3
2
1.5
1
0.7
0.3
Mean reversion strategies
The basic assumption of mean reversion strategies is that the true price of a
security is the mean. Another word for the mean is the average. These strategies
assume that when the price is extended to the up or downside, the price will
revert to the mean. These strategies are also called counter-trend trading
strategies. These strategies bet that the trend will not continue the price will thus
revert to the mean. These assumptions have several implications for the
performance of these strategies. These strategies have a high winning
percentage. Meaning they win more trades then they lose. Most of the time the
market is not experiencing big trends and prices mostly revert to the mean.
These moves are generally small. Therefore these strategies have small profit
factors. Meaning the average winning trade is sometimes equal or smaller than
the average losing trade. The smaller the profit factor the higher the percentage
of trades won needs to be to have a positive return. These strategies can suffer a
major loss when the market makes a big move. My advice, therefore, is to stay in
a trade shortly and sometimes use a strict stoploss set in place. When the trade
moves against you because the market is experiencing a big move, your stoploss
will prevent you from losing more money and will quit the trade.
Trend following strategies examples
Moving average crossover
Moving averages are trend indicators. A very simple trend-following strategy
uses two moving averages. One fast moving average and one slow moving
average. This strategy assumes that when the fast moving average crosses the
slow moving average upwards the upwards trend of price will continue.
In the figure below the fast moving average is the green line and the slow
moving average is the red line. When the fast moving average crosses the slow
moving average upwards, a long position is opened, indicated by the blue arrow
pointing upward. When the fast moving average crosses the slow moving
average downwards, the long trade is closed and a short trade is opened,
indicated by the red arrow pointing downwards.
Traders call it fast and slow because of their reaction to price movement. A fast
moving average is calculated with fewer candles than a slow moving average.
Traditional values are 50 candles for the fast moving average and 200 for the
slow moving average. As you can see in the figure the 50 candle moving average
reacts much faster and thus trails the price much closer than the red 200 candle
moving average.
Donchian channel
This might be one of the simplest strategies. This strategy assumes that when
price moves above the highest high of a certain period, the upwards trend will
continue. In the opposite direction, this strategy assumes that when the price
moves below the lowest low of a certain period the trend will continue
downwards. Traditional periods are the 30-day high and low, or the 100-day high
or low. As you can see in the figure below I have used a length of 100. So this
strategy places a long trade when the price moves above the highest high of the
last 100 candles.
You can transform this strategy by simply altering the timeframe or the number
of candles the calculation takes into account. A famous group of traders traded
based on this basic strategy with some slight alterations for closing and opening
a trade. In the book ‘way of the turtle’ this strategy is described. Although you
can also google this strategy, I recommend to buy this book because it discusses
a lot of other topics such as risk control that will help tremendously with the
creation of your strategy.
Bollinger bands break out
This strategy focuses on the very big moves and only takes long trades. When
the price moves above the 100 candle upper Bollinger band of 3 standard
deviations we take a long trade indicated by the blue arrow. We exit the trade
when the price moves below the 100 candle lower Bollinger band of 1 standard
deviation, indicated by the purple arrow.
Rate of change
A strategy I have created myself takes trades based on the slope of the moving
average. When the slope of the moving average becomes positive a long trade is
taken. When the slope of the moving average becomes negative we take a short
trade. In the example below I have plotted the slope in a separate plot. I have
used the 100 candle moving average in this example. You can see that this
strategy can catch the very big moves quite well.
Second derivative
This section is for the more mathematically minded people. I have used the first
derivative to calculate the slope. Then another idea popped in my head to use the
second derivative for the calculation of the curvature. I thought it might be
interesting to only trade when the slope is increasing and close the trade when
the slope is decreasing, although still positive. You can see the second derivative
as the blue line. As you can see the second derivative is very choppy which
results in a lot of trades being taken.
We can smooth the second derivative by creating a more smooth first derivative.
This can be done by calculating the slope of 5 data points instead of one data
point. This greatly smooths the green line and in turn smooths the second
derivative. Leading to fewer trades being taken. This might be an interesting
strategy to look into yourself and I will share the script with you. At
moneytreesolutions.nl/strategies.
Mean reversion strategies examples
Moving average
This might be the simplest strategy ever created and I remember that I was
totally surprised about how good the returns of this strategy can be. The basic
assumption of this strategy is that the price of a moving average is the true price
of the security you are trading. Thus when the candle closes above the moving
average the strategy assumes that the price will revert to the moving average.
Thus putting in a short trade. When the candle closes below the moving average,
this strategy will put in a long trade. As it assumes that price will revert to the
moving average. With this strategy you are always in a trade, you switch to long
and short trades continually.
Below is a picture of the return of this strategy. In this example, we are trading
the spx500usd of Oanda. With 100% of our portfolio each time, on a daily
timeframe, and we use a 5-day moving average. You see the return of 3-31-2003
to 7-31-2020. As you can see this strategy performs a lot better than the market,
which is the small blue line.
Bollinger bands
The first step in calculating Bollinger Bands is to compute the simple moving
average of the security in question, typically using a 20-day moving average.
Next, the standard deviation of the security's price will be calculated. Standard
deviation is a mathematical measurement of average variance and features
prominently in statistics, economics, accounting, and finance.
For a given data set, the standard deviation measures how spread out numbers
are from an average value. Standard deviation can be calculated by taking the
square root of the variance, which itself is the average of the squared differences
of the mean. Next, multiply that standard deviation value by two and both add
and subtract that amount from each point along the SMA. This produces the
upper and lower Bollinger bands.
For those of you familiar with statistics Bollinger bands will be familiar. When
we look at a normal distribution in statistics 95% of the values are within -2
standard deviations and +2 standard deviations. Although prices don’t have a
normal distribution, 80 to 90 % of the time prices between the Bollinger
(Grimes, 2012) The Bollinger bands assume that when the price is outside the 2
standard deviation range, the price is overextended and will return to the mean.
Chapter 7: Creating your first trend following
strategy
Select open pine script editor.
Select new and select new strategy script. Afterwards, a script will appear.
First, we delete everything below line 2. Now we will create a variable that will
be our fast moving average. Tradingview has a lot of built-in functions that will
do certain calculations for you. The calculation of a moving average is
incredibly simple. Sma is the function in Tradingview that calculates a moving
average for you. Now you will only need to specify the type of price
information, and the length. You can choose the open, high, low, or close as the
type of price information. And the length of the moving average is a metric you
can specify yourself. We will calculate the fast moving average based on the
open price and 50 candles. We will calculate the slow moving average based on
the open price and 200 candles.
Now that we have both moving averages we will specify when to buy and when
to sell. We only want to take a long trade or short trade if a specific condition is
met. Thus in Tradingview script, we begin with an If statement. Afterward, we
specify the long condition. We only want to take a long trade when the fast
moving average crosses the slow moving average upwards. Tradingview has a
function that exactly mirrors this statement. This function is called crossover.
The first variable we specify in this function is the variable that crosses over the
second variable. Thus crossover (fast_moving_average, slow_moving_average).
Now we will need to tell the software to take a long trade when this condition is
met. Tradingview also has a function that does this, strategy.entry. Between the
brackets we specify the trade ID, then we specify which side of the market we
want to trade. We want to take a long trade thus we state trade.long, and lastly,
we put in a comment which will show on the chart. This makes it easier to see
what happened. We will call this long. It is important to indent the strategy.entry
line. The indentation makes sure that we take a long trade only when the
condition in the IF statement is true.
For the short trade, we do almost the same. Only now we want to take a short
trade when the fast moving averages crosses under the slow moving average.
This is also a built-in Tradingview function, called crossunder. Furthermore, we
want to take a short trade thus we state trade.short.
Now we press the add to the chart button.
Congratulations! You have created your first strategy! On the chart, the blue
arrows that points upwards indicates a long trade and the red downward arrow
indicates a short trade.
When you switch to the strategy tester panel you can see the performance of the
strategy. When you press the setting icon the settings of the strategy will appear.
Now we have used the default settings. We have 100 000 initial capital and have
traded 1 contract. In this instance, 1 contract is thus 1 bitcoin. When we would
have traded with 1 bitcoin we would have made 2077 dollars. Which is a net
profit of 2.08% for the initial capital of 100 000 dollars. It is easy to see that this
is not ideal for testing the performance of your strategy. You might want to trade
100% of your capital at all times, allowing for compounding interest. Or you
want to trade with a specific amount of dollars. You can specify this in the
settings tab or the pine editor. I like to use the pine editor as these changes are
permanent until you change the code in the pine editor. I usually use the same
order size as the initial capital. This gives me the best overview of a strategy’s
performance. The ratio between the order size of 1 contract and the initial capital
differs per security. While the same order size and initial capital makes it
possible to compare the returns of strategies. In this scenario when we would
have traded with an order size of 100 000 we would have made a return of
roughly 20%.
Refinement of your first trend following strategy
You have just created your first strategy. Now we will refine the script to make
the results more meaningful and help you to improve this strategy.
In the second line, we now specify the title of this script. This will appear on the
chart screen and will help you to make distinctions when you chart multiple
indicators or strategies. Then we define the initial capital, I have used 100 000.
Next, we define the currency. You can use whatever you like, to use dollars type
USD instead of EUR. The default qty type specifies what type of order size to
use. You can choose to use a specific percentage of the initial capital, use a
specified amount of cash, or use contract sizes. I would advise you to use
specific amounts of cash or percentages as this makes a comparison between the
performance of strategies possible. I mostly use the cash method because the
performance metrics are more reliable. When I use the cash method I need to
define the qty value, I always set this to the same amount as the initial capital.
Overlay defines whether our plotted figures will appear on the same window as
the price or in a separate window. I set this to true for indicators that use roughly
the same scale as the price such as moving averages and Bollinger bands. For an
RSI or a MACD, I set the overlay to false, so that a separate window will appear.
Calculate on order fills, this needs to be set to false. I will show soon show you
why. When you made all these alterations you will get: Strategy("Moving
average crossover",initial_capital = 100000, currency = 'EUR', default_qty_type
= strategy.cash, default_qty_value=100000, overlay=true,
calc_on_order_fills=false)
In the pictures below you can see the difference between the calculate on order
fills settings. I show this for a strategy that takes a long trade when the price is
above the previous candle high. And closes the trade when the price hits the
previous candle low. In the first picture you can see the trades being exectured
when we set the calculate on order fill to false. We enter and exit the trades at
exactly the right prices.
When I set the calculate on order fills to true. We don’t execute the trades at the
right prices in. You can see that in the red candle we exit the trade at the candle
low, which doesn’t mirror the trading strategy’s criteria. So always set the
calculate on order fills to false.
Moreover, to easily analyze how the moving average strategy would have
performed with different moving average values we will change the length
values in lines 12 and 15 to input variables. Make all the alterations as in the
picture below. I will show you what the new lines of code will do.
Within the settings menu, we can now easily change the fast moving average
length and the slow moving average length. See below
Lines 4 to 10 allow you to specify when your strategy returns results. Making it
possible to select a specific period in the strategy settings. For instance, show the
strategy performance from 1-1-2019 to 1-1-2020. Or you can change default
values in the code. We will also need to add this to lines 19 and 22. In lines 19
and 22 we made a few additions. We have used a when statement. We will now
only take trades between the time specified in the lines between 3 and 10 or the
settings tab of your strategy. In the picture below you can see that you can now
specify by month, day and year when to show the strategy’s performance.
In lines 13 and 16 we have used the plot function. This function allows you to
show the indicator on the chart. First, we need to specify what variable we want
to plot and which color we would the variable to have. This will help
tremendously when evaluating your strategy performance as you can now see
when the green line of the fast moving average crosses the red line of the slow
moving average. I usually use this to check whether the strategy takes the trades
as I want them to take. Sometimes I will have to reevaluate my script.
Chapter 8: Automating our first trend following
strategy
Now that you have created your first trend following strategy it is time to
automate this strategy. We will automate this moving average crossover strategy
with BitMEX testnet. We will use the account you’ve created in chapter 3.
First, we need to transform our strategy script to a study script. Because we will
need to create alerts that Autoview picks up alerts and transforms into orders.
You can only create alerts with a study script. We open the strategy you just
created.
Now we select save as and give it a different name. I give it the name moving
average crossover study. Now we will begin transforming this script. We change
strategy to study, and delete everything after the title. After the title, we state the
overlay=true. Because we want to chart this study in the same window as the
price. We delete the input for time variables in lines 4 to 10, both if statements,
and the strategy.entry lines. In the figure below you can see the result.
We specify the long and short condition as a variable. This is the same as we did
with the if statements. But if the condition is true we now want to send an alert
that Autoview will transform into an order.
Now we use the alertcondition function of Tradingview. This function allows
you to create custom alerts. First, we tell the function when the alert should fire.
We want to fire an alert when the long condition is met, we give the alert the title
long. Because this will make it easy to select the correct alert. As you will see in
a minute. Furthermore, we already specify the message we typed in chapter 3,
with a minor addition.
e=bitmextestnet s=xbtusd b=short c=position t=market; this line will tell
Autoview to close a short position at market price. B is the side of the market, c
is close position and t is what type of order, in this case, market. We do this
because we first need to close a position before we can open a new one. If no
position is opened Autoview will just read the following line.
e=bitmextestnet s=xbtusd b=long q=98% t=market; this line will tell Autoview
to open a long position at market price. 98% of the capital available will be used.
Now press add to the chart.
Now we will create the alert. Make sure only the moving average crossover
study is charted, if not delete any other indicators.
The free version of Tradingview allows you to use 1 alert. Make sure you have
opened the correct chart. If not open xbtusd, and for the sake of testing I advise
you to use the 1-minute timeframe. With the 1 minute timeframe, the long and
short positions are met more often. Click on the clock security. And click on
create alert.
Now select XBTUSD and change it to moving average crossover. Change the
condition to long. This will be our long alert. Make sure the line that each line
that begins with e=bitmextesnet is separated by an enter, like the picture below.
Otherwise, Autoview will not pick up the alert.
To change to the short alert click on the box below moving average crossover
and select short.
Because we should have been in a short position (the fast moving average is
below the slow moving average). I want my strategy to take a trade when the
long condition is met. So I select long, once per bar, and click create.
Great job! You created your first automated strategy and you now have a trading
robot! Now you just have to wait until the condition is met to see whether your
trade is placed automatically.
The different trade alert options.
- Only once, only fire the alert once. If the condition is met once the alert will
stop working
- Once per bar: I advise you to use this option it fires an alert once per candle.
- Once per bar close: this option only fires an alert at the candle close, it doesn’t
fire an alert during the time a candle is created.
- Once per minute: I wouldn’t advise you to use this option because so many
alerts will fire. With some exchanges, you will end up with multiple positions.
Chapter 9: Creating your first mean reversion
strategy
You will now create your first mean reversion strategy on the SPXUSD500.
Click open pine script editor
Open the moving average cross over strategy you just created.
Save this script with another name. We will then begin the transformation of this
script to your first mean reversion strategy. I often reuse the scripts I’ve made
and simply transform it, instead of creating a new script from scratch. As a lot of
the scripts use the same functions and variables.
First, we change the title of line 2. We change it to the name we just saved. We
then delete the lines of the slow moving average and we change the fast moving
average to moving average. See the image below.
Now we need to specify the trading conditions. We want to take a long trade
when the candle closes below the moving average and we want to take a short
trade when the candle closes above the moving average. So we create a variable
called long and specify the long condition. And we create a variable called short
and specify the short condition.
Now we need to create the part that takes the trades. We don’t have to use the if
statements and therefore the lines that start with strategy.entry don’t have to be
indented. So we will delete those. Instead, we create an extra condition, when to
take an entry trade. We take a long trade when the long condition is true, and the
time falls between the specified time. We do the same for the short trade.
Now press save and then add to the chart. Oops, it didn’t work. How could this
happen? Tradingview has an excellent error log. In the lower part of the screen,
you will see a red line. This indicates an error. Luckily for us, Tradingview also
specifies what mistake we made. If you click on the red line, Tradingview will
automatically take you to the part where you made the mistake. How awesome is
that?!
Can you spot the mistake I’ve made in the line 13?
The mistake is that the variable moving average is unknown. The variable that I
wanted to plot is moving_average. We will change this now.
Oh no still didn’t work. What mistake did we make in line 16?
Do you see it already? I made the same mistake. I again referenced a variable
called moving average while I should have referenced moving_average instead.
This is our final code.
Now press save and then add to the chart.
Great job, you did it! You created your second strategy and you now know how
to deal with errors in your code. I’m very proud of you!
Chapter 10: Automating our first mean reversion
strategy.
Now that you have created your first trend following strategy it is time to
automate this strategy. We will automate this strategy with Oanda. We will first
create an account.
Head over to Oanda.com, and select the sign-in button at the top of the screen.
Select sign-up
Select fx trade practice
Fill out the form
Now when you have an account click on manage API access under the My
services header.
Create an API key by selecting the generate button. Save this in a file. You will
need it shortly.
Go back to my account page and select manage funds.
You also need the v20 account number. Save this in the same file.
Now head over to the Autoview settings page. Under the permissions header
select OANDA practice (beta)
Now under the exchanges head select OAND practice (beta)
Scroll up and create a new account. The v20 account number is your account ID.
The key you API key you just generated is the access token. Click test
credentials and then add account.
Transforming our script
First, we need to transform our strategy script to a study script. Because
Autoview picks up alerts and transforms these into orders. We open the strategy
you just created.
Now we select save as and give it a different name. I add to it that it is a study
script. Now we will begin transforming this script. We change strategy to study,
and delete everything after the title. After the title, we state the overlay=true.
Because we want to chart this study in the same window as the price. We delete
the input for time variables, both if statements, and the strategy.entry lines.
We already specified the long and short condition as a variable. If the long
condition is true we want to send an alert that Autoview will transform to an
order. We also do this for the short alert. We use the alertcondition function, just
as we did in the previous example. This function allows you to create custom
alerts. First, we tell the function when the alert should fire. We want to fire an
alert when the long condition is met, we give the alert the title long. Because this
will make it easy to select the correct alert. As you will see in a minute.
Furthermore, we need to specify a similar message but now for Oanda and on
the SPX500USD.
e=Oandapractice s=spx500usd b=short c=position t=market; this line will tell
Autoview to close a short position at market price. B is the side of the market, c
is close position and t is what type of order, in this case, market. We do this
because we first need to close a position before we can open a new one. If no
position is opened Autoview will just read the following line.
e=Oandapractice s=spx500usd b=long q= 1 t=market; this lines will tell
Autoview to open a long position at market price. Unfortunately for Oanda, the q
value needs to be in the number of units. It doesn’t work with percentage values.
How much 1 unit costs depends on the security you are trading and the amount
of leverage you use. In the Oanda trading environment, you can see how much
money you need to buy 1 unit for each security.
We also create an alert to take a short trade. First we need to close the long trade.
e=Oandapractice s=spx500usd b=long c=position t=market; this line will tell
Autoview to close a long position at market price. B is the side of the market, c
is close position and t is what type of order, in this case, market. We do this
because we first need to close a position before we can open a new one. If no
position is opened Autoview will just read the following line.
e=Oandapractice s=spx500usd b=short q= 1 t=market; this lines will tell
Autoview to open a short position at market price. Unfortunately for Oanda, the
q value needs to be in the number of units. It doesn’t work with percentage
values. How much 1 unit costs depends on the security you are trading and the
amount of leverage you use. In the Oanda trading environment, you can see how
much money you need to buy 1 unit for each security.
The picture below shows the final result
Now press add to the chart.
Now we will create the alert. Make sure only the study you just created is
charted, if not delete any other indicators or strategies.
The free version of Tradingview allows you to use 1 alert. Make sure you have
opened the correct chart. If not open SPX500USD, and for the sake of testing I
advise you to use the 1-minute timeframe. With the 1-minute timeframe, the long
condition is met more often. Click on the clock security.
And click on create alert.
Now click on SPX500USD and change it to the study you just created. Change
the condition to long. This will be our long alert. Make sure the line that each
line that begins with e=bitmextesnet is like the picture below. Otherwise,
Autoview will not pick up the alert.
To change to the short alert click on the box below long= price>sma and select
short.
I want my strategy to take a trade when the long condition is met, but only want
to take a trade when the candle is closed. So I select the option to only send an
alert at once per bar close. So I select long, once per bar close and click create.
Great job! You have created your second automated strategy, and this time it is a
mean reversion strategy. You are doing great. Now you just have to wait until the
condition is met to see whether your trade is placed automatically.
Chapter 11: How to determine whether a strategy is
profitable?
By now you know how to create strategies and you know how to automate them.
Making it possible to let the computer take the trades while you focus on doing
the things you love! Now we will try to determine whether a strategy is
profitable or not. So that you can let start your automated trading journey and
begin to earn a nice profit besides working your job.
In this chapter, we will deal with backtesting, furthermore, I will show you an
example of a profitability analyses for a trend following strategy and a
profitability analyses for a mean reversion strategy.
Backtesting.
The ultimate goal is to create a profitable trading robot. When you create a
strategy in Tradingview, Tradingview also shows the performance of the strategy
in the strategy tester tab. The strategy tester tab shows the performance of the
strategy against historical data. Testing your strategy against historical data is
called a backtest.
Testing your strategy against historical data is comparable to when you are
trading with a practice account before trading with real money. You want to test
your skills and improve upon them before trading with real money. The great
advantage of backtesting, however, is that you can test your strategy against
years of data in a matter of minutes, instead of testing your strategy over several
years. Furthermore testing a manually traded strategy and trading the manual
strategy live in the market are two very different things. The emotions and
discipline make it hard to take the trades exactly as you did when testing.
Moreover when you trade by hand you never quite know whether your trading
strategy has any statistical edge in the market. With backtesting, we can figure
this out and ultimately let a computer trade the strategy in the market while we
can focus on doing the things we like or work a regular job. Eventually earning
you a nice profit.
Backtest basics
Earlier we created a moving average crossover strategy. If we open this strategy
again and show it on the chart we can see the performance of the strategy in the
strategy tester tab. In this chapter, we will quickly go over the backtest
information Tradingview provides.
Open the strategy again and apply it to the chart. In the strategy tester tab of
Tradingview, you see what a backtest looks like. The enormous benefit of
Tradingview is that you can easily evaluate the performance of your strategy for
all securities that Tradingview offers. You just type in a security and it
automatically calculates the performance of the strategy. Furthermore, you can
just as easily see the performance of your strategy with different timeframes. Try
it out! And see how the performance metrics change.
In the strategy tester view, we can already see how the strategy would have
performed during the test period. In the list of trades view of the backtest, we
can see all the trades taken. I often use this tab to determine how much data is
available. In this instance, we have data from 5-30-2020 back to 5-6-2004.
When we switch back to the overview tab we can see how our strategy has
performed during this period. From left to right. At the end of the trading period,
we would have made 67.07%, while taking 34 trades. Of these trades, 44.12%
would have been profitable. The profit factor is 1.604. The profit factor is a
metric that tells you that the average winning trade is 1.604 times bigger than the
average losing trade. The drawdown is 26.68%. This metric tells you that if you
would have started trading this strategy at its worst-performing moment, you
would have had a maximum loss of 26%, before recovering. We can see that the
average time between opening and closing a trade is 122 candles. In this
instance, we would on average be 122 days in a position. Moreover, we can see
in the strategy tester chart how our trading balance would have developed and
we can compare it with a simple buy and hold strategy during this period. This is
the blue line. We can see that if we would have bought the spx500usd in 2004
and didn’t sell it, we would have made more money than when trading this
strategy. All of the metrics on this tab are crucial points of information when
developing a profitable trading robot and we will soon discuss these metrics in
more detail.
In the performance summary tab, we can see more detailed information. Which
is also important for the development of your trading robot. This tab specifies
the performance of the long trades and short trades. Over a long period, the short
trades have not been performing well, which makes it more likely that the short
trades will also perform badly in the future. The short trades have made an
overall loss of 16.67%. In this instance, I would run this strategy without taking
short trades. Another very important metric is the Sharpe ratio this ratio tells you
a lot about the statistical edge of your strategy in the market. Moreover, this tab
also shows the profit or loss of the currently opened trade. In this instance, we
have an open short trade with currently a 17.34% loss. The performance
summary furthermore dives into the specific numbers of trades, the percentage
of profitable trades, the profit factor, and the average time spent in a trade.
Chapter 12: Checklist for evaluating strategies
In the previous chapter, we have glanced at the backtest metrics Tradingview
provides. Although all metrics are important, a basic understanding of these
metrics is not enough to develop profitable strategies. You will need to evaluate
these metrics, which is what you will discover in this chapter. In this chapter, I
will share my checklist for evaluating trading strategies. Later we will perform
an analysis of a trading strategy. Together we will go over the checklist and try
to determine whether the strategy is potentially profitable or not.
Choosing the timeframe and security
The timeframe and security can make all the difference. I will share with you
how I will determine the timeframe and the security.
Determine the timeframe
When I have just created a strategy I will first focus on the timeframe. I am
generally interested in strategies that perform well on a 30 minute or 1 hour or 4
hour timeframe. I mostly focus on these timeframes because these timeframes
allow for many trading opportunities. When you want to determine whether a
strategy is profitable or not you will need a lot of trades to analyze. I have very
little confidence in a strategy that for instance only takes 10 trades during a
decade. I usually aim for 50+ trades being taken.
Determine the security you can trade profitably
When I have an idea about which timeframe I will use. I will go over a lot of
securities. I will try to determine for which securities my strategy is working. In
my experience, a strategy only has to work for 1 specific security to be
profitable. I generally also switch the timeframe when looking at 1 specific
security. It is about finding a good combination of the security and the
timeframe.
In contrast with many trading quants, I am a strong advocate of developing a
trading strategy based on 1 security instead of a whole range. In my experience
market conditions vary a lot which makes it a nearly impossible task to create a
trading strategy so robust it can be successfully traded on several securities. I
therefore advise you to trade 1 security. For the beginners out there I think
creating a strategy on Bitcoin is the most simple to create, followed by indexes,
and lastly forex. Creating strategies based on the continuous minor swings of the
forex market rank the most complex to me. I currently have created one strategy
that might be able to profit in the forex market, but am currently still putting it to
the test, while I already have 2 strategies for Bitcoin and 4 strategies for indexes.
Tip for fast analyses of the timeframe and security
Easily switch between securities and timeframes: Create a watchlist in which
you put all the securities your broker provides. Now you can quickly go through
them by selecting a security in the watchlist. Now you will see the strategy
return chart changing. The security in combination with the timeframe is the
most important when you have a robust strategy such as the moving average
crossover. To make the analysis easier, create input variables for parameters,
such as the length of both moving averages.
Tests for robustness
Robust trading results when changing the parameters
Although a strategy can never perform well for all securities and all timeframes,
the trading strategy must be robust for the security and timeframe you want to
trade. What I mean with the robustness of the trading strategy is that the trading
results don’t vary much when you alter the parameters. Take the moving average
crossover strategy as an example. The results of the trading strategy need to be
fairly stable when you change the value of the fast moving average from 3 to 20
and the performance of the slow moving average from 100 to 200. When the
returns are stable for a range of parameter values, it is more likely that the
returns will be stable in the future. Since prices will vary in the future the best
performing combination of the moving average strategy will likely change
leading to different results. If however, the returns would vary a lot between a
fast moving average with a parameter value of 5 or 6, the strategy is not robust.
When the prices change the return of your strategy will also change greatly and
often not for the better.
To deal with this test I strongly advise you to develop simple strategies. These
strategies deal with fewer parameters and are often more robust. This is a test
that my first strategies failed. I created strategies that would be massively
profitable when trading with a parameter value of 10 but would suffer major
losses with a parameter value of 11. This is an indication of curve fitting which
is a problem many people face when developing strategies. I will describe this
problem in another chapter.
Robust trading results on more and different data
Tradingview offers more data than they show, but you will need a subscription to
be able to see it. The cheapest subscription is sufficient. If you use the replay
function and go to the beginning of the chart and then select it Tradingview will
load the data before that point. In this way, you can see the results of your
strategy with new data. For example, on the 4-hour timeframe of the spx500usd,
I can see the data back to 2014 when I use the replay function twice. While at
first, I could only see the data from 2017-1-1 to 2020-6-6.
When I get more data I want to see comparable results as with the original data.
And if that is the case I try to determine which combination of input variables is
the best for all data for that security.
Analyses of performance in general
A positive return
When evaluating the performance always look at the return of the strategy at
first. The return should of course be positive. If you analyze a strategy that takes
both long and short trade, go to the performance summary tab. Is the strategy
profitable for both long and short trades? Or might it be better to quit trading one
of the sides in the market? When trading indexes I usually only take long trades,
as these indexes tend to be trending upwards.
The picture
The picture that shows the return of the strategy tells a lot of information. I
always look for five things.
Does the strategy perform well until the current date?
This is critical as it indicates that the strategy performs well across time. Below
you can see two pictures. I usually aim for a return like the first two pictures. I
recommend you not to trade a strategy that is already failing to perform as it
further decreases the likelihood that the strategy is profitable.
Not like this:
Is the strategy able to recover from losses?
Even great strategies suffer some small losses, but the ability to recover from
these losses differentiates between profitable and losing strategies. This is
something you also want to see when your trading strategy is running live in the
market. If a strategy suffers losses, I would like to see a recovery like this.
Is the strategy able to perform well when the security is in decline?
A great thing to see is when your trading strategy is performing better than a buy
and hold strategy when the securities return is in decline. Otherwise, the return
of your strategy might be due to the performance in the market. It is easy for a
strategy to perform well when the market performs well. But great strategies are
able to perform well when the market is in decline. I usually try to test my
strategy across different market conditions. When I am trading the S&P 500 on
a daily timeframe I spend some time evaluating the performance in the market
decline of 2008. You can compare the performance of your strategy against the
buy and hold return of the security against the blue line. If the blue line doesn’t
show up you will need to select the buy & hold equity box in the strategy
overview tab.
Is the return of the strategy distributed smoothly?
I am a big fan of trading a strategy that has a smooth equity curve. Although this
might be one of the hardest things to do, it will make it much more likely that
your strategy will be profitable. Moreover, it indicates that you will not
experience heavy losses. See the pictures below for a trading strategy that has a
smooth equity curve.
Is the strategy’s return positive for specific samples of your data-set?
Although losses are part of trading, I always strive for as few losing periods as
possible. For a daily timeframe, I will evaluate each year separately, in which
one losing year is acceptable to me. For a 4 hour, 1 hour or 30 minute timeframe,
I evaluate each month separately and I strive for only one losing period. If the
strategy does suffer some losses during a specific period, the ability to recover is
crucial. I usually look at the equities return picture evaluate this quickly. I like to
see something like this, in which each period regardless of how you slice the
data just by the look of the curve is profitable.
For the 30 minute or 1 hour timeframe, I evaluate the returns in a little more
detail, by altering the time input variables. I for instance evaluate each month. I
do this in more detail because there is less data available than with the other
larger timeframes.
I would not be comfortable trading the strategy below, just by the looks of it the
last hundreds of trades have not or only have been marginally profitable.
Small drawdown
With a simple buy and hold strategy for the S&P 500 most investors suffer
drawdowns of 50%, while the market only returns 8% on average. If you’ve
begun early with investing, these drawdowns won’t be too bad, as you still have
time to recover. But when you are older, you don’t have this recovery time. In
my opinion, the risk to reward for buy and hold investing is not good enough.
Over the past decades, each crisis wiped out 50% of your total invested capital. I
don’t want to waste my hard-earned money like that, and I would certainly lose
interest if my hard-earned money decreased to half of its value. Afterward taking
approximately 5 to 6 years to recover to its original value.
What I aim to do is develop strategies with a better risk to reward ratio than the
buy and hold strategy does. Most often I have strategies with lower drawdowns
than the buy and hold strategy, although the return can be slightly less. The
relationship between the drawdown and return is important and their relationship
is best explained as how much risk your willing to take for the potential profit.
This varies per person. When evaluating the drawdown of your strategy, always
keep the buy and hold strategy return and risk in mind. I would recommend you
to set a goal to create a strategy with a comparable return to the buy and hold
strategy, but with a smaller drawdown. This will be a great goal to start your
automated trading journey.
Leverage
Leverage is a very interesting topic, as it can greatly increase your trading
profits. This might be a difficult idea to grasp, but it in its simplest form leverage
works as a multiplier. When I trade with a leverage of 1:5, I’m trading with a
multiplier of 5. For instance, when I take a long trade with 1000 dollars and 1:5
leverage. I am no longer trading with 1000 dollars, but with 5000 dollars.
With the use of leverage I can increase my profits, but be careful it can also
increase your losses. If I take along trade with leverage of 1:5, a price increase of
1%, will become 5% of unrealized profits. This can grow your account very
quickly. However, it also can decrease your account quickly. If I take a long
trade with a leverage of 1:5, a price move down with 1%, will give me an
unrealized loss of 5%.
Leverage and drawdown are in my opinion closely connected when creating a
trading strategy. One strategy has a drawdown of 2%. Because of this drawdown,
I’m able and willing to trade it confidently with a leverage of 1:10. With the use
of leverage, this strategy can outperform the market, while without leverage it
cannot. It returns roughly 60%, while without the leverage it would only return
6%. The drawdown is so small because I trade a small timeframe, with a simple
conditional rule, and I only stay in trades for a short time limiting my risk.
Average trade size
When you want to develop a profitable trading strategy it is important to
consider the average trade size. This is important because the fees and spread
will also influence the profitability of your trading strategy. Be careful that the
spread is influenced by the liquidity of the market. A small spread is needed to
be profitable with small average trades. As a general rule, securities that are
traded a lot have smaller spreads. For instance, EUR/USD has a smaller spread
than USD/MXN. A strategy with an average trade size of 0.04% might be
profitable on EUR/USD, but would lose money on USD/MXN because of the
spreads and fees alone.
I only trade the biggest markets because of the lower fees and spreads. In my
experience strategies need to at least have an average trade that is bigger than
0.04%. When the average trade size is smaller your strategy won’t be profitable
because the spread and fees, will be more than the size of your average trade.
You might wonder, what is spread? Spread is the difference between the price
people want to sell for and the price people want to buy for. For instance,
someone wants to sell the SPX500USD for 3000, and someone wants to buy the
SPX500USD for 2999. The spread in this case is 1. When you use a market
order to buy a stock, you will pay the price of the best seller. In this case 3000.
In the order book, you can see all the prices people want to sell and buy for.
When you use a market order to buy the SPX500USD for 3000, the price of
3000 is no longer on the table. The best price someone is selling for will then be
3001, and the buyer will need to pay 3001. This difference in supply and demand
makes prices move.
Each time someone buys or sells a security is called a tick. The most accurate
data to use when backtesting is tick-based. Some software packages provide
tick-based data, Tradingview however does not. For some traders, this might
seem problematic, but it is not. Although tick-based data is the most accurate
data available I have compared the backtest results of Tradingview that does not
offer tick-based data and Metatrader that does, and the difference in results is
minimal. The backtesting software of Tradingview is thus incredibly accurate,
and most traders won’t notice the difference.
Total closed trades
I like to trade strategies with a lot of trades. Because it is impossible to
accurately predict the return with only a few trades in a certain timeframe. For
instance, evaluating your return when only 10 trades have been taken is not
reliable. You will need a lot more trades to estimate the profitability and
reliability of a strategy. In the next section about market edge, you will see how
much trades you will need to reliably estimate the return of a strategy.
Market edge
If your strategy is still promising after all these checks we need to check for an
edge in the market. This is a topic that takes a little bit more work, that is why I
only do this for the most promising strategies.
To determine the edge in the market we will need the Sharpe ratio, the number of
trades, and the risk-free return. This might be a bit too much mathematics for
some, but I strongly encourage you to follow along. Just do the calculation and
the outcome should be higher than 2. Ideally higher than 3.
We want to determine whether the returns of our strategy have a chance of
returning more than 0%. If we have a high chance that the strategy has a higher
return than 0%, we are more confident that our strategy has an edge in the
market. Meaning that in the long run, our strategy will probably be profitable
and return more than 0%.
We can compare this to playing roulette in a casino. There are 49 black, 49 red,
and 2 green options. This means that when you bet on black or red the casino has
a statistical edge over you, the player. You have a 49% chance of winning, while
the casino has a 49+2=51% chance of winning.
In the short term, this statistical edge might not be apparent, and you might be
lucky and win more than the casino. However, when you play infinitely long the
casino will win 49+2 = 51% of the times and you will win 49% of the times.
This is what we aim for as algorithmic traders. We want to be like the casino.
This approach also has some implications for trading strategies. Just like in the
casino the return of our strategy in the short term can be greatly different than
the long term results. Just as in the casino we may lose money at first. But in the
very long run, we will probably make money.
We calculate our statistical edge by comparing the distribution of our returns
with a distribution of returns with a mean return of 0%.
If our return overlaps very little with the distribution of returns with a mean of
0% we are more confident that we have a statistical edge. I always strive for a z
value larger than 3. This means that the chance that the returns are part of the
population of returns that is 0% is only 1%. Unfortunately, we can never be sure,
but it is a lot better than just trading based on unproven strategies, emotions, and
the news.
Although this calculation assumes a normal distribution and the returns of a
strategy are most likely to be skewed it does hold up pretty well. Because we try
to determine the overlap of the strategy’s returns with the returns of a
distribution of 0%. If the overlap is very little the distribution of the data is not
an issue. This is why I propose that your strategies return need to at least have a
z value of 2 and ideally 3.
The calculation
In this formula, X is the return of the strategy. μ is the mean of the population we
compare our returns with, in this case, 0%. ơp is the standard deviation. N is the
number of trades.
We don’t know the standard deviation. But we can infer it with the help of the
Sharpe ratio. The sharp ratio is calculated with the following formula.
Sharpe Ratio = (Rp – Rf) / ơp
In which Rp is the return of the strategy. Rf is the risk-free rate of return.
Tradingview uses 2%. And o is the standard deviation. We know the Sharpe
ratio. Thus our standard deviation is
ơp = (Rp-Rf)/sharpe ratio
An example:
rp = return of the strategy = 23.82
rf = risk free rate of return = 2
sharpe ratio =0.747
Thus the standard deviation is:
ơp = (23.82 - 2 )/0,747 = 29.210
To calculate the z value, we use the following formula:
Z = (X – μ)/ ơp
X = return of strategy
μ = mean of population = 0%
ơp = standard deviation
n = number of trades
Below we calculate the Z score for 2 strategies where only the number of trades
varies. It will become apparent how important the amount of trades is. In the
second example with very few trades, the strategy is less likely to be profitable
than the strategy of the first example.
Z = (23.82 – 0)/ (29.210/√58) = 6.210
Z = (23.82 – 0)/ (29.210/√9) = 2.44
Chapter 13: Common pitfalls of trading systems
Curve fitting
Curve fitting is also known as overfitting. This is the most common backtesting
mistake by all algorithmic traders. When you create a strategy you can change
the parameters to optimize your strategy’s performance. Overfitting happens
when you do this too such a high degree that your trading strategy only works on
that specific data set. When new price information is presented your trading
strategy fails miserably. You might wonder, but how do I know whether my
strategy is overfitting. To answer this question I recommend checking out your
script. If you have many trading rules, with specific values and changing one of
these values results in a very different strategy performance, you are overfitting
your strategy. This has been a problem for me as well. I created a strategy where
I was trading the RSI, with so many conditional variables that wouldn’t make
any sense. I for instance would take a long trade when the RSI was between 23
and 29, and the price was between the 4-day and 6-day moving average and
above the 100-day and 200-day moving average. This strategy looked good on
paper, but failed miserably when trading live in the market.
A simple tip is to reserve data for testing your strategy. If your strategy is robust
it will have roughly equal returns for the new data. If however your strategy is
overfitted the return will be vastly different. As a general rule, a robust strategy
is most often simple and the return is roughly the same for a range of values. For
instance, when using a moving average crossover, the return (with some
securities) does not differ much when using a range of values between 20-30 for
the fast moving average and between 50-70 for the slow moving average.
Developing robust profitable strategies that you can trade safely is the main goal.
Repainting
Although the Tradingview backtest does work well it comes with a problem
which many traders do not discover. Some strategies suffer a problem which is
known as repainting. I will explain this by using an example. In this strategy, we
take a long trade when the RSI based on the closing price of the last 14 candles
is below 30. We exit this trade when the RSI is above 70. A very simple strategy
with complex results. I recommend you to add this indicator to the chart. When
you look at a live chart you can see that the values of the RSI are changing as the
price changes. This happens because the closing price varies as the candle is still
being formed. In some instances, the RSI would have been below 30 at some
point. Thus when running this strategy an alert would have been triggered and
you would have taken a long trade. But when the candle closes the RSI is no
longer at 29 but now is 31. The strategy tester of Tradingview will only calculate
the strategy performance based on the RSI value at the closing price of 31 and
thus no trade is taken. This can become very problematic when trading your
strategy live in the market, as the live results will be different than the backtested
results.
I, therefore, recommend you to create strategies that are based on the open price,
or creating alerts based at the candle close, as these values don't vary.
The repainting problem also occurs when using stoploss and takeprofit in your
trading strategy, because Tradingview does not work with tick-based data. It will
exaggerate returns greatly.
When your long Tradingview assumes that the price moves to the high of the
candle before reverting to the low of the candle. When you are in a short trader
Tradingview assumes that the low is hit first before the price moves up to the
high. This greatly affects the returns of a trading strategy that uses a takeprofit
and stoploss. When in 1 candle both the stoploss and takeprofit are hit.
Tradingview assumes the takeprofit is hit first. I’ve developed a strategy that
makes this extremely clear. This strategy has an incredible win rate, but results
in the real world are enormously different and this strategy loses a lot of money.
Believe me, I ran this strategy live in a demo account and I blew the account in a
matter of days.
Not testing your backtested strategy live in the market
This is the mistake I have made and it cost me greatly. Especially because I
combined it with curve fitting and repainting. My trading strategy therefore
performed differently than the backtest results. In a month I lost 2000 dollars of
the 5000 dollar invested, which was a lot of money for me. I needed to learn this
lesson the hard way and I hope you won’t do the same. I advise you to test your
strategy for at least 3 months with a demo account. Many traders like myself
however are too eager and think it is not needed. The question I asked myself
was, what if it works and I could have made a lot of money? This however is the
wrong question to ask. It is much more costly to lose your hard-earned money.
Previously you probably didn’t trade profitable so there is no cost of waiting. I
thus advise you to start with a demo account or with a very small amount of
money. The amount of money should be so small that you would be comfortable
to throw it away now.
Using a computer and network connection that doesn’t work
flawlessly
When I just started I wanted to save money so I used a Raspberry Pi to trade.
However soon my internet connection was down, another moment the electricity
was down, and another moment someone in my family pulled out the adapter.
All these circumstances result in downtime in which my trading robot was not
able to trade. This can be very costly especially when you don’t notice it
happening. I, therefore, recommend you to use a virtual private server. For those
of you who don’t know what a virtual private server is. A virtual private server is
best explained as a pc that is in the cloud. You pay a subscription to use the pc
and the one you pay the subscription guarantees that the pc is functioning 99,9%
of the time. If you chose to buy a subscription to a windows VPS, it will work
just like a normal windows pc. These machines sound costly, but the costs can be
limited. I have a subscription for $18 a month.
Chapter 14: Simple improvements of strategies
Most trading strategies are not immediately profitable. You will need to make
some improvements to do this. In general, I always do 4 things for each strategy
I develop. If these steps won’t result in improvements I will quit trying as this
strategy will probably not work. If however, I keep tweaking the strategy, I
might end up with the curve fitting problem described earlier.
Change the security and timeframe combination
As discussed earlier I try to focus on one security, the first thing I will try to do is
find a security and timeframe combination that performs well. I mainly focus on
the picture in the strategy tester tab as discussed earlier.
Stop taking trades in one of the market sides
This is the first thing I check. In the performance summary tab, you can see the
performance of the trading strategy for long and short trades. Most of my
strategies only take long trades, because the strategy's performance when going
short was either negative or had a very bad risk to reward ratio.
Tweak the parameters, but don’t get to specific
Some strategies will benefit massively from changing the parameter inputs, but
be sure to check the robustness as described earlier. For a moving average
crossover strategy, I for instance try to determine a good combination of the fast
and slow moving average. When doing this I mainly focus on the strategy testers
tab picture, drawdown, and number of trades.
Improving a strategy with a simple conditional statement.
The return of a strategy can take an enormous positive leap when a conditional
statement is implemented. A conditional statement I often use is the 200 candle
moving average. With some strategies that only take long trades, I only trade
when the price is above the 200 candle moving average. Many traders around the
world consider the security to be in an uptrend when the price is larger than the
200-day moving average.
Great conditional statements:
- Only trade when the price is above a long term moving average, such as the
200 candles moving average (works for trend following strategies and mean
reversion strategies)
- Only trade when the price is between the Bollinger bands (works for mean
reversion strategies)
Chapter 15: Going over the checklist for a mean
reversion strategy and improving the strategy
I am curious about the simple moving average strategy we discussed earlier. The
results seem promising. Let’s analyze the performance and see whether we can
improve the strategy.
Change the security and timeframe combination
I already did this analysis work and determined that this strategy works
especially well for the SPX500USD on the daily timeframe. Always use the
same initial capital as the order size when comparing. And be sure to check that
the time period of trading is equal. Otherwise, comparisons won’t say much.
Stop taking trades in one of the market sides
In the performance summary tab, you can see the trading performance for long
and short trades. In this case, I notice that the long trades vastly outperform the
short trades.
I am not so happy with the picture of returns as the last few years seem to be no
longer profitable and the drawdown is quite large. Might this be attributed to
trading short. Let’s look at this in more detail. The picture below is with an
initial capital of 100000, and an order size of 100000.
This picture is if we use 100% of our capital. If we for instance make a
profitable trade of 1000 dollars we will now trade with 101000 dollars. This is
what I would like to be doing with this strategy. Let’s have a look at the return.
We see a change when we switch to the 100% trading, and see that the last
several hundred trades would not have been profitable, furthermore we
experienced a heavy drawdown. in the performance summary tab, we see that
the short order would have lost us a lot of money. So let’s stop taking the short
trades and analyze our returns. You will need to change the code to do this. In
the example below I comment line 24 with // so that no short trades are being
taken and add line 21. We use strategy.close so that the long trade will be closed.
Between the brackets, we specify which order to close and when to close it.
The drawdown decreased greatly and the strategy seems to perform slightly
better over the last few trades.
With the 100% order size, this is even more apparent. Although the last hundred
trades might not be profitable, I think we have been able to keep this strategy
from losing.
Tweak the parameters, but don’t get to specific
Some strategies will benefit massively from changing the parameter inputs,
however for this strategy, the moving average at 5 is the most profitable and
reliable one when we look at the overall performance picture, drawdown, and
number of trades.
Improving a strategy with a simple conditional statement.
200 day moving average
Let’s try to improve the return of this strategy by adding a conditional statement.
Since we only take long trades it would make sense to only trade in a trending
market. Overall traders assume the markets to be in an uptrend when the price is
higher than the 200 day moving average. So let’s implement this into our code.
First, save this script with another name and change the title in line 2.
I create another variable called moving_average-trend. And I store the values of
the 200 day moving average, just as we did before for the 5 day moving average.
Moreover, I would like to plot this 200 day moving average to the chart, so that I
can see whether the strategy takes the trades as I would expect.
Next, we implement the conditional statement. We do this by using an IF
statement. IF the close price is higher than the 200 day moving average we can
take a trade. To make sure we only enter a trade if the condition is true, we need
to indent line 22. For the close of the long trade however, we would like to get
out of the position even if the price dropped below the 200 day moving average.
That is why we don’t indent line 23.
Now add this strategy to the chart. Now analyze the returns. Did you improve
upon the strategy? If you look at the drawdown, the new strategy performs
better. You improved upon a drawdown of roughly 12% to 8%. Which is good.
If we now compare the strategy when using 100% of our capital. You can see
that the change in drawdown is immense. You changed a drawdown of 37% to a
drawdown of 12%. Furthermore, the picture of the return is smooth and
consistent, which is something I like to see.
Bollinger bands
Overall traders assume the markets to range between the Bollinger bands when
the market is not in a trend. So it would seem that I can improve upon the
strategy when only taking long trades when the market is between the Bollinger
bands. First, save this script with another name and change the title in line 2.
I create several other lines. First I create a variable in line 15 that specifies the
length of the Bollinger bands. Then I specify the source of the price, in this case,
we use the closing price. Next, I specify the multiplier, I want to use a Bollinger
band of 2 deviations, so the multiplier is set to 2. You might recall that the
Bollinger bands are created by adding or subtracting standard deviations from
the moving average, so I create a moving average for the Bollinger bands. In line
19 I create the deviations variable by letting Tradingview calculate the standard
deviation of the closing prices for the chosen period and I multiply this by the
multiplier which is 2. In lines 20 and 21 I create the upper and lower Bollinger
bands simply by adding or subtracting the deviation variable from the moving
average. As you have seen before it is useful to plot the indicators that you use in
your trading strategy. I give the Bollinger bands a blue color. Now I only need to
specify when to take a trade. I only want to take trades IF the price is between
the bands. So the close must be lower than the upper band and higher than the
lower band.
Now select add to the chart. And look at the performance. It does look pretty
good.
Now let’s look at the performance when trading with 100%. This looks pretty
good as well. Although the drawdown is higher than with the moving average
condition, 21.5% vs 12.8% the return increased 359% vs 134%. In my opinion,
the increase in drawdown is more than justified, and overall this strategy looks
promising. This strategy would return 22% each year.
Checklist
As you have just seen a strategy can be improved easily. Now let’s use the
checklist to evaluate the performance. Does it hold up to the tests?
A positive return
The return is positive, which is a good start.
The picture
Does the strategy perform well until the current date?
Yes, it does, it even performed better than in previous years.
Is the strategy able to recover from losses?
Yes, the strategy is able to recover. Close to the 200 and 400 trades, the strategy
suffers some losses, but it is able to recover and keep making money.
Is the strategy able to perform well when the security is in decline?
When you look at the blue line you can see that the strategy is able to perform
well even when the security is in decline, which occurs around the 200, 400, and
500 trades mark.
Is the return of the strategy distributed smoothly?
The return of this strategy is pretty smooth, sometimes the returns are a little bit
steeper and sometimes more flat, but overall you can see a smooth increase.
Is the strategy’s return positive for specific samples of your data-set?
Year
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
Return %
14.2
8.93
14.2
2.78
7.39
22.47
9.55
5.68
12.33
13.4
1.85
-2.31
11.66
15.38
-15.47
17.53
2020 until august 23.04
Although not each year is positive, in my opinion, the return for each year is
pretty consistent. The only thing that worries me is the return in 2018. The other
years are good. If the return in 2018 would have been rough -5 to -7% I would
be very comfortable in trading this strategy. But now I’m not so sure.
Small drawdown
The drawdown is 21.5%, when compared to the return of this strategy is worth it
in my opinion. Especially when we compare this to the simple buy and hold
drawdown and yearly return.
Leverage
The drawdown is already quite much, so I would not be comfortable trading this
with leverage.
Average trade size
The average trade size of 0.62% is more than enough to be profitable when
taking the spread and fees into account.
Market edge
Return with equal capital and order size, until august 2020. Which is 199 months
=160%, which is 9.648% on average.
Annual Risk free rate of return = 2
n = 581/199 =35 trades on average each year
ơp = (9.648-2)/0.176 =43.45455
Z = (9.648-0)/(43.35455/√35) = 1.316
So I am not confident that this strategy will outperform the market. Relatively
few trades are taken, which is very important for estimating the ability to
outperform the market.
Chapter 16: Proof of what is possible and tips of a 2year automated trading journey.
As described previously, I have multiple strategies running. I will show 2 of my
smaller accounts as I run these strategies with more leverage and thus higher
returns. These returns might be surprising to you and I hope they inspire you to
create your system even though you might have a lot of capital.
This is one of the strategies I have deployed. I started this strategy on 1
November 2019 with $1400. By February 24 2020 I had a P&L of $1624. I have
distributed the returns of this strategy across my other strategies and decreased
leverage. The results afterward are thus no longer an indication of the return. I
still have this strategy running and it is performing well although not at this
level.
Currently, I also run another strategy with a really small account. I started the
account on April 28 2020 with $168 which is just enough to buy 1 unit of
spx500usd with a maximum leverage of 20 times. The amount required to buy 1
unit is $168. I am curious how fast I can turn this account into a $1000 account. I
will share the results of this strategy on my website moneytreesolutions.nl. At
the current date, September 4, 2020, the account P&L is $187. I have thus made
a return of 111% in approximately 4 months. I am curious how this account will
grow and will share the results at moneytreesolutions.nl
Chapter 17: Backtesting and trade automation
software compared
Several software packages provide backtests for trading strategies. I’ve tested
many different software providers. Such as MetaTrader, Quantopian, Backtrader,
and Tradingview. My favorite is Tradingview. Tradingview offers a backtesting
software that is simple and one creates a strategy in less than a few minutes. The
other software packages are much more difficult and the learning curve is
enormously steep. Even if you’ve mastered one of these other software packages
Tradingview is the go-to software. Because Tradingview shows all your trades in
a chart, so you can easily analyze when your strategy performed well and when
it didn’t. In addition to this, the backtest performs instantaneously and you don’t
need to wait for the backtest to complete. For the inexperienced users, I might
seem a bit impatient, but this can take up a lot of time with backtesting on other
platforms taking anywhere from 3 to 5 minutes. Moreover, Tradingview offers
much more data than the other software packages. When we for instance
compare Metatrader and Tradingview data on a 4-hour timeframe on the
SPX500USD. Tradingview offers 5 years of data, while Metatrader offers only 2
years of data. The amount of data is crucial for developing profitable strategies.
Moreover, Tradingview also charts the trades that would have been taken.
Allowing you to figure out under which conditions your strategy works and
when not. This is very useful for developing strategies and I’ve generated a lot
of new strategies based on these insights.
Chapter 18: Conclusion
In this book, you have followed a masterclass in automated trading. Be sure to
go over this book someday, because you will probably discover new things you
might have missed the first time. By now you can confidently start your
automated trading journey, and be well on your way to creating your financial
future. You have learned how to create strategies, how to test these strategies
against years of data, and ultimately you have automated them. Moreover, the
skills you have developed will benefit all your trading efforts as you have also
discovered some new things about the market. I sincerely thank you for reading
this book and I hope this will be the start of a stream of passive income.
Allowing you to spend your time on doing the things you love, instead of
spending hours in front of your computer, and still earn money trading. I hope
that I’ve been able to give you not only all the knowledge to get started, but also
that I’ve been able to inspire you that you, yes you, can beat the smart boys at
Wallstreet!. Remember that the best strategies are simple by design and start
with a manageable goal to be profitable.
May we meet again,
Regards,
Jason Carson
Chapter 19: Free scripts
Dear reader in this book you have discovered many strategy’s. I hope you liked
the book. Would you be willing to leave a review?
I will share all the scripts that you have discovered with you at
www.moneytreesolutions.nl/automatedtrading. I will share two of them right
now. You can easily copy the sourcecode and paste it in the Tradingview pine
editor and then save it. I've done this so that you easily use the strategies that you
saw in an Automated Trading Masterclass.
Each script starts at //@version. So Start your copy there.
Moving average mean reversion
//@version=4
strategy("<5ma_buy",initial_capital = 100000, currency = 'EUR',
default_qty_type = strategy.cash, default_qty_value=100000, overlay=true,
calc_on_order_fills=false, commission_type= strategy.commission.percent,
commission_value= 0.0)
//input for time//
FromMonth = input(defval = 1, title = "From Month", minval = 1)
FromDay = input(defval = 1, title = "From Day", minval = 1)
FromYear = input(defval = 2000, title = "From Year", minval = 1800)
ToMonth = input(defval = 1, title = "To Month", minval = 1)
ToDay = input(defval = 1, title = "To Day", minval = 1)
ToYear = input(defval = 9999, title = "To Year", minval = 1800)
moving_average = sma(close, input(defval=5, title = "ma_length"))
plot(moving_average, color = color.lime)
long= close< moving_average
short = close>moving_average
//long trades
strategy.entry("long", strategy.long, comment="long", when = (long and time >
timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59)))
//strategy.close("long", when = (short and time > timestamp(FromYear,
FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth,
ToDay, 23, 59)))
//short trades
strategy.entry("short", strategy.short, comment="short", when = (short and time
> timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59)))
//strategy.close("short", when = (long and time > timestamp(FromYear,
FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth,
ToDay, 23, 59)))
Moving average mean reversion between BB
//@version=4
strategy("<5ma_buy_bb",initial_capital = 100000, currency = 'EUR',
default_qty_type = strategy.cash, default_qty_value=100000, overlay=true,
calc_on_order_fills=false, commission_type= strategy.commission.percent,
commission_value= 0.0)
//input for time//
FromMonth = input(defval = 1, title = "From Month", minval = 1)
FromDay = input(defval = 1, title = "From Day", minval = 1)
FromYear = input(defval = 2000, title = "From Year", minval = 1800)
ToMonth = input(defval = 1, title = "To Month", minval = 1)
ToDay = input(defval = 1, title = "To Day", minval = 1)
ToYear = input(defval = 9999, title = "To Year", minval = 1800)
moving_average = sma(close, input(defval=5, title = "ma_length"))
plot(moving_average, color = color.lime)
length_bb = input(50, minval=1)
src_bb = input(close, title="Source_bb")
mult_bb = input(2.0, minval=0.001, maxval=50)
moving_average_bb = sma(src_bb, length_bb)
dev = mult_bb * stdev(src_bb, length_bb)
upper = moving_average_bb + dev
lower = moving_average_bb - dev
plot(upper, color = color.blue)
plot(lower, color = color.blue)
long= close< moving_average
short = close>moving_average
if close<upper and close>lower
strategy.entry("long", strategy.long, comment="long", when = long and (time >
timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59)))
strategy.close("long", when = short and (time > timestamp(FromYear,
FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth,
ToDay, 23, 59)))
//if close<moving_average_trend
// strategy.entry("short", strategy.short, comment="short", when = short and
(time > timestamp(FromYear, FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59)))
//strategy.close("short", when = long and (time > timestamp(FromYear,
FromMonth, FromDay, 00, 00)) and (time < timestamp(ToYear, ToMonth,
ToDay, 23, 59)))
Download