Volume Quantile Profile [Drizzle_Algo56]

Drizzle_Algo56 · study · 906 行 · 点赞 61 · TradingView 原页

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

Pine Script

// Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International.
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Drizzle_Algo56
//@version=6
indicator("Volume Quantile Profile [Drizzle_Algo56]", "VQP", overlay=true, behind_chart=false, max_lines_count=250, max_boxes_count=500, max_labels_count=150, max_bars_back=5000)
 
const string G_MAIN = "01 · Profile window"
const string G_SESSION = "02 · Session & daily reset"
const string G_RANGE = "03 · Price range & direction"
const string G_FIB = "04 · Volume Fibonacci levels"
const string G_BANDS = "05 · Shared zone ratios & main fills"
const string G_NODES = "06 · Main LVN / HVN zones"
const string G_SEARCH = "07 · Main LVN / HVN detection"
const string G_SUB = "08 · Nested profile N1"
const string G_NCOLORS = "09 · N1 palette & levels"
const string G_NZONES = "10 · N1 zone fills"
const string G_N2 = "11 · Nested profile N2"
const string G_N2COLOR = "12 · N2 palette & levels"
const string G_N2ZONES = "13 · N2 zone fills"
const string G_COMPARE = "14 · Previous session comparison"
const string G_PV = "15 · Price / volume comparison"
const string G_DATA = "16 · Footprint data & resolution"
const string G_LAYOUT = "17 · Main chart layout"
const string G_APPEAR = "18 · Main appearance"
const string G_TEXT = "19 · Labels & data status"
 
string historyMode = input.string("Single session", "Profile window", options=["Single session", "Combined sessions", "All loaded history"], group=G_MAIN)
int dayOffset = input.int(0, "Session offset · 0 = latest", minval=0, maxval=20, group=G_MAIN, active=historyMode == "Single session")
string lookbackSelection = input.string("Latest + 1 previous", "Sessions to combine", options=["Latest session", "Latest + 1 previous", "Latest + 2 previous", "Latest + 3 previous", "Latest + 5 previous", "Latest + 10 previous", "Latest + 20 previous", "Custom"], group=G_MAIN, active=historyMode == "Combined sessions", tooltip="Combines the latest session with N preceding sessions under the selected reset rule. Sessions without chart bars do not count.")
int customDays = input.int(5, "Custom preceding sessions", minval=0, maxval=20, group=G_MAIN, active=historyMode == "Combined sessions" and lookbackSelection == "Custom")
 
string resetMode = input.string("Chart session", "New profile starts at", options=["Chart session", "Custom daily reset"], group=G_SESSION, tooltip="Chart session: one profile per chart trading session. Includes pre / post-market when those bars are enabled on the chart; overnight sessions remain one trading day. Uses chart session boundaries, not calendar midnight. Custom daily reset: consecutive daily windows starting at your selected local time; no session-hours filtering. Local days can span 23 or 25 hours at daylight-saving transitions.")
int resetHour = input.int(0, "Hour", minval=0, maxval=23, inline="reset", group=G_SESSION, active=resetMode == "Custom daily reset")
int resetMinute = input.int(0, "Minute", minval=0, maxval=59, inline="reset", group=G_SESSION, active=resetMode == "Custom daily reset")
string resetTimezone = input.string("Exchange", "Reset time zone", group=G_SESSION, active=resetMode == "Custom daily reset", tooltip="Exchange uses the symbol's exchange time zone. Otherwise enter an IANA zone, e.g. America/New_York or Europe/Berlin, for daylight-saving-aware resets. Changing the chart display time zone does not change this setting.")
 
float anchorA = input.price(4000.0, "Range anchor A", confirm=true, inline="anchors", group=G_RANGE)
float anchorB = input.price(4015.0, "Range anchor B", confirm=true, inline="anchors", group=G_RANGE)
string accumulation = input.string("From high", "Volume accumulation direction", options=["From high", "From low"], group=G_RANGE, tooltip="From high: 0 at upper anchor, 1 at lower anchor. From low reverses this. The 0.7 level contains 70% of lens volume counted from that side.")
 
