Tutorial

Pine Script ta.cum: Running Totals and Cumulative Values

Learn how ta.cum builds running totals in Pine Script v6: counters, accumulation lines, daily resets, and why the starting level misleads.

•10 min read

You are looking at an indicator that needs a running total. Maybe it is volume added up since the open, maybe it is a count of how many bars met a condition, maybe it is the accumulation line you saw on someone else's chart and want to rebuild. You reach for a for loop, then remember a loop over history on every bar is slow and awkward, then you find ta.cum and wonder why nobody told you earlier. This guide covers what ta.cum does, the handful of patterns it makes trivial, the one thing it cannot do on its own (reset), and the mistakes that make cumulative lines misleading.

ta.cum is one of the smallest functions in the ta namespace, and that is exactly why people underuse it. It takes one series and returns the sum of every value of that series from the first loaded bar up to the current bar. Everything else in this post is a consequence of that one sentence.

What ta.cum actually does

The signature in Pine Script v6 is ta.cum(source) → series float. For each bar, the result is the previous result plus the current value of source. On the first bar it is just the first value. There is no length argument, because the window is always "everything since the start of the data the script has loaded".

You can write the same thing by hand with a persistent variable, which is the clearest way to see what the function replaces.

pine
//@version=6
indicator("ta.cum basics", overlay=false)

// Built-in running total of volume since the first loaded bar
cumBuiltIn = ta.cum(volume)

// The same running total written by hand
var float cumManual = 0.0
cumManual += volume

plot(cumBuiltIn, "ta.cum(volume)", color=color.blue)
plot(cumManual, "manual total", color=color.orange)
plot(cumBuiltIn - cumManual, "difference", color=color.gray)

On a crypto chart, where volume is always present, the two lines sit on top of each other and the difference line stays flat at zero. If you are not yet comfortable with why var makes the manual version work, the post on var, varip, and persistent state in Pine Script explains how a variable survives from one bar to the next, and how Pine Script's execution model works explains why the script reruns once per bar in the first place.

So why use ta.cum instead of the manual version? Two practical reasons. It is shorter, so there is less to get wrong. And it reads as intent: anyone opening your script sees "running total" immediately rather than having to decode a var and a +=.

The bar counter and the running mean

The simplest use is counting. Feed it the constant 1 and you get the number of bars loaded so far, which equals bar_index + 1. That sounds useless until you divide by it.

pine
//@version=6
indicator("Running mean of close", overlay=true)

barsSoFar   = ta.cum(1)
runningMean = ta.cum(close) / barsSoFar

plot(runningMean, "Mean of every loaded close", color=color.teal)

This draws the average of every close the chart has loaded, up to and including the current bar. It is not a moving average. A moving average forgets old data after length bars, while the running mean never forgets anything, so it moves more slowly the longer the history gets. That property is occasionally exactly what you want, for example as a long-run reference line, and it is a good illustration of what "cumulative" means: the first bar and the ten-thousandth bar carry the same weight.

The same trick counts events. Pass an expression that is 1 when something happened and 0 when it did not, and the running total is the count of occurrences so far.

pine
//@version=6
indicator("Share of up bars", overlay=false)

upBars  = ta.cum(close > close[1] ? 1 : 0)
upShare = upBars / (bar_index + 1)

plot(upShare, "Share of bars that closed up", color=color.purple)
hline(0.5, "Half", color=color.gray)

The ternary lives inside the call as an ordinary expression, so it is evaluated on every bar as it should be. What you get is a descriptive count of the loaded history, nothing more. It says what happened on these bars, and it says nothing about what comes next.

Accumulation lines are just ta.cum of a per-bar quantity

Many named indicators are a running total of something computed on each bar. Once you see the pattern, you can rebuild them in two lines and, more importantly, invent your own variants.

On-balance volume adds the bar's volume when the close rises and subtracts it when the close falls. The accumulation/distribution line weights each bar's volume by where the close sat inside the bar's range. Both are a per-bar number fed into ta.cum.

pine
//@version=6
indicator("Cumulative volume flow lines", overlay=false)

