Showing posts with label my. Show all posts
Showing posts with label my. Show all posts

Sunday, 20 October 2024

Pine Script [OUTDATED V4] Tutorial Lesson 2 Drawing Data to Your Charts

[Music]
oh my god I'm doing it again what's
wrong with me dude
hello everybody welcome back to lesson
two it my Pyne script class my name is
Matt I run zen and the art of trading
comm and today I'm gonna pick up where I
left off in my last video if you haven't
seen that I'll leave a link in the
description but let's just get straight
into it in this video I'm gonna go over
a couple of new methods of using pine
script to achieve certain things on your
charts today we're going to be covering
plotting the lowest low and highest high
over a set period of candles this will
just give you an introduction to a
couple of the pine script methods and
functions I'll also go over certain
things like color and linewidth and
transparency a few things like that that
will help you down the line if you come
down here open up your pine script
editor and here we go now I've already
started this script chords lesson too
but apart from this if you open this
with a blank script then this should be
all the same as mean except for the
script name you can name your script
whatever you like I'm going with lesson
2 just for consistency's sake I'm going
to be making a lot of these lessons so
I'm just going to call them by the
lesson name so the first thing we're
going to do here is we're going to
detect the highest candle over the past
50 candles and it's really simple to
achieve that all we have to do is type
this in highest oops caps lock
good old caps lock gets you every time I
should mention real quick that a lot of
these functions that if you use the
wrong case it won't work if I go save
here I'll get an error could not find
function or function reference a lot so
keep that in mind spelling is extremely
important when it comes to programming
putting in the wrong bracket putting in
the wrong quotations anything like that
will result in errors it's very
important that you develop an attention
to detail when you're coding you'll work
that out through experience so I don't
need to go over that too much
but for the most part you should really
just copy what I'm doing note for note
this is in school they teach you not to
not to copy other people's work in
programming it's the complete opposite
don't try and be too original otherwise
you're going to run into all sorts of
problems so the first thing we're going
to do here is type in highest high and
the highest high is going to be set to
this equal sign means set this variable
we're creating to this value we're about
to define and here we're going to use a
pine script function an in-built pine
script function this all these functions
make our job so much easier then if we
were to have to code this stuff ourself
and here's a good opportunity to show
you another inbuilt feature of plan
script that you'll find extremely
helpful in your coding especially as a
beginner but if you type start to type
high and then put an e on the end there
because we're going to type highest but
if you press ctrl and then space it'll
list the inbuilt functions built-in
functions of pine script and so we're
going for highest here we're going for
highest and then all functions inbuilt
functions which are equivalent to
basically inbuilt scripts this will
return a value we need to tell it what
we're looking for here so we're looking
for the highest high and we're looking
over a period of 50 candles that's all
we have to write in here you could write
low in here or close anything like that
and it will detect the highest low over
the past 50 candles I'll go over that in
later videos but for now just keep it
simple because this is only lesson two
so that's going to detect the highest
high but if I change this close to high
click Save and then add to my chart
you'll see oops I forgot to set overlay
to true that's another thing that you'll
learn through experience when and when
not to use that so now if I add it to
chart you'll see it draws the highest
high oops I made another mistake sorry
it's a bit early in the morning here
I've only had my first coffee
this is drawing the high of the candle
you know before it had said close now
it's just drawing the high and we don't
want that we want the highest high which
is this variable we created here now I
save that
there we go you see so now it's drawing
the highest high over the past 50
candles so if I do this you see 49 bars
on the fiftieth bar this line starts to
drop and that's because it's detecting
the next candle down then the next
candle down and so on until it's hit by
price action and I don't need to explain
what this is useful for there's all
sorts of applications of this sort of
code but we'll go over that in later
videos for now I'm just showing you how
this stuff works so we're gonna write in
one more here and it's gonna be all what
is it wrong with me today lowest low is
set to the lowest low of the past 50
candles now if I come down here type in
another plot you can have infinite
amount of plots as far as I can tell
I've never reached a limit so you can
plot as much data as you want on to your
charts and this one is going to what the
lowest low and now if I hit save we'll
see another line up here at the bottom
here similar to this top line where it
will be detecting the lowest low of the
past 50 candles I click Save there you
go you can see that the line started to
rise here and then it rose and rose and
then price action hit it and the low
began to drop because this became the
new lowest low over the past 50 candles
and so on so on and then now this is a
current lowest low and this is a current
highest high of the past 50 candles so
that's about it for this technique but
what if you want to change this on the
fly right now if you go up to the
options you've got no way to change this
50 value and that can no one wants that
the the whole point of making scripts is
to make it convenient you have to come
down here and change this number every
time you want to change the value that's
going to be very inefficient so let's
add an input function we're going to
call this input function the look back
so this will be the look-back period we
get you know if you've got the RSI on
your chart I'll just show you real quick
for those who might not understand
exactly what's going on here that this
length 14 is saying calculate the RSI
value over the past 14 bars so we want
to do the same thing without with our
look back now highest high lowest low
indicator and we're going to
call on another inbuilt function called
input input allows you to create a
settings menu where you can have all
kinds of all kinds of value inputs from
numbers to timeframes to words what you
know whatever you want to use in your
script so there's three or four
variables we need to define in this
function in order for it to work how we
want it to the first is a title if you
don't put a title in I'm pretty sure
that when you open up the settings menu
it will just be called whatever the Val
the variable is so we want to call this
say look-back period or you could call
it length whatever you prefer and we
need to define what type of input this
is is that a number is it text is it a
time frame in this case it's going to be
a number and like I said in the previous
video there's a lot of jargon in
programming that you'll have to learn
one of those is that numbers aren't
called numbers in coding they called
integers the reason for that is because
there's all different types of numbers
there's numbers with floating decimal
points in pine strip that's called a
float a floating number a floating-point
number but we're not going to go into
that just yet because again that's a
little more advanced we're just going to
deal with a normal whole number which in
our case is an integer so we need to
type in that this type of input is an
input dot and then if you press control
space here's a list of inputs you can
choose from
we've got bull which is short for
boolean we went over that in the last
video
we've got float which I just spoke about
which is a decimal point number that can
be helpful for dealing with things like
ATR multipliers and stuff like that
we've got integer which is a whole
number that's what we're dealing with
today
I've got resolution which is time frame
basically we've got session which is a
like real world time setting so you
could set say between 9:00 a.m. and 3:00
p.m.
using this we'll go over that in later
videos we've got source which is open
high close that sort of thing that can
be useful for say we could change this
to a source input and so you could
change this to be high hello
close all of that in the settings menu
but again we'll go over that in another
video
I'm going to keep
today string is text just like boolean
is a jargon for true or false and
integer is jargon for whole number
string is jargon for text and finally we
have symbol symbol is the currency pair
you're going to be trading or the market
all that sort of stuff you can actually
reference other markets in your pants
trip codes so if you wanted to compare
the price of the British Pound and the
US dollar to say gold against the
Australian dollar for I don't know why
you'd want to do that but you can do it
in this script using the symbol input
function which is pretty cool that
allows you to achieve some some really
cool stuff really advanced stuff we'll
go over that there again in another
video so today we're going to click on
input integer now we also want to set
the default value of this input because
we don't want it to be 0 otherwise every
time you add the script to your chart
it's just going to show the height of
the read most recent high so we're gonna
type in de FV al and that's short for
default value and we're going to assign
this to 50 and that way we can replace
this later with this lookback variable
and it'll look exactly the same when you
first add the script to your chart but
then you can come up to the settings and
mess around with the look-back period
and we might as well while we're here I
can do this isn't really necessary but I
can show you how to set the minimum Val
the minimum value which is mi n VAR min
Val the minimum value we'll just set it
to 1 here because there's no point in
going below 1 with this sort of script
and just change this now to say look
back which is referencing this variable
we just created
put that on both of these because we
want to look back to be consistent
across both lines here you don't have to
do that you could have a separate look
back for the hires and a separate look
back for the lows if you wanted to you
just have to copy this line change the
variable name and put that in here but
now if I click Save nothing will change
unless we come up here and we play with
this new variable setting that's shown
up on our user interface so we can set
this to whatever we want say we want a
longer look back we can go
hundred and if I click okay here this
these lines will get longer because
we're looking over a longer look-back
period see and there you go you can
change this to whatever you want you
change it to a thousand if you wanted to
yeah that's about it I'll go over a
couple more features while we're here I
can show you a few more basic features
like changing the color of these lines
and the line width and all that sort of
thing but I should also mention that you
can we'll go over this again in later
videos is so much to cover I can't do it
all in one video but you can even
reference other time frames so you could
be drawing the weekly high or the weekly
low or the monthly high monthly look
daily high daily load whatever you want
pretty much any time period you want you
could do the three and a half hour high
if you wanted to there's a lot of
customizability I think that's a word in
pine script so yeah even though this is
quite simple these foundational
functions and features can work together
to create some really cool stuff which
we'll get to over the course of this
course if this is too simple for you
don't worry we're going to get much more
complicated as we go on and we're gonna
create some really cool stuff so while
we're here I might as well go over some
of these other features say you want to
change this top line to be red colored
we have to change the plot function
we're going to add a couple of new
variables to this we're going to say we
want to set the color color is set to
color dot and this color dot is going to
select from the group of color names so
if we press control space here you'll
see here's a list of colors we can
choose from and we want color dot red
because this is a resistance level
theoretically because it's a high this
is likely to act as resistance on price
not support so there's that we're also
going to set the transparency to zero
and the reason for that is because it
makes the lines a little bit more
vibrant makes the color stand out a
little more so transfer is P is short
for transparency so we're just going to
leave that as trance equals zero that
will set the transparency to zero if you
set this to 50 it'll be half transparent
but today we're going to leave it as
zero and then we're going to have the
line width is set to two
I'm gonna set it to do that right now
this is set to one which is quite thin
you can set this as high as you want I'm
not sure how look that - I know - looks
pretty good so believe it is - and
that's it for that one we'll come down
to the lowest low and we'll set the
lowest low to blue you could also set it
to green if you wanted to but we'll set
it to blue for now I will also set the
transparency on this to zero and we'll
set the line with two as well to be
consistent just like in trading you want
to be as consistent as possible with
your coding and so that's it we click
Save and that will change the color of
these lines and the line thickness just
like that and there you go you've got
your first little script setup you can
change this variable you can change the
colors of these so you wanted this to be
green instead of blue and you wanted
this to be pink because you're crazy and
there we have it you've got your first
little customizable script and I've gone
over a couple of really standard pine
script functions and features and
variables that you're going to be using
in your scripting and this is a pretty
good start I feel if you're brand new to
pine script then this will give you if
you study what we did here and you play
around with this stuff you're going to
learn a lot of the basics of pine script
coding and you're going to be using a
lot of these features and functions
quite often I hope you found that useful
and helpful I'll go over a couple of
other things really quickly how the
first thing is all of these values are
calculated on each tick each price tick
so it's calculated on a bar by bar basis
but it's also calculated in real time so
if we go down to the 1-minute chart and
I set this value to zero
oh one is our minimum value and it
appears the markets closed right now
which is bizarre I didn't think they
closed on a Tuesday morning I'll have to
go to a different currency pair to see
if we can get some movement I might just
go to Bitcoin because bitcoins always
moving
come on Bitcoin you can do it you can
move further than that
there we go so you can see this low is
being drawn but that the
you hold this candle you have really not
helping me here Bitcoin I was hoping
you'd be moving more than this right now
and they save bitcoins the volatile I'm
just kidding I know this is a one minute
chart doo doo doo doo where are the
bitcoin whales at come on I'm gonna
change this value to I'm gonna change
this to say close and I'm gonna comment
out this line just so that we can
quickly get get the idea here
see that line just moved down it's being
calculated in real time based on the
tick's of price action you can change
that functionality in the script if you
want it to only calculate based on
closed candles and not current candles
you can do that but I'll get over that
not in other videos but that's something
important to remember is when you when
this code is executed each time price
moves and one last thing I want to go
over is well first of all on my website
here I've got a few more lessons here if
you want to jump ahead it was going to
be take me a while to make some of these
videos but if you want to learn a little
bit more advanced stuff I've got things
here such as how to detect candlestick
patterns and that sort of thing so just
go to zen and the art of trading comm if
you want to find this stuff I'm gonna
make videos on all of this obviously
when I get to it
but if you want to steal the code and do
a bit of cheating here you go you can
come here and do that if you're a little
more advanced and this stuff is too
simple then come on over here and you
can learn a little bit more advanced
stuff before I get around to it with
these videos one other thing I want to
get into I want to show you behind
script wiki and you come up to the first
link here just tradingview com4 slash
wiki forward slash pine underscores grip
up I'll put a link to this in the
description you come here and well
nevermind have moved it okay I'll put
this link into the description so this
is the new documentation for the latest
version of pine script which is version
4 ah to be honest this guide looks a lot
better than their old guide so it's
probably a good thing they did this so
if you want to learn a lot of the
specifics like language fundamentals
this will quite be quite important
especially view if you
want to get into really advanced stuff
I'll teach you most of this stuff myself
but it can be helpful to come here and
find out some of this information these
are your like average everything I can't
speak this morning these are your
arithmetic operators so for dealing with
numbers and stuff like that you'll find
some really good stuff on here so this
is this can be quite useful obviously
there's also the autocomplete function
here but you need to know what you're
looking for before you can find it so
this site can be helpful for that this
is a great reference site and that's it
for today's video it's already gone
longer than I wanted it to I there's the
volatility we've been looking for
Bitcoin finally you've been asleep on us
and now you're awake or awesome anyway
that's it for today's video thanks for
watching I'll see in the next one and
we'll go over what the hell happened yet
we'll go over some more advanced
features of Pyne scripts see you then
guys have a great day good luck with
your trading good luck with your coding
and I'll speak to you soon see you guys
later
[Music]
you

