Volume Strata Profile

ADXAE · study · 3222 行 · 点赞 195 · TradingView 原页

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

Pine Script

// This Pine Script(R) code is subject to the terms of the Mozilla Public License 2.0
// at https://mozilla.org/MPL/2.0/
// (c) ADXAE
 
//@version=6
indicator(
     "Volume Strata Profile",
     "VSP",
     overlay = true,
     max_boxes_count = 500,
     max_lines_count = 120,
     max_labels_count = 80,
     max_bars_back = 3000,
     dynamic_requests = true
)
 
// ============================================================================
// VOLUME STRATA PROFILE
// ============================================================================
//
// VSP combines estimated Volume-at-Price with chronological time strata.
//
// Oldest  -> Indigo
// Middle  -> Teal
// Newest  -> Amber
//
// The adaptive intrabar engine automatically selects the finest practical
// lower timeframe that fits within the selected intrabar-data budget.
//
// IMPORTANT:
// Intrabar processing greatly improves price-volume resolution, but this
// remains OHLCV-derived Volume-at-Price estimation rather than tick-by-tick
// transaction Volume-at-Price or bid/ask order flow.
//
// No future data is used.
// Realtime values can evolve while the active bar is forming.
// ============================================================================
 
 
// ============================================================================
// CORE SERIES
// ============================================================================
 
float atr14 = ta.atr(14)
 
 
// ============================================================================
// INPUTS
// ============================================================================
 
// ---------------------------------------------------------------------------
// PROFILE RANGE
// ---------------------------------------------------------------------------
 
grpR = "PROFILE RANGE"
 
lookback = input.int(
     300,
     "Lookback bars",
     minval = 20,
     maxval = 3000,
     group = grpR,
     tooltip =
         "Number of chart bars used to construct the complete profile.\n\n" +
         "Higher values provide broader historical context but make the profile slower to react."
)
 
rowsN = input.int(
     45,
     "Price rows",
     minval = 10,
     maxval = 60,
     group = grpR,
     tooltip =
         "Number of horizontal price rows used by the profile.\n\n" +
         "More rows increase price resolution but can create a more fragmented profile."
)
 
strataN = input.int(
     5,
     "Time strata (layers)",
     minval = 2,
     maxval = 8,
     group = grpR,
     tooltip =
         "Divides the lookback period into chronological layers.\n\n" +
         "Oldest activity is indigo, intermediate activity transitions through teal, and newest activity is amber."
)
 
vaPct = input.float(
     70,
     "Value area %",
     minval = 10,
     maxval = 95,
     group = grpR,
     tooltip =
         "Percentage of total estimated profile volume included inside the Value Area.\n\n" +
         "70% is the commonly used Volume Profile convention."
)
 
 
// ---------------------------------------------------------------------------
// INTRABAR VOLUME ENGINE
// ---------------------------------------------------------------------------
 
grpI = "INTRABAR VOLUME ENGINE"
 
useIntrabar = input.bool(
     true,
     "Use intrabar volume",
     group = grpI,
     tooltip =
         "Uses lower-timeframe OHLCV data to improve Volume-at-Price resolution.\n\n" +
         "Recommended: ON."
)
 
ltfMode = input.string(
     "Auto",
     "Intrabar timeframe",
     options = [
         "Auto",
         "1",
         "3",
         "5",
         "15",
         "30",
         "60",
         "240",
         "1D"
     ],
     group = grpI,
     active = useIntrabar,
     tooltip =
         "Auto dynamically selects the finest lower timeframe that fits inside the data budget.\n\n" +
         "Manual values override the automatic selection.\n\n" +
         "Smaller timeframes provide greater price-volume resolution but require more intrabar history and processing."
)
 
autoPrecision = input.string(
     "High",
     "Auto precision",
     options = [
         "High",
         "Balanced"
     ],
     group = grpI,
     active = useIntrabar and ltfMode == "Auto",
     tooltip =
         "High uses up to approximately 100,000 requested intrabars and prioritizes maximum resolution.\n\n" +
         "Balanced uses approximately 50,000 as the selection budget for lower processing load."
)
 
 
// ---------------------------------------------------------------------------
// DISPLAY
// ---------------------------------------------------------------------------
 
grpD = "DISPLAY"
 
widthB = input.int(
     70,
     "Profile width (bars)",
     minval = 10,
     maxval = 200,
     group = grpD,
     tooltip =
         "Controls only the visual width of the profile.\n\n" +
         "It does not change calculations."
)
 
gapB = input.int(
     8,
     "Gap from last bar",
     minval = 0,
     maxval = 100,
     group = grpD,
     tooltip =
         "Horizontal space between the latest price bar and the beginning of the profile."
)
 
transpIn = input.int(
     10,
     "Transparency inside VA",
     minval = 0,
     maxval = 90,
     group = grpD,
     tooltip =
         "Transparency inside the Value Area.\n\n" +
         "0 = opaque.\n90 = highly transparent."
)
 
transpOut = input.int(
     55,
     "Transparency outside VA",
     minval = 0,
     maxval = 95,
     group = grpD,
     tooltip =
         "Transparency of profile rows outside the Value Area."
)
 
showVA = input.bool(
     true,
     "POC + value area lines",
     group = grpD,
     tooltip =
         "Displays Composite POC, VAH and VAL.\n\n" +
         "POC = highest-volume row.\n" +
         "VAH = Value Area High.\n" +
         "VAL = Value Area Low."
)
 
showMig = input.bool(
     true,
     "Value migration spine",
     group = grpD,
     tooltip =
         "Displays the chronological POC migration path.\n\n" +
         "Each colored point represents the POC of one time stratum."
)
 
showRib = input.bool(
     true,
     "Strata time ribbon",
     group = grpD,
     tooltip =
         "Displays the chronological color ribbon beneath the analyzed range."
)
 
showSt = input.bool(
     true,
     "Mark stale HVNs",
     group = grpD,
     tooltip =
         "Marks historically important High Volume Nodes with weak recent participation."
)
 
 
// ---------------------------------------------------------------------------
// STALE NODE RULE
// ---------------------------------------------------------------------------
 
grpS = "STALE NODE RULE"
 
adaptiveHVN = input.bool(
     true,
     "Adaptive HVN detection",
     group = grpS,
     active = showSt,
     tooltip =
         "Combines a minimum percentage-of-POC requirement with an adaptive statistical threshold."
)
 
hvnPct = input.float(
     35,
     "Minimum HVN = % of POC row",
     minval = 10,
     maxval = 100,
     group = grpS,
     active = showSt,
     tooltip =
         "Minimum row volume required to qualify as an HVN candidate, relative to the Composite POC row."
)
 
hvnSigma = input.float(
     0.50,
     "Adaptive HVN strength",
     minval = 0.0,
     maxval = 2.0,
     step = 0.10,
     group = grpS,
     active = showSt and adaptiveHVN,
     tooltip =
         "Adaptive threshold = average row volume + this multiplier × row-volume standard deviation.\n\n" +
         "Higher values identify fewer but stronger nodes."
)
 
recentPct = input.float(
     30,
     "Recent window % of lookback",
     minval = 10,
     maxval = 50,
     step = 5,
     group = grpS,
     active = showSt,
     tooltip =
         "Defines the recent portion of the analysis window.\n\n" +
         "Also used internally for Recent Acceptance POC."
)
 
