Session Volume Profile

Volume at each price per session, with POC and value area.

// Session Volume Profile: one volume profile per session, built from 1-minute bars on any chart timeframe.
// - Data: request.security_lower_tf reads the closed 1-minute bars inside each chart bar (about a month of
//   them is loaded, so older chart bars get no profile). Each minute's volume is spread evenly over the
//   ticks from its low to its high; it is up volume when the minute closes up (close > open, or
//   close == open and close >= the previous minute's close), else down volume.
// - Sessions: "Trading day" is one profile per CME trading day (17:00 to 16:00 Chicago time). "Custom" is
//   one profile per day for each session switched on (up to 4, HHMM-HHMM in the chosen time zone); a minute
//   belongs to the first session that contains its open. A session that started before the loaded
//   1-minute data is not drawn (it would be incomplete).
// - Rows: "Number of Rows" picks a whole number of ticks per row so the row count is closest to Row size;
//   "Ticks Per Row" uses Row size ticks per row. Rows run from the session low to the session high, drawn
//   with a small gap between them.
// - POC: the row with the most volume (the lowest one on a tie), drawn at the middle of the row.
// - Value area: starts at the POC row and adds the larger neighbour row (above wins a tie) until it holds
//   the asked share of the session volume. VAH is the top of its highest row, VAL the bottom of its lowest.
// - POC zones: a rectangle around the POC row of each of the last N finished sessions.
// - A session's profile is final once a minute outside it arrives (no look-ahead); the running session is
//   redrawn on the last bar. Extended POC / VAH / VAL lines stop at the first later chart bar that trades
//   through them. At most 500 boxes: the oldest whole sessions are removed to make room.
indicator("Session Volume Profile", shorttitle="SVP", overlay=true, max_boxes_count=500, max_lines_count=500)

GRP_SESS = "Sessions"
GRP_ROWS = "Profile"
GRP_LINES = "Lines"
GRP_ZONES = "POC zones"
GRP_COLORS = "Colors"
MAX_BOXES = 500
MAX_LINES = 500
WINDOW_TIP = "HHMM-HHMM in the time zone above. A window may cross midnight; the same start and end is a whole day."

sessMode = input.string("Trading day", "Sessions", options=["Trading day", "Custom"], group=GRP_SESS, tooltip="Trading day: one profile per CME trading day (17:00 to 16:00 Chicago time). Custom: one profile per day for each session switched on below.")
tz = input.string("America/New_York", "Time zone", options=["America/New_York", "America/Chicago", "Europe/London", "UTC"], group=GRP_SESS)
on1 = input.bool(true, "Session 1", inline="s1", group=GRP_SESS)
win1 = input.string("0930-1600", "Session 1 window", inline="s1", group=GRP_SESS, tooltip=WINDOW_TIP)
on2 = input.bool(false, "Session 2", inline="s2", group=GRP_SESS)
win2 = input.string("1800-0300", "Session 2 window", inline="s2", group=GRP_SESS, tooltip=WINDOW_TIP)
on3 = input.bool(false, "Session 3", inline="s3", group=GRP_SESS)
win3 = input.string("0300-0930", "Session 3 window", inline="s3", group=GRP_SESS, tooltip=WINDOW_TIP)
on4 = input.bool(false, "Session 4", inline="s4", group=GRP_SESS)
win4 = input.string("1600-1700", "Session 4 window", inline="s4", group=GRP_SESS, tooltip=WINDOW_TIP)

layout = input.string("Number of Rows", "Rows layout", options=["Number of Rows", "Ticks Per Row"], group=GRP_ROWS)
rowSize = input.int(24, "Row size", minval=1, maxval=1000, group=GRP_ROWS)
volMode = input.string("Up/Down", "Volume", options=["Up/Down", "Total", "Delta"], group=GRP_ROWS)
vaPct = input.int(70, "Value area volume %", minval=1, maxval=100, group=GRP_ROWS)
showProfile = input.bool(true, "Show profile", group=GRP_ROWS)
widthPct = input.int(30, "Width (% of the session)", minval=1, maxval=100, group=GRP_ROWS)
placement = input.string("Left", "Placement", options=["Left", "Right"], group=GRP_ROWS)
rowGap = input.int(12, "Row gap (% of a row)", minval=0, maxval=60, group=GRP_ROWS)

