How to COUNT CUMULATIVE or CONSECUTIVE bars on ENTIRE CHART or SPECIFIED TIME

@Izet99


you are focused on just starting the count but you have nothing defined as to when to finish or what triggers the stop count.
you have define the start and finish, because without a previous for future finish there is no start.
so youde have to not only start count but also tell it when to finish count.


I was wondering if somebody can help modify below code to get bar count from last fired signal,

if you simply want to count FIRED then you want to use the example code from the orignal post of COUNT OF THE TOTAL NUMBER OF CONSECUTIVE and then just modify the VAR

so;
Code:
def var = fired==1;
if you change the var to this code above you will get the consecutive count of how many times FIRED was true (fired=1)

you previously stated:
. I was wondering if somebody can help modify below code to get bar count from last fired signal, reset bar count when new signal is up/dn. For example in image below, arrow under bubble show uptrend, is it possible to count bar from that point on until trend reverses, once trend reverses, reset count and count again for next trend. Watchlist below give me color for the trend but wonder if bar count could be integrate for the trend direction.

scanning = if X then startcount else if Y then stopcount else keep scanning (note the isnt actual code, its just concept.)

like i said you may want to move this to a separate topic under questions part of the forum. thats alot of stuff going and you didnt define what you consider reversal, this topic can get quite long and you should post it under questions as it pertains to more than just counting.
 
Last edited:
okay, i'll try. below is a screenshot with the cumulative count as the last study. here's the code i've been using as well. chart is of a mutual fund JASVX, set for one month. i'm trying to get the label to show the number of bars on the screen that are either green or no change, along w/ the total number of bars. the current example should show 18 bars either up or the same, out of 22 total. Instead, it's showing 20 out of 22.

i think the problem is that, for some reason, the count is always starting at 3, which i have circled. that throws everything off. it should start at one. Got any idea how I can sort this out? thanks!

Code:
declare lower;
#( CUMULATIVE ) COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN)
# ON THE ENTIRE CHART WITHIN SPECIFIED TIMEFRAME
# By XeoNoX via Usethinkscript.com
input startTime = 0930;
input endTime = 1600;
def Active = SecondsFromTime(startTime) >= 0 and SecondsTillTime(endTime) >= 0;
def var = close>=close[1];

#close>open;

def cumulative = if Active and !Active[1] then var else if Active then cumulative[1] + var else cumulative[1];
plot scan  = cumulative;
addLabel(1, "Count = " + scan, color.dark_green);

AddLabel(yes, "total bars: " + BarNumber());

edited picture to show desired count:

sKRM9pB.jpg
beautiful, perfect. i changed the color and added the total sum and yup thanks again.

Code:
declare lower;
#( CUMULATIVE ) COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN)
# ON THE ENTIRE CHART
# By XeoNoX via Usethinkscript.com
def var =close>=close[1];
def count = totalsum(var);
AddLabel (yes, "COUNT " +  (count), color.dark_green   );
plot scan  =count;

AddLabel(yes, "total bars: " + BarNumber());
CLOSE >=CLOSE[1] DOES NOT MEAN ITS A BULLISH BAR OR GREEN FOR THAT MATTER. TOOK ME 20 MINTUES TO FIGURE OUT WHY THIS CODE WAS PRODUCING AND INACCURATE COUNT.......THE REST OF THE CODE DID HELP THOUGH SO THANK YOU FOR THE OTHER PORTION
 
I think what I want to do is impossible, can someone confirm? I want to count how many 15 minute bars generated over the last five trading days (maximum including extended hours would be 16 hours / 15 minutes = 64 bars * 5 days = 320 bars). So that means that for a very illiquid stock, there could have been no ticks for an hour every day, and the number of 15 minute bars over that five days would be 320 - (4 * 5 = 20) = 300 bars.

And the key difficulty here is that I want to count the number of bars over a chosen length of days, regardless of the number of days that are included in the current chart. I want to be able to count the number of bars that happened starting five days ago while I'm using a 5min 1 Day chart, for example.

I tried this code but of course it didn't work:

Code:
declare lower;
#  CUMULATIVE  COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN)

def Active_1 = GetDay() >= (GetLastDay()-5); #The previous five days
def var_1 = !isNan(close(period=aggregationperiod.fifTEEN_MIN));
def cumulativeA = if Active_1 and !Active_1[1] then var_1 else if Active_1 then cumulativeA[1] + var_1 else cumulativeA[1];

AddLabel (yes, "COUNT " +  (cumulativeA), color.dark_green  );

It seems that the issue is it's impossible to count bars that occurred before the date range of the current chart's display. So with a 1min / 2 day chart open, it seems impossible to count bars that occurred 3 days ago.

