Volume Profile - POC VAH VAL

danishnaeem541 · study · 331 行 · 点赞 54 · TradingView 原页

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

Pine Script

//@version=6
indicator("Volume Profile - POC VAH VAL", shorttitle = "VP Levels", overlay = true, max_bars_back = 5000, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 200)
 
// ================= Inputs: profile (same as FRVP) =================
GP = "Profile"
GR = "Range"
GS = "Style"
GL = "Layout"
 
rowsLayout  = input.string("Number Of Rows", "Rows Layout", options = ["Number Of Rows", "Ticks Per Row"], group = GP, tooltip = "Number Of Rows: Row Size = how many rows the price range is cut into.\nTicks Per Row: Row Size = how many ticks (minimum price steps) each row is tall.\nMax 2000 rows. POC / VAH / VAL are calculated on all rows; the bars on the chart are drawn merged into at most 240 rows (TradingView drawing limit).")
rowSizeIn   = input.int(1000, "Row Size", minval = 1, maxval = 2000, group = GP)
volMode     = input.string("Up/Down", "Volume", options = ["Up/Down", "Total", "Delta"], group = GP, tooltip = "Up/Down: buy (up-candle) and sell (down-candle) volume stacked.\nTotal: all volume in one bar.\nDelta: buy minus sell per row.")
vaPct       = input.float(70.0, "Value Area Volume", minval = 10.0, maxval = 100.0, step = 1.0, group = GP)
extendRight = input.bool(false, "Extend Right", group = GP, tooltip = "Also extend POC / VAH / VAL to the right of the box.")
 
rangeMode = input.string("Visible Range", "Profile range", options = ["Visible Range", "Fixed Bars", "Session (Day)", "Week"], group = GR, tooltip = "Visible Range: profile of the bars on screen (updates when you scroll/zoom).\nFixed Bars: the last N bars.\nSession (Day) / Week: from the start of today / this week until now (live).")
lookback  = input.int(500, "Bars for 'Fixed Bars'", minval = 10, maxval = 5000, group = GR)
 
