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
Sunday, 20 October 2024
Pine Scripters Network • Join Our PINE SCRIPT COMMUNITY!
hi traders in this video i'm excited to introduce you to the pine scriptures network the pine scriptures network is a new online forum i've set up and it's intended to be a community where pine scriptures such as yourself can communicate with each other share your scripts share your code and help each other with your own scripts and today i just want to introduce you to the website show you how to sign up and give you an idea of what to expect so if you go to pinescripters.net that will bring you to this page here and there's not a lot happening here yet because i'm the only user of this website but hopefully soon we'll have a bunch of active members here helping each other out with their scripts so the first thing you want to do is get rid of this cookies notification you want to come up here and click on register and here is the agreement registration agreement there's nothing hidden here this is just a disclaimer about trading and the just generic forum rules nothing too complicated i don't want your firstborn child or anything crazy like that you want to agree to these terms and then fill out this information with whatever relevant information you want to include so you need to input a username an email address password and down here this is optional this is your trading view profile you don't have to put this in if you don't want to and then finally this is the important part this is the registration code box so depending what code you put into this box will determine what group you added to when you sign up to the forum so at the moment there are three groups there's the pinescript mastery students group there's the pinescript mastery course graduates group and there is the pinescript mastery mentorship group so anyone can sign up to this website it's completely free to access but there are a handful of private forums that are only accessible by certain groups of people so anyone who signs up to the basics course or finds this website over google or from my youtube channel they can sign up for free and they get access to their own forum and this will be easier if i just show you what i'm talking about so everyone has access to these forums here you need to be registered in order to post in these forums but these forms are accessible by anyone same with these ones here and the feedback and support section but there are a handful of private forums so first there's the pine script scholars forum this is only for people who are enrolled in the pine script mastery course this is for you guys to talk among each other and you won't get any random trolls or anyone that's um that's not on your level of pine script expertise coming in to contribute to your conversations the next one is the pinescript masters forum now this forum is restricted only to people who have graduated the pinescript mastery course finished all the lessons in the course so this is for people who want to have a little bit more of a sophisticated conversation about pine script with each other and they know that the only other people who can comment on their discussions are people who are at the same level as them in their pine script education or even more educated and then finally there's another form here that you can't see unless you're signed in as a mentorship student but there's a pine script mentorship section as well so anyway let's go back to the register page and i'll explain what you do down here so because this is on youtube and it's open to everyone unless you're enrolled in the mastery course in which case you'll get an email with a code to sign up with then you can only sign up as a free user and you can just ignore this box here and don't put anything into it you just create a free account and you can communicate with other free users on the network if you want to access any of those restricted forms that i just mentioned you'll need to upgrade to the mastery course or graduate the mastery course if you want to talk to other mastery course graduates so if you have access to a code once you put it in here and you click submit you'll be automatically enrolled in the relevant group and once you confirm your email you can come in and access the form and start sharing your thoughts with the community now if you've already created an account on this forum and then you receive a new code so for example let's say you purchased a mastery course and you sign up as a mastery course student and then eventually you graduate the course and you complete all the lessons and you want to change your membership group type to the graduate group you need to come up here to your user control panel so click on your profile picture click on user control panel and come up to user groups and then in here you can type in the registration code that you receive and the codes here are exactly the same as they are on the other registration page other than that it just operates as a normal forum so there's a few guidelines and information here so i encourage you to read through this when you first sign up but there's nothing really fancy here it's just you know don't spam be kind to each other keep all topics relevant to pine script coding and don't advertise anything on the forum without asking me first so that i can verify that it's not something malicious or or low quality of course you are absolutely welcome to advertise your own scripts your own projects even your own websites but if you're going to advertise anything external to this platform other than a trading view script please let me know first so that i can just ok it and vet anything that goes through here because i don't want any scammy stuff happening or any spamming to occur i want to keep this as clean as possible and as useful as possible to everyone who signs up other than that there is also this forum here the show-and-tell slash request so you can share your scripts here with the community everyone has access to this forum and same with request scripts you can request scripts from other people in the community and so if you're a student say you're a pine script mastery core student and you want to test your skills i'd encourage you to come and check out if anyone requests a script in here maybe you can help them out and maybe you can test yourself and see what you're capable of there's also a forum for general trading discussions so i prefer if everyone can keep their trading related discussions that don't involve panscript in this forum and then there's a feedback and support section as well so i definitely want to hear your feedback if there's something you feel is missing from the site or something that's not working as you would like it to just let me know and this is supposed to be community effort and i really hope you guys will get involved and help me make this community as useful and engaging as possible this is for your benefit not for my benefit i created this for the pine scripting community so that when you guys have questions if you shoot them to me and i don't have time to answer them maybe you can throw them up in this form as well we can all benefit from the answers and maybe you guys can help each other solve each other's problems i plan to expand this in the future i'd like to have like some sort of store for people to sell their own scripts on here or just some sort of script library would be great so that you guys can get the most out of this but for now this is just a community for you to talk amongst each other help each other out and i hope you like it i hope you find it valuable that's it for this video i hope to see you over there if not that's fine there's no pressure to join this community this is just for fun and it's purely optional if you guys want to join up and help each other out so that's it for this video i'll see you in the next one take care guys [Music] you
Pine Script [OUTDATED V4] Tutorial Lesson 3 Getting Basic User Input
[Music]
hi traders welcome back to Zen on the
auto trading today I'm going to be
covering basic inputs in pine script
this is lesson 3 in my pine script
tutorial course so if you haven't seen
the other videos you might want to go
back and watch them unless you're a
little bit experienced with pine script
so let's get straight into this one I'm
going to start with a blank script here
all I've done is changed the script name
to lesson 3 what I'm gonna do here is
just show you how to use all the basic
inputs I'm not going to go over
timeframes and sessions and symbols I'm
just going to go over the basics such as
number inputs boolean inputs which means
true or false float inputs which is just
floating point numbers decimal place
numbers and string inputs which is just
text inputs I'm gonna plot all these
inputs on to the chart to show you how
to use them in the script we're not
going to actually do anything with these
values I'm just going to show you how to
get input from the user
these concepts will come back later in
future lessons so it's very important
that we go over these now get it out of
the way and then some of you more
advanced users can start playing around
with them yourself in the mean time so
let's start with boolean input the
boolean input is set to the input
function and we're going to call it
boolean it's going to be type we're
gonna set its type to input dot and then
you can press control space here if you
forgot about that and it'll list all of
the inputs here we're going to go with
ball input bool and then the default
value def val is going to be set to true
and obviously you can set this to
whatever you want true or false so in
order to plot the boolean to our chart
there's no way to plot a true or false
value to the chart because there's no
way to visually represent that other
than using numbers so we could use a 1
for true and a 0 for false that's what
I'm going to do in this example and now
the way to plot this
the easiest way to plot this is using
what is called a conditional operator
this is a little bit advanced but it's
not that advanced and it's very useful
to know so I'm going to teach you that
in this lesson so in programming there's
what we call if statements so the way
that would work is we type if and then
next we put in a boolean value so in
this case we'd write boolean input now
this next line will not be executed
unless the boolean value is true so an
example of that would be this if I would
write data equals say negative 1 here we
could say if the boolean input is true
we could set the data value to 1 and now
if we change this to plot that data
value and I save the script and I add it
to my chart you'll see it's plotting 1
because data was set to negative 1 but
because this is set to true the script
changed data to 1 now if we go into the
Settings menu here and we turn this off
it's now plotting as a negative 1 you
see down here on the right axis an
easier way to do this is to use what's
called a conditional operator so what we
can do here is we can say plot boolean
input question mark now what this is
saying is that if this value is true if
this boolean is set to true then we want
to plot one and then if you do a colon
symbol and then you write say 0 on the
other side what this is going to do if I
click Save it's going to do exactly the
same thing here it's going to plot this
line is 1 because this value is set to
true and now if I change this to false
it'll plot as 0 and watch on the right
axis and there you go it's plotting a 0
so that's the power of these conditional
operators they can really save you some
time you don't have to write out all
that code we did earlier you just just
write it out in this format here now
we're going to change
this to plot in the color red so that we
can differentiate this from the other
inputs that I'm about to show you so
that's the first input value and you can
see we can play around with that here in
the settings menu now and it will adjust
the plotted value the next example is
going to be an integer input which is
just any whole number so if I say
integer input is set to input function
or the title of integer and the type is
input dot integer and the default value
is let's say because this is 1 and 0 we
don't want to plot another one so we'll
set this to 2 and then if we come down
here and I type in plot integer input we
don't need to do any conditional values
here there's no if or else about this
it's just a straight-up
number input and we'll set the color to
this time we'll set it to blue 5 click
Save that'll update these scripts and
there you go we've got to plot it up
here in blue and we've got one floated
down here in red which is our boolean
input and our integer input so that very
simple to get these inputs from the user
if we go up to these settings menu you
can see you can change this now I can
change it to 1 and then it paints over
the top of our boolean value if I change
it to 0 it plots below it so I'll leave
that as 2 for now the next example is
going to be a float input so if I type
in float input is set to input function
title is float the type is input dot
float and the default value in this case
is going to be let's say one point five
now I come down I've got a plot it to
the chart so plot float input and the
color is set to color dot purple this
time why not click Save and there we
have it we've got our three input
functions plotting to the chart right
now you can go into the settings and we
can fool around with this change it to
0.5 1.1 whatever floats your boat pun
not intended alright next input is
string we're going to go with a little
bit of text he
this is gonna be a little bit advanced
as well because the only way to plot
text to your chart is to use a label
function that's quite an advanced topic
so just focus on the input section here
you more advanced programmers can play
around with the label function later but
this is a bit of a taste of what's to
come I guess for you for future lessons
so this is the last in base this is the
last basic input that we're going to
cover here there's a lot more advanced
input supertype and input control space
we're not going to go over resolution
session source or symbol in this video
I'm gonna go over those inputs in a
future video the reason for that is that
these two plot these two your chart
requires quite a bit of complex Pyne
scripts compared to what we're writing
here and I don't want to overload you
guys when we're only on lesson three so
let's get this string input working so
I'm going to call this input string and
it's gonna be type input dot string the
default value is going to be let's just
call it some text and now we need to use
what's called an array an array is
basically a collection of values in this
case it has to be called options so if
we say options equals open square
bracket and then close that square
bracket off anything we write in here is
basically a list it's gonna be a list of
values that can be selected from in this
settings menu so I'll show you what that
means right now we'll just type in some
text and then you separate these list
values these list entries using a comma
so if I say some text other value and
then final option if I click Save here
we come up to the settings menu this cog
icon we now have this drop-down box next
to string and there's a number of things
you can do with this type of input you
could use this to set for example
another symbol so say you wanted to plot
data on your chart on euro dollar here
from let's say the sp500 don't know why
you'd want to do that but you can't with
this sort of function here we'll go over
that in more advanced lessons but just
there you go that's how you would get a
list of string inputs to show up in your
settings menu here now if I get rid of
these get rid of this line and save it
to chart and we go up here now you can
type whatever you want in here so you
know whatever you whatever you feel like
and then you see up here in the
indicators values it's changed the text
so if that didn't make sense to you just
go over this video a couple of times
I'll cover a raise in a future video
because they can be quite complex
compared to what we've covered so far so
we'll go over that in the next video
today's video I'll just leave this is
this because I want to keep it simple so
if we go down here now this is going to
be a little bit complex so you can
ignore this part if you want to I'm just
going to draw this to the chart just to
show you that we can interact with this
string input so first of all I'm going
to use this if this is a good example of
an if statement so I'm gonna say if bar
state is last what that means is that if
the current candle that we're
calculating the script on is the last
bar in price action so this current bar
then this next few lines of code will be
executed we're going to create a label
example and the label example is gonna
be set to label dot new so we're
creating a new label the location of the
label is going to be the current bar
index which will be the current bar if
you were to type current a bar index
minus 2 then that will draw this label
two bars back from the current bar but
we don't want to do that in this case
the next input is not relevant so we're
gonna put in na and then the next input
after these two is string input that's
going to draw our string that we've just
created up here then we can set the
color I'll set the color to color green
now this is the color of the label
itself and then we can also
set the text color so I'll set the text
color to colored on white and then I'm
going to set the style to label dot
style label down there's a couple of
different styles you can go over such as
style label left label right label up
non-square blah blah blah blah blah I'm
just gonna go with label down for now
and then the Y location is where on this
y-axis do you want to do an it above the
bar do you want to below the bar so in
this case we're going to set it to Y
location Y lock dot above bar and now
that's our label created if I hit save
so I've got a couple of areas here I've
done a few typos done a couple of
whoopsies let's have a look I have first
of all a misspelled example because it's
early in the morning and I'm like that
at early in the morning I've also forgot
to put style in front of this option so
yeah another example of what happens
when you're not paying attention with
your coding you'll get errors but at
least the errors tell you what's going
wrong that's the best thing about pine
scripts and how easy it is to use and
learn so this should work theoretically
if I save now it should add a label to
the end and there we go there's our
label that's the end of this script and
this lesson to just recap let's just say
real quickly what we've done here so
first we created a boolean input we use
the input function we titled it boolean
so if I open the settings menu
we've got boolean here we can set that
to true or false and that will move the
plotting of our boolean value which is
assigned here to 1 or 0 based on whether
this boolean is true or false I'm sorry
it's this red line it's moving not this
purple line I don't know it looks like
the purple lines moving but if you can
look down on this right axis you can see
that the red line is plotting 0 and if I
turn it to true it's plotting 1 the next
thing we did was create an integer input
so if I adjust this this will move the
blue line at the top and it adjusts
scale of the right axis obviously and we
changed this value the next thing we did
was create a float input floating
decimal point input and that's plotting
the purple line so this one in the
middle so if we change this to say one
point one it will go down here above
just above our boolean input by changes
to one point zero one you can see you
can get quite a fair bit of precision
here so you can see here we've got one
two three four five decimal points on
this euro dollar so you can have one two
three four five decimal numbers after
the decimal point that's it for today's
lesson I hope you found it valuable hope
it wasn't too overwhelming just watch
this video a couple more times if it
didn't make sense to you or feel free to
leave any questions in the comment
section and I'll get back to you but
that's it for basic user inputs we'll
use this information in future videos so
make sure you practice with this in the
meantime thank you for watching guys
I'll see you in the next video have a
great week trade green good luck with
your coding take it easy guys goodbye
you
Pine Script V4 Color Gradients (& my first SIX FIGURE winning trade on Cardano!🥳)
hi traders in today's video i'm going to
be showing you how to use a new feature
that
the tradingview team recently added to
pinescript
this week i was planning to release the
seventh video in my auto view series
where i show you how to expand
the strategy script that we wrote in the
previous lesson
and add a bunch of filters to that
script but this week we had a gigantic
market crash in the crypto markets and
so i've been
very very busy managing my own money and
actively trading this week
i actually had the most profitable day
of my entire career
yesterday trading this correction on
cadano i managed to buy
very very close to the bottom
at one dollar and four cents u.s which
resulted in me having my very first
six figure profitable trading day which
was pretty exciting to say the least
i managed to sell up here at 2.37
i sold roughly half of my holdings and i
bought back in at a dollar and four
cents which is the best trade i've ever
made in my entire life
and here is the proof that on the 16th
i actually did sell half of my kadano
position
at 2.37 cents up on this week here
just really quickly the reason why i did
that was because on a five minute time
frame
uh we began making lower
lows and lower highs and so i sold on
this retracement here
and i was fully prepared to buy back in
if i was wrong and price
broke out above this previous high but
price never
did break through that previous high and
in fact
we had one of the biggest market crashes
that i've seen in crypto
in a very long time but anyway i'm not
saying all this just to brag
i'm just pointing out that over the
years i have become very very confident
in my own trading techniques and
processes and i do plan to
create a trading course later this year
demonstrating and explaining how i
analyze charts
why i picked all of these key support
and resistance levels on my chart
why i sold up here and brought back down
here and in fact i sold some more of my
position
in here at around 1.80 on a lower time
frame and
i have already bought back in to my
position down at
a dollar seventy so in a matter of two
or three days i have significantly
increased my cardano holdings
using extremely simple trading
techniques and i'm really excited to
pass on the knowledge that i've learned
over the past four or five years of
trading
and so if you're interested in learning
how i trade keep an eye out for that
course which i'll start rolling out at
some point later in the year
hopefully if i get time it's actually
really hard to find the time to make all
of these videos when i'm actively
trading my own accounts and managing my
own investments
but anyway enough about that let's get
into today's video
next week i'll pick up where i left off
in the previous auto view video
but for today we're just going to cover
an extremely simple but interesting pine
script update
that the team made where we can now work
with color gradients
so overnight the pine script team added
a new functionality or feature
to pine scripts dealing with colors so
we now have more control over the colors
we use in our scripts
it's a small change but it's a nice
change for those of you who like to have
your scripts look more aesthetically
pleasing so this will just be a quick
video
explaining the new changes and how you
can use them in your scripts so they've
added a couple of new functions
2pin script the first one is this
color.rgb function
which takes four function parameters
which is your red color green color blue
color and transparency now those of you
who are familiar with other programming
languages and have used rgb coloring
before
we'll already be familiar to this sort
of method
for generating colors so the numbers are
between 0
and 255. 0 being
no green or no red or no blue and 255
being
bright red bright green bright blue so
this is a little bit different to
hexadecimal coloring
and perhaps a little more intuitive so
i'll leave a link to this article
beneath this video the pinescript team
have included a couple of examples of
how to use
this code but we'll jump over to the
pine editor in a moment and play around
with an example so that's the first
change that made is this new color.rgb
function
the second function that they've added
is this color.from gradient
function which allows you to change the
color of something on your chart
based on where the value falls between
two
numbers so in this particular example
the script is plotting the rsi and the
closer the rsi is to 70
the more red the rsi turns and the
closer it is to 30
the more green the rsi turns and this is
all achieved
using this new from gradient function so
you can see here they're passing the rsi
value
they're passing their lower limit and
their upper limit and the two colors
they want to
calculate the gradient between and the
closer the rsi value is to 30
the closer the color is to lime green
and the closer that value is to 70
the closer the color is to red and you
can see that this allows
you to achieve some pretty cool stuff on
your charts it can really make some of
these scripts look a lot more futuristic
and modern so let's jump over to the
pine editor and
break down this particular example i've
just added a few comments
to this script to better explain what's
going on here
so this script is just plotting an rsi
standard rsi
14 length period with the price source
being the closing price
the first thing that's happening here is
we're creating a custom function
that takes two parameters one is the
color we want to work with
and the other is the transparency we
want to work with
and so later on the script is filling
the background it might be a bit hard to
see because of how
faint or transparent the coloring is but
the background of this rsi
is changing color based on the color of
the rsi so we'll come back to this
custom function in a moment
let's go over how the rsi coloring works
first because this function depends on
the rsi color being a parameter so the
first thing we do is just get the rsi
here
the second thing we do is get the color
gradient of the rsi so that's the actual
color
of this line that is plotting onto the
chart we do this using the color.from
gradient function
which takes several parameters the first
one is the value
we want to reference the second
parameter
is our bottom value so the closer this
value gets to
our bottom value the closer the color
will be to our bottom color
and the closer this value is to our top
value
the closer the color will be to this top
color
so we wanted to we could change this to
anything we could change this to
blue and color.green for example
if i save the script the gradient will
change
so this is a really cool feature that
makes it extremely simple
to basically create like a heat map kind
of
effect so let me change these back for a
moment
and move on to this custom function here
so the next thing we do is we just draw
our upper and lower limit
we're using the new color color.rgb
function
just to demonstrate how this works so
this is your red
green blue value and as you can see this
upper
limit the overbought limit has a higher
red amount than
blue and green and that makes the color
more red and once we plot our upper and
lower limit
we then fill the background between
these two limits with this color
function here which is this custom
function and we're passing
the color gradient of the rsi so the
color of our rsi line
into that custom function along with a
transparency amount which in this case
is 90 so 90
transparency then this function is
getting the red
value from our rsi color then
it's getting the green value and the
blue value and then we are rebuilding
that color using the color.rgb function
we're passing in the red value the green
value the blue value and our
transparency
here which is again 90 so there are
obviously more efficient ways to do what
the script is doing this is purely just
demonstrating
how we can use these new functions in a
practical manner
in our scripts and it's actually pretty
cool for example one use case for this
might be
a heat map like i mentioned so i have a
arvol by time script here that i created
uh many months ago
and it has a heat map color scheme here
and i had to custom code the color
gradients here so the more volume that
was printed on
a bar the brighter the color is i could
actually
add this color gradient functionality to
this script
which would mean i don't have to hard
code
the color gradients so that's it for
today's example of this latest pine
script update
if you want more information i'll leave
a link to the blog article beneath this
video
i've got a few more examples over there
a few more code examples
but that'll do it for today thanks for
watching best of luck with your trading
and coding and i'll see you in the next
lesson
you
PINE SCRIPT 75% Win Rate on a Simple Pullback Strategy
hi Traders welcome back to another video
today I want to start a new YouTube
series and this series is going to be
kind of a strategy development
investigation kind of process where I'm
going to go and find strategy ideas out
on the web on the internet I know how
dangerous that sounds but don't worry
we're going to vet these ideas using
code and running trading ideas through
the strategy tester and the whole
purpose of this series series is one I'm
doing it anyway it's something that I do
in my spare time anyway but two
hopefully it will give me a good
opportunity to show you guys demonstrate
to you guys some coding practices
techniques Concepts um that are
practical that we can build on and
hopefully this series these videos that
I'm going to start creating over the
months and probably years to come will
help inspire you guys and motivate you
guys to go and find your own trading
ideas convert them in the code adapt
them to suit your personality your
personal trading style and we can all
become better Traders together now as
mushy as that sounds that's the whole
purpose of my YouTube channel and what I
do here I'm a Trader I want to get
better at trading why not share the
journey with you guys and we can all get
better together and so without further
Ado let's get into today's video it's
going to be a bit of a longer one
compared to the recent videos I've done
but I think it's going to be extremely
valuable recently I've been going
through a mentorship program with Nick
he's an Australian Trader quite well
known if you haven't heard of him go and
check out his chat with Traders podcast
episodes they're brilliant they have
some really really powerful trading
ideas and lessons included in them I'll
leave links Below in the description
this morning I was just going through
the Forum here and reading up on um some
trading system articles that Nick Raj
particularly has posted there's other
students that post strategy ideas but
I'm always very interested in what Nick
Raj finds interesting
because he is such a great Trader I like
to try to emulate his thought process in
the markets I have very similar
philosophy on the markets to him he's
obviously far far more experienced than
I am he's been trading for decades I've
been trading for maybe 5 years actively
but this post here caught my eye this
morning so Nick posted this video here
by um JB marwood the YouTube channel JB
marwood um now I don't know anything
about Joe but I did watch this video
today and and I was really impressed by
the concepts here and so today I wanted
to convert some of these ideas into Pine
script show you guys how to build out a
simple strategy script to test an idea a
trading idea in Pine so before I get
started hopefully Joe doesn't mind me
doing this um I'm obviously giving a
shout out to his channel go and check it
out there's some really cool trading
ideas here some really powerful
stuff um today I want to go over his
simple pullback trading strategy and
convert the idea the rules into Pine and
when we're done we'll get something like
this now my results aren't 100% accurate
compared to his results but that could
be because he's using different data to
me um he's using a different back
testing software but the results are
similar enough and profitable enough to
Warrant investigating in pinescript so
before I get started I'll play a short
clip from his video just to um
demonstrate the rules that he lays out
and again when you uh finish with this
video or even now if you want to I'll
leave a link below in the description to
this video I definitely encourage you to
go and watch the whole video because
there's some really important ideas that
are laid out in this video but anyway
let me break down his rules and again
hopefully he's okay with this if you
ever see this video Joe and you you're
not happy with me um basically stealing
your work let me know and I'll take this
video down uh but I just want to share
this with my audience because I think
this is really important information and
an important template um that Traders
should be aware of Traders especially my
experience I obvious have a lot of
Traders come through my Mastery course
um there's a lot of questions I get
where Traders are over complicating
trading in a way that I feel is
unnecessary trading does not need to be
very complex in order for you to make
good money out of the markets and this
strategy right here is a good example so
let me skip forward to the rules here
and I'll just play a quick clip from
this video so now let's look at the
exact rules of this simple pullback
strategy so the buy rules first of all
we're going to want a close a above the
200 day moving
average and a close below the 10day
moving average so very basic rules the
longer term trend is the 200 day moving
average we want to be above that but we
want to close below the 10day moving
average so we've got a small pullback
within the longer term Trend now the
sell rules are extremely important here
um we're going to we're going to sell
when the close Rises back above that
10-day moving average so we're not
looking for long
term trades here we're just looking for
shortterm trades um short pullbacks and
the other rule is we will sell if we get
a 10% loss so if we get a 10% loss we're
going to exit on the next bar open okay
we need some more settings um that we
can put into our back tester um so that
we can run an accurate back test so
position size going to use just all
right I'll stop it here I don't want to
play too much of his work on my channel
uh again go and check out this video if
you're interested uh so the rules are
incredibly simple we're waiting for
price to close above the 200 day moving
average and close below the 10day SMA
simple moving average that's it buy
rules couldn't be simpler that's
something I really love about Nick R's
work um in his books and his um videos
online he's a huge advocate for using
simple and robust trading rules he goes
so far as to say that he doesn't believe
that the entry
reasons or entry criteria for strategies
is a very important aspect of a trading
system there are other aspects of a
trading system that are far more
important um such as the overall concept
of the system why it makes money um and
obviously your exit reasons are super
important and your money management risk
management um approach plays a massive
role in the profitability of any trading
system the entry criteria is one of the
least important criteria it's not not
important but it is one of the Le lesser
important aspects especially when we're
trading a robust system so this strategy
is extremely simple we're waiting for
the entry rules here and then the sell
rules are also very simple we um we're
waiting for the the candle the bar daily
bar this is a daily long early strategy
by the way on the S&P 500 ETF that's
what the strategy was designed to be
traded on but it uh in my preliminary
testing it seems to be profitable on
several other markets as well but anyway
the sell conditions are once we're in a
trade if price closes above 10day SMA uh
we exit our position we're just trying
to capture small chunks of the overall
long-term Trend um the secondary rule is
that if price declines by 10% from our
entry price or in other words we have a
10% loss on a closing basis we exit on
the next bars open uh we have a position
size of 100% of our Capital no Leverage
is used starting capital in this back
test is
$50,000 commissions is 0.005 cents per
share which is the Interactive Broker
rate and um execution is entering trades
on the next bars open which is luckily
how the training view strategy test to
work so that's really easy to emulate in
today's lesson so let's jump into the
pine editor and start coding this into
Pine code now before we do that I should
probably mention the um overall metrics
of this system according to Joe's back
testing using Amy broker which is a much
more powerful strategy tester system
than trading view but it's also much
more complex um I might consider
exploring Amy broker code in future
lessons if you guys are interested in
that I'm learning how to code in AFL the
um programming language for Amy broker
it's a it's a it's a very powerful
program but it is also much more complex
than Pine there's pros and cons to that
the pros are that you can do very
extensive statistical analysis of your
strategy results over historical data
the cons are it's expensive you need
extra data so data from a data provider
and the code is is just harder to learn
compared to Pine but anyway that's IR
relevant for today's video so the
metrics here have a decent annualized
return um but it is less than Buy and
Hold so Buy and Hold Returns on average
about 10% per year on the S&P 500 this
strategy returns about
7.6% so it's less profitable than just
simply buying and holding the Spy ETF
however look at our maximum draw down
the Max draw down of just holding the
S&P 500 ETF is 55% of your Capital so
you lose over half half your Capital by
just doing nothing and holding the ETF
but you do make about 10% per year which
is okay uh but this would make a lot of
investors uncomfortable and I'm sure a
lot of Traders and investors would sell
as you near that Max draw down and then
that will affect your annual annual
return negatively and so there's a lot
of psychological reasons why Buy and
Hold is not a good strategy despite the
fact that it does have a 10% return on
average per year whereas this system has
a slightly less return turn but look at
the max draw down 12% I would take a Max
draw down of 12% any day of the week on
any strategy that is well within my risk
tolerance and so that's kind of the idea
of this strategy it has a much better
risk adjusted return than Buy and Hold
and it also has a very high win rate 75%
win rate is pretty impressive now to
achieve that win rate it doesn't make a
lot of money on each trade so half a
percent per trade but its Edge is in its
win rate so this is a strategy where the
win rate plays a major part in its
profitability um I usually trade
strategies that are the opposite so the
risk reward profile is what accounts for
the profitability rather than the win
rate so I can trade strategies with 40
45% win rate but with a high risk reward
and that is how I tend to make my money
whereas this strategy is kind of the
opposite we're taking small wins but
very frequently anyway let's jump into
the pine editor and code all of this
into Pine all right so here we are with
a blank script a relatively blank script
all I've done here is input my default
strategy parameters so we have overlay
set to true so we're drawing over price
action our initial capital is set to
$50,000 our default quantity type for
this strategy is set to percentage of
our equity and our quantity value is set
to 100% of our account balance so on
each trade we get involved with we're
trading 100% of our account balance with
no leverage our commission type is set
to cash per contract and the commission
value is set to 0.005 cents per share
which as I mentioned earlier is
interactive brokers commission rate and
interactive brokers is probably one of
the most common if not the most common
stock trading platform and so that's why
we're using this as our default
parameters now if you've watched my
previous video on the latest update to
trading view strategy tester you'll know
that they've recently added this uh bar
magnifier setting and I said in that
video that we should always turn this on
on every single script we write now that
is true but only on scripts that have a
stop- loss and takeprofit like a fixed
stop-loss fixed takeprofit or entry
limit orders um for a strategy that
operates solely on candle closes it's
not necessary because there is no risk
of intra bar price action negatively
affecting our back testing results if
you're not sure what any of that just
meant make sure to go back and watch the
previous video on this channel about the
latest uh strategy tester update oh
leave a link to that in the description
as well so we don't need bar magnifier
for this particular strategy let's move
on to getting our user inputs so to save
time I'm just going to copy and paste
some code I've already written because
it's not important how the user input
code is written but we need several
inputs here so we need two moving
averages one is the 200 SMA the other is
a 10 SMA 10 period SM so a long-term and
a shortterm moving average the second or
third parameter here is our stoploss
percentage so by default that's set to
0.1 or 10% so if price declines 10% from
our entry we exit our position so that's
basically a fail safe stop loss so if
price never closes back above the 10
period SMA we can still exit our trade
for a loss to cut our losses short
instead of letting our losses run too
far the final inputs here are just a
start date and an end date filter these
are used for analyzing in Sample and out
of sample periods um I'm not going to go
into too much detail about statistical
analysis of our back testing results in
this video because it will make this
video way too long that's a subject that
deserves its own series let alone video
and maybe I'll cover that in the future
if you guys are interested in it I'm no
expert on that stuff I'm not very good
with mathematics to be perfectly honest
with you guys but I am learning a lot
about this stuff through Nick rager
courses and so in the future I will
probably record uh lessons on this super
important subject of deep and robust
back testing processes but for now we'll
keep things as simple as possible and
just focused on the pine code so today's
lesson is just an example a strategy
example how to code a really simple
concept into code into Pine code and
then test that theory in a simple but
quick manner the next thing we need to
do is get our indicator values so again
I'll just paste this code to save time
it's really simple we're just getting
two moving averages two smas using ta.
smma both based on the closing price
Source price source and one with a 200
one with a 10 period now I need to
replace these with our inputs so that we
can adjust these moving average length
in the settings menu uh if we want to so
now if I save my code we should have
these settings up here there they are
and they have little tool tips
explaining what each setting does this
is completely optional I'm only doing
this because this is a YouTube video
script and I want you guys to fully
understand what each user input does now
now next thing we need to do is get our
date filter so again I'll paste that
code in really simple here we're just
checking if the current Bar's time is
greater than or equal to our start date
and time and is the current Bar's time
less than or equal to our and date and
time so this allows us to filter what
trades get taken based on a date period
now we get to the juicy part where we
check our buy and sell conditions
so remember the rules are really simple
um the first thing we need to do before
I get to the rules is save our Buy price
so I'm just going to initialize a
persistent variable V variables mean
that they don't reset on every single
bar it's a float type so it's a number
type with a decimal place and it's going
to be set to Zero by default on the very
first bar on our chart and then we'll
obviously overwrite this with our Buy
price when we enter a trade that way we
can actually calculate our stop loss
that 10% decline from our Buy price so
that we can ex exit trades that go
against us now our buy condition is the
closing price greater than our ma1 which
is our long-term moving average the 200
period moving
average and is the closing price on the
current bar less than our short-term
moving average or the 10 period moving
average those are our basic entry
conditions but we also need to make sure
that we're not already involved in a
trade because this strategy does not
include pyramiding so we want to check
is our position size equal to zero if
it's equal to zero we're
flat and we want to check our date
filter so I'll throw in the date filter
here this just checks if the current bar
Falls within our two time periods and
that's it for our buy conditions um now
before I continue let's draw some pretty
colors onto the chart um and by that I
mean our moving M averages so we're
going to plot our ma1 and ma2 onto the
chart save my script and now what we're
looking
for is price
to be trading above the 200 period
moving average and close below the 10
period moving average and then we buy on
the next bars open and we sell when
price closes back above that 10 period
moving average or Price declines by 10%
that's it that's all we're looking for
so let's finish coding this out we have
our buy condition next up we need our
sell condition and that remember is just
is the closing price greater than our
short-term moving average or
ma2 let me indent these a little bit to
make it easier to read the second
condition for selling is that we are
currently involved in a trade so to
check if we're involved in a trade we
just check if position size is greater
than zero that means we have open
contracts and that's it for our basic
cell condition the next thing we need to
do is uh check our stop loss so our stop
loss remember uh I'll start with calling
it stop distance and stop distance is
going to be set to and now this is
completely optional what I'm about to do
next it does make the code a little bit
more difficult to read but it will make
our plots easier on the eyes when I'll
show you what I mean in a moment but
what I'm going to do is check is our
strategy. position size greater than
zero question mark if so if this
condition is met then we want to
calculate our Buy
price minus the closing price divided by
the closing price this will give us the
stop- loss distance as a percentage on
the current bar so this will calculate
the percentage decline from our entry so
let's say we entered on this bar here
I'll put a horizontal line there that
red line this code here will calculate
the percentage decline from this red
line on each bar on our chart on a
closing basis so each bar that closes
below this red
line um this code will calculate this
number here
6.53% or minus
6.53% this will calculate this as a
positive number so in this case it would
be 6.53%
-
6.53% and we use that to check our stop
loss but before we do that the next
thing I want to do is calculate our stop
loss price so that's going to be again
is our position size greater than zero
so are we involved in an open trade if
so we subtract our Buy price from our
Buy price multiplied by our stop
percentage so this is our stop loss
percentage Again by default it's 10% or
0.1
so this stop price will calculate again
using this red line as our Buy price the
stop price will be by default 10% below
this line so all the way down about
here at 1 uh 42 1.45
is so that's our stop loss if we entered
on this bar here our stop loss is down
here and if we never get a bar that
closes Above This short-term moving
average but price closes below this uh
red line then we exit our trade for a
loss that's our stop loss and then
finally the final thing we need to write
out here for our buy and sell conditions
is our stoploss condition itself and for
that again we check is the position size
currently greater than zero so we're
involved in an open trade and our stop
distance so the current deine on a
closing basis on a percentage basis from
our entry price
is greater than our I and I stands for
input so input stop
percent then that means price has
declined by our stop loss percentage
point and we need to exit our trade
that's it now I know I went over that
pretty quickly but I'm trying to keep
this video relatively short you can
always slow down the video or watch this
a couple more times if this went over
your head um but this is all we need to
enter and exit our trades the final
thing we need to do is actually tell the
strategy tester when to enter and when
to exit and that's actually really
simple so for enter positions we're
going to check if by whoops by condition
remember Pan's case sensitive so if by
condition is
true then we use the strategy. entry
function to enter a trade we need to
give it an ID so I'll just call this
long where long only remember this is a
long only strategy I believe this kind
of strategy is called a long beta
strategy so we're just trying to capture
long only returns out of the market and
in this case we're not even trying to
beat the market we're just trying to
beat the Market's Max draw down while
maintaining a decent return annual
return but anyway the next thing is a
direction we need to tell the strategy
tester which direction we want to enter
our trade today we're long early so we
just set that to strategy. long that's
it we're entering our trades based on
our buy condition now the next thing we
need to do is save our Buy price so that
all of this code here can actually be
calculated so so far we haven't actually
saved a Buy price we do that obviously
after we've entered a trade so we need
to put that code below our buy condition
now because we are entering on the next
bars open after the signal or the
condition is met so once our buy
condition is met the strategy tester
let's use this candle right here as an
example again so here we get a confirmed
entry we're above our 200 period moving
average we just closed below the 10
period shortterm that's our entry
criteria met on this bar that criteria
gets met but the strategy tester won't
enter our trade until the next bars open
which will be about
here so when we save our Buy price we
don't want to save the um signal candle
closing price we want to save the next
Bar's open price as our Buy price so to
do that we can just check if we had a
buy condition on the previous bar so if
buy condition on the previous bar is
true then we save our Buy price as the
current Bar's opening price and now we
have our Buy price saved and all of our
metrics here will be calculated properly
and that's it for our entry conditions
the next thing is to check our um exit
criteria to do that really simple we
just check if Cell can do
so if we have our standard takeprofit
sell condition uh which is that the
current bar closed back above the 10
period moving average so here for
example we're trading above both moving
averages and then we get a close below
the 10 period SMA we would enter long
right here we would hold our trade until
price closed back above that 10 period
moving average and then we would sell on
the next bars
open so that's what our sell condition
is but we also have our stop condition
remember so that can also be combined
with our sell condition so if we have or
sorry or if we have a sell condition or
a stop condition then we want to exit
our trade and to do that we can simply
use the strategy. close function we need
to tell it which um order to exit in
this case that's our long order so we're
exiting our entry ID of long on this
function here and to make it clear when
we exit for a profit or for our stop
loss being hit I'm going to add an
optional parameter here which is our
comment and the comment is just going to
say
exit so normally it will just say exit
if we close our trade however I'm also
going to add on a conditional statement
here that will say if and let me make
some some more room here if we had our
stop condition
met then add-on
SL equals true so this is text that's
going to display on our chart and it
just simply says stop loss equals true
so we exited our trade because our stop
loss was hit otherwise add nothing to
this string because we don't really care
we don't this will just differentiate
between trades that close back above the
10 SMA And Trades that close below our
10% decline from our entry that's it the
final thing I'm going to do here is just
overwrite our Buy price to n a this is
purely for drawing purposes we'll get to
that in a moment but now there's only
two more lines of code to write and our
script is completed and that is I'll
just copy this code over to save
time it's just two more plots so we're
going to plot our Buy price onto the
chart so that we can see when the script
bought which price it bought at and
we're going to plot our stop loss onto
the price so that we can see where the
script will exit our trade if price
declines beyond our stop- loss and I set
the offset on our stop loss to minus one
because the way we've written our code
up here it won't actually draw the stop-
loss until we've been in the trade for
one bar so we want to shift our stop
loss line back one bar so that the two
lines are drawing in sync so I'll show
you what I mean if we save my code here
hopefully this compiles without any
errors and there we go it definitely did
not so where is our error it's on line
30 I didn't finish our conditional
statements here
so for these two statements we're just
going to add na on the end so our stop
loss
distance if we are not involved in a
trade our stop distance is going to be
set to na so that we don't draw anything
onto the chart so here stop price is set
to na when we're not involved in a trade
if we don't do this um we'll have lines
drawing all over our chart even when
we're not involved in a trade we don't
want that so when we're not involved in
a trade we set our our stop price to Na
and our Buy price to Na and that way we
don't have lines drawing all over the
place so now when I save my code
hopefully this compiles there we go
there's our script completed so let's
find a good example here here's one that
I was using before as an example so
here's our entry conditions met trading
above the 200 SMA trading uh closing
below the 10 SMA on this bar we enter on
the next Bar's open we enter long and
then we hold this trade until price
closes above the 10 period SMA or we
close below our stop loss now in this
case that never happened we
actually uh we didn't hit our we tested
our stop loss we didn't close below it
uh but we did close back above the 10
SMA below our entry and so this
technically was a losing trade so here
uh This Bar closed back above the 10 SMA
we exit we sell on the next bars open
and so here we took a loss of about 3.7%
but there's our script completed and if
we open up the strategy tester here's
our metrics so we have approximately a
12% Max draw down from um 1995 until
today so I set my end filter to 2099
we're obviously nowhere near that yet
the way time's been flying this year I
feel like it won't be long before into
2099 but for now we're trading up until
the current day from 1995 and these are
our metrics so a net profit of 351
according to the trending view strategy
tester some of these metrics I feel like
the strategy tester calculates a bit
weirdly compared to what I'm used to but
anyway that's another subject for a
different day for now we have a decently
profitable strategy over 457 trades over
several years with a decent Max draw
down and a half decent return annual
return nothing spectacular but
considering that this would just be part
of a portfolio of strategies uh this is
a really cool concept to investigate
further and now before I wrap up this
video one thing that Joe speaks about in
his video at the very end is talking
about how we could expand on this
strategy by adding extra rules or
conditions to the strategy because it is
very very simple now I like to start my
strategy development with a really
simple idea or concept A arguably too
simple idea is better to start with and
then you build on that idea so right
here we have a strategy that is
profitable with a really high win rate
that's great how can we improve the
results of this strategy what's a simple
way we could improve this strategy one
way that I can see here that I thought
of earlier this morning is it doesn't
make a lot of sense to me to just exit
as soon as price closes above the 10 SMA
I prefer to have a reason to exit my
trades and it doesn't have to be a very
complex reason but I prefer it to be a
little bit more complex than simply just
closing back above a moving average and
so what if we
added here's a perfect
example look at this we we're trading
above our 200 SMA we close below our 10
period we enter long on this bars open
and then we exit on this bars open after
we close back above the SMA what is this
this is like a what 1% 2% gain 1% gain
that's pitiful considering how this
Market rallied from here so what if we
added a really simple exit reason such
as a lower close so we only exit our
trade if price is trading above the 10
SMA and we get a candle or a bar that
closes below the previous bars low and
then we exit on the next Bar's open
let's add that to our code and see how
that affects our strategy
results so for this I'm going to add a a
user input and I'll just copy some code
over to save time so here we've added a
new user input that says iore so input
lower close and it's a Boolean input
it's set to false by default and this
setting exit on Lower close simply waits
for a lower close before exiting above
our short-term moving average if I come
down to our sell condition line of code
here I can add on one more little
condition here I can check do we have
our standard exit reasons or conditions
met so did we close above our short-term
moving average while involved in an open
long trade and is iore lower close not
turned on so that would return true so
if we do not have that setting turned on
we will just exit when price closes back
above the SMA otherwise if we do have
this turned on then we want to check if
the current bars closing price is lower
than the previous bars low that's it
really simple just a couple of
characters of Code here and let's see
how it affects our bottom line so I'll
save that code let's look at this
particular trade right here if I come up
to our options or settings here bring it
over here we enter long here on this
bars open let's see what happens when I
click exit on Lower
close so now we stayed in this trade we
entered long here rather than exiting
right here we held our POS position
until we got a price action confirmation
that we should exit now it's a really
simple confirmation just a simple lower
close so this bar here closed lower than
the previous bar so we exit we sell our
long position on the next bars
open and that turned a 1% winning trade
into a 6% winning
trade and we still have our standard
stop- loss reasons so here's a here's an
example of a losing trade based on our
stop loss so exit SL equals true we
entered long on this Bar's open after a
close below the 10 period SMA while
price was technically above the
long-term moving average and then
unfortunately the market rolled over but
rather than holding on to our loser we
eventually exit our trade for
approximately I'd say this is like a
99.8% loss roughly so let's drag that
down
9.5 9.5% loss on that trade but we are
now holding our winning trades for much
longer um here's a good example of why
we use a stop loss back in the covid
crash on the market when the market took
a dive uh this is why we use stop losses
um but let's have a look here let's look
for a trade that really played out
nicely here's a good one so we enter
long here we hold all the way up to this
lower close and then we get back into
the market uh soon after that exit
when price closes back below this SMA so
this is a really cool strategy and now
here we have a
problem price did not
close uh above our SMA when we got our
lower close and so the script did not
exit our position so that's this rule
here if you wanted to you could play I'm
not going to in today's lesson I want to
wrap this up here but if you wanted to
you could negate this rule when using
the lower close rule and that way the
script would have exited up here but
because we have our prerequisite of
price being above um ma2 it waited until
here to exit that trade if you want to
that could be some homework for you I
guess to go and edit this code to
include that feature and see how that
affects your results but now let's look
at our metrics our draw Down's gone up
slightly gone up by 2% but our return
has gone up
significantly because our average trade
profit has gone up significantly whil
still maintaining a very high win rate
now I'd need to do some more testing to
make sure that I haven't missed
something and this is actually giving
out results that are accurate but the
whole point of today's video is not to
give you a strategy to go out and test
or trade but rather a concept to think
about some examples on how you can
achieve these things and yeah now I hope
this helped you better understand the
strategy development process I hope it
inspired some ideas for you to go out
and play around with and I'll wrap this
lesson up here as always the source code
will be below a link to the source code
will be below in the video description a
link to the original video by Joe that
inspired this video um basically I just
stole his trading idea and adapted it to
suit myself in pinescript but you get
the idea this is the strategy
development process basically is going
out finding cool ideas and then adapting
them to your personality your personal
preferences and then through the power
of pinescript we can really quick
quickly test this stuff and decide if
it's something that we are interested in
pursuing further this video is long
enough as it is so I'm going to wrap
this up here thanks for watching I
really appreciate it I hope you have a
fantastic weekend and I'll speak with
you in the next video take care and good
luck with your trading as always
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...
-
feb5G573mYo hey what's up traders in this video I want to revisit a system I made a few years ago during the last...
-
Bk5Okd1q10c [Music] solo there and welcome to another tutorial my name is Tamara Bakshi and this time we're going...
-
hi coders and traders this is Matthew from pine script mastery calm in today's lesson I'm gonna be addressing a questi...