100% found this document useful (1 vote)
203 views63 pages

Algorithmic Trading For Beginners - Automated Analysis & - ,,, - 2019 - Anna's Archive

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
203 views63 pages

Algorithmic Trading For Beginners - Automated Analysis & - ,,, - 2019 - Anna's Archive

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

1

Volume

TRADINGVIEW
Automated Analysis & Strategies

Algorithmic Trading
For Beginners
AUTOMATED ANALYSIS & STRATEGIES

Algorithmic Trading For Beginners

Algorithmic Trading For Beginners (December 19)


Copyright  Algorithmic Flow
Piazza della Rinascita, 8 (Piazza Salotto)
65122 Pescara, ITALY
https://fiverr.com/piazzasalotto

All rights are reserved by law and in accordance with international conventions.

Bibliography: GUIDA ALL’ANALISI TECNICA di Maurizio Mazziero - HOEPLI


Table of Contents
Introduction .............................................................................. 1

TradingView ............................................................................. 3

Let’s start ................................................................................. 6

1) Create an account in TradingView .............................................. 6

2) Set the filters in the screener ...................................................... 7

3) Add the study based on the algorithm....................................... 11

4) Add the strategy based on the algorithm .................................. 15

Interpretation .......................................................................... 20

Stochastic ..................................................................................... 22

Relative Strength Index (RSI) ....................................................... 25

Bollinger Bands (BB) ..................................................................... 27

Strategy Tester (backtesting results) ............................................ 33

How to make your own Imposed Rules ......................................... 35

Algorithms .............................................................................. 37

Stochastic Study ........................................................................... 37

1- Stochastic Slow Strategy .......................................................... 38

2- Stochastic Slow Strategy (Only Buy) ........................................ 39

3- Stochastic Slow Strategy (Stop Loss, Take Profit) .................... 40

Relative Strength Index Study (RSI) ............................................. 42

1- Relative Strength Index Strategy .............................................. 43


2- Relative Strength Index Strategy (Only Buy) ............................ 44

3- Relative Strength Index Strategy (Stop Loss, Take Profit) ........ 45

1- Bollinger Bands Study-Strategy ................................................ 47

2- Bollinger Bands Study-Strategy (Only Buy) .............................. 48

3- Bollinger Bands Study-Strategy (Stop Loss, Take Profit).......... 50

Conclusions ........................................................................... 53

Legal Disclaimer..................................................................... 58
1
Chapter
A L G O R I T H M I C T R A D I N G

Introduction
The greatest gift you can give someone is the
power to be successful. Giving people the
opportunity to struggle rather than giving them
the things they are struggling for will make them
stronger. Ray Dalio

T his is an easy-to-understand guide to start the trading using the power


of algorithms. Following the steps in this reading, you will be able,
at the end of this smart guide, to identify the best moment to buy
long or to sell short a financial instrument (stock, currency, crypto currency,
commodity, etc.) even if you are near to the 0 of knowledge about the
trading online or the financial world in general. Of course, if you’re
entering for the first time in this fantastic world that is the finance, and
more specifically in investing in financial markets through online trading,
we strongly recommend you to learn as best as you can the main
processes that make up a responsible investment. Therefore, below, you
will find a small table summarizing the basic knowledge you should have
before starting to invest your savings.

K N O W L E D G E F O R A R E S P O N S I B L E I N V E S T I N G

 Technical Analysis: Price Charts, Indicators, Oscillators.


 Fundamental Analysis: Company Analysis, Industry Analysis, Macroeconomic
Conditions, Future Profit Outlook.
 Latest financial, market & economic news.

1
A L G O R I T H M I C T R A D I N G

Note

At the end of this guide you can find a list of links where you
can get, for free, all the contents mentioned in the
summarizing table above.

Please consider that we do not provide the magic wand and we


strongly suggest you to stay away from those who promise easy profits
doing almost nothing. The land of dreams simply does not exist. What
exists instead is the positive result obtained with commitment,
constancy and respect for the imposed rules. What we provide is the
statistical advantage that, thanks to the number of positive
operations obtained with the backtesting of the algorithm on a given
financial instrument, gives you the possibility to structure a winning
strategy. This is how the big traders operate to get steady and solid
gains, earnings that are partly reinvested in trading, succeeding in
creating an asset that grows and acquires value over time, just like an
healthy and well-managed company.

Enjoy the reading.

2
A L G O R I T H M I C T R A D I N G

2
Chapter

TradingView
One coincidence is just a coincidence, two
coincidences are a clue, three coincidences are a
proof. Agatha Christie

B efore long you will be able to trade financial instruments through


the signals that the algorithms, included in this guide, will show
you on your screen. To exploit the potential of the algorithms
without having to install complicated and expensive softwares, we will use
a simple, powerful and free* platform. TradingView is the innovative
financial platform created by Multicharts for the web browsing market, in
order to bring the tools that were once granted only to institutional and
investment funds, free of charge to a much wider public.
*it also includes paid plans but for our purpose the free version is more than enough.

FIGURE 2.1 T r a d i n g V i e w . Homepage Screenshot.

3
A L G O R I T H M I C T R A D I N G

According to the latest data, the TradingView community now has more
than 3 million active users every month. In fact, the peculiarity of this
platform is that it combines graphics with a social component, in which
users share their trading ideas to compare themselves with others and
improve together. To create even more harmony, there are public chats,
where users exchange opinions in real time on the latest market
movements. You will enjoy to learn how to take advantage of this big
community that shares ideas, studies and strategies.

FIGURE 2.2 T r a d i n g V i e w . Community infobox.

Furthermore TradingView has designed its own scripting language called


Pine Script. It allows users to create customized indicators and oscillators
and run them on TradingView servers. It is exactly with the Pine Script
language that we’ve focused the development of our indicators and
oscillators. Included in this guide you will find both study and strategy
pine’s script based on some of most used oscillators and developed
through functions and algorithms. Pine studies also contain calculations
and may plot information on charts, but cannot be used in backtesting.
Pine strategies are used to run backtests. The backtest is the best part of
the algorithm’s power because we can immediately understand how many
times and to what extent a particular strategy has worked in the past for
the financial instrument under consideration. Based on the percentage
ratio between winning and losing (so the percentage ratio between it worked
and it didn’t worked on a specific financial instrument with the

4
A L G O R I T H M I C T R A D I N G

algorithmic indicator or oscillator used), we are able to get the statistical


advantage so precious to the big financial players.

FIGURE 2.1 – 2.2 T r a d i n g V i e w . Chart with a Study & Strategy in Action.

5
A L G O R I T H M I C T R A D I N G

3
Chapter

