Intermediate Trading Tutorial | Pine Script v6 custom indicators
Two five-bar windows can contain exactly the same total volume but represent very different distributions of trading activity. One window may have roughly equal volume on every candle, while the other contains a single exceptionally active candle surrounded by quiet bars. A moving average of volume cannot distinguish those distributions when their totals match. This tutorial develops a free TradingView indicator that measures the concentration of volume across completed bars. It borrows a mathematical concentration statistic and normalizes it to a consistent 0–100 scale. The purpose is to describe how activity is distributed through time, not to infer whether buyers or sellers are dominant.
From volume shares to a concentration score
Start with a window of N bars and let each bar's volume be V. Divide each observation by the sum of all volumes in the window to obtain its share of total activity. Square each share and add the squared shares. This quantity is commonly called the Herfindahl–Hirschman Index, or HHI, in concentration analysis. Here it is applied to bar volume rather than market participants. A large share contributes disproportionately to the squared sum, making the statistic sensitive to unusually dominant observations.
When all N observations are equal and positive, HHI equals 1/N. When one observation accounts for all the volume and the others are zero, HHI equals 1. To make the endpoints consistent across different window lengths, subtract 1/N and divide by 1 − 1/N. Multiply the result by 100. A score of zero means perfectly uniform positive volume, while a score of 100 means all measurable activity was concentrated in one bar. This normalization requires at least two bars. A window with zero total volume has no defined shares and must not be confused with the uniform positive-volume case.
A five-bar example with two equal totals
Consider a hypothetical sequence containing volumes of 100, 100, 200, 100 and 500 units. Total volume is 1,000. The shares are 0.1, 0.1, 0.2, 0.1 and 0.5. Their squares are 0.01, 0.01, 0.04, 0.01 and 0.25, which sum to 0.32. For N = 5, the theoretical lower bound is 0.2. The normalized score is 100 × (0.32 − 0.2) / (1 − 0.2) = 15.

| Hypothetical volumes | Total | HHI | Score |
|---|---|---|---|
| 200, 200, 200, 200, 200 | 1000 | 0.20 | 0 |
| 100, 100, 200, 100, 500 | 1000 | 0.32 | 15 |
| 0, 0, 0, 0, 1000 | 1000 | 1.00 | 100 |
All three sequences have an identical five-bar average of 200 units. Nevertheless, the concentration values span the entire theoretical range. Notice that 15 is not the percentage of volume on the largest bar; it measures normalized concentration across every bar. Also, changing the order of these five observations does not change their concentration for the same window. The statistic does not identify when a burst occurred, only how unevenly the activity was distributed.
Complete Pine Script v6 indicator
//@version=6
indicator("PatternSmart Volume Concentration", overlay = false,
precision = 2)
int length = input.int(5, "Window", minval = 2, maxval = 500)
// Count invalid observations separately, not as real zeros.
bool valid = not na(volume) and volume >= 0
float v = valid ? volume : 0.0
float count = math.sum(valid ? 1.0 : 0.0, length)
float total = math.sum(v, length)
float squares = math.sum(v * v, length)
float floorHHI = 1.0 / length
// Normalize the concentration to a 0-100 scale.
float score = na
if count == length and total > 0
float hhi = squares / (total * total)
score := 100.0 * math.max(0.0,
math.min(1.0, (hhi - floorHHI) / (1.0 - floorHHI)))
// Do not display a provisional reading on the live bar.
plot(barstate.isconfirmed ? score : na,
"Concentration", color = color.blue, linewidth = 2,
style = plot.style_linebr)
hline(0, "Uniform", color = color.gray)
hline(100, "Single-bar concentration", color = color.gray)
Implementation details and confirmed-bar behavior
Computing the squared shares individually is unnecessary. The sum of squared volumes divided by the square of total volume produces the same HHI. Pine's rolling math.sum function calculates the numerator and denominator using the same lookback. The separate count of valid observations ensures that missing volume is not silently interpreted as genuine inactivity. A valid zero-volume observation is allowed, whereas a missing value makes the entire affected window unavailable. The minimum window length is two and the maximum is 500 to keep the parameter explicit.
The script computes rolling sums on every execution, outside the conditional block. It only calculates a score when the window contains the required number of valid observations and its total is positive. The clamp to the interval from zero to one addresses small rounding discrepancies at the theoretical bounds. A genuine unavailable result remains na instead of being converted to zero.
On historical bars, barstate.isconfirmed is true. On a live bar it becomes true on the closing update. The plot therefore leaves the forming bar blank rather than displaying a fluctuating value that later disappears. The line-break plot style prevents visually bridging unavailable windows. This approach does not use future data, negative offsets or higher-timeframe requests. It does not guarantee immutability after data corrections, symbol adjustments or changes to the chart's historical series.
Installation and verification
- Open a TradingView chart and select Pine Editor.
- Create a new indicator, replace its contents with the complete source above, and save it under a descriptive name.
- Choose Add to chart. The indicator appears in a separate pane with reference lines at zero and 100.
- Keep the default window of five for the initial verification. Use the chart's Data Window and manually compare several completed bars with the formula.
- Observe the live bar and its closing update to confirm that a provisional value is not plotted.
The source uses Pine Script v6 syntax and native rolling calculations, but has not been compiled or executed in TradingView for this article. Local validation is necessary before relying on it in a production workflow.
Choosing the lookback and handling volume data
A small window highlights short-lived bursts of activity. As a dominant candle leaves the window, the score may fall abruptly even if the market has not changed substantially during the newest bar. A longer window provides a broader view but can preserve event-related concentration for a longer period. Although the theoretical endpoints are normalized, distributions observed at different lookbacks are not necessarily comparable. Test each length on the intended aggregation and instrument rather than treating a fixed threshold as universally meaningful.
The indicator is invariant to a common positive scaling of volume: multiplying every observation by the same factor leaves the shares unchanged. That does not mean volume from different feeds has identical meaning. Some instruments report exchange-traded volume, others tick volume or provider-specific measures. Certain symbols lack volume altogether. The script deliberately returns an unavailable reading for missing data. Intraday session patterns, auction prints, shortened sessions and contract changes can also influence concentration without implying a trading opportunity.
Validation checklist and limitations
Verify equal positive volumes, a single nonzero observation, all-zero windows, missing values and the first complete window. Confirm that multiplying every volume by ten leaves the result unchanged. Inspect the five-bar example and test the behavior on a chart without volume. Compare the most recent completed value across a reload, allowing for data corrections. If adding alerts in a later version, configure them for the intended confirmed-bar timing and verify their behavior separately.
The statistic does not measure net buying pressure, order-flow imbalance or price direction. A high score can occur during a rally, selloff or a quiet session with one modest trade burst. It also discards absolute activity, so low total volume and high total volume can produce the same reading. Pairing concentration with a separately defined activity filter or price-context feature may be useful, but any trading rule should be tested independently with transaction costs and out-of-sample data. Do not regard the example score of 15 as an optimized threshold.
If you would like session-adjusted volume concentration, additional activity filters, alerts or integration into a custom Pine Script indicator, contact us for Custom TradingView indicator Development Services.
Risk disclosure: This article is educational and does not constitute investment advice. Hypothetical calculations do not demonstrate trading profitability. Trading involves risk of loss.