Indicators··7 min read

Consecutive Close Counter with Streak Statistics

3 references, link-verified · 1 primaryEditor of record: Shane CantyStandards review editorial standard · audit log

A trader analyzing price momentum often needs to know how long a directional move has persisted. The Consecutive Close Counter tracks the number of bars in which consecutive closes have moved in the same direction, or remained above or below a defined level, and maintains a statistics table showing the current streak, maximum streak, average streak length, and total number of completed streaks. This helps identify whether the current move is typical, extreme, or weakening compared to historical patterns.

//@version=6
indicator("Consecutive Close Counter with Streak Statistics", overlay=false)

// Inputs
streakType = input.string("Up", "Streak Type", options=["Up", "Down", "Above Level", "Below Level"])
threshold = input.float(0, "Threshold (for Above/Below)", minval=-10000, maxval=10000)
tableLocation = input.string("Top Right", "Table Location", 
    options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", 
             "Bottom Left", "Bottom Center", "Bottom Right"])
textSize = input.string(size.small, "Text Size", options=[size.tiny, size.small, size.normal, size.large, size.huge])

// Map location string to position enum
getPosition(loc) =>
    switch loc
        "Top Left" => position.top_left
        "Top Center" => position.top_center
        "Top Right" => position.top_right
        "Middle Left" => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right" => position.middle_right
        "Bottom Left" => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right" => position.bottom_right
        => position.top_right

// Determine if bar satisfies streak condition
isStreakBar() =>
    switch streakType
        "Up" => close > open
        "Down" => close < open
        "Above Level" => close > threshold
        "Below Level" => close < threshold
        => false

// Track streak statistics
var int currentStreak = 0
var int maxStreak = 0
var int totalStreaks = 0
var float sumStreak = 0.0

// Update streak counters on each bar
if isStreakBar()
    currentStreak += 1
else
    if currentStreak > 0
        totalStreaks += 1
        sumStreak += currentStreak
        maxStreak := math.max(maxStreak, currentStreak)
    currentStreak := 0

// Calculate average streak length
avgStreak = totalStreaks > 0 ? sumStreak / totalStreaks : 0.0

// Create statistics table once at start
var table statsTable = na

if barstate.isfirst
    statsTable := table.new(getPosition(tableLocation), 2, 5, 
        border_color=color.gray, frame_color=color.gray, border_width=1, frame_width=1)
    
    // Header row
    table.cell(statsTable, 0, 0, "Metric", text_color=color.white, bgcolor=color.navy, text_size=textSize)
    table.cell(statsTable, 1, 0, "Value", text_color=color.white, bgcolor=color.navy, text_size=textSize)
    
    // Label rows
    table.cell(statsTable, 0, 1, "Current Streak", text_color=color.white, bgcolor=color.gray, text_size=textSize)
    table.cell(statsTable, 0, 2, "Max Streak", text_color=color.white, bgcolor=color.gray, text_size=textSize)
    table.cell(statsTable, 0, 3, "Avg Streak", text_color=color.white, bgcolor=color.gray, text_size=textSize)
    table.cell(statsTable, 0, 4, "Total Streaks", text_color=color.white, bgcolor=color.gray, text_size=textSize)

// Update statistics values on every bar
currentColor = currentStreak > 0 ? color.new(color.green, 30) : color.new(color.red, 30)
table.cell(statsTable, 1, 1, str.tostring(currentStreak), text_color=color.white, bgcolor=currentColor, text_size=textSize)
table.cell(statsTable, 1, 2, str.tostring(maxStreak), text_color=color.white, bgcolor=color.gray, text_size=textSize)
table.cell(statsTable, 1, 3, str.format("{0,.2f}", avgStreak), text_color=color.white, bgcolor=color.gray, text_size=textSize)
table.cell(statsTable, 1, 4, str.tostring(totalStreaks), text_color=color.white, bgcolor=color.gray, text_size=textSize)

// Plot current streak as lower study
plot(currentStreak, "Current Streak", color=color.blue, linewidth=2)

How the code works

