Showing posts with label back. Show all posts
Showing posts with label back. Show all posts

Sunday, 20 October 2024

PineConnector Template for AUTOMATING Pine Script

hi Traders welcome back today we are going to be doing more Pine connector material in the previous video I did a simple script template for automating your Pine script strategies through Pine connector using trading view alerts in today's video we are going to be dramatically or significantly expanding on that previous script to create a very Advanced template script that will allow you to automate pretty much 99% of most systems out there all you need to do is replace my strategy code with yours and the rest of the script should work mostly out of the box now for those of you who are not familiar with what Pine connector is make sure to go and watch the previous videos in this series it's basically a metatrader Plugin or expert advisor that allows us to automate our trading view scripts using trading view alerts directly from our pinescript code so it adds full automation functionality for um mostly Forex Traders but if your broker allows you to trade other markets you can automate those markets so crypto CF C fds Commodities some Brokers offer cfds on stocks that sort of thing if your broker offers the market through your metatrader platform then you can automate it through trading view scripts so this video is going to significantly ramp up the complexity of the previous videos so if you haven't watched them make sure to go back and watch them to get Pine connector all set up properly otherwise you're going to get lost in this video with all that out of the way let's get started so here is the source code this will be available on my website check out the uh pinned comment below so we're just dealing with a very simple strategy here it's not a particularly Advanced system all it does is buy and sell overbought and oversold um conditions so the RSI 14 period RSI is overbought it will buy bullish candles if it's oversold it will short bearish candles today's lesson is not a trading strategy lesson it's purely a pine connected template um so the whole idea here is that you rip out my strategy code this bit of code here these three lines of code you change these to your systems entry criteria and then with some minor adjustments elsewhere in the code you should be able to adapt this code to work with any of your systems now there are some exceptions for certain systems but I will get to that throughout the video let's get started with breaking down the user inputs so this script comes with a bunch of strategy settings for my sort of simple template strategy we have a stoploss distance this is in Pips if ATR multiplier is set to zero so if ATR multiplier is zero then stop-loss distance Is pips based it's a fixed pip stop-loss distance now if I set this to one that will override our stoploss distance in Pips and we will be using a average true range multiplier um for our stop loss so if I set this to one then we will have a 1 ATR distance from our entry the closing price of our signal candle down to our stop loss for a long trade or up to our stop loss for a short trade we can also so change this setting here to high low and then the stop loss will be calculated from the candles high or low so those are our stop- loss settings the next few settings here are our profit risk reward profile so if this is set to one then we have a one: one risk reward from our entry so we'll have if we have a 10 pip uh stop loss then we'll have a 10 pip Target Break Even is exactly the same except this is for triggering our break even stop- loss so if I set this to one and this to two then if price hits a 1: one target from our entry our stop loss will be moved to break even and then finally we have our trailing stop distance this is the same as these two but for our trailing stop so for example if we set this to 5 to1 now we have a 5x Target from our entry so if we have 10 pip stop loss we have a 50 pip Target uh but that's obviously not going to get hit very often so maybe we want to move our stop loss to break even at 1:1 so now our stop loss will be moved to break even when price moves 1 to one in our favor and then finally if we want to start trailing our stop loss we could set this to 2: one and it's going to be hard to find a trade that actually triggers these conditions but I'm sure we'll find one I see one here here we had a trade enter nearly got stopped out then our break even Target was hit our stop loss moved up to break even and then our trailing stop Target was hit and our stop loss began trailing to lock in profit had this trade continued in our favor this stop loss would have trailed upwards to lock in profit so those are our simple strategy settings um there were two more options here for exit reasons so if I turn exit on higher close on or off now the script will um let me find an example real quick um it'll be easier if I turn these settings off to find an example here we go this will do so if I have this setting setting turned on exit on higher close lower close and I'm in a long trade as soon as our Green Line gets hit that's our take profit if I'm using an exit reason here then we don't place a fixed Target instead the script will wait for price to touch this um Target and then when our exit uh condition is detected the script will exit our trade so in this case we're waiting for a lower close so this candle closed lower than this candle after our takeprofit was hit our profit trigger was hit and then we exit the trade on the next bars open after this lower close obviously for um short trades it's the opposite so for a short trade we would be looking for a higher close so in this case here we went short and then we had a higher close we exit on the next bars open and then here we have another exit reason I just wanted to show you guys how to use multiple exit reasons with pine connector these are purely for example purposes they're very simple exit reasons they can be effective on some systems I do use these sorts of exit reasons on some of my trading systems but you probably want to add some more complexity to these a little bit more sophistication you probably want to combine indicator conditions that sort of thing with your exit reason higher close lower close is a pretty good exit reason but opposite color bars not really you'd probably want to combine that with something like a um indicator overbought over sold condition again this is example purposes this is about the pinescript template not about the system itself um so yeah this will exit an open trade based on an opposite direction higher close or lower close this will exit the trade based on an opposite direction bar in general so if we're in a long trade and we print a red bar we exit and vice versa for a short trade so those are our system settings very simple system um but again you should be able to convert most training systems that are simple the more complicated a training system is the more difficult it's going to be to plug it into this template but personally all of my systems are very simple I can copy and paste probably all of my systems into this script and get it working um so for those of you with access to the Mastery course or my indicators and strategies course um feel free to play around with any of those scripts you should be able to copy and paste the majority of them um the entry conditions you should be able to replace this with the entry conditions from any my scripts and this script will work almost out of the box you will need to tweak a few things here and there for certain strategies but should be pretty simple so that's it for our system let's go over the pine connector settings this is this is the uh point of today's lesson all of these settings below this label here so if you watch the previous lesson on my simple template you'll recognize most of these settings but there are a bunch of new ones that I've added to make this Advanced template uh useful for most Traders this should cover 90% of requirements for Pine connector if this is off and you set up your alerts then they will not be sent to Pine connector so uh but this is on by default the next setting is obviously very important that's our Pine connector license ID if we don't have the correct ID then our order will not be routed to metatrader so make sure to put in the correct ID here then we have our risk per trade again I went over these settings in the previous videos this is BAS on your Pine connector expert advisor settings so if you've set pine connector up to use Lots then this would open one standard lot if you've set it up to use a percentage of your account balance then this would risk 1% of your account on the on any trade that is open by this script entry Pips is for our entry limit order so in the previous script we used Market orders in this script we can either use Market orders or we can use um limit orders so limit order will place in the case of a long trade let's say we get our awesome looking bullish candle here and this triggers our long trade um if we set this with this turned on our alert would send a limit order let's say this is the candle's um closing price the script would send a Buy limit order 0.1 Pips below that closing price over on metatrader so whatever the price is on metatrader if we had entry Pips set to 0.1 and this turned on when we um set up our alert then we would place a buy limit order 0.1 Pips below the signals confirmed closing price if you want to just use Market orders to enter your orders immediately then leave this setting off and then this setting here is ignored spread filter is another pine connector setting this will only execute trades if the current market spread on your broker is below this pier amount um I personally leave this on in most of my scripts just to prevent my um my system from taking trades during some sort of Market Calamity like if if the spread is greater than about three Pips on my broker that I use um then something's gone horribly wrong because my spread is usually around 0.1 Pips at least on the major pairs that I trade the next setting here is our break even offset so let me show you what this does if I set what do we want here we want this I'll set this to 5:1 and my break even to 1:1 let's find an example yeah this one will do when my break even um price is hit what happens here when this order is sent to uh Pine connector is this is our signal candle the RSI my settings are different here Al So currently for testing purposes I set my RSI period to three I was a bit confused there why this was a buy signal when the RSI wasn't oversold but let me just change this to be consistent with the script so let me explain what happens here what happens here is our script detects this green candle as our entry condition when this bar closes green while the RSI is oversold we have our long conditions met when this bar closes if I have alert set up then trading view will trigger my alert and the script will send the syntax to open a trade to Pine connector so with the settings I have here we would open a market order so at Market our stop loss would be down here and our break even price would be also included in our alert to Pine connector so when Pine connector receives our alert it would receive a command telling it that we want our stop loss to be moved to break even when price reaches this threshold so this is a 1: one distance from our entry to our stop loss here 1:1 now this is a p value when it's sent to Pine connector so if I measure out roughly from our entry up to the Blue Line This is what would get sent to Pine connector so if I bring the syntax over real quick for Break Even This syntax command be trigger automatically moves the stop loss of whatever position we tell it to manage when be trigger is satisfied so in this case my script would tell Pine connector set my be trigger to 1.3 we're on a 1 minute time frame here again for demonstration purposes I don't recommend trading this time frame not even with an automated script due to all kinds of reasons mostly slippage and commission costs um but anyway that's up to you this isn't trading advice uh make sure to read the disclaimer if you haven't already um this 1.3 pip Break Even trigger would be sent in this order so when this order is sent it would be be trigger equals 1.3 then Pine connected knows that when we enter our trade if price moves up 1.3 Pips then we want our stop loss to come up to break even so our break even functionality is handled completely by Pine connector the moment our trade is opened be trigger uh sorry be offset uh this setting here is how many Pips we want to offset our break even order so if I throw an array here um so actually I had to reset my settings here because my offset wasn't accurate but anyway let me start again with this example here's our entry price the open of this red candle so that's our entry price right there if I set Break Even offset to 0.1 now our break even price will be 0.1 Pips above our entry so the point of this is really just to cover the spread so if you set this to zero and price comes down and hits your break even um technically it's not really Break Even because you've got spread to account for and commissions to account for so um if you exit the trade at exact ly the same price you bought it at you're going to take a tiny loss because you're going to take the hit from the spread and the hit from the commission so for Traders who are sensitive to that maybe your system has a very thin Edge and you don't want those trading costs to infringe on your Edge or you just don't like um losing money on a break even trade uh then that's what this setting is for I wouldn't recommend setting it too much higher than the spread so just have a look at whatever your average spread is on your um whatever Market you're trading through your broker and if you want to then that's what I would set this to I would set it to whatever the spread usually is so that's all of these settings the next few settings here are use limit order we already went over that if this is off then we send a market order if it's on we use a limit order this many Pips from our entry price our signal price the candle that triggers our order use pip based entry is recommended to be on with uh Pine connector's documentation recommends using this setting and not not using this setting so so it recommends using Market orders to enter trades and pip based um stop- loss and takeprofit for your limit orders um that's because there is a slight difference a very slight inconsistency between trading views price data and metat Traders price data it shouldn't matter on most time frames but on the lower time frames it does matter a little bit and so to keep your script as consistent as possible with metatrader they recommend Pine connector recommend using pip based orders because that way no matter what price your trade is opened at over at metatrader your orders will be exactly the same distance as they are on trading view so that should mitigate any issues with price discrepancies or inconsistencies if you're not sure what I'm talking about go back and watch the previous couple of videos in this series where we went over that in detail so use pit based entry is for our entry limit orders so let me find our debug label here it is um if I turn use limit order on then our label here will change this is what gets sent to Pine connector we are sending a buy limit on Aussie Yen and our price value is 0.1 Pips from um in this particular uh case we are looking at this trade here as our debug trade um if I was using a by limit order with these settings then we would place our by limit order 0.1 Pips below um the trigger price if I turn this off now our script is sending a price value when this updates in a moment slow today there we go now we're sending a price value instead of Pips to Pine connector now you need to make sure that whatever you've set your script up here is consistent with whatever you've set pine connector settings to be uh so if you've set your Pine connector settings to use price values then you need to ensure that your script template here is also using price values but if you're using the recommended settings for Pine connector you would would want to leave this on you would want to set pine connector up to use pip based orders and then having these settings on will ensure that your stop loss is sent in Pips your take profit is sent in Pips and your entry limit orders are sent in Pips however if you have a reason why you want to use price values and it's up to you U personally I use price values in all of my Pine connector um automation scripts and I've never had any issues but that's probably because the broker I use has very very close price data to metatrader and trading view so um it's I haven't really run into any issues where one platform had a very significant different price to the other but if you have a broker that does some Brokers do have like as much as a whole pip or even a couple of Pips difference between the two platforms that is going to be a big problem if you're sending price orders to Pine connector so if that is the case you'll want to use these settings for me through pepperstone the broker I've been using for the past year or so I haven't had any issues with that anyway let's move on to the final optional settings here um I've included a metatrader symbol override for people who use my ultimate pullback indicator they have run into issues where some markets have totally different symbols to what they're trading on trading view so for most Forex pairs the symbol will be the same on both platforms but there might be a prefix or a suffix again if you if that sounds like gibberish to you go and watch the previous videos but on my broker for example o Yen when I'm sending an order it would need to look like this AUD do uh audjpy a if I don't put a on the end of my symbol then the order will not be sent to my broker or my broker will not accept the order so in this case I I would just add a on metatrader suffix and then any order that gets sent if I look at my label here my debug label you can see that my symbol now says audjpy do a if I wanted to override the symbol entirely I would put override um whatever text I want to override it to in there and now that's what gets sent to Pine connector so there's very very rare edge cases where this would be required so I just included that in the template why not most of the time you don't want to touch this 99.9% of the time you will not want to touch this unless you really know what you're doing and you're running into that issue where the symbols don't match at all on metatrader prefix is the same as suffix but it puts it be uh before wellow can't type before so now we'll get before before our symbol so uh yeah that's pretty self-explanatory um strategy ID is for running multiple strategies on the same Market same symbol so if I'm running a hedged account account or hedging account through my broker that allows me to open long and short trades at the same time or I'm running two systems that only trade in the same direction so if I'm um trading two long only systems one on a 5 minute chart and one on an hourly chart and I want both systems to run through the same account over on my broker through metatrader I can separate the systems using a strategy ID so if I type strategy one into this box now whenever my orders get sent for this particular setup so if I set an alert right now any alerts that are triggered by the script will include this comment and this comment is how we use multi strategies so multi strategy documentation here for Pine connector says um if you want to use multiple strategies you need to include a comment and all orders with the same comment will be handled um as if they're their own system so you can trade multiple systems on the one Pine connector ID through the same broker on the same Market um using this strategy setting this is obviously for advanced Traders only if you're not particularly Advanced with trading or experienced I'd stay away from this completely and just use one um script per symbol on your Pine connector setup uh for me personally I only run one script per symbol on my Pine connector as you might have noticed by now if you've been following me for any period of time I'm a simple Trader I prefer Simplicity over complexity any day of the week if I can make a system simple even if a particularly complex system would make me more money unless it's significantly more money then I prefer the simple system because Simplicity works it's easier to work with it's less headache there's less to go wrong there's less confusion when things do go wrong um but then again I do trade a lot of markets I trade um crypto stocks and Forex if you're only trading Forex then you may want to increase the complexity of your system setup through Pine connector um but I'll leave that with you guys this isn't a trading course right now this is just teaching you how to get P connector working through your trading view scripts in the future I do plan to expand the channel to cover more broad trading Concepts and techniques that I use but uh for now um that is not what we are talking about so that's it for the settings let's briefly go over the code because the code is a bit it's just a wall of text but it all it is pretty simple it looks more complicated than it is um again you can copy all of this code into a blank script replace your strategy settings with whatever settings you like to tweak replace the um if you just a quick tip if you press crlf and type for SL SL exclamation mark this will take you to the couple of um places where you need to replace your my code with your code so this is my entry criteria for long trades and short trades I'll change this back to 14 so here we need the RSI to be under 30 and we need a bullish candle and we can't have any open trades currently so this system only takes one trade at a time it does not pyramid it does not trade in multiple directions it's just one direction at a time one trade at a time very simple entry criteria short trades are just the opposite direction you'd want to replace these conditions with your systems conditions and that's it if you want to use different exit reasons so these are my exit reasons here that we already went over then you would um add those settings up here add in your exit settings so here are my two onoff values for my exit reasons and then you would need to again come down here change these to whatever your exit inputs are and then if use exit reason is on the script will behave slightly differently based on those exit reasons and then of course you'll need to come down to where the exit reasons are also triggered so these are my exit criteria if I have higher close lower close turned on and we get a bar that closes below the previous Bar's low then we exit our trade if exit trade is triggered then Pine connector will send an alert to close any open long trades so again just really quickly if you want to change the script to work with your code change this code here to match your your entry criteria or conditions the indicators you want to use the price conditions Etc make sure to change your exit reason criteria if you're using exit reasons and that's pretty much it I mean unless you're using particularly obscure trailing stops that don't use an ATR trailing stop or or if you want to change the ATR trailing stop distance you might want to add some more inputs to this I try to keep this script as simple and stripped back as possible I could have added a lot more settings here we could have had a setting for for our ATR distance or period we could have had a uh setting for our RSI period and our overboard oversold settings but these weren't relevant to the script today so I didn't include those obviously if you're working on your own script you might want to add those user inputs uh but anyway let's just wrap up this video by going over the important stuff here so you shouldn't need to touch any of this with your scripts this just prepares some um constant variables so it prepares things like our symbol that we send to Pine connector it just sort of helps us build our string this is our text string that gets sent to Pine connector this is all handled here um and we just pass in the relevant parameters so this function here PC alert entry and in fact let me rename this I'll rename this to PC entry alert to be more consistent with the styling of the script there we go so this function here is going to terrify some of you guys especially those of you who are new to pinescript don't worry about it you don't need to know what this does you can copy this into your script and it will just work it's a it's just a function that takes a few parameters and all it's doing is building a string so it's just adding all of the text up together in such a way that um Pine connector can read so it assembles this text alert in the correct syntax to be sent to pinec connector all we need to do is pass in a direction our price entry price if we're using a limit order our stop- loss value our take profit value our break even trigger value and this truncate here is purely for the label uh for some reason with trading view scripts if you're working with float numbers so decimal numbers it will add like an extra 10 decimal numbers after the decimal place um and so to make make this label easier to read I made sure to truncate or strip out the extra decimal places um so that we don't have so many numbers in our debug label but whatever is in this label will be sent to Pine connector now as far as I know Pine connector can accept as many decimal places as you send it but um if you are running into issues with having too many decimal places in your alerts for whatever reason just change this to true and that will make sure that the alert text that gets sent to Pine connector always only contains five decimal places that should fix any issues that you encounter on any markets out there there may be some very slight rounding errors on things like crypto that have a 100,000 Satoshi decimal places but it should be fine to do that if you run into any issues um I might even leave this on by default because I can't really think of any reason why rounding to five decimal places would break any scripts as far as I know there aren't many Market out there other than crypto that have more than five decimal places in their price quote and even if they do rounding the remaining six plus decimals shouldn't really affect anything significantly so I think I'll just leave this on by default but if you're having issues play around with this uh set it to false or true um or if you're having any issues with this uh just send an email to Pine connector support team and they should be able to walk you through a solution but I haven't encountered any issues with this um function I use this in all of my automated scripts so yeah that's it uh the next thing we do is we get our pip size so for Forex one pip is 10 points so so one pip is 10 points on stocks and other markets that's usually not the case usually one point is one pip so on Forex we want to set our pip size to 10 points on other markets it should be okay as one here is where we store all of our stops and targets Break Even prices this is mostly for drawing things onto the chart so in this case um drawing our stop-loss prices and break even prices Etc um when our alerts are sent to buy connector other than a trailing stop alert everything else is sent straight up when we um enter our trade so all of these variables here are mostly just for drawing the signals onto our chart so that we can see what's happening next up we calculate our stoploss distance so if we're using an ATR we take that into account if we're not using the ATR then we just use um our stop our stop loss distance settings here converted into Pips then we have our entry conditions we have this other custom function here which takes all of our trade parameters so our Trade Stop distance or Price our profit distance it takes all of that information our stop- loss our take profit our break even distance and and it uses this function that we just went over to build a string that gets sent through our alerts to Pine connector and that's what this code here does next we check if we have a long trade conditions met if we do have a long trade then we calculate all of our strategy parameters um build all of that together into into our string and that gets sent to Pine connector if Pine connector is enabled we also have our strategy code here if we're using a limit order then we need to use a bu limit in our strategy entry to match what gets sent to Pine connector otherwise we pass in na if this setting is turned off then we don't use a b limit order this will just enter at Market through the strategy tester short trade is obviously identical but the opposite direction then here I just update my entry price from the close of the signal candle so here for example when this bar closes and we open our trade on the next bar our stop loss and take profit is calculated from the signal CLE so once our sign signal is confirmed we calculate our stop loss and take profit but for things like a trailing stop and break even price we need to calculate that information based on where our trade was opened and so this bit of code here just makes sure that our entry price is consistent with what the strategy tester is working with um next up we have our long strategy management code this is for the strategy tester when our trade is opened I already went over this the break even trigger is sent in our alert to open the trade so we don't have to send any alerts to Pine connector that's all handled by Pine connector when our trade is opened but we still need to tell the trading view strategy tester that our trades at break even and we need to draw that information so that's why this code is here next up we have our trailing stop activation code so if I turn that on uh trailing stop distance let's set that to one and set this to zero now the line will turn orange when price touches this line that triggers our trailing stop to start locking in profit so that's what this parameter does if we have a trailing stop turned on and price exceeds that um activation price then we begin trailing our stop loss we'll get to that code in a moment but next up we check our exit reason code so this is the same basically as our trailing stop activation but it's for our profit price so again if I set profit let's turn trailing stop off and set our risk reward to 2:1 now when this green line is touched by Price the script will begin looking for our exit reasons so in this case that is a lower close which we get here and our trade exits at Market on this bars open and here if we are using a limit order and price exceeds our takeprofit price that means that if our trade has not yet been filled so let's say we've set our B limit order to 10 Pips for whatever reason I wouldn't recommend it you want this as close as possible to price um but if I set this to 10 Pips we got our entry signal and our buy order was placed down here and it was never touched by price so we never got filled on our long trade but price came up and touched our takeprofit then we want to cancel this pending limit order because now we're out of sync with our strategy tester code so that's what this does if our takeprofit is hit if our would be take profit is hit and we are using a limit order then we want to cancel that pending limit order um next up we have our confirmed bar code so when a bar is confirmed so the bar closes this is where we check for our exit reasons so if our exit criteria is met then we send an alert to Pine connector to close our long trade at market and we also close our strategy test to trade to be consistent with um the strategy tester and pine connector and then finally we have our long trailing stop code so if our trailing stop is activated and our new long stop loss is greater than our current stop- loss then we want to update our stop loss so if we're using a fixed stop loss up here so this is a fixed stop loss and this is turned off then we want to Trail our stop loss the same amount of distance from whatever we've Set uh this setting to so if we set it to close then on each bar that closes we would Trail our stop loss up in the case of a long trade by 5 Pips from the closing price if we set it to high or low then it would be 5 Pips from the low and if we're using an ATR traing stop then it will obviously be an ATR distance from the close or the low in the case of a long trade and then if Pine connector is enabled then we send an alert to Pine connector to update our stop loss to do that we use the new stop-loss take profit long command and we pass in our new stop loss and also a strategy if we're working with a strategy ID and then our short management code is identical to long but obviously in the opposite direction then we have our trigger stop-loss takeprofit orders in the strategy tester so this passes in our stop- loss price and our um takeprofit price if we're not using an exit reason so if I turn exit reason off this green line just becomes our takeprofit if I have an exit reason turned on then we don't want to place a take profit because out exit reason will trigger the exit at Market when it's detected so that's what this code here does and then finally we have our debug label which just shows what is going to be sent to Pine connector if a trade is detected so the next time a trade is detected um with the settings I've just set up we would send our Pine connector ID we would buy Aussie Yen at Market with a 5 pip stop loss and a 10 pip take profit with 1% of our account balance or one standard lot with a spread filter of three so if the if the spread is greater than three then the trade will not be placed we will not buy oen at Market so the spread filter is obviously most useful with Market orders if you're using limit orders to enter your trade it's not that big a deal if the spread is elevated because you won't be filled on your trade unless price exceeds your limit order price including the spread so the spread is useful for Market orders um but any anyway that's outside the scope of today's lesson hopefully if you're using pine connector you are experienced enough with trading to know what I'm talking about um finally we have all of our plots for drawing our orders and that's it that's the script it's a long video I apologize for that but there was a lot to cover here the source code will be on my website as mentioned at the start of the video check out the pin comment below in the video description if you want to learn more about pin script or get your hands on all of my personal systems and strategy IES go and check out our website pinescript mastery.com I'll speak with you in the next video take care best of luck with your trading I'm not sure what we'll do on the next video maybe we'll apply this template to an existing system that I've already published on YouTube um that might be a good way to wrap up this sort of tutorial series to demonstrate how you can copy all of this code into a blank script and Port over one of my existing systems to use this um template and with that said I'll leave this video here thanks for watching best of luck with your trading I love you guys make sure to subscribe if you haven't already and I'll speak to you soon goodbye