stalePct = input.float(
     10,
     "Stale = recent volume < % of row",
     minval = 0,
     maxval = 50,
     group = grpS,
     active = showSt,
     tooltip =
         "An HVN becomes stale when recent volume contributes less than this percentage of its historical row volume."
)
 
clusterGap = input.int(
     1,
     "Cluster gap tolerance (rows)",
     minval = 0,
     maxval = 3,
     group = grpS,
     active = showSt,
     tooltip =
         "Groups nearby stale rows into one logical Stale HVN cluster.\n\n" +
         "1 permits one non-stale row between qualifying candidates."
)
 
maxStale = input.int(
     3,
     "Maximum stale HVNs",
     minval = 1,
     maxval = 5,
     group = grpS,
     active = showSt,
     tooltip =
         "Maximum number of Stale HVN clusters displayed.\n\n" +
         "The strongest candidates are selected."
)
 
 
// ---------------------------------------------------------------------------
// STALE DISTANCE FILTER
// ---------------------------------------------------------------------------
 
grpSD = "STALE DISTANCE FILTER"
 
filterStaleDistance = input.bool(
     false,
     "Limit stale HVN distance",
     group = grpSD,
     active = showSt,
     tooltip =
         "Optionally suppresses Stale HVNs that are very far from current price.\n\n" +
         "Distance is normalized using ATR."
)
 
staleMaxATR = input.float(
     10.0,
     "Maximum distance (ATR)",
     minval = 1.0,
     maxval = 50.0,
     step = 0.5,
     group = grpSD,
     active = showSt and filterStaleDistance,
     tooltip =
         "Maximum allowed distance between current price and a Stale HVN, measured in ATR(14)."
)
 
 
// ---------------------------------------------------------------------------
// COLORS
// ---------------------------------------------------------------------------
 
grpC = "COLORS"
 
cOld = input.color(
     #3f3fb5,
     "Oldest stratum",
     group = grpC,
     tooltip = "Color representing the oldest chronological volume."
)
 
cMid = input.color(
     #1fa2a8,
     "Middle stratum",
     group = grpC,
     tooltip = "Center color of the chronological gradient."
)
 
cNew = input.color(
     #ffb300,
     "Newest stratum",
     group = grpC,
     tooltip = "Color representing the newest chronological volume."
)
 
cPoc = input.color(
     #000000,
     "POC line",
     group = grpC,
     tooltip = "Color of the Composite Point of Control line and POC-row outline."
)
 
cVa = input.color(
     #9e9e9e,
     "Value area lines",
     group = grpC,
     tooltip = "Color of VAH and VAL."
)
 
 
// ============================================================================
// HELPERS
// ============================================================================
 
f_layerCol(int k, int S) =>
    float t = S > 1 ? k / (S - 1.0) : 1.0
 
    t < 0.5 ?
         color.from_gradient(
             t,
             0.0,
             0.5,
             cOld,
             cMid
         ) :
         color.from_gradient(
             t,
             0.5,
             1.0,
             cMid,
             cNew
         )
 
 
f_fmt(float p) =>
    str.tostring(
         p,
         format.mintick
    )
 
 
// ---------------------------------------------------------------------------
// ROBUST ACTIVITY SUPPORT
// ---------------------------------------------------------------------------
//
// Activity is directional: more recent activity can legitimately provide
// additional support.
//
// However, the effect is bounded so extreme volume cannot create unlimited
// confidence.
//
// Approximate interpretation:
// < 0.5x  = weak
// ~1.0x   = healthy
// ~2.0x   = strong
// 5x+     = capped
// ---------------------------------------------------------------------------
 
f_activitySupport(float ratio) =>
    float r =
         math.max(
             0.0,
             ratio
         )
 
    float capped =
         math.min(
             r,
             5.0
         )
 
    r <= 0 ?
         0.0 :
         math.min(
             1.0,
             0.35 +
             0.65 *
             (
                 1.0 -
                 math.exp(
                     -1.20 *
                     capped
                 )
             )
         )
 
 
// ---------------------------------------------------------------------------
// PARTICIPATION BALANCE / COMPARABILITY
// ---------------------------------------------------------------------------
//
// Unlike Activity Support, participation comparison is NOT "higher is better".
//
// The most comparable condition occurs near 1.0x, where newest and previous
// strata contain similar overall volume.
//
// A very large difference between the strata can indicate a different
// liquidity/session/volume regime. Such a comparison is less reliable for
// validating value migration.
//
// The calculation is symmetrical:
//
//      2x and 0.5x
//
// receive the same penalty.
//
// Approximate behavior:
//
// 1.00x        -> 100%
// 1.50x/0.67x  -> ~70%
// 2.00x/0.50x  -> ~50%
// 4.00x/0.25x  -> ~28%
// extreme      -> floor near 20%
//
// This prevents a ratio such as 47x from being interpreted as perfect
// confirmation.
// ---------------------------------------------------------------------------
 
f_participationBalance(float ratio) =>
    if ratio <= 0
        0.0
    else
        float log2Distance =
             math.abs(
                 math.log(ratio) /
                 math.log(2.0)
             )
 
        float rawBalance =
             1.0 /
             (
                 1.0 +
                 math.pow(
                     log2Distance,
                     1.35
                 )
             )
 
        math.max(
             0.20,
             math.min(
                 1.0,
                 rawBalance
             )
         )
 
 
// ============================================================================
// SIMPLE-QUALIFIED INTRABAR HELPERS
// ============================================================================
 
f_requestEstimate(
     simple int chartSec,
     simple int lowerSec,
     simple int bars,
     simple float safetyMargin
) =>
    int result =
         lowerSec > 0 ?
         int(
             math.ceil(
                 float(bars) *
                 math.max(
                     1.0,
                     float(chartSec) /
                     float(lowerSec)
                 ) *
                 safetyMargin
             )
         ) :
         1000000000
 
    result
 
 
f_autoLtf(
     simple int bars,
     simple string precision
) =>
 
    int chartSec =
         timeframe.in_seconds()
 
    int budget =
         precision == "High" ?
         100000 :
         50000
 
    float margin =
         1.10
 
    string chosen =
         "1D"
 
 
    if chartSec > 60 and
         f_requestEstimate(
             chartSec,
             60,
             bars,
             margin
         ) <= budget
 
        chosen := "1"
 
 
    else if chartSec > 180 and
         f_requestEstimate(
             chartSec,
             180,
             bars,
             margin
         ) <= budget
 
        chosen := "3"
 
 
    else if chartSec > 300 and
         f_requestEstimate(
             chartSec,
             300,
             bars,
             margin
         ) <= budget
 
        chosen := "5"
 
 
    else if chartSec > 900 and
         f_requestEstimate(
             chartSec,
             900,
             bars,
             margin
         ) <= budget
 
        chosen := "15"
 
 
    else if chartSec > 1800 and
         f_requestEstimate(
             chartSec,
             1800,
             bars,
             margin
         ) <= budget
 
        chosen := "30"
 
 
    else if chartSec > 3600 and
         f_requestEstimate(
             chartSec,
             3600,
             bars,
             margin
         ) <= budget
 
        chosen := "60"
 
 
    else if chartSec > 14400 and
         f_requestEstimate(
             chartSec,
             14400,
             bars,
             margin
         ) <= budget
 
        chosen := "240"
 
 
    else if chartSec > 86400
 
        chosen := "1D"
 
 
    chosen
 
 
