Order Flow Candle Classifier [BullByte]

BullByte · study · 1333 行 · 点赞 399 · TradingView 原页

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

Pine Script

//@version=6
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BullByte
//
// ORDER FLOW CANDLE CLASSIFIER [BULLBYTE]
//
// WHY THIS INDICATOR WAS BUILT
// A candle shows where price travelled and where it finished. Volume shows how much
// activity accompanied that move, but volume alone does not explain whether price
// accepted the move, rejected it or made little progress despite heavy activity.
// OFCC brings those clues together so a trader can read participation, price response
// and the higher-timeframe backdrop as one picture instead of isolated signals.
//
// WHAT IT BRINGS TOGETHER
// • Participation: TradingView's native footprint data, or a clearly marked OHLCV estimate.
// • Price response: candle direction, body, wicks, close location and recent auction behaviour.
// • Context: higher-timeframe direction, nearby structure, cumulative delta and divergence.
// • Interpretation: a compact candle role that describes the strongest observed behaviour.
//
// TWO SOURCES, TWO DIFFERENT LEVELS OF EVIDENCE
// Estimated OHLCV assigns volume using lower-timeframe candle direction where available.
// When smaller candles are unavailable, it uses the chart candle's close location. Both
// methods are estimates; neither reveals the aggressor flag of each individual trade.
// TradingView Footprint mode uses the native footprint rows and their buy/sell values,
// imbalances, per-candle POC and value area. It still does not reconstruct the full
// exchange order book or provide a direct record of every buyer-initiated/seller-initiated trade.
// The two sources are therefore kept separate and are never presented as interchangeable.
//
// HOW TO READ THE RESULT
// Treat each role as a description of the candle and its context, not as a forecast or
// instruction to trade. Hover the chart labels and monitor cells for the calculation
// details. Estimated buy/sell allocations and their derived delta values carry a ~ marker;
// provider-reported total volume does not. Native-only measurements are never invented.
// when Estimated OHLCV is selected or when footprint data is unavailable.
//
// DATA BEHAVIOUR
// Chart labels and alerts use confirmed chart candles. This avoids reporting a role before
// the chart candle closes, but it cannot guarantee immutable history: data providers can
// revise lower-timeframe or historical values, and intrabar coverage varies by plan/feed.
// Reloading a chart can therefore change earlier estimates when the source data is revised.
//
// DISCLAIMER
// For informational and educational purposes only. This indicator is not financial
// advice, does not predict outcomes and does not guarantee trading results. Trading
// involves substantial risk. Market data, volume units and historical coverage depend
// on the symbol, exchange, broker and TradingView data feed. Check the selected source,
// understand its limitations and independently verify results before making decisions.
//
indicator("Order Flow Candle Classifier [BullByte]", shorttitle = "OFCC [BullByte]", overlay = false, max_labels_count = 500, dynamic_requests = true)
 
// INPUTS
 
grpSource = "Data Source"
dataSourceInput = input.string("Estimated OHLCV", "Order-flow data source", options = ["Estimated OHLCV", "TradingView Footprint (Premium/Ultimate)"], group = grpSource, display = display.none, tooltip = "Estimated OHLCV is the default. TradingView Footprint uses native footprint data and requires a Premium or Ultimate plan. The same dashboard switches its two source-specific metrics when you change this setting.")
bool useNativeFootprint = dataSourceInput == "TradingView Footprint (Premium/Ultimate)"
 
grpFP = "Footprint Engine"
footprintTicksInput = input.int(100, "Footprint ticks per row", minval = 1, group = grpFP, active = useNativeFootprint, display = display.none, tooltip = "Price height of each native footprint row, expressed in symbol ticks. Smaller values create more rows and finer price detail, but can increase memory and processing requirements. Increase this value if TradingView reports memory limits exceeded; larger rows reduce price detail. Used only in Footprint mode.")
vaPercentInput = input.int(70, "Value Area %", minval = 1, maxval = 99, group = grpFP, active = useNativeFootprint, display = display.none, tooltip = "Percentage of native footprint volume included in the value area. Used for native VAH/VAL rows only.")
imbalancePercentInput = input.int(300, "Diagonal imbalance threshold %", minval = 100, maxval = 1000, group = grpFP, active = useNativeFootprint, display = display.none, tooltip = "Diagonal buy/sell row imbalance threshold passed to TradingView's native footprint request.")
initStackCountInput = input.int(2, "Stack-strength scale (Initiative confirm)", minval = 1, group = grpFP, active = useNativeFootprint, display = display.none, tooltip = "Scales native stack strength as longest stack divided by twice this value. The initiative gate accepts stack strength of 0.75 or higher.")
 
grpEstimator = "Estimated OHLCV Engine"
ltfModeInput = input.string("Auto", "Intrabar timeframe mode", options = ["Auto", "Custom"], group = grpEstimator, active = not useNativeFootprint, display = display.none, tooltip = "Auto uses 1-minute intrabars on intraday charts, 5-minute intrabars on daily charts and 60-minute intrabars on weekly/monthly charts. Auto never selects seconds. On a 1-minute chart, Auto has no smaller bars and uses the disclosed chart-candle allocation.")
ltfCustomInput = input.timeframe("1", "Custom intrabar timeframe", group = grpEstimator, active = not useNativeFootprint and ltfModeInput == "Custom", display = display.none, tooltip = "Must be strictly lower than the chart timeframe. Seconds are manual only and depend on plan, symbol and available history.")
 
grpVerdict = "Character Engine"
deltaThreshPct = input.float(4.0, "Initiative Delta Threshold %", minval = 1.0, step = 0.5, group = grpVerdict, display = display.none, tooltip = "Minimum absolute delta percentage used by initiative and estimated-flow candidate rules.")
relativeVolumeThresholdInput = input.float(1.30, "Elevated participation threshold (x)", minval = 0.5, maxval = 5.0, step = 0.05, group = grpVerdict, display = display.none, tooltip = "Current volume divided by its 14-bar average must reach this multiple for elevated-participation checks.")
trapLookbackInput = input.int(10, "Trap breakout lookback", minval = 2, group = grpVerdict, display = display.none, tooltip = "Previous-bar range used to identify failed breaks beyond the recent high or low.")
 
grpDivergence = "Delta Divergence"
pivotLeftBarsInput = input.int(3, "Pivot Left Bars", minval = 1, maxval = 50, group = grpDivergence, display = display.none, tooltip = "Completed candles to the left of a candidate pivot. Higher values identify broader swings.")
pivotRightBarsInput = input.int(2, "Pivot Right Bars", minval = 1, maxval = 50, group = grpDivergence, display = display.none, tooltip = "Completed candles required to confirm a pivot. The divergence marker and alert appear on the confirmation candle, not on the earlier pivot candle.")
exhVelocityThreshInput = input.float(0.25, "Exhaustion Delta Velocity Threshold", minval = 0.05, step = 0.05, group = grpVerdict, active = useNativeFootprint, display = display.none, tooltip = "Native-footprint delta change, normalised by current total volume, used by the exhaustion score. Footprint mode only.")
charMinScoreInput = input.float(0.58, "Minimum classifier score", minval = 0.40, maxval = 0.90, step = 0.01, group = grpVerdict, active = useNativeFootprint, display = display.none, tooltip = "Threshold for scored Footprint candidates: TRAP, directional response/absorption, exhaustion and initiative. Neutral absorption is a separate rule-based exception with a fixed 0.50 score; continuation and pullback are auction-state fallbacks. This is not a probability.")
auctionLookbackInput = input.int(8, "Auction state lookback", minval = 3, maxval = 30, group = grpVerdict, display = display.none, tooltip = "Bars used to measure recent path efficiency and directional persistence.")
auctionStateThresholdInput = input.float(0.58, "Auction state threshold", minval = 0.45, maxval = 0.85, step = 0.01, group = grpVerdict, display = display.none, tooltip = "Minimum weighted efficiency/persistence score for an upward or downward auction state.")
 
grpTrend = "Trend Context (HTF + Structure)"
autoHTFInput = input.bool(true, "Auto HTF", group = grpTrend, display = display.none, tooltip = "Automatically derives the higher timeframe from the chart timeframe and multiplier.")
htfMultInput = input.int(10, "Auto HTF multiplier", minval = 2, group = grpTrend, active = autoHTFInput, display = display.none, tooltip = "Higher-timeframe multiplier used when Auto HTF is enabled.")
manualHTFInput = input.timeframe("60", "Manual HTF", group = grpTrend, active = not autoHTFInput, display = display.none, tooltip = "Manual higher timeframe. It must be strictly higher than the chart timeframe.")
pivotLenInput = input.int(10, "Structure lookback", minval = 2, maxval = 100, group = grpTrend, display = display.none, tooltip = "Previous-bar lookback used for the simple structure break check.")
 
grpCVD = "CVD Trend & Flow Confirmation"
cvdTrendLenInput = input.int(8, "CVD Trend EMA Length (bars)", minval = 2, group = grpCVD, display = display.none, tooltip = "EMA length applied to the daily-reset cumulative delta series.")
flowConfirmLookbackInput = input.int(8, "Flow Confirmation Lookback (bars)", minval = 2, maxval = 100, group = grpCVD, display = display.none, tooltip = "Number of confirmed chart bars in the dominant-flow window (maximum 100). Bars without valid flow occupy a slot but do not count as bullish or bearish flow.")
grpPOC = "POC Drift"
pocDriftTicksInput = input.float(1.0, "POC Drift Min Move (ticks)", minval = 0.1, step = 0.5, group = grpPOC, active = useNativeFootprint, display = display.none, tooltip = "UP or DOWN requires this many ticks between adjacent native per-candle POCs. Missing current or previous POC returns N/A. Native footprint mode only.")
 
grpDisplay = "Display - History Monitor"
displayLayoutInput = input.string("Full", "Layout", options = ["Compact", "Full"], group = grpDisplay, display = display.none, tooltip = "Full shows the selected history count. Compact shows the latest five completed candles.")
historyBarsInput = input.int(18, "History bars in Full layout", minval = 5, maxval = 30, group = grpDisplay, active = displayLayoutInput == "Full", display = display.none, tooltip = "Number of completed candles shown in Full layout. Default is 18; maximum is 30.")
showOrderFlowMonitorInput = input.bool(true, "Show Order Flow Monitor", group = grpDisplay, display = display.none, tooltip = "Show or hide the history monitor in the indicator's separate pane. Its position is fixed within that pane.")
showVaLinesInput = input.bool(false, "Show native VAH/VAL lines", group = grpDisplay, active = useNativeFootprint, display = display.none, tooltip = "Plots native Value Area High and Low on the price chart. Available only when TradingView Footprint is selected on a Premium or Ultimate plan; no VA lines are fabricated in Estimated OHLCV mode.")
showBarLabelsInput = input.bool(true, "Show candle and divergence labels", group = grpDisplay, display = display.none, tooltip = "Show the primary candle role and any separate bullish/bearish divergence marker on confirmed candles. Divergence never replaces the main candle role.")
showTooltipInput = input.bool(true, "Show candle data tooltip marker", group = grpDisplay, display = display.none, tooltip = "Adds a small marker below confirmed candles. Hover it for selected volume, delta, source-specific metrics and CVD availability.")
showModeBadgeInput = input.bool(true, "Show data-source badge",group = grpDisplay,display = display.none,tooltip = "Show or hide the small data-source badge at the bottom-right of the main price chart.")
 
