Volume Nodes [ITA]

itamardrori_ · study · 349 行 · 点赞 59 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// © ITA Trading Tools - itamardrori_
//@version=6
// =============================================================================
// Volume Nodes [ITA]
//
// Price alone says where the market turned. Volume says where it actually did
// business. A high volume node is a price zone where a large share of the
// period's volume changed hands, and traders mark these by hand from a volume
// profile because price tends to slow down when it comes back to them.
//
// This builds the profile from the last 250 bars, finds the real peaks in it,
// and draws each one across the chart as a zone: green under price, red above
// it, gold if price is inside. A small panel names the nearest node above and
// below, so the question "where is the next wall" has an answer on screen.
//
// Three decisions worth stating:
//
//   closed bars   the profile is built from closed bars only, so the zones do
//                 not move while a bar is forming.
//
//   peaks         a node has to be a local peak of the smoothed profile. The
//                 tallest rows are not enough: without this the rows next to
//                 the biggest peak would be reported as more nodes.
//
//   the smear     chart bars have no volume-at-price inside them, so each
//                 bar's volume is spread over its own high-low range. It is an
//                 estimate, and a good one over hundreds of bars.
// =============================================================================
 
indicator("Volume Nodes [ITA]", overlay = true, max_boxes_count = 500, max_labels_count = 50, max_lines_count = 10)
 
// ─── INPUTS ──────────────────────────────────────────────────────────────────
grpCalc  = "Calculation"
lookback = input.int(250, "Bars In The Profile", minval = 30, maxval = 2000, group = grpCalc,
     tooltip = "How much history the profile is built from. 250 is about one trading year on a daily chart.")
rowCount = input.int(80, "Price Rows", minval = 20, maxval = 150, group = grpCalc,
     tooltip = "How finely the price range is cut. More rows give narrower zones.")
maxNodes = input.int(6, "Nodes To Draw", minval = 1, maxval = 10, group = grpCalc)
edgePct  = input.float(75, "Node Edge, Percent Of Its Peak", minval = 50, maxval = 95, step = 5, group = grpCalc,
     tooltip = "A zone ends where the profile falls below this share of its own peak. Higher gives tighter zones.")
 
grpShow     = "Display"
showProfile = input.bool(true, "Show The Profile", group = grpShow)
showBands   = input.bool(true, "Show The Zones", group = grpShow)
showLabels  = input.bool(true, "Label The Zones", group = grpShow)
showPanel   = input.bool(true, "Show The Panel", group = grpShow)
profWidth   = input.int(40, "Profile Width In Bars", minval = 10, maxval = 200, group = grpShow)
profOffset  = input.int(6, "Profile Offset From Last Bar", minval = 0, maxval = 100, group = grpShow,
     tooltip = "The profile grows to the left from this point, so it stays on screen without scrolling.")
statPos     = input.string("Top Right", "Panel Position",
     options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpShow)
statSizeStr = input.string("Normal", "Panel Text Size",
     options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpShow)
 
grpCol  = "Colors"
belowCol  = input.color(#089981, "Node Below Price", group = grpCol)
aboveCol  = input.color(#f23645, "Node Above Price", group = grpCol)
insideCol = input.color(#e5c56b, "Price Inside Node And POC", group = grpCol)
plainCol  = input.color(#787b86, "Rest Of The Profile", group = grpCol)
 
sizeOf(string s) =>
    r = size.normal
    if s == "Tiny"
        r := size.tiny
    else if s == "Small"
        r := size.small
    else if s == "Large"
        r := size.large
    else if s == "Huge"
        r := size.huge
    r
 
posOf(string s) =>
    r = position.top_right
    if s == "Top Left"
        r := position.top_left
    else if s == "Bottom Right"
        r := position.bottom_right
    else if s == "Bottom Left"
        r := position.bottom_left
    r
 
statSize = sizeOf(statSizeStr)
 
// ─── THE HISTORY ─────────────────────────────────────────────────────────────
// Kept in arrays rather than read with high[i], so a long lookback can never
// run into the history buffer limit.
var array<float> hH = array.new<float>()
var array<float> hL = array.new<float>()
var array<float> hV = array.new<float>()
 
if barstate.isconfirmed and not na(volume)
    array.push(hH, high)
    array.push(hL, low)
    array.push(hV, volume)
    if array.size(hV) > lookback
        array.shift(hH)
        array.shift(hL)
        array.shift(hV)
 
// ─── STATE ───────────────────────────────────────────────────────────────────
var array<float> nLo = array.new<float>()
var array<float> nHi = array.new<float>()
 
var array<box>   drawnBoxes  = array.new<box>()
var array<line>  drawnLines  = array.new<line>()
var array<label> drawnLabels = array.new<label>()
 
var float pocPrice = na
var bool  noVolume = false
 
// Only when a bar has closed, and once on load. The forming bar never moves
// the zones.
build = barstate.islastconfirmedhistory or (barstate.isrealtime and barstate.isconfirmed)
n     = array.size(hV)
 
colorOf(float lo, float hi) =>
    close > hi ? belowCol : close < lo ? aboveCol : insideCol
 
// ─── THE BUILD ───────────────────────────────────────────────────────────────
if build and n >= 10
    for bx in drawnBoxes
        box.delete(bx)
    for ln in drawnLines
        line.delete(ln)
    for lb in drawnLabels
        label.delete(lb)
    array.clear(drawnBoxes)
    array.clear(drawnLines)
    array.clear(drawnLabels)
    array.clear(nLo)
    array.clear(nHi)
 
    pMax  = array.max(hH)
    pMin  = array.min(hL)
    rowH  = (pMax - pMin) / rowCount
    total = array.sum(hV)
    noVolume := total <= 0
 
    if rowH > 0 and total > 0
        // Each bar's volume goes to the rows its range covers, in proportion
        // to how much of the range each row holds.
        raw = array.new<float>(rowCount, 0.0)
        for b = 0 to n - 1
            bHi = array.get(hH, b)
            bLo = array.get(hL, b)
            bV  = array.get(hV, b)
            rFrom = math.min(rowCount - 1, math.max(0, int(math.floor((bLo - pMin) / rowH))))
            rTo   = math.min(rowCount - 1, math.max(0, int(math.floor((bHi - pMin) / rowH))))
            if bHi <= bLo
                array.set(raw, rFrom, array.get(raw, rFrom) + bV)
            else
                for r = rFrom to rTo
                    rowBot  = pMin + r * rowH
                    overlap = math.min(bHi, rowBot + rowH) - math.max(bLo, rowBot)
                    if overlap > 0
                        array.set(raw, r, array.get(raw, r) + bV * overlap / (bHi - bLo))
 
        // A short smoothing pass, so one noisy row is not called a peak.
        smooth = array.new<float>(rowCount, 0.0)
        for i = 0 to rowCount - 1
            sumV = 0.0
            sumW = 0.0
            for k = -2 to 2
                j = i + k
                if j >= 0 and j < rowCount
                    wt = 3.0 - math.abs(k)
                    sumV += array.get(raw, j) * wt
                    sumW += wt
            array.set(smooth, i, sumV / sumW)
 
        maxV  = array.max(smooth)
        meanV = array.avg(smooth)
 
        // A row is a peak only if nothing near it is taller.
        peaks  = array.new<int>()
        radius = 3
        for i = 0 to rowCount - 1
            v = array.get(smooth, i)
            isPeak = v > meanV * 1.05
            if isPeak
                for k = -radius to radius
                    j = i + k
                    if k != 0 and j >= 0 and j < rowCount
                        o = array.get(smooth, j)
                        if o > v or (o == v and k < 0)
                            isPeak := false
            if isPeak
                array.push(peaks, i)
 
        // Tallest first. Each node claims its rows, so a shoulder of a big
        // node can never come back as a second one.
        taken   = array.new<bool>(rowCount, false)
        rowNode = array.new<int>(rowCount, -1)
        halfCap = math.max(2, int(rowCount / 20))
        nShare  = array.new<float>()
        nVisits = array.new<int>()
 
        while array.size(nLo) < maxNodes and array.size(peaks) > 0
            bestPos = 0
            bestV   = -1.0
            for p = 0 to array.size(peaks) - 1
                pv = array.get(smooth, array.get(peaks, p))
                if pv > bestV
                    bestV   := pv
                    bestPos := p
            best = array.remove(peaks, bestPos)
 
            if not array.get(taken, best)
                floorV = bestV * edgePct / 100.0
                rLow   = best
                rHigh  = best
                // Walks down each side of the peak and stops at the edge, at
                // a neighbouring node, or where the profile starts rising.
                while rLow > 0 and best - rLow < halfCap and not array.get(taken, rLow - 1) and array.get(smooth, rLow - 1) >= floorV and array.get(smooth, rLow - 1) <= array.get(smooth, rLow) * 1.01
                    rLow -= 1
                while rHigh < rowCount - 1 and rHigh - best < halfCap and not array.get(taken, rHigh + 1) and array.get(smooth, rHigh + 1) >= floorV and array.get(smooth, rHigh + 1) <= array.get(smooth, rHigh) * 1.01
                    rHigh += 1
 
                zoneVol = 0.0
                idx = array.size(nLo)
                for r = rLow to rHigh
                    array.set(taken, r, true)
                    array.set(rowNode, r, idx)
                    zoneVol += array.get(raw, r)
 
                zLo = pMin + rLow * rowH
                zHi = pMin + (rHigh + 1) * rowH
 
                // A visit is one unbroken run of bars touching the zone.
                visits = 0
                wasIn  = false
                for b = 0 to n - 1
                    touching = array.get(hH, b) >= zLo and array.get(hL, b) <= zHi
                    if touching and not wasIn
                        visits += 1
                    wasIn := touching
 
                array.push(nLo, zLo)
                array.push(nHi, zHi)
                array.push(nShare, zoneVol / total * 100.0)
                array.push(nVisits, visits)
 
        pocRow = array.indexof(smooth, maxV)
        pocPrice := pMin + (pocRow + 0.5) * rowH
 
        // ─── THE DRAWING ─────────────────────────────────────────────────────
        xRight = bar_index + profOffset
        xLeft  = bar_index - n + 1
        count  = array.size(nLo)
 
        if showBands and count > 0
            for i = 0 to count - 1
                zLo  = array.get(nLo, i)
                zHi  = array.get(nHi, i)
                c    = colorOf(zLo, zHi)
                fade = count > 1 ? 14.0 * i / (count - 1) : 0.0
                array.push(drawnBoxes, box.new(xLeft, zHi, xRight, zLo, border_color = color.new(c, 55), border_width = 1, bgcolor = color.new(c, 72 + fade)))
 
        if showProfile
            for r = 0 to rowCount - 1
                w = int(math.round(profWidth * array.get(smooth, r) / maxV))
                if w >= 1
                    node    = array.get(rowNode, r)
                    rowLo   = pMin + r * rowH
                    rowHi   = rowLo + rowH * 0.9
                    rowCol  = color.new(plainCol, 68)
                    if node >= 0
                        rowCol := color.new(colorOf(array.get(nLo, node), array.get(nHi, node)), 35)
                    if r == pocRow
                        rowCol := color.new(insideCol, 10)
                    array.push(drawnBoxes, box.new(xRight - w, rowHi, xRight, rowLo, border_color = color.new(color.white, 100), border_width = 0, bgcolor = rowCol))
 
        array.push(drawnLines, line.new(xLeft, pocPrice, xRight, pocPrice, color = color.new(insideCol, 15), width = 1, style = line.style_dashed))
 
        if showLabels and count > 0
            for i = 0 to count - 1
                zLo = array.get(nLo, i)
                zHi = array.get(nHi, i)
                txt = str.tostring(array.get(nShare, i), "#.#") + "%"
                tip = str.tostring(array.get(nShare, i), "#.#") + "% of the volume, " + str.tostring(array.get(nVisits, i)) + " visits, " + str.tostring(zLo, format.mintick) + " - " + str.tostring(zHi, format.mintick)
                // To the right of the profile, where there are no candles.
                // Anywhere inside the chart a node zone is by definition full
                // of candles, and the candles are drawn over the labels.
                array.push(drawnLabels, label.new(xRight + 1, (zLo + zHi) / 2, txt, style = label.style_label_left, color = color.new(#131722, 12), textcolor = colorOf(zLo, zHi), size = size.small, tooltip = tip))
 
// ─── NEAREST NODES ───────────────────────────────────────────────────────────
// This part runs on every tick, on zones that were fixed at the last close.
insideNow = false
float upLo = na
float upHi = na
float dnLo = na
float dnHi = na
 
if barstate.islast and array.size(nLo) > 0
    for i = 0 to array.size(nLo) - 1
        zLo = array.get(nLo, i)
        zHi = array.get(nHi, i)
        if close > zHi
            if na(dnHi) or zHi > dnHi
                dnLo := zLo
                dnHi := zHi
        else if close < zLo
            if na(upLo) or zLo < upLo
                upLo := zLo
                upHi := zHi
        else
            insideNow := true
 
var bool wasInside = false
enteredNode = barstate.islast and insideNow and not wasInside
leftNode    = barstate.islast and wasInside and not insideNow
if barstate.islast
    wasInside := insideNow
 
// ─── THE PANEL ───────────────────────────────────────────────────────────────
rangeText(float lo, float hi) =>
    na(lo) ? "none in range" : str.tostring(lo, format.mintick) + " - " + str.tostring(hi, format.mintick)
 
distText(float edge) =>
    na(edge) ? "" : str.tostring((edge - close) / close * 100.0, "+#.#;-#.#") + "%"
 
var table panel = na
if showPanel and barstate.islast
    if na(panel)
        panel := table.new(posOf(statPos), 3, 4, border_width = 1)
    txtCol = color.new(color.white, 25)
    table.cell(panel, 0, 0, "VOLUME NODES", text_color = insideCol, text_size = statSize, text_halign = text.align_left)
    table.cell(panel, 1, 0, insideNow ? "Price inside a node" : "", text_color = insideCol, text_size = statSize)
    table.cell(panel, 2, 0, "", text_size = statSize)
 
    if noVolume or n == 0
        table.cell(panel, 0, 1, "This symbol has no volume data.", text_color = txtCol, text_size = statSize)
    else if n < 10
        table.cell(panel, 0, 1, "Needs at least 10 closed bars.", text_color = txtCol, text_size = statSize)
    else
        table.cell(panel, 0, 1, "Next node above", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 1, rangeText(upLo, upHi), text_color = aboveCol, text_size = statSize)
        table.cell(panel, 2, 1, distText(upLo), text_color = aboveCol, text_size = statSize)
        table.cell(panel, 0, 2, "Next node below", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 2, rangeText(dnLo, dnHi), text_color = belowCol, text_size = statSize)
        table.cell(panel, 2, 2, distText(dnHi), text_color = belowCol, text_size = statSize)
        table.cell(panel, 0, 3, "Point of control", text_color = txtCol, text_size = statSize, text_halign = text.align_left)
        table.cell(panel, 1, 3, na(pocPrice) ? "" : str.tostring(pocPrice, format.mintick), text_color = insideCol, text_size = statSize)
        table.cell(panel, 2, 3, distText(pocPrice), text_color = insideCol, text_size = statSize)
 
// ─── ALERTS ──────────────────────────────────────────────────────────────────
alertcondition(enteredNode, "Price entered a node", "Price entered a high volume node.")
alertcondition(leftNode, "Price left a node", "Price left a high volume node.")

← 返回列表