Pine Script [OUTDATED V4] Tutorial Lesson 9 How To Avoid Repainting!

hey traders welcome back to another pine script tutorial my name is matthew from zen and the art of trading and today i'm excited to ramp things up a notch and explain to you how to create a higher time frame indicator that references the previous day's high and low and doesn't repaint now that sounds like a mouthful to you that you just don't understand then I highly recommend you go back a few lessons maybe to the start if you're new to Pine script but what are we doing here well let's go out to the daily chart first of all and hide this indicator and let me draw in a couple of lines so first of all let me draw in the high of this day and the low of this previous day the script that I'm going to teach you how to code today will do just this it will draw the previous day's high and low over your intraday charts so now if we drop down or one hour chart you can see that the high of the day was this wick here and the low of the day was this wick here and everything that is happening today as at this bar here is within the context of this previous day's high and previous day's low so all of these bars this is basically all of today has been an inside bar meaning that the high and low of today's bar is contained within the high and low of the previous day's bar and so if we get a breakout today that'll create a new high new daily high and that's the purpose of creating the script I'm going to show you how to create today we can use this script to see how price action is performing within the bounds of the previous day's high and low but I'm gonna take this lesson one step further today and I'm going to show you how to achieve this without repainting to your chart so before I continue if I turn the script off this um today I'm going to recreate a script I made a while ago so if you type into the indicators box HTF you'll see here this indicated by a zen and the art of trading called higher timeframe high and low if you click on that this script does basically the same thing the difference is I haven't updated it yet let me change this to daily but this script repaints repainting is the arch-nemesis of all beginner pan script coders basically what this is doing is that on historical bars it's referencing the previous day's high which is what we want but on the current bar as it's moving as the price is changing our value is changing so if I hover my mouse over the current bar you can see that that's where these values change they diverge from the historical values the reason for that is that these historical values are referencing the previous day's high and this current value is referencing the current daily bars high because every time price action moves it recalculates the higher time frame values we don't want that not on this particular script and some scripts you may want that but on this particular script we do not want this what we want is this a clean line a clean value that shows us the previous day's high in context of the current price action so you can see here that price action is actually breaking through the previous day's high but if I turn on the repainting script our high is changing with price action so today I'm going to show you how to eliminate that I'm going to show you how to manipulate a higher time frame data to show the high and low of the previous day or week change this to week and it will show the previous week's high and low and so all of that and more in today's lesson let's get straight into the coding so first things first let's start with a blank slate I'm gonna create a new blank indicator script and I'm going to save it and call it lesson 9 and so here we have a blank script I'll get rid of some of this because it's unnecessary for today and now we have a clean blank script or blank canvas if you will so I'm going to rename this script lesson 9 you can call it whatever you want to and I'm going to set the overlay to true now as always I'd like to begin my scripts by getting the user input variables so I'm going to write a comment here saying get user input and the first input we're going to get is what time frame to reference so I'm going to call this res short for resolution I'm going to use the inbuilt input function it's going to have a title a settings title of time frame and it's going to be of type input dot control space to bring this box up resolution is what we're looking for so that's another word for timeframe the final variable we're going to put into this input function is the default value and today we're going to be using D so our default higher time frame reference is going to be the daily chart you can change this to whatever you like you could change it to W for weekly or even M for monthly but I'm going to leave mine is D for daily because that's what most intraday traders will be referencing that's the only input variable we need for this lesson so let's move on to the next line of code so the next thing we're going to do here is create our own custom function now this is going to be a little bit advanced so if you're new to pan script don't freak out this is gonna be a little bit difficult to understand but I'll do my best to explain it in a way that makes sense to both people who are proficient with programming and those who are new to this stuff a function is something like plug you can see this is an inbuilt Pyne script function created by the pine script development team and the tradingview developers but you can also create your own custom functions so say that there's a repetitive complex task you want to keep doing in your scripts that pine script doesn't provide an inbuilt function for well you can just create your own and today I'm going to show you exactly how to do that we're going to create our own security function that eliminates repainting and the first thing we need to do just like any variable in pine script we need to define what the variable is called so in this case I'm going to call it RP short for repaint underscore function so this is our repaint function or in should be called NRP non repainting function but I'll keep it RP for short because it's just easier to to write and this RP function unlike a typical variable which is assigned a value based on a inbuilt pan script function or operation this function actually requires input variables so the input variables were going to reference here is the symbol the current market we're trading and the res resolution the current time frame we're trading and also source so our open high/low or closed so now we've defined and our custom function and we've defined what inputs it takes now we need to assign it to an expression basically we need to tell pine script what this function does and the way we do that is using an equal sign just like when we're assigning a variable to a value but instead of just leaving the equal sign we're also going to put a right arrow on the end so this is saying the repaint function with these inputs is defined by this next line of code and so what we're going to reference here is we're going to reference the inbuilt security function so our custom function is going to return the inbuilt security function while taking our custom inputs into consideration and so the way we do that is will write underscore symbol underscore R as an underscore source and so now we can hit save and this will compile and it's still plotting the closing press but our function is created and right now this is just duplicating the security function it's returning exactly what this would do if we were to say if we were to use this inbuilt security function with the default values so I'm gonna leave this for now and we'll come back to it in a second first of all we're going to get our price data in this case it's higher time frame price data and what we want to get is the higher time frame high and the higher time frame low and so higher time frame high is going to be assigned to our custom repaint function and for the market the symbol is going to take our current symbol Aussie CAD so we're gonna write in sin in fur dot ticker or ticket ID sorry ticket ID so that's the ticket identification tag in this case AUD C ad it's going to take res which is this variable here we created so we can change our time frame value so by default it's going to take a daily time frame input and the source is going to be the high so the high time frame low is going to be exactly the same repaint that takes an input of symbol info ticker ID our custom resolution variable which is set to daily by default and it's going to reference the low source the source for this custom function input is going to be low so high and low high timeframe high high time frame low so now we can draw these values to our chart so let's overwrite this clothes value with a higher time frame high we're going to color it red and we're going to title at higher time frame high then we're also going to plot the high time frame low it's going to have a color of blue and it's going to be titled higher timeframe low if I hit save that should draw these values to our chart and there we go but notice it's repainting every time the current intraday bar changes its value so does the higher time frame high and low we don't want that we want to eliminate that so that this high previous day is high continues drawing until the current days bar closes so how do we do that let's come back up to our custom function this is why we created this custom repaint function now if we add on to the end of source two square brackets and the conditional statement then we can eliminate repainting altogether so our conditional statement is going to be if the bar state dot control space is real time question mark one otherwise zero what this is saying is if the current daily bar higher time frame bar is real time meaning it hasn't closed yet it's not a historical bar then we want to reference the previous day's source high low close open otherwise if this bar is not real time meaning it is a historical bar then we do want a reference that days high low and now you can see that repainting has gone away as the intraday bar changes its value the high and low is no longer changing with it and so we've just eliminated repainting we're drawing the previous day's high and low to our chart and if we go out to the daily chart we zoom right in as this daily chart bar is moving the high and low is not moving when this daily bar closes these lines will adjust for today's closing prices high and low and those lines will draw over tomorrow's intraday price action and so there we have our completed indicator it's not repainting it's drawing the high and low the previous day's the higher time frames bar and we can adjust this to what every one we can change this to one week and it will now draw the previous week's high and low and so if price action gets down here there's a good chance it could act as support and so that brings me to the end of today's lesson I hope that this was helpful to you hope that it made sense to you if not go back and watch the previous lessons that may make this lesson make more sense if you haven't watched them yet otherwise if you want to take your pants trip coding to the next level I've left a link in the description to my advanced pine script cost and I'm working on where I go into far more structured detail about all of these different functions of pine script and how they all come together to create a indicator or strategy script so if you're excited about buying scripts and you'd like to take your coding to the next level I highly encourage you to check that one out and I should quickly mention that anyone who signs up to my mailing list to be informed of when the Advanced Course releases will receive a 50% discount off the opening price so if you're interested in that head over now to my website the link is in the description and sign up to be notified about the course release otherwise I'll be back soon with their new free pine script tutorial where I think I'll probably cover time zones and I'll show you how to plot data within a particular time zone so thank you for watching guys if you have any questions leave them in the comment section below and I'll get back to you as soon as I can otherwise I'm excited to see you guys in the advance pilot script course or on my next free video so I'll speak to you then take it easy everyone goodbye [Music]