Let’s start
Past performance is the best predictor of success.
James Harris Simons

H ere we go. We will create an account in TradingView (1), set the


filters in the screener (2), add the study based on the algorithm
(3) and add the strategy based on the algorithm (4).

1) Create an account in TradingView


First of all we need to create an account in TradingView. Open an
account in TradingView is totally free and take just a few minutes.
Go on https://tradingview.com/ and click on JOIN FOR FREE in the
top right corner.

FIGURE 3.1 T r a d i n g V i e w . Registration process, click on JOIN FOR FREE .

6
A L G O R I T H M I C T R A D I N G

Sign up with one of your social account OR insert the requested


information (Username, Email, Password).

FIGURE 3.2 T r a d i n g V i e w . Registration process, social account OR requested information .

After the activation, log in with your access data.

2) Set the filters in the screener


One of the most important part of a winning strategy will be the right
setting of the filters in the screener page. This process is important for
two main reasons:
1. Thanks to the large number of filters that you will find (based on
Descriptive, Fundamental and Technical information), you can filter
your researches and go directly to the scope of your idea (e.g. if you
want to entry long in a public company you can avoid including in
your quantitative analysis all those companies which their P/E ratio,
Price to Earnings Ratio, is more than 10 years. This simple filter will
considerably reduce the pool of your research, thus providing a clean
and ready to use result).

2. You can set filters in the way that, upon the occurrence of one or
more conditions, which are the same of the algorithmic indicators or
oscillators, you will receive an alert box (on the screen of the
platform but also via email once set) which will warn you that a
financial instrument or multiple financial instruments are ready to be
analyzed and may open a position on them (e.g. filter results based
on the occurrence of important conditions, from the point of view

7
A L G O R I T H M I C T R A D I N G

of technical analysis, such as crossing multi-period moving averages


or a considerable exit of the price from the Bollinger Bands).

With this guide we propose also some filters that are suggested to use.
Those filters are indicated for the three oscillators that are included in this
beginner guide. The oscillators proposed, which are the most used from
technical analysis players, are the Slow Stochastic, the Relative Strength
Index (RSI) and the Bollinger Bands (BB).
Go on https://tradingview.com/screener/ OR click on “Screener” on
the top menu and then click on “Filters”, the blue button on the top right.

FIGURE 3.3 T r a d i n g V i e w . Setting the filters in the screener page.

You will see that two filters and some sub-filters are already set in default.
We can click on the first filter “Symbol Type” and leave ticked only
Common Stock, because to start we prefer to analyze the common
stocks. Then we can pass to the second filter already set in default,
Exchange. Here we can leave all the exchanges already ticked as sub-filters
(NYSE ARCA, NASDAQ, NYSE).

8
A L G O R I T H M I C T R A D I N G

FIGURE 3.4 T r a d i n g V i e w . Setting the filters in the screener and modification of the default
filters.

Now we can add the following filters:


1. Last: Above - Value - (5) - Many brokers apply commissions also
based on the number of stocks to buy or sell. With a value above
5$/share we avoid to pay too much commission for a single
position. With the experience, and after having found your broker of
reference, you will decide whether this filter is useful for you or not.

2. Market Capitalization: (50M) (>200B) - With this filter we exclude


from our analysis companies that have a capitalization that make
them too vulnerable and dangerous and therefore unattractive to
trade.

3. Average Volume (30 day): (50k) (>50M) - With this filter we make
sure that the stocks taken into consideration are actively traded with
high average volumes, thus excluding all those stocks that are in
short supply of liquidity in the last 30 days.

9
A L G O R I T H M I C T R A D I N G

FIGURE 3.5 T r a d i n g V i e w . Setting more filters in the screener box.

At this point you can close the pop-up filter box (save it to have these
filters always active) and as you will see, on the top left under
TICKER, a consistent number of matches based on your new set of
filters will be indicated.

FIGURE 3.6 T r a d i n g V i e w . Under TICKER all the matches based on the set of the filters will
be indicated.

Last suggested setting to do is to place the financial products in order of


greater quantity of volumes traded in the last (or current) session. To do
that just click on “VOL” from the horizontal menu of the list. In this way
we can take advantage from the broader movements of the most traded
financial products in the current time.

10
A L G O R I T H M I C T R A D I N G

FIGURE 3.7 TradingView. Place the financial products in orde r of greater quantity of
volumes traded in the last (or current) session .

Note

Compare the volumes (VOL) and the market capitalization


(MKT CAP) with the price of the financial product (LAST) to
be sure that the volumes are proportionally consistent
compared to the capitalization of the financial securities in
question.

3) Add the study based on the algorithm


Now we can proceed in adding one of our included study oscillators in
the chart of a financial instrument. A study oscillator (or a study indicator)
is the visual part of a strategy. With the study it is possible to see, in a
chart, why the strategy gives the buying or selling signal (or even the signal
to close a position already opened).
So, right click on the top stock you can see in the list on your screen and
then click on “Open stock name Chart...”.

11
A L G O R I T H M I C T R A D I N G

FIGURE 3.8 T r a d i n g V i e w . Click on “Open PCG Chart” to open it in a new page.

The chart will be opened in a new page. From here click on the “Pine
Editor” tab situated in the bottom left part of the page.

FIGURE 3.9 T r a d i n g V i e w . Click on “Pine Editor” to add the code.

Now we can copy/paste one of our study script included in this guide. We
will add the Stochastic study oscillator that can be found in the chapter 5,
Algorithms, STOCHASTIC STUDY.

12
A L G O R I T H M I C T R A D I N G

FIGURE 3.10 T r a d i n g V i e w . Copy/paste the provided code.

We can click on “Save” tab on the top right of the Pine Script box. A
pop-up box will ask you to confirm the name of your script, just click on
the blue button “Save”.

13
A L G O R I T H M I C T R A D I N G

FIGURE 3.11 – 3.12 T r a d i n g V i e w . Save the script with the name set by default.

Note

You can find all your saved study scripts in Indicators -->
My Scripts from the top menu in the chart page.
If you want more study scripts you can find them in
Indicators --> Built-ins and in Indicators --> Public
Library. Some of them are completely free, to get some
others you have to pay for.

Last step to see the oscillator in the chart is by clicking on “Add to


Chart” tab in the top right of the Pine Script box.

14
A L G O R I T H M I C T R A D I N G

FIGURE 3.13 T r a d i n g V i e w . Add the script to the chart clicking on Add to Chart tab.

Close the Pine Editor box by clicking again on the “Pine Editor” tab
and you will see the oscillator at work.

FIGURE 3.14 T r a d i n g V i e w . The oscillator (the study) as will be shown after adding it to the
chart.

