GC Evidence Sniper Dashboard

Nbrx · study · 1232 行 · 点赞 29 · TradingView 原页

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

Pine Script

//@version=6
indicator("Aurum Evidence Sniper", "AES GC", overlay=true, scale=scale.none, max_lines_count=60, max_labels_count=60, max_boxes_count=500, max_bars_back=2000)
 
// SOURCE AND FIXED PRICE MAPPING
gSource = "01 | Shared GC source"
source = input.symbol("COMEX:GC1!", "GC source", group=gSource)
gcSource = ticker.modify(source, session=session.extended)
isXau = input.bool(false, "Translate prices to XAUUSD", group=gSource)
basisMode = input.string("Auto — fixed reference", "Price mapping", options=["Auto — fixed reference", "Manual fixed offset"], group=gSource)
xauSource = input.symbol("OANDA:XAUUSD", "XAU reference feed", group=gSource)
referenceTime = input.time(timestamp("26 Oct 2026 00:00 +0100"), "Reference candle time", group=gSource)
basis = input.float(-13.44, "Manual XAU minus GC offset", step=0.01, group=gSource)
 
// OPTIONS SNAPSHOT
gOpt = "02 | Daily snapshot — edit in BOTH indicators"
sourceDate = input.string("OG1X6 + OGZ6 | OI 03 Nov | IV 04 Nov 15:20 print", "Source dates / note", group=gOpt)
callWall = input.float(4100, "Largest call OI in selected strikes", minval=0, group=gOpt)
putWall = input.float(3900, "Largest put OI in selected strikes", minval=0, group=gOpt)
float flip = 0.0
gammaScenario = input.string("Long calls / short puts", "Dealer assumption", options=["Long calls / short puts", "Short calls / long puts", "Off"], group=gOpt)
snapshotHideTime = input.time(timestamp("06 Nov 2026 00:00 +0100"), "Hide snapshot at (conservative cutoff)", group=gOpt)
bool optionExpired = timenow >= snapshotHideTime
string optionStatus = optionExpired ? "DATED SNAPSHOT | HIDDEN" : "OI 03 NOV | IV 04 NOV | 2 EXP."
// Model input rows: strike, OG1X6 call/put OI, OGZ6 call/put OI, OG1X6/OGZ6 IV percent.
// Sources: CME 1.pdf p9; CME 3(1).pdf pp2–3; CME 4(1).pdf pp8–9.
// Black-76: use 2.17 and 20.17 DTE, ACT/365, 3.875% flat rate, 100 oz.
// Gamma = exp(-r*T) * normal_pdf(d1) / (F*IV*sqrt(T)).
// Sum (call OI - put OI) * gamma * 100 * F^2 * 0.01 for the first dealer scenario.
// The reverse scenario negates this sum. Price scan uses fixed strike IV and common GCZ6 F.
// 3900,87,340,352,6070,31.26,23.24
// 3925,153,190,33,452,30.78,23.03
// 3950,102,132,188,4155,30.29,22.83
// 3975,192,77,196,895,30.04,22.69
// 4000,330,305,1651,4841,29.87,22.57
// 4025,87,77,170,1158,29.74,22.49
// 4050,202,122,1802,2415,29.95,22.45
// 4075,85,50,252,385,30.37,22.44
// 4100,216,123,3691,2183,31.07,22.5
// 4125,148,80,170,341,31.91,22.58
// 4150,174,19,2058,1431,32.91,22.73
float modelGexMillions = -325.870
string gamma = optionExpired ? "SNAPSHOT HIDDEN" : gammaScenario == "Off" ? "UNKNOWN | N/A" : (gammaScenario == "Long calls / short puts" ? "NEGATIVE" : "POSITIVE") + " | FLIP N/A"
string gammaTip = "Black-76 at GC 4055. 11 selected strikes 3900–4150 for OG1X6 and OGZ6. Fixed IV by strike. GEX " + str.tostring(gammaScenario == "Short calls / long puts" ? -modelGexMillions : modelGexMillions, "#.0") + "M USD per 1% move under selected dealer scenario. No sign change on the 3900–4150 scan. Snapshot only."
ladder = input.text_area("", "Optional dated volume: strike,calls,puts", group=gOpt)
oiText = input.text_area("3900,439,6410\n3925,186,642\n3950,290,4287\n3975,388,972\n4000,1981,5146\n4025,257,1235\n4050,2004,2537\n4075,337,435\n4100,3907,2306\n4125,318,421\n4150,2232,1450", "Selected OI levels: strike,callOI,putOI", group=gOpt)
 
// APPEARANCE
gView = "03 | Appearance"
showPanel = input.bool(true, "Dashboard", group=gView)
positionInput = input.string("Top right", "Position", options=["Top right", "Bottom right", "Top left", "Bottom left"], group=gView)
small = input.string("Small", "Text size", options=["Tiny", "Small", "Normal"], group=gView)
showActivity = input.bool(false, "CME volume levels", group=gView)
showOI = input.bool(true, "CME OI levels", group=gView)
showTouch = input.bool(false, "Historical reach on labels", group=gView)
showLabels = input.bool(true, "Level labels", group=gView)
labelOffset = input.int(4, "Label offset", minval=1, maxval=50, group=gView)
 
// TREND AND VOLUME
gModel = "04 | GC calculations"
fastLen = input.int(9, "Fast EMA", minval=2, maxval=200, group=gModel)
slowLen = input.int(21, "Slow EMA", minval=3, maxval=400, group=gModel)
slopeLen = input.int(3, "Slope lookback", minval=1, maxval=50, group=gModel)
flowLen = input.int(10, "Volume lookback", minval=2, maxval=200, group=gModel)
flowLimit = input.float(15, "Volume pressure threshold (%)", minval=1, group=gModel)
pivotLen = input.int(2, "CVD pivot length", minval=1, maxval=20, group=gModel)
freshBars = input.int(4, "Fresh divergence bars", minval=1, group=gModel)
horizon = input.int(6, "Historical horizon (GC bars)", minval=1, maxval=100, group=gModel)
minSamples = input.int(30, "Minimum examples", minval=5, group=gModel)
 
// AMD
gAMD = "05 | AMD — all GC sessions"
showAMD = input.bool(true, "Show AMD zones", group=gAMD)
amdMode = input.string("30m", "AMD reference range", options=["30m", "1H", "4H", "Daily"], group=gAMD)
string amdTF = amdMode == "30m" ? "30" : amdMode == "1H" ? "60" : amdMode == "4H" ? "240" : "D"
zoneAlpha = input.int(82, "Zone transparency", minval=50, maxval=95, group=gAMD)
keepDays = input.int(8, "Keep AMD cycles", minval=1, maxval=20, group=gAMD)
 
color bg = color.rgb(17,22,30)
color muted = color.rgb(151,164,181)
color white = color.rgb(230,237,245)
color green = color.rgb(55,202,151)
color red = color.rgb(239,68,68)
color amber = color.rgb(249,149,45)
color blue = color.rgb(59,130,246)
color purple = color.rgb(184,151,255)
 
f_parse(string txt) =>
    float[] prices = array.new_float()
    float[] calls = array.new_float()
    float[] puts = array.new_float()
    for row in str.split(txt, "\n")
        if str.length(str.trim(row)) > 0
            parts = str.split(row, ",")
            if array.size(parts) != 3
                runtime.error("Each snapshot row needs: strike,calls,puts")
            float p = str.tonumber(str.trim(array.get(parts,0)))
            float c = str.tonumber(str.trim(array.get(parts,1)))
            float u = str.tonumber(str.trim(array.get(parts,2)))
            if na(p) or na(c) or na(u) or p <= 0 or c < 0 or u < 0
                runtime.error("Use positive strikes and nonnegative counts.")
            array.push(prices,p)
            array.push(calls,c)
            array.push(puts,u)
    if array.size(prices) > 15
        runtime.error("Use at most 15 rows per snapshot list.")
    [prices,calls,puts]
 
f_parseColumn(string txt, int column) =>
    [prices,calls,puts] = f_parse(txt)
    column==0 ? prices : column==1 ? calls : puts
 
var float[] volPrices = f_parseColumn(ladder,0)
var float[] volCalls = f_parseColumn(ladder,1)
var float[] volPuts = f_parseColumn(ladder,2)
var float[] oiPrices = f_parseColumn(oiText,0)
var float[] oiCalls = f_parseColumn(oiText,1)
var float[] oiPuts = f_parseColumn(oiText,2)
 
f_price(float p) =>
    na(p) ? "N/A" : str.tostring(p, "#.00")
 
f_pct(float p) =>
    na(p) ? "N/A" : str.tostring(p, "#.0") + "%"
 
// HISTORICAL OBSERVATIONS
gStudy = "07 | Scalping research"
signalReset = input.string("AMD cycle", "New signal allowance", options=["AMD cycle", "Session"], group=gStudy)
studyFrom = input.time(0, "Count signals from (1970 = all loaded history)", group=gStudy)
historyBars = input.int(5000, "Requested source bars", minval=2000, maxval=20000, step=1000, group=gStudy)
xauCostPrice = input.float(0.20, "XAU round-trip cost in USD price units", minval=0, step=0.01, group=gStudy)
xauBufferPrice = input.float(0.20, "XAU swing-stop buffer in USD price units", minval=0.01, step=0.01, group=gStudy)
compareSetup = input.string("MR3", "Compare GC vs XAU setup", options=["MR3", "Old entry", "Breakout"], group=gStudy)
testBars = input.int(6, "Maximum holding period (source bars)", minval=1, maxval=100, group=gStudy)
studyBand = input.float(1.5, "VWAP distance / previous ATR(14)", minval=0.25, step=0.25, group=gStudy)
studyCost = input.float(2, "Round-trip costs + slippage (GC ticks)", minval=0, step=0.5, group=gStudy)
studyHighVX = input.float(25, "High VXN threshold (unused comparison)", minval=1, group=gStudy)
studyMin = input.int(30, "Minimum closed cases before displaying %", minval=10, group=gStudy)
showSetupLevels = input.bool(true, "Show active setup target / stop", group=gStudy)
showOpeningRange = input.bool(true, "Show current 30-minute opening range", group=gStudy)
 
// VWAP AND VOLATILITY
gVW = "08 | VWAP and volatility filter"
showVWAP = input.bool(true, "Show session VWAP", group=gVW)
vwapColor = input.color(color.aqua, "VWAP colour", group=gVW)
showMRSignals = input.bool(true, "Show confirmed MR signals", group=gVW)
volMin = input.float(0.75, "Minimum ATR / recent average", minval=0.1, step=0.05, group=gVW)
volMax = input.float(1.25, "Maximum ATR / recent average", minval=0.1, step=0.05, group=gVW)
if volMin > volMax
    runtime.error("Minimum volatility ratio must not exceed maximum.")
 
// ENTRY
gEntry = "09 | Confirmed swing entry"
entryFastLen = input.int(9, "Entry fast EMA", minval=2, group=gEntry)
entrySlowLen = input.int(21, "Entry slow EMA", minval=3, group=gEntry)
requireTrend = input.bool(false, "Require fast EMA above/below slow EMA", group=gEntry)
swingBuffer = input.int(2, "Stop buffer beyond swing (GC ticks)", minval=1, group=gEntry)
minEntryRR = input.float(1.2, "Minimum net reward / risk to VWAP", minval=0.1, step=0.1, group=gEntry)
 
f_anchor(string tz, int hh, int mm) =>
    int a = timestamp(tz, year(time,tz), month(time,tz), dayofmonth(time,tz), hh, mm)
    time < a ? timestamp(tz, year(time,tz), month(time,tz), dayofmonth(time,tz)-1, hh, mm) : a
 
