Skip to main contentSkip to content
Squeeze Setups A live squeeze scanner built around the Slingshot Squeeze, with 22 years of backtest results behind it. See it, $99/month →
TOS Indicators
  • Tools

    Categories

    • Indicators
    • Backtesters
    • Scans
    • Dashboards
    • thinkScript
    • Member Resources
    Browse Full Library

    Featured Tutorials

    Fair Value Gap Indicator
    Fair Value Gap Indicator
    Indicators

    Download our free Fair Value Gap indicator for ThinkorSwim. It shades every...

    Learn more →
    False Breakout Scanner for ThinkorSwim (Free Scan Pair)
    False Breakout Scanner for ThinkorSwim (Free Scan Pair)
    Scans

    A two-scan pair that flags failed breakouts and failed breakdowns with volume...

    Learn more →
    Heiken Ashi Trend Indicator
    Heiken Ashi Trend Indicator
    Indicators

    Download our Custom Heiken Ashi indicator for ThinkOrSwim. Full ThinkScript code, formula...

    Learn more →

    Popular Posts

    Unusual Volume Pro Scans
    Unusual Volume Pro Scans
    Scans

    4 additional scans to find unusual volume overlapping with key...

    Learn more →
    High Short Interest Near 52 Week Highs (thinkScript)
    High Short Interest Near 52 Week Highs (thinkScript)
    Scans

    Build a simple scan in which to find stocks that...

    Learn more →
    Upcoming Earnings with High Short Interest
    Upcoming Earnings with High Short Interest
    Scans

    Build a scan to find stocks that are likely to...

    Learn more →
  • Courses
    Squeeze Course
    Squeeze Course
    19 Modules

    Scan, backtest, and trade the TTM Squeeze setup with precision.

    View Course →
    Earnings Course
    Earnings Course
    3 Modules

    Master earnings plays with free indicators and proven strategies for ThinkOrSwim.

    View Course →
    V-Shaped Reversals
    V-Shaped Reversals
    7 Modules

    Identify and trade powerful V-shaped reversal patterns with confidence and precision.

    View Course →
    Fibonacci Trading
    Fibonacci Trading
    4 Modules

    Learn to trade Fibonacci retracements and extensions in ThinkOrSwim effectively.

    View Course →
  • Products
    Futures Volatility Box Premium
    Futures Volatility Box

    Volatility models for 10 major futures markets, including the micros.

    Explore Futures VB →
    Stock Volatility Box Premium
    Stock Volatility Box

    Volatility levels for 600+ stocks and ETFs, with a live scanner.

    Explore Stock VB →
    Opening Range Breakouts Premium
    Opening Range Breakouts

    Scans 600+ stocks every 2 seconds for opening range breaks, with a backtester.

    Explore ORB Setups →
My Account
All Indicators
Beginner-Friendly 16 minutes ThinkOrSwim

Candle Counter Indicator for ThinkorSwim

A free candle counter for ThinkorSwim. It counts green and red candles in a row, plots each run as a histogram and labels the max and average counts.

Download Indicator
How to install in ThinkOrSwim →
Table of Contents
  • Key Takeaways
  • What Is a Candle Counter?
  • What the Candle Counter Shows
  • How to Add the Candle Counter to ThinkorSwim
  • How the Code Works
  • What the Avg Labels Measure
  • Examples From the Video
  • How to Read the Candle Counter
  • Common Problems and Fixes
  • More Ways to Count Bars in ThinkorSwim

In this tutorial I build a candle counter indicator for ThinkorSwim that counts how many green candles, and how many red candles, print in a row. A histogram in a lower panel shows each count bar by bar, and 4 labels show the highest and the average count for each color across all the data on your chart.

I built it to profile the S&P 500: how many green days in a row it tends to have before a red day, and the reverse, so you have a better idea of where a trend might be exhausting. It’s also a short, beginner-friendly thinkScript exercise in counter variables, resetting them, labels and histograms.