For the understanding of the scripts we’ve made a special section


where we describe the function and the purpose of the three
oscillators included in this guide. You can find it just after point 4.

4) Add the strategy based on the algorithm


Finally we’re ready to add the core of the guide, the algorithm that
provides us the signals to trade. The strategy is the automatic system

15
A L G O R I T H M I C T R A D I N G

which is not limited to giving us the signals but also tells us how much
and to what extent that strategy worked in the past. Since the American
billionaire, mathematician and hedge fund manager, James Harris
Simons, a man that built his own fortune thanks to backtests and
algorithms, said that past performance is the best predictor of success, you will
easily understand what kind of power you have in your hands if you use a
solid strategy associated to a good money management and perfect
respect of the imposed rules. In this way you will gain the most important
attitude that every trader, professional or not, obtains only after years and
years of practice, many of them at a loss, the capacity to leave the
emotions away from your trading decisions, with particular reference to
the moment of entry into a financial instrument. So, let's go with this last
step.
From the same page click again on the “Pine Editor” tab situated in the
bottom left part of the page and then click on “New▼ --> Blank strategy
script” situated in the horizontal menu of the Pine Editor box.

FIGURE 3.15 TradingView. Click on New▼ and then Blank strategy script to add a new
strategy script.

Now, as we did for the study, we can copy/paste one of our strategy script
included in this guide. We will add the Stochastic strategy indicator that
can be found in the chapter 5, Algorithms, STOCHASTIC SLOW
STRAGEY.

16
A L G O R I T H M I C T R A D I N G

Note

You will find also two more strategies of the same oscillator
but with different settings. We will consider this part in the
chapter 4, of this guide.

We can click on “Save” tab on the top right of the Pine Script box. A
pop-up box will ask you to confirm the name of your script, just click on
the blue button “Save”.

FIGURE 3.15 – 3.16 TradingView. Save the script. Save the script with the name set by
default.

17
A L G O R I T H M I C T R A D I N G

Note

You can find all your saved strategy scripts in Indicators -->
My Scripts from the top menu in the chart page.
If you want more strategy scripts you can find them in
Indicators --> Built-ins and in Indicators --> Public
Library. Some of them are completely free, to get some
others you have to pay for.

To add our indicator in the chart just click on “Add to Chart” tab in the
top right of the Pine Script box. After a few seconds you will see the
strategy in the screen and the Strategy Tester tab will be opened with the
results of the backtest.

Note

If you see No data or the percentages look like too low do not
worry, in the next chapter, Interpretation, you will find more
settings to do to get the strategy more useful to the scope.

18
A L G O R I T H M I C T R A D I N G

FIGURE 3.17 – 3.18 T r a d i n g V i e w .


Add the script to the chart clicking on Add to Chart tab.
In the Strategy Tester tab find the results of the backtest .

19
A L G O R I T H M I C T R A D I N G

4
Chapter

Interpretation
Rule No.1: Never lose money. Rule No.2: Never
forget rule No.1. Warren Buffett

I n this section we are going to briefly analyze how to interpret the


three oscillators included in this guide, the possible various methods
to set the strategies in the way to find the most profitable one and
how to read the results produced by the algorithms. But, before all, we
need to describe which type of settings are possible to manage by default
from the platform and what is their meaning.
Click on “Settings” from the strategy in the chart to open a pop-up box.

20
A L G O R I T H M I C T R A D I N G

FIGURE 4.1 – 4.2 TradingView. Clicking on Settings from the strategy in the chart , it is
possible to modify the strategy rules to set the backtesting in the most profitable way as
possible.

In the Inputs tab we can find the parameters of the algorithm used. In our
case, for the Stochastic Slow Strategy script that we are using, we can find,
from the top: Length, OverBought, OverSold and then all the settings for
the Backtest Time Range (FROM: Month, Day Year - TO: Month, Day,
Year). In these last parameters it is possible to change the reference period
for backtesting.

FIGURE 4.3 T r a d i n g V i e w . Properties tab settings view .

21
A L G O R I T H M I C T R A D I N G

In the Properties tab we find:


Initial Capital - argument that sets the strategy’s starting funds.
Base Currency - argument that specifies the account currency.
Order Size - argument that specifies the default order size.
Pyramiding - argument that specifies how many entries are allowed in
the same direction.
Commission - argument that specifies the commission cost for each
order.
For the other possible default settings, in order to keep this guide less
complicated as possible, we’ve preferred to redirect to the official page of
the strategies of the platform where, with examples, the more complex
and less used* settings are explained.
*less used at least in this first approach to the platform.

Stochastic
STUDY (or Indicator in TradingView)

Definition: The Stochastic is an oscillator encoded by George Lane


whose value depends on the position of the most recent closure to a
maximum and to a minimum of quotes within the observation time
window. Typically, in a trend with rising prices, the Stochastic will tend to
reach values close to the maximum oscillation limit (100) and, on the
contrary, in the presence of falling prices it will tend to approach the
minimum values (0). The extreme zones are indicated by the two
horizontal lines and correspond to levels 80 (red line) and 20 (green line).
The oscillator consists of two lines called %K (blue line) and %D (red
line). The stochastic is an anticipatory oscillator, as it allows the early
identification of possible trend reversals.
How to use:

 BUY LONG when the %K line and %D line cross (the %K


line crosses the %D line from the bottom upwards) in the zone
of oversold (under the horizontal line 20, green).

22
A L G O R I T H M I C T R A D I N G

FIGURE 4.4 T r a d i n g V i e w .
By default, the signal of BUY LONG always come the day
after the condition is completed.

 CLOSE or SELL SHORT when the %K and %D cross (the


%K line crosses the line %D from the top downwards) in the
overbought zone (above the horizontal line 80, red).

FIGURE 4.5 T r a d i n g V i e w .
By default, the signal of CLOSE or SELL SHORT always
come the day after the condition is completed.

STRATEGY

In this guide is included a strategy based on the Stochastic oscillator rules


that splits into three different versions. What differentiates the three
versions are the possible settings to do in order to manage a different
approach to trading.

23
A L G O R I T H M I C T R A D I N G

1- Stochastic Slow Strategy.


