- 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 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 ...Here are some resources that you may find useful: