Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Friday, May 17, 2024

Pine Script: ULTIMATE BEGINNER'S GUIDE! 💹 [2024]

 
hey what's up traders! welcometo my pine script basics course!this
is basically a stripped down version of my freepine script basics course the official version
on my website goes into a lot more detail it'smore geared towards complete beginners who have
never written a line of code in their life soif that sounds like you you might want to go
through the official material as there's a lot ofpresentations and information about programming in
general like how to get started what programmingis all the technical jargon i explain all of that
stuff in the official course i've stripped all ofthat out for this version because there's four or
five hours of content in my official basics courseon my website and i wanted to keep this video as
close to two hours or less as possible i thinkit's going to be a little bit over two hours
but it's going to be worth going throughbecause the material you are about to watch
will teach you everything you need to know inorder to get started with pine scripts and start
writing your own scripts i'm going to teachyou the core fundamentals of pine how to use
some of the more common basic functions likedrawing to the chart getting user input generating
alerts and referencing inbuilt indicators so ihope you find the course material interesting
if you do make sure to hit the subscribe buttonand like button and all that youtube stuff
and uh i hope you enjoy it i really doi'm really passionate about trading and
especially pinescript and i hope that passionrubs off on you throughout this material with
all that said i'll get my ugly mug out of yourface and let you get started with the content uh
have fun best of luck with your trading and i'llspeak with you in the lessons to come take care
hi traders in this video i'm going to be showingyou a basic overview and breakdown of the pine
script editor so the pinescript editor is inbuiltdirectly into the tradingview platform and you can
open it and use it directly through your browserso here i am on the tradingview platform to open
up the pine editor we just click on this tab hereso we click on that that will bring up the pine
editor so this is what the editor looks like whenyou first open it up with a blank script there are
a few things to go over here first of all you canopen existing scripts by clicking on this button
here if i open that you can open an existingscript from your own script library you can
create a new default built-in script so this willcreate a new script based on an inbuilt indicator
so if i scroll down to let's find the let's gowith a just a moving average if i click on that
this will create a new script with the sourcecode for the inbuilt moving average indicator
and if we come up and open a new blank indicatorscript that will open a new blank indicator
template and if we open a strategy this is thetemplate for a new blank strategy then we have
our new blank library script and this will createa new blank library now don't worry we'll go over
what each of these different types are there'sreally only three we've got an indicator script a
strategy script and a library script we'll go overall of these throughout the course next up we have
save so if i click save on this blank scripti can name this script it doesn't matter what
you name it but i would recommend getting into ahabit of some sort of consistent organized naming
system so for me for example i like to put 2021 orthe current year 2022 whatever the current year is
in square brackets in front of my scriptor something like that just to organize
my scripts if i open up my scripts here if igo open my script you can see that i have a
significant amount of scripts here and a lot ofthem aren't organized but i have recently begun
organizing them by a year and also by subject soyou can see i have a bunch of psmc scripts here
this is a part of script mastery course thisis from the previous version of this course
from version 4 of pine script from when pinescript was version four it's now updated to
version five so i'm re-recording this entirecourse so whenever i create a new script for
this course i will probably call it p psmc versionfive dash and then the name or something like this
that way when i open up my scripts i can just typein psmc and i get a list of all my psmc scripts
you don't need to do this but this is just a goodhabit to get into early if you plan on writing
a lot of scripts so let me open up a blankindicator here and save it and i'll call this
psmc v5 dash pine editor let me save that scriptand now we'll move on to add to chart so if i
click on add to chart that will add the script tomy chart and now we have our script here and then
next we have publish script this will publish yourscript to the trading view library we'll go over
this in more detail in a future lesson but this iswhere you can publish your script you can give it
a description as detailed as you want it to be umyou have your privacy settings so you could make
it a public or private script a private scriptmeans it's only visible to those with the link
a public script is visible to all uh traderson the tradingview platform but you can protect
your source code so that only you can see it butpeople can still use your script or you can make
it an invite-only script so that only you can seethe source code and you choose who can use it this
is particularly valuable or useful for creatingpremium scripts that you can charge traders money
to use such as my ultimate pullback indicatorwhich is a good example of using this invite-only
version of a public script but let's cancelout of this publish script dialogue and move
on to this little button here if we click onthis we have a whole bunch of resources here
so we can make a copy of our current scriptthat we have open we can view the pine script
official documentation we can view the plan scriptofficial reference manual this is the same thing
but as a pop-up so if i click on this we have thereference manual pop up within our browser this is
really useful when you're learning pan scriptif there's something that doesn't quite make
sense to you or something i haven't covered in thecourse material you can search through the search
box here for whatever that is so for exampleif we're looking at an rsi lesson and i don't
cover something in enough detail and you want tolearn more then you can just click on this ta.rsi
at the top of this list and that will give youthe reference manual for this function and it will
tell you in detail exactly how it works and howto use this function but let's close out of that
the next thing we have is our pine editor keyboardshortcuts this is a useful thing to look over
and try to memorize some of these keyshortcuts if i click on this drop down
box under pine editor we have a whole bunch ofkeyboard shortcuts for use in the pine editor
so for example you can save your script by justpressing ctrl s which is useful and then we have
a bunch of lesson resources here so the pinecodersand codify are kind of tutorials and examples
of how to use pine they're kind of just writtenguides one other thing to mention in regards to
the pine editor keyboard shortcuts is that whenyou're writing out your code pressing control
space will list all of the available functionsand inbuilt variables we have to work with
so for example if i wanted to see what technicalanalysis functions we have i can type t a dot and
then control space will list all of the functionswe have that deal with technical analysis so here
we have the atr if i click on that we now have theatr so if i put in a period length here like ta
dot atr 14 if i wanted to plot this to mychart i could just cut this ctrl x and paste it
into the plot function save the script andnow we're plotting the atr onto my chart
so this is the power of pinescript just how easyit is to get certain information and plot it onto
our chart but that's something to keep in mind thecontrol space feature of pine script is extremely
valuable you'll be using that keyboard shortcuta lot in your coding and i believe it's command
space on a mac next up we have this littlebutton here which just renames your script
then we have this favorite buttonif you click on this this will add
your script to your favorites menu so when youclick on the indicators and strategies button
your favorite scripts will be at the top of thelist up here mine are taking a while to load
because my internet sucks but yours should loada lot quicker than that hopefully and you can see
here that these are all my favorite scripts someof them are other people's scripts and some of
them are my scripts then we have the search buttonhere this is useful for finding and replacing
things in your script so you won't be usingthis very often on smaller or simpler scripts
but on longer and complex scripts this is a reallyuseful tool especially for refactoring or changing
parts of your code if you click on this littlebutton here that will drop down the replace text
box and in here we could write something likeatr let's replace atr with rsi to do that you can
click on this button which will replace the firstinstance of this atr so the very first time this
tool finds atr in your script it will replaceit with rsi if we click on the second button
it will replace all mentions of atr with rsiand if you want to add more filters to this
find and replace tool you can click on this buttonhere and we can match case we can match the whole
word or you can use regular expressions which isbasically patterns in text you don't need to worry
about this unless you're an advanced programmernow the final thing worth mentioning here is this
button here this is your revision or scriptversion button if i click on 1.0 that will load
into the pine editor the very first revisionof the script we have loaded into this editor
so this will load the script before i made thischange of plotting the atr so let me click on 1.0
and now we're back to our blank script andif i want to load the latest version of the
script i can click on 2.0 and that will loadback the latest version as far as i can tell
there is no limit to how many revisions every timeyou save your script and make a change to your
script there will be a new revision added to thislist so i have scripts with hundreds of revisions
and i can drop back to any prior version of myscript this is particularly useful for debugging
scripts so let's say you're trying to add a newfeature to a script and after several changes to
your script you realize you've broken somethingin the script and you can't work out what you did
using this as a as a sort of undo button canundo any changes you've made to your script
and reload a previous version so it's basicallylike an inbuilt backup tool in the pine editor
anyway that's about all you need toknow about the pine editor itself
in the next few lessons we'll cover somepractical coding examples i'll see you there
now before we get into actually writing code it'sprobably a good idea for me to go over some of
the basic things you will need to know about thecompiler for pinescript so the compiler is what
compiles our code converts it into informationthat trading views servers can understand so all
of this english written code will turn intocomputer code that the computer can run and
execute our commands the pinescript compiler isresponsible for doing that so when i click save
here i'm just going to delete this script after soi'll just name this delete my script just compiled
and i know it compiled because i didn't getany errors if however we do something like
this let me get rid of one of these parentheseshere and save the script now we have a problem
we have a syntax error this red line here now thewonderful thing about most programming languages
and compilers is that they will usually tell youwhere the error happened so we get the exact line
that this error occurred on it occurred on linesix this line here so that makes it really easy
for us to you can even click on this um it'sa link that will take you to that line of code
in your script if i click on that it takes mestraight there now every error message will be
different depending on what you messed up in yourscript a lot of these error messages are quite
cryptic so end of line without line continuationeven i don't know what that really means um it's
kind of it's amusing to me some of the errormessages you get in some programming languages
sometimes they're really helpful sometimes you'rejust like wow thanks compiler that was really
helpful so now if i close this off and save myscripts we don't have any errors the compiler
compiled our code without any problems let'stry getting rid of one of these quotation marks
save the script now we get a different errormismatched character this character here means we
have a new line starting so pan script got tothe end of this line and then a new line started
but it was expecting this quotationmark to close off this string of text
and so it through an error on line five so most ofthe problems in your script are going to be pretty
obvious and intuitive when you see an error popup usually it means you didn't close something off
you missed a comma you missed a bracket somethinglike that and within just a few seconds of reading
your code back you should be able to spot theproblem now some errors will be a little more
difficult to solve but in part scriptit's very rare that you run into an error
that can't be solved very quickly because usuallyit's a result of a typo of some kind and you don't
even need to know what the error message meansyou can just click on that line of code and see
at a glance that you missed something relatingto the syntax i will cover errors in your code in
much more detail in its own section of the coursetowards the end of the course so if you run into
any problems maybe jump ahead and check out thatsection but the last thing i'm going to show you
here is what happens if we get rid of the compilerdirective if i get rid of that and save the script
now we're going to get all kinds of weird problemsand errors with our code the reason for that is
that the compiler now doesn't know what version ofpanel script we're using so right now we are using
the original version of pinescript the versionlessversion of pinescript the first iteration of this
language i have no idea what the syntax is forthat language i wasn't around when that was a
thing i started using pine script when it was inversion three and so recently version five has
released so i've had to learn the new syntax ofpine script three times now i started with version
three so i learned version three syntax then itupdated a version four and i learned version four
syntax now we're on version 5. the good newsis it's not that much different to version 4.
if i set the version to 4 say the script we'llstill get the same error because in version 4 of
pinescript we don't use the indicator annotationfunction we use the study annotation function to
create an indicator so now my script just compiledfine and so it's very important that you keep
this compiler directive in and that you get yoursyntax correct in your code you don't need these
comments if you don't want them there this willcompile just fine as well the reason why we have
this compiler directive that allows us to targetolder versions of pine script is for backwards
compatibility so there are hundreds if notthousands of scripts that have been written from
the beginning of trading views existence that arestill very useful even though they were written
in an old version of pinescript and rather thanforce all of those coders to update their code
to version 5 of pinescript tradingviews simplyallow you to target old versions of pinescript
so that you don't need to update your scripts forthem to work the only reason you would want to
update your script to version 5 of pinescriptis to take advantage of the new features
of that version so i have dozens of indicatorswritten in version 4. i'm not going to convert
all of them into version 5 of pinescript exceptfor the ones that i use regularly now one last
thing i want to mention about the compileris that it is not particularly picky about
where you put some of your syntax for exampleif you have a plot function that has a lot of
parameters which we'll cover in future lessons youcan separate them across multiple lines now there
are some rules with this that takes some gettingused to but let me just quickly demonstrate what i
mean by this so for example we could put a spacebetween our plot and our parentheses save the
script and this will work just fine no problems nocompiler errors we can also split our parameters
across multiple lines so if i press enter hereand i tab indent this line of code and i save the
script we'll get an error in pinescript if youwant to indent your parameters across multiple
lines you need to put a space after your tab sonow if i say the script this compiles just fine
so the purpose of being able to do thisis maybe you have a bunch of parameters
in your plot function that stretch way off yourscreen you can separate these onto multiple lines
to make it easier to read your code so forexample if i put a comma here and then enter
i could say offset equals one comma titleequals plot close comma a line width equals two
comma and let's set the color to color dot blackand then let's move this parenthesis down one
line now if i save the script this compiles justfine so we'll cover this sort of thing in future
lessons i just wanted to make you aware of thefact that the compiler is quite flexible when it
comes to your syntax just so long as everythingis in the right order and you respect some of
the indentation rules which we'll cover in futurelessons as well but anyway i just wanted to make
you aware of the fact that we can do this sortof thing in pinescript the compiler will allow us
to separate our code across multiple lines undercertain circumstances as long as we respect
certain syntax rules i'll leave it there becausei don't want to overwhelm you guys with too much
information before we actually cover what all ofthese parameters do but now at least you know that
when we get into future advanced lessons that thissort of thing is possible if you need to separate
your code across multiple lines anyway that aboutsums it up for the compiler i'm sure we will run
into other issues that i haven't covered herethat we'll address in future lessons especially
the error section of the course so i'll wrapthis up here and i'll see you in the next lesson
all right traders welcome back i was thinkingwhile recording this material about my early
days as a programmer and i thought this wouldbe a fun lesson in this lesson we're just going
to plot the text hello world onto our chart nowtechnically we're already doing that you can see
i've got an indicator here indicator function withthe title hello world and that's drawing under my
chart but we're going to do something slightlydifferent we're going to plot a shape onto our
chart with the text hello world above it butbefore we do that i want to sort of reminisce on
my early days as a programmer i first discoveredprogramming when i was in high school i was
playing a computer game called runescape it wasan online computer game and in that game you
had to do a bunch of repetitive clicking tasks itwas like an old school game kind of like pokemon
where you had a little character that would runaround the screen and you'd have to click on
things to make him walk there or mine a rock ordo some fishing or whatever now i can't remember
where i found out about this but at some point idiscovered that some people were writing scripts
that were playing the game for them and performingsome of the more repetitive tasks that weren't fun
so there were elements of the game that were a lotof fun and there were elements of the game that
were extremely monotonous and boring a lot liketrading actually i'm getting ahead of myself but
that's kind of why i got into coding and tradingas well is i wanted to automate some of the more
boring tasks and hopefully this course will helpyou do the same in your own trading but anyway
back when i was a teenager i was around 14 or 15i discovered the world of coding in the context of
a computer game and so i was writing scriptsto perform tasks in this computer game that
i didn't want to do in real life because my timewas limited i had to be at school all day i'd get
home from school and only have a couple of hoursto play and i didn't have time to do everything
i wanted to do and so i wrote these scriptsthat would play the game while i was at school
and it would level up my character and do allthese things technically it was cheating and i did
get banned for it in the end luckily in tradingautomating your processes is completely legal
we're allowed to do that in trading but anywayback when i was learning to code this was before
the wealth of information on the internetyou couldn't just google how to learn coding
and be met with thousands of examples and guidesand i mean youtube was barely a thing when i
first started learning to code and there wasnot that much educational content on youtube
so i had to learn all of my coding frombooks i had to buy books rent books
from the library and it was a really monotonousjob learning how to code but i remember when i
got my first hands on a coding book to learn javaand one of the first lessons in that book showed
me how to write the words hello world into thecommand prompt on windows and i still remember the
feeling of getting that short sentence to appearon my screen it was absolutely exhilarating to see
my own work my own hands telling the computer tooutput something nowadays that's kind of normal
i mean everyone has some experience in scriptingor excel or just generally telling computers to
do something on your behalf but back then it waspretty revolutionary to me and so i hope that this
course can inspire that kind of feeling in youas we go through it i hope that you get excited
about what is possible with coding especiallyin pine script as you learn to translate your
trading ideas into code i hope you get excitedover the possibilities because they truly are
almost infinite almost endless there aresome limitations you'll run into as you
learn to code but for the most part most basicprocesses can be done in code and you can automate
a significant part or semi-automate at least asignificant part of your trading process your
analysis process setup detection indicator signalsall of that stuff but anyway for this lesson
let's just quickly write the words helloworld onto our chart to do that i'm going
to use the plot shape function now thisplot shape function takes a boolean
series meaning true or false so i'm just going topass true in here and in fact that's all we need
if i save the script we'll be having a cross drawnonto our chart you can see all these crosses here
drawing onto our chart um let's first of allset overlay to true so this is actually drawing
onto price action so let me save the scriptremove that and add it back to my chart
now let's add some text to this shape to do thatwe can use the text argument or parameter so text
equals and now let's write hello world and wheni save the script we're going to be getting hello
world drawn all over our chart on every bar hereso let me save the script and you can see it's
pretty unreadable we have way too many shapesdrawing onto our chart now so let's change
that really quickly let's just add on a booleancondition here let's say bar state dot is last so
now this will only draw our shape on the last baron our chart so let me save the script there we go
we are plotting the words hello world onto ourchart as simple as that literally one line of
code we have our indicator function you need thisline of code in every script same with this but
if we get rid of this and i save it technicallythree lines of code and we're drawing text onto
our chart that is incredible it's amazing howfar the world has come in technology back when
i was learning how to code it took over a dozenlines and a heck of a lot of times setting up the
programming language java the runtime environmentfinding a word editor a code editing they call
them integrated development environments theyweren't even really a thing back when i was
learning how to code in java or at least theyweren't available to everyone for free and now
in 2021 as i'm recording this we can do allof this in our browser right through the
tradingview platform in a handful of lines ofcode it's just it's absolutely phenomenal it's
so exciting the world we live in and what ispossible for everyday people like you and me
so this is just the beginning of your journeyas a coder and the beginning of your journey
taking your trading to the next level so i hopeyou're as excited as i am to teach you this stuff
and as excited as i was to learn this stuff inthe beginning believe it or not this right here
is the basic building blocks for every scriptyou're ever going to write in pine script
and it really is this simple you can obviouslymake this as complex as you want you can change
the shape we're drawing you can change thecolor you can change all kinds of things the
location of the shape all sorts of things butit's not difficult it's not complex all it is
is learning new habits and new rules codingis still in english this is all english words
but the rules in which we express the commands wewant to give pinescript are important but they are
very simple so you will learn them throughout thecourse don't be afraid if this is the first time
you've ever learned any coding if you followthe lessons step by step one after another
you will be able to write your own scripts bythe end especially if you take the whole mastery
course so strap in we're going to cover somereally exciting stuff in the lessons to come
i can't wait good luck with your tradingand good luck with your coding speak soon
all right traders so in this lesson i'm goingto be breaking down how comments work in pine
scripts so comments are basically a wayof leaving notes in your code for yourself
or for other traders or coders who readyour script so right here i have a blank
indicator script using the defaulttemplate that tradingview have created
and you can see two comments at the top here theseare automatically added to all scripts that you
create through the pine editor this top commenthere is saying that our source code is subject
to the terms of the mozilla public license andhere's a link to that license if you want to read
what this means here's the license here andjust really quickly while we're here i figured
we might as well go over this as i'm sure someof you are interested in what what this means
if you haven't seen it before but basicallythis just limits your liability as a coder
so it just says the covered software which is ourscripts is provided under this license on an as-is
basis without warranty of any kind the entire riskas to the quality and performance of the covered
software is with you and you being the script useror anyone who uses your script basically is using
your script at their own risk most open sourcesoftware will operate under a license like this
and then next up we have our copyright so this isa copyright and then it will automatically insert
your trading view username here now both of thesecomments are not read by the pinescript compiler
what that means is when the engine that runs yourscript through the tradingview platform does its
thing it ignores these lines it's like theydon't exist and this is all the compiler will
see in fact it will really only see this so thesecomments are really just for your eyes only and
the way you write them is with two forward slashesyou can put them anywhere they don't need to be
at the start of the line they could be after theline so i could say here i declare my indicator
here we could say plot the close and you can evenuse them to comment out code so let's say we want
to get the rsi here 14 period rsi on the closingprice let's say there's a problem with our code
or there's something we want to test and we wantto temporarily remove this code without deleting
it we can just add two comments in front of itand now this code is ignored by the compiler
so that is the purpose of comments to leavenotes to yourself one other purpose which
we'll cover in future lessons is what's calledannotation comments so this right here is a
annotation comment it's a special comment thatis not ignored by the compiler but technically
isn't code you could think of this as kind oflike metadata if you're familiar with metadata
so this is just telling pinescript that we want towork with version 5 of pinescript if we get rid of
this and compile our script we're now dealingwith the original version of pinescript which
had no version and we're going to get all kindsof errors because of that because the syntax of
version five of pine script is very differentto prior versions and by syntax i just mean
the grammar of the language the way we express ourcode is different in version five than any other
version if i bring back that annotation commentand save the script now it compiles just fine
so that's the purpose of comments we'll be usingthem a lot in our scripts i highly encourage you
to comment your scripts heavily it's always betterto have too many comments and not enough comments
the reason for that is there will be times whenyou write a script and you'll come back to it
weeks maybe even months or years later and youmight not remember why you did things a certain
way or why your code was written the way it washaving comments can help remind you why you did
what you did and it can help other traders knowwhat you're trying to do with your code as well
so if you're writing public open source scripts idefinitely encourage you to comment them and it's
just a good idea in general to get into a habitof commenting your code regularly and extensively
so that you know what you're doing and it's kindof like um if you remember in school when you
did math stuff you always had to show your workyou needed to explain how you got to your answer
comments are basically the samething using comments can explain
how you got to where you got to in terms of yoursolution in your code if i open up a script i've
been working on recently which is my zen libraryyou can see that this script has i think more
comments in it than actual lines of code in factit certainly does have more comments in it than
actual lines of code now that's not a normal thingyou wouldn't normally see that in most scripts but
because this is a library and we'll get intolibraries in future lessons i don't want to
overwhelm you with too much information but eachcomment here explains what each block of code does
in great detail the reason for this is that thislibrary is designed so that i could give it to a
complete stranger who knows nothing about me whoknows nothing about how i like to code and they
can work out exactly exactly to a t what everysingle part of my code does if i got rid of all
of these comments the code becomes significantlyharder to read because there is no explanation
on um what is happening if we get rid of allof these comments and we're just left with this
this is not useful to most traders mosttraders will see this and they'll just
move on to a different script becauseno one has the time to reverse engineer
and deconstruct exactly what this code doesbut by having all these comments suddenly this
script is much much easier to read for anyonewho um is unfamiliar with what the code does
so that's the purpose of comments we'llbe using them a lot throughout the course
so as i said before it's a good idea to get intoa habit of using them but don't worry you'll see
lots of examples of how to use comments in yourcode in future lessons so this doesn't quite
make sense to you don't worry it will by theend of the course see you in the next lesson
all right hey traders welcome back in thislesson we're going to be covering the indicator
annotation function now annotation function couldbe also thought of as like a directive function
it's a special function that tells pan scriptimportant information about the general nature
of your script so this comment here of at versionequals five is what's called a compiler directive
so this is directing the compiler to version 5of pinescript it's telling pinescript the engine
that runs pinescript to treat the code of thisscript by the rules of version 5 of pinescript
the indicator annotation function does the exactsame thing except that it tells pine script to
treat the code of this script as an indicator thereason we need to use this is because there are a
couple of different variations of script typesso we have strategy scripts so if i call this
strategy that changes the rules of this scriptif i say library that changes the rules again
so we only have three to work with indicatorstrategy and library but each of those have
different rules that govern your script for thislesson we're going to break down the indicator
function which is probably the script type thatyou'll be working with the most especially in the
beginning of your pine script journey so let'sbreak down the parameters of this function so by
calling this an indicator function that givesthe script access to a different subset of
inbuilt functions and commands to work with so forexample let's try and use a strategy function here
let's say strategy.close and we need to pass an idhere let's just say close our buy trade if i save
this script we'll get an error here that says youcannot use strategy functions in indicator scripts
please replace indicator with strategy so that'swhy we need to use these annotation functions if
i change this to strategy suddenly the script istreated differently by the pine script compiler it
has different functionality and features but let'sstick with indicator for this lesson and let's
break down what we can do with this indicatorfunction so if i hover my mouse over indicator and
hold down control or command on a mac and clickon this function on the name of this function
we'll get the pinescript language referencemanual popping up here and this will tell us
all of the various arguments we have to work withhere it'll give us a description of each one i'm
going to break down the most common ones here thatyou will most likely use in most of your scripts
so let's get rid of our title for a moment hereand hover my mouse over this function name and
we'll get a list of arguments so the first onewe have is title so this is your long title
so let's say i want to call this my super fancyscript and if i save this and move this down a
bit you can see that my script name has changedthere and if i were to publish this script to the
trading view library this is what it would becalled on the trading view library this is its
long title this is its more descriptive title butyou can see that it takes up quite a lot of space
on my chart and if we had a lot of plotshere a lot of numbers plotting out here
having a long indicator title name could be aproblem so let's say we want to abbreviate this to
msfs to do that we just add in a comma here allof our arguments in any function are separated by
commas so to add another argument or parameterto this function we need to put a comma there
and then i need to pass in short title and thenthis is a string as well so we open up with
two quotations and let's say we want to call thismsfs now if i save the script watch our title name
here it's now abbreviated to msfs but our officialtitle is still my super fancy script and if i were
to publish this to the training view library thatis still what this script would be called but when
it's added to our chart this is what it will sayin the indicator box so that's how our titles work
next up we have overlay so by default overlayis set to false so if i save the script having
it set to false draws into its own box you can seewe're in our own oscillator box here like the rsi
or stochastics macd those sorts of indicators theyare drawn into their own indicator box they're not
drawn directly on the price action like a movingaverage would for example but if you want to draw
overprice action say you're working with a movingaverage script for example you want overlay to be
set to true overlay just means it overlays overyour price action so if we set this to true and
save the script first nothing will happen becausewe've already added the script to our chart so to
update this particular parameter we need to removeour script by clicking on this remove button here
and then re-add it to our chart so now wheni click add to chart overlay will be updated
and it will be drawing over price action so if izoom in here you can see that this script is just
plotting the closing price so it's connecting theclosing price of all of these candles on my chart
directly over price action so that's what overlaydoes next up we have format so let's set overlay
back to false and remove the script save it addit back to my chart and let's say we want to plot
volume instead of the closing price so now let'ssave the script and it will update whoops we'll
update and now it's plotting the volume of eachbar on my chart let me go to the daily so that
we get a higher number here so notice this numberdown here is an exact number of the volume printed
um it's not that readable we don't really needto know the exact quantity of shares traded on
on a stock or in the crypto market how many of aparticular crypto asset was traded in this case
we're dealing with ticks price ticks on theforex market tick volume we don't need to know
the precise number so if you are dealing thisis mostly useful for volume this i don't really
know of any other use cases where you'd wantto do this but this format parameter you can
see down there above the blue underline format canbe set to format dot and if i press control space
or command space on a mac you get a list of thevarious formatting options we have to work with
here i'm not going to go over all of these youcan play around with these in your own time to
see what they do it's not often you will need tochange the format of your script anyway but in
today's example we're dealing with volume rightnow so let's click on volume and save the script
now keep an eye on this number here it's nowchanged to a smaller number with a k after it
so if i hover over the last bar on mychart that says 6.037 k so roughly 6 000
volume on this latest bar so that's the purposeof the format parameter in the indicator function
next up we have precision this is your decimalprecision so let me get rid of this format
for now and let me get rid of this reallyquickly and save the script to update it
um the precision argument changesyour decimal precision of the
numbers that draw onto the chart in your scriptso by default the precision is going to be set to
the decimal precision of your price so right nowwe have five decimals here on euro dollar if we
were to go to a different market like uh bitcoinfor example now we have a two decimal precision
and you can see after the decimal place herewe have two digits but if we wanted to override
that to a higher precision or a lower precisionwe can do that using the precision argument in
this function so let me set this to 5 and save thescript now you can see 5 decimal places after the
decimal place on this script now in thisparticular case we're just plotting the
closing price so that's not that useful seeingfive extra or three extra decimal places
on this price value but what if we wereplotting other values other indicator values
where we wanted to see those extra decimal placesbut we couldn't see them because of the number
of decimals on our price so for example whatabout a relative volume indicator let's say we
want to compare today's volume or this bar'svolume to the average over the past 10 days
and we want to know that number to a three decimalprecision instead of just two that's where this
argument comes into handy you can changethe precision override the precision of
your indicator plot values with this argument wewill be using this in future lessons but for now
we can move on i'll show you practical examples ofthis later on in the course next up we have scale
so this is the axis the scale axis you wantto plot your values onto so by default your
indicator is going to plot onto whatever priceaccess you have on your chart so in this case we
have price plotting onto our right axis but if wewanted this to plot onto our left axis for example
you can use the scale argument here so we can setscale to scale dot control space let's set it to
left and save the script and we need to remove thescript to update this and add it back to our chart
now you can see that our our values here are beingplotted onto the left scale not the right scale
so again not often you will need to do this butthere is the option to if you need to let's get
rid of that for now save the script remove it addit back to our chart so whenever you're dealing
with a visual update like scale or overlay youneed to remove the script and re-add it back to
your chart so if you make a change to your scriptand it doesn't update a general good rule of thumb
is to try removing it had it back on that willforce tradingview to update your script entirely
now the next parameter we have to work with is maxbars back this is not something you will often use
in your scripts i've never used it in my scriptsto be honest but it's here if you need to use it
now this tells the script how many bars back itcan reference from whichever current bar it's
calculating on so if we're looking at the finalbar on my chart and we set max bars back to 10
for example and i save the script whatever codeis running on this last script this last bar on my
chart the script can only reference the past 1 2 34 5 6 7 8 9 10 bars so only this price action here
now personally in my own coding i've writtendozens of scripts over the years i've never
used this feature i've never used this max barsback i've never had to i've never had a reason to
but if you do run into a situation where you needto use this function this feature this is how you
would do it you can set your max bars back to10 just keep in mind that this is in reference
to the current bar so when your script isrunning over historical price action each
bar on your chart can look back 10 bars and thenthis bar can look back 10 bars and then this one
etc so that's how that argument works but let'sget rid of it for now since we would rarely use
that the final parameter i'm going to cover herethat is commonly used is time frame so time frame
specifies what time frame your script can runon so for example let's drop down to the four
hour chart and change this to d short for dailyand save the script now my script is plotting
the daily time frame closing price onto my chartinstead of the four hour so if i zoom in here
you can see that each time this updates weget a new value down here so on this bar here
a new day began and the previous day's closingprice was five four six nine zero and then on the
bars in between we get n a because these fourhour bars are plotting in between the next day
and then on that next day's beginning we get theprevious day's closing price which was five seven
four eight seven and so on so that's one wayto hard code your script to only reference a
particular time frame i wouldn't recommend doingthis there are better ways to do this depending on
the script if you have a script that you only wantto reference a particular time frame you might
want to hard code it this way but if you have ascript that you want to be able to use on multiple
time frames you're better off using user inputsto specify the time frame of your script and we
will cover that in future lessons i don't want tooverload you with too much information so we'll
leave this lesson here if you want to see whatthese other parameters do again just hold ctrl
and click on this function name and you'll get alist of the arguments we have here with detailed
descriptions on how they work but anyway that'lldo it for this lesson i'll see you in the next one
hey traders in this short lesson i will introduceyou to the concept of namespaces so namespaces
in pine script are what we call the keywordsthat contain certain functions or variables so
that might sound a bit confusing but when i showyou a visual example it should make perfect sense
there are several namespaces that we have accessto in our pine script code the first one i'm going
to show you is the technical analysis namespace sofor example let's say we want to get the rsi value
to do that i can create a new variable calledrsi and we can assign this variable or initialize
this variable using the equal sign so rsi isset to and then we need to reference the ta
or technical analysis namespace so if iwrite ta here then a full stop and then
control space or command space on a mac we get alist of all of our technical analysis functions
so if i start writing rsi here is our rsifunction and you can see here that it is
underneath the ta or technical analysis namespaceso we'll click on that we pass in as price source
close and 14 default period there we go we havean rsi value and if i cut this plot down here
and change the plot from the closing price to thersi value we just retrieved let's save the script
we're now plotting the rsi so pinescript makesit really easy to access all of the most popular
indicator tools that traders typically use andyou'll find all of your indicator functions
under the ta namespace so that's really itfor namespaces that's all you really need to
know you can also create your own librariesum we'll cover that later on in the course
but when you create your own custom library itbehaves pretty much identically to these inbuilt
name spaces so for example if i type in import zenand the art of trading control space here is one
of my libraries i've created if i import this aszen i can now reference my zen library namespace
the same way we did the technical analysisnamespace so for example if i write here zen dot
control space command space we get a list ofall of my custom functions these are functions
that i created that i wrote in my own codein the zen library script and i published
this to the trading view platform i can nowreference all of these functions the same way
we can reference the inbuilt functions thattradingview offers what pinescript offers
but as i said we'll cover libraries in a futurelesson because it is quite an advanced concept so
i just wanted to make you aware of that featureand so you can basically think of a namespace as
a collection of functions or tools that you'vewritten either you've written or the trading
view pan script developers have created so beforewe end this lesson um we'll go over just a couple
of other namespaces for example if we're dealingwith strings so text this is a string right here
if i create a variable called my stringand we just call this a string of
text i can now use the string name space so stris short for string if i put in a dot and then
control space or command space we get a list ofall of the different functions we can use relating
to strings so for example um if i set this tothe text 10 and then i use the two two number
function and we pass in my string if i cut thatand paste that into our plot and save the script
we are now plotting the number 10 after usingthe string namespace to convert this text
into a number and there are a whole bunch ofother namespaces we have the strategy namespace
when you're dealing with strategy scripts so youhave your trade commands and various variables
that you can reference such as your currentaccount balance and things like that
we also have the request namespace which we'llcover in future lessons this is where you retrieve
or request financial data about stocks you canreference quandl which is a third-party resource
uh that offers all sorts of things like umsentiment interest rate information all kinds
of stuff we'll cover quandl in a future lesson andthen we also have the security function here which
we use to reference other symbols and other timeframes so you use the request.security function
to request for example we're on euro dollarone hour chart here maybe i want to check
what the daily high and low is and then plotthat information over this one hour intraday
time frame to do that we would use therequest.security function and so that is
a quick crash course on pine scriptsnamespaces and we'll be using these frequently
in our scripts so you'll get used to usingthese and you'll soon memorize them all very
quickly anyway that's it for this lessoni will speak with you in the next one
all right traders welcome to the price serieslesson in this lesson i'm going to be showing
you how to reference candlestick price data soyou're open high low and close this is obviously
going to make up the backbone of most of yourscripts you're going to need to reference this
data very frequently in your scripts since what isprice analysis without referencing price so it's
quite simple to access this data obviously thechallenge comes with what you do with this data
first of all let me get rid of precision onethat's from a previous lesson so here i have a
blank script let me save the script to show youso we're just plotting the closing price onto
our chart so by default this is the defaulttemplate for any new script we already have
our closing data being referenced and to referencethe other price points on your chart is as simple
as you might think so let's say we want to getour candle open price i'm going to declare a new
variable here called candle open and it's goingto be set to the open price value next up we'll
get our high so candle high is set to high then wecan get our candle low is set to the low and then
candle close is set to the close now you don'tnormally need to do this you can just directly
reference open high low and close in your scriptbut for today's example i thought this might be
a little more intuitive to see what's going onhere so now let's save the script and let's draw
these values onto our chart so i'm going to use acomment here say draw candle data onto our chart
i'm going to paste candle open in there copy thisand i'll paste it four times and i'll just paste
in each variable here and let's change the colorof each plot because if i save the script now
we're going to get four blue lines drawingon our chart and we can't tell what's what
so let's set the color of the open to color dotblue and now i'm going to copy this line of code
and paste it in and let's change the color ofeach data value here let's change the high to red
we'll change the low to green and let's changethe clothes to purple and save the script we
should get four different colors plotting onto ourchart here now and each color corresponds to each
candle price so it's as simple as that to getour price data which is what we're doing here
so now let's say we want to do something usefulwith this data let's say we want to get the
current bar's size in points so we want tosubtract the high from the low so now let's
create a new section of code here and i'll sayanalyze price data and for this we're going to
create a couple of variables the first variablewe create is going to be called candle size and
to calculate the candle size is really easy allwe need to do is subtract the low from the high
so high minus low will give us our candle sizein points and let's plot this onto our chart
as well so we'll call this candle size we'll setthis to color dot orange and in fact let's comment
out all of our open high low close because wedon't really need to see that data on our chart
save the script we should be getting an orangeline drawing here now which is showing the candle
size in points or pips in this case so right nowas i hover over the last bar on my chart here
our candle size is 6.9 pips so as you can see it'sreally easy to analyze price data obviously it
gets more complex the more complex analysis you'redoing but it's really simple to access this data
and to analyze it let's try something a littlebit more complicated to demonstrate the historical
operator so let's say we want to referencea historical bar on our chart this will
reference the current bar and this will run onevery bar in our chart so as i hover my mouse
let's hover over this bar here which is quitelarge if i hover my mouse over that you can
see down here this number says 65.2 pips sothis script is running on each historical bar
on our chart and so every bar on our chartwill reference its own open high low and close
but what if we wanted to reference let's say10 bars back so we want to reference 10 bars
in the past let's go back to our current bar andlet's say we want to compare the current bar's
candle size to the candle size of a bar 10 barsago to do that is really simple let's just create
a new variable here called candle size 10. andwe'll set that to the high of the bar 10 bars ago
minus the low of the bar 10 bars ago so toreference historical data we use square brackets
and then we pass in a number an integer number awhole number this whole number is your look back
count so this will get the candle sizeof the bar 10 bars ago so let's compare
these two values to do that we'll say candle sizeratio and we will divide our current candle size
by the candle size 10 bars ago and let's plotthat onto our chart as well candle size ratio
with the color of purple so when i save thescript we'll be getting another line drawing
onto our chart that is comparing the current bar'ssize to the bar size 10 bars ago save the script
and there we go so the current bar is 130 percentthe size of the bar from 10 bars ago or 1.3 times
and it's that simple that's how we referencehistorical price data very easy and this
historical operator works on any series of datathat we can reference in pine script so this
applies to indicator values as well it appliesto basically anything that has a series of data
that we can reference so for example let's saywe wanted to get the atr value of the current bar
to do that we could just create a new variablehere called atr is set to ta.atr and let's just
pass in the default 14 length periodso this will get the current atr value
and let's say we wanted to plot the atrfrom 10 bars ago we can do so just like that
so this plot function now will reference theatr value from 10 bars ago save the script and
now our white number here is drawing theatr of 10 bars ago really really simple
to reference historical data and this appliesto anything as i said we could reference the
volume from 100 bars ago if we wanted to let's say234 bars ago save the script now our white line
is the volume from 234 bars ago there is a limitto how far back you can look so if i set this to
99999 and save the script we'll get a error youcan see this little warning sign pops up here
if i click on that it says too large max totalbars back and then we have our large number here
the maximum is 300 000 bars which is still quite alot of bars so let's set this back to let's say 10
save the script and there we go so that's how youreference open high load close data that's how you
reference historical data using the historicalseries operator and this technique applies to
any value indicator values as well so if we wantedto compare the atr from 10 bars ago the same way
we did here we could just say atr 10 and thenatr ratio is atr divided by hr10 this will work
just fine the same way this did now obviouslythis is a pretty useless example of how to use
price series and indicator seriesin our scripts but in future lessons
we'll be covering more complex more practicaldemonstrations of analyzing price action using
this information and that brings me to theend of this lesson i'll see in the next one
in this lesson we're going to be covering thefundamental commonly used data types that you
will be using in most of your scripts to performyour calculations and analysis the first data type
you're going to be working with in all of yourscripts for the most part will be number types
so there are two types of numbers inpinescript we have integer type this is
whole numbers so for example 1 would be ainteger this could be 1 10 100 20 whatever
just as long as it's a whole number and there'sno decimal in it that will be called an integer
next up we have float type this is like aninteger except it has a decimal place after it
so any number with a decimal place is considereda float the reason this is called a float type is
because there is no fixed number of digits beforeand after the decimal place so the decimal place
can float around and so that's why they call ita float programming can be weird like that don't
ask me why that became a thing but you'll get usedto it so there's a lot of technical jargon you'll
need to learn in coding integers just mean wholenumbers there is more nuance to this for example
there is a maximum number that an integer can bebut you don't need to know about that because it's
extremely unlikely you're going to run into thatissue in pine script i certainly never have in the
three plus years i've been working on all kinds ofscripts but anyway moving on we have our floating
point numbers float type numbers um for examplea closing price is a float because there's a
decimal number in it you can see here on bitcoinwe have two digits after the decimal place that
means that this price here is a floating pointdata type next up we have it's not another data
type it's just a different way of using floatingpoints so float type e we'll call this and if i
were to say 0.1 and then use the mathematicaloperator e and then put 2 on the end here
what this is saying is return the number orthe result of this equation which is 0.1 times
10 to the power of 2. now it's not often you'llneed to use this if ever but the option is there
if you need to or if you're mathematicallyinclined for me personally i'm terrible at math
which is interesting considering i became a traderand programmer but that's a beauty of modern
programming you don't need to be good at math tobe a programmer but if you are talented at math
this is a tool your disposal the next datatype we have to work with is what's called
boolean values so a boolean data type issimply yes or no true or false one or zero
in pine script it's represented by the word trueand the word false so a bull type or boolean type
would look something like this true for true falsefor false so let me leave that as true this is
quite simple to understand you'll use this datatype quite a lot in your scripts in fact these
first three data types will make up the majorityof your scripts in terms of how you calculate
stuff the next data type we have that will becommonly used is color types so color types
in pine script are their own data type and toreference color data types you can use the inbuilt
data types that panes could provide if i type outcolor and then a full stop and hit control space
or command space on a mac and i scroll down youcan see a list of inbuilt colors here so if i
say color.red that will give the pine scriptinbuilt red color as a data type and this can be
passed into any of my drawing tools so for examplewe've got a plot here that is plotting our float
type e if i change this to say color equals colortype whoops and i save the script our line will
turn red so you can see there so that's whatcolor data types are like you can also use um
hexadecimal colors so if i wanted to color thisred in hexadecimal that would look like ff000
i save that we get bright red we'll coverhexadecimal colors in a future lesson
you don't need to know them in order to to usecolors in your script but if you are familiar
with hexadecimals from web development primarilythese are used in web development so if you're
familiar with working on websites you'll knowhow hexadecimal colors work or you can use a
hexadecimal color picker just look up hex colorpicker on google and this can be an easy way to
fill out custom colors in your scripts one otheroption we have to work with in pan script is the
color dot rgb function this we can pass in threevalues or four values actually red green blue
and transparency so for example if i wanted fullred i could type in two five five comma zero green
zero blue and zero transparencynow the transparency is optional
if i just put in rgb as two five five zerozero save the script this will stay red
actually let's change this color so that wecan actually see the difference so this will
now be bright green there we go because we've setgreen to full so rgb colors range from 0 to 255
0 being none and 255 being the maximum andif we wanted to change the transparency let's
say we wanted to make the line completelytransparent we could set transparency to 100
save the script and now the line will disappearfrom our chart but it's still plotting up here so
that's a one way of plotting values onto yourchart without the user seeing the actual line
being drawn i use this quite a lot in my scriptsto draw information onto the chart that i want
to reference in my indicator values butthat i don't want to see on the actual
chart such as stop loss sizes and things likethat don't worry if this was a bit confusing
we'll cover color types in future lessons ingreat detail and in more practical examples
the next data type we have to work with thatyou will commonly use in your scripts not all
scripts but some scripts will be the stringdata type so this will be string type equals
text so string is just what programmers calltext and in order to define it we need to put
two quotation marks on either side of our text thereason why we do that is if we just say text here
then pinescript doesn't know the differencebetween this and an actual function or variable
in our script if i save the script we'll getan error here it'll say undeclared identifier
text if we put quotation marks around it andsave the script will get no error because
now pine script knows that this is text nowyou can use quotation marks or you can use
single quotation marks as well that will workjust the same if i say the script this is
treated exactly the same as if we'd used quotationmarks so it's really just a matter of preference
which one you use i prefer to use the doublequotes personally just because i'm used to that
from other programming languages but if you'reexperienced in a different language and you're
used to using single quotes you can use them inyour scripts if you want to and just as a side
note while we're here if you want to includea single quote in your text you can't just add
another single quote because now that's treatingthis as a string and then we just have a single
quote on its own if i save the script we'llget an error because we didn't close off
this string here if we add a backslash in frontof this text pinescript will now know that we want
to include this quote within our string then thisbackslash is telling pinescript we want to include
this single quote within our text sofor example let's change this to it s
bullish now if we were to draw this onto ourchart using a label or any other text drawing
function a table or something like thatthis text would display on our chart as this
so this quotation would be included in thetext and the backslash would be removed
so that's the purpose of the backslash you canalso do things like backslash n and that would
move bullish onto a new line and so if we were todraw this onto our chart it would look like this
it's bullish on a new line there are severalescape characters you can use in your strings
we won't cover that in today's lesson becauseit's outside the scope of this lesson i'm just
introducing you to these concepts i don't wantto overwhelm you with too much information
and so let's just get rid of all this and goback to text and we'll cover escape characters
and stuff like that in future lessons so beforewe wrap up this lesson let's plot all of these
types to our chart and we'll just have a quicklook at what they look like so we have integer
type float type flow type e and bull type wecan't plot a boolean directly onto our chart
so we can only plot these numbers at the momentdirectly onto our chart so let me change this to
color dot white and i'll change this tocolor.white as well and we'll save the
script so now you can see that we're plotting ourinteger type as 20 it's just a whole number and
then our float type let me change my floattype to [Music] 33.3 and save the script
now here's our float type 33.30 now remember in aprevious lesson i talked about precision of your
script because we have two decimal placesafter our market price we have two decimal
places on our indicator values so even thoughi set this number to 33.3 it displays as 33.30
if i didn't want that i could change my precisionto one save the script and now it's certainly
plotting to one decimal place and so here we'replotting our integer number as a whole number
our float number and then our float typee number and in our integer plot we are
passing in our color type now let's use ourbull type here let's say if bull type is true
then let's overwrite our color type to color dotred so now when i save the script this color here
this plot will turn to red because bull type isset to true and we just said if bull type is true
override color type with the color red and tooverride something we need to use the colon equals
symbol we can't just use equals because that'sdeclaring a new variable we want to overwrite this
variable with this new one and don't worry we'llcover this in future lessons i'm just showing this
to you before we wrap this lesson up how balltypes work so now if i save the script this
color will turn red because bull type is true andwe've overwritten our color with red if i change
this to false the color will go back to greenbecause bull type is no longer true say the script
there we go so that's it for this lesson thereare several data types here that we'll work
with these are the common data types there areother data types too like tables labels drawing
objects things like that but we'll cover thosein future lessons once you become more familiar
with the basics of pine script so don't worryif you're overwhelmed by any of this lesson
throughout the course we'll be using all of thesedata types quite regularly in practical scenarios
and over time you'll learn how they all workand how you can use them in your own scripts
so that'll do it for this lesson ihope you're enjoying the course so far
and if you are stick around becauseit's about to get a lot more interesting
hi welcome back to another partnership lessonin this lesson we are going to be covering how
to appropriately uh or correctly declare yourvariables in your scripts so variables are used
in all programming languages we've already covereda few examples of them in this lesson we're just
going to keep things simple and cover the basicfundamentals of variable declaration in order to
declare a variable we need to basically give it aname and then that name is like a key so we have a
key and a value so in today's example we're goingto be counting candles in our chart so i want to
count how many green candles are on my chart soi'm going to say green candle count is set to zero
so right here we have declared a variablewe've declared a variable with the name or key
green candle count and we've given it thevalue 0. now pi script will automatically
determine what data type your variable is basedon what value you give it so pinescript knows
that 0 without any decimal places is an integervalue a whole number value so whatever we do
with this variable will be treated as an integervalue if we were to add a decimal place like 0.1
suddenly this becomes a float and now whateverwe do to this variable needs to be governed by
the rules of floating point numbers and thereare certain things you can and can't do with
data types so it's important that you understandhow the data types work the good news is you'll
pick this up throughout the course it's notparticularly complex but it is important that
you understand how data types work now you canexplicitly tell pinescript what type of variable
you want for example we wanted to tell pinescriptthat this green candle count needs to be a float
we can just add the word float infront of it and save the script
and now pinescript knows that even though there'sno decimal place after this whole number value
this essentially becomes 0.0 pinescript isnow treating this as a floating point number
even though we gave it an integer value now if wewere to change this to text for example a string
this won't work if i save the script pinescriptsays declared typefloat is not compatible with
the assigned type string so whatever data typeyou give it you need to make sure it's accurate
but the option to explicitly define what data typeyour variable is is possible using these data type
operators so this can be useful in certainsituations for example if i get rid of this
and i set green candle counter n a or not a numberthis is basically null nothing i've set green
candle count to literally nothing it's not a datatype of any kind if i then want to draw that onto
my chart so let me paste the green can accountinto the plot save the script you can see that
it says down here line seven value with n a typecannot be assigned to a variable that was defined
without a type keyword so we cannot declare greencandle count as n a but if we add float on the end
and save the script this will now compileand we are now plotting n a onto the chart
so that is one useful way of declaring a data typewith nothing as its initial value so we don't want
this to be zero we want this to be nothing theonly way to do that is to explicitly give this
variable a type keyword but we don't usually needto do this so i'm going to get rid of that and
set this back to 0 and save my script so now we'replotting just zero onto our chart on every bar
now let's say that we want to count every greenbar on our chart to do that we need to check if
the closing price is greater than the openingprice then set green candle count to green
candle count plus one now notice that i used thecolon equals operator here and i didn't just set
equals now the reason for this is because once avariable is already declared in order to overwrite
the value that we've given this variable weneed to use the equals the colon equals operator
to reassign this variable to a new value so forexample if i set this to 50 and i save the script
we will still be plotting zero here and we get anerror or a warning this orange writing down here
is a warning not an error it's just bringingto our attention that maybe we made a mistake
it says here that shadowing variablegreen candle count exists in the parent
scope did you want to use the assign operatorinstead of the initialize operator or equals
so when you're first declaring a variable you needto use the equals that initializes the variable
you can't use the assigned variable until thevariable already exists so if i save the script
now we'll get an error that green candle countis an undeclared variable so the equal sign is
for declaring a new variable and the colon equalsis for reassigning an existing variable and new
value so now if i change this to colon equalsinstead of plotting 0 onto our chart like we do
here if i use the colon equals we will now beplotting 50 because our green candle count is
being overwritten with the number 50 but onlyon bullish bars so let's say we want to count
all the green bars on our chart to do that we needto set green candle count two green candle count
plus one so that will increment this variable byone it will get whatever its current value is and
add one to it so let me save the script hereand you'll notice that on each bullish bar in
our chart we're only drawing one onto the chartand on bearish bars we draw zero the reason for
this is that our variables are re-declared onevery new bar on our chart so every time a new
bar historical or real time begins drawing ontoour chart our script code is run all over again
it just keeps looping our code so every time ourscript runs green candle count is set to zero
and so it never gets past one because on everynew bar this code is run again green candle
count is reset back to zero and then incrementedby one on bullish bars if we want this variable
to not update on new bars but to persist acrossall of the bars on our chart we need to use the
var operator so var converts this green candlecount variable into what is called a persistent
variable so this variable will now persist acrossall of the bars on our chart and so whenever
we detect a green bar the green candle countwill increment by one whenever we encounter a
red or bearish bar nothing will happenbecause our little if statement here
will not be true don't worry we'll cover ifstatements in more detail in future lessons
but for now if i save this script we will nowbe counting every green bar over historical
price data so if i save the script there youcan see that our line is incrementing slowly
from bottom left to top right if i reset mychart and hover over this last bar on my chart
we have 11 771 bullish bars on our chart fromwhenever our historical price action began
so that is the purpose of the var variable now thereason um not all variables of va are variables
are because let's say we want to draw a shapewhenever we detect a bullish bar if i change draw
shape to true and then we use the plot shapefunction and we pass in our draw shape variable
if i save the script now you can seean x plotting in our box whenever a
bar is bullish so for every green bar here we havean x if i change this draw shape to a var variable
and i click save all of these bars will havean x above them because the very first time
we detect a bullish bar draw shape will be setto true and it will never reset back to false
because we're using a var variable so let mesave the script here to show you what i mean
you can see we have all these x's if i go backto the very first bar on my chart using the alt g
shortcut here you can see that the very first barin our chart is bullish and so draw shape is set
to true and it is never set back to false becausethis is a persistent variable and so we draw xs on
every single bar if i get rid of var and save thescript now draw shape is reset on every new bar on
our chart and we want that to happen in this casefor this particular variable because we want it to
be reset on every new bar we want each new bar tobe considered as a brand new calculation so that
is why not all variables are persistent with thisvar tag and we need to explicitly tell pine script
when we want a variable to be saved across all ofthe bars on our chart this var can be useful for
all kinds of things such as saving your stoploss and target until one is hit and drawing
that onto the chart it can be useful for keepingtrack of certain market conditions so for example
maybe you want to check when the rsi goesoverbought so you would set your var variable
to true when the rsi goes overbought and then youwant to wait for a bearish candle and once that
happens maybe you enter short for example andthen maybe you reset your rsi flag or your rsi
overbought monitoring variable thoseare some practical use cases for this
variable type let's get rid of our draw shapevariable here for a moment and let's just count
every single bar on our chart to do that we canrename our variable to total bars and get rid
of our if statement and get rid of this and justplot total bars down here now before we continue
i should probably quickly go over the namingconventions for variables the most important
thing you need to know is that variables cannotstart with a number so if we change this to one
total bars and save the script we'll get an errordown here because you cannot start a variable
name with a number you can have it after text sowe could say t1 odual bars and save the script
that will work just fine you can have any numberon the end of your variable name and that will
work just fine you can have an underscore infront of your name your variable name that'll
be okay you can't use any other symbol sowe couldn't use a dollar sign for example
that will give us a compile errorso you can only use underscores
and text to begin your variable name andyou can have numbers and underscores in
your variable names but that's as creative asyou can get with your variable names so that's
important to keep in mind but anyway let's wrapthis lesson up by counting how many bars in total
have drawn onto our chart to do that all we needto do is increment our total bars by 1 whenever
our script runs on a new bar so let's save thescript and see how many bars drew onto our chart
there you can see a diagonal line allthe way from bottom left to top right
you can see that we've had 23 553 bars plottedonto our chart in total you could also get this
number by using the bar underscore index so if iplot that onto our chart you can see we get the
same number minus one the reason for that is thateverything in programming starts from zero and
so the very first bar on our chart isconsidered by our index zero and our script
would have incremented our total bars to one soin our scripts case let's plot total bars with the
color of color dot purple and save the script nowwe'll get two lines drawing um offset by one so if
i hover my mouse over this very first bar you cansee that our script says that this bar number one
whereas bar index says it's bar number zero thereason for that is that our total bars number is
incremented on the first bar whereas bar indexis not it's only incremented after that bar is
finished drawing so it starts from zero one twothree so on all the way to our final bar and our
total bars starts from 1 and counts all the wayup to the last bar so that about does it for our
variable declaration rules and fundamentals we'llbe covering variable declaration in quite some
detail in the lessons to come and in much morepractical use cases so again if this is all brand
new to you and you're a little bit overwhelmeddon't worry just keep going through this content
and eventually it will start to click you canalways re-watch the lessons or send an email
to support the artoftrading.com if somethingdoesn't make sense to you and i can help guide
you to understand these concepts better but withthat said that brings me to the end of this lesson
i'll see you in the next one where we will covergetting user input in your scripts see you there
okay so in the official pinescript basics courseover on my website at pinescriptmastery.com
this is where i would get into how toget user input from the settings menu
in your scripts now the problem i have hereis that this video alone is 40 minutes long
almost and would make this youtube video threehours long and i wanted to try and keep this
at two hours or less so instead of copying thislesson from the official course into this youtube
series i'm just going to briefly go over thebasics of user input so in the official lesson
i go into great detail about each input typeand all of the parameters we have to work with
when getting user input but for this lessoni'm going to keep things extremely simple we're
just going to get a couple of user inputswithout bothering with all of these extra
optional parameters and if you do want to learnthe specifics of all of the various advanced
user input functionality and features we have towork with in pine then it's definitely going to be
worth signing up to the official pine scriptbasics course and going through the material
so let's jump into the pine editor and go oversome basic user input so that you can at least
get started with adding options to your scriptsso here i am with a blank script all i'm doing
is plotting an a to the chart so that my scriptwill compile and let's get started with getting
some user input so the first type of input iwant to show you guys is a boolean input and to
get a boolean input which is just a true or falsevalue we use the input dot bool function and this
function has several parameters we can work withi'm just going to show you how to use the title
and the default value so i can title this sometrue false setting and set the default value
to let's set it to true save my code and nowi've opened up the little settings menu here
we have our some true false setting that we canturn on or off and we can reference this in our
script like we would any other variable the nexttwo inputs i want to show you are number inputs
so the first one is going to be an integer inputthat's just a whole number so input.int will get
you a whole number input again this has severalparameters we're only going to cover a couple
of parameters here the first one is going tobe title we'll set this to an integer input
we'll set the default value to 33 and we will setthe minimum value to zero and the max val to 40.
and let's also set the step to two so nowwhen i save my code i'll explain what each
parameter here does open up the settings menuwe now have a number input the step parameter
tells the interface how many numbers to incrementor decrement when we click the up and down arrows
here so if i click up you can see it's going upin steps of two and now that we've reached 39
we cannot go any higher because our maximum valueis 40 and because this up arrow is trying to
increment this to 41 it's not working you'd haveto type in manually 40. and that will work if you
type in anything higher if we type in 50 it willdo what i just did there just cut off the zero
let's try something different let's try 77. let'stry 99. yeah you can see it's just cutting off
the second number there and rounding down to thefirst number um and same with our minimum vowel if
we go down to zero because we're incrementing insteps of two we're trying to go to minus one but
we can't here because we've set the minimum valueto zero if i set this to negative ten save my code
open the settings now we can go down intothe negative numbers so that's how we
get integer inputs from the user let's have alook at float inputs or decimal numbers to do that
we just use the input.float title this decimalinput we'll give it a default value of 11.1 and
if i hover over this function name you can seeit has a bunch of other input function parameters
now i won't bother with min val maxval and stepi just showed you how to do that with integers
it's exactly the same with floats but whati will show you how to do is use the confirm
parameter so if i set confirm to true save mycode for this to work i need to remove the script
from my chart and when i add the script to mychart now that i've set confirm equals true
on this input variable watch what happens wheni click add to chart i now have to confirm
this input so this confirm dialog popped upanything you set confirm equals true to will pop
up when you first add the script to your chart andnow you need to set this to whatever this setting
is supposed to be then you click apply now whenyou open up settings menu everything is uh back to
normal so that's a float input very simple therepretty much the same as an integer one slightly
different input i'll show you how to use is theprice input so price input is essentially a float
input except that it's treated as a price value soif i set price input let's set the default value
to zero and set confirm equals true watch whathappens now when i click uh save and add the
script to my chart actually let me get rid of thisconfirming true since i already showed you how
that works this one is slightly different a priceinput is slightly different to a float input and
i'll show you what i mean if i click add to chartwe now have to set the price input price for our
basic user input script and you can see we havethis horizontal line that tracks with my mouse
this is making me forcing me to select a pricevalue with my mouse so for example if you're
writing a script maybe that detects candlestickpatterns around a support and resistance level
and alerts you so that you don't need to babysityour charts all day you could use this type of
input to place this line at a support level likei see here if i click right here and i open up my
settings menu my price input has now been set tothe price value that i just clicked on so that's
a really cool feature in pine you can also do thiswith time inputs so if i quickly show you a time
input input dot time and i forgot to mention ifyou press control space after you write input
here is a list of all the inputfunctions we have to work with
i'm not going to cover all of them because that'swhy the other video is 40 minutes long in the
main transcript basics course on my websitebut i will quickly show you how to use a time
input the same way we just uh used the priceinput so let's just set the default value to zero
and set confirm equals true and watch what happensnow if i get rid of the confirm equals true in our
price input and i save my code and i remove thescript and add it back to my chart now i have
to select the time input for this variable andwe now have a vertical line tracking my mouse
which is showing the time that i'm hovering overthis is perfect for something like an atr trailing
stop there is a video on my youtube channel ifyou search my channel for atr trailing stop i did
release a video lesson explaining how to create anatr based training stop where you use this type of
input to select where to begin trailing from andonce you select the bar the script begins trailing
below price action until price comes down andhits it so that's a really cool input there
now i think i'll wrap this lesson up here to keepit short hopefully you get the idea by now anyway
that will do it for this particular part of thebasics lesson video here on youtube if you want
to go into more detail about some of these otherparameters or some of the inputs i haven't covered
here make sure to go to pine scriptmastery.comand sign up for the basics course it's completely
free but there is a lot more informationthere there's at least a couple of hours
of extra content anyway with that said i will seeyou in the next lesson coming up right about now
hi traders in this lesson i'm going to be showingyou the fundamental concepts that you need to know
regarding alerts in pine script so there aretwo ways to trigger alerts in pine script both
ways depend on boolean triggers so true or falsetriggers if the trigger is true an alert is fired
if it is false no alert is triggeredso for today's example we're going to
keep it extremely simple i will cover practicalalerts for things like setup detection indicator
conditions that sort of thing in future lessonsfor now i'm just going to give you an overview
of the basic functionality of alerts so to dothat we're going to create a really simple uh
alert condition for this lesson we're going todetect higher closers and lower closers so hc
is going to stand for higher close and that'sjust going to check does the current bar close
higher than the previous bar's high and thenlower close is the same but the opposite
does the current bar close lower thanthe previous low and this is the first
time you're seeing the greater than and less thanoperators in a future lesson in the next section
we'll cover all of the different math operatorsand pine script operators we have to work with
don't worry about that for now basically todaywe're just dealing with two boolean variables
high close lower close if the current bar closeshigher than the previous high higher close is set
to true otherwise it's set to false and the samefor lower close but the opposite it needs to close
lower than the previous bar's low and so now wehave two different ways we can trigger alerts
with these variables the first way is to use thealert function the second way is to use the alert
condition function and i'll go over thedifferences now so first of all let's use
the alert function the way this works is an alertfunction triggers an alert as soon as it is called
so for example if we check if hc is equal to truefire our alert and this alert function takes two
parameters message which is a string and frequencywhich is an inbuilt variable or built-in variable
so we have three options here once per bar onceper bar close and both of these options basically
so if we set this to once per bar close thisalert will only fire if the current bar closes
as a higher close bar and the message can beanything so we could make our string anything
i'm going to say here that this bar closedhigher than previous bar and then i'm going
to add a colon on the end and then i'm going toadd on the current closing price of the bar to our
alert so to do that we need to use the tostringfunction because you cannot add a number directly
to a string and we need to use the str name spacehere we'll go over namespaces in a future lesson
but we need to say str.2 string and then passin our number and this will convert the current
closing price into text into a string and so whenwe get a higher close bar that closes so our alert
frequency is set to once per bar close if we get ahigher close bar an alert will be fired with this
text so that's one way we can triggeralerts it's quite simple really and now
you don't need to specify these parametershere the function will assume that the first
parameter you give it is a string so we could getrid of message equals i mean it will also assume
that the next parameter will be a alert frequencyso we can get rid of that so we have our alert
function triggering with a string argument anda frequency argument only on high close bars we
could do the same for if lower close i could copythis string paste it in there change that to lower
and now we've got an alert firing on alower close candle and just to demonstrate
that we can do it let's change this to frequencyonce per bar so this will not wait for the bar to
be confirmed it won't wait for the bar to closeso that's one way to fire alerts and it's my
preferred way to trigger alerts in my scripts butthere is also another option here and that is the
alert condition function so this alert conditionfunction cannot be placed in an if statement
it needs to be in your main script scope so itcan't be in an if statement it needs to be in
your main scripts sort of body of text so it needsto be checked on every single bar on your chart
and this function takes three parameters insteadof two the first is the condition the boolean
condition to trigger the function so in this caseif we wanted to trigger an alert for higher closes
we would pass in h c comma that's our conditionif hc is true then the alert will fire and then
we have our title so here i'm going to say umhire close alert and then we have our message
so for this i'm just going to say the same thinghere this bar closed higher than the previous bar
let's save the script and make sure thatcompiles and there we go no problems there
now how this will work is on our real-time bar onthe current bar in our chart this alert condition
function will check is hc true if it is thenfire an alert with the title higher close alert
and the message this bar closed higher thanthe previous bar now there are a couple of
differences between these functions the firstimportant one is that we cannot just add on our
closing price as a string here the same way we canwith this alert function if i save this script now
we will get an error cannot call alert conditionwith argument message equals and then our series
string so a series string just means a stringthat can change based on certain conditions so
the closing price can obviously change at any timethe alert condition function does not accept any
parameter that can change at any time it needsa constant string meaning a string that never
changes such as this right here the onlyexception with this is that we can use placeholder
tags so if i come up to the alert button here andclick on that and i scroll down to the bottom here
you can see this text here you can use specialplaceholders such as close time plot zero etc
if you click on this little question mark buttonhere you can see all of the different placeholders
we can use in our alerts and there are quite afew of them when we are using the alert condition
function the placeholder tags are the only wayto put in variables that change so for example
if we wanted to put in the closing price we wouldneed to do two curly brackets and then right close
and then to close curly brackets this placeholderwould be replaced by trading view when the alert
fires with the current closing price so now ifi save the script and we come up to the alert
button and i select our script alerts if i clickon this little drop down box here you'll see
that we have our any alert function call as anoption that is this function here so we could
set up an alert so that either of these get firedor we can select our higher close alert which is
our alert condition so if i click on that andi say once per bar and turn off my web hook
uh we'll cover web hooks in a futurelesson don't worry about them for now
but if i just set now an alert as thisis right now i've set it to once per bar
because the current bar's price is greater thanthe previous bar's high this alert should fire
immediately so let me click create we'll wait forprice action to move as soon as price action moves
there we go our alert is fired so you can seewhen i hover over that alert it says this bar
closed higher than the previous bar and then ithas the closing price so our little placeholder
here was replaced with the closing price youcould also put in the ticker if you wanted to
so now if i save the script and set a newalert and select hire close alert and click
create now we have a new alert that fired and youcan see that it now says the market the ticker id
of the market that fired this alert so that's howyou pass in dynamic information into your alert
condition functions the alert function on theother hand is a lot easier to pass in information
so this particular function is definitely thepreferred method for dealing with third-party apis
for example for trade automation using tradingviewalerts you would be better off using this
alert function if you can this alert condition onthe other hand is great for manual alerts because
you can give each alert a title so for examplei could copy this paste it down here change
this to lower close and change the condition toour lower close variable change that to lower
so here's our lower close alert and then let'ssay we want to merge both of these so we want to
say if we have a higher close or we have a lowerclose then we have a hclc alert and then we could
just say this bar closed higher or lower than theprevious bar now if i save the script and we come
up to the alerts dialog and select our scriptwhen i click on this drop down box we have three
different alerts to choose from here we have ahigher close level close alert high close alert
and lower close alert with their own titles sothis is really useful for setting manual alerts
in your scripts say you have a script thatis designed to help traders trade your script
manually and you want to detect things likea certain candlestick patterns or certain
indicator conditions that sort of thing this isa great way to separate your alerts with a title
to make it more intuitive for the user whereasthis any alert function call will literally fire
for any alert function call that we put in ourscript now if i were to create this alert nothing
would happen because i've set my alert frequencyto once per bar closed so we would have to wait
for the bar to close higher than the previousbar for this to fire let me get rid of this
close out of our alert frequency so this shouldnow fire immediately as soon as i set an alert
on this any alert function call so let mefirst click show pop-up and then click create
we'll see what happens there we go an alert justfired on euro dollar it fired based on the any
alert function call condition and we get our texthere that we wrote out here so this bar closed
higher than the previous bar and then we haveour bar price our closing price so for example
let's say we wanted to pass the current rsi valueto our alert as well we could replace um this bar
close higher than the previous bar and then setthe rsi value in there so now it will tell us
the current rsi value when we set our alert so letme select alerts leave that as it is click create
there we have it now you can see our rsi value nowthere's a lot of decimal places here um i'll show
you in a future lesson how you can truncateor cut excess decimal places off your alerts
but for now that's not important you can seethe the current rsi value over the 14 period
is 68.62 or 63 if we round it up and that'sreally all you need to know for alerts we
have these two methods for setting alerts bothhave their pros and cons the pros for the alert
function is that we can easily pass in values soprice values indicator values third-party syntax
for sending your alerts to a service thatautomates your trades based on your alerts
if you're using a service like that they willrequire a certain syntax for your alerts so for
example you might need to say um set my stop lossto and then in here you could set tostring your
stop loss price and then you might need to put ina comma take profit equals and then put in your
take profit price etc and then you could sendthis information to a third-party api using a
web hook using this so for example i've beenusing pine connector recently to automate
some of my trading strategy scripts if i sendthe right syntax in an alert message to this
url using the trainingview alert functionalitypi connector will automatically manage my trades
for me based on the commands i give it in myalert message and i can pass in my stop-loss price
breakeven distance trailing stops limit orderentry prices all that sort of thing just using
this technique that you see right here so that'lldo it for this particular lesson on alerts this
is the basic core functionality of alerts we'llcover more detailed practical applications of this
information in future lessons especially when weget into setup detection and indicator conditions
that sort of thing so i hope you found this lessoninteresting and i'll see you in the next one
hi traders welcome back to another lesson in thislesson we're going to be breaking down the plot
function and i'll be demonstrating how you canuse it to plot data onto your chart so the plot
function is used to plot numbers onto the chartand numbers only we can't plot any other data type
other than numbers using this particular functionso here we are just plotting the closing price
onto our little indicator box here if i changethis to anything else let's try and plot a boolean
plot true i'll save the script we'll get an errorcannot call plot with argument an argument of bull
type was used but a series float type was expectedso we can only plot numbers let's try a string
text save error cannot call plot with argumenttext an argument of string was used but float is
expected so we cannot plot any data type otherthan numbers using this function to plot other
data types we need to use other types of functionsbut the plot function is still extremely useful
for plotting things obviously like indicatorvalues and so on and so for this particular lesson
i'm just going to plot the closing price i'mgoing to walk you through the various parameters
that this plot function takes that we can use tomanipulate its output so the first thing it takes
is a series and this could be anything it couldbe a price value open high low close it could be
an indicator value it could just be a number thatwe want to plot so here we can plot the number one
across our chart we can also title the functionso i'm going to call this our plot save the script
and now if i open up the settings menu by clickingon this little cog icon here on the style tab you
can see that our plot now has a title if we don'ttitle our plot then it would just be called plot
so the purpose of titling your plots is to makeit easy for your user the users of your script
to know what your plot does and maybe they wantto turn it off or change its color or its style
the next parameter we have to work with with ourplot function is the color parameter so you can
set the color to anything you want by defaultit's usually blue but you can set this to any
inbuilt color or custom color that you want sofor now let's set it to purple save the script
and we have a purple line the next parameterthis plot function takes is line width so this
ranges from one to five i believe so by defaultit's one which is the thinnest line you can plot
if we set it to five it becomes very thick like soone valuable use case for this line width function
is when plotting things like a moving averagemaybe you want your longer term moving average
to be thicker than your shorter term movingaverage for example i created a script here called
multiple moving averages if i add that to my chartand we zoom out if i turn on all of the moving
averages you can see that they range from thin tovery thick at the bottom here based on the length
of the look back period for that moving averageso that's one useful practical use case for this
line width parameter the next parameter we have isstyle so this is the style of the data that we're
plotting to change the style you just type in plotdot and then control space and any of these style
built-in variables will dictate what your datalooks like so you can set it to circles save the
script now we're plotting um actual circlesunder the chart you could set it to an area
for example it's hard to see the peaks and valleysof this area because price action is so tight on
this time frame if we go out to the weekly we cansee a little bit more of that we could also plot
columns if we wanted to so if i set this tocolumns and save the script now we're plotting
price as a column so this is obviously mostuseful for something like plotting volume so if
we change the plot to volume now we're plottingvolume as a column let's change this back to
a simple line and i'll change our plot back tothe closing price as well now the next parameter
we have to work with with our plot function is thetrack price parameter so track price is a boolean
parameter true or false it's false by defaultso it's turned off by default but if you want to
turn it on you just set this to true and what thiswill do is just plot a horizontal line across our
chart like you see there which is tracking thecurrent price of our plot so if i go down to a one
minute time frame you'll notice this line movingaround as price action moves and it's literally
just tracking the price the current price ofthis plot the next parameter we can use in this
function is the hist base parameter so hist baseis short for histogram base and this is the base
price of histograms columns and let me open up theplot documentation so it says here that hist base
is the price value used as the reference levelwhen rendering plot with histograms columns or
areas so if i drop out to the four hour chartand we change our hist base to let's say 117.
if i set it to 1.17 and i set my style to stylecolumns and save the script our hist base is now
1.17 and so any value that prints above 1.17 willbe a column that prints in the upper half and any
value that prints below 1.17 will be in the lowerhalf so that's the purpose of hist base you might
have seen this style of plotting in somethinglike a macd and it works on columns as we just
saw it works on areas as well so there's an areawith the hist base applied and it also works with
histograms so if i save the script we get thesame sort of effect now let me change this back to
a simple line and get rid of our track price andhist base and we'll go over some of these other
parameters that we have to work with so thenext parameter we have to work with is offset
now offset does exactly what it sounds likeit offsets the plot so if we want to shift
this plot 10 bars to the right you would setoffset to 10 and now watch when i save the script
our line here will shift over 10 bars to the righthere so if you want to shift to the left you would
use negative 10 if you want to shift to the rightyou use a positive number so let's shift this line
10 bars to the right let me save this scriptand now you can see that the plot is plotting
with an offset of 10 bars so the current value isbeing plotted 10 bars to the right if we wanted
to plot this line 10 bars back you would just adda negative sign in front of that offset parameter
and now the line is drawing 10 bars back now thereare a handful of reasons why you would want to
use this offset parameter in your plots we'renot going to cover them all in today's lesson
but we will in future lessons when we get intomore practical use cases of these parameters in
actual indicator and strategy scripts so nowlet's get rid of this offset for a moment and
look at the last few remaining parametersthe next one is join and the join parameter
is a true or false variable and it basicallyjust adds a joining line between our plots now
when you're plotting a line like we are here youdon't need to use this parameter it's useless but
if we were using something like let's try a stylecross save the script zoom in a little bit you
can see these crosses have gaps in between themwe're plotting the closing price so it's jumping
up here as this big green bullish bar printedthe cross jumped up here if we set join to true
and save the script now we have a line connectingall of our shapes so any shape that has a gap
between it you can draw a line between themusing the join parameter and setting it to true
the next parameter we can work with is editableso by default all of our plots are editable but if
you want to stop the user from changing your plotfor whatever reason personally i've never used
this parameter but maybe there's a reason why youmight want to prevent users from editing a certain
plot in your script you can set this to falseso by default this is always true but if we set
it to false watch what happens before i say thescript we'll open up the settings menu and here's
our plot here if i save this script wait for itto update and then open the settings menu again
you'll notice that our plot style settings aregone we can no longer change the style of this
purple plot again i don't know why you would wantto limit the customization of your script by your
users but the option is there if you need tonow the next parameter we can work with is show
underscore last and show last basically justtells the script um how many plots to display
on the chart so if we set show underscore last to10 for example we will only show the last 10 plots
onto our chart so let's save the script and nowyou can see we only have 10 plots drawing onto the
chart so you won't need to use this often i neverhave but it could be useful in certain scripts
where you don't want to show historical analysisyou only want to show the most recent analysis
onto your chart for example maybe you wantto reduce clutter from your chart if you're
drawing something like support and resistancelevels for example maybe you don't want your
chart covered in lines that were drawn hundredsof bars ago you just want to show the last handful
and now the final parameter we have to work withwhen it comes to plotting data to our chart is
the display parameter the display parameter justbasically turns on or off the drawing of your plot
so by default it's obviously enabled but if youwant to you can hard code your plot to set it to
display.none and then the plot will not draw ontoyour chart this is great for debugging so maybe
you have some functionality in your script thatyou want to be able to check visually what it's
doing from time to time but you don't actuallywant that information drawing onto the chart all
of the time you can set display.none in your plotparameter and then in order to actually see this
drawn to the chart you need to come up to thesettings menu and turn it on here by clicking
on this little checkbox now when you set thisto display.none it does stop drawing the actual
indicator value as you can see here we don't getour value plotting so this essentially just turns
the plot off completely but let's say that youdon't want the data actually plotting onto your
chart but you still want to see the number thebest way to achieve this is using transparency
now we'll cover the color functionality inpan script in a future lesson we won't go
into detail in this lesson but just really quicklyto show you how it's possible to set a plot to be
transparent you can use the color.new function sohere i'm creating a new color i'm using the color
dot new and then passing in the purple colorif i add a comma on the end here and type in
100 and then close off this parentheses we openedhere we're now creating a new color of the color
purple with 100 transparency and now if i savethe script you'll see our plots disappear but the
value is still plotting on the indicator statusbar so this is another great debugging tool
or a way to plot something like the atr forexample maybe you want to plot the atr in your
script but you don't want the atr actually drawingover the top of price action this is how you could
go about doing that and that brings us to theend of this lesson i'll see you in the next one
let's have a look at one of the most simpletechnical analysis conditions we can check for
in pine script which is moving average crosses nowthis is not a trading lesson i do not encourage
you to trade moving average crossovers and crosshunters they may be profitable with the right
rules the right set of rules and entry reasons etci personally don't trade them but for the purposes
of this lesson they are a great example of howeasy it is to detect certain market conditions in
pine script so to get started we of course needtwo moving averages in order to detect a cross
so let's get some mas and again just todaybecause it's my favorite moving average i'm
going to use an ema an exponential moving averagebut you can use any moving average type you like
i'm going to set ema 1 to ta.ema and we'll baseit on the closing price as always and this one
will have a length of 50. and then the secondema will have a length of 100. so now before we
proceed let's draw the mas onto our chart and iwill style the first one with the color of color
green and the second one can be red so let's savethe code make sure that this is working fine there
we go two moving averages on our chart now let'sdetect our crosses our crossovers and cross unders
so we'll create two variables here two newvariables called ma cross over and may cross
under now for our crossover and cross underwe're going to use the inbuilt function t a
dot and then if i start writing cross here we haveour various options now cross will detect either a
crossover or a cross under for today we're goingto separate these two into their own variables
and so for crossover i'm going to use crossoverobviously and for cross under we'll use ta.cross
under and now these functions take twoparameters two values that need to cross
these could be any values they don't need tobe moving average values they could be anything
macd lines for example um or the rsi crossing overa certain threshold for today we're just going
to put in ema1 and ema2 if i copy that into oursecond function here we are now detecting our m8
crosses and at the bottom of our script i'm goingto draw crosses and here i'm going to set bg color
to ma cross over question mark if the movingaverage has crossed over the other moving
average if ema1 is crossed over ema2 i'll set thebackground color to color.green otherwise i'll do
nothing with the background color set it to n ai can copy this line of code paste it underneath
i'll change this to cross under and we'll changethe color to red and now if i save my script
we'll be getting the background color of ourchart changing based on which cross happened
so click save and that will do it for this lessonvery simple one here just again introducing you
to the ta namespace and combining some of thethings we've learned so far to create practical
uh indicators that can be actually useful in ourtrading anyway i'll leave this one here and i'll
speak with you in the next lesson the source codewill be below if you want to play around with this
hello my friend well done you made it to the veryend of this very long video congratulations you
are one of the few traders who actually committo learning this stuff obviously i have access
to the metrics and analytics of my videos in bothyoutube and on my course website and you would be
surprised how few traders actually commit andmake it to the end most give up halfway through
so well done for making it this far you should nowbe able to go out and start playing around with
pine script and start writing your own scriptsbut if you do run into trouble or you want
further guidance make sure to check out my masterycourse i recently re-recorded all of the content
for pine script version 5. so this is the new andimproved version i've stepped up the content a lot
and the new course has over 140 lessons andcounting i haven't even started recording the
strategy section yet i'm about to start doing thatthis week so if you found this free basics course
interesting i think you will love the masterycourse we have a lot of great reviews here from
traders who have gone through the courseyou can come and read these here if you're
not convinced that it's worth your time andmoney there is a lot of content here from
obviously the basics which we just covered to umsome of the more intermediate things like how to
analyze price how to detect candlestick patternshow to use all of the various inbuilt functions
and variables as well as the inbuilt indicatorsi've got a lot of material on indicators here then
we go into information about accessing other timeframes and markets using the security function
we cover arrays this is still inprogress this material here arrays
are quite an advanced subject as far as pinescript is concerned we cover libraries and
soon i will be expanding into strategy scriptsand even automation how to automate your pine
scripts through third-party apis so if thissounds like something you'd be interested in
head over to my website pine scriptmastery.comi have another course here as well where i share
the source code to all of my published indicatorsand strategy scripts including a bunch of private
scripts that i've never actually released andthe source code to my really popular ultimate
pullback indicator which is the most advancedand sophisticated profitable trading script i've
ever written but anyway i'll leave it herethanks for watching the video again if you
liked this content make sure to hit the subscribebutton because i will be back soon with more free
pan script material if you're not yet ready tocommit to learning more about pine script and
signing up to the mastery course at least hitthe subscribe button because i definitely will
be back soon with more free content with all ofthat said well done getting to the end good luck
with your trading i hope you kill it out there inthe markets i hope pinescript helps you to enhance
your edge and take your trading to that next leveland i'll leave you here have a great day or night
wherever you are in the world whatever time it isand i'll speak with you in the next video goodbye
[Music]
[Music]
you