Key Takeaways

  • The candle counter is a free ThinkorSwim lower study that counts consecutive green candles (close above open) and consecutive red candles (close at or below open). Each count resets to 0 when a candle of the other color prints.
  • It plots both counts as histograms, green for green candles and pink for red, and prints 4 labels: Max Green, Max Red, Avg Green and Avg Red.
  • A doji, where the close equals the open, counts as a red candle, so it ends a green run.
  • In the video, with 20 years of daily SPY data loaded, Max Green read 13, a run that started on March 25, and Max Red read 10.
  • The labels use HighestAll and TotalSum, so they cover every bar loaded on the chart. Load more history and the max and average can change.

What Is a Candle Counter?

A candle counter is an indicator that counts how many candles of the same color have printed in a row. On a daily chart, a green count of 5 means the market has closed above its open 5 days running.

The question behind ours is simple: how many green days in a row does the S&P 500 have before a red day, and how many red days before a green one? Knowing the longest run and the average count gives you a profile of the market, so a run that is getting long by that market’s standards stands out.

The video is also a thinkScript lesson. You’ll see how to create counter variables, how to reset them, how to plot a histogram, and how to keep two groups of data, the green candles and the red candles, separate from each other.

What the Candle Counter Shows

The candle counter shows 2 histograms in a lower panel and 4 labels at the top of that panel. The histograms count, and the labels summarize those counts over the whole chart.

Item What it shows Color
Green histogram How many green candles in a row up to this bar, 0 on a red candle Green
Red histogram How many red candles in a row up to this bar, 0 on a green candle Pink
Max Green label The highest green count on the chart Green
Max Red label The highest red count on the chart Pink
Avg Green label The average green count across all green candles, to 1 decimal Green
Avg Red label The average red count across all red candles, to 1 decimal Pink

In the video’s example, 6 green candles in a row built the green histogram up to a bar of 6. The next red candle dropped it back to 0 and started the red count.

How to Add the Candle Counter to ThinkorSwim

The candle counter is a regular ThinkorSwim study, created from the Studies menu.

  1. Click the Studies icon on your chart, then click Create.
  2. Name the study, for example candle counter, and delete the starter code in the editor.
  3. Paste in the code from the Code tab on this page, then click OK and Apply.
  4. Load enough history for the labels to mean something. I used 20 years of daily candles on SPY.

The code starts with declare lower, so it opens in its own panel under the price chart. To import the downloaded file instead, follow our guide on how to import a study into ThinkorSwim.

How the Code Works

The candle counter code is 23 lines of thinkScript, built in 5 steps. The snippets below come from the downloaded file.

Step 1: Define Green and Red Candles

def green = close > open;
def red = close <= open;

A green candle closes above its open. A red candle closes below its open or right at it, so a doji counts as red.

Step 2: The Counter Variables

def greenCounter = if green then greenCounter[1] + 1 else if red then 0 else greenCounter[1];

def redCounter = if red then redCounter[1] + 1 else if green then 0 else redCounter[1];

If the bar is green, the green counter takes its value from the previous bar, greenCounter[1], and adds 1. If the bar is red, it resets to 0.

The red counter is the mirror image. While I built it in the video, I put the green counter in a chart bubble over each candle: it counted 1, 2, 3 up to 6, dropped to 0 on the next red candle and started again at 1 on the next green one. Then I removed the bubble.

Step 3: The Max Values

def maxGreenCount = HighestAll(greenCounter);
def maxRedCount = HighestAll(redCounter);

AddLabel(yes, "Max Green: " + maxGreenCount, color.green);
AddLabel(yes, "Max Red: " + maxRedCount, color.pink);

HighestAll finds the highest value of a variable across every bar on the chart. I made the red labels pink so they’re easier to see.

Step 4: The Average Values

An average is a sum divided by the number of values. For the numbers 1, 2, 3, 4 and 5, you add them up to 15 and divide by 5 to get 3. The candle counter does the same with its counters, one color at a time:

def totalGreenCandleSum = TotalSum(greenCounter);
def totalGreenOccurrences = TotalSum(if greenCounter >= 1 then 1 else 0);
def avgGreenCounter = totalGreenCandleSum / totalGreenOccurrences;

TotalSum adds a value up across every bar on the chart.

The occurrences line counts 1 only where the green counter is 1 or more. If you divided by every bar, all the 0s from red candles would drag the average down. The red side repeats the same three lines with redCounter.

Step 5: The Labels and the Histograms

AddLabel(yes, "Avg Green: " + Round(avgGreenCounter, 1), color.green);
AddLabel(yes, "Avg Red: " + Round(avgRedCounter, 1), color.pink);