f_sname(int s) =>
    s == 0 ? "ASIA" : s == 1 ? "LONDON" : "NEW YORK"
 
f_stext(int state, int side, int age) =>
    state == 1 ? "ACTIVE "+(side==1 ? "LONG" : "SHORT")+" | "+str.tostring(age)+" bars" : state==0 ? "NO ACTIVE SETUP" : "CLOSED: "+(state==2 ? "TARGET" : state==3 ? "STOP" : "TIME LIMIT")
 
f_result(array<int> nn, array<int> hh, array<float> rr, array<float> aa, int k, bool detail) =>
    int n = array.get(nn,k)
    int h = array.get(hh,k)
    string basic = str.tostring(h)+"/"+str.tostring(n)
    basic += n >= studyMin ? " ("+str.tostring(100.0*h/n,"#.0")+"%)" : ""
    detail ? basic + (n>0 ? " | mean net "+str.tostring(array.get(rr,k)/n,"#.00")+"R | adverse <= "+str.tostring(array.get(aa,k)/n,"#.00")+"R" : "") : basic
 
gAudit = "10 | Results audit"
dashboardView = input.string("Overview", "Dashboard view", options=["Overview", "Compare markets", "Results", "Trading", "Macro", "Gold context"], group=gAudit)
auditSession = input.string("All", "Results session", options=["All", "Asia", "London", "New York"], group=gAudit)
 
f_count(int x, int n) =>
    str.tostring(x)+(n>0 ? " / "+str.tostring(100.0*x/n,"#.0")+"%" : "")
 
f_audit(array<int> nn, array<int> hh, array<int> stops, array<int> exps, array<int> wins, array<float> rr, array<float> gains, array<float> losses, array<float> exr, int k, bool pending) =>
    int total=0
    int hits=0
    int stopped=0
    int timed=0
    int won=0
    float net=0.0
    float gp=0.0
    float gl=0.0
    float timeR=0.0
    for ss=0 to 2
        bool includeSession = auditSession=="All" or (auditSession=="Asia" and ss==0) or (auditSession=="London" and ss==1) or (auditSession=="New York" and ss==2)
        if includeSession
            int z=(k*3+ss)*6
            total+=array.get(nn,z)
            hits+=array.get(hh,z)
            stopped+=array.get(stops,z)
            timed+=array.get(exps,z)
            won+=array.get(wins,z)
            net+=array.get(rr,z)
            gp+=array.get(gains,z)
            gl+=array.get(losses,z)
            timeR+=array.get(exr,z)
    if total!=hits+stopped+timed
        runtime.error("Outcome reconciliation failed.")
    string pf = gl>0 ? str.tostring(gp/gl,"#.00") : gp>0 ? "No losses yet" : "N/A"
    str.tostring(total)+(total<studyMin ? " (small)" : "")+";"+f_count(hits,total)+";"+f_count(stopped,total)+";"+f_count(timed,total)+";"+f_count(won,total)+";"+(total>0 ? str.tostring(net/total,"#.00")+"R" : "N/A")+";"+str.tostring(net,"#.00")+"R;"+pf+";"+(timed>0 ? str.tostring(timeR/timed,"#.00")+"R" : "N/A")+";"+(pending ? "ACTIVE (excluded)" : "NONE")
 
