Transcripts
1. Mastering TradingView Pine Script v5 Intro for SkillShare: Colon, welcome to
Mastering trading view Pin Script version five, from fundamentals to custom
indicators and strategies. I'm Serge Bass, a seasoned
trader and programmer with extensive experience
in developing custom trading tools
using Pine script. In this comprehensive course, we'll dive deep into the world of Pin
Script version five. Trading views powerful
programming language. Whether you're a
complete beginner or have some coding experience, this course is designed to
take you from the basics to creating your own sophisticated trading indicators
and strategies. Over 13 engaging lessons, you learn the fundamentals of Pi script version
five syntax, how to create and customize popular indicators like moving averages and Bollinger bands, techniques for
building, back testing, and optimizing your own
trading strategies. Advanced features new to
Pi script version five, such as libraries and
advanced loop structures. This course is perfect for traders looking to
automate their strategies, technical analysts wanting
to create custom indicators, and anyone interested in
quantitative trading. No prior programming
experience is needed. We'll cover everything
you need to know. To get started, you'll just need a free trading
view account. We'll walk through setting
that up in your first lesson. For your class project, you'll develop your own
MA price cross strategy. By the end of this course, you'll have the skills
to create test and implement your own custom
indicators and strategies, potentially giving you a significant edge
in your trading. Remember, while we'll be
working with trading concepts, this course focuses on programming skills and not
providing financial advice. I am excited to guide
you on this journey into the powerful world of
Pine scrit programming. Let's get started and take your trading
to the next level. See you in the first lesson.
2. Introduction to TradingView Pine Script v5 and How It Can Be Used.: H one, welcome to this
lesson introduction to Trading view Pine Script, version five, and
how it can be used. This lesson consist of
following sections. In introduction
section, I will review Trading view Pine Script
and trading view platform. In the next section,
I will cover some features of Trading
view Pine script, such as custom indicators
and strategies, real time analysis,
back testing, and accessing external
data sources. In the next section, I
will talk about setting up Trading view account and how to access Pine Script editor. In the next section, I
will cover some features. Such as Fin script editor,
the bagging console, built in Back testing feature, and built in functions
library. Let's begin. Rading view Pin script
version five is a powerful scripting
language that allows you to create
custom indicators, strategies, and libraries for analyzing financial markets
and making trading decisions. It is used on the
trading view platform, which is a popular web based charting and social
trading platform that provides real time
and historical market, as well as wide range
of technical indicators and tools for analyzing
financial markets. Ding Pine Script is a
programming language that is specifically designed for creating
technical indicators, strategies and alerts
for financial markets. It is based on the Pine
programming language, which is a simple and
easy to learn language that is similar to C and
JavaScript language. The main advantage of
trading vi Pan script is its ability to create custom indicators and strategies that can be applied to
charts in real time. This allows you to analyze
financial markets and make trading decisions based on your own unique set of
rules and conditions. Radu Pan script also
allows you to bates your strategies using
historical market data, which can help you to evaluate the performance of
your strategy and identify potential issues or areas of improvement before putting real money on the line. Radu Pan script also allows you to access external data sources, such as financial data from
externalEPI, news articles, and other relevant information, which can help you make more
informed trading decisions. To use Trading Ve Panscript, you need to set up
trading view account that can be set up for free. A Aces Panscript editor. The Panscript editor is a web based integrated
development environment, IDE in short, that provides quote editor a debugging Console and built in Back
testing feature. Once you registered in trading view platform and logged in to Access inscript editor, you can click on this menu
item in Product Charts, or you can click
on this button to Access Full Chart view.
Let's click on it. In this screen, on
the right side, you can see the list of
financial instruments. When you click on any of
this financial instrument, chart for that
instrument is loaded. If you want to select another financial
instrument that is not, for example, on this list, you can click on
this Ticker textbox and s for the symbol
that you need. For example. Let's look
for Microsoft stock. MSFT, and when we click on it, Chart for Microsoft
stock is loaded. Let's click on this
textbox again. Here you can see the
several buttons that is related to certain financial
instrument categories. We click, for example,
on any of it, only instruments
for that category is loaded in this list. We click on crypto, for example, and we want to search
for some crypto, for example, ium, USD. Then we can click on
this found ticker for Vm SD and chart for
that ypto is loaded. When you have free
count, sometimes you can see these banners, you can close them
and ignore them. Now, to access Pine Editor, we can click on this button, Pine Editor button at the
button section of the screen. Pine editor is expanded, and we can for example, maximize this window for our Pine editor by click on
this maximized panel button, or we can minimize it by
click on on Hide panel. Now let's click on
Pine Editor again. This pine editor section
consists of two main sections, code editor, and consult. Console section has
some text related to your activity in
the code editor. For example, if you make any
changes and try to save it. It's going to ask you to
enter the script name. Let's keep my script
one, save it. Then you can see on the debugging console
related information to your actions. You compiled it and
then it has been saved. The script has been saved. You can expand the
console by dragging this splitter line or
shrink it if you need to. Also by clicking right
click on the console, you can clear the console. Your script has any errors, you will see errors
in the script, the bugging console
in this section. Now, if you want to expand and
shrink Pin editor section, you can do it by dragging this splitter line between
chart and Pin editor. The Pin editor also provides a library of built in functions that can be used to perform calculations and make
decisions in your script. These functions include
mathematical functions, technical indicators,
and charting. Let's review built in
indicators and strategies. To access this window, we can click on
Indicators button. Then in this screen, we can see that there are
several buttons over here that can be clicked and that way we can filter scripts
for a certain category. When we click on Favorites, you can see the list of the scripts that
you favored before. When you click on M scripts, you can see the list
of all your scripts that you have created and
saved on your account. When you click on technicals, you can see the old built in scripts in trading
wheel platform that you can use in
your own script. Now, let's say for example, we want to load one of
the built in scripts. Let's load, for
example, MacD strategy. When you click on it, it's
loaded in our screen. You can see that Mac
Di Strategy label is located in the chart section, and also it has
some buttons on it. Let's review them. This
is the hide button. When you click in it,
that script is hidden, gets hidden from
your chart section. To make it visible again, click on this button again. Next button is the
settings button. When you click in
it, you can see all the settings of your script, such as input parameters
property visibility and. You can change this prime
finito and click again. Next button is the
source code button. You can click on this
source code button to access script of this strategy. As you see, we access the script and the
script is in gray color, and there is a lock
label over here. It means that we cannot edit this script because it
is built in script. However, if you're interested
to use this script, we can save this script and make it our own by making
a copy of it. To do that, we can click on this three dots button
and click savers. Let's keep it MD Strategy
copy and let's click Save. Now, we created a copy
of Mac D strategy, and now we can use
it and edited. Let's remove the older
MD strategy that we have previously added to remove
the script from your chart, click on this remove button. Now we have created our
own Mac D Strategy copy. If you want to apply this
script to the chart, we need to click
on this button at t. Now it's added to the chart. We can see some strategy performance
statistics over here, and even we can see
some trades that have been performed by this
strategy on this chart. Now, to access the code, the code of this script, again, we can click on this source
code to make a changes. We just can the script
and let's change the, for example, default value. To save the changes, you can click on Save button. There is another way to change
it by clicking on Control. Key and on S key simultaneously. For example, let's just
change this to 30, click and hold control key
on the keyboard and click on S. This is a shortcut
to save the script. Now let's take a look at
the built in functions. For example, now
c current script, there are some
built in functions. MA is a function calculating MA. Value. To access the
reference to that function, we can click on Coral and
click on this EMA function. You can see the reference
manual opened up. If you want to take a look
what this function does, we can read the related
information for that function. Functions. Many functions
are grouped in script. For example, if
you want to access technical analysis
related functions, we can type in this
screen TA dot, and we can see all
the related to technical analysis
functions that are grouped to the TA
namespace are here. We can select them and
use them in our script. There are other name spaces. Name space is the prefix of the functions that is separated from the
functions by dot. For example, there is a
mouth namespace, Muth dot, and there are related
functions related to math name space functions. You can see in this screen. For example. Math apps. This is the functions that is
calculating absolute value. To access this reference manual, you can click on this button
and reference manual pop up. Here you can type
any functions that you're in order to find. In summary, trading view
Pine script version five is a powerful scripting
language that allows you to create custom
indicators, libraries, and strategies for analyzing
financial markets and making trading decisions
with its ability to access external data sources, B testing capabilities,
and simple syntax. It's a versatile tool
for any trader or investor looking to gain an edge in the
financial markets. This is the end of this lesson, and I will see you in the next.
3. Setting Up a TradingView Account and Accessing the Pine Script Editor: Hell one, welcome
to this lesson, setting up a trading
view account and accessing the
Pin Script editor. This lesson consists
of following sections. Introduction section where I will review Trading
view Pinscript, and we'll point out
the importance of Trading view account in order to work with Pin Script editor. In the next section, I'm going
to explain step by step, how to create trading
view account. After that, in the next section, I will explain and demonstrate how to access
Pin script editor. In the next section,
we're going to create our first scripts, and I will point out
importance of Pn Pro plus account in order to access
all features of Trading view. Last section, a conclusion
section where I'm going to point out key takeaways
from this lesson. Let's begin. In order to use Trading
view Pin Script, you will need to have
Trading view account to access the Pin script editor. In this lesson, I will go
over the steps for setting up trading view account and
accessing Pin script editor. In order to create
Trading view account, you need to go to
trading com website. Then click on Get
Started Balton. After that, click
on Sign up Bon. Enter e mail address
and password and check in these
two checkboxes and click on Create account. You will get an e mail address, click on link on
that e mail address to verify your e mail. And after that, you're
going to be able to log in to trading view platform. Let's log in. Let's have a quick overview of existing plans in
trading view platform. Free plan is sufficient
for this course. But I will mention that Fri
plan has some limitations. For free plan, you
see some ad banners. You can just click
them and ignore them, but you can see them. For paid plans, those ad banners you're not
going to see them. They are disabled. Also, you have only
one chart p t, and a number of layouts. Number of sad chart
layouts is one as well. You have less historical data, but it's still a lot of data, seven years and eight
years of historical data. Also for alerts, you have
only one alert in free plan. O paid plan, you
have 20 and more. Also, you have only one
watch list in free account. That's pretty much all. Now let's access
P script editor. In order to access
Pine script editor, click on products and
then charts menu options. This way, you will get to full chart view screen where
pine script editor is. Now, let's take a look at
the features on this screen. I'll explain you
the main features of this screen so you can easily gate and understand some important features
on this screen. On the right side, you can see the financial instrument
sections where watch list is. Watch list is a list of
financial instruments. You can edit this watch list, and you can have financial
instruments in this list, only the instruments
that interests you. You can edit them, you can remove financial
instrument, for example, let's remove this
financial instrument by clicking on this
remove button. To add instrument,
click on add symbol. Then you can just add
any symbol you want. Let's for example, add Tesla. We have added Tesla ticker
to this watch list. Now, I'll explain some important
buttons on this right side. Watch list button works
like a togal button. One time you click
it it collapses, one time you click
it it expands. Next button is Alerts button. This way you create alerts. Alert is representation
of an event that happens on certain
financial instrument or in your script. On that event happens, you will get an alert. Alert could be e
mail that you will receive popup message
or sound, for example. Next important feature
here is the data window. This is the values data coming from the chart
and from your script. You can see for every bar, the value is different. You can use this screen as a debugging window to
debug your scripts. When you debug your scripts, you can plot some variables in your script and by
navigating to any bar, you can see the value of those
variables in this window. Also, there is another
important button notifications. Whenever you get alert, that alert will be
logged in this window. You can see the history
of all alerts that happened that happened within your allerts that
you have set up. Now, other important
buttons here are, for example, chart settings. In this chart settings, you can change the look
and heel of your charts. You can change the how your candles look
like in your charts. You can change the colors. You can change some other
information if you need to. You can change you can change if you
want to see the body, you can change if you want to see the border of those candles, et c. Status line is the line of the
financial instrument that you have loaded
in your chart. You can remove the title, or you can just disable
the OLC values, or HLC is open high
low close values. You can disable them if you're not
interested to see them. Next scales, you can customize
scales in your chart. You can change data
format, date format, you can change time format, and you can do other
customizations if you need. In appearance, you can
change the, for example, the background colors
in your chart. Next control here is
the layout control. You can click on this
control and you can see some of the menu options
related to the layout. Layout is basically the chart and indicators that you
applied to this chart. You can save all the settings. Next time when you log in, you can see exactly
this chart and all the indicators that you
have added to that chart. For example, right
now, you can see our Layout is named class. You can rename it if you
need to, by the way. In the free plan, you can
have only one layout, but in paid plan,
you can have many. If you have many, you can load them load any chart that
you saved from here. Next, let's review the dis
controls on the left sections. You have a textbox for tickers. You can s for a symbol
if you want to, and you can Lad chart
for that symbol. Tesla, click Chart for
the Tesla is load. Next, this button is responsible
for loading comparing Symbol. If you want to compare your chart with another
chart of another ticker. For example, you want to compare the corn Tesla chart
with spx chart. Click on spx. Yellow line is Sp X chart. You
can compare them. If you want to delete chart or any script that you have
loaded in your chart. You just go to that label
related to that Ticker, and just click on
the remove button. Next control is the
time frame control. We can change the time
frame of the current chart. Currently is one day time frame, which means one candle on this
chart represents one day. We can change it for any other
time frame from this list, for example, one week. Now chart looks different. Every candle
represents one week. For example, if we select
this candle and click and look at the OH LC values on the top left of the
chart, this section. You can see that open price
for this candle is 36.84. If you navigate to
any other candle, you can see OH LC price for any other candle that
you navigate to. Next is the type of a bar. Currently we have candles, but we can change it
to another type of the chart like a bar
chart if we want to, and some other type of
charts as well here. Indicators chart here, we
have a list of my scripts, meaning our scripts that
you have developed. We can have we can load any built inscript
that allocated in technical section
of this window, any built in script from trading view
allocated here, et c. On the left side, you can
see some other buttons here. Most of these buttons are dedicated to drawing
on the chart. For example, this button expands and we can see some graphics that we
can add to our chart, for example, tread line. We can draw tread line. Next button, for example, we can draw fib
retracement if we need to. Et c To remove any
graphics on your chart, click on this button,
click, remove drawings. Now, let's take a look how
we can access Pine Editor. Pine Editor button is located on the bottom part of this screen. Let's click on it. When we click on
it, we can see that Pine Editor section
panel expand it. If you want to maximize it, we can click on Maximize button. If you want to hide it, we can click on Hide button. If you want to expand it again, we can click on this button
as well. Show panel. Now, if you want to
create a new script, we can do it several ways. In order to create a new script, you can click, for
example, an open button, and we can click on any of
these three menu options. You can create new indica, new strategy, new library. Let's create a new indicator. When you create a new indicator, default indicator is created
that is simply closed. Let's say, for example,
we want to add this simple indicator into our chart and see how
it's going to look like. In order to add this
indicator to our chart, we need to click on
add two Chart button. We can see that
indicator is added, but not to the chart to the bottom panel located
just below the chart. This is because by
default is going to be added to the bottom panel, not to the actual chart. In order to correct that, if you want to add our
indicator to the main chart, we need to specify overlay parameter and set it
to true in our indicators. So our indicator have
a parameter overlay. If we set it to true, and if we save it, let's click counter
S to save it. This guy is asking us a name. Let's keep it my script, save. Then if you want to add it, we need to add it, but we have a previously
added M script. We need to remove it
because we changed overlay. We no longer need this indicator on this button panel.
Let's remove it. Click on remove button. Now let's add this simple
indicator to our chart. We can see that our,
which is a blue line is going exactly through close
price of every candle. This is what we expect
because we draw, we plot the closed
prices for every candle. Now, L et's create another
script, another way. Let's for example, create a
script from built in scripts. One way to do it is
from this many options. We go to open and we need to click on built in
scripts. Many option. Here we have all trading
view platform built in scripts that we can use in order to develop
our own. Script. For example, I'm
interested to create customized Mag D indicator based on built in MD indicator, or not even indicator. Let's create a strategy. I type Mac D and I can
see that there is a built in MD strategy. I click on it. Now, the script from that built in Mac Di strategy or copy
it to this code editor, and we can customize it and use it to develop our own script. For example, we can
start changing it, change the default
fast length if we need to change the
default slow length, and let's save it. It's going to ask us name. Let's call it MacD strategy. Customized. And click save. Now, previously, we had our
my script added to the chart. Let's remove it. We no longer interested. You
have it on the chart. Let's add our newly created
Mac D strategy customized. Let's add it to our chart. In Order to do that, click
on Add Chart button. Here we have it. Our str has
been applied to the chart. We can see some
trades on the chart. So buying and some
selling events happening. We can see the
graph representing the profit and loss
of our strategy. We can see the some trading
strategy statistics here, net profit percent
profitable MGS draw down. If you want to see some
performance summary, we click on this button
performance summary button. We can see additional
trading strategy statistics. We can see a list
of trades here. When we click List
on trades button, we can see all the
trades that have been performed by this strategy. Now, let's go back
to our review, and let's go back to Pin Editor. To access Pin editor
from strategy tester, screen, we just
click on Pin Editor. Now we are back to
our Pine script. That is the Pin script of
our MacDtr customized. I demonstrated how to
create simple indicator, how to apply to the chart, how to create simple
trading strategy from Built in Script. And also, we covered some basic features on
this full chart screen. In this lesson, we discussed the steps for setting up
trading view account and accessing the Pine script editor in order to use trading
view Pine Script. The process includes creating trading vi account
by going to website, signing up, verifying
the e mail address, and then logging
into the account. Once logged in, the Pine script
editor can be accessed by clicking on Charts
Options in products menu, and then click on
Pine editor button on the bottom of Chart screen. The Pan script editor can be used to start creating
custom indicators, strategies, and
libraries for analyzing financial markets and
making trading decisions. This is the end of the lesson, and I will see you
in the next one.
4. Variables and Data Types in TradingView Pine Script: Hello, welcome to this lesson. Variables and data types in
trading view Pine script. This lesson consists
of following sections. In introduction
section, I will review variables and data types in
trading view Pine script, and I will explain importance of understanding variables
and other types. In the next section, I will cover variables
in Pine script, how to define them, and how to use
variables in scripts. In the next section, I will name all existing data
types in Pine script. After that in the next section, I will demonstrate how to declare variables
in Pine script. In the next section,
I will talk about the importance of using
appropriate data type, and I will demonstrate some examples of
appropriate data types. In the last conclusion section, I will summarize what we
studied in this lesson. Let's begin. In trading view Pine Script, variables and data
types are used to store and manipulate
data in your script. Understanding how to
use variables and data types is
essential for creating effective and efficient
a variable is a named storage location in the memory of a computer
that can hold a value. In Pine Script, variables
are used to store values, such as prices, indicators, and other data that is
used in the script. Pin Script version five
supports several data types. First datatype that
we're going to review is integer datatype. Integer datatype is
specified by using Int, which is a type name, and then to declare variable
of integer data type, we specified in then space, one more spaces, and then we specify the name
of the variable. In our case, my integer. After that, we specify
operator equal and initialize that variable
with the value of five. Integer variable can
store only whole numbers, like five or ten or
11, for example. Next datatype is
a flow data type. Flow datatype can store
only decimal numbers. Decimal number is a number
that has decimal part, separated by dot
from the whole part. In our example, let's declare flowed
variable. Piece five. The name of the float type, which is a float,
then space, my float, which is our variable
name, then operator equal, and then the value
that we want to assign to the flowed
variable, 3.14. As you see, decimal value has a whole part three
and the decimal part, 1.4, and the separated by. This decimal part, we can
assign to the float variable. Type. This variable can
have different values, different flow flow values. For example, we could set another decimal value
like 10.254 for example. Next data type is
a Bolin data type. Bleing datatype can store
only value true or false. Variable of bin. Data type can store
only true or false. We specified data type. Bu in our example, space, the name of the bin variable, my bin, peraor equal, and the value true. We can set it to true or false, let's set it to false. Next data type is a
string data type. String is a sequence of
characters such as hello, goodbye, high, et cetera. This sequence of
characters must be between quotes if you want
to assign it to the string. Variable. If for example, we do not specify a quote, then we can see that we
get an error that way. Collection of characters
that we put between quotes. After that, we can
assign this string to the variable of
string data type. Next data type is
a color data type. Variable of color datatype, can store only color. To define variable
of color data type, we specify color space and
the name of the variable. Then we specify equal
operator and the color. There are pre existing colors in color space in Pine script, and we can select any
available color if you want to specify
the color by name. To look up what
colors are available. We can go to reference
manual pop up, and then we can type color dot. I can see that all
available colors, for example, color dot, green, color dot red, et c, we can select any of
these available colors. Keep in mind that
color name space can have not only color
in this name space, it can have some functions
as well color dot RGB. Right? So we defined our variable of type color
using the named color. There is another way to define variable of a color by using
color dot RGB function. When we use color
dot RGB function, we specify levels of red, green, and blue, and
level of transparency. By combining all these values, we generate a new color. We do that if you want
to create a color that does not exist
in color namespace. We can change any of these
numbers if we need to and we can specify transparency as the last parameter
in this function. That way we created
our custom color. There is another way
to do it by using the window color
selector window. When you have the
color gB function, you can see this color
selector pops up. Then you can just select any custom color by
dragging this circle, or by dragging this selector and to select different
color grades. For example, some
type of something approximately blue or
something approximately red. Is const it over here to red, and then you can customize
it more. Change color. Also we can change
the transparency. By doing that, all these
values have changed and we created our custom color
using color selector. Next, next variable
type is array. A ray the collection of
values of the same type. A array has a size. In our example, we
use a ray function to declare and defined an array. We use array of new
function after that, we specify type of an array. In our example, it's in, then we specify the
size of an array, ten coma and initial value of
each element of that array. When this lining is executed, array in will be an
array type variable, and it's going to
have ten items, and each item is going
to have zero value. Next data type is a
series data type. Series is a series of data, such as closing price of
stock or open price of stock, or value of exponential moving average or some
other indicators. In this example, we calculate exponential moving
average value from close price with the period of ten and we assign
that value to MA. In this case, MA is
the seres data type. Why? Because a MA
function returns ser data Sers data type is the data type that
calculated for each bar. In our chart. In this example, EMA is calculated for
each bar in our chart, and that variable stores
value of MA for each bar. In our case, we
have 9 bars here. Whenever last bar is executed, whenever our script is executed
for all the bars here. MA will have values
of all the 9 bars. Per each bar, MA will
have calculated value. Also to get those
values, for example, you can use MA, you can use reference
history reference operator, which is consist of these brackets and then
we specify the index. At zero is the A value of the Sers variable of
the current bar value. If you specify one, it's going to calculate A
value from the previous bar. This is how you get those
values from this serious vari. Next, let's review
how we use Var KR. You can use Aki
keyword to specify data type that is detected from the value you
assign to that variable. For example, now, in our case, we have space count, which is the name
of our variable, and then we assign
value of zero. Zero is a whole number. The count in this example, will be type of it will be detected from the value that we assigned
to that variable, which is going to be integer because the value that
we assign is integer. If we assign value 0.5, the type will be considered
as a float data type. Then in the rest of the script, discount is going to be
used as a float data type. In this example, below, I design a simple indicator that calculates green
bar in the chart. It calculates all green
bars in the chart, and this demonstrates how
count variable is used. Because whenever there is a very important characteristics
for the variables. They store value between bars. For each bar, they
preserve the value. It means that whenever you assign the value
for such variable. The first bar is going to
still remember that value when the script is executed
for each bar in our chart. And this script
demonstrates that. So otherwise, if we
use type like in, every time whenever script
is executed for each bar, that value is reset and it's going to be assigned
and it's going to be zero assigned to that value again so that it will
not preserve the value. Let's see how it works. This small indicator
calculates green bars. In this line, we detect
if current bar is green, by checking if close
is bigger than open, then this bul and variable is
true whenever bar is green. Then we check if this
variable value is true, then we increment count by one. O incremented we reassign the Value to the count
variable count plus one. That way, we increment count
value, and then we plot it. What this script does is
whenever body is green, it's going to increment
count by one. By the way, this operator colon equal is called a re
assignment operator, and you need to use it
whenever we need to reassign a new value to previously
declared variable. Like in our case, you declare a variable first, you use equal parator. If you need to re assign new
value to such a variable, you need to use a re
assigned parator. Now, let's verify how this small indicator works if
it produces proper results. As you see this indicator
plotted this line, and the value of this indicator on the last
bar is six as you see here. It calculated all the green
bars and the value is six. We can see the total number of green bars in our chart six, it means that the
bar works correctly and it means that
variable that we declared with the var keyword actually does preserve
the value between bars because we keep incrementing it and keeps remembering
the value that we calculated previously
on previous bars. If, for example, we want
to look up In some bar, what value this indicator had. Let's see, for example, for this green bar. We can see that whenever we
navigate to certain bar, we can see in this
section, the blue number, the current value of this
indicator, which is three, meaning calculated value of the end of this current
bar was three, y? Because including current bar, they are only three green
bars up to this point, including the current one. Therefore, we verified that this indicator calculated for this bar number of
green bars properly. So it's important to use
appropriate datatype for each variable as this will ensure that your script runs
correctly and efficiently. For example, if you're
working with prices, you should use sis data type. If you're working with colors, you should use color data type. And if you're working
with values from moving averages or
from other indicators, you should use flawed datatype. In summary, in this lesson, we have covered the basics of variables and data types in
trading view pine script. Understanding how to use
variables and data types is essential step in creating effective and efficient scripts. This is the end of the lesson, and I'll see you
in the next one.
5. Operators and Expressions in TradingView Pine Script: A one, welcome to this lesson. Parators, and expressions and
trading view Pine script. This lesson consists
of following sections. In introduction section, I will review operators and expressions and trading view Pine script. In the next section, I will
explain types of operators, such as arithmetic
comparisongical assignment and some other operators. In the next section, I will cover expressions
in Pine script. In the next section, I
will explain how to use operators and expressions
in Pin script. We'll review examples
of calculations, comparisons and
conditions in Pin script. In the conclusion section, I will point out importance
of understanding, operators and
expressions for creating effective and efficient
scripts. So let's begin. In trading pine script, apparatus and
expressions are used to manipulate and evaluate
data in script. Understanding how to
use operators and expressions is essential for creating effective
and efficient script. An operator is a
symbol that performs a specific operation
on one of moves. P script version five
supports several types of operators, including
arithmetic operator, such as addition subtraction, multiplication,
and division, for addition operator
reviews plus symbol, for subtraction operator
reviews, minus symbol, for multiplication
operator reviews, star symbol, and for division operator reviews,
backslash symbol. Next, comparison operator,
such as greater than less than greater or equal to
and less or equal to. Next logical operators,
such as n or n nought. Logical operator, we use
exactly this keyword, n or n nought. Next operator is
assignment operator. Assignment iperator,
we use equal sign. Signment iperator
is used to assign a variable when it
is initialized or declared reassignment
operator consists of two symbols column and equal. Reassignment operator is used to reassign a value to
an existing variable. Next, operator is a history
referencing operator that consists of bracket opening
bracket and closing bracket. For example, expression one, open bracket, expression
two, close bracket. This operator provides access to previous values of
series expression one, where expression two is a number of bars back and
must be numerical. The last operator
that we're going to review is a ternary operator. It consists of question mark
symbol and colon symbol. This operator is used to create expressions of the
form condition. Value and condition is true. Colon, value and
condition is false. The result of this expression will be dependent on condition. If this condition is true, then the result will be equal to value when condition is true, otherwise, it will be equal to value when
condition is false. Now let's review these
operators in fine script. First, let's review
arithmetic operator. This example, we declared and initialized two
integer variables, x equals to five and
y equals to three. Then using arithmetic
operator plus, we created an
expression x plus y and assigned value of
this expression to the new variable result. This example x plus y, five plus three equals. Eight and the value of eight will be assigned
to the variable result. This is an example how to use arithmetic operator
plus addition. Next operator is a
comparison operator. We use comparison operators
to compare values. In this example, we declared
is greater bole variable, and we assigned value
of x plus y expression. This expression is using comparison operator,
greater than. Let's calculate it
x greater than y. Is it true or false? X is five, y is three, five bigger than three, this Expression will be equal
to true, therefore, and we will assign true
to the variable is great. After this expression is
calculated and result is true, then this value true will be assigned to the
variable is great. Now let's review
logical operator. Logical operator is using keywords such as and or and not. Let's review this example. We declare variable is true and we assigned
to that variable. The result of this
expression is bigger than three and y less than five. Let's calculate this expression. I x bigger than three,
y bigger than three. Yes, left part of this
expression is true. Is y less than five. Yes, part of this
expression is true as well. Left part is true and y
right part is true as well. True and true equals to true. Therefore, the result of this
entire expression is true, so we assign value to
the variable is T. Let's review another example. We declared b in
operator is false and we assigned to that variable the
result of this expression, is bigger than six
or y less than two. X bigger than six? No, because five is
not bigger than six. This left part of this
expression is false, right part is y less than two. No. Therefore, right
part is false two. False or false equals files. Therefore, we assign
false value to our variable is false. Let's review another example. I is true two. We declared this variable and we assigned to the variable value
of this expression. Is bigger than
three and embraces, y less than five or
y bigger than ten. Let's calculate left part
is bigger than three. S. Let's calculate this
right part in braces. Y less than five. Yes, or y bigger than ten? No. However, the
entire expression in braces is going to be true because when
you use operator, it's sufficient
when at least one part of this expression. Is true. Because y
is less than five, therefore, entire expression
in this brass is true. Then we have left part is true and right
part is true as well. Therefore, true and
tru e t. Therefore, we assign true value to
de variable is true. Let's review
assignment operator. We use assignment operator to assign the value
to a variable. We declared string
variable my string, and we assign value to
that variable hello. This is an example how we
use assignment operator. Next operator is a reassignment
operator that consists of two symbols colon and equal. We use reassign. Operator, we need to reassign new value
to existing variable. This example, we use
already declared variable, which is existing
variable, my string, and when we need to reassign
new value to that variable, we use reassignment
operator column and equal. If we need to reassign another value to the
same existing variable, will need to use again,
reassignment operator. In this example, we
reassign another value, good by two to
existing variable. My string, therefore, we
use re assignment pertor. Now let's review
how to use history, referencing operator,
which consist of brackets. This example, I created a
small indicator that will demonstrate how to use
history referencing operator. First, I declared close variable and assigned value
zero to that variable. And then I assigned to that variable the higher
close from previous bar. Therefore, we use referencing
operator brackets, and we use one indicating
that we need to access previous bar previous bar for that serious variable. This is serious variable, and we assign to the current value of
the serious variable, the value of this variable
from the previous bar, because we use one,
which means 1 bar back. Right? Now, then we
have a condition. I clothe bigger than open, meaning if bar is green, then we assign close to
our variable higher close. Obviously, whenever this
condition is false, high close will equal to the
value from previous bar. We plot this value, high close. Now, let's take a look
in this chart and see how this indicator is
working, actually. Let's review, for
example, this bar. The idea of this indicator
is whenever bar is green, veal of this indicator, which is a blue
line will be equal to the close of the current bar. Whenever indicator is
whenever bar is red, the value of the
indicator will be equal to the previous
value of this indicator. For example, in this
bar, bar is green, the green the indicator value equals to the close
price of this bar. If bar is red, then the value of this
blue indicator is equal to the value of the
indicator at previous bar. Therefore, value of indicator
of these 2 bars are equal, et cetera when
this bar is green, then we value of the
indicator is equal again to the close
price of this bar. Now, let's review how
we use Turner repert. In this example, I will try to recreate the same indicators
as I just explained, but using Turner repertor. In this example, I declared variable i close
two and assigned value zero, and then using ternary operator, I assigned value to this variable, using
ternary operator. If close bigger than
open, if bar is green, I will assign close
price to this variable, otherwise, hi close
two from previous bar. The logic is the same for
this as in these three lines. But by using ternary operators, we shortened our code and made it more elegant
and easier to read. Now, let's plot this
high close two indicator and make sure it's plotting
the same values in our chart. The same values as
high close indica, blue indicator that
we plot previously. High close indicator is
plotting blue color indicator, and the high close two indicator isloting orange color indicator. Let's plot one on another. If they're plotting
the same values, so high close two
will be plotting values and drawing line right on top of higher
close indicator. Therefore, as you
see on the chart, we do not see the
blue line because orange line is plotted exactly
on top of the blue line. Therefore, this
demonstrates that these two indicators are
calculating the same values. However, the second indicator
is using Turner Epert. But the first indicator
is using per. Let's say, for example,
we still want to see the blue indicator
on this chart. Therefore, we need to go to
settings of this indicator, and we rest on this gear. But xs parameters
of this indicator. As you see here
in the style pap, there are yclose indicators
and yclose two indicators. One is blue and other is orange. If we disable and hide
yclose two indicators, which is orange indicators, we expect to see the
blue indicator there. As you see whenever I
disabled the high close to. I can see that blue indicator
is still on the chart. These two indicators
are calculating the same values just
different ways. In summary, in this lesson, we have covered the basics of operators and expressions
in trading view by script. Understanding how to use
operators and expressions is essential step in creating effective and efficient scripts. By using operators
and expressions, we can perform calculations, compare values, and create complex conditions
in your script. This is the end of the lesson, and I will see you
in the next one.
6. Conditional Statements and Loops in TradingView Pine Script: Hell, welcome to this lesson. Conditional statements and loops in trading view, Pin script. This lesson consists
of following section, Introduction section
where I will overview conditional statements and loops in trading view, Pin script. In the next section, we'll
review conditional statements, the basic syntax and examples. In the next section, I will
explain loops in fine script, particularly type of
loops and examples. In the next section, I will
explain best practices, how to avoid infinite loops, and how to use
loops efficiently. In the last section, I will explain the importance of understanding
conditional statements and loops for creating effective and efficient
scripts. Let's begin. In trading view Pine
script version five, conditional statements
and loops are used to control the
flow of a script. Understanding how to use conditional statements
and loops is essential for creating effective
and efficient scripts. A conditional statement
is a statement that is executed only if
certain condition is met. The basic syntax for a conditional statement in
Pine script is as follows. If expression local
block, L z expression, another local block,
another local block, where parts that enclosed
in square brackets. This part can appear
zero or one time, and those enclosed in
the curly bracket, this can appear
zero or more times. Expression must be of bull type or be out
cust to that type, which is only possible for
integer of flowed values. Local blocks here,
here and here, consist of zero or
more statements followed by return value. It must be intended
by four spaces or at. There can be zero
or more clauses. This z clause with a local
log can be zero or more time. There can be 01
time else closes, this else and local block, it can be only 01 time. Let's review this
statement in Pine screen. In this example, if statement is using not to
return any value, because we do not have a
variable preceding if statement. It can return different
type of value, and there will be no error. In this statement,
which if close is bigger than open there are
certain statements executed, then he low statement
is returned. Then otherwise if
this condition is not true s clause will be executed. All statements in's
scope will be executed, and then one will be returned. In this case, the returning
value is not used, therefore, it could
be different type. However, if for example, we assign a value, returning from e statement. We get an error. Why? Because we return
different type of value, we return string in I
scope and we return one, which is in this scope. There should be one
type. How to fix that. For example, we could
return only integer. Then we get no error. In the next example, we assign to P variable, the return value from statement, I close big good and open, then return close,
otherwise, return open. Now let's review how if
statement works with condition. This example, we have and
condition if C less than two, then this statement
will be executed. Otherwise, L, this
condition is true, then this statement
will be executed. If none of the two condition, not this one and not this one is if both of them are false, then this statement
will be executed. If statement could have zero
or more else if statement. This is how if statement
works with else if condition. Now, let's review
how loops work. A loop is a block of code that is repeated a
certain number of times. Pin script supports
several types of loops, including follow. Let's review four loop. Holop is a loop that is executed specific
number of times. Syntax of this statement
is as follows. R declaration equal four counter equal from number two to
number by step number. Number of statements
continue or break aparators, and then return expression. Where R declaration, an optional variable
declaration that will be assigned the value of the
Loops return expression, counter a variable holding the value of the loops counter, which is incremented,
decremented by one or by step number value and
each iteration of the loop. If step number is present, it will be incremented
decremented by step number. Otherwise, by default,
step number is one. From number, the starting
value of the counter. Integer of float values,
expressions are allowed. Two number, the end
value of the counter. From number, starting
value of this counter, two number is the end
value for this counter. Step number, the increment value of the counter, it's optional. The default value is one. It must be positive, depending on what value is
from number or two number, the step will be added or
subtracted to and from number. In other words, If from number
is less than two number, then counter will be
incremented by step number. Otherwise, it will be
decremented by this step number. Statements continue break. I can have any number
of statements, or or break the words, and all this has
to be intended by four spaces or
Return expression, the loops return value, which is assigned
to the variable in R de if one is present. This value return expression
will be assigned to declaration after
all these statements are executed in the scope
of the statement for. If it's not present, the return expression
simply will be ignored. If the loop exits because of
continuum or break keyword. The loop's return
value is that of the last variable assigned to the value before
the loop exit. Continue a keyword that
can only be used in loops, it causes the next iteration
of the loop to be executed. Break a keyword that
exits the loop. Let's review this statement
in the final script code. In this example, we have a fool loop that
has starting value, zero ending value
for this i counter, nine and by step number is one. This statement in the scope of four operator will be
executed ten times 0-9, and will be every time I counter will be
incremented by one. In case, for example, we do not specify
the step number. The fs statement will be executed the same number of
times ten because by default, step number is one. Now, let's for example, we want to start from
nine until zero. Now, first, value of i counter in this four
statement will be nine. The next value will
be eight, et cetera, because start number is
bigger than two number, nine is bigger than zero. Then every time the counter
will be decremented by one. It's going to start from
nine after that eight, et cetera up till zero
in total ten times. This is how four
statement is used. Now let's review
another type of lo. Which is while loop, while loop is a loop that is executed while a certain
condition is true. The syntax of while
statement is as follows. Variable declaration
equal while bing expression statements
or continue or break and then
return expression. Variable declaration, an
optional variable declaration, It's an optional parameter. The return expression
can provide the initialization
value of this variable. If variable declaration
is present, then after this while
statement is executed, return expression will be assigned to variable
declaration. Bull and expression when true, the local block of while
statement is executed, this is local block,
number of statements or continue or break operator. When false execution of the script resumes
after while statement. In other words, these statements and while statement will be executed until Bolen
expression is false. These statements will
not be executed at all if when we start
executing while operation, while statement, Bolen
expression is already false. Then the statements are not
going to be executed at all. Continue. Continue
is the keyword causes the loop to branch
to its next iteration. In other words, we start
the while executing while. Bolen expression is
true, then statements. If we have statements,
they will be executed. Then if another statement in this sequence of statements
will be continue, then another iteration
will be executed. It will go back to the while statement
and Bullen expression will be checked again. The remaining statements after
continue will be ignored. Break the breaky word causes
the loop to terminate. The script execution resumes
after the while statement. I now if part of the
statement is break, entire while statement
is going to break and the execution of the program will start right after while. Return expression, and optional. An optional line
that is providing the wile statement
returning value. Let's review this while
statement in Pines cryptic. Here in this example,
we have statement, then we have a condition
y bigger than zero, and we have a statement. Y reassign value, y minus one. Before while statement, we
declared an initialized y25. Then we check in le statement
if y is bigger than zero. Yes, it is bigger than the zero. Then we decrement y by one, every iteration of the loop. This loop is going to be iterated five times while
this condition is true. When this condition is false, the while statement
will terminate. This is how you use while s. It's important to keep
in mind that using too many loops on estate loops can cause
the script to slow down. It's also essential
to break the loop when conditions are met
to avoid infinite loops. In summary, in this lesson, we have covered the basics of conditional statements and loops in trading view pine script. Understanding how to use
conditional statements and loops is essential step in creating effective
and efficient script. By using conditional
statements and loops, you can control the flow of a script and perform
repetitive tasks. This is the end of the lesson, and I'll see you
in the next one.
7. How to Create and Customize Moving Average Indicator in Pine Script: Colon, welcome to this lesson, how to create and customize moving average indicator in
trading view pine scape. This lesson consists
of following sections. In introduction
section, I will review the moving average
indicator and we will explain how to use it in
trading view pine scape. In the next section,
I will create moving average indicator
using t a dot SMA function. In the next section,
I will explain different types of moving
average indicators. For example, we're going to create moving average
indicator using t dot MA function to calculate exponential
moving average indicator. In the next section, I will demonstrate
how to customize appearance of moving average
by change its color, line width, and style. The next section, I will explain best practices of how to choose proper number of period for
moving average indicator. In the last section, I will
point out importance of understanding how to
create and customize moving average indicator
in trading via in script. So let's begin. The moving average indicator is a popular technical
indicator that is used to smooth out price fluctuations,
and identify trends. In trading view Pine script, you can create and customize your moving average indicator using built in the SMA function. Let's create an indicator and create a script that will calculate simple moving
average indicator. You create new indicator, you can click on Open
button after that, click on indicator menu. Now, et's give a name
to our indicator. First parameter
indicator function that is the script name. Let's give it a proper name. We're going to calculate moving average indicators in this, therefore, let's
name it indicator. And there another
important parameter here that we're going
to use is overlay. Overlay parameter is the
parameter that decides where to plot the indicator on the chart or the pine
below the chart. This is moving
average indicators, therefore, we want to
plot them on the chart. Therefore overlay should be true by default
overlay is false. Now, to calculate and plot
simple moving average, so let's declare the variable, and then let's use the TA dot SMA function to calculate simple moving average indicator. As a source for this function, let's use close price. As a length or period for this, function, let's use
for example 20. Therefore, after we calculated the simple moving
average, we can plot it. Let's plot it. In plot function, first
parameter is the ser. We plotting simple
moving average s. The next parameter is the title. Let's give it a proper title. It's simple moving
average indicator. Therefore, let's use S A. Title. Next parameter color,
let's give it a color. Colors are there are pre existing colors that
in color name space. Let's choose a
color. For example, I'm interested in blue color. Next parameter is
lined linewidth. Let's say, for
example, by default, line width is one, if I want to make it
thicker, the line. I'll use some bigger
number like a two. Next parameter is a style. As you see, there
are different styles over here that we can use. Let's say I want to
use the line style. To do that, this type plot. After that, we click on the point and we can choose
the available styles here. For example, line. Now,
let's say I indicated. Let's confirm the
name, this script. After we save it, we need to add this indicator to the chart. Let's click on this button
to add it to the chart. As you see it plotted, our simple moving
average indicator. Also, let's talk a little
about the parameters. As a parameter for this
calculation moving average, we could use any serias. For example, we could use
high low or open prices. For the period, we could
choose different period. If we chose, for example, smaller period, it will
follow the price closely. Let's, for example, choose
the period of five and save. It's following the price closer. Let's choose another period
bigger 50 in this case. When you choose bigger period, it's smoothing the
changes of the price. Now, there are different
types of moving averages. There are different
built in functions in trading view that you can use to calculate different types
of moving averages. For example, let's calculate exponential moving
average indicator. To do that quickly,
we can copy and paste existing two lines and
then just change do some minor changes to
these lines in order to calculate and plot exponential
moving average indicator. It's going to be MA variable. Then I name space, there are exponential
moving average fun. And so we're going to use it to calculate
exponential moving average. After that, for the source, let's use, for example, high of the price. After that, let's specify a
length, for example, ten. After that, let's plot
this A that we calculated. Let's change it to the
proper title, which is MA. We wanted to have
different color. Let's choose, for example, P and the line width, let's make it thicker three, and let's use different plot. We use line, we specify plot, dot, and after that,
let's choose different. Style. For example,
circles and save. As you see, we just plotted foot share color indicator
with the style circle. Now, let's calculate and plot another type
of moving average, which is weighted
moving average. We just scope and paste these
two lines and we'll just change appropriately
what we need to change. We change the
variable name to WA. It's going to be
weighted moving average. After that, let's select. Weighted moving
average function. Let's use for example, low low of the bar to calculate this
weighted moving average, and the length length
to be 100 for example. Let's paste this calculated weighted moving average
to this plot function. Let's change
appropriately the title for that weighted
moving average. We need to change the color
some color, for example, let's use the line with I want it to be thicker four
and the style plot dot, and that's choose
different style. Example, step line. T's say we calculated weighted moving average and
we plotted it with the green color and
step line style. Now, I demonstrated how to create different types
of moving average, and also we used different seras to calculate this moving average
and different periods. In summary, In this lesson, we have covered the basics of
how to create and customize moving average indicator in trading view pine script by
using the built in T dot SMA, T dot EMA, and TA dot WMA functions and customizing the appearance
and type of moving averages. We can create moving
average indicator that suits your specific
needs and preferences. This is the end of the lesson, and I'll see you in the next p.
8. How to Create and Customize Bollinger Bands Indicator in Pine Script: Holl on, welcome to this lesson, how to create and customize olnger bands indicator and
trading view pine script. This lesson consists
of following sections. In introduction
section, I will review Bollinger Bands indicator and its use in trading
view pine script. In the next section, I
will explain how to create Bollinger bands indicator
using KB function. In the next section,
I will explain how to customize appearance of
Bollinger bands indicator. In the next section, I will explain different types
of moving averages to construct banger bands
indicators such as weighted moving average and
exponential moving average. In the next section, I will
explain best practices, how to choose right number of periods and standard deviations when you set up anger
bands indicator. In conclusion, I will point out importance of
understanding how to create and customize
anger bands indicator in trading view by script. So let's begin. The Bolinger bands is a popular technical
indicator that is used to measure volatility and identify potential overbought and
oversold conditions. In trading PI script, you can create and customize your own bolder bands indicator
using TA BB function. The basic syntax of this
function is as follows, A BB, and in braces, you specify three parameters, series, period, and
standard deviation. Where series is a data series, you want to calculate
the ballinger bands for, for example, close,
open, high or low. Period is a number of data points used to
calculate booling bands, and standard deviation
is a number of standard deviations used to calculate the upper
and lower bands. Standard deviation is a statistical measure
of market volatility measuring how wildly prices are dispersed from
the average price. For example, the following code creates Bollinger
bands indicator for closing price using period
of 22 standard deviation. In this case, we use tab function to calculate
banger bands indicator. By default, tAB function
returns three lines. The simple moving average. The upper band and lower band. Simple average as a middle, upper band and lower band. This collection of
values is called tuple. A.bb returns tuple that
consists of three values. Simple moving average,
upper band, and lower band. You can customize the
banger bands indicator by using different types
of moving averages, such as weighted moving average, exponential moving
average, and many more. For example, the
following indicator calculates moving average from weighted moving average with the period of 20
from closed price, and 20 period for banger bands and two
standard deviations. It is important to
note that number of periods and standard
deviations you choose for ballinger bands will have an impact on sensitivity
of the indicator. A shorter period and
higher number of standard deviations will result in a more responsitive
ballinger bands. While a longer period and a lower number of
standard deviations will produce smoother results. Also, we could customize the Bolinger bands
indicator by specifying color when we plot middle
line upper and lower bands. We set color and
we assign color to the color that we need. Now, let's take a look how to create Bolinger bands
indicator in pine. Three. You create indicator, you open on click on open button after
that, click an indicator. Now, let's name our indicator. This is going to be a custom
ballinger bands indicator. Cast and bulg bands. Now, this indicator, we want
overlay parameter to be true because we want to overlay the indicator
on the main chart. Otherwise, it would be plotted on the pane
below the chart. Now, let's use a tAB function
to calculate the middle, upper and lower band
of the bulger band. Now we're going to
start doing that by specifying the tuple
from three values. B middle. BB upper and the lower. Now, we specify the
tuple after that. We'll use the t BB. Function and we specify series. Let's say we want to use
close price as a series. But you could use high low or any other
series if you need to. Close, after that, we specify period of data points that we want this indicator to be calculated 20 and number of standard deviations,
let's use two. Now, we calculated middle, p, and lower bands for this
ballinger band indicator. Now let's plot all these lines. Let's plot start
from middle line. Middle. After that,
we specify the title. Let's use the same title
as the variable name. Let's specify a color. For example, blue. Now, let's plot other lines for this bonder band indicator. Per line, per line, let's choose another
color, for example, and for the lower Band, let's use the same color, F and let's plot the lower band as well. Now we finished plotting. We don't need to
flot close anymore. Now let's save it. Let's confer the name
custom bloger band. The name is looks okay. After we saved, we need to add this script that we have
developed to the chart. Right? So now we can see that
the middle line is blue, and upper and lower
lines have color. Now, let's just change the period and the standard deviation to see how it affects the plotting
the indicator. As I pointed out earlier, a shorter period and a higher number of
standard deviations will result more
responsive bolder bands, a shorter period like ten and
higher standard deviation. Three. Will result more
responsitive banger bands. Became more responsitive.
For example, if let's set it to five. The boolinger bands are closer to the price
and more responsitive. Now, let's return to 22. Those values are usually used as default values for
boolinger bands. Now, let's modify this
boolinger band indicator and use weighted moving average
to calculate boolinger bands. To do that, we will use t WA. Function to calculate the
weighted moving average, and we're going to use the
result of that calculation as a serious parameter for
this ballinger band. So TWA, we'll use close
price and period of 20. Now what we did is that we calculated weighted moving
average from close price with the period of 20 and using this result of calculation
of weighted moving average as a data source
for our ballinger band. Let's say the Bollinger bands looks different now
because we used weighted moving average
as a data source for our boolinger
band indicator. So now, I demonstrated how to create bonder band indicator, and how to use weighted moving average to create
bonder band indicator. In summary, in this lesson, we have covered basics, how to create and customize
bonder bands indicator in trading view pine script by using built in the BB function, and customizing appearance
and type of moving averages, and the number of periods
and standard deviations. You can create banger
bands indicator that suits your specific
needs and preferences. This is the end of the lesson, and I'll see you
in the next one. A.
9. Creating, Backtesting and Optimizing Strategy using RSI Indicator: Alone, welcome to this lesson,
creating custom strategy, using a sign indicator
and back testing it using Pine script editor in
Trading view Pine script. This lesson consists
of following section. In introduction
section, I will review custom strategy creation and back testing in trading
view Pine script. Also, I will point
out importance of back testing in evaluating
trading strategy performance. After that, I will be
creating a custom strategy. I will use strategy function
to create a strategy, and I will demonstrate
in the example. Process of creation,
custom trading strategy using RSI indicator. After that, I will
start back testing, the strategy, and I will use built in back testing
feature in trading view. After that, I will be setting up certain parameters for back
testing such as date range, RSI period, and others. Also, I will be evaluating the strategy performance
using metrics, such as net profit
and sharp ratio. In conclusion, I will point out the importance of considering
limitations of b testing, such as survivorship, bills, and market condition change. I will reiterate of the benefits of ba
testing in identifying potential issues or areas for improvement in trading
str. Let's begin. In trading view Pine script, you can create custom strategies
and back test them using historical market data to evaluate the performance
of trading strategy. Back testing allows you to simulate how strategy
would have performed in the past and can
help you identify potential issues or areas for improvement before putting
real money on the line. In this lesson, I'm
going to create a custom strategy that
is going to generate by signal when a sie
indicator is below level of 30 and sell signal when
si indicator is above 70. Let's begin. To start custom
strategy creation, we go to Pine editor, and then we click on O pen
and create new strategy. After that, we are going to use strategy function to specify certain important parameters
for this strategy. Let's begin. First of all, let's set
up the strategy name. This is going to be
a custom I strategy. Let's name it this way.
Customer strategy. Next, overlay overlay, we need to set it to files
because our sign indicator that we are going to
plot is going to be plotted on the pane below
where the main chart is. Therefore, this parameter
should be filed. Next. Next parameter, let's set
the default quantity type. Default quantity
type, we need to set, which we'll let the strategy know of how much we are going to trade
for certain transaction, how much from our
entire balance. Let's set up that parameter. So default quantity type. Default quantity type, and let's set it up to str
percent of equity. Strategy do percent of equity. What it means that for
every trading signal, we are going to trade
certain percent of available balance
in our strategy. Now let's set the
default quantity value, what percent of our balance we are going to trade
for every trade. For that for that value, there is another parameter, which is called default
quantity value, quantity value, and let
it be equal to 100. Meaning that 100% of
all available balance, we are going to trade
in every trade. It could be less than a 100. Of course. Next parameter
is initial capital. Initial capital,
so let's say $100. We want this strategy
when we back tested to produce
realistic results. Therefore, we need to
consider commissions. So let's set up the
commission parameter. Let's set up Commission type. Ci commission type, let's set up the percent of the
trade position. Commission type equal
strategy Commission. Emission percent. We need to set up what percent? We need to set up
commission value. Emission value.
Let's set it to 0.1. It means that 0.1% will be de from the transaction amount. Now, let's set up and configure other parameters
for this strategy. We use RSI indicator
in this strategy. Therefore, we need to specify parameters for our
RSI indicator. RSI indicator has
following parameters, period, and over both
level and overs level. Let's set up this parameters. First, RS period. RS period. It will be obviously
period of RSI indicator, and it's going to be
input integer parameter. Input type of int, then we specify
the name or title. Title will be RS period. Also, let's specify
the default value, which is going to be 14. Next two parameters
that we need to set up for RSI indicator in this strategy is RSI
oversold, and RSI overbought. These are the levels
where we are going to trade buy and sell when
RSI reaches this level. This parameter should be configurable because
we are going to change them when we optimize the parameters for a certain
financial instrument. RSI oversold. Rsa salt, also it's an integer parameter, solt and default is 30. Usually salt value for
RSI indicator is 30. Now, Rs overbot,
another parameter. Rs overbought. Let's specify the proper title. And proper default value
usually RSI is 70. Now, we specified the parameters for this RSI indicator
that we are going to use. Now in str, calculate the
RSI value the parameters. So RSI value. Will be equal to, and now let's use the function T dot RSI to calculate
our RS indicator value. TA it's a name space for a lot of technical
analysis function. Dot RSI. Now, in this function, First parameter, sours,
we're going to use the close price of the
financial instrument, and after that, we need to
specify the length or in other words period for
this RS calculations. We have a parameter
for that RS period. We calculated this RS value. Next, let's specify the
conditions under which we are going to perform the BI trade. We're going to buy whenever R value is below RSI bot level. Let's do that. If RSI value below RS sold. Then we are going to
enter new position. We're going to buy a
financial instrument that we are going to apply
this transaction on. To do that, we're going to
use the str dot function. After that as a parameter, we're going to specify
ID of this trade. Let's use it by as
an ID by string. After that, we need to
specify the direction. Long, str long. We're going to go long, we're going to buy whenever
this condition is true. Next, when do we sell? We sell when I value is
above over bot level. Let's copy to do it faster. Whenever is above overbt level. Then we are going to close a side dot close and we need to specify the ID of the
trade when we bought it. This is referencing
to this trade when we bought it and
we close that position. After that, let's specify and plot the actual RSI indicator. It's going to help
us to visualize the trait and the refilm. To do that, let's
plot the Si value on the pain below the main chart. To do that, we're going
to use the plot function. Plot, and then we specify
series, in this case, it's raci value,
then plot name, Ri. After that, let's specify the
color, for example, green. Color green. We plotting si value, we gave to that plot name, and the color of that
plot will be green. Now, also, when p, we need to Plot three additional
lines usually. The middle line, the bot line, and the salt line.
Let's plot them. To do that, we're going
to use the line function, which is a horizontal
line function. H line, and after that, we specify first
the value at which it's going to be
plotted the name, 50 is right in the middle. I fluctuates 0-100,
50 is in the middle. First, we draw the middle line. Middle line. Then we could specify the color and we could specify the type
of line. Let's do that. Middle line, let's
set it as a gray, and by default, it will be d, but I want in this plot, the middle line to be solid. Let's specify the
solid line type. It's going to be H line, style. He is solid. And let's plot the
other two lines. Next one, will be asi over bot. Overbought. This is
our overbought line. And we don't need slid, we need to be dashed, and the color will be red
because it's overbought. We need to sell it ally. Here, the last horizontal
line will be oversold. Sold. Let's specify
the proper title for that line and
the proper color. Color, let's set it
for example green. Now we finished the main
code for this strategy. Let's save it. Customer size
strategy will keep the name. Now, after we saved it, let's add it to the
chart using this bt. We added this strategy to the chart and we
can see on the chart buy and sell transactions
already buy and sell trades. And we see also these
trades over here. They start from 2015, when we trade on the currency, when ether first
appeared on the market. And we have 12 trades. What else do we see here? We see on this chart that
equity is in green, blue line, how equity performs if
you just bought and held it, and draw downs. Let's remove the draw downs. We don't need them
at the moment. Now, Let's say I don't want to optimize the strategy for the
entire period from 2015. I want to optimize
the strategy on the last three years,
for example, that, we would need to add parameters that would limit the
dates when we can trade. Do that. We will have a start date and we are going to going to
allow to trade only between This date. To do that, we're going to need to add
another six parameters. For start date, it's
going to be a start day, month and year,
and for end date, it's going to be three another
parameters for the day, month and year,
for the end date. Let's do that. Start day is going to be all of them are going
to be integer parameter. Input start input in so now default value will be one for the
day for the date and the title start Day. Start day. This is the start day, let's set up another
three for start month. Month. Let's keep it
to one and start year. If you notice what I'm doing
often that I'm copying and pasting part of the
text to type faster. In this example, I just
selected this text, clicked control C to copy it and went in this position and
just selected and pasted it. This way, I just type faster. Now, we have set up all the
parameters of the start date. Now let's do that for the end. So it's going to
be almost the same but with end graphics here. Let's replace the
starts for end. For the year, we need to
set the proper years. Let's set it 2010, and for the end. Let's set it to some
future date, 25. Now we have we have set all the parameters
for the start date. Date. Now, let's use these parameters to
calculate actually the valid period in
order to compare current time in the chart
to these parameters. We need to calculate
the time stem, which is going to be a time certain time D is going to use these
parameters. Let's do that. Time start, and we're going
to use time stamp function. This function returns
the unix time or specified date in time. View it it like a certain date, there is a certain value, and that value is calculated using parameters that
we already have set. It starts from year, then month, the date. Then we need to start from
this year, then month. Then and we also need to specify the hour and minute, zero, zero. T star, the same
idea for the end. We will replace all the
starts here for end And we calculate the start
and then so let's save it. I just saved it or find no
error, so let's continue. Now, let's create
the custom function in this strategy that is going to if the current time of the str is within the range between start time
start and time end, which we just calculated. To do that, so let's create
the custom function. The create custom function, let's set name of that function. For example, is time enabled. Is time enabled, and
then for the function, we use this error, this error to specify that this is going
to be a function. And then we use the tap, t, and then we specify the
code for that function. Here we'll specify
the condition. Current time of the strategy
must be more equal, equal to the time
start time start, and time must be equal to time and and if this
condition is true, then we are going to return
true, otherwise fils. We're going to use this function that when we need to
decide in our strategy, if we allow the strategy
to trade or not. Now, let's use this function and put it over here
in this condition. We're going to add additional
condition when we allow to trade when we allow in this example to
enter a new position. So, time must be enabled in order for us to
allow the strategy to trade, and same over here. When we exit, we will check
if time is enabled as well. Let's say it. We saved it. Now, let's check the parameters
of the strategy. To check the parameters
of the strategy, we go and click on this gear
button of our size strategy. We can see all the
parameters here, and let's just test them. Now, let's take a look
at the str tester, we have 12 trades, and we see that strategy starts to trade from
2015 and until 2023. So let's change the period of the allowed traits
for this strategy. Let's set, for example,
start year 2018. Now we can see that
trades started from 2018. This is an example how
to use and how to set up valid range for the
trades in the strategy. Now, Let's try to optimize the strategy and to make a better performance for the strategy for
this instrument. What do you mean
better performance? I mean that I would expect
the strategy to trade with higher profit than
comparing to just buy and hold. What does that mean? If
you go to performance str, let f 2010, and entire period whenever
this instrument is available. If you go to
performance summary, we can see that
current net profit of these strategies using the default parameters
is only 350%. By buy and hold is 182,000%. If we can make this strategy trade with the higher
return than buy and hold, then it makes sense to trade it. Otherwise, you would
rather just buy And hold this
financial instrument and without any trading. So let's try to change
this parameter and see if we can optimize
these parameters that way, so the profit of that strategy would be higher than
buy and hold return. The blue line here
as you see here, is the buy and hold equity. The green line is our equity of our strategy
is how strategy performs, how much money strategy made. Our goal now is to make the net profit of a strategy is to make it
higher than buy and hold. In this strategy, we have
three parameters to optimize, a recipe, a recip bot, and versalt, and si overboat. Whenever you
optimize parameters, you try to optimize parameters
one by one. In circle. That means that you optimize
first first parameter, and try to find the
highest net profit if you optimize
it on net profit. Then start changing
second parameter with the same goal to find
the highest net profit v, then third, after
you finish third, then you go for another round
of changes cero, recibo. After that, you keep doing this cycles until you can
no longer optimize it. Now only after that,
you can say that you tried different values, you've been optimizing it in several cycles and
you did not find any parameters to
increase the net profit. In that case, optimization
is completed, and you would see if you achieved better net
profit than in this case, equity buying hold return. Let's do that. As you
see here, we have 350, Let's keep changing
higher and lower recipiod and to see if we
can get better returns. To do that, you can just press on these buttons up and down, or you could just
point leave the cursor here and press arrows
on the keyboard. Arrow up, and arrow down. I usually press the keys on
keyboard because it's faster. We change it higher. It's 35419. 48, 62, 310. We had here, as you see, highest was 419 for 15. Let's go down and see if
we can achieve anything below hundred and 2065. The highest was over
here in 151519, next, i over sold. Let's go higher. We have two. 609-87-6406. We have here 876 or 876. Let's check the lower. If we can get more than that. No, we cannot get
more than that. Then 800 with something was our highest
value. This one, 876. Next parameter. 876 is our highest net profit that we could get by optimizing
first two parameters. Now let's optimize
the parameter. Let's go higher. One. We got 921. We got 162, 1040, 2000 702,800. Now they're not increasing here. Now let's check what parameter was there when we got
the highest value. So two. So this value. 86 is highest, but let's
check below 786 is high. 79. Nine. You always want to make
sure that you tested above the val current value and below the current value
of the parameter. We're not getting the better
values here obviously. 86. We already see that by
optimizing the first round. In the first round of
optimizing all the parameters, we achieved that net
profit is already 2800. Now let's do another one. Acid. We got 4,200. This is the highest.
4,200. Let's do this. 4,200. Okay, so we got we have 4,900
already 52 52, right? Okay. So we have 88708909400715015951 61,000 61,300. Now it's dropping.
Let's keep it 70. 70 and let's change this
61,000 121,000 hundred 93. 158, 202 207. Now it's dropping again, then the 90 is optimal. If we go below, now it's dropping here. So 90, looks like 90 is the best parameter
here. Let's check this out. Our period. Let's go another cycle of
optimizing the parameters. So so it's dropping from 2000. We start from from 207,000%. If we go down, it's dropping. Now when you go up higher, it's dropping too, then
this 11 is optimal. Now 12 is optimal. This It does not change much. Then we'll keep it. If you change the parameter
and values do not change, just keep the old
one keep the old v. We change it. We change
it for less values, is dropping, we change it for higher values,
it's dropping. It means that we found the
optimal parameters for this strategy that gives
us the highest return, which is two 207%. Let's check the performance. Our str produces the return
207,000 approximately, the buy and hold is 140,000. So we made it 50% return higher by using the strategy
higher than buy and hold. It means that this strategy
appears to be beneficial. Now, let's review the other
parameters of the strategy. When you optimize the
strategy, normally, Net profit is very important, but you need to keep an eye
on other parameters as well. All these parameters
are important. Some of them a bit higher
have higher importance, some of them less importance. For example, next parameter, which I normally look at
is the profit factor. Profit factor is the parameter that basically here
is full explanation. This is the amount of
money the strategy made for every unit
of money it lost. Gross profit is
divided by gross loss. Means, for example, if
profit factory is two, it means that for
every lost dollar, you made $2. That's
what it means. The higher value the better. Normally, I look for this value
to be at least above two. In this strategy, it's
one, which is great. Next, very important
Mx drawdown. We get 69% drawdown, which is pretty high drawdown. However, this theorem
cryptocurrency is very volatile and its drawdown for that
cryptocurrency would be 95% much higher
than this percent. We got this strategy. This cycurc, this financial
instrument is very volatile. We have average trad
for how much usually we How much is our
usual average profit, which is 210%
percent profitable, all of them 100% profitable and the total number of
trades is seven. In this lesson, to
summarize this lesson, I demonstrated how to create custom trading strategy using
just one RSI indicator. In the trading
strategies, normally, when you put money on the line, you will use probably
more than one indicator. Normally to make robust and
solid trading strategy, you would use more than one more than one financial
trading indicator. This is just an
example how you can create custom trading
strategy using only one. Indicator, and even
with one indicator, I demonstrated that
it is possible to generate profit higher
than buy and hold. This financial instrument. Remember that created strategy. There is no strategy that will be performing well
for every instrument. And there is no instrument that you can apply to it like any strategy
and it will work. When you develop strategy, we need to keep in mind for which instruments which
markets you're going to use. For example,
cryptocurrency are very volatile for certain types of strategies are good for them. Stocks les volatile. Many of stocks in ranging. They are arranging,
they go up, go down, go up, go down, they
are less trending. For those type of
financial instruments, some other types of strategy
will be beneficial. Now, to summarize this lesson, I want to say that it's
important to know that ba testing that we just did is not a guarantee
of future performance, is just a way to get an idea how a strategy would
have performed in the past. Also, it's important to consider the limitations
of back testing, such as survivorship bills, look ahead bills, and
market conditions change. In summary, this lesson
discussed how to create custom strategies and the bac test them using historical
market data in trading view. Back testing allows you to simulate how strategy
would have performed in the past and can
help you identify potential issues or areas for improvement before putting
real money on the line. An example of creating custom
strategy that generates a b signal when a SI is
below certain level, and to cell signal to generating
cell signal when thei is above certain level was
provided in this lesson. To back test the strategy, we can use built in back
testing feature in trading view that I just demonstrated by selecting the strategy
in the strategy tester, setting up back
testing parameters, such as a recipio, of a bot level and
a result level, and then running a back test. Then optimizing these
parameters one by one in certain rounds
of optimization to find the very best set of parameter values when this
strategy performs the best. Now, this is what have been
covered in this lesson, it's important to note that ba testing is not a guarantee
for performance and it has some limitations
and that you need to run certain tests and
even forward test tested not on real money before committing real
money on the str. This is the end of the lesson and I'll see you
in the next one.
10. Creating, Backtesting and Optimizing Strategy with Moving Averages: Alone, welcome to this lesson, creating a strategy based on two simple averages crossing and trading viewpoint script. This lesson consists
of following section. In introduction section, we're
going to overview creating a strategy based on two simple
moving average crossing in trading pine scrim. Then I will point
out the importance of using the strategy function. In the next section, we're going to define strategy function. We're going to use
strategy keyword to define the strategy function. Then we're going to set up
parameters strategy parameters for moving average al. After that, we're going to be calculating the moving
averages in our strategy. We're going to be using
TA dot SMA function to calculate the fast
and slow moving average. After that, I'm going to
demonstrate an example of evaluating 12 day and
26 day moving averages. In the next section,
we're going to generate by and cell signals. We're going to use if
and if statements to generate signals based on the intersection of
the moving averages. Then I'm going to demonstrate
an example of generating b signal and cell signal based on moving
averages, crossover. In the next section,
we're going to be visualizing the
strategy indicators. We're going to be drawing
the moving averages on the chart for visualization. And I'm going to demonstrate
an example of plotting the fast and slow moving
averages on the chart. In the next section, we're going to be back testing the strategy. We're going to be using built in back testing feature in trading view to
test the strategy. And then we're going to be
evaluating the performance of the strategy using built
in performance metrics, and we're going to be optimizing the strategy parameters
for better performance. Then the final
conclusion section, I'm going to summarize the creating strategy based on two simple moving
averages crossover, and I will point
out importance of back testing and evaluating the performance of the strategy. Let's begin. Rating view Pine script
is a powerful tool for creating custom indicators
and trading strategies. One popular strategy that
can be created using Pine script is moving
average crossover strategy, which generates buy and
sell signals based on the intersection of the two
simple moving averages. In this lesson, we will
go over the steps for creating a moving average
crossover strategy in trading view Pine Script. To start creating a strategy, let's go to Pin
Editor and click on Open Menu and New
Strategy Menu Option. After that, let's remove
this section from this default strategy that
we not going to need. And let's name our strategy. For example, like A
cross over strategy. After that, let's set
up the next parameters. Overlay will be true
because we're going to plot our moving averages within
this str on the main chart. After that, let's specify the other parameters of the str. Next parameter will be
default quantity type. Default quantity
type, Let's set it to strategy percent of equity. Percent of equity, meaning
that we're going to define the amount the amount of
balance that we're going to trade in each trade
as a percent of entire equity of our balance
of our trading account. Next parameter will be
default quantity value. Default quantity value
is going to be 100%, meaning that in each trade, we're going to trade
100% of our balance. Next, let's set initial capital. Initial capital, let's set
it to $100, for example. Next parameter, let's
set the commissions. We want our trades
to be realistic. Therefore, we need to
account emissions. Commission type commission type, let's set it to strategy
do Commission dot percent. Percent. The actual commission
value Commission value, let's set it to 0.1%, meaning that for the
Comision for every trade, we're going to deduct 0.1%
from each trade. Commission. Now, let's set the trade
range of our strategy. We're going to set this if
you want to, for example, to trade our strategy on
certain period of time, not for an entire period, whenever financial
instrument is available. For that purpose, let's
create the parameters to define start date of our str and end date
of our strategy. Within this range, our
strategy will be trading. So Let's set up set of
start date parameters. It's going to be start day, start months, let's start year. Start day, all these parameters
is going to be integer. Input in and let's
set the default value for the day as a one and the
title will be start day. Let's set the remaining
three parameters for the start date, start mouth. Let's update the
title and start year. Let's update this title to. For the year, let's set
the default year 2010. Let's set three similar
parameters for and the We have end day and month and end year, and let's update the titles
for these parameters. And day and month end year. For the end year,
d fall parameter, let's set it 2025. We have set the parameters related to the start
date and end date. Now, next parameter,
let's calculate now the actual time start and time using these parameters
that we just have set above. Tim start is going to be equal to return of a
function time state. And time stamp,
we're going to pass start year, month, and day. Year, month, and start two
remaining parameters for this function for
hours and minute, let's say to zero. We need this time start and
time end because we're going to use this integer
representation of a date in order to calculate, we're going to use
variables in our logic when we try to determine if the current time is
allowed to trade. Time end. For time end, we're going to use
n here, and mouth. And A. We calculate it time start time
time start and time. Now, let's create
the function that is going to return
the bulion value, and we're going to
use that function in our trading logic below. I time enable is time
enables power trade. Let's create a custom
function and to do that, we will use this arrow symbol and after that,
let's specify the Logic that is going to use the time start and time
and we just calculated. We're going to be checking
the current time. If it's current time
is bigger or equal to time start and current time is less or equal to
time and in that case, we want this function to
return true, otherwise pulse. This function is
completed, and after that, let's calculate the let's set up parameters for our fast
moving average period and slow moving average period. Faster M is going to be integer parameter
and default wheel, let's say it 212. After that, let's specify
the title pasta period. Minimum value, let's set 21, maximum value 200 and
step, let's set 25. After that, Let's
correct this function. After that, let's set
up slow parameter. For that, let's set
default value 26. Let's correct the
title, slow MA period. We have set the parameters for past MA period and
for slow MA period. Next, let's set another
parameter called trade type. This parameter is going
to be a string parameter. We're going to use trade type to define what type of trade our
strategy is going to take. Long, short, or long and short. Let's have a title trade type. Title trade type, and then default value default
value. Long and short. After that, let's
specify the options. Option parameter, we have a list of all available options
for this string setting. The options we have
following parameters long and long. And short. We have set this
trade type parameter. By using this parameter, we can set our strategy to trade only long positions or to trade only short position or to
trade both long and short. Now, let's calculate the moving average and
slow moving average value based on the input parameters for fast and slow
moving average. Fast value will be calculated using TA SMA function that is calculating
simple moving average, and we're going to pass as a source close price
as a parameter length, we'll use fast MA. And the same for
the slow MI value. Except just we're going to
use the slow MA parameter to calculate slow MI value. Now, let's develop the logic when we going to open the
trade in this strategy. First of all, we need to check if strategy
is allowed to trade. In order to do that,
we already have developed the function
is time enabled. After that, let's check the
main strategy condition. We want to open long
positions when they are allowed whenever fast MA
crosses above slow MA. Let's write this logic. If bigger than slow value. But our strategy can
trade long and shorts. I case when our strategy is
not allowed to trade long, we need to check if
shorts are allowed, then cover the short position. We need to add more conditions because we have a trade type. Let's check if long
trades are allowed. To do that, we need to check if trade type not equal to Short. When trade type is not equal to short meaning longs are allowed. When trade type is
not equal to short, meaning that trade type equal
to long or long and short. In these two cases,
longs are allowed. Therefore, here, we
can open long trade. Strategy entry, and the ID will belong, and the trade type will belong. Now, otherwise, when type is, we're going to cover
short position. We're going to close
short position if short position is open. Then to do that, we're
going to add condition else if strategy dot position
size less than zero. Meaning short trade is open. Only in that case, we're
going to so called cover short position or
close short position. To do that, we're going to
use strategy dot close, and the position ID, which is going to
be s in this case. Strategy position size indicate the current position size. If it's less than zero, it means that we have
opened short position. If it's bigger than zero, it means that we have currently
opened long position. Short position is
the position when you generate profit when you get profit whenever
financial instrument goes down after you
initiated the trade. No. Let's the condition when we want to open
the short traits. It's going to be similar
to this set of commands. Therefore, we can simply
copy them and rag them. Another condition will be the opposite condition
will be less. Then slow MA, meaning that fast moving average crosses below crosses under slow MA. Then we might open
the short position, but we need to change
this logic over here. Then we're going to first,
what we're going to do, we need to check if
shorts are allowed. Shorts are allowed, whenever trade type is not equal to long. Because when trade type
is not equal to long, meaning that trade type equals to short or
long and short. In these two cases, shorts
are allowed. In that case, We can open short position, and we need to
correct this as well. Otherwise, when
position is long, meaning strategy position
size is bigger than zero. We're going to need to close our long Our logic generating bi
cell signals is completed. Now, let's plot the moving
averages on the chart. To do that, we're going
to use lot function. Lot fast MA value. Title will be fast MA. After that, we can
set up the color. Color, for example, blue, and the line width of the of the plotting
line, L sub two. Similar similar command will
use for to plot slow vue. Let's the parameter. Flow. We'll use different color. Let's use M color to
plot this slow moving. Now let's save the strategy. Let's keep this script name, and let's add it to the. Now let's analyze
how strategy trades. First of all, let's verify if the strategy is executing
trades as we expect. Blue line is the
fast moving average. Maron line is the
slow moving average. Whenever fast moving
average crosses above, the slow moving average, we initiate the long
trade works correct here. When opposite happens, when
FastA crosses under slow MA, then short position opens. It behaves as we expect. Now, let's check the
other parameters. Let's check how our strategy works for different
trade ranges. If our parameters
are actually working parameters that defined start and end date of this strategy. In order to do that, let's
check the parameters. We have from 2010 until 2025, dates within which strategy
is allowed to trade. Now let's check the
list of trades. We can see that strategy
starts to trade from 2011, and until time 2023. Let's limit the period of period when strategy
is allowed to trade. For example, from 2015. Now, let's see when
strategy started to trade. Started to trade
from 2015 until now. Our range is defining when the strategy is
actually allowed to trade. Now, let's check the metric performance
matrix or our strategy. We can see that in
the blue line is the buy and hold equity curve, green line is our
performance equity. Can see that buy and hold return is essentially higher than
our strategy perform return. It means that this
strategy needs improvements in order
to be tradeable in order to generate return
bigger than buy and hold. Buy and hold is when is the performance when
we just bought at the beginning of when this
strategy starts to trade, we just bought the
financial instrument. Entire account balance and just held this position till the end. Our goal is to update the strategy,
change the parameters. The performance of the
strategy is better. The return is higher
than buy and Hall. Then that str would
make sense to trade. In order to do that, let's try to optimize
parameters strategy. We have three
parameters to optimize. Fast may period, slow may
period, and trade type. Let's focus on these
two parameters first and change them. And keep an eye on net profit, profit factor and MCs draw down. Our goal is to make net
profit as as high as possible and make
profit factor at least bigger than two and make Ms draw down as small as possible. L et's change this to 2010, and let's start for
example, from slow period. The step of this
parameter is five. Therefore, when I change
this parameter by pressing arrows up and
down on the keyboard. It changes by five. We have 100,361.6
million, 1.7 million, 6.2 million net profit, 6.2 million% net profit. Now 600 100,000. 46 was the best.
Now let's check. Let's try to change
this fast MA period. So let's Increase it. Now, it's reducing. The net profit is reducing. Let's change it in
opposite direction, 4.8 million or 12 is optimal. Now let's check it by one, because we've been
changing it by five with the step by five
now, let's change it by one. 4.3, foe, two s. Let's
change it to 11. 3.2 million t 2.3 million. 12 is optimal because 12
gives us 6.2 million% return. 46, let's try 47.5. Eight 2.8. 46 was better, but let's try less
smaller than 46, 45, 2.1 and 44.3. We've been changing sequentially faster
ma period and slow ma period to find the optimal
parameters that would generate for the
highest net profit. However, profit factor is 1.4, which is less than
minimum desirable 2.0, and drawdown is pretty high. Draw down is $47 million and
net profit is $62 million. Draw down is high. However, we see that the strategy return is
higher than Bin Hall. Green line is than blue line. Also we can check the
statistics over here. In performance summary,
We can see that bind hold is 2.6 million
sorry bind hold is 867,000%, but net profit of the strategy is 6.2
million%, much higher. Now, what can we do to make? What can we else do to try
to improve the strategy? So it has less risk, but it's going to have
less risk when we increase profit factor and
decrease the max draw down. We have one more
parameter to try to optimize long and short. Let's try short for example. To take only short. We can see that only
26% short straight, short trades are not
beneficial for us. But let's try on long trades. We can see that now it
makes less return 4.8. However, profit factor
is bigger than 2.0, and Max down is
essentially less. It means that This
strategy has less risk. Draw down is less profit
factor is higher. However, it makes
less money 4.8. It's always about
when you try to find optimal set of
parameters for the strategy. When you're optimizing
the strategy, you need to try the correct
balance by optimizing it to get the highest
possible net profit with the acceptable profit
factor and Mx draw down. These parameters are
more acceptable. I consider because they have for factories bigger than 2.0. Meaning for every dollar lost, you make 2.3 dollar. You have bigger In case strategy performs not as well as you just optimize in case of when
strategy performs poorly. We completed optimizing
this strategy and Summarizing this lesson, I want to say that we discussed in this
lesson how to create a strategy in trading
U pine script based on crossing of two
simple moving averages. The strategy uses the built in function str to define
the entry and exit rules, two moving average indicators calculated using T SMA function. I provided the full strategy
code example for calculating the moving averages
and generating by and cell signals based
on their crossing. Additionally, we
discussed how to be test and optimize
the strategy, using historical market data and evaluate its performance, using built in performance M. This is the end
of the lesson, and I'll see you
in the next one.
11. Bonus Lesson: Create, Backtest, Optimize Strategy with MACD & MA Indicators: Hell on. Welcome to this
Trading ew Pinscript lesson. In this lesson, I'm going to create trading strategy
using Trading Vw Pinscript. Trading strategy will be
based on two indicators, MacD and moving average. To start creating a strategy
we'll go to trading website, and after that, we'll go to
products and Super charts. You can create account at
tradingw.com for three. Now, after that, we'll
go to Pine Editor, and then we'll create trading view strategy by
clicking on Open a new str. We can expand this
window with P editor, and now we can start
typing our strategy. First of all, what we're
going to do is that we going to type parameters
of this strategy. That is defined by this
strategy function. We'll remove all default lines that we're not going to need. After that, we can start creating the title
of the strategy. Let's call it MD, NMA because is based on two indicators MD and
moving average indicators. After that, let's set
up a delay parameter. Lay is a parameter that defines where any plots that you're going to add into your strategy going
to be actually plotted on the
main chart or not. Olay is false for this strategy because Mac D is an indicator which is plot, not on the main chart. Therefore, we set it files. After that, let's set up a
few other parameters for our strategy, default
quantity type. Default quantity type, and so let's set it to
strategy percent of equity. Strategy percent of equity, it means that in each trade, you're going to allocate certain percentage of
your simulated account. Now, another parameter
default quantity value, default quantity value, and let's use 100% of our account balance to be
allocated for each trade. Therefore, we specify 100. Now, Our strategy is going to have several
input parameters, and to set up these
input parameters, we are going to use
input function. McDs an indicator that is
using three parameters. Fast period, slow period,
and signal period. Let's set them up. All these parameters
are integer parameters. We specify the variable in
our strategy, fast period. Fast period, and
it's going to get a value from the
input parameter. I Input is an integer parameter. Therefore, we specify input.in. After that, we si as
a first parameter, we specify the default value, which is going to be
for fast period for MD. Let's set it up to 12. After that, we'll set the
title of that parameter, which is fast period. It is actually fast period
of Mac D. Therefore, let's set it like a
Mac D fast period, and that will be enough. For this parameter, and let's set up other two parameters. We have fast period and we
have slow period for MD. And for the slow period. Let's have a default 26, Y 26, because for the MD, default parameters usually
fast 12, slow is 26. Let's update the title, and let's set up the last
parameter for Magd indicator, which is signal period. Signal period. Signal period usually default value
for MD is nine. And let's update the title. Now, our strategy will have two indicators McDe
and simple moving average. Therefore, simple moving average
has one input parameter, which is period of
that moving average. Let's set up the input
parameter for that indicator. SMA simple moving
average period, and this is the
variable that will get value of the
input parameter. And it's going to be also
integer input parameter. Default, let's set
it, for example, 50, and the title will
be MA, period. For a may period, let's sap mean and
max and and the step. Because by default, when
you don't specify the step, for example, it's
going to be one. But for simple moving average, I want to specify ten because when we optimize or
change this parameter, I would prefer for simple moving average for
this indicator, for this strategy to be not 110. That way we'll pick the
optimal value faster. So The minimum parameter for
that input parameter is one, maximum, lets 30 to 300 and
the step let 30 to ten. We completed setting up parameters for this
trading strategy. Now, now we need to calculate our indicators
based on these parameters. Therefore, let's calculate
the MD indicator. Made indicator using
TA MD function. That function returns value, which consist of three
sequential values. Tp values put in brackets and separated
by coma for the Mac D. Therefore, first parameter for the tup that is going to be returned from TA MacD
function is MacD line, MacD line, second parameter is signal line and
30 is histogram. This histogram, and now we
can specify our function, ta McD we'll specify the
parameters for that indicator. First is the source. We're going to use
the close price of our financial instrument
to calculate this indicator. After that, we'll
specify the periods, fast slow and signal. We'll use our input
parameters that we have already defined on
the top of our strategy. Fast period for this slow, we'll use slow period. And for the signal line, we use signal line. That's all for our MGD. This function TA MGD will return sequnce of value
that we're going to use to draw our indicator in the
pane below the main chart, and also we'll use the
values of calculated McD to develop our logic,
our trading logic. Let's correct this
third parameter. Now, let's calculate the simple
moving average indicator. SMA, which is our
parameter that is going to hold values calculated
from TA dot SMA function. D dot SA, and after that, we specify the source
perfors parameter is this source to calculate this moving average close
is the close price of the current bar of your financial instrument that
you're going to trade on. Close and after that, we
need to specify the period. We have that parameter
already defined as SA period. Now, we we calculated the
simple moving average. Now, we are ready to implement our trading
strategy logic. When we are going to buy and sell our financial instrument that we're
going to trade on. MacD usually generate
trading signals when when McDe line is crossing
above the signal line. I will demonstrate it
later on the chart, and now we can just implement this logic and after I
plot the MacD indicator, I will demonstrate
and I will show where these lines are
crossing and at that point, strategy will generate
trading signal. Let's develop the condition. If Mac D line is bigger
than signal line. Mad line bigger
than signal line. This means that Macd line
crosses above the signal line. It first is going to happen
right at that moment. In that case, we need to check another conditions
because we use two indicators and close meaning close price is bigger than calculated SMA
indicator for that bar. Why we use this specific logic? Because usually the bullish
momentum one close price is above certain moving average. In this case, we are going
to enter the position. We're going to buy. To do that, we're going to use strategy. Dot entry function. And we're going to
specify the signal ID, which is in our case, could be, for example, buy. After that, we'll specify
the type of trade. It's going to be a long
trade because we are buying. Now, Now we need to specify
when we're going to sell. We're going to sell if Mac De
line is below signal line. In other words,
when first time it crosses Macd crosses
below the signal line. Therefore, let's
specify that condition. If MacD line below signal line or because
we use two indicators. I want this strategy to have
a cell signal to generate cell signal when either of
these conditions is true. Either MacD line crosses
below signal line or price closes below
moving average, which indicates bearish momentum for our financial instrument. To do that, We will
specify this condition, close below simple
moving average. That's it, we specify D
close trade condition. In that case, we simply
going to close our position. Strategy close, and
we need to specify the signal ID of
what we are closing. Signal ID is by, because we bought it with
signal by, therefore, when we close that entry, we need to specify that ID. Our strategy will be trading only long
positions because I intend to trade only markets
that are trending up. In our case, it's
going to be Bitcoin. Now we specified entry
condition, and entry function, and close position condition
and close function. Now, now we can specify
the ploting functions. We want to plot our
Mac D indicator. We're going to do that
in order for us to verify how our strategy works if it does what we
actually expected to do and at the time
that we wanted to do. Therefore, we'll
plot the Made using these parameters that we
already have defined. For MacD we have
horizontal line, which is called zero line. Let's plot it. We'll use the H line function to plot horizontal line
and we'll plot it at zero at zero and we'll call it 00 line. After that, let's set color for that line as a gray color. Color should be
gray. In this case. Now, let's plot all
these three values. We have for Magd we have Mcdine, we have signal line,
and we have histogram. Let's plot all of them. For that, we'll
use plot function, and first, we're going
to plot Mag D line. For Magdne, let's
specify the title. It pitches our actual
Macd After that, let's set the color. Color, we can set it to blue. And the line width.
Let's set it to two. Similar using the same function, we're going to aplot two
other values of our Mg. Second, we will be signal line. Signal line, and let's call
it signal, and the color, let's select color, for example, Moon, lined with will be two, and let's plot the histogram. Histogram, and let's
call it the same way. Histogram. For the histogram, for histogram is will be a bars above and
below the zero line, we need to set the it to be plot that in order to do that, Let's set the style parameter. Style will be plot
dot style columns. Plot dot style columns, and for the color, I want the colors
to be variable for this because I want
histogram histogram to be green above
zero line and red or colors close to red when
it's below the zero line. This will have a that way, our indicator will
be more telling us that when the histogram
is bullish or bearish. To do that, we need to set
several conditions here. Color will be pending
on the histogram value. If histogram is above zero, therefore, we'll set
conditions what color. We want that histogram to be. When histogram histogram
previous value, Is lower than current value. It means that
histogram is rising. In that case, I want
it to be lime color. Otherwise green. Otherwise, it means
that it's falling. Now, when histogram is below the zero value. I want different set of colors. In that case, if histogram previous value of histogram
is lower than histogram. It means that
histogram is rising, but it's below the zero value. I won't color, for
example, Fuchsia. Otherwise red. If it's below the
zero line histogram, then but histogram is rising. Color will be Foote. But if it's below and
histogram is falling, color will be red. Now, let's save our str. To do that, we can
click on save button, it's going to propose if you want to keep this script name. Let's say yes, We can see that it says that there is some error
here, Let's fix that. It's a syntax error at input
end of line. Over here. Let's see what we need
to make sure that we have a proper number of taps, and we miss here the question
mark in this function. Now, let's try to save it. Now it is successful. Now, Now let's add our
indicator to the chart. We developed the indicator, we compiled it, we
saved it, no errors. Now next step is
add to the chart. We added it to the chart. Now let's see what it plotted. Because of relays files
for that strategy. It's plotting the indicator, you see McDe indicator. It's plotted not on
the main chart where our candles are plotted. It's plotted below
in the pane below. We can see that blue
line as we plotted it is our Mac De line
actual mag indicator. The line that the next line that we plotted here is the signal
line with the maroon color. That line is the
maroon maroon color, which is a signal line. All these green green
bars and the red bars or bars with the color close to green and close to
red, they are histograms. You see the colors lime color when histograms
are rising in bullish Meta. When histogram starts
falling, the bar is green, as we intended as we intended
to develop it that way. For the histogram that
is below the zero value, when it's falling, it's
red when it's rising. Each bar, each histogram bar is higher than the
previous ones. Then the color is fui. We plotted the MGD. It looks correct. Now, The simple moving average cannot be plotted over
here, it can be plotted, but it will not make sense because there is no prices
over here from our main chart. Therefore, if we
need to verify how our moving average
is going to look, we're going to add it
later after we set certain parameters for
that moving average. In other words, we'll add simple moving average indicator
later to the main chart. Now, Let's back test this
parameter and let's see what kind of return
it generates, and if this return is
satisfactory for us. Now, we select BTCS
D, which is Bitcoin, and our goal when we
develop a strategy is to generate net
profit with as low risk as possible to generate
maximum of net profit with the desirable other parameters, such as, for example,
profit factor. Profit factor, I personally would recommend more than two, which means that for every
$1 your strategy loses, it makes $2 as a profit. Now, as you see in this form a statistic
for our strategy, blue line is the buy and hold. It means that we bought it at the beginning of
when our strategy started to trade and we held
all the trading period. It makes less money
than our strategy, which is good because we want
our strategy to generate more money than buy
and hold strategy. Otherwise, doesn't make
sense to trade it. I could make sense
to trade if it if you do that
with a lower risk. But what we want is that ideally net profit to be
bigger than buy and hold with the less draw down with
the less draw down than the actual financial
instrument and profit factor is bigger than two. Now, let's see if
we can optimize the strategy to generate
even more profit than this. To do that, we're going to
click on this settings button. And after that, we'll try to
optimize this parameters. First of all, we're
going to change each parameter
sequentially until we find optimal performance
for our strategy. By pi performance,
I mean all set of these parameters to
be desirable for us. Maximum net profit as high
profit factor as possible, as low max drawdown as possible. Now we have 2.4 million% profit and we have 1.9 profit factor and we
have 40% drawdown. Let's try to change that. 60, so we have 2.5 million So 2.5 is
bigger, let's try 70. Now, it's 1.5, it's
less, 1.4 is less. Let's try 50, let's try
opposite direction. 50, 2.4 million 2.1 million%. I'm looking at this
percentage of the net profit. It looks like 660 was optimal. Let's keep it 60, t's try
to change other parameters. 12 here. Let's change
this or it's 4 million. It was 2.5, now it's 4.1
million% net profit. 4.03. It looks like 4.1
was 13 as the best, but let's go in the
different direction. 2.52 0.84 0.2. We have another 4.2 here. Three. We have 13, 4.1, and we have ten, 4.2. This is the optimal
for that parameter. Let's change the other one. Three, 2.62 0.8. Now, L et's try opposite
direction, 2.7, 3.6 now. Actually, 26 was the
optimal 4.2 million%. Let's try to change this
signal 2.8, 2.54 0.4 0.4. This is the best for now. Again, 4.4. We have
5 million% already. So this is so far the best. 16 was the best, 18. Yeah. When you see
it stops reducing. It means that it's going to the direction direction when
performance gets worse. We have here 5 million. Now what we did is we
optimized the parameters. We did one cycle of
changing the parameters. When you want to
optimize it more, you can do another cycle. For example, you could try again this parameter to change it and see if we can
make it better. We see we made it
better Pi f 5.4. Let's do one more cycle here. We have 5.4 million.
We have 6.1. Let's keep 6.1. This
is demonstration and we need to do several cycles until we see you
cannot make it better. Still 6.1 is the best. We have seven.
Seven is the best. 7.0, and signal period, let's try to change this one. No, it does not improve
our net profit. Let's change it in
different direction, 5.844. It means that we ran
over two cycles of optimizations and
now our strategy generates around 7 million%, much bigger net profit
comparing to the buy and hold. We have 2.3 profit factor,
which is excellent, it's above two, and
we have 40% drawdown. Bitcoins drawdown
itself could be 70-90%. We have 40% drawdown
now strategy, which is not bad. Also you can take a look at the performance
summary over here. It has more performance
statistics, we can see here that no
net profit generated by our strategy
around 7 million%, by and hold only eight
around 860,000%, much less. There are some other parameters. You can see that long
column filled with numbers, it means that this strategy
takes only long positions. Short column has zeros. That's pretty much all. In this lesson, I
demonstrated how to create trading strategy using trading view Pine
script from scratch, using MacD and simple
moving average indicators. Also, I demonstrated how to plot MD indicator using
different colors for our histogram and for
our signal and Mac De lines. Also, if you want
to for example, to visualize the
simple moving average that is used in our strategy. You can add moving average
indicator on the chart itself. Let's take a look at the values. We need to add simple
moving average with the period of 50. This is built in moving
average indicator, we can add it just to visualize simple moving
average indicator that we actually use. In order to do that, we
click on indicators and we search for moving
average indicator. I'm going to use the
built in indicators. They come under technicals. This is moving average, simple moving average
that we're going to use. And also we need to make sure
that we set the length or period 50 matching the period that is currently
our strategy using. 50. Now, let's see how
strategy is actually trading. Is it following what we had
in mind when we developed it? What we had in mind is that when MacD blue line crosses above the Moon signal line and the price is above
simple moving average. As you see, Here, both these conditions
are true on this bar, therefore, strategy enters
long position in here. Blue signal line above blue Mag D line above maroon signal line and the close price is above
simple moving average. For the closing position signal, we can check as well. For example, in here, what we have here
is that the Close. Price is below the
simple moving average. Therefore, this
single condition is sufficient for the
for our exit trade. Therefore, this is
how we verify if our strategy is
trading as we expect. This is the end of this lesson. I wish you all the best
and happy trading.
13. What is new in TradingView Pine Script v5: Alone, welcome to this lesson. This lesson is going
to cover what is new in Trading Pin
script, version five. This lesson consists
of following sections. In the introduction section, I will explain the
new features and improvements in
the latest version of Trading V Pin Script. After that, we'll review
version four to version five, conversion two, and I will
explain how to use it. Next feature is libraries. I will explain how to create
and share custom functions. I will explain reusability of libraries across
different scripts. Next feature is default values
or user defined functions. I will explain how to assign default values to parameters
in user defined functions. We'll review an example of usage in custom
function, custom pole. Next feature is
switch statement. We'll review comparison
to if else statement. After that, we'll
review an example of usage in built in average
through range indicator. Next feature that we'll
review is ile loop. I will explain how to use while
loops in trade MP script. And we'll review an example of usage in an indicator that
calculates the difference between the average
distance needed to look back to find the
up and down volume. The last feature that we'll
review is new namespaces. I will explain how to use new namespaces in trading
view Pine script. In conclusion, we'll summarize the key features available in Trading view Pine
Script, version five. I will explain how the
new features can enhance the capabilities of the language in creating indicators
and strategies. L et's begin. Trading view
Pan script version five, the latest version
of the indicator and strategy
programming language of Trading view Platform brings a wealth of new features
and improvement. This version has made Pinscript more powerful
than ever before. These changes will help take the language
to the new heights. In this lesson, we'll
introduce some of the key features available in Trading Ve Pinscri,
version five. First, feature that
we'll review is version four to version
five converter. Existing Pine script written using earlier versions of Pine, will continue to function as is. But for those who wish to, a conversion tool has been
provided in the Pine editor to assist with converting version four scripts to version five. You can see this in this slide. This menu option is
available in Pine Editor. You will need to click on this three dots button,
and after that, this feature will be available to you to click on Convert
Code version five. After you click on on that, you will be able
to convert current all the Pin script to the
latest version five Pin script. This is how you're going
to use this converter to Next feature that we'll
review is libraries. One of the major new
features in trading view Pine Script version five is the introduction
of libraries. These libraries are a
way to create and share custom function that can be reed across
different scripts. Once a library is published, other scripts, such
as indicators, strategies, or even
other libraries can import and make use
of these functions. This allows for
centralization of complex algorithm or
friendly used functions, making them easily reusable for you or the entire Pine
script community. In this example, in this slide, we can see that library is
defined in this pine script. To define of the library, you will use library keyword. After that, you'll specify the library name and if it's
going to be overlaid or not. After that, you specify the
functions of the library. You specify the function, you will use keyword and after that function
with its parameter. After you defined and save
the library function, you can reuse it
in other script. In this slide is the
demonstration how to use the library that has
been previously defined. In this script,
you see indicator, and to use the library, we need to import it
using input keyword. We specify the part keyword. After that, we specify the user library name
and the library version. After that, we specify Elias, in this case is all time Elias. After that, we can use this s and we can call the
functions from that library, like in this example. All time dot i, i is the function from that library that we
have defined before. This is an example how to use the library that has
been previously defined. Next feature that we'll review is default values or
user defined functions, an enhancement that complements libraries is the ability to assign default values
to parameters in user defined functions,
making them optional. An example of this is the custom function custom pole that raises a base
to a power of EXP. If the eXP is not specified
when the function is called, it will use two as
a default value. As you see in this example, in this indicator, we specified
function custom pole. Right? This custom p
function has two parameters. Base is one parameter, and exp is the parameter
that has a default value. You don't have to specify
always the second parameter in this function because the
second parameter is optional. For example, in this care of
that function, custom pool, and we used only
one parameter value 11 for the base parameter. Second parameter, we
have not specified. Therefore, default value for that parameter is
going to be used. In this case in the next
call of that function, we used first parameter
and second parameter. Second parameter, we
specified value four. Therefore, in this case, for exp parameter, value
of four will be used. That's how you use
optional parameter with the default values. Next feature that we'll
review is a switch statement. The switch statement is
the new variation of the well known if statement in trade Pine script
version five. It is a more efficient
way of achieving the same results as a big
tree of if else statements. An example of its
usage can be seen in the built in average
true range indicator, which now utilizes a switch
statement to provide different smoothing algorithm
in the calculations, making it more
convenient to use. The code snippet in this slide demonstrates the usage
of this statement. As you see in this indicator, we have a MA function
that has two parameters, and After that, we see
that in this function, there is a switch
statement is used. This switch statement has a
parameter of smoothing input, Smoothing input is our
parameter in our indicator, depending on the so
input parameter. The switch will direct the execution of this
function to the direction, and certain statement
will be used. For example, when smoothing
input equal to RA string. Then t dot RMA function will be called I smoothing
input is equal to SMA, T dot SMA function
will be called. When smoothing input is equal to neither of
those RMA SMA and EMA, the default will be used tat
WA function in this case. This is an example how
to use switch statement. The next feature
that we are going to review is while statement. Another highly anticipated
feature in trading view Pan script version five is
the inclusion of while loops. The while statement creates
a loop that continues to execute until a
certain condition is, or break command is
used within the loop. One example of usage is an indicator that calculates
the difference between the average distance needed
to look back to find the up and down
volume that is equal to the total volume
of the last n bars. The greater the
distance needed to look back to find the up
and down volume. The more bearish and bullish, its value is L et's review. In this indicator, we can
see that while loop is used. In this while statement, there are certain conditions. In this case, the
condition is not volume found and bar
less than max loop back. After that, there are several statements
within this loop. How it works. These statements within this loop are going to execute when while
conditions are true, when those wil conditions specified after the wil
statements are false, then this wil
statement will exit. For example, whenever
this wilt statement is executed in this pine script, these conditions are
going to be evaluated. If these conditions right after the while
statement is true, then execution within while
statement is executed. After that, again, this
condition will be checked. If not volume found and bar
less than max look back, and if this condition
again is true, then another cycle of commands in wile statement
will be executed. This execution is going to be repeated as long as condition in wile statement is this
condition becomes false, then while statement exit. This is how wil
statement is working. One of the new additions
in trading view, Pine script version five is the implementation
of namespaces, which allow a
better organization of variables and functions. An example of this
is TA namespace, which includes all variables and functions related to
technical analysis. This makes it easier to navigate
the reference manual and find all the variables
and functions that return values of
common indicators. As a result of this change, the SMA function is now
referred to as TA dot SMA. However, it is worth noting that remembering the new name
spaces is not necessary as pine script editor has built in outer complete
feature that suggests matching names when you type the older name of the function
without its name space. The outer complete feature
can be activated by pressing control space or common
space in MCS ps. This is an example of how namespaces are used
in this indicator. As you see, TA do SMA, in this function,
TA is a namespace. SMA is a function
within that namespace. When we type in Pinscript, TA and type dot, we'll be able to see
all available function in that namespace. They are grouped the
grouped in TA namespace. All related technical
analysis functions are grouped in TA namespace. That's what we achieved
by introducing this namespace in ding
Pine sk version five. Below is another example
of using namespace. You have another function Str. Parmat is the function
in the namespace Str In STR namespace, trading view, inscript grouped all functions related to
manipulation with string. By doing that, we group, we organized better the
functions in trading view. We put all related
functions in STR namespace, all functions that related
to the string manipulation. By introducing these
new namespaces, we grouped the related functions
to a certain namespace. This is how new name
spaces can be used. Summarizing this lesson. Training view Pine
script version five is the latest version of the indicator and the strategy
programming language, which includes many new
features and improvements. This version has made Pine
script more powerful than before and will help take the language
to the new heights. This lesson introduces some of the key features available
in trading view, Pine Script version five. This is the end of the lesson and I will see you
in the next one.
14. Summary of Key Takeaways from this course: Alone, welcome to this lesson, summary of key takeaways
from this course. This course has
following main topics. Introduction to Trading view
Pine Script, version five, setting up Trading view account and accessing the
Pine script editor. Also we covered variables
and data types in Pine Script and aparators and
expressions in Pine Script. Also we discussed and covered conditional statements
and loops in Pine Script. Then we created from scratch and customized moving average
and binger band indicators. After that, we created
from scratch, customized, back tested and optimized
for the best performance, the trading strategy using RSI and moving
averages indicators. After that, we covered also new features in trading view
Pine script version five, compared to previous
version of Pine script. Now, here are some key
takeaways from this course. Trading view Pine
script version five is a powerful scripting language that allows you to create
custom indicators, studies, and strategies, oralyzing financial markets
and making trading decisions. To use Pinscript,
you need to set up trading view account and
access the Pinscript editor. Pinscript version five
uses variables and data types to store
and manipulate data. You can use operators
and expressions to perform calculations and make
decisions in Pin Script. Conditional statements
and loops in PI script allow you to control the flow of script
and perform actions based on specific conditions. You can create customized moving average and ger bands indicators in PI script now. Also, you can now create
BC test and optimize for best performance
trading strategies using RSI and moving
average indicators. Overall, this course provides a comprehensive introduction to trading in view Pan
script version five and gives you the tools and
knowledge you need to create your own custom indicators
and strategies that can improve your
trading and automated. This is the end of the lesson, and I'll see you
in the next one.
15. Resources for Further Learning and Development in Pine Script: Alone, welcome to this lesson, resources for further learning and development in
trading view Pine script. As you continue to learn and develop your skills in
trading view Pine script, version five, there are
a variety of resources available to help you
improve and stay up to date. Here are few
recommended resources for further learning and development in trading
view Pine Script. First, the trading view website, the trading view website,
tradingview.com, Link provided, provides a wealth of
information on Pin Script, including documentation,
tutorials, and exam. It's a great place to start learning and
developing your skill. Second, the Trading
view Pin Script, the trading view
Pinscript community available at tradingvi.com slash scripts is a forum where
you can ask questions, share your scripts, and learn
from other Pinscript users. Third, P script version
five tutorials, and examples on YouTube. There are a lot of pc tutorials and examples
available on YouTube. This is the easy
way to learn and see the scripts in action. Fourth, practice. The most important thing is to practice practice practice. The more you practice
writing Pinscript, the better you will become. And fifth, to learn about
technical analysis indicators. I recommend chart school section on stockcharts.com website, school stocharts.com slash
do pP link provided. There you will find in depth information
about calculation, interpretation and
trading signals of wide range of
technical indicators, such as moving average, scistics, ADX, et cetera. By utilizing these resources
and continuing to practice, you will be able to improve your skills and develop
your own custom indicators, studies, and strategies
for analyzing financial markets and
making trading decisions. Congratulations. This is
the end of this course. I wish you all the best
and happy trading.