Do you ever find yourself spending hours to write an elaborate function or block of code only to find later that a built-in function or a super simple implementation already exists? I know I have fallen foul to this annoyance on many occasions. It is why reading the docs or reviewing some of the excellent open source scripts in the community can save you a lot of time and energy. Unfortunately, some of us (myself included) like to jump in head first, play around and explore without spending enough time on background reading.
Today, we are going to take a look at one such case. A simple solution to a common task that might not be obvious at first. We shall take a look at counting how often something happens!
It goes without saying that counting is used in many different scenarios. It is one of the most basic math skills we learn as a child and forms the foundation needed to create interesting statistics that we can then use to make trading decisions.
So what’s the problem?
There is no problem really. As the old saying goes “there are many ways to skin a cat”. However, hopefully, the code snippet in this post will help slip that skin off like a knife through butter.
When attempting to count, we might first try to do it with the for loop. I assume the reason for this is that is how we might decide to tackle this task in other programming languages. In fact, even this site has an example in the for loops tutorial that used a for loop for counting!
// Run through historical data
for i = 0 to lbp -1
if open[i] < close[i]
up := up + 1
if open[i] > close[i]
dn := dn + 1
if open[i] == close[i]
nc := nc + 1
The Simple Solution
Pinescript is a series based programming language. On each new bar of data, we loop through our script and build new lines off that data. Additionally, we can access any historical value through indexing. We can take advantage of this and use Tradingview’s built-in
sum()function to achieve the same results as a long for loop. All we have to do is use a ternary conditional operator to assign a value of 1 or 0 to a new line and then sum it up by the period we want.
A simple example of this is:
study("Green Candle Counter")
green_candles = close > open ? 1 : 0
green_candles_sum = sum(green_candles, 100)
This snippet will count of how many times in the last 100 bars a candle closed up, aka. Green. On the chart is looks like this:
This same technique can be used to count whatever you like over any period and does not require the complexity of a for loop.
Support the site
If you like this article and are thinking to become a Tradingview subscriber, you can support the site by clicking on the affiliate link below before signing up!