Search code examples
sessionvolumecumulative-sumpine-script

Compute the cumulative volume within the session in pine-script


I want to compute the cumulative volume of bars - within each trading session - in pine-script (TradingView.com). I wrote the script below but I get error "Script could not be translated from: for i = 1 to session_bar_counter"

I've tried the below solution but it does not work.

session_timeframe = input(defval='D', type=resolution)

// Bars since session started:
session_bar_counter = n - valuewhen(change(time(session_timeframe)) != 0, n, 0)

CumVol() =>
    for i = 1 to session_bar_counter
                sum = 0.0
        sum := session_timeframe ? cum(nz(volume[i])) : na
        sum

plot(series=CumVol(), title="Cumulative volume", color=red, linewidth=4)

The expected result should be a line chart resetting each day and cumulative volume. For instance, for the first bar of the session, the value will be the volume for that bar. At the second bar, the value will be the volume[1] (volume at previous bar) + volume at current bar.


Solution

  • //version=3
    
    study("[FMF] Volume Buzz v2", shorttitle="[FMF] Volume Buzz", overlay=true)
    
    session_timeframe = input(defval='D', type=resolution)
    session_bar_counter = n - valuewhen(change(time(session_timeframe)) != 0, n, 0)
    
    CumVol(TimeFrame, Period) => 
        sum = volume
        for i = 1 to Period 
            sum := sum + nz(volume[i]) 
        sum 
    plot(CumVol(session_timeframe,session_bar_counter), color=green)