// SAME ENGINE EXECUTED IN EACH SOURCE CONTEXT
f_engine(bool nativeXau) =>
    float costPoints = nativeXau ? xauCostPrice : studyCost*syminfo.mintick
    float bufferPoints = nativeXau ? xauBufferPrice : swingBuffer*syminfo.mintick
    var int loadedBars = 0
    loadedBars += 1
    float fast = ta.ema(close, fastLen)
    float slow = ta.ema(close, slowLen)
    bool volOK = not na(volume) and volume > 0
    float signedVol = volOK ? volume * (close > open ? 1 : close < open ? -1 : 0) : 0
    float validShare = ta.sma(volOK ? 1.0 : 0.0, flowLen)
    float avgVol = ta.sma(nz(volume), flowLen)
    float avgSigned = ta.sma(signedVol, flowLen)
    float pressure = validShare == 1 and avgVol > 0 ? 100 * avgSigned / avgVol : na
    float rvol = volOK and avgVol > 0 ? volume / avgVol : na
    bool ready = not na(slow[slopeLen]) and not na(pressure) and not na(rvol)
    int bullPoints = (close > fast ? 1 : 0) + (fast > slow ? 1 : 0) + (fast > fast[slopeLen] ? 1 : 0) + (slow > slow[slopeLen] ? 1 : 0) + (pressure > flowLimit ? 1 : 0)
    int bearPoints = (close < fast ? 1 : 0) + (fast < slow ? 1 : 0) + (fast < fast[slopeLen] ? 1 : 0) + (slow < slow[slopeLen] ? 1 : 0) + (pressure < -flowLimit ? 1 : 0)
    int trendState = close > fast and fast > slow ? 2 : close < fast and fast < slow ? 0 : 1
    int flowState = pressure > flowLimit ? 2 : pressure < -flowLimit ? 0 : 1
    int state = ready ? trendState * 6 + flowState * 2 + (rvol >= 1 ? 1 : 0) : na
 
    float cvd = ta.cum(signedVol)
    float gaps = ta.cum(volOK ? 0.0 : 1.0)
    float pl = ta.pivotlow(low, pivotLen, pivotLen)
    float ph = ta.pivothigh(high, pivotLen, pivotLen)
    var float oldLow = na
    var float lowCVD = na
    var float lowGaps = na
    var float oldHigh = na
    var float highCVD = na
    var float highGaps = na
    var int bullBar = na
    var int bearBar = na
    if not na(pl)
        if not na(oldLow) and volOK[pivotLen] and gaps[pivotLen] == lowGaps and pl < oldLow and cvd[pivotLen] > lowCVD
            bullBar := bar_index
        oldLow := pl
        lowCVD := cvd[pivotLen]
        lowGaps := gaps[pivotLen]
    if not na(ph)
        if not na(oldHigh) and volOK[pivotLen] and gaps[pivotLen] == highGaps and ph > oldHigh and cvd[pivotLen] < highCVD
            bearBar := bar_index
        oldHigh := ph
        highCVD := cvd[pivotLen]
        highGaps := gaps[pivotLen]
 
    var int[] counts = array.new_int(18, 0)
    var int[] ups = array.new_int(18, 0)
    var int[] downs = array.new_int(18, 0)
    float windowHigh = ta.highest(high, horizon)
    float windowLow = ta.lowest(low, horizon)
    var int[] touchStates = array.new_int()
    var float[] touchUp = array.new_float()
    var float[] touchDown = array.new_float()
    var int baseN = 0
    var int baseUp = 0
    if bar_index >= horizon and bar_index % horizon == 0
        int prior = state[horizon]
        if not na(prior) and ready and close[horizon] > 0
            array.set(counts, prior, array.get(counts, prior) + 1)
            if close > close[horizon]
                array.set(ups, prior, array.get(ups, prior) + 1)
                baseUp += 1
            if close < close[horizon]
                array.set(downs, prior, array.get(downs, prior) + 1)
            baseN += 1
            array.push(touchStates, prior)
            array.push(touchUp, math.max(0.0, (windowHigh / close[horizon] - 1) * 100))
            array.push(touchDown, math.max(0.0, (1 - windowLow / close[horizon]) * 100))
            if array.size(touchStates) > 2000
                array.shift(touchStates)
                array.shift(touchUp)
                array.shift(touchDown)
    int n = not na(state) ? array.get(counts,state) : 0
    float up = n > 0 ? 100.0 * array.get(ups,state) / n : na
    float dn = n > 0 ? 100.0 * array.get(downs,state) / n : na
    bool lastBull = not na(bullBar) and (na(bearBar) or bullBar > bearBar)
    int divBar = lastBull ? bullBar : bearBar
    int age = na(divBar) ? na : bar_index - divBar
    string reach = ""
    if showTouch and not nativeXau and bar_index >= last_bar_index - 2
        float[] targets = array.from(callWall,putWall,flip)
        for p in volPrices
            array.push(targets,p)
        for p in oiPrices
            array.push(targets,p)
        for p in targets
            int cases = 0
            int hits = 0
            float distance = math.abs(p / close - 1) * 100
            if not na(state) and array.size(touchStates) > 0
                for j = 0 to array.size(touchStates)-1
                    if array.get(touchStates,j) == state
                        cases += 1
                        float excursion = p >= close ? array.get(touchUp,j) : array.get(touchDown,j)
                        if excursion >= distance
                            hits += 1
            reach += (cases >= minSamples ? str.tostring(100.0 * hits/cases,"#") + "%" : "N/A") + ";"
 
    [refHigh, refLow] = request.security(syminfo.tickerid, amdTF, [high[1], low[1]], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
    int cycle = time(amdTF)
    var int previousCycle = na
    var int at = na
    var int mt = na
    var int dt = na
    var int ae = na
    var int me = na
    var int de = na
    var float ah = na
    var float al = na
    var float mh = na
    var float ml = na
    var float dh = na
    var float dl = na
    var int sweep = 0
    var int sweepAt = na
    var int direction = 0
    bool supported = timeframe.isintraday and timeframe.in_seconds() < timeframe.in_seconds(amdTF)
    if supported and not na(refHigh) and not na(refLow)
        if na(previousCycle) or cycle != previousCycle
            previousCycle := cycle
            at := time
            ae := time_close
            ah := refHigh
            al := refLow
            mt := na
            dt := na
            mh := na
            ml := na
            dh := na
            dl := na
            sweep := 0
            sweepAt := na
            direction := 0
        ae := time_close
        bool highSweep = high > ah and close < ah and close > al
        bool lowSweep = low < al and close > al and close < ah
        if sweep == 0 and highSweep != lowSweep
            sweep := lowSweep ? 1 : -1
            sweepAt := bar_index
            mt := time
            mh := highSweep ? high : al
            ml := highSweep ? ah : low
        if not na(mt) and direction == 0
            me := time_close
            if sweep == -1
                mh := math.max(mh, high)
            else
                ml := math.min(ml, low)
        if direction == 0 and not na(sweepAt) and bar_index > sweepAt
            if sweep == 1 and close > ah
                direction := 1
            if sweep == -1 and close < al
                direction := -1
            if direction != 0
                dt := time
                dh := direction == 1 ? high : al
                dl := direction == 1 ? ah : low
        if direction != 0
            de := time_close
            if direction == 1
                dh := math.max(dh,high)
            else
                dl := math.min(dl,low)
 
    int asStart = f_anchor("Asia/Tokyo",9,0)
    int euStart = f_anchor("Europe/London",8,0)
    int usStart = f_anchor("America/New_York",9,30)
    int sStart = math.max(asStart,math.max(euStart,usStart))
    int sID = sStart == asStart ? 0 : sStart == euStart ? 1 : 2
    bool sNew = na(sStart[1]) or sStart != sStart[1]
    float atrNow = ta.atr(14)
    float atrNormal = ta.sma(atrNow,50)
    float volRatio = atrNormal>0 ? atrNow/atrNormal : na
    bool volAligned = not na(volRatio) and volRatio>=volMin and volRatio<=volMax and atrNow<atrNow[1]
    var bool rVolAligned = false
    float atrRef = atrNow[1]
    bool tfOK = timeframe.isminutes and (timeframe.multiplier == 1 or timeframe.multiplier == 2 or timeframe.multiplier == 3 or timeframe.multiplier == 5 or timeframe.multiplier == 10 or timeframe.multiplier == 15)
    var float orHigh = na
    var float orLow = na
    var int orMs = 0
    var float pv = 0.0
    var float vv = 0.0
    var bool sComplete = false
    var bool sVolumeOK = false
    var bool orbUsed = false
    var bool revUsed = false
    var bool confirmedUsed = false
    if sNew
        orHigh := na
        orLow := na
        orMs := 0
        pv := 0.0
        vv := 0.0
        sComplete := time == sStart
        sVolumeOK := true
        orbUsed := false
        revUsed := false
        confirmedUsed := false
    if signalReset == "AMD cycle" and not sNew and cycle != cycle[1]
        orbUsed := false
        revUsed := false
        confirmedUsed := false
    if not volOK
        sVolumeOK := false
    if volOK
        pv += hlc3 * volume
        vv += volume
    float sessionVWAP = sComplete and sVolumeOK and vv>0 ? pv/vv : na
    if time>=sStart and time_close<=sStart+30*60000
        orHigh := na(orHigh) ? high : math.max(orHigh,high)
        orLow := na(orLow) ? low : math.min(orLow,low)
        orMs += time_close-time
    bool orReady = tfOK and sComplete and orMs==30*60000 and time>=sStart+30*60000 and orHigh>orLow
    float fixedMean = not sNew ? sessionVWAP[1] : na
    float lowerBand = fixedMean-studyBand*atrRef
    float upperBand = fixedMean+studyBand*atrRef
    bool breakUp = orReady and close>orHigh and close[1]<=orHigh
    bool breakDn = orReady and close<orLow and close[1]>=orLow
    bool reverseUp = orReady and sVolumeOK and low<lowerBand and close>lowerBand and close<fixedMean
    bool reverseDn = orReady and sVolumeOK and high>upperBand and close<upperBand and close>fixedMean
 
    float entryFast = ta.ema(close,entryFastLen)
    float entrySlow = ta.ema(close,entrySlowLen)
    bool sameSession3 = sStart==sStart[2]
    bool adjacent3 = time==time_close[1] and time[1]==time_close[2]
    bool swingLow3 = sameSession3 and adjacent3 and low[1]<low[2] and low[1]<low
    bool swingHigh3 = sameSession3 and adjacent3 and high[1]>high[2] and high[1]>high
    bool emaLong = close>entryFast and entryFast>entryFast[1] and (not requireTrend or entryFast>entrySlow)
    bool emaShort = close<entryFast and entryFast<entryFast[1] and (not requireTrend or entryFast<entrySlow)
    bool confirmedUp = orReady and sVolumeOK and volAligned and swingLow3 and low[1]<lowerBand[1] and close>high[1] and close>lowerBand and close<fixedMean and emaLong
    bool confirmedDn = orReady and sVolumeOK and volAligned and swingHigh3 and high[1]>upperBand[1] and close<low[1] and close<upperBand and close>fixedMean and emaShort
    float testVX = na
    int testVXEnd = na
    bool vxKnown = not na(testVXEnd) and testVX>0 and time>=testVXEnd and time-testVXEnd<=3*86400000
    int vxBucket = not vxKnown ? 3 : testVX>=studyHighVX ? 1 : 2
 
    var int[] sn = array.new_int(54,0)
    var int[] sh = array.new_int(54,0)
    var float[] sr = array.new_float(54,0.0)
    var int[] stopCounts = array.new_int(54,0)
    var int[] expiryCounts = array.new_int(54,0)
    var int[] netWins = array.new_int(54,0)
    var float[] positiveR = array.new_float(54,0.0)
    var float[] negativeR = array.new_float(54,0.0)
    var float[] expiryR = array.new_float(54,0.0)
    var float[] sa = array.new_float(54,0.0)
    var int[] st = array.new_int(3,0)
    var int[] side = array.new_int(3,0)
    var int[] startBar = array.new_int(3,na)
    var int[] startTime = array.new_int(3,na)
    var int[] sess = array.new_int(3,0)
    var int[] vxClass = array.new_int(3,3)
    var int[] divClass = array.new_int(3,5)
    var float[] entry = array.new_float(3,na)
    var float[] target = array.new_float(3,na)
    var float[] stop = array.new_float(3,na)
    var float[] adverse = array.new_float(3,0.0)
    var float[] eventR = array.new_float(3,na)
 
    for k=0 to 2
        bool settled = false
        if array.get(st,k)==1 and bar_index>array.get(startBar,k)
            int d = array.get(side,k)
            float e = array.get(entry,k)
            float t = array.get(target,k)
            float sl = array.get(stop,k)
            float risk = math.abs(e-sl)
            bool hitStop = d==1 ? low<=sl : high>=sl
            bool hitTarget = d==1 ? high>=t : low<=t
            bool expired = bar_index-array.get(startBar,k)>=testBars
            float a = math.max(0.0,d==1 ? e-low : high-e)/risk
            array.set(adverse,k,math.max(array.get(adverse,k),a))
            if hitStop or hitTarget or expired
                float fill = hitStop ? (d==1 ? math.min(open,sl) : math.max(open,sl)) : hitTarget ? t : close
                float netR = (d*(fill-e)-costPoints)/risk
                bool success = hitTarget and not hitStop
                array.set(st,k,hitStop ? 3 : hitTarget ? 2 : 4)
                array.set(eventR,k,netR)
                int base = (k*3+array.get(sess,k))*6
                for group=0 to 5
                    if group==0 or group==array.get(vxClass,k) or group==array.get(divClass,k)
                        int z = base+group
                        array.set(sn,z,array.get(sn,z)+1)
                        array.set(sh,z,array.get(sh,z)+(success ? 1 : 0))
                        array.set(sr,z,array.get(sr,z)+netR)
                        array.set(stopCounts,z,array.get(stopCounts,z)+(hitStop ? 1 : 0))
                        array.set(expiryCounts,z,array.get(expiryCounts,z)+(not hitStop and not hitTarget ? 1 : 0))
                        array.set(netWins,z,array.get(netWins,z)+(netR>0 ? 1 : 0))
                        array.set(positiveR,z,array.get(positiveR,z)+math.max(netR,0))
                        array.set(negativeR,z,array.get(negativeR,z)+math.max(-netR,0))
                        array.set(expiryR,z,array.get(expiryR,z)+(not hitStop and not hitTarget ? netR : 0))
                        array.set(sa,z,array.get(sa,z)+array.get(adverse,k))
                settled := true
        bool unused = k==0 ? not orbUsed : k==1 ? not revUsed : not confirmedUsed
        bool sigUp = k==0 ? breakUp : k==1 ? reverseUp : confirmedUp
        bool sigDown = k==0 ? breakDn : k==1 ? reverseDn : confirmedDn
        if tfOK and time>=studyFrom and unused and not settled and array.get(st,k)!=1 and (sigUp or sigDown)
            int d = sigUp ? 1 : -1
            float t = k==0 ? close+d*(orHigh-orLow) : fixedMean
            float sl = k==0 ? (d==1 ? orLow : orHigh) : k==1 ? close-d*atrRef : d==1 ? low[1]-bufferPoints : high[1]+bufferPoints
            t := math.round(t/syminfo.mintick)*syminfo.mintick
            sl := math.round(sl/syminfo.mintick)*syminfo.mintick
            float expectedRisk = d*(close-sl)
            float expectedReward = d*(t-close)
            float assumedCost = costPoints
            float netRR = expectedRisk>0 ? (expectedReward-assumedCost)/(expectedRisk+assumedCost) : na
            bool roomOK = k!=2 or (not na(netRR) and netRR>=minEntryRR)
            if expectedRisk>=syminfo.mintick and expectedReward>=syminfo.mintick and roomOK
                array.set(st,k,1)
                array.set(side,k,d)
                array.set(startBar,k,bar_index)
                array.set(startTime,k,time_close)
                array.set(sess,k,sID)
                array.set(vxClass,k,vxBucket)
                bool aligned = d==1 ? not na(bullBar) and bar_index-bullBar<=freshBars : not na(bearBar) and bar_index-bearBar<=freshBars
                array.set(divClass,k,aligned ? 4 : 5)
                array.set(entry,k,close)
                array.set(target,k,t)
                array.set(stop,k,sl)
                array.set(adverse,k,0.0)
                array.set(eventR,k,na)
                if k==0
                    orbUsed := true
                else if k==1
                    revUsed := true
                    rVolAligned := volAligned
                else
                    confirmedUsed := true
 
    string bStatus = f_stext(array.get(st,0),array.get(side,0),bar_index-array.get(startBar,0))
    string rStatus = f_stext(array.get(st,1),array.get(side,1),bar_index-array.get(startBar,1))
    if not tfOK
        bStatus := "Use 1/2/3/5/10/15 min"
        rStatus := bStatus
    else
        if array.get(st,0)==0
            bStatus := orReady ? "WAITING FOR BREAK" : "BUILDING / MISSING RANGE"
        if array.get(st,1)==0
            rStatus := na(sessionVWAP) ? "VWAP DATA MISSING" : "WAITING FOR RE-ENTRY"
 
    string statsAsia = bar_index >= last_bar_index - 2 and not nativeXau ? "C "+f_result(sn,sh,sr,sa,36,false) : ""
    string statsLondon = bar_index >= last_bar_index - 2 and not nativeXau ? "C "+f_result(sn,sh,sr,sa,42,false) : ""
    string statsNY = bar_index >= last_bar_index - 2 and not nativeXau ? "C "+f_result(sn,sh,sr,sa,48,false) : ""
    string studyDetails = bar_index >= last_bar_index - 2 and not nativeXau ? "Historical observations. Target before stop within "+str.tostring(testBars)+" bars. Entry bar excluded; stop wins same-bar ties. Costs "+str.tostring(studyCost)+" ticks. Pending excluded. Independent setup tests, not a portfolio.\n" : ""
    if bar_index>=last_bar_index-2 and not nativeXau
        for ss=0 to 2
            studyDetails += "\n"+f_sname(ss)+"\n"
            for kk=0 to 2
                int base = (kk*3+ss)*6
                studyDetails += (kk==0 ? "Breakout: " : kk==1 ? "Legacy reversal: " : "CONFIRMED SWING: ")+f_result(sn,sh,sr,sa,base,true)+"\n"
                studyDetails += "Aligned divergence: "+f_result(sn,sh,sr,sa,base+4,true)+"\nOther: "+f_result(sn,sh,sr,sa,base+5,true)+"\n"
 
    float bTarget = array.get(st,0)==1 ? array.get(target,0) : na
    float bStop = array.get(st,0)==1 ? array.get(stop,0) : na
    float rTarget = array.get(st,1)==1 ? array.get(target,1) : na
    float rStop = array.get(st,1)==1 ? array.get(stop,1) : na
    int bSignal = array.get(startTime,0)
    int rSignal = array.get(startTime,1)
    float bResult = array.get(eventR,0)
    float rResult = array.get(eventR,1)
    int bOutcome = array.get(st,0)
    int rOutcome = array.get(st,1)
    float bEntry = array.get(entry,0)
    float rEntry = array.get(entry,1)
    float bEventTarget = array.get(target,0)
    float rEventTarget = array.get(target,1)
    float bEventStop = array.get(stop,0)
    float rEventStop = array.get(stop,1)
    float bAdverse = array.get(adverse,0)
    float rAdverse = array.get(adverse,1)
    string cStatus = f_stext(array.get(st,2),array.get(side,2),bar_index-array.get(startBar,2))
    if array.get(st,2)==0
        cStatus := not tfOK ? "Use intraday minutes" : not orReady ? "BUILDING / MISSING RANGE" : "WAITING FOR CONFIRMATION"
    float cTarget = array.get(st,2)==1 ? array.get(target,2) : na
    float cStop = array.get(st,2)==1 ? array.get(stop,2) : na
    float cEntry = array.get(entry,2)
    int cSignal = array.get(startTime,2)
    int cOutcome = array.get(st,2)
    float cResult = array.get(eventR,2)
    float cEventTarget = array.get(target,2)
    float cEventStop = array.get(stop,2)
    float cAdverse = array.get(adverse,2)
    bool pendingB = array.get(st,0)==1 and (auditSession=="All" or auditSession=="Asia" and array.get(sess,0)==0 or auditSession=="London" and array.get(sess,0)==1 or auditSession=="New York" and array.get(sess,0)==2)
    bool pendingL = array.get(st,1)==1 and (auditSession=="All" or auditSession=="Asia" and array.get(sess,1)==0 or auditSession=="London" and array.get(sess,1)==1 or auditSession=="New York" and array.get(sess,1)==2)
    bool pendingC = array.get(st,2)==1 and (auditSession=="All" or auditSession=="Asia" and array.get(sess,2)==0 or auditSession=="London" and array.get(sess,2)==1 or auditSession=="New York" and array.get(sess,2)==2)
    string auditB = bar_index>=last_bar_index-2 ? f_audit(sn,sh,stopCounts,expiryCounts,netWins,sr,positiveR,negativeR,expiryR,0,pendingB) : ""
    string auditL = bar_index>=last_bar_index-2 ? f_audit(sn,sh,stopCounts,expiryCounts,netWins,sr,positiveR,negativeR,expiryR,1,pendingL) : ""
    string auditC = bar_index>=last_bar_index-2 ? f_audit(sn,sh,stopCounts,expiryCounts,netWins,sr,positiveR,negativeR,expiryR,2,pendingC) : ""
    var int historyStart = time
    string sessionText = f_sname(sID)
 
    [time[1],time_close[1],close[1],volume[1],pressure[1],rvol[1],bullPoints[1],bearPoints[1],n[1],up[1],dn[1],lastBull[1],age[1],reach[1],at[1],ae[1],ah[1],al[1],mt[1],me[1],mh[1],ml[1],dt[1],de[1],dh[1],dl[1],direction[1],sweep[1],bStatus[1],rStatus[1],statsAsia[1],statsLondon[1],statsNY[1],studyDetails[1],bTarget[1],bStop[1],rTarget[1],rStop[1],bSignal[1],rSignal[1],bResult[1],rResult[1],bOutcome[1],rOutcome[1],orHigh[1],orLow[1],sessionText[1],bEntry[1],rEntry[1],bEventTarget[1],rEventTarget[1],bEventStop[1],rEventStop[1],bAdverse[1],rAdverse[1],sessionVWAP[1],sNew[1],volRatio[1],volAligned[1],rVolAligned[1],cStatus[1],cTarget[1],cStop[1],cEntry[1],cSignal[1],cOutcome[1],cResult[1],cEventTarget[1],cEventStop[1],cAdverse[1],auditB[1],auditL[1],auditC[1],historyStart[1],loadedBars[1]]
 
[gt,gEnd,gClose,gVol,gPressure,gRvol,bull,bear,samples,upRate,downRate,divBull,divAge,reachText,at,ae,ah,al,mt,me,mh,ml,dt,de,dh,dl,direction,sweep,bStatus,rStatus,statsAsia,statsLondon,statsNY,studyDetails,bTarget,bStop,rTarget,rStop,bSignal,rSignal,bResult,rResult,bOutcome,rOutcome,orHigh,orLow,sessionText,bEntry,rEntry,bEventTarget,rEventTarget,bEventStop,rEventStop,bAdverse,rAdverse,gVWAP,vwapReset,volRatio,volAligned,rVolAligned,cStatus,cTarget,cStop,cEntry,cSignal,cOutcome,cResult,cEventTarget,cEventStop,cAdverse,auditB,auditL,auditC,historyStart,loadedBars] = request.security(gcSource,timeframe.period,f_engine(false),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=historyBars)
 
f_xauAudit() =>
    [gt,gEnd,gClose,gVol,gPressure,gRvol,bull,bear,samples,upRate,downRate,divBull,divAge,reachText,at,ae,ah,al,mt,me,mh,ml,dt,de,dh,dl,direction,sweep,bStatus,rStatus,statsAsia,statsLondon,statsNY,studyDetails,bTarget,bStop,rTarget,rStop,bSignal,rSignal,bResult,rResult,bOutcome,rOutcome,orHigh,orLow,sessionText,bEntry,rEntry,bEventTarget,rEventTarget,bEventStop,rEventStop,bAdverse,rAdverse,gVWAP,vwapReset,volRatio,volAligned,rVolAligned,cStatus,cTarget,cStop,cEntry,cSignal,cOutcome,cResult,cEventTarget,cEventStop,cAdverse,auditB,auditL,auditC,historyStart,loadedBars] = f_engine(true)
    [auditB,auditL,auditC,historyStart,gt,gEnd,loadedBars]
 
[xAuditB,xAuditL,xAuditC,xHistoryStart,xLastTime,xLastEnd,xLoadedBars] = request.security(xauSource,timeframe.period,f_xauAudit(),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=historyBars)
[xt,xEnd,xClose] = request.security(xauSource,timeframe.period,[time[1],time_close[1],close[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=historyBars)
 
// LOCKED GC -> XAU BASIS
var float lockedBasis = na
var float lockedGC = na
var float lockedXAU = na
var int lockedTime = na
bool matchingReference = not na(gClose) and not na(xClose) and gt == xt and gEnd == xEnd and gt <= referenceTime and gEnd > referenceTime
if na(lockedBasis) and matchingReference
    lockedBasis := xClose - gClose
    lockedGC := gClose
    lockedXAU := xClose
    lockedTime := gt
float activeBasis = basisMode == "Manual fixed offset" ? basis : lockedBasis
float shift = isXau ? activeBasis : 0.0
bool mappingReady = not isXau or not na(activeBasis)
bool feedOK = not na(gClose)
bool staleFeed = feedOK and time - gEnd > timeframe.in_seconds()*1000*2
 
// AMD DRAWINGS
var box[] pool = array.new_box()
var float[] rawTops = array.new_float()
var float[] rawBottoms = array.new_float()
var box aBox = na
var box mBox = na
var box dBox = na
var int lastA = na
var int lastM = na
var int lastD = na
 
f_box(int left,int right,float hi,float lo,color tint,string caption) =>
    array.push(rawTops,hi)
    array.push(rawBottoms,lo)
    box.new(left=left,right=right,top=hi,bottom=lo,xloc=xloc.bar_time,bgcolor=color.new(tint,zoneAlpha),border_color=color.new(tint,30),text=caption,text_color=tint,text_size=size.tiny,text_halign=text.align_left,text_valign=text.align_top,force_overlay=true)
 
f_update(box id,int right,float hi,float lo,color tint,string caption) =>
    box.set_right(id,right)
    int i = array.indexof(pool,id)
    if i >= 0
        array.set(rawTops,i,hi)
        array.set(rawBottoms,i,lo)
    box.set_top(id,hi)
    box.set_bottom(id,lo)
    box.set_bgcolor(id,color.new(tint,zoneAlpha))
    box.set_border_color(id,color.new(tint,30))
    box.set_text_color(id,tint)
    box.set_text(id,caption)
 
bool amdOK = showAMD and timeframe.isintraday and timeframe.in_seconds() < timeframe.in_seconds(amdTF) and chart.is_standard
if amdOK and feedOK
    if not na(at)
        if na(lastA) or at != lastA
            aBox := f_box(at,ae,ah,al,blue,amdMode + " | PRIOR RANGE")
            array.push(pool,aBox)
            lastA := at
        else
            f_update(aBox,ae,ah,al,blue,amdMode + " | PRIOR RANGE")
    if not na(mt)
        string caption = sweep == 1 ? "MANIPULATION | LOW SWEEP" : sweep == -1 ? "MANIPULATION | HIGH SWEEP" : "MANIPULATION | WINDOW"
        if na(lastM) or mt != lastM
            mBox := f_box(mt,me,mh,ml,red,caption)
            array.push(pool,mBox)
            lastM := mt
        else
            f_update(mBox,me,mh,ml,red,caption)
    if not na(dt)
        color tint = direction == 1 ? green : direction == -1 ? amber : muted
        string caption = direction == 1 ? "DISTRIBUTION | UP" : direction == -1 ? "DISTRIBUTION | DOWN" : "DISTRIBUTION | WAITING"
        if na(lastD) or dt != lastD
            dBox := f_box(dt,de,dh,dl,tint,caption)
            array.push(pool,dBox)
            lastD := dt
        else
            f_update(dBox,de,dh,dl,tint,caption)
    while array.size(pool) > keepDays*3
        box.delete(array.shift(pool))
        array.shift(rawTops)
        array.shift(rawBottoms)
 
var line[] lines = array.new_line()
var label[] labels = array.new_label()
 
f_level(float p,string title,color tint,int idx,string extra) =>
    if p > 0
        float mapped = p+shift
        array.push(lines,line.new(bar_index,mapped,bar_index+1,mapped,extend=extend.right,color=color.new(tint,15),width=2,force_overlay=true))
        if showLabels
            string caption = title + "  " + f_price(mapped) + extra
            int vi = array.indexof(volPrices,p)
            if showActivity and idx < 3 and vi >= 0
                caption += "\nCalls: " + str.tostring(array.get(volCalls,vi),"#") + " | Puts: " + str.tostring(array.get(volPuts,vi),"#")
            rates = str.split(na(reachText) ? "" : reachText,";")
            if showTouch and idx >= 0
                caption += "\nPast reach " + str.tostring(horizon) + " bars: " + (array.size(rates)>idx ? array.get(rates,idx) : "N/A")
            string tip = idx<0 ? "Modeled setup reference, not an option level." : "G1MX6 OI 30 Oct 2026; expiry 02 Nov. Not the whole GC market. Mapping to GC1/XAU is indicative. Historical reach is a comparable-distance frequency, not a forecast or test of this option level."
            array.push(labels,label.new(bar_index+labelOffset,mapped,caption,style=label.style_label_left,color=color.new(bg,8),textcolor=tint,size=size.small,tooltip=tip,force_overlay=true))
 
// MACRO DATA
gMacro = "11 | Gold macro context"
usdSource = input.symbol("TVC:DXY", "US dollar index", group=gMacro)
realSource = input.symbol("FRED:DFII10", "10-year REAL yield", group=gMacro)
silverSource = input.symbol("COMEX:SI1!", "Silver futures", group=gMacro)
macroMaxDays = input.int(5, "Mark daily observations old after calendar days", minval=1, maxval=14, group=gMacro)
macroNoteDate = input.string("NOT SET", "Manual context as-of date / source", group=gMacro)
inflationNote = input.string("Fed 28 Oct: hold 3.75-4.00%; 2 dissent for +25bp", "CPI / Fed note", group=gMacro)
riskNote = input.string("Fed 28 Oct: geopolitical uncertainty elevated; no live news", "Geopolitical / event context", group=gMacro)
cotNote = input.string("NOT UPDATED", "COT manual note", group=gMacro)
etfNote = input.string("NOT UPDATED", "ETF manual note", group=gMacro)
bankNote = input.string("NOT UPDATED", "Central-bank manual note", group=gMacro)
seasonNote = input.string("NOT TESTED", "Seasonality note", group=gMacro)
 
[usdClose,usdPrior,usdStamp,usdEnd] = request.security(usdSource,"D",[close[1],close[2],time[1],time_close[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=20)
[realClose,realPrior,realStamp,realEnd] = request.security(realSource,"D",[close[1],close[2],time[1],time_close[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=20)
[macroGold,macroGoldPrior,macroGoldStamp,macroGoldEnd] = request.security(gcSource,"D",[close[1],close[2],time[1],time_close[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=20)
[macroSilver,macroSilverPrior,macroSilverStamp,macroSilverEnd] = request.security(silverSource,"D",[close[1],close[2],time[1],time_close[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=20)
 
f_macroOld(int stamp) =>
    na(stamp) or time<stamp or time-stamp>macroMaxDays*86400000
 
f_macroDate(int stamp) =>
    na(stamp) ? "Unavailable" : str.format_time(stamp,"dd MMM yyyy","Etc/UTC")
 
f_change(float current,float prior) =>
    na(current) or na(prior) ? "N/A" : current>prior ? "UP" : current<prior ? "DOWN" : "FLAT"
 
f_manual(string value) =>
    str.length(value)>36 ? str.substring(value,0,36)+"..." : value
 
bool usdAvailable = not na(usdClose) and not na(usdPrior)
bool realAvailable = not na(realClose) and not na(realPrior)
bool macroFresh = usdAvailable and realAvailable and not f_macroOld(usdStamp) and not f_macroOld(realStamp)
bool macroSameDate = not na(usdStamp) and not na(realStamp) and f_macroDate(usdStamp)==f_macroDate(realStamp)
string opportunity = not macroFresh ? "MISSING / OLD DATA" : not macroSameDate ? "DATES DIFFER" : usdClose<usdPrior and realClose<realPrior ? "USD DOWN / REAL YIELD DOWN" : usdClose>usdPrior and realClose>realPrior ? "USD UP / REAL YIELD UP" : "MIXED / FLAT"
bool ratioAligned = not na(macroGoldStamp) and not na(macroSilverStamp) and macroGoldStamp==macroSilverStamp and macroGoldEnd==macroSilverEnd and macroSilver>0
float goldSilver = ratioAligned ? macroGold/macroSilver : na
float yieldBp = realAvailable ? (realClose-realPrior)*100 : na
 
// TWO-FACTOR HISTORICAL ASSOCIATION
macroWindow = input.int(60,"Macro model: prior matched observations",minval=30,maxval=120,group=gMacro)
macroMinFit = input.float(0.10,"Minimum in-sample R2 for directional label",minval=0,maxval=1,step=0.05,group=gMacro)
 
f_macroDrivers() =>
    [goldD,goldDay] = request.security(gcSource,"D",[close,time_tradingday],gaps=barmerge.gaps_on,lookahead=barmerge.lookahead_off,ignore_invalid_symbol=true,calc_bars_count=500)
    [dollarD,dollarDay] = request.security(usdSource,"D",[close,time_tradingday],gaps=barmerge.gaps_on,lookahead=barmerge.lookahead_off,ignore_invalid_symbol=true,calc_bars_count=500)
    var float[] xx = array.new_float()
    var float[] yy = array.new_float()
    var float[] zz = array.new_float()
    var float prevGold = na
    var float prevDollar = na
    var float prevYield = na
    var int prevDate = na
    var float usdPart = na
    var float yieldPart = na
    var float fit = na
    var int modelDate = na
    var int used = 0
    var string modelState = "INSUFFICIENT DATA"
    string thisDate = str.format_time(time,"yyyyMMdd","Etc/UTC")
    bool aligned = not na(goldD) and not na(dollarD) and not na(close) and not na(goldDay) and not na(dollarDay) and str.format_time(goldDay,"yyyyMMdd","Etc/UTC")==thisDate and str.format_time(dollarDay,"yyyyMMdd","Etc/UTC")==thisDate
    if aligned
        if not na(prevDate) and time>prevDate and time-prevDate<=4*86400000 and goldD>0 and prevGold>0 and dollarD>0 and prevDollar>0
            float x = 100*math.log(dollarD/prevDollar)
            float y = 100*(close-prevYield)
            float z = 100*math.log(goldD/prevGold)
            int n = array.size(xx)
            usdPart := na
            yieldPart := na
            fit := na
            used := n
            modelDate := time
            modelState := "INSUFFICIENT DATA"
            if n>=macroWindow
                float mx = array.avg(xx)
                float my = array.avg(yy)
                float mz = array.avg(zz)
                float sxx = 0.0
                float syy = 0.0
                float sxy = 0.0
                float sxz = 0.0
                float syz = 0.0
                float szz = 0.0
                for i=0 to n-1
                    float dx = array.get(xx,i)-mx
                    float dy = array.get(yy,i)-my
                    float dz = array.get(zz,i)-mz
                    sxx += dx*dx
                    syy += dy*dy
                    sxy += dx*dy
                    sxz += dx*dz
                    syz += dy*dz
                    szz += dz*dz
                float determinant = sxx*syy-sxy*sxy
                modelState := "UNSTABLE FIT"
                if sxx>0 and syy>0 and szz>0 and determinant>0.01*sxx*syy
                    float bx = (sxz*syy-syz*sxy)/determinant
                    float yieldBeta = (syz*sxx-sxz*sxy)/determinant
                    usdPart := bx*x
                    yieldPart := yieldBeta*y
                    fit := math.max(0,math.min(1,(bx*sxz+yieldBeta*syz)/szz))
                    modelState := fit<macroMinFit ? "WEAK FIT" : "MODEL READY"
            array.push(xx,x)
            array.push(yy,y)
            array.push(zz,z)
            if array.size(xx)>macroWindow
                array.shift(xx)
                array.shift(yy)
                array.shift(zz)
        prevGold := goldD
        prevDollar := dollarD
        prevYield := close
        prevDate := time
    [usdPart[1],yieldPart[1],fit[1],modelDate[1],used[1],modelState[1]]
 
[driverUSD,driverYield,driverFit,driverDate,driverN,driverState] = request.security(realSource,"D",f_macroDrivers(),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=500)
bool driverFresh = not na(driverDate) and not f_macroOld(driverDate)
bool driverReady = driverFresh and driverState=="MODEL READY" and not na(driverUSD) and not na(driverYield)
float driverTotal = math.abs(driverUSD)+math.abs(driverYield)
float usdShare = driverTotal>0 ? 100*math.abs(driverUSD)/driverTotal : na
float driverNet = driverUSD+driverYield
string dominantDriver = not driverFresh ? "MISSING / OLD DATA" : not driverReady ? driverState : na(usdShare) ? "NO FACTOR MOVE" : usdShare>=60 ? "US DOLLAR | "+str.tostring(usdShare,"#")+"% share" : usdShare<=40 ? "REAL YIELD | "+str.tostring(100-usdShare,"#")+"% share" : "SIMILAR CONTRIBUTIONS"
string driverPressure = not driverReady ? "NO RELIABLE MODEL READ" : math.abs(driverNet)<0.01 ? "BALANCED / SMALL" : driverNet>0 ? "BULLISH CONTEXT*" : "BEARISH CONTEXT*"
string driverTip = "Exploratory OLS using prior "+str.tostring(driverN)+" matched intervals. Contribution shares are not probabilities or causal importance. R2 is training fit, not forecast accuracy. Dates are source labels, not verified release times. FRED may be revised. As of "+f_macroDate(driverDate)+". No effect on entries or historical trade tests."
 
// DATED GOLD CONTEXT
gContext = "12 | Gold context — automatic + manual"
gvzSource = input.symbol("CBOE:GVZ","GVZ (GLD proxy, not GC CVOL)",group=gContext)
eventName = input.string("Not set","Next event name (manual)",group=gContext)
eventTime = input.time(0,"Next event time (manual)",group=gContext)
contextDate = input.time(timestamp("28 Oct 2026 18:00 +0000"),"Fed / geopolitical notes checked at",group=gContext)
physicalDate = input.time(timestamp("30 Sep 2026 00:00 +0000"),"Physical demand observation date",group=gContext)
physicalNote = input.string("China Sep: SGE92t; +48% m/m, -22% y/y; WGC15Oct","Physical demand note",group=gContext)
etfReady = input.bool(true,"Use dated ETF report snapshot",group=gContext)
etfTonnes = input.float(67,"ETF net holdings change, tonnes",group=gContext)
etfDate = input.time(timestamp("07 Oct 2026 00:00 +0000"),"ETF publication date",group=gContext)
etfPeriod = input.string("September 2026; WGC 7Oct; holdings 4256t; flows USD10bn","ETF period and source",group=gContext)
cotReady = input.bool(true,"Use dated CFTC snapshot",group=gContext)
cotLong = input.int(122508,"COT Managed Money long (futures only)",minval=0,group=gContext)
cotShort = input.int(16946,"COT Managed Money short (futures only)",minval=0,group=gContext)
cotDate = input.time(timestamp("27 Oct 2026 00:00 +0000"),"COT position date",group=gContext)
cotPublished = input.time(timestamp("30 Oct 2026 19:30 +0000"),"COT publication date",group=gContext)
bankReady = input.bool(true,"Use dated central-bank snapshot",group=gContext)
bankTonnes = input.float(39,"Central-bank net purchases, tonnes",group=gContext)
bankDate = input.time(timestamp("06 Oct 2026 00:00 +0000"),"Central-bank publication date",group=gContext)
bankPeriod = input.string("August 2026 REPORTED net buying; WGC/IMF 6Oct; YTD 170t","Central-bank period and source",group=gContext)
[gvzClose,gvzPrior,gvzDate] = request.security(gvzSource,"D",[close[1],close[2],time[1]],gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=20)
 
f_contextAge(int stamp, int limit) =>
    stamp==0 ? "DATE MISSING" : stamp>timenow ? "FUTURE DATE" : timenow-stamp>limit*86400000 ? "OLD" : "DATED"
 
f_reportValue(bool entered,float value,int stamp,int limit,string unit) =>
    not entered ? "NOT UPDATED" : stamp==0 or stamp>timenow ? f_contextAge(stamp,limit) : (value>0 ? "+" : "")+str.tostring(value,"#.0")+unit+" | "+f_contextAge(stamp,limit)
 
f_contextNote(string note,int stamp) =>
    note=="NOT UPDATED" or str.length(str.trim(note))==0 ? "NOT UPDATED" : stamp==0 or stamp>timenow ? f_contextAge(stamp,7) : f_manual(note)+" | "+f_contextAge(stamp,7)
 
bool useCalendarSnapshot = input.bool(true,"Use Nov 2026 calendar snapshot (not live)",group=gContext)
int effectiveEventTime = eventTime
string effectiveEventName = eventName
if useCalendarSnapshot
    effectiveEventTime := 0
    effectiveEventName := "Calendar snapshot exhausted"
    if effectiveEventTime==0 and timenow<timestamp("02 Nov 2026 10:00 -0500")
        effectiveEventTime := timestamp("02 Nov 2026 10:00 -0500")
        effectiveEventName := "ISM Manufacturing"
    if effectiveEventTime==0 and timenow<timestamp("03 Nov 2026 10:00 -0500")
        effectiveEventTime := timestamp("03 Nov 2026 10:00 -0500")
        effectiveEventName := "JOLTS"
    if effectiveEventTime==0 and timenow<timestamp("04 Nov 2026 10:00 -0500")
        effectiveEventTime := timestamp("04 Nov 2026 10:00 -0500")
        effectiveEventName := "ISM Services"
    if effectiveEventTime==0 and timenow<timestamp("05 Nov 2026 08:30 -0500")
        effectiveEventTime := timestamp("05 Nov 2026 08:30 -0500")
        effectiveEventName := "US Productivity"
    if effectiveEventTime==0 and timenow<timestamp("06 Nov 2026 08:30 -0500")
        effectiveEventTime := timestamp("06 Nov 2026 08:30 -0500")
        effectiveEventName := "US Employment / NFP"
    if effectiveEventTime==0 and timenow<timestamp("10 Nov 2026 08:30 -0500")
        effectiveEventTime := timestamp("10 Nov 2026 08:30 -0500")
        effectiveEventName := "US CPI"
    if effectiveEventTime==0 and timenow<timestamp("13 Nov 2026 08:30 -0500")
        effectiveEventTime := timestamp("13 Nov 2026 08:30 -0500")
        effectiveEventName := "US PPI"
 
float eventMinutes = effectiveEventTime==0 ? na : (effectiveEventTime-timenow)/60000.0
string eventStatus = effectiveEventTime==0 ? (useCalendarSnapshot ? "REFRESH CALENDAR SNAPSHOT" : "CALENDAR NOT SET") : eventMinutes<0 ? "PASSED — UPDATE EVENT" : eventMinutes<=60 ? effectiveEventName+" | "+str.tostring(math.ceil(eventMinutes))+" min" : effectiveEventName+" | "+str.format_time(effectiveEventTime,"dd MMM HH:mm","Europe/Oslo")
bool eventHigh = effectiveEventName == "US Employment / NFP" or effectiveEventName == "US CPI" or str.contains(str.upper(effectiveEventName),"FOMC")
color eventImpactColor = effectiveEventTime <= 0 or eventMinutes < 0 ? muted : eventHigh ? red : amber
string eventTip = "Selected ISM/BLS events through 13 Nov 2026. Not a complete or live calendar. Uses current clock, not replay time. Disable snapshot for manual event. No entry filter."
 
// DASHBOARD
string pos = positionInput == "Top left" ? position.top_left : positionInput == "Bottom left" ? position.bottom_left : positionInput == "Bottom right" ? position.bottom_right : position.top_right
string txtSize = small == "Tiny" ? size.tiny : small == "Normal" ? size.normal : size.small
var table panel = table.new(pos,dashboardView=="Results" ? 4 : dashboardView=="Compare markets" ? 3 : 2,15,bgcolor=bg,frame_color=color.rgb(45,55,69),frame_width=1,force_overlay=true)
 
f_row(int r,string key,string val,color tint,string tip) =>
    color rowBG = r%2==0 ? bg : color.rgb(21,27,36)
    table.cell(panel,0,r,key,text_color=muted,bgcolor=rowBG,text_size=txtSize,text_halign=text.align_left,tooltip=tip)
    table.cell(panel,1,r,val,text_color=tint,bgcolor=rowBG,text_size=txtSize,text_halign=text.align_right,tooltip=tip)
 
if barstate.islast
    if array.size(pool) > 0
        for i = 0 to array.size(pool)-1
            box.set_top(array.get(pool,i),mappingReady ? array.get(rawTops,i)+shift : na)
            box.set_bottom(array.get(pool,i),mappingReady ? array.get(rawBottoms,i)+shift : na)
    for ln in lines
        line.delete(ln)
    for lb in labels
        label.delete(lb)
    array.clear(lines)
    array.clear(labels)
 
    if chart.is_standard and mappingReady and not optionExpired
        f_level(callWall,"CALL OI MAX [SAMPLE]",amber,0,"")
        f_level(putWall,"PUT OI MAX [SAMPLE]",green,1,"")
        if showActivity and array.size(volPrices)>0
            for i=0 to array.size(volPrices)-1
                float p = array.get(volPrices,i)
                string caption = "\nCalls: " + str.tostring(array.get(volCalls,i),"#") + " | Puts: " + str.tostring(array.get(volPuts,i),"#")
                if p != callWall and p != putWall and p != flip
                    f_level(p,"CME VOLUME [HIST]",array.get(volCalls,i)>=array.get(volPuts,i) ? amber : green,i+3,caption)
        if showOI and array.size(oiPrices)>0
            for i=0 to array.size(oiPrices)-1
                string caption = "\nCall OI: " + str.tostring(array.get(oiCalls,i),"#") + " | Put OI: " + str.tostring(array.get(oiPuts,i),"#")
                if array.get(oiPrices,i) != callWall and array.get(oiPrices,i) != putWall
                    f_level(array.get(oiPrices,i),"OI [03 NOV]",purple,i+3+array.size(volPrices),caption)
 
    if chart.is_standard and mappingReady
        if showOpeningRange
            f_level(orHigh,"OPENING HIGH",blue,-1,"")
            f_level(orLow,"OPENING LOW",blue,-1,"")
        if showSetupLevels
            f_level(bTarget,"BREAKOUT TARGET",blue,-1,"")
            f_level(bStop,"BREAKOUT STOP",red,-1,"")
            f_level(cTarget,"CONFIRMED TARGET",green,-1,"")
            f_level(cStop,"CONFIRMED STOP",red,-1,"")
 
    if showPanel and dashboardView=="Trading"
        bool ready = feedOK and not na(gPressure)
        string regime = not ready ? "GC data unavailable" : bull>=3 and bull>bear ? "BULLISH" : bear>=3 and bear>bull ? "BEARISH" : "MIXED"
        color tint = regime=="BULLISH" ? green : regime=="BEARISH" ? red : muted
        string score = ready ? " | " + str.tostring(math.max(bull,bear)*20) + "% aligned" : ""
        string phase = not showAMD ? "Off" : not amdOK ? "Use chart below " + amdMode : not na(dt) ? direction==1 ? "Distribution UP" : direction==-1 ? "Distribution DOWN" : "Distribution waiting" : not na(mt) ? "Sweep confirmed" : not na(at) ? "Range / waiting" : "Waiting for GC range"
        string studyTip = studyDetails + "\nHistorical model, not verified fills or predictive probabilities. Pending cases excluded."
        f_row(0,isXau ? "XAU / GC SCALP" : "GC SCALP",sessionText,white,"GC source. Tokyo, London and New York session anchors.")
        f_row(1,"Market",regime+score,tint,"Five-check alignment score, not win probability.")
        f_row(2,"Breakout",bStatus,not na(bTarget) ? blue : muted,studyTip)
        f_row(3,"Confirmed entry",cStatus,not na(cTarget) ? green : muted,studyTip)
        f_row(4,"Target / stop",not na(cTarget) ? "C "+f_price(cTarget+shift)+" / "+f_price(cStop+shift) : not na(bTarget) ? "B "+f_price(bTarget+shift)+" / "+f_price(bStop+shift) : "No active setup",white,"Frozen modeled levels. C = MR3; B = separate breakout.")
        f_row(5,"Asia hits",statsAsia,muted,studyTip)
        f_row(6,"London hits",statsLondon,muted,studyTip)
        f_row(7,"New York hits",statsNY,muted,studyTip)
        f_row(8,"CVD / volume",(na(divAge) ? "No divergence" : (divBull ? "Bull" : "Bear")+" "+str.tostring(divAge)+" bars"+(divAge>freshBars ? " old" : " fresh"))+" | "+str.tostring(gRvol,"#.0")+"x",muted,"OHLCV proxy; not aggressor order flow.")
        f_row(9,"Call / Put OI sample",optionExpired ? "HIDDEN" : not mappingReady ? "BASIS MISSING" : f_price(callWall+shift)+" / "+f_price(putWall+shift),white,"Maxima among selected strikes only. "+sourceDate)
        f_row(10,"Gamma / flip [sample]",gamma,optionExpired or gammaScenario == "Off" ? muted : purple,gammaTip)
        f_row(11,"AMD / "+amdMode,phase,direction==1 ? green : direction==-1 ? amber : blue,"Price-pattern labels; not proof of participant manipulation.")
        f_row(12,"GC → XAU",na(activeBasis) ? "REFERENCE MISSING" : (activeBasis>0 ? "+" : "")+str.tostring(activeBasis,"#.00")+" | LOCKED",na(activeBasis) ? amber : green,"Fixed reference offset. Reference: "+(na(lockedTime) ? "Manual / unavailable" : str.format_time(lockedTime,"dd MMM HH:mm","Europe/Oslo")))
        f_row(13,"Options snapshot",optionStatus,amber,sourceDate+". Refresh before actual expiry. Date guard is not exact expiry time.")
        f_row(14,"MR volatility",na(volRatio) ? "WARMING UP" : (volAligned ? "ATR FILTER PASS" : "ATR FILTER FAIL")+" | "+str.tostring(volRatio,"#.00")+"x ATR",volAligned ? green : muted,"Only one entry requirement; not reversal probability.")
    else
        table.clear(panel,0,0,dashboardView=="Results" ? 3 : dashboardView=="Compare markets" ? 2 : 1,14)
 
// ALERTS AND DATA WINDOW
bool newBreakout = not na(bSignal) and (na(bSignal[1]) or bSignal!=bSignal[1])
bool newReversal = not na(rSignal) and (na(rSignal[1]) or rSignal!=rSignal[1])
alertcondition(newBreakout and chart.is_standard and mappingReady,"Breakout setup","Closed-source-bar breakout. Inspect target, stop and timestamp.")
alertcondition(newReversal and chart.is_standard and mappingReady,"Legacy VWAP reversal (comparison)","Closed-source-bar legacy reversal. Inspect target and stop.")
plot(bSignal,"Breakout event close time",display=display.data_window)
plot(rSignal,"Legacy reversal event close time",display=display.data_window)
plot(bOutcome,"Breakout status: 1 active 2 target 3 stop 4 expired",display=display.data_window)
plot(rOutcome,"Legacy status: 1 active 2 target 3 stop 4 expired",display=display.data_window)
plot(bEntry,"Breakout entry source price",display=display.data_window)
plot(rEntry,"Legacy entry source price",display=display.data_window)
plot(bEventTarget,"Breakout frozen target",display=display.data_window)
plot(rEventTarget,"Legacy frozen target",display=display.data_window)
plot(bEventStop,"Breakout frozen stop",display=display.data_window)
plot(rEventStop,"Legacy frozen stop",display=display.data_window)
plot(bAdverse,"Breakout adverse upper bound R",display=display.data_window)
plot(rAdverse,"Legacy adverse upper bound R",display=display.data_window)
plot(bResult,"Breakout last settled net R",display=display.data_window)
plot(rResult,"Legacy last settled net R",display=display.data_window)
 
plot(showVWAP and chart.is_standard and mappingReady and not vwapReset ? gVWAP+shift : na,"Session VWAP (GC source)",color=vwapColor,linewidth=2,style=plot.style_linebr,force_overlay=true)
bool newConfirmed = not na(cSignal) and (na(cSignal[1]) or cSignal!=cSignal[1])
bool filteredMR = newConfirmed and chart.is_standard and mappingReady and not staleFeed
bool mrLong = filteredMR and cEventTarget>cEntry
bool mrShort = filteredMR and cEventTarget<cEntry
plotshape(showMRSignals and mrLong,title="Confirmed swing long",style=shape.triangleup,location=location.belowbar,color=green,text="MR3",textcolor=green,size=size.tiny,force_overlay=true)
plotshape(showMRSignals and mrShort,title="Confirmed swing short",style=shape.triangledown,location=location.abovebar,color=amber,text="MR3",textcolor=amber,size=size.tiny,force_overlay=true)
alertcondition(mrLong,"Confirmed MR long","Confirmed GC swing-low, EMA, ATR and minimum net reward/risk setup.")
alertcondition(mrShort,"Confirmed MR short","Confirmed GC swing-high, EMA, ATR and minimum net reward/risk setup.")
plot(rVolAligned ? 1 : 0,"Legacy volatility aligned 1/0",display=display.data_window)
plot(volRatio,"GC ATR / 50-bar average",display=display.data_window)
plot(cSignal,"Confirmed MR event close time",display=display.data_window)
plot(cOutcome,"MR status: 1 active 2 target 3 stop 4 expired",display=display.data_window)
plot(cEntry,"Confirmed MR entry source price",display=display.data_window)
plot(cEventTarget,"Confirmed MR frozen target",display=display.data_window)
plot(cEventStop,"Confirmed MR frozen stop",display=display.data_window)
plot(cResult,"Confirmed MR settled net R",display=display.data_window)
plot(cAdverse,"Confirmed MR adverse upper bound R",display=display.data_window)
 
// RESULTS VIEW
if barstate.islast and showPanel and dashboardView=="Results"
    string tip = "Independent observational tests, not broker fills or a portfolio. Entry bar excluded. Stop first on ties, adverse stop gaps filled at open. Costs deducted. No predictive guarantee."
    string[] titles = array.from("RESULTS / "+auditSession,"Old entry","MR3","Breakout")
    for col=0 to 3
        table.cell(panel,col,0,array.get(titles,col),bgcolor=bg,text_color=white,text_size=txtSize,tooltip=tip)
    string[] keys = array.from("Closed cases","Target first","Stop first","Time limit","Net winners","Mean net R","Total net R","Profit factor","Time-limit mean","Pending")
    for row=1 to 10
        table.cell(panel,0,row,array.get(keys,row-1),text_color=muted,text_size=txtSize,bgcolor=bg,tooltip=tip)
    for col=1 to 3
        string packed = col==1 ? auditL : col==2 ? auditC : auditB
        string[] vals = str.split(na(packed) ? "" : packed,";")
        for row=1 to 10
            string val = array.size(vals)>row-1 ? array.get(vals,row-1) : "N/A"
            table.cell(panel,col,row,val,text_color=white,text_size=txtSize,bgcolor=row%2==0 ? bg : color.rgb(21,27,36),tooltip=tip)
    table.cell(panel,0,11,"Cost / event",text_color=muted,text_size=txtSize)
    table.cell(panel,1,11,str.tostring(studyCost)+" GC ticks",text_color=white,text_size=txtSize)
    table.cell(panel,2,11,"Horizon",text_color=muted,text_size=txtSize)
    table.cell(panel,3,11,str.tostring(testBars)+" bars",text_color=white,text_size=txtSize)
    table.cell(panel,0,12,"Loaded from",text_color=muted,text_size=txtSize)
    table.cell(panel,1,12,na(historyStart) ? "N/A" : str.format_time(historyStart,"dd MMM HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,2,12,"Count from",text_color=muted,text_size=txtSize)
    table.cell(panel,3,12,str.format_time(studyFrom,"dd MMM yy","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,0,13,"Source",text_color=muted,text_size=txtSize)
    table.cell(panel,1,13,staleFeed ? "STALE GC" : feedOK ? "CLOSED GC" : "NO DATA",text_color=staleFeed or not feedOK ? amber : muted,text_size=txtSize)
    table.cell(panel,2,13,"Last bar Oslo",text_color=muted,text_size=txtSize)
    table.cell(panel,3,13,na(gt) ? "N/A" : str.format_time(gt,"dd MMM HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,0,14,"Interpretation",text_color=muted,text_size=txtSize)
    table.cell(panel,1,14,"Historical",text_color=amber,text_size=txtSize)
    table.cell(panel,2,14,"Not validated",text_color=amber,text_size=txtSize)
    table.cell(panel,3,14,"No forecast",text_color=amber,text_size=txtSize)
 
// MACRO VIEW
if barstate.islast and showPanel and dashboardView=="Macro"
    string slowTip = "Daily context only. Source dates are not verified publication times. Data may be delayed or revised. No effect on entries or historical tests."
    string notesTip = "Manual note. Source/as-of: "+macroNoteDate
    f_row(0,"GOLD MACRO","CONTEXT ONLY",white,slowTip)
    f_row(1,"US dollar / daily",usdAvailable ? str.tostring(usdClose,"#.00")+" | "+f_change(usdClose,usdPrior)+(f_macroOld(usdStamp) ? " OLD" : "") : "FEED UNAVAILABLE",muted,usdSource+" "+f_macroDate(usdStamp)+". "+slowTip)
    f_row(2,"10Y real yield",realAvailable ? str.tostring(realClose,"#.00")+"% | "+str.tostring(yieldBp,"#.0")+" bp"+(f_macroOld(realStamp) ? " OLD" : "") : "FEED UNAVAILABLE",muted,realSource+" "+f_macroDate(realStamp)+". "+slowTip)
    f_row(3,"USD / rates",opportunity,muted,slowTip)
    f_row(4,"Gold / silver",na(goldSilver) ? "FEEDS NOT ALIGNED" : str.tostring(goldSilver,"#.00")+(f_macroOld(macroGoldStamp) ? " OLD" : ""),muted,"GC1/SI1 ratio. Futures rolls and basis affect the ratio.")
    f_row(5,"GC daily change",not na(macroGoldPrior) and macroGoldPrior>0 ? str.tostring(100*(macroGold/macroGoldPrior-1),"#.00")+"%" : "UNAVAILABLE",muted,slowTip)
    f_row(6,"CPI / Fed [manual]",f_manual(inflationNote),amber,notesTip+". "+inflationNote)
    f_row(7,"Event risk [manual]",f_manual(riskNote),amber,notesTip+". "+riskNote)
    f_row(8,"COT [manual]",f_manual(cotNote),amber,notesTip+". "+cotNote)
    f_row(9,"ETF flows [manual]",f_manual(etfNote),amber,notesTip+". "+etfNote)
    f_row(10,"Central banks [manual]",f_manual(bankNote),amber,notesTip+". "+bankNote)
    f_row(11,"Seasonality [manual]",f_manual(seasonNote),amber,notesTip+". "+seasonNote)
    f_row(12,"Manual as-of",f_manual(macroNoteDate),muted,notesTip)
    f_row(13,"GRAM","NOT REPLICATED",muted,"This indicator does not reproduce WGC GRAM.")
    f_row(14,"Entry / statistics","UNCHANGED",white,"Macro context does not change the entry model.")
 
// MAIN OVERVIEW
if barstate.islast and showPanel and dashboardView=="Overview"
    string macroTip = "Last completed daily observations. USD "+f_macroDate(usdStamp)+", real yield "+f_macroDate(realStamp)+", silver "+f_macroDate(macroSilverStamp)+". Context, not entry signals."
    bool dollarsOK = usdAvailable and not f_macroOld(usdStamp)
    bool yieldsOK = realAvailable and not f_macroOld(realStamp)
    bool silverOK = not na(macroSilverPrior) and macroSilverPrior>0 and not f_macroOld(macroSilverStamp)
    string usdHelp = not dollarsOK ? "MISSING / OLD" : usdClose<usdPrior ? "DOWN | gold tailwind*" : usdClose>usdPrior ? "UP | gold headwind*" : "FLAT"
    string yieldHelp = not yieldsOK ? "MISSING / OLD" : realClose<realPrior ? "DOWN | gold tailwind*" : realClose>realPrior ? "UP | gold headwind*" : "FLAT"
    string entry = not feedOK or staleFeed ? "GC FEED UNAVAILABLE / OLD" : cOutcome==1 ? "ACTIVE | "+cStatus : "WAIT | no active MR3"
    f_row(0,"AURUM EVIDENCE SNIPER",sessionText,white,"GC signals with optional fixed XAU translation.")
    f_row(1,"Entry / GC model",entry,cOutcome==1 ? green : muted,"Historical completed signal. Confirm actual execution conditions separately.")
    f_row(2,"Target / stop",cOutcome==1 ? f_price(cTarget+shift)+" / "+f_price(cStop+shift) : "—",white,"Frozen modeled GC levels, with fixed XAU offset when enabled.")
    f_row(3,"US dollar",usdHelp,muted,macroTip)
    f_row(4,"Real yield",yieldHelp,muted,macroTip+" Value "+str.tostring(realClose,"#.00")+"%; change "+str.tostring(yieldBp,"#.0")+" bp.")
    f_row(5,"Silver",silverOK ? f_change(macroSilver,macroSilverPrior)+" | "+str.tostring(100*(macroSilver/macroSilverPrior-1),"#.00")+"%" : "MISSING / OLD",muted,macroTip)
    f_row(6,"Next News",eventStatus,eventImpactColor,eventTip)
    f_row(7,"Largest modeled driver",dominantDriver,muted,driverTip)
    f_row(8,"Price volatility",volAligned ? "ATR CHECK PASSES" : "ATR CHECK FAILS",muted,"ATR condition alone is not an entry.")
    f_row(9,"AMD / "+amdMode,direction==1 ? "UP DISTRIBUTION" : direction==-1 ? "DOWN DISTRIBUTION" : not na(mt) ? "SWEEP / WAIT" : "PRIOR RANGE / WAIT",blue,"Heuristic price-pattern labels.")
    f_row(10,"Call / Put OI sample",optionExpired ? "HIDDEN" : not mappingReady ? "BASIS MISSING" : f_price(callWall+shift)+" / "+f_price(putWall+shift),white,"Maxima among selected strikes only. "+sourceDate)
    f_row(11,"Gamma / flip [sample]",gamma,optionExpired or gammaScenario == "Off" ? muted : purple,gammaTip)
    f_row(12,"Gold macro pressure",driverPressure,driverReady ? driverNet>0 ? green : amber : muted,driverTip)
    f_row(13,"Model evidence",na(driverFit) ? "Need "+str.tostring(macroWindow)+" matched intervals" : "R2 "+str.tostring(100*driverFit,"#")+"% | "+str.tostring(driverN)+" samples",muted,driverTip)
    f_row(14,"Options snapshot",optionStatus,amber,sourceDate+". Not live. Refresh before actual expiry.")
 
// NATIVE GC / XAU COMPARISON
if barstate.islast and showPanel and dashboardView=="Compare markets"
    string[] labelsAudit = array.from("Closed cases","Target first","Stop first","Time limit","Net winners","Mean net R","Total net R","Profit factor","Time-limit mean","Pending")
    string gPack = compareSetup=="MR3" ? auditC : compareSetup=="Old entry" ? auditL : auditB
    string xPack = compareSetup=="MR3" ? xAuditC : compareSetup=="Old entry" ? xAuditL : xAuditB
    string compareTip = "Each source uses its own OHLCV and entry calculations. XAU volume may be tick volume. History and costs can differ. These are modeled outcomes, not broker fills."
    table.cell(panel,0,0,"AES / "+compareSetup+" / "+auditSession,text_color=white,text_size=txtSize,tooltip=compareTip)
    table.cell(panel,1,0,"GC1! native",text_color=white,text_size=txtSize,tooltip=gcSource)
    table.cell(panel,2,0,"XAU native",text_color=white,text_size=txtSize,tooltip=xauSource)
    for row=1 to 10
        table.cell(panel,0,row,array.get(labelsAudit,row-1),text_color=muted,text_size=txtSize,tooltip=compareTip)
    for col=1 to 2
        string[] parts = str.split(na(col==1 ? gPack : xPack) ? "" : col==1 ? gPack : xPack,";")
        for row=1 to 10
            table.cell(panel,col,row,array.size(parts)>row-1 ? array.get(parts,row-1) : "UNAVAILABLE",text_color=white,text_size=txtSize,bgcolor=row%2==0 ? bg : color.rgb(21,27,36),tooltip=compareTip)
    table.cell(panel,0,11,"Actual first bar",text_color=muted,text_size=txtSize)
    table.cell(panel,1,11,na(historyStart) ? "N/A" : str.format_time(historyStart,"dd MMM yy HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,2,11,na(xHistoryStart) ? "N/A" : str.format_time(xHistoryStart,"dd MMM yy HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,0,12,"Last closed bar",text_color=muted,text_size=txtSize)
    table.cell(panel,1,12,na(gt) ? "N/A" : str.format_time(gt,"dd MMM yy HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,2,12,na(xLastTime) ? "N/A" : str.format_time(xLastTime,"dd MMM yy HH:mm","Europe/Oslo"),text_color=white,text_size=txtSize)
    table.cell(panel,0,13,"Processed bars",text_color=muted,text_size=txtSize,tooltip="Includes warmup. Requested maximum "+str.tostring(historyBars)+".")
    table.cell(panel,1,13,str.tostring(loadedBars),text_color=white,text_size=txtSize)
    table.cell(panel,2,13,str.tostring(xLoadedBars),text_color=white,text_size=txtSize)
    table.cell(panel,0,14,"Cost per event",text_color=muted,text_size=txtSize)
    table.cell(panel,1,14,str.tostring(studyCost)+" GC ticks",text_color=white,text_size=txtSize)
    table.cell(panel,2,14,str.tostring(xauCostPrice,"#.00")+" USD price",text_color=white,text_size=txtSize)
 
// DAILY UNFILLED PRICE-GAP ZONES
gDaily = "13 | Daily imbalance zones"
dzDirection = input.string("Upward moves only", "Zone origin", options=["Upward moves only", "Downward moves only", "Both"], group=gDaily)
dzFrom = input.time(timestamp("01 Jan 2025 00:00 +0000"), "Include zones confirmed from", group=gDaily)
dzShow = input.bool(true, "Show daily zones", group=gDaily)
dzDrawLimit = input.int(200, "Maximum visible open zones (oldest first)", minval=20, maxval=400, group=gDaily)
dzDays = input.int(800, "Requested daily bars", minval=100, maxval=2000, group=gDaily)
dzAlpha = input.int(82, "Zone transparency", minval=70, maxval=98, group=gDaily)
dzMove = input.float(0.0, "Minimum displacement body / prior ATR14", minval=0, step=0.1, group=gDaily)
 
f_dailyZones() =>
    var float[] tops = array.new_float()
    var float[] bottoms = array.new_float()
    var float[] fills = array.new_float()
    var int[] sides = array.new_int()
    var int[] starts = array.new_int()
    var string[] notes = array.new_string()
    var int firstDaily = time
    float atrDaily = ta.atr(14)
    if array.size(tops)>0
        for i=array.size(tops)-1 to 0
            float hi = array.get(tops,i)
            float lo = array.get(bottoms,i)
            float fraction = array.get(sides,i)==1 ? (hi-low)/(hi-lo) : (high-lo)/(hi-lo)
            array.set(fills,i,math.max(array.get(fills,i),math.max(0.0,math.min(100.0,100*fraction))))
            if array.get(fills,i)>=100
                array.remove(tops,i)
                array.remove(bottoms,i)
                array.remove(fills,i)
                array.remove(sides,i)
                array.remove(starts,i)
                array.remove(notes,i)
    float newTop = na
    float newBottom = na
    int newSide = 0
    string note = ""
    string feedState = "OHLC PRICE PROXY"
    bool upGap = low>high[2] and close[1]>open[1] and math.abs(close[1]-open[1])>=atrDaily[2]*dzMove
    bool downGap = high<low[2] and close[1]<open[1] and math.abs(close[1]-open[1])>=atrDaily[2]*dzMove
    if upGap or downGap
        newTop := upGap ? low : low[2]
        newBottom := upGap ? high[2] : high
        newSide := upGap ? 1 : -1
        note := "PRICE GAP PROXY"
    bool directionOK = dzDirection=="Both" or dzDirection=="Upward moves only" and newSide==1 or dzDirection=="Downward moves only" and newSide==-1
    if not na(newTop) and newTop>newBottom and directionOK and time_close>=dzFrom
        array.push(tops,newTop)
        array.push(bottoms,newBottom)
        array.push(fills,0.0)
        array.push(sides,newSide)
        array.push(starts,time_close)
        array.push(notes,note)
    string packed = ""
    if bar_index>=last_bar_index-2 and array.size(tops)>0
        for i=0 to array.size(tops)-1
            packed += str.tostring(array.get(starts,i))+","+str.tostring(array.get(tops,i))+","+str.tostring(array.get(bottoms,i))+","+str.tostring(array.get(sides,i))+","+str.tostring(array.get(fills,i))+","+array.get(notes,i)+";"
    [packed[1],time_close[1],feedState[1],firstDaily[1]]
 
[dzPack,dzAsOf,dzFeed,dzFirstDaily] = request.security(gcSource,"D",f_dailyZones(),gaps=barmerge.gaps_off,lookahead=barmerge.lookahead_on,ignore_invalid_symbol=true,calc_bars_count=dzDays)
var box[] dzBoxes = array.new_box()
var table dzStatus = table.new(position.bottom_left,1,2,bgcolor=color.new(color.black,25),force_overlay=true)
 
if barstate.islast
    while array.size(dzBoxes)>0
        box.delete(array.pop(dzBoxes))
    table.clear(dzStatus,0,0,0,1)
    int shown = 0
    int retained = 0
    float nearestDistance = na
    string nearestInfo = ""
    if dzShow and chart.is_standard and mappingReady and not na(dzPack)
        for item in str.split(dzPack,";")
            string[] fields = str.split(item,",")
            if array.size(fields)==6
                int born = int(str.tonumber(array.get(fields,0)))
                float hi = str.tonumber(array.get(fields,1))+shift
                float lo = str.tonumber(array.get(fields,2))+shift
                int side = int(str.tonumber(array.get(fields,3)))
                float filled = str.tonumber(array.get(fields,4))
                retained += 1
                if filled<100 and shown<dzDrawLimit
                    color tint = side==1 ? color.aqua : color.orange
                    float distance = close>hi ? close-hi : close<lo ? lo-close : 0
                    if na(nearestDistance) or distance<nearestDistance
                        nearestDistance := distance
                        nearestInfo := "Nearest zone: "+str.tostring(lo,"#.00")+" - "+str.tostring(hi,"#.00")+" | "+str.tostring(filled,"#.0")+"% revisited"
                    string caption = "D FVG PROXY | "+(side==1 ? "UP" : "DOWN")+"\n"+str.tostring(filled,"#.0")+"% revisited | "+str.tostring(100-filled,"#.0")+"% remaining\n"+array.get(fields,5)+" | confirmed "+str.format_time(born,"dd MMM yy","Europe/Oslo")
                    array.push(dzBoxes,box.new(left=born,top=hi,right=time_close,bottom=lo,xloc=xloc.bar_time,extend=extend.right,bgcolor=color.new(tint,dzAlpha),border_color=color.new(tint,20),border_width=2,text=caption,text_color=tint,text_size=size.small,text_halign=text.align_right,text_valign=text.align_center,force_overlay=true))
                    shown += 1
    if dzShow
        string msg = not mappingReady ? "DAILY ZONES | XAU BASIS MISSING" : na(dzAsOf) ? "DAILY ZONES | SOURCE UNAVAILABLE" : "D FVG PROXY | "+str.tostring(shown)+" shown / "+str.tostring(retained)+" OPEN | "+dzFeed+" | closed D "+str.format_time(dzAsOf,"dd MMM","Europe/Oslo")
        string coverage = na(dzFirstDaily) ? "History unavailable" : "Daily history: "+str.format_time(dzFirstDaily,"dd MMM yyyy","Europe/Oslo")+(dzFirstDaily>dzFrom ? " | INCOMPLETE for selected start" : "")
        string reason = not chart.is_standard ? "Use standard candles" : retained==0 ? "No open qualifying zones in loaded history | "+coverage : nearestInfo+" | "+coverage+(shown<retained ? " | DISPLAY LIMIT: increase Maximum visible open zones" : "")
        table.cell(dzStatus,0,1,reason,text_color=shown==0 ? color.orange : color.white,text_size=size.small)
        table.cell(dzStatus,0,0,msg,text_color=color.silver,text_size=size.tiny,tooltip="GC daily OHLC price-gap proxy. Percentages measure maximum price penetration, not traded volume or unfilled orders. Updates after completed daily bars. Fully crossed zones removed. Price gaps and continuous-futures rolls can affect results.")
 
// GOLD CONTEXT VIEW
if barstate.islast and showPanel and dashboardView=="Gold context"
    string contextTip = "Context only. Automatic feeds are completed daily readings. Manual snapshots are not live. Observation period and publication date differ. No historical entry filter."
    f_row(0,"AURUM / GOLD CONTEXT","AUTO + MANUAL",white,contextTip)
    f_row(1,"Next News",eventStatus,eventImpactColor,eventTip)
    f_row(2,"Fed / inflation [M]",f_contextNote(inflationNote,contextDate),muted,contextTip)
    f_row(3,"Dollar / real yield",opportunity,muted,contextTip)
    f_row(4,"Largest modeled driver",dominantDriver,muted,driverTip)
    f_row(5,"Gold macro pressure",driverPressure,muted,driverTip)
    f_row(6,"GVZ / GLD proxy",na(gvzClose) or na(gvzPrior) ? "FEED UNAVAILABLE" : str.tostring(gvzClose,"#.00")+" | "+f_change(gvzClose,gvzPrior)+" | "+f_contextAge(gvzDate,5),muted,"GLD implied volatility, not GC CVOL. "+gvzSource+" "+f_macroDate(gvzDate))
    f_row(7,"ETF holdings change [M]",f_reportValue(etfReady,etfTonnes,etfDate,45,"t"),muted,etfPeriod+". Published "+f_macroDate(etfDate)+". "+contextTip)
    string cotStatus = not cotReady ? "NOT UPDATED" : cotDate==0 or cotPublished==0 ? "DATES MISSING" : cotDate>cotPublished or cotPublished>timenow ? "CHECK DATES" : str.tostring(cotLong-cotShort)+" net | "+f_contextAge(cotDate,10)
    f_row(8,"COT Managed Money [M]",cotStatus,muted,"Futures-only long minus short. Position "+f_macroDate(cotDate)+"; published "+f_macroDate(cotPublished)+". Not an extreme-position signal.")
    f_row(9,"Central banks [M]",f_reportValue(bankReady,bankTonnes,bankDate,120,"t"),muted,bankPeriod+". Published "+f_macroDate(bankDate)+". "+contextTip)
    f_row(10,"Physical demand [M]",f_contextNote(physicalNote,physicalDate),muted,contextTip)
    f_row(11,"Geopolitical risk [M]",f_contextNote(riskNote,contextDate),muted,contextTip)
    f_row(12,"GC momentum",not na(macroGoldPrior) and macroGoldPrior>0 ? str.tostring(100*(macroGold/macroGoldPrior-1),"#.00")+"% last daily" : "UNAVAILABLE",muted,"Source "+f_macroDate(macroGoldStamp)+". Futures rolls can affect returns.")
    f_row(13,"Notes checked",contextDate==0 ? "NOT SET" : f_macroDate(contextDate)+" | "+f_contextAge(contextDate,7),muted,"Review date for manual notes.")
    f_row(14,"[M] = manual","Settings → Gold context",white,"Missing data does not mean neutral conditions.")

← 返回列表