Trapped Positioning Map [ML]

Market_Logic_India · study · 735 行 · 点赞 59 · 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/
//@version=6
// ═════════════════════════════════════════════════════════════════════════════
//  © Market_Logic_India                                                  MPL-2.0
//  Trapped Positioning Map [ML] — Forced-Flow & Squeeze Zones      Pine Script v6
//  shorttitle: Trapped Map
//  OPEN-SOURCE (MPL-2.0). Free to study, use and adapt under the licence terms;
//  attribution appreciated. Published open as a contribution to the community.
// -----------------------------------------------------------------------------
//  ★ WHAT THIS TOOL DOES ★
//    Every large move leaves a crowd offside: someone bought the high that just
//    failed, someone shorted the low that just reversed. Those TRAPPED positions
//    are fuel — as price pushes further against them their pain mounts until they
//    are FORCED to act (cover, stop out, scramble to break-even). This tool
//    estimates WHERE the offside crowd sits, WHICH WAY they will be forced, and
//    HOW MUCH fuel is there, from signed intrabar order-flow deposited at price.
//
//    For each trapped cluster it projects two tradeable prices:
//      • MAGNET  — the crowd's break-even, where they bail (support / resistance).
//      • TRIGGER — the level beyond which their stops cascade (acceleration zone).
//    Clusters are ranked A / B / C by how much forced flow they hold, and the
//    tool FORWARD-TESTS its own triggers (triple-barrier) to show a Wilson-bounded
//    release probability and typical follow-through in R per tier.
//
//  ★ DESIGN PRINCIPLE ★  MEASURE, DON'T ASSERT. Nothing is shown that is not
//    either measured on your chart or honestly flagged as a proxy.
//
//  ★ HOW IT IS BUILT (data reality) ★
//    Only NIFTY spot and futures stream live, so the engine runs entirely on
//    price + futures volume + the spot–futures basis. The signed-volume source
//    defaults to NIFTY current-month FUTURES (the cash index has no real volume);
//    the chart symbol is used only for the PRICE axis. Nothing depends on a live
//    options / open-interest feed; max-pain is a manual input only.
//
//  ★ RELATIONSHIP TO THE LIQUIDITY FAMILY ★
//    A fragility read asks "is the book thin here?". This asks "who is underwater
//    here, and which way will they be forced?". They multiply: a trap formed in a
//    thin book is the genuine squeeze — so fragility-at-formation is one weight.
//
//  NON-REPAINT
//    Profile, clusters, formation tests and the forward test all resolve on
//    CONFIRMED bars; the live bar is provisional. Wilson LB is lagged by design.
//
//  CONCEPT CREDITS (original authors of the ideas synthesised here)
//    • Adverse-excursion / MAE-MFE framing — J. Sweeney; trapped-trader lore.
//    • Failed-auction / upthrust-spring — R. Wyckoff; VSA (T. Williams).
//    • Price impact of order flow (lambda) — A. S. Kyle (1985).
//    • Binomial proportion confidence interval — E. B. Wilson (1927).
//      Implementation is the author's own.
//
//  DISCLAIMER
//    Research and education only. NOT financial advice, NOT a signal service,
//    NOT a guarantee of future results. Trapped positioning is ESTIMATED from bar
//    and intrabar flow — it is not order-book, OI or positioning truth. It is a
//    risk / fuel read, forward-tested, not a prediction. Manage your own risk.
// ═════════════════════════════════════════════════════════════════════════════
indicator("Trapped Positioning Map [ML]", "Trapped Map", overlay = true,
     max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500,
     max_bars_back = 3000, dynamic_requests = true)
 
// ═════════════════════════ 00 · ASSET MODE & FLOW SOURCE ════════════════════
g0 = "00 · Asset & flow source"
assetMode = input.string("NIFTY", "Asset mode", options = ["NIFTY", "Generic"], group = g0,
     tooltip = "NIFTY: pre-wires the futures flow symbol, NSE session, Tue expiry weighting and the spot–futures basis read. Generic: uses the chart symbol for flow and drops the NIFTY-specific rows.")
flowOverride = input.string("", "Flow symbol (volume source) — blank = auto", group = g0,
     tooltip = "The VOLUME-bearing symbol used for signed flow. Blank + NIFTY = NSE:NIFTY1! (current-month futures). Blank + Generic = the chart symbol. The chart symbol is always the PRICE axis; this supplies the signed volume deposited at those prices.")
ltfMode = input.string("Auto (finest)", "Sub-bar resolution", options = ["Auto (finest)", "Seconds", "1 minute"], group = g0,
     tooltip = "Lower timeframe used to measure true intrabar flow. Falls back to bar-return sign on bars with no sub-bar data, then to volumeless price-pressure on symbols with no volume at all.")
 
// ═════════════════════════ 01 · PROFILE / WINDOW ════════════════════════════
g1 = "01 · Profile window"
frameMode = input.string("Auto (session)", "Lookback frame", options = ["Auto (session)", "Session", "Rolling N-bar"], group = g1,
     tooltip = "Auto: session-anchored (resets each day) when intraday, else rolling. Session: always day-anchored. Rolling: a fixed-anchor window with decay (for daily+/Generic).")
binMultATR = input.float(0.25, "Bin height (× ATR)", minval = 0.05, maxval = 1.0, step = 0.05, group = g1,
     tooltip = "Height of each price bin as a multiple of ATR(14). Smaller = finer profile, more bins.")