showPoc = input.bool(true, "POC", inline="poc", group=GRP_LINES)
pocColor = input.color(color.amber, "POC color", inline="poc", group=GRP_LINES)
extendPoc = input.bool(false, "Extend POC right", inline="poc", group=GRP_LINES)
showVah = input.bool(true, "VAH", inline="vah", group=GRP_LINES)
vahColor = input.color(color.slate, "VAH color", inline="vah", group=GRP_LINES)
extendVah = input.bool(false, "Extend VAH right", inline="vah", group=GRP_LINES)
showVal = input.bool(true, "VAL", inline="val", group=GRP_LINES)
valColor = input.color(color.slate, "VAL color", inline="val", group=GRP_LINES)
extendVal = input.bool(false, "Extend VAL right", inline="val", group=GRP_LINES)
lineWidth = input.int(1, "Line width", minval=1, maxval=4, group=GRP_LINES)
showDev = input.bool(false, "Developing POC and value area", group=GRP_LINES, tooltip="Plots the POC, VAH and VAL as they were at the end of each bar of the session. Slower on long charts.")

showZones = input.bool(false, "POC zones", inline="zone", group=GRP_ZONES, tooltip="A rectangle around the POC row of each of the last finished sessions.")
zoneCount = input.int(5, "Last sessions", minval=1, maxval=50, inline="zone", group=GRP_ZONES)
zoneColor = input.color(color.new(color.amber, 85), "Zone fill", group=GRP_ZONES)
zoneBorder = input.color(color.new(color.amber, 40), "Zone border", group=GRP_ZONES)
zoneExtend = input.bool(true, "Extend zones to the latest bar", group=GRP_ZONES)

upColor = input.color(color.new(color.teal, 75), "Up volume", group=GRP_COLORS)
downColor = input.color(color.new(color.clay, 75), "Down volume", group=GRP_COLORS)
vaUpColor = input.color(color.new(color.teal, 45), "Value area up", group=GRP_COLORS)
vaDownColor = input.color(color.new(color.clay, 45), "Value area down", group=GRP_COLORS)

tick = syminfo.mintick > 0 ? syminfo.mintick : 0.01
upDown = volMode == "Up/Down"
// boxes per row; rows are capped so one session always fits in the box limit
boxesPerRow = upDown ? 2 : 1
maxRows = int(MAX_BOXES / boxesPerRow / 2)
zoneRoom = showZones ? zoneCount : 0
zoneName = sessMode == "Trading day" ? "America/Chicago" : tz

// ---------- session windows (minutes since midnight in zoneName), read once ----------

var winStarts = array.new_int(0)
var winEnds = array.new_int(0)

// Adds the window "HHMM-HHMM" (stops the script when it is malformed).
addWindow(name, text) =>
    parts = str.split(text, "-")
    a = parts.size() == 2 ? str.tonumber(parts.get(0)) : na
    b = parts.size() == 2 ? str.tonumber(parts.get(1)) : na
    if na(a) or na(b) or a % 100 >= 60 or b % 100 >= 60 or a >= 2400 or b >= 2400 or a < 0 or b < 0
        runtime.error(name + " must look like 0930-1600 (HHMM-HHMM), got " + text)
    winStarts.push(math.floor(a / 100) * 60 + int(a % 100))
    winEnds.push(math.floor(b / 100) * 60 + int(b % 100))
    0

if barstate.isfirst
    if sessMode == "Trading day"
        winStarts.push(1020)
        winEnds.push(1020)
    else
        if on1
            addWindow("Session 1", win1)
        if on2
            addWindow("Session 2", win2)
        if on3
            addWindow("Session 3", win3)
        if on4
            addWindow("Session 4", win4)

// Index of the first window holding minute m, or -1.
windowOf(m) =>
    int found = -1
    for [w, s] in winStarts
        e = winEnds.get(w)
        inside = s < e ? m >= s and m < e : s > e ? m >= s or m < e : true
        if inside
            found := w
            break
    found

// Minutes from the start of window w to minute m (0 to 1439): it drops when a new day of the window begins.
phase(m, w) => (m - winStarts.get(w) + 1440) % 1440

// ---------- state ----------

// volume per tick of the running session, index 0 = the tick at baseTick * tick (the session low)
var upTicks = array.new_float(0)
var downTicks = array.new_float(0)
var int baseTick = na
var bool active = false
// the running session began before the loaded 1-minute data (incomplete, not drawn)
var bool partial = false
var int curWin = -1
var int sessStart = na
var int sessEnd = na
// the previous 1-minute bar
var float prevTime = na
var int prevMin = 0
var float prevClose = na
// work arrays: volume per row, bottom row first
var rowUp = array.new_float(0)
var rowDown = array.new_float(0)
// developing values: rows kept up to date minute by minute, rebuilt only when the session range grows
var devUp = array.new_float(0)
var devDown = array.new_float(0)
var int devTicks = na
var int devBase = na
var int devSize = na
// drawings of finished sessions (oldest first) and how many each session has
var doneBoxes = array.new_box(0)
var doneLines = array.new_line(0)
var sessBoxCount = array.new_int(0)
var sessLineCount = array.new_int(0)
// drawings of the running session (redrawn on the last bar)
var curBoxes = array.new_box(0)
var curLines = array.new_line(0)
// extended lines that no bar has traded through yet, and their prices
var extLines = array.new_line(0)
var extPrices = array.new_float(0)
// POC zones of the last finished sessions, oldest first
var zoneBoxes = array.new_box(0)

// Sums the tick levels into rows: fills up and down (one element per row, bottom row first) and
// returns the ticks per row.
fillRows(up, down) =>
    span = upTicks.size() - 1
    int rowTicks = rowSize
    if layout == "Number of Rows"
        fewer = math.max(1, math.floor(span / rowSize))
        more = math.max(1, math.ceil(span / rowSize))
        rowTicks := math.abs(math.ceil(span / fewer) - rowSize) <= math.abs(math.ceil(span / more) - rowSize) ? fewer : more
    rowTicks := math.max(rowTicks, math.ceil(span / maxRows))
    rowCount = math.max(1, math.ceil(span / rowTicks))
    up.clear()
    down.clear()
    for r = 1 to rowCount
        up.push(0.0)
        down.push(0.0)
    for [k, u] in upTicks
        row = math.min(math.floor(k / rowTicks), rowCount - 1)
        up.set(row, up.get(row) + u)
        down.set(row, down.get(row) + downTicks.get(k))
    rowTicks

// The point of control row and the value area rows of the rows in up and down: [poc, vaLow, vaHigh].
valueArea(up, down) =>
    rowCount = up.size()
    total = 0.0
    best = -1.0
    poc = 0
    for [i, u] in up
        v = u + down.get(i)
        total += v
        if v > best
            best := v
            poc := i
    lo = poc
    hi = poc
    inArea = best
    target = total * vaPct / 100
    while inArea < target and (lo > 0 or hi < rowCount - 1)
        above = hi < rowCount - 1 ? up.get(hi + 1) + down.get(hi + 1) : -1.0
        below = lo > 0 ? up.get(lo - 1) + down.get(lo - 1) : -1.0
        if above >= below
            hi += 1
            inArea += above
        else
            lo -= 1
            inArea += below
    [poc, lo, hi]

// Deletes the oldest finished sessions until room more boxes and lineRoom more lines fit under the limits
// (the POC zones keep their own room).
makeRoom(room, lineRoom) =>
    while (doneBoxes.size() + room + zoneRoom > MAX_BOXES or doneLines.size() + lineRoom > MAX_LINES) and sessBoxCount.size() > 0
        nb = sessBoxCount.shift()
        if nb > 0
            for j = 1 to nb
                box.delete(doneBoxes.shift())
        nl = sessLineCount.shift()
        if nl > 0
            for j = 1 to nl
                line.delete(doneLines.shift())
    0

// Price edges of row i (rows run from lowPrice up; the top row ends at the session high).
rowBottom(lowPrice, rowHeight, i) => lowPrice + i * rowHeight
rowTop(lowPrice, highPrice, rowHeight, rowCount, i) => i == rowCount - 1 ? highPrice : lowPrice + (i + 1) * rowHeight

// One row segment from x a to x b (either order), rowGap % of the row height shorter so rows stand apart.
segment(a, b, top, bottom, col, boxes) =>
    if b != a
        gap = (top - bottom) * rowGap / 200
        boxes.push(box.new(math.min(a, b), top - gap, math.max(a, b), bottom + gap, border_color=na, bgcolor=col))
    0