Pine Script [OUTDATED V4] Tutorial Lesson 8 Using The Security Function & Higher Timeframe Data

a traders welcome back to another pine script tutorial today's tutorial is going to focus on the security function in order to use higher time frame data so the example I'm going to use today is implementing a higher time frame EMA so what we're going to do is we're going to access the 50 day EMA on these intraday time frames so on this four hour chart when we're finished it will be plotting the 50 day EMA as opposed to the 50 standard EMA so let's get straight into this one it's going to be called less than 8 today because that's what we're up to the first thing we need to do is set the overlaid to true so that this will draw on to our charts the next thing we need to do is get some user input so the first input I'm going to get is the time frame what time frame do we want a reference so this is going to be called EMA time frame it's going to be a type of input dot resolution we're working with resolution here which is which means time time frame and the default value is going to be D for daily chart you could also set this to 1440 which is 1440 minutes 1440 minutes is one day otherwise just use D for short the next input is going to be the EMA length so MA length and a type of integer integer and the default value is going to be 50 typos everywhere today all right the next input is going to be whether or not to color this EMA now this will make more sense later but what basically what this is going to do is if price action is above the EMA the EMA will be colored green and if price action is below the EMA to be colored red this is just something I like to do with my indicators the ones that use emas so red obviously means I'm looking for short trades and green means I'm looking for long trades and so I'll show you how to do that in this tutorial today as well so this will be called color EMA and it'll be a type of input bool boolean and the default value is gonna be true last but not least is going to be our smoothing function now I'll explain this one later when we actually have the EMA plotting to the chart but this is going to also be a boolean input so input title equals smooth type whoops type is input bull and this one is going to be set to true as well I'll save that and we'll move on to the next bit of code which is going to be get actually getting the EMA value itself so I'll call this calculate EMA and we'll begin here by establishing an EI EMA variable so this EMA variable is going to be set to the inbuilt EMA function if you hover your mouse over this it'll tell you what you need to input in order to get a return value and this EMA function takes a source and a length source is high low close that sort of thing length is obviously the period length of the EMA so we want to calculate this EMA based on the closing price and it's going to be a length of Len of our variable we created here so a default of 50 the next thing we need to do is get the higher time frame EMA so we're going to basically plug this liner code into the security function in order to use this to calculate this EMA value based on the daily closing price or whatever time frame you set in your resolution input so we're going to get to email use here and this is gonna be a little bit complicated to explain but I'll do my best basically when you're calculating a higher time something like a higher time frame EMA you've got to remember that if I go down to a one-hour chart for example there's 24 one-hour bars in a day 24 one-hour bars make up one daily bar and so there's gaps between the star of this 24-hour period and the beginning of the next four-hour period there's gonna be gaps in price data on that higher time frame and so what we're going to do in order to compensate that is we're gonna have to EMI values one is going to compensate for that value and the other is not so basically one is going to be a smooth higher time frame EMA value and one is going to be a stepped higher time frame EMA value so this will make a lot more sense when this is drawing to the chart so let's just write the code first and then I'll come back to explaining what's happening so the first EMA value are going to get is the smooth EMA value and we're going to assign this one this variable to the security function and now I'll explain what goes into this one if you hover your mouse over the function name it will tell you what inputs it takes and it outputs whatever it needs to floating-point numbers like price price data integers boolean's color which I believe is candlestick color today we're going to be working with the float because we're going to be calculating an EMA value which is a float because it has decimal point numbers just like price action does because it is a an average of price action values the first input this thing takes this function takes is what's symbol do you want to calculate this data on so you can actually use this to reference other symbols so you could reference and we're on Ozzy CAD here Australian dollar versus Canadian dollar but you could reference the euro dollar or or a stock commodity whatever you feel like so I'm not going to go into detail about that in this tutorial this is just introducing you to the security function but in future tutorials I'll show you how to reference other markets today is market we're just going to reference the current symbol so we need to write in here sim info which is short for symbol info press control space and you get a list of of variables you can you can grab from this basically this this collection of instrument data and so out of this list we want ticket ID and this will give us the Australian cat AUD C ad and I believe it will also get it from the same brokerage so so whatever broker you're on it will get the price action data for the symbol you're on from the same broker which is important obviously because different brokers have different price data and so you want this to be consistent with the symbol you're referencing on your charts so trading view takes care of that all for you just by this little happy little line of code here to reference Bob Ross but the next variable we need to input here is the resolution what time frame are we referencing and we can just reference our time frame important from up here so just type in res sorry I could have taken lots of breaks between writing this out because my neighbors are redoing their lawn and there's someone out there shoveling a whole lot of gravel I don't envy them today that's a harder job than writing code that's for damn sure so the next input variable we need to get we need to plug in to this security function is it's called expression here you can see expression is a third input basically this is any expression any line of code and so we're going to be plugging in this here into into this expression slot or whatever and what this is saying is on the current symbol ticker ID or Z CAD on the current time frame or that are on the reference time frame the daily time frame it's saying tradingview please get us the EMA variable from this information so this will be the daily clothes on the daily chart and we'll be calculating a 50 period EMA with that information but we're not quite done yet we also need to plug in the gaps variable and the look-ahead variable and I'll explain what those do next so the first one is gaps and we're gonna write in here bar merge dot and press control space and that will show us the available variables for bar merch basically if you put bar merge caps on what that will do is remember I said that there's 24 one-hour bars in a day well this will merge the gaps between the start of the day and the start of the next day and basically what that will give us is a an average of the average we're going into EMA inception here and we're calculating a average of the EMA the exponential moving average and merging the gaps between price action so again that'll make more sense when you can see it on the chart so for this one we're just going to write gaps on so we're turning bar merge on emerging the gaps of any price action gaps on the higher time frame we're turning that feature on the next input is an interesting one as well this is the look ahead so if I type bar merge dot control space we have look ahead on or look ahead off basically what look ahead is is that in historical data when you're referencing a higher time frame pine Script obviously has access to the days closing price the current days closing price so right now the day daily chart hasn't closed on this time frame so if you were to turn this to look ahead on it would be referencing the current days closing price and that's how you would run into what's called repainting issues I'll get into that in another lesson because it's a little bit advanced for this stage of this this course but basically in layman's terms what that means is that if you set this to look ahead on throughout historical price action the script will be able to look into the future to see what the day's closing price was before the day would have closed in live action so first of all there's all sorts of reasons why you would want the script to be able to cheat and look ahead but I'm not gonna go into them today I'm just gonna say that for the most part for most scripts that you create it's probably safest to just turn look-ahead off so this script is going to merge any price action gaps between any missing price action gaps and it's going to not look ahead and basically when you turn this off what that means is that instead of on historical data instead of referencing the days closing price and cheating seeing looking ahead to see what the day's closing price was it will simply reference the previous day's closing price instead which in this case for the purposes we're using this higher time for an EMA for is exactly what we want so we'll leave that off and the next step in this tutorial lesson is to create the EMA steped version and then I'll will plot these to the chart and it'll make a lot more sense what these to do so again we're going to reference the security function we're going to do all the same here we're going to reference the same symbol that we're currently on the same higher time frame setting the same EMA expression the only difference on this line of code is that we're going to set Bar merge gaps off and the BOM merge look-ahead is also going to be off so literally the only difference between these two lines of code is that this one has gaps off and now we can plot these two variables to our chart so let's do that here now we don't want to draw both of these EMAS at the same time which is why I have this smooth setting here so whether this is turned on or off we'll determine which one of these EMA is we draw it to the chart so this is going to be a little bit of a messy line of code but I'll explain it as we go first thing we're going to use is what's called a conditional operator if you're not sure what this is just go back and go through my previous lessons where I explain in detail how this works but this is like an if if or else statement so we're going to say if smoothing is on if this smooth bullying is set to true in the settings menu then we want to draw the EMA smooth otherwise if this is set to false we want to draw the EMA step value then comma for that the next function setting for this this plot function is going to be the color what color are we going to draw this EMA at and that's where this color variable boolean comes into play or you want to say if we're coloring this EMA then we want it to be green if the current closing price on this time frame is above our higher time frame I'm gonna use EMA step for this and I'm not gonna explain why but that'll make more sense if you if you go over this lesson a couple times and you and you really think about what these two lines of code do but anyway here we're going to stack two conditional operators on top of each other so we're gonna say if the color variable is turned on this boolean is set to true and the if the closing price is above the higher time frame EMA then we want to set the color to green otherwise if color is set to true and the closing price is not above the EMA higher time frame EMA then we want to set the color to red and then we'll draw another semicolon here otherwise we're just going to paint it black as the rolling stones would say I'll just go over this one more time because the nodes would be confusing to look at but what it's saying is if the color variable is set to true if the user has set this boolean to true this check box is ticked and the closing price is currently above the higher time frame EMA then we want to set the EMA color to green otherwise if it's the closing prices below the EMA or equal to it then we want to set it to red and if this color variable input variable is not set to true meaning the check box is not ticked then we're just going to paint it a solid black color and that's it for this section now we're just going to set the line width to two so that it's just a little bit thicker I feel that that works better on EMAS especially a higher time frame EMA and we're going to title this plot function so that our users can go into the settings menu and change these colors if they want to so I'm going to say EMA in brackets hiya time frame and that's it for this script basically we can hit save and add to chart hopefully there's no errors doesn't look like it add to chart and there we have it it's now plotting to the chart but because we're so zoomed in on this one hour time frame we can't see it so zoom out a little bit let's go up to the 4-hour chart and here we have the higher time frame EMA 50-day EMA being drawn to our 4-hour chart but we do have smoothing turned on so if we come up to here and we turn smooth off now we have our stepped 50-day EMA and so I'll just quickly explain this stepped EMA again now that we can see it on our chart and that'll be the end of this lesson so we go down the one-hour chart zoom out a bit if I count the amount of bars between each step you'll see that it adds up to 24 so during this whole day of price action the EMA was one solid value and this was the previous day's 50 EMA value based on the closing price and this is exactly what we want if you're going to use this information to trade off this is what you want on your chart and now this script isn't quite perfect if I am if you look up here you can see that it's it is actually repainting it's still repainting even though we set look ahead to off I'm not going to go over how to fix that in this in this lesson because it's it's quite a detailed process and the lessons already long enough but this is the gist of what you would need to do in order to achieve working with higher time frame data using the security function in future lessons we'll do other things like drawing the higher time frame high or low but that sort of thing but this is a great introduction to the security function and what all the variables do and so yeah this if we turn this to smooth if we turn the smooth function on you can see that it's merging the gaps and so we're not getting that stepped effect but but this is an inaccurate 50-day EMA reading looks a lot better looks cleaner on your chart and it could be useful for things like just performing general technical analysis on your charts but if you wanted to use these levels to trade off it would be much better to have this depth version on so that during this day you are referencing the previous previous days 50 EMA value instead of the current days 50 EMA value which really we won't know until the end of the trading session and that and the current daily chart closes so yeah that's it for this lesson I hope that made sense if not leave a question in the comment section and I'll get back to you as soon as I can if you found this lesson helpful please subscribe to the channel that there's a lot of motivation to continue making these videos and I'm glad to be able to help you guys learn this new skill and just before I leave I just wanted to let you guys know that there is a lot that goes into creating complex and practical useful Pyne script scripts and indicators and so I'm considering creating a very in-depth advanced plan script course for you guys going into detail maybe going over how I create my own indicators my own complex indicators such as my ultimate pull back indicator which I actually used to trade the live markets forex markets and this is painting pull back signals to the charts so you can see it's it sends me an alert telling me when to go long or short tells me my stop-loss my target placement and you can see it's had a couple of winning trades here I'm considering teaching you guys exactly how I made this sort of indicator the catch is this information is quite valuable it took me a long time many many many hours of work to get something like this working and I don't really feel comfortable giving away all of my secrets for free so I'm considering creating a premium pine script course where I'll go into much more detail about how to practically apply all of this information and I'll make it affordable when it is finished and by the end of it you will be able to create your own strategy scripts your own indicators and tools to aid in your own trading and so over the next few maybe months I'm going to be working on that and building that and making that as great as I possibly can and I'll let you guys know when it's ready and for those of you who really want to take this to the next level that'll be a great resource for you guys to really enhance your edge and in that course I may even include a mentorship option where you can get one-on-one access with me and ask me questions and I'll help you to create your own scripts because right now I'm getting a lot of questions from traders and coders and I just I really don't have the time to help everyone and so I'd love to offer a service where I can help you guys but obviously with the amount of time I spend on my own trading and content creation I just don't have the time to do that for everyone so I'll have to find a way to prioritize that and maybe the core students can get that priority and so if you're interested in that I'll leave a link in the video description to sign up to my PI inscript mailing list and anyone who signs up before the course is released I'll send out an email to you when it is released and I'll give you a significant discount on the opening price for supporting me and for pursuing success and being proactive about your trading because I respect that and I will reward that where I can so we'll speak to you guys in the next lesson good luck with your trading best of luck with your coding keep at it I know this stuff can be confusing and it takes time to learn but it's extremely extremely valuable information to master and once you do you will be able to take your trading to the next level completely and possibly even automate your strategies that'll be another thing I'll cover in the paid course how to use third-party api's to automate strategy scripts so take it easy everybody I've enjoyed this time with you I hope you did too and I'll see you in the next lesson good bye [Music]