Features: Signal to BUY LONG and SELL SHORT. The algorithm
will tell you BUY LONG when the lines cross in the oversold zone
and SELL SHORT when the lines cross in the overbought zone.
Additional settings available: Backtest Range.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
2- Stochastic Slow Strategy (Only Buy).
Features: Signal to BUY LONG and CLOSE POSITION
(LONG). No SELL SHORT signal will be provided. The
algorithm will tell you BUY LONG when the lines cross in the
oversold zone and CLOSE POSITION when the lines cross in the
overbought zone.
Additional settings available: Backtest Range.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
3- Stochastic Slow Strategy (Stop Loss, Take Profit).
Features: Signal to BUY LONG, SELL SHORT, CLOSE
POSITION (LONG, SHORT). The algorithm will tell you BUY
LONG when the lines cross in the oversold zone and SELL
SHORT when the lines cross in the overbought zone. When the
price reaches your imposed limits (Stop Loss, Take Profit), any
opened position will be closed.
Additional settings available: Backtest Range, Stop Loss Percentage,
Take Profit Percentage.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size), Stop Loss
Percentage (10), Take Profit Percentage (10).

24
A L G O R I T H M I C T R A D I N G

Relative Strength Index (RSI)


STUDY (or Indicator in TradingView)

Definition: The Relative Strength Index (RSI) is an oscillator designed by


Walles Wilder that measures the relative strength of bullish measures
compared to the bearish ones. RSI measures the driving force of the
analyzed stock. The oscillator moves positively in the bullish phases and
negatively in the bearish phases. This trend is due to the fact that, within a
time window, in the bullish phases, the positions will be greater
numerically and of greater intensity in terms of variation with respect to
the negative ones; similarly, in the bearish phases, the negative measures
will be greater numerically and of greater intensity in terms of variation
than the positive ones. The two horizontal lines delimit the extreme zones
of overbought (70, red line) and oversold (30, green line).
How to use:

 BUY LONG when the oscillator (blue line) crosses the


oversold line from the bottom upwards (green line, 30).

FIGURE 4.6 T r a d i n g V i e w .
By default, the signal of BUY LONG always come the day
after the condition is completed.

 CLOSE or SELL SHORT when the oscillator (blue line)


crosses the overbought line (red line, 70) from top to
downwards.

25
A L G O R I T H M I C T R A D I N G

FIGURE 4.7 T r a d i n g V i e w .
By default, the signal of CLOSE or SELL SHORT always
come the day after the condition is completed .

STRATEGY

For the strategy based on the RSI rules, there are also three different
versions included.
1- RSI Strategy.
Features: Signal to BUY LONG and SELL SHORT. The algorithm
will tell you BUY LONG when the blue line crosses the oversold
line from the bottom upwards and SELL SHORT when the blue
line crosses the overbought line from top to downwards.
Additional settings available: Backtest Range.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
2- RSI Strategy (Only Buy).
Features: Signal to BUY LONG and CLOSE POSITION
(LONG). No SELL SHORT signal will be provided. The
algorithm will tell you BUY LONG when the blue line crosses the
oversold line from the bottom upwards and CLOSE POSITION
when the blue line crosses the overbought line from top to
downwards.
Additional settings available: Backtest Range.

26
A L G O R I T H M I C T R A D I N G

Default settings: Backtest Range (Beginning of the year 2019 to the


present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
3- RSI Strategy (Stop Loss, Take Profit).
Features: Signal to BUY LONG, SELL SHORT, CLOSE
POSITION (LONG, SHORT). The algorithm will tell you BUY
LONG when the blue line crosses the oversold line from the
bottom upwards and SELL SHORT when the blue line crosses the
overbought line from top to downwards. When the price reaches
your imposed limits (Stop Loss, Take Profit), any opened position
will be closed.
Additional settings available: Backtest Range, Stop Loss Percentage,
Take Profit Percentage.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size), Stop Loss
Percentage (10), Take Profit Percentage (10).

Bollinger Bands (BB)


STUDY (or Indicator in TradingView)

Definition: The Bands conceived by John Bollinger are a dynamic


channel that accompanies the price movement, whose amplitude adapts
automatically according to the volatility of the prices. They are useful in
forecasting trend reversals, as well as in developing new directional
movements after a period of low volatility. The Bollinger Bands are
composed of a median line and two other lines at the ends, which seem to
build levees to price fluctuations. The Bands are born from the intent of
John Bollinger to create a channel capable of describing the movement of
prices and adapting to changes of volatility, with a narrowing in periods of
low volatility and an automatic expansion in periods of increasing
volatility, without any human settings.

27
A L G O R I T H M I C T R A D I N G

How to use:

 BUY LONG when, following a closure outside the lower


Band (green Band), there will be a subsequent internal closure
to the same Band.

FIGURE 4.8 T r a d i n g V i e w .
By default, the signal of BUY LONG always come the day
after the condition is completed .

 CLOSE or SELL SHORT when, following a closure outside


the upper Band (red Band), there will be a subsequent internal
closure to the same Band.

FIGURE 4.9 T r a d i n g V i e w .
By default, the signal of CLOSE or SELL SHORT always
come the day after the condition is completed.

28
A L G O R I T H M I C T R A D I N G

STRATEGY

As for the others strategies included, you will find three different versions
based on the Bollinger Bands strategy.
1- Bollinger Bands Study-Strategy.
Features: Signal to BUY LONG and SELL SHORT. The algorithm
will tell you BUY LONG when, following a closure outside the
lower Band there will be a subsequent internal closure to the same
Band and SELL SHORT when, following a closure outside the
upper Band, there will be a subsequent internal closure to the same
Band.
Additional settings available: Backtest Range.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
2- Bollinger Bands Study-Strategy (Only Buy).
Features: Signal to BUY LONG and CLOSE POSITION
(LONG). No SELL SHORT signal will be provided. The
algorithm will tell you BUY LONG when, following a closure
outside the lower Band, there will be a subsequent internal closure
to the same Band and CLOSE POSITION when, following a
closure outside the upper Band, there will be a subsequent internal
closure to the same Band.
Additional settings available: Backtest Range.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size).
3- Bollinger Bands Study-Strategy (Stop Loss, Take Profit).
Features: Signal to BUY LONG, SELL SHORT, CLOSE
POSITION (LONG, SHORT). The algorithm will tell you BUY
LONG when, following a closure outside the lower Band there
will be a subsequent internal closure to the same Band and SELL

29
A L G O R I T H M I C T R A D I N G

SHORT when, following a closure outside the upper Band, there


will be a subsequent internal closure to the same Band. When the
price reaches your imposed limits (Stop Loss, Take Profit), any
opened position will be closed.
Additional settings available: Backtest Range, Stop Loss Percentage,
Take Profit Percentage.
Default settings: Backtest Range (Beginning of the year 2019 to the
present day), Initial Capital (USD 100,000), Order size (USD
10,000), Commission (0.3% of the Order size), Stop Loss
Percentage (10), Take Profit Percentage (10).

Notes for all strategies