// One POC / VAH / VAL line from bar x1 to x2; finished sessions may extend it to the right.
level(x1, x2, price, col, extendIt, isFinal, lines) =>
    l = line.new(x1, price, x2, price, color=col, width=lineWidth)
    lines.push(l)
    if isFinal and extendIt
        extLines.push(l)
        extPrices.push(price)
    0

// Draws the profile of the session in upTicks / downTicks, from bar x1 to bar x2, after removing old
// sessions to make room. Returns [boxes added, lines added, POC row top, POC row bottom].
drawProfile(x1, x2, isFinal, boxes, lines) =>
    rowTicks = fillRows(rowUp, rowDown)
    [poc, vaLow, vaHigh] = valueArea(rowUp, rowDown)
    rowCount = rowUp.size()
    lowPrice = baseTick * tick
    highPrice = (baseTick + upTicks.size() - 1) * tick
    rowHeight = rowTicks * tick
    makeRoom(showProfile ? rowCount * boxesPerRow : 0, 3)
    boxesBefore = boxes.size()
    linesBefore = lines.size()
    if showProfile
        biggest = 0.0
        for [i, u] in rowUp
            d = rowDown.get(i)
            biggest := math.max(biggest, volMode == "Delta" ? math.abs(u - d) : u + d)
        // the biggest row is widthPct % of the session wide
        full = (x2 - x1 + 1) * widthPct / 100
        left = placement == "Left"
        anchor = left ? x1 : x2
        dir = left ? 1 : -1
        if biggest > 0
            for [i, u] in rowUp
                d = rowDown.get(i)
                inVa = i >= vaLow and i <= vaHigh
                cUp = inVa ? vaUpColor : upColor
                cDown = inVa ? vaDownColor : downColor
                top = rowTop(lowPrice, highPrice, rowHeight, rowCount, i)
                bottom = rowBottom(lowPrice, rowHeight, i)
                if upDown
                    wUp = full * u / biggest
                    wDown = full * d / biggest
                    segment(anchor, anchor + dir * wUp, top, bottom, cUp, boxes)
                    segment(anchor + dir * wUp, anchor + dir * (wUp + wDown), top, bottom, cDown, boxes)
                else if volMode == "Total"
                    segment(anchor, anchor + dir * full * (u + d) / biggest, top, bottom, cUp, boxes)
                else
                    segment(anchor, anchor + dir * full * math.abs(u - d) / biggest, top, bottom, u >= d ? cUp : cDown, boxes)
    pocTop = rowTop(lowPrice, highPrice, rowHeight, rowCount, poc)
    pocBottom = rowBottom(lowPrice, rowHeight, poc)
    if showPoc
        level(x1, x2, (pocTop + pocBottom) / 2, pocColor, extendPoc, isFinal, lines)
    if showVah
        level(x1, x2, rowTop(lowPrice, highPrice, rowHeight, rowCount, vaHigh), vahColor, extendVah, isFinal, lines)
    if showVal
        level(x1, x2, rowBottom(lowPrice, rowHeight, vaLow), valColor, extendVal, isFinal, lines)
    [boxes.size() - boxesBefore, lines.size() - linesBefore, pocTop, pocBottom]

clearCurrent() =>
    for b in curBoxes
        box.delete(b)
    for l in curLines
        line.delete(l)
    curBoxes.clear()
    curLines.clear()
    0

// ---------- the 1-minute bars of this chart bar, one at a time ----------

[mTime, mOpen, mHigh, mLow, mClose, mVol] = request.security_lower_tf(syminfo.tickerid, "1", [time, open, high, low, close, volume])