// ================= Inputs: style (same names as FRVP Style tab) =================
showProfile = input.bool(true, "Volume profile", group = GS)
showValues  = input.bool(false, "Values", group = GS, inline = "val")
valuesCol   = input.color(#787B86, "", group = GS, inline = "val")
widthPct    = input.int(30, "Width (% of the box)", minval = 1, maxval = 100, group = GS)
placement   = input.string("Left", "Placement", options = ["Left", "Right"], group = GS)
upVolCol    = input.color(color.new(#4A4F5C, 45), "Up Volume", group = GS)
dnVolCol    = input.color(color.new(#2B2F3A, 45), "Down Volume", group = GS)
vaUpCol     = input.color(color.new(#1FA3B5, 25), "Value Area Up", group = GS)
vaDnCol     = input.color(color.new(#C2386A, 25), "Value Area Down", group = GS)
 
showVAH  = input.bool(true, "VAH", group = GS, inline = "vah")
vahCol   = input.color(#E0E0E0, "", group = GS, inline = "vah")
vahStyle = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], group = GS, inline = "vah")
vahW     = input.int(1, "", minval = 1, maxval = 5, group = GS, inline = "vah")
showVAL  = input.bool(true, "VAL", group = GS, inline = "val2")
valCol   = input.color(#E0E0E0, "", group = GS, inline = "val2")
valStyle = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], group = GS, inline = "val2")
valW     = input.int(1, "", minval = 1, maxval = 5, group = GS, inline = "val2")
showPOC  = input.bool(true, "POC", group = GS, inline = "poc")
pocCol   = input.color(#E0E0E0, "", group = GS, inline = "poc")
pocStyle = input.string("Solid", "", options = ["Solid", "Dashed", "Dotted"], group = GS, inline = "poc")
pocW     = input.int(2, "", minval = 1, maxval = 5, group = GS, inline = "poc")
 
showDevPOC = input.bool(false, "Developing POC", group = GS, inline = "dpoc")
devPocCol  = input.color(#808080, "", group = GS, inline = "dpoc")
showDevVA  = input.bool(false, "Developing VA", group = GS, inline = "dva")
devVACol   = input.color(#17808E, "", group = GS, inline = "dva")
boxCol     = input.color(color.new(#0F4A55, 82), "Histogram Box", group = GS)
 
// ================= Inputs: layout =================
boxBars    = input.int(150, "Box width (bars)", minval = 10, maxval = 450, group = GL, tooltip = "The histogram box sits to the right of the last bar. 'Width (% of the box)' is a share of this. Give the chart enough right margin to see it.")
gapBars    = input.int(3, "Gap right of last bar (bars)", minval = 0, maxval = 40, group = GL)
extendLeft = input.bool(true, "Extend POC / VAH / VAL to the left", group = GL, tooltip = "On: the lines run from the box across the whole chart to the left. Off: they stop at the start of the profile range.")
showLabels = input.bool(true, "Show price labels", group = GL)
 
// ================= Helpers =================
styleOf(string s) =>
    s == "Dashed" ? line.style_dashed : s == "Dotted" ? line.style_dotted : line.style_solid
 
// spread one bar's volume over the rows its high-low range covers; returns the first and last row touched
addVol(array<float> arr, float v, float bl, float bh, float lo, float rowH, int rows) =>
    int r0 = math.max(0, math.min(rows - 1, int(math.floor((bl - lo) / rowH))))
    int r1 = math.max(0, math.min(rows - 1, int(math.floor((bh - lo) / rowH))))
    if r0 == r1 or bh <= bl
        arr.set(r0, arr.get(r0) + v)
        r1 := r0
    else
        float span = bh - bl
        for r = r0 to r1
            float rb = lo + r * rowH
            float ov = math.min(bh, rb + rowH) - math.max(bl, rb)
            if ov > 0
                arr.set(r, arr.get(r) + v * ov / span)
    [r0, r1]
 
// value area: grow from the POC by the larger pair of rows until the target volume is inside
calcVA(array<float> tot, int pocRow, int rows, float target) =>
    float acc = tot.get(pocRow)
    int lowR = pocRow
    int highR = pocRow
    while acc < target and (lowR > 0 or highR < rows - 1)
        float u1 = 0.0
        float u2 = 0.0
        float d1 = 0.0
        float d2 = 0.0
        if highR + 1 < rows
            u1 := tot.get(highR + 1)
        if highR + 2 < rows
            u2 := tot.get(highR + 2)
        if lowR - 1 >= 0
            d1 := tot.get(lowR - 1)
        if lowR - 2 >= 0
            d2 := tot.get(lowR - 2)
        bool goUp = true
        if highR >= rows - 1
            goUp := false
        else if lowR > 0
            goUp := (u1 + u2) >= (d1 + d2)
        if goUp
            acc += u1 + u2
            highR := math.min(rows - 1, highR + 2)
        else
            acc += d1 + d2
            lowR := math.max(0, lowR - 2)
    [lowR, highR]
 
// ================= Session start tracking =================
chgD = timeframe.change("D")
chgW = timeframe.change("W")
var int sessStart = 0
if (rangeMode == "Session (Day)" and chgD) or (rangeMode == "Week" and chgW)
    sessStart := bar_index
 
var array<line>  lns  = array.new<line>()
var array<label> lbls = array.new<label>()
var array<box>   bxs  = array.new<box>()
 
// ================= Build + draw on the live bar =================
if barstate.islast
    for l in lns
        line.delete(l)
    lns.clear()
    for lb in lbls
        label.delete(lb)
    lbls.clear()
    for bb in bxs
        box.delete(bb)
    bxs.clear()
 
    int maxI = math.min(bar_index, 4999)
    int iFrom = 0
    int iTo = 0
 
    if rangeMode == "Fixed Bars"
        iTo := math.min(lookback - 1, maxI)
    else if rangeMode == "Visible Range"
        bool found = false
        for i = 0 to maxI
            if time[i] > chart.right_visible_bar_time
                continue
            if time[i] < chart.left_visible_bar_time
                break
            if not found
                iFrom := i
                found := true
            iTo := i
    else
        iTo := math.min(bar_index - sessStart, maxI)
 
    // price range of the profile
    float hi = high[iFrom]
    float lo = low[iFrom]
    for i = iFrom to iTo
        hi := math.max(hi, high[i])
        lo := math.min(lo, low[i])
    if hi <= lo
        hi := lo + syminfo.mintick
 
    // rows
    int rows = rowSizeIn
    if rowsLayout == "Ticks Per Row"
        float rh = rowSizeIn * syminfo.mintick
        rows := math.max(1, math.min(2000, int(math.ceil((hi - lo) / rh))))
    float rowH = (hi - lo) / rows
 
    // volume per row, split by candle direction
    array<float> upV = array.new_float(rows, 0.0)
    array<float> dnV = array.new_float(rows, 0.0)
    for i = iFrom to iTo
        float v = nz(volume[i])
        if v > 0
            array<float> tgt = close[i] >= open[i] ? upV : dnV
            [ta0, ta1] = addVol(tgt, v, low[i], high[i], lo, rowH, rows)
 
    // totals, POC row
    array<float> tot = array.new_float(rows, 0.0)
    float maxV = 0.0
    float sumV = 0.0
    int pocRow = 0
    for r = 0 to rows - 1
        float t = upV.get(r) + dnV.get(r)
        tot.set(r, t)
        sumV += t
        if t > maxV
            maxV := t
            pocRow := r
 
    // histogram box geometry (right of the newest bar in the range)
    int anchorX = bar_index - iFrom
    int xlBox = anchorX + gapBars
    int xrBox = xlBox + boxBars
    bool leftP = placement == "Left"
    int base = leftP ? xlBox : xrBox
    int maxLen = math.max(1, int(math.round(boxBars * widthPct / 100.0)))
 
    if maxV <= 0
        lbls.push(label.new(bar_index, close, "No volume data for this symbol", style = label.style_label_left, color = color.new(color.gray, 20), textcolor = color.white))
    else
        [lowR, highR] = calcVA(tot, pocRow, rows, sumV * vaPct / 100.0)
 
        if showProfile
            bxs.push(box.new(xlBox, hi, xrBox, lo, xloc = xloc.bar_index, border_color = color(na), bgcolor = boxCol))
 
            // merge rows for drawing (max 240 drawn rows)
            int g = math.max(1, int(math.ceil(rows / 240.0)))
            int nd = int(math.ceil(rows / float(g)))
            array<float> mU = array.new_float(nd, 0.0)
            array<float> mD = array.new_float(nd, 0.0)
            for r = 0 to rows - 1
                int j = int(math.floor(r / g))
                mU.set(j, mU.get(j) + upV.get(r))
                mD.set(j, mD.get(j) + dnV.get(r))
            float maxM = 0.0
            float maxDelta = 0.0
            for j = 0 to nd - 1
                maxM := math.max(maxM, mU.get(j) + mD.get(j))
                maxDelta := math.max(maxDelta, math.abs(mU.get(j) - mD.get(j)))
 
            for j = 0 to nd - 1
                float u = mU.get(j)
                float d = mD.get(j)
                float t = u + d
                if t > 0
                    float rb = lo + j * g * rowH
                    float rt = lo + math.min(rows, (j + 1) * g) * rowH
                    int rc = math.min(rows - 1, j * g + int(math.floor(g / 2)))
                    bool inVA = rc >= lowR and rc <= highR
                    color cUp = inVA ? vaUpCol : upVolCol
                    color cDn = inVA ? vaDnCol : dnVolCol
                    if volMode == "Total"
                        int len = math.max(1, int(math.round(t / maxM * maxLen)))
                        bxs.push(box.new(leftP ? base : base - len, rt, leftP ? base + len : base, rb, xloc = xloc.bar_index, border_color = color(na), bgcolor = cUp))
                    else if volMode == "Up/Down"
                        int lenT = math.max(1, int(math.round(t / maxM * maxLen)))
                        int lenU = math.min(lenT, int(math.round(u / maxM * maxLen)))
                        if lenU > 0
                            bxs.push(box.new(leftP ? base : base - lenU, rt, leftP ? base + lenU : base, rb, xloc = xloc.bar_index, border_color = color(na), bgcolor = cUp))
                        if lenT - lenU > 0
                            bxs.push(box.new(leftP ? base + lenU : base - lenT, rt, leftP ? base + lenT : base - lenU, rb, xloc = xloc.bar_index, border_color = color(na), bgcolor = cDn))
                    else if maxDelta > 0
                        float dl = u - d
                        int len = math.max(1, int(math.round(math.abs(dl) / maxDelta * maxLen)))
                        bxs.push(box.new(leftP ? base : base - len, rt, leftP ? base + len : base, rb, xloc = xloc.bar_index, border_color = color(na), bgcolor = dl >= 0 ? cUp : cDn))
 
            // Values: volume numbers at the tip of the biggest row of ~100 row groups
            if showValues
                int bucket = math.max(1, int(math.ceil(nd / 100.0)))
                for b0 = 0 to nd - 1 by bucket
                    float bsum = 0.0
                    int bestJ = b0
                    float bestT = -1.0
                    int b1 = math.min(nd - 1, b0 + bucket - 1)
                    for j = b0 to b1
                        float t = mU.get(j) + mD.get(j)
                        bsum += t
                        if t > bestT
                            bestT := t
                            bestJ := j
                    if bsum > 0
                        int blen = math.max(1, int(math.round(bestT / maxM * maxLen)))
                        int tipX = leftP ? base + blen : base - blen
                        float yMid = lo + (bestJ * g + g / 2.0) * rowH
                        lbls.push(label.new(tipX, yMid, str.tostring(bsum, format.volume), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = leftP ? label.style_label_left : label.style_label_right, textcolor = valuesCol, size = size.tiny))
 
        // developing POC / VA: replay the range bar by bar on the same row grid, drawn as ~150 segments each
        if showDevPOC or showDevVA
            array<float> dv = array.new_float(rows, 0.0)
            int nBars = iTo - iFrom + 1
            int stepD = math.max(1, int(math.ceil(nBars / 150.0)))
            float runMax = 0.0
            int runPoc = 0
            float runSum = 0.0
            int cnt = 0
            float pX = na
            float pPoc = na
            float pH = na
            float pL = na
            for k = iTo to iFrom
                float vv = nz(volume[k])
                if vv > 0
                    [da, db] = addVol(dv, vv, low[k], high[k], lo, rowH, rows)
                    runSum += vv
                    for r = da to db
                        if dv.get(r) > runMax
                            runMax := dv.get(r)
                            runPoc := r
                if (cnt % stepD == 0 or k == iFrom) and runMax > 0
                    int xk = bar_index - k
                    float pocV = lo + (runPoc + 0.5) * rowH
                    float vahV = na
                    float valV = na
                    if showDevVA
                        [dl2, dh2] = calcVA(dv, runPoc, rows, runSum * vaPct / 100.0)
                        vahV := lo + (dh2 + 1) * rowH
                        valV := lo + dl2 * rowH
                    if not na(pX)
                        if showDevPOC
                            lns.push(line.new(int(pX), pPoc, xk, pocV, xloc = xloc.bar_index, color = devPocCol, width = 1))
                        if showDevVA
                            lns.push(line.new(int(pX), pH, xk, vahV, xloc = xloc.bar_index, color = devVACol, width = 1))
                            lns.push(line.new(int(pX), pL, xk, valV, xloc = xloc.bar_index, color = devVACol, width = 1))
                    pX := xk
                    pPoc := pocV
                    pH := vahV
                    pL := valV
                cnt += 1
 
        // levels
        float pocP = lo + (pocRow + 0.5) * rowH
        float vahP = lo + (highR + 1) * rowH
        float valP = lo + lowR * rowH
        int xs = extendLeft ? xrBox - 1 : bar_index - iTo
        string ext = extend.none
        if extendLeft and extendRight
            ext := extend.both
        else if extendLeft
            ext := extend.left
        else if extendRight
            ext := extend.right
 
        if showPOC
            lns.push(line.new(xs, pocP, xrBox, pocP, xloc = xloc.bar_index, extend = ext, color = pocCol, style = styleOf(pocStyle), width = pocW))
            if showLabels
                lbls.push(label.new(xrBox, pocP, "POC " + str.tostring(pocP, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_left, textcolor = pocCol, size = size.small))
        if showVAH
            lns.push(line.new(xs, vahP, xrBox, vahP, xloc = xloc.bar_index, extend = ext, color = vahCol, style = styleOf(vahStyle), width = vahW))
            if showLabels
                lbls.push(label.new(xrBox, vahP, "VAH " + str.tostring(vahP, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_left, textcolor = vahCol, size = size.small))
        if showVAL
            lns.push(line.new(xs, valP, xrBox, valP, xloc = xloc.bar_index, extend = ext, color = valCol, style = styleOf(valStyle), width = valW))
            if showLabels
                lbls.push(label.new(xrBox, valP, "VAL " + str.tostring(valP, format.mintick), xloc = xloc.bar_index, yloc = yloc.price, color = color(na), style = label.style_label_left, textcolor = valCol, size = size.small))

← 返回列表