Skip to main content Candle Counter Indicator For ThinkOrSwim Skip to main content Skip to content
Master the TTM Squeeze with our comprehensive 19-module course Start Learning →
TOS Indicators
  • Tools

    Categories

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

    Featured Tutorials

    Heiken Ashi Trend Indicator
    Heiken Ashi Trend Indicator
    Indicators

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

    Learn more →
    Commodities Tracker
    Commodities Tracker
    Indicators

    For acceleration signals: trend-following strategies and buying pullbacks. For deceleration signals: short...

    Learn more →
    Build an Election Backtester in 10 Minutes
    Build an Election Backtester in 10 Minutes
    Backtesters

    Learn how to create a Post-Election Backtester in ThinkOrSwim to analyze market...

    Learn more →

    Popular Posts

    Unusual Volume
    Unusual Volume
    Scans

    Build 4 scans to easily find stocks with greater than...

    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 →
    Unusual Volume Pro Scans
    Unusual Volume Pro Scans
    Scans

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

    Learn more →
  • Courses
    Squeeze Course
    Squeeze Course
    19 Modules

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

    Unlock Course →
    Earnings Course
    Earnings Course
    3 Modules

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

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

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

    Unlock Course →
    Fibonacci Trading
    Fibonacci Trading
    4 Modules

    Learn to trade Fibonacci retracements and extensions in ThinkOrSwim effectively.

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

    Volatility models for 10 major futures markets, including micros & SPX.

    Explore Futures VB →
    Stock Volatility Box Premium
    Stock Volatility Box

    Dynamic support & resistance for 595+ stocks/ETFs, with a live scanner.

    Explore Stock VB →
    Opening Range Breakouts Premium
    Opening Range Breakouts

    Powerful live scanner & backtester for ORB strategies on 595+ stocks.

    Explore ORB Setups →
My Account
Back to Tutorials
Beginner-Friendly 16 mins ThinkOrSwim

Candle Counter

Learn how to build a powerful candle counter indicator for ThinkOrSwim that tracks consecutive green and red candles. Get max counts, averages, and histogram visualization to understand market patterns.

Download Indicator
How to install in ThinkOrSwim →
Table of Contents
  • Why Streak Analysis Matters for Trading
  • What the Indicator Actually Tracks
  • Building the Core Logic
  • Calculating Maximum Streaks
  • The Tricky Part: Calculating Averages
  • Histogram Visualization
  • Real Market Examples
  • Practical Trading Applications
  • Customizing the Code
  • Adding Alert Functionality
  • Understanding the Data
  • Common Insights from Streak Analysis
  • Advanced Applications
  • Code Optimization Tips

Track Market Momentum with a Candle Counter

How many green candles in a row does the S&P 500 usually have before hitting a red candle? This candle counter indicator gives you exact data on consecutive candle patterns to understand when trends might be exhausting.

What this candle counter shows you:

  • Real-time counting of consecutive green and red candles
  • Maximum candle counts for both directions
  • Average candle counts to understand normal market behavior
  • Histogram visualization to spot extreme candle runs instantly

Perfect for identifying when trends are getting extended and reversals could be coming.

Why Streak Analysis Matters for Trading

Markets don’t move in straight lines, but they do have patterns. The S&P 500 might average 2.3 consecutive green days before hitting a red day, but when you see 7 green days in a row, that’s telling you something different is happening.

This streak counter indicator tracks exactly that – how many consecutive green or red candles you’re seeing compared to what’s normal for that market. No more guessing about whether a trend is getting extended.

What the Indicator Actually Tracks

The streak counter gives you four key metrics displayed as labels on your chart:

Max Green: The longest consecutive streak of green candles in your data set
Max Red: The longest consecutive streak of red candles
Avg Green: The average number of consecutive green candles before a red candle appears
Avg Red: The average number of consecutive red candles before a green candle appears

Plus you get a histogram that shows the current streak count in real-time, making it easy to spot when you’re approaching extreme levels.

Building the Core Logic

The foundation is simple – define what makes a green versus red candle:

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