Pine Script V4 A Breakout Strategy

what's up my friends and fellow traders
welcome back to another partnership
video i've got a good one for you today
i'm sorry it's been a couple of weeks
since i posted a video
i've been extremely busy lately working
on my own trading but today's lesson is
going to address a question i got from a
student of my pantry mastery course so
here's the question here from dj and dj
wants to know how to create a script
that first draws the previous days low
and high onto his chart
and then he wanted to do something like
entering a trade i'm guessing in the
back tester system he didn't say that
explicitly here but i'm assuming he
means enter a trade in the back tester
system
with a buy stop order three pips above
the previous day's high a stop loss five
pips below his entry and his take profit
ten pips from his entry so two to one
risk reward
and using a buy stop order above the
previous day's high and i'm assuming
also below the previous day's low and so
that is exactly what i'm going to show
you how to do today so here we are with
a blank strategy script i'm going to do
things a little bit differently today
instead of writing out each line of code
as i go to save time and be a little
more efficient and concise i'm just
going to copy and paste blocks of code
over into the editor and explain what
that code does as we go so as you know
if you've watched any of my previous
lessons the first thing i like to do in
my scripts is get my user input so i'm
going to paste in my user input for this
script here one other thing or one new
habit i've gotten into with my scripts
is just lining up all of these equal
signs so this particular script only has
three user inputs entry pips stop pips
and target pips they're all pretty
self-explanatory entry pips is
the distance from the daily high and low
that we want to set our buy or sell stop
order
stop pips is our stop-loss distance in
pips from our entry target pips is our
profit target our take profit uh
distance in pips from our entry they're
all using the data type float floating
point numbers so they are decimal
numbers meaning we could have 3.1 pips
as our
entry pips if we wanted to and then
finally i'm using the new tooltip
feature of pinescript was not that new
but it was added a couple of months ago
and now we can explain what each setting
does so that when we hover over this
little i information icon
this little tool tip pops up that
explains what that setting does these
settings are very self-explanatory so
let's just move on to the next block of
code which is getting the daily high and
low
so i'm going to copy this code over here
to get these values we use the security
function
when you need to reference either
another market or another time frame we
do that using the security function
the security function takes a bunch of
input parameters i've left
our gaps and look ahead as the default
settings if you want to learn more about
this function just hold down control and
click on it
and there'll be a description that pops
up here and a few examples
but basically all we're doing today is
we're referencing sim info or symbol
info dot ticker id
and that will get the current market
that we have loaded onto our chart
in this case that would be euro new
zealand dollar
from the oanda
price source or data feed so ticker id
would be replaced with a string
that looks like this oanda
colon euro new zealand dollar
if we just put in ticker then it would
just look like that but we don't want
that we want to actually get the price
data from the
exact same market that we've loaded onto
our charts here
then we reference a resolution or time
frame in this case we're referencing the
daily chart you could also put 1440 here
for 14 40 minutes which is a daily
resolution as well but to keep it simple
i just left mine as d next up we need to
reference an expression now this
expression could be anything it could be
an indicator value so for example we
could get the daily ema 50 ema
or the daily rsi value in this case
we're just referencing the high price so
we're getting the high and the low from
the daily time frame on the current
market that we have loaded onto our
chart
pretty simple now we get to the more
complicated part of the script which is
calculating our entry price stop loss
price and take profit price so we'll
copy these in one at a time
the first thing we do is we determine
our buy
and sell point that should say and sell
point uh and it's going to be above
below
the high slash low
so our buy point is going to be the
daily high
plus
our entry pip setting so
3.0 by default
multiplied by 10
because
pinescript deals in points not pips and
so we need to multiply anything dealing
with pips by 10 in order to convert that
into points
and then we need to multiply
our
points
by this symbol info or siminfo dot
minimum tick value and this is just the
last decimal place on our price chart so
it would be 0.00001
obviously depending which market you're
on this value will be different and
that's why we need to do this
but moving on we then do the same thing
for our cell point now one thing i
didn't do here is replace the default
three pips with our user setting so this
is how it should look
that multiplied by 10 multiplied by our
minimum tick
so our buy point is our entry pips above
the daily high previous daily high our
sell point is our entry pips
below the previous day's low
the next thing we need to do is
determine our stop loss and our take
profit so to do that we subtract our
stop pips multiplied by 10 to turn it
into points multiplied by our minimum
tick value and then we subtract this
number from our buy point and then we
add that number to our sell point so for
longs our stop obviously goes below
our entry and for shorts it goes above
so we need to add in the case of our
short stop loss
next up we get our take profit price to
calculate that we do exactly the same
thing as our stop loss except in the
opposite direction and using our target
pips instead of our stock pips so we add
to our buy point our target pips
converted into the correct amount of
points for this market so that's it for
our trade entry data
the next thing we need to do is detect
when a new day begins
and when we detect that new day
beginning we place our stop orders our
buy stop order and our sell stop order
at our buy and sell point now this code
here is a little bit more complicated so
let me just paste in the first part of
it
and go over what's happening here let's
save the script make sure there's no
errors and we're all good
so
next up we check if a new day has
started and we're flat meaning we have
no positions open no trades open then we
want to place a buy stop and a sell stop
above and below the previous days high
and low before we can do that we need to
detect
when a new day begins the easiest way
i've found to do that is to use the
change function inbuilt change function
and then pass it in this time function
that references a resolution or time
frame so this new day variable will be
set to true
if
a change is detected in the daily time
frame and a change will only be detected
on the daily time frame if a new daily
bar
begins
and then i have a bunch of var variables
these are persistent variables that are
stored across our chart so they're not
recalculated on every new bar like these
ones are these variables will stay as
0.0 until we overwrite them
with a different value
and that's what we do next so first we
check if we have a new day
then we want to check if
our strategy dot position
size is equal to zero that means we do
not have any trades open
then if these two conditions are met we
have a new day starting and we have no
trades open then we want to enter our
buy stop and sell stop orders because
obviously if we have a position open
that means we took a trade yesterday
that has not yet hit its stop loss or
take profit and we don't want to enter
any new trades because this
particular strategy is not
a pyramiding strategy it's just a one in
one out very simple
approach to trading daily breakouts so
let's start with our long orders first
let me copy in our long code
so the first thing we do is we save our
long stop loss price
by overriding this var variable with the
current stop loss long and then we save
our take profit price
then we use the strategy.entry function
to place our buy stop order and the way
this works is we need to give it an id
to reference so that we can close this
trade later if our stop or target is hit
then we need to tell panscript which
direction we're trading in so we set
long to strategy.long or you could also
write true here but just to make it more
readable i like to leave it as
strategy.long then to place a by stop
order we use the stop parameter and then
this parameter takes a price
and so we pass in our buy point which we
calculated up here our buy and sell
point which is by default three pips
above the daily high and three pips
below the daily low and then i use
a couple of new parameters that we
haven't covered before in any video that
i've ever done and that is the oca or
one cancels all parameter
so oca name is the name of our one
cancels all group and then the oca type
tells pinescript what we want to do with
this group so this is completely
optional you don't need to add this you
could cut this out if you want to
but i included this just because it was
a good
opportunity to demonstrate this
functionality basically what i'm doing
here or what i plan to do is
when we set up our shorts as well
and it might be easy to show you this
visually so let me copy over my short
entry code which is exactly the same as
our long entry but obviously for the
short side so we're saving our shortstop
and our short target and then we're
using the strategy.entry function to
enter a short cell stop at our cell
point but you can see here that these
both have oca name set to x you could
set this to anything any string just so
long as they're the same string
and the type is set to the same type so
this is a one cancels all order meaning
that if we get filled on a long trade
then our short
entry sell stop will be cancelled in
other words we're only taking one trade
per day so if we get filled on a long
breakout and then that trade either hits
its profit target or reverses and stops
us out and then we
clear or break through the previous
day's low
rather than enter a new short trade
nothing will happen
and again this is optional you could
remove this i haven't noticed it affect
the profitability much at all in my
preliminary testing uh probably because
it's not a common occurrence that the
previous day's high gets taken out and
then the previous day's low gets taken
out it does happen but not that
frequently so this is just for example
purposes just to demonstrate how you can
use the one cancels all in your strategy
scripts so the next thing we need to do
is tell pinescript when to exit these
trades so i'm going to paste in that
code now
so here we are exiting our trade if our
stop loss or our take profit is hit to
do that we use the strategy.exit
function
we give it its own unique id and then we
need to tell it which
order which entry we want to exit so
from underscore entry needs to
correspond to one of our open orders in
this case
we have our strategy.entry with an id of
long
and a strategy.exit with a from entry id
of long so this will exit
this
trade but it will only exit this trade
if our take profit is hit by price
action or our stop loss is hit by price
action
so limit is for your take profit limit
order
stop is for your stop loss order and
then we do the same thing for our short
trades we exit from our short trade only
if our short take profit is hit or our
short stop loss is hit so that's pretty
much it the strategy is written um the
only thing left to do is visually plot
this information to the chart
so that's what i do next i'm just going
to copy this entire block of code in
down here
and i'll explain what we're doing so
it's all pretty self-explanatory we're
just plotting all of the relevant data
for this strategy script so we're
plotting the daily high we're plotting
the daily low we're plotting our buy
price or our long buy stop price
and then we're plotting our stop loss
and our take profit for our long trades
and then the same for our short trades
we're plotting our sell stop price
our short stop loss price
and our
short take profit price and then we're
setting the color of each plot
our daily high and low has a line width
of two so it's just a little bit thicker
stands out a little more and then i've
titled all of these plots so that we can
adjust them in the settings menu under
the style tab so let's save the script
make sure it compiles without any errors
and there we go
open up the strategy tester you can see
that
because we're on a euro yen
and i did set the default quantity value
to quite a high number uh this is off
the scales
i need to come up here and drop our
position size just a little bit
to get more reasonable results here and
we're pretty much done with our script
let's just go over a couple of trades to
see what it's actually doing
here's
a trade here
so when a new day begins
as it did on this bar right here
we start plotting the previous day's
high
and we place a buy stop order three pips
above that high on this purple line so
if i measure that out that should be
three pips
it's exactly three pips you can see that
the strategy tester entered long here
and then exited our long trade at our
profit target which is 10 pips
from our entry and our stop loss down
here was 5 pips so we've got a 2 1 risk
reward profile 5 pip stop loss 10 pip
take profit
and this was a example of a winning
trade now one thing to be aware of is
i'm not 100 sure how the tester system
knows that this trade did not um come up
and fill us on this order and then
decline to hit our stop loss and then
rally to hit our take profit so for
example let's just draw
this
information onto the chart
and then we'll drop down to a 15 minute
time frame
and see exactly what happened here so
let's draw a line there drop down to the
15 minute chart
and have a look at what actually
happened on that day
yeah and just as i thought
this trade did not play out how the
strategy tester thinks it did let me
change the color of these lines
this is our entry this is our take
profit and this is our stop loss
so you can see the price action rallied
here
filled us on our order and then on that
same bar retraced all the way down and
then hit our stop loss before it rallied
to hit our take profit but if we drop
out to the one hour time frame
and turn on our strategy script you can
see that the backtester system
picked this up as a winning trade
and so that is why i'm very skeptical
that this strategy has as high of a win
rate as the tester is telling us it has
and there's really no way to verify
how a trade played out at the moment at
least without doing it manually the way
i just showed you so that is why i'm
always telling traders to be very
skeptical of the backtester system in
trading view
quite frankly i don't like it at all
the backtester system is quite popular
among a lot of traders and you can see
why i mean every trader wants to speed
up their process no one enjoys
backtesting i don't think i've ever met
anyone who enjoyed back testing and if
they do
they're either lying or they're nuts
because it is one of the most boring
things you could ever do
but
this is an example of why you should
manually back test your strategies if
you want accurate results there is no
way to shortcut that process
at least not with pinescript one other
thing to mention is that the strategy
tester is trading a fixed position size
which is not something i would normally
do normally i trade with a percentage of
my account balance so in every single
trade i might risk one percent or two
percent
maximum of my account balance
this tester system doesn't allow you to
do that
instead it is just trading a fixed
position size in this case of ten
thousand contracts
or one mini lot on a hundred thousand
dollar account
so basically our max drawdown and our
net profit are not accurate figures and
so this is a great example of how the
strategy tester can be misleading and so
while the backtester system can be
helpful in identifying potentially
profitable strategies
do not under any circumstances
take this information as accurate it
should only be used as a very very rough
indication of a strategy that might have
potential to be profitable you still
need to manually back test all of your
strategies in order to get accurate
results and again if you're not sure how
to back test there will be a link in the
video description to
a guide i made a couple of years ago on
how to manually back test strategies and
with all that said there are some
strategies that perform a little bit
better in the backtester system
basically the more simple your strategy
is the better as strategies become more
complex the backtester system can give
more and more misleading results but
anyway for those traders who insist on
using pine script 2 test strategies
i hope that you found this lesson
interesting
at least there is a
decent back testing tool here
if you change this to a study script and
remove all the references to the
strategy
functionality we've got a pretty good
indicator here to assist in the back
testing process for a breakout strategy
like this anyway that'll do it for today
i think in my next video i'll record a
example of why the back tester system
on trading view
should be treated with a huge amount of
skepticism
and why when something like this seems
too good to be true it probably is so
this strategy might be profitable but we
can't know for sure unless we manually
back test it because the tester system
who knows how many times this has
happened
over 773 trades
where it gave a false reading
and the trade was filled but then
stopped out before our target was hit
and the tester system never accounted
for that but anyway to be honest um the
more simple your strategy is and
especially if your strategy operates on
candle closes instead of
like limit orders and buy stop orders
like we have here
or like we used here
then the chances of this sort of thing
happening are significantly reduced the
reason for that is say we were trading
daily breakouts but we only entered on
the closing price of this bar the
closing price of this bar would have
factored in that dip below our stop loss
and then rally back up to here
and so this trade would have gone from a
losing trade
into a winning trade just by operating
based on candle closes now the one time
that this does affect
strategies that operate on candle closes
is if your take profit and your
stop-loss is hit on the same bar
uh there is no way to know how the
tester handles that sort of situation
and so a trade that is recorded as a win
might have actually been a losing trade
depending on which price got hit first
on that intra bar price action
so anyway i hope you found this lesson
interesting at least
um
it's a good cautionary tale but it's
also
um i think interesting code and there
are a lot of ways you could use this
like i said if you remove all the
strategy code out of the script we've
got a decent indicator here to assist in
trading breakouts manually and if you
were to forward test this kind of
strategy over a few weeks
or months even you might find it to be
profitable i'll leave it there
thanks dj or daniel for sending in this
question and for all of you traders who
are not involved in the panscript
mastery program if you'd like to take
your coating to the next level or you
simply just want to steal the source
code to every script i've ever written
head over to panscriptmastery.com to
check out some of my courses over there
otherwise i'll be back soon with a free
lesson here on youtube so if you haven't
hit the subscribe button make sure to do
that as well and i will see you in the
next video take care best of luck with
your trading and be careful
using the trading view strategy tester
goodbye
you

