Day Trade Setup - Volume Profile

daytradesetupx · study · 717 行 · 点赞 161 · TradingView 原页

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

Pine Script

//@version=6
// Day Trade Setup - Volume Profile · Pine Script v6 · 2026-11-17
// Original work for Day Trade Setup. Analytical overlay only: no orders, no strategy.
//
// DATA GATE (read this first)
//   TradingView scripts cannot read true volume-at-price. This profile is an APPROXIMATION:
//     - "Volume" type: each bar's volume (or each intrabar's volume) is spread across the
//       price rows its High-Low range overlaps, proportional to the overlap.
//     - "TPO" type: time-at-price. Each bar adds 1 to every row its range touches. No volume used.
//   Forex / CFD / metals volume on TradingView is TICK volume, not traded quantity.
//   Futures volume is not comparable with OTC spot/CFD volume.
//
// SIGNAL TIMING
//   Profiles are rebuilt from stored bars; nothing reads future bars.
//   The current profile is DEVELOPING and can change (including its row size) until the
//   period closes. A profile is FINAL only after the next period starts; its row size is then frozen.
//   VA_ACCEPT / VA_REJECT are evaluated on confirmed bar closes against the PREVIOUS final profile.
//   POC_SHIFT is evaluated on the first bar of a new period (period boundary is known at bar open).
indicator("Day Trade Setup - Volume Profile", shorttitle = "DTS · Volume Profile", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
string G_START = "01 · Quick start"
string profileType = input.string("Volume", "Profile type", options = ["Volume", "TPO"], tooltip = "Volume: approximate volume-at-price from bar ranges. TPO: time-at-price (counts bars touching each row), needs no volume. If the symbol has no volume at all the script falls back to TPO and says so in the panel.", group = G_START)
string rangeMode = input.string("Session", "Range", options = ["Session", "Fixed bars"], tooltip = "Session: one profile per period (day, week...). Fixed bars: one rolling profile over the last N chart bars.", group = G_START)
string periodTf = input.timeframe("D", "Session period", tooltip = "Used in Session mode. Must be higher than the chart timeframe. Period boundaries follow the exchange calendar of the symbol.", group = G_START)
int fixedBars = input.int(200, "Fixed bars", minval = 20, maxval = 5000, group = G_START)
int keepCount = input.int(0, "Previous profiles", minval = 0, maxval = 3, tooltip = "0 = draw only today's (developing) profile, with its lines starting at the period start. Raise it to also draw completed previous profiles. The VA_ACCEPT / VA_REJECT / POC_SHIFT events still use the previous final profile internally even when it is not drawn.", group = G_START)
bool intraSel = input.bool(true, "Use intrabars", tooltip = "Volume type only. Builds the profile from lower-timeframe bars when available. Falls back to chart bars where intrabar history is missing. Still an approximation.", group = G_START)
string ltf = input.timeframe("1", "Intrabar timeframe", tooltip = "Must be lower than the chart timeframe, otherwise chart bars are used.", group = G_START)
 
string splitMode = input.string("Close location", "Buy-Sell split (proxy)", options = ["Close location", "Candle direction"], tooltip = "PROXY ONLY: TradingView provides no bid/ask or aggressor data. Close location: share counted as buy = (close-low)/(high-low). Candle direction: all buy if close>open, all sell if close<open, half/half if equal. Applied per bar, or per intrabar when intrabars are on.", group = G_START)
 
string G_VA = "02 · Rows & Value Area"
float vaPct = input.float(70.0, "Value Area %", minval = 50.0, maxval = 95.0, step = 1.0, group = G_VA)
string rowMode = input.string("Auto (ATR)", "Row size", options = ["Auto (ATR)", "Manual (ticks)"], tooltip = "Auto: row = max(mintick, ATR x multiple), rounded to a mintick multiple. Manual: ticks per row x symbol mintick. Never assumes a fixed tick size.", group = G_VA)
int atrLen = input.int(14, "ATR length", minval = 1, group = G_VA)
float atrMult = input.float(0.25, "ATR multiple", minval = 0.02, maxval = 5.0, step = 0.01, group = G_VA)
int ticksPerRow = input.int(10, "Ticks per row (manual)", minval = 1, group = G_VA)
int maxRows = input.int(60, "Max rows", minval = 20, maxval = 120, tooltip = "Hard cap. If the range needs more rows the row size grows. Drawing budget is 480 of 500 boxes: Classic uses 1 box per row, Buy/Sell + Delta uses 3 per row + 3 bands. The developing profile is drawn first, then the newest previous profiles that still fit.", group = G_VA)
int smoothLen = input.int(1, "Node smoothing (rows each side)", minval = 0, maxval = 3, group = G_VA)
float promQ = input.float(0.15, "Node prominence (x max volume)", minval = 0.02, maxval = 0.8, step = 0.01, tooltip = "HVN/LVN must stand out by at least this fraction of the highest smoothed row.", group = G_VA)
int maxNodes = input.int(2, "Nodes per side (HVN / LVN)", minval = 0, maxval = 3, group = G_VA)
 
string G_VIEW = "03 · Appearance"
string viewStyle = input.string("Buy/Sell + Delta", "Style", options = ["Buy/Sell + Delta", "Classic"], tooltip = "Buy/Sell + Delta: two-tone rows (buy next to the axis, sell outside), grey outside the Value Area, Delta column to the right, bands on POC/VAH/VAL. Uses 3 boxes per row, so fewer previous profiles fit within TradingView's 500-box limit. TPO type always uses Classic.", group = G_VIEW)
int widthBars = input.int(60, "Histogram width (bars)", minval = 10, maxval = 200, tooltip = "Widths are whole chart bars, so a wider histogram gives a finer buy/sell split.", group = G_VIEW)
int segGap = input.int(2, "Gap between buy and sell (bars)", minval = 0, maxval = 6, tooltip = "Stacked layout: empty bars between the blue (buy) and gold (sell) segments of each row. Mirrored layout: gap between the sell side and the buy side. Ignored by Split rows. 0 = touching.", group = G_VIEW)
string bsLayout = input.string("Split rows", "Buy-Sell layout", options = ["Split rows", "Stacked", "Mirrored"], tooltip = "Split rows: two separate thin bars per price level, sell (gold) above, buy (blue) below, both from the axis. Stacked: one bar per row, buy next to the axis and sell outside. Mirrored: sell grows left of the axis, buy grows right. In Split rows and Mirrored, each side is scaled to the largest single side, not to the row total.", group = G_VIEW)
bool showValues = input.bool(false, "Value labels (Split rows, today only)", tooltip = "Writes the sell and buy volume at the end of each bar of the developing profile. Needs about 2 labels per row, so lower Max rows or zoom in to keep it readable.", group = G_VIEW)
bool mirrored = bsLayout == "Mirrored"
bool splitRows = bsLayout == "Split rows"
int deltaWidth = input.int(12, "Delta column width (bars)", minval = 4, maxval = 40, group = G_VIEW)
bool showDelta = input.bool(true, "Delta column", group = G_VIEW)
bool showBands = input.bool(true, "Level bands", group = G_VIEW)
int axisOffset = input.int(10, "Gap from last bar", minval = 0, maxval = 100, tooltip = "Developing profile only: empty bars between the last candle and the left edge of the histogram. The histogram, Delta column and labels are all drawn to the right of this gap (about gap + histogram width + Delta width + 10 bars in total), so scroll the chart right or add right margin.", group = G_VIEW)
string placement = input.string("Range start →", "Placement", options = ["Range start →", "Range end ←"], group = G_VIEW)
bool showLabels = input.bool(true, "Price labels", group = G_VIEW)
bool showNodes = input.bool(true, "Show HVN / LVN", group = G_VIEW)
bool extendLatest = input.bool(false, "Extend latest previous-profile levels", tooltip = "Only affects a drawn previous profile (Previous profiles > 0). Off: its lines stop at its own last bar.", group = G_VIEW)
int finalFade = input.int(25, "Final profile fade", minval = 0, maxval = 50, group = G_VIEW)
bool showIB = input.bool(false, "Initial Balance", inline = "ib", group = G_VIEW)
int ibMinutes = input.int(60, "minutes", minval = 5, maxval = 720, inline = "ib", group = G_VIEW)
bool showAvwap = input.bool(false, "Anchored VWAP (period start)", inline = "av", group = G_VIEW)
bool avwapBands = input.bool(false, "Bands", inline = "av", group = G_VIEW)
float avwapMult = input.float(1.0, "Band σ", minval = 0.5, maxval = 4.0, step = 0.5, group = G_VIEW)
bool showPanel = input.bool(true, "Status panel", group = G_VIEW)
string panelCorner = input.string("Top right", "Panel position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G_VIEW)
string panelSizeIn = input.string("Small", "Panel text size", options = ["Tiny", "Small", "Normal"], group = G_VIEW)
 
string G_EVT = "04 · Events & alerts"
bool showEvents = input.bool(true, "Show event markers", group = G_EVT)
int acceptBars = input.int(2, "VA accept: closes outside", minval = 1, maxval = 10, tooltip = "Consecutive confirmed closes outside the previous final Value Area needed for VA_ACCEPT. Fewer closes followed by a close back inside = VA_REJECT.", group = G_EVT)
int pocShiftRows = input.int(3, "POC shift: minimum rows", minval = 1, maxval = 20, tooltip = "POC_SHIFT fires on the first bar of a new period when the previous final POC differs from the one before by at least this many rows of the newer profile.", group = G_EVT)
 
string G_COLOR = "05 · DTS palette"
color cCyan = input.color(#00D4FF, "Value Area / Cyan", group = G_COLOR)
color cBlue = input.color(#5368FF, "Outside VA / Electric blue", group = G_COLOR)
color cMagenta = input.color(#D82BFF, "POC / Magenta", group = G_COLOR)
color cNavy = input.color(#050A1F, "Panel background", group = G_COLOR)
color cBuy = input.color(#2448C0, "Buy (in VA)", inline = "bs", group = G_COLOR)
color cSell = input.color(#B38B2E, "Sell (in VA)", inline = "bs", group = G_COLOR)
color cGrayBuy = input.color(#303030, "Buy (outside VA)", inline = "gr", group = G_COLOR)
color cGraySell = input.color(#6E6E6E, "Sell (outside VA)", inline = "gr", group = G_COLOR)
color cDeltaPos = input.color(#347A73, "Delta +", inline = "dl", group = G_COLOR)
color cDeltaNeg = input.color(#9C3C3C, "Delta -", inline = "dl", group = G_COLOR)
color cBand = input.color(#8A5A1A, "Level band", group = G_COLOR)
color cInk = #DCE4F1
color cMuted = #94A3C5
// Dashboard text colours (lighter than the bar colours so they stay readable on the dark panel).
color cUpTxt = #5EE0D2
color cDnTxt = #FF7A7A
color cBuyTxt = #6C8CFF
color cSellTxt = #E0B24F
color cRowA = #070D22
color cRowB = #0B1430
 
// ─────────────────────────────────────────────────────────────────────────────
// DERIVED SETTINGS
// ─────────────────────────────────────────────────────────────────────────────
const int MAX_ATOMS = 50000
// Drawings use bar_index x positions. Pine rejects positions further back than the history buffer
// (max_bars_back = 5000), so every x is clamped to MAX_BACK bars before the last bar, and profiles
// that end beyond it are not drawn.
const int MAX_BACK = 4900
bool isSession = rangeMode == "Session"
bool tpoSel = profileType == "TPO"
bool periodOk = not isSession or timeframe.in_seconds(periodTf) > timeframe.in_seconds(timeframe.period)
bool ltfLower = timeframe.in_seconds(ltf) < timeframe.in_seconds(timeframe.period)
bool useIntra = intraSel and not tpoSel and ltfLower
string panelPos = panelCorner == "Top left" ? position.top_left : panelCorner == "Bottom left" ? position.bottom_left : panelCorner == "Bottom right" ? position.bottom_right : position.top_right
string panelSz = panelSizeIn == "Tiny" ? size.tiny : panelSizeIn == "Normal" ? size.normal : size.small
 
float atrV = ta.atr(atrLen)
float volSeen = ta.cum(nz(volume))
bool tpoMode = tpoSel or volSeen == 0
 
// ─────────────────────────────────────────────────────────────────────────────
// TYPES AND STATE
// ─────────────────────────────────────────────────────────────────────────────
// One completed or developing profile. Row r covers [baseLow + r*bin, baseLow + (r+1)*bin).
type Profile
    int startBar
    int endBar
    float baseLow
    float bin
    int rows
    array<float> vol
    array<float> buy
    float total
    int pocRow
    int valRow
    int vahRow
    float vaVolume
    array<int> hvnRows
    array<int> lvnRows
    float ibHigh
    float ibLow
    bool tpo
    bool developing
 
// "Atoms" = the volume pieces the profile is built from: one per chart bar, or one per intrabar.
var array<float> aLo = array.new<float>()
var array<float> aHi = array.new<float>()
var array<float> aVol = array.new<float>()
var array<int> aBar = array.new<int>()
var array<float> aShare = array.new<float>() // share of the atom's volume counted as buy (proxy)
var array<Profile> finals = array.new<Profile>()
var int sessStartBar = 0
var int sessStartTime = time
var float sessIbH = na
var float sessIbL = na
var float refVah = na
var float refVal = na
var int outDir = 0
var int outCnt = 0
var bool outAccepted = false
var bool truncated = false
var array<box> dBoxes = array.new<box>()
var array<line> dLines = array.new<line>()
var array<label> dLabels = array.new<label>()
var table panel = table.new(panelPos, 3, 12, frame_color = color.new(cCyan, 70), frame_width = 1, border_width = 0)
 
// ─────────────────────────────────────────────────────────────────────────────
// PURE HELPERS
// ─────────────────────────────────────────────────────────────────────────────
 
// Share of a bar's volume counted as buy. A proxy from candle shape, not bid/ask data.
buyShare(float o, float h, float l, float c) =>
    float s = 0.5
    if splitMode == "Candle direction"
        s := c > o ? 1.0 : c < o ? 0.0 : 0.5
    else
        s := h > l ? (c - l) / (h - l) : 0.5
    math.max(0.0, math.min(1.0, s))
 
pocPrice(Profile p) => p.baseLow + (p.pocRow + 0.5) * p.bin
vahPrice(Profile p) => p.baseLow + (p.vahRow + 1) * p.bin
valPrice(Profile p) => p.baseLow + p.valRow * p.bin
 
// Moving average over +-s rows (window shrinks at the edges). Caller guarantees size >= 1.
smoothArray(array<float> v, int s) =>
    int n = v.size()
    array<float> out = array.new<float>(n, 0.0)
    for i = 0 to n - 1
        int wLo = math.max(0, i - s)
        int wHi = math.min(n - 1, i + s)
        float acc = 0.0
        for j = wLo to wHi
            acc += v.get(j)
        out.set(i, acc / (wHi - wLo + 1))
    out
 
// Topographic prominence of the peak at index i: peak - max(left base, right base).
// Each base is the lowest value walked before meeting a strictly higher value or the array end.
peakProminence(array<float> a, int i) =>
    float peak = a.get(i)
    int n = a.size()
    float leftMin = peak
    int jl = i - 1
    while jl >= 0
        float vl = a.get(jl)
        if vl > peak
            break
        leftMin := math.min(leftMin, vl)
        jl -= 1
    float rightMin = peak
    int jr = i + 1
    while jr < n
        float vr = a.get(jr)
        if vr > peak
            break
        rightMin := math.min(rightMin, vr)
        jr += 1
    peak - math.max(leftMin, rightMin)
 
// Local maxima (edge rows excluded) with prominence >= minProm, strongest first, at most maxCount.
// Rows within skipRad of skipRow are ignored (used to keep HVNs off the POC).
findPeaks(array<float> a, float minProm, int maxCount, int skipRow, int skipRad) =>
    array<int> out = array.new<int>()
    array<int> cand = array.new<int>()
    array<float> prom = array.new<float>()
    int n = a.size()
    if n >= 3
        for i = 1 to n - 2
            if a.get(i) > a.get(i - 1) and a.get(i) >= a.get(i + 1) and math.abs(i - skipRow) > skipRad
                float pr = peakProminence(a, i)
                if pr > 0 and pr >= minProm
                    cand.push(i)
                    prom.push(pr)
    int picks = math.min(maxCount, cand.size())
    int taken = 0
    while taken < picks
        int best = -1
        float bestP = -1.0
        for m = 0 to cand.size() - 1
            if prom.get(m) > bestP
                bestP := prom.get(m)
                best := m
        out.push(cand.get(best))
        prom.set(best, -2.0)
        taken += 1
    out
 
// ─────────────────────────────────────────────────────────────────────────────
// PROFILE ENGINE
// 1) row size  2) distribute atoms into rows  3) POC  4) Value Area  5) HVN / LVN
// ─────────────────────────────────────────────────────────────────────────────
buildProfile(array<float> los, array<float> his, array<float> vs, array<float> shs, int startBar, int endBar, float ibH, float ibL, float atrIn, bool tpo, bool developing) =>
    Profile out = na
    int n = vs.size()
    if n > 0
        float tick = syminfo.mintick
        float pLow = los.min()
        float pHigh = his.max()
        float mid = (pLow + pHigh) / 2.0
 
        // 1) Row size from symbol spec / ATR, never a hardcoded tick.
        float rawBin = rowMode == "Manual (ticks)" ? ticksPerRow * tick : nz(atrIn, 0.0) * atrMult
        float bin = math.max(tick, math.round(rawBin / tick) * tick)
        float base = math.floor(pLow / bin) * bin
        int rows = math.max(1, math.ceil((pHigh - base) / bin - 1e-9))
        if rows > maxRows
            bin := math.max(tick, math.ceil((pHigh - pLow) / (maxRows - 1) / tick) * tick)
            base := math.floor(pLow / bin) * bin
            rows := math.max(1, math.ceil((pHigh - base) / bin - 1e-9))
 
        // 2) Distribute. Volume: proportional to range overlap. TPO: +1 per touched row.
        array<float> vol = array.new<float>(rows, 0.0)
        array<float> buy = array.new<float>(rows, 0.0)
        for i = 0 to n - 1
            float aLow = los.get(i)
            float aHigh = his.get(i)
            float av = vs.get(i)
            float ash = nz(shs.get(i), 0.5)
            if tpo or av > 0
                int r0 = math.max(0, math.min(rows - 1, math.floor((aLow - base) / bin)))
                float span = aHigh - aLow
                if span < tick * 0.001
                    vol.set(r0, vol.get(r0) + (tpo ? 1.0 : av))
                    buy.set(r0, buy.get(r0) + (tpo ? 0.0 : av * ash))
                else
                    int r1 = math.max(r0, math.min(rows - 1, math.floor((aHigh - base) / bin)))
                    for r = r0 to r1
                        float rowLo = base + r * bin
                        float ov = math.min(aHigh, rowLo + bin) - math.max(aLow, rowLo)
                        if ov > tick * 1e-6
                            vol.set(r, vol.get(r) + (tpo ? 1.0 : av * ov / span))
                            buy.set(r, buy.get(r) + (tpo ? 0.0 : av * ov / span * ash))
        float total = vol.sum()
 
        if total > 0
            // 3) POC = max row; tie -> row centre closest to the range midpoint.
            float eps = total * 1e-12
            int poc = 0
            float bestV = -1.0
            float bestD = 0.0
            for i = 0 to rows - 1
                float vi = vol.get(i)
                float di = math.abs(base + (i + 0.5) * bin - mid)
                if vi > bestV + eps or (math.abs(vi - bestV) <= eps and di < bestD)
                    bestV := vi
                    bestD := di
                    poc := i
 
            // 4) Value Area: from POC add the larger of the next two rows above / below
            //    until the covered volume reaches vaPct of the total. Tie -> upper pair.
            float target = vaPct / 100.0 * total
            int vaLo = poc
            int vaHi = poc
            float acc = vol.get(poc)
            while acc < target and (vaLo > 0 or vaHi < rows - 1)
                float upSum = 0.0
                int upN = 0
                if vaHi < rows - 1
                    upSum := vol.get(vaHi + 1)
                    upN := 1
                    if vaHi + 1 < rows - 1
                        upSum += vol.get(vaHi + 2)
                        upN := 2
                float dnSum = 0.0
                int dnN = 0
                if vaLo > 0
                    dnSum := vol.get(vaLo - 1)
                    dnN := 1
                    if vaLo - 1 > 0
                        dnSum += vol.get(vaLo - 2)
                        dnN := 2
                if upN > 0 and (dnN == 0 or upSum >= dnSum)
                    acc += upSum
                    vaHi += upN
                else
                    acc += dnSum
                    vaLo -= dnN
 
            // 5) Nodes on the smoothed histogram. LVN = peaks of the inverted histogram.
            array<float> sm = smoothArray(vol, smoothLen)
            float smMax = sm.max()
            float minProm = promQ * smMax
            array<int> hv = findPeaks(sm, minProm, maxNodes, poc, smoothLen)
            array<float> inv = array.new<float>(rows, 0.0)
            for i = 0 to rows - 1
                inv.set(i, smMax - sm.get(i))
            array<int> lv = findPeaks(inv, minProm, maxNodes, -100, 0)
 
            out := Profile.new(startBar = startBar, endBar = endBar, baseLow = base, bin = bin, rows = rows, vol = vol, buy = buy, total = total, pocRow = poc, valRow = vaLo, vahRow = vaHi, vaVolume = acc, hvnRows = hv, lvnRows = lv, ibHigh = ibH, ibLow = ibL, tpo = tpo, developing = developing)
    out
 
// ─────────────────────────────────────────────────────────────────────────────
// DRAWING (called on the last bar only; everything is deleted and redrawn)
// ─────────────────────────────────────────────────────────────────────────────
clearDrawings() =>
    while dBoxes.size() > 0
        box.delete(dBoxes.pop())
    while dLines.size() > 0
        line.delete(dLines.pop())
    while dLabels.size() > 0
        label.delete(dLabels.pop())
 
addLevel(int xa, int xb, int xl, float y, string txt, color c, int wdt, string sty, bool ext) =>
    line ln = line.new(math.max(xa, bar_index - MAX_BACK), y, xb, y, xloc = xloc.bar_index, color = c, style = sty, width = wdt)
    if ext
        line.set_extend(ln, extend.right)
    dLines.push(ln)
    if showLabels and txt != ""
        dLabels.push(label.new(xl, y, txt + " " + str.tostring(y, format.mintick), xloc = xloc.bar_index, style = label.style_label_left, color = color.new(cNavy, 25), textcolor = c, size = size.tiny))
 
// Level lines and labels shared by both styles. xl = x position of the price labels.
drawLevels(Profile p, bool latest, int xl) =>
    bool ext = latest and extendLatest
    int xLineEnd = ext ? bar_index : p.endBar
    addLevel(p.startBar, xLineEnd, xl, pocPrice(p), "POC", cMagenta, 2, line.style_solid, ext)
    addLevel(p.startBar, xLineEnd, xl, vahPrice(p), "VAH", cCyan, 1, line.style_solid, ext)
    addLevel(p.startBar, xLineEnd, xl, valPrice(p), "VAL", cCyan, 1, line.style_solid, ext)
    if showIB and isSession and not na(p.ibHigh) and not na(p.ibLow)
        addLevel(p.startBar, p.endBar, xl, p.ibHigh, "IB H", cInk, 1, line.style_dashed, false)
        addLevel(p.startBar, p.endBar, xl, p.ibLow, "IB L", cInk, 1, line.style_dashed, false)
    if showNodes
        int nh = p.hvnRows.size()
        if nh > 0
            for k = 0 to nh - 1
                addLevel(p.startBar, p.endBar, xl, p.baseLow + (p.hvnRows.get(k) + 0.5) * p.bin, "HVN", cInk, 1, line.style_dotted, false)
        int nl = p.lvnRows.size()
        if nl > 0
            for k = 0 to nl - 1
                addLevel(p.startBar, p.endBar, xl, p.baseLow + (p.lvnRows.get(k) + 0.5) * p.bin, "LVN", cMuted, 1, line.style_dashed, false)
    true
 
// Classic style: one box per row, POC magenta, Value Area cyan, outside blue.
drawClassic(Profile p, bool latest) =>
    float maxV = p.vol.max()
    int fade = p.developing ? 0 : finalFade
    bool leftAnchor = placement == "Range start →"
    // Range end ←: developing profile sits to the right of the last bar, after the gap.
    int axisX = p.developing ? p.endBar + axisOffset + widthBars : p.endBar
    for r = 0 to p.rows - 1
        float vr = p.vol.get(r)
        if vr > 0
            int wr = math.max(1, math.round(vr / maxV * widthBars))
            bool inVa = r >= p.valRow and r <= p.vahRow
            color baseCol = r == p.pocRow ? cMagenta : inVa ? cCyan : cBlue
            int transp = (r == p.pocRow ? 12 : inVa ? 42 : 72) + fade
            int xLeft = math.max(p.startBar, bar_index - MAX_BACK)
            int x1 = leftAnchor ? xLeft : math.max(0, bar_index - MAX_BACK, axisX - wr)
            int x2 = leftAnchor ? xLeft + wr : axisX
            float yLo = p.baseLow + r * p.bin
            dBoxes.push(box.new(x1, yLo + p.bin, x2, yLo, border_color = na, bgcolor = color.new(baseCol, math.min(95, transp)), xloc = xloc.bar_index))
    int xLineEnd = latest and extendLatest ? bar_index : p.endBar
    drawLevels(p, latest, (p.developing and not leftAnchor ? axisX : xLineEnd) + 2)
    true
 
// Buy/Sell + Delta style. Bars grow LEFT from an axis; delta column grows RIGHT of it.
// Per row: buy (next to axis) + sell (outside) = row volume. Delta = buy - sell.
// Boxes per profile: 3 x rows + 3 bands.
drawBS(Profile p, bool latest) =>
    float maxV = p.vol.max()
    float maxD = 0.0
    float maxS = 0.0
    for r = 0 to p.rows - 1
        float vAll = p.vol.get(r)
        float vBuy = p.buy.get(r)
        maxD := math.max(maxD, math.abs(2.0 * vBuy - vAll))
        maxS := math.max(maxS, math.max(vBuy, vAll - vBuy))
    int fade = p.developing ? 0 : finalFade
    // Layouts (all grow left from the axis unless noted):
    //   Split rows : sell bar in the upper part of the row, buy bar in the lower part, each from the axis,
    //                each scaled to the biggest single side (maxS). Optional value labels on the developing profile.
    //   Stacked    : one bar per row, buy next to the axis, sell outside, optional gap between.
    //   Mirrored   : sell grows left of the axis, buy grows right of it (segGap apart), half width each.
    int sideW = math.max(2, math.round(widthBars / 2.0))
    int leftW = mirrored ? sideW : widthBars
    int rightW = mirrored ? segGap + sideW : 0
    int xAx = p.developing ? p.endBar + axisOffset + leftW : p.endBar
    int xFar = math.max(0, bar_index - MAX_BACK, xAx - leftW)
    int xDelta = xAx + rightW + 1
    if showBands
        array<int> bandRows = array.from(p.pocRow, p.vahRow, p.valRow)
        for bandRow in bandRows
            float bLo = p.baseLow + bandRow * p.bin
            dBoxes.push(box.new(xFar, bLo + p.bin, xAx + rightW, bLo, border_color = na, bgcolor = color.new(cBand, math.min(95, 60 + fade)), xloc = xloc.bar_index))
    for r = 0 to p.rows - 1
        float vr = p.vol.get(r)
        if vr > 0
            float buyV = p.buy.get(r)
            float sellV = vr - buyV
            bool inVa = r >= p.valRow and r <= p.vahRow
            float rowLo = p.baseLow + r * p.bin
            float yLo = rowLo + 0.08 * p.bin
            float yHi = rowLo + 0.92 * p.bin
            color colBuy = color.new(inVa ? cBuy : cGrayBuy, math.min(95, fade))
            color colSell = color.new(inVa ? cSell : cGraySell, math.min(95, fade))
            if splitRows
                int wB = buyV > 0 ? math.max(1, math.round(buyV / maxS * widthBars)) : 0
                int wS = sellV > 0 ? math.max(1, math.round(sellV / maxS * widthBars)) : 0
                float sBot = rowLo + 0.52 * p.bin
                float bTop = rowLo + 0.48 * p.bin
                if wS > 0
                    dBoxes.push(box.new(xAx - wS, yHi, xAx, sBot, border_color = na, bgcolor = colSell, xloc = xloc.bar_index))
                if wB > 0
                    dBoxes.push(box.new(xAx - wB, bTop, xAx, yLo, border_color = na, bgcolor = colBuy, xloc = xloc.bar_index))
                if showValues and p.developing
                    if wS > 0
                        dLabels.push(label.new(xAx - wS - 1, (yHi + sBot) / 2.0, str.tostring(sellV, format.volume), xloc = xloc.bar_index, style = label.style_label_right, color = color.new(cNavy, 100), textcolor = cSell, size = size.tiny))
                    if wB > 0
                        dLabels.push(label.new(xAx - wB - 1, (bTop + yLo) / 2.0, str.tostring(buyV, format.volume), xloc = xloc.bar_index, style = label.style_label_right, color = color.new(cNavy, 100), textcolor = cBuy, size = size.tiny))
            else if mirrored
                int wB = buyV > 0 ? math.max(1, math.round(buyV / maxS * sideW)) : 0
                int wS = sellV > 0 ? math.max(1, math.round(sellV / maxS * sideW)) : 0
                if wS > 0
                    dBoxes.push(box.new(xAx - wS, yHi, xAx, yLo, border_color = na, bgcolor = colSell, xloc = xloc.bar_index))
                if wB > 0
                    dBoxes.push(box.new(xAx + segGap, yHi, xAx + segGap + wB, yLo, border_color = na, bgcolor = colBuy, xloc = xloc.bar_index))
            else
                int scaleW = math.max(1, widthBars - segGap)
                int wTot = math.max(1, math.round(vr / maxV * scaleW))
                int wBuy = math.round(buyV / vr * wTot)
                int wSell = wTot - wBuy
                int gapUsed = wBuy > 0 and wSell > 0 ? segGap : 0
                if wBuy > 0
                    dBoxes.push(box.new(xAx - wBuy, yHi, xAx, yLo, border_color = na, bgcolor = colBuy, xloc = xloc.bar_index))
                if wSell > 0
                    dBoxes.push(box.new(xAx - wBuy - gapUsed - wSell, yHi, xAx - wBuy - gapUsed, yLo, border_color = na, bgcolor = colSell, xloc = xloc.bar_index))
            if showDelta and maxD > 0
                float dl = 2.0 * buyV - vr
                int wD = math.round(math.abs(dl) / maxD * deltaWidth)
                if wD > 0
                    dBoxes.push(box.new(xDelta, yHi, xDelta + wD, yLo, border_color = na, bgcolor = color.new(dl >= 0 ? cDeltaPos : cDeltaNeg, math.min(95, fade)), xloc = xloc.bar_index))
    drawLevels(p, latest, xDelta + (showDelta ? deltaWidth : 0) + 3)
    true
 
// Boxes this profile will use (for the 500-box budget).
boxCost(Profile p) => viewStyle == "Buy/Sell + Delta" and not p.tpo ? p.rows * 3 + 3 : p.rows
 
drawAny(Profile p, bool latest) =>
    bool bs = viewStyle == "Buy/Sell + Delta" and not p.tpo
    // Skip profiles that would need x positions beyond the history buffer.
    int oldest = bar_index - MAX_BACK
    bool tooOld = bs ? p.endBar - widthBars < oldest : p.endBar < oldest
    if not tooOld
        if bs
            drawBS(p, latest)
        else
            drawClassic(p, latest)
    true
 
// One dashboard row: label (left), value (right), extra (left, padded).
setRow(int row, string a, string b, string c, color ca, color cb, color cc, color bg) =>
    table.cell(panel, 0, row, a, text_color = ca, text_halign = text.align_left, text_size = panelSz, bgcolor = bg)
    table.cell(panel, 1, row, b, text_color = cb, text_halign = text.align_right, text_size = panelSz, bgcolor = bg)
    table.cell(panel, 2, row, c == "" ? "" : "  " + c, text_color = cc, text_halign = text.align_left, text_size = panelSz, bgcolor = bg)
 
// Distance from the current close to a level: arrow shows whether the level is above or below price.
distTxt(float level) => na(level) ? "" : (level >= close ? "▲ " : "▼ ") + str.tostring(math.abs(level - close), format.mintick)
 
// ─────────────────────────────────────────────────────────────────────────────
// MAIN, PER BAR
// ─────────────────────────────────────────────────────────────────────────────
// Intrabar requests (chart-bar fallback is used when empty).
array<float> ltfHi = useIntra ? request.security_lower_tf(syminfo.tickerid, ltf, high) : na
array<float> ltfLo = useIntra ? request.security_lower_tf(syminfo.tickerid, ltf, low) : na
array<float> ltfVol = useIntra ? request.security_lower_tf(syminfo.tickerid, ltf, nz(volume)) : na
array<float> ltfOpen = useIntra ? request.security_lower_tf(syminfo.tickerid, ltf, open) : na
array<float> ltfClose = useIntra ? request.security_lower_tf(syminfo.tickerid, ltf, close) : na
 
bool evAcceptUp = false
bool evAcceptDn = false
bool evRejectUp = false
bool evRejectDn = false
bool evPocUp = false
bool evPocDn = false
 
bool tfChanged = timeframe.change(periodTf) // evaluated every bar: v6 short-circuiting must not skip it
bool newPeriod = isSession and periodOk and tfChanged
if newPeriod
    // Finalise the period that just ended (bars up to bar_index - 1). Its row size is frozen here.
    if aVol.size() > 0
        Profile fin = buildProfile(aLo, aHi, aVol, aShare, aBar.first(), bar_index - 1, sessIbH, sessIbL, nz(atrV[1], 0.0), tpoMode, false)
        if not na(fin)
            if finals.size() > 0
                Profile prv = finals.last()
                float shiftRows = (pocPrice(fin) - pocPrice(prv)) / fin.bin
                evPocUp := shiftRows >= pocShiftRows
                evPocDn := shiftRows <= -pocShiftRows
            finals.push(fin)
            while finals.size() > 4
                finals.shift()
            refVah := vahPrice(fin)
            refVal := valPrice(fin)
    aLo.clear()
    aHi.clear()
    aVol.clear()
    aBar.clear()
    aShare.clear()
    sessStartBar := bar_index
    sessStartTime := time
    sessIbH := na
    sessIbL := na
    outDir := 0
    outCnt := 0
    outAccepted := false
 
// Collect atoms for the current range.
if periodOk
    int nI = useIntra and volSeen > 0 and not na(ltfVol) ? ltfVol.size() : 0
    bool haveIntra = nI > 0 and ltfHi.size() == nI and ltfLo.size() == nI and ltfOpen.size() == nI and ltfClose.size() == nI
    if haveIntra
        for k = 0 to nI - 1
            float ih = ltfHi.get(k)
            float il = ltfLo.get(k)
            if not na(ih) and not na(il)
                aLo.push(il)
                aHi.push(ih)
                aVol.push(nz(ltfVol.get(k)))
                aBar.push(bar_index)
                aShare.push(nz(buyShare(ltfOpen.get(k), ih, il, ltfClose.get(k)), 0.5))
    else
        if not na(high) and not na(low)
            aLo.push(low)
            aHi.push(high)
            aVol.push(nz(volume))
            aBar.push(bar_index)
            aShare.push(nz(buyShare(open, high, low, close), 0.5))
    if not isSession
        while aBar.size() > 0 and aBar.first() <= bar_index - fixedBars
            aLo.shift()
            aHi.shift()
            aVol.shift()
            aBar.shift()
            aShare.shift()
    while aVol.size() > MAX_ATOMS
        aLo.shift()
        aHi.shift()
        aVol.shift()
        aBar.shift()
        aShare.shift()
        truncated := true
 
// Initial Balance of the current period (bar open time inside the first ibMinutes).
if isSession and periodOk and time - sessStartTime < ibMinutes * 60 * 1000
    sessIbH := na(sessIbH) ? high : math.max(sessIbH, high)
    sessIbL := na(sessIbL) ? low : math.min(sessIbL, low)
 
// Acceptance / rejection against the previous FINAL Value Area, on confirmed closes only.
if barstate.isconfirmed and isSession and periodOk and not na(refVah) and not na(refVal)
    int side = close > refVah ? 1 : close < refVal ? -1 : 0
    if side != 0
        if side == outDir
            outCnt += 1
        else
            outDir := side
            outCnt := 1
            outAccepted := false
        if outCnt == acceptBars
            outAccepted := true
            evAcceptUp := side == 1
            evAcceptDn := side == -1
    else
        if outDir != 0 and not outAccepted
            evRejectUp := outDir == 1
            evRejectDn := outDir == -1
        outDir := 0
        outCnt := 0
        outAccepted := false
 
// ─────────────────────────────────────────────────────────────────────────────
// ANCHORED VWAP, EVENT MARKERS, ALERTS
// ─────────────────────────────────────────────────────────────────────────────
[avwapV, avwapUp, avwapLo] = ta.vwap(hlc3, newPeriod, avwapMult)
bool avOn = showAvwap and isSession and periodOk
plot(avOn ? avwapV : na, "AVWAP", color = cCyan, linewidth = 2)
plot(avOn and avwapBands ? avwapUp : na, "AVWAP +σ", color = color.new(cBlue, 10))
plot(avOn and avwapBands ? avwapLo : na, "AVWAP -σ", color = color.new(cBlue, 10))
 
display_t = showEvents ? display.all : display.none
plotshape(evAcceptUp, "VA_ACCEPT_UP", shape.triangleup, location.belowbar, cCyan, size = size.tiny, display = display_t)
plotshape(evAcceptDn, "VA_ACCEPT_DOWN", shape.triangledown, location.abovebar, cCyan, size = size.tiny, display = display_t)
plotshape(evRejectUp, "VA_REJECT_UP", shape.xcross, location.abovebar, cMagenta, size = size.tiny, display = display_t)
plotshape(evRejectDn, "VA_REJECT_DOWN", shape.xcross, location.belowbar, cMagenta, size = size.tiny, display = display_t)
plotshape(evPocUp, "POC_SHIFT_UP", shape.diamond, location.belowbar, cBlue, size = size.tiny, display = display_t)
plotshape(evPocDn, "POC_SHIFT_DOWN", shape.diamond, location.abovebar, cBlue, size = size.tiny, display = display_t)
 
alertcondition(evAcceptUp, "VA_ACCEPT_UP", "DTS Volume Profile: VA_ACCEPT_UP {{ticker}} accepted above previous VAH")
alertcondition(evAcceptDn, "VA_ACCEPT_DOWN", "DTS Volume Profile: VA_ACCEPT_DOWN {{ticker}} accepted below previous VAL")
alertcondition(evRejectUp, "VA_REJECT_UP", "DTS Volume Profile: VA_REJECT_UP {{ticker}} failed excursion above previous VAH")
alertcondition(evRejectDn, "VA_REJECT_DOWN", "DTS Volume Profile: VA_REJECT_DOWN {{ticker}} failed excursion below previous VAL")
alertcondition(evPocUp, "POC_SHIFT_UP", "DTS Volume Profile: POC_SHIFT_UP {{ticker}} previous session POC moved up")
alertcondition(evPocDn, "POC_SHIFT_DOWN", "DTS Volume Profile: POC_SHIFT_DOWN {{ticker}} previous session POC moved down")
 
// ─────────────────────────────────────────────────────────────────────────────
// LAST BAR: build the developing profile, redraw everything, update the panel
// ─────────────────────────────────────────────────────────────────────────────
if barstate.islast
    clearDrawings()
    Profile dev = na
    if periodOk and aVol.size() > 0
        int devStart = isSession ? sessStartBar : aBar.first()
        dev := buildProfile(aLo, aHi, aVol, aShare, devStart, bar_index, sessIbH, sessIbL, nz(atrV, 0.0), tpoMode, true)
        // Box budget 480 of 500: developing profile first, then the newest finals that still fit.
        int budget = 480
        if not na(dev)
            budget -= boxCost(dev)
        int fN = finals.size()
        int fi = fN - 1
        int shown = 0
        while isSession and fi >= 0 and shown < keepCount
            Profile fp = finals.get(fi)
            int cost = boxCost(fp)
            if cost > budget
                break
            budget -= cost
            drawAny(fp, fi == fN - 1)
            shown += 1
            fi -= 1
        if not na(dev)
            drawAny(dev, false)
 
    if showPanel
        bool haveDev = not na(dev)
        float dVah = haveDev ? vahPrice(dev) : na
        float dPoc = haveDev ? pocPrice(dev) : na
        float dVal = haveDev ? valPrice(dev) : na
        string modeTxt = (isSession ? "SESSION " + periodTf : "FIXED " + str.tostring(fixedBars)) + " · DEV"
        string srcTxt = tpoMode ? "Time (TPO)" : useIntra ? "Intrabars " + ltf : "Chart bars"
        string volTxt = tpoMode ? "No volume" : syminfo.type == "forex" or syminfo.type == "cfd" ? "Tick vol" : "Feed vol"
 
        // Where is price relative to today's developing Value Area?
        string locTxt = not haveDev ? "—" : close > dVah ? "ABOVE VA" : close < dVal ? "BELOW VA" : "INSIDE VA"
        color locCol = not haveDev ? cMuted : close > dVah ? cCyan : close < dVal ? cMagenta : cInk
 
        // Buy / sell share and delta (proxies).
        float bsum = haveDev and not tpoMode ? dev.buy.sum() : na
        float buyPct = na(bsum) ? na : bsum / dev.total * 100.0
        float devDelta = na(bsum) ? na : 2.0 * bsum - dev.total
        string buyTxt = na(buyPct) ? "—" : str.tostring(buyPct, "#") + "% BUY"
        string sellTxt = na(buyPct) ? "" : str.tostring(100.0 - buyPct, "#") + "% SELL"
        string deltaTxt = na(devDelta) ? "—" : (devDelta >= 0 ? "+" : "") + str.tostring(devDelta, format.volume)
        color deltaCol = na(devDelta) ? cMuted : devDelta >= 0 ? cUpTxt : cDnTxt
 
        bool warn = not periodOk or truncated or (volSeen == 0 and not tpoSel)
        string noteTxt = not periodOk ? "Period must be above chart TF" : volSeen == 0 and not tpoSel ? "No volume: TPO fallback" : truncated ? "Oldest data dropped (50k cap)" : tpoMode ? "Time-based, no volume" : "Approximation"
        string noteTip = "Volume-at-price is spread across each bar's High-Low range. Buy/sell and Delta are proxies from candle shape: TradingView has no bid/ask data. Forex/CFD volume is tick volume, not traded quantity."
 
        setRow(0, "DTS · VOLUME PROFILE", "", modeTxt, cCyan, cInk, cInk, color.new(cCyan, 88))
        setRow(1, "Price", str.tostring(close, format.mintick), locTxt, cInk, cInk, locCol, cRowA)
        setRow(2, "VAH", haveDev ? str.tostring(dVah, format.mintick) : "—", distTxt(dVah), cCyan, cInk, cMuted, cRowB)
        setRow(3, "POC", haveDev ? str.tostring(dPoc, format.mintick) : "—", distTxt(dPoc), cMagenta, cInk, cMuted, cRowA)
        setRow(4, "VAL", haveDev ? str.tostring(dVal, format.mintick) : "—", distTxt(dVal), cCyan, cInk, cMuted, cRowB)
        setRow(5, "Prev VAH", not na(refVah) ? str.tostring(refVah, format.mintick) : "—", distTxt(refVah), cMuted, cInk, cMuted, cRowA)
        setRow(6, "Prev VAL", not na(refVal) ? str.tostring(refVal, format.mintick) : "—", distTxt(refVal), cMuted, cInk, cMuted, cRowB)
        setRow(7, "Buy / Sell", buyTxt, sellTxt, cMuted, cBuyTxt, cSellTxt, cRowA)
        setRow(8, "Delta", deltaTxt, "proxy", cMuted, deltaCol, cMuted, cRowB)
        setRow(9, "Source", srcTxt, volTxt, cMuted, cInk, cMuted, cRowA)
        setRow(10, "Rows", haveDev ? str.tostring(dev.rows) + " × " + str.tostring(dev.bin, format.mintick) : "—", "", cMuted, cInk, cMuted, cRowB)
        table.cell(panel, 0, 11, "Note", text_color = cMuted, text_halign = text.align_left, text_size = panelSz, bgcolor = cRowA)
        table.cell(panel, 1, 11, noteTxt, text_color = warn ? cMagenta : cMuted, text_halign = text.align_right, text_size = panelSz, bgcolor = cRowA, tooltip = noteTip)
        table.cell(panel, 2, 11, "", text_size = panelSz, bgcolor = cRowA)

← 返回列表