what's up Traders I'm Kevin Hart and in today's video I'm going to be showing you how to install Pine connector into metatrader 4 so that we can automate our trading view scripts now I've already done a video on metatrader 5 that is the platform I will be using personally to go through the rest of this series but for those of you who have a broker that does not offer metat trator 5 or you prefer metat trator 4 I'm going to quickly show you how to set up Pine connector for this platform now if you want to know more information about Pine connector go and watch the metatrader 5 version even though it shows you how to install Pine connector on metatrader 5 I also go into a lot of information about what Pine connector is and how it functions and I'm going to skip all of that for this video to keep it really brief I don't want to repeat myself unnecessarily so if you're new to Pine connector and you have no idea what it is go and check that out uh the metat trator 5 version of this instructional video now before we continue I need to mention that this is not trading advice I'm not a financial adviser this is risky stuff if you don't know what you're doing if you're not a competent Trader I recommend you stay away from Pine connector or at least spend a lot of time on the demo account before you even consider uh live trading using this expert advisor there is a lot that can go wrong you can lose money very quickly if you don't know what you're doing but in this video series on Pine connector I will walk you through each step of the way and for those of you who are comfortable with the risks involved in automated trading we will automate a script by the end of this series I can't promise it'll be profitable cuz it's an example script but I will show you guys how to set up a fully automated script through trading View and pine connector so that you can execute trades on your broker while you sleep anyway with that out of the way let's continue with the instructions let's download the windows version of metatrader 4 and let's install this onto my system next and then click finish we can close this tab I need to select server 01 next existing trade account paste in my um metatrader account number I'm going to change these account numbers these are demo accounts anyway way um but if you're doing this yourself don't give this number out uh because people can try to screw around with your account so click finish to log in hopefully this works there we go incoming mail there we go we have logged in and once again we need to turn off these obnoxious sound effects so I'm going to go to tools options events and stop that click okay there we go all right so let's jump over to the Pine connector instructions and download the metatrader 4 expert advisor for Pine connector so here I am on my members portal the first thing I need to do is change my account number because I've already set this up on metatrader 5 so if I go to file uh login copy this number and paste it in here now my license will work with this new metatrader account number now you need to use your own metatrader account number number this will not work with my number it needs to be the one you've logged into your platform with so now that I've done that I need to download the metatrader 4 expert advisor so I can open this folder up right click this EX4 file cut open up metatrader go to file open data folder then we need to go into mql4 experts and paste this file into here now I can open up my expert advisors tab down here right click on this and click refresh and here is our Pine connector expert advisor but before we use this we need to change a few settings so we need to come up to tools options um expert advisors we need to click to allow automated trading and we also need to allow these dll Imports now this allows expert advisers to do things like access the internet outside of the platform which is required for uh Pine connector if you're not comfortable with this make sure to reach out to the Pine connector support team to discuss any apprehensions you have but personally I trust these guys I've used them for a couple of years now so I'm going to allow that click okay and the final thing we need to do is make sure this is turned on make sure this is green um now let's go through the instructions here if I click EA guide let's make sure I haven't missed anything we click on metatrader 4 I've downloaded the EA I've installed it into my data folder into mql4 I have allowed dll Imports I have enabled auto trading the final thing to do is attach the pine connector EA to my chart so I can right click this and click attach to chart now I need to come to commment make sure allow live trading is turned on and allow dll Imports is turned on as long as these two options are on the expert advisor should be able to execute trades through our broker through the metatrader platform now we need to come to inputs this is where we put in our license ID now there'll be a link in the video description if you haven't used Pine connector before it's an affiliate link so if you do sign up I do get get a small cut of your payment at no extra cost to you so if you want to support the channel that's one way to do it but if you don't want to support the channel for whatever reason uh that's fine to just go to the Pine connector website and sign up for a free trial you get a 7-Day free trial um get your license ID from your uh the main site dashboard so if I go to members portal scroll down and copy this number I can paste that into here and click okay and now assuming I've done everything correctly this should enable Pine connector there we go we have successfully connected to Pine connector's server everything is good to go so let's jump back over to the instructions here I've allowed live trading and dll imports on the expert advisor settings tab I've inputed my license ID we have successfully connected to the server so our connection is good um the final thing to do is send a test alert to make sure this is working correctly so first we need to find a symbol so if we go back to to metatrader and I go file uh or view where is it here symbols you can press control U on a Windows computer or just click symbols here uh we go to FX Majors we need to make sure that the symbol we want to trade is enabled so if we double click on these you can see they turn gray that means that trading is not enabled on these symbols and the expert advisor Pine connector uh will not be able to execute trades on these symbols if we send alerts to these symbols so we need to enable all the markets we want to trade once these are enabled we can click close now notice in my symbols list we're going to send a test command to open a long trade on euro dollar and my euro dollar symbol in this list has a suffix so depending on the broker you are using you may have a prefix or a suffix on the market you want to trade in my case I have a suffix which is a full stop a I need to send this entire string to Pine connector in my alert if I want to open a trade on euro dollar so let's do that now let's scroll down through the instructions we have enabled euro dollar we have gone over the suffix here so the final thing to do is um copy this line here go to trading view let me delete the metatrader 5 test alert click ADD alert make sure that euro dollar is selected um I went over this in the metat trader 5 version of this video but it is IDE to use the same broker feed you can see here this says pepperstone that is the same broker I'm using on my metatrader platform this is not necessary you don't have to use the same um data feed as long as you send the correct symbol the correct symbol oh my goodness Euro doll. a as long as I send this to the correct link with the correct license ID it doesn't matter what Market I trigger this alert on the trade will go through to Pine connector here but obviously does help to be using a data feed that is as close as possible to whatever your uh metatrader platform is using so in this case I'm using euro dollar on metatrader and uh trading view through pepperstone um and the data feed is pretty close so we shouldn't have too many issues with trades being executed at um different prices on both platforms so now I can paste in what I copied from the pine connector website and now I need to replace my license ID and my symbol with the corresponding parameters to trigger an alert on euro dollar so to do that I can come back to this page copy my license ID I paste that in here now this license ID again corresponds to your metatrader account number so you can't use my license ID don't even bother trying you need to create your own um but there is a one week free trial for those of you who aren't ready to commit any money to this and you just want to play around make sure to sign up to the free trial um go to your member dashboard copy your license ID in here buy means we are going to buy at Market risk equals 1 means with the default um expert advisor settings with the default settings here uh we will go over these settings in detail in future videos but for now using the default settings sending a risk equals one command will open one standard lot on the symbol we specify and for the symbol remember we need to type out the um the market we want to trade and then the suffix so a now I need to change my condition to greater than zero and now this alert will trigger as soon as I create it and price moves because obviously price will always be greater than zero unless the world has imploded and the euro is no more uh but hopefully by the time you watch this video that hasn't happened anyway the next thing we need to do is come to Notifications make sure web hook URL is turned on and this link is pasted in you can get this link from the uh instructions here so you need to copy this URL paste it into the web hook turn the web hook on all of these other settings do not matter they're optional if you want to be notified when your script executes a trade then you might want to set these up when you create your alerts but for today's test we don't need to worry about that um and it looks like we're good to go I'll just change this to Pine connector test mt4 now when I click create this should trigger immediately and we should either get an error in the experts tab or trade should be executed there we go it looks like our trade executed just fine there we go we have a trade opened we have opened one standard lot on euro dollar at Market um using an alert sent from Trading view amazing stuff now if you get an error in this experts tab uh when you try to trigger this alert if there's an error code here like a number then you need to come to pinec connector.com error and then if you you search for your error code um there should be a description on what the error means and Rec and recommendations on how to rectify that error but we didn't get an error luckily uh this works straight out of the box with the default settings so I can wrap this video up here and in future videos we will go into more detail about the settings of this expert advisor I'll be doing most of my um personal examples on metatrader 5 but you guys should be able to follow along on metatrader 4 if you're using metatrader for because these settings are pretty much identical on both platforms with all that said I'll wrap this video up here I'll speak with you in the next one take care and good luck with your training
Sunday, 20 October 2024
PineConnector Settings Guide - Automate TradingView Scripts
hey what's up Traders I'm Guy Sebastian and in today's video we're going to have another look at Pine connector today we're going to break down the pine connector settings and the syntax commands for sending alerts from Trading view to metatrader to autot trade our Pine script indicators and strategies I'm going to open up the settings for this expert advisor um in the previous video I recorded on a 4K resolution so you'll notice this dashboard thing looks kind of janky in the first video of this series I'll record on 1080p for the rest of the series so this looks normal don't be alarmed by all the red in this uh dashboard I accidentally left the trade open from the last video and it racked up a pretty big loss on euro dollar but luckily this is a demo account that's why we use demo accounts for this sort of thing when we're learning and setting up um tools like this I do have pine Connector running on a live account it's running on my ultimate pullback indicator um you can get more information about that on our website pinescript mastery.com if you're interested it's um got full integration for Pine connector all you need to do is insert your license ID and any relevant parameters for Pine connector and it will automatically send any trading signals to Pine connector and it's working really well over the past few weeks so towards the end of this series after we've gone over a lot of the um core fundamentals of pine connector I'll revisit that script I'll show you what the results are and we'll break down what I've learned from that experience and what tips and advice I can give you guys um but anyway let's get into the pine connector settings if this is the first video you're watching make sure to go back and watch the first video in the series I've got an instructional video on how to set this up for metatrader 4 and 5 two different videos I'm using metatrader 5 but it shouldn't matter what platform you use the settings will be slightly different in some areas but the core fundamentals are all the same so I'm assuming you've already set up Pine connector and today we're going to open these settings to do that we can just right click our chart we come down to expert list and then click properties now again you will need to use your own license ID you can't steal mine um because it's linked to your metatrader account number so yeah don't try to use mine but the good news is you can sign up for a onee free trial if you're not confident that this is worth your money yet and you can play around with the full functionality of the tool for that full week all right so let's break down the core settings here I'll just do these quickly because in future videos we'll go over practical examples of these settings with actual scripts so obviously you need your license ID that's the most important input here if you don't put this in correctly then this tool will not work the next most important setting is our stop loss and take profit setting so by default it's set to Pips that is the recommended setting for Pine connector but there are other options here so if we set it to Pips then when we send SL and TP in our alert syntax so open up the charts these settings here and it does matter which order you put these in by the way when whenever you send an alert to Pine connector we need to first put our license ID then a buy or sell or pending limit order command then the currency we want to trade then we have our stop loss and take profit and risk if I set both of these to 50 and we open up the settings and have this set to Pips then our stop loss will be 50 Pips from the current market price when our trade is executed so we would have a 50 pip stop loss in a 50 pip take profit if I change this to price then these values need to be price values so if I wanted to put my stop loss at uh 1.58 I would type in here 1.58 and now my stop loss would be a price value but my takeprofit also needs to be a price value so we change this to 1.62 that would give us a roughly one:1 risk reward profile if our trade were to be entered at 1.06 the current market price and then the final option here is percentage that's exactly the same as Pips but obviously percentage based so most Traders probably wouldn't use this option maybe crypto Traders might uh but for Forex Traders it's unlikely you would ever use percentage based stop losses and take profits most of you will be working with pips but we do have the option for price as well if you need to use that option again the recommended option is Pips because that helps alleviate the issue of the pricing discrepancy between metatrader and trading view when your trade is entered it's entered at metat Traders price and so if you enter your stop L and take profit based on Pips that keeps everything as consistent as possible across both platforms next up we have risk so the default setting is set to Lots so if we set our risk to one and look on the left here we have these um example parameters if we set risk equals 1 in our alert then our position size will be whatever number we put here so in that example it would be one standard lot if we put 0.1 it would be one mini lot 0.01 would be a micr lot there are other options here dollar amount percentage of balance based on lots and margin available margin and then finally percentage of account balance as a loss so this is the most commonly used one I would imagine this is the one I use in all my scripts and this limits my loss based on a percentage of my account balance so if I set risk equals 1 and I have this set up in the pine connector settings then if my trade loses I will only lose 1% of my account balance now on the settings page there is more information here so under volume there is a description of each setting so go and read this if you want to know more about these middle three options but for me I will mostly be using percentage of account balance so that's what I'll leave this on for now next up we have our pending order this is our entry order so if we send an alert of buy or sell like this that's a market order but if I change this to buy limit or sell limit now we're placing buy and sell limit orders and if we are sending buy or sell limit orders this setting comes into into play so by default it's set to Pips from current market price so if we send an alert that says price equals 10 then our buy limit will be set 10 Pips below the current market price on Pine connector uh on metatrader same as our Target type so our Target type has Pips price and percentage so does our entry pending limit order Pips price and percentage most most of the time we will be using Pips um but I'll show you some examples of these others in future videos finally we have account filter basis and we have four settings here balance Equity margin percentage and free margin let's go over to the settings page and read what these do so this setting helps filter the trades that Pine connector can take so if we choose balance and we set account filter to 1,000 then the signal will only be processed if your account balance is greater than 1,000 if it's set to equity then our open Equity needs to be greater than 1,000 if we set it the free margin then our margin needs to be greater than 1,000 and margin percentage is the same as uh free margin but uh but obviously this will only be processed if your margin percentage is more than the specified number so I personally don't touch this setting in my own trading or rather I don't send this parameter in my alerts but this parameter here is there for you guys to basically control your risk that's what this setting would be mostly used for that way that way if your script goes ballistic and starts pumping out dodgy trades um you have like a a break an emergency break limit um if your account balance Falls below a certain number the expert advisor will stop taking trades or if you just have a lot of um signals being generated and you don't want to take any trades when your margin is used up for example so you're not getting margin calls anyway moving on to input so here is like a master override that you can um input so that when you're trades are received by the expert advisor these settings are used instead of whatever you send from your alert I've never used these settings um so I'm not going to go over these but this option is here for you if you need to do this for whatever reason um personally I like my script to send my trade parameters so I leave this setting as it is um so let's move on to General pyramiding so typically pyramiding is used to add to winning trades the first setting is on if you set this to on then all incoming trades will open without restrictions so if you have a hedging account that allows open long and short trades on the same symbol then any long and short trades that come in will be will be allowed to execute if you select on if symbol and direction in profit so this setting here then the trade will only open if if you have no open trades on euro dollar or your open trades on euro dollar have a profit that's Break Even or better and if we set it it to off either one buy or sell then if you have one trade open on euro dollar then a short trade will not open or if you have one uh Buy trade long trade on euro dollar another long trade will also not open and then finally we have off only one buy and one sell this will allow one long trade and one short trade to be open on the same symbol so these are advanced settings for accounts with hedging enabled um some Brokers allow you to have that setting enabled so that you can have long and short trades open simultaneously I personally have never played around with that just because it adds a lay of complexity to the back testing process that I'm not um comfortable dealing with I just can't be bothered I'd rather have a simple system that trades either long or short at any given time it's a lot easier to back test and prove that it works on historical data so I keep this um off typically so I'd usually have this off either one buy or one sell um or there's another setting down here Max open open positions per symbol I'll usually just set that to one and leave this on that way only one trade is open at a time but anyway we'll get to that next up we have close on reverse close on reverse determines the treatment of opposite signals so this is another setting that I've never played around with personally perhaps we'll cover this in a future video if you guys are interested in this but personally I leave this off and as I said I I stick to simple systems when I'm automating my trading next up we have Shadow targets I'm actually not sure what this is let's have a quick read Shadow targets hides your intended stop loss and take profit now I actually have no idea what this is we'll have to play around with this in a future video I've again I've never used this setting I'm not sure what that does Shadow targets hides your intended stop loss and take profits I'm guessing it means it doesn't enter these stop loss and take profits into the market to hide your stop- loss and take profit from your broker I'm guessing that's what this does we'll have to play around with this in a future video moving on partial close percent percentage this determines the percentage of your positions to close when using the close long percent and close short percent commands so we have three options 25% 34% and 50% this is obviously useful for scaling out of positions instead of exiting your trade entirely this is also not a setting I've ever played around with perhaps we'll cover this in a future video if you guys are interested in that uh next up we have Max open positions this defines the maximum number of positions across all of your symbols so if it's set to zero the pine connector EA will not limit your position count if it's above zero then uh Pine connector will limit how many open trades you can have accordingly so let's say you set up alerts on like 20 different markets but you only have enough money in your account to have three or four open trades you might want to set this number to three or four that way you won't be getting margin calls and trades trying to execute when you already have a lot of open trades um and then finally we have Max open position positions per symbol which does exactly what it sounds like defines the maximum number of positions per symbol um I typically set this to one um because I as I said I trade simple systems that only have one open trade per symbol I prefer to trade lots of symbols and only have one trade per symbol then have lots of Trades executing on a single symbol just makes it a lot easier to go through the strategy development process and back testing for me personally the way I do things all right let's wrap this video up with the last few settings categories here next we have dashboard that is this dashboard here and um we'll maybe break this down in a future video cuz there's a lot of information here to dissect but uh this shows you your p&l and your performance metrics for your system since um from Pine connector's perspective based on live executed trades you can see my giant loss here from the trade I left open from the previous video and if we go to the documentation here um the settings we have to work with are profit computation so by default it's set to calculate your p&l while including commission taxes and swap fees so that's really cool that gives you a very realistic portrayal of your systems performance metrics um then you also have the option to display this information without commission taxes and swap um but your results will be um better than realistic when you have this setting turned on because it's not taking into account all the hidden costs of trading in terms of system development so your back testing results will usually not show this information at least not on trading view since trading view doesn't have access to this information from your broker directly so these are the sorts of things you need to factor in during your system development and back testing process but by running your system on a demo account or a small real money account for a couple of weeks you should get a pretty realistic representation of how your system's performing with these fees um included in that performance you can also change the font size and turn the dashboard on or off um so if we go to experts properties dashboard um you have three options here Tech size on or off and the uh calculation technique then we have some risk parameters here so let's go over the documentation for these um first we have daily profit this determines your daily account takeprofit the daily recompute occurs at midnight GMT so that's important to know if you're using this set if it's off then your system will just continue taking trades regardless of how much profit you make in a day if it's below one then you're using a percentage amount so 0.1 in this parameter here would turn your system off it would stop allowing Pine connector to take new trading signals if your profit for the day exceeds this number personally I've never been a fan of limiting The Profit I make in a day but there are probably reasons to use this um especially if if you're trading a managed account and you're trying to keep your performance metrics and your Equity curve volatility in a certain range so a number below one would be a percentage amount so 0.01 would be 1% 0.5 would be 50% so on good luck making 50% in a day um but if you do more power to you if you set this setting to a number greater than one then this is a dollar amount so 100 would mean that if your account makes $100 worth of profit your um expert advisor will stop taking trades and you can check the day's profit Target using your experts log which is this setting here next we have daily loss which is exactly the same but obviously limits your daily loss which is a setting that it makes a lot more sense for me to use Um this can stop your system from going haywire if your system is taking a lot of Trades and you're racking up losses quickly um setting a daily loss limit can protect your account from that happening again if you're trading managed accounts you might want to turn this on so that you don't exceed your daily loss limit if you're a retail Trader you probably use this mostly to protect your account from something going wrong with your system or maybe you're a day trader and you want to limit your loss for the day not a bad idea to use this setting if you're trading lower time frames especially and it works exactly the same way as the daily profit limit um but obviously this is losing percentage and losing dollar figures and then we have our action so this is the action the EA or pine connector will take if one of these um thresholds are hit so halt EA will stop the EA for the day and it will restart automatically on a new day which I'm guessing is midnight GMT as it says up here so at midnight GMT your daily p&l will reset and if you have the setting turned on um the new day's p&l cumulative p&l will be acted on on accordingly you could also set it to close all positions so if your daily profit or loss is hit it exits all of your open positions or the third option is to close all positions and halt the EA so if you just have halt EA on and your daily loss limit is hit for example then all your open positions will still play out so if you've got stops and targets set the trades will play out as they were set up um but no new trades will be taken however if you set close all positions and hold EA then it will exit any open position positions and also hold the EA so you'd probably want to use this setting if you're going to use a loss limit on your uh account next up we have cumulative profit so this is like the daily p&l um setting except it's for cumulative profit since Inception so since you started running your system um this setting will add up your pnl so we open up experts properties so we have a daily profit and daily loss limit limit and an according action and then we have a cumulative profit and cumulative loss limit um and a ea action so we can hold the EA for a day we can hold the EA permanently until we turn it back on manually and then we have our same options but we close all positions or we close all positions and pause the EA for the day or we close all positions and turn the EA off until we manually override this and that's it that's the core settings for Pine connector again we'll go into more detail on these settings in future videos as we start coding scripts to send this information these parameters directly to Pine connector from Trading view alerts so that we can automate our trading um so far we've only done test alerts using uh test alert syntax in future videos we will code all of this and I'll give you a template for a script that includes all of this information so that you can set up your alerts like I have here with my UPI I can select my script select any alert function call make sure my web Hook is turned on and my license ID is inputed into the script and then whenever my script detects a training setup an alert will be generated and sent to P connector you can see here a signal is being detected if this signal closes valid so this bullish engulfing candle closes with all the conditions met in 45 minutes from now uh Pine connector will execute a trade on my Live account so really cool stuff here really powerful um it's a really powerful tool for systematic Traders I hope you found this video interesting thanks for watching I love you guys I'll speak with you in the next video where we'll start coding we'll go into more detail about the syntax so so far we've only really covered fixed profit and uh stop losses and risk in future videos we'll cover more Dynamic stuff like trailing stops how to exit trades so for example based on exit reasons so if I come up to the settings of my UPI and scroll down to um exit settings I've got the option to use a trailing stop here that will use a a trailing stop to lock in profit so once my target is hit the script will start trailing my stop loss until it's hit we can send alerts to Pine connector to update our stop loss as it changes or I can tell Pine connector to close a trade when an exit reason is detected so if I say so for example if I turn on use higher close lower close exit as soon as my target is hit and we get a candle that closes above the previous candles high I can tell Pine connector to exit that trade at Market so there's some really cool powerful combinations of settings and script parameters and code that we can use to create pretty versatile trading view systems that can be automated through our broker using pine connector that's where the fun stuff will start to happen in this series so make sure to subscribe to the channel if you haven't already and I'll speak with you in the next video take care good luck with your trading now none of this is trading advice be careful out there it is possible to lose a lot of money if you don't know what you're doing with this stuff so take it slow start with the demo account if you're going to play with this tool treat it with respect and you should do just fine have a fantastic day and I'll speak with you soon goodbye
Pine Script V4 A Breakout Strategy
what's up my friends and fellow traders
welcome back to another partnership
video i've got a good one for you today
i'm sorry it's been a couple of weeks
since i posted a video
i've been extremely busy lately working
on my own trading but today's lesson is
going to address a question i got from a
student of my pantry mastery course so
here's the question here from dj and dj
wants to know how to create a script
that first draws the previous days low
and high onto his chart
and then he wanted to do something like
entering a trade i'm guessing in the
back tester system he didn't say that
explicitly here but i'm assuming he
means enter a trade in the back tester
system
with a buy stop order three pips above
the previous day's high a stop loss five
pips below his entry and his take profit
ten pips from his entry so two to one
risk reward
and using a buy stop order above the
previous day's high and i'm assuming
also below the previous day's low and so
that is exactly what i'm going to show
you how to do today so here we are with
a blank strategy script i'm going to do
things a little bit differently today
instead of writing out each line of code
as i go to save time and be a little
more efficient and concise i'm just
going to copy and paste blocks of code
over into the editor and explain what
that code does as we go so as you know
if you've watched any of my previous
lessons the first thing i like to do in
my scripts is get my user input so i'm
going to paste in my user input for this
script here one other thing or one new
habit i've gotten into with my scripts
is just lining up all of these equal
signs so this particular script only has
three user inputs entry pips stop pips
and target pips they're all pretty
self-explanatory entry pips is
the distance from the daily high and low
that we want to set our buy or sell stop
order
stop pips is our stop-loss distance in
pips from our entry target pips is our
profit target our take profit uh
distance in pips from our entry they're
all using the data type float floating
point numbers so they are decimal
numbers meaning we could have 3.1 pips
as our
entry pips if we wanted to and then
finally i'm using the new tooltip
feature of pinescript was not that new
but it was added a couple of months ago
and now we can explain what each setting
does so that when we hover over this
little i information icon
this little tool tip pops up that
explains what that setting does these
settings are very self-explanatory so
let's just move on to the next block of
code which is getting the daily high and
low
so i'm going to copy this code over here
to get these values we use the security
function
when you need to reference either
another market or another time frame we
do that using the security function
the security function takes a bunch of
input parameters i've left
our gaps and look ahead as the default
settings if you want to learn more about
this function just hold down control and
click on it
and there'll be a description that pops
up here and a few examples
but basically all we're doing today is
we're referencing sim info or symbol
info dot ticker id
and that will get the current market
that we have loaded onto our chart
in this case that would be euro new
zealand dollar
from the oanda
price source or data feed so ticker id
would be replaced with a string
that looks like this oanda
colon euro new zealand dollar
if we just put in ticker then it would
just look like that but we don't want
that we want to actually get the price
data from the
exact same market that we've loaded onto
our charts here
then we reference a resolution or time
frame in this case we're referencing the
daily chart you could also put 1440 here
for 14 40 minutes which is a daily
resolution as well but to keep it simple
i just left mine as d next up we need to
reference an expression now this
expression could be anything it could be
an indicator value so for example we
could get the daily ema 50 ema
or the daily rsi value in this case
we're just referencing the high price so
we're getting the high and the low from
the daily time frame on the current
market that we have loaded onto our
chart
pretty simple now we get to the more
complicated part of the script which is
calculating our entry price stop loss
price and take profit price so we'll
copy these in one at a time
the first thing we do is we determine
our buy
and sell point that should say and sell
point uh and it's going to be above
below
the high slash low
so our buy point is going to be the
daily high
plus
our entry pip setting so
3.0 by default
multiplied by 10
because
pinescript deals in points not pips and
so we need to multiply anything dealing
with pips by 10 in order to convert that
into points
and then we need to multiply
our
points
by this symbol info or siminfo dot
minimum tick value and this is just the
last decimal place on our price chart so
it would be 0.00001
obviously depending which market you're
on this value will be different and
that's why we need to do this
but moving on we then do the same thing
for our cell point now one thing i
didn't do here is replace the default
three pips with our user setting so this
is how it should look
that multiplied by 10 multiplied by our
minimum tick
so our buy point is our entry pips above
the daily high previous daily high our
sell point is our entry pips
below the previous day's low
the next thing we need to do is
determine our stop loss and our take
profit so to do that we subtract our
stop pips multiplied by 10 to turn it
into points multiplied by our minimum
tick value and then we subtract this
number from our buy point and then we
add that number to our sell point so for
longs our stop obviously goes below
our entry and for shorts it goes above
so we need to add in the case of our
short stop loss
next up we get our take profit price to
calculate that we do exactly the same
thing as our stop loss except in the
opposite direction and using our target
pips instead of our stock pips so we add
to our buy point our target pips
converted into the correct amount of
points for this market so that's it for
our trade entry data
the next thing we need to do is detect
when a new day begins
and when we detect that new day
beginning we place our stop orders our
buy stop order and our sell stop order
at our buy and sell point now this code
here is a little bit more complicated so
let me just paste in the first part of
it
and go over what's happening here let's
save the script make sure there's no
errors and we're all good
so
next up we check if a new day has
started and we're flat meaning we have
no positions open no trades open then we
want to place a buy stop and a sell stop
above and below the previous days high
and low before we can do that we need to
detect
when a new day begins the easiest way
i've found to do that is to use the
change function inbuilt change function
and then pass it in this time function
that references a resolution or time
frame so this new day variable will be
set to true
if
a change is detected in the daily time
frame and a change will only be detected
on the daily time frame if a new daily
bar
begins
and then i have a bunch of var variables
these are persistent variables that are
stored across our chart so they're not
recalculated on every new bar like these
ones are these variables will stay as
0.0 until we overwrite them
with a different value
and that's what we do next so first we
check if we have a new day
then we want to check if
our strategy dot position
size is equal to zero that means we do
not have any trades open
then if these two conditions are met we
have a new day starting and we have no
trades open then we want to enter our
buy stop and sell stop orders because
obviously if we have a position open
that means we took a trade yesterday
that has not yet hit its stop loss or
take profit and we don't want to enter
any new trades because this
particular strategy is not
a pyramiding strategy it's just a one in
one out very simple
approach to trading daily breakouts so
let's start with our long orders first
let me copy in our long code
so the first thing we do is we save our
long stop loss price
by overriding this var variable with the
current stop loss long and then we save
our take profit price
then we use the strategy.entry function
to place our buy stop order and the way
this works is we need to give it an id
to reference so that we can close this
trade later if our stop or target is hit
then we need to tell panscript which
direction we're trading in so we set
long to strategy.long or you could also
write true here but just to make it more
readable i like to leave it as
strategy.long then to place a by stop
order we use the stop parameter and then
this parameter takes a price
and so we pass in our buy point which we
calculated up here our buy and sell
point which is by default three pips
above the daily high and three pips
below the daily low and then i use
a couple of new parameters that we
haven't covered before in any video that
i've ever done and that is the oca or
one cancels all parameter
so oca name is the name of our one
cancels all group and then the oca type
tells pinescript what we want to do with
this group so this is completely
optional you don't need to add this you
could cut this out if you want to
but i included this just because it was
a good
opportunity to demonstrate this
functionality basically what i'm doing
here or what i plan to do is
when we set up our shorts as well
and it might be easy to show you this
visually so let me copy over my short
entry code which is exactly the same as
our long entry but obviously for the
short side so we're saving our shortstop
and our short target and then we're
using the strategy.entry function to
enter a short cell stop at our cell
point but you can see here that these
both have oca name set to x you could
set this to anything any string just so
long as they're the same string
and the type is set to the same type so
this is a one cancels all order meaning
that if we get filled on a long trade
then our short
entry sell stop will be cancelled in
other words we're only taking one trade
per day so if we get filled on a long
breakout and then that trade either hits
its profit target or reverses and stops
us out and then we
clear or break through the previous
day's low
rather than enter a new short trade
nothing will happen
and again this is optional you could
remove this i haven't noticed it affect
the profitability much at all in my
preliminary testing uh probably because
it's not a common occurrence that the
previous day's high gets taken out and
then the previous day's low gets taken
out it does happen but not that
frequently so this is just for example
purposes just to demonstrate how you can
use the one cancels all in your strategy
scripts so the next thing we need to do
is tell pinescript when to exit these
trades so i'm going to paste in that
code now
so here we are exiting our trade if our
stop loss or our take profit is hit to
do that we use the strategy.exit
function
we give it its own unique id and then we
need to tell it which
order which entry we want to exit so
from underscore entry needs to
correspond to one of our open orders in
this case
we have our strategy.entry with an id of
long
and a strategy.exit with a from entry id
of long so this will exit
this
trade but it will only exit this trade
if our take profit is hit by price
action or our stop loss is hit by price
action
so limit is for your take profit limit
order
stop is for your stop loss order and
then we do the same thing for our short
trades we exit from our short trade only
if our short take profit is hit or our
short stop loss is hit so that's pretty
much it the strategy is written um the
only thing left to do is visually plot
this information to the chart
so that's what i do next i'm just going
to copy this entire block of code in
down here
and i'll explain what we're doing so
it's all pretty self-explanatory we're
just plotting all of the relevant data
for this strategy script so we're
plotting the daily high we're plotting
the daily low we're plotting our buy
price or our long buy stop price
and then we're plotting our stop loss
and our take profit for our long trades
and then the same for our short trades
we're plotting our sell stop price
our short stop loss price
and our
short take profit price and then we're
setting the color of each plot
our daily high and low has a line width
of two so it's just a little bit thicker
stands out a little more and then i've
titled all of these plots so that we can
adjust them in the settings menu under
the style tab so let's save the script
make sure it compiles without any errors
and there we go
open up the strategy tester you can see
that
because we're on a euro yen
and i did set the default quantity value
to quite a high number uh this is off
the scales
i need to come up here and drop our
position size just a little bit
to get more reasonable results here and
we're pretty much done with our script
let's just go over a couple of trades to
see what it's actually doing
here's
a trade here
so when a new day begins
as it did on this bar right here
we start plotting the previous day's
high
and we place a buy stop order three pips
above that high on this purple line so
if i measure that out that should be
three pips
it's exactly three pips you can see that
the strategy tester entered long here
and then exited our long trade at our
profit target which is 10 pips
from our entry and our stop loss down
here was 5 pips so we've got a 2 1 risk
reward profile 5 pip stop loss 10 pip
take profit
and this was a example of a winning
trade now one thing to be aware of is
i'm not 100 sure how the tester system
knows that this trade did not um come up
and fill us on this order and then
decline to hit our stop loss and then
rally to hit our take profit so for
example let's just draw
this
information onto the chart
and then we'll drop down to a 15 minute
time frame
and see exactly what happened here so
let's draw a line there drop down to the
15 minute chart
and have a look at what actually
happened on that day
yeah and just as i thought
this trade did not play out how the
strategy tester thinks it did let me
change the color of these lines
this is our entry this is our take
profit and this is our stop loss
so you can see the price action rallied
here
filled us on our order and then on that
same bar retraced all the way down and
then hit our stop loss before it rallied
to hit our take profit but if we drop
out to the one hour time frame
and turn on our strategy script you can
see that the backtester system
picked this up as a winning trade
and so that is why i'm very skeptical
that this strategy has as high of a win
rate as the tester is telling us it has
and there's really no way to verify
how a trade played out at the moment at
least without doing it manually the way
i just showed you so that is why i'm
always telling traders to be very
skeptical of the backtester system in
trading view
quite frankly i don't like it at all
the backtester system is quite popular
among a lot of traders and you can see
why i mean every trader wants to speed
up their process no one enjoys
backtesting i don't think i've ever met
anyone who enjoyed back testing and if
they do
they're either lying or they're nuts
because it is one of the most boring
things you could ever do
but
this is an example of why you should
manually back test your strategies if
you want accurate results there is no
way to shortcut that process
at least not with pinescript one other
thing to mention is that the strategy
tester is trading a fixed position size
which is not something i would normally
do normally i trade with a percentage of
my account balance so in every single
trade i might risk one percent or two
percent
maximum of my account balance
this tester system doesn't allow you to
do that
instead it is just trading a fixed
position size in this case of ten
thousand contracts
or one mini lot on a hundred thousand
dollar account
so basically our max drawdown and our
net profit are not accurate figures and
so this is a great example of how the
strategy tester can be misleading and so
while the backtester system can be
helpful in identifying potentially
profitable strategies
do not under any circumstances
take this information as accurate it
should only be used as a very very rough
indication of a strategy that might have
potential to be profitable you still
need to manually back test all of your
strategies in order to get accurate
results and again if you're not sure how
to back test there will be a link in the
video description to
a guide i made a couple of years ago on
how to manually back test strategies and
with all that said there are some
strategies that perform a little bit
better in the backtester system
basically the more simple your strategy
is the better as strategies become more
complex the backtester system can give
more and more misleading results but
anyway for those traders who insist on
using pine script 2 test strategies
i hope that you found this lesson
interesting
at least there is a
decent back testing tool here
if you change this to a study script and
remove all the references to the
strategy
functionality we've got a pretty good
indicator here to assist in the back
testing process for a breakout strategy
like this anyway that'll do it for today
i think in my next video i'll record a
example of why the back tester system
on trading view
should be treated with a huge amount of
skepticism
and why when something like this seems
too good to be true it probably is so
this strategy might be profitable but we
can't know for sure unless we manually
back test it because the tester system
who knows how many times this has
happened
over 773 trades
where it gave a false reading
and the trade was filled but then
stopped out before our target was hit
and the tester system never accounted
for that but anyway to be honest um the
more simple your strategy is and
especially if your strategy operates on
candle closes instead of
like limit orders and buy stop orders
like we have here
or like we used here
then the chances of this sort of thing
happening are significantly reduced the
reason for that is say we were trading
daily breakouts but we only entered on
the closing price of this bar the
closing price of this bar would have
factored in that dip below our stop loss
and then rally back up to here
and so this trade would have gone from a
losing trade
into a winning trade just by operating
based on candle closes now the one time
that this does affect
strategies that operate on candle closes
is if your take profit and your
stop-loss is hit on the same bar
uh there is no way to know how the
tester handles that sort of situation
and so a trade that is recorded as a win
might have actually been a losing trade
depending on which price got hit first
on that intra bar price action
so anyway i hope you found this lesson
interesting at least
um
it's a good cautionary tale but it's
also
um i think interesting code and there
are a lot of ways you could use this
like i said if you remove all the
strategy code out of the script we've
got a decent indicator here to assist in
trading breakouts manually and if you
were to forward test this kind of
strategy over a few weeks
or months even you might find it to be
profitable i'll leave it there
thanks dj or daniel for sending in this
question and for all of you traders who
are not involved in the panscript
mastery program if you'd like to take
your coating to the next level or you
simply just want to steal the source
code to every script i've ever written
head over to panscriptmastery.com to
check out some of my courses over there
otherwise i'll be back soon with a free
lesson here on youtube so if you haven't
hit the subscribe button make sure to do
that as well and i will see you in the
next video take care best of luck with
your trading and be careful
using the trading view strategy tester
goodbye
you
Pine Script ULTIMATE BEGINNER'S GUIDE! 💹 [2024]
hey what's up traders! welcomeÂ
to my pine script basics course!
the material in this video is taken from myÂ
website over at pine scriptmastery.com this Â
is basically a stripped down version of my freeÂ
pine script basics course the official version Â
on my website goes into a lot more detail it'sÂ
more geared towards complete beginners who have Â
never written a line of code in their life soÂ
if that sounds like you you might want to go Â
through the official material as there's a lot ofÂ
presentations and information about programming in Â
general like how to get started what programmingÂ
is all the technical jargon i explain all of that Â
stuff in the official course i've stripped all ofÂ
that out for this version because there's four or Â
five hours of content in my official basics courseÂ
on my website and i wanted to keep this video as Â
close to two hours or less as possible i thinkÂ
it's going to be a little bit over two hours Â
but it's going to be worth going throughÂ
because the material you are about to watch Â
will teach you everything you need to know inÂ
order to get started with pine scripts and start Â
writing your own scripts i'm going to teachÂ
you the core fundamentals of pine how to use Â
some of the more common basic functions likeÂ
drawing to the chart getting user input generating Â
alerts and referencing inbuilt indicators so iÂ
hope you find the course material interesting Â
if you do make sure to hit the subscribe buttonÂ
and like button and all that youtube stuff Â
and uh i hope you enjoy it i really doÂ
i'm really passionate about trading and Â
especially pinescript and i hope that passionÂ
rubs off on you throughout this material with Â
all that said i'll get my ugly mug out of yourÂ
face and let you get started with the content uh Â
have fun best of luck with your trading and i'llÂ
speak with you in the lessons to come take care
hi traders in this video i'm going to be showingÂ
you a basic overview and breakdown of the pine Â
script editor so the pinescript editor is inbuiltÂ
directly into the tradingview platform and you can Â
open it and use it directly through your browserÂ
so here i am on the tradingview platform to open Â
up the pine editor we just click on this tab hereÂ
so we click on that that will bring up the pine Â
editor so this is what the editor looks like whenÂ
you first open it up with a blank script there are Â
a few things to go over here first of all you canÂ
open existing scripts by clicking on this button Â
here if i open that you can open an existingÂ
script from your own script library you can Â
create a new default built-in script so this willÂ
create a new script based on an inbuilt indicator Â
so if i scroll down to let's find the let's goÂ
with a just a moving average if i click on that Â
this will create a new script with the sourceÂ
code for the inbuilt moving average indicator Â
and if we come up and open a new blank indicatorÂ
script that will open a new blank indicator Â
template and if we open a strategy this is theÂ
template for a new blank strategy then we have Â
our new blank library script and this will createÂ
a new blank library now don't worry we'll go over Â
what each of these different types are there'sÂ
really only three we've got an indicator script a Â
strategy script and a library script we'll go overÂ
all of these throughout the course next up we have Â
save so if i click save on this blank scriptÂ
i can name this script it doesn't matter what Â
you name it but i would recommend getting into aÂ
habit of some sort of consistent organized naming Â
system so for me for example i like to put 2021 orÂ
the current year 2022 whatever the current year is Â
in square brackets in front of my scriptÂ
or something like that just to organize Â
my scripts if i open up my scripts here if iÂ
go open my script you can see that i have a Â
significant amount of scripts here and a lot ofÂ
them aren't organized but i have recently begun Â
organizing them by a year and also by subject soÂ
you can see i have a bunch of psmc scripts here Â
this is a part of script mastery course thisÂ
is from the previous version of this course Â
from version 4 of pine script from when pineÂ
script was version four it's now updated to Â
version five so i'm re-recording this entireÂ
course so whenever i create a new script for Â
this course i will probably call it p psmc versionÂ
five dash and then the name or something like this Â
that way when i open up my scripts i can just typeÂ
in psmc and i get a list of all my psmc scripts Â
you don't need to do this but this is just a goodÂ
habit to get into early if you plan on writing Â
a lot of scripts so let me open up a blankÂ
indicator here and save it and i'll call this Â
psmc v5 dash pine editor let me save that scriptÂ
and now we'll move on to add to chart so if i Â
click on add to chart that will add the script toÂ
my chart and now we have our script here and then Â
next we have publish script this will publish yourÂ
script to the trading view library we'll go over Â
this in more detail in a future lesson but this isÂ
where you can publish your script you can give it Â
a description as detailed as you want it to be umÂ
you have your privacy settings so you could make Â
it a public or private script a private scriptÂ
means it's only visible to those with the link Â
a public script is visible to all uh tradersÂ
on the tradingview platform but you can protect Â
your source code so that only you can see it butÂ
people can still use your script or you can make Â
it an invite-only script so that only you can seeÂ
the source code and you choose who can use it this Â
is particularly valuable or useful for creatingÂ
premium scripts that you can charge traders money Â
to use such as my ultimate pullback indicatorÂ
which is a good example of using this invite-only Â
version of a public script but let's cancelÂ
out of this publish script dialogue and move Â
on to this little button here if we click onÂ
this we have a whole bunch of resources here Â
so we can make a copy of our current scriptÂ
that we have open we can view the pine script Â
official documentation we can view the plan scriptÂ
official reference manual this is the same thing Â
but as a pop-up so if i click on this we have theÂ
reference manual pop up within our browser this is Â
really useful when you're learning pan scriptÂ
if there's something that doesn't quite make Â
sense to you or something i haven't covered in theÂ
course material you can search through the search Â
box here for whatever that is so for exampleÂ
if we're looking at an rsi lesson and i don't Â
cover something in enough detail and you want toÂ
learn more then you can just click on this ta.rsi Â
at the top of this list and that will give youÂ
the reference manual for this function and it will Â
tell you in detail exactly how it works and howÂ
to use this function but let's close out of that Â
the next thing we have is our pine editor keyboardÂ
shortcuts this is a useful thing to look over Â
and try to memorize some of these keyÂ
shortcuts if i click on this drop down Â
box under pine editor we have a whole bunch ofÂ
keyboard shortcuts for use in the pine editor Â
so for example you can save your script by justÂ
pressing ctrl s which is useful and then we have Â
a bunch of lesson resources here so the pinecodersÂ
and codify are kind of tutorials and examples Â
of how to use pine they're kind of just writtenÂ
guides one other thing to mention in regards to Â
the pine editor keyboard shortcuts is that whenÂ
you're writing out your code pressing control Â
space will list all of the available functionsÂ
and inbuilt variables we have to work with Â
so for example if i wanted to see what technicalÂ
analysis functions we have i can type t a dot and Â
then control space will list all of the functionsÂ
we have that deal with technical analysis so here Â
we have the atr if i click on that we now have theÂ
atr so if i put in a period length here like ta Â
dot atr 14 if i wanted to plot this to myÂ
chart i could just cut this ctrl x and paste it Â
into the plot function save the script andÂ
now we're plotting the atr onto my chart Â
so this is the power of pinescript just how easyÂ
it is to get certain information and plot it onto Â
our chart but that's something to keep in mind theÂ
control space feature of pine script is extremely Â
valuable you'll be using that keyboard shortcutÂ
a lot in your coding and i believe it's command Â
space on a mac next up we have this littleÂ
button here which just renames your script Â
then we have this favorite buttonÂ
if you click on this this will add Â
your script to your favorites menu so when youÂ
click on the indicators and strategies button Â
your favorite scripts will be at the top of theÂ
list up here mine are taking a while to load Â
because my internet sucks but yours should loadÂ
a lot quicker than that hopefully and you can see Â
here that these are all my favorite scripts someÂ
of them are other people's scripts and some of Â
them are my scripts then we have the search buttonÂ
here this is useful for finding and replacing Â
things in your script so you won't be usingÂ
this very often on smaller or simpler scripts Â
but on longer and complex scripts this is a reallyÂ
useful tool especially for refactoring or changing Â
parts of your code if you click on this littleÂ
button here that will drop down the replace text Â
box and in here we could write something likeÂ
atr let's replace atr with rsi to do that you can Â
click on this button which will replace the firstÂ
instance of this atr so the very first time this Â
tool finds atr in your script it will replaceÂ
it with rsi if we click on the second button Â
it will replace all mentions of atr with rsiÂ
and if you want to add more filters to this Â
find and replace tool you can click on this buttonÂ
here and we can match case we can match the whole Â
word or you can use regular expressions which isÂ
basically patterns in text you don't need to worry Â
about this unless you're an advanced programmerÂ
now the final thing worth mentioning here is this Â
button here this is your revision or scriptÂ
version button if i click on 1.0 that will load Â
into the pine editor the very first revisionÂ
of the script we have loaded into this editor Â
so this will load the script before i made thisÂ
change of plotting the atr so let me click on 1.0Â Â
and now we're back to our blank script andÂ
if i want to load the latest version of the Â
script i can click on 2.0 and that will loadÂ
back the latest version as far as i can tell Â
there is no limit to how many revisions every timeÂ
you save your script and make a change to your Â
script there will be a new revision added to thisÂ
list so i have scripts with hundreds of revisions Â
and i can drop back to any prior version of myÂ
script this is particularly useful for debugging Â
scripts so let's say you're trying to add a newÂ
feature to a script and after several changes to Â
your script you realize you've broken somethingÂ
in the script and you can't work out what you did Â
using this as a as a sort of undo button canÂ
undo any changes you've made to your script Â
and reload a previous version so it's basicallyÂ
like an inbuilt backup tool in the pine editor Â
anyway that's about all you need toÂ
know about the pine editor itself Â
in the next few lessons we'll cover someÂ
practical coding examples i'll see you there
now before we get into actually writing code it'sÂ
probably a good idea for me to go over some of Â
the basic things you will need to know about theÂ
compiler for pinescript so the compiler is what Â
compiles our code converts it into informationÂ
that trading views servers can understand so all Â
of this english written code will turn intoÂ
computer code that the computer can run and Â
execute our commands the pinescript compiler isÂ
responsible for doing that so when i click save Â
here i'm just going to delete this script after soÂ
i'll just name this delete my script just compiled Â
and i know it compiled because i didn't getÂ
any errors if however we do something like Â
this let me get rid of one of these parenthesesÂ
here and save the script now we have a problem Â
we have a syntax error this red line here now theÂ
wonderful thing about most programming languages Â
and compilers is that they will usually tell youÂ
where the error happened so we get the exact line Â
that this error occurred on it occurred on lineÂ
six this line here so that makes it really easy Â
for us to you can even click on this um it'sÂ
a link that will take you to that line of code Â
in your script if i click on that it takes meÂ
straight there now every error message will be Â
different depending on what you messed up in yourÂ
script a lot of these error messages are quite Â
cryptic so end of line without line continuationÂ
even i don't know what that really means um it's Â
kind of it's amusing to me some of the errorÂ
messages you get in some programming languages Â
sometimes they're really helpful sometimes you'reÂ
just like wow thanks compiler that was really Â
helpful so now if i close this off and save myÂ
scripts we don't have any errors the compiler Â
compiled our code without any problems let'sÂ
try getting rid of one of these quotation marks Â
save the script now we get a different errorÂ
mismatched character this character here means we Â
have a new line starting so pan script got toÂ
the end of this line and then a new line started Â
but it was expecting this quotationÂ
mark to close off this string of text Â
and so it through an error on line five so most ofÂ
the problems in your script are going to be pretty Â
obvious and intuitive when you see an error popÂ
up usually it means you didn't close something off Â
you missed a comma you missed a bracket somethingÂ
like that and within just a few seconds of reading Â
your code back you should be able to spot theÂ
problem now some errors will be a little more Â
difficult to solve but in part scriptÂ
it's very rare that you run into an error Â
that can't be solved very quickly because usuallyÂ
it's a result of a typo of some kind and you don't Â
even need to know what the error message meansÂ
you can just click on that line of code and see Â
at a glance that you missed something relatingÂ
to the syntax i will cover errors in your code in Â
much more detail in its own section of the courseÂ
towards the end of the course so if you run into Â
any problems maybe jump ahead and check out thatÂ
section but the last thing i'm going to show you Â
here is what happens if we get rid of the compilerÂ
directive if i get rid of that and save the script Â
now we're going to get all kinds of weird problemsÂ
and errors with our code the reason for that is Â
that the compiler now doesn't know what version ofÂ
panel script we're using so right now we are using Â
the original version of pinescript the versionlessÂ
version of pinescript the first iteration of this Â
language i have no idea what the syntax is forÂ
that language i wasn't around when that was a Â
thing i started using pine script when it was inÂ
version three and so recently version five has Â
released so i've had to learn the new syntax ofÂ
pine script three times now i started with version Â
three so i learned version three syntax then itÂ
updated a version four and i learned version four Â
syntax now we're on version 5. the good newsÂ
is it's not that much different to version 4. Â
if i set the version to 4 say the script we'llÂ
still get the same error because in version 4 of Â
pinescript we don't use the indicator annotationÂ
function we use the study annotation function to Â
create an indicator so now my script just compiledÂ
fine and so it's very important that you keep Â
this compiler directive in and that you get yourÂ
syntax correct in your code you don't need these Â
comments if you don't want them there this willÂ
compile just fine as well the reason why we have Â
this compiler directive that allows us to targetÂ
older versions of pine script is for backwards Â
compatibility so there are hundreds if notÂ
thousands of scripts that have been written from Â
the beginning of trading views existence that areÂ
still very useful even though they were written Â
in an old version of pinescript and rather thanÂ
force all of those coders to update their code Â
to version 5 of pinescript tradingviews simplyÂ
allow you to target old versions of pinescript Â
so that you don't need to update your scripts forÂ
them to work the only reason you would want to Â
update your script to version 5 of pinescriptÂ
is to take advantage of the new features Â
of that version so i have dozens of indicatorsÂ
written in version 4. i'm not going to convert Â
all of them into version 5 of pinescript exceptÂ
for the ones that i use regularly now one last Â
thing i want to mention about the compilerÂ
is that it is not particularly picky about Â
where you put some of your syntax for exampleÂ
if you have a plot function that has a lot of Â
parameters which we'll cover in future lessons youÂ
can separate them across multiple lines now there Â
are some rules with this that takes some gettingÂ
used to but let me just quickly demonstrate what i Â
mean by this so for example we could put a spaceÂ
between our plot and our parentheses save the Â
script and this will work just fine no problems noÂ
compiler errors we can also split our parameters Â
across multiple lines so if i press enter hereÂ
and i tab indent this line of code and i save the Â
script we'll get an error in pinescript if youÂ
want to indent your parameters across multiple Â
lines you need to put a space after your tab soÂ
now if i say the script this compiles just fine Â
so the purpose of being able to do thisÂ
is maybe you have a bunch of parameters Â
in your plot function that stretch way off yourÂ
screen you can separate these onto multiple lines Â
to make it easier to read your code so forÂ
example if i put a comma here and then enter Â
i could say offset equals one comma titleÂ
equals plot close comma a line width equals two Â
comma and let's set the color to color dot blackÂ
and then let's move this parenthesis down one Â
line now if i save the script this compiles justÂ
fine so we'll cover this sort of thing in future Â
lessons i just wanted to make you aware of theÂ
fact that the compiler is quite flexible when it Â
comes to your syntax just so long as everythingÂ
is in the right order and you respect some of Â
the indentation rules which we'll cover in futureÂ
lessons as well but anyway i just wanted to make Â
you aware of the fact that we can do this sortÂ
of thing in pinescript the compiler will allow us Â
to separate our code across multiple lines underÂ
certain circumstances as long as we respect Â
certain syntax rules i'll leave it there becauseÂ
i don't want to overwhelm you guys with too much Â
information before we actually cover what all ofÂ
these parameters do but now at least you know that Â
when we get into future advanced lessons that thisÂ
sort of thing is possible if you need to separate Â
your code across multiple lines anyway that aboutÂ
sums it up for the compiler i'm sure we will run Â
into other issues that i haven't covered hereÂ
that we'll address in future lessons especially Â
the error section of the course so i'll wrapÂ
this up here and i'll see you in the next lesson
all right traders welcome back i was thinkingÂ
while recording this material about my early Â
days as a programmer and i thought this wouldÂ
be a fun lesson in this lesson we're just going Â
to plot the text hello world onto our chart nowÂ
technically we're already doing that you can see Â
i've got an indicator here indicator function withÂ
the title hello world and that's drawing under my Â
chart but we're going to do something slightlyÂ
different we're going to plot a shape onto our Â
chart with the text hello world above it butÂ
before we do that i want to sort of reminisce on Â
my early days as a programmer i first discoveredÂ
programming when i was in high school i was Â
playing a computer game called runescape it wasÂ
an online computer game and in that game you Â
had to do a bunch of repetitive clicking tasks itÂ
was like an old school game kind of like pokemon Â
where you had a little character that would runÂ
around the screen and you'd have to click on Â
things to make him walk there or mine a rock orÂ
do some fishing or whatever now i can't remember Â
where i found out about this but at some point iÂ
discovered that some people were writing scripts Â
that were playing the game for them and performingÂ
some of the more repetitive tasks that weren't fun Â
so there were elements of the game that were a lotÂ
of fun and there were elements of the game that Â
were extremely monotonous and boring a lot likeÂ
trading actually i'm getting ahead of myself but Â
that's kind of why i got into coding and tradingÂ
as well is i wanted to automate some of the more Â
boring tasks and hopefully this course will helpÂ
you do the same in your own trading but anyway Â
back when i was a teenager i was around 14 or 15Â
i discovered the world of coding in the context of Â
a computer game and so i was writing scriptsÂ
to perform tasks in this computer game that Â
i didn't want to do in real life because my timeÂ
was limited i had to be at school all day i'd get Â
home from school and only have a couple of hoursÂ
to play and i didn't have time to do everything Â
i wanted to do and so i wrote these scriptsÂ
that would play the game while i was at school Â
and it would level up my character and do allÂ
these things technically it was cheating and i did Â
get banned for it in the end luckily in tradingÂ
automating your processes is completely legal Â
we're allowed to do that in trading but anywayÂ
back when i was learning to code this was before Â
the wealth of information on the internetÂ
you couldn't just google how to learn coding Â
and be met with thousands of examples and guidesÂ
and i mean youtube was barely a thing when i Â
first started learning to code and there wasÂ
not that much educational content on youtube Â
so i had to learn all of my coding fromÂ
books i had to buy books rent books Â
from the library and it was a really monotonousÂ
job learning how to code but i remember when i Â
got my first hands on a coding book to learn javaÂ
and one of the first lessons in that book showed Â
me how to write the words hello world into theÂ
command prompt on windows and i still remember the Â
feeling of getting that short sentence to appearÂ
on my screen it was absolutely exhilarating to see Â
my own work my own hands telling the computer toÂ
output something nowadays that's kind of normal Â
i mean everyone has some experience in scriptingÂ
or excel or just generally telling computers to Â
do something on your behalf but back then it wasÂ
pretty revolutionary to me and so i hope that this Â
course can inspire that kind of feeling in youÂ
as we go through it i hope that you get excited Â
about what is possible with coding especiallyÂ
in pine script as you learn to translate your Â
trading ideas into code i hope you get excitedÂ
over the possibilities because they truly are Â
almost infinite almost endless there areÂ
some limitations you'll run into as you Â
learn to code but for the most part most basicÂ
processes can be done in code and you can automate Â
a significant part or semi-automate at least aÂ
significant part of your trading process your Â
analysis process setup detection indicator signalsÂ
all of that stuff but anyway for this lesson Â
let's just quickly write the words helloÂ
world onto our chart to do that i'm going Â
to use the plot shape function now thisÂ
plot shape function takes a boolean Â
series meaning true or false so i'm just going toÂ
pass true in here and in fact that's all we need Â
if i save the script we'll be having a cross drawnÂ
onto our chart you can see all these crosses here Â
drawing onto our chart um let's first of allÂ
set overlay to true so this is actually drawing Â
onto price action so let me save the scriptÂ
remove that and add it back to my chart Â
now let's add some text to this shape to do thatÂ
we can use the text argument or parameter so text Â
equals and now let's write hello world and whenÂ
i save the script we're going to be getting hello Â
world drawn all over our chart on every bar hereÂ
so let me save the script and you can see it's Â
pretty unreadable we have way too many shapesÂ
drawing onto our chart now so let's change Â
that really quickly let's just add on a booleanÂ
condition here let's say bar state dot is last so Â
now this will only draw our shape on the last barÂ
on our chart so let me save the script there we go Â
we are plotting the words hello world onto ourÂ
chart as simple as that literally one line of Â
code we have our indicator function you need thisÂ
line of code in every script same with this but Â
if we get rid of this and i save it technicallyÂ
three lines of code and we're drawing text onto Â
our chart that is incredible it's amazing howÂ
far the world has come in technology back when Â
i was learning how to code it took over a dozenÂ
lines and a heck of a lot of times setting up the Â
programming language java the runtime environmentÂ
finding a word editor a code editing they call Â
them integrated development environments theyÂ
weren't even really a thing back when i was Â
learning how to code in java or at least theyÂ
weren't available to everyone for free and now Â
in 2021 as i'm recording this we can do allÂ
of this in our browser right through the Â
tradingview platform in a handful of lines ofÂ
code it's just it's absolutely phenomenal it's Â
so exciting the world we live in and what isÂ
possible for everyday people like you and me Â
so this is just the beginning of your journeyÂ
as a coder and the beginning of your journey Â
taking your trading to the next level so i hopeÂ
you're as excited as i am to teach you this stuff Â
and as excited as i was to learn this stuff inÂ
the beginning believe it or not this right here Â
is the basic building blocks for every scriptÂ
you're ever going to write in pine script Â
and it really is this simple you can obviouslyÂ
make this as complex as you want you can change Â
the shape we're drawing you can change theÂ
color you can change all kinds of things the Â
location of the shape all sorts of things butÂ
it's not difficult it's not complex all it is Â
is learning new habits and new rules codingÂ
is still in english this is all english words Â
but the rules in which we express the commands weÂ
want to give pinescript are important but they are Â
very simple so you will learn them throughout theÂ
course don't be afraid if this is the first time Â
you've ever learned any coding if you followÂ
the lessons step by step one after another Â
you will be able to write your own scripts byÂ
the end especially if you take the whole mastery Â
course so strap in we're going to cover someÂ
really exciting stuff in the lessons to come Â
i can't wait good luck with your tradingÂ
and good luck with your coding speak soon
all right traders so in this lesson i'm goingÂ
to be breaking down how comments work in pine Â
scripts so comments are basically a wayÂ
of leaving notes in your code for yourself Â
or for other traders or coders who readÂ
your script so right here i have a blank Â
indicator script using the defaultÂ
template that tradingview have created Â
and you can see two comments at the top here theseÂ
are automatically added to all scripts that you Â
create through the pine editor this top commentÂ
here is saying that our source code is subject Â
to the terms of the mozilla public license andÂ
here's a link to that license if you want to read Â
what this means here's the license here andÂ
just really quickly while we're here i figured Â
we might as well go over this as i'm sure someÂ
of you are interested in what what this means Â
if you haven't seen it before but basicallyÂ
this just limits your liability as a coder Â
so it just says the covered software which is ourÂ
scripts is provided under this license on an as-is Â
basis without warranty of any kind the entire riskÂ
as to the quality and performance of the covered Â
software is with you and you being the script userÂ
or anyone who uses your script basically is using Â
your script at their own risk most open sourceÂ
software will operate under a license like this Â
and then next up we have our copyright so this isÂ
a copyright and then it will automatically insert Â
your trading view username here now both of theseÂ
comments are not read by the pinescript compiler Â
what that means is when the engine that runs yourÂ
script through the tradingview platform does its Â
thing it ignores these lines it's like theyÂ
don't exist and this is all the compiler will Â
see in fact it will really only see this so theseÂ
comments are really just for your eyes only and Â
the way you write them is with two forward slashesÂ
you can put them anywhere they don't need to be Â
at the start of the line they could be after theÂ
line so i could say here i declare my indicator Â
here we could say plot the close and you can evenÂ
use them to comment out code so let's say we want Â
to get the rsi here 14 period rsi on the closingÂ
price let's say there's a problem with our code Â
or there's something we want to test and we wantÂ
to temporarily remove this code without deleting Â
it we can just add two comments in front of itÂ
and now this code is ignored by the compiler Â
so that is the purpose of comments to leaveÂ
notes to yourself one other purpose which Â
we'll cover in future lessons is what's calledÂ
annotation comments so this right here is a Â
annotation comment it's a special comment thatÂ
is not ignored by the compiler but technically Â
isn't code you could think of this as kind ofÂ
like metadata if you're familiar with metadata Â
so this is just telling pinescript that we want toÂ
work with version 5 of pinescript if we get rid of Â
this and compile our script we're now dealingÂ
with the original version of pinescript which Â
had no version and we're going to get all kindsÂ
of errors because of that because the syntax of Â
version five of pine script is very differentÂ
to prior versions and by syntax i just mean Â
the grammar of the language the way we express ourÂ
code is different in version five than any other Â
version if i bring back that annotation commentÂ
and save the script now it compiles just fine Â
so that's the purpose of comments we'll be usingÂ
them a lot in our scripts i highly encourage you Â
to comment your scripts heavily it's always betterÂ
to have too many comments and not enough comments Â
the reason for that is there will be times whenÂ
you write a script and you'll come back to it Â
weeks maybe even months or years later and youÂ
might not remember why you did things a certain Â
way or why your code was written the way it wasÂ
having comments can help remind you why you did Â
what you did and it can help other traders knowÂ
what you're trying to do with your code as well Â
so if you're writing public open source scripts iÂ
definitely encourage you to comment them and it's Â
just a good idea in general to get into a habitÂ
of commenting your code regularly and extensively Â
so that you know what you're doing and it's kindÂ
of like um if you remember in school when you Â
did math stuff you always had to show your workÂ
you needed to explain how you got to your answer Â
comments are basically the sameÂ
thing using comments can explain Â
how you got to where you got to in terms of yourÂ
solution in your code if i open up a script i've Â
been working on recently which is my zen libraryÂ
you can see that this script has i think more Â
comments in it than actual lines of code in factÂ
it certainly does have more comments in it than Â
actual lines of code now that's not a normal thingÂ
you wouldn't normally see that in most scripts but Â
because this is a library and we'll get intoÂ
libraries in future lessons i don't want to Â
overwhelm you with too much information but eachÂ
comment here explains what each block of code does Â
in great detail the reason for this is that thisÂ
library is designed so that i could give it to a Â
complete stranger who knows nothing about me whoÂ
knows nothing about how i like to code and they Â
can work out exactly exactly to a t what everyÂ
single part of my code does if i got rid of all Â
of these comments the code becomes significantlyÂ
harder to read because there is no explanation Â
on um what is happening if we get rid of allÂ
of these comments and we're just left with this Â
this is not useful to most traders mostÂ
traders will see this and they'll just Â
move on to a different script becauseÂ
no one has the time to reverse engineer Â
and deconstruct exactly what this code doesÂ
but by having all these comments suddenly this Â
script is much much easier to read for anyoneÂ
who um is unfamiliar with what the code does Â
so that's the purpose of comments we'llÂ
be using them a lot throughout the course Â
so as i said before it's a good idea to get intoÂ
a habit of using them but don't worry you'll see Â
lots of examples of how to use comments in yourÂ
code in future lessons so this doesn't quite Â
make sense to you don't worry it will by theÂ
end of the course see you in the next lesson
all right hey traders welcome back in thisÂ
lesson we're going to be covering the indicator Â
annotation function now annotation function couldÂ
be also thought of as like a directive function Â
it's a special function that tells pan scriptÂ
important information about the general nature Â
of your script so this comment here of at versionÂ
equals five is what's called a compiler directive Â
so this is directing the compiler to version 5Â
of pinescript it's telling pinescript the engine Â
that runs pinescript to treat the code of thisÂ
script by the rules of version 5 of pinescript Â
the indicator annotation function does the exactÂ
same thing except that it tells pine script to Â
treat the code of this script as an indicator theÂ
reason we need to use this is because there are a Â
couple of different variations of script typesÂ
so we have strategy scripts so if i call this Â
strategy that changes the rules of this scriptÂ
if i say library that changes the rules again Â
so we only have three to work with indicatorÂ
strategy and library but each of those have Â
different rules that govern your script for thisÂ
lesson we're going to break down the indicator Â
function which is probably the script type thatÂ
you'll be working with the most especially in the Â
beginning of your pine script journey so let'sÂ
break down the parameters of this function so by Â
calling this an indicator function that givesÂ
the script access to a different subset of Â
inbuilt functions and commands to work with so forÂ
example let's try and use a strategy function here Â
let's say strategy.close and we need to pass an idÂ
here let's just say close our buy trade if i save Â
this script we'll get an error here that says youÂ
cannot use strategy functions in indicator scripts Â
please replace indicator with strategy so that'sÂ
why we need to use these annotation functions if Â
i change this to strategy suddenly the script isÂ
treated differently by the pine script compiler it Â
has different functionality and features but let'sÂ
stick with indicator for this lesson and let's Â
break down what we can do with this indicatorÂ
function so if i hover my mouse over indicator and Â
hold down control or command on a mac and clickÂ
on this function on the name of this function Â
we'll get the pinescript language referenceÂ
manual popping up here and this will tell us Â
all of the various arguments we have to work withÂ
here it'll give us a description of each one i'm Â
going to break down the most common ones here thatÂ
you will most likely use in most of your scripts Â
so let's get rid of our title for a moment hereÂ
and hover my mouse over this function name and Â
we'll get a list of arguments so the first oneÂ
we have is title so this is your long title Â
so let's say i want to call this my super fancyÂ
script and if i save this and move this down a Â
bit you can see that my script name has changedÂ
there and if i were to publish this script to the Â
trading view library this is what it would beÂ
called on the trading view library this is its Â
long title this is its more descriptive title butÂ
you can see that it takes up quite a lot of space Â
on my chart and if we had a lot of plotsÂ
here a lot of numbers plotting out here Â
having a long indicator title name could be aÂ
problem so let's say we want to abbreviate this to Â
msfs to do that we just add in a comma here allÂ
of our arguments in any function are separated by Â
commas so to add another argument or parameterÂ
to this function we need to put a comma there Â
and then i need to pass in short title and thenÂ
this is a string as well so we open up with Â
two quotations and let's say we want to call thisÂ
msfs now if i save the script watch our title name Â
here it's now abbreviated to msfs but our officialÂ
title is still my super fancy script and if i were Â
to publish this to the training view library thatÂ
is still what this script would be called but when Â
it's added to our chart this is what it will sayÂ
in the indicator box so that's how our titles work Â
next up we have overlay so by default overlayÂ
is set to false so if i save the script having Â
it set to false draws into its own box you can seeÂ
we're in our own oscillator box here like the rsi Â
or stochastics macd those sorts of indicators theyÂ
are drawn into their own indicator box they're not Â
drawn directly on the price action like a movingÂ
average would for example but if you want to draw Â
overprice action say you're working with a movingÂ
average script for example you want overlay to be Â
set to true overlay just means it overlays overÂ
your price action so if we set this to true and Â
save the script first nothing will happen becauseÂ
we've already added the script to our chart so to Â
update this particular parameter we need to removeÂ
our script by clicking on this remove button here Â
and then re-add it to our chart so now whenÂ
i click add to chart overlay will be updated Â
and it will be drawing over price action so if iÂ
zoom in here you can see that this script is just Â
plotting the closing price so it's connecting theÂ
closing price of all of these candles on my chart Â
directly over price action so that's what overlayÂ
does next up we have format so let's set overlay Â
back to false and remove the script save it addÂ
it back to my chart and let's say we want to plot Â
volume instead of the closing price so now let'sÂ
save the script and it will update whoops we'll Â
update and now it's plotting the volume of eachÂ
bar on my chart let me go to the daily so that Â
we get a higher number here so notice this numberÂ
down here is an exact number of the volume printed Â
um it's not that readable we don't really needÂ
to know the exact quantity of shares traded on Â
on a stock or in the crypto market how many of aÂ
particular crypto asset was traded in this case Â
we're dealing with ticks price ticks on theÂ
forex market tick volume we don't need to know Â
the precise number so if you are dealing thisÂ
is mostly useful for volume this i don't really Â
know of any other use cases where you'd wantÂ
to do this but this format parameter you can Â
see down there above the blue underline format canÂ
be set to format dot and if i press control space Â
or command space on a mac you get a list of theÂ
various formatting options we have to work with Â
here i'm not going to go over all of these youÂ
can play around with these in your own time to Â
see what they do it's not often you will need toÂ
change the format of your script anyway but in Â
today's example we're dealing with volume rightÂ
now so let's click on volume and save the script Â
now keep an eye on this number here it's nowÂ
changed to a smaller number with a k after it Â
so if i hover over the last bar on myÂ
chart that says 6.037 k so roughly 6 000Â Â
volume on this latest bar so that's the purposeÂ
of the format parameter in the indicator function Â
next up we have precision this is your decimalÂ
precision so let me get rid of this format Â
for now and let me get rid of this reallyÂ
quickly and save the script to update it Â
um the precision argument changesÂ
your decimal precision of the Â
numbers that draw onto the chart in your scriptÂ
so by default the precision is going to be set to Â
the decimal precision of your price so right nowÂ
we have five decimals here on euro dollar if we Â
were to go to a different market like uh bitcoinÂ
for example now we have a two decimal precision Â
and you can see after the decimal place hereÂ
we have two digits but if we wanted to override Â
that to a higher precision or a lower precisionÂ
we can do that using the precision argument in Â
this function so let me set this to 5 and save theÂ
script now you can see 5 decimal places after the Â
decimal place on this script now in thisÂ
particular case we're just plotting the Â
closing price so that's not that useful seeingÂ
five extra or three extra decimal places Â
on this price value but what if we wereÂ
plotting other values other indicator values Â
where we wanted to see those extra decimal placesÂ
but we couldn't see them because of the number Â
of decimals on our price so for example whatÂ
about a relative volume indicator let's say we Â
want to compare today's volume or this bar'sÂ
volume to the average over the past 10 days Â
and we want to know that number to a three decimalÂ
precision instead of just two that's where this Â
argument comes into handy you can changeÂ
the precision override the precision of Â
your indicator plot values with this argument weÂ
will be using this in future lessons but for now Â
we can move on i'll show you practical examples ofÂ
this later on in the course next up we have scale Â
so this is the axis the scale axis you wantÂ
to plot your values onto so by default your Â
indicator is going to plot onto whatever priceÂ
access you have on your chart so in this case we Â
have price plotting onto our right axis but if weÂ
wanted this to plot onto our left axis for example Â
you can use the scale argument here so we can setÂ
scale to scale dot control space let's set it to Â
left and save the script and we need to remove theÂ
script to update this and add it back to our chart Â
now you can see that our our values here are beingÂ
plotted onto the left scale not the right scale Â
so again not often you will need to do this butÂ
there is the option to if you need to let's get Â
rid of that for now save the script remove it addÂ
it back to our chart so whenever you're dealing Â
with a visual update like scale or overlay youÂ
need to remove the script and re-add it back to Â
your chart so if you make a change to your scriptÂ
and it doesn't update a general good rule of thumb Â
is to try removing it had it back on that willÂ
force tradingview to update your script entirely Â
now the next parameter we have to work with is maxÂ
bars back this is not something you will often use Â
in your scripts i've never used it in my scriptsÂ
to be honest but it's here if you need to use it Â
now this tells the script how many bars back itÂ
can reference from whichever current bar it's Â
calculating on so if we're looking at the finalÂ
bar on my chart and we set max bars back to 10Â Â
for example and i save the script whatever codeÂ
is running on this last script this last bar on my Â
chart the script can only reference the past 1 2 3Â
4 5 6 7 8 9 10 bars so only this price action here Â
now personally in my own coding i've writtenÂ
dozens of scripts over the years i've never Â
used this feature i've never used this max barsÂ
back i've never had to i've never had a reason to Â
but if you do run into a situation where you needÂ
to use this function this feature this is how you Â
would do it you can set your max bars back toÂ
10 just keep in mind that this is in reference Â
to the current bar so when your script isÂ
running over historical price action each Â
bar on your chart can look back 10 bars and thenÂ
this bar can look back 10 bars and then this one Â
etc so that's how that argument works but let'sÂ
get rid of it for now since we would rarely use Â
that the final parameter i'm going to cover hereÂ
that is commonly used is time frame so time frame Â
specifies what time frame your script can runÂ
on so for example let's drop down to the four Â
hour chart and change this to d short for dailyÂ
and save the script now my script is plotting Â
the daily time frame closing price onto my chartÂ
instead of the four hour so if i zoom in here Â
you can see that each time this updates weÂ
get a new value down here so on this bar here Â
a new day began and the previous day's closingÂ
price was five four six nine zero and then on the Â
bars in between we get n a because these fourÂ
hour bars are plotting in between the next day Â
and then on that next day's beginning we get theÂ
previous day's closing price which was five seven Â
four eight seven and so on so that's one wayÂ
to hard code your script to only reference a Â
particular time frame i wouldn't recommend doingÂ
this there are better ways to do this depending on Â
the script if you have a script that you only wantÂ
to reference a particular time frame you might Â
want to hard code it this way but if you have aÂ
script that you want to be able to use on multiple Â
time frames you're better off using user inputsÂ
to specify the time frame of your script and we Â
will cover that in future lessons i don't want toÂ
overload you with too much information so we'll Â
leave this lesson here if you want to see whatÂ
these other parameters do again just hold ctrl Â
and click on this function name and you'll get aÂ
list of the arguments we have here with detailed Â
descriptions on how they work but anyway that'llÂ
do it for this lesson i'll see you in the next one
hey traders in this short lesson i will introduceÂ
you to the concept of namespaces so namespaces Â
in pine script are what we call the keywordsÂ
that contain certain functions or variables so Â
that might sound a bit confusing but when i showÂ
you a visual example it should make perfect sense Â
there are several namespaces that we have accessÂ
to in our pine script code the first one i'm going Â
to show you is the technical analysis namespace soÂ
for example let's say we want to get the rsi value Â
to do that i can create a new variable calledÂ
rsi and we can assign this variable or initialize Â
this variable using the equal sign so rsi isÂ
set to and then we need to reference the ta Â
or technical analysis namespace so if iÂ
write ta here then a full stop and then Â
control space or command space on a mac we get aÂ
list of all of our technical analysis functions Â
so if i start writing rsi here is our rsiÂ
function and you can see here that it is Â
underneath the ta or technical analysis namespaceÂ
so we'll click on that we pass in as price source Â
close and 14 default period there we go we haveÂ
an rsi value and if i cut this plot down here Â
and change the plot from the closing price to theÂ
rsi value we just retrieved let's save the script Â
we're now plotting the rsi so pinescript makesÂ
it really easy to access all of the most popular Â
indicator tools that traders typically use andÂ
you'll find all of your indicator functions Â
under the ta namespace so that's really itÂ
for namespaces that's all you really need to Â
know you can also create your own librariesÂ
um we'll cover that later on in the course Â
but when you create your own custom library itÂ
behaves pretty much identically to these inbuilt Â
name spaces so for example if i type in import zenÂ
and the art of trading control space here is one Â
of my libraries i've created if i import this asÂ
zen i can now reference my zen library namespace Â
the same way we did the technical analysisÂ
namespace so for example if i write here zen dot Â
control space command space we get a list ofÂ
all of my custom functions these are functions Â
that i created that i wrote in my own codeÂ
in the zen library script and i published Â
this to the trading view platform i can nowÂ
reference all of these functions the same way Â
we can reference the inbuilt functions thatÂ
tradingview offers what pinescript offers Â
but as i said we'll cover libraries in a futureÂ
lesson because it is quite an advanced concept so Â
i just wanted to make you aware of that featureÂ
and so you can basically think of a namespace as Â
a collection of functions or tools that you'veÂ
written either you've written or the trading Â
view pan script developers have created so beforeÂ
we end this lesson um we'll go over just a couple Â
of other namespaces for example if we're dealingÂ
with strings so text this is a string right here Â
if i create a variable called my stringÂ
and we just call this a string of Â
text i can now use the string name space so strÂ
is short for string if i put in a dot and then Â
control space or command space we get a list ofÂ
all of the different functions we can use relating Â
to strings so for example um if i set this toÂ
the text 10 and then i use the two two number Â
function and we pass in my string if i cut thatÂ
and paste that into our plot and save the script Â
we are now plotting the number 10 after usingÂ
the string namespace to convert this text Â
into a number and there are a whole bunch ofÂ
other namespaces we have the strategy namespace Â
when you're dealing with strategy scripts so youÂ
have your trade commands and various variables Â
that you can reference such as your currentÂ
account balance and things like that Â
we also have the request namespace which we'llÂ
cover in future lessons this is where you retrieve Â
or request financial data about stocks you canÂ
reference quandl which is a third-party resource Â
uh that offers all sorts of things like umÂ
sentiment interest rate information all kinds Â
of stuff we'll cover quandl in a future lesson andÂ
then we also have the security function here which Â
we use to reference other symbols and other timeÂ
frames so you use the request.security function Â
to request for example we're on euro dollarÂ
one hour chart here maybe i want to check Â
what the daily high and low is and then plotÂ
that information over this one hour intraday Â
time frame to do that we would use theÂ
request.security function and so that is Â
a quick crash course on pine scriptsÂ
namespaces and we'll be using these frequently Â
in our scripts so you'll get used to usingÂ
these and you'll soon memorize them all very Â
quickly anyway that's it for this lessonÂ
i will speak with you in the next one
all right traders welcome to the price seriesÂ
lesson in this lesson i'm going to be showing Â
you how to reference candlestick price data soÂ
you're open high low and close this is obviously Â
going to make up the backbone of most of yourÂ
scripts you're going to need to reference this Â
data very frequently in your scripts since what isÂ
price analysis without referencing price so it's Â
quite simple to access this data obviously theÂ
challenge comes with what you do with this data Â
first of all let me get rid of precision oneÂ
that's from a previous lesson so here i have a Â
blank script let me save the script to show youÂ
so we're just plotting the closing price onto Â
our chart so by default this is the defaultÂ
template for any new script we already have Â
our closing data being referenced and to referenceÂ
the other price points on your chart is as simple Â
as you might think so let's say we want to getÂ
our candle open price i'm going to declare a new Â
variable here called candle open and it's goingÂ
to be set to the open price value next up we'll Â
get our high so candle high is set to high then weÂ
can get our candle low is set to the low and then Â
candle close is set to the close now you don'tÂ
normally need to do this you can just directly Â
reference open high low and close in your scriptÂ
but for today's example i thought this might be Â
a little more intuitive to see what's going onÂ
here so now let's save the script and let's draw Â
these values onto our chart so i'm going to use aÂ
comment here say draw candle data onto our chart Â
i'm going to paste candle open in there copy thisÂ
and i'll paste it four times and i'll just paste Â
in each variable here and let's change the colorÂ
of each plot because if i save the script now Â
we're going to get four blue lines drawingÂ
on our chart and we can't tell what's what Â
so let's set the color of the open to color dotÂ
blue and now i'm going to copy this line of code Â
and paste it in and let's change the color ofÂ
each data value here let's change the high to red Â
we'll change the low to green and let's changeÂ
the clothes to purple and save the script we Â
should get four different colors plotting onto ourÂ
chart here now and each color corresponds to each Â
candle price so it's as simple as that to getÂ
our price data which is what we're doing here Â
so now let's say we want to do something usefulÂ
with this data let's say we want to get the Â
current bar's size in points so we want toÂ
subtract the high from the low so now let's Â
create a new section of code here and i'll sayÂ
analyze price data and for this we're going to Â
create a couple of variables the first variableÂ
we create is going to be called candle size and Â
to calculate the candle size is really easy allÂ
we need to do is subtract the low from the high Â
so high minus low will give us our candle sizeÂ
in points and let's plot this onto our chart Â
as well so we'll call this candle size we'll setÂ
this to color dot orange and in fact let's comment Â
out all of our open high low close because weÂ
don't really need to see that data on our chart Â
save the script we should be getting an orangeÂ
line drawing here now which is showing the candle Â
size in points or pips in this case so right nowÂ
as i hover over the last bar on my chart here Â
our candle size is 6.9 pips so as you can see it'sÂ
really easy to analyze price data obviously it Â
gets more complex the more complex analysis you'reÂ
doing but it's really simple to access this data Â
and to analyze it let's try something a littleÂ
bit more complicated to demonstrate the historical Â
operator so let's say we want to referenceÂ
a historical bar on our chart this will Â
reference the current bar and this will run onÂ
every bar in our chart so as i hover my mouse Â
let's hover over this bar here which is quiteÂ
large if i hover my mouse over that you can Â
see down here this number says 65.2 pips soÂ
this script is running on each historical bar Â
on our chart and so every bar on our chartÂ
will reference its own open high low and close Â
but what if we wanted to reference let's sayÂ
10 bars back so we want to reference 10 bars Â
in the past let's go back to our current bar andÂ
let's say we want to compare the current bar's Â
candle size to the candle size of a bar 10 barsÂ
ago to do that is really simple let's just create Â
a new variable here called candle size 10. andÂ
we'll set that to the high of the bar 10 bars ago Â
minus the low of the bar 10 bars ago so toÂ
reference historical data we use square brackets Â
and then we pass in a number an integer number aÂ
whole number this whole number is your look back Â
count so this will get the candle sizeÂ
of the bar 10 bars ago so let's compare Â
these two values to do that we'll say candle sizeÂ
ratio and we will divide our current candle size Â
by the candle size 10 bars ago and let's plotÂ
that onto our chart as well candle size ratio Â
with the color of purple so when i save theÂ
script we'll be getting another line drawing Â
onto our chart that is comparing the current bar'sÂ
size to the bar size 10 bars ago save the script Â
and there we go so the current bar is 130 percentÂ
the size of the bar from 10 bars ago or 1.3 times Â
and it's that simple that's how we referenceÂ
historical price data very easy and this Â
historical operator works on any series of dataÂ
that we can reference in pine script so this Â
applies to indicator values as well it appliesÂ
to basically anything that has a series of data Â
that we can reference so for example let's sayÂ
we wanted to get the atr value of the current bar Â
to do that we could just create a new variableÂ
here called atr is set to ta.atr and let's just Â
pass in the default 14 length periodÂ
so this will get the current atr value Â
and let's say we wanted to plot the atrÂ
from 10 bars ago we can do so just like that Â
so this plot function now will reference theÂ
atr value from 10 bars ago save the script and Â
now our white number here is drawing theÂ
atr of 10 bars ago really really simple Â
to reference historical data and this appliesÂ
to anything as i said we could reference the Â
volume from 100 bars ago if we wanted to let's sayÂ
234 bars ago save the script now our white line Â
is the volume from 234 bars ago there is a limitÂ
to how far back you can look so if i set this to Â
99999 and save the script we'll get a error youÂ
can see this little warning sign pops up here Â
if i click on that it says too large max totalÂ
bars back and then we have our large number here Â
the maximum is 300 000 bars which is still quite aÂ
lot of bars so let's set this back to let's say 10Â Â
save the script and there we go so that's how youÂ
reference open high load close data that's how you Â
reference historical data using the historicalÂ
series operator and this technique applies to Â
any value indicator values as well so if we wantedÂ
to compare the atr from 10 bars ago the same way Â
we did here we could just say atr 10 and thenÂ
atr ratio is atr divided by hr10 this will work Â
just fine the same way this did now obviouslyÂ
this is a pretty useless example of how to use Â
price series and indicator seriesÂ
in our scripts but in future lessons Â
we'll be covering more complex more practicalÂ
demonstrations of analyzing price action using Â
this information and that brings me to theÂ
end of this lesson i'll see in the next one
in this lesson we're going to be covering theÂ
fundamental commonly used data types that you Â
will be using in most of your scripts to performÂ
your calculations and analysis the first data type Â
you're going to be working with in all of yourÂ
scripts for the most part will be number types Â
so there are two types of numbers inÂ
pinescript we have integer type this is Â
whole numbers so for example 1 would be aÂ
integer this could be 1 10 100 20 whatever Â
just as long as it's a whole number and there'sÂ
no decimal in it that will be called an integer Â
next up we have float type this is like anÂ
integer except it has a decimal place after it Â
so any number with a decimal place is consideredÂ
a float the reason this is called a float type is Â
because there is no fixed number of digits beforeÂ
and after the decimal place so the decimal place Â
can float around and so that's why they call itÂ
a float programming can be weird like that don't Â
ask me why that became a thing but you'll get usedÂ
to it so there's a lot of technical jargon you'll Â
need to learn in coding integers just mean wholeÂ
numbers there is more nuance to this for example Â
there is a maximum number that an integer can beÂ
but you don't need to know about that because it's Â
extremely unlikely you're going to run into thatÂ
issue in pine script i certainly never have in the Â
three plus years i've been working on all kinds ofÂ
scripts but anyway moving on we have our floating Â
point numbers float type numbers um for exampleÂ
a closing price is a float because there's a Â
decimal number in it you can see here on bitcoinÂ
we have two digits after the decimal place that Â
means that this price here is a floating pointÂ
data type next up we have it's not another data Â
type it's just a different way of using floatingÂ
points so float type e we'll call this and if i Â
were to say 0.1 and then use the mathematicalÂ
operator e and then put 2 on the end here Â
what this is saying is return the number orÂ
the result of this equation which is 0.1 times Â
10 to the power of 2. now it's not often you'llÂ
need to use this if ever but the option is there Â
if you need to or if you're mathematicallyÂ
inclined for me personally i'm terrible at math Â
which is interesting considering i became a traderÂ
and programmer but that's a beauty of modern Â
programming you don't need to be good at math toÂ
be a programmer but if you are talented at math Â
this is a tool your disposal the next dataÂ
type we have to work with is what's called Â
boolean values so a boolean data type isÂ
simply yes or no true or false one or zero Â
in pine script it's represented by the word trueÂ
and the word false so a bull type or boolean type Â
would look something like this true for true falseÂ
for false so let me leave that as true this is Â
quite simple to understand you'll use this dataÂ
type quite a lot in your scripts in fact these Â
first three data types will make up the majorityÂ
of your scripts in terms of how you calculate Â
stuff the next data type we have that will beÂ
commonly used is color types so color types Â
in pine script are their own data type and toÂ
reference color data types you can use the inbuilt Â
data types that panes could provide if i type outÂ
color and then a full stop and hit control space Â
or command space on a mac and i scroll down youÂ
can see a list of inbuilt colors here so if i Â
say color.red that will give the pine scriptÂ
inbuilt red color as a data type and this can be Â
passed into any of my drawing tools so for exampleÂ
we've got a plot here that is plotting our float Â
type e if i change this to say color equals colorÂ
type whoops and i save the script our line will Â
turn red so you can see there so that's whatÂ
color data types are like you can also use um Â
hexadecimal colors so if i wanted to color thisÂ
red in hexadecimal that would look like ff000Â Â
i save that we get bright red we'll coverÂ
hexadecimal colors in a future lesson Â
you don't need to know them in order to to useÂ
colors in your script but if you are familiar Â
with hexadecimals from web development primarilyÂ
these are used in web development so if you're Â
familiar with working on websites you'll knowÂ
how hexadecimal colors work or you can use a Â
hexadecimal color picker just look up hex colorÂ
picker on google and this can be an easy way to Â
fill out custom colors in your scripts one otherÂ
option we have to work with in pan script is the Â
color dot rgb function this we can pass in threeÂ
values or four values actually red green blue Â
and transparency so for example if i wanted fullÂ
red i could type in two five five comma zero green Â
zero blue and zero transparencyÂ
now the transparency is optional Â
if i just put in rgb as two five five zeroÂ
zero save the script this will stay red Â
actually let's change this color so that weÂ
can actually see the difference so this will Â
now be bright green there we go because we've setÂ
green to full so rgb colors range from 0 to 255Â Â
0 being none and 255 being the maximum andÂ
if we wanted to change the transparency let's Â
say we wanted to make the line completelyÂ
transparent we could set transparency to 100Â Â
save the script and now the line will disappearÂ
from our chart but it's still plotting up here so Â
that's a one way of plotting values onto yourÂ
chart without the user seeing the actual line Â
being drawn i use this quite a lot in my scriptsÂ
to draw information onto the chart that i want Â
to reference in my indicator values butÂ
that i don't want to see on the actual Â
chart such as stop loss sizes and things likeÂ
that don't worry if this was a bit confusing Â
we'll cover color types in future lessons inÂ
great detail and in more practical examples Â
the next data type we have to work with thatÂ
you will commonly use in your scripts not all Â
scripts but some scripts will be the stringÂ
data type so this will be string type equals Â
text so string is just what programmers callÂ
text and in order to define it we need to put Â
two quotation marks on either side of our text theÂ
reason why we do that is if we just say text here Â
then pinescript doesn't know the differenceÂ
between this and an actual function or variable Â
in our script if i save the script we'll getÂ
an error here it'll say undeclared identifier Â
text if we put quotation marks around it andÂ
save the script will get no error because Â
now pine script knows that this is text nowÂ
you can use quotation marks or you can use Â
single quotation marks as well that will workÂ
just the same if i say the script this is Â
treated exactly the same as if we'd used quotationÂ
marks so it's really just a matter of preference Â
which one you use i prefer to use the doubleÂ
quotes personally just because i'm used to that Â
from other programming languages but if you'reÂ
experienced in a different language and you're Â
used to using single quotes you can use them inÂ
your scripts if you want to and just as a side Â
note while we're here if you want to includeÂ
a single quote in your text you can't just add Â
another single quote because now that's treatingÂ
this as a string and then we just have a single Â
quote on its own if i save the script we'llÂ
get an error because we didn't close off Â
this string here if we add a backslash in frontÂ
of this text pinescript will now know that we want Â
to include this quote within our string then thisÂ
backslash is telling pinescript we want to include Â
this single quote within our text soÂ
for example let's change this to it s Â
bullish now if we were to draw this onto ourÂ
chart using a label or any other text drawing Â
function a table or something like thatÂ
this text would display on our chart as this Â
so this quotation would be included in theÂ
text and the backslash would be removed Â
so that's the purpose of the backslash you canÂ
also do things like backslash n and that would Â
move bullish onto a new line and so if we were toÂ
draw this onto our chart it would look like this Â
it's bullish on a new line there are severalÂ
escape characters you can use in your strings Â
we won't cover that in today's lesson becauseÂ
it's outside the scope of this lesson i'm just Â
introducing you to these concepts i don't wantÂ
to overwhelm you with too much information Â
and so let's just get rid of all this and goÂ
back to text and we'll cover escape characters Â
and stuff like that in future lessons so beforeÂ
we wrap up this lesson let's plot all of these Â
types to our chart and we'll just have a quickÂ
look at what they look like so we have integer Â
type float type flow type e and bull type weÂ
can't plot a boolean directly onto our chart Â
so we can only plot these numbers at the momentÂ
directly onto our chart so let me change this to Â
color dot white and i'll change this toÂ
color.white as well and we'll save the Â
script so now you can see that we're plotting ourÂ
integer type as 20 it's just a whole number and Â
then our float type let me change my floatÂ
type to [Music] 33.3 and save the script
now here's our float type 33.30 now remember in aÂ
previous lesson i talked about precision of your Â
script because we have two decimal placesÂ
after our market price we have two decimal Â
places on our indicator values so even thoughÂ
i set this number to 33.3 it displays as 33.30Â Â
if i didn't want that i could change my precisionÂ
to one save the script and now it's certainly Â
plotting to one decimal place and so here we'reÂ
plotting our integer number as a whole number Â
our float number and then our float typeÂ
e number and in our integer plot we are Â
passing in our color type now let's use ourÂ
bull type here let's say if bull type is true Â
then let's overwrite our color type to color dotÂ
red so now when i save the script this color here Â
this plot will turn to red because bull type isÂ
set to true and we just said if bull type is true Â
override color type with the color red and toÂ
override something we need to use the colon equals Â
symbol we can't just use equals because that'sÂ
declaring a new variable we want to overwrite this Â
variable with this new one and don't worry we'llÂ
cover this in future lessons i'm just showing this Â
to you before we wrap this lesson up how ballÂ
types work so now if i save the script this Â
color will turn red because bull type is true andÂ
we've overwritten our color with red if i change Â
this to false the color will go back to greenÂ
because bull type is no longer true say the script Â
there we go so that's it for this lesson thereÂ
are several data types here that we'll work Â
with these are the common data types there areÂ
other data types too like tables labels drawing Â
objects things like that but we'll cover thoseÂ
in future lessons once you become more familiar Â
with the basics of pine script so don't worryÂ
if you're overwhelmed by any of this lesson Â
throughout the course we'll be using all of theseÂ
data types quite regularly in practical scenarios Â
and over time you'll learn how they all workÂ
and how you can use them in your own scripts Â
so that'll do it for this lesson iÂ
hope you're enjoying the course so far Â
and if you are stick around becauseÂ
it's about to get a lot more interesting
hi welcome back to another partnership lessonÂ
in this lesson we are going to be covering how Â
to appropriately uh or correctly declare yourÂ
variables in your scripts so variables are used Â
in all programming languages we've already coveredÂ
a few examples of them in this lesson we're just Â
going to keep things simple and cover the basicÂ
fundamentals of variable declaration in order to Â
declare a variable we need to basically give it aÂ
name and then that name is like a key so we have a Â
key and a value so in today's example we're goingÂ
to be counting candles in our chart so i want to Â
count how many green candles are on my chart soÂ
i'm going to say green candle count is set to zero Â
so right here we have declared a variableÂ
we've declared a variable with the name or key Â
green candle count and we've given it theÂ
value 0. now pi script will automatically Â
determine what data type your variable is basedÂ
on what value you give it so pinescript knows Â
that 0 without any decimal places is an integerÂ
value a whole number value so whatever we do Â
with this variable will be treated as an integerÂ
value if we were to add a decimal place like 0.1Â Â
suddenly this becomes a float and now whateverÂ
we do to this variable needs to be governed by Â
the rules of floating point numbers and thereÂ
are certain things you can and can't do with Â
data types so it's important that you understandÂ
how the data types work the good news is you'll Â
pick this up throughout the course it's notÂ
particularly complex but it is important that Â
you understand how data types work now you canÂ
explicitly tell pinescript what type of variable Â
you want for example we wanted to tell pinescriptÂ
that this green candle count needs to be a float Â
we can just add the word float inÂ
front of it and save the script Â
and now pinescript knows that even though there'sÂ
no decimal place after this whole number value Â
this essentially becomes 0.0 pinescript isÂ
now treating this as a floating point number Â
even though we gave it an integer value now if weÂ
were to change this to text for example a string Â
this won't work if i save the script pinescriptÂ
says declared typefloat is not compatible with Â
the assigned type string so whatever data typeÂ
you give it you need to make sure it's accurate Â
but the option to explicitly define what data typeÂ
your variable is is possible using these data type Â
operators so this can be useful in certainÂ
situations for example if i get rid of this Â
and i set green candle counter n a or not a numberÂ
this is basically null nothing i've set green Â
candle count to literally nothing it's not a dataÂ
type of any kind if i then want to draw that onto Â
my chart so let me paste the green can accountÂ
into the plot save the script you can see that Â
it says down here line seven value with n a typeÂ
cannot be assigned to a variable that was defined Â
without a type keyword so we cannot declare greenÂ
candle count as n a but if we add float on the end Â
and save the script this will now compileÂ
and we are now plotting n a onto the chart Â
so that is one useful way of declaring a data typeÂ
with nothing as its initial value so we don't want Â
this to be zero we want this to be nothing theÂ
only way to do that is to explicitly give this Â
variable a type keyword but we don't usually needÂ
to do this so i'm going to get rid of that and Â
set this back to 0 and save my script so now we'reÂ
plotting just zero onto our chart on every bar Â
now let's say that we want to count every greenÂ
bar on our chart to do that we need to check if Â
the closing price is greater than the openingÂ
price then set green candle count to green Â
candle count plus one now notice that i used theÂ
colon equals operator here and i didn't just set Â
equals now the reason for this is because once aÂ
variable is already declared in order to overwrite Â
the value that we've given this variable weÂ
need to use the equals the colon equals operator Â
to reassign this variable to a new value so forÂ
example if i set this to 50 and i save the script Â
we will still be plotting zero here and we get anÂ
error or a warning this orange writing down here Â
is a warning not an error it's just bringingÂ
to our attention that maybe we made a mistake Â
it says here that shadowing variableÂ
green candle count exists in the parent Â
scope did you want to use the assign operatorÂ
instead of the initialize operator or equals Â
so when you're first declaring a variable you needÂ
to use the equals that initializes the variable Â
you can't use the assigned variable until theÂ
variable already exists so if i save the script Â
now we'll get an error that green candle countÂ
is an undeclared variable so the equal sign is Â
for declaring a new variable and the colon equalsÂ
is for reassigning an existing variable and new Â
value so now if i change this to colon equalsÂ
instead of plotting 0 onto our chart like we do Â
here if i use the colon equals we will now beÂ
plotting 50 because our green candle count is Â
being overwritten with the number 50 but onlyÂ
on bullish bars so let's say we want to count Â
all the green bars on our chart to do that we needÂ
to set green candle count two green candle count Â
plus one so that will increment this variable byÂ
one it will get whatever its current value is and Â
add one to it so let me save the script hereÂ
and you'll notice that on each bullish bar in Â
our chart we're only drawing one onto the chartÂ
and on bearish bars we draw zero the reason for Â
this is that our variables are re-declared onÂ
every new bar on our chart so every time a new Â
bar historical or real time begins drawing ontoÂ
our chart our script code is run all over again Â
it just keeps looping our code so every time ourÂ
script runs green candle count is set to zero Â
and so it never gets past one because on everyÂ
new bar this code is run again green candle Â
count is reset back to zero and then incrementedÂ
by one on bullish bars if we want this variable Â
to not update on new bars but to persist acrossÂ
all of the bars on our chart we need to use the Â
var operator so var converts this green candleÂ
count variable into what is called a persistent Â
variable so this variable will now persist acrossÂ
all of the bars on our chart and so whenever Â
we detect a green bar the green candle countÂ
will increment by one whenever we encounter a Â
red or bearish bar nothing will happenÂ
because our little if statement here Â
will not be true don't worry we'll cover ifÂ
statements in more detail in future lessons Â
but for now if i save this script we will nowÂ
be counting every green bar over historical Â
price data so if i save the script there youÂ
can see that our line is incrementing slowly Â
from bottom left to top right if i reset myÂ
chart and hover over this last bar on my chart Â
we have 11 771 bullish bars on our chart fromÂ
whenever our historical price action began Â
so that is the purpose of the var variable now theÂ
reason um not all variables of va are variables Â
are because let's say we want to draw a shapeÂ
whenever we detect a bullish bar if i change draw Â
shape to true and then we use the plot shapeÂ
function and we pass in our draw shape variable Â
if i save the script now you can seeÂ
an x plotting in our box whenever a Â
bar is bullish so for every green bar here we haveÂ
an x if i change this draw shape to a var variable Â
and i click save all of these bars will haveÂ
an x above them because the very first time Â
we detect a bullish bar draw shape will be setÂ
to true and it will never reset back to false Â
because we're using a var variable so let meÂ
save the script here to show you what i mean Â
you can see we have all these x's if i go backÂ
to the very first bar on my chart using the alt g Â
shortcut here you can see that the very first barÂ
in our chart is bullish and so draw shape is set Â
to true and it is never set back to false becauseÂ
this is a persistent variable and so we draw xs on Â
every single bar if i get rid of var and save theÂ
script now draw shape is reset on every new bar on Â
our chart and we want that to happen in this caseÂ
for this particular variable because we want it to Â
be reset on every new bar we want each new bar toÂ
be considered as a brand new calculation so that Â
is why not all variables are persistent with thisÂ
var tag and we need to explicitly tell pine script Â
when we want a variable to be saved across all ofÂ
the bars on our chart this var can be useful for Â
all kinds of things such as saving your stopÂ
loss and target until one is hit and drawing Â
that onto the chart it can be useful for keepingÂ
track of certain market conditions so for example Â
maybe you want to check when the rsi goesÂ
overbought so you would set your var variable Â
to true when the rsi goes overbought and then youÂ
want to wait for a bearish candle and once that Â
happens maybe you enter short for example andÂ
then maybe you reset your rsi flag or your rsi Â
overbought monitoring variable thoseÂ
are some practical use cases for this Â
variable type let's get rid of our draw shapeÂ
variable here for a moment and let's just count Â
every single bar on our chart to do that we canÂ
rename our variable to total bars and get rid Â
of our if statement and get rid of this and justÂ
plot total bars down here now before we continue Â
i should probably quickly go over the namingÂ
conventions for variables the most important Â
thing you need to know is that variables cannotÂ
start with a number so if we change this to one Â
total bars and save the script we'll get an errorÂ
down here because you cannot start a variable Â
name with a number you can have it after text soÂ
we could say t1 odual bars and save the script Â
that will work just fine you can have any numberÂ
on the end of your variable name and that will Â
work just fine you can have an underscore inÂ
front of your name your variable name that'll Â
be okay you can't use any other symbol soÂ
we couldn't use a dollar sign for example Â
that will give us a compile errorÂ
so you can only use underscores Â
and text to begin your variable name andÂ
you can have numbers and underscores in Â
your variable names but that's as creative asÂ
you can get with your variable names so that's Â
important to keep in mind but anyway let's wrapÂ
this lesson up by counting how many bars in total Â
have drawn onto our chart to do that all we needÂ
to do is increment our total bars by 1 whenever Â
our script runs on a new bar so let's save theÂ
script and see how many bars drew onto our chart Â
there you can see a diagonal line allÂ
the way from bottom left to top right Â
you can see that we've had 23 553 bars plottedÂ
onto our chart in total you could also get this Â
number by using the bar underscore index so if iÂ
plot that onto our chart you can see we get the Â
same number minus one the reason for that is thatÂ
everything in programming starts from zero and Â
so the very first bar on our chart isÂ
considered by our index zero and our script Â
would have incremented our total bars to one soÂ
in our scripts case let's plot total bars with the Â
color of color dot purple and save the script nowÂ
we'll get two lines drawing um offset by one so if Â
i hover my mouse over this very first bar you canÂ
see that our script says that this bar number one Â
whereas bar index says it's bar number zero theÂ
reason for that is that our total bars number is Â
incremented on the first bar whereas bar indexÂ
is not it's only incremented after that bar is Â
finished drawing so it starts from zero one twoÂ
three so on all the way to our final bar and our Â
total bars starts from 1 and counts all the wayÂ
up to the last bar so that about does it for our Â
variable declaration rules and fundamentals we'llÂ
be covering variable declaration in quite some Â
detail in the lessons to come and in much moreÂ
practical use cases so again if this is all brand Â
new to you and you're a little bit overwhelmedÂ
don't worry just keep going through this content Â
and eventually it will start to click you canÂ
always re-watch the lessons or send an email Â
to support the artoftrading.com if somethingÂ
doesn't make sense to you and i can help guide Â
you to understand these concepts better but withÂ
that said that brings me to the end of this lesson Â
i'll see you in the next one where we will coverÂ
getting user input in your scripts see you there
okay so in the official pinescript basics courseÂ
over on my website at pinescriptmastery.com Â
this is where i would get into how toÂ
get user input from the settings menu Â
in your scripts now the problem i have hereÂ
is that this video alone is 40 minutes long Â
almost and would make this youtube video threeÂ
hours long and i wanted to try and keep this Â
at two hours or less so instead of copying thisÂ
lesson from the official course into this youtube Â
series i'm just going to briefly go over theÂ
basics of user input so in the official lesson Â
i go into great detail about each input typeÂ
and all of the parameters we have to work with Â
when getting user input but for this lessonÂ
i'm going to keep things extremely simple we're Â
just going to get a couple of user inputsÂ
without bothering with all of these extra Â
optional parameters and if you do want to learnÂ
the specifics of all of the various advanced Â
user input functionality and features we have toÂ
work with in pine then it's definitely going to be Â
worth signing up to the official pine scriptÂ
basics course and going through the material Â
so let's jump into the pine editor and go overÂ
some basic user input so that you can at least Â
get started with adding options to your scriptsÂ
so here i am with a blank script all i'm doing Â
is plotting an a to the chart so that my scriptÂ
will compile and let's get started with getting Â
some user input so the first type of input iÂ
want to show you guys is a boolean input and to Â
get a boolean input which is just a true or falseÂ
value we use the input dot bool function and this Â
function has several parameters we can work withÂ
i'm just going to show you how to use the title Â
and the default value so i can title this someÂ
true false setting and set the default value Â
to let's set it to true save my code and nowÂ
i've opened up the little settings menu here Â
we have our some true false setting that we canÂ
turn on or off and we can reference this in our Â
script like we would any other variable the nextÂ
two inputs i want to show you are number inputs Â
so the first one is going to be an integer inputÂ
that's just a whole number so input.int will get Â
you a whole number input again this has severalÂ
parameters we're only going to cover a couple Â
of parameters here the first one is going toÂ
be title we'll set this to an integer input Â
we'll set the default value to 33 and we will setÂ
the minimum value to zero and the max val to 40. Â
and let's also set the step to two so nowÂ
when i save my code i'll explain what each Â
parameter here does open up the settings menuÂ
we now have a number input the step parameter Â
tells the interface how many numbers to incrementÂ
or decrement when we click the up and down arrows Â
here so if i click up you can see it's going upÂ
in steps of two and now that we've reached 39Â Â
we cannot go any higher because our maximum valueÂ
is 40 and because this up arrow is trying to Â
increment this to 41 it's not working you'd haveÂ
to type in manually 40. and that will work if you Â
type in anything higher if we type in 50 it willÂ
do what i just did there just cut off the zero Â
let's try something different let's try 77. let'sÂ
try 99. yeah you can see it's just cutting off Â
the second number there and rounding down to theÂ
first number um and same with our minimum vowel if Â
we go down to zero because we're incrementing inÂ
steps of two we're trying to go to minus one but Â
we can't here because we've set the minimum valueÂ
to zero if i set this to negative ten save my code Â
open the settings now we can go down intoÂ
the negative numbers so that's how we Â
get integer inputs from the user let's have aÂ
look at float inputs or decimal numbers to do that Â
we just use the input.float title this decimalÂ
input we'll give it a default value of 11.1 and Â
if i hover over this function name you can seeÂ
it has a bunch of other input function parameters Â
now i won't bother with min val maxval and stepÂ
i just showed you how to do that with integers Â
it's exactly the same with floats but whatÂ
i will show you how to do is use the confirm Â
parameter so if i set confirm to true save myÂ
code for this to work i need to remove the script Â
from my chart and when i add the script to myÂ
chart now that i've set confirm equals true Â
on this input variable watch what happens whenÂ
i click add to chart i now have to confirm Â
this input so this confirm dialog popped upÂ
anything you set confirm equals true to will pop Â
up when you first add the script to your chart andÂ
now you need to set this to whatever this setting Â
is supposed to be then you click apply now whenÂ
you open up settings menu everything is uh back to Â
normal so that's a float input very simple thereÂ
pretty much the same as an integer one slightly Â
different input i'll show you how to use is theÂ
price input so price input is essentially a float Â
input except that it's treated as a price value soÂ
if i set price input let's set the default value Â
to zero and set confirm equals true watch whatÂ
happens now when i click uh save and add the Â
script to my chart actually let me get rid of thisÂ
confirming true since i already showed you how Â
that works this one is slightly different a priceÂ
input is slightly different to a float input and Â
i'll show you what i mean if i click add to chartÂ
we now have to set the price input price for our Â
basic user input script and you can see we haveÂ
this horizontal line that tracks with my mouse Â
this is making me forcing me to select a priceÂ
value with my mouse so for example if you're Â
writing a script maybe that detects candlestickÂ
patterns around a support and resistance level Â
and alerts you so that you don't need to babysitÂ
your charts all day you could use this type of Â
input to place this line at a support level likeÂ
i see here if i click right here and i open up my Â
settings menu my price input has now been set toÂ
the price value that i just clicked on so that's Â
a really cool feature in pine you can also do thisÂ
with time inputs so if i quickly show you a time Â
input input dot time and i forgot to mention ifÂ
you press control space after you write input Â
here is a list of all the inputÂ
functions we have to work with Â
i'm not going to cover all of them because that'sÂ
why the other video is 40 minutes long in the Â
main transcript basics course on my websiteÂ
but i will quickly show you how to use a time Â
input the same way we just uh used the priceÂ
input so let's just set the default value to zero Â
and set confirm equals true and watch what happensÂ
now if i get rid of the confirm equals true in our Â
price input and i save my code and i remove theÂ
script and add it back to my chart now i have Â
to select the time input for this variable andÂ
we now have a vertical line tracking my mouse Â
which is showing the time that i'm hovering overÂ
this is perfect for something like an atr trailing Â
stop there is a video on my youtube channel ifÂ
you search my channel for atr trailing stop i did Â
release a video lesson explaining how to create anÂ
atr based training stop where you use this type of Â
input to select where to begin trailing from andÂ
once you select the bar the script begins trailing Â
below price action until price comes down andÂ
hits it so that's a really cool input there Â
now i think i'll wrap this lesson up here to keepÂ
it short hopefully you get the idea by now anyway Â
that will do it for this particular part of theÂ
basics lesson video here on youtube if you want Â
to go into more detail about some of these otherÂ
parameters or some of the inputs i haven't covered Â
here make sure to go to pine scriptmastery.comÂ
and sign up for the basics course it's completely Â
free but there is a lot more informationÂ
there there's at least a couple of hours Â
of extra content anyway with that said i will seeÂ
you in the next lesson coming up right about now
hi traders in this lesson i'm going to be showingÂ
you the fundamental concepts that you need to know Â
regarding alerts in pine script so there areÂ
two ways to trigger alerts in pine script both Â
ways depend on boolean triggers so true or falseÂ
triggers if the trigger is true an alert is fired Â
if it is false no alert is triggeredÂ
so for today's example we're going to Â
keep it extremely simple i will cover practicalÂ
alerts for things like setup detection indicator Â
conditions that sort of thing in future lessonsÂ
for now i'm just going to give you an overview Â
of the basic functionality of alerts so to doÂ
that we're going to create a really simple uh Â
alert condition for this lesson we're going toÂ
detect higher closers and lower closers so hc Â
is going to stand for higher close and that'sÂ
just going to check does the current bar close Â
higher than the previous bar's high and thenÂ
lower close is the same but the opposite Â
does the current bar close lower thanÂ
the previous low and this is the first Â
time you're seeing the greater than and less thanÂ
operators in a future lesson in the next section Â
we'll cover all of the different math operatorsÂ
and pine script operators we have to work with Â
don't worry about that for now basically todayÂ
we're just dealing with two boolean variables Â
high close lower close if the current bar closesÂ
higher than the previous high higher close is set Â
to true otherwise it's set to false and the sameÂ
for lower close but the opposite it needs to close Â
lower than the previous bar's low and so now weÂ
have two different ways we can trigger alerts Â
with these variables the first way is to use theÂ
alert function the second way is to use the alert Â
condition function and i'll go over theÂ
differences now so first of all let's use Â
the alert function the way this works is an alertÂ
function triggers an alert as soon as it is called Â
so for example if we check if hc is equal to trueÂ
fire our alert and this alert function takes two Â
parameters message which is a string and frequencyÂ
which is an inbuilt variable or built-in variable Â
so we have three options here once per bar onceÂ
per bar close and both of these options basically Â
so if we set this to once per bar close thisÂ
alert will only fire if the current bar closes Â
as a higher close bar and the message can beÂ
anything so we could make our string anything Â
i'm going to say here that this bar closedÂ
higher than previous bar and then i'm going Â
to add a colon on the end and then i'm going toÂ
add on the current closing price of the bar to our Â
alert so to do that we need to use the tostringÂ
function because you cannot add a number directly Â
to a string and we need to use the str name spaceÂ
here we'll go over namespaces in a future lesson Â
but we need to say str.2 string and then passÂ
in our number and this will convert the current Â
closing price into text into a string and so whenÂ
we get a higher close bar that closes so our alert Â
frequency is set to once per bar close if we get aÂ
higher close bar an alert will be fired with this Â
text so that's one way we can triggerÂ
alerts it's quite simple really and now Â
you don't need to specify these parametersÂ
here the function will assume that the first Â
parameter you give it is a string so we could getÂ
rid of message equals i mean it will also assume Â
that the next parameter will be a alert frequencyÂ
so we can get rid of that so we have our alert Â
function triggering with a string argument andÂ
a frequency argument only on high close bars we Â
could do the same for if lower close i could copyÂ
this string paste it in there change that to lower Â
and now we've got an alert firing on aÂ
lower close candle and just to demonstrate Â
that we can do it let's change this to frequencyÂ
once per bar so this will not wait for the bar to Â
be confirmed it won't wait for the bar to closeÂ
so that's one way to fire alerts and it's my Â
preferred way to trigger alerts in my scripts butÂ
there is also another option here and that is the Â
alert condition function so this alert conditionÂ
function cannot be placed in an if statement Â
it needs to be in your main script scope so itÂ
can't be in an if statement it needs to be in Â
your main scripts sort of body of text so it needsÂ
to be checked on every single bar on your chart Â
and this function takes three parameters insteadÂ
of two the first is the condition the boolean Â
condition to trigger the function so in this caseÂ
if we wanted to trigger an alert for higher closes Â
we would pass in h c comma that's our conditionÂ
if hc is true then the alert will fire and then Â
we have our title so here i'm going to say umÂ
hire close alert and then we have our message Â
so for this i'm just going to say the same thingÂ
here this bar closed higher than the previous bar Â
let's save the script and make sure thatÂ
compiles and there we go no problems there Â
now how this will work is on our real-time bar onÂ
the current bar in our chart this alert condition Â
function will check is hc true if it is thenÂ
fire an alert with the title higher close alert Â
and the message this bar closed higher thanÂ
the previous bar now there are a couple of Â
differences between these functions the firstÂ
important one is that we cannot just add on our Â
closing price as a string here the same way we canÂ
with this alert function if i save this script now Â
we will get an error cannot call alert conditionÂ
with argument message equals and then our series Â
string so a series string just means a stringÂ
that can change based on certain conditions so Â
the closing price can obviously change at any timeÂ
the alert condition function does not accept any Â
parameter that can change at any time it needsÂ
a constant string meaning a string that never Â
changes such as this right here the onlyÂ
exception with this is that we can use placeholder Â
tags so if i come up to the alert button here andÂ
click on that and i scroll down to the bottom here Â
you can see this text here you can use specialÂ
placeholders such as close time plot zero etc Â
if you click on this little question mark buttonÂ
here you can see all of the different placeholders Â
we can use in our alerts and there are quite aÂ
few of them when we are using the alert condition Â
function the placeholder tags are the only wayÂ
to put in variables that change so for example Â
if we wanted to put in the closing price we wouldÂ
need to do two curly brackets and then right close Â
and then to close curly brackets this placeholderÂ
would be replaced by trading view when the alert Â
fires with the current closing price so now ifÂ
i save the script and we come up to the alert Â
button and i select our script alerts if i clickÂ
on this little drop down box here you'll see Â
that we have our any alert function call as anÂ
option that is this function here so we could Â
set up an alert so that either of these get firedÂ
or we can select our higher close alert which is Â
our alert condition so if i click on that andÂ
i say once per bar and turn off my web hook Â
uh we'll cover web hooks in a futureÂ
lesson don't worry about them for now Â
but if i just set now an alert as thisÂ
is right now i've set it to once per bar Â
because the current bar's price is greater thanÂ
the previous bar's high this alert should fire Â
immediately so let me click create we'll wait forÂ
price action to move as soon as price action moves Â
there we go our alert is fired so you can seeÂ
when i hover over that alert it says this bar Â
closed higher than the previous bar and then itÂ
has the closing price so our little placeholder Â
here was replaced with the closing price youÂ
could also put in the ticker if you wanted to Â
so now if i save the script and set a newÂ
alert and select hire close alert and click Â
create now we have a new alert that fired and youÂ
can see that it now says the market the ticker id Â
of the market that fired this alert so that's howÂ
you pass in dynamic information into your alert Â
condition functions the alert function on theÂ
other hand is a lot easier to pass in information Â
so this particular function is definitely theÂ
preferred method for dealing with third-party apis Â
for example for trade automation using tradingviewÂ
alerts you would be better off using this Â
alert function if you can this alert condition onÂ
the other hand is great for manual alerts because Â
you can give each alert a title so for exampleÂ
i could copy this paste it down here change Â
this to lower close and change the condition toÂ
our lower close variable change that to lower Â
so here's our lower close alert and then let'sÂ
say we want to merge both of these so we want to Â
say if we have a higher close or we have a lowerÂ
close then we have a hclc alert and then we could Â
just say this bar closed higher or lower than theÂ
previous bar now if i save the script and we come Â
up to the alerts dialog and select our scriptÂ
when i click on this drop down box we have three Â
different alerts to choose from here we have aÂ
higher close level close alert high close alert Â
and lower close alert with their own titles soÂ
this is really useful for setting manual alerts Â
in your scripts say you have a script thatÂ
is designed to help traders trade your script Â
manually and you want to detect things likeÂ
a certain candlestick patterns or certain Â
indicator conditions that sort of thing this isÂ
a great way to separate your alerts with a title Â
to make it more intuitive for the user whereasÂ
this any alert function call will literally fire Â
for any alert function call that we put in ourÂ
script now if i were to create this alert nothing Â
would happen because i've set my alert frequencyÂ
to once per bar closed so we would have to wait Â
for the bar to close higher than the previousÂ
bar for this to fire let me get rid of this Â
close out of our alert frequency so this shouldÂ
now fire immediately as soon as i set an alert Â
on this any alert function call so let meÂ
first click show pop-up and then click create Â
we'll see what happens there we go an alert justÂ
fired on euro dollar it fired based on the any Â
alert function call condition and we get our textÂ
here that we wrote out here so this bar closed Â
higher than the previous bar and then we haveÂ
our bar price our closing price so for example Â
let's say we wanted to pass the current rsi valueÂ
to our alert as well we could replace um this bar Â
close higher than the previous bar and then setÂ
the rsi value in there so now it will tell us Â
the current rsi value when we set our alert so letÂ
me select alerts leave that as it is click create Â
there we have it now you can see our rsi value nowÂ
there's a lot of decimal places here um i'll show Â
you in a future lesson how you can truncateÂ
or cut excess decimal places off your alerts Â
but for now that's not important you can seeÂ
the the current rsi value over the 14 period Â
is 68.62 or 63 if we round it up and that'sÂ
really all you need to know for alerts we Â
have these two methods for setting alerts bothÂ
have their pros and cons the pros for the alert Â
function is that we can easily pass in values soÂ
price values indicator values third-party syntax Â
for sending your alerts to a service thatÂ
automates your trades based on your alerts Â
if you're using a service like that they willÂ
require a certain syntax for your alerts so for Â
example you might need to say um set my stop lossÂ
to and then in here you could set tostring your Â
stop loss price and then you might need to put inÂ
a comma take profit equals and then put in your Â
take profit price etc and then you could sendÂ
this information to a third-party api using a Â
web hook using this so for example i've beenÂ
using pine connector recently to automate Â
some of my trading strategy scripts if i sendÂ
the right syntax in an alert message to this Â
url using the trainingview alert functionalityÂ
pi connector will automatically manage my trades Â
for me based on the commands i give it in myÂ
alert message and i can pass in my stop-loss price Â
breakeven distance trailing stops limit orderÂ
entry prices all that sort of thing just using Â
this technique that you see right here so that'llÂ
do it for this particular lesson on alerts this Â
is the basic core functionality of alerts we'llÂ
cover more detailed practical applications of this Â
information in future lessons especially when weÂ
get into setup detection and indicator conditions Â
that sort of thing so i hope you found this lessonÂ
interesting and i'll see you in the next one
hi traders welcome back to another lesson in thisÂ
lesson we're going to be breaking down the plot Â
function and i'll be demonstrating how you canÂ
use it to plot data onto your chart so the plot Â
function is used to plot numbers onto the chartÂ
and numbers only we can't plot any other data type Â
other than numbers using this particular functionÂ
so here we are just plotting the closing price Â
onto our little indicator box here if i changeÂ
this to anything else let's try and plot a boolean Â
plot true i'll save the script we'll get an errorÂ
cannot call plot with argument an argument of bull Â
type was used but a series float type was expectedÂ
so we can only plot numbers let's try a string Â
text save error cannot call plot with argumentÂ
text an argument of string was used but float is Â
expected so we cannot plot any data type otherÂ
than numbers using this function to plot other Â
data types we need to use other types of functionsÂ
but the plot function is still extremely useful Â
for plotting things obviously like indicatorÂ
values and so on and so for this particular lesson Â
i'm just going to plot the closing price i'mÂ
going to walk you through the various parameters Â
that this plot function takes that we can use toÂ
manipulate its output so the first thing it takes Â
is a series and this could be anything it couldÂ
be a price value open high low close it could be Â
an indicator value it could just be a number thatÂ
we want to plot so here we can plot the number one Â
across our chart we can also title the functionÂ
so i'm going to call this our plot save the script Â
and now if i open up the settings menu by clickingÂ
on this little cog icon here on the style tab you Â
can see that our plot now has a title if we don'tÂ
title our plot then it would just be called plot Â
so the purpose of titling your plots is to makeÂ
it easy for your user the users of your script Â
to know what your plot does and maybe they wantÂ
to turn it off or change its color or its style Â
the next parameter we have to work with with ourÂ
plot function is the color parameter so you can Â
set the color to anything you want by defaultÂ
it's usually blue but you can set this to any Â
inbuilt color or custom color that you want soÂ
for now let's set it to purple save the script Â
and we have a purple line the next parameterÂ
this plot function takes is line width so this Â
ranges from one to five i believe so by defaultÂ
it's one which is the thinnest line you can plot Â
if we set it to five it becomes very thick like soÂ
one valuable use case for this line width function Â
is when plotting things like a moving averageÂ
maybe you want your longer term moving average Â
to be thicker than your shorter term movingÂ
average for example i created a script here called Â
multiple moving averages if i add that to my chartÂ
and we zoom out if i turn on all of the moving Â
averages you can see that they range from thin toÂ
very thick at the bottom here based on the length Â
of the look back period for that moving averageÂ
so that's one useful practical use case for this Â
line width parameter the next parameter we have isÂ
style so this is the style of the data that we're Â
plotting to change the style you just type in plotÂ
dot and then control space and any of these style Â
built-in variables will dictate what your dataÂ
looks like so you can set it to circles save the Â
script now we're plotting um actual circlesÂ
under the chart you could set it to an area Â
for example it's hard to see the peaks and valleysÂ
of this area because price action is so tight on Â
this time frame if we go out to the weekly we canÂ
see a little bit more of that we could also plot Â
columns if we wanted to so if i set this toÂ
columns and save the script now we're plotting Â
price as a column so this is obviously mostÂ
useful for something like plotting volume so if Â
we change the plot to volume now we're plottingÂ
volume as a column let's change this back to Â
a simple line and i'll change our plot back toÂ
the closing price as well now the next parameter Â
we have to work with with our plot function is theÂ
track price parameter so track price is a boolean Â
parameter true or false it's false by defaultÂ
so it's turned off by default but if you want to Â
turn it on you just set this to true and what thisÂ
will do is just plot a horizontal line across our Â
chart like you see there which is tracking theÂ
current price of our plot so if i go down to a one Â
minute time frame you'll notice this line movingÂ
around as price action moves and it's literally Â
just tracking the price the current price ofÂ
this plot the next parameter we can use in this Â
function is the hist base parameter so hist baseÂ
is short for histogram base and this is the base Â
price of histograms columns and let me open up theÂ
plot documentation so it says here that hist base Â
is the price value used as the reference levelÂ
when rendering plot with histograms columns or Â
areas so if i drop out to the four hour chartÂ
and we change our hist base to let's say 117. Â
if i set it to 1.17 and i set my style to styleÂ
columns and save the script our hist base is now Â
1.17 and so any value that prints above 1.17 willÂ
be a column that prints in the upper half and any Â
value that prints below 1.17 will be in the lowerÂ
half so that's the purpose of hist base you might Â
have seen this style of plotting in somethingÂ
like a macd and it works on columns as we just Â
saw it works on areas as well so there's an areaÂ
with the hist base applied and it also works with Â
histograms so if i save the script we get theÂ
same sort of effect now let me change this back to Â
a simple line and get rid of our track price andÂ
hist base and we'll go over some of these other Â
parameters that we have to work with so theÂ
next parameter we have to work with is offset Â
now offset does exactly what it sounds likeÂ
it offsets the plot so if we want to shift Â
this plot 10 bars to the right you would setÂ
offset to 10 and now watch when i save the script Â
our line here will shift over 10 bars to the rightÂ
here so if you want to shift to the left you would Â
use negative 10 if you want to shift to the rightÂ
you use a positive number so let's shift this line Â
10 bars to the right let me save this scriptÂ
and now you can see that the plot is plotting Â
with an offset of 10 bars so the current value isÂ
being plotted 10 bars to the right if we wanted Â
to plot this line 10 bars back you would just addÂ
a negative sign in front of that offset parameter Â
and now the line is drawing 10 bars back now thereÂ
are a handful of reasons why you would want to Â
use this offset parameter in your plots we'reÂ
not going to cover them all in today's lesson Â
but we will in future lessons when we get intoÂ
more practical use cases of these parameters in Â
actual indicator and strategy scripts so nowÂ
let's get rid of this offset for a moment and Â
look at the last few remaining parametersÂ
the next one is join and the join parameter Â
is a true or false variable and it basicallyÂ
just adds a joining line between our plots now Â
when you're plotting a line like we are here youÂ
don't need to use this parameter it's useless but Â
if we were using something like let's try a styleÂ
cross save the script zoom in a little bit you Â
can see these crosses have gaps in between themÂ
we're plotting the closing price so it's jumping Â
up here as this big green bullish bar printedÂ
the cross jumped up here if we set join to true Â
and save the script now we have a line connectingÂ
all of our shapes so any shape that has a gap Â
between it you can draw a line between themÂ
using the join parameter and setting it to true Â
the next parameter we can work with is editableÂ
so by default all of our plots are editable but if Â
you want to stop the user from changing your plotÂ
for whatever reason personally i've never used Â
this parameter but maybe there's a reason why youÂ
might want to prevent users from editing a certain Â
plot in your script you can set this to falseÂ
so by default this is always true but if we set Â
it to false watch what happens before i say theÂ
script we'll open up the settings menu and here's Â
our plot here if i save this script wait for itÂ
to update and then open the settings menu again Â
you'll notice that our plot style settings areÂ
gone we can no longer change the style of this Â
purple plot again i don't know why you would wantÂ
to limit the customization of your script by your Â
users but the option is there if you need toÂ
now the next parameter we can work with is show Â
underscore last and show last basically justÂ
tells the script um how many plots to display Â
on the chart so if we set show underscore last toÂ
10 for example we will only show the last 10 plots Â
onto our chart so let's save the script and nowÂ
you can see we only have 10 plots drawing onto the Â
chart so you won't need to use this often i neverÂ
have but it could be useful in certain scripts Â
where you don't want to show historical analysisÂ
you only want to show the most recent analysis Â
onto your chart for example maybe you wantÂ
to reduce clutter from your chart if you're Â
drawing something like support and resistanceÂ
levels for example maybe you don't want your Â
chart covered in lines that were drawn hundredsÂ
of bars ago you just want to show the last handful Â
and now the final parameter we have to work withÂ
when it comes to plotting data to our chart is Â
the display parameter the display parameter justÂ
basically turns on or off the drawing of your plot Â
so by default it's obviously enabled but if youÂ
want to you can hard code your plot to set it to Â
display.none and then the plot will not draw ontoÂ
your chart this is great for debugging so maybe Â
you have some functionality in your script thatÂ
you want to be able to check visually what it's Â
doing from time to time but you don't actuallyÂ
want that information drawing onto the chart all Â
of the time you can set display.none in your plotÂ
parameter and then in order to actually see this Â
drawn to the chart you need to come up to theÂ
settings menu and turn it on here by clicking Â
on this little checkbox now when you set thisÂ
to display.none it does stop drawing the actual Â
indicator value as you can see here we don't getÂ
our value plotting so this essentially just turns Â
the plot off completely but let's say that youÂ
don't want the data actually plotting onto your Â
chart but you still want to see the number theÂ
best way to achieve this is using transparency Â
now we'll cover the color functionality inÂ
pan script in a future lesson we won't go Â
into detail in this lesson but just really quicklyÂ
to show you how it's possible to set a plot to be Â
transparent you can use the color.new function soÂ
here i'm creating a new color i'm using the color Â
dot new and then passing in the purple colorÂ
if i add a comma on the end here and type in Â
100 and then close off this parentheses we openedÂ
here we're now creating a new color of the color Â
purple with 100 transparency and now if i saveÂ
the script you'll see our plots disappear but the Â
value is still plotting on the indicator statusÂ
bar so this is another great debugging tool Â
or a way to plot something like the atr forÂ
example maybe you want to plot the atr in your Â
script but you don't want the atr actually drawingÂ
over the top of price action this is how you could Â
go about doing that and that brings us to theÂ
end of this lesson i'll see you in the next one
let's have a look at one of the most simpleÂ
technical analysis conditions we can check for Â
in pine script which is moving average crosses nowÂ
this is not a trading lesson i do not encourage Â
you to trade moving average crossovers and crossÂ
hunters they may be profitable with the right Â
rules the right set of rules and entry reasons etcÂ
i personally don't trade them but for the purposes Â
of this lesson they are a great example of howÂ
easy it is to detect certain market conditions in Â
pine script so to get started we of course needÂ
two moving averages in order to detect a cross Â
so let's get some mas and again just todayÂ
because it's my favorite moving average i'm Â
going to use an ema an exponential moving averageÂ
but you can use any moving average type you like Â
i'm going to set ema 1 to ta.ema and we'll baseÂ
it on the closing price as always and this one Â
will have a length of 50. and then the secondÂ
ema will have a length of 100. so now before we Â
proceed let's draw the mas onto our chart and iÂ
will style the first one with the color of color Â
green and the second one can be red so let's saveÂ
the code make sure that this is working fine there Â
we go two moving averages on our chart now let'sÂ
detect our crosses our crossovers and cross unders Â
so we'll create two variables here two newÂ
variables called ma cross over and may cross Â
under now for our crossover and cross underÂ
we're going to use the inbuilt function t a Â
dot and then if i start writing cross here we haveÂ
our various options now cross will detect either a Â
crossover or a cross under for today we're goingÂ
to separate these two into their own variables Â
and so for crossover i'm going to use crossoverÂ
obviously and for cross under we'll use ta.cross Â
under and now these functions take twoÂ
parameters two values that need to cross Â
these could be any values they don't need toÂ
be moving average values they could be anything Â
macd lines for example um or the rsi crossing overÂ
a certain threshold for today we're just going Â
to put in ema1 and ema2 if i copy that into ourÂ
second function here we are now detecting our m8Â Â
crosses and at the bottom of our script i'm goingÂ
to draw crosses and here i'm going to set bg color Â
to ma cross over question mark if the movingÂ
average has crossed over the other moving Â
average if ema1 is crossed over ema2 i'll set theÂ
background color to color.green otherwise i'll do Â
nothing with the background color set it to n aÂ
i can copy this line of code paste it underneath Â
i'll change this to cross under and we'll changeÂ
the color to red and now if i save my script Â
we'll be getting the background color of ourÂ
chart changing based on which cross happened Â
so click save and that will do it for this lessonÂ
very simple one here just again introducing you Â
to the ta namespace and combining some of theÂ
things we've learned so far to create practical Â
uh indicators that can be actually useful in ourÂ
trading anyway i'll leave this one here and i'll Â
speak with you in the next lesson the source codeÂ
will be below if you want to play around with this
hello my friend well done you made it to the veryÂ
end of this very long video congratulations you Â
are one of the few traders who actually commitÂ
to learning this stuff obviously i have access Â
to the metrics and analytics of my videos in bothÂ
youtube and on my course website and you would be Â
surprised how few traders actually commit andÂ
make it to the end most give up halfway through Â
so well done for making it this far you should nowÂ
be able to go out and start playing around with Â
pine script and start writing your own scriptsÂ
but if you do run into trouble or you want Â
further guidance make sure to check out my masteryÂ
course i recently re-recorded all of the content Â
for pine script version 5. so this is the new andÂ
improved version i've stepped up the content a lot Â
and the new course has over 140 lessons andÂ
counting i haven't even started recording the Â
strategy section yet i'm about to start doing thatÂ
this week so if you found this free basics course Â
interesting i think you will love the masteryÂ
course we have a lot of great reviews here from Â
traders who have gone through the courseÂ
you can come and read these here if you're Â
not convinced that it's worth your time andÂ
money there is a lot of content here from Â
obviously the basics which we just covered to umÂ
some of the more intermediate things like how to Â
analyze price how to detect candlestick patternsÂ
how to use all of the various inbuilt functions Â
and variables as well as the inbuilt indicatorsÂ
i've got a lot of material on indicators here then Â
we go into information about accessing other timeÂ
frames and markets using the security function Â
we cover arrays this is still inÂ
progress this material here arrays Â
are quite an advanced subject as far as pineÂ
script is concerned we cover libraries and Â
soon i will be expanding into strategy scriptsÂ
and even automation how to automate your pine Â
scripts through third-party apis so if thisÂ
sounds like something you'd be interested in Â
head over to my website pine scriptmastery.comÂ
i have another course here as well where i share Â
the source code to all of my published indicatorsÂ
and strategy scripts including a bunch of private Â
scripts that i've never actually released andÂ
the source code to my really popular ultimate Â
pullback indicator which is the most advancedÂ
and sophisticated profitable trading script i've Â
ever written but anyway i'll leave it hereÂ
thanks for watching the video again if you Â
liked this content make sure to hit the subscribeÂ
button because i will be back soon with more free Â
pan script material if you're not yet ready toÂ
commit to learning more about pine script and Â
signing up to the mastery course at least hitÂ
the subscribe button because i definitely will Â
be back soon with more free content with all ofÂ
that said well done getting to the end good luck Â
with your trading i hope you kill it out there inÂ
the markets i hope pinescript helps you to enhance Â
your edge and take your trading to that next levelÂ
and i'll leave you here have a great day or night Â
wherever you are in the world whatever time it isÂ
and i'll speak with you in the next video goodbye
[Music]
[Music]Â Â
you
PineConnector TradingView Automation MetaTrader 4 Setup Guide
what's up Traders I'm Kevin Hart and in today's video I'm going to be showing you how to install Pine connecto...
-
9XVmTMv2TOE so hello there and welcome to another tutorial my name is Tammy Bakshi and today we're going to be go...
-
cf24R12l0uw [Music] so well there and welcome to another tutorial my name is Tammy Bakshi and this time we're goi...
-
5I8rLVvcbok hey guys welcome back to another lesson in this lesson i'm going to be covering a popular request whi...