Range Volume Density Profile [Drizzle_Algo56]

Drizzle_Algo56 · study · 786 行 · 点赞 15 · TradingView 原页

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

Pine Script

// Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International.
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Drizzle_Algo56
//@version=6
indicator("Range Volume Density Profile", shorttitle = "RVDP", overlay = true, max_boxes_count = 500, max_lines_count = 150, max_labels_count = 100, max_polylines_count = 4)
// Price-anchored rolling trading-day footprint, with the POC / VA / profile-node methodology
// of Aurora Profile VWAP v1.14. Not the Aurora VWAP / pressure-takeover engine.
// Fixed price anchors, extended history and optional second display column.
string gPrice = "Price Range"
float anchorA = input.price( 4000.0, "Price anchor 1", confirm = true, group = gPrice, inline = "anchors")
float anchorB = input.price( 4015.0, "Price anchor 2", confirm = true, group = gPrice, inline = "anchors")
string gLookback = "Lookback"
string historyMode = input.string("Selected days", "History mode", options = ["Selected days", "All loaded history"], group = gLookback, tooltip = "Selected days uses the lookback selection below. All loaded history uses all loaded bars with available footprint data.")
string lookbackSelection = input.string("Previous 1 day", "Lookback", options = ["Current", "Previous 1 day", "Previous 2 days", "Previous 3 days", "Previous 5 days", "Previous 10 days", "Previous 20 days", "Custom"], group = gLookback, active = historyMode == "Selected days", tooltip = "Current = current trading day only. Previous N days = current trading day plus N completed trading days. Day boundaries follow the symbol's 1D candles.")
int customLookbackDays = input.int(30, "Custom previous trading days", minval = 0, maxval = 3650, group = gLookback, active = historyMode == "Selected days" and lookbackSelection == "Custom")
int lookbackDays = switch lookbackSelection
    "Current" => 0
    "Previous 1 day" => 1
    "Previous 2 days" => 2
    "Previous 3 days" => 3
    "Previous 5 days" => 5
    "Previous 10 days" => 10
    "Previous 20 days" => 20
    => customLookbackDays
