all right traders welcome back to another pinescript lesson this is the second last blog post i have planned in my auto view series so if you haven't watched the previous videos make sure to go back and watch them because this lesson will build on the previous lesson where we built out the strategy script that you see on my screen right here in today's lesson we're going to add a bunch of filters to this script so we're going to add an ema filter an atr filter a time of day filter and a date filter we're also going to implement our gtd code for our limit orders our expiry code that calculates the expiry date for the limit orders we send to oanda so i hope you're excited to get started adding filters to our scripts is quite easy all we need to do is create a series of boolean true or false values and add them to our setup detection the hardest thing about implementing filters into your scripts is you need trading experience and creativity so you need to understand how the markets work so you know what an effective filter might be and then you need to have the creativity to build that filter and implement all the parameters you think might be necessary so today should be an interesting lesson for those of you who have never done this before and for those of you who have done this before maybe this lesson will inspire some new ideas for your own scripts so let's get started here i am with the script from the previous lesson nothing has been changed since that lesson yet uh before we continue i just want to address these warnings we're getting down here in the editor in case you're not sure what's going on here the first one here is that the tradingview team have implemented new functions called color.new and color.rgb these are the functions we should be using to specify the transparency of our plots because the trans parameter argument function argument will be deprecated soon which means basically made redundant and is no longer encouraged to be used in your scripts so you can ignore these warnings for now it doesn't really matter but this is a new habit i'm personally going to have to get into with my scripts is using these functions to specify the transparency of my plots not sure why they chose to do this because i thought the transparency argument was quite convenient to use but i'm sure they have their reasons and then the last two warnings here say the function two whole should be called on each calculation for consistency it is recommended to extract the call from this scope so if we go down to line 84 that is because we are calling this function two-hole within an if block so everything that occurs within this if statement will only occur will only execute if this boolean is true and that is not going to be the case on every bar on our chart which means that whatever this function does will not be consistent if it depends on bar data in order to calculate whatever it outputs in this particular case this two-hole function is only converting pips into whole numbers it doesn't depend on any actively changing data on our chart so it doesn't matter that this function is being called within this if statement if however we were calculating something within this if statement using a indicator value so for example if we needed the atr distance and we did something like this this would produce incorrect calculations because the atr function needs to be executed on every single bar on our chart in order to accurately calculate its value over the past 14 bars and so what we would need to do in this case if we were using an indicator function or any function even a custom function that depends on price data we'd need to extract the call from the scope that's what that warning means so what you would need to do is create a new variable here and then paste that over the top of this indicator call this could be anything this could be an rsi or a macd anything that or moving average anything that requires previous data you would need to extract that call from the scope so i just wanted to go over that really quickly before we move on because i feel like i'm doing you guys a disservice if i don't explain that information so the first thing i want to do today is add the gtd functionality to our script so the expiry for our limit orders we've already got the input for this our days to leave limit order so if i scroll down to just before we begin calculating our stops and targets this is where i want to calculate the expiry date for my limit order so i'm going to call this set up our gtd good till day or date border info so the first thing we need to do is get the time in milliseconds for the date we want our order to expire on so for that i'm going to create a new variable called gtd time and this is going to be set to the current bar's time plus and then we need to calculate how many milliseconds from now from the current bars time would constitute x amount of days from wherever we are so this is set to 2 by default we need to calculate two days worth of milliseconds and add that onto the current bar's time to get the expiry time and then once we have that time in milliseconds we can use a bunch of pine script inbuilt functions to convert that into a date so we could just google how many milliseconds are in a day and times that number by two but a more intuitive way might be to break down this math so we need to get how many days we want our limit order to be on the broker or exchange for we need to multiply that number by how many minutes are in a day 1440 then we need to multiply that number by how many uh seconds are in a minute which is 60 and then to convert that number into milliseconds we need to multiply that by 1000 so this will give us two days worth of milliseconds and add that onto the current bar's time in milliseconds and if you're not sure what we're working with basically pine script when working with time deals in unix format which is the number of milliseconds that have elapsed since midnight of the first of january 1970. so that's just a standard programming practice to use this unix format and this number gives us 86 million four hundred thousand milliseconds per day so that's the hard work now all we need to do is convert all this information into a date and then convert the date into a string to add to our auto view command so first we need gtd year then we need gtd month then we need gtd day of the month and then finally we need our gtd string which will convert all this data into a into text so first up gtd year we just use the inbuilt function year and we pass our gtd time into that and that will retrieve the year from this unix timestamp same with the month gtd time and same with the day but for here we need to use day of month gtd i'll just keep doing that gtd time it's hard to type around my microphone sometimes i need to uh i need to work on that so now we have all the information we need to calculate our date it's time to convert that into a string so for this we need to specify our order view parameter out the syntax for specifying this command which is dt or date slash time and then we need to add and convert these numbers to strings so that the script will compile first we need to add the format for this is the year first and then we need to add a hyphen and then two string again and then the second parameter is the month and again another hyphen and then the final parameter is our gtd day of month so this would give us the current time of today plus two days worth of milliseconds so whatever time it is right now this string here will be set to the date of two days from now and that's it really all we need to do now is add this string to our order view parameter list here and you can add it in anywhere i personally added on at the very end so we just add a new string here and then for this we have already put in our date time parameter here syntax command and now we can just add our gtd string variable here but we need to check if the user is actually using a limit order before we just pass a two day expiry because they might not have this turned on and they don't want this number to be used at all so the way we check that is we use a conditional statement and we want to check is the gtd order not equal to zero so the user has set the days to leave limit order to something other than zero and have they turned on the limit order checkbox here so if the user turns this off and the script detects a setup on the current bar then a market order will be sent to oanda to buy or sell at market with our stops and targets and we'll pay the spread if the user turns this on but sets this to zero then the script will send a limit order command to oanda at the closing price of our setup and our stops and targets the same as the market order except that the limit order will stay on our broker indefinitely for whatever the maximum time is and then finally if the user changes this number to something other than zero so if you set this to zero this disables the expiry date if you set it to a positive number this is how many days we want our limit order to stay active so now the final thing is to check if this condition is true then we want to pass our gtd string to the end of our alert syntax otherwise we just want to pass nothing just a blank string then we need to add a comma on the end here we can copy this line of code and paste it to our short trade command as well since this information applies to both long and short trades so now we can save the script and we have a error uh let me check what that is 93 plus i forgot to get rid of this comma here at the end of ftp and i probably did the same there yep so now the script should compile because remember all of these parameters belong to all of these arguments for this alert message parameter is just one long string broken up by concatenations or these plus signs and so we need to add the comma at the very end of all of these lines which is why i got an error just then so the script is now compiling everything's working fine we have added expiries to our limit orders so if we come up to the settings menu if we set this up and i leave this as it is and i come up and set an alert select the script and select alert function calls only if i were to click create now then next time a setup is detected the script will send a limit order with a two-day expiry to oanda to enter into the position at a good price ignoring the spread so obviously this is not trading advice i'm not encouraging you to go and trade this script it's not that profitable anyway uh because it is a daily chart strategy and it only works on forex and it only works on a handful of forex pairs it's not an extremely profitable script but it does work on some pairs as you can see here the 57 win rate with a one to one risk reward is profitable and we can bump this up as high as 1.4 and still have a 50 win rate so it is a profitable script but 184 trades from the year what 2000 or something is not a lot of trades so even though it's profitable i wouldn't suggest trading this script or if you do trade this script it should really be part of a wider portfolio of multiple strategies but i'm not allowed to give trading advice because i don't know your risk preferences your risk tolerance i don't know your financial situation your trading experience all of that so none of this is trading advice this is all for example purposes but in saying that i am using this script myself in my own trading and so far it has been working just fine one thing to note is you might want to change the day days to leave limit order to three so that if you get a signal on a friday and there's a long weekend or something you can still get filled on the monday or tuesday or even four four days four or five days on a daily chart strategy is not an unreasonable amount of time to leave a limit order on your chart to get filled by price action if we were trading a 15-minute chart or something then yeah maybe three days would be far too long remember the purpose of having this gtd order is to prevent the script from leaving a position let's say for example the script detected a short trade here but price action just fell from here all the way down to our target and never filled our limit order we don't want the order to stay on our chart any longer than necessary to give the limit order time to be filled because otherwise if this scenario were to unfold we could end up getting filled after the trade's already played out hit our take profit and then it might come up and stop us out and then we just took a loss on a trade that does not meet our trading strategies rules because it's already played out and we've missed it so that's the purpose of having an expiry on limit orders we use limit orders to mitigate the issue of spread but then we use the expiry to mitigate the issue of leaving our limit orders on for too long and then finally before i move on to the filter section of today's lesson it's worth noting that you can change this to something like hours let's say you wanted to leave a limit order that only remains active for one hour you could simply change this to sixty thousand and this would add sixty thousand milliseconds or one hour to the current time and one hour from the time that your order is sent to oanda it will expire so this particular script is designed and optimized to be traded on the daily chart so this approach doesn't really make sense if you were using autoview to automate a script that trades a lower time frame then that is how you would add a limit order with an expiry that only lasts a few minutes or a few hours but to keep today's lesson short we'll leave that there and we'll move on to the next section of this lesson which is adding a couple of filters to our script to hopefully optimize our trading setup accuracy or quality so let's come up to the top here because we need to add a bunch of new user inputs i'm going to keep these new inputs separate from the existing ones just to make the changes we're making to the script a little easier to read so i'm going to create a new comment here called filter settings and the first setting we're going to create is an atr filter now these are filters i already use in my existing scripts so i'm just going to copy and paste the inputs for these particular filters just to save time because you don't need to sit here and watch me type out 15 lines of inputs you should already know by now how inputs work if you've watched any of my previous videos so the first inputs we're working with here are our atr minimum filter size and atr maximum filter size and these are just float inputs with a default value for the minimum of 0.0 and for the maximum of 3.0 so the minimum atr filter means that the current bar the size of the current bar from its high to as low must be at least this many times the atr so by default it's essentially disabled because zero times anything is zero and so any bar size will meet this condition by default the second filter here though is set to three so if the bar size is three times the value of the atr then the setup will be ignored because that bar is far too large to enter on and this stops the script from entering on like flash crash candles like this one if we were to enter long on this bar with a stop loss below this low and a target up here i mean we could be in this trade literally for years and so that's the purpose of having an atr filter in our script so if i save this script now we should have two new inputs up here here they are down the bottom in their own filter section and now let's add this filter to the script so first we need to check atr filter and we need to check the atr minimum filter and the atr maximum filter so for this we need to calculate the candle size in pips so we just subtract the low from the high and that will give us the size and pips of all the bars on our chart and we need to compare this is this number greater than or equal to our atr min filter size multiplied by the current atr value if this is true then the candle size exceeds our minimum filter size and this is a valid setup or if atr min filter size is set to 0.0 then the user has disabled this filter and this min filter boolean will also return true and if either of these conditions are not met it will return false and the setup will not be taken we need to do the same for our max so the high minus the low needs to be less than or equal to our atr max filter size multiplied by the current atr or the user must have set our atr max filter size to 0.0 now we simply add these two filter checks to the setup detection code but before we do that because we are adding multiple filters to this script i'm going to preemptively set up a few variables where we can combine all of our filters for long and short trades so here i'll just say merge filters and we'll have our long filters and our short filters but first let's merge our two atr filters so atr filter is going to be atr min filter and atr max filter so we need both of our filters to pass their checks in order for this to be true and we can paste that into our long and short filters now if we come down to our valid hammer and valid star setups and add on the end here a hammer candle is a long setup so we need to check our long filters and the opposite for our short trades we want to check our short filters now we can save the script make sure everything compiles which it should and there we go so let's play around with these settings make sure they work let's set the minimum atr filter to three that should remove all of the setups on our chart because an atr or a candle size greater than three times the atr is very rare on the daily chart so that's working let's change our maximum atr filter to one and see what that does there we go that changes the setups that are detected to only very small candles and you can see how that affects your win rate and your trade quantity and all of that and that's the point of these filters so that we can play around with them and see how they affect our win rate okay so that's our atr filter let's move on to the next filter i want to add which is an ema filter so for this i'm going to comment this as ema filter and we need to get an ema filter length and again i'll just copy and paste this over to save time this input is just getting an integer input by default it's set to zero and that means that this filter is disabled you could add a checkbox like this for these filters but i find that just setting them to zero to disable them reduces interface clutter so that's why i take this approach so this will be our ema length for this filter so next up let's check ema filter so for this we need to get an ema value and first we need to check is ema filter length set to zero if so then we don't want to do anything we want to set ema to na or null otherwise we want to get the current ema based on the closing price and pass in our ema filter length as the ema period length for calculating this moving average so now we have our ema variable or value we can check our ema long and short filters and for this it's going to be extremely simple while price is trading above the ema we will only look for long trades and when price trades below the ema we will only look for short trades or star candles so for that we need to create two new variables ema long filter so if our ema filter length is set to zero then our ema filter is disabled and ema long filter will return true so we want all of our filters to return true in order to have a valid setup so this will return true if the user has turned ema filter off or left it disabled or if they haven't set email length to zero we want to check if the current closing price is greater than the ema value and the ema value is not n a so remember when dealing with indicator values on our charts it's important to check that the ema has been calculated so 50 ema for example on our chart needs 50 bars to plot onto this chart before it can start calculating its values and so if we don't add this check in here to make sure that the ema has a value that can mess with how the script detects our filters and if you remember from the previous lesson i went over that when we added our atr na check so that's our ema long filter check next we need our ema short filter which is going to be the same sort of thing we need to check has the user left ema filter off or is the closing price of the current bar less than the current ema value and the ema value is not n a just to make sure this is working we can add a visual check here we can add a plot that checks is the ema filter length equal to zero if so we want to plot nothing otherwise we want to plot our ema value and then we can change the color based on whether price is above the ema so the if price is above the ema we can set the color to green otherwise we can set it to red and then we can title this ema filter all right so now if i save the script we should have an ema plotting onto our chart when we specify an ema length in the settings menu so there we go script is loaded let's change our ema length to let's do 50 and now we have a 50 ema plotting onto the chart changing color based on whether price is above or below it the last thing we need to do is add this same check to our setup detection and the purpose of this i don't know if it will increase the accuracy of the script or not but the purpose of this is to stop taking short trades when price is trading to the upside all of these filters are just for example purposes so it's possible that some of these filters we add may decrease the accuracy of the script but that's okay this is all for example purposes and that's why i'm leaving the filters off by default so now if we come down to our long filters we can add and ema long filter and add and ema short filter to our short filters save the script and then we can check to see if the script will still take the short trade if we put the ema filter onto 50 5 0 okay and that trade goes away and the accuracy of the script has actually increased a little bit i think our trade quantity has decreased but the win rate has gone up just slightly 57 percent so that's interesting something to play around with uh 10 ema 20 ema 20 ema actually produces a 61 win rate over as still a decent sample size being that this is a daily chart that's pretty cool so there's a successful ema filter added to the chart and just because i like to keep my scripts tidy i'm going to move this plot down to the end here i'll just paste it under draw trade data and come back up and we'll add our next filter which is going to be a date filter so date filter i'll copy these inputs over yet again so these inputs are getting a input.time data type which is a timestamp and you can see here that we've passed two default time stamps between 1st of january 2000 and 1st of january 2099. and so by default the script will only take trades between these two dates you could change this if you wanted to something like 1000 to include all of price history on any market you load the script onto and then if you want to fine tune your start and end date you can do that in the settings menu so let's come down to our ema filter and add on our date filter underneath there and for this all we need to do is add a new boolean called date filter and this one is the easiest filter of all all we need to do is check if the current bar's time its unix timestamp falls between our start time and our end time so is the current bar's millisecond unix timestamp greater than or equal to our start time timestamp and is the time of the current bar less than or equal to our end time timestamp so now if i copy this boolean onto the end of our long and short filters we have now added a date filter to our script and so if i come up to the settings menu and we change this to 2000 and let's go 20 click ok if i zoom out you can see that the script is no longer taking any trades that fall between 1st of january 2020 and we can see how these strategy performed over certain time periods so for example we could see how it performed during the 2008 financial crisis so between 2007 2009 uh it still had a decent win rate 51 1.4 profit factor so that's the purpose of a date filter it's useful for back testing your script and just seeing how it performed during certain periods of time and then there's one more filter i want to add to the script which is a time filter now this particular filter is not particularly relevant to the script because as i mentioned earlier this is intended to be a daily chart trading strategy so having a time filter is kind of pointless for the script but i figured while we're here i might as well show you guys how to do this because it's almost as easy as making the date filter so we might as well do it while we're here just so that you guys can go and play around with this in your own scripts in your own time so i'm going to copy these filters as well to save time and we're getting two variables here from the user the first is our time session this is the time session to ignore trades and it uses a type of input.session and the second input is just a boolean checkbox that determines whether or not we actually use the time session filter because there is no way to set this to zero like we can with the ema filter or the atr filter so now we have our session we want to check if the current bar's time falls within this session and if it does we don't want to take any trades so to do that let's come down to our date filter and add in our check time filter code so for this i like to create a custom function called is in session and this custom function is only going to take one input parameter or argument and i'm just going to call this one sess short for session and then we need to declare or define the function and what it does using the equals and then right arrow operator and this function is going to check if the time of our time frame dot period in this current session is not n a so there's a bit going on here let me just break this down so the first thing we're doing is getting the time of the current bar for the specified resolution and session so we've passed in our session which by default is between 6 am and 9 15 am which happens to be when the spread in my place in the world is terrible i don't like trading between 6 am and quarter past nine because my spread is as high as 10 times what it normally is that is why i'm using that session as the default and so we're checking is the current bars time frame within this session that we have specified if it isn't then this time function will return n a and our n a function check will return true and so this block of code here will be true if the current bar's time does not fall within the session we've specified so we're checking if this is equal to false that means that the current bar is within our specified session and is in session will return true otherwise if it's not within that time period it will return false and now we have our time filter so before we use the time filter we need to check i'm going to create a new boolean variable here called time filter and we're going to check is use time filter turned on and are we not in the session that we want to be in or has the user turned off use time filter so if use time filter is not on time filter will return true however if use time filter is turned on and the current bar is not within the session that we've specified and of course we need to pass our session into this function which is this variable here time session this user input paste that into our is in session function call now if i save the script this time filter will return true if the user has turned on the time filter and the bar is not within the session they've specified so let me add on to the end of our filters and time filter and now if i save the script if we come up to the settings menu we now have this new filter at the end of the list so if i turn this on then the script will not take trades within this time period so that's it the script is pretty much completed now just before we wrap things up i will add a quick visual indication for our filters so in this case i want to change the background color of our chart to red if any of our filters are not met so for this i'm going to use the bg color function and i'm going to set the color to and then i want to check is use time filter turned on and are we in the session that we have specified or do we not meet the requirements for our date filter or do we not meet the requirements for our atr filter the only thing i'm not going to check here is our ema filter because if prices above the ema we're looking for longs and if it's below looking for shorts if any of these filters are not met then we're not looking for any trades so i want to set the background color of my chart to red when any of these filters are not met or not satisfied so that we know what the script is doing so i add my conditional check here if any of these are true then we want to set the background color to red otherwise we want to set it to nothing leave it as it is i want to set the transparency to 70 percent and i'll title this filter color and close that off and now if i say the script hopefully that should compile without any problems and our script is now finally completed so let's play around with some of these filters first of all let's check the time filter let me go down to a 15 minute chart and turn on our time session filter now you can see that the background of the chart goes red between 6 a.m and 9 a.m and you can see here that this bar here is obviously greater than three times the atr and that's why the background color turned red for that bar so if this had been a valid trading pattern we would not have entered it because it is invalidated by our atr filter the script is completed this will not be profitable it was highly unlikely to be profitable on lower time frames maybe the higher time frames like 4 hour and above i'm barely about break even but the daily chart is where this particular strategy is the strongest because of the concept we're trading here hammer and shooting star candles are far more reliable on the higher time frames than the lower time frames where there's a lot of noise so that will about do it for today's video hope you found that interesting a link to the source code will be below this video in the video description the next lesson in this series is going to show you how to set up a virtual server private server through something like amazon web services is probably what i'll use so that you can run auto view in your browser 24 7 without needing to leave your computer on if that's not an option for you and then i'll wrap up the series there any future lessons i create on this subject will be going up in the pine script mastery course and i actually want to move on to different topics on this youtube channel in the months to come i'll still be doing pine script videos but just less frequently i'm planning to move over to more general trading related videos make sure to hit the subscribe button i'll be back real soon with a new lesson but if you can't wait for that there's plenty of lessons over at panscriptmastery.com including my free basics course and the panscript mastery course which now has over 100 lessons and 14 hours of content covering pinescript in great detail and of course if you want to steal all of my source code for every script i've ever written over the past four years there is my indicators and strategies course which contains the source code and detailed lessons several hours of video lessons breaking down the source code to all of my most popular scripts take care thanks for watching to the end and i will be back real soon good luck with your trading and thanks for being a part of this community
Wednesday, May 29, 2024
Sunday, May 26, 2024
How to use FOR LOOPS in Pine Script • Pine Script [OUTDATED V4] Tutorial
hey traders in today's pine script lesson we are going to be covering for loops and for today's lesson i'm going to be creating a positive bars percentage oscillator so this indicator you see on my chart right now is counting all of the positive or bullish bars over the past 10 bars and you can change the look back period to whatever you want and then it's drawing this blue line as a percentage of how many of those bars were bullish and then we have our 80 limit and our 30 limit similar to an rsi oscillator and so this indicator is going to oscillate between 0 and 100 and in order to achieve this functionality we're going to be using for loops so let's get into the pine script editor get started but before we begin if you have any content suggestions any pine script subjects you want me to cover please suggest them in the comments section and you guys can vote by using the like button on the comment and i'm going to pick whichever comment has the highest votes to cover in the next video anyway let's get started alright so here i am with a blank script absolutely nothing has been changed except the title of my script uh the first thing we need to do with this particular script is set overlay to false now you don't need to do this overlay is set to false by default but it's just a habit i like to get into i like to specify my overlay parameter in my study annotation function just to make it clear what this code does if you're not reading it while it's attached to your chart we're also going to change one more parameter here which i don't think we've covered in previous youtube videos and that is our decimal precision so this is how many decimal places will show in your indicators value title so by default this is set to whatever the precision of your chart is so in this case i'm on a 4x pair which has five decimal places after the decimal place we don't need that many for this particular script so i'm going to set our precision today to 2. if i save the script you'll notice now that our indicator value rounds to two numbers our decimal value so that's it for our study annotation function our script is ready to get started and the first thing we need to do is as always get our user input so get user input and the only input we need for this script is our look back period our upper limit and our lower limit so we need to look back an upper limit and a lower limit and these are going to look something like this we need to use the input function with the title of look back oops a type of integer input.integer and a default value of 10. so by default we're going to be looking back 10 bars to calculate our positive bar value and now to save time i'm going to copy this line of code and paste it in here twice change this to upper limit and change the default value to 80. this one will be lower limit and i'll change this value to 20 and i need to space that out so there's our user inputs look back upper limit lower limit so the next step is to use this information in a for loop to count how many bars were positive over our look back period so to do that we need to count past x positive bars where x equals our look back period let me make more space here so the first thing we need to do before we start our for loop is declare a positive bars counter variable so this is going to be what counts how many positive bars were over our look back period and next we use our for loop so a for loop for anyone who is unfamiliar with them is just a loop of code similar to an if statement you indent your code here and you tell this for loop how many times to loop this code this xxx code whatever this expression is will be looped for however many times you tell pinescript to execute this for loop so a for loop works like this you need to declare your loop variable which a common programming practice is to just call it i so for i is set to and then you set your number so you could say here 0 and then 2 10 and what that would do is count from the current bar on your chart back 10 bars and whatever code you put underneath this for loop will be executed 10 times and you can use this i variable to reference historical bars within your for loop so technically this for loop would loop 11 times reason for that is it would loop as zero then one two three four all the way up to ten with zero counting as a cycle a loop cycle so it's important to take that into consideration so when we're looping up to our look back amount we need to minus one from that amount so zero to nine would count from the current bar back nine bars which is technically 10 bars because 0 is counted as an index that's what i stands for i is short for index the for loops index because the most common practice for a for loop is to use it to reference array variables or values contained within a list in this particular case we're using this index value to reference historical bars so our for loop is going to look something like this if the closing price of this current index of our loop so it will start off as zero which is the current bar on our chart if the current bar's closing price is greater than the current bar's opening price that means we have a bullish candle our close is higher than our open that's a positive bar so once we detect a positive bar we need to add it to our positive bars counter now remember when you're assigning an existing variable a new value you need to use the colon equals operator so this is assigning this initializes positive bars of zero this operator assigns positive bars and then we want to reference whatever the current positive bars value is and add one to it and so that's really it for our for loop um if this is confusing to you which it definitely will be if you're new to programming it usually takes new traders a little while to wrap their heads around things like for loops and conditional statements and complex things with lots of moving parts like that but i promise you if you practice with this code play around with it it'll make perfect sense to you for example you could compare different conditions to your bullish candles you could check if the past x amount of bars were above a moving average for example so if you're a little bit stumped by this i encourage you to copy this block of code here and play around with it in your pine editor until it clicks for you but anyway before we move on there's one more functionality or feature to this for loop that i should mention and that is that you don't have to loop by increments of one so looping from zero to look back minus one means we're looping from zero to nine if the user hasn't changed the default value of our look back so we're looping from zero to nine by increments of one so the loop will go zero one two three four five blah blah blah you can change that if you want to by using the buy operator so if i were to set this to two then this for loop would go from zero to two to four to six to eight and skip every odd bar and you can make this any number you want so that's important to mention by default it's looks like this so the for loop will operate like this it will function like this we're counting from zero to our look back minus one by increments of one and the final thing i should mention with a for loop that's important to know is that you can count backwards as well so we could swap these operators and now we'll be counting from nine down to zero so nine eight seven six five etc so these four loops are really powerful once you master them you can achieve some really cool stuff with a for loop but anyway let's leave this as it was we'll get rid of buy one because it's unnecessary and this code here should work just fine so the next thing we need to do before we start drawing this information to the chart is convert our positive bars into a percentage so if the user changes the look back period of something like 15 then we want to divide our positive bars by that look back period in order to get our positive bars over our look back period as a percentage so if the reading says 60 then that means that 60 of the bars over our look back period were bullish so to do that we need to get positive bars as a percentage and to do that we need to declare a new variable called positive bars percent and that is going to be initialized or set to our positive bars divided by our look back period multiplied by 100 to turn it into a whole number percentage and now we can change our plot from the default plotting of the closing price to our positive bars percentage i'm going to set the color to blue and i'm going to title this positive bars percent so that our users can come up into the settings menu and change the style of this plot if they want to now if i save the script the magic should happen and there we have it so our script is now calculating our positive bars over the past 10 bars looking left as a percentage between 0 and 100 pretty cool but we're not done yet we need to add a couple more plots to this indicator so that we can actually see the upper and lower limits so remember that all plots are plotted in order to your chart so if you want something to draw over the top of another thing you need to plot that first so in the case of our upper and lower limits our overbought and oversold lines if you will which is what they would be on a an rsi oscillator we're basically copying that style of uh indicator appearance so what we want to happen is we want our indicator value or our blue line here to draw over the top of our upper and lower limit and so what we need to do is plot our upper and lower limit before we plot our positive bars as a line and to do this we're going to use a different technique to the plot we're going to use h lines which are short for horizontal lines and this parameter or this function takes a few parameters um the only one we need to use is price color and title but you can play around with the others in your own time if you want to so the first thing we're doing is drawing our upper limit i'm going to color this color.orange and i'm going to give it a title of upper limit so that it'll appear in our style menu with the title this just cleans up our user interface it makes the user experience a little better for anyone who wants to adjust these settings so we're done now with our upper and lower limit if i save the script we'll be having an orange line drawn at 80 and 20. we can change this in the settings if we wanted to go to inputs change this to 70 and 30. if you wanted to but one last thing i want to do with this indicator is i want to draw our 0 and 100 level on the chart so that we can actually see them so that when these values get to extremes we have something to reference it against and this will make sense in a second so i'm going to say draw top and bottom of oscillator and for this we're going to plot just a flat whole number 100 i'm going to give this a color of color.black i'm going to set it it's editable parameter to false because we don't want the user to be able to change the style of this this is an optional thing to do but i thought while we're here i might as well show you how to do this so we're setting editable to false and we're going to title it top now i can copy this line of code paste it there change our plot value to 0 change our title to bottom now if i save the script we'll be having a solid black line drawing at 100 and at zero so now we have a reference point for our oscillator we have our upper and lower limit and our maximum extremes and because we've set editable to false if i come up into the style menu you'll notice that the these two plots are not listed under our style menu now again that's an optional thing to do you don't need to do that if you wanted to be able to change these lines you could leave editable the editable parameter out of this plot function but for future reference if you do want to disable the style of a plot in your indicator that's how you do it and then finally the script is pretty much done now but while we're here we might as well add alert functionality to this script because it's not difficult to do and what our alerts are going to do is when our positive bars percentage line this blue line exceeds our upper or lower limit it will trigger an alert if the user is set one so let's do that now open up the pine editor again i'm going to add another comment here it just says trigger alerts and we're going to put in here two alert conditions so copy that paste that there one of these alert conditions is going to be for our upper limit and one is for our lower limit so for this we need to say does the current positive bars percent value exceed is it greater than or equal to our upper limit value if it is then we want to trigger our alert and for this i'm going to um just keep the title short i'm going to call it pb short for positive bars and this first alert is going to be a positive one so the plus sign means it's exceeded our upper limit i'll add alert on the end of that and we're going to set our message to positive bars has exceeded upper limit and now i'm going to show you how to do one last cool little trick which is adding a plot value to your alert messages so when this alert triggers we're also going to use this special placeholder plot underscore 0 within two curly brackets so you can see that there what this is doing is it's going to be replaced by the pine script engine by the trading view platform when this alert triggers this plot underscore 0 will be replaced with the value of the very first plot in our script which is this one here so h lines don't count as plots so plot underscore zero remember everything in programming starts from zero not one so our very first plot number zero is this plot here positive bars percent which is our blue line or our blue value here so this code that we've just written is going to add our current positive bars percentage to our alert message so that when you get your email or your push notification or however you set up your alert you can see at a glance exactly what our positive bars percentage value is before you even open up your chart now this is also very useful for sending or relaying script data to third-party apis so you can automate trade execution by sending your plots to a third party using this technique so if this was a stop loss price or a take profit price or an order size you could relay that info to a third party but i'm not going to go over that today obviously because that is far too advanced for this particular lesson i might cover that stuff in the future if there's enough interest in that in the youtube comments so leave a comment below if you have a suggestion that you'd like me to cover i do take them into consideration when i'm planning content for this channel and i love getting feedback from you guys it's great i'm really enjoying seeing so many traders improve their scripting and their trading as a result it's really really great to see i know first hand just how much pine script has helped my trading and i'm really excited to be able to share my knowledge with you guys here but anyway let's wrap this lesson up by writing our final condition which will be positive bars as a percentage is less than or equal to our lower limit if this condition is met then our alert will be fired uh or triggered i'm going to give this a title of pb minus sign alert and it's going to be it's going to have a message of positive bars has exceeded lower limit and then again we'll write in plot underscore 0 in curly brackets and our script is now done we have completed our positive bars oscillator script and so our script is now plotting the positive bars over our look back period as a percentage and we can set alerts on this information so if you come up to your alert interface and you select under condition you select our script here are our two alerts pb positive and pb negative if you were to create this positive alert then you will be triggered depending on what options you select your alert will be triggered when this blue line exceeds our upper limit and the message for our alert will contain our blue lines value and that's it we are done the last thing i should do is just demonstrate how we can play around with this script now so we could change this look back period to 15 for example and now you'll notice that our our positive bars percentage has changed from whole numbers to having two decimal places we don't really need more than two decimal places for an oscillator like this that's why we set our precision to 2 up here and the script is functioning as expected on all time frames it doesn't matter what time frame you're on doesn't matter what your look back period is you could set this to three you could set this to 100 change our upper and lower limits to 60 and 40 and there you have it we have a functioning positive bars oscillator indicator all achieved using our for loop so i hope you found this lesson interesting and helpful in your programming and trading journey if you did find this lesson interesting and helpful then i'd love it if you could leave a comment letting me know how it helped you and most importantly what you'd like to see next and also while you're there please hit the like button hit the subscribe button if you haven't already i'll be back soon with plenty more free content like this i'm trying to get into a regular routine of releasing these videos every fortnight but if you don't want to wait for that or you want to learn more about panscript more rapidly and shortcut your learning process dramatically then head over to pinescriptmastery.com where you'll find all of my courses covering pine scripts i have a completely free basics course over there that covers the fundamentals of pine script i have the pine script mastery course which has 85 lessons and a few dozen hours of content covering pine script in great detail imparting nearly everything i know about pinescript to you we've had several graduates from the pine script mastery course go on to create great things which i'm really proud of and then finally i've just recently released the planscript mentorship program where i mentor you in your pinescript journey and produce ongoing content each and every month and it's a monthly subscription fee if you sign up to a year worth of the mentorship program you get all of my courses included for 50 off but that's it for today's lesson thanks for hanging out with me and i'll see you in the next one good luck with your trading good luck with your coding and take care be safe out there see you in the next one [Music] you
Tracking the Ichimoku Base Line in PINE SCRIPT
hey what's up traders welcome back to another lesson in this lesson [Music] hey what's up traders welcome back to another lesson sorry this one is a little bit later than usual i was on holiday last week with my girlfriend we actually went up to noosa where the great nick raj lives got to eat at some of his recommended restaurants that he recommended on twitter recently and it was fantastic anyway we're back to work now and in this lesson here this is from the mastery course so i'm answering a question here that was asked by a student in the course and the reason i'm posting this on blog is because while it's a bit of an edge case and not everyone will want to do the sort of thing that the student wants to do in in his particular script working with the ichimoku cloud in a particular way which i'll explain in a moment i think that the techniques in this lesson can be useful especially to traders who are relatively new to panscript and still trying to wrap their head around things like tracking values after a certain condition is met detecting price patterns around certain conditions that sort of thing i think this will be a valuable lesson for you guys the next lesson i'm working on i'm hopefully going to revisit pine connector because there's been a lot of changes with the pine connector expert advisor so i do want to go back into automation and automating our scripts through plan script i want to revisit that a new and improved series on that subject but for now i hope you find this lesson interesting if you have any suggestions as always leave them in the comments section i read all the comments i can't always respond to all of them but i do check on them some are really kind some are not so kind and some are very helpful in guiding the subjects that i cover in these lessons so thank you for that thank you for your support enjoy the lesson [Music] question comes from marty i believe is how you pronounce your name sorry if i butchered that um he asks a question about the ichimoku cloud he says here as i know one of the features of using ichimoku cloud is finding potential support and resistance in the image he sent me if i drag this over can i do that yes this is the image he's talking about this is the baseline of the ichimoku cloud and his plan is to write a script in which it shows the baseline only when it is horizontal and he also wants this horizontal line to be saved into a variable that he can reference to tell whether price is above or below that horizontal line so this is actually quite a easy thing to achieve the first thing i'm going to do is throw on the ichimoku cloud inbuilt indicator from the trading view team i'm going to open this up copy and paste all this code out into a new blank script and i'll just call this delete for now since i'm not going to keep this script but you can name this whatever you want obviously and if i get rid of these two indicators and throw this on we now have the inbuilt ichimoku indicator on our charts um a couple of things i'm going to do here is i'm going to disable all of the displays here i'm not going to bother formatting this code to look nicer like i normally do just to save time because it's not really relevant hopefully you guys by now have your own style of formatting your scripts and you you know how to do that so for this sort of lesson or demonstration i'm going to turn off all of the default plots since we don't want them in this particular case if i save that code all of those lines should go away there we go we still have the background color there i'll leave that on for now just so that we know what the ichimoku cloud is doing and if you come into the settings menu and go to style you can turn all these back on if you want but they're now off by default so in order to track the baseline let me turn that one on for a moment the bass line is this uh red line you see here on my chart we want to track this line only when it's moving sideways so when it's doing this this oops sorry my phone is ringing i need to answer this one second all right i'm back sorry about that uh now i believe i was talking about tracking this line only when it's moving horizontally so when it's doing this we don't want to draw it we only want to draw it when it's going sideways and we want to track that price value as well so this is pretty easy to do all i'm going to do here is create a var persistent variable so remember var variables do not get reset on every bar so this will track the price when it's going horizontal i'm going to call it baseline saved and it's going to be set to baseline by default when it's first initialized and then i'm going to use an if statement here that says if the bass line which is our red line the inbuilt calculated donchi and whatever you say that word donchian line if this red line is not equal to its value on the previous bar that means it's moving either down or up if this value is equal to the previous bar then it's going sideways obviously so this if statement will track that all we need to do now is save our baseline saved variable so now this variable will be assigned the value of baseline and then we can say else so if the baseline is not equal to the previous baseline that means the line is moving down or up as i said and we want to set baseline saved to n a so it doesn't draw anything on the chart and so now we can plot this onto our chart just using the plot function baseline saved is the value we want to plot i'll give it a color of color dot purple and we need to make sure that we set the style whoops to plot dot style underscore line br br is short for break and that will break the line um whenever its value is not equal to the previous value so i'll show you what i mean here first of all let me title this really quick we'll call it baseline saved save my code and now we have this purple line drawing here and sorry it's first thing in the morning i'm still waiting for my coffee to kick in i have put these around in the wrong order so i'm actually tracking only when it's moving down which is the opposite of what we want so here we're saying some of you would have picked that up while i was explaining this but now if the baseline on the current bar is not equal to the baseline on the previous bar then we set baseline saved to n a or nothing otherwise if these two values are the same that means that we are going sideways or horizontal and we do save the baseline value so now if i save my code we should be getting the correct thing happening here there we go so now the purple line is only drawing when the red line is horizontal and so now i can turn off our baseline red line save my code and uh whoops what have i done i have forgotten to put in the parameter name that'll do it save the code let that load there we go so now you can see that we have a really nice support resistance kind of thing happening here and it is tracking our baseline only when it's going horizontal now as soon as this baseline changes the value changes we stop drawing a horizontal line if for whatever reason you wanted to continue drawing that line you could just get rid of this statement and make this equals and then save my code and now it's going to save that line regardless of if there's a new baseline but for now i'll leave it how it was whoops save my code and to wrap up this lesson i'm going to show you how to track your prices above or below this purple line so that too is pretty easy i can just say here is price above baseline equals is a closing price greater than baseline saved and then just to track this in an easy manner i'm going to use a background color function and we'll just say if price is above our baseline then set the color to color.green actually color.new color.green and then we need to add some transparency otherwise it'll be very bright and otherwise if price is not above if the closing price value of the current candle is not greater than our purple line then we want to set the color to color dot red with 50 transparency and that's it now if i save my code we should be getting a background color there we go it's still pretty bright but you can see that the script is tracking when price is above our purple line now because we set baseline save to n a that kind of complicates things here because what it's doing is now when our baseline is n a it's just plotting red so what we need to do here is say i'll simplify this a little bit um let's say uh price trading above bl for baseline and price trading below bl for below the baseline and what we can say here is is price above baseline and not n a baseline saved now i can copy this down here and say not so this is going to be a little bit confusing especially for those of you who are newer to pine you probably shouldn't be watching this lesson if you aren't you should go through the course as it's laid out as a lot of this information is explained throughout the course in a methodical way but what we're doing here is we're saying this is a boolean value that will only be true if price is trading above the baseline so the closing price is above our baseline saved and our baseline saved is not an a so now i can change this code here maybe to say let me cut this out this will make sense in a moment i'll have two background color functions here price trading above baseline and price trading below baseline i'll paste that in and so now when i save this code hopefully i've done this correctly and i have now what we're seeing is that when our purple line is drawing let me lower the transparency of this a bit because it's still a bit too bright so now when price is trading above this purple line and the purple line is drawing onto our chart our background turns green and this boolean value here is tracking it'll be only set to true if this condition is met so we have a baseline that's horizontal and price is above it this variable on the other hand is the opposite we must have a baseline going horizontal and price must be below that baseline and that's it that uh pretty much um if i turn off the cloud that is answering the question from marty now what you do with this information is up to you and obviously there's a million different things you could do with this you could track uh price action patterns while prices above or below this purple line um you could track tests so like here for example it's a very nice test bullish engulfing candle uh hammer candle followed by a bullish engulfing candle right off this baseline while it's moving horizontal really nice trading opportunity there you could track this sort of thing by checking um you know you could have candle pattern equals price trading above bl and low let's say previous low is lower than our baseline saved and the closing price of the current bar is greater than baseline saved that would detect a candlestick rejection off our baseline and if i use the plot shape function here and we say candle pattern color let's go style equal shape dot uh triangle up color dot green save my code that should be tracking yeah there we go i've got the thing in the wrong place uh location equals location.below bar save my code and let me lower the transparency on this too it's annoying me now well that was the opposite whoops i need to go the other way there we go so now you can see we're tracking rejections off this baseline when it's moving sideways and you could obviously do the opposite for short trades it's not perfect needs some refinement this for example isn't a rejection off the line this is a recovery back above the line but you get the idea with a few more conditions added to these checks you could detect candlestick patterns above or below or on these uh baselines in the mastery course i left this lesson off here but i'm going to expand this lesson just slightly to explain how you can better track actual rejections off these purple lines so all i did here if i scroll down to the bottom of my script let's add some white space here i added one more condition to our candle pattern bull and candle bat candle pattern bear boolean conditions so now instead of just checking if price is trading above the baseline or below the baseline we check is price trading above the baseline and was it trading above the baseline on the previous bar that gets rid of a lot of false signals so now you can see we're getting a lot more sort of accurate rejections off this purple line so whenever the purple line is going horizontally and price tests it trades above it and then gets rejected and closes back below it we get this arrow drawing above or below that candle now i'm not saying you should trade this obviously it's very rudimentary but with a bunch of additions you can detect really nice trading patterns like this for example you could check for hammer candles of this purple line you could check for bullish engulfing candles this candlestick pattern right here a long wick to the downside followed by a close in the upper third of the candle followed by a bullish engulfing candle or a bearish example in the opposite direction uh would look something like this and we're rejected to the downside sorry i don't know why i bother drawing with this tool i'm terrible at it but hopefully you get the idea that is a candlestick pattern that i love to trade in my own trading i often implement this candlestick pattern into whatever sort of market condition i'm trying to capture so for example i have my ultimate pullback indicator if i throw that on really quickly once it loads you can see that this also picks up this exact same pattern above a moving average so those are just some ideas to play around with i'll wrap the lesson up here the source code will be below with the added changes to the code to make the candlestick pattern detection a little bit more accurate and so yeah i'm going to leave this lesson here as always a link to this source code will be below in the description if you did find this lesson interesting please hit the subscribe button and all of that youtube jargon that i'm supposed to say and i'll speak with you in the next lesson don't forget to check out the mastery course if you're new to plan script i think you'll find it incredibly valuable a lot of traders have so far that's why i feel confident saying that if you sign up i'd love to have you there and i'd love to help you on your journey if not that's fine too stick around on the blogs and i'll be back soon with some more content take care and good luck with your training as always [Music] you
Saturday, May 25, 2024
Pine Script: A Profitable MEAN REVERSION STRATEGY
hey Traders welcome back to another post thanks for tuning back into my blog uh sorry for the delay between posts I was on holiday for a couple of weeks but I'm back now and I'm excited to show you guys another trading view strategy so today's strategy is a daily time frame long only mean reversion system designed for us equities that's what I originally designed this system for but it does work on all markets it's not necessarily profitable on all markets but this system should work on any Market you apply it to but when I initially designed it I have been using the Russell 2000 as my sort of in Sample data set for developing the system so the system was originally created in Amy broker as some of you may know I've been learning how to use Amy broker to back test more sophisticated systematic trading systems and this is a system I developed in Amy broker I've been testing and developing in Amy broker and I've converted the code from Amy broker's language into Pine script because I think this is a really cool system it's quite simple and it will be a great way to demonstrate some features in Pine that I haven't demonstrated yet such as using limit orders to enter positions so I haven't finished optimizing the system I haven't finished the the entire development and back testing process I'm about halfway through that process at the moment but the system is profitable at least according to my initial testing let me bring up some trading results here so we have a single run back test here on the Russell 3000 using 50 margin or leverage so I can trade double my account balance and according to a 20 position portfolio where I'm trading 10 of My Equity per position it had a roughly 20 annual return with a drawdown around 20 not fantastic numbers but also not too bad so there is definitely potential to this system has a 57 win rate and over 6 000 trades so it seems pretty robust I've done a little bit of Monte Carlo just testing on the system just to see what the distribution of results are over you know slightly randomized data sets and entry criteria that sort of thing and it seems pretty robust it definitely needs some work before I would actually put real money at risk using the system but it's in a decent enough position now that I feel comfortable sharing my idea and my code with you guys so this system was inspired by information I've learned from Nick Rogers many of you will know if you've been following my channel for a while I've been enrolled in a mentorship program with Nick for about a year now and I've learned tons and tons of incredibly valuable information from Nick if you've never heard of Nick go and check out his chat with Traders interviews they're fantastic I'll leave a link in the video description but basically this system is attempting to buy healthy stocks experiencing short-term sell-offs so right here is a perfect example of what this system is designed to capture so what we're looking at here is a 200 period EMA this is my directional bias filter so I need the market to be trading Above This long-term moving average before I even start looking for trading signals the second blue line here is a 20 period EMA so we've got two EMAs here 200 period EMA a 20 period EMA and you can see these upper and lower lines these are an ATR stretch from this middle EMA so what this is officially called is celt I can't even say it Keltner bands so kalthner is a Trader who invented this technique and we're just simply subtracting with the default settings a one ATR distance from this Central Moving average and this gives us basically volatility bands as kind of like Bollinger Bands but instead of using standard deviations we're just using the ATR I did try using Bollinger Bands with this system when I initially started testing the idea and from my testing Kelton abandons just seem to work better so I've stuck with them while developing the system I'm also not a mathematical minded person so I find an ATR and moving averages just easy to wrap my head around than standard deviations and all that sort of stuff that I'm still admittedly learning and I'm not that proficient with my understanding of that sort of thing I come from a musician background so when it comes to me developing trading systems I'd like to keep it simple so that my dumb mind can wrap my head around what I'm doing but the good news is for people like me you don't need to be that advanced with your systems in order to develop profitable systems and strategies so anyway we're using Keltner bands one ATR stretch above and below this Central Moving average the upper band I don't we use in my system I'm only drawing it there just for reference purposes that's why it's quite faint it's like a 50 transparent gray color what we really are focusing on is this middle blue band this green band and this red moving average long-term filter and what I want to happen before I enter a trade is I want price action to be trading below this lower band this green band so I want price to be trading away from the mean and I Define the mean in this system as this 20 period short-term moving average so long as the market is trading Above This longer term moving average I consider this an upward trending stock and when it trades below this lower band I'm hoping for it to revert to the mean which is our Central Moving average but I don't just buy because price has closed below this lower band I tried testing that it didn't seem very profitable so what I've done this is a technique I've learned from Nick is I'm using an ATR stretch to place a limit order to enter my positions so as soon as price closes below this lower band while trading above the long-term moving average I place a buy limit order one ATR from the low of that bar so that on the next day if price action trades down and hits that limit order I enter long on this Market this stock and so you can see here that we generated a buy limit order for this day here on that next day did not get filled price did not trade that low but then on that following day we generated another buy limit order one ETR from the low and on that next trading day it did in fact get filled by a price we went long and then my exit criteria is either if price continues lower and closes below this 200 EMA if that happens I get out and that's my stop loss if that does not happen what I wait for is price to revert to the mean and the way I Define that is by having the high of a daily bar touch our 20 EMA so on this bar here price touched the Central Moving average and on the next bars open we exit our position for a small but reasonable profit and if you do that over and over again over 84 trades on this particular Market Southwest Airlines we can generate a decent return so we've got a thousand percent return over however many years of trading this stock and a 26 Max drawdown not too bad that's a comfortable drawdown for me and keep in mind that this is trading 100 of our equity on this Market what I would normally do and what I'm doing in Amy broker when I'm developing the system is I would trade this on a portfolio of stocks so I would trade 10 to 20 stocks at a time that would be my Max open position count and so these numbers would reflect on a fraction of My overall account balance so maybe I would have about a hundred thousand dollars invested in the system um so I would have a 26 Max drawdown on this Market on ten thousand dollars worth of My overall equity and these numbers would be sort of averaged down across multiple markets and so this would just be a micro cosm of the overall system the overall portfolio so keep all of that in mind so now that we understand what the system is doing let's break down the source code it's not too complicated and then I'll give you some final thoughts at the end of the video okay so let's get coding what I have here is a essentially blank strategy script I've just titled it ATR reversion system we've got overlay set to true so that we're drawing over price action and not into our own indicator box we have initial Capital set to 100 000 US dollars I believe um base currency default I might actually Define my base currency here as well and I've already forgotten which parameter that is currency I guess currency equals currency dot USD and by the way the trading view team have released a really cool update to the Pine editor and now the editor runs on the same infrastructure software as Microsoft Visual Studio if you've ever used that that's quite a quite a um fun editing program which I don't often use the word fun to describe a text editor but it's really convenient really efficient so now the pine editor has some really cool features that we'll go over in today's video as well nothing major has changed but we have some quality of life improvements and things that make coding more efficient we'll cover some of those throughout the video so we have overly set to True our base currency is US Dollars our initial Capital 100 000 our default quantity type is a percentage of equity this is our position sizing our default position sizing type is a percent of our overall account balance and the default value or position size is 100 of our account balance so the very first trade we take will invest one hundred thousand dollars into that trade and then someone the commission type is set to commission cash per order so when we buy I pay 9.95 when I sell I pay a flat rate of 9.95 that's the self-wealth broker fees I use self wealth to operate some of my Equity trading systems I also use Interactive Broker and they operate a little bit differently they use a it's like a like different brackets depending on your position sizing so I think the default one I normally pay is about 0.005 cents per share but for today's lesson I'm going to keep things simple we're just going to go with a flat commission rate of about 10 bucks per trade 10 US dollars per trade so those are our default parameters the next thing to do is get some user input I'm just going to copy this code over to save time since it's not that important what we're doing here I'll tidy up these a little bit to make them easy to read just by indenting everything it's a new habit I've gotten into that I quite like makes the code easier to read so what we're getting here is our long-term EMA so a 200 period EMA by default our short term EMA which is a 20 period by default a ATR period which is five by default so we're calculating the ATR based on the past five daily bars our ATR band distance is a multiplier of the ATR by default it's set to one our ATR bias stretch is the stretch from the lower band that we place our buy limit order at that's also set to 180r by default then we have which band to sell at so this is our mean reversion sell Point by default it's set to the middle band which is our short term EMA and the price value value here I underscore sell Source short for input underscore cell source is a price source and it is the high of the bar by default so when the high of the bar touches our Central Moving average the 20 period EMA I consider price to have reverted to the mean and I exit on the next Bar's open so those are our user inputs the next thing we need to do is get our indicator values paste that in there so we're getting our long-term EMA using the ta.ema inbuilt function we pass in the price Source we want to calculate our EMA on and the length so that's 200 by default and our short-term EMA is 20 by default and then we get our current ETR value the next thing we need to do is get our ATR bands so I'll type this out get ATR bands so we need ATR band top and now I can demonstrate some of the cool new features of this new editor I see when we start to type all this stuff popping up at first it's overwhelming if you're new to Pine but it's actually extremely efficient and convenient what this pop-up is and I'll explain how to use it in a second but we have ATR top and bottom so to calculate the ATR bands top we need to add our ATR band input to our Central Moving average so to do that I need to reference our EMA short and see how this has popped up I can just simply hit tab now and it will automatically fill that out which makes coding in Pines so much faster um than it used to be you used to only be able to autofill built-in functions but now we can reference even our own custom variables and things like that so it's really cool makes coding in Pine a real um a real pleasure to be honest so we need to add our ATR value the current ATR multiplied by our input ATR band so that's this input here so one ATR by default but we can adjust that in the settings and we can see how that affects our strategy performance for the lower band the one we actually use to reference for our buy conditions we need to subtract the same values so EMA short term minus the ATR value multiplied by our ATR band that gives us our two uh bands so before we continue let's draw all of this to the Chart so that we can see what our script is actually doing so the first thing we're going to do is plot our EMA long term I'll give it a title of EMA filter this is our filter for filtering out trees that we shouldn't take when price is trading below this EMA I'll set the color to color.red and the line width to two you can see as I'm typing this out it actually references which parameter we're working with which is really cool it also shows the color that we'll be drawing onto the chart when I save this code so little things but they do add up to make working with pine just so much more efficient and easier we can actually change the color here with a click of a mouse really cool new feature the next thing we're going to plot is our EMA short term I'll call this ATR Band Middle and I'll give it a color of color.blue and then I'll just copy and paste the other plots over to save time since you get the idea now of what I'm what I'm doing here so we're plotting the EMA long term the EMA short term or our middle band we're plotting the ATR top and bottom and then we are going to plot our limit order the price that we are going to place our limit order but we haven't written that code yet so I'll comment that out for now and we'll add that in later but now if I saved my code we should be getting our core indicators drawing to the Chart we have our Central Moving average the two bands and our long term price filter directional bias filter so when price is trading below this the system does nothing it's a long only System since stocks especially U.S stocks tend to Trend upwards over time far more often than they Trend downwards this system is taking advantage of that overall directional bias and then we're just buying short-term weakness in stocks that are trading above their long-term moving average so now we have everything we need in order to combine this information to create our buy and sell filters or conditions so to do that I'm going to first Define my price stretch variable so that's just going to be a float or a price value and I'm going to call this buy limit price and I'm going to initialize it as n a or not a number nothing null to begin with and then we'll reassign this value later to our actual Buy price once we've calculated that so the next thing we need to do is check our setup conditions or in other words is the bar close below the ATR band the lower band and is it above our long term EMA pretty simple entry criteria for this system so I can create a new variable here called setup condition and this will be set to is the current bars closing price lower than our lower band our ATR band bottom and is the low of the current bar greater than our EMA long term so price is trading above the EMA and below our lower band so it's in this sort of Zone here this is what I consider to be trading away from the mean and we are looking for price to have a sharp sell-off and then revert back to that mean um that's what this system is attempting to capture so I'm getting a little bit ahead of myself here but the next thing we're going to do is clear any pending limit orders so when you place a limit order using the strategy tester in Pine that limit order stays there indefinitely until it gets filled basically or canceled so what I'm going to do here before we even place the limit order is we're going to cancel any pending limit orders using the strategy dot cancel all function so if we have a limit order that has not been filled yet we cancel that immediately on the start of each new bar so if the limit order was not filled on the previous bar and it was placed on the previous bar we just cancel that order because we don't want the limit order staying on the chart indefinitely if it doesn't get filled the next day then we basically the trade's gone and we just keep repeating the process waiting for the next bar to exceed one ATR from our lower band and that's how the system works so now that we've got all our limit orders cleared we have all our entry criteria set up and ready to go the final thing to do is enter and exit our positions so to enter our trades I'll just say here enter trades on next bar after our setup condition is met our setup criteria is met which is this line of code here so I'm going to use an if statement here if setup condition is true and then we need to tab to indent within the scope of this if statement otherwise we won't compile this script will give an error if we don't do this so if our setup condition is met we need to calculate our buy limit price so I'm going to set by limit price to the current bars low and then we need to subtract the current ATR value multiplied by our ATR stretch so this is the stretch from the lower band that we want to place our limit order at by default it's set to one ATR so basically once price is trading below our lower band we place a buy limit order 180r below that lower band sorry below that Bar's low and we're hoping for a Sharp sell-off like this bar here followed by a quick reversion to the mean that's the edge that this system is trying to capture so now we need to strategy dot entry we use this function to enter our position we need to give it an ID so this is a long only system so I'll just call this entry ID long and then we need to tell it which direction we are trading in so I'll just say here strategy dot long and we now need to specify some of these other parameters you can use stop to enter a buy stop above price action you can use quantity to set your position size and OCA stand stands for one cancels all I'll cover these in a different video that's on my to-do list pretty soon it's been requested a few times to show how this parameter works but for today's lesson we are focusing on limit so limit is a buy limit price so we need to specify our limit as this variable here that we just calculated so the low minus one ATR is our buy limit price now that we've defined by limit price we can uncomment this code here and now this will draw a little cross to identify which price we are placing our limit order at so we are now entering our positions but we're not exiting them yet so we need to add a couple more lines of code here the first thing we're going to do is because I've defined in the settings menu this option here that allows the user to select which band to sell at and which price source to reference we need to do a couple of things here the first thing we need to do is get the cell whoops get sell price get which price we we are referencing as our mean our average that we are reverting to I'm going to use a switch statement here to Define this value sell price because it's just a little bit more efficient than using several if statements and what how this function works is we need to pass in a value so I'm going to pass in my cell band input which is this setting here so we're passing that into our switch statement and then what the Syntax for this switch statement is to Simply say is cell band equal to this value top if so then we want to reference our ATR band top price value otherwise if it's not top we check is it middle if it's middle then we set it to our EMA short term and then finally if it's bottom then we set it to ATR band bottom and I'll indent these to make it a little easy to read and that's it we now have our sell price variable defined depending on which setting the user selected here that will dictate which value gets selected as this variable's value and finally we can exit our trades so the criteria for exiting our trades on this particular system is if our price source which is this parameter here the high by default so with the default settings we're going to check is the current bars High greater than or equal to sell price which is the variable we just defined here so depending on which one we've selected will dictate which sell price we are looking at so by default it's the middle band our short term moving average the 20 EMA so by default this would be saying if the current bar is high is greater than or equal to the 20 EMA or price has closed below our long-term moving average remember that's our stop loss so if uh the current bars closing price is less than EMA long term or our red line then we need to exit our trade either for profit hopefully not always this condition will not always mean that we're exiting for a profit because price might have trickled lower and then touched the 20 EMA after we bought higher than that EMA it doesn't happen often but it can happen so this will usually exit the trade for a profit or a small loss this on the other hand is our sort of Fail-Safe if price just continues plummeting lower we want to exit at some point we don't want to hold on Forever Until price comes back up to that 20 EMA because who knows when that might happen once the 200 EMA is breached so if price has touched our 20 EMA or closed below our 200 EMA we call strategy Dot close and this function will close any open orders we need to pass in the ID of the order to close in that case now in this case that's long that's the only order type we have open so passing along there and this is optional but I'm going to add a comment here uh comment equals exit trade the reason I'm doing this is because otherwise uh the strategy tester has a really long label for exiting your long trades I'll show you what I mean in a moment that's how script completed we have finished writing all the code we need hopefully I haven't made any mistakes and when I save this it should compile and we should have that first trade popping up here there we go so I'll show you what I mean with this comment if I get rid of this comment which you don't need to include but if I get rid of that this label up here uh it just clutters up your chart when you have a lot of trades in a short period of time so I like to include this comment just to tidy up my charts a little bit just a matter of OCD preference but here we go so let's go over this one more time we have our 200 period moving average and a giant drawing tool don't know what happened there one second hit the wrong hotkey so again we got the 200 EMA this is our filter price must be trading above this red line then we have our short-term moving average the 20 EMA price must be trading one ATR below that EMA so price must close below this green line and then these Green Dots here or crosses are our buy limit orders so on this bar here we close below the band and we place the buy limit order one ATR below the low it was not hit on the next bar and so we canceled our pending orders on this bar and then we we repeat the process so this bar also closed below our green line so our buy conditions are still met so we place another buy limit order one ATR below the low and this time on the next bar it was actually filled by Price action and we entered long when price came down and hit ow buy limit order if this bar had gapped down lower than our buy limit order and opened down here somewhere let's say this was a green bar and this was the open then our entry price would actually be the open of this bar not where we placed our buy limit order because when the Market opens if it's trading below our buy limit order it's basically giving us a better price than we wanted and so our broker would enter us long down here instead of up here it doesn't happen often but it can happen it's not a bad thing because it just means we're getting a better price than we wanted and oftentimes a big gap down will be followed by a short-term rally back to the mean and two quite often when that does happen unless there's a steep sell-off like during the covert crash and price just plummets throughout 200 EMA and stops us out for a loss we'll use it usually get a nice snap back to the mean after that sort of price action and so that's completely fine with the system in this case this price opened up here traded down throughout the day eventually exceeded our buy limit order and then closed up here and then on the next few days we sort of plateaued here we Consolidated for a couple days and then we had that reversion to the mean price tagged out upper moving average and we exited on the next bars open for a small profit so that's our script completed uh before I wrap up this lesson obviously the source code will be in the video description if you want to play around with it yourself but let's go over some of these settings and see how they affect this system so first of all let's try seeing what happens if we change sell it band to the top band this gray band so if I hit Top now we exit all the way up here so we still enter down here but now we hold on to our trade much longer it's not really a mean reversion trade now because we're exceeding the mean the 20 EMA by quite a bit here so this is now more of a pullback system that's trading Trend continuation setups just by changing that one parameter another thing we could do is change the band to the lower band now this is a more conservative mean reversion system now the system is entering Along on this bar and then the next bar tags our lower band and so on the bar after that we exited the open so that's a more conservative approach uh it can still be profitable I found in my testing that it um over the Russell 3000 Universe of stocks it's still profitable but just not quite as much as the middle band the top band is a little bit too aggressive and I have found that it increases the drawdown without increasing the return much the middle band is the sweet spot for this sort of system I've found at least with the default parameters and so that's what I use I have also played around with the price Source that's why we have these two inputs while I'm developing the system once I decide which parameters best suit the system I will hard code this and you won't be able to select it when I finish my script in Amy broker but if you want to you can play around with different price sources so for example we could sell after a close above the 220 Emmy instead of just touching it with the high so that's another option for this particular system on this particular stock it performs pretty similarly to referencing the high so if I reference the high pretty much same drawdown a little bit less profit but obviously this is cherry picking and data mining one single stock you'd want to see how this performs on multiple stocks preferably hundreds of stocks if not thousands because the nature of the system doesn't take that many trades so we need a larger sample size to be able to dictate whether or not this system is performing acceptably within our risk metrics so our we want the system to trade with a Max drawdown that we're comfortable with while also producing a profit and a win rate that we're comfortable with and that is acceptable to us anyway that's it for this system I'll just quickly run through a few markets here so this one wasn't that profitable um neither was this one this one was not profitable at all this one was basically break even a little bit profitable only took three trades on this one um this a bit better 60 return with a 10 drawdown 40 return with a 60 drawdown is pretty rough but again trading over a large portfolio of stocks that wouldn't be as bad um 86 return with 28 drawdown um 34 return with a six percent drawdown but only nine trades so you get the idea we need a larger sample size in order to determine if uh this system is profitable or not Netflix not too bad 130 return with a 30 drawdown over multiple years and multiple stocks with a larger portfolio of positions the system would give you results much closer to what we see here where you can see that over the past 30 years or so the system has been quite profitable it's pretty volatile it does have some pretty major down months but every year pretty much besides two years in the current year which isn't over yet were losses so we had two maybe three losing years over the past 30 years with a reasonable return a pretty big year here in 1999 it's obviously during the tech crash there's probably a lot of mean reversion happening and sell-offs around this period so it does pretty well during a sell-off market let's look at 2018 2019 it did okay did okay the past couple of years this is a single run back test so you can't depend on this data too much but it gives us a fair idea of uh you know 20 Max drawdown if we ran a few Monte Carlo tests and added some more parameters and filters this might be a pretty profitable and acceptable system to trade so before I wrap up this video I just want to mention one last thing in relation to um one of the potential risks when using limit orders enter your trades it's important that you guys are aware that the use of limit orders introduces the potential for selection bias now selection bias is a sneaky risk that not many Traders understand until they've been burned by it through experience but selection bias basically manifests itself in real time trading you may get very different results in real time than you did on historical price data due to the fact that the system generates lots of variations of signals when you use limit orders so even when we're using leverage or margin depending on the quantity of signals that gets generated by your system there will be times when your system generates more signals than you can actually execute due to Capital limitations or not having enough money so if your system generates a hundred buy limit orders for the next day you're not going to get filled on all on all 100 of those and you're not going to know ahead of time which ones will get filled and which ones won't that introduces selection bias because now either you have to choose which limit orders to place which is the classic definition of selection bias or your system basically just has a random selection based on whichever stocks fill your limit orders first when back testing on a daily time frame unless you have access to intraday price data for the past 30 plus years and you can run your system and detect which limit orders were filled first you kind of have this issue now there are several ways you can mitigate the issue of selection bias which I'll probably cover in a future video because this video is already long enough and it's not just a problem related to this particular system but it affects all systems that generate lots of signals see how this performed on bitcoin not great profitable but not great anyway the main ways that I know to mitigate selection bias is to increase the sophistication of your signal generation to reduce the signal quantity so your system will just produce less signals to trade based on having more sophisticated entry criteria now this is not ideal and not always suitable for all strategies as generally speaking talking when it comes to trading simple is better but depending on the system sometimes simple means you get a ton of signals so other than increasing the set of conditions required to generate a trading signal my two favorite methods are to introduce signal ranking into the system so for example you might take the rate of change as a percentage over the past 100 bars and only take the top 10 trades ranked by that metric so if your system generates a hundred trades you only take the 10 that had the highest rate of change over the past 100 bars or in other words the strongest trending stocks over that sample size doesn't necessarily mean that the trades are more likely to win but it does reduce the subjectivity the discretion involved in which trades to actually execute and then your real-time results will be closer to the metrics discovered through your back testing this method is appropriate and quite powerful for systems where you can actually choose which trades to enter so trades where you enter on the next bars open for example instead of using a limit order but for today's system it's not really appropriate because we don't know ahead of time which limit orders are going to get filled on any given day so an alternative ranking method might be to only place 10 or 20 limit orders based on a ranking system and how you want to distribute your Capital over those 10 or 20 trades and whether you're using margin leverage or not and then if some of those 10 or 20 limit orders get filled that's great if some don't then you just skip those trades the negative side effect of this approach is that you might significantly reduce your trading opportunities and exposure which will result in probably slower Equity gains but the benefit is that you almost entirely eliminate selection bias and your real-time trading results should be much closer to the metrics discovered through your historical back testing process anyway there are a ton of methods for reducing the damage caused by selection bias but we'll cover them in a future videos I could speak on this subject alone for an hour easily and we haven't even mentioned the plethora of other devices that can pop up When developing systematic strategies like this one that we made today but anyway I've kept you and rambled long enough I'll wrap up this video here thanks for watching as always I hope you found it interesting and I hope it inspires some ideas for you to go out and test yourself please in the comments section let me know your thoughts on the system let me know what changes you would make to it if it reminds you of any existing systems as Traders we often get excited that we've discovered some magic system and then you find out that it was written down in a book 10 20 years ago and you're basically Reinventing the wheel or stealing someone else's idea without realizing it that's a problem with music as well by the way I used to write songs years ago and get all excited that I'd found this awesome Melody and then realize a couple days later that I just ripped off a song that was in my subconscious or something but anyway thanks for watching good luck with your trading as always if you want to learn more about Pine script or steal my best code go to panscriptmastery.com you can find my courses there including a course where I give the source code to every script I've ever created including several trading systems that I used to trade the Forex crypto and stock markets profitably with all that said I will see you in the next video take care and have a great weekend [Music]