The script initializes four persistent variables (declared with var) to accumulate streak statistics across the entire chart history: currentStreak counts the unbroken run of bars meeting the condition; maxStreak records the longest streak ever seen; totalStreaks counts how many complete streaks have finished; and sumStreak accumulates the length of all completed streaks for averaging.

On each bar, the isStreakBar() function evaluates whether the current bar meets the chosen condition. If "Up" is selected, it checks whether close > open (a bullish bar); "Down" checks close < open; "Above Level" and "Below Level" compare the close against a user-defined threshold. If the condition is met, currentStreak increments; if not and a streak was active, the streak ends, triggering totalStreaks and sumStreak to update, and maxStreak to record the new maximum if applicable.

The statistics table is created once at the first bar using table.new() and positioned at the location chosen in inputs. Header rows and labels are set in that initialization block. On every subsequent bar, the table cells containing the numerical values (current streak, max, average, and total count) are refreshed with the latest statistics. The current streak cell is colored green when active and red when inactive, providing visual feedback on the streak state. A plot of the current streak line appears as a lower study for additional context.

Reading it on a chart

The table displays four key metrics. The "Current Streak" cell changes from green (streak in progress) to red (streak broken) and shows the count of consecutive bars meeting the condition. A rising count during a green period indicates momentum continuation; a reset to zero and shift to red signals that the condition has failed. The "Max Streak" records the longest unbroken run ever recorded on this timeframe and dataset; comparing it to the current streak reveals whether the current move is exceptional or routine. The "Avg Streak" provides a baseline: if the current streak approaches or exceeds the average, the move is above the norm; if it falls well short, the market is being choppy. The "Total Streaks" counter shows how many complete runs have been counted since the chart loaded or the indicator was applied, giving context to how much history has been processed.

A trader watching price action might, for example, observe that on a 5-minute chart in a given pair, the historical maximum "Up" streak is 12 bars, the average is 4.3 bars, and the current streak has just reached 8 bars. This signals that the current rally is strong relative to the mean but still below the extreme, suggesting room for continuation but also increasing probability of reversal near the all-time high. Conversely, if the "Avg Streak" is 6 but the current streak resets to zero every 2-3 bars, the market is choppy and directional trades are likely to fail quickly.

Limitations

The indicator counts only consecutive close-direction bars; it does not account for the magnitude of moves, only their direction. A series of tiny up closes and a series of large up closes register identically, yet their risk and reward profiles differ. The threshold for "Above Level" and "Below Level" modes is static and must be manually adjusted; it does not adapt to changing volatility or price levels, so a level set for daily charts becomes stale if the underlying drifts sharply. Streak statistics accumulate from the first bar loaded on the chart; they do not reflect the longer-term market regime if the chart window is small or if the indicator is applied after significant price history has passed off-screen. The logic is backward-looking: a streak ending and resetting to zero lags a single bar behind the reversal, so the table reports the broken streak's length only after it has already failed. Finally, on timeframes where the condition rarely or never occurs, the "Max" and "Avg" metrics may remain zero or misleadingly low, offering little insight into typical behavior.

Key definitions

Streak: A continuous sequence of bars in which the defined condition is met on each successive bar, ending when the condition fails on the next bar.

Close direction: The relationship between the bar's open and close prices; "Up" means close above open (bullish bar), "Down" means close below open (bearish bar).

Current Streak: The number of consecutive bars satisfying the condition up to and including the most recent bar; resets to zero when the condition fails.

Max Streak: The longest unbroken sequence of bars meeting the condition since the indicator began tracking.

Average Streak: The mean length of all completed streaks, calculated as the sum of all completed streak lengths divided by the total number of completed streaks.

Threshold: A user-defined price level against which closing prices are compared in "Above Level" or "Below Level" modes, allowing measurement of time spent in defined price zones.

References


Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.

Last reviewed by the PropLedger research pipeline: 2026-11-01. Educational research on historical data, not financial advice.

Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard. Found an error? Email support@prop-ledger.org and the paper is corrected or withdrawn.