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
No comments:
Post a Comment