NEW PINE SCRIPT V4 FEATURE Group & Inline Inputs

hello my friends and fellow traders
today's lesson is covering the latest
update to the panscript language that
the trading view development team have
added
this new update is a great one it's a
simple one
but it does improve pine script quite
dramatically in my opinion
so this new update now allows us to
organize script inputs
in sections and lines so this is
something i've personally wanted for a
long time because i have a number of
scripts
with a huge amount of settings and it
has always been
extremely difficult to organize those
settings visually
on the user interface so that the user
of my script
can quickly and easily navigate the
settings and keep everything neat and
organized
so this new update is just a simple user
interface visual
change to pine script and i'm going to
show you how we can use this new change
in our scripts to better organize
our settings interface but before we do
that let's read the words
so it says here our latest pine update
introduces two
improvements to inputs the new group
parameter allows programmers to define
a section header for a group of inputs
and the new inline parameter allows
multiple inputs to be joined on one line
using these new features you can
organize inputs more neatly
as we do here for our auto fib
retracement indicator so you can see
that they've
used the inline parameter to merge all
of these
fibonacci settings into two columns
instead of having these laid out all the
way down
on a single column they've also added
the option
to create section headers or titles
so you can see here that this section of
settings
applies to the date range header so
today's lesson is going to be a really
quick and easy one i'm going to jump
into the pine editor load up one of my
existing scripts and we're just going to
play around with these new parameters
and as always i will leave a link in the
video description to
this article here and i'll also leave a
link to the plan script
reference manuals entry for input which
describes
how you can use these new settings
in detail but i'll quickly read this out
to you the inline parameter
is a string parameter and it combines
all the input calls using the same
string or argument into one line
the string used as an argument is not
displayed it is only used to identify
inputs belonging to that same line so if
you apply the same
inline parameter string to a bunch of
inputs in your script then they will all
be merged onto the same line
where possible and the new group
parameter is also a string parameter
this creates a header above all inputs
using the same group
argument string the string is also used
as the header
text so this parameter is displayed on
your chart
inline is not it's just used to identify
which inputs you want to merge on the
one line
so let's jump into the pine editor and
play around with these new
input parameters so here i am with a
strategy script that i wrote
it has a bunch of inputs here as you can
see
not as many as some of my scripts do but
we're going to use this as an example
we're going to
segment some of our sections so this
section up here
is going to be our strategy settings and
this section down here is going to be my
auto view settings this is the settings
i use to
inform autoview how to auto trade my
strategies
and how to calculate my position size
for each trade that autoview takes
i'm not going to go into detail about
autoview in this lesson this is purely
for example purposes
if you want to learn how to use autoview
to automate your forex trading
i'll leave a link to that in the video
description and up
on the right side of your screen right
now will pop up a little eye
icon that will take you to that video
lesson that i did a few months ago
on how to set up auto view but anyway
today's lesson is going to cover input
parameters so let's get into it
so here i have a bunch of inputs bunch
of user inputs completely
unorganized we can now use the group
parameter to specify which inputs we
want to belong
to each group that we define so here i'm
going to just call this
strategy settings and now if i save the
script
and we come up to the settings menu you
can see that we now have a header here
that says strategy
settings but i've only applied it to one
input parameter so far
if i were to apply this to multiple
input parameters they would all fall
under this header
and that is one way we can separate our
script settings
using this new parameter so let me copy
this bit of code here and
paste it over all of these input
parameters
now all of these ones here are for auto
view all of these settings here
are for the strategy script so now i can
paste
this group parameter into these other
input variables
and we can change this to say auto view
settings
and now i copy this bit of code and
paste it over these few settings
and i save the script now when i come up
to the settings menu
you will notice that all my strategy
settings are grouped together
under one header and all of my order
view
settings are grouped together under one
header so on your more complicated
scripts that have
many different types of settings you
might have a bunch of candlestick
filters or candlestick patterns your
script wants to detect
like for example my ultimate
pullback indicator i need to go back and
modify the source code to the script
to include these new group parameters
and inline parameters because if i open
up the settings to this script
you'll notice that i have dozens of
settings here
and i have grouped them myself using
check boxes blank check boxes that do
nothing
but i can now use this new group
parameter to create a header
for all of these different various
script setting
sections so for example here i have a
section
that determines what my candle patterns
will be
so using the new group parameter i can
group all of these check boxes
under a nice neat header that isn't
as messy as using these blank check
boxes
so hopefully now you can see the power
of this new update
but let's get back to our script and
i'll show you how the inline parameter
works
so the group parameter is extremely
simple by combining the same group
parameter for all of my inputs
that groups them all together and the
group string is also what is displayed
in my settings menu the inline parameter
is a little bit different
it is not drawn onto your settings menu
and it can be named anything
so i could just write a one here if i
wanted to i can copy this
paste it there and now when i come to
the settings menu after i save my script
these two inputs will be merged onto
just one
line so let's save this script and i'll
show you what i mean
there we go come up here now these two
inputs
are on one line and this inline string
doesn't really matter what i call this
and that's really it it's quite a simple
update but it's very powerful
for organizing your script settings and
something that i've personally been
waiting for for many years now three
years
i could have used this feature and then
finally added it to
pine script and it is going to help a
lot with making your scripts look more
professional
more organized now the inline parameter
will
only merge as many inputs
as it can fit into your settings
screen so if i were to add another
inline here
to the next input here and save the
script now if i come to the settings
menu
these will not all be merged onto one
line but instead
they are just grouped together a little
bit closer however one thing you can do
is just put in a blank title for these
settings and that will group them all
onto one line so if i just backspace
all of this and save the script let me
come up to the settings menu
now all of these boxes are on one line
but they don't have a title explaining
what they do
but depending how you set up your script
maybe this would be obvious to your
script user you could use the header
title to explain what these three
boxes do and it's just a way to better
organize your script settings
one other thing i need to mention is
that if you wanted to merge
other boxes onto a single line such as
these two here
you would need to use a different inline
string
so here i can write inline equals
two copy that code onto the next line
save the script come up to the settings
and now these two boxes are on
a single line and these three boxes are
on their own line as well
so that's it for today's lesson i hope
you found that interesting if you want
to learn more about this new update go
and read the documentation
and go and play around with it with your
existing scripts it may seem like a
minor thing but if you've been using
panscript for any length of time
you will be just as excited as i am to
have this new feature added
anyway that's it i'll see you in the
next lesson take care guys best of luck
with your trading
and i will speak to you soon

