Volume Elevation Map [AlgoNorth]

AlgoNorth · study · 646 行 · 点赞 105 · TradingView 原页

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

Pine Script

// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © AlgoNorth
//@version=6
indicator("Volume Elevation Map [AlgoNorth]", shorttitle = "V.E.M [AlgoNorth]", overlay = true, max_polylines_count = 100, max_labels_count = 150, max_lines_count = 150, max_bars_back = 500, calc_bars_count = 500)
 
// ───────── Inputs
string grpD = "Volume data"
string ltfMode   = input.string("Auto", "Intrabar timeframe", options = ["Auto", "Manual"], group = grpD, tooltip = "The map reads volume from intrabar candles: each lower-timeframe bar's volume is placed at that bar's close, so the hills show where volume traded inside each candle. A candle with no intrabar data places its whole volume at its middle. The buy/sell split behind the row colours and the verdict is ESTIMATED: an intrabar bar's volume counts as buying if that bar closed up and selling if it closed down, and flat bars carry the previous direction (a candle with no intrabar data uses its own direction, or the previous one if it is flat). This is not bid/ask data. Auto picks the intrabar timeframe from the chart: seconds charts use 1-second bars, a 1-minute chart uses each candle itself, up to 15m uses 1m, up to 1h uses 5m, up to 4h uses 15m, up to 1D uses 1h, up to 1W uses 4h, higher uses 1D.")
string ltfManual = input.timeframe("1", "Manual intrabar timeframe", group = grpD, active = ltfMode == "Manual", tooltip = "Used only when Intrabar timeframe is Manual. It cannot be higher than the chart timeframe, and it cannot be so fine that the bars covered would need more than 90,000 intrabars, counted as if every day traded 24 hours (for example 1 minute on a daily chart at the default 90 bars covered, even for a stock): the script then stops with an error. A finer timeframe places volume more precisely and gives a finer buy/sell estimate, but loads more data; near the limit, loading can take up to a minute.")
int    barsCov   = input.int(90, "Bars covered", minval = 20, maxval = 400, group = grpD, tooltip = "How many recent bars the map, the volume dots and the verdict cover. On a chart with less history the map uses every bar available; it needs at least 20. TradingView's Calculated bars setting must be at least this number, or the map covers fewer bars.")
 
string grpR = "Elevation map"
string anchorMode = input.string("Range", "Anchor", options = ["Range", "Price"], group = grpR, tooltip = "Range: rows sit on the high–low of the bars covered. Price: rows are centred on the last close and widen so every bar covered still fits.")
int    nRows      = input.int(21, "Price rows", minval = 8, maxval = 22, group = grpR, tooltip = "How many price levels the map is split into, from the low at the front to the high at the back.")
int    nCols      = input.int(30, "Time columns", minval = 10, maxval = 60, group = grpR, tooltip = "How many time slices the bars covered are split into, oldest on the left. Never more than the number of bars covered.")
float  colBars    = input.float(2.0, "Column width (bars)", minval = 0.5, maxval = 4.0, step = 0.5, group = grpR, tooltip = "Width of each time column in chart bars. The front of the map is never narrower than twice (price rows − 1) bars, so the back row keeps at least half the width of the front, and never so narrow that two time columns would share a bar in the back row; when a minimum is wider, the columns widen to fill it and this setting has no effect.")
int    offBars    = input.int(8, "Gap from last bar (bars)", minval = 2, maxval = 50, group = grpR, tooltip = "Space between the last candle and the map. The map sits to the right of price, so give the chart enough right margin to see it.")
string leanMode   = input.string("Perspective", "3D angle", options = ["Perspective", "Side view", "Flat"], group = grpR, tooltip = "Perspective: the left side leans in 1 bar per row and the right side stays upright, so every row lands exactly on both edges; rows further back get narrower and shorter. Side view: seen from the front-right, so the right side face shows. Flat: front-on.")
float  heightPct  = input.float(29, "Elevation height (% of range)", minval = 5, maxval = 60, group = grpR, tooltip = "Height of the map's tallest hill if it sits in the front row, as a share of the map's price range; in the 3D angles, rows further back are drawn shorter. A hill's height is the volume traded at that price and time (per bar, so a time column holding one more bar does not stand taller), so the tallest hills mark where the most trading happened. The same volume packed into a short burst stands taller than when it is spread across all the bars covered, so the Volume POC row (the most volume overall) need not have the tallest hill. Heights are drawn on a softened scale so smaller hills stay visible. Each price row is coloured by which side's volume led at that price: dark, muted shades where the two sides are near even, deeper green or red for a small lead, and full bright green or red for the biggest leads on the map. That buy/sell split is ESTIMATED from intrabar candles, not bid/ask data.")
int    smoothN    = input.int(2, "Smoothing passes", minval = 0, maxval = 4, group = grpR, tooltip = "Softens the hills by blending each cell with its neighbours in price and time. 0 shows the raw grid. Cells on the map's edges have fewer neighbours, so a burst in the first or last time column, or in the front or back row, stands taller than the same burst mid-map: about 1.3× on an edge and 1.6× in a corner at 2 passes.")
int    labelEvery = input.int(6, "Price label every N rows", minval = 2, maxval = 21, group = grpR, tooltip = "How often a price is printed on the left of the map. A price that would sit on the PRICE PATH caption moves to the nearest clear row, or is left out. At least one price is always printed.")
bool   showPath   = input.bool(true, "Price path on the map", group = grpR, tooltip = "A white trail joining the hill summits in time order: where volume peaked in each stretch of time. Volume only trades where price is, so the trail follows price across the map; a step back into the map means price moved up. It stops one time slice short of NOW, where the NOW ridge takes over. Summits hidden behind a taller hill in front, and very small ones, are skipped.")
bool   showVerdict = input.bool(true, "Verdict strip", group = grpR, tooltip = "A slim strip under the map. Left and centre: which side traded more of the volume across the bars covered (an even 50/50 reads BALANCED) and that side's share of it, with the buy/sell split as a green/red edge underneath; the split is ESTIMATED from intrabar candles, not bid/ask data. Right: whether price is above, in or below the value area, the price rows holding up to 70% of that volume, built out from the Volume POC row by adding whichever neighbouring row traded more, the way TradingView's volume profile builds it.")
 