// ============================================================================
// ADAPTIVE INTRABAR RESOLUTION
// ============================================================================
 
simple string autoTF =
     f_autoLtf(
         lookback,
         autoPrecision
     )
 
 
simple string lowerTF =
     ltfMode == "Auto" ?
     autoTF :
     ltfMode
 
 
simple int chartSeconds =
     timeframe.in_seconds()
 
 
simple int lowerSeconds =
     timeframe.in_seconds(
         lowerTF
     )
 
 
simple bool validIntrabarTF =
     useIntrabar and
     lowerSeconds > 0 and
     lowerSeconds < chartSeconds
 
 
simple float theoreticalIntrabarsPerChartBar =
     validIntrabarTF ?
     math.max(
         1.0,
         float(chartSeconds) /
         float(lowerSeconds)
     ) :
     1.0
 
 
simple float intrabarHistorySafetyMargin =
     1.10
 
 
simple int requestedIntrabars =
     int(
         math.min(
             100000.0,
             math.max(
                 float(lookback + 10),
                 math.ceil(
                     float(lookback) *
                     theoreticalIntrabarsPerChartBar *
                     intrabarHistorySafetyMargin
                 )
             )
         )
     )
 
 
// ============================================================================
// LOWER-TIMEFRAME REQUEST
// ============================================================================
 
[ltfHigh, ltfLow, ltfVolume] =
     request.security_lower_tf(
         syminfo.tickerid,
         lowerTF,
         [
             high,
             low,
             volume
         ],
         ignore_invalid_timeframe = true,
         calc_bars_count = requestedIntrabars
     )
 
 
// ============================================================================
// DRAWING REGISTRIES
// ============================================================================
 
var array<box> boxes =
     array.new<box>()
 
var array<line> lines =
     array.new<line>()
 
var array<label> labels =
     array.new<label>()
 
 
// ============================================================================
// MAIN ENGINE
// ============================================================================
 