How to use the STUDY Function • Pine Script [OUTDATED V4] Tutorial

hey traders my name is Matthew from
Pines crib month and in this video today
I'm going to show you some content from
my PI inscript mastery course where I'm
going to break down the study annotation
function and explain all the various
parameters that we have to work with
but before we begin I should mention
that if you enjoy this content
there's plenty more available over at
pine script mastery com including a free
basics course for beginners so go and
check that out if it's something that
interests you but for now let's get into
the content
so hey coders welcome to the very first
pan script coding lesson in this course
this lesson is going to cover the study
annotation function which is this guy
down here so I'm going to explain what
this does and how to use it what all the
input parameters do so this study
function is what pine strip refers to as
a annotation function so similar to this
as an annotation comment which tells
it's a compiler directive it tells the
pine Script compiler what version of
pine strips are using in this case
version 4 the latest version as of
making this course the study function
does a similar thing it tells pine
script all of the code that follows this
study annotation function is to be
treated as a study script for in other
words an indicator script as opposed to
a strategy script so if we were to make
a strategy script we would have access
to different functions such as all these
strategy calls but we're not doing that
today we're going to cover strategy much
later in the course
so today we're just working with the
study function so first of all what
inputs does the study annotation
function take it takes two titles it
takes an overlay our boolean input it
takes a text format input it takes a
precision input a scale input and a max
bars back input so those are the
parameters we have to work with and I'll
explain what each of them do one by one
so the first input parameter is a title
and this is the only input parameter
that is required so if you don't have
this title and you try to save your
script
it won't work we'll get an error so this
first title input is the name of the
script and you can call it whatever you
want so in this case I'm going to call
it pine script mastery course study
example and hit save and you'll see up
here our script name has now changed to
PS MC study example now you don't need
to have the
title equals here we could just do that
and that would also work but just for
clarity's sake I'm gonna leave that in
because we also have access to the short
title so I'll show what that does now
short title is set to let's call this
study and now if I hit save that'll
change the name of our script to just
study and so the reason there's two
titles is that the main title is for
explaining in detail what your script
name is the short title is for an
abbreviation on your chart so for
example I have indicated called the
ultimate pullback indicator but that's a
long name to have it clutters up your
chart a fair bit so what I have used the
short title for is to abbreviate it to
UPI and so when you use my ultimate
pullback indicator that's all you get on
your child is UPI
so that's the purpose of the short
titles to abbreviate any long skip names
you come up with so that's those two
input parameters the next input
parameter is overlay so by default
overlay is set to false and what this
means is that our script will draw into
its own window pane its own box as you
can see here it's drawing in its own
oscillator type box so this is useful
for scripts like the RSI stochastics
even volume that sort of thing but if
you want to draw onto your actual chart
you have to set this to true so if I set
this to true and I hit save first of all
I need to remove the script this
parameter to update and if we click add
to chart the script is now drawing the
closing price to the chart instead of
into its own oscillator box so it's save
again and I remove the script add it
back now it's in its own box so that's
what the overlay our parameter does the
next import is the format input so this
is for setting how the values number
values are formatted when they're drawn
to your chart so we only have to
formatting options if you type format
control space technically three inherit
price and volume by default it's set to
inherit which will
inherit your chart access formatting but
you can override this with whichever
formatting type you want so if we set
this to format volume and hit save you
can see that it is now drawing a 1 down
here I changed this to say 20,000 hit
save you'll see that it now puts a K on
the end and if we would have changed
this to say 20,000 420 and we hit save
now it says 20.4 2k that's useful for
creating indicators like your volume
indicator or anything that works with
volume and that sort of thing because if
you set this to price and hit save then
we'll get the exact number there so for
most scripts you're going to want this
exact number but for other scripts
especially ones working with volume this
formatting volume format can be helpful
so I'll leave this is inherit for now so
if I set this back to plot the closing
price and we move on I will show you
what the next input does which is
precision so the next input parameter is
precision and this specifies how much
precision to go into with your decimal
values so if you were to set this to 2
it's going to cut all these decimal
digits in the indicator value and it's
going to round the number up to the
nearest two digits so if I hit save
you'll see that this number will just
become zero point six nine and then as
it gets closer to 70 it rounds up to 70
there so we only have two decimal digits
and that's what precision does we go all
the way to 1 and then we'll just get 0.7
because it's rounding up zero point 6 9
to 7 so for most instruments on your
chart most markets precision of 5 is
about as much as you will ever need but
you can go higher if you want to we
could go to 6 I'm not sure what the
maximum precision is but it's a lot
there we have a precision of 10 that
might be helpful for analyzing
cryptocurrency markets maybe like
satoshis on some cryptocurrency markets
but by default this is set to whatever
your price
is so I'll leave that as five now and
we'll move on to the next input
parameter which is scale now this
parameter tells pine script which scale
to attach your indicator values to so we
have a number of options here by default
that's set to your main price scale but
if I type in scale and then control
space that'll bring up the list of
scales we have to choose from so if I
set the scale to scale dot left and I
save the chart save this script and I
remove the script from my chart add it
back on now you can see that the
indicator values are plotting to the
left scale so that's what this input
parameter does it allows you to move
which scale that your indicator value is
attached to so the final input parameter
we can work with is max bars back so if
you type in max underscore bars on the
score back this determines how far back
your script can reference historical
bars so I set this to 5 now our script
can only reference the past 5 historical
bars so that will be the maximum amount
of historical values we can go back so
it's very unlikely you will ever have to
use this input parameter I'm not even
sure why it's included but I'm sure
there's a reason for it
maybe for saving the amount of memory
that a script uses when calculating its
values if your script is failing to
execute because it's running into plan
scripts computer resource limitations
may be evil to use this feature but that
is all of these study annotation input
parameters we have to work with for your
average indicator you will only really
be working with these three values your
main title your short title and overlay
that's the most common three inputs I
use in my own scripts anyway so that's
it for this lesson I hope you found that
helpful if you did and you want to learn
more about Pyne scripts head over to pan
skip mastery com here you'll find my
advanced pan script courses and my
basics course which is free so if you
want to learn more about behind script
head over here and you'll find out a
little bit more about me and a little
bit more about Pine script I hope you
found this lesson interesting and
helpful I'll see you the next one
[Music]