Round(..., 1) keeps each average to 1 decimal place.

plot greenHistogram = greenCounter;
plot redHistogram = redCounter;
greenHistogram.setPaintingStrategy(PaintingStrategy.Histogram);
redHistogram.setPaintingStrategy(PaintingStrategy.Histogram);
greenHistogram.setDefaultColor(Color.green);
redHistogram.setDefaultColor(Color.pink);

The two plots draw the counters. In the video they showed nothing until I added declare lower at the top.

Plotted as lines, they rise with each candle of the same color and fall back to 0. The histogram painting strategy is easier to read, and the default colors fix the green and pink no matter what else is on your chart.

What the Avg Labels Measure

The Avg Green label is the average reading of the green counter across every green candle on the chart. Each green candle adds its count to the sum: the first candle of a run adds 1, the second adds 2, and so on.

That makes the label different from the average length of a run. If a single run of 5 green candles were the only one on the chart, the counter would read 1, 2, 3, 4 and 5, and Avg Green would show 3. Read it as the count a typical green candle sits at, and Max Green as the longest run.

If you want the average length of a run instead, here is a suggested edit, not in the video or the download. Add these 2 lines below the existing average lines:

def greenRuns = TotalSum(if greenCounter == 1 then 1 else 0);
AddLabel(yes, "Avg Green Run: " + Round(totalGreenOccurrences / greenRuns, 1), color.green);

greenRuns counts the bars where a new run starts. Green candles divided by runs is the average run length. For the red side, copy both lines, change every green to red (redRuns, redCounter, totalRedOccurrences and the label text) and use color.pink.

Examples From the Video

The candle counter examples in the video ran on daily candles with 20 years of data loaded. I read out the max labels and found each run on the chart. The video doesn’t read out the Avg Green or Avg Red values.

Symbol and chart Reading What I found
SPY, daily, 20 years Max Green 13 The tallest green spike. The run started on March 25 (the year isn’t stated), and I counted the 13 candles off one by one.
SPY, daily, 20 years Max Red 10 Found by scrolling back toward the start of the data: 10 red candles, then a green one.
SPY, daily A spike of 7 While the counters were still plotted as lines, one spike lined up with 7 green candles in a row.
QQQ, daily, 20 years Max Red A little bigger than SPY’s. No figure read out.

To find the max run yourself, zoom out and look for the tallest bar of that color in the histogram, then zoom in on it. The label and the bar should show the same number.

How to Read the Candle Counter

The candle counter tells you the personality of a market: how long its runs of green and red candles have been, at their longest and on average. The current histogram bar tells you where today’s run stands against that history.

  • Compare markets. Switch the symbol and the labels update. I went from SPY to QQQ in the video, and you can do the same with the Dow, the Russell or single stocks like Apple and Microsoft.
  • Compare the current run. A green bar near Max Green means the run is already long by that market’s own standards, which is where a trend might be exhausting.
  • Keep the history long. The labels cover only the bars on your chart, so a short chart gives you a short profile.

A long run is context, and it doesn’t time the turn. Use the count to anticipate where a trend may be stretched, decide your stop before you trade, and size the position so a stop-out costs a small, fixed share of your account.

Common Problems and Fixes

The candle counter is short, and most problems come from three places.

  • The histograms don’t show. Check that declare lower is at the top of the code, so the study plots in its own panel.
  • The labels changed. HighestAll and TotalSum use every bar on the chart, so a new time range or symbol gives new numbers.
  • A green run ended on a doji. A doji closes at its open and counts as red, so it resets the green counter.

Our AddLabel tutorial explains how the labels work if you want to change their text or colors.

More Ways to Count Bars in ThinkorSwim

The candle counter’s pattern, adding 1 to the previous bar’s value while a condition holds and resetting to 0 when its opposite appears, works for other conditions too. Replace the green and red definitions with your own pair of opposite conditions and the counters, labels and histograms follow.

For other examples, our increasing volume scan checks for 3 bars in a row with Sum, and our Extreme TICK counter counts +1,000 and -1,000 NYSE TICK readings each day. To define more detailed candles, see how to turn candlestick patterns into code. More free studies are on our ThinkorSwim indicators page.