posLife = input.float(60.0, "Position half-life (bars, 0 = off)", minval = 0.0, maxval = 500.0, step = 5.0, group = g1,
     tooltip = "Trapped size bleeds out over time (positions get stopped or averaged). Each bar every bin decays by 0.5^(1/half-life). 0 disables decay (not recommended in Rolling mode).")
carryPrior = input.bool(true, "Carry unresolved clusters from prior session", group = g1,
     tooltip = "Keep the prior session's unmitigated trapped levels visible (faded, dotted) into the new session.")
 
// ═════════════════════════ 02 · TRAP WEIGHTING ══════════════════════════════
g2 = "02 · Trap weighting"
wDepth   = input.float(1.0, "Weight · adverse-excursion depth", minval = 0.0, maxval = 3.0, step = 0.1, group = g2,
     tooltip = "How far offside the positions are (in ATR). Deeper underwater = closer to a forced exit.")
wForm    = input.float(0.8, "Weight · formation signature", minval = 0.0, maxval = 3.0, step = 0.1, group = g2,
     tooltip = "A cluster built on failed-breakout / swept-and-reversed bars (wick rejection + sweep) traps more than one built in quiet drift.")
wFrag    = input.float(0.6, "Weight · fragility-at-formation", minval = 0.0, maxval = 3.0, step = 0.1, group = g2,
     tooltip = "A trap formed in a thin / impact-driven book is more reversible and more likely to force the crowd out.")
swLen    = input.int(10, "Sweep lookback (bars)", minval = 3, maxval = 60, group = g2,
     tooltip = "Swing length for the failed-breakout / sweep-reversal test used in the formation signature.")
regimeGate = input.bool(true, "Regime-gate the forced direction", group = g2,
     tooltip = "In a strong trend, boost clusters whose forced move runs WITH the trend and fade those that fight it.")
 
// ═════════════════════════ 03 · CLUSTERS & RANK ═════════════════════════════
g3 = "03 · Clusters & rank"
mergeGap  = input.int(1, "Merge gap (empty bins)", minval = 0, maxval = 5, group = g3,
     tooltip = "Trapped bins of the same side within this many empty bins are merged into one cluster.")
minDepth  = input.float(0.3, "Minimum underwater depth (× ATR)", minval = 0.0, maxval = 3.0, step = 0.1, group = g3,
     tooltip = "A bin must be at least this far offside from current price to count as trapped.")
trigBufATR = input.float(0.75, "Trigger stop-pool distance (× ATR beyond cluster edge)", minval = 0.0, maxval = 3.0, step = 0.05, group = g3,
     tooltip = "The stop-cascade TRIGGER sits this far beyond the cluster's far edge — where the offside crowd's stops realistically pool. ~0.5–1.0 ATR puts it at the live squeeze / liquidation level rather than right at the cluster edge.")
 
// ═════════════════════════ 04 · SELF-VALIDATION ═════════════════════════════
g4 = "04 · Self-validation (forward test)"
fwdBars = input.int(20, "Forward horizon (bars)", minval = 5, maxval = 100, group = g4,
     tooltip = "Triple-barrier horizon: after price crosses a trigger, how many bars to resolve the forced move.")
contR   = input.float(1.0, "Continuation barrier (× ATR)", minval = 0.3, maxval = 5.0, step = 0.1, group = g4,
     tooltip = "A trigger 'releases' (success) if price travels this far in the forced direction before the revert barrier or the horizon.")
revR    = input.float(0.7, "Revert barrier (× ATR)", minval = 0.3, maxval = 5.0, step = 0.1, group = g4,
     tooltip = "A trigger 'fails' if price retraces this far against the forced direction first.")
showValid = input.bool(false, "Show validation detail panel", group = g4,
     tooltip = "Adds a per-tier A/B/C breakdown. The release-P column and the confidence footer are always on.")
 
// ═════════════════════════ 05 · DISPLAY ═════════════════════════════════════
g5 = "05 · Display"
density = input.string("A + B", "Cluster density", options = ["A only", "A + B", "A + B + C"], group = g5,
     tooltip = "Which ranks draw on the chart. A + B is the default — the live opportunity plus the backstop.")