barRange = high - low

// Close location value: +1 when the close is at the high, -1 at the low
clv = barRange == 0 ? 0.0 : ((close - low) - (high - close)) / barRange

adLine  = ta.cum(clv * volume)
obvLine = ta.cum(math.sign(ta.change(close)) * volume)

plot(adLine,  "Accumulation/distribution", color=color.green)
plot(obvLine, "On-balance volume",         color=color.red)

The guard on barRange == 0 matters. A bar whose high equals its low would divide by zero and produce na, and an na inside a running total is the kind of problem the post on how Pine Script handles na describes: it can quietly poison everything downstream. Guarding the denominator keeps the total clean. Pine Script also ships ta.obv as a built-in, and the line above is the same arithmetic, which is useful to know when you want to change one rule, for example counting only bars above a volume threshold. The On-Balance Volume guide covers how traders read that line, and the Delta Flow post builds an estimated cumulative delta with the same idea.

Notice what these lines share. The absolute level of an accumulation line means almost nothing, because it depends on where the loaded history happens to start. Only its shape and slope carry information: a line climbing steadily, flattening, or turning down. Reading the level as if it were a meaningful number is the most common mistake with cumulative indicators, and we come back to it below.

Resetting a running total

Here is the limitation. ta.cum has no reset argument. It always sums from the first loaded bar. If you want volume since the start of the day, or a count of triggers since the session opened, you need a small workaround, and there are two clean ones.

The first is to snapshot the total at the reset point and subtract it. At every new day, record what the total was just before that bar, then report the difference.

pine
//@version=6
indicator("Cumulative volume per day", overlay=false)

newDay = timeframe.change("D")
total  = ta.cum(volume)

// Total just before the first bar of the current day
dayStart  = ta.valuewhen(newDay, total - volume, 0)
dayVolume = total - nz(dayStart)

// The same thing with a persistent variable that resets
var float manualDay = 0.0
if newDay
    manualDay := 0.0
manualDay += volume

plot(dayVolume, "ta.cum with offset", style=plot.style_columns, color=color.new(color.blue, 60))
plot(manualDay, "var with reset",     color=color.orange)

The two plots agree. The version with var and an if is usually easier to read and is what most people end up keeping, because it states the reset rule directly. The ta.cum version earns its place when you already have a total you need for other reasons, or when you want several different reset points from one running sum, since each is just another subtraction. The details of detecting the new day, week, or session are in the post on detecting a new day with ta.change and timeframe.change, and the session and time filter guide covers custom sessions.

One rule applies to both: keep the ta.cum call and the ta.valuewhen call at the top level of the script, not inside an if or a ternary branch. Functions in the ta namespace keep internal state that depends on being evaluated on every bar. If they run only on some bars, the state skips updates and the numbers drift from what you expected. The compiler warns about this for good reason.

Smoothing a cumulative line

A raw accumulation line is noisy and trending, so people often compare it to a smoothed copy of itself. Because the cumulative line is an ordinary series, you can pass it to any other ta function.

pine
//@version=6
indicator("Cumulative delta with smoothing", overlay=false)

// Rough per-bar estimate: bar direction times volume
perBar = close >= open ? volume : -volume
cumDelta = ta.cum(perBar)
smoothed = ta.ema(cumDelta, 21)

plot(cumDelta, "Cumulative estimate", color=color.blue)
plot(smoothed, "21-bar EMA",          color=color.orange)

bgcolor(cumDelta > smoothed ? color.new(color.green, 90) : color.new(color.red, 90))

The per-bar quantity here is a crude estimate, since candle direction is only a rough proxy for who was buying and who was selling. Treat it as an illustration of the mechanics. The shading shows which side of its own average the line sits on, and that is a description of the chart, not a forecast.

Why the level of a cumulative line depends on your data

This deserves its own section because it trips up almost everyone once. ta.cum starts at the first bar your chart loaded. Load 5,000 bars and you get one total. Load 20,000 and you get a different one, with the same shape but a different vertical offset. Switch timeframe and the first bar changes again. Open the same script on another symbol and the starting point is different once more.