if mTime.size() > 0
    // midnight of the chart bar's exchange date in the session zone; minutes past a day wrap with % 1440
    zoneMidnight = timestamp(zoneName, year, month, dayofmonth)
    for [j, t] in mTime
        m = int(((t - zoneMidnight) / 60000 % 1440 + 1440) % 1440)
        w = windowOf(m)
        // the same window starts a new day: its start was passed, or a day or more of data is missing
        newDay = w >= 0 and w == curWin and not na(prevTime) and (t - prevTime >= 86400000 or phase(m, w) < phase(prevMin, w))

        // a session ends: draw its final profile
        if active and (w != curWin or newDay)
            clearCurrent()
            if not partial and not na(baseTick)
                [addedBoxes, addedLines, pocTop, pocBottom] = drawProfile(sessStart, sessEnd, true, doneBoxes, doneLines)
                sessBoxCount.push(addedBoxes)
                sessLineCount.push(addedLines)
                if showZones
                    if zoneBoxes.size() >= zoneCount
                        box.delete(zoneBoxes.shift())
                    zoneBoxes.push(box.new(sessStart, pocTop, zoneExtend ? bar_index : sessEnd, pocBottom, border_color=zoneBorder, bgcolor=zoneColor))
            active := false

        // a session starts
        if w >= 0 and not active
            upTicks.clear()
            downTicks.clear()
            baseTick := na
            devBase := na
            sessStart := bar_index
            sessEnd := bar_index
            active := true
            // the first loaded minute only starts a whole session when it is the window's first minute
            partial := na(prevTime) and m != winStarts.get(w)

        // add this minute's volume
        o = mOpen.get(j)
        c = mClose.get(j)
        v = mVol.get(j)
        hi = mHigh.get(j)
        lo = mLow.get(j)
        if active
            sessEnd := bar_index
        if active and not na(v) and v > 0 and not na(hi) and not na(lo)
            lowTick = math.round(lo / tick)
            highTick = math.max(lowTick, math.round(hi / tick))
            if na(baseTick)
                baseTick := lowTick
            while lowTick < baseTick
                upTicks.unshift(0.0)
                downTicks.unshift(0.0)
                baseTick -= 1
            while baseTick + upTicks.size() - 1 < highTick
                upTicks.push(0.0)
                downTicks.push(0.0)
            isUp = c > o or (c == o and c >= nz(prevClose, c))
            share = v / (highTick - lowTick + 1)
            for k = lowTick - baseTick to highTick - baseTick
                if isUp
                    upTicks.set(k, upTicks.get(k) + share)
                else
                    downTicks.set(k, downTicks.get(k) + share)
            if showDev
                if na(devBase) or baseTick != devBase or upTicks.size() != devSize
                    devTicks := fillRows(devUp, devDown)
                    devBase := baseTick
                    devSize := upTicks.size()
                else
                    // same rows as before: add this minute's ticks row by row
                    rowCount = devUp.size()
                    kLow = lowTick - baseTick
                    kHigh = highTick - baseTick
                    for r = math.min(math.floor(kLow / devTicks), rowCount - 1) to math.min(math.floor(kHigh / devTicks), rowCount - 1)
                        first = math.max(kLow, r * devTicks)
                        last = r == rowCount - 1 ? kHigh : math.min(kHigh, (r + 1) * devTicks - 1)
                        if isUp
                            devUp.set(r, devUp.get(r) + share * (last - first + 1))
                        else
                            devDown.set(r, devDown.get(r) + share * (last - first + 1))
        curWin := w
        prevTime := t
        prevMin := m
        prevClose := c

// ---------- extended lines and zones follow the newest bar ----------

if extLines.size() > 0
    for j = extLines.size() - 1 to 0
        l = extLines.get(j)
        l.set_x2(bar_index)
        p = extPrices.get(j)
        // a line stops at the first bar that trades through it
        if high >= p and low <= p
            extLines.remove(j)
            extPrices.remove(j)

if zoneExtend
    for z in zoneBoxes
        z.set_right(bar_index)

// ---------- the running session ----------

showing = active and not partial and not na(baseTick)
if barstate.islast and showing
    clearCurrent()
    [addedBoxes, addedLines, pocTop, pocBottom] = drawProfile(sessStart, sessEnd, false, curBoxes, curLines)

float devPoc = na
float devVah = na
float devVal = na
if showDev and showing and not na(devBase)
    [poc, vaLow, vaHigh] = valueArea(devUp, devDown)
    rowHeight = devTicks * tick
    lowPrice = devBase * tick
    highPrice = (devBase + devSize - 1) * tick
    rowCount = devUp.size()
    devPoc := (rowBottom(lowPrice, rowHeight, poc) + rowTop(lowPrice, highPrice, rowHeight, rowCount, poc)) / 2
    devVah := rowTop(lowPrice, highPrice, rowHeight, rowCount, vaHigh)
    devVal := rowBottom(lowPrice, rowHeight, vaLow)
plot(devPoc, "Developing POC", color=pocColor, style=plot.style_stepline)
plot(devVah, "Developing VAH", color=vahColor, style=plot.style_stepline)
plot(devVal, "Developing VAL", color=valColor, style=plot.style_stepline)