If the strategy provides No data please expand the time range.


By default, the signals of BUY LONG, SELL SHORT or
CLOSE POSITION always come the day after the condition
is completed.
Do not open any new positions on all those days where the
company reports new earnings (red E at the bottom of the
TradingView chart).
This range of time, in general, is congruous for a short or
medium term investment. It is advisable to carry out other
backtests by expanding the range of time in consideration, to
have an overall idea of how the stock performed in the various
cyclical stock market scenarios.

After launching any strategy, the result will look like the following
screenshots.

30
A L G O R I T H M I C T R A D I N G

FIGURE 4.10 – 4.11 TradingView. In this example, the financial product under our
consideration, performed 100% Profitable with a 46.01% of Net Profit. The Max Drawdown
has been only 0.32%. The Buy & Hold Return ha s been 17.63%. The algorithm has
outperformed the stock performance. We used the Stochastic strategy.

31
A L G O R I T H M I C T R A D I N G

FIGURE 4.12 – 4.13 TradingView. In our example, the financial product under our
consideration, performed 100% Profitable with a 81.68% of Net Profit. The Max Drawdown
has been only 0.3%. The Buy & Hold Return ha s been 1.82%. The algorithm has largely
outperformed the stock performance . We used the RSI strategy.

32
A L G O R I T H M I C T R A D I N G

FIGURE 4.14 – 4.15 TradingView. In our example, the financial product under our
consideration, performed 100% Profitable with a 48.02% of Net Profit. The Max Drawdown
has been only 0.3%. The Buy & Hold Return ha s been 4.65%. The algorithm has largely
outperformed the stock performance. We used the Bollinger Bands strategy .

Strategy Tester (backtesting results)


In the Overview tab of the Strategy Tester you will see the following
information:
Net Profit: it is expressed as the net profit of the difference between
profits and losses of the strategy in the pre-established time. It is red when
negative.
Total Closed Trades: the number of closed positions managed by the
algorithm. Those positions determine the Net Profit.
Percent Profitable: it is the number of times that the algorithm has
provided the right input signal in percentage.
Profit Factor: the profit factor is defined as the gross profit divided by
the gross loss (including commissions) for the entire trading period. It is
red when negative.
Max Drawdown: it is a risk indicator of the financial instrument and it
represents the maximum loss accrued, in the analysis period, with respect
to the peak value recorded.

33
A L G O R I T H M I C T R A D I N G

Avg Trade: average of profit for each single trade expressed in


percentage. It is red when negative.
Avg # Bars in Trades: average of days (bars) in which the position
remained open.
In the Performance Summary tab there are, in more detail, all the
information shown in the Overview tab. In the List of Trades tab you can
find each single trade in detail.
The most important value to consider is the Percent Profitable. From
this data we start to consider all the rest in the context. If the percentage
of profitable is within the range of our imposed rules, we need to relate it
to the Net Profit value. The next consideration is to relate the Net Profit
with the Buy & Hold Return data that we can find in the Performance
Summary tab. If the Net Profit is greater than the Buy & Hold Return,
our algorithm worked in an excellent way since it performed better than
the title itself. In essence it has exploited the cycles of the trend.
Exploiting the cycles of a trend is the purpose of the three algorithms
considered in this guide. Algorithms that, if well exploited, give, with
explosive certainty, the statistical advantage that separates the winning
traders from the losing ones. If the relation of these first three factors are
within and congruous to our imposed rules, we can proceed with the
inclusion of a new important factor, the Max Drawdown. With this
element, we know the maximum correction and consequently we can
know the risk of maximum loss that can be suffered. Indirectly, by
relating this data to the Acceptable Risk pre-imposed in our rules, we
understand whether the transaction could fall within our risk parameters.
Only after analyzing all the factors reported in the backtesting, we can
have a clear picture of the risks and advantages in case we decide to open
a transaction on the financial instrument in question.
A smart suggestion about the consideration of the Percent
Profitable.
When can the percentage of profitable be considered satisfactory ?
To answer to this question we propose, just here below, an interesting
chart extrapolated from the 10-K report of The Goldman Sachs Group,
Inc. In this chart we have the Daily Net Revenues ($ in millions) in the x-
axis and the Number of Days in the y-axis. If we simply consider the

34
A L G O R I T H M I C T R A D I N G

number of days where they report a loss in comparison to of the days


where they make profits, we can observe that their percent of profitable is
87,65%. They do trading with the security of making a mistake almost
once every 9 operations. Those are the big players that we mentioned
many times in this guide. Our scope is to let you have the same statistical
advantage thanks to the algorithmic trading. We invite you to structure a
strategy based on the percentage of risk you’re willing to take for your
trading operations. Risk that must be managed with a calculated stop loss
limit. In this way you can contain the losses and make the most from all
those operations where you’re on the right side of the chart.

FIGURE 4.16 T h e above chart presents the frequency distribution of daily net revenues for
positions included in 2018. The Goldman Sachs Group, Inc.

How to make your own Imposed Rules


To structure the rules that will be our bible, namely all that points that
associated to our strategies indicate, like a GPS, the way to go, we need to
consider important aspects like all that techniques, more or less complex,
that make investments much more efficient, managing the capital and
reducing the risk of loss in result, in few words, the Money Management.
Who loses, in 90% of the cases, does not have a plan. The 70% of
beginner traders close the year with a loss precisely because they do not
have a Money Management plan.

35
A L G O R I T H M I C T R A D I N G

When we talk about Money Management, we refer both to real money


management, which identifies the capital to be used for each individual
transaction, and to trade (or risk) management that establishes specific
rules to manage the position.
Below we are given simple but important formulas to start setting up all
those rules that every successful trader will self impose so that, statistically,
at the end of the reference period, the winnings outweigh the losses. As
we saw above, when we talked about the algorithm strategies included in
the guide, as Default Settings we have:
Initial Capital --> USD 100,000
Stop Loss Percentage -->10%
Acceptable Risk -->1%
Our Max Loss will be:
Max Loss = Initial Capital * Acceptable Risk = 100,000 * 1% = USD
1,000
Our order size for a single position will be calculated as:
Order size = Max Loss / Stop Loss Percentage = 1,000 / 10% = 10,000
USD

Summary: the key points

- Determine the portion of capital to be used for trading.


- Calculate the maximum loss that must not exceed 1% of
the capital (this means that the cancellation of the capital
itself could come after 100 consecutive operations in loss,
without having any one in profit). This is a very
conservative strategy.
- Calculate the size of the position in monetary terms.

36
A L G O R I T H M I C T R A D I N G

5
Chapter

Algorithms
STOCHASTIC STUDY

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