How to use ARRAYS in Pine Script V4 to calculate CORRELATION & COVARIANCE

hi traders welcome back my name is
matthew from the art of trading today's
lesson
is going to be covering how to use
arrays in pinescript
we're not going to do anything too
complicated we're just going to
introduce you to the basics but we are
going to create something pretty useful
we're going to create a correlation
meter which is going to determine
exactly how correlated two different
markets are and we're going to achieve
that using arrays so if that sounds like
something you'd be interested in please
stick around hit the like button while
the intro rolls and we'll get started in
a second
so the script we're going to be working
with today does a couple of different
things
the first thing it does is it stores the
past
x amount of price data so in this case
we're going to use candle closes by
default
but you can change that here but we're
going to save the last
20 candle closes on the current market
and on our reference market we're going
to save those values
into two separate arrays and then we are
going to use some inbuilt
pinescript functions to analyze that
data
we're going to get the correlation
between
these two data sets and we're also going
to get the covariance well we need to
get the covariance first
and then we'll use the covariance to
calculate our correlation coefficient
now if all of that sounds like gibberish
to you don't worry
i literally learned most of this stuff
this morning it's not rocket science but
it is quite advanced for
a fool like me i have the equivalent of
math dyslexia
so if i can handle this you should be
able to too
and as we go through the lesson i'm
going to explain all of these concepts
hopefully in a way that makes sense
to you whether you are experienced with
this stuff or a complete beginner
so with all that said let's get started
so right now i have euro yen weekly
chart
up on my trading view charts the script
is drawing these red lines here these
red bars
are the s p 500 closes so if it closes
positive
that means the s p 500 closed higher and
if it closes
negative that means it closed lower and
by closers i mean
percentage gains so each bar on this
indicator box here represents the
percentage
change from the previous bar on the s p
500
but we can change this to whatever we
want so we could we could change this to
aussie yen for example
and now we're comparing the euro yen's
weekly candles to the aussie yen's
weekly candles
and as you can see here we have quite a
high correlation
the closer this black number is to 1 1.0
the more positively correlated these
markets are which just means that if one
market is moving up
then the other market is also likely to
be moving up
and the micro movements might not be the
same but the correlation number here the
correlation coefficient
can give you a rough idea of just how
correlated a market
is and what this would be useful for
there's a few uses you could use this
for
in forex trading the way i would use
this is i would
use it to determine which currency pairs
are likely to be
correlated so that i can manage my risk
accordingly so for example if i'm
trading the euro yen
and i'm long on the euro yen let's say i
have a high probability set up and i'm
aggressive with it i have two or three
percent
of my total capital involved in that
trade
it's probably not a good idea for me to
then open a trade on aussie yen
with the same amount of risk if these
two pairs are highly correlated because
all that means is that if one trade
loses
the other trade is likely to lose as
well and then i'm taking a double hit
for nothing what would be better in that
scenario if i do have two trading
opportunities on two highly correlated
pairs
would be to split my risk so if i have
one position on euro yen
that might be 1.5 percent risk and on
aussie yen i might have 1.5 percent risk
as well that way in the
unlikely or off chance that one of them
wins and one loses
i don't double my loss by taking a large
position on a correlated market
and there are other use cases for this
as well which we'll go into later
but anyway let's get into the code and
i'll explain what we're doing as we go
and if you're already lost don't worry
this should make sense by the end
hopefully this makes sense by the end of
the lesson
i'm going to do my best to explain all
of this stuff in detail
so let's get into the pine editor and
start this lesson just really quickly
before we get into the pine editor
i thought i should probably show you a
visual representation of what an array
is
it's basically just a list of data so
here we have
our values and they can be anything
so we saw that here they can be a float
an integer a boolean a color a string
and they're stored in these little boxes
which correspond
to a array index
so similar to historical operators for
price action like
referencing previous bars you can do the
same thing with arrays
now dealing with them in partnership is
slightly different to using the
historical operator
which if you're not sure what that is
that's the square brackets
to reference previous bars so you could
reference the previous closing price
like this you could also reference the
value corresponding with the array index
of one it's the same concept in theory
and arrays in partscript have a maximum
size of 100 000
data values which is quite large i don't
think there's many cases where you would
need to exceed that many
data entries into an array so that's
what an array is in pinescript just
think of it as a data set
with each uh entry corresponding to
a array index which starts at 0
and counts up from there in increments
of one and so in this particular case we
have
nine values an array length of nine
but the array index for the final entry
in this array
is eight because we do start at zero so
keep that in mind that takes a little
bit of practice
to get used to if you're not used to
dealing with arrays anyway let's jump
over to the pine editor and get into
this script first thing i'm going to do
is delete all of this code
and we're going to start from scratch so
that you can follow along
and see what i'm doing and i'll explain
what i'm doing
line by line all right so first things
first we just have a blank script here
we just have our study annotation
function you can call this title
whatever you want
i've set overlay to false because i want
to be drawing into my own oscillator box
or indicator box
and the first thing i'm going to do here
is always is get some user input
i'm just going to copy this code over
here because
hopefully by now if you've followed
enough of my lessons you should know how
getting user input works we're getting
three user inputs here we're getting a
look back period
our price source and our reference
market
so we're using the inbuilt in input
function just titling them
accordingly so the user knows what they
correspond to
and i'm setting the types our lookback
is going to be an integer this is how
many bars to look back
our source is a price source which can
be anything if i
minimize this and open this up here is
our price sources
and you can also choose from price
sources on indicators or markets that
you've
added to your chart so if we wanted to
we could calculate
all of this data based on an average of
the open the high the low and the close
or just the high the low and the close
for today's lesson i'm sticking i'm
keeping it simple i'm sticking with
close
and then the final input we're getting
is our reference market that's just the
type of input dot string
and this default value here if you've
never used the security function to
reference other markets other than the
one that you've loaded onto your chart
the format of this is you can either
just put in the string i could have just
put in spx 500 usd here
and that would reference that market
that ticker id this is the ticker id
but i like to also specify which
brokerage or exchange
i want to get that data from so in this
particular case
we're referencing the oanda exchange i'm
using the
semicolon to then reference the ticker
id
so this is the broker or exchange this
is the market
i want to reference and this works with
any
exchange if you go up into here and we
type in apple for example
you could write nasdaq apple so i could
change that to nasdaq and apple if i
wanted to
and then this would reference apple's
price from the nasdaq exchange
so that's it for our user inputs so the
first thing we need to do before we
continue is get the percentage
change of our reference data
so the way we do that i'm going to
create a variable here that
references the security function and the
security function takes a minimum
of three parameters or arguments
we need to specify the symbol we want to
reference
we need to specify the resolution or
time frame we want to reference
and we need to give it an expression
that we want to reference
so this could be anything this could be
an indicator expression
this could be any number of
code expressions that you could use in
pinescript
but for today's lesson we're going to be
keeping it really simple and we're just
going to be referencing
the source input so by default this is
going to be the closing price
so our symbol is going to be our
reference input
and our resolution is going to be our
time frame
dot period so that's whatever time frame
we've currently set
our chart to so right now i'm on the
weekly chart this would just
reference the weekly chart on our
reference market
so hopefully that makes sense so now
just to make sure that we're getting
the right data here let's plot our
reference data
to the chart say the script make sure
there's no compile errors
and there we go everything's working
fine if i go to spx 500 us dollar
this blue line should mimic the closing
price of this chart
i'll get rid of that don't need that so
um
it's on percentage right now three nine
three five
and three nine three five perfect so
so far so good and get rid of that plot
so the next thing we need to do
is get the percentage change of
the current bar on our reference market
compared to the previous bar
so to do that i'm going to create a new
variable called reference
change that is going to be set to i'm
going to open two
parentheses here i'm going to say
reference data
subtracted from our previous
bars reference data divided by our
previous
reference close multiplied by 100
this line of code here this expression
will give us
our reference markets change as a
percentage
so now if i plot this to the chart
reference change save the script oops
and i have a typo here
hopefully that's the only one there we
go minimize that
so now this blue line here is printing
the percentage change so up here you can
see that the current bar has a plus
0.84 percent change from the previous
bar and down here we have
0.8 or positive 0.8 so we are
calculating an accurate reading so
that's how we get the percentage
change in price next thing we need to do
is get the percentage change of our
current market
so to do that i'm going to create a new
variable called current data and this is
going to be set to our source
input so we want to compare the same
source
across our reference market and our
current market so if you were to change
this
default value to something like
ohlc 4 or open high low close
then it will compare the average of our
open high low close on our reference
market
to the average of our open high low
close on the current market
and again to get our percentage we can
pretty much copy this
line of code here i'm going to change
this to current
change copy current data we can paste
that across there
and now we're getting the exact same
percentage
change calculation but on the current
market instead of our reference
market so now we have our two value data
sets
all that's left to do is input these
into an array
and then once we have some data to work
with we can start calculating
our correlation coefficient so now we
have our two data sets we're getting our
reference markets change and our current
markets change all that's left to do is
input this data into two different
arrays
and then we can use those arrays to
perform some
statistical calculations so to declare
an array
it's extremely simple i'm just going to
comment this here
we're going to use the var operator and
if you're unfamiliar with the var
operator all that does
is it makes sure that this variable
we're about to declare does not get
reset on each new bar
it's only declared once on the very
first bar on our chart
as opposed to these variables here which
are not var variables
and these get recalculated on every new
bar on our chart
but since we're using arrays the whole
purpose of arrays
is to store data across all of the bars
on our charts so that we can perform
calculations
and analyze that data so if we don't
create these as var
arrays then these arrays will be cleared
and reset on every new bar in our chart
we don't want that so we use the var
operator to make sure that doesn't
happen and we're going to create two
arrays here
one's going to be called reference array
and the other other one
i'm going to call current array so
reference array
is an array or a list of our reference
markets
change in percentages and current array
is exactly the same but for the current
market
that we've loaded onto our chart and let
me change this market
so that we have two different data sets
here to work with so to declare an array
you need to use the array inbuilt array
object or um class and this array
operator just contains the list of all
the inbuilt array functions that we can
work with
in pine script so arrays behave very
similarly in pinescript to
lines and labels so if we were creating
a label here you would
write label dot new or line
dot new but for today we're using arrays
the main difference with arrays is that
there is a number of different
data types that we can reference so you
can make a color array
you can make a float array or decimal
point number array you can make an
integer array or whole number array
you can make a label array a line array
or a string
array today we're only going to be
working with floats
so floats are just any number with a
decimal place
such as a price or a percentage value so
the array
dot new float function if we click
control click
on this name this function name we can
get a rundown
on exactly how this function works this
function
can take either a single input parameter
or function parameter or
two function parameters so one is the
size
of the array if you're unfamiliar with
arrays
think of them like lists with the main
difference being that we need to specify
the length of the list before we start
working with it and
initial value is the initial value of
all array elements so this think of this
as like a default value
for your arrays we're not going to be
using the default value today
we're just going to be using the array
size and for our array size we're going
to reference our lookback
input parameter so i paste look back in
there
by default these two arrays will be
initialized as floating point arrays
with a look back period of 20 or a size
of 20 meaning that these arrays these
two arrays will hold
20 historical price
changes as percentages by default if you
don't change
this variable here in your script
settings then these two arrays will be
initialized with a length of 20
and so these arrays will store the past
20 bar changes as percentages
so because we have an array length of 20
here our look back is set to 20 by
default
so our array length is only 20
data values we need to make sure that
every time we add a new value
to our array we delete a previous value
to make room for it so the way we're
going to approach this
today in this script is we are going to
use a first in
first out approach if you're not sure
what that means there's a little diagram
here that's quite helpful
so we're creating a q version of an
array
you could also create a stack version
today's version is going to be q
so the first value that goes in gets
shifted down until we hit our array size
in this case will be 20. so when we have
20 values
in our array the first value that
entered this array
will be the first one to be deleted and
so we basically cycle through
with a first in first out approach an
alternative method
for using arrays is a last in first out
approach which is like a stack
so think of it like a stack of papers
you stack up a bunch of values
for whatever reason and there are some
cases where you don't want
to remove the very first value you want
to remove the last value that went in
first but for today's lesson we are just
focusing on a q
array so the first variable that goes
into our array is the first one to be
deleted when the array's maximum
capacity is reached
so in order to achieve that we need to
shift or remove
the last or the first entered
value from our arrays which is a
first in first out approach or fifo for
short
and to do that we need to use the array
dot shift
function and then we need to input our
array id
so id stands for our array variable name
so paste that in there that will delete
the very first data value we entered
into our reference array
before we add a new variable into this
array so this will make sense in one
second
because the next thing we're going to do
is
add the current values to
our arrays in order to add a value to an
array
we need to use the push function so the
array.push function you can think of
this as an array.add
function this will add our data value
to the specified array so the array
we're going to add to first is our
reference
array and the data value we're going to
add to this array
is our reference change so our
percentage change for the current bar
and by current bar i mean the current
bar that this script is running on so
this happens to be a historical bar then
that bar's
percentage change will be added to the
array and once our array hits our
maximum capacity
of 20 it will start deleting or removing
the first value that was added like a
queue and will cycle through those
values
as more data is printed to our chart so
i can copy this line of code here
and we can push to our current array
our current change is a percentage so
these four lines of code here handle all
of our array
operations we are first removing the
oldest
data value from our array before we add
any new
data values to our array
give me a second my cat wants to come in
here he doesn't like being locked out of
the office you want to help me
are you going to be annoying huh
this is hunter hunter s thompson if
anyone's wondering
what his name is there you go entertain
yourself for a bit
so now that we've set up our array
commands or functions
the next thing we need to do is
determine and plot
our covariance relationship so
covariance
i found a pretty good definition here on
investopedia
so first what is covariance
covariance measures the directional
relationship
between the returns on two assets a
positive
covariance means that asset returns move
together
while a negative covariance means they
move inversely or apart
covariance is calculated by analyzing at
return surprises or standard deviations
from the expected return or by
multiplying the correlation between the
two variables by the standard deviation
of each variable
now some of you will understand what all
of that means i don't
but the good news is we don't need to
understand this in order to use it in
our script
so let's go back to the pine editor and
determine
our covariance best of all we don't even
need to write the code
ourselves i'm going to create a new
variable here called covariance
and that's going to be set to array dot
co variance so this inbuilt function
will perform all of that calculation for
us
in a single line of code couldn't be
easier which is perfect for
dummies like me that have no idea how to
calculate this stuff
so to get the covariance we need to
reference two arrays
so that we can get the variance between
the two of them so we're going to
input our reference array here and our
current
array and we're done we're getting the
covariance
but before we continue we should
probably plot that data to the chart so
that we can
visually see what's going on so i'm
going to plot our covariance
value i'm going to give it a color of
color dot purple
i'm going to give it a style of plot dot
style
underscore area i'm going to give it a
transparency of 0
and i'm going to title it our co
variance
so now i'm going to save my script and
make sure everything compiles
and there we go working perfectly so as
you can see
throughout this period here which was
the peak of the covert
pandemic outbreak so if we have a quick
look
if we look at the 16th
of march on gold and we go over to the s
p 500 and look at the
16th of march from there you can see
that
since that day both these markets
have moved higher so
during this period we had a high a
positive covariance
or a directional correlation so these
markets were moving in sync
but that's not always the case there are
occasions when
we have a negative covariance and that
means that these markets
are moving in opposite directions so
anyway
our script is working as we wanted to so
let's finish writing our code and then
we'll go and look over a few different
covariance and correlation examples over
various markets
so before we calculate the correlation
coefficient
between these two data sets let's plot
our reference
market data to the chart just for visual
representation
so here i'm going to say plot our
reference data
we're going to use two plot functions
here one is going to plot our reference
change the other is going to plot our
current markets change and then we're
going to set the color of our reference
market to red our style to plot
dot style columns we're going to set
transparency to 10
i'm going to give this a title of
reference market
and then for our current markets price
change we're going to set the color to
blue
we're going to set the style to plot dot
style
histogram we're going to set the line
width to 4
and then i'm going to title this one our
current
market so now if i save the script we
should get a little bit of a different
visual representation
on the chart so the red bars here is our
reference markets percentage change
so each bar on our chart this red bar is
representing
our reference mark of the s p 500 its
percentage change on that same bar
and the blue number here is the
percentage
change of the current bar so you can see
here we had a 0.73 percent change on the
current bar
that corresponds to the same number up
here
so far so good let's wrap up this script
by calculating
our correlation coefficient before i do
that i should probably explain what that
is
so here we are back on investopedia i'll
leave these links in the video
description
and here's a short summary definition of
correlation coefficient the correlation
coefficient is a statistical measure
of the strength of the relationship
between the relative movements of two
variables
or two markets the coefficient values
range between
negative one and positive one if they
fall outside that range then there's
been an error
in the calculation so correlation of
negative one shows a perfect
negative correlation meaning that for
every dollar a market goes up
the other market goes down a dollar and
a correlation coefficient
of positive one shows a perfect positive
correlation
meaning that for every dollar a market
goes up the reference market
also goes up a dollar and finally a
correlation of zero
means there is no correlation no direct
correlation between the two
markets or two variable data sets so
ideally in your portfolio
depending how you've set it up you would
hedge your positions by
trading a market with a negative
correlation to whatever market you're
investing in and from a trading
perspective if you
are creating a trading strategy across a
portfolio of different markets
ideally you'd want a correlation as
close to zero as possible
because if you have a high correlation
between two markets that you're trading
uh it's the equivalent of doubling your
risk and obviously you can double your
reward that way as well but
it's just magnifying your trading
results if you can find two markets that
have
zero correlation or as close to zero as
possible
that's a good deal as far as portfolio
theory goes
or in other words the closer to zero
your correlation coefficient
is across all the markets you trade and
invest in
the more diversified your portfolio is
and so for investors your portfolio
might be a
bunch of stocks you want those stocks to
have as little correlation as possible
and for a trader you want your
strategies and the markets you trade
to have as little correlation as
possible at least in a perfect world
with currencies that can be a little bit
difficult which will show at the end of
the lesson
where we finish our script i will show
you the correlation
between several different markets so
before we calculate
our correlation coefficient between
these two arrays
or these two different markets we need
to get a little bit more information
first thing we need to do is determine
the standard
deviation of our two arrays or two data
sets
again just like this inbuilt function
here
pinescript has made this extremely easy
for us we don't need to even know what a
standard deviation is
it probably helps to know but we don't
need to because we can just use the
array.stdev
function which will get that value for
us so for our reference
market i'm going to create a new
variable called reference dev
short for deviation and we're going to
pass
our reference array into this standard
deviation
function and this line of code will get
our standard deviation
for our reference market copy this line
of code
change this to current deviation
and paste that in there change this to
current
array now we're getting the
standard deviation of our reference
market and our current markets data set
now that we have that information we can
calculate our correlation coefficient
which is
extremely easy there's no inbuilt
function for this as far as i know for
buying script
but it's easy enough to calculate all we
need to do is divide our covariance
by our reference deviation multiplied
by our current deviation that's it
this formula here will give us our
correlation ranging between negative one
and positive one so to prove that is the
case let's plot this
to the chart we're going to plot our
correlation
value to the chart it's going to have a
color of color dot black
a line width of two and a style of plot
dot um i'm gonna use a step line
for this just for something different
you could use plot this as anything you
want
but i'm trying to keep this varied here
and show you
multiple different ways to plot this
data to your chart
while we're at it and then finally i'm
going to title this our
correlation strength so this is the
strength of the correlation between the
two markers
oscillating so it's a form of an
oscillator i suppose between
negative one and positive one so that's
it our script is complete if i save the
script
hopefully it compiles without any errors
there we go
and now our black line here is plotting
the correlation coefficient
of these two markets so this number here
this black number
is our correlation coefficient between
the s p 500
and gold on the weekly chart and this
value is being calculated over the past
20 bars on our chart pretty cool pretty
easy
so that's the power of pine script the
concepts that we're working with here
may be very advanced this mathematical
concept may be quite advanced
but to achieve it in panscript couldn't
be simpler
so one last thing before we continue
this was something i did that
i thought was interesting i'm gonna just
paste this in here
i'm just creating three horizontal lines
here h lines
at positive one negative one and zero
if i save the script here i minimize the
editor
and let's just look at this visually
basically the
purple area here is our covariance
there's not a lot we can do with this
information in particular
but we needed to get that information in
order to calculate
our correlation coefficient now this
correlation coefficient
is much more useful than the covariance
because we can use this
as a gauge to determine just how
correlated two different markets are
and i'm going to show you exactly what i
mean right now i'm going to come up to
the settings menu
of our correlation meter go to style i'm
going to turn off covariance
and our reference market and current
market so now this black line
represents the correlation between
whichever markets we've set up here
so just to confirm that this is indeed
working
right now we're on the chart for gold
let's change our ticker to silver
and let's just see how correlated gold
is
to silver so now you can see this black
line
hovers very close to one which means
these two markets gold and silver are
extremely correlated
it stays above zero uh almost
indefinitely if we zoom out our chart uh
all the way to the beginning
of price action this market has
maintained extremely high correlation
directional correlation
to silver in layman's terms
that just means when gold goes up silver
goes up when gold goes down
silver goes down when gold goes sideways
silver goes sideways
in practical terms that means that if
you're putting
a lot of risk on gold you do not want to
put a lot of risk
on silver in the same direction because
then you're doubling your risk
essentially and for just a couple more
examples let's check the correlation
between
silver and the s
p 500
click ok uh we'll go to the weekly chart
i feel like the weekly chart shows the
best
representation so again after that
initial
panic sell silver has rallied quite
aggressively to the upside
so did the u.s stock market and so we
had a high
correlation coefficient between those
two markets
let's do something a little bit
different let's try a stock
so here is apple compared to
the s p 500 again during
the panic everything sold off and then
we had this strong rally
during this period we had a high
correlation coefficient
between apple and the s p 500
so hopefully now you're seeing how this
could be quite useful
in your trading process to identify just
exactly how correlated certain markets
are
let's look at one last example before i
wrap this video up let's go to a
currency pair like the euro dollar
and right now you can see that the
correlation between
the us dollar and the s p 500 is all
over the place there is no direct
correlation here
we hover around zero most of the time
but if we were to change our market to
let's say
euro yen now we have a high
positive correlation you can see that
this black line
stays above zero most of the time that
indicates a high positive correlation
let's change this to australian dollar
against the swiss franc
now we have a high negative correlation
so this black line stays below zero most
of the time
that means that often when euro dollar
is selling off
aussie swiss is rallying so there's an
interesting
correlation statistic there that you
would probably not recognize
if it wasn't for this sort of
information being plotted onto your
chart
so that brings me to the end of today's
lesson i hope you found that interesting
this was the most practical example i
could think of to use arrays
for there are obviously many different
ways you can use arrays
you could use them to calculate support
and resistance
zones potentially you could use it to
store
information so for example you could use
it to
store pivots or you know tests of
support
and resistance and you can check if a
certain zone gets tested more than three
times
maybe you can draw a h line across your
chart if
current price action is within an x
amount of percentage
of that zone that's a good example of
a way you could use arrays but there are
many many different use cases for these
most of them are quite obscure
and so i don't think i'll be going into
arrays much more
on youtube if you want to learn a lot
more about arrays and go into more
detail about them
check out pinescriptmastery.com i have a
course there the punch punishment
mastery course
where i'll be going into more detail
about this if and when students request
that
over the months to come as i become more
familiar with arrays myself
well that's it for today's lesson thanks
for sticking around to the end i
appreciate it if you found it valuable
please hit the like button
hit the subscribe button if you haven't
already i'll be back soon with more
lessons
on pinescript and uh yeah that's it for
today
uh good luck with your trading stay away
from exposing yourself
too much on correlated markets and i
will see you in the next one
take care goodbye

PineConnector TradingView Automation MetaTrader 4 Setup Guide

what's up Traders I'm Kevin Hart and in today's video I'm going to be showing you how to install Pine connecto...