Notice that doji candles (close = open) get classified as red candles. This keeps the logic clean since we're looking for clear directional momentum.

Next comes the counter logic. This is where it gets interesting:

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

Here's what this does: If the current candle is green, take the previous green counter value and add 1. If it's red, reset the counter to 0. Otherwise, carry forward the previous value.

The red counter works exactly the same way but in reverse - counting up on red candles and resetting to 0 on green candles.

Calculating Maximum Streaks

Finding the max streaks is straightforward once you have the counters:

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

HighestAll() looks at every value in your data set and returns the highest one. So if your green counter hit 13 at some point (like in the example with 13 consecutive green days starting March 25th), that becomes your max.

The Tricky Part: Calculating Averages

Averages require more work because you can't just use a simple average function. You need to exclude all the zero values that occur when streaks reset.

First, calculate the total sum of all counter values:

def totalGreenCandleSum = TotalSum(greenCounter);

Then count how many times the counter was actually active (greater than 0):

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

Finally, divide sum by occurrences to get the true average:

def avgGreenCounter = totalGreenCandleSum / totalGreenOccurrences;

This gives you the average length of green streaks, ignoring all the periods when the market was red.

Histogram Visualization

The histogram makes it easy to spot extreme streaks at a glance:

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

When you see a tall green bar, you know you're in an extended green streak. The height tells you exactly how many consecutive green candles you've had.

Real Market Examples

In the tutorial example using 20 years of S&P 500 data, the max green streak was 13 consecutive days (starting March 25th in the data set). The max red streak was 10 consecutive days.

But here's what's really useful - the averages. If the S&P normally sees about 2-3 green days in a row, and you're currently on day 7 of a green streak, you're in unusual territory. That doesn't mean it will reverse immediately, but it tells you the current move is statistically extended.

Practical Trading Applications

Trend Exhaustion: When current streaks exceed the average by 2-3x, start watching for reversal signals. A 7-day green streak when the average is 2.3 days suggests the move might be getting tired.

Market Comparison: Run this on different markets. QQQ might show different streak patterns than SPY, which shows different patterns than individual stocks like AAPL or MSFT.

Historical Context: Use this to understand the personality of whatever you're trading. Some stocks are naturally more streaky than others.

Entry Timing: When a streak reaches extreme levels, it might be time to start looking for counter-trend opportunities or at least tighten stops on trend-following positions.

Customizing the Code

The basic version counts daily candles, but you can modify it for different timeframes:

Intraday Streaks: Use on 5-minute or hourly charts to track intraday momentum

Weekly Analysis: Apply to weekly charts for longer-term trend analysis

Different Definitions: Modify the green/red logic to use different criteria (maybe body size or gap analysis)

Adding Alert Functionality

You could extend this code to alert when streaks reach certain levels:

Alert(greenCounter >= maxGreenCount * 0.8, "Extended Green Streak", Alert.BAR, Sound.Chimes);

This would alert when the current green streak reaches 80% of the historical maximum.

Understanding the Data

The indicator works best with significant amounts of historical data. The tutorial uses 20 years of data, which gives reliable statistics. With only a few months of data, the averages might not be as meaningful.

Also remember that market conditions change. A streak pattern from 2008-2010 might be different from 2020-2022 due to different volatility regimes and market structure.

Common Insights from Streak Analysis

Most Markets Aren't Very Streaky: You'll often find that average streaks are only 2-3 candles, meaning reversals happen more frequently than you might expect.

Extreme Streaks Are Rare: When you see streaks of 7+ candles, you're witnessing unusual market behavior that often precedes significant moves or reversals.

Volatility Affects Streaks: Low volatility periods often show longer streaks, while high volatility periods show more frequent reversals.

Index vs Individual Stocks: Broad market indices like SPY tend to be less streaky than individual stocks, which can have more extreme runs in either direction.

Advanced Applications

Once you understand basic streak analysis, consider these extensions:

Volatility-Adjusted Streaks: Weight streaks by the size of the moves, not just the count

Volume-Confirmed Streaks: Only count candles that also meet volume criteria

