Auto Anchored VWAP [Auto AVWAP]

GoofyFarmer · study · 729 行 · 点赞 99 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GoofyFarmer — Systems Research & Quantitative Practice
// Master References: CME 24-Hour Auction Market Theory (AMT), Microstructural Variance & Polyline Geometry
 
//@version=6
indicator("Autonomous Structure-Anchored VWAP [Auto SAVWAP]", 
          shorttitle = "AutoSAVWAP", 
          overlay = true, 
          max_bars_back = 2000,
          max_lines_count = 500, 
          max_boxes_count = 500, 
          max_labels_count = 500,
          max_polylines_count = 100)
 
// -----------------------------------------------------------------------------
// 1. CORE VECTOR GEOMETRY & ASSOCIATIVE MEMORY IMPORT
//    Powered by GoofyFarmer/IsotropicVectorSpace/1 (Unit-Hypersphere k-NN)
// -----------------------------------------------------------------------------
import GoofyFarmer/IsotropicVectorSpace/1 as ivs
 
// ============================================================================
// 2. ARCHITECTURAL & OPERATOR INPUTS
// ============================================================================
grp_savwap = "1. SAVWAP Structural Anchor & Mechanics"
savwap_mode = input.string(
     "Dynamic Structural Impulse (Sweep / Climax Latch)",
     "Anchor Mechanics Mode",
     options = [
         "Dynamic Structural Impulse (Sweep / Climax Latch)",
         "Dynamic Swing Extremes (Pivot High / Low Latch)",
         "Static Session Benchmark (09:30 RTH / 00:00 UTC)"
     ],
     group = grp_savwap,
     tooltip = "Anchor Mechanics:\n• Dynamic Structural Impulse (Recommended): Latches t_0 to structural liquidity sweeps (ONH/ONL/PDH/PDL), high-volume climax absorption pivots, or conviction directional expansions.\n• Dynamic Swing Extremes: Latches to confirmed fractal price highs/lows.\n• Static Session Benchmark: Standard clock session VWAP (09:30 RTH for CME/Equities, 00:00 UTC for Crypto)."
 )
 
session_profile = input.string(
     "Auto-Detect Asset Session",
     "Session Model",
     options = [
         "Auto-Detect Asset Session",
         "CME Globex 24-Hour (18:00 - 17:00 ET)",
         "Crypto 24/7 Continuous (00:00 UTC Day)",
         "Equities Regular (09:30 - 16:00 ET)"
     ],
     group = grp_savwap,
     tooltip = "Session Adaptation:\n• Auto-Detect: Identifies chart asset type (Crypto, CME Futures, Equities) and automatically applies institutional session anchors and liquidity levels.\n• CME Globex: Anchors to 18:00 ET Overnight and 09:30 ET RTH.\n• Crypto 24/7: Continuous trading with 00:00 UTC daily session rollover.\n• Equities: US Cash Session 09:30 - 16:00 ET."
 )
 
latch_atr_mult = input.float(1.5, "Impulse Latch Sensitivity (ATR Multiple)", minval = 0.5, maxval = 4.0, step = 0.25, group = grp_savwap)
min_hold_bars  = input.int(5, "Min Anchor Hold Duration (Bars)", minval = 1, maxval = 30, group = grp_savwap, tooltip = "Prevents micro-flip step ladders during tight consolidation by enforcing a minimum structural anchor lifespan.")
swing_len      = input.int(5, "Swing Pivot Lookback (Bars)", minval = 2, maxval = 30, group = grp_savwap)
 
grp_vol = "2. Volume Weighting Engine & Multi-Tier Feeds"
vol_engine = input.string(
     "Auto-Detect (Real Volume with Range Proxy Fallback)",
     "Volume Weighting Engine",
     options = [
         "Auto-Detect (Real Volume with Range Proxy Fallback)",
         "Pure Exchange Volume",
         "Tick / Range Imbalance Proxy"
     ],
     group = grp_vol,
     tooltip = "Multi-Tier Volume Architecture across TradingView Tiers:\n• Auto-Detect (Recommended): Dynamically uses real exchange volume where present (Futures, Equities, Crypto); seamlessly activates synthetic tick/range proxy on non-volume feeds (SPX, NDX, FX) or missing bars.\n• Pure Exchange Volume: Strictly uses raw exchange volume; falls back to unweighted (1.0) if missing.\n• Tick / Range Imbalance Proxy: Weights bars strictly by microstructural excursion (Bar Range / MinTick) regardless of feed availability."
 )
 
grp_htf = "3. Higher-Timeframe (HTF) Macro Context"
show_htf_vwap  = input.bool(false, "Show HTF Macro VWAP on Chart", group = grp_htf, tooltip = "Disabled by default to maintain pristine candlestick clarity. HTF Macro VWAP remains continuously active under the hood to power the Telemetry HUD and the ML Anchor Conviction Engine.")
htf_res        = input.timeframe("D", "HTF Timeframe Anchor", group = grp_htf, tooltip = "Higher-timeframe volume anchor used for macro directional filtering and ML confluence.")
 