string grpO = "On price"
bool showDots   = input.bool(true, "Volume dots above candles", group = grpO, tooltip = "The three highest-volume closed candles in the bars covered, at least 5 bars apart and never in the same time slice: a large dot above each, green if the candle closed up, red if it closed down (white if flat), and a black-ringed dot on the map where that candle's volume sits: its own time slice, at the price row where most of its intrabar volume traded. The live candle joins once it closes, so the dots only change when a bar closes.")
bool showThread = input.bool(true, "Threads from dots to the map", group = grpO, active = showDots, tooltip = "Needs Volume dots. A curved dashed line from each dot above its candle to that candle's dot on the map.")
bool showCalls  = input.bool(true, "Volume call-outs under candles", group = grpO, tooltip = "Each of those candles' own volume, hung under it on a dashed stem, in the colour of its dot. A call-out that would print over another drops below it.")
bool showPoc    = input.bool(false, "Volume POC band on candles", group = grpO, tooltip = "The price row with the most volume traded (the volume point of control), shaded across the candles covered. It stops just short of the map. The gold ridge and VOLUME POC tag on the map always show.")
 
string grpC = "Colours"
color buyCol   = input.color(#00E676, "Buying volume", group = grpC)
color sellCol  = input.color(#FF1744, "Selling volume", group = grpC)
color goldCol  = input.color(#FFC400, "Volume POC", group = grpC)
color ridgeCol = input.color(#FFFFFF, "Ridges, frame & NOW", group = grpC, tooltip = "Ridge lines, the floor frame and the NOW ridge. On a light chart background the NOW tag and the NOW time tick use the chart's own text colour.")
 
// ───────── Colour helpers
f_lum(color c) =>
    color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114
 
// black text on light fills, white text on dark ones
f_ink(color c) =>
    f_lum(c) > 128 ? color.black : color.white
 
// strength step of a row's lead (its buying volume minus its selling volume), as a share of the biggest lead on the map:
//    0 balanced, 1 weak, 2 medium, 3 strong
f_step(float t) =>
    float a = math.abs(t)
    a < 0.12 ? 0 : a < 0.35 ? 1 : a < 0.6 ? 2 : 3
 
f_scale(color c, float f) =>
    color.rgb(color.r(c) * f, color.g(c) * f, color.b(c) * f)
 
// shade of a strength step, always in the true red or green: deeper for weak, full signature neon for strong.
// Only the weak and balanced steps mix in neutral graphite (the balanced step is mostly graphite), so no row drifts toward pink, plum or teal
f_scol(int st, color base) =>
    st == 0 ? color.from_gradient(0.7, 0, 1, f_scale(base, 0.5), #34363A) : st == 1 ? color.from_gradient(0.15, 0, 1, f_scale(base, 0.68), #3A3A3A) : st == 2 ? f_scale(base, 0.86) : base
 
// volume with k, M or B; below 10 keeps one decimal and below 1 up to three, so fractional volumes still read
f_fmt(float v) =>
    v >= 999950000 ? str.tostring(v / 1e9, "0.0") + "B" : v >= 999950 ? str.tostring(v / 1e6, "0.0") + "M" : v >= 999.5 ? str.tostring(v / 1e3, "0.0") + "k" : v >= 9.95 ? str.tostring(math.round(v)) : v >= 0.995 ? str.tostring(v, "0.0") : str.tostring(v, "0.###")
 
// ───────── Chart theme: the map sits on its own dark floor; only what is drawn on the bare chart follows the background
bool  lightBg = f_lum(chart.bg_color) > 140
color offTxt  = lightBg ? chart.fg_color : color.white
color nowPill = lightBg ? chart.fg_color : ridgeCol
 
// ───────── Window: the bars covered, or every bar there is on a shorter history
int lb = math.min(barsCov, last_bar_index + 1)
int nC = math.min(nCols, lb)
 
// ───────── Perspective: bars per row each side moves right as rows go back
//           (whole bars per row on the left so row starts sit exactly on the floor edge; chart points snap to whole bars)
float leanL = leanMode == "Flat" ? 0.0 : 1.0
float leanR = leanMode == "Side view" ? 0.5 : 0.0
int   backL = math.floor((nRows - 1) * leanL)                             // floor's back-left corner: the back row's start
// front row width in bars: at least twice (rows − 1), so the back row keeps half the front, and at least (columns − 1) bars more
//    than the back row's lean, so even the back row has a bar for every time column
int   xeB   = math.max(math.round((nC - 1) * colBars), 2 * (nRows - 1), nC - 1 + backL)
int   backR = xeB + math.floor((nRows - 1) * leanR)                       // floor's back-right corner: the back row's end
 
// x one bar clear of the map's right side at a given row
f_tagX(int x0, int q) =>
    x0 + math.ceil(xeB + q * (backR - xeB) / (nRows - 1.0)) + 1
 
// one smoothing pass over a (price rows × time slices) grid: each cell blends with its neighbours in price and time, weights 4 / 2 / 1
//    (1 / 2 / 1 each way), and a cell on the map's edge divides by the weights it has. Done as a sweep along time, then a sweep across
//    price, which gives the same result as blending each 3 × 3 block at once while reading every cell only once per sweep
f_blur(array<float> g, int nR, int nK) =>
    array<float> t = array.new_float(nR * nK, 0.0)
    for q = 0 to nR - 1
        int   c0 = q * nK
        float a  = 0.0
        float b  = g.get(c0)
        for k = 0 to nK - 1
            float n = k < nK - 1 ? g.get(c0 + k + 1) : 0.0
            t.set(c0 + k, (a + 2 * b + n) / (k > 0 and k < nK - 1 ? 4 : 3))
            a := b
            b := n
    array<float> o = array.new_float(nR * nK, 0.0)
    for k = 0 to nK - 1
        float a = 0.0
        float b = t.get(k)
        for q = 0 to nR - 1
            float n = q < nR - 1 ? t.get((q + 1) * nK + k) : 0.0
            o.set(q * nK + k, (a + 2 * b + n) / (q > 0 and q < nR - 1 ? 4 : 3))
            a := b
            b := n
    o
 
// ───────── Intrabar volume
f_autoLtf() =>
    int s = timeframe.in_seconds()
    timeframe.isseconds ? "1S" : s <= 900 ? "1" : s <= 3600 ? "5" : s <= 14400 ? "15" : s <= 86400 ? "60" : s <= 604800 ? "240" : "1D"
string ltf = ltfMode == "Auto" ? f_autoLtf() : ltfManual
if timeframe.in_seconds(ltf) > timeframe.in_seconds()
    runtime.error("Manual intrabar timeframe must not be higher than the chart timeframe.")
if timeframe.in_seconds() * 1.0 / timeframe.in_seconds(ltf) * lb > 90000
    runtime.error("Intrabar timeframe too fine for this chart and Bars covered setting. Choose a higher one or fewer bars covered.")
if not chart.is_standard
    runtime.error("V.E.M needs a standard chart type such as candles or bars. Heikin Ashi, Renko and other synthetic charts would distort the map.")
// intrabars per chart candle, rounded up: the request asks only for intrabars of the bars covered plus a 10-candle margin that carries
//    the buy/sell direction into the window, instead of intrabars for every calculated bar
int ibPer = math.ceil(timeframe.in_seconds() * 1.0 / timeframe.in_seconds(ltf))
[aC, aO, aV] = request.security_lower_tf(syminfo.tickerid, ltf, [close, open, volume], calc_bars_count = (barsCov + 10) * ibPer)
 
// each intrabar's price, its volume signed by the side it is estimated to belong to (+ buying, − selling), and its candle
var array<float> tPx  = array.new_float()
var array<float> tSv  = array.new_float()
var array<int>   tBar = array.new_int()
var int dirKeep = 1
 
// a live candle's ticks are rolled back before each update, so these arrays never hold it twice
// only bars inside the window are stored; older bars just carry the candle direction forward
bool inWin = bar_index > last_bar_index - lb
int dirRun = dirKeep
if aC.size() > 0
    for i = 0 to aC.size() - 1
        float c_ = aC.get(i)
        float o_ = aO.get(i)
        dirRun := c_ > o_ ? 1 : c_ < o_ ? -1 : dirRun
        if inWin
            tPx.push(c_)
            tSv.push(dirRun * nz(aV.get(i)))
            tBar.push(bar_index)
else
    dirRun := close > open ? 1 : close < open ? -1 : dirRun
    if inWin
        tPx.push(hl2)
        tSv.push(dirRun * nz(volume))
        tBar.push(bar_index)
// carried into the next candle; on a live candle only the closing tick's value sticks
dirKeep := dirRun
// keep only the window's bars: the oldest candle's intrabars are dropped in one step. Rollback undoes the trim on every live tick,
//    so it is redone each tick, and one copy costs far less than removing the intrabars one by one
int nDrop = 0
while nDrop < tBar.size() and tBar.get(nDrop) < bar_index - lb + 1
    nDrop += 1
if nDrop > 0
    tBar := tBar.slice(nDrop, tBar.size()).copy()
    tPx  := tPx.slice(nDrop, tPx.size()).copy()
    tSv  := tSv.slice(nDrop, tSv.size()).copy()
 
// ───────── Drawing handles
var array<polyline> plns = array.new<polyline>()
var array<label>    lbs  = array.new<label>()
var array<line>     lns  = array.new<line>()
var array<linefill> lfs  = array.new<linefill>()
color clear = color.new(color.black, 100)
 
if barstate.islast
    for pl in plns
        polyline.delete(pl)
    plns.clear()
    for lb_ in lbs
        label.delete(lb_)
    lbs.clear()
    for lf in lfs
        linefill.delete(lf)
    lfs.clear()
    for ln in lns
        line.delete(ln)
    lns.clear()
    // fewer than 20 bars (the minimum for Bars covered, which keeps at least 10 time columns): say so instead of leaving the chart blank
    if bar_index < 19
        lbs.push(label.new(bar_index + offBars, close, "NEEDS 20 BARS", style = label.style_label_left, color = clear, textcolor = offTxt, size = size.normal, text_formatting = text.format_bold))
 
if barstate.islast and bar_index >= 19
    // ── anchor: the window's high–low, or centred on the close and wide enough to hold the whole window
    float hh = high
    float ll = low
    for i = 1 to lb - 1
        hh := math.max(hh, high[i])
        ll := math.min(ll, low[i])
    float half = math.max(hh - close, close - ll)
    float rHi0 = anchorMode == "Price" ? close + half : hh
    float rLo0 = anchorMode == "Price" ? close - half : ll
    // a window narrower than one tick per row is widened evenly on both sides, so it stays centred
    float pad  = math.max(0.0, syminfo.mintick * nRows - (rHi0 - rLo0)) / 2
    float rLo  = rLo0 - pad
    float rng  = rHi0 - rLo0 + 2 * pad
    float bh   = rng / nRows
    // a thousandth of a tick keeps a price that sits exactly on a row edge in its own row despite float rounding
    float eps  = syminfo.mintick * 0.001
 
    // ── grids at (price row, time column): volume, plus each row's volume and lead (its buying minus its selling volume);
    //    the dots on the map also need where each candle's intrabars sit in the arrays, so that is only built when the volume dots are on
    bool  needDots  = showDots or showCalls
    int   firstBar  = bar_index - lb + 1
    int   nCell     = nRows * nC
    // bars in each time slice: equal when the bars covered are a multiple of the columns, otherwise some slices hold one more bar,
    //    so the hills take each slice's volume per bar
    array<int> colN = array.new_int(nC, 0)
    for bj = 0 to lb - 1
        int kb = math.floor(bj * nC / lb)
        colN.set(kb, colN.get(kb) + 1)
    array<float> gV       = array.new_float(nCell, 0.0)
    array<float> rowNet   = array.new_float(nRows, 0.0)
    array<float> rowVol   = array.new_float(nRows, 0.0)
    array<int>   barFirst = array.new_int(showDots ? lb : 0, -1)
    array<int>   barLast  = array.new_int(showDots ? lb : 0, -1)
    for i = 0 to tBar.size() - 1
        int   q   = math.max(0, math.min(nRows - 1, math.floor((tPx.get(i) - rLo + eps) / bh)))
        int   bj  = tBar.get(i) - firstBar
        int   k   = math.floor(bj * nC / lb)
        int   idx = q * nC + k
        float sv  = tSv.get(i)
        gV.set(idx, gV.get(idx) + math.abs(sv) / colN.get(k))
        rowNet.set(q, rowNet.get(q) + sv)
        rowVol.set(q, rowVol.get(q) + math.abs(sv))
        if showDots
            if barFirst.get(bj) < 0
                barFirst.set(bj, i)
            barLast.set(bj, i)
    // total volume in the window and the part estimated as buying, both from the rows (a row's buying is its volume plus its lead,
    //    halved); Volume POC: the row with the most volume; dm: the biggest lead of any row, which sets the colour steps
    float totV = 0.0
    float buyV = 0.0
    float dm   = 1e-9
    int   poc  = 0
    for q = 0 to nRows - 1
        totV += rowVol.get(q)
        buyV += (rowVol.get(q) + rowNet.get(q)) / 2
        dm   := math.max(dm, math.abs(rowNet.get(q)))
        if rowVol.get(q) > rowVol.get(poc)
            poc := q
 
    if totV == 0
        lbs.push(label.new(bar_index + offBars, close, "NO VOLUME DATA", style = label.style_label_left, color = clear, textcolor = offTxt, size = size.normal, text_formatting = text.format_bold))
    else
        // hills: the volume grid blended smoothN times (f_blur)
        array<float> g = gV
        if smoothN > 0
            for ps = 1 to smoothN
                g := f_blur(g, nRows, nC)
        float mx = g.max()   // positive: the window has volume
        int nq = math.min(nRows - 1, math.floor((close - rLo + eps) / bh))
 
        // ── geometry: the floor runs from the front-left corner (xFL, rLo) back to the back row (yB)
        float HS    = rng * heightPct / 100
        float T     = rng * 0.035
        int   xFL   = bar_index + offBars
        int   xFR   = xFL + xeB
        int   xBL   = xFL + backL
        int   xBR   = xFL + backR
        float yB    = rLo + (nRows - 1) * bh
        float pocPx = rLo + (poc + 0.5) * bh
 
        // ── surfaces, built once: hill height, surface price and x of every cell, height scale of every row
        array<float> hgt   = array.new_float(nCell, 0.0)
        array<float> ySurf = array.new_float(nCell, 0.0)
        array<int>   cx    = array.new_int(nCell, 0)
        array<float> shQ   = array.new_float(nRows, 0.0)
        for q = 0 to nRows - 1
            // in the 3D angles rows further back get narrower, and shorter a little faster than they narrow (exponent 1.4); Flat keeps every row the same
            float sh = math.pow((xeB + q * (leanR - leanL)) / xeB, 1.4)
            int   s0 = math.ceil(q * leanL)
            int   s1 = xeB + math.floor(q * leanR)
            shQ.set(q, sh)
            for k = 0 to nC - 1
                int   c = q * nC + k
                // softened height scale (power 0.7) so smaller hills stay visible; taller means more volume at that price and time
                float h = HS * sh * math.pow(g.get(c) / mx, 0.7)
                hgt.set(c, h)
                ySurf.set(c, rLo + q * bh + h)
                cx.set(c, xFL + s0 + math.round(k * (s1 - s0) / (nC - 1.0)))
 
        // ── volume dots: the three highest-volume closed candles in the bars covered, at least 5 bars apart and never in the same time slice
        //    (two candles a slice's width apart can't share one). Each is tied to its own cell on the map: its time slice, at the price
        //    row where most of its intrabar volume traded. The live candle is left out until it closes, so no dot appears, moves or
        //    changes while a candle is still forming
        array<int> dotQ = array.new_int()
        array<int> dotK = array.new_int()
        array<int> dotB = array.new_int()   // each candle, by its place in the window (0 = oldest)
        if needDots
            int minGap = math.max(5, math.ceil(lb * 1.0 / nC))
            int jMax   = barstate.isconfirmed ? lb - 1 : lb - 2   // last closed candle's place
            while dotB.size() < 3
                int   best  = -1
                float bestV = 0.0
                for j = 0 to jMax
                    float vj = nz(volume[lb - 1 - j])
                    if vj > bestV
                        bool clash = false
                        for ub in dotB
                            if math.abs(ub - j) < minGap
                                clash := true
                                break
                        if not clash
                            bestV := vj
                            best  := j
                if best < 0
                    break
                // the candle's busiest row, for its dot on the map: where most of its intrabar volume traded (its middle when its
                //    intrabars carry no volume)
                int bq = math.max(0, math.min(nRows - 1, math.floor((hl2[lb - 1 - best] - rLo + eps) / bh)))
                if showDots and barFirst.get(best) >= 0
                    array<float> rv = array.new_float(nRows, 0.0)
                    for i = barFirst.get(best) to barLast.get(best)
                        int q = math.max(0, math.min(nRows - 1, math.floor((tPx.get(i) - rLo + eps) / bh)))
                        rv.set(q, rv.get(q) + math.abs(tSv.get(i)))
                    float bv = 0.0
                    for q = 0 to nRows - 1
                        if rv.get(q) > bv
                            bv := rv.get(q)
                            bq := q
                dotQ.push(bq)
                dotK.push(math.floor(best * nC / lb))
                dotB.push(best)
 
        // ── on price: Volume POC band drawn as a flat pane at the floor's lean (in the 3D angles it leans back one bar, so it reads as a
        //    parallelogram; in Flat it is a rectangle; faint grid). Its tag sits a sliver above the pane's top edge, at the first stretch
        //    from the left where no candle reaches into the space above it and no dotted candle carries a dot or call-out
        if showPoc
            int   xOnEnd = math.max(xFL - 4, bar_index + 1)                     // stops short of the map's price labels, never before the last candle
            float zTop   = rLo + (poc + 1) * bh
            float zBot   = rLo + poc * bh
            int   tagW   = 10
            float tagM   = rng * 0.01
            float tagH   = rng * 0.06
            int   sP     = -1
            for s = 0 to lb - tagW
                bool ok = true
                for j = s to s + tagW - 1
                    int off = lb - 1 - j
                    if dotB.includes(j) or not (low[off] > zTop + tagH or high[off] < zTop - tagM)
                        ok := false
                        break
                if ok
                    sP := s
                    break
            int  zLean = int(leanL)
            line zB = line.new(firstBar, zBot, xOnEnd, zBot, color = color.new(goldCol, 30))
            line zT = line.new(firstBar + zLean, zTop, xOnEnd + zLean, zTop, color = color.new(goldCol, 65))
            line zL = line.new(firstBar, zBot, firstBar + zLean, zTop, color = color.new(goldCol, 55))
            line zR = line.new(xOnEnd, zBot, xOnEnd + zLean, zTop, color = color.new(goldCol, 55))
            lns.push(zB)
            lns.push(zT)
            lns.push(zL)
            lns.push(zR)
            lfs.push(linefill.new(zB, zT, color.new(goldCol, 80)))
            // faint grid on the pane, slanting back like the floor's grid
            for gx = 8 to xOnEnd - firstBar - 4 by 8
                lns.push(line.new(firstBar + gx, zBot, firstBar + gx + zLean, zTop, color = color.new(goldCol, 78)))
            lbs.push(label.new((sP >= 0 ? firstBar + sP : firstBar) + zLean, zTop + rng * 0.008, "VOLUME POC", style = label.style_label_lower_left, color = goldCol, textcolor = f_ink(goldCol), size = size.normal, text_formatting = text.format_bold))
 
        // ── floor (a trapezoid narrowing toward the back in the 3D angles, a rectangle in Flat) and front slab; the side slab only shows
        //    in Side view. The grid lines run from the front row's time columns to the back row's
        line lFront  = line.new(xFL, rLo, xFR, rLo, color = color.new(ridgeCol, 80))
        line lBack   = line.new(xBL, yB, xBR, yB, color = color.new(ridgeCol, 90))
        line lFrontD = line.new(xFL, rLo - T, xFR, rLo - T, color = color.new(ridgeCol, 85))
        lns.push(lFront)
        lns.push(lBack)
        lns.push(lFrontD)
        lfs.push(linefill.new(lFront, lBack, #0B0D12))
        lfs.push(linefill.new(lFront, lFrontD, #1A1E27))
        if leanR > 0
            line lSide  = line.new(xFR, rLo, xBR, yB, color = color.new(ridgeCol, 85))
            line lSideD = line.new(xFR, rLo - T, xBR, yB - T, color = color.new(ridgeCol, 90))
            lns.push(lSide)
            lns.push(lSideD)
            lfs.push(linefill.new(lSide, lSideD, #11141B))
        for k = 0 to nC - 1 by 3
            lns.push(line.new(cx.get(k), rLo, cx.get((nRows - 1) * nC + k), yB, color = color.new(ridgeCol, 93)))
 
        // ── rows, back (high price) to front (low price): fill, lit band, shade band, ridge
        for q = nRows - 1 to 0
            float b0  = rLo + q * bh
            float sh  = shQ.get(q)
            int   c0  = q * nC
            array<chart.point> ridge = array.new<chart.point>()
            array<chart.point> fillP = array.new<chart.point>()
            array<chart.point> litP  = array.new<chart.point>()
            array<chart.point> shdP  = array.new<chart.point>()
            array<float> litY = array.new_float(nC, 0.0)
            array<float> shdY = array.new_float(nC, 0.0)
            for k = 0 to nC - 1
                float hk    = hgt.get(c0 + k)
                float slope = hgt.get(c0 + math.min(nC - 1, k + 1)) - hgt.get(c0 + math.max(0, k - 1))
                float band  = math.min(HS * 0.21 * sh, hk * 0.62)
                litY.set(k, b0 + hk - (slope > 0 ? band : 0))
                shdY.set(k, b0 + hk - (slope < 0 ? band : 0))
                chart.point p = chart.point.from_index(cx.get(c0 + k), ySurf.get(c0 + k))
                ridge.push(p)
                fillP.push(p)
                litP.push(p)
                shdP.push(p)
            fillP.push(chart.point.from_index(cx.get(c0 + nC - 1), b0))
            fillP.push(chart.point.from_index(cx.get(c0), b0))
            for k = nC - 1 to 0
                litP.push(chart.point.from_index(cx.get(c0 + k), litY.get(k)))
                shdP.push(chart.point.from_index(cx.get(c0 + k), shdY.get(k)))
            // bold 3D faces: a lit face on the rising slope and a shadow face on the falling one; the lit face and the ridge get stronger with each strength step
            float tq      = rowNet.get(q) / dm
            int   st      = f_step(tq)
            // row colour from its lead: green where buying volume led, red where selling volume led
            color rowCol  = f_scol(st, tq < 0 ? sellCol : buyCol)
            color litCol  = color.new(color.from_gradient(0.3, 0, 1, rowCol, color.white), st == 0 ? 50 : st == 1 ? 45 : st == 2 ? 38 : 32)
            int   ridgeT  = st == 0 ? 45 : st == 1 ? 40 : st == 2 ? 25 : 0
            bool  isPoc   = q == poc
            bool  special = isPoc or q == nq
            color lineCol = isPoc ? goldCol : ridgeCol
            plns.push(polyline.new(fillP, closed = true, line_color = clear, fill_color = rowCol))
            plns.push(polyline.new(litP, closed = true, line_color = clear, fill_color = litCol))
            plns.push(polyline.new(shdP, closed = true, line_color = clear, fill_color = color.new(color.black, 50)))
            if special
                plns.push(polyline.new(ridge, line_color = color.new(lineCol, 75), line_width = 6))
            plns.push(polyline.new(ridge, line_color = special ? lineCol : color.new(ridgeCol, ridgeT), line_width = special ? 2 : 1))
 
        // ── Side view: right side face over the row ends (the even rows land on the straight edge, exactly when the row count is odd and
        //    within half a bar otherwise; the back row closes the corner)
        if leanR > 0
            array<chart.point> side = array.new<chart.point>()
            for q = 0 to nRows - 1
                if q % 2 == 0 or q == nRows - 1
                    int c = q * nC + nC - 1
                    side.push(chart.point.from_index(cx.get(c), ySurf.get(c)))
            side.push(chart.point.from_index(xBR, yB))
            side.push(chart.point.from_index(xFR, rLo))
            plns.push(polyline.new(side, closed = true, line_color = color.new(ridgeCol, 65), fill_color = #151922))
 
        // ── price path: the hill summits (cells not below the time slice before them and above the one after), joined in time order.
        //    Volume only exists where price traded, so walking the summits left to right follows price across the map;
        //    within one time slice the path takes the summit nearest the last one first; summits hidden behind a hill in front are left out;
        //    it stops before the right edge: the NOW ridge already carries the eye to current price
        float capY = na
        if showPath
            array<chart.point> path = array.new<chart.point>()
            int lastQ = nq
            for k = 0 to nC - 2
                array<int> colQ = array.new_int()
                for q = 0 to nRows - 1
                    int   c = q * nC + k
                    float v = g.get(c)
                    // over 10% of the tallest hill
                    if v / mx > 0.1 and v >= (k > 0 ? g.get(c - 1) : 0.0) and v > g.get(c + 1)
                        // skip a summit hidden behind a taller hill in a row in front (rows in front draw over it; the dot would show through)
                        float yS     = ySurf.get(c)
                        bool  hidden = false
                        if q > 0
                            for q2 = 0 to q - 1
                                if ySurf.get(q2 * nC + k) > yS
                                    hidden := true
                                    break
                        if not hidden
                            colQ.push(q)
                while colQ.size() > 0
                    int bi = 0
                    for c = 0 to colQ.size() - 1
                        if math.abs(colQ.get(c) - lastQ) < math.abs(colQ.get(bi) - lastQ)
                            bi := c
                    int qp = colQ.remove(bi)
                    lastQ := qp
                    int cp = qp * nC + k
                    path.push(chart.point.from_index(cx.get(cp), ySurf.get(cp)))
            if path.size() > 1
                // dotted at 2 px: bigger dots, spaced a little wider, so the path reads clearly over the hills
                plns.push(polyline.new(path, line_color = color.white, line_style = line.style_dotted, line_width = 2))
                // a dot on the summits, thinned evenly so a long path never runs past the label budget
                int step = math.ceil(path.size() / 60.0)   // at least 1, since the path has at least 2 points
                for i = 0 to path.size() - 1
                    if i % step == 0
                        chart.point pp = path.get(i)
                        lbs.push(label.new(pp.index, pp.price, "●", style = label.style_label_center, color = clear, textcolor = color.white, size = size.normal))
                chart.point p0 = path.first()
                capY := p0.price
                // on a black pill like the price labels, so it reads on any background, over the hills or over the chart
                lbs.push(label.new(p0.index - 1, p0.price, "PRICE PATH", style = label.style_label_right, color = color.black, textcolor = color.white, size = size.normal, text_formatting = text.format_bold))
 
        // ── volume dots: dot above each candle, dashed thread from that dot to the candle's cell on the map, call-out with the candle's
        //    own volume hung under it. A call-out within 20 bars of an earlier one and less than one tier (6% of the range) above or below
        //    it drops a tier below that one, so call-outs never print over each other; the biggest volume keeps its place
        bool dotAtNow = false
        bool dotAtPoc = false
        if dotB.size() > 0
            // dots and call-outs are spaced by the map's range as it stood at the last closed candle, so the live candle can't nudge them
            int   o0    = barstate.isconfirmed ? 0 : 1
            float cHi   = high[o0]
            float cLo   = low[o0]
            for o = o0 + 1 to lb - 1
                cHi := math.max(cHi, high[o])
                cLo := math.min(cLo, low[o])
            float cHalf = math.max(cHi - close[o0], close[o0] - cLo)
            float rngC  = math.max(anchorMode == "Price" ? 2 * cHalf : cHi - cLo, syminfo.mintick * nRows)
            array<int>   coX = array.new_int()
            array<float> coY = array.new_float()
            for n = 0 to dotB.size() - 1
                int   offB = lb - 1 - dotB.get(n)
                int   px   = bar_index - offB
                // coloured by the candle itself: green if it closed up, red if it closed down, white if flat
                color pc   = close[offB] > open[offB] ? buyCol : close[offB] < open[offB] ? sellCol : ridgeCol
                if showDots
                    int   cP = dotQ.get(n) * nC + dotK.get(n)
                    int   rx = cx.get(cP)
                    float ry = ySurf.get(cP)
                    // a map dot in the last time slice of the NOW or Volume POC row sits where that row's tag starts, so the tag steps right
                    if dotK.get(n) == nC - 1
                        dotAtNow := dotAtNow or dotQ.get(n) == nq
                        dotAtPoc := dotAtPoc or dotQ.get(n) == poc
                    // dot (a text glyph) just above the candle's high, with a sliver of space; on a light chart it gets a black ring,
                    //    so a green dot stays visible on white
                    float yDot = high[offB] + rngC * 0.04
                    if lightBg
                        lbs.push(label.new(px, yDot, "●", style = label.style_label_center, color = clear, textcolor = color.black, size = size.huge))
                    lbs.push(label.new(px, yDot, "●", style = label.style_label_center, color = clear, textcolor = pc, size = size.large))
                    // on the map the dot sits on the candle's cell, so it gets a black ring to stand out
                    lbs.push(label.new(rx, ry, "●", style = label.style_label_center, color = clear, textcolor = color.black, size = size.huge))
                    lbs.push(label.new(rx, ry, "●", style = label.style_label_center, color = clear, textcolor = pc, size = size.large))
                    // thin and faded so it guides the eye without competing with the map
                    if showThread
                        array<chart.point> thread = array.new<chart.point>()
                        thread.push(chart.point.from_index(px, yDot))
                        thread.push(chart.point.from_index(int((px + rx) / 2), (yDot + ry) / 2 + rng * 0.03))
                        thread.push(chart.point.from_index(rx, ry))
                        plns.push(polyline.new(thread, curved = true, line_color = color.new(pc, lightBg ? 30 : 60), line_style = line.style_dashed, line_width = 1))
                if showCalls
                    // call-out hangs below the lowest wick of this candle and its closed neighbours, on a dashed stem from the candle's low
                    float nLo = low[offB]
                    for o = math.max(o0, offB - 3) to math.min(lb - 1, offB + 3)
                        nLo := math.min(nLo, low[o])
                    float tier = rngC * 0.06
                    float yLab = nLo - tier
                    if coX.size() > 0
                        bool moved = true
                        while moved
                            moved := false
                            for j = 0 to coX.size() - 1
                                if math.abs(px - coX.get(j)) <= 20 and yLab > coY.get(j) - tier and yLab < coY.get(j) + tier
                                    yLab  := coY.get(j) - tier
                                    moved := true
                    coX.push(px)
                    coY.push(yLab)
                    lns.push(line.new(px, low[offB] - rngC * 0.008, px, yLab, color = color.new(pc, lightBg ? 25 : 50), style = line.style_dashed, width = 1))
                    lbs.push(label.new(px, yLab, f_fmt(nz(volume[offB])) + " VOLUME", style = label.style_label_up, color = pc, textcolor = f_ink(pc), size = size.normal, text_formatting = text.format_bold))
 
        // ── tags: one bar clear of the map's right side (three when a map dot sits at that row's end), each pinned to the end of its own
        //    ridge (NOW ridge colour, gold Volume POC), so each tag sits on the hill it names; each still prints its price, and the chart's
        //    price scale marks the live price
        float yPoc   = ySurf.get(poc * nC + nC - 1)
        float yNow   = ySurf.get(nq * nC + nC - 1)
        float tagGap = rng * 0.05
        // keep the two tags from stacking: both move apart by the same amount
        if math.abs(yNow - yPoc) < tagGap
            bool  up  = yNow >= yPoc
            float mid = (yNow + yPoc) / 2
            yNow := mid + (up ? 1 : -1) * tagGap / 2
            yPoc := mid - (up ? 1 : -1) * tagGap / 2
        lbs.push(label.new(f_tagX(xFL, poc) + (dotAtPoc ? 2 : 0), yPoc, "VOLUME POC  " + str.tostring(pocPx, format.mintick), style = label.style_label_left, color = goldCol, textcolor = f_ink(goldCol), size = size.normal, text_formatting = text.format_bold))
        lbs.push(label.new(f_tagX(xFL, nq) + (dotAtNow ? 2 : 0), yNow, "NOW  " + str.tostring(close, format.mintick), style = label.style_label_left, color = nowPill, textcolor = f_ink(nowPill), size = size.normal, text_formatting = text.format_bold))
        // price scale: each label one bar clear of the two rows in front of it, on a black pill.
        //    The PRICE PATH caption is tied to the path's first summit, so a pill within 2.5 rows of it steps to the nearest clear row within
        //    its spacing (away from the caption first), or is left out when there is none; a moved pill prints that row's own price, so it
        //    stays correct. 2.5 rows keeps the two apart at any zoom where a row is 7 px or taller
        int lEvery = math.min(labelEvery, nRows - 1)   // never more than the rows, so at least one price is always printed
        for q = lEvery to nRows - 1 by lEvery
            int qL = q
            if not na(capY) and math.abs(rLo + q * bh - capY) < 2.5 * bh
                qL := -1
                int dir = rLo + q * bh >= capY ? 1 : -1
                for s = 1 to lEvery - 1
                    int qa = q + dir * s
                    int qb = q - dir * s
                    if qa >= 2 and qa <= nRows - 1 and math.abs(rLo + qa * bh - capY) >= 2.5 * bh
                        qL := qa
                    else if qb >= 2 and qb <= nRows - 1 and math.abs(rLo + qb * bh - capY) >= 2.5 * bh
                        qL := qb
                    if qL >= 0
                        break
            if qL >= 0
                float yP = rLo + qL * bh
                lbs.push(label.new(cx.get((qL - 2) * nC) - 1, yP, str.tostring(yP, format.mintick), style = label.style_label_right, color = color.black, textcolor = color.white, size = size.small, text_formatting = text.format_bold))
        // time ticks: the age in bars of each marked column's middle bar
        array<int> tk = array.from(0, int(nC / 3), int(2 * nC / 3), nC - 1)
        for kk in tk
            string tt = kk == nC - 1 ? "NOW" : "−" + str.tostring(math.round(lb - 1 - (kk + 0.5) * lb / nC)) + (kk == 0 ? " BARS" : "")
            lbs.push(label.new(cx.get(kk), rLo - T - rng * 0.012, tt, style = label.style_label_up, color = clear, textcolor = kk == nC - 1 ? nowPill : offTxt, size = size.small, text_formatting = text.format_bold))
 
        // ── verdict strip under the map: all volume in the bars covered, split into estimated buying and selling. It shows which side
        //    traded more and that side's share of the volume, with the buy/sell split as the strip's bottom edge, and on the right
        //    where price sits against the value area
        if showVerdict
            float bShare = buyV / totV
            int   share  = math.round(bShare * 100)
            // the verdict follows the rounded split, so it can never contradict the numbers beside it; an even 50/50 reads BALANCED
            int   side   = share > 50 ? 1 : share < 50 ? -1 : 0
            color vCol   = side > 0 ? buyCol : side < 0 ? sellCol : color.white
            float sTop   = rLo - T - rng * 0.045
            float sBot   = sTop - rng * 0.042
            float sMid   = (sTop + sBot) / 2 + rng * 0.002
            int   xS     = xFL + math.round(xeB * bShare)
            line sT = line.new(xFL, sTop, xFR, sTop, color = color.new(ridgeCol, 86))
            line sB = line.new(xFL, sBot, xFR, sBot, color = clear)
            lns.push(sT)
            lns.push(sB)
            lfs.push(linefill.new(sT, sB, #12151C))
            lns.push(line.new(xFL, sTop, xFL, sBot, color = color.new(ridgeCol, 86)))
            lns.push(line.new(xFR, sTop, xFR, sBot, color = color.new(ridgeCol, 86)))
            // split edge: buy share in green from the left, sell share in red to the right
            lns.push(line.new(xFL, sBot, xS, sBot, color = buyCol, width = 3))
            lns.push(line.new(xS, sBot, xFR, sBot, color = sellCol, width = 3))
            // verdict in its colour; a coloured verdict is drawn twice on the same spot so it carries the same weight as the white text beside it
            string vTxt = side > 0 ? "BUYERS IN CONTROL" : side < 0 ? "SELLERS IN CONTROL" : "BALANCED"
            for rep = 1 to (side != 0 ? 2 : 1)
                lbs.push(label.new(xFL + 1, sMid, vTxt, style = label.style_label_left, color = clear, textcolor = vCol, size = size.normal, text_formatting = text.format_bold))
            lbs.push(label.new(xFL + math.round(xeB / 2), sMid, str.tostring(side < 0 ? 100 - share : share) + "% OF VOLUME", style = label.style_label_center, color = clear, textcolor = color.white, size = size.normal, text_formatting = text.format_bold))
            // value area, TradingView's way: start from the Volume POC row and add whichever neighbouring row (just above or just below)
            //    traded more, as long as the area stays within 70% of the window's volume; a tie goes to the row nearer the POC, then
            //    the one above. Price is read by its row, the one the NOW ridge sits on
            int   vaLo   = poc
            int   vaHi   = poc
            float vaLeft = totV * 0.7 - rowVol.get(poc)
            while vaLo > 0 or vaHi < nRows - 1
                float vUp  = vaHi < nRows - 1 ? rowVol.get(vaHi + 1) : -1.0
                float vDn  = vaLo > 0 ? rowVol.get(vaLo - 1) : -1.0
                bool  goUp = vUp > vDn or (vUp == vDn and vaHi + 1 - poc <= poc - vaLo + 1)
                float vAdd = goUp ? vUp : vDn
                if vAdd > vaLeft
                    break
                vaLeft -= vAdd
                if goUp
                    vaHi += 1
                else
                    vaLo -= 1
            string vaTxt = nq > vaHi ? "PRICE ABOVE VALUE AREA" : nq < vaLo ? "PRICE BELOW VALUE AREA" : "PRICE IN VALUE AREA"
            lbs.push(label.new(xFR - 1, sMid, vaTxt, style = label.style_label_right, color = clear, textcolor = color.white, size = size.normal, text_formatting = text.format_bold))

← 返回列表