That has three consequences. First, never compare the absolute value of a cumulative line across symbols, timeframes, or two charts that loaded different history. Second, never hard-code a threshold such as "alert when the total passes 1,000,000", because the number means nothing without the starting point. If you need a threshold, compare the line to its own moving average or to its value some number of bars ago, as in cumDelta - cumDelta[50]. Third, lines that grow forever can reach large magnitudes, and very large floats lose precision at the small end, so a cumulative sum of tiny increments over a very long history can behave strangely. Resetting per session, or working with the difference over a window, avoids the problem.

A related trap is the first bar. ta.change(close) is na on bar zero, so an on-balance line built from it has no real value there. The built-in ta.obv is defined the same way, so this is normal, but check the first few bars of your own line and compare it with the built-in before you trust it.

Checking a cumulative line on the chart

A running total is easy to get subtly wrong and hard to eyeball. The honest way to check one is to watch it build. PineScripter runs your script on its own chart, which covers 308 crypto spot markets across 14 timeframes with up to 5,000 bars per run, and draws the plots so you can see the line before you paste anything into TradingView. Bar replay then steps through the run one bar at a time, so you can watch the total increase on a bullish bar, drop on a bearish one, and snap back to zero at your reset.

A sensible request in the editor is plain English: "Plot cumulative volume that resets at the start of each day, and color the column green when the day's total is above the previous day's total." The AI writes Pine Script v6 and checks it against a linting engine that follows the same rules TradingView uses, fixing its own compile errors before you see them. Then you can ask for a follow-up such as "add a 21-bar EMA of the cumulative line", and only the affected lines change, with a line-by-line view of what moved. Plans and credits are on the pricing page. The code is yours to copy and keep, and you should still read it and run it on the instruments you care about, because the market data in PineScripter is crypto spot only and your own chart may differ.

If your total ever looks wrong, the first things to inspect are the reset condition, the first loaded bar, and any na entering the sum. The article on debugging Pine Script when there is no error message shows how to put those values on the chart.

Common mistakes

Calling ta.cum inside a conditional is the most frequent one, and it silently produces a total that skips bars. Compute the per-bar value conditionally, then pass the result to a top-level ta.cum call.

Treating the level as meaningful is the second. Compare slopes and relationships to the line's own average, never raw numbers across charts.

Forgetting the reset is the third. If you wanted "today's total" and see a line that only ever rises, you are plotting the all-history sum.

Mixing up ta.cum with math.sum is the fourth. math.sum(source, length) sums the last length bars and forgets the rest, which makes it a rolling window. ta.cum is the unbounded version. If your line should "forget", you want the rolling one, as in the rolling extremes covered in ta.highest and ta.lowest.

Last, remember that a cumulative line describes the loaded history. Whether a rising accumulation line has any bearing on what the next bar does is a question you have to test yourself, in the Strategy Tester or on your own data. This post is about writing correct code, and nothing here is a statement about future price.

PineScripter is a coding tool. It does not give financial advice, and nothing in this post is a recommendation to buy or sell anything. Past behavior shown by any indicator does not predict future results.

Frequently asked questions

What does ta.cum do in Pine Script?

It returns the sum of a series from the first loaded bar to the current bar. Each bar's result is the previous result plus the current value of the source.

Can ta.cum reset at the start of each day?

Not by itself, because it has no reset argument. Either subtract the total captured at the start of the day with ta.valuewhen, or use a var variable that you set to zero when timeframe.change detects a new day.

What is the difference between ta.cum and math.sum?

ta.cum sums everything since the first loaded bar. math.sum(source, length) sums only the last length bars, so older values drop out.

Why does my cumulative line look different on another chart?

ta.cum starts at the first bar the chart loaded. A different symbol, timeframe or amount of history changes the starting point and so the vertical level, while the shape stays similar.

Is ta.obv the same as ta.cum of signed volume?

Yes. On-balance volume is the running total of volume with the sign of the close change, which is what ta.cum(math.sign(ta.change(close)) * volume) computes.

Run your script on real market data and see what it plots →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.