Another issue I notice is that specifying the aggregation period for var_1 doesn't do anything, the count still returns as 900+ if I have a 1min / 1 Day chart open for example, so the script is calculating the bars without taking account of the period inputted there.

Part of the reason I'm trying to do this is that I wanted to be able to calculate Fib retracement values based on going back X number of calendar days, while using a chart that only shows bars for the current day, and while using an intraday period to get the highs and lows since using the Day period will exclude extended hours highs and lows. But I think it can't be done. Can anyone confirm that this is impossible?

EDIT: I just went ahead and made what I wanted to make but only using Day period so that extended hours candles are lost from the calculations of the fib retracement lines. It's probably close enough most of the time that it's not worth the huge hassle of trying to solve this problem of using intraday period bar count over a specific number of calendar days which seems impossible. So no need to donate time trying to solve it on my account, I've moved on. But if anyone has a solution that they're interested in sharing for the sake of the challenge then I'd still be curious.
 
Last edited:
CUMULATIVE COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN) ON THE ENTIRE CHART
Code:
declare lower;
#( CUMULATIVE ) COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN)
# ON THE ENTIRE CHART
# By XeoNoX via Usethinkscript.com
def var =close>open;
def count = totalsum(var);
plot scan = count;
AddLabel (yes, "COUNT " + (count) );
Hi, can someone help to write code using this as first part of code. This code counts total amount of green bars on the entire chart, but i wanna know what will be average "spike" (high - open) in percent of all these counted green bars.
 
Hi, can someone help to write code using this as first part of code. This code counts total amount of green bars on the entire chart, but i wanna know what will be average "spike" (high - open) in percent of all these counted green bars.

Try this...

Code:
declare lower;
#( CUMULATIVE ) COUNT OF THE TOTAL NUMBER OF GREEN BARS (CLOSE>OPEN)
# ON THE ENTIRE CHART
# By XeoNoX via Usethinkscript.com
def var = close>open;
def spike = high - open;
def spikeper = if var then spike / open * 100 else 0;
def spikepercount = totalsum(spikeper);
def count = totalsum(var);
def avgspikeper = spikepercount / count;
plot averagespikepercentage = avgspikeper;
AddLabel (yes, "AvgSpike " + (avgspikeper) );

Note, I haven't actually tested this, I just came up with the code on the spot so it may be inaccurate, but test it out and see what you get.
 
When using the consecutive count script remember if you are in Heikin Ashi your count will differ from the visible candles as HA is smoothing!
 
@XeoNoX - Thanks for the counting info!!! I'm running into a little challenge that seems like it should exist.

The varCount result with this block of CODE comes back as "N/A".


Code:
def var =     if var1 then var1 else
            if var2 then var2 else
            if var3 then var3 else
            double.nan;
          
def varCount = TotalSum(var);

AddLabel(if varCount > 0 then yes else no,"varCount: "+varCount,color.yellow);

When i simply input one of the variables, as in,

Code:
"def var = var1;"

The count comes up fine. The basics are that I'm trying to get a counter to "respond" to a market event. Since I have used this technique with labels, I thought it would be easy peezy, but, it doesn't seem that straightforward. I've tried many variants in the variable list like,

Code:
if var1 ==1 then var1 else.....

to NO avail!!

Any ideas why?

THANKS!!
 
Last edited:
@XeoNoX - Thanks for the counting info!!! I'm running into a little challenge that seems like it should exist.

The varCount result with this block of CODE comes back as "N/A".


Code:
def var =     if var1 then var1 else
            if var2 then var2 else
            if var3 then var3 else
            double.nan;
         
def varCount = TotalSum(var);

AddLabel(if varCount > 0 then yes else no,"varCount: "+varCount,color.yellow);

When i simply input one of the variables, as in,

Code:
"def var = var1;"

The count comes up fine. The basics are that I'm trying to get a counter to "respond" to a market event. Since I have used this technique with labels, I thought it would be easy peezy, but, it doesn't seem that straightforward. I've tried many variants in the variable list like,

Code:
if var1 ==1 then var1 else.....

to NO avail!!

Any ideas why?

THANKS!!

hard to help without the actual code of what you are doing. i tried to make it as easy as possible. the only thing that should be changed is one line which is the def VAR line.

"def VAR = (your TRUE/YES or FALSE/NO scan goes here);"

the scan has to be a yes or no result which in thinkorswim comes back and 1 or 0, 1 for true and 0 for false.

if you arent sure if you scan is coming back as 1 or 0 then you can just plug your scan in as a study and plot it and it should show if your script is returning 1 or 0.

i cant help you beyond this without actual code of what you are attempting to do. good luck
 

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
323 Online
Create Post

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top