showBoxes   = input.bool(true, "Cluster zones", group = g5)
showMagnet  = input.bool(true, "Magnet lines (break-even S/R)", group = g5)
showTrigger = input.bool(true, "Trigger lines (stop cascade)", group = g5)
showFuel    = input.bool(true, "Squeeze-fuel meter", group = g5)
showNow     = input.bool(true, "Now-marker", group = g5)
showHUD     = input.bool(true, "Dashboard HUD", group = g5)
hudPos      = input.string("Top Right", "HUD position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = g5)
hudSize     = input.string("Small", "HUD text size", options = ["Tiny", "Small", "Normal"], group = g5)
rightOff    = input.int(14, "Label / line right offset (bars)", minval = 2, maxval = 60, group = g5)
 
g6 = "06 · Colors"
colLongTrap  = input.color(#F23645, "Trapped longs (supply, ↓ fuel)", group = g6)
colShortTrap = input.color(#089981, "Trapped shorts (demand, ↑ fuel)", group = g6)
colTrig      = input.color(#FF9800, "Trigger lines", group = g6)
colTxt       = input.color(#FFFFFF, "Label text", group = g6)
 
g7 = "07 · NIFTY context (futures / expiry)"
showBasis = input.bool(true, "Spot–futures basis & expiry row", group = g7,
     tooltip = "NIFTY mode only. Reads the live futures basis and flags expiry day — no options feed required.")
maxPainIn = input.float(0.0, "Max-pain strike (manual, 0 = off)", minval = 0.0, group = g7,
     tooltip = "Options are NOT live. Optionally type today's max-pain strike to flag alignment with the nearest A-cluster. 0 = hidden.")
 
g8 = "08 · Alerts"
alMagnet  = input.bool(true, "Price enters an A-cluster magnet", group = g8)
alTrigger = input.bool(true, "Price breaks an A-cluster trigger", group = g8)
alFlip    = input.bool(false, "Net trapped imbalance flips", group = g8)
alProx    = input.bool(false, "Nearest A-trigger within proximity", group = g8)
proxATR   = input.float(0.5, "  └ proximity (× ATR)", minval = 0.1, maxval = 3.0, step = 0.1, group = g8)
 
// ═════════════════════════ HELPERS (top-level) ══════════════════════════════
f_txtSize(string s) => s == "Tiny" ? size.tiny : s == "Normal" ? size.normal : size.small
 
f_wilson(float k, float n) =>
    float out = 0.0
    if n > 0
        float p = k / n
        float z = 1.96
        float den = 1.0 + z * z / n
        float ctr = p + z * z / (2.0 * n)
        float mrg = z * math.sqrt(math.max(p * (1.0 - p) / n + z * z / (4.0 * n * n), 0.0))
        out := math.max((ctr - mrg) / den, 0.0)
    out
 
f_pct(float v) => na(v) ? "–" : str.tostring(v * 100.0, "#") + "%"
f_px(float v)  => na(v) ? "–" : str.tostring(v, format.mintick)
f_rstr(float v) => na(v) ? "–" : (v >= 0 ? "+" : "-") + str.tostring(math.abs(v), "0.0") + "R"
// where price sits between a cluster's magnet (break-even) and its trigger (stop pool):
//   FADE = at/near the magnet (S/R, fade the move) · RIDE = at/near the trigger (break rides the cascade)
//   mid  = between · past = price has blown through the trigger (squeeze largely spent)
f_action(int side, float mag, float trig) =>
    string out = "mid"
    if not na(mag) and not na(trig) and trig != mag
        float frac = side == 1 ? (close - mag) / (trig - mag) : (mag - close) / (mag - trig)
        out := frac < 0.33 ? "FADE" : frac > 1.2 ? "past" : frac > 0.66 ? "RIDE" : "mid"
    out
f_rankTxt(int r) => r == 0 ? "A" : r == 1 ? "B" : "C"
f_rankShow(int r) => density == "A only" ? r == 0 : density == "A + B" ? r <= 1 : true
 
// ═════════════════════════ FLOW SYMBOL RESOLUTION ═══════════════════════════
string _flowSym = flowOverride != "" ? flowOverride : (assetMode == "NIFTY" ? "NSE:NIFTY1!" : syminfo.tickerid)
int    _chartSec = timeframe.in_seconds()
string _ltf = ltfMode == "1 minute" ? "1" : ltfMode == "Seconds" ? (_chartSec <= 120 ? "1S" : "15S") : (_chartSec <= 300 ? "1" : _chartSec <= 3600 ? "5" : "15")
 
[fO, fC, fV] = request.security(_flowSym, timeframe.period, [open, close, volume], lookahead = barmerge.lookahead_off)
[lO, lC, lV] = request.security_lower_tf(_flowSym, _ltf, [open, close, volume], ignore_invalid_timeframe = true)
 
// ═════════════════════════ PER-BAR SIGNED FLOW ══════════════════════════════
float _rng    = math.max(high - low, syminfo.mintick)
float _atr    = ta.atr(14)
float safeAtr = nz(_atr, _rng)
 
float sdSub = 0.0
float tvSub = 0.0
if lC.size() > 0
    for i = 0 to lC.size() - 1
        float c_ = lC.get(i)
        float o_ = lO.get(i)
        float v_ = nz(lV.get(i))
        sdSub += c_ > o_ ? v_ : c_ < o_ ? -v_ : 0.0
        tvSub += v_
 
float barVol    = 0.0
float barSigned = 0.0
if tvSub > 0
    barVol    := tvSub
    barSigned := sdSub
else if nz(fV) > 0
    barVol    := fV
    barSigned := (fC > fO ? 1.0 : fC < fO ? -1.0 : 0.0) * fV
else
    float travel = (close - nz(close[1], open)) / _rng
    float dirn   = (close - open) / _rng
    float cloc   = (2.0 * close - high - low) / _rng
    float pres   = 0.55 * travel + 0.25 * dirn + 0.20 * cloc
    barVol    := math.abs(pres) + 0.01
    barSigned := pres
 
// ═════════════════════════ FORMATION & FRAGILITY ════════════════════════════
float upWick = (high - math.max(open, close)) / _rng
float dnWick = (math.min(open, close) - low) / _rng
float wick   = math.max(upWick, dnWick)
float priHiLvl = ta.highest(high, swLen)[1]
float priLoLvl = ta.lowest(low, swLen)[1]
bool  sweptHi  = not na(priHiLvl) and high > priHiLvl and close < priHiLvl
bool  sweptLo  = not na(priLoLvl) and low  < priLoLvl and close > priLoLvl
float formScore = 1.0 + wForm * (wick + (sweptHi or sweptLo ? 0.6 : 0.0))
 
float impact  = math.abs(close - open) / math.max(barVol, 1.0)
float fragPct = nz(ta.percentrank(impact, 300) / 100.0, 0.5)
float fragScore = 1.0 + wFrag * fragPct
 
float erNet  = math.abs(close - nz(close[10], close))
float erPath = math.sum(math.abs(close - nz(close[1], close)), 10)
float er = erPath > 0 ? erNet / erPath : 0.0
int   regimeDir = close > nz(close[10], close) ? 1 : close < nz(close[10], close) ? -1 : 0
bool  trending  = er >= 0.35
 
// ═════════════════════════ SESSION / WINDOW STATE ═══════════════════════════
bool useSession = frameMode == "Session" or (frameMode == "Auto (session)" and timeframe.isintraday)
bool newSess = useSession and timeframe.isintraday and ta.change(time("D")) != 0
 
var float binH   = na
var float anchor = na
var map<int, float> binBuy  = map.new<int, float>()
var map<int, float> binSell = map.new<int, float>()
var map<int, float> binForm = map.new<int, float>()
var map<int, float> binFrag = map.new<int, float>()
var map<int, float> binTot  = map.new<int, float>()
 
var array<float> carryPx   = array.new<float>()
var array<int>   carrySide = array.new<int>()
 
float decay = posLife > 0 ? math.pow(0.5, 1.0 / posLife) : 1.0
 
// deposit one bar's signed flow into bin k (reference-mutates the global maps)
f_depositBin(int k, float signed, float vmag, float fScore, float frScore) =>
    binTot.put(k,  nz(binTot.get(k))  + vmag)
    binForm.put(k, nz(binForm.get(k)) + vmag * fScore)
    binFrag.put(k, nz(binFrag.get(k)) + vmag * frScore)
    if signed >= 0
        binBuy.put(k,  nz(binBuy.get(k))  + vmag)
    else
        binSell.put(k, nz(binSell.get(k)) + vmag)
    0
 
// which side is seated in bin k: +1 buy-dominant (longs), -1 sell-dominant (shorts)
f_sideOf(int k) =>
    float b = nz(binBuy.get(k))
    float s = nz(binSell.get(k))
    b > s ? 1 : s > b ? -1 : 0
 
// base trap weight for bin k at price lvl (gate applied in the loop)
f_trapWeightBin(int k, float lvl) =>
    float b = nz(binBuy.get(k))
    float s = nz(binSell.get(k))
    float expo = math.abs(b - s)
    float depthA = math.abs(lvl - close) / safeAtr
    float tot = nz(binTot.get(k))
    float formA = tot > 0 ? binForm.get(k) / tot : 1.0
    float fragA = tot > 0 ? binFrag.get(k) / tot : 1.0
    expo * (1.0 + wDepth * depthA) * formA * fragA
 
// ═════════════════════════ ENGINE (confirmed bars) ══════════════════════════
if barstate.isconfirmed
    if newSess
        binBuy.clear()
        binSell.clear()
        binForm.clear()
        binFrag.clear()
        binTot.clear()
        anchor := open
        binH   := math.max(binMultATR * safeAtr, syminfo.mintick)
    if na(anchor)
        anchor := open
        binH   := math.max(binMultATR * safeAtr, syminfo.mintick)
 
    // position bleed (and prune empties so Rolling mode stays bounded)
    if decay < 1.0 and binTot.size() > 0
        array<int> dk = binTot.keys()
        for di = 0 to dk.size() - 1
            int k = dk.get(di)
            float nt = binTot.get(k) * decay
            if nt < 0.000001
                binTot.remove(k)
                binForm.remove(k)
                binFrag.remove(k)
                if binBuy.contains(k)
                    binBuy.remove(k)
                if binSell.contains(k)
                    binSell.remove(k)
            else
                binTot.put(k, nt)
                binForm.put(k, binForm.get(k) * decay)
                binFrag.put(k, binFrag.get(k) * decay)
                if binBuy.contains(k)
                    binBuy.put(k, binBuy.get(k) * decay)
                if binSell.contains(k)
                    binSell.put(k, binSell.get(k) * decay)
 
    // deposit this bar across the bins its range spans (range-proportional)
    int kLo = int(math.floor((low  - anchor) / binH))
    int kHi = int(math.floor((high - anchor) / binH))
    int span = math.max(kHi - kLo, 0)
    if span <= 200
        float perBin = span == 0 ? 1.0 : 1.0 / (span + 1)
        for k = kLo to kHi
            f_depositBin(k, barSigned, barVol * perBin, formScore, fragScore)
 
// ═════════════════════════ CLUSTER BUILD (per confirmed bar) ════════════════
var array<float> clPx   = array.new<float>()   // magnet (break-even)
var array<float> clTrig = array.new<float>()   // trigger
var array<int>   clSide = array.new<int>()     // +1 trapped shorts (↑fuel) / -1 trapped longs (↓fuel)
var array<float> clWt   = array.new<float>()
var array<int>   clRank = array.new<int>()     // 0=A,1=B,2=C
var array<float> clTop  = array.new<float>()
var array<float> clBot  = array.new<float>()
 
if barstate.isconfirmed
    // snapshot the prior session's A/B clusters into the carry list before they are cleared
    if newSess and carryPrior
        carryPx.clear()
        carrySide.clear()
        if clPx.size() > 0
            for ci = 0 to clPx.size() - 1
                if clRank.get(ci) <= 1
                    carryPx.push(clPx.get(ci))
                    carrySide.push(clSide.get(ci))
    clPx.clear()
    clTrig.clear()
    clSide.clear()
    clWt.clear()
    clRank.clear()
    clTop.clear()
    clBot.clear()
 
    if not na(binH) and binTot.size() > 0
        array<int> keys = binTot.keys()
        array.sort(keys, order.ascending)
        int n = keys.size()
 
        float accW   = 0.0
        float accPxW = 0.0
        float accTop = na
        float accBot = na
        int   accSide = 0
        int   prevK = na
        bool  open_ = false
 
        for idx = 0 to n - 1
            int k = keys.get(idx)
            float lvl = anchor + (k + 0.5) * binH
            int seat = f_sideOf(k)
            int fuelSide = 0
            if seat == 1 and lvl > close and (lvl - close) / safeAtr >= minDepth
                fuelSide := -1
            else if seat == -1 and lvl < close and (close - lvl) / safeAtr >= minDepth
                fuelSide := 1
 
            float w = 0.0
            if fuelSide != 0
                w := f_trapWeightBin(k, lvl)
                if regimeGate and trending
                    w := w * (regimeDir == fuelSide ? 1.15 : 0.85)
 
            bool contiguous = not na(prevK) and (k - prevK - 1) <= mergeGap
            bool doFlush  = false
            bool startNew = false
 
            if fuelSide != 0
                if open_ and fuelSide == accSide and contiguous
                    accW   := accW + w
                    accPxW := accPxW + lvl * w
                    accTop := math.max(accTop, lvl)
                    accBot := math.min(accBot, lvl)
                else
                    doFlush  := true
                    startNew := true
            else
                doFlush := true
 
            if doFlush and open_ and accW > 0
                float magnet = accPxW / accW
                float trig = accSide == 1 ? accTop + trigBufATR * safeAtr : accBot - trigBufATR * safeAtr
                clPx.push(magnet)
                clTrig.push(trig)
                clSide.push(accSide)
                clWt.push(accW)
                clTop.push(accTop)
                clBot.push(accBot)
                clRank.push(2)
 
            if startNew
                accW    := w
                accPxW  := lvl * w
                accTop  := lvl
                accBot  := lvl
                accSide := fuelSide
                open_   := true
            else if doFlush
                open_ := false
                accW  := 0.0
 
            prevK := k
 
        if open_ and accW > 0
            float magnet = accPxW / accW
            float trig = accSide == 1 ? accTop + trigBufATR * safeAtr : accBot - trigBufATR * safeAtr
            clPx.push(magnet)
            clTrig.push(trig)
            clSide.push(accSide)
            clWt.push(accW)
            clTop.push(accTop)
            clBot.push(accBot)
            clRank.push(2)
 
        // rank A/B/C by weight share
        int m = clWt.size()
        if m > 0
            float wMax = array.max(clWt)
            for ci = 0 to m - 1
                float r = wMax > 0 ? clWt.get(ci) / wMax : 0.0
                clRank.set(ci, r >= 0.66 ? 0 : r >= 0.33 ? 1 : 2)
 
// ═════════════════════════ NEAREST CLUSTER / EXP READS ══════════════════════
var float nUpMag  = na
var float nUpTrig = na
var int   nUpRank = 3
var float nDnMag  = na
var float nDnTrig = na
var int   nDnRank = 3
var float fuelUp  = 0.0
var float fuelDn  = 0.0
var float topScore = 0.0
 
if barstate.isconfirmed
    nUpMag  := na
    nUpTrig := na
    nUpRank := 3
    nDnMag  := na
    nDnTrig := na
    nDnRank := 3
    fuelUp  := 0.0
    fuelDn  := 0.0
    topScore := 0.0
    if clPx.size() > 0
        for ci = 0 to clPx.size() - 1
            int sd = clSide.get(ci)
            float mg = clPx.get(ci)
            float tg = clTrig.get(ci)
            float w  = clWt.get(ci)
            if sd == 1
                fuelUp := fuelUp + w
                if na(nUpTrig) or tg < nUpTrig
                    nUpTrig := tg
                    nUpMag  := mg
                    nUpRank := clRank.get(ci)
            else
                fuelDn := fuelDn + w
                if na(nDnTrig) or tg > nDnTrig
                    nDnTrig := tg
                    nDnMag  := mg
                    nDnRank := clRank.get(ci)
        topScore := 100.0
 
float netImb = (fuelUp + fuelDn) > 0 ? (fuelUp - fuelDn) / (fuelUp + fuelDn) : 0.0
 
// ═════════════════════════ FORWARD TEST (triple-barrier) ════════════════════
var array<float> aEntry = array.new<float>()
var array<int>   aDir   = array.new<int>()
var array<int>   aTier  = array.new<int>()
var array<int>   aBar   = array.new<int>()
var array<float> tWin  = array.from(0.0, 0.0, 0.0)
var array<float> tTot  = array.from(0.0, 0.0, 0.0)
var array<float> tSumR = array.from(0.0, 0.0, 0.0)
 
if barstate.isconfirmed
    if not na(nUpTrig) and nUpRank <= 2 and high >= nUpTrig and nz(high[1]) < nUpTrig and aEntry.size() < 16
        aEntry.push(nUpTrig)
        aDir.push(1)
        aTier.push(nUpRank)
        aBar.push(bar_index)
    if not na(nDnTrig) and nDnRank <= 2 and low <= nDnTrig and nz(low[1]) > nDnTrig and aEntry.size() < 16
        aEntry.push(nDnTrig)
        aDir.push(-1)
        aTier.push(nDnRank)
        aBar.push(bar_index)
 
    if aEntry.size() > 0
        for ti = aEntry.size() - 1 to 0
            float en = aEntry.get(ti)
            int   dr = aDir.get(ti)
            int   tr = aTier.get(ti)
            int   b0 = aBar.get(ti)
            float contLvl = en + dr * contR * safeAtr
            float revLvl  = en - dr * revR * safeAtr
            bool hitCont = dr == 1 ? high >= contLvl : low <= contLvl
            bool hitRev  = dr == 1 ? low  <= revLvl  : high >= revLvl
            bool expired = bar_index - b0 >= fwdBars
            if hitCont or hitRev or expired
                int tix = math.min(tr, 2)
                tTot.set(tix, tTot.get(tix) + 1.0)
                float rr = 0.0
                if hitCont
                    tWin.set(tix, tWin.get(tix) + 1.0)
                    rr := contR
                else if hitRev
                    rr := -revR
                else
                    rr := dr * (close - en) / safeAtr
                    if rr > 0
                        tWin.set(tix, tWin.get(tix) + 1.0)
                tSumR.set(tix, tSumR.get(tix) + rr)
                aEntry.remove(ti)
                aDir.remove(ti)
                aTier.remove(ti)
                aBar.remove(ti)
 
f_tierRel(int ti) => f_wilson(tWin.get(ti), tTot.get(ti))
f_tierR(int ti)   => tTot.get(ti) > 0 ? tSumR.get(ti) / tTot.get(ti) : na
 
float relUp = not na(nUpTrig) ? f_tierRel(math.min(nUpRank, 2)) : na
float relDn = not na(nDnTrig) ? f_tierRel(math.min(nDnRank, 2)) : na
float sepA = f_tierR(0)
float sepC = f_tierR(2)
bool  ranksOk = not na(sepA) and not na(sepC) and sepA > sepC
float totalN = tTot.get(0) + tTot.get(1) + tTot.get(2)
float trust = totalN > 0 ? math.min(1.0, totalN / 40.0) : 0.0
 
// ═════════════════════════ NIFTY BASIS / EXPIRY ═════════════════════════════
float basis = na
bool  isExpiryDay = false
if assetMode == "NIFTY" and showBasis
    float futC  = request.security("NSE:NIFTY1!", timeframe.period, close, lookahead = barmerge.lookahead_off)
    float spotC = request.security("NSE:NIFTY",   timeframe.period, close, lookahead = barmerge.lookahead_off)
    basis := nz(futC) - nz(spotC)
    isExpiryDay := dayofweek == dayofweek.tuesday
 
// ═════════════════════════ DRAWING OBJECTS ══════════════════════════════════
var array<box>   drawBox = array.new<box>()
var array<line>  drawLn  = array.new<line>()
var array<label> drawLb  = array.new<label>()
 
f_clearDraw() =>
    if drawBox.size() > 0
        for i = 0 to drawBox.size() - 1
            box.delete(drawBox.get(i))
        drawBox.clear()
    if drawLn.size() > 0
        for i = 0 to drawLn.size() - 1
            line.delete(drawLn.get(i))
        drawLn.clear()
    if drawLb.size() > 0
        for i = 0 to drawLb.size() - 1
            label.delete(drawLb.get(i))
        drawLb.clear()
    0
 
var table hud = na
if barstate.islast and na(hud)
    hud := table.new(hudPos == "Top Left" ? position.top_left : hudPos == "Bottom Right" ? position.bottom_right : hudPos == "Bottom Left" ? position.bottom_left : position.top_right, 8, 24, bgcolor = color.new(#0B0E14, 8), frame_color = color.new(#2A3447, 40), frame_width = 1, border_color = color.new(#2A3447, 60), border_width = 1)
 
if barstate.islast
    f_clearDraw()
    int xR = bar_index + rightOff
    if clPx.size() > 0
        for ci = 0 to clPx.size() - 1
            int r = clRank.get(ci)
            if f_rankShow(r)
                int sd = clSide.get(ci)
                color col = sd == 1 ? colShortTrap : colLongTrap
                int trans = r == 0 ? 72 : r == 1 ? 82 : 90
                float tp = clTop.get(ci)
                float bt = clBot.get(ci)
                float mg = clPx.get(ci)
                float tg = clTrig.get(ci)
                string actD = f_action(sd, mg, tg)
                if showBoxes
                    drawBox.push(box.new(bar_index - 1, tp, xR, bt, border_color = color.new(col, 55), bgcolor = color.new(col, trans)))
                if showMagnet
                    drawLn.push(line.new(bar_index - 1, mg, xR, mg, color = col, width = r == 0 ? 2 : 1, style = line.style_solid))
                    drawLb.push(label.new(xR, mg, f_rankTxt(r) + " · " + (sd == 1 ? "shorts" : "longs") + " · mag " + f_px(mg) + " · " + actD, style = label.style_label_left, color = color.new(col, 10), textcolor = colTxt, size = size.tiny))
                if showTrigger
                    drawLn.push(line.new(bar_index - 1, tg, xR, tg, color = color.new(colTrig, r == 0 ? 0 : 30), width = 1, style = line.style_dashed))
                    drawLb.push(label.new(xR, tg, "trig " + f_px(tg) + (sd == 1 ? " ↑" : " ↓"), style = label.style_label_left, color = color.new(colTrig, 15), textcolor = color.black, size = size.tiny))
    if carryPrior and carryPx.size() > 0
        for ci = 0 to carryPx.size() - 1
            int sd = carrySide.get(ci)
            color col = sd == 1 ? colShortTrap : colLongTrap
            drawLn.push(line.new(bar_index - 1, carryPx.get(ci), xR, carryPx.get(ci), color = color.new(col, 55), width = 1, style = line.style_dotted))
    if showFuel and (fuelUp + fuelDn) > 0
        string arrow = netImb > 0.15 ? "▲ UP" : netImb < -0.15 ? "▼ DOWN" : "— balanced"
        color fcol = netImb > 0.15 ? colShortTrap : netImb < -0.15 ? colLongTrap : color.gray
        drawLb.push(label.new(xR, close, "fuel " + arrow + "  " + str.tostring(math.abs(netImb) * 100, "#") + "%", style = label.style_label_left, color = color.new(fcol, 20), textcolor = colTxt, size = size.small))
    if showNow
        drawLb.push(label.new(bar_index, close, "◉", style = label.style_label_left, color = color.new(color.gray, 20), textcolor = colTxt, size = size.tiny))
 
// ═════════════════════════ HUD ══════════════════════════════════════════════
f_cell(int c, int r, string t, color bg, color fg) =>
    table.cell(hud, c, r, t, bgcolor = bg, text_color = fg, text_size = f_txtSize(hudSize), text_halign = text.align_left)
    0
 
if barstate.islast and showHUD and not na(hud)
    table.clear(hud, 0, 0, 7, 23)
    color hb = color.new(#182030, 0)
    color rb = color.new(#10141C, 20)
    color fg = color.new(#E0E0E0, 0)
    float wMaxH = clWt.size() > 0 ? array.max(clWt) : 1.0
    int rr = 0
 
    // ① context header
    string regTxt = trending ? (regimeDir == 1 ? "TREND ↑" : "TREND ↓") : "RANGE"
    string netTxt = netImb > 0.1 ? "SHORTS offside ↑fuel" : netImb < -0.1 ? "LONGS offside ↓fuel" : "balanced"
    f_cell(0, rr, "TRAPPED MAP · " + regTxt + " · net: " + netTxt + " · tested N=" + str.tostring(totalN, "#"), hb, fg)
    table.merge_cells(hud, 0, rr, 7, rr)
    rr += 1
 
    // ② ladder header
    f_cell(0, rr, "Rk", rb, color.silver)
    f_cell(1, rr, "Act", rb, color.silver)
    f_cell(2, rr, "Side", rb, color.silver)
    f_cell(3, rr, "Wt", rb, color.silver)
    f_cell(4, rr, "Magnet", rb, color.silver)
    f_cell(5, rr, "Trigger", rb, color.silver)
    f_cell(6, rr, "Rel P", rb, color.silver)
    f_cell(7, rr, "Typ R", rb, color.silver)
    rr += 1
 
    // ladder rows — A, then B, then C, up to 6
    if clPx.size() > 0
        int shown = 0
        for want = 0 to 2
            if shown < 6
                for ci = 0 to clPx.size() - 1
                    if shown < 6 and clRank.get(ci) == want
                        int sd = clSide.get(ci)
                        color sc = sd == 1 ? colShortTrap : colLongTrap
                        int tix = math.min(want, 2)
                        string act = f_action(sd, clPx.get(ci), clTrig.get(ci))
                        color actc = act == "RIDE" ? colTrig : act == "FADE" ? #4FC3F7 : act == "past" ? color.new(color.gray, 30) : color.silver
                        f_cell(0, rr, f_rankTxt(want), rb, sc)
                        table.cell(hud, 1, rr, act, bgcolor = rb, text_color = actc, text_size = f_txtSize(hudSize))
                        table.cell(hud, 2, rr, sd == 1 ? "shorts" : "longs", bgcolor = rb, text_color = sc, text_size = f_txtSize(hudSize))
                        table.cell(hud, 3, rr, str.tostring(clWt.get(ci) / wMaxH * 100, "#") + "%", bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 4, rr, f_px(clPx.get(ci)), bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 5, rr, f_px(clTrig.get(ci)), bgcolor = rb, text_color = color.new(colTrig, 0), text_size = f_txtSize(hudSize))
                        table.cell(hud, 6, rr, f_pct(f_tierRel(tix)) + " (" + str.tostring(tTot.get(tix), "#") + ")", bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        table.cell(hud, 7, rr, f_rstr(f_tierR(tix)), bgcolor = rb, text_color = fg, text_size = f_txtSize(hudSize))
                        rr += 1
                        shown += 1
 
    // ③ squeeze read
    string sq = na(nUpTrig) and na(nDnTrig) ? "no active triggers" : (not na(nUpTrig) and (na(nDnTrig) or (nUpTrig - close) < (close - nDnTrig)) ? "↑ trig " + f_px(nUpTrig) + "  +" + str.tostring((nUpTrig - close) / safeAtr, "0.0") + " ATR · rel " + f_pct(relUp) : "↓ trig " + f_px(nDnTrig) + "  +" + str.tostring((close - nDnTrig) / safeAtr, "0.0") + " ATR · rel " + f_pct(relDn))
    f_cell(0, rr, "Squeeze: " + sq, hb, fg)
    table.merge_cells(hud, 0, rr, 7, rr)
    rr += 1
 
    // ④ forced-flow verdict (with the dominant cluster's current zone)
    string actUp = f_action(1, nUpMag, nUpTrig)
    string actDn = f_action(-1, nDnMag, nDnTrig)
    string verdict = "Two-sided — wait for an imbalance."
    if netImb > 0.1
        verdict := "Trapped shorts below → UP fuel · " + (actUp == "RIDE" ? "RIDE: break " + f_px(nUpTrig) + " squeezes up" : actUp == "FADE" ? "FADE: magnet " + f_px(nUpMag) + " = support, buy the dip" : actUp == "past" ? "squeeze largely spent above " + f_px(nUpTrig) : "mid: magnet " + f_px(nUpMag) + " / trig " + f_px(nUpTrig))
    else if netImb < -0.1
        verdict := "Trapped longs above → DOWN pressure · " + (actDn == "RIDE" ? "RIDE: break " + f_px(nDnTrig) + " cascades down" : actDn == "FADE" ? "FADE: magnet " + f_px(nDnMag) + " = resistance, sell the rip" : actDn == "past" ? "liquidation largely spent below " + f_px(nDnTrig) : "mid: magnet " + f_px(nDnMag) + " / trig " + f_px(nDnTrig))
    f_cell(0, rr, verdict, rb, fg)
    table.merge_cells(hud, 0, rr, 7, rr)
    rr += 1
 
    // ⑤ live read
    f_cell(0, rr, "Now " + f_px(close) + " · fuel " + (netImb >= 0 ? "↑" : "↓") + str.tostring(math.abs(netImb) * 100, "#") + "%", rb, fg)
    table.merge_cells(hud, 0, rr, 7, rr)
    rr += 1
 
    // ⑥ confidence footer
    string conf = "Ranks " + (ranksOk ? "✓" : "–") + " (A " + f_rstr(sepA) + " vs C " + f_rstr(sepC) + ") · trust " + str.tostring(trust, "0.00")
    f_cell(0, rr, conf, hb, color.new(#9AE6B4, 0))
    table.merge_cells(hud, 0, rr, 7, rr)
    rr += 1
 
    // ⑦ NIFTY expiry / basis
    if assetMode == "NIFTY" and showBasis
        string exTxt = "Expiry " + (isExpiryDay ? "Tue (T−0)" : "—") + " · basis " + (na(basis) ? "–" : str.tostring(basis, "0.0")) + (maxPainIn > 0 ? " · max-pain " + str.tostring(maxPainIn, format.mintick) : "")
        f_cell(0, rr, exTxt, rb, fg)
        table.merge_cells(hud, 0, rr, 7, rr)
        rr += 1
 
    // validation detail
    if showValid
        f_cell(0, rr, "Valid: A " + f_pct(f_tierRel(0)) + "/" + str.tostring(tTot.get(0), "#") + " " + f_rstr(f_tierR(0)) + " · B " + f_pct(f_tierRel(1)) + "/" + str.tostring(tTot.get(1), "#") + " · C " + f_pct(f_tierRel(2)) + "/" + str.tostring(tTot.get(2), "#"), rb, color.silver)
        table.merge_cells(hud, 0, rr, 7, rr)
        rr += 1
 
// ═════════════════════════ EXP BUS (Data Window) ════════════════════════════
color exC = color.new(color.gray, 100)
plot(fuelUp,   "EXP_TrapFuelUp",   exC, display = display.data_window)
plot(fuelDn,   "EXP_TrapFuelDn",   exC, display = display.data_window)
plot(netImb,   "EXP_TrapNet",      exC, display = display.data_window)
plot(nUpMag,   "EXP_TrapMagnetUp", exC, display = display.data_window)
plot(nDnMag,   "EXP_TrapMagnetDn", exC, display = display.data_window)
plot(nUpTrig,  "EXP_TrapTrigUp",   exC, display = display.data_window)
plot(nDnTrig,  "EXP_TrapTrigDn",   exC, display = display.data_window)
plot(topScore, "EXP_TrapScore",    exC, display = display.data_window)
float sqProx = not na(nUpTrig) and not na(nDnTrig) ? math.min(math.abs(nUpTrig - close), math.abs(close - nDnTrig)) / safeAtr : na
plot(sqProx,   "EXP_SqueezeProx",  exC, display = display.data_window)
plot(na(basis) ? na : basis, "EXP_Basis", exC, display = display.data_window)
 
// ═════════════════════════ ALERTS ═══════════════════════════════════════════
bool magHit = alMagnet and ((not na(nUpMag) and nUpRank == 0 and ta.cross(close, nUpMag)) or (not na(nDnMag) and nDnRank == 0 and ta.cross(close, nDnMag)))
bool trigUp = alTrigger and not na(nUpTrig) and nUpRank == 0 and ta.crossover(high, nUpTrig)
bool trigDn = alTrigger and not na(nDnTrig) and nDnRank == 0 and ta.crossunder(low, nDnTrig)
bool flipImb = alFlip and ta.change(math.sign(netImb)) != 0 and math.abs(netImb) > 0.1
bool proxHit = alProx and not na(sqProx) and sqProx <= proxATR and nz(sqProx[1], 99.0) > proxATR
 
alertcondition(magHit, "Trapped Map · A-magnet touched", "Trapped Map: price reached an A-cluster magnet (break-even exit zone) on {{ticker}} {{interval}}.")
alertcondition(trigUp, "Trapped Map · A-trigger up break", "Trapped Map: price broke an A-cluster UP trigger (short-squeeze cascade) on {{ticker}} {{interval}}.")
alertcondition(trigDn, "Trapped Map · A-trigger down break", "Trapped Map: price broke an A-cluster DOWN trigger (long-liquidation cascade) on {{ticker}} {{interval}}.")
alertcondition(flipImb, "Trapped Map · imbalance flip", "Trapped Map: net trapped imbalance flipped on {{ticker}} {{interval}}.")
alertcondition(proxHit, "Trapped Map · trigger proximity", "Trapped Map: price is within proximity of an A-cluster trigger on {{ticker}} {{interval}}.")

← 返回列表