Pine Script [OUTDATED V4] Tutorial Lesson 7 How To Use ATR Trailing Stop Loss

hey friends welcome back to another plane script coding lesson my name is matthew from zen and the art of trading and today i'm gonna be showing you how to use the ATR indicator in your scripts so in the previous lesson i showed you how to use the RSI indicator to create overbought and oversold signals in this lesson I'm going to show you how to use the ATR indicator to create a trailing stop so we're just going to draw onto the chart our trailing long position stop and a short position stop I'm going to do it this way because it's just a lot more simple to demonstrate the logistics behind using this indicator in your scripts but in future lessons I'll come back to this lesson 6 script this RSI script and I'll show you how to plot your stop-loss and target placement so say you wanted to go along here after the RSI went oversold then we got a bullish engulfing candle so you want to have a 180 our stop loss and a 180 our target then you can actually plot these values directly to your chart using pine script but today's lesson we're not going to cover that I'm just going to keep it simple we're gonna delete the script I'm gonna start a new blank script and I'm going to call it lesson you guessed it seven keeping it really simple for you guys here alright so the first thing we need to do is set our overlay to true now overly to true if you if you set this to false then if I save this and add it to my chart it'll draws an oscillator box so now we're plotting the price we have a line chart that is separate to our main chart so that's useful when you're creating oscillator indicators basically like the RSI stochastics when you're working with those sorts of those styles of indicators but today's script we're going to be drawing directly to the chart so that I can visually represent the information I'm going to show you so if I click Save there delete this script and add this back to my chart we now have the closing price plotted directly to the chart so let's get straight into this one so first thing we're going to do is we're going to get inputs from the user because it's always useful to be able to adjust these values on the fly the first thing we're gonna want to get is the ATR length by default this is usually 40 a 14 period ATR so we'll leave that as the default setting but it's also great even creating scripts especially to release to the public it's always considered good etiquette to include as many options as you can for customizing the scripts so I'm gonna get in get you guys into that habit early on and so we're gonna call this 180 our length and we're going to have a type of input integer it's gonna be a whole number we're gonna have a default value of 14 and a min value of 1 might as well this isn't necessary but the ATR length can't be calculated beyond a 0 or negative value so might as well get into a good habit of using this min Val function as well or feature the second input we're going to use is a boolean and we're gonna call this one use structure so I'll explain what this does later first of all let's just code it in so we're gonna say use structure I like to put question marks on the end of my boolean inputs just out of habit you don't have to do that the default value is going to be true in this case this is going to be used for detecting swing lows and swing highs to trial stop-loss the alternative method is to just have a 180 R or whatever multiplier you want of the a TR from the closing price so that'll make more sense later I'll explain that later on so we're gonna have two more inputs the next one is look back this is for the structure look back so title is how far to look back for high-lows and we're gonna make this a integer as well because it's gonna be a whole number and we're gonna set a default value of 7 so we're gonna look back seven bars for swing high and swing lows the min value be 1 as well on this input and then we're going to create one more variable called the ATR stop multiplier and I'll also explain what this does later this will make more sense later I just like to get these inputs out of the way early so we're gonna say ATR times question mark and this one is going to be an input dot float it's gonna be a floating point variable and if I just quickly add the ATR indicator on to my chart you'll see why that is see if I hover my candle my cursor mouse cursor over any of these bars the it'll show you down here in the left-hand corner of this indicator this oscillator box it will show the ATR value and that's obviously a floating-point number it's not a whole number it's got a decimal point zero point zero zero zero one six is one point six pips I'm on the 1-minute chart here if you're wondering why the ATR is so low I just figured that the one-minute chart would be the best time frame to demonstrate this technique on but this script will obviously work on all time frames so for this one we're going to have a default value of one point zero so we're going to have a default value of a one ATR stop multiplier so whatever the ATR indicator is giving us that will be our stop loss so say above this swing high will have a one ATR stop above this swing high we don't need to set a minimum value for this but might as well while we're here and I'll set it to zero point one if you're going lower than a zero point one ATR multiplier then you might as well not use this at all so that's all of our inputs we're going to be using today so now the next step is to calculate the data that we're going to be plotting to the chart so we'll call this comment calculate data just for our own reference and the first thing we need to do is get the current ATR value so we're going to call this variable ATR just keep it simple I like my scripts to be as simple as possible we'll call it ATR and we'll use the ATR function to get the current ATR value with our specified ATR length so this by default is 14 that's the that's what this see 14 RMA is giving us a default AGI reading and so we'll this line of code here so these values will be identical and I'll show you that right now actually if we click the save and we look up here that at the top left of the chart you can see that those numbers are identical so we're plotting a 0.2 for now fit ATR it's the same on both indicators so that's good let's move on to now calculate our stop losses so our long trailing stop is going to be plotted below price and that's for long position so if we were to have gone long here then it will plot where our trailing stop should be which will be 180 our below the most recent swing low so let's type that in long stop is set to and then this is going to get a little bit complicated here but it's not that crazy it's just gonna be a bit confusing to read so I'll explain it as I go but we're going to use the conditional operator again and this just saves space in our code and we can put all of this if-then statement into one line of code so we're going to say use structure question mark if we're using structure if we've ticked YES on this you structure input then we want to calculate the stop loss based on the lowest low over our look-back period otherwise if we're not using structure then we just want to use the closing price so this line of code here now does two things if we have this ticked as true use structure is true then we're going to search back seven candles that's the default value of our look-back variable we're gonna look back seven bars and we're going to find the lowest low in those seven bars so in this case that would be this low in here and then we will calculate the stop loss as one eighty are below this swing low so the way we do that is we're gonna - because our stop loss is below price we're gonna - this lowest low or this closing price by the ATR value which is here but we're not just going to do that because otherwise we can only use a standard 180 our trailing stop what if your user wants to have a two ATR or three ATO or half ATR trailing stop well the way that you achieve that is by timesing this value this calculation by our ATR stop multiplier so if I type that in there we now have our trailing long stop so if I just quickly I'll just demonstrate what this looks like so we'll type in plot our long stop the color is going to be color dark green it's going we're going to use a little bit of style here we're gonna say style equals plot style underscore line break line be are the short for line break then we're going to call it we're gonna title it long trailing stop we're going to set the transparency to zero we don't want any transparency on this if I hit save here you can see we are now plotting our trailing stop and it's plotting 180 are below the lowest candle or the lowest low of the past seven candles so say you wanted to use a standard trend following technique and you wanted to trail your stop-loss below the low of the pullback preceding the breakout the most recent breakup so in this case it would look like this we have a swing high here a couple of candles pullback then we break in close above the swing high on this candle here if you were to hold your mouse cursor over this candle look back seven bars the ATR indicator over this candle here this trailing stop will be plotting the lowest low below these seven bars so on this one-minute chart you might want to make these look-back period a little bit shorter than seven bars because you can see here that that's that would put you on this bar here which is lower than the swing low of the pullback but let's just say we hover our mouse over this here this will give us the trailing stop value so say you went long down here on this bullish engulfing candle and you had a 180 ah stop below this entry which would put you around here somewhere and say that when this breakout happened you wanted to trail your stop-loss up a little bit you would move your stop-loss you'd hover your mouse over here look for the value which up in the top left here is zero point six zero three eight eight so you would help bring your your stop-loss up to this green line here and so that's how this indicator would work in practical terms but that's not important for the demonstration so let's just continue onwards now and we'll draw the short trailing stop so the short stop is going to be set to use structure question mark are we using structure if we are we want to use the highest high over the pier over the look-back period as our reference price otherwise we won't just want to use the close and because this is a trailing stop that is above price action we've won the plus we want to add to this value so we're going to add the current ATR times our ATR stop multiplier so by default this is set to one so this is just one ATR but as you can see if you want to change that to say - ATR that will widen your stop-loss or a zero point five ATR which is why we set this to a float not a whole number we can set it even tighter it's up to you that's a matter of preference so now we've got that we can now plot I'm just going to copy this line of code I'm going to plot our shortstop and the shortstop's going to be colored red everything else can stay the same we'll change this to say short trailing stop click Save and it will now plot our short trailing stop above price so if you had word to have gone short up here on this little double top up here maybe you had a 180 our stop above the high then as price went into your favor you were just simply every time we had a breaking close below a swing low so we had a break and close below the swing low here you'd hover your mouse over that candle and then whatever value you get up here is where you would put your stop loss and so that's a practical way of using this particular indicator this script and so I'll do one last thing before we finish this lesson and that's we're going to keep plotting this ATR indicator but we don't want to actually plot the value if I scroll this right down right down you'll see that it's actually plotting our ATR to the chart we don't want that because it's gonna on some instruments that may draw over price action and we don't we don't want that so what we can do is use the transparency function so what we'll do here is I'll set the color you can set the color to whatever you want I'll leave it as blue in this case I will also title it so that our users of our script can adjust this color and transparency as they wish and we'll set the transparency in this case to a hundred we wanted a hundred percent transparent here we have zero percent transparent because we want it to be drawn to the chart clearly here we don't want to drawn at all if I type that in hit save and now if I scroll right down you'll see that it's not plotting to the chart anymore and so that's the end of this demonstration we now have a trailing stop 180 our indicator so I can you can see if I hover my mouse on any of these candles the blue line up here that's plotting to the top left is the same as the actual ATR indicator in the bottom left down there so we can now remove this and we now have our trailing stop indicator and if account to the settings first of all you can adjust our values here see that we've titled our plot our drawings so that we can actually change the color of these so if you wanted a blue trailing stop and an orange a blue long trailing stop and an orange short trailing stop you can change that in here and of course if you wanted to adjust the ATR multiplier in come up here and have a one and a half eighty our multiplier that'll widen your stop-loss or if you want to change the look-back period of the ATR the ATR length you can change that in here to say calculate the ATR based on the past seven candles instead of the past 14 or you can adjust this so you might want to make this even less of a look-back so maybe three candle look back and now it will detect the highest high and highest low of the past three bars to draw our trailing stop above or below and there we have it I hope that all made sense if not feel free to leave any questions in the comment section I'll get back to you as soon as I can and the reason why I'm making this lesson is less than seven is because the future scripts that I go into are going to use the ATR indicator probably quite a lot so it's important we get this out of the way early and this is the simplest method I can think of to demonstrate how to actually use the ATR indicator on your charts so that brings me to the end of this lesson I hope you enjoyed it please leave any feedback in the comment section any suggestions of topics you'd like me to cover anything I missed or didn't make clear enough shoot me a question I'll get back to you as soon as I can I've been getting a lot of positive feedback from these lessons and it's really encouraging I'm really glad that you guys have finding value out of these lessons and I'm glad I'm helping you guys advance your own trading career this stuff has really dramatically improved my own trading and I'm just super grateful to have these tools at my disposal and I'm really excited to pass them on to you as always if you have any questions head over to Zen in the art of trading comm there's a link in the description I have heaps of lessons over there written lessons and a whole library of free indicators free scripts that I've created myself I've created dozens and dozens and dozens of scripts some of them premium you have to pay for them because they took me quite a long time to create like my my ultimate pull back indicator for example if I throw that on the chart this will just give you an example of what you can achieve when you master this skill so you can see here this indicator is plotting signals to the chart pullback signals so if I turn off lesson seven it's plotting my stop-loss one eighty are above the swing high and my target one eighty are below the entry point and it's using the EMA has changed color based on price action all of this stuff you I'll teach you guys how to do yourself but if you want to skip ahead head over to my website and check out some of my free indicators the source code for my free indicators is readily available so you can go there and use them as reference material if you want to that's it for today see you next time guys take it easy trade green and good luck with your coding [Music] you