grp_bands = "4. Volume-Weighted Variance Corridors & Visuals"
render_style      = input.string("Discrete Polyline Spines (Clean Modern)", "Render Architecture", options = ["Discrete Polyline Spines (Clean Modern)", "Continuous Plot Ribbon (Classic)"], group = grp_bands, tooltip = "• Discrete Polyline Spines (Recommended): Completely eliminates the ugly connecting ribbon and step jumps. Renders the clean current developing anchor segment, plus past completed anchor spines.\n• Continuous Plot Ribbon: Plots standard continuous lines across all bars.")
max_past_sess     = input.int(10, "Max Past SAVWAP Spines Preserved", minval = 1, maxval = 25, group = grp_bands, tooltip = "Number of completed historical SAVWAP curves to preserve as faint dashed spines on the chart (1 to 25).")
past_spine_transp = input.int(70, "Past SAVWAP Spines Transparency (%)", minval = 20, maxval = 95, step = 5, group = grp_bands, tooltip = "Opacity of preserved historical SAVWAP dashed spines (lower is more visible, higher is fainter).")
show_sd1          = input.bool(true,  "Show ±1.0σ Tactical Trend-Walk Corridor", group = grp_bands)
show_sd2          = input.bool(true,  "Show ±2.0σ Statistical Exhaustion Boundary", group = grp_bands)
show_sd3          = input.bool(false, "Show ±3.0σ Tail Outlier Corridor (Chart Plot)", group = grp_bands)
fill_corr         = input.bool(true,  "Fill ±1.0σ Tactical Corridor Cloud", group = grp_bands)
cloud_transp      = input.int(95, "Corridor Cloud Transparency (%)", minval = 80, maxval = 98, step = 1, group = grp_bands)
 