grpSummary = "Display - Chart Dashboard"
showSummaryDashboardInput = input.bool(true, "Show chart dashboard", group = grpSummary, display = display.none, tooltip = "Show or hide the summary dashboard on the main price chart. This does not affect the Order Flow Monitor.")
summaryPositionInput = input.string("Top Right", "Dashboard Position", options = ["Bottom Left","Bottom Center","Bottom Right","Top Left","Top Center","Top Right","Middle Left","Middle Center","Middle Right"], group = grpSummary, active = showSummaryDashboardInput, display = display.none, tooltip = "Position of the chart dashboard on the main price chart.")
summarySizeInput = input.string("Small", "Dashboard Text Size", options = ["Tiny","Small","Normal","Large","Huge"], group = grpSummary, active = showSummaryDashboardInput, display = display.none, tooltip = "Text size for the summary dashboard. Compact history layout also reduces dashboard text size.")
summaryBgInput = input.color(color.new(#131722, 10), "Background Color", group = grpSummary, active = showSummaryDashboardInput, display = display.none, tooltip = "Background used by the summary dashboard and its neutral footer.")
summaryBordInput = input.color(color.new(#363a45, 0), "Border Color", group = grpSummary, active = showSummaryDashboardInput, display = display.none, tooltip = "Border colour for the summary dashboard.")
int visibleHistoryBars = displayLayoutInput == "Compact" ? 5 : historyBarsInput
string historyTimezone = syminfo.timezone
string historyTimeFormat = timeframe.isintraday ? (timeframe.in_seconds() <= 60 ? "HH:mm:ss" : "HH:mm") : "dd MMM"
 
// COLOUR PALETTE
// Teal marks buying or upward behaviour; coral red marks selling or downward behaviour.
// Blue is used for response/absorption, amber for exhaustion, cyan for failed auctions,
// violet for divergence, slate for balance and gold for the current LIVE column.
// The dashboard and monitor keep dark panels with high-contrast text. Chart labels use
// lighter or darker colours according to the chart background so they remain readable.
 
c_buy      = color.new(#26a69a, 0)
c_sell     = color.new(#ef5350, 0)
c_bull     = color.new(#147D72, 0)
c_bear     = color.new(#B8323B, 0)
c_abs      = color.new(#2855A6, 0)
c_exht     = color.new(#9A5700, 0)
c_trap     = color.new(#006B80, 0)
c_div      = color.new(#713E91, 0)
c_chp      = color.new(#475569, 0)
c_headerBg = color.new(#1e222d, 0)
c_titleBg  = color.new(#131722, 0)
c_liveBg   = color.new(#2a2e39, 0)
c_accent   = color.new(#ffb300, 0)
c_muted    = color.new(#787b86, 70)
 
// These names keep the same colour meanings consistent across the dashboard and monitor.
color cBuy = c_buy
color cSell = c_sell
color cWhite = color.white
color cNeutral = color.new(#c7cdd6, 0)
color cBlue = color.new(#477fe0, 18)
color cGold = c_accent
color cHeader = c_headerBg
color cPanel = c_titleBg
color cLiveBg = c_liveBg
 
// SMALL DISPLAY HELPERS
// These functions keep table placement, role format, colour contrast and number formats
// consistent. They do not change how a candle is classified.
 
f_tablePos(string p) =>
    switch p
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        "Bottom Right"  => position.bottom_right
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Right"  => position.middle_right
        => position.middle_center
f_charColor(string code) =>
    switch code
        "BULL" => c_bull
        "BEAR" => c_bear
        "ABS" => c_abs
        "EXHT" => c_exht
        "TRAP" => c_trap
        "DIV" => c_div
        => c_chp
f_roleTextColor(string roleText) =>
    switch roleText
        "INIT BUY" => c_bull
        "EST INIT BUY" => c_bull
        "UP RESPONSE" => c_bull
        "FAILED LOW" => c_bull
        "CONT UP" => c_bull
        "UP AUCTION" => c_bull
        "PULL UP" => c_bull
        "INIT SELL" => c_bear
        "EST INIT SELL" => c_bear
        "DOWN RESPONSE" => c_bear
        "FAILED HIGH" => c_bear
        "CONT DOWN" => c_bear
        "DOWN AUCTION" => c_bear
        "PULL DOWN" => c_bear
        "BUYER RESPONSE" => c_abs
        "SELLER RESPONSE" => c_abs
        "BALANCED ABSORPTION" => c_abs
        "BUYER EXHAUSTION" => c_exht
        "SELLER EXHAUSTION" => c_exht
        "TRAP BUY" => c_trap
        "TRAP SELL" => c_trap
        "BALANCE" => cNeutral
        "N/A" => cNeutral
        => cNeutral
f_monitorRole(string roleText) =>
    switch roleText
        "BUYER RESPONSE" => "BUYER\nRESPONSE"
        "SELLER RESPONSE" => "SELLER\nRESPONSE"
        "BALANCED ABSORPTION" => "BALANCED\nABSORPTION"
        "BUYER EXHAUSTION" => "BUYER\nEXHAUSTION"
        "SELLER EXHAUSTION" => "SELLER\nEXHAUSTION"
        "UP RESPONSE" => "UP\nRESPONSE"
        "DOWN RESPONSE" => "DOWN\nRESPONSE"
        "EST INIT BUY" => "EST INIT\nBUY"
        "EST INIT SELL" => "EST INIT\nSELL"
        "INIT BUY" => "INIT\nBUY"
        "INIT SELL" => "INIT\nSELL"
        "TRAP BUY" => "TRAP\nBUY"
        "TRAP SELL" => "TRAP\nSELL"
        "FAILED HIGH" => "FAILED\nHIGH"
        "FAILED LOW" => "FAILED\nLOW"
        "UP AUCTION" => "UP\nAUCTION"
        "DOWN AUCTION" => "DOWN\nAUCTION"
        "CONT DOWN" => "CONT\nDOWN"
        "PULL DOWN" => "PULL\nDOWN"
        => roleText
f_chartLabelColor(string code, int direction) =>
    float chartLuminance = (color.r(chart.bg_color) * 0.2126 + color.g(chart.bg_color) * 0.7152 + color.b(chart.bg_color) * 0.0722) / 255.0
    bool lightChart = chartLuminance > 0.52
    color bullText = lightChart ? color.rgb(0, 105, 92) : color.rgb(38, 166, 154)
    color bearText = lightChart ? color.rgb(183, 28, 28) : color.rgb(239, 83, 80)
    color blueText = lightChart ? color.rgb(21, 101, 192) : color.rgb(68, 133, 255)
    color orangeText = lightChart ? color.rgb(160, 75, 0) : color.rgb(255, 167, 38)
    color cyanText = lightChart ? color.rgb(0, 105, 120) : color.rgb(0, 188, 212)
    color purpleText = lightChart ? color.rgb(106, 27, 154) : color.rgb(186, 104, 200)
    switch code
        "BULL" => bullText
        "BEAR" => bearText
        "CONT" => direction > 0 ? bullText : direction < 0 ? bearText : chart.fg_color
        "PULL" => direction > 0 ? bullText : direction < 0 ? bearText : chart.fg_color
        "ABS" => blueText
        "EXHT" => orangeText
        "TRAP" => cyanText
        "DIV" => purpleText
        => chart.fg_color
f_contrastText(color bg) =>
    float luminance = (color.r(bg) * 0.2126 + color.g(bg) * 0.7152 + color.b(bg) * 0.0722) / 255.0
    luminance > 0.52 ? color.rgb(24, 29, 38) : color.white
f_formatVol(float v) =>
    float absV = math.abs(v)
    float div  = absV >= 1000000000 ? 1000000000 : absV >= 1000000 ? 1000000 : absV >= 1000 ? 1000 : 1
    string suf = absV >= 1000000000 ? "B" : absV >= 1000000 ? "M" : absV >= 1000 ? "K" : ""
    str.tostring(v / div, suf == "" ? "#.#" : "#.##") + suf
f_tableSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        "Huge"   => size.huge
        => size.tiny
f_tableSizeBump(string s) =>
    switch s
        "Tiny"   => size.small
        "Small"  => size.normal
        "Normal" => size.large
        "Large"  => size.huge
        "Huge"   => size.huge
        => size.small
sumSize    = f_tableSize(summarySizeInput)
sumSizeBig = f_tableSizeBump(summarySizeInput)
 
// MARKET BACKDROP - HIGHER-TIMEFRAME TREND AND RECENT STRUCTURE
// The trend uses the last completed higher-timeframe candle, so it does not change while
// that higher-timeframe candle is still forming. Structure compares price with recent
// highs and lows; it is context for the candle, not a standalone buy/sell signal.
 
chartTFSeconds = timeframe.in_seconds()
autoHTFString = timeframe.from_seconds(chartTFSeconds * htfMultInput)
htfToUse = autoHTFInput ? autoHTFString : manualHTFInput
htfSeconds = timeframe.in_seconds(htfToUse)
if barstate.isfirst and (na(htfSeconds) or htfSeconds <= chartTFSeconds)
    runtime.error("HTF must be higher than the chart timeframe.")
[htfClose, htfEma20, htfEma50] = request.security(
     syminfo.tickerid,
     htfToUse,
     [close[1], ta.ema(close, 20)[1], ta.ema(close, 50)[1]],
     gaps = barmerge.gaps_off,
     lookahead = barmerge.lookahead_on)
htfBullish = htfEma20 > htfEma50 and htfClose > htfEma20
htfBearish = htfEma20 < htfEma50 and htfClose < htfEma20
regimeCode = htfBullish ? "UP" : htfBearish ? "DOWN" : "BAL"
string htfText = htfBullish ? "Bullish" : htfBearish ? "Bearish" : "Balanced"
regimeColor = htfBullish ? c_bull : htfBearish ? c_bear : c_chp
structureHigh = ta.highest(high[1], pivotLenInput)
structureLow = ta.lowest(low[1], pivotLenInput)
structureCode = close > structureHigh ? "UP" : close < structureLow ? "DOWN" : "RANGE"
 
// TRADINGVIEW FOOTPRINT DATA
// This branch runs only when the user selects the native Footprint source. Buy/sell
// volume, delta, footprint rows and value-area levels come from TradingView's footprint
// object. The default Estimated OHLCV mode does not call this data source.
 
// Keep one native footprint request and call it only when Footprint mode is selected.
footprint fp = na
if useNativeFootprint
    fp := request.footprint(
        footprintTicksInput,
        vaPercentInput,
        imbalancePercentInput)
haveFP = not na(fp)
fpBuyVol   = haveFP ? fp.buy_volume()   : na
fpSellVol  = haveFP ? fp.sell_volume()  : na
fpTotalVol = haveFP ? fp.total_volume() : na
fpDelta    = haveFP ? fp.delta()        : na
nativeDeltaPct = (haveFP and fpTotalVol > 0) ? fpDelta / fpTotalVol * 100 : na
volume_row pocRow = haveFP ? fp.poc() : na
volume_row vahRow = haveFP ? fp.vah() : na
volume_row valRow = haveFP ? fp.val() : na
pocPrice = not na(pocRow) ? (pocRow.up_price() + pocRow.down_price()) * 0.5 : na
vahPrice = not na(vahRow) ? vahRow.up_price() : na
valPrice = not na(valRow) ? valRow.down_price() : na
 
// ESTIMATED OHLCV - DIRECTIONAL VOLUME ESTIMATE
// Auto uses 1-minute candles on intraday charts, 5-minute candles on daily charts and
// 60-minute candles on weekly/monthly charts. It never chooses seconds automatically.
// A selected lower-timeframe candle is assigned to the buy or sell side by its direction.
// Dojis use their change from the previous intrabar close; an unchanged doji carries the
// last direction, or splits its volume evenly when no direction is known yet.
//
// If no smaller candles are available (for example, a 1-minute chart using Auto), chart
// volume is divided by the candle's close location. That estimate comes from price itself,
// so it is not independent proof of buying or selling pressure. It is never used as a
// replacement for native footprint rows, POC, diagonal imbalance or CVD confirmation.
 
// Reuse the chart interval calculated above so both timeframe checks use the same value.
string autoLtfString = timeframe.isintraday ? "1" : timeframe.isdaily ? "5" : "60"
string lowerTfToUse = ltfModeInput == "Auto" ? autoLtfString : ltfCustomInput
int lowerTFSeconds = timeframe.in_seconds(lowerTfToUse)
bool requestedTrueLowerTF = not na(lowerTFSeconds) and lowerTFSeconds < chartTFSeconds
if barstate.isfirst and not chart.is_standard
    runtime.error("Order Flow Candle Classifier requires a standard time-based chart. Synthetic chart types are not supported for price-response classification.")
if barstate.isfirst and not useNativeFootprint and ltfModeInput == "Custom" and (na(lowerTFSeconds) or lowerTFSeconds >= chartTFSeconds)
    runtime.error("Custom intrabar timeframe must be lower than the chart timeframe. Select a smaller interval or use Auto.")
 
// On a 1-minute chart, Auto also selects 1 minute. There are then no smaller candles
// to inspect, so the estimate falls back to the chart candle's close location.
int intrabarCount = 0
int validIntrabarCount = 0
float rawIntrabarVolume = 0.0
float rawIntrabarBuy = 0.0
float rawIntrabarSell = 0.0
var int priorIntrabarDirection = 0
 
// Footprint mode does not request or process OHLCV intrabars. Pine v6 permits this
// lower-timeframe request inside the selected source branch.
if not useNativeFootprint
    [ltfOpen, ltfClose, ltfPrevClose, ltfVolume] = request.security_lower_tf(
         syminfo.tickerid,
         lowerTfToUse,
         [open, close, close[1], volume],
         ignore_invalid_timeframe = true)
    intrabarCount := array.size(ltfOpen)
    if requestedTrueLowerTF and intrabarCount > 0
        for intrabarIndex = 0 to intrabarCount - 1
            float iOpen = array.get(ltfOpen, intrabarIndex)
            float iClose = array.get(ltfClose, intrabarIndex)
            float iPrevClose = array.get(ltfPrevClose, intrabarIndex)
            float iVolume = array.get(ltfVolume, intrabarIndex)
            bool validIntrabar = not na(iOpen) and not na(iClose) and not na(iVolume) and iVolume > 0
            if validIntrabar
                validIntrabarCount += 1
                int iDirection = priorIntrabarDirection
                if iClose > iOpen
                    iDirection := 1
                else if iClose < iOpen
                    iDirection := -1
                else if not na(iPrevClose) and iClose > iPrevClose
                    iDirection := 1
                else if not na(iPrevClose) and iClose < iPrevClose
                    iDirection := -1
                float iBuyVolume = iDirection > 0 ? iVolume : iDirection < 0 ? 0.0 : iVolume * 0.5
                float iSellVolume = iDirection < 0 ? iVolume : iDirection > 0 ? 0.0 : iVolume * 0.5
                priorIntrabarDirection := iDirection
                rawIntrabarVolume += iVolume
                rawIntrabarBuy += iBuyVolume
                rawIntrabarSell += iSellVolume
if validIntrabarCount == 0
    priorIntrabarDirection := 0
bool hasChartVolume = not na(volume) and volume > 0
bool hasIntrabarDirectionEstimate = not useNativeFootprint and requestedTrueLowerTF and rawIntrabarVolume > 0
bool hasEstimatedVolume = hasChartVolume or rawIntrabarVolume > 0
float estimatedTotalVolume = hasChartVolume ? volume : rawIntrabarVolume
 
// Scale the lower-timeframe buy/sell estimate to the chart's reported total volume.
// This keeps the two sides adding back to the volume shown on the chart candle.
float intrabarScale = hasChartVolume and rawIntrabarVolume > 0 ? volume / rawIntrabarVolume : 1.0
float estimatedBuyVolume = hasIntrabarDirectionEstimate ? rawIntrabarBuy * intrabarScale : na
float estimatedSellVolume = hasIntrabarDirectionEstimate ? rawIntrabarSell * intrabarScale : na
 
// When smaller candles are unavailable, split chart volume by close location. Because
// the estimate is derived from the same candle's price, it cannot confirm its own flow.
float chartCloseLocation = high > low ? (close - low) / (high - low) : 0.5
float proxyBuyShare = math.max(0.0, math.min(1.0, chartCloseLocation))
if not useNativeFootprint and not hasIntrabarDirectionEstimate and hasChartVolume
    estimatedBuyVolume := volume * proxyBuyShare
    estimatedSellVolume := volume - estimatedBuyVolume
float estimatedDelta = hasEstimatedVolume and not na(estimatedBuyVolume) and not na(estimatedSellVolume) ? estimatedBuyVolume - estimatedSellVolume : na
float estimatedDeltaPct = hasEstimatedVolume and estimatedTotalVolume > 0 and not na(estimatedDelta) ? estimatedDelta / estimatedTotalVolume * 100.0 : na
 
// Estimated mode has its own price measures: the current directional run and
// the close's location in the candle range. Neither is described as a footprint statistic.
var int directionalRunBars = 0
int sharedBarDirection = close > open ? 1 : close < open ? -1 : 0
if sharedBarDirection == 0
    directionalRunBars := 0
else if sharedBarDirection == nz(sharedBarDirection[1], 0)
    directionalRunBars += 1
else
    directionalRunBars := 1
string directionalRunText = sharedBarDirection > 0 ? "UP x" + str.tostring(directionalRunBars) : sharedBarDirection < 0 ? "DOWN x" + str.tostring(directionalRunBars) : "NO RUN"
string directionalRunShort = sharedBarDirection > 0 ? "UP " + str.tostring(directionalRunBars) : sharedBarDirection < 0 ? "DN " + str.tostring(directionalRunBars) : "NONE"
string closeAcceptanceBand = chartCloseLocation >= 0.67 ? "UPPER" : chartCloseLocation <= 0.33 ? "LOWER" : "MIDDLE"
string closeAcceptanceText = closeAcceptanceBand + " " + str.tostring(chartCloseLocation * 100.0, "#.0") + "%"
string closeAcceptanceShort = (closeAcceptanceBand == "UPPER" ? "UP " : closeAcceptanceBand == "LOWER" ? "LOW " : "MID ") + str.tostring(chartCloseLocation * 100.0, "#.0")
 
// NATIVE BUY/SELL IMBALANCE STACKS
// Count the longest uninterrupted run of native footprint rows marked as imbalanced.
// A stack counts adjacent price rows, not bullish/bearish candles.
int maxBuyStack = 0
int maxSellStack = 0
if haveFP
    array<volume_row> rowsArr = fp.rows()
    int nRows = array.size(rowsArr)
    if nRows > 0
        int curBuy = 0
        int curSell = 0
        for i = 0 to nRows - 1
            volume_row r = array.get(rowsArr, i)
            if r.has_buy_imbalance()
                curBuy += 1
                maxBuyStack := math.max(maxBuyStack, curBuy)
            else
                curBuy := 0
            if r.has_sell_imbalance()
                curSell += 1
                maxSellStack := math.max(maxSellStack, curSell)
            else
                curSell := 0
 
// ONE SELECTED SOURCE FOR THE SHARED DASHBOARD
// From this point on, the dashboard and monitor read the selected buy, sell, delta and
// delta-percent values from one place. Native-only calculations stay native-only; the
// two source-specific metric slots change their names when the source is changed.
 
float selectedBuyVolume = useNativeFootprint ? fpBuyVol : estimatedBuyVolume
float selectedSellVolume = useNativeFootprint ? fpSellVol : estimatedSellVolume
float selectedTotalVolume = useNativeFootprint ? fpTotalVol : estimatedTotalVolume
float selectedDelta = useNativeFootprint ? fpDelta : estimatedDelta
float selectedDeltaPct = useNativeFootprint ? nativeDeltaPct : estimatedDeltaPct
bool selectedVolumeAvailable = useNativeFootprint ? haveFP : hasEstimatedVolume
bool flowEvidenceAvailable = useNativeFootprint ? haveFP : hasIntrabarDirectionEstimate
deltaPct = selectedDeltaPct
string metric5Label = useNativeFootprint ? "Imbalance\nStacks (B/S)" : "Directional\nRun"
string metric6Label = useNativeFootprint ? "POC\nShift" : "Close\nAcceptance"
string metric5HistoryLabel = useNativeFootprint ? "B/S STACKS" : "RUN"
string metric6HistoryLabel = useNativeFootprint ? "POC SHIFT" : "ACCEPT"
string selectedValuePrefix = useNativeFootprint ? "" : "~"
string volumeUnitText = syminfo.volumetype == "base" ? "base-currency volume" : syminfo.volumetype == "quote" ? "quote-currency volume" : syminfo.volumetype == "tick" ? "tick volume (transaction count)" : "unspecified volume units"
string selectedDataMethod = useNativeFootprint ? (haveFP ? "TRADINGVIEW NATIVE FOOTPRINT" : "FOOTPRINT DATA UNAVAILABLE") : hasIntrabarDirectionEstimate ? "LOWER-TIMEFRAME DIRECTIONAL ESTIMATE" : hasChartVolume ? "CHART-CANDLE CLOSE-LOCATION PROXY" : "OHLCV VOLUME UNAVAILABLE"
 
// CUMULATIVE VOLUME DELTA (CVD) TREND
// CVD adds the selected delta during the current day and follows its EMA direction.
// It is shown only when native footprint or lower-timeframe flow data is actually present.
 
bool cvdTimeframeSupported = not na(chartTFSeconds) and chartTFSeconds <= 86400
bool currentCvdDeltaAvailable = flowEvidenceAvailable and not na(selectedDelta)
var float cvdValue = na
var bool cvdSessionComplete = false
 
// CVD is reset at each day boundary. A weekly or multi-day chart bar contains more
// than one day, so it cannot reproduce that daily reset from one aggregate bar value.
// Keep CVD unavailable above 1D rather than presenting a weekly/monthly sum as daily CVD.
// If any chart candle in the day has no valid delta, the running total becomes incomplete.
// It therefore stays N/A until the next daily reset instead of silently skipping that candle.
// The chart-candle close-location proxy is never used as independent flow confirmation.
if not cvdTimeframeSupported
    cvdValue := na
    cvdSessionComplete := false
else if timeframe.change("D")
    cvdSessionComplete := currentCvdDeltaAvailable
    cvdValue := cvdSessionComplete ? selectedDelta : na
else if not cvdSessionComplete or not currentCvdDeltaAvailable
    cvdSessionComplete := false
    cvdValue := na
else
    cvdValue += selectedDelta
bool cvdFlowAvailable = cvdTimeframeSupported and cvdSessionComplete and currentCvdDeltaAvailable and not na(cvdValue)
 
// Smooth only the current session's cumulative delta. The EMA starts from the first
// valid CVD value each day, and its first slope is deliberately unavailable because
// there is no earlier value from the same session to compare with.
var float cvdEma = na
var float cvdSlope = na
float cvdEmaAlpha = 2.0 / (cvdTrendLenInput + 1.0)
if not cvdTimeframeSupported or not cvdFlowAvailable
    cvdEma := na
    cvdSlope := na
else if timeframe.change("D")
    cvdEma := cvdValue
    cvdSlope := na
else
    float previousCvdEma = cvdEma
    cvdEma := na(previousCvdEma) ? cvdValue : previousCvdEma + cvdEmaAlpha * (cvdValue - previousCvdEma)
    cvdSlope := na(previousCvdEma) ? na : cvdEma - previousCvdEma
 
bool cvdTrendAvailable = cvdFlowAvailable and not na(cvdSlope)
cvdTrendCode = not cvdTrendAvailable ? "N/A" : cvdSlope > 0 ? "UP" : cvdSlope < 0 ? "DOWN" : "FLAT"
string cvdUnavailableReason = not cvdTimeframeSupported ? "N/A - daily-reset CVD is unavailable above 1D because each chart candle spans multiple days." : not cvdSessionComplete ? "N/A - a complete sequence of valid deltas for this daily session is not available. CVD resumes at the next daily reset." : not currentCvdDeltaAvailable ? useNativeFootprint ? "N/A - native footprint delta is unavailable on this candle." : requestedTrueLowerTF ? "N/A - no valid lower-timeframe flow sequence was returned. The chart-candle proxy is excluded from CVD." : "N/A - the selected interval is not lower than this chart. The close-location proxy is excluded from CVD." : timeframe.isdaily ? "N/A - a daily chart has one aggregate candle per session, so it cannot show an intraday CVD direction." : "N/A - first valid candle of the daily session. CVD direction is available after another valid candle."
string cvdStatusText = cvdTrendAvailable ? cvdTrendCode : cvdUnavailableReason
 
// CONFIRMED PIVOT-TO-PIVOT DELTA DIVERGENCE
// A swing is considered only after the configured right-side candles have closed.
// The marker and alert are placed on that confirmation candle, never back on the pivot.
// High pivots are compared only with the preceding confirmed high; low pivots are
// compared only with the preceding confirmed low. The two sequences remain independent.
// Every confirmed pivot replaces its reference, even when its flow data is unavailable.
// This prevents the engine from skipping a missing-data pivot and comparing unrelated swings.
// Delta percentage remains signed: bearish divergence requires a higher high and lower
// signed delta percentage; bullish divergence requires a lower low and higher signed delta.
// If one confirmation candle qualifies as both a high and a low pivot, both references
// are updated but no divergence is emitted from that ambiguous outside-bar event.
 
float confirmedPivotHigh = ta.pivothigh(high, pivotLeftBarsInput, pivotRightBarsInput)
float confirmedPivotLow = ta.pivotlow(low, pivotLeftBarsInput, pivotRightBarsInput)
bool hasConfirmedPivotHigh = barstate.isconfirmed and not na(confirmedPivotHigh)
bool hasConfirmedPivotLow = barstate.isconfirmed and not na(confirmedPivotLow)
bool confirmsBothPivotTypes = hasConfirmedPivotHigh and hasConfirmedPivotLow
 
var float previousConfirmedHighPrice = na
var float previousConfirmedHighDeltaPct = na
var bool previousConfirmedHighFlowValid = false
var int previousConfirmedHighBarIndex = na
var int previousConfirmedHighTime = na
 
var float previousConfirmedLowPrice = na
var float previousConfirmedLowDeltaPct = na
var bool previousConfirmedLowFlowValid = false
var int previousConfirmedLowBarIndex = na
var int previousConfirmedLowTime = na
 
bool isBearishDiv = false
bool isBullishDiv = false
string divergenceDetailTooltip = ""
 
if hasConfirmedPivotHigh
    float currentPivotHighDeltaPct = selectedDeltaPct[pivotRightBarsInput]
    bool currentPivotHighFlowValid = flowEvidenceAvailable[pivotRightBarsInput] and not na(currentPivotHighDeltaPct)
    bool hasPreviousConfirmedHigh = not na(previousConfirmedHighPrice) and not na(previousConfirmedHighBarIndex)
 
    if not confirmsBothPivotTypes and hasPreviousConfirmedHigh and previousConfirmedHighFlowValid and currentPivotHighFlowValid and confirmedPivotHigh > previousConfirmedHighPrice and currentPivotHighDeltaPct < previousConfirmedHighDeltaPct
        isBearishDiv := true
        divergenceDetailTooltip := "BEARISH CONFIRMED PIVOT DIVERGENCE" +
             "\nCurrent pivot time: " + str.format_time(time[pivotRightBarsInput], "yyyy-MM-dd HH:mm", syminfo.timezone) +
             "\nPrevious pivot time: " + str.format_time(previousConfirmedHighTime, "yyyy-MM-dd HH:mm", syminfo.timezone) +
             "\nCurrent pivot high: " + str.tostring(confirmedPivotHigh, format.mintick) +
             "\nPrevious pivot high: " + str.tostring(previousConfirmedHighPrice, format.mintick) +
             "\nCurrent signed Delta %: " + selectedValuePrefix + (currentPivotHighDeltaPct >= 0 ? "+" : "") + str.tostring(currentPivotHighDeltaPct, "#.0") + "%" +
             "\nPrevious signed Delta %: " + selectedValuePrefix + (previousConfirmedHighDeltaPct >= 0 ? "+" : "") + str.tostring(previousConfirmedHighDeltaPct, "#.0") + "%" +
             "\nConfirmed " + str.tostring(pivotRightBarsInput) + " bars after the pivot."
 
    previousConfirmedHighPrice := confirmedPivotHigh
    previousConfirmedHighDeltaPct := currentPivotHighDeltaPct
    previousConfirmedHighFlowValid := currentPivotHighFlowValid
    previousConfirmedHighBarIndex := bar_index - pivotRightBarsInput
    previousConfirmedHighTime := time[pivotRightBarsInput]
 
if hasConfirmedPivotLow
    float currentPivotLowDeltaPct = selectedDeltaPct[pivotRightBarsInput]
    bool currentPivotLowFlowValid = flowEvidenceAvailable[pivotRightBarsInput] and not na(currentPivotLowDeltaPct)
    bool hasPreviousConfirmedLow = not na(previousConfirmedLowPrice) and not na(previousConfirmedLowBarIndex)
 
    if not confirmsBothPivotTypes and hasPreviousConfirmedLow and previousConfirmedLowFlowValid and currentPivotLowFlowValid and confirmedPivotLow < previousConfirmedLowPrice and currentPivotLowDeltaPct > previousConfirmedLowDeltaPct
        isBullishDiv := true
        divergenceDetailTooltip := "BULLISH CONFIRMED PIVOT DIVERGENCE" +
             "\nCurrent pivot time: " + str.format_time(time[pivotRightBarsInput], "yyyy-MM-dd HH:mm", syminfo.timezone) +
             "\nPrevious pivot time: " + str.format_time(previousConfirmedLowTime, "yyyy-MM-dd HH:mm", syminfo.timezone) +
             "\nCurrent pivot low: " + str.tostring(confirmedPivotLow, format.mintick) +
             "\nPrevious pivot low: " + str.tostring(previousConfirmedLowPrice, format.mintick) +
             "\nCurrent signed Delta %: " + selectedValuePrefix + (currentPivotLowDeltaPct >= 0 ? "+" : "") + str.tostring(currentPivotLowDeltaPct, "#.0") + "%" +
             "\nPrevious signed Delta %: " + selectedValuePrefix + (previousConfirmedLowDeltaPct >= 0 ? "+" : "") + str.tostring(previousConfirmedLowDeltaPct, "#.0") + "%" +
             "\nConfirmed " + str.tostring(pivotRightBarsInput) + " bars after the pivot."
 
    previousConfirmedLowPrice := confirmedPivotLow
    previousConfirmedLowDeltaPct := currentPivotLowDeltaPct
    previousConfirmedLowFlowValid := currentPivotLowFlowValid
    previousConfirmedLowBarIndex := bar_index - pivotRightBarsInput
    previousConfirmedLowTime := time[pivotRightBarsInput]
 
// PER-CANDLE POC SHIFT - FOOTPRINT MODE ONLY
// POC is the highest-volume price row inside one candle's footprint. This metric compares
// it with the immediately previous candle's POC. If either candle has no POC, the result
// is N/A; it never skips a gap to compare against an older candle. The minimum movement
// is measured in the symbol's own ticks, and the same result appears everywhere.
 
float previousBarPocPrice = pocPrice[1]
float nativePocMoveTicks = not na(pocPrice) and not na(previousBarPocPrice) and syminfo.mintick > 0 ? (pocPrice - previousBarPocPrice) / syminfo.mintick : na
string nativePocShiftText = useNativeFootprint and haveFP and not na(nativePocMoveTicks) ? (nativePocMoveTicks >= pocDriftTicksInput ? "UP" : nativePocMoveTicks <= -pocDriftTicksInput ? "DOWN" : "FLAT") : "N/A"
 
// CANDLE ROLE - THE STRONGEST OBSERVED BEHAVIOUR
// The classifier compares pressure, price response, participation and recent auction
// context. It selects the strongest qualifying description; the score is a ranking aid,
// not a probability that the next candle will move in a particular direction.
 
barRange = high - low
barDirection = close > open ? 1 : close < open ? -1 : 0
closePos = barRange > 0 ? (close - low) / barRange : 0.5
bodyPct = barRange > 0 ? math.abs(close - open) / barRange : 0
upperWickPct = barRange > 0 ? (high - math.max(open, close)) / barRange : 0
lowerWickPct = barRange > 0 ? (math.min(open, close) - low) / barRange : 0
volSma14 = ta.sma(selectedVolumeAvailable ? selectedTotalVolume : na, 14)
avgDeltaAbs = ta.sma(flowEvidenceAvailable ? math.abs(selectedDelta) : na, 14)
participationRatio = selectedVolumeAvailable and not na(volSma14) and volSma14 > 0 ? selectedTotalVolume / volSma14 : 0.0
relativeVolume = participationRatio
participationOK = flowEvidenceAvailable and participationRatio >= 0.40
deltaActivityRatio = flowEvidenceAvailable and not na(avgDeltaAbs) and avgDeltaAbs > 0 ? math.abs(selectedDelta) / avgDeltaAbs : 0.0
deltaActivityOK = flowEvidenceAvailable and deltaActivityRatio >= 0.50
isSignifAboveAvgV = flowEvidenceAvailable and not na(selectedTotalVolume) and not na(volSma14) and selectedTotalVolume > volSma14 * relativeVolumeThresholdInput
prevDelta = selectedDelta[1]
currTotal = selectedTotalVolume
deltaVelocity = flowEvidenceAvailable and not na(selectedDelta) and not na(prevDelta) and not na(currTotal) and currTotal > 0 ? (selectedDelta - prevDelta) / currTotal : na
recentHigh = ta.highest(high[1], trapLookbackInput)
recentLow = ta.lowest(low[1], trapLookbackInput)
recentHigh3 = ta.highest(high[1], 3)
recentLow3 = ta.lowest(low[1], 3)
pathMove = math.sum(math.abs(close - close[1]), auctionLookbackInput)
netMove = close - close[auctionLookbackInput]
avgStep = pathMove / auctionLookbackInput
priceEfficiency = pathMove > 0 ? math.abs(netMove) / pathMove : 0.0
upPersistence = math.sum(close > close[1] ? 1.0 : 0.0, auctionLookbackInput) / auctionLookbackInput
downPersistence = math.sum(close < close[1] ? 1.0 : 0.0, auctionLookbackInput) / auctionLookbackInput
auctionUpScore = netMove > 0 ? priceEfficiency * 0.65 + upPersistence * 0.35 : 0.0
auctionDownScore = netMove < 0 ? priceEfficiency * 0.65 + downPersistence * 0.35 : 0.0
auctionHigh = ta.highest(high[1], auctionLookbackInput)
auctionLow = ta.lowest(low[1], auctionLookbackInput)
var string auctionState = "BAL"
if auctionUpScore >= auctionStateThresholdInput and auctionUpScore > auctionDownScore
    auctionState := "UP"
else if auctionDownScore >= auctionStateThresholdInput and auctionDownScore > auctionUpScore
    auctionState := "DOWN"
else if auctionState == "UP" and close < auctionLow
    auctionState := "BAL"
else if auctionState == "DOWN" and close > auctionHigh
    auctionState := "BAL"
rangeExpansion = avgStep > 0 ? math.min(barRange / avgStep, 2.0) / 2.0 : 0.0
responseUp = closePos * 0.55 + bodyPct * 0.25 + rangeExpansion * 0.20
responseDown = (1.0 - closePos) * 0.55 + bodyPct * 0.25 + rangeExpansion * 0.20
counterMoveUp = avgStep > 0 ? math.max(close[1] - close, 0) / avgStep : 0.0
counterMoveDown = avgStep > 0 ? math.max(close - close[1], 0) / avgStep : 0.0
breakUp = not na(recentHigh) and high > recentHigh
breakDown = not na(recentLow) and low < recentLow
failUp = breakUp and close < recentHigh
failDown = breakDown and close > recentLow
returnDepthUp = avgStep > 0 and not na(recentHigh) ? math.min(math.max((recentHigh - close) / avgStep, 0.0), 1.0) : 0.0
returnDepthDown = avgStep > 0 and not na(recentLow) ? math.min(math.max((close - recentLow) / avgStep, 0.0), 1.0) : 0.0
extensionUp = avgStep > 0 and not na(recentHigh3) ? math.min(math.max((high - recentHigh3) / avgStep, 0.0), 1.0) : 0.0
extensionDown = avgStep > 0 and not na(recentLow3) ? math.min(math.max((recentLow3 - low) / avgStep, 0.0), 1.0) : 0.0
deltaStrengthBull = flowEvidenceAvailable and not na(deltaPct) ? math.min(math.max(deltaPct / math.max(deltaThreshPct, 0.01), 0.0), 1.0) * math.min(deltaActivityRatio, 1.0) : 0.0
deltaStrengthBear = flowEvidenceAvailable and not na(deltaPct) ? math.min(math.max(-deltaPct / math.max(deltaThreshPct, 0.01), 0.0), 1.0) * math.min(deltaActivityRatio, 1.0) : 0.0
stackStrengthBull = initStackCountInput > 0 ? math.min(maxBuyStack / (initStackCountInput * 2.0), 1.0) : 0.0
stackStrengthBear = initStackCountInput > 0 ? math.min(maxSellStack / (initStackCountInput * 2.0), 1.0) : 0.0
volumeFactor = flowEvidenceAvailable and not na(selectedTotalVolume) and not na(volSma14) and volSma14 > 0 ? math.min(selectedTotalVolume / volSma14, 2.0) / 2.0 : 0.0
deltaDecayUp = haveFP and not na(deltaVelocity) and deltaVelocity < 0 ? math.min(math.max(-deltaVelocity / math.max(exhVelocityThreshInput, 0.01), 0.0), 1.0) : 0.0
deltaDecayDown = haveFP and not na(deltaVelocity) and deltaVelocity > 0 ? math.min(math.max(deltaVelocity / math.max(exhVelocityThreshInput, 0.01), 0.0), 1.0) : 0.0
exhaustBuyScore = haveFP and participationOK and deltaActivityOK and auctionState == "UP" and extensionUp > 0 ? extensionUp * 0.35 + deltaDecayUp * 0.35 + upperWickPct * 0.15 + (1.0 - responseUp) * 0.15 : 0.0
trapBuyScore = haveFP and participationOK and deltaActivityOK and failUp ? deltaStrengthBull * 0.35 + returnDepthUp * 0.30 + upperWickPct * 0.20 + stackStrengthBull * 0.15 : 0.0
trapSellScore = haveFP and participationOK and deltaActivityOK and failDown ? deltaStrengthBear * 0.35 + returnDepthDown * 0.30 + lowerWickPct * 0.20 + stackStrengthBear * 0.15 : 0.0
buyAbsorbScore = haveFP and participationOK and deltaActivityOK and deltaStrengthBear > 0 and barDirection > 0 ? deltaStrengthBear * 0.45 + closePos * 0.25 + lowerWickPct * 0.15 + volumeFactor * 0.15 : 0.0
sellAbsorbScore = haveFP and participationOK and deltaActivityOK and deltaStrengthBull > 0 and barDirection < 0 ? deltaStrengthBull * 0.45 + (1.0 - closePos) * 0.25 + upperWickPct * 0.15 + volumeFactor * 0.15 : 0.0
exhaustSellScore = haveFP and participationOK and deltaActivityOK and auctionState == "DOWN" and extensionDown > 0 ? extensionDown * 0.35 + deltaDecayDown * 0.35 + lowerWickPct * 0.15 + (1.0 - responseDown) * 0.15 : 0.0
initiativeBullGate = haveFP and participationOK and deltaActivityOK and barDirection > 0 and (deltaStrengthBull >= 0.75 or stackStrengthBull >= 0.75) and (rangeExpansion >= 0.55 or breakUp) and closePos >= 0.65
initiativeBearGate = haveFP and participationOK and deltaActivityOK and barDirection < 0 and (deltaStrengthBear >= 0.75 or stackStrengthBear >= 0.75) and (rangeExpansion >= 0.55 or breakDown) and closePos <= 0.35
initiativeBullScore = initiativeBullGate ? deltaStrengthBull * 0.50 + stackStrengthBull * 0.15 + responseUp * 0.20 + rangeExpansion * 0.15 : 0.0
initiativeBearScore = initiativeBearGate ? deltaStrengthBear * 0.50 + stackStrengthBear * 0.15 + responseDown * 0.20 + rangeExpansion * 0.15 : 0.0
isNeutralAbsorption = haveFP and isSignifAboveAvgV and barDirection == 0 and math.abs(nz(deltaPct)) <= math.max(deltaThreshPct * 0.2, 0.75) and closePos >= 0.4 and closePos <= 0.6
isPullbackUp = auctionState == "UP" and counterMoveUp > 1.25
isPullbackDown = auctionState == "DOWN" and counterMoveDown > 1.25
isContinuationUp = auctionState == "UP" and not isPullbackUp
isContinuationDown = auctionState == "DOWN" and not isPullbackDown
string charCode = "CHP"
int charDir = 0
float charScore = 0.0
string charEventSide = ""
if trapBuyScore >= charMinScoreInput and trapBuyScore > charScore
    charCode := "TRAP"
    charDir := -1
    charScore := trapBuyScore
    charEventSide := "BUY"
if trapSellScore >= charMinScoreInput and trapSellScore > charScore
    charCode := "TRAP"
    charDir := 1
    charScore := trapSellScore
    charEventSide := "SELL"
if sellAbsorbScore >= charMinScoreInput and sellAbsorbScore > charScore
    charCode := "ABS"
    charDir := -1
    charScore := sellAbsorbScore
    charEventSide := "SELL"
if buyAbsorbScore >= charMinScoreInput and buyAbsorbScore > charScore
    charCode := "ABS"
    charDir := 1
    charScore := buyAbsorbScore
    charEventSide := "BUY"
// Balanced absorption is a deliberately fixed-score exception. Keep it as a primary
// role; the auction fallback below runs only when no primary role was selected.
if isNeutralAbsorption and charScore < charMinScoreInput
    charCode := "ABS"
    charDir := 0
    charScore := 0.50
    charEventSide := ""
if exhaustBuyScore >= charMinScoreInput and exhaustBuyScore > charScore
    charCode := "EXHT"
    charDir := -1
    charScore := exhaustBuyScore
    charEventSide := "BUY"
if exhaustSellScore >= charMinScoreInput and exhaustSellScore > charScore
    charCode := "EXHT"
    charDir := 1
    charScore := exhaustSellScore
    charEventSide := "SELL"
if initiativeBullScore >= charMinScoreInput and initiativeBullScore > charScore
    charCode := "BULL"
    charDir := 1
    charScore := initiativeBullScore
    charEventSide := "BUY"
if initiativeBearScore >= charMinScoreInput and initiativeBearScore > charScore
    charCode := "BEAR"
    charDir := -1
    charScore := initiativeBearScore
    charEventSide := "SELL"
if charCode == "CHP"
    if isContinuationUp
        charCode := "CONT"
        charDir := 1
        charScore := auctionUpScore
        charEventSide := "UP"
    else if isContinuationDown
        charCode := "CONT"
        charDir := -1
        charScore := auctionDownScore
        charEventSide := "DOWN"
    else if isPullbackUp
        charCode := "PULL"
        charDir := -1
        charScore := math.min(counterMoveUp / 2.0, 1.0)
        charEventSide := "DOWN"
    else if isPullbackDown
        charCode := "PULL"
        charDir := 1
        charScore := math.min(counterMoveDown / 2.0, 1.0)
        charEventSide := "UP"
 
// ESTIMATED OHLCV ROLE INTERPRETATION
// This branch is used only when Estimated OHLCV is selected. It can describe a failed
// breakout, continuation, pullback or directional price response from the chart itself.
// Initiative and response candidates that rely on lower-timeframe estimates are used only
// when smaller candles are actually available. OHLCV cannot prove queue absorption or
// identify the aggressor for every trade, so its response labels remain interpretations.
 
if not useNativeFootprint
    charCode := "CHP"
    charDir := 0
    charScore := 0.0
    charEventSide := ""
    bool estimatedBuyPressure = hasIntrabarDirectionEstimate and not na(estimatedDeltaPct) and estimatedDeltaPct >= deltaThreshPct
    bool estimatedSellPressure = hasIntrabarDirectionEstimate and not na(estimatedDeltaPct) and estimatedDeltaPct <= -deltaThreshPct
    bool estimatedParticipation = not na(relativeVolume) and relativeVolume >= 1.0
    bool estimatedHighParticipation = not na(relativeVolume) and relativeVolume >= relativeVolumeThresholdInput
    bool estimatedBuyResponse = estimatedSellPressure and estimatedHighParticipation and barDirection > 0 and closePos >= 0.60 and lowerWickPct >= 0.20
    bool estimatedSellResponse = estimatedBuyPressure and estimatedHighParticipation and barDirection < 0 and closePos <= 0.40 and upperWickPct >= 0.20
    bool estimatedBuyExhaustion = estimatedBuyPressure and auctionState == "UP" and extensionUp > 0 and upperWickPct >= 0.35 and closePos < 0.65
    bool estimatedSellExhaustion = estimatedSellPressure and auctionState == "DOWN" and extensionDown > 0 and lowerWickPct >= 0.35 and closePos > 0.35
    bool estimatedInitiativeBuy = estimatedBuyPressure and estimatedParticipation and barDirection > 0 and closePos >= 0.65 and bodyPct >= 0.35 and (rangeExpansion >= 0.45 or breakUp)
    bool estimatedInitiativeSell = estimatedSellPressure and estimatedParticipation and barDirection < 0 and closePos <= 0.35 and bodyPct >= 0.35 and (rangeExpansion >= 0.45 or breakDown)
 
    // A failed break is checked first: price moved beyond a recent high or low,
    // then closed back through that level. That close-back-inside is the key clue.
    if failUp
        charCode := "TRAP"
        charDir := -1
        charScore := math.min(returnDepthUp * 0.60 + upperWickPct * 0.40, 1.0)
        charEventSide := "BUY"
    else if failDown
        charCode := "TRAP"
        charDir := 1
        charScore := math.min(returnDepthDown * 0.60 + lowerWickPct * 0.40, 1.0)
        charEventSide := "SELL"
    else if estimatedBuyResponse
        charCode := "ABS"
        charDir := 1
        charScore := math.min(0.45 + lowerWickPct * 0.30 + math.min(relativeVolume / relativeVolumeThresholdInput, 1.5) * 0.15, 1.0)
        charEventSide := "BUY"
    else if estimatedSellResponse
        charCode := "ABS"
        charDir := -1
        charScore := math.min(0.45 + upperWickPct * 0.30 + math.min(relativeVolume / relativeVolumeThresholdInput, 1.5) * 0.15, 1.0)
        charEventSide := "SELL"
    else if estimatedBuyExhaustion
        charCode := "EXHT"
        charDir := -1
        charScore := math.min(extensionUp * 0.45 + upperWickPct * 0.35 + (1.0 - responseUp) * 0.20, 1.0)
        charEventSide := "BUY"
    else if estimatedSellExhaustion
        charCode := "EXHT"
        charDir := 1
        charScore := math.min(extensionDown * 0.45 + lowerWickPct * 0.35 + (1.0 - responseDown) * 0.20, 1.0)
        charEventSide := "SELL"
    else if estimatedInitiativeBuy
        charCode := "BULL"
        charDir := 1
        charScore := math.min(estimatedDeltaPct / math.max(deltaThreshPct * 2.0, 0.01) * 0.45 + responseUp * 0.35 + rangeExpansion * 0.20, 1.0)
        charEventSide := "BUY"
    else if estimatedInitiativeSell
        charCode := "BEAR"
        charDir := -1
        charScore := math.min(math.abs(estimatedDeltaPct) / math.max(deltaThreshPct * 2.0, 0.01) * 0.45 + responseDown * 0.35 + rangeExpansion * 0.20, 1.0)
        charEventSide := "SELL"
    else if isPullbackUp
        charCode := "PULL"
        charDir := -1
        charScore := math.min(counterMoveUp / 2.0, 1.0)
        charEventSide := "DOWN"
    else if isPullbackDown
        charCode := "PULL"
        charDir := 1
        charScore := math.min(counterMoveDown / 2.0, 1.0)
        charEventSide := "UP"
    else if isContinuationUp
        charCode := "CONT"
        charDir := 1
        charScore := auctionUpScore
        charEventSide := "UP"
    else if isContinuationDown
        charCode := "CONT"
        charDir := -1
        charScore := auctionDownScore
        charEventSide := "DOWN"
    else if barDirection > 0 and closePos >= 0.67
        charCode := "BULL"
        charDir := 1
        charScore := responseUp
        charEventSide := "BUY"
    else if barDirection < 0 and closePos <= 0.33
        charCode := "BEAR"
        charDir := -1
        charScore := responseDown
        charEventSide := "SELL"
// No native footprint means no native character classification for this candle.
// Keep the dashboard explicit instead of allowing a price-only auction fallback to look
// like a completed Footprint-mode classification.
if useNativeFootprint and not haveFP
    charCode := "CHP"
    charDir := 0
    charScore := 0.0
    charEventSide := ""
 
charTrapDir = charCode == "TRAP" ? charEventSide : ""
flowEvent = isBearishDiv ? "DIV BEAR" : isBullishDiv ? "DIV BULL" : ""
charDisplayColor = charCode == "CHP" ? cNeutral : charCode == "CONT" or charCode == "PULL" ? charDir == 1 ? c_bull : charDir == -1 ? c_bear : cNeutral : f_charColor(charCode)
color charLabelTextColor = f_chartLabelColor(charCode, charDir)
 
// ALIGNMENT WITH THE HIGHER-TIMEFRAME BACKDROP
// Shows whether the candle's direction agrees with, opposes or is neutral to the HTF trend.
 
alignCode = regimeCode == "BAL" ? "NEUTRAL" : charCode == "ABS" ? "ABSORB" : charCode == "TRAP" or charCode == "EXHT" or charDir == 0 ? "NEUTRAL" : charDir == 1 and regimeCode == "UP" ? "AGREE" : charDir == -1 and regimeCode == "DOWN" ? "AGREE" : "OPPOSE"
 
// RECENT FLOW BALANCE
// Count bullish and bearish classified candles in the selected recent window. The warning
// appears when the dominant classification direction disagrees with the CVD trend.
 
var array<string> histCharFC = array.new<string>(0)
if barstate.isconfirmed
 
    // Keep one slot for every completed candle. A bar without flow data is marked N/A;
    // it must not make an older flow reading appear more recent than it really is.
 
    array.push(histCharFC, flowEvidenceAvailable ? charCode : "N/A")
    while array.size(histCharFC) > flowConfirmLookbackInput
        array.shift(histCharFC)
int fcSize   = array.size(histCharFC)
int fcBullCount = 0
int fcBearCount = 0
if fcSize > 0
    for i = 0 to fcSize - 1
        string hc = array.get(histCharFC, i)
        if hc == "BULL"
            fcBullCount += 1
        else if hc == "BEAR"
            fcBearCount += 1
int    fcTagged     = fcBullCount + fcBearCount
string flowDominant = "NONE"
if fcTagged > 0
    if fcBullCount / fcTagged >= 0.6
        flowDominant := "BULL"
    else if fcBearCount / fcTagged >= 0.6
        flowDominant := "BEAR"
string flowWarning =
     (flowDominant == "BULL" and cvdTrendCode == "DOWN") ? "⚠ Bullish move - not yet confirmed by flow" :
     (flowDominant == "BEAR" and cvdTrendCode == "UP")   ? "⚠ Bearish move - not yet confirmed by flow" : ""
 
// VALUE AREA HIGH / LOW - NATIVE FOOTPRINT ONLY
// These optional chart lines are drawn only from TradingView's native footprint rows.
// They remain unavailable in Estimated OHLCV mode rather than being approximated.
 
plot(showVaLinesInput and useNativeFootprint and haveFP ? vahPrice : na, "VAH · Native Footprint", color.new(f_chartLabelColor("BULL", 1), 20), style = plot.style_stepline, linewidth = 1, force_overlay = true)
plot(showVaLinesInput and useNativeFootprint and haveFP ? valPrice : na, "VAL · Native Footprint", color.new(f_chartLabelColor("BEAR", -1), 20), style = plot.style_stepline, linewidth = 1, force_overlay = true)
 
// EXPLANATION AND EVIDENCE
// The role is the strongest description selected by the rules. The support count records
// how many of six descriptive checks are present. Checks can overlap; this is not a
// probability, forecast, win rate or statistical confidence score.
 
string statusText = ""
if useNativeFootprint
    statusText := not haveFP ? "Footprint data unavailable." :
      charCode == "TRAP" ? (charEventSide == "BUY" ? "Prior high failed; price closed\nback below the breakout level." : "Prior low failed; price closed\nback above the breakdown level.") :
      charCode == "ABS" ? (charEventSide == "BUY" ? "Native selling pressure met a positive\nprice response; absorption is an interpretation." : charEventSide == "SELL" ? "Native buying pressure met a negative\nprice response; absorption is an interpretation." : "Balanced two-sided native activity;\nabsorption remains an interpretation.") :
      charCode == "EXHT" ? (charEventSide == "BUY" ? "Buying extended price; the close\nand upper wick show a weaker response." : "Selling extended price; the close\nand lower wick show a weaker response.") :
      charCode == "BULL" ? "Initiative buying produced a\npositive price response." :
      charCode == "BEAR" ? "Initiative selling produced a\nnegative price response." :
      charCode == "CONT" ? (auctionState == "UP" ? "Upward auction remains in\ncontinuation." : "Downward auction remains in\ncontinuation.") :
      charCode == "PULL" ? (auctionState == "UP" ? "Counter-move within an\nupward auction." : "Counter-move within a\ndownward auction.") :
      "Balanced auction; no dominant\ncandle role."
else
    statusText := charCode == "TRAP" ? (charEventSide == "BUY" ? "Prior high failed; price closed\nback below the breakout level." : "Prior low failed; price closed\nback above the breakdown level.") :
      charCode == "ABS" ? (charEventSide == "BUY" ? "Estimated selling allocation coincided\nwith a positive price response." : charEventSide == "SELL" ? "Estimated buying allocation coincided\nwith a negative price response." : "Balanced estimated activity;\nno directional response was selected.") :
      charCode == "EXHT" ? (charEventSide == "BUY" ? "Estimated buying extended price;\nresponse weakened near the high." : "Estimated selling extended price;\nresponse weakened near the low.") :
      charCode == "BULL" ? (hasIntrabarDirectionEstimate ? "Estimated upward participation\nsupports a bullish response." : "Bullish price response; lower-timeframe\nflow evidence is unavailable.") :
      charCode == "BEAR" ? (hasIntrabarDirectionEstimate ? "Estimated downward participation\nsupports a bearish response." : "Bearish price response; lower-timeframe\nflow evidence is unavailable.") :
      charCode == "CONT" ? (auctionState == "UP" ? "Upward auction remains in\ncontinuation." : "Downward auction remains in\ncontinuation.") :
      charCode == "PULL" ? (auctionState == "UP" ? "Counter-move within an\nupward auction." : "Counter-move within a\ndownward auction.") :
      "Balanced price action; no dominant\ncandle role."
string selectedBuyText = na(selectedBuyVolume) ? "N/A" : selectedValuePrefix + f_formatVol(selectedBuyVolume)
string selectedSellText = na(selectedSellVolume) ? "N/A" : selectedValuePrefix + f_formatVol(selectedSellVolume)
string selectedTotalText = na(selectedTotalVolume) ? "N/A" : f_formatVol(selectedTotalVolume)
string selectedDeltaText = na(selectedDelta) ? "N/A" : selectedValuePrefix + (selectedDelta >= 0 ? "+" : "") + f_formatVol(selectedDelta)
string selectedDeltaPctText = na(selectedDeltaPct) ? "N/A" : selectedValuePrefix + (selectedDeltaPct >= 0 ? "+" : "") + str.tostring(selectedDeltaPct, "#.#") + "%"
string nativeImbalanceStacksText = not haveFP ? "N/A" : "B" + str.tostring(maxBuyStack) + " / S" + str.tostring(maxSellStack)
string selectedMetric5Text = useNativeFootprint ? nativeImbalanceStacksText : directionalRunText
string selectedMetric6Text = useNativeFootprint ? nativePocShiftText : closeAcceptanceText
 
// Six simple checks support the current description. More checks mean more of the
// selected conditions are present, not that the event is more likely to succeed.
int evidenceCount = 0
evidenceCount += barDirection != 0 ? 1 : 0
evidenceCount += bodyPct >= 0.35 ? 1 : 0
evidenceCount += closePos >= 0.65 or closePos <= 0.35 ? 1 : 0
evidenceCount += isSignifAboveAvgV ? 1 : 0
evidenceCount += flowEvidenceAvailable and math.abs(nz(selectedDeltaPct)) >= deltaThreshPct ? 1 : 0
evidenceCount += (charDir > 0 and regimeCode == "UP") or (charDir < 0 and regimeCode == "DOWN") ? 1 : 0
string dashCharText = useNativeFootprint and not haveFP ? "FOOTPRINT N/A" : charCode == "BULL" ? (useNativeFootprint ? "INIT BUY" : hasIntrabarDirectionEstimate ? "EST INIT BUY" : "UP RESPONSE") :
     charCode == "BEAR" ? (useNativeFootprint ? "INIT SELL" : hasIntrabarDirectionEstimate ? "EST INIT SELL" : "DOWN RESPONSE") :
     charCode == "CONT" ? (charDir == 1 ? "UP AUCTION" : "DOWN AUCTION") :
     charCode == "PULL" ? (charDir == 1 ? "PULL UP" : "PULL DOWN") :
     charCode == "ABS" ? (charEventSide == "BUY" ? "BUYER RESPONSE" : charEventSide == "SELL" ? "SELLER RESPONSE" : "BALANCED ABSORPTION") :
     charCode == "EXHT" ? (charEventSide == "BUY" ? "BUYER EXHAUSTION" : "SELLER EXHAUSTION") :
     charCode == "TRAP" ? (not useNativeFootprint ? (charEventSide == "BUY" ? "FAILED HIGH" : "FAILED LOW") : (charEventSide == "BUY" ? "TRAP BUY" : "TRAP SELL")) : "BALANCE"
string dashboardFooter = barstate.isconfirmed ? "CONFIRMED" : "DEVELOPING"
string metric5Tooltip = useNativeFootprint ?
     "Footprint: B is the longest consecutive run of native buy-imbalance price rows; S is the longest consecutive run of native sell-imbalance price rows. The two counts are calculated independently for this candle. They count adjacent price rows, not bullish or bearish candles." :
     "Estimated OHLCV - Directional Run: consecutive chart candles moving in the same direction as the current candle. A doji resets the run. This is a price measure, not bid/ask imbalance."
string metric6Tooltip = useNativeFootprint ?
     "Footprint - POC Shift: this candle's native POC compared with the immediately previous candle's POC. Missing adjacent POC data returns N/A; this is not session POC drift." :
     "Estimated OHLCV - Close Acceptance: close location within this candle's own range: upper 67%+, lower 33% or less, middle otherwise. This is not time-at-price or multi-candle acceptance."
string volumeTooltip = useNativeFootprint ?
     "Source: TradingView native footprint. Buy/sell volume and delta come from TradingView's footprint classification, not a full order book or direct per-trade aggressor feed. Reported units: " + volumeUnitText + "." :
     "Source: estimated OHLCV, not true aggressor flow. Buy/sell allocation and resulting delta are estimates; total volume remains provider-reported. Lower-timeframe candles are assigned by direction; if no usable smaller bars exist, chart volume is allocated by close location. Requested interval: " + lowerTfToUse + "; valid intrabars: " + str.tostring(validIntrabarCount) + "/" + str.tostring(intrabarCount) + ". Reported units: " + volumeUnitText + "."
string deltaTooltip = "Delta = buy volume minus sell volume. Delta % = delta divided by selected total volume. In Estimated OHLCV mode, ~ marks the estimated buy/sell allocation and the resulting delta values. Total volume is provider-reported, not an estimated allocation. " + volumeTooltip
string continuationNote = charCode == "CONT" ? "\nAUCTION NOTE: UP/DOWN AUCTION describes the broader recent auction state. The current candle can point the other way if it has not crossed the pullback threshold." : ""
string pullbackNote = charCode == "PULL" ? (charDir == -1 ? "\nPULLBACK NOTE: PULL DOWN is a downward counter-move within an UP AUCTION." : "\nPULLBACK NOTE: PULL UP is an upward counter-move within a DOWN AUCTION.") : ""
string supportCheckText = useNativeFootprint and not haveFP ? "N/A - Footprint data unavailable." : str.tostring(evidenceCount) + "/6 (descriptive checks; not a probability or confidence level)."
string detailTooltip = "ROLE: " + dashCharText + "\n" + statusText + "\nHTF: " + regimeCode + " · Structure: " + structureCode + "\nAuction: " + auctionState + " · Alignment: " + alignCode + "\nCVD: " + cvdStatusText + "\nSecondary divergence: " + (flowEvent == "" ? "None" : flowEvent) + (flowWarning == "" ? "" : "\n" + flowWarning) + continuationNote + pullbackNote + "\nSupport checks: " + supportCheckText
string dataTooltip = "OHLC: " + str.tostring(open, format.mintick) + " / " + str.tostring(high, format.mintick) + " / " + str.tostring(low, format.mintick) + " / " + str.tostring(close, format.mintick) + "\nBODY: " + str.tostring(bodyPct * 100.0, "#.0") + "% · CLOSE: " + str.tostring(closePos * 100.0, "#.0") + "%\nBUY: " + selectedBuyText + " · SELL: " + selectedSellText + "\nDELTA: " + selectedDeltaText + " · DELTA %: " + selectedDeltaPctText + "\nTOTAL (REPORTED): " + selectedTotalText + "\n" + metric5Label + ": " + selectedMetric5Text + " · " + metric6Label + ": " + selectedMetric6Text + "\nHTF: " + htfText + " · ROLE: " + dashCharText + "\nCVD: " + cvdStatusText + "\nSecondary divergence: " + (flowEvent == "" ? "None" : flowEvent) + "\nSOURCE: " + selectedDataMethod + " · UNITS: " + volumeUnitText
 
// CHART LABELS AND HOVER DETAILS
// Primary role and separate divergence labels are created only after the chart candle closes.
// Divergence is a secondary event and never replaces the main role. The dashboard can still show
// developing values, while the monitor stores completed candles only. A later provider
// revision to historical intrabars can still change a result after the chart is reloaded.
 
var array<label> charLabels = array.new<label>(0)
var array<string> charStrings = array.new<string>(0)
var array<int> charLabelBars = array.new<int>(0)
var array<label> divLabels = array.new<label>(0)
var array<label> ttLabels = array.new<label>(0)
if barstate.isconfirmed
    bool currentSourceDataAvailable = not useNativeFootprint or haveFP
 
    if currentSourceDataAvailable
        bool bearSide = charDir < 0
        if showBarLabelsInput
            string baseText = not useNativeFootprint and charCode == "TRAP" ? (charEventSide == "BUY" ? "FAILED HIGH" : "FAILED LOW") :
                 charCode == "TRAP" ? "TRAP " + charTrapDir :
                 charCode == "ABS" ? (charEventSide == "BUY" ? "BUYER RESPONSE" : charEventSide == "SELL" ? "SELLER RESPONSE" : "BALANCED ABSORPTION") :
                 charCode == "EXHT" ? (charEventSide == "BUY" ? "BUYER EXHAUSTION" : "SELLER EXHAUSTION") :
                 charCode == "BULL" ? (useNativeFootprint ? "INIT BUY" : hasIntrabarDirectionEstimate ? "EST INIT BUY" : "UP RESPONSE") :
                 charCode == "BEAR" ? (useNativeFootprint ? "INIT SELL" : hasIntrabarDirectionEstimate ? "EST INIT SELL" : "DOWN RESPONSE") :
                 charCode == "CONT" ? (charDir == 1 ? "UP AUCTION" : "DOWN AUCTION") :
                 charCode == "PULL" ? (charDir == 1 ? "PULL UP" : "PULL DN") : "BAL"
            label lbl = label.new(
                 bar_index, bearSide ? high : low,
                 text = baseText,
                 xloc = xloc.bar_index,
                 yloc = bearSide ? yloc.abovebar : yloc.belowbar,
                 style = label.style_none,
                 textcolor = charLabelTextColor,
                 color = color.new(color.black, 100),
                 size = size.tiny,
                 tooltip = detailTooltip,
                 force_overlay = true)
            array.push(charLabels, lbl)
            array.push(charStrings, baseText)
            array.push(charLabelBars, bar_index)
 
        if showTooltipInput
            float markerOffset = (high - low) * 0.08 + syminfo.mintick
            label ttLbl = label.new(
                 bar_index, low - markerOffset,
                 text = "",
                 xloc = xloc.bar_index,
                 yloc = yloc.price,
                 style = label.style_circle,
                 color = color.new(chart.fg_color, 65),
                 size = size.tiny,
                 tooltip = dataTooltip,
                 force_overlay = true)
            array.push(ttLabels, ttLbl)
 
    // A divergence marker is eligible when its two pivot candles have valid flow data.
    // The confirmation candle itself does not need a Footprint reading; it supplies timing.
    if showBarLabelsInput and (isBullishDiv or isBearishDiv)
        bool bearishDivergence = isBearishDiv
        float divergenceOffset = (high - low) * 0.16 + syminfo.mintick * 2.0
        string currentRoleDetail = useNativeFootprint and not haveFP ? "Current confirmation candle has no Footprint reading; divergence is based on the two pivot candles shown above." : detailTooltip
        label divLbl = label.new(
             bar_index,
             bearishDivergence ? high + divergenceOffset : low - divergenceOffset,
             text = bearishDivergence ? "DIV BEAR" : "DIV BULL",
             xloc = xloc.bar_index,
             yloc = yloc.price,
             style = label.style_none,
             textcolor = f_chartLabelColor("DIV", bearishDivergence ? -1 : 1),
             color = color.new(chart.bg_color, 100),
             size = size.tiny,
             tooltip = divergenceDetailTooltip + "\n\nSECONDARY EVENT: Divergence is confirmed on this candle after the right-side pivot bars close. It does not replace the primary candle role.\n" + currentRoleDetail,
             force_overlay = true)
        array.push(divLabels, divLbl)
 
    while array.size(charLabels) > historyBarsInput
        label.delete(array.shift(charLabels))
        array.shift(charStrings)
        array.shift(charLabelBars)
    while array.size(divLabels) > historyBarsInput
        label.delete(array.shift(divLabels))
    while array.size(ttLabels) > historyBarsInput
        label.delete(array.shift(ttLabels))
if array.size(charLabels) > 0
    for labelIndex = 0 to array.size(charLabels) - 1
        int labelBarIndex = array.get(charLabelBars, labelIndex)
        int labelBarsAgo = bar_index - labelBarIndex
        string labelAge = labelBarsAgo > 0 ? " (-" + str.tostring(labelBarsAgo) + ")" : ""
        label.set_text(array.get(charLabels, labelIndex), array.get(charStrings, labelIndex) + labelAge)
 
// ORDER FLOW MONITOR - COMPLETED-CANDLE HISTORY
// Each column in the monitor belongs to one completed candle. All stored values are added
// and removed together, so time, OHLC, volume, delta, role and context stay on the same bar.
// Changing the data source rebuilds the history in that source; values from the two modes
// are never mixed in one monitor.
 
var array<int> histTime = array.new<int>(0)
var array<float> histOpen = array.new<float>(0)
var array<float> histHigh = array.new<float>(0)
var array<float> histLow = array.new<float>(0)
var array<float> histClose = array.new<float>(0)
var array<float> histChartVolume = array.new<float>(0)
var array<float> histBuyVol = array.new<float>(0)
var array<float> histSellVol = array.new<float>(0)
var array<float> histDelta = array.new<float>(0)
var array<float> histDeltaPct = array.new<float>(0)
var array<float> histTotal = array.new<float>(0)
var array<string> histMetric5 = array.new<string>(0)
var array<string> histMetric6 = array.new<string>(0)
var array<string> histHtf = array.new<string>(0)
var array<string> histRole = array.new<string>(0)
var array<string> histAlign = array.new<string>(0)
var array<string> histCvd = array.new<string>(0)
var array<string> histDataMethod = array.new<string>(0)
var array<string> histDiv = array.new<string>(0)
if barstate.isconfirmed
    array.push(histTime, time)
    array.push(histOpen, open)
    array.push(histHigh, high)
    array.push(histLow, low)
    array.push(histClose, close)
    array.push(histChartVolume, volume)
    array.push(histBuyVol, selectedBuyVolume)
    array.push(histSellVol, selectedSellVolume)
    array.push(histDelta, selectedDelta)
    array.push(histDeltaPct, selectedDeltaPct)
    array.push(histTotal, selectedTotalVolume)
    array.push(histMetric5, useNativeFootprint ? nativeImbalanceStacksText : directionalRunShort)
    array.push(histMetric6, useNativeFootprint ? nativePocShiftText : closeAcceptanceShort)
    array.push(histHtf, htfText)
    array.push(histRole, (useNativeFootprint ? haveFP : true) ? dashCharText : "N/A")
    array.push(histAlign, (useNativeFootprint ? haveFP : true) ? alignCode : "N/A")
    array.push(histCvd, cvdStatusText)
    array.push(histDataMethod, selectedDataMethod)
    array.push(histDiv, flowEvent == "" ? "None" : flowEvent)
    while array.size(histTime) > historyBarsInput + 1
        array.shift(histTime)
        array.shift(histOpen)
        array.shift(histHigh)
        array.shift(histLow)
        array.shift(histClose)
        array.shift(histChartVolume)
        array.shift(histBuyVol)
        array.shift(histSellVol)
        array.shift(histDelta)
        array.shift(histDeltaPct)
        array.shift(histTotal)
        array.shift(histMetric5)
        array.shift(histMetric6)
        array.shift(histHtf)
        array.shift(histRole)
        array.shift(histAlign)
        array.shift(histCvd)
        array.shift(histDataMethod)
        array.shift(histDiv)
 
// ONE CHART DASHBOARD, ONE HISTORY MONITOR
// Both data sources use the same tables. Buy, sell, delta, delta percent and HTF keep the
// same positions; only the two source-specific metric names and values change. The tables
// are refreshed on the last chart bar, while the monitor history is saved after each close.
 
dashboardTextSize = displayLayoutInput == "Compact" ? size.tiny : sumSize
dashboardHeroSize = displayLayoutInput == "Compact" ? size.normal : sumSizeBig
var table sumTable = table.new(f_tablePos(summaryPositionInput), 2, 12, border_width = 1, border_color = summaryBordInput, bgcolor = summaryBgInput, force_overlay = true)
var table gridTable = table.new(position.top_left, visibleHistoryBars + 2, 11, border_width = 1, border_color = color.new(#363a45, 0))
float gridLabelWidth = displayLayoutInput == "Full" ? 7.0 : 18.0
float gridDataWidth = displayLayoutInput == "Full" ? 93.0 / (visibleHistoryBars + 1) : 82.0 / (visibleHistoryBars + 1)
if barstate.isfirst
    table.merge_cells(sumTable, 0, 0, 1, 0)
    table.merge_cells(sumTable, 0, 1, 1, 1)
    table.merge_cells(sumTable, 0, 2, 1, 2)
    table.merge_cells(sumTable, 0, 11, 1, 11)
    table.merge_cells(gridTable, 0, 0, visibleHistoryBars + 1, 0)
if barstate.islast
    if showSummaryDashboardInput
        string summaryTitle = "OFCC DASHBOARD"
        string summaryRole = f_monitorRole(dashCharText)
        color summaryRoleColor = charDisplayColor
        color summaryStatusBg = charCode == "CHP" ? summaryBgInput : summaryRoleColor
        string evidenceLine = useNativeFootprint and not haveFP ? "FOOTPRINT N/A" : str.tostring(evidenceCount) + "/6 SUPPORT CHECKS"
        string footerText = dashboardFooter
        table.cell(sumTable, 0, 0, summaryTitle, text_color = f_contrastText(cPanel), bgcolor = cPanel, text_size = size.tiny, text_halign = text.align_center, text_formatting = text.format_bold)
        table.cell(sumTable, 0, 1, summaryRole, text_color = f_contrastText(summaryRoleColor), bgcolor = summaryRoleColor, text_size = dashboardHeroSize, text_halign = text.align_center, text_formatting = text.format_bold, tooltip = detailTooltip)
        table.cell(sumTable, 0, 2, statusText, text_color = f_contrastText(summaryStatusBg), bgcolor = summaryStatusBg, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = detailTooltip)
        table.cell(sumTable, 0, 3, "METRIC", text_color = color.new(cWhite, 30), bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, text_halign = text.align_center)
        table.cell(sumTable, 1, 3, "RESULT", text_color = color.new(cWhite, 30), bgcolor = cHeader, text_size = size.tiny, text_halign = text.align_center, text_formatting = text.format_bold)
        table.cell(sumTable, 0, 4, "Buy volume", text_color = cBuy, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = volumeTooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 4, selectedBuyText, text_color = cBuy, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = volumeTooltip)
        table.cell(sumTable, 0, 5, "Sell volume", text_color = cSell, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = volumeTooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 5, selectedSellText, text_color = cSell, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = volumeTooltip)
        table.cell(sumTable, 0, 6, "Delta", text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = deltaTooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 6, selectedDeltaText, text_color = na(selectedDelta) ? cNeutral : selectedDelta >= 0 ? cBuy : cSell, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = deltaTooltip)
        table.cell(sumTable, 0, 7, "Delta %", text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = deltaTooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 7, selectedDeltaPctText, text_color = na(selectedDeltaPct) ? cNeutral : selectedDeltaPct >= 0 ? cBuy : cSell, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = deltaTooltip)
        table.cell(sumTable, 0, 8, metric5Label, text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = metric5Tooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 8, selectedMetric5Text, text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = metric5Tooltip)
        table.cell(sumTable, 0, 9, metric6Label, text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = metric6Tooltip, text_halign = text.align_center)
        table.cell(sumTable, 1, 9, selectedMetric6Text, text_color = useNativeFootprint and nativePocShiftText == "UP" ? cBuy : useNativeFootprint and nativePocShiftText == "DOWN" ? cSell : cWhite, bgcolor = cPanel, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = metric6Tooltip)
        table.cell(sumTable, 0, 10, "HTF", text_color = cWhite, bgcolor = cPanel, text_size = dashboardTextSize, tooltip = "Higher-timeframe trend from the previous completed HTF candle.", text_halign = text.align_center)
        table.cell(sumTable, 1, 10, htfText, text_color = color.white, bgcolor = regimeColor, text_size = dashboardTextSize, text_halign = text.align_center, tooltip = "HTF: " + regimeCode + " · Structure: " + structureCode + " · Auction: " + auctionState)
        table.cell(sumTable, 0, 11, footerText + " · " + evidenceLine, text_color = f_contrastText(summaryBgInput), bgcolor = summaryBgInput, text_size = size.tiny, text_halign = text.align_center, tooltip = (useNativeFootprint and not haveFP ? "No support count is shown because Footprint data is unavailable. " : "Support checks count six descriptive conditions. They can overlap and are not independent observations, probability, prediction accuracy or statistical confidence. ") + cvdStatusText)
    else
        table.clear(sumTable, 0, 0, 1, 11)
    if showOrderFlowMonitorInput
        int historySize = array.size(histTime)
        int historyDisplaySize = math.max(historySize - (barstate.isconfirmed ? 1 : 0), 0)
        table.cell(gridTable, 0, 0, "ORDER FLOW MONITOR", text_color = f_contrastText(cPanel), bgcolor = cPanel, text_size = size.small, text_halign = text.align_center, text_formatting = text.format_bold)
        table.cell(gridTable, 0, 1, "BAR", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, width = gridLabelWidth)
        table.cell(gridTable, 0, 2, "TIME", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = "Candle time in the symbol's exchange timezone (" + historyTimezone + "). Pine cannot read the chart's display-timezone setting.", width = gridLabelWidth)
        table.cell(gridTable, 0, 3, "BUY VOL", text_color = cBuy, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = volumeTooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 4, "SELL VOL", text_color = cSell, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = volumeTooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 5, "DELTA", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = deltaTooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 6, "DELTA %", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = deltaTooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 7, metric5HistoryLabel, text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = metric5Tooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 8, metric6HistoryLabel, text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = metric6Tooltip, width = gridLabelWidth)
        table.cell(gridTable, 0, 9, "HTF", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = "Higher-timeframe trend from the previous completed candle.", width = gridLabelWidth)
        table.cell(gridTable, 0, 10, "ROLE", text_color = cWhite, bgcolor = cHeader, text_size = size.tiny, text_formatting = text.format_bold, tooltip = "Classifier interpretation for the candle. Hover a role cell for HTF, alignment and CVD details.", width = gridLabelWidth)
        for col = 1 to visibleHistoryBars
            int barsAgo = visibleHistoryBars - col + 1
            int idx = historyDisplaySize - barsAgo
            bool valid = idx >= 0 and idx < historySize
            float bVal = valid ? array.get(histBuyVol, idx) : na
            float sVal = valid ? array.get(histSellVol, idx) : na
            float dVal = valid ? array.get(histDelta, idx) : na
            float pVal = valid ? array.get(histDeltaPct, idx) : na
            float tVal = valid ? array.get(histTotal, idx) : na
            string m5Val = valid ? array.get(histMetric5, idx) : ""
            string m6Val = valid ? array.get(histMetric6, idx) : ""
            string htfVal = valid ? array.get(histHtf, idx) : ""
            string roleVal = valid ? array.get(histRole, idx) : ""
            string alignVal = valid ? array.get(histAlign, idx) : ""
            string cvdVal = valid ? array.get(histCvd, idx) : ""
            string methodVal = valid ? array.get(histDataMethod, idx) : ""
            string divVal = valid ? array.get(histDiv, idx) : "None"
            int candleTime = valid ? array.get(histTime, idx) : na
            string timeVal = valid ? str.format_time(candleTime, historyTimeFormat, historyTimezone) : ""
            string barVal = valid ? "-" + str.tostring(barsAgo) : ""
            float oVal = valid ? array.get(histOpen, idx) : na
            float hVal = valid ? array.get(histHigh, idx) : na
            float lVal = valid ? array.get(histLow, idx) : na
            float cVal = valid ? array.get(histClose, idx) : na
            float vVal = valid ? array.get(histChartVolume, idx) : na
            float candleRange = valid ? hVal - lVal : na
            float bodyShare = valid and candleRange > 0 ? math.abs(cVal - oVal) / candleRange * 100.0 : na
            float closeShare = valid and candleRange > 0 ? (cVal - lVal) / candleRange * 100.0 : na
            string timeTip = valid ?
                 str.format_time(candleTime, "yyyy-MM-dd HH:mm:ss", historyTimezone) + " (exchange time)" +
                 "\nOHLC: " + str.tostring(oVal, format.mintick) + " / " + str.tostring(hVal, format.mintick) + " / " + str.tostring(lVal, format.mintick) + " / " + str.tostring(cVal, format.mintick) +
                 "\nChart volume: " + (na(vVal) ? "N/A" : f_formatVol(vVal)) + " · Selected total (reported): " + (na(tVal) ? "N/A" : f_formatVol(tVal)) +
                 "\nBody: " + (na(bodyShare) ? "N/A" : str.tostring(bodyShare, "#.0") + "%") + " · Close location: " + (na(closeShare) ? "N/A" : str.tostring(closeShare, "#.0") + "%") +
                 "\nBuy: " + (na(bVal) ? "N/A" : selectedValuePrefix + f_formatVol(bVal)) + " · Sell: " + (na(sVal) ? "N/A" : selectedValuePrefix + f_formatVol(sVal)) +
                 "\nDelta: " + (na(dVal) ? "N/A" : selectedValuePrefix + (dVal >= 0 ? "+" : "") + f_formatVol(dVal)) + " (" + (na(pVal) ? "N/A" : selectedValuePrefix + str.tostring(pVal, "#.0") + "%") + ")" +
                 "\n" + metric5HistoryLabel + ": " + m5Val + " · " + metric6HistoryLabel + ": " + m6Val +
                 "\nHTF: " + htfVal + " · Role: " + roleVal +
                 "\nAlignment: " + alignVal + " · CVD: " + cvdVal +
                 "\nCalculation method: " + methodVal + "\nSecondary divergence: " + divVal : ""
            table.cell(gridTable, col, 1, barVal, text_color = color.new(cWhite, 35), bgcolor = cHeader, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 2, timeVal, text_color = color.new(cWhite, 25), bgcolor = cPanel, text_size = size.tiny, tooltip = timeTip, width = gridDataWidth)
            table.cell(gridTable, col, 3, na(bVal) ? "N/A" : selectedValuePrefix + f_formatVol(bVal), text_color = cBuy, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 4, na(sVal) ? "N/A" : selectedValuePrefix + f_formatVol(sVal), text_color = cSell, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 5, na(dVal) ? "N/A" : selectedValuePrefix + (dVal >= 0 ? "+" : "") + f_formatVol(dVal), text_color = na(dVal) ? cNeutral : dVal >= 0 ? cBuy : cSell, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 6, na(pVal) ? "N/A" : selectedValuePrefix + (pVal >= 0 ? "+" : "") + str.tostring(pVal, "#.#") + "%", text_color = na(pVal) ? cNeutral : pVal >= 0 ? cBuy : cSell, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 7, m5Val, text_color = cWhite, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 8, m6Val, text_color = cWhite, bgcolor = cPanel, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 9, htfVal, text_color = color.white, bgcolor = htfVal == "Bullish" ? c_bull : htfVal == "Bearish" ? c_bear : c_chp, text_size = size.tiny, width = gridDataWidth)
            table.cell(gridTable, col, 10, f_monitorRole(roleVal), text_color = f_contrastText(f_roleTextColor(roleVal)), bgcolor = f_roleTextColor(roleVal), text_size = size.tiny, tooltip = "ROLE: " + roleVal + "\nHTF: " + htfVal + " · ALIGN: " + alignVal + " · CVD: " + cvdVal + "\nDivergence: " + divVal + "\nMethod: " + methodVal, width = gridDataWidth)
        int liveCol = visibleHistoryBars + 1
        table.cell(gridTable, liveCol, 1, "CURRENT", text_color = color.black, bgcolor = cGold, text_size = size.tiny, text_formatting = text.format_bold, width = gridDataWidth)
        table.cell(gridTable, liveCol, 2, str.format_time(time, historyTimeFormat, historyTimezone), text_color = cWhite, bgcolor = cLiveBg, text_size = size.tiny, tooltip = barstate.isconfirmed ? "Current candle confirmed (exchange time)." : "Current candle is developing (exchange time).", width = gridDataWidth)
        table.cell(gridTable, liveCol, 3, selectedBuyText, text_color = cBuy, bgcolor = cLiveBg, text_size = size.tiny, tooltip = volumeTooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 4, selectedSellText, text_color = cSell, bgcolor = cLiveBg, text_size = size.tiny, tooltip = volumeTooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 5, selectedDeltaText, text_color = na(selectedDelta) ? cNeutral : selectedDelta >= 0 ? cBuy : cSell, bgcolor = cLiveBg, text_size = size.tiny, tooltip = deltaTooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 6, selectedDeltaPctText, text_color = na(selectedDeltaPct) ? cNeutral : selectedDeltaPct >= 0 ? cBuy : cSell, bgcolor = cLiveBg, text_size = size.tiny, tooltip = deltaTooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 7, selectedMetric5Text, text_color = cWhite, bgcolor = cLiveBg, text_size = size.tiny, tooltip = metric5Tooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 8, selectedMetric6Text, text_color = cWhite, bgcolor = cLiveBg, text_size = size.tiny, tooltip = metric6Tooltip, width = gridDataWidth)
        table.cell(gridTable, liveCol, 9, htfText, text_color = color.white, bgcolor = regimeColor, text_size = size.tiny, width = gridDataWidth)
        table.cell(gridTable, liveCol, 10, f_monitorRole(dashCharText), text_color = f_contrastText(f_roleTextColor(dashCharText)), bgcolor = f_roleTextColor(dashCharText), text_size = size.tiny, tooltip = detailTooltip, width = gridDataWidth)
    else
        table.clear(gridTable, 0, 0, visibleHistoryBars + 1, 10)
 
 
 
// CHART DATA-SOURCE BADGE
 
var table ofccModeBadge = table.new(
     position.bottom_right, 1, 1,
     bgcolor = color.new(#131722, 0),
     border_width = 1,
     border_color = color.new(#363a45, 0),
     force_overlay = true)
 
if barstate.islast
    if showModeBadgeInput
        string modeBadgeText = useNativeFootprint ? "MODE · FOOTPRINT" : "MODE · ESTIMATED OHLCV"
 
        string modeBadgeTip = useNativeFootprint ?
             (haveFP ? "Selected source: TradingView native Footprint. Current candle has native footprint data." : "Selected source: TradingView native Footprint. Current candle data is unavailable; no OHLCV substitute is used.") :
             hasIntrabarDirectionEstimate ? "Selected source: Estimated OHLCV. Current candle uses lower-timeframe directional-volume allocation." :
             hasChartVolume ? "Selected source: Estimated OHLCV. Current candle uses the chart-candle close-location proxy." :
             "Selected source: Estimated OHLCV. Volume data is unavailable."
 
        table.cell(
             ofccModeBadge, 0, 0,
             modeBadgeText,
             text_color = color.white,
             bgcolor = useNativeFootprint ? color.new(#2855A6, 0) : color.new(#147D72, 0),
             text_size = size.tiny,
             text_halign = text.align_center,
             tooltip = modeBadgeTip)
    else
        table.clear(ofccModeBadge, 0, 0, 0, 0)
 
 
 
// ALERTS - ONE UNIVERSAL ROUTE OR INDIVIDUAL EVENT CHOICES
// The universal alert sends one detailed message for every non-neutral candle role
// and for a standalone bullish/bearish confirmed pivot-to-pivot delta divergence. Individual conditions let
// users create alerts only for the events they follow.
// In TradingView, choose either "Any alert() function call" for the universal route,
// or one/more named OFCC conditions for individual events. Do not create both types
// for the same event unless duplicate notifications are intentional.
 
bool roleAlertReady = barstate.isconfirmed and (not useNativeFootprint or haveFP)
bool divergenceAlertReady = barstate.isconfirmed and (isBullishDiv or isBearishDiv)
bool alertableRole = charCode != "CHP" and roleAlertReady
bool alertableEvent = alertableRole or divergenceAlertReady
 
// Universal message: includes the selected source and the exact pivot comparison when
// divergence is confirmed. A missing confirmation-bar Footprint reading does not cancel
// an event whose two pivot candles already passed the flow-evidence requirement.
if barstate.isrealtime and alertableEvent
    string alertRoleText = useNativeFootprint and not haveFP ? "N/A - Footprint unavailable on confirmation candle" : dashCharText
    string alertMessage = "Order Flow Candle Classifier [BullByte]" +
         "\nSymbol: " + syminfo.tickerid + " · Timeframe: " + timeframe.period +
         "\nRole: " + alertRoleText +
         (useNativeFootprint and not haveFP ? "" : "\n" + statusText) +
         "\nDivergence: " + (isBullishDiv ? "Bullish confirmed pivot-to-pivot" : isBearishDiv ? "Bearish confirmed pivot-to-pivot" : "None") +
         ((isBullishDiv or isBearishDiv) ? "\n" + divergenceDetailTooltip : "") +
         (flowWarning == "" ? "" : "\n" + flowWarning) +
         "\nConfirmation close: " + str.tostring(close, format.mintick) +
         "\nSelected delta: " + selectedDeltaText + " · Delta %: " + selectedDeltaPctText +
         "\nSource: " + (useNativeFootprint ? "TradingView Footprint" : "Estimated OHLCV")
    alert(alertMessage, alert.freq_once_per_bar_close)
 
// Individual alert choices. Each message is deliberately static so it appears as
// its own selectable condition in TradingView's Create Alert dialog.
alertcondition(alertableRole and charCode == "BULL", "OFCC · Bullish Initiative / Response", "OFCC bullish initiative or price response on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "BEAR", "OFCC · Bearish Initiative / Response", "OFCC bearish initiative or price response on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "ABS" and charEventSide == "BUY", "OFCC · Buyer Response", "OFCC buyer response candidate on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "ABS" and charEventSide == "SELL", "OFCC · Seller Response", "OFCC seller response candidate on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "ABS" and charEventSide == "", "OFCC · Balanced Absorption", "OFCC balanced absorption interpretation on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "EXHT" and charEventSide == "BUY", "OFCC · Buyer Exhaustion", "OFCC buyer exhaustion interpretation on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "EXHT" and charEventSide == "SELL", "OFCC · Seller Exhaustion", "OFCC seller exhaustion interpretation on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "TRAP" and charEventSide == "BUY", "OFCC · Failed High / Buy Trap", "OFCC failed-high / buy-trap interpretation on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "TRAP" and charEventSide == "SELL", "OFCC · Failed Low / Sell Trap", "OFCC failed-low / sell-trap interpretation on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "CONT" and charDir == 1, "OFCC · Upward Auction", "OFCC upward auction state on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "CONT" and charDir == -1, "OFCC · Downward Auction", "OFCC downward auction state on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "PULL" and auctionState == "UP", "OFCC · Pullback in Upward Auction", "OFCC pullback within an upward auction on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(alertableRole and charCode == "PULL" and auctionState == "DOWN", "OFCC · Pullback in Downward Auction", "OFCC pullback within a downward auction on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(divergenceAlertReady and isBullishDiv, "OFCC · Bullish Delta Divergence", "OFCC bullish price/delta divergence on {{ticker}} ({{interval}}). Close: {{close}}.")
alertcondition(divergenceAlertReady and isBearishDiv, "OFCC · Bearish Delta Divergence", "OFCC bearish price/delta divergence on {{ticker}} ({{interval}}). Close: {{close}}.")

← 返回列表