Candle Counter Indicator.ts
#Written by TOS Indicators 2023
#Home of the Volatility Box
#Indicator: Candle Counter
#Full Tutorial Link: tosindicators.com/indicators/candle-counter


declare lower;

def green = close > open;
def red = close <= open;

def greenCounter = if green then greenCounter[1] + 1 else if red then 0 else greenCounter[1];

def redCounter = if red then redCounter[1] + 1 else if green then 0 else redCounter[1];

## Max Value

def maxGreenCount = HighestAll(greenCounter);
def maxRedCount = HighestAll(redCounter);

AddLabel(yes, "Max Green: " + maxGreenCount, color.green);
AddLabel(yes, "Max Red: " + maxRedCount, color.pink);

## Average Value

def totalGreenCandleSum = TotalSum(greenCounter);
def totalRedCandleSum = TotalSum(redCounter);

def totalGreenOccurrences = TotalSum(if greenCounter >= 1 then 1 else 0);
def totalRedOccurrences = TotalSum(if redCounter >= 1 then 1 else 0);

def avgGreenCounter = totalGreenCandleSum / totalGreenOccurrences;
def avgRedCounter = totalRedCandleSum / totalRedOccurrences;

AddLabel(yes, "Avg Green: " + Round(avgGreenCounter, 1), color.green);
AddLabel(yes, "Avg Red: " + Round(avgRedCounter, 1), color.pink);


## Histogram

plot greenHistogram = greenCounter;
plot redHistogram = redCounter;
greenHistogram.setPaintingStrategy(PaintingStrategy.Histogram);
redHistogram.setPaintingStrategy(PaintingStrategy.Histogram);
greenHistogram.setDefaultColor(Color.green);
redHistogram.setDefaultColor(Color.pink);

Want the .ts file and the one-click import? Both come with a free account.

Create Free Account Login
A candle counter counts how many candles of the same color print in a row. Ours is a free ThinkorSwim lower study that counts green candles and red candles separately, plots each count as a histogram, and labels the highest and the average count for each color across the chart.
Click the Studies icon, click Create, name the study and delete the starter code. Paste in the code from the Code tab, click OK and Apply. You can also import the downloaded TI_CandleCounterSTUDY.ts file. The study opens in its own panel under the price chart because the code starts with declare lower.
The green counter adds 1 to its previous value on every green candle and resets to 0 on a red candle. The red counter does the opposite. So after 6 green candles the green histogram reads 6, and the next red candle drops it to 0 while the red histogram starts at 1.
A doji counts as red. The code defines a red candle as a close at or below the open, so a candle that closes exactly at its open is red. That means a doji ends a green run, resets the green counter to 0 and adds 1 to the red counter.
With 20 years of daily SPY data loaded, the Max Green label read 13: a run of 13 green candles in a row that started on March 25. The video doesn't state the year. The longest red run on the same chart was 10 candles. Both numbers cover only the data loaded at the time.
Avg Green adds up the green counter on every bar and divides by the number of bars where it is 1 or more, which leaves out the 0s from red candles. That gives the average count a green candle sits at. A single run of 5 green candles would read 3, while its length is 5.
Check that declare lower is at the top of the code. In the video the two plots showed nothing until I added it, because declare lower moves the study into its own panel under the price chart. Also check that both plots use the histogram painting strategy if you see lines instead of bars.
Yes. The code has no symbol or timeframe setting, so it counts the candles of whatever chart you load. In the video I switched from SPY to QQQ, where Max Red was a little bigger, and mentioned the Dow, the Russell, Apple and Microsoft. On an intraday chart it counts intraday candles the same way.

Here are some resources that you may find useful:

  • How to import an indicator into ThinkOrSwim (video tutorial)
  • How to add a label in ThinkOrSwim
  • How to turn candlestick patterns into code
  • Extreme TICK Counter indicator
  • More free ThinkOrSwim indicators
Featured Tools:
Stock Volatility Box

Stock Volatility Box

Spot reversal zones across 600 stocks & ETFs.

  • Hourly & daily models
  • Powerful Live Scanner
  • Built for day traders
Futures Volatility Box

Futures Volatility Box

Pinpoint reversal zones in 10 major futures markets.

  • 5 models (incl. Scalper)
  • ThinkOrSwim & TradingView
  • SPX traders