Pine Script [OUTDATED V4] Tutorial Lesson 6 Detecting Engulfing Candles

all right welcome back traders this is matt from zen and the art of trading today's video i'm gonna be covering how to detect basic candlestick patterns in pine scripts so this lesson is going to build off the previous lesson lesson 5 and in lesson 4 and 5 I showed you how to detect RSI conditions indicator conditions using the inbuilt pine script function and we're just going to adjust the script here so that alerts are only triggered when the RSI is overbought and oversold and we get a engulfing candle like this here and this up here we've got a bullish engulfing candle here and a bearish engulfing candle here after the RSI is gone overbought and oversold so I'm going to show you guys how to detect that condition using pine scripts and let's get into it I'm gonna break this up into three lines of code to make this easier to understand so the first thing we're doing here is we're gonna identify engulfing candles so the first one we're going to detect is a bullish engulfing candle and in order to detect a valid engulfing candle we need to find a candle that closes higher than the previous candle opened it's it can be different for stocks and things like that where there's gaps in price action but for this lesson we're gonna keep it simple we're just gonna focus on this catalyst Forex pair this gold versus US dollar where there are no gaps in price action and so what we need to detect is whether this current closing price of the current candle is greater than or equal to the previous opening price so using this as an example we want to check if this closing price is greater than or equal to this opening price and the way you would reference this previous bar is by using what's called an array so this array will reference depending what number you put in here say 1 2 3 4 100 whatever you put in here will reference the number in previous bars from the current candle so let's just assume that this right here is our current candle we want to detect whether the closing price is greater than the candle before it so we're looking one candle back so we put in a 1 in here but this is also going to detect if we just leave this as it is it's also going to detect hi-hi-hi closets because this candle here closed higher than the previous open as well so we need to filter this signal and make sure that the previous candle closed bearish and all that means is that the closing price is lower than the opening price so in order to do that we combine these two boolean values so we want to find out did the candle close higher than or equal to the previous open and did the previous candle close lower than its opening price that's it that's all we need in order to detect this pattern here very simple so the next one is a bearish engulfing candle and it's basically just the opposite of all of this so we're looking for a candle that closed less than or equal to the previous open and the previous candle must have closed bullish so in this case the previous closing price must be greater than the previous open price and now that's all we need in order to detect bullish and bearish engulfing candles and then to create a trading signal out of this we're going to create a new boolean value called trade signal and trade signal is going to be assigned to we're going to combine these two variables these two boolean values with these two boolean values so the way we're going to do that is we're going to use as we're going to open two parentheses so we're gonna have one open bracket and then another open bracket so if you remember algebra from school whatever is in this bracket here this X is going to be executed before whatever's in the outer brackets so this will be execute X will be executed before Y the reason we need this is that we're going to check whether the RSI was overbought on the current candle or the previous candle so see in this example here there is no RSI signal below the candle that's because when this candle closed the RSI indicator went from oversold to not oversold but the previous candle was oversold so we want to detect this candlestick pattern if the RSI was oversold on this candle or the previous candle so the way we would do that in Pine script is we would say is RSI oversold or is the RSI oversold on the previous candle so the same way we can reference previous open/close high-low prices using this array functionality we can do the same with our own custom boolean x' so this in a bracket here will be true only if the current candle is oversold or the candle before it is oversold and then we want to combine that with our bullish engulfing candle detection so we'll just type in here bullish you see so now this will turn true this trade signal boolean will turn true if the current RSI is oversold or it was oversold on the previous candle and we got a bullish engulfing candle signal we want to do the same for bearish so this trade signal is going to detect both bullish and bearish signals and so after this outer bracket that encompasses all of this boolean calculation we want to add the or operator and do the same thing for the bearish detection so to open brackets and then is the RSI overbought or was it over bought on the previous candle and do we have a bearish engulfing candle detected closed bracket so now this line of code will turn true if we detect a bullish or bearish engulfing candle while that while the RSI is overbought or oversold now if we save this script nothing's going to change here because we haven't changed our plot shape and our alert functionality so what we'll do here is we'll say plot the overbought signal the cell signal only if we get a trade signal and that trade signal is a bearish engulfing candle we'll do the same for the next plot shape we're going to say here plot a buy signal only if we got a trade signal and it was a bullish engulfing candle we'll do the same down here he cept here because we want these alerts to be triggered for both bullish and bearish engulfing candle signals we only need to put in trade signal here we don't need to specify what type of trade see you that's only for plotting the signal to the chart so now if I hit save we're going to eliminate all of these signals here and we'll only detect this one and this one up here so let's hit save and watch the magic happen there we go we get only two signals on this chart now and we have our bullish buy signal when the RSI goes oversold and we get a bullish engulfing candle and then the same is true of a sell signal it only plots when the RSI goes overbought and we get a bearish engulfing candle and the same is true of our alerts we'll only get an alert to our phone and charting platform if these market conditions are met and so that's the beginnings of using plan script to create your own strategy scripts or to detect your own setups in the markets so once you get proficient at using pine script you can use these these functionality and what I've been teaching you to detect your own trading setups in the markets and send alerts to your phone or email account whenever your trading setup appears in the markets this helps you to stay on top of the markets without having to check the charts especially if you trade the 15-minute chart or the five-minute chart this can help you stay on top of multiple markets depending on your trading view subscription type you can set as many alerts as you want I'm on the Pro I'm on the Pro Plus subscription so I can set as many alerts as I want and I could set an alert for every currency pair that I'm trading and then I don't have to scroll through my charts all the time to detect these setups this script will detect it for me and send me an alert so that's it for this lesson I hope you found it helpful and in the next lesson I'm not sure what I will be covering but it'll be something more advanced than this so these lessons are going to build on top of each other and become more and more advanced so if you haven't seen the other lessons go back and watch them if you need a pine script otherwise hang in there more content is coming I appreciate your support please hit the like button and the subscribe button if you want to be alerted whenever I come out with a new pine script lesson and I'll see you in the next one have a great week guys good luck with your trading good luck with your coding I'll speak to you soon take it easy [Music]