study("@piazzasalotto - Stochastic Study", shorttitle =


"@piazzasalotto - Stoch", format=format.price,
precision=2)

//Parameter Setting
periodK = input(14, title="K", minval=1)
periodD = input(3, title="D", minval=1)
smoothK = input(3, title="Smooth", minval=1)

//Stochastic
k = sma(stoch(close, high, low, periodK), smoothK)
d = sma(k, periodD)

//Stochastic Plots
plot(k, title="%K", style=plot.style_line, linewidth=3,
color=color.blue, transp=0)
plot(d, title="%D", style=plot.style_line, linewidth=3,
color=color.red, transp=0)
h0 = plot(80, title="Upper Line",
style=hline.style_dashed, linewidth=2, color=color.red,
transp=0)
h1 = plot(20, title="Lower Line",
style=hline.style_dashed, linewidth=2,
color=color.green, transp=0)
fill(h0, h1, title="No Trade Zone", color=color.yellow,
transp=80)

37
A L G O R I T H M I C T R A D I N G

1- STOCHASTIC SLOW STRATEGY

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy(title = "@piazzasalotto - Stochastic Slow


Strategy", overlay=true, initial_capital=100000,
currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
length = input(14, minval=1)
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3

//Slow Stochastic
k = sma(stoch(close, high, low, length), smoothK)
d = sma(k, smoothD)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

38
A L G O R I T H M I C T R A D I N G

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//Long & Short Strategy


if (not na(k) and not na(d) and backTestPeriod())
if (crossover(k,d) and k < OverSold)
strategy.entry("StochLONG", strategy.long,
comment="StochLONG")
if (crossunder(k,d) and k > OverBought)
strategy.entry("StochSHORT", strategy.short,
comment="StochSHORT")

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

2- STOCHASTIC SLOW STRATEGY (Only Buy)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy(title = "@piazzasalotto - Stochastic Slow


Strategy (Only Buy)", overlay=true,
initial_capital=100000, currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
length = input(14, minval=1)
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3

//Slow Stochastic
k = sma(stoch(close, high, low, length), smoothK)
d = sma(k, smoothD)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)

39
A L G O R I T H M I C T R A D I N G

FromMonth = input(defval = 1, title = "Month",


minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//Long & Short Strategy


if (not na(k) and not na(d) and backTestPeriod())
if (crossover(k,d) and k < OverSold)
strategy.entry("StochLONG", strategy.long,
comment="StochLONG")
if (crossunder(k,d) and k > OverBought)
strategy.entry("StochCLOSE", strategy.short,
comment="StochCLOSE")

strategy.risk.allow_entry_in(strategy.direction.long)

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

3- STOCHASTIC SLOW STRATEGY (Stop Loss, Take


Profit)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy(title = "@piazzasalotto - Stochastic Slow


Strategy (Stop Loss, Take Profit)", overlay=true,

40
A L G O R I T H M I C T R A D I N G

initial_capital=100000, currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
length = input(14, minval=1)
OverBought = input(80)
OverSold = input(20)
smoothK = 3
smoothD = 3

//Slow Stochastic
k = sma(stoch(close, high, low, length), smoothK)
d = sma(k, smoothD)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//Limits Settings
stopLoss = input(10, title = "Stop loss percentage",
minval = 1)
takeProfit = input(10, title = "Take profit
percentage", minval = 1)

//Long & Short Strategy

41
A L G O R I T H M I C T R A D I N G

if (not na(k) and not na(d) and backTestPeriod())


if (crossover(k,d) and k < OverSold)
strategy.entry("StochLONG", strategy.long,
comment="StochLONG")
if (crossunder(k,d) and k > OverBought)
strategy.entry("StochSHORT", strategy.short,
comment="StochSHORT")

strategy.exit("StochCLOSE", loss = close * stopLoss /


100 / syminfo.mintick, profit = close * takeProfit /
100 / syminfo.mintick)

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

RELATIVE STRENGTH INDEX STUDY (RSI)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

study("@piazzasalotto - Relative Strength Index Study",


shorttitle = "@piazzasalotto - RSI",
format=format.price, precision=2)

//Parameter Setting
src = close, len = input(14, minval=1, title="Length")

//RSI
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 +
up / down))

//RSI Plots
plot(rsi, title="Stochastic", style=plot.style_line,
linewidth=3, color=color.blue, transp=0)
band1 = plot(70, title="Upper Line",
style=hline.style_dashed, linewidth=2, color=color.red,
transp=0)
band0 = plot(30, title="Lower Line",
style=hline.style_dashed, linewidth=2,
color=color.green, transp=0)

42
A L G O R I T H M I C T R A D I N G

fill(band1, band0, title="No Trade Zone",


color=color.yellow, transp=80)

1- RELATIVE STRENGTH INDEX STRATEGY

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//version 12.19

strategy("@piazzasalotto - RSI Strategy", overlay =


true, initial_capital=100000, currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type = strategy.cash,
default_qty_value = 10000)

//Parameter Setting
src = close, len = input(14, title="Length", minval=1)
OverBought = input(70)
OverSold = input(30)

//RSI
vrsi = rsi(src, len)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

43
A L G O R I T H M I C T R A D I N G

//Long & Short Strategy


if (not na(vrsi) and backTestPeriod())
if (crossover(vrsi, OverSold))
strategy.entry("RsiLONG", strategy.long,
comment="RsiLONG")
if (crossunder(vrsi, OverBought))
strategy.entry("RsiSHORT", strategy.short,
comment="RsiSHORT")

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

2- RELATIVE STRENGTH INDEX STRATEGY (Only


Buy)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//version 12.19

strategy("@piazzasalotto - RSI Strategy (Only Buy)",


overlay = true, initial_capital=100000, currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type = strategy.cash,
default_qty_value = 10000)

//Parameter Setting
src = close, len = input(14, title="Length", minval=1)
OverBought = input(70)
OverSold = input(30)

//RSI
vrsi = rsi(src, len)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

44
A L G O R I T H M I C T R A D I N G

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//Long & Short Strategy


if (not na(vrsi) and backTestPeriod())
if (crossover(vrsi, OverSold))
strategy.entry("RsiLONG", strategy.long,
comment="RsiLONG")
if (crossunder(vrsi, OverBought))
strategy.entry("RsiCLOSE", strategy.short,
comment="RsiCLOSE")

strategy.risk.allow_entry_in(strategy.direction.long)

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

3- RELATIVE STRENGTH INDEX STRATEGY (Stop


Loss, Take Profit)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//version 12.19

strategy("@piazzasalotto - RSI Strategy (Stop Loss,


Take Profit)", overlay = true, initial_capital=100000,
currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type = strategy.cash,
default_qty_value = 10000)

//Parameter Setting

45
A L G O R I T H M I C T R A D I N G

src = close, len = input(14, title="Length", minval=1)


OverBought = input(70)
OverSold = input(30)

//RSI
vrsi = rsi(src, len)

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//Limits Settings
stopLoss = input(10, title = "Stop loss percentage")
takeProfit = input(10, title = "Take profit
percentage")

//Long & Short Strategy


if (not na(vrsi) and backTestPeriod())
if (crossover(vrsi, OverSold))
strategy.entry("RsiLONG", strategy.long,
comment="RsiLONG")
if (crossunder(vrsi, OverBought))
strategy.entry("RsiSHORT", strategy.short,
comment="RsiSHORT")

46
A L G O R I T H M I C T R A D I N G

strategy.exit("RsiCLOSE", loss = close * stopLoss / 100


/ syminfo.mintick, profit = close * takeProfit / 100 /
syminfo.mintick)

//Histogram Plot
//plot(strategy.equity, title="equity",
color=color.yellow, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

1- BOLLINGER BANDS STUDY-STRATEGY

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy("@piazzasalotto - Bollinger Bands


Study/Strategy", shorttitle = "@piazzasalotto - BB",
format=format.price, precision=2, overlay=true,
initial_capital=100000, currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
source = close
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)

//Bollinger Bands
basis = sma(source, length)
dev = mult * stdev(source, length)

upper = basis + dev


lower = basis - dev

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

47
A L G O R I T H M I C T R A D I N G

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//BB Plots
h0 = plot(upper, title="upper", style=plot.style_line,
linewidth=3, color=color.red, transp=0)
h1 = plot(lower, title="lower", style=plot.style_line,
linewidth=3, color=color.green, transp=0)
plot(basis, title="basis", style=plot.style_line,
linewidth=3, color=color.blue, transp=0)
fill(h0, h1, title="No Trade Zone", color=color.yellow,
transp=80)

//Long & Short Strategy


if (crossover(source, lower) and backTestPeriod())
strategy.entry("BBLONG", strategy.long,
comment="BBLONG")
if (crossunder(source, upper) and backTestPeriod())
strategy.entry("BBSHORT", strategy.short,
comment="BBSHORT")

//plot(strategy.equity, title="equity",
color=color.red, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

2- BOLLINGER BANDS STUDY-STRATEGY (Only Buy)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy("@piazzasalotto - Bollinger Bands


Study/Strategy (Only Buy)", shorttitle =
"@piazzasalotto - BB (OB)", format=format.price,
precision=2, overlay=true, initial_capital=100000,

48
A L G O R I T H M I C T R A D I N G

currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
source = close
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)

//Bollinger Bands
basis = sma(source, length)
dev = mult * stdev(source, length)

upper = basis + dev


lower = basis - dev

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//BB Plots
h0 = plot(upper, title="upper", style=plot.style_line,
linewidth=3, color=color.red, transp=0)
h1 = plot(lower, title="lower", style=plot.style_line,
linewidth=3, color=color.green, transp=0)

49
A L G O R I T H M I C T R A D I N G

plot(basis, title="basis", style=plot.style_line,


linewidth=3, color=color.blue, transp=0)
fill(h0, h1, title="No Trade Zone", color=color.yellow,
transp=80)

//Long & Short Strategy


if (crossover(source, lower) and backTestPeriod())
strategy.entry("BBLONG", strategy.long,
comment="BBLONG")
if (crossunder(source, upper) and backTestPeriod())
strategy.entry("BBCLOSE", strategy.short,
comment="BBCLOSE")

strategy.risk.allow_entry_in(strategy.direction.long)

//plot(strategy.equity, title="equity",
color=color.red, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

3- BOLLINGER BANDS STUDY-STRATEGY (Stop Loss,


Take Profit)

//@version=4
//author=@https://www.fiverr.com/piazzasalotto
//v. 12.19

strategy("@piazzasalotto - Bollinger Bands


Study/Strategy (Stop Loss, Take Profit)", shorttitle =
"@piazzasalotto - BB (SL, TP)", format=format.price,
precision=2, overlay=true, initial_capital=100000,
currency="USD",
commission_type=strategy.commission.percent,
commission_value=0.3, default_qty_type=strategy.cash,
default_qty_value=10000)

//Parameter Setting
source = close
length = input(20, minval=1)
mult = input(2.0, minval=0.001, maxval=50)

//Bollinger Bands
basis = sma(source, length)
dev = mult * stdev(source, length)

upper = basis + dev

50
A L G O R I T H M I C T R A D I N G

lower = basis - dev

//Backtest Range
backTestSectionFrom = input(title = "FROM", defval =
true, type = input.bool)
FromMonth = input(defval = 1, title = "Month",
minval = 1)
FromDay = input(defval = 1, title = "Day",
minval = 1)
FromYear = input(defval = 2019, title = "Year",
minval = 1900)

backTestSectionTo = input(title = "TO", defval = true,


type = input.bool)
ToMonth = input(defval = 31, title = "Month",
minval = 1)
ToDay = input(defval = 12, title = "Day",
minval = 1)
ToYear = input(defval = 9999, title = "Year",
minval = 1900)

backTestPeriod() => (time > timestamp(FromYear,


FromMonth, FromDay, 00, 00)) and (time <
timestamp(ToYear, ToMonth, ToDay, 23, 59))

//BB Plots
h0 = plot(upper, title="upper", style=plot.style_line,
linewidth=3, color=color.red, transp=0)
h1 = plot(lower, title="lower", style=plot.style_line,
linewidth=3, color=color.green, transp=0)
plot(basis, title="basis", style=plot.style_line,
linewidth=3, color=color.blue, transp=0)
fill(h0, h1, title="No Trade Zone", color=color.yellow,
transp=80)

//Limits Settings
stopLoss = input(10, title = "Stop loss percentage",
minval = 1)
takeProfit = input(10, title = "Take profit
percentage", minval = 1)

//Long & Short Strategy


if (crossover(source, lower) and backTestPeriod())
strategy.entry("BBLONG", strategy.long,
comment="BBLONG")
if (crossunder(source, upper) and backTestPeriod())

51
A L G O R I T H M I C T R A D I N G

strategy.entry("BBSHORT", strategy.short,
comment="BBSHORT")

strategy.exit("BBCLOSE", loss = close * stopLoss / 100


/ syminfo.mintick, profit = close * takeProfit / 100 /
syminfo.mintick)

//plot(strategy.equity, title="equity",
color=color.red, linewidth=2,
style=plot.style_histogram, trackprice=true, transp=50)

52
A L G O R I T H M I C T R A D I N G

6
Chapter

Conclusions
Investing is a business where you can look very
silly for a long period of time before you are
proven right. Bill Ackman

Don't trust to those who promise to make you


rich in a day. Usually they are either mad or
rogues! The Adventures of Pinocchio,
Carlo Collodi

T he magic formula for the markets has not yet been invented. The
positive results can come with a lot of study, application,
continuous observation of the markets and even with some losses.
The more they burn, the more they will be useful for the future.
In today’s world there is no room for improvisation, rather it is necessary
to develop a sensitivity for details and to feel a healthy distrust of what
seems easy, avoiding to follow head down the path of the crowds.
With this guide our goal is to give the beginner in algorithmic trading a
vision of the magnitude, completeness and effectiveness of this system.
TradingView is just one of the many ways in which excellent algorithms
based on technical indicators and oscillators can be programmed and
used. What was previously done by the technical financial analyst with
careful and lengthy analysis, is now done in a few seconds by a computer
through a handful of lines of code. Today, thanks to platforms such as
TradingView, it is possible to trade, saving a lot of time and resources, but
above all, keeping the emotional factor out of operation. We focus only
on the interpretation of the signals and calculations provided by the

53
A L G O R I T H M I C T R A D I N G

algorithm. Data that, must then be aggregated to other analyzes carried


out on the financial title in question. Analysis of all the fundamentals
and/or news that can be put together.
Below we provide you with a series of very valuable tools, all of them
include a free and paid plan, which will support you in the analytical
management of the trading process.
Bloomberg delivers business and markets news, data, analysis, and video to the
world, featuring stories from Businessweek and Bloomberg News
https://bloomberg.com/
Business Insider is a fast-growing business site with deep financial, media, tech,
and other industry verticals. Launched in 2007, the site is now the largest
business news site on the web.
https://businessinsider.com/
https://markets.businessinsider.com/

Yahoo Finance - Stock Market Live, Quotes, Business & Finance News
https://finance.yahoo.com/

Fintel Provides Advanced Equity Research Tools for Intelligent Investors


https://fintel.io/

Stock screener for investors and traders, financial visualizations.


https://finviz.com/

Market insights and news of the investment gurus. Value investing screens and
valuation tools.
https://gurufocus.com/

Investing offers free real time quotes, portfolio, streaming charts, financial news,
live stock market data and more.
https://investing.com/

The Premier Research Platform for Long Term Investors


https://macrotrends.net/

MarketWatch provides the latest stock market, financial and business news. Get
stock market quotes, personal finance advice, company news and more.
https://marketwatch.com/

54
A L G O R I T H M I C T R A D I N G

What we have omitted in this guide is a rather important aspect of


algorithmic trading, that is the automaticity of trading. This means that
algorithmic trading is not just giving the signals of entry and exit on
financial securities, but is also leaving the robot in complete autonomy in
carrying out market entry and exit transactions with real money. There are
several platforms and brokers that offer these options. As proposed in
this beginner guide, exploit the signals provided by the strategies and only
when you are sure, you can proceed with the input of the operation on
the market through your broker. You will have the task of leaving the
market manually or setting the limits (stop loss, take profit, trailing stop).
With TradingView you can use algorithmic trading with real money and
on a demo account. Start with the demo to gain experience. To learn
about this aspect of the platform and all the various functions and
specifications of TradingView and to deepen all the topics covered in the
guide related to the platform, we leave you, below, some reference links.
All the contents proposed below are free.

Pine Script 4 User Manual - Official Documentation


https://tradingview.com/pine-script-docs/en/v4/index.html

TradingView Beginner’s Guide 2019 - Unofficial guide for a better look to all the
function of the platform
https://forex4noobs.com/tradingview-beginners-guide-2019/

The economy and finance in general, and, investments and online trading
specifically make up a fascinating and exciting world. Do not let yourself
ruin all the poetry of this world by losing your savings because you have
been hurried and unprepared.
Below we provide you with some useful links to start to understand what
you are about to do. All the contents proposed below are free.
How The Economic Machine Works by Ray Dalio
https://www.youtube.com/watch?v=PHe0bXAIuk0

William Ackman: Everything You Need to Know About Finance and Investing in
Under an Hour
https://www.youtube.com/watch?v=WEDIj9JBTC8
Technical Analysis
http://www.mrao.cam.ac.uk/~mph/Technical_Analysis.pdf

55
A L G O R I T H M I C T R A D I N G

Introduction To Fundamental Analysis


http://i.investopedia.com/inv/pdf/tutorials/fundamentalanalysis_intro.p
df
Contact us at any time and for any need at our official profile on Fiverr
platform (https://fiverr.com/piazzasalotto) and we will be happy to
support you.
Good trading to all of you!

56
A L G O R I T H M I C T R A D I N G

A nd back in the spring of 1720, Sir Isaac Newton


owned shares in the South Sea Company, the
hottest stock in England. Sensing that the market
was getting out of hand, the great physicist muttered
that he “could calculate the motions of the heavenly
bodies, but not the madness of the people.” Newton
dumped his South Sea shares, pocketing a 100% profit
totaling £7,000. But just months later, swept up in the
wild enthusiasm of the market, Newton jumped back
in at a much higher price—and lost £20,000 (or more
than $3 million in today’s money). For the rest of his
life, he forbade anyone to speak the words “South
Sea” in his presence.
Benjamin Graham, The Intelligent Investor

57
A L G O R I T H M I C T R A D I N G

Legal Disclaimer
Government Required Disclaimer

A ll content presented through this guide is done so for


informational and educational purposes only. We had take great
care in ensuring the accuracy of all information presented in this
guide, however, users should be aware that content on this guide is
subject to change without notice, eventually, in an updated version.
Before deciding to invest your savings, you should carefully consider your
investment objectives, level of experience, and risk appetite. No
information or opinion contained on this guide should be taken as a
solicitation or offer to buy or sell any financial product or other financial
service.
We will not accept liability for any loss or damage, including without
limitation to, any loss of profit, which may arise directly or indirectly from
use of or reliance on information contained on this guide. Past
performance is no guarantee of future performance.
Are welcome any reporting of typing error or incorrect or not completely
correct information.
Thank you.

58
A L G O R I T H M I C T R A D I N G

…COMING SOON…
On the right side of the chart
New algorithmic strategies and smart considerations for a winning trading

Preorder at [email protected]

Thanks to M.M.V. for all her time spent to give us suggestions and analysis to the
success of this guide.

59

You might also like