if barstate.islast
 
    for b in boxes
        b.delete()
 
    for l in lines
        l.delete()
 
    for lb in labels
        lb.delete()
 
    boxes.clear()
    lines.clear()
    labels.clear()
 
 
    int n =
         math.min(
             lookback,
             bar_index + 1
         )
 
    int S =
         strataN
 
 
    if n >= S * 2
 
        // -------------------------------------------------------------------
        // PROFILE RANGE
        // -------------------------------------------------------------------
 
        float top =
             high
 
        float bot =
             low
 
 
        for i = 0 to n - 1
 
            top :=
                 math.max(
                     top,
                     high[i]
                 )
 
            bot :=
                 math.min(
                     bot,
                     low[i]
                 )
 
 
        float priceRange =
             top -
             bot
 
        float step =
             priceRange /
             rowsN
 
 
        if step > 0
 
            // ===============================================================
            // DATA STRUCTURES
            // ===============================================================
 
            matrix<float> m =
                 matrix.new<float>(
                     rowsN,
                     S,
                     0.0
                 )
 
            array<float> tot =
                 array.new<float>(
                     rowsN,
                     0.0
                 )
 
            array<float> lay =
                 array.new<float>(
                     S,
                     0.0
                 )
 
            array<int> layBars =
                 array.new<int>(
                     S,
                     0
                 )
 
            array<int> jFirst =
                 array.new<int>(
                     S,
                     -1
                 )
 
            array<int> jLast =
                 array.new<int>(
                     S,
                     -1
                 )
 
            array<float> recentRowVol =
                 array.new<float>(
                     rowsN,
                     0.0
                 )
 
 
            int recentBars =
                 math.max(
                     1,
                     int(
                         math.ceil(
                             n *
                             recentPct /
                             100.0
                         )
                     )
                 )
 
 
            // ===============================================================
            // INTRABAR DIAGNOSTICS
            // ===============================================================
 
            int parentBarsWithIntrabars =
                 0
 
            int parentBarsFallback =
                 0
 
            int totalIntrabarsUsed =
                 0
 
            int observedMaxIntrabars =
                 0
 
 
            // ===============================================================
            // DISTRIBUTE VOLUME
            // ===============================================================
 
            for i = 0 to n - 1
 
                int j =
                     n -
                     1 -
                     i
 
 
                int k =
                     math.min(
                         S -
                         1,
                         int(
                             j *
                             S /
                             n
                         )
                     )
 
 
                layBars.set(
                     k,
                     layBars.get(k) +
                     1
                )
 
 
                if jFirst.get(k) < 0
                    jFirst.set(
                         k,
                         j
                    )
 
 
                jFirst.set(
                     k,
                     math.min(
                         jFirst.get(k),
                         j
                     )
                )
 
 
                jLast.set(
                     k,
                     math.max(
                         jLast.get(k),
                         j
                     )
                )
 
 
                bool isRecent =
                     i <
                     recentBars
 
 
                array<float> hiArr =
                     ltfHigh[i]
 
                array<float> loArr =
                     ltfLow[i]
 
                array<float> volArr =
                     ltfVolume[i]
 
 
                int intraCount =
                     math.min(
                         hiArr.size(),
                         math.min(
                             loArr.size(),
                             volArr.size()
                         )
                     )
 
 
                bool useIntrabarForBar =
                     validIntrabarTF and
                     intraCount >
                     0
 
 
                // ===========================================================
                // INTRABAR DISTRIBUTION
                // ===========================================================
 
                if useIntrabarForBar
 
                    parentBarsWithIntrabars +=
                         1
 
                    totalIntrabarsUsed +=
                         intraCount
 
                    observedMaxIntrabars :=
                         math.max(
                             observedMaxIntrabars,
                             intraCount
                         )
 
 
                    for q = 0 to intraCount - 1
 
                        float iHi =
                             hiArr.get(q)
 
                        float iLo =
                             loArr.get(q)
 
                        float iVol =
                             nz(
                                 volArr.get(q)
                             )
 
 
                        if iVol > 0 and
                             not na(iHi) and
                             not na(iLo)
 
                            int r0 =
                                 math.max(
                                     0,
                                     math.min(
                                         rowsN -
                                         1,
                                         int(
                                             (
                                                 iLo -
                                                 bot
                                             ) /
                                             step
                                         )
                                     )
                                 )
 
 
                            int r1 =
                                 math.max(
                                     0,
                                     math.min(
                                         rowsN -
                                         1,
                                         int(
                                             (
                                                 iHi -
                                                 bot
                                             ) /
                                             step
                                         )
                                     )
                                 )
 
 
                            if iHi <= iLo or
                                 r0 == r1
 
                                m.set(
                                     r0,
                                     k,
                                     m.get(
                                         r0,
                                         k
                                     ) +
                                     iVol
                                )
 
 
                                if isRecent
 
                                    recentRowVol.set(
                                         r0,
                                         recentRowVol.get(
                                             r0
                                         ) +
                                         iVol
                                    )
 
 
                            else
 
                                float intraRange =
                                     iHi -
                                     iLo
 
 
                                for r = r0 to r1
 
                                    float rowLo =
                                         bot +
                                         r *
                                         step
 
                                    float rowHi =
                                         rowLo +
                                         step
 
 
                                    float overlap =
                                         math.min(
                                             iHi,
                                             rowHi
                                         ) -
                                         math.max(
                                             iLo,
                                             rowLo
                                         )
 
 
                                    if overlap > 0
 
                                        float allocatedVolume =
                                             iVol *
                                             overlap /
                                             intraRange
 
 
                                        m.set(
                                             r,
                                             k,
                                             m.get(
                                                 r,
                                                 k
                                             ) +
                                             allocatedVolume
                                        )
 
 
                                        if isRecent
 
                                            recentRowVol.set(
                                                 r,
                                                 recentRowVol.get(
                                                     r
                                                 ) +
                                                 allocatedVolume
                                            )
 
 
                // ===========================================================
                // CHART-BAR FALLBACK
                // ===========================================================
 
                else
 
                    parentBarsFallback +=
                         1
 
 
                    float v =
                         nz(
                             volume[i]
                         )
 
                    float lo =
                         low[i]
 
                    float hi =
                         high[i]
 
 
                    if v > 0
 
                        int r0 =
                             math.max(
                                 0,
                                 math.min(
                                     rowsN -
                                     1,
                                     int(
                                         (
                                             lo -
                                             bot
                                         ) /
                                             step
                                     )
                                 )
                             )
 
 
                        int r1 =
                             math.max(
                                 0,
                                 math.min(
                                     rowsN -
                                     1,
                                     int(
                                         (
                                             hi -
                                             bot
                                         ) /
                                             step
                                     )
                                 )
                             )
 
 
                        if hi <= lo or
                             r0 == r1
 
                            m.set(
                                 r0,
                                 k,
                                 m.get(
                                     r0,
                                     k
                                 ) +
                                 v
                            )
 
 
                            if isRecent
 
                                recentRowVol.set(
                                     r0,
                                     recentRowVol.get(
                                         r0
                                     ) +
                                     v
                                )
 
 
                        else
 
                            float barRange =
                                 hi -
                                 lo
 
 
                            for r = r0 to r1
 
                                float rowLo =
                                     bot +
                                     r *
                                     step
 
                                float rowHi =
                                     rowLo +
                                     step
 
 
                                float overlap =
                                     math.min(
                                         hi,
                                         rowHi
                                     ) -
                                         math.max(
                                             lo,
                                             rowLo
                                         )
 
 
                                if overlap > 0
 
                                    float allocatedVolume =
                                         v *
                                         overlap /
                                         barRange
 
 
                                    m.set(
                                         r,
                                         k,
                                         m.get(
                                             r,
                                             k
                                         ) +
                                         allocatedVolume
                                    )
 
 
                                    if isRecent
 
                                        recentRowVol.set(
                                             r,
                                             recentRowVol.get(
                                                 r
                                             ) +
                                             allocatedVolume
                                        )
 
 
            // ===============================================================
            // ADAPTIVE INTRABAR QUALITY ENGINE
            // ===============================================================
 
            float intrabarCoverage =
                 n > 0 ?
                 parentBarsWithIntrabars /
                 float(n) :
                 0.0
 
 
            float intrabarCoveragePct =
                 intrabarCoverage *
                 100.0
 
 
            float averageIntrabarsPerCoveredBar =
                 parentBarsWithIntrabars > 0 ?
                 totalIntrabarsUsed /
                 float(
                     parentBarsWithIntrabars
                 ) :
                 0.0
 
 
            float observedDensityTarget =
                 observedMaxIntrabars > 0 ?
                 float(
                     observedMaxIntrabars
                 ) :
                 1.0
 
 
            float densityAdequacy =
                 observedDensityTarget > 0 ?
                 math.min(
                     1.0,
                     averageIntrabarsPerCoveredBar /
                     observedDensityTarget
                 ) :
                 0.0
 
 
            float densityAdequacyPct =
                 densityAdequacy *
                 100.0
 
 
            float intrabarQuality =
                 validIntrabarTF ?
                 math.sqrt(
                     math.max(
                         0.0,
                         intrabarCoverage
                     ) *
                     math.max(
                         0.0,
                         densityAdequacy
                     )
                 ) :
                 0.0
 
 
            float intrabarQualityPct =
                 intrabarQuality *
                 100.0
 
 
            string intrabarQualityClass =
                 intrabarQualityPct >= 90 ?
                 "EXCELLENT" :
                 intrabarQualityPct >= 75 ?
                 "GOOD" :
                 intrabarQualityPct >= 55 ?
                 "MODERATE" :
                 "LOW"
 
 
            string engineState =
                 validIntrabarTF and
                 parentBarsWithIntrabars > 0 ?
                 "INTRABAR " +
                 lowerTF :
                 "CHART BAR"
 
 
            // ===============================================================
            // TOTAL PROFILE
            // ===============================================================
 
            float sumAll =
                 0.0
 
            float maxTot =
                 0.0
 
            int poc =
                 0
 
 
            for r = 0 to rowsN - 1
 
                float rowTotal =
                     0.0
 
 
                for k = 0 to S - 1
 
                    float mv =
                         m.get(
                             r,
                             k
                         )
 
 
                    rowTotal +=
                         mv
 
 
                    lay.set(
                         k,
                         lay.get(k) +
                         mv
                    )
 
 
                tot.set(
                     r,
                     rowTotal
                )
 
 
                sumAll +=
                     rowTotal
 
 
                if rowTotal >
                     maxTot
 
                    maxTot :=
                         rowTotal
 
                    poc :=
                         r
 
 
            if sumAll > 0 and
                 maxTot > 0
 
                // ===========================================================
                // RECENT ACCEPTANCE POC
                // ===========================================================
 
                int recentPocRow =
                     0
 
                float recentPocVolume =
                     -1.0
 
 
                for r = 0 to rowsN - 1
 
                    float rv =
                         recentRowVol.get(
                             r
                         )
 
 
                    if rv >
                         recentPocVolume
 
                        recentPocVolume :=
                             rv
 
                        recentPocRow :=
                             r
 
 
                float recentPocP =
                     bot +
                     (
                         recentPocRow +
                         0.5
                     ) *
                     step
 
 
                // ===========================================================
                // ROW STATISTICS
                // ===========================================================
 
                float meanRowVolume =
                     sumAll /
                     rowsN
 
 
                float varianceSum =
                     0.0
 
 
                for r = 0 to rowsN - 1
 
                    float d =
                         tot.get(r) -
                         meanRowVolume
 
 
                    varianceSum +=
                         d *
                         d
 
 
                float rowStdDev =
                     math.sqrt(
                         varianceSum /
                         rowsN
                     )
 
 
                float fixedHVNThreshold =
                     maxTot *
                     hvnPct /
                     100.0
 
 
                float adaptiveThreshold =
                     meanRowVolume +
                     hvnSigma *
                     rowStdDev
 
 
                float hvnThreshold =
                     adaptiveHVN ?
                     math.max(
                         fixedHVNThreshold,
                         adaptiveThreshold
                     ) :
                     fixedHVNThreshold
 
 
                // ===========================================================
                // VALUE AREA
                // ===========================================================
 
                int up =
                     poc
 
                int dn =
                     poc
 
 
                float accumulated =
                     tot.get(
                         poc
                     )
 
 
                float target =
                     sumAll *
                     vaPct /
                     100.0
 
 
                while accumulated < target and
                     (
                         up < rowsN - 1 or
                         dn > 0
                     )
 
                    float aboveVolume =
                         up < rowsN - 1 ?
                         tot.get(
                             up +
                             1
                         ) :
                         -1.0
 
 
                    float belowVolume =
                         dn > 0 ?
                         tot.get(
                             dn -
                             1
                         ) :
                         -1.0
 
 
                    if aboveVolume >=
                         belowVolume
 
                        up +=
                             1
 
                        accumulated +=
                             aboveVolume
 
                    else
 
                        dn -=
                             1
 
                        accumulated +=
                             belowVolume
 
 
                float pocP =
                     bot +
                     (
                         poc +
                         0.5
                     ) *
                     step
 
 
                float vah =
                     bot +
                     (
                         up +
                         1
                     ) *
                     step
 
 
                float val =
                     bot +
                     dn *
                     step
 
 
                // ===========================================================
                // STRATUM POCs
                // ===========================================================
 
                array<int> lPoc =
                     array.new<int>(
                         S,
                         0
                     )
 
 
                for k = 0 to S - 1
 
                    float best =
                         -1.0
 
                    int bestRow =
                         0
 
 
                    for r = 0 to rowsN - 1
 
                        float mv =
                             m.get(
                                 r,
                                 k
                             )
 
 
                        if mv >
                             best
 
                            best :=
                                 mv
 
                            bestRow :=
                                 r
 
 
                    lPoc.set(
                         k,
                         bestRow
                    )
 
 
                // ===========================================================
                // DEVELOPING POC
                // ===========================================================
 
                array<int> devPoc =
                     array.new<int>(
                         S,
                         0
                     )
 
 
                for k = 0 to S - 1
 
                    float bestCum =
                         -1.0
 
                    int bestCumRow =
                         0
 
 
                    for r = 0 to rowsN - 1
 
                        float cumulative =
                             0.0
 
 
                        for kk = 0 to k
 
                            cumulative +=
                                 m.get(
                                     r,
                                     kk
                                 )
 
 
                        if cumulative >
                             bestCum
 
                            bestCum :=
                                 cumulative
 
                            bestCumRow :=
                                 r
 
 
                    devPoc.set(
                         k,
                         bestCumRow
                    )
 
 
                // ===========================================================
                // ACTIVITY
                // ===========================================================
 
                array<float> layerVolumePerBar =
                     array.new<float>(
                         S,
                         0.0
                     )
 
 
                float overallVolumePerBar =
                     sumAll /
                     n
 
 
                for k = 0 to S - 1
 
                    int barsInLayer =
                         math.max(
                             1,
                             layBars.get(
                                 k
                             )
                         )
 
 
                    float volumePerBar =
                         lay.get(
                             k
                         ) /
                         barsInLayer
 
 
                    layerVolumePerBar.set(
                         k,
                         volumePerBar
                    )
 
 
                float newestVolumePerBar =
                     layerVolumePerBar.get(
                         S -
                         1
                     )
 
 
                float newestActivityRatio =
                     overallVolumePerBar > 0 ?
                     newestVolumePerBar /
                     overallVolumePerBar :
                     0.0
 
 
                float activityConfidence =
                     f_activitySupport(
                         newestActivityRatio
                     )
 
 
                // ===========================================================
                // MIGRATION
                // ===========================================================
 
                float pOld =
                     bot +
                     (
                         lPoc.get(
                             0
                         ) +
                         0.5
                     ) *
                     step
 
 
                float pNew =
                     bot +
                     (
                         lPoc.get(
                             S -
                             1
                         ) +
                         0.5
                     ) *
                     step
 
 
                float migrationPct =
                     pOld != 0 ?
                     (
                         pNew -
                         pOld
                     ) /
                     pOld *
                     100.0 :
                     0.0
 
 
                float normalizedMigration =
                     priceRange > 0 ?
                     (
                         pNew -
                         pOld
                     ) /
                     priceRange :
                     0.0
 
 
                float migrationPath =
                     0.0
 
 
                if S > 1
 
                    for k = 1 to S - 1
 
                        float p1 =
                             bot +
                             (
                                 lPoc.get(
                                     k -
                                     1
                                 ) +
                                 0.5
                             ) *
                             step
 
 
                        float p2 =
                             bot +
                             (
                                 lPoc.get(
                                     k
                                 ) +
                                 0.5
                             ) *
                             step
 
 
                        migrationPath +=
                             math.abs(
                                 p2 -
                                 p1
                             )
 
 
                float migrationEfficiency =
                     migrationPath > 0 ?
                     math.abs(
                         pNew -
                         pOld
                     ) /
                     migrationPath :
                     0.0
 
 
                // ===========================================================
                // PARTICIPATION BALANCE / COMPARABILITY
                // ===========================================================
 
                float previousLayerVolume =
                     S > 1 ?
                     lay.get(
                         S -
                         2
                     ) :
                     lay.get(
                         S -
                         1
                     )
 
 
                float newestLayerVolume =
                     lay.get(
                         S -
                         1
                     )
 
 
                float latestParticipationRatio =
                     previousLayerVolume > 0 ?
                     newestLayerVolume /
                     previousLayerVolume :
                     1.0
 
 
                float participationBalance =
                     f_participationBalance(
                         latestParticipationRatio
                     )
 
 
                string participationBalanceClass =
                     participationBalance >= 0.80 ?
                     "HIGH" :
                     participationBalance >= 0.50 ?
                     "MODERATE" :
                     "LOW"
 
 
                // ===========================================================
                // RECENT ACCEPTANCE ALIGNMENT
                // ===========================================================
 
                float recentDistanceRows =
                     step > 0 ?
                     math.abs(
                         pNew -
                         recentPocP
                     ) /
                     step :
                     0.0
 
 
                float recentAlignmentConfidence =
                     math.exp(
                         -recentDistanceRows /
                         3.0
                     )
 
 
                float recentAlignmentPct =
                     recentAlignmentConfidence *
                     100.0
 
 
                // ===========================================================
                // STRUCTURAL CONFIDENCE
                // ===========================================================
                //
                // Participation now measures comparability between the newest
                // and previous strata rather than rewarding raw volume excess.
                //
                // This is especially important on intraday charts where one
                // stratum can occur during high-liquidity market hours while
                // another can contain thin pre/post-market activity.
                // ===========================================================
 
                float structuralProduct =
                     math.max(
                         0.0,
                         migrationEfficiency
                     ) *
                     math.max(
                         0.0,
                         activityConfidence
                     ) *
                     math.max(
                         0.0,
                         participationBalance
                     ) *
                     math.max(
                         0.0,
                         recentAlignmentConfidence
                     )
 
 
                float structuralConfidence =
                     math.pow(
                         structuralProduct,
                         0.25
                     )
 
 
                float structuralConfidencePct =
                     structuralConfidence *
                     100.0
 
 
                // ===========================================================
                // DATA-QUALITY GATE
                // ===========================================================
 
                float qualityMultiplier =
                     0.50 +
                     0.50 *
                     intrabarQuality
 
 
                float qualityAdjustedConfidence =
                     structuralConfidence *
                     qualityMultiplier
 
 
                float qualityCeiling =
                     intrabarQuality <
                     0.50 ?
                     0.49 :
                     intrabarQuality <
                     0.70 ?
                     0.74 :
                     1.00
 
 
                float migrationConfidence =
                     math.min(
                         qualityAdjustedConfidence,
                         qualityCeiling
                     )
 
 
                float migrationConfidencePct =
                     migrationConfidence *
                     100.0
 
 
                string confidenceClass =
                     migrationConfidencePct >= 75 ?
                     "HIGH" :
                     migrationConfidencePct >= 50 ?
                     "MODERATE" :
                     "LOW"
 
 
                string qualityGateClass =
                     intrabarQuality <
                     0.50 ?
                     "LOW ceiling" :
                     intrabarQuality <
                     0.70 ?
                     "MODERATE ceiling" :
                     "FULL"
 
 
                // ===========================================================
                // VALUE STABILITY
                // ===========================================================
 
                float pocMean =
                     0.0
 
 
                for k = 0 to S - 1
 
                    pocMean +=
                         bot +
                         (
                             lPoc.get(
                                 k
                             ) +
                             0.5
                         ) *
                         step
 
 
                pocMean /=
                     S
 
 
                float pocVariance =
                     0.0
 
 
                for k = 0 to S - 1
 
                    float pk =
                         bot +
                         (
                             lPoc.get(
                                 k
                             ) +
                             0.5
                         ) *
                         step
 
 
                    float d =
                         pk -
                         pocMean
 
 
                    pocVariance +=
                         d *
                         d
 
 
                float pocStd =
                     math.sqrt(
                         pocVariance /
                         S
                     )
 
 
                float valueInstability =
                     priceRange > 0 ?
                     pocStd /
                     priceRange :
                     0.0
 
 
                string stabilityClass =
                     valueInstability < 0.08 ?
                     "HIGH" :
                     valueInstability < 0.18 ?
                     "MODERATE" :
                     "LOW"
 
 
                string migrationClass =
                     normalizedMigration > 0.25 ?
                     "STRONG UP" :
                     normalizedMigration > 0.08 ?
                     "UP" :
                     normalizedMigration < -0.25 ?
                     "STRONG DOWN" :
                     normalizedMigration < -0.08 ?
                     "DOWN" :
                     "BALANCED"
 
 
                // ===========================================================
                // DRAW PROFILE
                // ===========================================================
 
                int x0 =
                     bar_index +
                     gapB
 
 
                for r = 0 to rowsN - 1
 
                    float rLo =
                         bot +
                         r *
                         step
 
                    float rHi =
                         rLo +
                         step
 
 
                    bool inVA =
                         r >= dn and
                         r <= up
 
 
                    int transparency =
                         inVA ?
                         transpIn :
                         transpOut
 
 
                    float cumulativeWidth =
                         0.0
 
 
                    for k = 0 to S - 1
 
                        float layerWidth =
                             m.get(
                                 r,
                                 k
                             ) /
                             maxTot *
                             widthB
 
 
                        if layerWidth > 0
 
                            int xl =
                                 x0 +
                                 int(
                                     math.round(
                                         cumulativeWidth
                                     )
                                 )
 
 
                            int xr =
                                 x0 +
                                 int(
                                     math.round(
                                         cumulativeWidth +
                                         layerWidth
                                     )
                                 )
 
 
                            if xr > xl
 
                                boxes.push(
                                     box.new(
                                         xl,
                                         rHi,
                                         xr,
                                         rLo,
                                         border_width =
                                             0,
                                         bgcolor =
                                             color.new(
                                                 f_layerCol(
                                                     k,
                                                     S
                                                 ),
                                                 transparency
                                             )
                                     )
                                )
 
 
                        cumulativeWidth +=
                             layerWidth
 
 
                // ===========================================================
                // POC ROW
                // ===========================================================
 
                int pocW =
                     int(
                         math.round(
                             tot.get(
                                 poc
                             ) /
                             maxTot *
                             widthB
                         )
                     )
 
 
                boxes.push(
                     box.new(
                         x0,
                         bot +
                         (
                             poc +
                             1
                         ) *
                         step,
                         x0 +
                         math.max(
                             1,
                             pocW
                         ),
                         bot +
                         poc *
                         step,
                         border_color =
                             cPoc,
                         border_width =
                             1,
                         bgcolor =
                             color.new(
                                 color.white,
                                 100
                             )
                     )
                )
 
 
                int xStart =
                     bar_index -
                     (
                         n -
                         1
                     )
 
 
                int xEnd =
                     x0 +
                     widthB
 
 
                // ===========================================================
                // POC / VAH / VAL
                // ===========================================================
 
                if showVA
 
                    lines.push(
                         line.new(
                             xStart,
                             pocP,
                             xEnd,
                             pocP,
                             color =
                                 color.new(
                                     cPoc,
                                     30
                                 ),
                             width =
                                 1,
                             style =
                                 line.style_solid
                         )
                    )
 
 
                    lines.push(
                         line.new(
                             xStart,
                             vah,
                             xEnd,
                             vah,
                             color =
                                 color.new(
                                     cVa,
                                     40
                                 ),
                             width =
                                 1,
                             style =
                                 line.style_dotted
                         )
                    )
 
 
                    lines.push(
                         line.new(
                             xStart,
                             val,
                             xEnd,
                             val,
                             color =
                                 color.new(
                                     cVa,
                                     40
                                 ),
                             width =
                                 1,
                             style =
                                 line.style_dotted
                         )
                    )
 
 
                    labels.push(
                         label.new(
                             xEnd,
                             pocP,
                             "POC " +
                             f_fmt(
                                 pocP
                             ),
                             style =
                                 label.style_label_left,
                             color =
                                 color.new(
                                     color.black,
                                     100
                                 ),
                             textcolor =
                                 cPoc,
                             size =
                                 size.tiny
                         )
                    )
 
 
                    labels.push(
                         label.new(
                             xEnd,
                             vah,
                             "VAH " +
                             f_fmt(
                                 vah
                             ),
                             style =
                                 label.style_label_left,
                             color =
                                 color.new(
                                     color.black,
                                     100
                                 ),
                             textcolor =
                                 cVa,
                             size =
                                 size.tiny
                         )
                    )
 
 
                    labels.push(
                         label.new(
                             xEnd,
                             val,
                             "VAL " +
                             f_fmt(
                                 val
                             ),
                             style =
                                 label.style_label_left,
                             color =
                                 color.new(
                                     color.black,
                                     100
                                 ),
                             textcolor =
                                 cVa,
                             size =
                                 size.tiny
                         )
                    )
 
 
                // ===========================================================
                // MIGRATION SPINE
                // ===========================================================
 
                if showMig
 
                    int spineX =
                         xEnd +
                         16
 
 
                    for k = 0 to S - 1
 
                        float yk =
                             bot +
                             (
                                 lPoc.get(
                                     k
                                 ) +
                                 0.5
                             ) *
                             step
 
 
                        float developingYK =
                             bot +
                             (
                                 devPoc.get(
                                     k
                                 ) +
                                 0.5
                             ) *
                             step
 
 
                        int xk =
                             spineX +
                             k *
                             4
 
 
                        if k > 0
 
                            float yp =
                                 bot +
                                 (
                                     lPoc.get(
                                         k -
                                         1
                                     ) +
                                     0.5
                                 ) *
                                 step
 
 
                            lines.push(
                                 line.new(
                                     xk -
                                     4,
                                     yp,
                                     xk,
                                     yk,
                                     color =
                                         f_layerCol(
                                             k,
                                             S
                                         ),
                                     width =
                                         2
                                 )
                            )
 
 
                        string migrationTooltip =
                             "Stratum " +
                             str.tostring(
                                 k +
                                 1
                             ) +
                             " of " +
                             str.tostring(
                                 S
                             ) +
                             "\n" +
                             "Stratum POC: " +
                             f_fmt(
                                 yk
                             ) +
                             "\n" +
                             "Developing POC: " +
                             f_fmt(
                                 developingYK
                             )
 
 
                        if k ==
                             S -
                             1
 
                            migrationTooltip +=
                                 "\n\n" +
                                 "Volume engine: " +
                                 engineState +
                                 "\n" +
                                 "Resolution mode: " +
                                 (
                                     ltfMode == "Auto" ?
                                     "AUTO " +
                                     autoPrecision :
                                     "MANUAL"
                                 ) +
                                 "\n" +
                                 "Selected intrabar TF: " +
                                 lowerTF +
                                 "\n" +
                                 "Requested intrabars: " +
                                 str.tostring(
                                     requestedIntrabars
                                 ) +
                                 "\n" +
                                 "Intrabar coverage: " +
                                 str.tostring(
                                     intrabarCoveragePct,
                                     "#.#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Avg intrabars / covered bar: " +
                                 str.tostring(
                                     averageIntrabarsPerCoveredBar,
                                     "#.##"
                                 ) +
                                 "\n" +
                                 "Observed max intrabars / bar: " +
                                 str.tostring(
                                     observedMaxIntrabars
                                 ) +
                                 "\n" +
                                 "Density adequacy: " +
                                 str.tostring(
                                     densityAdequacyPct,
                                     "#.#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Intrabar quality: " +
                                 str.tostring(
                                     intrabarQualityPct,
                                     "#"
                                 ) +
                                 "% (" +
                                 intrabarQualityClass +
                                 ")" +
                                 "\n" +
                                 "Intrabars used: " +
                                 str.tostring(
                                     totalIntrabarsUsed
                                 ) +
                                 "\n" +
                                 "Fallback chart bars: " +
                                 str.tostring(
                                     parentBarsFallback
                                 ) +
                                 "\n\n" +
                                 "Value migration: " +
                                 (
                                     migrationPct >= 0 ?
                                     "+" :
                                     ""
                                 ) +
                                 str.tostring(
                                     migrationPct,
                                     "#.##"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Value migration state: " +
                                 migrationClass +
                                 "\n" +
                                 "Migration efficiency: " +
                                 str.tostring(
                                     migrationEfficiency *
                                     100.0,
                                     "#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Recent Acceptance POC: " +
                                 f_fmt(
                                     recentPocP
                                 ) +
                                 "\n" +
                                 "Recent alignment: " +
                                 str.tostring(
                                     recentAlignmentPct,
                                     "#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Newest activity: " +
                                 str.tostring(
                                     newestActivityRatio,
                                     "#.##"
                                 ) +
                                 "x average" +
                                 "\n" +
                                 "Activity support: " +
                                 str.tostring(
                                     activityConfidence *
                                     100.0,
                                     "#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Newest vs previous layer volume: " +
                                 str.tostring(
                                     latestParticipationRatio,
                                     "#.##"
                                 ) +
                                 "x" +
                                 "\n" +
                                 "Participation balance: " +
                                 str.tostring(
                                     participationBalance *
                                     100.0,
                                     "#"
                                 ) +
                                 "% (" +
                                 participationBalanceClass +
                                 ")" +
                                 "\n" +
                                 "Structural confidence: " +
                                 str.tostring(
                                     structuralConfidencePct,
                                     "#"
                                 ) +
                                 "%" +
                                 "\n" +
                                 "Data-quality gate: " +
                                 qualityGateClass +
                                 "\n" +
                                 "Value Migration Confidence: " +
                                 str.tostring(
                                     migrationConfidencePct,
                                     "#"
                                 ) +
                                 "% (" +
                                 confidenceClass +
                                 ")" +
                                 "\n" +
                                 "Value stability: " +
                                 stabilityClass
 
 
                        labels.push(
                             label.new(
                                 xk,
                                 yk,
                                 "",
                                 style =
                                     label.style_circle,
                                 size =
                                     size.tiny,
                                 color =
                                     f_layerCol(
                                         k,
                                         S
                                     ),
                                 tooltip =
                                     migrationTooltip
                             )
                        )
 
 
                // ===========================================================
                // TIME RIBBON
                // ===========================================================
 
                if showRib
 
                    float ribbonTop =
                         bot -
                         step *
                         0.6
 
 
                    float ribbonBottom =
                         bot -
                         step *
                         1.4
 
 
                    for k = 0 to S - 1
 
                        int jf =
                             jFirst.get(
                                 k
                             )
 
                        int jl =
                             jLast.get(
                                 k
                             )
 
 
                        if jf >= 0
 
                            int leftBar =
                                 bar_index -
                                 (
                                     n -
                                     1 -
                                     jf
                                 )
 
 
                            int rightBar =
                                 bar_index -
                                 (
                                     n -
                                     1 -
                                     jl
                                 ) +
                                 1
 
 
                            boxes.push(
                                 box.new(
                                     leftBar,
                                     ribbonTop,
                                     rightBar,
                                     ribbonBottom,
                                     border_width =
                                         0,
                                     bgcolor =
                                         color.new(
                                             f_layerCol(
                                                 k,
                                                 S
                                             ),
                                             15
                                         )
                                 )
                            )
 
 
                // ===========================================================
                // ADVANCED STALE HVN ENGINE
                // ===========================================================
 
                if showSt
 
                    array<int> candidateRows =
                         array.new<int>()
 
                    array<float> candidateScores =
                         array.new<float>()
 
                    array<float> candidateRecentShares =
                         array.new<float>()
 
 
                    for r = 0 to rowsN - 1
 
                        float rowVolume =
                             tot.get(
                                 r
                             )
 
 
                        float recentVolume =
                             recentRowVol.get(
                                 r
                             )
 
 
                        float recentShare =
                             rowVolume > 0 ?
                             recentVolume /
                             rowVolume *
                             100.0 :
                             0.0
 
 
                        float rowPrice =
                             bot +
                             (
                                 r +
                                 0.5
                             ) *
                             step
 
 
                        float distanceATR =
                             atr14 > 0 ?
                             math.abs(
                                 rowPrice -
                                 close
                             ) /
                             atr14 :
                             0.0
 
 
                        bool passesDistance =
                             not filterStaleDistance or
                             distanceATR <=
                             staleMaxATR
 
 
                        bool strongNode =
                             r != poc and
                             rowVolume >=
                             hvnThreshold
 
 
                        bool staleNode =
                             strongNode and
                             recentShare <
                             stalePct and
                             passesDistance
 
 
                        if staleNode
 
                            float historicalStrength =
                                 rowVolume /
                                 maxTot
 
 
                            float freshnessDeficit =
                                 stalePct > 0 ?
                                 1.0 -
                                 math.min(
                                     1.0,
                                     recentShare /
                                     stalePct
                                 ) :
                                 1.0
 
 
                            float staleScore =
                                 historicalStrength *
                                 freshnessDeficit
 
 
                            candidateRows.push(
                                 r
                            )
 
                            candidateScores.push(
                                 staleScore
                            )
 
                            candidateRecentShares.push(
                                 recentShare
                            )
 
 
                    array<int> clusterRows =
                         array.new<int>()
 
                    array<float> clusterScores =
                         array.new<float>()
 
                    array<float> clusterRecentShares =
                         array.new<float>()
 
                    array<int> clusterLowRows =
                         array.new<int>()
 
                    array<int> clusterHighRows =
                         array.new<int>()
 
 
                    int candidateCount =
                         candidateRows.size()
 
 
                    if candidateCount > 0
 
                        int currentLow =
                             candidateRows.get(
                                 0
                             )
 
                        int currentHigh =
                             candidateRows.get(
                                 0
                             )
 
                        int currentBestRow =
                             candidateRows.get(
                                 0
                             )
 
                        float currentBestScore =
                             candidateScores.get(
                                 0
                             )
 
                        float currentBestRecent =
                             candidateRecentShares.get(
                                 0
                             )
 
 
                        if candidateCount > 1
 
                            for idx = 1 to candidateCount - 1
 
                                int candidateRow =
                                     candidateRows.get(
                                         idx
                                     )
 
                                float candidateScore =
                                     candidateScores.get(
                                         idx
                                     )
 
                                float candidateRecent =
                                     candidateRecentShares.get(
                                         idx
                                     )
 
 
                                int rowDistance =
                                     candidateRow -
                                     currentHigh
 
 
                                bool sameCluster =
                                     rowDistance <=
                                     clusterGap +
                                     1
 
 
                                if sameCluster
 
                                    currentHigh :=
                                         candidateRow
 
 
                                    if candidateScore >
                                         currentBestScore
 
                                        currentBestScore :=
                                             candidateScore
 
                                        currentBestRow :=
                                             candidateRow
 
                                        currentBestRecent :=
                                             candidateRecent
 
 
                                else
 
                                    clusterRows.push(
                                         currentBestRow
                                    )
 
                                    clusterScores.push(
                                         currentBestScore
                                    )
 
                                    clusterRecentShares.push(
                                         currentBestRecent
                                    )
 
                                    clusterLowRows.push(
                                         currentLow
                                    )
 
                                    clusterHighRows.push(
                                         currentHigh
                                    )
 
 
                                    currentLow :=
                                         candidateRow
 
                                    currentHigh :=
                                         candidateRow
 
                                    currentBestRow :=
                                         candidateRow
 
                                    currentBestScore :=
                                         candidateScore
 
                                    currentBestRecent :=
                                         candidateRecent
 
 
                        clusterRows.push(
                             currentBestRow
                        )
 
                        clusterScores.push(
                             currentBestScore
                        )
 
                        clusterRecentShares.push(
                             currentBestRecent
                        )
 
                        clusterLowRows.push(
                             currentLow
                        )
 
                        clusterHighRows.push(
                             currentHigh
                        )
 
 
                    int clusterCount =
                         clusterRows.size()
 
 
                    int drawCount =
                         math.min(
                             maxStale,
                             clusterCount
                         )
 
 
                    if drawCount > 0
 
                        array<bool> used =
                             array.new<bool>(
                                 clusterCount,
                                 false
                             )
 
 
                        for selection = 0 to drawCount - 1
 
                            float bestScore =
                                 -1.0
 
                            int bestIndex =
                                 -1
 
 
                            for idx = 0 to clusterCount - 1
 
                                if not used.get(
                                     idx
                                )
 
                                    float score =
                                         clusterScores.get(
                                             idx
                                         )
 
 
                                    if score >
                                         bestScore
 
                                        bestScore :=
                                             score
 
                                        bestIndex :=
                                             idx
 
 
                            if bestIndex >= 0
 
                                used.set(
                                     bestIndex,
                                     true
                                )
 
 
                                int staleRow =
                                     clusterRows.get(
                                         bestIndex
                                     )
 
                                int lowRow =
                                     clusterLowRows.get(
                                         bestIndex
                                     )
 
                                int highRow =
                                     clusterHighRows.get(
                                         bestIndex
                                     )
 
 
                                float recentShare =
                                     clusterRecentShares.get(
                                         bestIndex
                                     )
 
 
                                float staleY =
                                     bot +
                                     (
                                         staleRow +
                                         0.5
                                     ) *
                                     step
 
 
                                float zoneLow =
                                     bot +
                                     lowRow *
                                     step
 
 
                                float zoneHigh =
                                     bot +
                                     (
                                         highRow +
                                         1
                                     ) *
                                     step
 
 
                                float staleDistanceATR =
                                     atr14 > 0 ?
                                     math.abs(
                                         staleY -
                                         close
                                     ) /
                                     atr14 :
                                     0.0
 
 
                                lines.push(
                                     line.new(
                                         xStart,
                                         staleY,
                                         x0,
                                         staleY,
                                         color =
                                             color.new(
                                                 cOld,
                                                 20
                                             ),
                                         width =
                                             1,
                                         style =
                                             line.style_dashed
                                     )
                                )
 
 
                                labels.push(
                                     label.new(
                                         xStart,
                                         staleY,
                                         "stale HVN",
                                         style =
                                             label.style_label_right,
                                         color =
                                             color.new(
                                                 color.black,
                                                 100
                                             ),
                                         textcolor =
                                             cOld,
                                         size =
                                             size.tiny,
                                         tooltip =
                                             "Stale High Volume Node" +
                                             "\n\n" +
                                             "Representative price: " +
                                             f_fmt(
                                                 staleY
                                             ) +
                                             "\n" +
                                             "Cluster range: " +
                                             f_fmt(
                                                 zoneLow
                                             ) +
                                             " - " +
                                             f_fmt(
                                                 zoneHigh
                                             ) +
                                             "\n" +
                                             "Strength score: " +
                                             str.tostring(
                                                 bestScore *
                                                 100.0,
                                                 "#.#"
                                             ) +
                                             "\n" +
                                             "Recent share: " +
                                             str.tostring(
                                                 recentShare,
                                                 "#.##"
                                             ) +
                                             "%" +
                                             "\n" +
                                             "Distance: " +
                                             str.tostring(
                                                 staleDistanceATR,
                                                 "#.##"
                                             ) +
                                             " ATR" +
                                             "\n\n" +
                                             "High historical volume combined with weak recent participation."
                                     )
                                )

← 返回列表