Pine Script [OUTDATED V4] Tutorial Lesson 4 Generating RSI Signals

hey traders welcome back to zen in the
art of trading
my name is matt and today i'm going to
be creating another pinescript tutorial
lesson
and this video is going to be covering
how to use inbuilt indicators for this
lesson i'm going to be covering the rsi
indicator
but in future lessons we'll go over
other indicators and
how to combine the indicators with price
action in order to generate trading
signals
so let's get started let's open up the
pine script editor here we have a blank
script
i'm going to call mine lesson4
and i'm going to set the overlay to true
so that this
draws straight to my chart i'll save
this as lesson
4
and then click add to chart and it'll
just plot the closing price for now
so the first thing that we're going to
do is get
some user input now these inputs are
going to allow us to customize the rsi
indicator
the in build rsi that we're going to be
using in the script
so the first thing we're going to get
from the user is
what source what price source they want
the rsi to be calculated with
so we're going to say rsi source is set
to
input and the title of this input
is going to be rsi source
the type is going to be set to input
dot source and the default value
is going to be candle closes we want
this rsi to be calculated using candle
close
the next variable we're going to get
from the user is the rsi length
so rsi length is set to input title is
rsi length the type
is input dot integer for
whole numbers and the default value is
going to be the same as the rsi's
default value which is 14.
the next input we're going to be getting
is the uh
rsi overbought threshold so
when the rsi exceeds this number
we will consider the price action
overbought and we'll plot
sell signals to the chart now obviously
it's not a great idea to trade
these sell and buy and sell signals
blindly i'm just using this as an
example
so this one we're going to call rsi
overbought
level it's going to be type
integer and the default value
is going to be set to 80 in this case
normally at 70.
the traditional overbought oversold
readings for the rsi is
70 and 30 but today we're going to be
using 80 and 20.
we want the most extreme overbought and
oversold levels we can detect
and this is just an example of how you
can tweak these indicators to suit your
own
preferences so the next input we're
getting is rsi oversold
is set to input title
rsi oversold level
and the type is the same as the others
input dot integer
and the default value is going to be 20.
so if i save the script we should get no
compile errors
hopefully yup there we go so now we're
ready to
get the actual rsi indicator value
so the way that you get an rsi the way
that you get an
inbuilt indicator is using the inbuilt
plan script functions
normally they're named the same as the
indicator so in this case we're going to
say we're getting the rsi value
and the rsi value is in this case it's
going to be assigned to
the inbuilt function called rsi very
simple
now this rsi indicator this particular
script
requires two inputs in order to get its
calculation in order to calculate its
value
the two inputs it requires is the rsi
whoops rsi source
and the rsi length now obviously you can
hard code these two values to be
whatever you want but by allowing the
user
to change these values in the settings
menu
it really really adds to the user
experience
it makes it a lot easier to adjust
things on the fly
when you need to now we have the rsi
value
in order to determine whether or not
price is overbought or oversold
we need to compare this value to our
overbought
and oversold thresholds so in this case
we're going to create
a boolean value remember the boolean
value is just a true or false you know
one or zero
essentially binary value and
we're going to call it is the rsi
overbought i like to put
a question at the start of my booleans
like is just so that i know
that it is a boolean but in this case
we're going to say is
rsi overbought and this is going to be
true
if the rsi value is greater than
or equal to the rsi
overbought threshold
so this operator in here is just the
same as mathematics normal mathematics
this sign here is greater than
and this combining these two is saying
set this rsi overbought value to true
only if the current rsi value
is higher than or equal to 80.
pretty simple so the next thing we need
to do is determine when
the rsi is oversold so here we'll say is
rsi oversold is assigned to
true only if the rsi value
is less than or equal to the rsi
oversold threshold and that's it
it's done these two variables here will
tell us
when the rsi is greater than 80 or lower
than 20.
and so the last thing to do is to plot
this information to the chart
visually so now we're going to plot
these signals
to chart and the way we do that is using
what's called the plot
shape function so if we write plot
shape open bracket the first
value that this function requires is a
boolean value
so we're going to plot the shape only if
the rsi is overbought
we're going to title this if you title
this to something that you recognize
you can go into the settings menu later
and you can change the color of the
shape
the size of the shape etc so it's always
a good idea to title
your shapes that you plot to the chart
the next variable that this function
takes is the location
where do we want this shape to be
plotted
we want it to be plotted location dot
if you press control space you'll get
all the valid options
for locations today we're going to be
using above bar
so we want the over bought shapes the
overbought signals to be plotted above
the candles
on this chart the next
variable that we can put in is the color
so with this we're going to set the
overbought
signals to red because typically red
means sell
green means buy so overbought is going
to be red
we want to set the transparency to zero
so we don't want any transparency
on this shape well not in this lesson
you can just play around with this if
you want to
see how it looks on your chart and the
next uh
input that this function takes is the
style what style do we want
the shape what you know what what do we
want the shape to look like
so if you type style is set to shape
and then a full stop and then control
space you get a list of all the valid
shapes you can choose from
i'm going to stick with triangle up and
triangle down for this lesson just
because it
suits what we're going for but you can
play around with all of these shapes
when you
when in your own time and you might find
others that you prefer
but today we're going with triangle down
for a cell
signal and the next variable
that we can put in here is the text that
is drawn
to the actual chart so this is different
to the title the title is for the
settings menu
the text is for drawing onto the actual
chart so in this case we're going to
call it
ob we want this signal to have the text
ob next to it now in pine script
you have to plot at least one thing
either plot a
price action variable like the close the
high the low etc
or a shape so we can now get rid of this
plot close
and the indicator will save and it will
add
this uh code to our chart so on this
time frame there is no overbought
signals if you go down the 15-minute
chart there we go
we have our first rsi overbought signal
being plotted directly to the chart so
that's great
let's move down and start plotting the
oversold
levels for buy signals so this
we're going to use exactly the same
function plot shape
and we're going to copy this basically
copy this entire
line of code so we're going to change
all these values to represent oversold
levels but it follows the same format so
the first variable is a boolean this is
the flag the trigger
to plot the shape if this is false it'll
just plot nothing
as you can see on all of these other
charts there's no nothing being plotted
that's because this overbought boolean
is false
it's the same for oversold so if we go
rsi
plot the shape only if the rsi is
oversold
we'll call the settings menu oversold
so this plot shape will be called
oversold in the settings menu
the location is location dot below bar
this time because it's a buy signal we
want it under the candle
the color will be color.green
for a buy signal transparency is zero
again
style is going to be set to start oh
sorry
it's going to be set to shape dot
triangle
up for a buy signal and the text is
going to be set to oversold
now we hit save our chart will update
and there we have our oversold
rsi signals simple as that now obviously
this is
just a very rudimentary example of using
an indicator
in future lessons i'll show you how to
detect candlestick patterns alongside
these rsi values so for here for example
you could make a strategy script out of
this by detecting when the rsi goes
oversold
and then detecting a candlestick pattern
while this condition is true
so here for example we could make the
script detect engulfing candles
or high high higher close candles only
when the rsi is oversold
and then you could create a counter
trend trading strategy or mean reversion
trading strategy out of this
information so this code is very useful
i know it's very simple right now but if
you practice this
uh you'll be able to create some very
impressive things
in the future so just quickly you can
change this text to whatever you want so
say you wanted this to say
sell and oversold signals to say
bye if i hit save that'll change this
text up here
to say sell signal and buy signal
and that's all you need to code in order
to detect these
market conditions now obviously you
could change this to anything you wanted
you could use stochastics or you could
combine this
with other indicators like a ema or the
atr indicator anything you really
want to so that's it for this lesson i
hope you found that
helpful i'll see you in the next lesson
where we'll go over candlestick patterns
so i'll see you there have a great
trading day good luck with your trading
best of luck with your coding i'll see
you in the next video goodbye traders
[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...