ORB Setups

ORB Setups

Find the best Opening Range Breakout setups.

  • Powerful real-time scanner
  • Instant backtests
  • 2+ years data

Get Free Access

Create a free account for downloads and new tutorial alerts.

Create Free Account

Related tutorials and research

2 Ways to Use NYSE $TICK to Spot Trend Days

2 Ways to Use NYSE $TICK to Spot Trend Days

Research
How to Build a Fair Value Gap Indicator in ThinkorSwim

How to Build a Fair Value Gap Indicator in ThinkorSwim

Indicators · Beginner-Friendly
How to Build a Heiken Ashi Trend Dots Indicator in ThinkorSwim

How to Build a Heiken Ashi Trend Dots Indicator in ThinkorSwim

Indicators · Beginner-Friendly
How to Build a Commodities Tracker in ThinkorSwim

How to Build a Commodities Tracker in ThinkorSwim

Indicators · Beginner
Trend Squeeze Indicator for ThinkorSwim

Trend Squeeze Indicator for ThinkorSwim

Indicators · Beginner
Volume Intensity Indicator for ThinkorSwim

Volume Intensity Indicator for ThinkorSwim

Indicators · Beginner-Friendly

Ready to Trade With an Edge?

Join 40,000+ traders using institutional-grade tools for ThinkOrSwim.

Get the Bundle
TOS Indicators

Premium thinkorswim indicators, scans, and trading tools to help you trade smarter.

ThinkOrSwim Tools

  • Indicators
  • Scans
  • Backtesters
  • Dashboards
  • thinkScript
  • Browse All

Courses

  • Squeeze Course
  • Earnings Course
  • V-Shaped Reversals
  • Fibonacci Trading

Products

  • Futures Volatility Box
  • Stock Volatility Box
  • ORB Setups
  • Shop All

Guides

  • TTM Squeeze
  • Automated Trading
  • Volatility Trading
  • Opening Range Breakouts
  • Trade Reports
  • Contact Us

© 2026 TOS Indicators. All rights reserved.

Privacy Policy Terms of Service Disclaimer Accessibility

The information contained on this website is solely for educational purposes, and does not constitute investment advice. The risk of trading in securities markets can be substantial. You must review and agree to our Terms of Service prior to using this site.

U.S. Government Required Disclaimer - Commodity Futures Trading Commission. Futures and options trading has large potential rewards, but also large potential risk. You must be aware of the risks and be willing to accept them in order to invest in the futures and options markets. Don't trade with money you can't afford to lose. This website is neither a solicitation nor an offer to Buy/Sell futures or options. No representation is being made that any account will or is likely to achieve profits or losses similar to those discussed on this website. The past performance of any trading system or methodology is not necessarily indicative of future results.

Individual results may vary, and testimonials are not claimed to represent typical results. All testimonials are by real people, and may not reflect the typical purchaser's experience, and are not intended to represent or guarantee that anyone will achieve the same or similar results.

TOS Indicator's Traders and employees will NEVER manage or offer to manage a customer or individual's options, stocks, currencies, futures, or any financial markets or securities account. If someone claiming to represent or be associated with TOS Indicator solicits you for money or offers to manage your trading account, do not provide any personal information and contact us immediately.

CFTC RULE 4.41 - HYPOTHETICAL OR SIMULATED PERFORMANCE RESULTS HAVE CERTAIN LIMITATIONS. UNLIKE AN ACTUAL PERFORMANCE RECORD, SIMULATED RESULTS DO NOT REPRESENT ACTUAL TRADING. ALSO, SINCE THE TRADES HAVE NOT BEEN EXECUTED, THE RESULTS MAY HAVE UNDER-OR-OVER COMPENSATED FOR THE IMPACT, IF ANY, OF CERTAIN MARKET FACTORS, SUCH AS LACK OF LIQUIDITY, SIMULATED TRADING PROGRAMS IN GENERAL ARE ALSO SUBJECT TO THE FACT THAT THEY ARE DESIGNED WITH THE BENEFIT OF HINDSIGHT. NO REPRESENTATION IS BEING MADE THAT ANY ACCOUNT WILL OR IS LIKELY TO ACHIEVE PROFIT OR LOSSES SIMILAR TO THOSE SHOWN.