sum
Total over rolling N-period window
sum(source, periods)
Calculates the total of values over a rolling window of N periods. Unlike cumsum() which accumulates from the start, sum() uses a sliding window that always includes only the most recent N bars. This is useful for calculating totals over fixed lookback periods, such as volume accumulation or gain/loss sums.
Parameters
- source (field): Data series to sum (close, volume, or any expression)
- periods (int): Number of bars to include in the sum
Formula
sum(x, n) = x[0] + x[1] + x[2] + ... + x[n-1]
where x[0] is the current bar and x[n-1] is n-1 bars ago
Examples
Volume Accumulation
Find stocks with high accumulated volume over recent bars:
// total volume over last 10 days exceeds 50 million
sum(volume, 10) > 50M;
Net Price Change
Calculate the net price movement over a period:
// net change over 5 bars (sum of daily changes)
sum(change(close, 1), 5) > 0;
Relative Strength Calculation
Compare total gains to total losses for custom RS ratios:
// ratio of gains to losses over 14 periods
sum(gain(close), 14) / sum(loss(close), 14) > 1;
Relationship to SMA
Sum and SMA are related mathematically:
// these are equivalent: sum = sma * period
sum(close, 20) ~= sma(close, 20) * 20;
Returns
Float (total of all values in the rolling window)
Notes
- The window always contains exactly N values (current bar + N-1 previous)
- For cumulative totals from the start of data, use cumsum() instead