string gFP = "Profile Engine"
int binCount = input.int(100, "Profile rows", minval = 10, maxval = 200, group = gFP)
int ticksPerRow = input.int(5, "Ticks per footprint row", minval = 1, group = gFP)
float vaPercent = input.float(70.0, "Value Area (%)", minval = 1, maxval = 100, group = gFP)
string gPlot = "Profile Display"
string viewMode = input.string("Buy/Sell", "Profile mode", options = ["Buy/Sell", "Total + Delta color"], group = gPlot)
int offsetBars = input.int(10, "Horizontal offset (bars)", minval = -150, maxval = 150, group = gPlot)
int maxWidth = input.int(200, "Maximum width (bars)", minval = 5, maxval = 200, group = gPlot)
bool showValueAreaBG = input.bool(true, "Shade Value Area", group = gPlot)
bool showRangeBackground = input.bool(false, "Show range background", group = gPlot)
string gSecondColumn = "Profile Display · Second Column"
bool showSecondColumn = input.bool(true, "Show second column", group = gSecondColumn)
int secondColumnOffset = input.int(5, "Offset from first column (bars)", minval = 0, maxval = 100, group = gSecondColumn)
int secondColumnWidth = input.int(200, "Maximum width (bars)", minval = 5, maxval = 200, group = gSecondColumn)
string secondColumnMode = input.string("Total + Delta color", "Volume coloring", options = ["Buy/Sell", "Total + Delta color"], group = gSecondColumn, tooltip = "Renders the same range and volume in a second column. No separate profile engine or price anchors.")
bool secondShowValueArea = input.bool(true, "Shade Value Area", group = gSecondColumn)
bool secondShowRangeBackground = input.bool(false, "Show range background", group = gSecondColumn)
string gSecondColors = "Colors · Second Column"
color secondBuyColor = input.color(#03F10D, "Buy / positive delta", group = gSecondColors)
color secondSellColor = input.color(#5100DE, "Sell / negative delta", group = gSecondColors)
int secondInsideVAAlpha = input.int(10, "Profile transparency · inside VA", minval = 0, maxval = 100, group = gSecondColors)
int secondOutsideVAAlpha = input.int(50, "Profile transparency · outside VA", minval = 0, maxval = 100, group = gSecondColors)
color secondVAColor = input.color(#4E9090, "Value Area fill", group = gSecondColors)
int secondVAAlpha = input.int(93, "Value Area fill transparency", minval = 0, maxval = 100, group = gSecondColors)
color secondBackgroundColor = input.color(#4E9090, "Range background", group = gSecondColors)
int secondBackgroundAlpha = input.int(96, "Range background transparency", minval = 0, maxval = 100, group = gSecondColors)
string gLevels = "Levels & Labels"
bool showPOC = input.bool(true, "Show POC", group = gLevels, inline = "levels")
bool showVA = input.bool(true, "Show VAH / VAL", group = gLevels, inline = "levels")
bool showZoneLabels = input.bool(false, "Show zone labels", group = gLevels)
string gNode = "Zones · Display"
bool showZones = input.bool(false, "Show zones", group = gNode)
string zoneMode = input.string("LVN + HVN", "Zone mode", options = ["LVN", "HVN", "LVN + HVN"], group = gNode)
int maxZones = input.int(8, "Maximum zones per type / side", minval = 1, maxval = 12, group = gNode)
string gConfirm = "Zones · Confirmation"
int minimumBars = input.int(20, "Minimum profile bars", minval = 5, maxval = 300, group = gConfirm)
int detectionEvery = input.int(1, "Scan interval (confirmed bars)", minval = 1, maxval = 60, group = gConfirm)
int zoneConfirmScans = input.int(2, "Confirmation scans", minval = 1, maxval = 10, group = gConfirm)
float minDepth = input.float(25, "Entry prominence (%)", minval = 5, maxval = 95, group = gConfirm)
float zoneExitDepth = input.float(15, "Retention prominence (%)", minval = 1, maxval = 95, group = gConfirm)
int zoneMissingScans = input.int(3, "Expire after missing scans", minval = 1, maxval = 20, group = gConfirm)
string gSearch = "Zones · Search"
int smoothRadius = input.int(1, "Smoothing radius (rows)", minval = 0, maxval = 4, group = gSearch)
int peakWindow = input.int(8, "Shoulder search per side (rows)", minval = 2, maxval = 20, group = gSearch)
float minHVN = input.float(10, "Minimum HVN volume (% of peak)", minval = 1, maxval = 100, group = gSearch)
float zoneRise = input.float(20, "HVN expansion (%)", minval = 0, maxval = 70, group = gSearch)
float lvnCorridorRise = input.float(50, "LVN expansion (%)", minval = 10, maxval = 90, group = gSearch)
int maxZoneRows = input.int(4, "Maximum HVN height (rows)", minval = 1, maxval = 10, group = gSearch)
int maxLVNRows = input.int(8, "Maximum LVN height (rows)", minval = 2, maxval = 20, group = gSearch)
int maxEdgeLVNRows = input.int(2, "Maximum edge LVN height (rows)", minval = 1, maxval = 8, group = gSearch)
string gLines = "Node Markers"
bool showLVNLowest = input.bool(true, "LVN · lowest volume", group = gLines, inline = "lvnmarkers")
bool showLVNHighest = input.bool(false, "LVN · highest volume", group = gLines, inline = "lvnmarkers")
bool showHVNLowest = input.bool(false, "HVN · lowest volume", group = gLines, inline = "hvnmarkers")
bool showHVNHighest = input.bool(true, "HVN · highest volume", group = gLines, inline = "hvnmarkers")
int nodeLineBars = input.int(500, "Chart extension (bars)", minval = 1, maxval = 9999, group = gLines, tooltip = "Projects current zone boxes and horizontal level lines this many chart bars to the left. This is a visual projection of the current structure, not its historical detection time. Right endpoints remain clipped to the profile.")
int reactionWidth = input.int(2, "Marker width", minval = 1, maxval = 4, group = gLines)
string lvnLineType = input.string("Dashed", "LVN line type", options = ["Solid", "Dashed", "Dotted"], group = gLines)
string hvnLineType = input.string("Dashed", "HVN line type", options = ["Solid", "Dashed", "Dotted"], group = gLines)
string lvnLineStyle = lvnLineType == "Solid" ? line.style_solid : lvnLineType == "Dotted" ? line.style_dotted : line.style_dashed
string hvnLineStyle = hvnLineType == "Solid" ? line.style_solid : hvnLineType == "Dotted" ? line.style_dotted : line.style_dashed
string gDash = "Dashboard"
bool showStats = input.bool(true, "Show dashboard", group = gDash)
string dashboardLocation = input.string("Top right", "Position", options = ["Top left", "Top right", "Bottom left", "Bottom right"], group = gDash)
string dashboardFont = input.string("Small", "Text size", options = ["Tiny", "Small", "Normal"], group = gDash)
string gCP = "Colors · Profile"
color buyColor = input.color(#03F10D, "Buy", group = gCP)
color sellColor = input.color(#5100DE, "Sell", group = gCP)
color valueAreaColor = input.color(#4E9090, "Value Area fill", group = gCP)
int insideVAAlpha = input.int(10, "Profile transparency · inside VA", minval = 0, maxval = 100, group = gCP)
int outsideVAAlpha = input.int(50, "Profile transparency · outside VA", minval = 0, maxval = 100, group = gCP)
int valueAreaAlpha = input.int(93, "Value Area fill transparency", minval = 0, maxval = 100, group = gCP)
string gCL = "Colors · Levels"
color pocColor = input.color(#4E9090, "POC", group = gCL)
color vaColor = input.color(#4E9090, "VAH / VAL", group = gCL)
color rangeGuideColor = input.color(#8B92A4, "Range guides", group = gCL)
color rangeBackgroundColor = input.color(#4E9090, "Range background", group = gCL)
int rangeBackgroundAlpha = input.int(96, "Range background transparency", minval = 0, maxval = 100, group = gCL)
string gCZ = "Colors · Zones"
color lvnColor = input.color(#5100DE, "LVN", group = gCZ)
color hvnColor = input.color(#03F10D, "HVN", group = gCZ)
int zoneAlpha = input.int(88, "Zone fill transparency", minval = 0, maxval = 100, group = gCZ)
string gCM = "Colors · Node Markers"
color lvnLowColor = input.color(#FF70C9, "LVN · lowest volume", group = gCM)
color lvnHighColor = input.color(#F3CC65, "LVN · highest volume", group = gCM)
color hvnLowColor = input.color(#00D9C0, "HVN · lowest volume", group = gCM)
color hvnHighColor = input.color(#F3CC65, "HVN · highest volume", group = gCM)
string gShape = "Shape Recognition"
bool shapeEnabled = input.bool(true, "Enable shape engine", group = gShape, tooltip = "Geometric volume-distribution classes D, P, b, B or Mixed. Both columns share one underlying volume profile and therefore the same classification.")
int shapeMinimumBars = input.int(20, "Minimum footprint bars", minval = 1, maxval = 300, group = gShape)
int shapeSmooth = input.int(2, "Smoothing radius (analysis rows)", minval = 1, maxval = 6, group = gShape)
float shapePeakFloor = input.float(45, "Significant peak (% of maximum)", minval = 20, maxval = 90, group = gShape) / 100.0
float shapeValleyRatio = input.float(70, "B: valley / smaller peak (%)", minval = 20, maxval = 95, group = gShape) / 100.0
float shapeSeparation = input.float(18, "Minimum peak separation (%)", minval = 8, maxval = 40, group = gShape) / 100.0
float shapeSymmetryLimit = input.float(35, "D: maximum asymmetry (%)", minval = 10, maxval = 60, group = gShape) / 100.0
bool showShapeFirst = input.bool(true, "Show first-column contour", group = gShape)
bool showShapeSecond = input.bool(true, "Show second-column contour", group = gShape)
color firstShapeColor = input.color(#00D9C0, "First-column contour", group = gShape)
color secondShapeColor = input.color(#FF70C9, "Second-column contour", group = gShape)
int shapeLineWidth = input.int(2, "Contour width", minval = 1, maxval = 4, group = gShape)
 
// Visual dashboard configuration.
string dashboardPosition = switch dashboardLocation
    "Top right" => position.top_right
    "Bottom left" => position.bottom_left
    "Bottom right" => position.bottom_right
    => position.top_left
string dashboardSize = dashboardFont == "Tiny" ? size.tiny : dashboardFont == "Normal" ? size.normal : size.small
// Both anchors keep their original meaning and independent price handles.
float priceLow = math.min(anchorA, anchorB)
float priceHigh = math.max(anchorA, anchorB)
if barstate.isfirst
    if priceHigh <= priceLow
        runtime.error("Upper price must exceed lower price.")
    if not timeframe.isintraday or not chart.is_standard
        runtime.error("Use standard time-based intraday candles.")
    if (priceHigh - priceLow) / binCount < syminfo.mintick
        runtime.error("Profile bin size is less than the minimum tick size.")
float binSize = (priceHigh - priceLow) / binCount
// One footprint call only. POC/VA are calculated from the aggregated profile.
footprint fp = request.footprint(ticksPerRow, vaPercent)
type NodeCandidate
    float bottom
    float top
    int kind               // -1 = LVN, +1 = HVN
    float prominence
type ActiveNode
    float bottom
    float top
    int kind
    float prominence
    int bornBar
    int missingScans
type PendingNode
    float bottom
    float top
    int kind
    int seenScans
    int lastScan
// Aurora's triangular smoothing, bounded at the profile limits.
f_smooth(array<float> totals, int radius) =>
    int n = array.size(totals)
    array<float> result = array.new<float>(n, 0.0)
    for r = 0 to n - 1
        float weighted = 0.0
        float weights = 0.0
        for k = math.max(0, r - radius) to math.min(n - 1, r + radius)
            float w = radius + 1 - math.abs(k - r)
            weighted += array.get(totals, k) * w
            weights += w
        array.set(result, r, weighted / weights)
    result
// Aurora v1.14 local peaks/valleys and prominence, with side-based candidate
// selection and bin-limited expansion around each qualifying node.
f_candidates(array<float> sm, int kind, float currentPrice, int observedLo, int observedHi) =>
    int n = array.size(sm)
    float maximum = array.max(sm)
    array<float> scores = array.new<float>(n, 0.0)
    array<float> shoulders = array.new<float>(n, 0.0)
    array<NodeCandidate> result = array.new<NodeCandidate>()
    if maximum > 0 and observedHi - observedLo >= 2
        for zoneSide = -1 to 1 by 2
            array.fill(scores, 0.0)
            array.fill(shoulders, 0.0)
            for r = observedLo to observedHi
                float node = array.get(sm, r)
                float nodePrice = priceLow + (r + 0.5) * binSize
                bool onSide = zoneSide == -1 ? nodePrice < currentPrice : nodePrice >= currentPrice
                bool extremum = kind == -1 ? (r == observedLo ? node <= array.get(sm, r + 1) : r == observedHi ? node < array.get(sm, r - 1) : node < array.get(sm, r - 1) and node <= array.get(sm, r + 1)) : (r == observedLo ? node >= array.get(sm, r + 1) : r == observedHi ? node > array.get(sm, r - 1) : node > array.get(sm, r - 1) and node >= array.get(sm, r + 1))
                // Price anchor can extend into never-traded territory. Unlike
                // Aurora's session high/low profile, those tails are not LVNs.
                if onSide and extremum and r >= observedLo and r <= observedHi
                    float left = kind == -1 ? 0.0 : maximum
                    float right = kind == -1 ? 0.0 : maximum
                    if r > observedLo
                        for k = math.max(observedLo, r - peakWindow) to r - 1
                            left := kind == -1 ? math.max(left, array.get(sm, k)) : math.min(left, array.get(sm, k))
                    if r < observedHi
                        for k = r + 1 to math.min(observedHi, r + peakWindow)
                            right := kind == -1 ? math.max(right, array.get(sm, k)) : math.min(right, array.get(sm, k))
                    float shoulder = r == observedLo ? right : r == observedHi ? left : kind == -1 ? math.min(left, right) : math.max(left, right)
                    float prominence = kind == -1 ? (shoulder > 0 ? (shoulder - node) / shoulder : 0.0) : (node > 0 ? (node - shoulder) / node : 0.0)
                    if prominence >= math.min(minDepth, zoneExitDepth) / 100.0 and (kind == -1 or node >= maximum * minHVN / 100.0)
                        array.set(scores, r, prominence)
                        array.set(shoulders, r, shoulder)
            int selected = 0
            for attempt = 0 to n - 1
                float best = array.max(scores)
                if best <= 0 or selected >= maxZones
                    break
                int center = array.indexof(scores, best)
                float node = array.get(sm, center)
                float shoulder = array.get(shoulders, center)
                float cutoff = kind == -1 ? node + (shoulder - node) * lvnCorridorRise / 100.0 : node + (shoulder - node) * zoneRise / 100.0
                int widthLimit = kind == -1 ? (center == observedLo or center == observedHi ? maxEdgeLVNRows : maxLVNRows) : maxZoneRows
                int lo = center
                int hi = center
                while hi - lo + 1 < widthLimit
                    float below = lo > observedLo ? array.get(sm, lo - 1) : na
                    float above = hi < observedHi ? array.get(sm, hi + 1) : na
                    bool canDown = not na(below) and (kind == -1 ? below <= cutoff : below >= cutoff)
                    bool canUp = not na(above) and (kind == -1 ? above <= cutoff : above >= cutoff)
                    if not canDown and not canUp
                        break
                    if canDown and (not canUp or (kind == -1 ? below <= above : below >= above))
                        lo -= 1
                    else
                        hi += 1
                array.push(result, NodeCandidate.new(priceLow + lo * binSize, priceLow + (hi + 1) * binSize, kind, best))
                selected += 1
                for k = math.max(0, lo - 1) to math.min(n - 1, hi + 1)
                    array.set(scores, k, 0.0)
    result
f_overlap(float lo1, float hi1, float lo2, float hi2) =>
    lo1 < hi2 and hi1 > lo2
// Aurora's overlapping-zone identity: retain the birth bar when a node shifts,
// and limit the number of zones on each side of the current market price.
f_register(array<ActiveNode> active, NodeCandidate c, int currentBar, float currentClose) =>
    int match = -1
    if array.size(active) > 0
        for i = 0 to array.size(active) - 1
            ActiveNode z = array.get(active, i)
            if z.kind == c.kind and f_overlap(z.bottom, z.top, c.bottom, c.top)
                match := i
                break
    if match >= 0
        ActiveNode z = array.get(active, match)
        z.bottom := c.bottom
        z.top := c.top
        z.prominence := c.prominence
        z.missingScans := 0
        array.set(active, match, z)
    else
        int side = (c.bottom + c.top) * 0.5 < currentClose ? -1 : 1
        int sideCount = 0
        int oldestIndex = -1
        int oldestBar = currentBar + 1
        if array.size(active) > 0
            for i = 0 to array.size(active) - 1
                ActiveNode z = array.get(active, i)
                if z.kind == c.kind and ((z.bottom + z.top) * 0.5 < currentClose ? -1 : 1) == side
                    sideCount += 1
                    if z.bornBar < oldestBar
                        oldestBar := z.bornBar
                        oldestIndex := i
        if sideCount >= maxZones and oldestIndex >= 0
            array.remove(active, oldestIndex)
        array.push(active, ActiveNode.new(c.bottom, c.top, c.kind, c.prominence, currentBar, 0))
    true
// Aurora's POC-anchored, *contiguous* Value Area. Ties alternate by balancing
// distance from the POC, rather than always preferring the upper row.
f_valueArea(array<float> totals, float fraction) =>
    int n = array.size(totals)
    int poc = array.indexof(totals, array.max(totals))
    int lo = poc
    int hi = poc
    float included = array.get(totals, poc)
    float target = array.sum(totals) * fraction
    while included < target and (lo > 0 or hi < n - 1)
        float below = lo > 0 ? array.get(totals, lo - 1) : -1.0
        float above = hi < n - 1 ? array.get(totals, hi + 1) : -1.0
        bool takeAbove = above > below or (above == below and hi - poc <= poc - lo)
        if takeAbove
            hi += 1
            included += above
        else
            lo -= 1
            included += below
    [poc, lo, hi]
// Shape rules are geometric heuristics, not probabilities or trade signals.
// References: Overcharts distribution types; Alchemy Markets volume profile.
// Equal-width rebins keep classification independent of Display Rows.
f_shapeCurve(array<float> source) =>
    int n = source.size()
    int bins = math.min(48, n)
    array<float> packed = array.new<float>(bins, 0.0)
    array<float> smooth = array.new<float>(bins, 0.0)
    if bins > 0
        for j = 0 to n - 1
            float lo = float(j) * bins / n
            float hi = float(j + 1) * bins / n
            int first = math.max(0, int(math.floor(lo)))
            int last = math.min(bins - 1, int(math.ceil(hi)) - 1)
            for b = first to last
                float overlap = math.max(0.0, math.min(hi, b + 1.0) - math.max(lo, float(b)))
                packed.set(b, packed.get(b) + source.get(j) * overlap / (hi - lo))
        for b = 0 to bins - 1
            float weighted = 0.0
            float kernel = 0.0
            for k = math.max(0, b - shapeSmooth) to math.min(bins - 1, b + shapeSmooth)
                float weight = shapeSmooth + 1.0 - math.abs(k - b)
                weighted += packed.get(k) * weight
                kernel += weight
            smooth.set(b, weighted / kernel)
    smooth
 
f_classifyShape(array<float> curve) =>
    string code = "Mixed"
    int peaks = 0
    float peakPosition = na
    float asymmetry = na
    int n = curve.size()
    float total = n > 0 ? curve.sum() : 0.0
    if n >= 12 and total > 0
        float peak = curve.max()
        int main = curve.indexof(peak)
        peakPosition := (main + 0.5) / n
        float mean = 0.0
        float lowerMass = 0.0
        float upperMass = 0.0
        float middleMass = 0.0
        float difference = 0.0
        for j = 0 to n - 1
            float z = (j + 0.5) / n
            float value = curve.get(j)
            mean += z * value / total
            lowerMass += z < 1.0 / 3.0 ? value / total : 0.0
            upperMass += z > 2.0 / 3.0 ? value / total : 0.0
            middleMass += z >= 1.0 / 3.0 and z <= 2.0 / 3.0 ? value / total : 0.0
            difference += math.abs(value - curve.get(n - 1 - j))
        asymmetry := difference / (2.0 * total)
        array<int> candidates = array.new<int>()
        array<float> heights = array.new<float>()
        for j = 1 to n - 2
            if curve.get(j) > curve.get(j - 1) and curve.get(j) >= curve.get(j + 1) and curve.get(j) >= peak * shapePeakFloor
                candidates.push(j)
                heights.push(curve.get(j))
        array<int> major = array.from(main)
        if candidates.size() > 0
            array<int> ranked = array.sort_indices(heights, order.descending)
            for rank in ranked
                int candidate = candidates.get(rank)
                bool distinct = candidate != main
                for anchor in major
                    if math.abs(candidate - anchor) < math.max(2, int(math.ceil(n * shapeSeparation)))
                        distinct := false
                    else
                        float valley = peak
                        for j = math.min(candidate, anchor) to math.max(candidate, anchor)
                            valley := math.min(valley, curve.get(j))
                        if valley > math.min(curve.get(candidate), curve.get(anchor)) * shapeValleyRatio
                            distinct := false
                if distinct and major.size() < 4
                    major.push(candidate)
        peaks := major.size()
        if peaks == 2
            int left = math.min(major.get(0), major.get(1))
            int right = math.max(major.get(0), major.get(1))
            int split = left
            float valley = peak
            for j = left to right
                if curve.get(j) < valley
                    valley := curve.get(j)
                    split := j
            float firstLobe = 0.0
            for j = 0 to split
                firstLobe += curve.get(j) / total
            if firstLobe >= 0.20 and firstLobe <= 0.80
                code := "B"
        else if peaks == 1
            bool tapered = curve.first() < peak * 0.45 and curve.last() < peak * 0.45
            if peakPosition >= 0.30 and peakPosition <= 0.70 and mean >= 0.40 and mean <= 0.60 and asymmetry <= shapeSymmetryLimit and middleMass >= 0.40 and tapered
                code := "D"
            else if peakPosition >= 0.60 and mean >= 0.57 and upperMass > lowerMass * 1.5 and curve.first() < peak * 0.45
                code := "P"
            else if peakPosition <= 0.40 and mean <= 0.43 and lowerMass > upperMass * 1.5 and curve.last() < peak * 0.45
                code := "b"
    else
        code := "Waiting"
    [code, peaks, peakPosition, asymmetry]
 
 
// Keep one independent volume snapshot per loaded trading day.
// The current day plus lookbackDays completed days form the rolling window.
// Ordinary var state rolls back on live-bar updates to avoid double counting.
type DayProfile
    array<float> buys
    array<float> sells
    int visits
    int fpBars
    int bars
var array<DayProfile> profileDays = array.new<DayProfile>()
var array<float> buyBins = array.new_float(binCount, 0.0)
var array<float> sellBins = array.new_float(binCount, 0.0)
var array<ActiveNode> activeNodes = array.new<ActiveNode>()
var array<PendingNode> pendingNodes = array.new<PendingNode>()
var int touches = 0
var bool touchedPreviousBar = false
var int footprintBars = 0
var int dayBars = 0
var int scanId = 0
var int lastScanBar = na
var int loadedDays = 0
bool newProfileDay = timeframe.change("1D") or barstate.isfirst
if newProfileDay
    loadedDays += 1
    if historyMode == "All loaded history"
        // The aggregate retains old volume; only the current day's snapshot is needed.
        array.clear(profileDays)
    array.push(profileDays, DayProfile.new(array.new_float(binCount, 0.0), array.new_float(binCount, 0.0), 0, 0, 0))
    if historyMode == "Selected days"
        // Remove only expired volume: rollover cost is independent of retained history length.
        while array.size(profileDays) > lookbackDays + 1
            DayProfile expired = array.shift(profileDays)
            touches -= expired.visits
            footprintBars -= expired.fpBars
            dayBars -= expired.bars
            for i = 0 to binCount - 1
                array.set(buyBins, i, math.max(0.0, array.get(buyBins, i) - array.get(expired.buys, i)))
                array.set(sellBins, i, math.max(0.0, array.get(sellBins, i) - array.get(expired.sells, i)))
        // Reconfirm nodes after the trading-day window changes.
        array.clear(activeNodes)
        array.clear(pendingNodes)
        scanId := 0
        lastScanBar := na
    touchedPreviousBar := false
DayProfile today = array.get(profileDays, array.size(profileDays) - 1)
today.bars += 1
dayBars += 1
bool touchedNow = high >= priceLow and low <= priceHigh
if touchedNow and not touchedPreviousBar
    touches += 1
    today.visits += 1
touchedPreviousBar := touchedNow
// Aggregate only rows overlapping the selected price range.
// Partial rows contribute in proportion to their price overlap.
if touchedNow and not na(fp)
    footprintBars += 1
    today.fpBars += 1
    for row in fp.rows()
        float rowLow = row.down_price()
        float rowHighEx = row.up_price() + syminfo.mintick
        float rowWidth = math.max(syminfo.mintick, rowHighEx - rowLow)
        float clipLow = math.max(rowLow, priceLow)
        float clipHigh = math.min(rowHighEx, priceHigh)
        if clipHigh > clipLow
            int firstBin = math.max(0, math.min(binCount - 1, int(math.floor((clipLow - priceLow) / binSize))))
            int lastBin = math.max(0, math.min(binCount - 1, int(math.floor((clipHigh - priceLow) / binSize))))
            float rowBuy = row.buy_volume()
            float rowSell = row.sell_volume()
            for i = firstBin to lastBin
                float lowI = priceLow + i * binSize
                float highI = lowI + binSize
                float overlap = math.max(0.0, math.min(clipHigh, highI) - math.max(clipLow, lowI))
                if overlap > 0
                    float share = overlap / rowWidth
                    float addBuy = rowBuy * share
                    float addSell = rowSell * share
                    array.set(buyBins, i, array.get(buyBins, i) + addBuy)
                    array.set(sellBins, i, array.get(sellBins, i) + addSell)
                    array.set(today.buys, i, array.get(today.buys, i) + addBuy)
                    array.set(today.sells, i, array.get(today.sells, i) + addSell)
// Reconcile Aurora node identities only on confirmed chart bars. The display
// can still include the latest provisional live-bar footprint.
if barstate.isconfirmed and showZones and dayBars >= minimumBars and (na(lastScanBar) or bar_index - lastScanBar >= detectionEvery)
    array<float> totals = array.new_float(binCount, 0.0)
    for i = 0 to binCount - 1
        array.set(totals, i, array.get(buyBins, i) + array.get(sellBins, i))
    if array.sum(totals) > 0
        lastScanBar := bar_index
        array<float> sm = f_smooth(totals, smoothRadius)
        int observedLo = binCount
        int observedHi = -1
        for i = 0 to binCount - 1
            if array.get(totals, i) > 0
                observedLo := math.min(observedLo, i)
                observedHi := i
        array<NodeCandidate> candidates = array.new<NodeCandidate>()
        for kind = -1 to 1 by 2
            bool enabled = kind == -1 ? zoneMode != "HVN" : zoneMode != "LVN"
            if enabled
                array<NodeCandidate> found = f_candidates(sm, kind, close, observedLo, observedHi)
                for c in found
                    array.push(candidates, c)
        scanId += 1
        // 15%-retention candidates keep existing confirmed zones alive.
        int oldIndex = array.size(activeNodes) - 1
        while oldIndex >= 0
            ActiveNode z = array.get(activeNodes, oldIndex)
            bool present = false
            for c in candidates
                if c.kind == z.kind and f_overlap(c.bottom, c.top, z.bottom, z.top)
                    present := true
                    break
            if present
                z.missingScans := 0
            else
                z.missingScans += 1
                if z.missingScans >= zoneMissingScans
                    array.remove(activeNodes, oldIndex)
            // Reference modifications persist; explicit write for clarity.
            if present or z.missingScans < zoneMissingScans
                array.set(activeNodes, oldIndex, z)
            oldIndex -= 1
        for c in candidates
            bool strong = c.prominence >= minDepth / 100.0
            bool activeMatch = false
            for z in activeNodes
                if z.kind == c.kind and f_overlap(z.bottom, z.top, c.bottom, c.top)
                    activeMatch := true
                    break
            if activeMatch
                if strong
                    f_register(activeNodes, c, bar_index, close)
            else if strong
                int matchPending = -1
                if array.size(pendingNodes) > 0
                    for k = 0 to array.size(pendingNodes) - 1
                        PendingNode p = array.get(pendingNodes, k)
                        if p.kind == c.kind and f_overlap(p.bottom, p.top, c.bottom, c.top)
                            matchPending := k
                            break
                if matchPending < 0
                    array.push(pendingNodes, PendingNode.new(c.bottom, c.top, c.kind, 1, scanId))
                    matchPending := array.size(pendingNodes) - 1
                else
                    PendingNode p = array.get(pendingNodes, matchPending)
                    p.seenScans := p.lastScan == scanId - 1 ? p.seenScans + 1 : 1
                    p.lastScan := scanId
                    p.bottom := c.bottom
                    p.top := c.top
                    array.set(pendingNodes, matchPending, p)
                PendingNode ready = array.get(pendingNodes, matchPending)
                if ready.seenScans >= zoneConfirmScans
                    f_register(activeNodes, c, bar_index, close)
                    array.remove(pendingNodes, matchPending)
        // Non-consecutive candidate scans must not build up confirmation credit.
        int pendingIndex = array.size(pendingNodes) - 1
        while pendingIndex >= 0
            PendingNode p = array.get(pendingNodes, pendingIndex)
            if p.lastScan != scanId
                array.remove(pendingNodes, pendingIndex)
            pendingIndex -= 1
// Draw once per update; never retain duplicate profile boxes/lines.
var array<box> profileBoxes = array.new<box>()
var array<line> guideLines = array.new<line>()
var array<label> nodeLabels = array.new<label>()
var array<polyline> shapeLines = array.new<polyline>()
var table stats = table.new(dashboardPosition, 2, 14, border_width = 1, border_color = #24324A, frame_color = #35445C, frame_width = 1)
// Both display columns share the same calculation arrays. Group adjacent display
// rows only if needed to keep all boxes within TradingView's object limit.
f_drawColumn(int left, int columnWidth, string mode, int rows, int vaLeft, int vaRight, color positiveColor, color negativeColor, int insideAlpha, int outsideAlpha) =>
    array<int> rowEnds = array.new_int(binCount, left)
    array<float> displayedBuys = array.new_float(rows, 0.0)
    array<float> displayedSells = array.new_float(rows, 0.0)
    float peak = 0.0
    for row = 0 to rows - 1
        int first = int(math.floor(float(row) * binCount / rows))
        int last = int(math.floor(float(row + 1) * binCount / rows)) - 1
        float buy = 0.0
        float sell = 0.0
        for i = first to last
            buy += buyBins.get(i)
            sell += sellBins.get(i)
        displayedBuys.set(row, buy)
        displayedSells.set(row, sell)
        peak := math.max(peak, buy + sell)
    if peak > 0
        for row = 0 to rows - 1
            float buy = displayedBuys.get(row)
            float sell = displayedSells.get(row)
            float total = buy + sell
            if total <= 0
                continue
            int first = int(math.floor(float(row) * binCount / rows))
            int last = int(math.floor(float(row + 1) * binCount / rows)) - 1
            float bottom = priceLow + first * binSize
            float top = priceLow + (last + 1) * binSize
            int middle = int(math.floor((first + last) * 0.5))
            int fade = middle >= vaLeft and middle <= vaRight ? insideAlpha : outsideAlpha
            int width = math.max(1, int(math.round(columnWidth * total / peak)))
            for i = first to last
                rowEnds.set(i, left + width)
            if mode == "Buy/Sell"
                int sellWidth = int(math.round(width * sell / total))
                if sellWidth > 0
                    profileBoxes.push(box.new(left, top, left + sellWidth, bottom, border_width = 0, bgcolor = color.new(negativeColor, fade)))
                if width - sellWidth > 0
                    profileBoxes.push(box.new(left + sellWidth, top, left + width, bottom, border_width = 0, bgcolor = color.new(positiveColor, fade)))
            else
                color delta = color.from_gradient((buy - sell) / total, -1.0, 1.0, negativeColor, positiveColor)
                profileBoxes.push(box.new(left, top, left + width, bottom, border_width = 0, bgcolor = color.new(delta, fade)))
    rowEnds
 
// Each price band receives at most one background fill. All boxes share the
// exact histogram bounds: no extra right-hand strips and no frame objects.
f_columnBackground(int left, int width, float val, float vah, bool rangeOn, bool vaOn, color rangeColor, int rangeAlpha, color vaColor, int vaAlpha) =>
    if rangeOn
        if vaOn
            if val > priceLow
                profileBoxes.push(box.new(left, val, left + width, priceLow, border_color = na, border_width = 0, bgcolor = color.new(rangeColor, rangeAlpha)))
            if vah < priceHigh
                profileBoxes.push(box.new(left, priceHigh, left + width, vah, border_color = na, border_width = 0, bgcolor = color.new(rangeColor, rangeAlpha)))
        else
            profileBoxes.push(box.new(left, priceHigh, left + width, priceLow, border_color = na, border_width = 0, bgcolor = color.new(rangeColor, rangeAlpha)))
    if vaOn
        profileBoxes.push(box.new(left, vah, left + width, val, border_color = na, border_width = 0, bgcolor = color.new(vaColor, vaAlpha)))
    true
 
f_shapeLine(array<float> curve, int left, int width, float bottom, float height, color lineColor) =>
    float maximum = curve.max()
    if maximum > 0
        array<chart.point> points = array.new<chart.point>()
        points.push(chart.point.from_index(left, bottom))
        for j = 0 to curve.size() - 1
            int x = left + int(math.round(width * curve.get(j) / maximum))
            float y = bottom + (j + 0.5) / curve.size() * height
            points.push(chart.point.from_index(x, y))
        points.push(chart.point.from_index(left, bottom + height))
        shapeLines.push(polyline.new(points, curved = false, closed = false, xloc = xloc.bar_index, line_color = lineColor, line_width = shapeLineWidth))
    true
 
f_tableRow(table t, int r, string title, string value) =>
    color bg = r == 0 ? #21304A : #111C2E
    table.cell(t, 0, r, title, text_color = #D5DFEF, bgcolor = r == 0 ? bg : #18243A, text_size = dashboardSize)
    table.cell(t, 1, r, value, text_color = color.white, bgcolor = bg, text_size = dashboardSize)
if barstate.islast
    while array.size(profileBoxes) > 0
        box.delete(array.pop(profileBoxes))
    while array.size(guideLines) > 0
        line.delete(array.pop(guideLines))
    while array.size(nodeLabels) > 0
        label.delete(array.pop(nodeLabels))
    while shapeLines.size() > 0
        polyline.delete(shapeLines.pop())
    array<float> totals = array.new_float(binCount, 0.0)
    float totalBuy = 0.0
    float totalSell = 0.0
    float maxBinVol = 0.0
    for i = 0 to binCount - 1
        float b = array.get(buyBins, i)
        float s = array.get(sellBins, i)
        float v = b + s
        array.set(totals, i, v)
        totalBuy += b
        totalSell += s
        maxBinVol := math.max(maxBinVol, v)
    float totalVol = totalBuy + totalSell
    float totalDelta = totalBuy - totalSell
    float pocPrice = na
    float vahPrice = na
    float valPrice = na
    int activeHVN = 0
    int activeLVN = 0
    string shapeCode = shapeEnabled ? "Waiting" : "Off"
    int shapePeaks = 0
    if totalVol > 0
        [pocIndex, vaLeft, vaRight] = f_valueArea(totals, vaPercent / 100.0)
        pocPrice := priceLow + (pocIndex + 0.5) * binSize
        valPrice := priceLow + vaLeft * binSize
        vahPrice := priceLow + (vaRight + 1) * binSize
        int x0 = math.max(0, bar_index + offsetBars)
        int firstColumnEnd = x0 + maxWidth + 2
        int secondLeft = firstColumnEnd + secondColumnOffset
        // Reserve room for level endpoints and labels within the 500 future-bar limit.
        int secondWidth = math.min(secondColumnWidth, math.max(1, bar_index + 497 - secondLeft))
        int xEnd = showSecondColumn ? secondLeft + secondWidth + 2 : firstColumnEnd
        int objectsPerRow = (viewMode == "Buy/Sell" ? 2 : 1) + (showSecondColumn ? (secondColumnMode == "Buy/Sell" ? 2 : 1) : 0)
        int drawingReserve = (showZones ? activeNodes.size() : 0) + (showSecondColumn ? 6 : 3)
        int displayRows = math.min(binCount, math.max(1, int(math.floor((500.0 - drawingReserve) / objectsPerRow))))
        int xLineLeft = math.max(0, bar_index - nodeLineBars)
        f_columnBackground(x0, maxWidth, valPrice, vahPrice, showRangeBackground, showValueAreaBG, rangeBackgroundColor, rangeBackgroundAlpha, valueAreaColor, valueAreaAlpha)
        array<int> visibleRowEnds = f_drawColumn(x0, maxWidth, viewMode, displayRows, vaLeft, vaRight, buyColor, sellColor, insideVAAlpha, outsideVAAlpha)
        if showSecondColumn
            f_columnBackground(secondLeft, secondWidth, valPrice, vahPrice, secondShowRangeBackground, secondShowValueArea, secondBackgroundColor, secondBackgroundAlpha, secondVAColor, secondVAAlpha)
            visibleRowEnds := f_drawColumn(secondLeft, secondWidth, secondColumnMode, displayRows, vaLeft, vaRight, secondBuyColor, secondSellColor, secondInsideVAAlpha, secondOutsideVAAlpha)
        if shapeEnabled and footprintBars >= shapeMinimumBars
            // Exclude never-traded tails from shape geometry while retaining prices.
            int occupiedLow = 0
            int occupiedHigh = binCount - 1
            while occupiedLow < occupiedHigh and totals.get(occupiedLow) <= 0
                occupiedLow += 1
            while occupiedHigh > occupiedLow and totals.get(occupiedHigh) <= 0
                occupiedHigh -= 1
            array<float> occupied = totals.slice(occupiedLow, occupiedHigh + 1)
            array<float> curve = f_shapeCurve(occupied)
            [code, peaks, peakPosition, asymmetry] = f_classifyShape(curve)
            shapeCode := code
            shapePeaks := peaks
            if curve.size() >= 12
                float shapeBottom = priceLow + occupiedLow * binSize
                float shapeHeight = (occupiedHigh - occupiedLow + 1) * binSize
                if showShapeFirst
                    f_shapeLine(curve, x0, maxWidth, shapeBottom, shapeHeight, firstShapeColor)
                if showSecondColumn and showShapeSecond
                    f_shapeLine(curve, secondLeft, secondWidth, shapeBottom, shapeHeight, secondShapeColor)
        // Use the actual rendered row edge, including compressed display rows
        // and whichever column is rightmost. Empty rows end at the profile baseline.
        int pocEnd = visibleRowEnds.get(pocIndex)
        int vahEnd = visibleRowEnds.get(vaRight)
        int valEnd = visibleRowEnds.get(vaLeft)
        int upperRangeEnd = visibleRowEnds.get(binCount - 1)
        int lowerRangeEnd = visibleRowEnds.get(0)
        if showPOC
            array.push(guideLines, line.new(math.min(xLineLeft, pocEnd), pocPrice, pocEnd, pocPrice, color = pocColor, width = 2))
        if showVA
            array.push(guideLines, line.new(math.min(xLineLeft, vahEnd), vahPrice, vahEnd, vahPrice, color = color.new(vaColor, 15), style = line.style_dashed))
            array.push(guideLines, line.new(math.min(xLineLeft, valEnd), valPrice, valEnd, valPrice, color = color.new(vaColor, 15), style = line.style_dashed))
        array.push(guideLines, line.new(math.min(xLineLeft, upperRangeEnd), priceHigh, upperRangeEnd, priceHigh, color = color.new(rangeGuideColor, 65), style = line.style_dotted))
        array.push(guideLines, line.new(math.min(xLineLeft, lowerRangeEnd), priceLow, lowerRangeEnd, priceLow, color = color.new(rangeGuideColor, 65), style = line.style_dotted))
        // Aurora: separate price zone from its smoothed intra-zone marker row.
        if showZones and array.size(activeNodes) > 0
            array<float> sm = f_smooth(totals, smoothRadius)
            for z in activeNodes
                bool isLVN = z.kind == -1
                color zoneColor = isLVN ? lvnColor : hvnColor
                // Visually project the current zone into the chart independently of its birth bar.
                int zoneX = xLineLeft
                // Stop zone shading before the profile. Only node marker lines cross it.
                int zoneRight = x0
                if zoneRight > zoneX
                    array.push(profileBoxes, box.new(zoneX, z.top, zoneRight, z.bottom, border_width = 0, bgcolor = color.new(zoneColor, zoneAlpha)))
                if isLVN
                    activeLVN += 1
                else
                    activeHVN += 1
                float lowestV = na
                float highestV = na
                float lowestP = na
                float highestP = na
                for i = 0 to binCount - 1
                    float rowBottom = priceLow + i * binSize
                    float rowTop = rowBottom + binSize
                    if rowTop > z.bottom and rowBottom < z.top
                        float smV = array.get(sm, i)
                        if na(lowestV) or smV < lowestV
                            lowestV := smV
                            lowestP := rowBottom + 0.5 * binSize
                        if na(highestV) or smV > highestV
                            highestV := smV
                            highestP := rowBottom + 0.5 * binSize
                bool drawLow = isLVN ? showLVNLowest : showHVNLowest
                bool drawHigh = isLVN ? showLVNHighest : showHVNHighest
                if drawLow and not na(lowestP)
                    int lowRow = math.max(0, math.min(binCount - 1, int(math.floor((lowestP - priceLow) / binSize))))
                    int lowEnd = visibleRowEnds.get(lowRow)
                    array.push(guideLines, line.new(math.min(zoneX, lowEnd), lowestP, lowEnd, lowestP, color = isLVN ? lvnLowColor : hvnLowColor, style = isLVN ? lvnLineStyle : hvnLineStyle, width = reactionWidth))
                if drawHigh and not na(highestP)
                    int highRow = math.max(0, math.min(binCount - 1, int(math.floor((highestP - priceLow) / binSize))))
                    int highEnd = visibleRowEnds.get(highRow)
                    array.push(guideLines, line.new(math.min(zoneX, highEnd), highestP, highEnd, highestP, color = isLVN ? lvnHighColor : hvnHighColor, style = isLVN ? lvnLineStyle : hvnLineStyle, width = reactionWidth))
                if showZoneLabels
                    float marker = isLVN ? lowestP : highestP
                    string zoneName = isLVN ? "LVN" : "HVN"
                    array.push(nodeLabels, label.new(xEnd + 1, marker, zoneName + " " + str.tostring(marker, format.mintick), style = label.style_label_left, color = color.new(chart.bg_color, 100), textcolor = zoneColor, size = size.tiny))
    if showStats
        f_tableRow(stats, 0, "PRICE RANGE", str.tostring(priceLow, format.mintick) + " - " + str.tostring(priceHigh, format.mintick))
        f_tableRow(stats, 1, "Window", historyMode == "All loaded history" ? "All loaded history | days: " + str.tostring(loadedDays) : "Current + " + str.tostring(lookbackDays) + " previous | loaded: " + str.tostring(array.size(profileDays) - 1))
        f_tableRow(stats, 2, "Rows / Footprint", str.tostring(binCount) + " / " + str.tostring(ticksPerRow) + " ticks")
        f_tableRow(stats, 3, "Visits (bar clusters)", str.tostring(touches))
        f_tableRow(stats, 4, "Volume in range", str.tostring(totalVol, format.volume))
        f_tableRow(stats, 5, "Buy / Sell", str.tostring(totalBuy, format.volume) + " / " + str.tostring(totalSell, format.volume))
        f_tableRow(stats, 6, "Delta", str.tostring(totalDelta, format.volume))
        f_tableRow(stats, 7, "POC", na(pocPrice) ? "No data" : str.tostring(pocPrice, format.mintick))
        f_tableRow(stats, 8, "VAL / VAH", na(valPrice) ? "No data" : str.tostring(valPrice, format.mintick) + " / " + str.tostring(vahPrice, format.mintick))
        f_tableRow(stats, 9, "Footprint bars in range", str.tostring(footprintBars))
        f_tableRow(stats, 10, "Confirmed HVN / LVN", str.tostring(activeHVN) + " / " + str.tostring(activeLVN))
        f_tableRow(stats, 11, "Node method", "Aurora nodes + hysteresis")
        f_tableRow(stats, 12, "Profile shape", shapeCode)
        f_tableRow(stats, 13, "Shape peaks", str.tostring(shapePeaks))
    else
        table.clear(stats, 0, 0, 1, 13)

← 返回列表