bool on0 = input.bool(true, "", inline="f0", group=G_FIB)
float r0 = input.float(0.0, "Level 1", minval=0, maxval=1, step=0.001, inline="f0", group=G_FIB)
color fibColor0 = input.color(#787B86, "", inline="f0", group=G_FIB)
bool on1 = input.bool(true, "", inline="f1", group=G_FIB)
float r1 = input.float(0.236, "Level 2", minval=0, maxval=1, step=0.001, inline="f1", group=G_FIB)
color fibColor1 = input.color(#787B86, "", inline="f1", group=G_FIB)
bool on2 = input.bool(true, "", inline="f2", group=G_FIB)
float r2 = input.float(0.382, "Level 3", minval=0, maxval=1, step=0.001, inline="f2", group=G_FIB)
color fibColor2 = input.color(#787B86, "", inline="f2", group=G_FIB)
bool on3 = input.bool(true, "", inline="f3", group=G_FIB)
float r3 = input.float(0.5, "Level 4", minval=0, maxval=1, step=0.001, inline="f3", group=G_FIB)
color fibColor3 = input.color(#787B86, "", inline="f3", group=G_FIB)
bool on4 = input.bool(true, "", inline="f4", group=G_FIB)
float r4 = input.float(0.618, "Level 5", minval=0, maxval=1, step=0.001, inline="f4", group=G_FIB)
color fibColor4 = input.color(#787B86, "", inline="f4", group=G_FIB)
bool on5 = input.bool(true, "", inline="f5", group=G_FIB)
float r5 = input.float(0.7, "Level 6", minval=0, maxval=1, step=0.001, inline="f5", group=G_FIB)
color fibColor5 = input.color(#787B86, "", inline="f5", group=G_FIB)
bool on6 = input.bool(true, "", inline="f6", group=G_FIB)
float r6 = input.float(0.786, "Level 7", minval=0, maxval=1, step=0.001, inline="f6", group=G_FIB)
color fibColor6 = input.color(#787B86, "", inline="f6", group=G_FIB)
bool on7 = input.bool(true, "", inline="f7", group=G_FIB)
float r7 = input.float(1.0, "Level 8", minval=0, maxval=1, step=0.001, inline="f7", group=G_FIB)
color fibColor7 = input.color(#787B86, "", inline="f7", group=G_FIB)
 
bool band1 = input.bool(true, "", inline="b1", group=G_BANDS)
float band1A = input.float(0.618, "Zone 1 · from", minval=0, maxval=1, step=0.001, inline="b1", group=G_BANDS)
float band1B = input.float(0.786, "to", minval=0, maxval=1, step=0.001, inline="b1", group=G_BANDS)
color band1Color = input.color(#787B86, "", inline="b1", group=G_BANDS)
bool band2 = input.bool(false, "", inline="b2", group=G_BANDS)
float band2A = input.float(0.382, "Zone 2 · from", minval=0, maxval=1, step=0.001, inline="b2", group=G_BANDS)
float band2B = input.float(0.5, "to", minval=0, maxval=1, step=0.001, inline="b2", group=G_BANDS)
color band2Color = input.color(#787B86, "", inline="b2", group=G_BANDS)
int bandAlpha = input.int(94, "Main zone transparency", minval=0, maxval=100, group=G_BANDS, tooltip="Zone ratios are shared by Main, N1 and N2; each profile has independent visibility and colors. The main checkboxes affect only main fills. A 0.618–0.786 band spans 16.8% of that profile's volume, subject to interpolation.")
 
bool showNodes = input.bool(true, "Show LVN / HVN zones", group=G_NODES)
string nodeMode = input.string("LVN + HVN", "Zone type", options=["LVN", "HVN", "LVN + HVN"], inline="nodes", group=G_NODES)
int maxNodes = input.int(3, "Maximum per type", minval=1, maxval=6, inline="nodes", group=G_NODES)
string nodeScope = input.string("Near enabled fibs", "Detection scope", options=["Near enabled fibs", "Whole lens"], group=G_NODES)
float fibToleranceTicks = input.float(2, "Level proximity (ticks)", minval=0, maxval=100, step=0.25, group=G_NODES)
bool showNodeMarkers = input.bool(true, "Center lines", inline="markers", group=G_NODES)
bool showNodeText = input.bool(false, "Zone text", inline="markers", group=G_NODES)
bool annotateFib = input.bool(true, "Annotate levels near LVN / HVN", group=G_NODES, tooltip="Adds LVN/HVN to fib text when inside a zone; ~LVN/~HVN means within proximity tolerance. Does not alter the original volume-quantile price.")
color lvnColor = input.color(#787B86, "LVN", inline="nc", group=G_NODES)
color hvnColor = input.color(#787B86, "HVN", inline="nc", group=G_NODES)
int nodeAlpha = input.int(92, "LVN / HVN zone transparency", minval=0, maxval=100, group=G_NODES)
 
bool confirmedNodes = input.bool(true, "Use closed-bar profile for zones", group=G_SEARCH, tooltip="Updates zones after each chart candle closes. The live profile and fibs may still develop; zone membership is checked against the last confirmed zones. Zones are recalculated, not permanent support/resistance.")
int minimumNodeBars = input.int(10, "Minimum footprint bars in lens", minval=1, maxval=300, group=G_SEARCH)
int smoothRadius = input.int(1, "Smoothing radius (rows)", minval=0, maxval=4, group=G_SEARCH)
int shoulderWindow = input.int(8, "Shoulder search per side (rows)", minval=2, maxval=30, group=G_SEARCH)
float minimumProminence = input.float(25, "Minimum prominence (%)", minval=1, maxval=95, group=G_SEARCH)
float minimumPeak = input.float(10, "HVN minimum volume (% of peak)", minval=1, maxval=100, group=G_SEARCH)
float zoneExpansion = input.float(30, "Expansion toward shoulders (%)", minval=0, maxval=90, group=G_SEARCH)
int maxZoneRows = input.int(8, "Maximum zone height (rows)", minval=1, maxval=30, group=G_SEARCH)
 
bool subEnabled = input.bool(true, "Show N1 profile", group=G_SUB)
float subA = input.float(0.618, "Main volume ratio · from", minval=0, maxval=1, step=0.001, inline="sub", group=G_SUB)
float subB = input.float(0.786, "to", minval=0, maxval=1, step=0.001, inline="sub", group=G_SUB)
int subRows = input.int(60, "N1 analysis rows", minval=5, maxval=100, group=G_SUB)
int subWidth = input.int(30, "N1 histogram width (bars)", minval=5, maxval=60, group=G_SUB)
int subInsideGap = input.int(3, "N1 gap before live candle (bars)", minval=1, maxval=100, group=G_SUB)
bool subLevels = input.bool(true, "Show N1 levels", inline="subshow", group=G_SUB)
bool subText = input.bool(true, "Show N1 labels", inline="subshow", group=G_SUB)
bool nestedHeading = input.bool(false, "Show N1 heading", group=G_SUB)
string nestedTextSize = input.string("Small", "Nested label size · N1 / N2", options=["Tiny", "Small", "Normal", "Large"], group=G_SUB)
 
string nestedMap = input.string("Ocean", "N1 palette", options=["Ocean", "Violet", "Warm", "Custom", "Base"], group=G_NCOLORS)
int nestedAlpha = input.int(55, "N1 histogram transparency", minval=0, maxval=100, group=G_NCOLORS)
color nColor0 = input.color(#93C5FD, "N1 color 1 / level 1", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor1 = input.color(#60A5FA, "N1 color 2 / level 2", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor2 = input.color(#38BDF8, "N1 color 3 / level 3", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor3 = input.color(#22D3EE, "N1 color 4 / level 4", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor4 = input.color(#2DD4BF, "N1 color 5 / level 5", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor5 = input.color(#34D399, "N1 color 6 / level 6", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor6 = input.color(#A3E635, "N1 color 7 / level 7", group=G_NCOLORS, active=nestedMap == "Custom")
color nColor7 = input.color(#D9F99D, "N1 color 8 / level 8", group=G_NCOLORS, active=nestedMap == "Custom")
 
bool n1Zone1 = input.bool(true, "Show zone 1", inline="n1z1", group=G_NZONES)
color n1Zone1Color = input.color(#2DD4BF, "Color", inline="n1z1", group=G_NZONES, active=n1Zone1)
bool n1Zone2 = input.bool(false, "Show zone 2", inline="n1z2", group=G_NZONES)
color n1Zone2Color = input.color(#38BDF8, "Color", inline="n1z2", group=G_NZONES, active=n1Zone2)
int n1ZoneAlpha = input.int(92, "N1 zone transparency", minval=0, maxval=100, group=G_NZONES, tooltip="Uses the shared Zone 1 / Zone 2 ratios, measured against N1's own total volume. Independent of main zone visibility and the N1 histogram palette.")
 
bool n2Enabled = input.bool(false, "Show N2 profile", group=G_N2)
string n2Parent = input.string("Nested N1", "Parent profile", options=["Main profile", "Nested N1"], group=G_N2, active=n2Enabled, tooltip="Main: independent sibling lens. Nested N1: N2 bounds are volume quantiles inside N1. N1 can be hidden while still acting as a parent. Each profile has its own 100% denominator.")
float n2A = input.float(0.382, "Parent volume ratio · from", minval=0, maxval=1, step=0.001, inline="n2bounds", group=G_N2, active=n2Enabled)
float n2B = input.float(0.618, "to", minval=0, maxval=1, step=0.001, inline="n2bounds", group=G_N2, active=n2Enabled)
int n2Rows = input.int(60, "N2 analysis rows", minval=5, maxval=100, group=G_N2, active=n2Enabled, tooltip="Uses Shared nested analysis rows with N1. Extra nesting cannot resolve data finer than that grid or the source footprints.")
int n2Width = input.int(25, "N2 histogram width (bars)", minval=5, maxval=60, group=G_N2, active=n2Enabled)
int n2Gap = input.int(6, "N2 gap before N1 (bars)", minval=1, maxval=100, group=G_N2, active=n2Enabled, tooltip="N2 is drawn to the left of N1. If N1 is hidden, this is the gap before the live candle.")
bool n2Levels = input.bool(true, "Show N2 levels", inline="n2show", group=G_N2, active=n2Enabled)
bool n2Text = input.bool(true, "Show N2 labels", inline="n2show", group=G_N2, active=n2Enabled)
bool n2Heading = input.bool(false, "Show N2 heading", group=G_N2, active=n2Enabled)
 
string n2Map = input.string("Warm", "N2 palette", options=["Ocean", "Violet", "Warm", "Custom", "Base"], group=G_N2COLOR, active=n2Enabled)
int n2Alpha = input.int(55, "N2 histogram transparency", minval=0, maxval=100, group=G_N2COLOR, active=n2Enabled)
color n2Color0 = input.color(#FEF3C7, "N2 color 1 / level 1", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color1 = input.color(#FDE68A, "N2 color 2 / level 2", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color2 = input.color(#FCD34D, "N2 color 3 / level 3", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color3 = input.color(#FBBF24, "N2 color 4 / level 4", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color4 = input.color(#FB923C, "N2 color 5 / level 5", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color5 = input.color(#F97316, "N2 color 6 / level 6", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color6 = input.color(#F87171, "N2 color 7 / level 7", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
color n2Color7 = input.color(#FDA4AF, "N2 color 8 / level 8", group=G_N2COLOR, active=n2Enabled and n2Map == "Custom")
 
bool n2Zone1 = input.bool(true, "Show zone 1", inline="n2z1", group=G_N2ZONES, active=n2Enabled)
color n2Zone1Color = input.color(#FB923C, "Color", inline="n2z1", group=G_N2ZONES, active=n2Enabled and n2Zone1)
bool n2Zone2 = input.bool(false, "Show zone 2", inline="n2z2", group=G_N2ZONES, active=n2Enabled)
color n2Zone2Color = input.color(#FCD34D, "Color", inline="n2z2", group=G_N2ZONES, active=n2Enabled and n2Zone2)
int n2ZoneAlpha = input.int(92, "N2 zone transparency", minval=0, maxval=100, group=G_N2ZONES, active=n2Enabled, tooltip="Uses the shared Zone 1 / Zone 2 ratios, measured against N2's own total volume. Independent of main / N1 zone visibility and the N2 histogram palette.")
 
bool compareDay = input.bool(false, "Show preceding session levels", group=G_COMPARE, tooltip="Single session: compare with the preceding session relative to the selected offset. Other windows: compare with the preceding session. Uses the same range and ratios; comparison levels are dashed.")
bool compareText = input.bool(false, "Show comparison labels", inline="compare", group=G_COMPARE, active=compareDay)
int comparisonAlpha = input.int(65, "Transparency", minval=0, maxval=100, inline="compare", group=G_COMPARE, active=compareDay)
 
bool pvEnabled = input.bool(false, "Compare price and volume levels", group=G_PV)
bool pvLines = input.bool(true, "Geometric price-fib lines", group=G_PV, active=pvEnabled)
bool pvBands = input.bool(false, "Shade price/volume displacement", group=G_PV, active=pvEnabled)
bool pvTag = input.bool(true, "P=V tag at confluence", group=G_PV, active=pvEnabled)
float pvToleranceTicks = input.float(2, "Confluence tolerance (ticks)", minval=0, maxval=100, step=0.25, group=G_PV, active=pvEnabled, tooltip="Linear price-space comparison; interior ratios only. P=V means geometric price fib and volume fib are within this distance. Original volume-fib prices never move.")
color pvColor = input.color(#A3A3A3, "Price-fib color", group=G_PV, active=pvEnabled)
int pvAlpha = input.int(95, "Displacement fill transparency", minval=0, maxval=100, group=G_PV, active=pvEnabled)
 
int fpTicks = input.int(1, "Footprint row size (ticks)", minval=1, group=G_DATA)
int requestedRows = input.int(100, "Main analysis rows", minval=10, maxval=200, group=G_DATA, tooltip="Separate analysis grid, as in the range-profile reference. Automatically reduced for a lens narrower than this many ticks. No smoothing before quantiles.")
bool fpLive = input.bool(true, "Include live candle", inline="live", group=G_DATA)
bool fpAllowPartial = input.bool(false, "Allow incomplete data", inline="partial", group=G_DATA, tooltip="Off hides profiles with missing relevant footprints, incomplete loaded sessions or candles crossing a custom reset. Invalid data and mass errors always hide the profile.")
int fineResolution = input.int(1000, "Shared nested analysis rows", minval=200, maxval=4000, group=G_DATA, tooltip="Direct footprint aggregation, independent of parent analysis rows. Actual count is capped to whole ticks. Child profiles cannot resolve finer detail than this grid/source footprint rows.")
 
bool showProfile = input.bool(true, "Show main histogram", inline="profile", group=G_LAYOUT)
int offsetBars = input.int(8, "Main histogram offset (bars)", minval=1, maxval=100, group=G_LAYOUT)
int projectionBars = input.int(300, "Main level / zone extension (bars)", minval=1, maxval=9999, group=G_LAYOUT)
int profileWidth = input.int(40, "Histogram width (bars)", minval=5, maxval=150, inline="layoutsize", group=G_LAYOUT)
bool showGuides = input.bool(true, "Show range boundaries", inline="guides", group=G_LAYOUT)
bool showBackground = input.bool(false, "Shade price range", inline="guides", group=G_LAYOUT)
 
color mono = input.color(#787B86, "Base color · histogram / guides / status", group=G_APPEAR)
bool useLevelColors = input.bool(true, "Use individual main level colors", group=G_APPEAR, tooltip="Controls only main volume-level colors. Zone fills, LVN / HVN colors and both nested palettes remain independent.")
string lineType = input.string("Solid", "Line style", options=["Solid", "Dotted", "Dashed"], inline="line", group=G_APPEAR)
int lineWidth = input.int(1, "Width", minval=1, maxval=3, inline="line", group=G_APPEAR)
int profileAlpha = input.int(78, "Main histogram transparency", minval=0, maxval=100, group=G_APPEAR)
int backgroundAlpha = input.int(96, "Price range transparency", minval=0, maxval=100, group=G_APPEAR, active=showBackground)
 
bool showText = input.bool(true, "Show labels", inline="text", group=G_TEXT)
string textSize = input.string("Normal", "Size", options=["Tiny", "Small", "Normal", "Large", "Huge"], inline="text", group=G_TEXT)
bool textRatio = input.bool(true, "Ratio", inline="fields", group=G_TEXT)
bool textVolume = input.bool(false, "Accumulated / total range volume", inline="fields", group=G_TEXT)
int nestedLaneWidth = input.int(12, "Nested label lane width (bars)", minval=6, maxval=40, group=G_TEXT)
int textGap = input.int(2, "Label gap (bars)", minval=1, maxval=20, group=G_TEXT)
bool readableText = input.bool(true, "Use chart foreground for main labels", group=G_TEXT, tooltip="On uses TradingView's light/dark chart foreground, fully opaque. Off uses each item's color, also fully opaque. Line colors stay unchanged.")
bool avoidTextOverlap = input.bool(true, "Stagger nearby labels", group=G_TEXT)
int labelColumnGap = input.int(12, "Label column spacing (bars)", minval=2, maxval=25, group=G_TEXT)
float textSpacingRange = input.float(1.8, "Close-label threshold (% of price lens)", minval=0, maxval=10, step=0.2, group=G_TEXT)
float textSpacingTicks = input.float(4, "Close-label threshold (ticks)", minval=0, maxval=100, step=0.25, group=G_TEXT)
bool showStatus = input.bool(true, "Show data status", group=G_TEXT, tooltip="Plain text without backgrounds. Reports child-lens state and data gaps. No tables.")
 
int previousDays = switch lookbackSelection
    "Latest session" => 0
    "Latest + 1 previous" => 1
    "Latest + 2 previous" => 2
    "Latest + 3 previous" => 3
    "Latest + 5 previous" => 5
    "Latest + 10 previous" => 10
    "Latest + 20 previous" => 20
    => customDays
int comparisonOffset = historyMode == "Single session" ? dayOffset + 1 : 1
int keepDays = math.max(historyMode == "Single session" ? dayOffset + 1 : historyMode == "Combined sessions" ? previousDays + 1 : 1, compareDay ? comparisonOffset + 1 : 1)
float priceLow = math.min(anchorA, anchorB)
float priceHigh = math.max(anchorA, anchorB)
int binCount = math.max(1, math.min(requestedRows, int(math.floor((priceHigh - priceLow) / syminfo.mintick + 1e-7))))
float binSize = (priceHigh - priceLow) / binCount
int detailCount = math.max(binCount, math.min(fineResolution, int(math.floor((priceHigh - priceLow) / syminfo.mintick + 1e-7))))
float detailSize = (priceHigh - priceLow) / detailCount
float textATR = ta.atr(14)
bool fromHigh = accumulation == "From high"
f_size(string value) =>
    value == "Tiny" ? size.tiny : value == "Normal" ? size.normal : value == "Large" ? size.large : value == "Huge" ? size.huge : size.small
f_style(string value) =>
    value == "Dotted" ? line.style_dotted : value == "Dashed" ? line.style_dashed : line.style_solid
 
if barstate.isfirst
    if priceHigh - priceLow < syminfo.mintick * 0.999999
        runtime.error("Choose price anchors at least one tick apart.")
    if not chart.is_standard or not timeframe.isintraday
        runtime.error("Use standard time-based intraday candles.")
 
// Add volume by overlap. Difference-array interiors avoid a rows x bins loop.
f_gridAdd(array<float> edges, array<float> changes, float lo, float hi, float vol, float gridLow, float gridHigh, int count) =>
    float step = (gridHigh - gridLow) / count
    float a = math.max(lo, gridLow)
    float b = math.min(hi, gridHigh)
    float kept = 0.0
    if vol > 0 and b > a and hi > lo
        int first = math.max(0, math.min(count - 1, int(math.floor((a - gridLow) / step))))
        int last = math.max(0, math.min(count - 1, int(math.ceil((b - gridLow) / step - 1e-9)) - 1))
        float density = vol / (hi - lo)
        kept := density * (b - a)
        if first == last
            array.set(edges, first, array.get(edges, first) + kept)
        else
            array.set(edges, first, array.get(edges, first) + density * (gridLow + (first + 1) * step - a))
            array.set(edges, last, array.get(edges, last) + density * (b - (gridLow + last * step)))
            if last > first + 1
                array.set(changes, first + 1, array.get(changes, first + 1) + density * step)
                array.set(changes, last, array.get(changes, last) - density * step)
    kept
 
f_allocate(array<float> edges, array<float> changes, float lo, float hi, float vol) =>
    f_gridAdd(edges, changes, lo, hi, vol, priceLow, priceHigh, binCount)
 
f_dense(array<float> edges, array<float> changes) =>
    array<float> result = array.new<float>(edges.size(), 0.0)
    float running = 0.0
    for j = 0 to edges.size() - 1
        running += changes.get(j)
        result.set(j, math.max(0.0, edges.get(j) + running))
    result
 
f_slice(array<float> source, float low, float high, int count) =>
    array<float> edges = array.new<float>(count, 0.0)
    array<float> changes = array.new<float>(count, 0.0)
    for j = 0 to source.size() - 1
        float v = source.get(j)
        if v > 0
            f_gridAdd(edges, changes, priceLow + j * detailSize, priceLow + (j + 1) * detailSize, v, low, high, count)
    f_dense(edges, changes)
 
f_quantileGrid(array<float> bins, float ratio, float total, float low, float high) =>
    int count = bins.size()
    float step = (high - low) / count
    float p = na
    if ratio <= 0
        p := fromHigh ? high : low
    else if ratio >= 1
        p := fromHigh ? low : high
    else
        float cum = 0.0
        float target = ratio * total
        for k = 0 to count - 1
            int j = fromHigh ? count - 1 - k : k
            float v = array.get(bins, j)
            if v > 0 and cum + v >= target
                float fraction = math.max(0, math.min(1, (target - cum) / v))
                p := fromHigh ? low + (j + 1 - fraction) * step : low + (j + fraction) * step
                break
            cum += v
    p
 
f_quantile(array<float> bins, float ratio, float total) =>
    f_quantileGrid(bins, ratio, total, priceLow, priceHigh)
 
type DailyProfile
    int key
    bool partial
    bool cut
    int touches
    int covered
    int invalid
    float fullVolume
    float lensVolume
    array<float> bins
    array<float> detailEdges
    array<float> detailChanges
 
var array<DailyProfile> days = array.new<DailyProfile>()
var array<float> allBins = array.new<float>(binCount, 0.0)
var float allFull = 0.0
var float allLens = 0.0
var int allTouches = 0
var int allCovered = 0
var int allInvalid = 0
var bool allPartial = false
var bool allCut = false
var int loadedDays = 0
 
var array<float> allDetailEdges = array.new<float>(detailCount, 0.0)
var array<float> allDetailChanges = array.new<float>(detailCount, 0.0)
// Reset identity and boundary timestamps are separate: time_tradingday is a
// trading-day identifier, NOT the actual opening time of an overnight session.
string resetZone = resetTimezone == "Exchange" ? syminfo.timezone : resetTimezone
f_resetStart(int t) =>
    int y = year(t, resetZone)
    int m = month(t, resetZone)
    int d = dayofmonth(t, resetZone)
    int todayReset = timestamp(resetZone, y, m, d, resetHour, resetMinute)
    // Calendar arithmetic preserves local reset time over DST and month changes.
    t >= todayReset ? todayReset : timestamp(resetZone, y, m, d - 1, resetHour, resetMinute)
 
bool customReset = resetMode == "Custom daily reset"
int customStart = customReset ? f_resetStart(time) : na
int dayFinish = customReset ? timestamp(resetZone, year(customStart, resetZone), month(customStart, resetZone), dayofmonth(customStart, resetZone) + 1, resetHour, resetMinute) : na
bool chartSessionChanged = session.isfirstbar or (not na(time_tradingday[1]) and time_tradingday != time_tradingday[1])
bool newDay = barstate.isfirst or (customReset ? customStart != customStart[1] : chartSessionChanged)
var int dayKey = na
if newDay
    dayKey := customReset ? customStart : time
    // Never treat UTC midnight in time_tradingday as a session opening.
    // Flag both sides of a candle spanning a custom reset; no volume splitting.
    bool crossedPrevious = customReset and not barstate.isfirst and time[1] < customStart and time_close[1] > customStart
    bool partial = barstate.isfirst ? (customReset ? time > customStart : not session.isfirstbar) : crossedPrevious
    days.push(DailyProfile.new(dayKey, partial, false, 0, 0, 0, 0.0, 0.0, array.new<float>(binCount, 0.0), array.new<float>(detailCount, 0.0), array.new<float>(detailCount, 0.0)))
    loadedDays += 1
    allPartial := allPartial or partial
    while days.size() > keepDays
        days.shift()
// One API request only. Never copy it into request.security().
footprint fp = request.footprint(fpTicks)
if fpLive or barstate.isconfirmed
    DailyProfile today = days.last()
    bool cut = na(time_close) or (customReset and time_close > dayFinish)
    today.cut := today.cut or cut
    allCut := allCut or cut
    bool touched = high >= priceLow and low < priceHigh
    if touched
        today.touches += 1
        allTouches += 1
    if not na(fp)
        float full = fp.total_volume()
        today.fullVolume += nz(full)
        allFull += nz(full)
        if touched
            array<volume_row> rows = fp.rows()
            bool covered = rows.size() > 0
            today.covered += covered ? 1 : 0
            allCovered += covered ? 1 : 0
            array<float> edges = array.new<float>(binCount, 0.0)
            array<float> changes = array.new<float>(binCount, 0.0)
            float kept = 0.0
            int invalid = 0
            for row in rows
                float lo = row.down_price()
                float hi = row.up_price()
                float v = row.total_volume()
                if na(lo) or na(hi) or na(v) or hi <= lo or v < 0
                    invalid += 1
                else
                    kept += f_allocate(edges, changes, lo, hi, v)
                    f_gridAdd(today.detailEdges, today.detailChanges, lo, hi, v, priceLow, priceHigh, detailCount)
                    if historyMode == "All loaded history"
                        f_gridAdd(allDetailEdges, allDetailChanges, lo, hi, v, priceLow, priceHigh, detailCount)
            float running = 0.0
            for j = 0 to binCount - 1
                running += changes.get(j)
                float v = math.max(0.0, edges.get(j) + running)
                today.bins.set(j, today.bins.get(j) + v)
                if historyMode == "All loaded history"
                    allBins.set(j, allBins.get(j) + v)
            today.lensVolume += kept
            allLens += kept
            today.invalid += invalid
            allInvalid += invalid
 
f_selected() =>
    array<float> bins = array.new<float>(binCount, 0.0)
    float fullVolume = 0.0
    float expectedLens = 0.0
    int touches = 0
    int covered = 0
    int invalid = 0
    bool partial = false
    bool cut = false
    bool missingDays = false
    if historyMode == "All loaded history"
        bins := array.copy(allBins)
        fullVolume := allFull
        expectedLens := allLens
        touches := allTouches
        covered := allCovered
        invalid := allInvalid
        partial := allPartial
        cut := allCut
    else
        int first = historyMode == "Single session" ? days.size() - 1 - dayOffset : math.max(0, days.size() - previousDays - 1)
        int last = historyMode == "Single session" ? first : days.size() - 1
        missingDays := first < 0 or (historyMode == "Combined sessions" and loadedDays < previousDays + 1)
        if first >= 0
            for i = first to last
                DailyProfile d = days.get(i)
                fullVolume += d.fullVolume
                expectedLens += d.lensVolume
                touches += d.touches
                covered += d.covered
                invalid += d.invalid
                partial := partial or d.partial
                cut := cut or d.cut
                for j = 0 to binCount - 1
                    bins.set(j, bins.get(j) + d.bins.get(j))
    float total = array.sum(bins)
    bool badMass = math.abs(total - expectedLens) > math.max(1e-6, expectedLens * 1e-7)
    bool incomplete = partial or missingDays or touches > covered or cut
    bool usable = total > 0 and invalid == 0 and not badMass and (fpAllowPartial or not incomplete)
    int identity = historyMode == "Single session" and days.size() > dayOffset ? days.get(days.size() - 1 - dayOffset).key : days.last().key
    [bins, total, fullVolume, touches, covered, invalid, partial, cut, missingDays, badMass, incomplete, usable, identity]
 
f_detailSelected() =>
    array<float> edges = array.new<float>(detailCount, 0.0)
    array<float> changes = array.new<float>(detailCount, 0.0)
    if historyMode == "All loaded history"
        edges := array.copy(allDetailEdges)
        changes := array.copy(allDetailChanges)
    else
        int first = historyMode == "Single session" ? days.size() - 1 - dayOffset : math.max(0, days.size() - previousDays - 1)
        int last = historyMode == "Single session" ? first : days.size() - 1
        if first >= 0
            for i = first to last
                DailyProfile d = days.get(i)
                for j = 0 to detailCount - 1
                    edges.set(j, edges.get(j) + d.detailEdges.get(j))
                    changes.set(j, changes.get(j) + d.detailChanges.get(j))
    f_dense(edges, changes)
 
// Local profile geometry. Detection smoothing never feeds back into quantiles.
type ProfileNode
    int first
    int last
    int center
    int kind
    float prominence
    float volume
 
f_smooth(array<float> raw) =>
    array<float> sm = array.new<float>(binCount, 0.0)
    for j = 0 to binCount - 1
        float numerator = 0.0
        float denominator = 0.0
        for k = math.max(0, j - smoothRadius) to math.min(binCount - 1, j + smoothRadius)
            float w = smoothRadius + 1 - math.abs(k - j)
            numerator += raw.get(k) * w
            denominator += w
        sm.set(j, numerator / denominator)
    sm
 
f_nearFib(int first, int last, array<float> prices) =>
    float lo = priceLow + first * binSize - fibToleranceTicks * syminfo.mintick
    float hi = priceLow + (last + 1) * binSize + fibToleranceTicks * syminfo.mintick
    bool found = false
    for p in prices
        if p >= lo and p <= hi
            found := true
    found
 
f_nodes(array<float> raw, array<float> fibPrices) =>
    array<ProfileNode> candidates = array.new<ProfileNode>()
    array<ProfileNode> result = array.new<ProfileNode>()
    array<float> sm = f_smooth(raw)
    float peak = array.max(sm)
    float epsilon = math.max(1e-10, peak * 1e-9)
    float dust = array.sum(raw) * 1e-12
    int observedFirst = binCount
    int observedLast = -1
    for j = 0 to binCount - 1
        if raw.get(j) > dust
            observedFirst := math.min(observedFirst, j)
            observedLast := j
    float observedMinimum = array.max(raw)
    if observedLast >= observedFirst
        for k = observedFirst to observedLast
            observedMinimum := math.min(observedMinimum, raw.get(k))
    bool shaped = array.max(raw) - observedMinimum > epsilon
    if shaped and peak > 0 and observedLast - observedFirst >= 2
        int j = observedFirst + 1
        while j < observedLast
            float centerValue = sm.get(j)
            int end = j
            while end < observedLast and math.abs(sm.get(end + 1) - centerValue) <= epsilon
                end += 1
            if end < observedLast
                float leftNeighbor = sm.get(j - 1)
                float rightNeighbor = sm.get(end + 1)
                bool valley = centerValue < leftNeighbor - epsilon and centerValue < rightNeighbor - epsilon
                bool hill = centerValue > leftNeighbor + epsilon and centerValue > rightNeighbor + epsilon
                int kind = valley ? -1 : hill ? 1 : 0
                bool enabled = kind == -1 ? nodeMode != "HVN" : kind == 1 ? nodeMode != "LVN" : false
                if enabled and end - j + 1 <= maxZoneRows
                    float leftShoulder = kind == -1 ? 0.0 : peak
                    float rightShoulder = kind == -1 ? 0.0 : peak
                    for k = math.max(observedFirst, j - shoulderWindow) to j - 1
                        leftShoulder := kind == -1 ? math.max(leftShoulder, sm.get(k)) : math.min(leftShoulder, sm.get(k))
                    for k = end + 1 to math.min(observedLast, end + shoulderWindow)
                        rightShoulder := kind == -1 ? math.max(rightShoulder, sm.get(k)) : math.min(rightShoulder, sm.get(k))
                    float baseline = kind == -1 ? math.min(leftShoulder, rightShoulder) : math.max(leftShoulder, rightShoulder)
                    float prominence = kind == -1 ? (baseline > epsilon ? 100.0 * (baseline - centerValue) / baseline : 0.0) : 100.0 * (centerValue - baseline) / peak
                    bool strong = prominence >= minimumProminence and (kind == -1 or centerValue >= peak * minimumPeak / 100.0)
                    if strong
                        float threshold = kind == -1 ? centerValue + (baseline - centerValue) * zoneExpansion / 100.0 : centerValue - (centerValue - baseline) * zoneExpansion / 100.0
                        int first = j
                        int last = end
                        bool growing = true
                        while growing and last - first + 1 < maxZoneRows
                            bool canLeft = first > observedFirst and (kind == -1 ? sm.get(first - 1) <= threshold : sm.get(first - 1) >= threshold)
                            bool canRight = last < observedLast and (kind == -1 ? sm.get(last + 1) <= threshold : sm.get(last + 1) >= threshold)
                            if canLeft and canRight
                                bool preferLeft = kind == -1 ? sm.get(first - 1) <= sm.get(last + 1) : sm.get(first - 1) >= sm.get(last + 1)
                                if preferLeft
                                    first -= 1
                                else
                                    last += 1
                            else if canLeft
                                first -= 1
                            else if canRight
                                last += 1
                            else
                                growing := false
                        if nodeScope == "Whole lens" or f_nearFib(first, last, fibPrices)
                            float zoneVolume = 0.0
                            for k = first to last
                                zoneVolume += raw.get(k)
                            int center = int(math.floor((j + end) / 2.0))
                            candidates.push(ProfileNode.new(first, last, center, kind, prominence, zoneVolume))
            j := end + 1
    // Rank by prominence, keep at most maxNodes per kind, suppress overlaps.
    array<bool> consumed = array.new<bool>(candidates.size(), false)
    for kind = -1 to 1 by 2
        for slot = 0 to maxNodes - 1
            int best = -1
            float bestScore = -1.0
            if candidates.size() > 0
                for i = 0 to candidates.size() - 1
                    ProfileNode candidate = candidates.get(i)
                    if candidate.kind == kind and not consumed.get(i)
                        bool overlap = false
                        for chosen in result
                            if chosen.kind == kind and candidate.first <= chosen.last and candidate.last >= chosen.first
                                overlap := true
                        if not overlap and candidate.prominence > bestScore
                            bestScore := candidate.prominence
                            best := i
            if best >= 0
                result.push(candidates.get(best))
                consumed.set(best, true)
    result
 
// Locate a profile node on the volume-fib axis without moving a fib line.
f_volumeRatio(array<float> raw, float p, float total) =>
    float below = 0.0
    for j = 0 to binCount - 1
        float share = math.max(0.0, math.min(1.0, (p - (priceLow + j * binSize)) / binSize))
        below += raw.get(j) * share
    float ratioBelow = total > 0 ? below / total : na
    fromHigh ? 1.0 - ratioBelow : ratioBelow
 
f_context(float p, array<ProfileNode> nodes) =>
    string result = ""
    bool near = false
    for node in nodes
        float lo = priceLow + node.first * binSize
        float hi = priceLow + (node.last + 1) * binSize
        bool inside = p >= lo and p <= hi
        bool closeBy = p >= lo - fibToleranceTicks * syminfo.mintick and p <= hi + fibToleranceTicks * syminfo.mintick
        if closeBy
            string name = node.kind == -1 ? "LVN" : "HVN"
            result += (result == "" ? "" : "/") + (inside ? "" : "~") + name
            near := true
    [result, near]
 
type TextItem
    float price
    string content
    color col
    int anchorX = na
    int labelX = na
    bool nested = false
    bool mainFib = false
 
f_paintNested(array<box> boxes, array<float> source, float lo, float hi, int left, int width, int budget, array<color> palette, int opacity) =>
    int count = math.min(budget, source.size())
    array<float> merged = array.new<float>(count, 0.0)
    for j = 0 to count - 1
        int first = int(math.floor(float(j) * source.size() / count))
        int last = int(math.floor(float(j + 1) * source.size() / count)) - 1
        float v = 0.0
        for k = first to last
            v += source.get(k)
        merged.set(j, v)
    float peak = merged.max()
    int drawn = 0
    float total = merged.sum()
    float cumulative = 0.0
    if peak > 0 and width > 0
        for j = 0 to count - 1
            float v = merged.get(j)
            if v > 0
                int first = int(math.floor(float(j) * source.size() / count))
                int last = int(math.floor(float(j + 1) * source.size() / count))
                float lower = lo + (hi - lo) * first / source.size()
                float upper = lo + (hi - lo) * last / source.size()
                int w = math.max(1, int(math.round(width * v / peak)))
                float q = (cumulative + v * 0.5) / total
                q := fromHigh ? 1.0 - q : q
                color col = palette.get(math.max(0, math.min(7, int(math.floor(q * 8)))))
                boxes.push(box.new(left, upper, left + w, lower, border_color=na, bgcolor=color.new(col, opacity)))
                drawn += 1
            cumulative += v
    drawn
 
f_palette(string mapName, array<color> customColors) =>
    switch mapName
        "Violet" => array.from(#E9D5FF, #D8B4FE, #C084FC, #A78BFA, #818CF8, #6366F1, #A5B4FC, #C7D2FE)
        "Warm" => array.from(#FEF3C7, #FDE68A, #FCD34D, #FBBF24, #FB923C, #F97316, #F87171, #FDA4AF)
        "Custom" => customColors
        "Base" => array.from(mono, mono, mono, mono, mono, mono, mono, mono)
        => array.from(#93C5FD, #60A5FA, #38BDF8, #22D3EE, #2DD4BF, #34D399, #A3E635, #D9F99D)
 
f_nestedPalette() =>
    f_palette(nestedMap, array.from(nColor0, nColor1, nColor2, nColor3, nColor4, nColor5, nColor6, nColor7))
f_secondPalette() =>
    f_palette(n2Map, array.from(n2Color0, n2Color1, n2Color2, n2Color3, n2Color4, n2Color5, n2Color6, n2Color7))
 
type NestedProfile
    float low
    float high
    float total
    int rows
    array<float> bins
    bool valid
    string issue
 
// One reusable engine: quantile-defined bounds, direct fine-grid slice, own CDF.
f_buildNested(array<float> fine, array<float> parent, float parentLow, float parentHigh, float ratioA, float ratioB, int requested, bool ready) =>
    NestedProfile result = NestedProfile.new(parentLow, parentHigh, 0.0, 1, array.new<float>(1, 0.0), false, "parent profile unavailable")
    float parentTotal = parent.sum()
    if ready and parentTotal > 0
        if ratioA == ratioB
            result.issue := "choose two different parent fibs"
        else
            float boundA = f_quantileGrid(parent, ratioA, parentTotal, parentLow, parentHigh)
            float boundB = f_quantileGrid(parent, ratioB, parentTotal, parentLow, parentHigh)
            result.low := math.min(boundA, boundB)
            result.high := math.max(boundA, boundB)
            if result.high - result.low > syminfo.mintick * 1e-6
                result.rows := math.max(1, math.min(requested, int(math.floor((result.high - result.low) / detailSize + 1e-7))))
                result.bins := f_slice(fine, result.low, result.high, result.rows)
                result.total := result.bins.sum()
                result.valid := result.total > 0
                result.issue := result.valid ? "" : "no volume inside parent fib band"
            else
                result.issue := "parent fib bounds coincide; choose a wider band"
    result
 
f_drawNested(NestedProfile profile, string prefix, array<color> palette, int opacity, int left, int right, int projectionRight, int labelX, bool levelsOn, bool textOn, bool headingOn, array<bool> bandsOn, array<color> zoneColors, int zoneAlpha, array<float> ratios, array<bool> enabled, array<box> boxes, array<line> lines, array<TextItem> texts) =>
    if profile.valid
        array<float> boundsA = array.from(band1A, band2A)
        array<float> boundsB = array.from(band1B, band2B)
        for bi = 0 to 1
            if bandsOn.get(bi) and boundsA.get(bi) != boundsB.get(bi)
                float a = f_quantileGrid(profile.bins, boundsA.get(bi), profile.total, profile.low, profile.high)
                float b = f_quantileGrid(profile.bins, boundsB.get(bi), profile.total, profile.low, profile.high)
                boxes.push(box.new(left, math.max(a, b), projectionRight, math.min(a, b), border_color=na, bgcolor=color.new(zoneColors.get(bi), zoneAlpha)))
        f_paintNested(boxes, profile.bins, profile.low, profile.high, left, right - left, 100, palette, opacity)
        if showText and textOn and headingOn
            texts.push(TextItem.new(profile.high, prefix, palette.get(4), na, labelX, true))
        if levelsOn
            array<float> usedRatios = array.new<float>()
            for k = 0 to ratios.size() - 1
                float r = ratios.get(k)
                if enabled.get(k) and not usedRatios.includes(r)
                    usedRatios.push(r)
                    float value = f_quantileGrid(profile.bins, r, profile.total, profile.low, profile.high)
                    color col = palette.get(k)
                    lines.push(line.new(left, value, projectionRight, value, color=col, style=line.style_dotted, width=1))
                    if showText and textOn
                        texts.push(TextItem.new(value, prefix + " " + str.tostring(r, "0.###"), col, projectionRight, labelX, true))
    profile.valid
 
var array<line> drawingLines = array.new<line>()
var array<box> drawingBoxes = array.new<box>()
var array<label> drawingText = array.new<label>()
var array<TextItem> textItems = array.new<TextItem>()
var array<ProfileNode> cachedNodes = array.new<ProfileNode>()
var int cachedIdentity = na
 
if barstate.islast or barstate.islastconfirmedhistory
    [bins, total, fullVolume, touches, covered, invalid, partial, cut, missingDays, badMass, incomplete, usable, identity] = f_selected()
    array<float> ratios = array.from(r0, r1, r2, r3, r4, r5, r6, r7)
    array<bool> enabled = array.from(on0, on1, on2, on3, on4, on5, on6, on7)
    array<color> colors = array.from(fibColor0, fibColor1, fibColor2, fibColor3, fibColor4, fibColor5, fibColor6, fibColor7)
    array<float> fibPrices = array.new<float>()
    if usable
        for k = 0 to ratios.size() - 1
            if enabled.get(k)
                fibPrices.push(f_quantile(bins, ratios.get(k), total))
    array<ProfileNode> nodes = array.new<ProfileNode>()
    if showNodes and usable and covered >= minimumNodeBars
        if confirmedNodes
            if barstate.isconfirmed or barstate.islastconfirmedhistory
                cachedNodes := f_nodes(bins, fibPrices)
                cachedIdentity := identity
            if cachedIdentity == identity
                nodes := cachedNodes
        else
            nodes := f_nodes(bins, fibPrices)
    if barstate.islast
        for id in drawingLines
            line.delete(id)
        for id in drawingBoxes
            box.delete(id)
        for id in drawingText
            label.delete(id)
        drawingLines.clear()
        drawingBoxes.clear()
        drawingText.clear()
        textItems.clear()
        // Day profile stays right. Structural zones end at its LEFT spine
        // and extend into the chart, not beyond the histogram to the right.
        int laneStride = int(math.ceil(float(nestedLaneWidth + textGap) / labelColumnGap)) * labelColumnGap
        int nestedTextX = bar_index + textGap
        int n2TextX = nestedTextX + (subEnabled and subText and showText ? laneStride : 0)
        int profileLeft = bar_index + offsetBars + (subEnabled and subText and showText ? laneStride : 0) + (n2Enabled and n2Text and showText ? laneStride : 0)
        int lineLeft = math.max(0, profileLeft - projectionBars)
        int lineRight = profileLeft
        int profileRight = profileLeft + profileWidth
        int textX = profileRight + textGap
        int childRight = math.max(0, bar_index - subInsideGap)
        int childLeft = math.max(0, childRight - subWidth)
        int childProjectionRight = math.max(childRight, bar_index - 1)
        int secondRight = math.max(0, (subEnabled ? childLeft : bar_index) - n2Gap)
        int secondLeft = math.max(0, secondRight - n2Width)
        float textHalf = math.max(syminfo.mintick * 0.25, (priceHigh - priceLow) * 0.007)
        array<float> liveFine = array.new<float>()
        bool fineValid = false
        if (subEnabled or n2Enabled) and usable
            liveFine := f_detailSelected()
            fineValid := math.abs(liveFine.sum() - total) <= math.max(1e-6, total * 1e-7)
        bool comparisonUsable = false
        if compareDay and days.size() > comparisonOffset
            DailyProfile reference = days.get(days.size() - 1 - comparisonOffset)
            float refTotal = reference.bins.sum()
            bool refIncomplete = reference.partial or reference.cut or reference.touches > reference.covered
            bool refMassError = math.abs(refTotal - reference.lensVolume) > math.max(1e-6, reference.lensVolume * 1e-7)
            comparisonUsable := refTotal > 0 and reference.invalid == 0 and not refMassError and (fpAllowPartial or not refIncomplete)
            if comparisonUsable
                for k = 0 to ratios.size() - 1
                    if enabled.get(k)
                        float ratio = ratios.get(k)
                        float p = f_quantile(reference.bins, ratio, refTotal)
                        color c = useLevelColors ? colors.get(k) : mono
                        drawingLines.push(line.new(lineLeft, p, lineRight, p, color=color.new(c, comparisonAlpha), style=line.style_dashed, width=1))
                        if showText and compareText
                            string content = str.tostring(ratio, "0.###") + " S-" + str.tostring(comparisonOffset)
                            textItems.push(TextItem.new(p, content, color.new(c, comparisonAlpha), lineRight))
        if usable
            if showBackground
                drawingBoxes.push(box.new(lineLeft, priceHigh, profileLeft, priceLow, border_color=na, bgcolor=color.new(mono, backgroundAlpha)))
            array<bool> bandEnabled = array.from(band1, band2)
            array<float> bandStarts = array.from(band1A, band2A)
            array<float> bandEnds = array.from(band1B, band2B)
            array<color> bandColors = array.from(band1Color, band2Color)
            for k = 0 to 1
                if bandEnabled.get(k) and bandStarts.get(k) != bandEnds.get(k)
                    float a = f_quantile(bins, bandStarts.get(k), total)
                    float b = f_quantile(bins, bandEnds.get(k), total)
                    color c = bandColors.get(k)
                    drawingBoxes.push(box.new(lineLeft, math.max(a, b), profileLeft, math.min(a, b), border_color=na, bgcolor=color.new(c, bandAlpha)))
            for node in nodes
                float lo = priceLow + node.first * binSize
                float hi = priceLow + (node.last + 1) * binSize
                float center = priceLow + (node.center + 0.5) * binSize
                color c = node.kind == -1 ? lvnColor : hvnColor
                drawingBoxes.push(box.new(lineLeft, hi, profileLeft, lo, border_color=na, bgcolor=color.new(c, nodeAlpha)))
                if showNodeMarkers
                    drawingLines.push(line.new(lineLeft, center, lineRight, center, color=color.new(c, 45), style=line.style_dotted, width=1))
                if showText and showNodeText
                    string content = (node.kind == -1 ? "LVN" : "HVN") + " " + str.tostring(f_volumeRatio(bins, center, total), "0.000") + "  " + str.tostring(node.volume / total * 100.0, "0.0") + "%"
                    textItems.push(TextItem.new(center, content, c, lineRight))
            if showProfile
                float peak = array.max(bins)
                for j = 0 to binCount - 1
                    float v = bins.get(j)
                    if v > 0
                        int width = math.max(1, int(math.round(profileWidth * v / peak)))
                        drawingBoxes.push(box.new(profileLeft, priceLow + (j + 1) * binSize, profileLeft + width, priceLow + j * binSize, border_color=na, bgcolor=color.new(mono, profileAlpha)))
            if showGuides
                drawingLines.push(line.new(lineLeft, priceLow, lineRight, priceLow, color=color.new(mono, 65), style=line.style_dotted))
                drawingLines.push(line.new(lineLeft, priceHigh, lineRight, priceHigh, color=color.new(mono, 65), style=line.style_dotted))
            for k = 0 to ratios.size() - 1
                if enabled.get(k)
                    float ratio = ratios.get(k)
                    float p = f_quantile(bins, ratio, total)
                    color c = useLevelColors ? colors.get(k) : mono
                    [context, nearNode] = f_context(p, nodes)
                    int width = lineWidth + (annotateFib and nearNode ? 1 : 0)
                    float geometric = fromHigh ? priceHigh - ratio * (priceHigh - priceLow) : priceLow + ratio * (priceHigh - priceLow)
                    bool interior = ratio > 0 and ratio < 1
                    bool aligned = pvEnabled and interior and math.abs(p - geometric) <= pvToleranceTicks * syminfo.mintick
                    if pvEnabled and interior
                        if pvLines
                            drawingLines.push(line.new(lineLeft, geometric, profileLeft, geometric, color=color.new(pvColor, 35), style=line.style_dashed, width=1))
                        if pvBands and math.abs(p - geometric) > syminfo.mintick * 0.001
                            drawingBoxes.push(box.new(lineLeft, math.max(p, geometric), profileLeft, math.min(p, geometric), border_color=na, bgcolor=color.new(pvColor, pvAlpha)))
                    drawingLines.push(line.new(lineLeft, p, textX, p, color=c, style=f_style(lineType), width=width))
                    string content = textRatio ? str.tostring(ratio, "0.###") : ""
                    content += textVolume ? (content == "" ? "" : "  ") + str.tostring(ratio * total, format.volume) + " / " + str.tostring(total, format.volume) : ""
                    content += aligned and pvTag ? " P=V" : ""
                    content += annotateFib and context != "" ? (content == "" ? "" : "  ") + context : ""
                    if showText
                        if content == ""
                            content := str.tostring(ratio, "0.###")
                        textItems.push(TextItem.new(p, content, c, textX, na, false, true))
        string warning = missingDays ? "Requested sessions are not loaded" : cut ? "Chart candles cross the custom reset; use a lower aligned timeframe" : partial ? "Selected session is incomplete at the start of loaded history or reset" : touches > covered ? "Footprints missing on " + str.tostring(touches - covered) + " relevant bars" : ""
        warning := invalid > 0 or badMass ? "Footprint data check failed; levels hidden" : warning
        if total <= 0
            warning += (warning == "" ? "" : " · ") + "No footprint volume inside price range"
        if compareDay and not comparisonUsable
            warning += (warning == "" ? "" : " · ") + "Comparison session unavailable or incomplete"
        if showStatus and warning != ""
            float y = priceLow - textHalf * 4
            textItems.push(TextItem.new(y, warning, mono))
        string extraStatus = ""
        bool needFirst = subEnabled or (n2Enabled and n2Parent == "Nested N1")
        NestedProfile first = f_buildNested(liveFine, bins, priceLow, priceHigh, subA, subB, subRows, needFirst and usable and fineValid)
        if subEnabled
            f_drawNested(first, "N1", f_nestedPalette(), nestedAlpha, childLeft, childRight, childProjectionRight, nestedTextX, subLevels, subText, nestedHeading, array.from(n1Zone1, n1Zone2), array.from(n1Zone1Color, n1Zone2Color), n1ZoneAlpha, ratios, enabled, drawingBoxes, drawingLines, textItems)
            if not first.valid
                extraStatus := "N1: " + first.issue
        if n2Enabled
            bool cascade = n2Parent == "Nested N1"
            array<float> parentBins = cascade ? first.bins : bins
            float parentLow = cascade ? first.low : priceLow
            float parentHigh = cascade ? first.high : priceHigh
            bool parentReady = usable and fineValid and (not cascade or first.valid)
            NestedProfile secondP = f_buildNested(liveFine, parentBins, parentLow, parentHigh, n2A, n2B, n2Rows, parentReady)
            f_drawNested(secondP, "N2", f_secondPalette(), n2Alpha, secondLeft, secondRight, childProjectionRight, n2TextX, n2Levels, n2Text, n2Heading, array.from(n2Zone1, n2Zone2), array.from(n2Zone1Color, n2Zone2Color), n2ZoneAlpha, ratios, enabled, drawingBoxes, drawingLines, textItems)
            if not secondP.valid
                extraStatus += (extraStatus == "" ? "" : " · ") + "N2: " + (cascade and not first.valid ? "N1 parent: " + first.issue : secondP.issue)
        if showStatus and extraStatus != ""
            textItems.push(TextItem.new(priceLow - textHalf * 8, extraStatus, mono))
 
        // No vertical displacement: labels AND connectors stay on true price.
        // Horizontal columns handle close labels without slanted end segments.
        if textItems.size() > 0
            array<float> textPrices = array.new<float>()
            for item in textItems
                textPrices.push(item.price)
            array<int> sortedTextIndices = array.sort_indices(textPrices, order.ascending)
            map<int, float> lastPriceByColumn = map.new<int, float>()
            float threshold = math.max(textSpacingTicks * syminfo.mintick, math.max(nz(textATR, binSize) * 0.08, (priceHigh - priceLow) * textSpacingRange / 100.0))
            for index in sortedTextIndices
                TextItem item = textItems.get(index)
                int baseX = na(item.labelX) ? textX : item.labelX
                int x = baseX
                float y = item.price
                bool stagger = avoidTextOverlap or item.nested
                if stagger
                    int remaining = math.max(0, bar_index + 480 - baseX)
                    int columns = math.min(textItems.size(), int(math.floor(float(remaining) / labelColumnGap)) + 1)
                    bool placed = false
                    for column = 0 to columns - 1
                        int candidateX = baseX + column * labelColumnGap
                        float lastPrice = lastPriceByColumn.get(candidateX)
                        if na(lastPrice) or item.price - lastPrice >= threshold
                            x := candidateX
                            placed := true
                            break
                    // If all allowed columns are occupied, retain true price;
                    // never exceed Pine's future-coordinate limit or bend a line.
                    if not placed
                        x := baseX
                color c = item.nested ? color.new(item.col, 0) : readableText ? chart.fg_color : color.new(item.col, 0)
                drawingText.push(label.new(x=x, y=y, text=item.content, xloc=xloc.bar_index, yloc=yloc.price, color=color.new(c, 100), style=label.style_label_left, textcolor=c, size=f_size(item.nested ? nestedTextSize : textSize), textalign=text.align_left, text_font_family=font.family_monospace, tooltip=item.content, force_overlay=true))
                if item.mainFib
                    if x > baseX
                        drawingLines.push(line.new(baseX, item.price, x, item.price, color=item.col, style=f_style(lineType), width=lineWidth))
                else if not na(item.anchorX)
                    drawingLines.push(line.new(item.anchorX, item.price, x, item.price, color=color.new(item.col, 55), style=line.style_dotted, width=1))
                lastPriceByColumn.put(x, item.price)

← 返回列表