grp_hud = "5. Microstructural Telemetry & Pivot Badges"
show_hud       = input.bool(true, "Show Telemetry HUD Table", group = grp_hud)
hud_position   = input.string("Top Right", "HUD Position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = grp_hud)
show_anc_tags  = input.bool(true, "Show Structural Pivot & Anchor Badges", group = grp_hud)
badge_style    = input.string("Sleek Tags (High / Low Price)", "Badge Style", options = ["Sleek Tags (High / Low Price)", "Minimalist Pips (Clean ⚓)", "Full Detailed Cards"], group = grp_hud)
tag_max_cap    = input.int(35, "Max Anchor Badges on Chart (FIFO)", minval = 5, maxval = 100, group = grp_hud)
 
grp_ml = "6. Microstructural Machine Learning (IVS)"
enable_ml_eval = input.bool(true, "Enable ML Anchor Conviction Scorer", group = grp_ml, tooltip = "Synthesizes a 4D microstructural vector on each anchor (Volume Surge, Wick Asymmetry, Isotropic Theta, and HTF Alignment) and queries past anchor twin setups using unit-hypersphere vector memory.")
sim_threshold  = input.float(0.20, "k-NN Cosine Similarity Threshold", minval = 0.05, maxval = 0.80, step = 0.05, group = grp_ml)
 
// ============================================================================
// 3. ASSET-AWARE SESSION ENGINE (CME FUTURES / CRYPTO 24/7 / EQUITIES)
// ============================================================================
bool is_crypto_mode = session_profile == "Crypto 24/7 Continuous (00:00 UTC Day)" or (session_profile == "Auto-Detect Asset Session" and syminfo.type == "crypto")
bool is_futures_mode = session_profile == "CME Globex 24-Hour (18:00 - 17:00 ET)" or (session_profile == "Auto-Detect Asset Session" and syminfo.type == "futures")
 
// 1. CME Globex & RTH Session Strings (America/New_York)
string SESS_CME_RTH = "0930-1600:23456"
string SESS_CME_GLX = "1800-0930:23456"
 
// 2. Crypto 24/7 Daily Rollover Anchor (00:00 UTC)
int  t_crypto_d    = time("D", "0000-2359:1234567", "UTC")
bool is_crypto_day = not na(t_crypto_d) and (na(t_crypto_d[1]) or t_crypto_d != t_crypto_d[1])
 
// 3. CME Futures Triggers
bool in_cme_rth    = not na(time(timeframe.period, SESS_CME_RTH, "America/New_York"))
bool in_cme_glx    = not na(time(timeframe.period, SESS_CME_GLX, "America/New_York"))
bool is_cme_rth_op = in_cme_rth and not in_cme_rth[1]
bool is_cme_glx_op = in_cme_glx and not in_cme_glx[1]
 
// 4. Equities / Stocks Triggers
bool in_eq_rth     = not na(time(timeframe.period, "0930-1600:23456", "America/New_York"))
bool is_eq_rth_op  = in_eq_rth and not in_eq_rth[1]
 
// Unified Session Open Triggers
bool is_sess_open  = is_crypto_mode ? is_crypto_day : (is_futures_mode ? is_cme_rth_op : is_eq_rth_op)
bool is_glx_open   = is_crypto_mode ? false : (is_futures_mode ? is_cme_glx_op : false)
bool in_sess_raw   = is_crypto_mode ? true : (is_futures_mode ? in_cme_rth : in_eq_rth)
bool in_glx_raw    = is_crypto_mode ? false : (is_futures_mode ? in_cme_glx : false)
 
// Prior Day & Overnight Extreme Tracking
var float cur_sess_hi = na
var float cur_sess_lo = na
var float cur_sess_op = na
var float cur_sess_cl = na
 
var float pd_high  = na
var float pd_low   = na
var float pd_close = na
 
if is_sess_open
    if not na(cur_sess_hi) and not na(cur_sess_lo)
        pd_high  := cur_sess_hi
        pd_low   := cur_sess_lo
        pd_close := cur_sess_cl
    cur_sess_op := open
    cur_sess_hi := high
    cur_sess_lo := low
    cur_sess_cl := close
else if in_sess_raw
    cur_sess_hi := math.max(not na(cur_sess_hi) ? cur_sess_hi : high, high)
    cur_sess_lo := math.min(not na(cur_sess_lo) ? cur_sess_lo : low, low)
    cur_sess_cl := close
 
var float on_high    = na
var float on_low     = na
var float locked_onh = na
var float locked_onl = na
 
if is_glx_open
    on_high := high
    on_low  := low
else if in_glx_raw
    on_high := math.max(not na(on_high) ? on_high : high, high)
    on_low  := math.min(not na(on_low) ? on_low : low, low)
 
if is_sess_open
    locked_onh := is_crypto_mode ? pd_high : on_high
    locked_onl := is_crypto_mode ? pd_low  : on_low
 
// Volatility & Relative Volume Sensors
float atr14_raw  = ta.atr(14)
float atr14      = math.max(not na(atr14_raw) ? atr14_raw : syminfo.mintick * 10.0, syminfo.mintick)
float bar_rng    = math.max(syminfo.mintick, high - low)
float upper_wick = (high - math.max(open, close)) / bar_rng
float lower_wick = (math.min(open, close) - low) / bar_rng
 
// Multi-Tier Volume Engine & Range Proxy Synthesizer
float safe_mintick     = not na(syminfo.mintick) and syminfo.mintick > 0.0 ? syminfo.mintick : 0.01
float tick_range_proxy = math.max(1.0, bar_rng / safe_mintick)
bool  has_real_vol     = not na(volume) and volume > 0.0
 
float v_bar            = 1.0
string vol_mode_str    = "Auto: Real Vol"
color  vol_status_col  = #10B981
 
if vol_engine == "Pure Exchange Volume"
    v_bar          := math.max(1.0, nz(volume, 1.0))
    vol_mode_str   := has_real_vol ? "Exchange Vol" : "Flat (No Vol)"
    vol_status_col := has_real_vol ? #10B981 : #F59E0B
else if vol_engine == "Tick / Range Imbalance Proxy"
    v_bar          := tick_range_proxy
    vol_mode_str   := "Range Proxy"
    vol_status_col := #38BDF8
else // "Auto-Detect (Real Volume with Range Proxy Fallback)"
    if has_real_vol
        v_bar          := volume
        vol_mode_str   := "Auto: Real Vol"
        vol_status_col := #10B981
    else
        v_bar          := tick_range_proxy
        vol_mode_str   := "Auto: Range Proxy"
        vol_status_col := #F59E0B
 
float vol_sma20  = ta.sma(v_bar, 20)
float rvol_bar   = not na(vol_sma20) and vol_sma20 > 0.0 ? (v_bar / vol_sma20) : 1.0
 
// Microstructural Sweep & Climax Conditions
bool swept_demand = (not na(locked_onl) and low <= locked_onl and close > locked_onl) or (not na(pd_low) and low <= pd_low and close > pd_low)
bool swept_supply = (not na(locked_onh) and high >= locked_onh and close < locked_onh) or (not na(pd_high) and high >= pd_high and close < pd_high)
bool climax_demand = (rvol_bar >= 1.50 and lower_wick >= 0.30 and close >= open) or swept_demand
bool climax_supply = (rvol_bar >= 1.50 and upper_wick >= 0.30 and close <= open) or swept_supply
 
// Higher-Timeframe Macro VWAP Anchor
float cur_base_vwap  = ta.vwap(hlc3)
float safe_base_vwap = not na(cur_base_vwap) ? cur_base_vwap : hlc3
float htf_vwap_raw   = request.security(syminfo.tickerid, htf_res, safe_base_vwap, lookahead = barmerge.lookahead_off, gaps = barmerge.gaps_off)
float htf_vwap       = not na(htf_vwap_raw) ? htf_vwap_raw : safe_base_vwap
bool  htf_bull       = close >= htf_vwap
 
// ============================================================================
// 4. DYNAMIC SAVWAP STATE MACHINE & ANCHOR DETECTOR
// ============================================================================
var int    anc_bar   = 0
var int    anc_time  = time
var float  anc_price = close
var string anc_type  = "Session Init"
var int    sav_dir   = 0 // +1: Bullish Impulse Anchor, -1: Bearish Impulse Anchor
 
var float  sess_max_hi = high
var int    sess_max_hi_bar = 0
var int    sess_max_hi_time = time
 
var float  sess_min_lo = low
var int    sess_min_lo_bar = 0
var int    sess_min_lo_time = time
 
var float  cum_pv   = 0.0
var float  cum_pv2  = 0.0
var float  cum_vol  = 0.0
bool       latch_trigger    = false
bool       in_place_upgrade = false
 
float eff_latch_pts = latch_atr_mult * atr14
 
// Historical Anchor Ring Buffers for Past Spines
var array<int>   past_anc_bars = array.new<int>()
var array<int>   past_end_bars = array.new<int>()
var array<float> past_anc_pxs  = array.new<float>()
var array<int>   past_anc_dirs = array.new<int>()
 
// Fractal Pivot Anchors
float ph = ta.pivothigh(high, swing_len, swing_len)
float pl = ta.pivotlow(low, swing_len, swing_len)
 
// Archive completed anchor when a new structural anchor latches
f_archive_anchor(int old_b, int old_end_b, float old_p, int old_dir) =>
    if old_b > 0 and (old_end_b - old_b) >= 5
        array.push(past_anc_bars, old_b)
        array.push(past_end_bars, old_end_b)
        array.push(past_anc_pxs,  old_p)
        array.push(past_anc_dirs, old_dir)
        while array.size(past_anc_bars) > 25
            array.shift(past_anc_bars)
            array.shift(past_end_bars)
            array.shift(past_anc_pxs)
            array.shift(past_anc_dirs)
 
if bar_index == 0 or (savwap_mode == "Static Session Benchmark (09:30 RTH / 00:00 UTC)" and is_sess_open)
    if anc_bar > 0
        f_archive_anchor(anc_bar, bar_index - 1, anc_price, sav_dir)
    anc_bar       := bar_index
    anc_time      := time
    anc_price     := hlc3
    anc_type      := is_crypto_mode ? "Daily UTC Open" : (is_futures_mode ? "CME RTH Open" : "Session Open")
    sav_dir       := 0
    sess_max_hi   := high
    sess_min_lo   := low
    latch_trigger := true
 
else if savwap_mode == "Dynamic Swing Extremes (Pivot High / Low Latch)"
    if not na(ph)
        if sav_dir == -1 and high[swing_len] > anc_price
            // Same-polarity higher high upgrade in-place
            anc_bar          := bar_index - swing_len
            anc_time         := time[swing_len]
            anc_price        := high[swing_len]
            in_place_upgrade := true
        else if sav_dir != -1
            if anc_bar > 0
                f_archive_anchor(anc_bar, bar_index - swing_len, anc_price, sav_dir)
            anc_bar       := bar_index - swing_len
            anc_time      := time[swing_len]
            anc_price     := high[swing_len]
            anc_type      := "Swing High"
            sav_dir       := -1
            latch_trigger := true
    else if not na(pl)
        if sav_dir == 1 and low[swing_len] < anc_price
            // Same-polarity lower low upgrade in-place
            anc_bar          := bar_index - swing_len
            anc_time         := time[swing_len]
            anc_price        := low[swing_len]
            in_place_upgrade := true
        else if sav_dir != 1
            if anc_bar > 0
                f_archive_anchor(anc_bar, bar_index - swing_len, anc_price, sav_dir)
            anc_bar       := bar_index - swing_len
            anc_time      := time[swing_len]
            anc_price     := low[swing_len]
            anc_type      := "Swing Low"
            sav_dir       := 1
            latch_trigger := true
 
else if savwap_mode == "Dynamic Structural Impulse (Sweep / Climax Latch)"
    bool is_bar_closed = barstate.isconfirmed or not barstate.isrealtime
 
    if is_sess_open
        if anc_bar > 0
            f_archive_anchor(anc_bar, bar_index - 1, anc_price, sav_dir)
        sess_max_hi      := high
        sess_max_hi_bar  := bar_index
        sess_max_hi_time := time
        sess_min_lo      := low
        sess_min_lo_bar  := bar_index
        sess_min_lo_time := time
        anc_bar          := bar_index
        anc_time         := time
        anc_price        := open
        anc_type         := is_crypto_mode ? "Daily UTC Open" : "RTH Open"
        sav_dir          := close >= open ? 1 : -1
        latch_trigger    := true
    else
        // Track developing session extremes (always active across all ticks)
        if high >= sess_max_hi
            sess_max_hi      := high
            sess_max_hi_bar  := bar_index
            sess_max_hi_time := time
 
        if low <= sess_min_lo
            sess_min_lo      := low
            sess_min_lo_bar  := bar_index
            sess_min_lo_time := time
 
        // Structural re-anchoring, in-place upgrades, and array archival are strictly gated by
        // barstate.isconfirmed to prevent real-time tick flickering and array buffer pollution
        bool can_reanchor = (bar_index - anc_bar) >= min_hold_bars and is_bar_closed
 
        if sav_dir == -1 and sess_max_hi_bar != anc_bar and is_bar_closed and high >= sess_max_hi
            // Same-Polarity In-Place Upgrade on confirmed bar close
            anc_bar          := sess_max_hi_bar
            anc_time         := sess_max_hi_time
            anc_price        := sess_max_hi
            anc_type         := "Impulse Crest"
            in_place_upgrade := true
 
        else if sav_dir == 1 and sess_min_lo_bar != anc_bar and is_bar_closed and low <= sess_min_lo
            // Same-Polarity In-Place Upgrade on confirmed bar close
            anc_bar          := sess_min_lo_bar
            anc_time         := sess_min_lo_time
            anc_price        := sess_min_lo
            anc_type         := "Impulse Trough"
            in_place_upgrade := true
 
        bool valid_demand_loc = low <= sess_min_lo + 0.5 * eff_latch_pts
        bool valid_supply_loc = high >= sess_max_hi - 0.5 * eff_latch_pts
 
        if sav_dir <= 0 and can_reanchor and (close >= sess_min_lo + eff_latch_pts or (climax_demand and valid_demand_loc))
            f_archive_anchor(anc_bar, sess_min_lo_bar, anc_price, sav_dir)
            sav_dir          := 1
            anc_bar          := sess_min_lo_bar
            anc_time         := sess_min_lo_time
            anc_price        := sess_min_lo
            anc_type         := climax_demand ? (swept_demand ? "Sweep Demand" : "Climax Demand") : "Bull Impulse"
            sess_max_hi      := high
            sess_max_hi_bar  := bar_index
            sess_max_hi_time := time
            latch_trigger    := true
 
        else if sav_dir >= 0 and can_reanchor and (close <= sess_max_hi - eff_latch_pts or (climax_supply and valid_supply_loc))
            f_archive_anchor(anc_bar, sess_max_hi_bar, anc_price, sav_dir)
            sav_dir          := -1
            anc_bar          := sess_max_hi_bar
            anc_time         := sess_max_hi_time
            anc_price        := sess_max_hi
            anc_type         := climax_supply ? (swept_supply ? "Sweep Supply" : "Climax Supply") : "Bear Impulse"
            sess_min_lo      := low
            sess_min_lo_bar  := bar_index
            sess_min_lo_time := time
            latch_trigger    := true
 
// ============================================================================
// 5. TRUE VOLUME-WEIGHTED ACCUMULATION & VARIANCE CORRIDORS
// ============================================================================
float p_bar = hlc3
// Note: v_bar is instantiated upstream in Section 3 (Multi-Tier Volume Engine)
 
max_bars_back(p_bar, 2000)
max_bars_back(v_bar, 2000)
max_bars_back(rvol_bar, 2000)
max_bars_back(lower_wick, 2000)
max_bars_back(upper_wick, 2000)
 
if latch_trigger or in_place_upgrade
    int lookback = math.min(math.max(0, bar_index - anc_bar), 1900)
    float sum_pv  = 0.0
    float sum_pv2 = 0.0
    float sum_v   = 0.0
    for k = 0 to lookback
        float pk = p_bar[k]
        float vk = v_bar[k]
        sum_pv  += pk * vk
        sum_pv2 += pk * pk * vk
        sum_v   += vk
    cum_pv  := sum_pv
    cum_pv2 := sum_pv2
    cum_vol := sum_v
else
    cum_pv  += p_bar * v_bar
    cum_pv2 += p_bar * p_bar * v_bar
    cum_vol += v_bar
 
float savwap_val = cum_vol > 0.0 ? (cum_pv / cum_vol) : close
float raw_var    = cum_vol > 0.0 ? ((cum_pv2 / cum_vol) - (savwap_val * savwap_val)) : 0.0
float savwap_sd  = math.sqrt(math.max(syminfo.mintick * syminfo.mintick, raw_var))
 
// Corridor Bounds
float upper_1sd = savwap_val + savwap_sd
float lower_1sd = savwap_val - savwap_sd
float upper_2sd = savwap_val + 2.0 * savwap_sd
float lower_2sd = savwap_val - 2.0 * savwap_sd
float upper_3sd = savwap_val + 3.0 * savwap_sd
float lower_3sd = savwap_val - 3.0 * savwap_sd
 
// True Wall-Clock Elapsed Time
float elapsed_minutes = math.max(0.0, float(time - anc_time) / 60000.0)
int   elapsed_hrs     = int(elapsed_minutes / 60.0)
int   elapsed_mins_rem= int(elapsed_minutes) % 60
string elapsed_str    = (elapsed_hrs > 0 ? str.tostring(elapsed_hrs) + "h " : "") + str.tostring(elapsed_mins_rem) + "m"
 
// Z-Score Relative to Developing Volume-Weighted Variance
float z_score = savwap_sd > 0.0 ? (close - savwap_val) / savwap_sd : 0.0
 
// ============================================================================
// 6. STRUCTURAL VECTOR SIMILARITY ENGINE (IVS LIBRARY)
// ============================================================================
var array<ivs.VectorMem> anchor_mem = array.new<ivs.VectorMem>()
var float cur_conviction  = 50.0
var float cur_ml_sim      = 0.0
var int   cur_ml_twins    = 0
 
float dir_sign = sav_dir == -1 ? -1.0 : 1.0
 
if latch_trigger and enable_ml_eval
    int anc_off = math.min(math.max(0, bar_index - anc_bar), 250)
 
    // 1. Coordinate 1: Volume Surge Intensity at Pivot Inception / Latch
    float rvol_piv = math.max(rvol_bar, not na(rvol_bar[anc_off]) ? rvol_bar[anc_off] : rvol_bar)
    float f1_vol   = ivs.sigmoid_fast(rvol_piv - 1.0)
    
    // 2. Coordinate 2: Wick Absorption Asymmetry
    float wick_cur = (lower_wick - upper_wick) * dir_sign
    float wick_piv = not na(lower_wick[anc_off]) ? (lower_wick[anc_off] - upper_wick[anc_off]) * dir_sign : wick_cur
    float f2_abs   = math.max(wick_cur, wick_piv)
    
    // 3. Coordinate 3: Isotropic Angular Departure Velocity (Theta)
    float dep_move = anc_off > 0 ? (close - anc_price) * dir_sign : (close - (not na(close[5]) ? close[5] : open)) * dir_sign
    [z_iso, theta_deg, f3_theta] = ivs.to_isotropic(dep_move, atr14, 1.5)
    
    // 4. Coordinate 4: HTF Macro Alignment (+1.0 aligned, -1.0 counter)
    float f4_htf = htf_bull ? (sav_dir >= 0 ? 1.0 : -1.0) : (sav_dir == -1 ? 1.0 : -1.0)
    
    // Query Similar Historical Anchor Twins from Unit-Sphere Memory Bank
    [twin_score, mean_sim, matches] = anchor_mem.query(f1_vol, f2_abs, f3_theta, f4_htf, sim_thresh = sim_threshold)
    cur_ml_sim   := mean_sim
    cur_ml_twins := matches
    
    // Structural Pivot Strength + Historical Twin Concordance
    float struct_score = 0.30 * f1_vol + 0.25 * f2_abs + 0.25 * f3_theta + 0.20 * f4_htf
    float combined     = matches >= 3 ? (0.75 * struct_score + 0.25 * twin_score) : struct_score
    cur_conviction     := math.min(98.0, math.max(15.0, 50.0 + combined * 42.0))
    
    // Store 4D structural vector into circular unit-sphere memory bank
    anchor_mem.insert(f1_vol, f2_abs, f3_theta, f4_htf, struct_score, 0.0, 0.0, cap = 200)
 
// ============================================================================
// 7. DISCRETE POLYLINES & PAST SAVWAP SPINES RENDERING
// ============================================================================
color col_mid   = sav_dir == 1 ? #00E5FF : (sav_dir == -1 ? #F43F5E : #6366F1)
color col_sd1   = color.new(col_mid, 60)
color col_sd2   = color.new(#F59E0B, 68)
color col_sd3   = color.new(#8B5CF6, 75)
 
// Preserving Data Window & CSV Exports (Always populated, zero nulls)
plot(savwap_val, "SAVWAP Midline", color = render_style == "Continuous Plot Ribbon (Classic)" ? col_mid : na, linewidth = 2, display = display.all)
plot(upper_1sd,  "+1.0σ Tactical Upper", color = render_style == "Continuous Plot Ribbon (Classic)" and show_sd1 ? col_sd1 : na, linewidth = 1, display = display.all)
plot(lower_1sd,  "-1.0σ Tactical Lower", color = render_style == "Continuous Plot Ribbon (Classic)" and show_sd1 ? col_sd1 : na, linewidth = 1, display = display.all)
plot(upper_2sd,  "+2.0σ Exhaustion Upper", color = render_style == "Continuous Plot Ribbon (Classic)" and show_sd2 ? col_sd2 : na, linewidth = 1, display = display.all)
plot(lower_2sd,  "-2.0σ Exhaustion Lower", color = render_style == "Continuous Plot Ribbon (Classic)" and show_sd2 ? col_sd2 : na, linewidth = 1, display = display.all)
plot(upper_3sd,  "+3.0σ Tail Upper", color = col_sd3, linewidth = 1, display = show_sd3 and render_style == "Continuous Plot Ribbon (Classic)" ? display.all : display.data_window)
plot(lower_3sd,  "-3.0σ Tail Lower", color = col_sd3, linewidth = 1, display = show_sd3 and render_style == "Continuous Plot Ribbon (Classic)" ? display.all : display.data_window)
 
// HTF Macro VWAP Spine (Distinct Royal Purple Circles)
plot(show_htf_vwap ? htf_vwap : na, "HTF Macro VWAP", color = color.new(#A855F7, 25), linewidth = 2, style = plot.style_circles, display = display.pane)
 
// Diagnostic & Quantitative Research Data Window Export (Accessible via CSV & Inspector)
plot(enable_ml_eval ? cur_conviction : na, "Anchor Conviction Score", display = display.data_window)
plot(enable_ml_eval ? cur_ml_twins : na,   "Anchor Historical Twins",  display = display.data_window)
plot(enable_ml_eval ? cur_ml_sim : na,     "Anchor Twin Avg Similarity", display = display.data_window)
 
// Discrete Polylines Engine (Draws active anchor curve without historical connecting step jumps)
var polyline poly_active_spine = na
var polyline poly_active_u1    = na
var polyline poly_active_d1    = na
var polyline poly_active_u2    = na
var polyline poly_active_d2    = na
var polyline poly_active_fill  = na
var array<polyline> past_polys = array.new<polyline>()
 
if render_style == "Discrete Polyline Spines (Clean Modern)" and barstate.islast
    // 1. Delete prior active polylines
    if not na(poly_active_spine)
        polyline.delete(poly_active_spine)
    if not na(poly_active_u1)
        polyline.delete(poly_active_u1)
    if not na(poly_active_d1)
        polyline.delete(poly_active_d1)
    if not na(poly_active_u2)
        polyline.delete(poly_active_u2)
    if not na(poly_active_d2)
        polyline.delete(poly_active_d2)
    if not na(poly_active_fill)
        polyline.delete(poly_active_fill)
    
    // 2. Render Current Developing SAVWAP
    int n_bars = math.min(1500, bar_index - anc_bar)
    if n_bars >= 0
        array<chart.point> pts_sp   = array.new<chart.point>()
        array<chart.point> pts_u1   = array.new<chart.point>()
        array<chart.point> pts_d1   = array.new<chart.point>()
        array<chart.point> pts_u2   = array.new<chart.point>()
        array<chart.point> pts_d2   = array.new<chart.point>()
        array<chart.point> pts_fill = array.new<chart.point>()
 
        float c_pv  = 0.0
        float c_pv2 = 0.0
        float c_vol = 0.0
 
        int step = n_bars > 500 ? 3 : (n_bars > 250 ? 2 : 1)
        for b = n_bars to 0
            int   b_idx = bar_index - b
            float p_b   = p_bar[b]
            float v_b   = v_bar[b]
            c_pv  += p_b * v_b
            c_pv2 += p_b * p_b * v_b
            c_vol += v_b
 
            if (b % step == 0) or b == 0 or b == n_bars
                float vw_b = c_vol > 0.0 ? (c_pv / c_vol) : p_b
                float vr_b = c_vol > 0.0 ? math.max(0.0, (c_pv2 / c_vol) - vw_b * vw_b) : 0.0
                float sg_b = math.sqrt(math.max(syminfo.mintick * syminfo.mintick, vr_b))
                float u1_b = vw_b + sg_b
                float d1_b = vw_b - sg_b
                float u2_b = vw_b + 2.0 * sg_b
                float d2_b = vw_b - 2.0 * sg_b
 
                array.push(pts_sp,   chart.point.from_index(b_idx, vw_b))
                array.push(pts_u1,   chart.point.from_index(b_idx, u1_b))
                array.push(pts_d1,   chart.point.from_index(b_idx, d1_b))
                array.push(pts_u2,   chart.point.from_index(b_idx, u2_b))
                array.push(pts_d2,   chart.point.from_index(b_idx, d2_b))
                array.push(pts_fill, chart.point.from_index(b_idx, u1_b))
 
        // Faint Cloud Fill
        if show_sd1 and fill_corr and array.size(pts_d1) > 1
            for k = array.size(pts_d1) - 1 to 0
                array.push(pts_fill, array.get(pts_d1, k))
            poly_active_fill := polyline.new(pts_fill, curved = false, closed = true, line_color = color.new(col_mid, 100), fill_color = color.new(col_mid, cloud_transp))
 
        poly_active_spine := polyline.new(pts_sp, curved = false, line_color = col_mid, line_width = 2)
        if show_sd1
            poly_active_u1 := polyline.new(pts_u1, curved = false, line_color = col_sd1, line_width = 1)
            poly_active_d1 := polyline.new(pts_d1, curved = false, line_color = col_sd1, line_width = 1)
        if show_sd2
            poly_active_u2 := polyline.new(pts_u2, curved = false, line_color = col_sd2, line_width = 1, line_style = line.style_dashed)
            poly_active_d2 := polyline.new(pts_d2, curved = false, line_color = col_sd2, line_width = 1, line_style = line.style_dashed)
 
    // 3. Render Past SAVWAP Spines (Faint Historical Dashed Curves)
    while array.size(past_polys) > 0
        polyline.delete(array.shift(past_polys))
 
    int n_past = array.size(past_anc_bars)
    if n_past > 0 and max_past_sess > 0
        int start_k = math.max(0, n_past - max_past_sess)
        for k = n_past - 1 to start_k
            int p_anc_b = array.get(past_anc_bars, k)
            int p_end_b = array.get(past_end_bars, k)
            int p_dir   = array.get(past_anc_dirs, k)
            int p_age   = bar_index - p_anc_b
            
            if p_anc_b >= 0 and p_end_b > p_anc_b and p_age <= 1900
                int p_anc_off = math.min(p_age, 1900)
                int p_end_off = math.max(1, bar_index - p_end_b)
                array<chart.point> pts_hist = array.new<chart.point>()
                float pv_h = 0.0
                float vl_h = 0.0
                for b = p_anc_off to p_end_off
                    int   b_idx = bar_index - b
                    float p_b   = p_bar[b]
                    float v_b   = v_bar[b]
                    pv_h += p_b * v_b
                    vl_h += v_b
                    array.push(pts_hist, chart.point.from_index(b_idx, vl_h > 0.0 ? (pv_h / vl_h) : p_b))
                
                if array.size(pts_hist) > 1
                    color past_c = p_dir == 1 ? #22D3EE : (p_dir == -1 ? #F43F5E : #DDD6FE)
                    polyline pl_hist = polyline.new(pts_hist, curved = false, line_color = color.new(past_c, past_spine_transp), line_width = 1, line_style = line.style_dashed)
                    array.push(past_polys, pl_hist)
 
// Anchor Badges FIFO Queue with Anti-Collision
var array<label> anc_tags = array.new<label>()
var int   last_badge_bar  = 0
var float last_badge_px   = 0.0
 
if show_anc_tags and latch_trigger
    bool allow_badge = (bar_index - last_badge_bar) >= 3 or (math.abs(anc_price - last_badge_px) >= (3.0 * syminfo.mintick))
    if allow_badge
        last_badge_bar := bar_index
        last_badge_px  := anc_price
        color badge_c  = sav_dir == 1 ? #00E5FF : (sav_dir == -1 ? #F43F5E : #A855F7)
        float y_pos    = anc_price
        
        label lb = na
        if badge_style == "Minimalist Pips (Clean ⚓)"
            lb := label.new(
                 x = anc_bar,
                 y = y_pos,
                 text = "⚓",
                 color = color.new(badge_c, 80),
                 textcolor = badge_c,
                 style = label.style_circle,
                 size = size.tiny,
                 tooltip = "SAVWAP Anchor: " + anc_type + " @ " + str.tostring(anc_price, "#.##")
             )
        else if badge_style == "Sleek Tags (High / Low Price)"
            string tag_str = (sav_dir == 1 ? "▲ Low " : (sav_dir == -1 ? "▼ High " : "⚓ ")) + str.tostring(anc_price, "#.##")
            lb := label.new(
                 x = anc_bar,
                 y = y_pos,
                 text = tag_str,
                 color = color.new(#090714, 15),
                 textcolor = badge_c,
                 style = sav_dir == 1 ? label.style_label_up : label.style_label_down,
                 size = size.small,
                 tooltip = anc_type + " (" + str.tostring(anc_price, "#.##") + ")\nSAVWAP Anchor Initiated"
             )
        else // Full Detailed Cards
            lb := label.new(
                 x = anc_bar,
                 y = y_pos,
                 text = "⚓ " + anc_type + "\n" + str.tostring(anc_price, "#.##"),
                 color = color.new(#090714, 15),
                 textcolor = badge_c,
                 style = sav_dir == 1 ? label.style_label_up : label.style_label_down,
                 size = size.small
             )
        
        array.push(anc_tags, lb)
        while array.size(anc_tags) > tag_max_cap
            label.delete(array.shift(anc_tags))
 
// ============================================================================
// 8. MICROSTRUCTURAL TELEMETRY HUD TABLE
// ============================================================================
var table hud = na
if show_hud and barstate.islast
    string hud_pos_str = hud_position == "Top Right" ? position.top_right : (hud_position == "Bottom Right" ? position.bottom_right : (hud_position == "Top Left" ? position.top_left : position.bottom_left))
    hud := table.new(hud_pos_str, 2, enable_ml_eval ? 9 : 8, bgcolor = color.new(#090714, 8), border_color = color.new(#6D28D9, 45), border_width = 1)
    
    // Rich Educational Hover Tooltips
    string tt_hdr = "True Structure-Anchored VWAP (SAVWAP) Institutional Engine v2.0\nAnchors dynamically to confirmed structural liquidity sweeps, volume absorption climaxes, and volatility impulse pivots."
    string tt_anc = "Active Structural Anchor:\nOrigin pivot type and price level establishing the developing volume-weighted auction baseline.\n• Sweep: Liquidity raid beyond ONH/ONL or PDH/PDL with immediate re-absorption.\n• Climax: RVOL ≥ 1.50 with ≥30% wick absorption defense.\n• Impulse: Directional volatility breakout (≥1.5× ATR)."
    string tt_vol = "Datafeed & Volume Engine:\n• Real Vol (Emerald): Active exchange orderflow/volume feed (CME Futures, Crypto, Equities).\n• Range Proxy (Amber): Non-volume feed (SPX, NDX, FX) weighted by true microstructural bar volatility range to preserve Auction Market Theory."
    string tt_age = "Wall-Clock Lifespan (True Elapsed Time):\nCalculated as (time - t_0) / 60000 in actual elapsed minutes and hours.\n• Invariant to chart timeframe compression (1m, 5m, 15m) and holiday session gaps.\n• As an anchor matures beyond 2 hours, volume accumulation hardens the benchmark into institutional fair value."
    string tt_sd  = "Developing Volume-Weighted Variance Corridors:\nTrue volume-weighted standard deviation: σ = sqrt(E[P²] - E[P]²).\n• ±1.0σ: Tactical Trend-Walk Corridor (institutional re-accumulation boundary).\n• ±2.0σ: Statistical Exhaustion Extreme (responsive mean-reversion boundary)."
    string tt_z   = "Microstructural Displacement Z-Score:\nNormalized price distance from SAVWAP: Z = (Close - SAVWAP) / σ.\n• |Z| < 1.0σ: Rotational Value Bracket (equilibrium / balanced auction).\n• 1.0σ ≤ |Z| < 2.0σ: Initiative Trend Walk (directional expansion).\n• |Z| ≥ 2.0σ: Statistical Exhaustion (high probability of responsive rotation back to value)."
    string tt_reg = "Auction Market Theory (AMT) Regime State:\n• Rotational Value Bracket (|Z| < 1.0σ): Market is in balance; favor mean-reversion toward SAVWAP.\n• Initiative Trend Walk (1.0σ ≤ |Z| < 2.0σ): Aggressive conviction volume driving price outside value; trade continuation.\n• Statistical Exhaustion (|Z| ≥ 2.0σ): Overextended stretch from volume core; responsive participants absorb extreme prices."
    string tt_htf = "Higher-Timeframe (HTF) Macro Context:\nVolume-weighted benchmark calculated across the macro timeframe (e.g., Daily 'D').\n• Bullish (> Macro VWAP): Intraday long setups align with the macro institutional tide.\n• Bearish (< Macro VWAP): Intraday short setups align with the macro institutional tide.\n• Alignment with HTF elevates anchor conviction and trade expectancy."
    string tt_cnv = "Anchor Conviction Score:\nSynthesizes 4 normalized microstructural dimensions at anchor inception:\n1. f1 Volume Surge: RVOL relative expansion via fast algebraic sigmoid.\n2. f2 Wick Absorption: Limit order defense asymmetry at extremes.\n3. f3 Isotropic Theta: Scale-invariant angular velocity vector.\n4. f4 HTF Alignment: Macro trend concordance (+1 / -1).\nCombined score reflects institutional commitment at this structural pivot."
 
    // Header
    table.cell(hud, 0, 0, "Auto SAVWAP Engine", bgcolor = color.new(#4C1D95, 25), text_color = color.white, text_size = size.small, tooltip = tt_hdr)
    table.cell(hud, 1, 0, "v2.0 AMT & Corridors", bgcolor = color.new(#4C1D95, 25), text_color = #DDD6FE, text_size = size.small, tooltip = tt_hdr)
    
    // Active Anchor Status
    table.cell(hud, 0, 1, "Active Anchor", text_color = #C4B5FD, text_size = size.small, tooltip = tt_anc)
    table.cell(hud, 1, 1, anc_type + " (" + str.tostring(anc_price, "#.##") + ")", text_color = color.white, text_size = size.small, tooltip = tt_anc)
    
    // Datafeed & Volume Status
    table.cell(hud, 0, 2, "Datafeed Mode", text_color = #C4B5FD, text_size = size.small, tooltip = tt_vol)
    table.cell(hud, 1, 2, vol_mode_str, text_color = vol_status_col, text_size = size.small, tooltip = tt_vol)
    
    // Wall-Clock Elapsed Time
    table.cell(hud, 0, 3, "Wall-Clock Age", text_color = #C4B5FD, text_size = size.small, tooltip = tt_age)
    table.cell(hud, 1, 3, elapsed_str + " (" + str.tostring(bar_index - anc_bar) + " bars)", text_color = #22D3EE, text_size = size.small, tooltip = tt_age)
    
    // Standard Deviation Volatility
    table.cell(hud, 0, 4, "Developing σ", text_color = #C4B5FD, text_size = size.small, tooltip = tt_sd)
    table.cell(hud, 1, 4, "±" + str.tostring(savwap_sd, "#.##") + " pts", text_color = #E9D5FF, text_size = size.small, tooltip = tt_sd)
    
    // Statistical Displacement Z-Score
    color z_col = math.abs(z_score) >= 2.0 ? #F43F5E : (math.abs(z_score) >= 1.0 ? #22D3EE : #10B981)
    table.cell(hud, 0, 5, "Displacement Z", text_color = #C4B5FD, text_size = size.small, tooltip = tt_z)
    table.cell(hud, 1, 5, (z_score >= 0.0 ? "+" : "") + str.tostring(z_score, "#.##") + " σ", text_color = z_col, text_size = size.small, tooltip = tt_z)
    
    // Auction Market Theory Regime
    string amt_regime = "Rotational Value Bracket"
    color  amt_col    = #10B981
    if math.abs(z_score) >= 2.0
        amt_regime := "Statistical Exhaustion"
        amt_col    := #C084FC
    else if math.abs(z_score) >= 1.0
        amt_regime := "Initiative Trend Walk"
        amt_col    := #22D3EE
    table.cell(hud, 0, 6, "AMT Regime", text_color = #C4B5FD, text_size = size.small, tooltip = tt_reg)
    table.cell(hud, 1, 6, amt_regime, text_color = amt_col, text_size = size.small, tooltip = tt_reg)
 
    // Higher Timeframe Alignment
    table.cell(hud, 0, 7, "HTF (" + htf_res + ") Macro", text_color = #C4B5FD, text_size = size.small, tooltip = tt_htf)
    table.cell(hud, 1, 7, htf_bull ? "Bullish (> Macro VWAP)" : "Bearish (< Macro VWAP)", text_color = htf_bull ? #10B981 : #F43F5E, text_size = size.small, tooltip = tt_htf)
 
    // Microstructural Anchor Conviction Scorer
    if enable_ml_eval
        string stars = cur_conviction >= 75.0 ? "★★★★★" : (cur_conviction >= 65.0 ? "★★★★☆" : (cur_conviction >= 50.0 ? "★★★☆☆" : "★★☆☆☆"))
        string cnv_str = stars + " (" + str.tostring(cur_conviction, "#") + "% | " + str.tostring(cur_ml_twins) + " Twins)"
        color  cnv_col = cur_conviction >= 65.0 ? #10B981 : (cur_conviction >= 50.0 ? #22D3EE : #C084FC)
        table.cell(hud, 0, 8, "Anchor Conviction", text_color = #C4B5FD, text_size = size.small, tooltip = tt_cnv)
        table.cell(hud, 1, 8, cnv_str, text_color = cnv_col, text_size = size.small, tooltip = tt_cnv)

← 返回列表