Sector Analysis: Compare streak patterns across different sectors to identify rotation

Multi-Timeframe: Look at streak patterns on both daily and weekly charts simultaneously

Code Optimization Tips

The code is designed to be efficient, but here are some considerations:

Data Scope: More historical data gives better statistics but may slow calculation slightly

Label Updates: The labels recalculate on every bar, which is normal but worth noting

Memory Usage: TotalSum functions store all historical data, so extremely long data sets might affect performance

This streak counter transforms simple price action into quantified momentum analysis. Instead of guessing whether a trend is getting extended, you have concrete data about what's normal versus extreme for your specific market.

The beauty is in its simplicity - just counting consecutive candles, but doing it systematically gives you insights that most traders never consider. Whether you're looking for trend continuation or reversal opportunities, understanding streak patterns gives you a statistical edge in timing your entries and exits.

Candle Counter Indicator.ts
# Candle Counter for ThinkOrSwim

# Written by TOS Indicators 2023

# Home of the Volatility Box

# Full Tutorial Link: tosindicators.com/indicators/candle-counter

declare lower;


// ... 33 more lines ...

Unlock This Code

Create a free account to access the full source code and download files.

Create Free Account Login
To build a candle counter in ThinkOrSwim, start by defining green and red candles (green = close > open), then create counter variables that increment on consecutive candles and reset to 0 when the pattern breaks. Use conditional logic: if green then greenCounter[1] + 1, else if red then 0, else greenCounter[1]. This candle counter creates a running count of consecutive candles in each direction.
Max candle count shows the longest consecutive run of green or red candles in your entire data set - like finding that one time you had 13 green candles in a row. Average candle count shows the typical length of consecutive runs, calculated by dividing total sum of all counts by the number of occurrences. Your candle counter's average gives you normal market behavior, max shows extreme events.
In your candle counter, use TotalSum(if greenCounter >= 1 then 1 else 0) to count only active periods, then divide TotalSum(greenCounter) by this count. This excludes all the zero values that occur when the opposite color candle appears, giving you the true average length of actual candle runs rather than including reset periods in your candle counter calculations.
Yes, the candle counter works on any timeframe. Use your candle counter on 5-minute charts for intraday momentum analysis, daily charts for swing trading insights, or weekly charts for long-term trend analysis. Each timeframe will show different patterns in your candle counter - intraday tends to be more volatile with shorter counts, while weekly data shows longer, more sustained trends.
The candle counter histogram bars show the current count in real-time. A green bar of height 6 means you currently have 6 consecutive green candles. The candle counter histogram makes it easy to visually identify when you're in extended runs compared to normal market behavior. Tall bars in your candle counter indicate unusual lengths that might signal trend exhaustion.
Your candle counter needs at least several years of data for reliable statistics. The tutorial example uses 20 years of S&P 500 data, which provides robust averages and max values for the candle counter. With only a few months of data, your candle counter averages might not represent normal market behavior. More data gives your candle counter better insight into what constitutes normal versus extreme lengths.
In this candle counter, doji candles (close = open) are classified as red to maintain clean logic for directional momentum. Since the candle counter tracks consecutive directional moves, neutral candles break the momentum just like opposing moves do. This prevents doji candles from artificially extending green counts in your candle counter when there's no clear bullish momentum.
Use your candle counter to identify potential trend exhaustion points. When current counts in your candle counter exceed the historical average by 2-3x (like 7 green candles when average is 2.3), start watching for reversal signals. Compare different markets using your candle counter - QQQ vs SPY vs individual stocks show different patterns. Use extreme candle counter readings as signals to tighten stops or look for counter-trend opportunities.

Here are some resources that you may find useful:

  • How to import an indicator into ThinkOrSwim (video tutorial)
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

More Tutorials Like This

Edge Signals

Edge Signals

Beginner-Friendly • 14 mins
Moving Average Clouds

Moving Average Clouds

Beginner-Friendly • 13 mins
Commodities Tracker

Commodities Tracker

Beginner • 15 minutes

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

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.