EVM Confluence Signals v1.0

NotLazyBear · study · 1165 行 · 点赞 43 · 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/
// © NotLazyBear
 
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NotLazyBear
 
//@version=6
indicator("EVM Confluence Signals v1.0", "EVM", overlay = true, max_bars_back = 2000, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 20)
 
// ═════════════════════════════════════════════════════════════════════════════
// EVM = Exhaustion × Volume × Magnets
// Merges Exhaustion Research Engine v3 (ERE), Volume Turning Point Engine v1.0
// (VTPE) and Magnet Levels v2.1 into one causal BUY / SELL process.
//
// 1 CONTEXT    A move must exist to reverse: prior-bar extension from the trend
//              EMA plus directional efficiency (ERE), remembered for a few bars.
// 2 EVIDENCE   Six bounded factors (0-1), one per distinct family, so no idea
//              is counted twice:
//                Momentum decay ...... ERE deceleration + efficiency loss
//                Rejection / climax .. wick rejection at a range extreme,
//                                      amplified by a volume shock or dry-up (VTPE)
//                Absorption .......... effort vs. result, four horizons (VTPE)
//                Flow divergence ..... delta / CLV / OBV flow vs. location (VTPE)
//                Volume exhaustion ... weak effort on a retest (VTPE)
//                Magnet location ..... price just revisited a high-volume node
//              A volume-backed, efficient trend subtracts points (VTPE health veto).
// 3 CALIBRATE  The composite is ranked against PRIOR eligible bars of the same
//              side (ERE). The current bar never ranks itself.
// 4 SETUP      Percentile + minimum score + agreeing factors + price-and-volume
//              cross-check. The move's extreme must be at most a few bars old,
//              so pullbacks inside a trend are not called tops or bottoms.
// 5 TRIGGER    A LATER close beyond the setup bar's extreme with supportive
//              pressure, micro-horizon flow and relative volume (VTPE). A small
//              undercut of the setup extreme is tolerated; a deeper one fails it.
//              The next magnet in the trade's direction is the target. If it
//              leaves too little reward for the structural stop, the signal is
//              blocked (Magnet Levels).
// 6 TRACK      Every signal is followed to target, stop, time exit, or opposite
//              signal. Results are IN-SAMPLE on the loaded chart.
//
// CHANGES FROM THE SOURCE SCRIPTS
//  · VTPE absorption treated any efficiency below 1.0 as "failure to progress",
//    so it fired through ordinary trends. Failure now means LOW efficiency.
//  · VTPE's VWAP-failure family is dropped: it was the other families times
//    stretch, so it double-counted them.
//  · A rejection bar only counts with an anomaly: volume shock, climax or
//    dry-up (VTPE bar model), or a wide range when volume is unavailable.
//  · ERE's late structure confirmation is replaced by VTPE's earlier,
//    volume-backed trigger. A small undercut no longer kills a setup.
//
// Scores are evidence indices, NOT probabilities. Pressure and flow are OHLCV
// estimates, NOT order-flow data. Without volume the engine falls back to price
// factors and a time-at-price profile, and the dashboard says so.
// Experimental: logic exercised on synthetic data only, not validated on market
// data. Native TradingView compilation unverified.
// ═════════════════════════════════════════════════════════════════════════════
 
// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────
 
const string G1 = "1 · Signals"
string sensitivity = input.string("Balanced", "Sensitivity", options = ["Conservative", "Balanced", "Aggressive", "Custom"], group = G1, tooltip = "Conservative: 85th percentile, score 22, 3 factors. Balanced: 80th, 15, 2. Aggressive: 70th, 10, 2. Choose Custom to use the three 'Custom ·' values below.")
string sideMode = input.string("Long & short", "Trade mode", options = ["Long & short", "Long only", "Short only"], group = G1, tooltip = "Long only: BUY opens a long and SELL only closes it. Short only: the reverse. Both signal types are always drawn.")
float customRank = input.float(80.0, "Custom · setup percentile", minval = 50, maxval = 99, step = 1, group = G1, tooltip = "Composite evidence must rank at or above this percentile among PRIOR bars of the same side that had the same trend context.")
float customScore = input.float(15.0, "Custom · minimum composite score", minval = 0, maxval = 100, step = 1, group = G1, tooltip = "The composite averages six factors, so two strong factors score roughly 15-20.")
int customFactors = input.int(2, "Custom · minimum agreeing factors (of 6)", minval = 1, maxval = 6, group = G1)
float resetRank = input.float(60.0, "Re-arm below percentile", minval = 1, maxval = 95, step = 1, group = G1, tooltip = "After a setup, that side can set up again only once its evidence falls below this percentile or its trend context ends.")
float factorOn = input.float(0.30, "A factor agrees at", minval = 0.05, maxval = 0.95, step = 0.05, group = G1)
bool crossCheck = input.bool(true, "Require price AND volume agreement", group = G1, tooltip = "With volume: a volume-qualified rejection bar, OR momentum decay plus absorption, flow divergence or volume exhaustion. Without volume: momentum decay AND a wide-range rejection bar.")
int triggerBars = input.int(6, "Bars allowed for the trigger", minval = 1, maxval = 30, group = G1)
float triggerATR = input.float(0.05, "Trigger buffer (ATR)", minval = 0, maxval = 2, step = 0.05, group = G1)
float invalidATR = input.float(0.50, "Tolerated undercut of setup extreme (ATR)", minval = 0, maxval = 3, step = 0.05, group = G1)
bool volTrigger = input.bool(true, "Trigger needs pressure and volume support", group = G1)
float confirmRV = input.float(0.85, "Trigger minimum relative volume", minval = 0, maxval = 3, step = 0.05, group = G1)
float confirmPres = input.float(0.10, "Trigger minimum directional pressure", minval = 0, maxval = 0.8, step = 0.05, group = G1)
int cooldown = input.int(5, "Bars between same-side signals", minval = 0, maxval = 100, group = G1)
 
const string G2 = "2 · Trend context (Exhaustion)"
int emaLen = input.int(34, "Trend EMA", minval = 10, maxval = 200, group = G2)
int atrLen = input.int(14, "ATR length", minval = 2, maxval = 100, group = G2)
int fastLen = input.int(5, "Fast window", minval = 2, maxval = 50, group = G2)
int trendLen = input.int(20, "Trend efficiency window", minval = 5, maxval = 200, group = G2)
float minExt = input.float(0.75, "Minimum prior extension (ATR)", minval = 0.1, step = 0.05, group = G2)
float minEff = input.float(0.15, "Minimum prior directional efficiency", minval = 0.01, maxval = 1, step = 0.05, group = G2)
int ctxMemory = input.int(3, "Context memory (bars)", minval = 1, maxval = 10, group = G2, tooltip = "Trend context stays valid this many bars, so evidence that appears just after the peak still qualifies. The move's high (or low) over the small horizon must also be at most this many bars old.")
 
const string G3 = "3 · Volume engine"
bool useVolume = input.bool(true, "Use volume when available", group = G3)
int baseLen = input.int(100, "Volume baseline bars", minval = 20, maxval = 500, group = G3)
string pressureMode = input.string("Chart-bar estimate", "Directional volume source", options = ["Chart-bar estimate", "Lower-timeframe estimate"], group = G3)
string lowerTF = input.timeframe("1", "Lower timeframe (below chart)", group = G3, tooltip = "Lower-timeframe mode only. A bar whose intrabar volume covers under 80% or over 120% of the chart bar's volume counts as invalid data.")
bool seasonal = input.bool(false, "Normalize relative volume by time of day", group = G3)
int seasonSamples = input.int(20, "Time-of-day EMA length", minval = 5, maxval = 100, group = G3)
int n1 = input.int(5, "Micro horizon", minval = 2, maxval = 50, group = G3)
int n2 = input.int(20, "Small horizon", minval = 5, maxval = 150, group = G3)
int n3 = input.int(60, "Large horizon", minval = 10, maxval = 350, group = G3)
int n4 = input.int(180, "Major horizon", minval = 20, maxval = 600, group = G3)
 
const string G4 = "4 · Magnet levels"
int fastProf = input.int(60, "Recent profile bars", minval = 20, maxval = 1000, group = G4)
int slowProf = input.int(240, "Context profile bars", minval = 80, maxval = 1000, group = G4)
int rows = input.int(64, "Profile resolution", minval = 32, maxval = 200, group = G4)
int refresh = input.int(5, "Rebuild every N closes", minval = 1, maxval = 50, group = G4)
int nodeConfirms = input.int(2, "Consecutive profile appearances", minval = 2, maxval = 52, group = G4)
float qualityFloor = input.float(40.0, "Minimum node quality", minval = 10, maxval = 100, group = G4)
float minGap = input.float(0.75, "Minimum gap to zone (ATR)", minval = 0.25, maxval = 3, group = G4)
float maxGap = input.float(8.0, "Maximum target distance (ATR)", minval = 2, maxval = 20, group = G4)
float zoneSize = input.float(0.12, "Minimum zone half-width (ATR)", minval = 0.05, maxval = 0.4, group = G4)
float mergeSize = input.float(0.35, "Match nearby nodes (ATR)", minval = 0.1, maxval = 1, group = G4)
int touchMemory = input.int(8, "A magnet touch counts for (bars)", minval = 1, maxval = 50, group = G4)
 
const string G5 = "5 · Calibration"
int calBars = input.int(1500, "Maximum sample age (bars)", minval = 100, maxval = 5000, group = G5)
int capacity = input.int(200, "Samples kept per side", minval = 30, maxval = 500, group = G5)
int minSamples = input.int(30, "Minimum prior samples", minval = 10, maxval = 500, group = G5)
 
const string G6 = "6 · Factor weights (0 = off)"
float wMom = input.float(1.0, "Momentum decay", minval = 0, maxval = 3, step = 0.25, group = G6)
float wRej = input.float(1.0, "Rejection / climax bar", minval = 0, maxval = 3, step = 0.25, group = G6)
float wAbs = input.float(1.0, "Absorption", minval = 0, maxval = 3, step = 0.25, group = G6)
float wFlow = input.float(1.0, "Flow divergence", minval = 0, maxval = 3, step = 0.25, group = G6)
float wExh = input.float(1.0, "Volume exhaustion", minval = 0, maxval = 3, step = 0.25, group = G6)
float wLoc = input.float(1.0, "Magnet location", minval = 0, maxval = 3, step = 0.25, group = G6)
float healthPenalty = input.float(20.0, "Healthy-trend penalty (points)", minval = 0, maxval = 50, step = 1, group = G6)
 
const string G7 = "7 · Risk & tracking"
float stopATR = input.float(0.25, "Stop buffer beyond setup extreme (ATR)", minval = 0, maxval = 3, step = 0.05, group = G7)
bool useMagnetTarget = input.bool(true, "Target the next magnet level", group = G7)
float minRR = input.float(1.0, "Minimum reward:risk to magnet (0 = off)", minval = 0, maxval = 10, step = 0.25, group = G7)
float fallbackR = input.float(2.0, "Target without a magnet (R multiple)", minval = 0.5, maxval = 10, step = 0.25, group = G7)
int maxHold = input.int(40, "Time exit after (bars)", minval = 1, maxval = 500, group = G7)
 
const string G8 = "8 · Display"
bool showSignals = input.bool(true, "BUY / SELL labels", group = G8)
bool showSetups = input.bool(true, "Setup markers", group = G8)
bool showFails = input.bool(false, "Failed / expired setup markers", group = G8)
bool showTrade = input.bool(true, "Entry, stop and target lines", group = G8)
bool showOutcome = input.bool(true, "Outcome labels", group = G8)
bool showMagnets = input.bool(true, "Live magnet zones", group = G8)
bool showHistory = input.bool(false, "Historical magnet trace", group = G8)
int forwardBars = input.int(18, "Magnet projection bars", minval = 5, maxval = 100, group = G8)
string tableMode = input.string("Compact", "Dashboard", options = ["Compact", "Full", "Off"], group = G8)
string tablePos = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = G8)
color buyColor = input.color(#22B8A0, "Buy color", group = G8)
color sellColor = input.color(#EF6F6C, "Sell color", group = G8)
 
// Presets. Custom uses the three "Custom ·" inputs.
float setupRank = sensitivity == "Conservative" ? 85.0 : sensitivity == "Balanced" ? 80.0 : sensitivity == "Aggressive" ? 70.0 : customRank
float minScore = sensitivity == "Conservative" ? 22.0 : sensitivity == "Balanced" ? 15.0 : sensitivity == "Aggressive" ? 10.0 : customScore
int minFactors = sensitivity == "Conservative" ? 3 : sensitivity == "Balanced" ? 2 : sensitivity == "Aggressive" ? 2 : customFactors
 
bool useLTF = pressureMode == "Lower-timeframe estimate"
color stopColor = #F05454
color targetColor = #2BB673
color inkColor = #C9D1D9
 
if barstate.isfirst
    if not (n1 < n2 and n2 < n3 and n3 < n4)
        runtime.error("Volume horizons must strictly increase: micro < small < large < major.")
    if fastProf >= slowProf
        runtime.error("Recent profile bars must be fewer than context profile bars.")
    if minGap >= maxGap
        runtime.error("Minimum magnet gap must be below the maximum target distance.")
    if resetRank >= setupRank
        runtime.error("Re-arm percentile must be below the setup percentile.")
    if minSamples > capacity
        runtime.error("Minimum prior samples cannot exceed samples kept per side.")
    if wMom + wRej + wAbs + wFlow + wExh + wLoc <= 0
        runtime.error("At least one factor weight must be above zero.")
    if useLTF and timeframe.in_seconds(lowerTF) >= timeframe.in_seconds()
        runtime.error("The lower timeframe must be below the chart timeframe, or use the chart-bar estimate.")
 
// ─────────────────────────────────────────────────────────────────────────────
// TYPES
// ─────────────────────────────────────────────────────────────────────────────
 
type Magnet
    float price
    float halfWidth
    float quality
    int created
    int lastSeen
    int confirms
    int armedAt
    int spentAt
    bool armed = false
    bool spent = false
    bool retired = false
 
type Target
    Magnet node
    line ray
    box band
    label caption
 
type Trade
    int dir = 0
    int openBar
    float entry
    float stop
    float target
    float risk
    string grade = ""
    line lEntry
    line lStop
    line lTarget
 
type Stats
    int n = 0
    int wins = 0
    float sumR = 0.0
    int blocked = 0
 
// ─────────────────────────────────────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────────────────────────────────────
 
f_div(float x, float y, float fallback) =>
    not na(x) and not na(y) and math.abs(y) > 1e-12 ? x / y : fallback
 
f_cap(float x) =>
    math.max(0.0, math.min(1.0, nz(x, 0.0)))
 
f_ramp(float x, float lo, float hi) =>
    f_cap(f_div(x - lo, hi - lo, 0.0))
 
f_clamp(float x, float lo, float hi) =>
    math.max(lo, math.min(hi, x))
 
// Peak plus consensus across horizons (VTPE), not four independent votes.
f_pool(float a, float b, float c, float d) =>
    0.55 * math.max(math.max(a, b), math.max(c, d)) + 0.45 * (a + b + c + d) / 4.0
 
// Directional efficiency: net change over path length (ERE).
f_eff(int length) =>
    float path = math.sum(math.abs(nz(ta.change(close))), length)
    (close - close[length]) / math.max(path, syminfo.mintick)
 
// Drop samples older than the calibration window (ERE).
f_prune(array<float> values, array<int> times, int oldest) =>
    while array.size(times) > 0
        if array.get(times, 0) < oldest
            array.shift(times)
            array.shift(values)
        else
            break
    array.size(values)
 
// Midrank percentile of the current reading among PRIOR samples. Ties count half (ERE).
f_rank(array<float> values, float observation, int minimum) =>
    int count = array.size(values)
    float result = na
    if count >= minimum and count > 0 and not na(observation)
        float below = 0.0
        float equal = 0.0
        for i = 0 to count - 1
            float sample = array.get(values, i)
            below += sample < observation ? 1.0 : 0.0
            equal += sample == observation ? 1.0 : 0.0
        result := 100.0 * (below + 0.5 * equal) / count
    result
 
f_add(array<float> values, array<int> times, float value, int maxSize) =>
    array.push(values, value)
    array.push(times, bar_index)
    if array.size(values) > maxSize
        array.shift(values)
        array.shift(times)
    array.size(values)
 
// Intrabar candle direction; previous close or last direction for dojis (VTPE).
f_intrabar_signed_volume() =>
    var float lastDirection = 0.0
    lastDirection := close > open ? 1.0 : close < open ? -1.0 : close > close[1] ? 1.0 : close < close[1] ? -1.0 : lastDirection
    nz(volume, 0.0) * lastDirection
 
// ─────────────────────────────────────────────────────────────────────────────
// PRICE CONTEXT (ERE)
// ─────────────────────────────────────────────────────────────────────────────
 
float tick = math.max(syminfo.mintick, 1e-10)
float atr = ta.atr(atrLen)
float atrNow = math.max(nz(atr, tick), tick)
float priorATR = math.max(nz(atr[1], tick), tick)
float trendEMA = ta.ema(close, emaLen)
float extension = (close[1] - trendEMA[1]) / priorATR
float fastEff = f_eff(fastLen)
float trendEff = f_eff(trendLen)
float priorTrendEff = nz(trendEff[1])
float recentMove = close - close[fastLen]
float olderMove = close[fastLen] - close[2 * fastLen]
 
int priceWarmup = math.max(3 * emaLen, math.max(2 * fastLen + 1, math.max(trendLen + 2, math.max(atrLen + 1, n2 + 1))))
bool ready = bar_index >= priceWarmup and not na(trendEff[1]) and not na(atr[1]) and atr[1] > 0
 
// ─────────────────────────────────────────────────────────────────────────────
// VOLUME DATA (VTPE)
// ─────────────────────────────────────────────────────────────────────────────
 
float v = math.max(nz(volume, 0.0), 0.0)
bool validVolume = not na(volume) and volume >= 0
float span = math.max(high - low, tick)
float changePrice = nz(ta.change(close), 0.0)
float clv = (2.0 * close - high - low) / span
float body = (close - open) / span
float upperWick = (high - math.max(open, close)) / span
float lowerWick = (math.min(open, close) - low) / span
float priceDir = math.sign(changePrice)
float pressure = f_clamp(0.50 * clv + 0.25 * body + 0.25 * priceDir, -1.0, 1.0)
bool validPressure = true
float ltfCoverage = na
 
if useLTF
    [signedArray, volumeArray] = request.security_lower_tf(syminfo.tickerid, lowerTF, [f_intrabar_signed_volume(), nz(volume, 0.0)])
    float intraVolume = array.size(volumeArray) > 0 ? array.sum(volumeArray) : 0.0
    ltfCoverage := f_div(intraVolume, v, 0.0)
    validPressure := v > 0 ? ltfCoverage >= 0.80 and ltfCoverage <= 1.20 : array.size(volumeArray) > 0
    pressure := validPressure and intraVolume > 0 ? f_clamp(array.sum(signedArray) / intraVolume, -1.0, 1.0) : 0.0
 
// Relative volume uses prior observations only.
float rollingBase = ta.sma(v, baseLen)[1]
var array<float> slotVolumes = array.new_float(1440, na)
var array<int> slotCounts = array.new_int(1440, 0)
int slot = hour * 60 + minute
bool useSeason = seasonal and timeframe.isintraday and timeframe.in_seconds() >= 60
float slotBase = array.get(slotVolumes, slot)
int slotCount = array.get(slotCounts, slot)
bool seasonReady = useSeason and slotCount >= 5 and not na(slotBase) and slotBase > 0
float expectedV = seasonReady ? slotBase : rollingBase
float rv = f_div(v, expectedV, 0.0)
float logRV = math.log(math.max(rv, 0.001))
float logMean = ta.sma(logRV, baseLen)[1]
float logSD = ta.stdev(logRV, baseLen)[1]
float logZ = f_div(logRV - logMean, logSD, 0.0)
float shock = math.max(f_ramp(rv, 1.30, 3.00), f_ramp(logZ, 1.0, 3.0))
float dry = 1.0 - f_ramp(rv, 0.35, 0.90)
float trueSpan = math.max(span, math.max(math.abs(high - nz(close[1], close)), math.abs(low - nz(close[1], close))))
float normalSpan = ta.sma(trueSpan, baseLen)[1]
float barResult = f_div(math.abs(changePrice), normalSpan, 0.0)
float smallResult = 1.0 - f_ramp(barResult, 0.20, 1.00)
 
// Volume mode is decided from data coverage. Price-only mode is shown, never silent.
bool barDataOK = validVolume and validPressure
float cleanShare = ta.sma(barDataOK ? 1.0 : 0.0, n4)
float liveShare = ta.sma(v > 0 ? 1.0 : 0.0, n4)
int volWarmup = 2 * n4 + 2 * baseLen
bool volOK = useVolume and bar_index >= volWarmup and cleanShare >= 0.98 and liveShare >= 0.80 and expectedV > 0
bool noVolume = bar_index >= n4 and liveShare < 0.50
bool modeKnown = not useVolume or bar_index >= volWarmup or noVolume
bool calibReady = ready and modeKnown
 
// ─────────────────────────────────────────────────────────────────────────────
// VOLUME FAMILIES PER HORIZON (VTPE)
// Current n bars vs. the preceding, non-overlapping n bars. VTPE's VWAP-failure
// family is omitted: it was the other families multiplied by stretch, so it
// counted them twice.
// ─────────────────────────────────────────────────────────────────────────────
 
f_scale(simple int n, float vol, float deltaV, float moneyV, float obvV, float effort) =>
    float total = math.sum(vol, n)
    float eTotal = math.sum(effort, n)
    float eRatio = f_div(eTotal, eTotal[n], 1.0)
    float delta = f_div(math.sum(deltaV, n), total, 0.0)
    float money = f_div(math.sum(moneyV, n), total, 0.0)
    float obv = f_div(math.sum(obvV, n), total, 0.0)
 
    // Related flow proxies form ONE family.
    float flow = 0.60 * delta + 0.25 * money + 0.15 * obv
    float oldFlow = flow[n]
    float net = close - close[n]
    float oldNet = net[n]
    float path = math.sum(math.abs(changePrice), n)
    float efficiency = f_div(net, path, 0.0)
    float hi = ta.highest(high, n)
    float lo = ta.lowest(low, n)
    float rangeN = math.max(hi - lo, tick)
    float pos = f_cap((close - lo) / rangeN)
    float upperPos = f_ramp(pos, 0.50, 0.90)
    float lowerPos = f_ramp(1.0 - pos, 0.50, 0.90)
    float oldHigh = hi[n]
    float oldLow = lo[n]
    float oldRange = math.max(oldHigh - oldLow, tick)
    float testedHigh = f_ramp((hi - oldHigh) / oldRange, -0.15, 0.05)
    float testedLow = f_ramp((oldLow - lo) / oldRange, -0.15, 0.05)
 
    // Price distance per unit of baseline-normalized volume, by direction.
    float upImpact = f_div(math.max(net, 0.0), eTotal, 0.0)
    float downImpact = f_div(math.max(-net, 0.0), eTotal, 0.0)
    float lostUp = oldNet > tick ? f_cap(1.0 - f_div(upImpact, upImpact[n], 1.0)) : 0.0
    float lostDown = oldNet < -tick ? f_cap(1.0 - f_div(downImpact, downImpact[n], 1.0)) : 0.0
    float heavy = f_ramp(eRatio, 0.95, 1.80)
    float weak = 1.0 - f_ramp(eRatio, 0.45, 0.95)
    float upDrive = f_ramp(flow, 0.0, 0.40)
    float downDrive = f_ramp(-flow, 0.0, 0.40)
    // Failure to progress means LOW efficiency. (VTPE used 1 - efficiency, which
    // stayed high through ordinary trends and made absorption a trend signal.)
    float upFail = 1.0 - f_ramp(efficiency, 0.05, 0.40)
    float downFail = 1.0 - f_ramp(-efficiency, 0.05, 0.40)
 
    // Heavy effort with poor progress, or pressure that cannot move price its way.
    float absorbTop = upperPos * math.max(heavy * (0.65 * lostUp + 0.35 * upFail), upDrive * upFail)
    float absorbBottom = lowerPos * math.max(heavy * (0.65 * lostDown + 0.35 * downFail), downDrive * downFail)
    float flowTop = upperPos * math.max(f_ramp(-flow, 0.03, 0.40), testedHigh * f_ramp(oldFlow - flow, 0.08, 0.50))
    float flowBottom = lowerPos * math.max(f_ramp(flow, 0.03, 0.40), testedLow * f_ramp(flow - oldFlow, 0.08, 0.50))
 
    // Participation = effective contributing bars / n. Narrow participation
    // strengthens a dry-up reading but cannot trigger it alone.
    float squared = math.sum(vol * vol, n)
    float participation = f_cap(f_div(total * total, squared * n, 0.0))
    float narrow = 1.0 - participation
    float fadeTop = f_ramp(oldFlow - flow, 0.02, 0.40)
    float fadeBottom = f_ramp(flow - oldFlow, 0.02, 0.40)
    float exhaustTop = upperPos * testedHigh * weak * math.max(lostUp, fadeTop) * (0.75 + 0.25 * narrow)
    float exhaustBottom = lowerPos * testedLow * weak * math.max(lostDown, fadeBottom) * (0.75 + 0.25 * narrow)
 
    float healthUp = math.max(efficiency, 0.0) * upDrive * (1.0 - 0.5 * lostUp)
    float healthDown = math.max(-efficiency, 0.0) * downDrive * (1.0 - 0.5 * lostDown)
 
    [absorbBottom, absorbTop, flowBottom, flowTop, exhaustBottom, exhaustTop, healthUp, healthDown, flow]
 
float signedV = v * pressure
float clvV = v * clv
float obvStep = v * priceDir
 
[aB1, aT1, fB1, fT1, xB1, xT1, hu1, hd1, flow1] = f_scale(n1, v, signedV, clvV, obvStep, rv)
[aB2, aT2, fB2, fT2, xB2, xT2, hu2, hd2, flow2] = f_scale(n2, v, signedV, clvV, obvStep, rv)
[aB3, aT3, fB3, fT3, xB3, xT3, hu3, hd3, flow3] = f_scale(n3, v, signedV, clvV, obvStep, rv)
[aB4, aT4, fB4, fT4, xB4, xT4, hu4, hd4, flow4] = f_scale(n4, v, signedV, clvV, obvStep, rv)
 
// Horizon agreement enters through VTPE's peak-plus-consensus pooling.
float absorbB = f_pool(aB1, aB2, aB3, aB4)
float absorbT = f_pool(aT1, aT2, aT3, aT4)
float divB = f_pool(fB1, fB2, fB3, fB4)
float divT = f_pool(fT1, fT2, fT3, fT4)
float exhB = f_pool(xB1, xB2, xB3, xB4)
float exhT = f_pool(xT1, xT2, xT3, xT4)
float healthyUp = nz(0.25 * hu1 + 0.35 * hu2 + 0.25 * hu3 + 0.15 * hu4)
float healthyDown = nz(0.25 * hd1 + 0.35 * hd2 + 0.25 * hd3 + 0.15 * hd4)
 
// ─────────────────────────────────────────────────────────────────────────────
// PRICE FACTORS
// ─────────────────────────────────────────────────────────────────────────────
 
// Momentum decay (ERE): the latest fast move is weaker than the one before it,
// and short-term efficiency has fallen below the prior trend's efficiency.
float decelScale = priorATR * math.sqrt(fastLen)
float decelUp = f_cap((olderMove - recentMove) / decelScale)
float decelDn = f_cap((recentMove - olderMove) / decelScale)
float lossUp = f_cap((priorTrendEff - fastEff) / 2.0)
float lossDn = f_cap((fastEff - priorTrendEff) / 2.0)
float momT = 0.5 * decelUp + 0.5 * lossUp
float momB = 0.5 * decelDn + 0.5 * lossDn
 
// Rejection / climax (VTPE bar model). A wick rejection at a range extreme only
// counts with an anomaly: volume shock, climax range or dry-up. Without volume,
// a wider-than-normal range stands in for the anomaly.
float priorHigh = ta.highest(high, n2)[1]
float priorLow = ta.lowest(low, n2)[1]
float priorRange = math.max(priorHigh - priorLow, tick)
float atTop = f_ramp((high - priorLow) / priorRange, 0.65, 1.00)
float atBottom = f_ramp((priorHigh - low) / priorRange, 0.65, 1.00)
float rejectTop = f_cap(2.0 * upperWick + 0.4 * math.max(-clv, 0.0))
float rejectBottom = f_cap(2.0 * lowerWick + 0.4 * math.max(clv, 0.0))
float climax = shock * f_ramp(span / math.max(normalSpan, tick), 1.30, 2.80)
float barTopV = atTop * math.max(math.max(shock * rejectTop, shock * smallResult * f_ramp(-pressure, 0.0, 0.5)), math.max(climax * rejectTop, 0.60 * dry * rejectTop))
float barBotV = atBottom * math.max(math.max(shock * rejectBottom, shock * smallResult * f_ramp(pressure, 0.0, 0.5)), math.max(climax * rejectBottom, 0.60 * dry * rejectBottom))
float rangeExpansion = f_ramp(span / math.max(normalSpan, tick), 1.0, 2.2)
float rejT = volOK ? barTopV : atTop * rejectTop * rangeExpansion
float rejB = volOK ? barBotV : atBottom * rejectBottom * rangeExpansion
 
// Trend context (ERE eligibility), remembered for ctxMemory bars. The move's
// extreme must also be recent: a pullback inside a trend is not a top or bottom.
bool upContextNow = extension >= minExt and priorTrendEff >= minEff
bool dnContextNow = -extension >= minExt and -priorTrendEff >= minEff
float upContextCount = math.sum(upContextNow ? 1.0 : 0.0, ctxMemory)
float dnContextCount = math.sum(dnContextNow ? 1.0 : 0.0, ctxMemory)
int barsSinceHigh = ta.highestbars(high, n2)
int barsSinceLow = ta.lowestbars(low, n2)
bool recentHigh = not na(barsSinceHigh) and barsSinceHigh > -ctxMemory
bool recentLow = not na(barsSinceLow) and barsSinceLow > -ctxMemory
bool topEligible = calibReady and upContextCount > 0 and recentHigh
bool botEligible = calibReady and dnContextCount > 0 and recentLow
 
// ─────────────────────────────────────────────────────────────────────────────
// MAGNET LEVELS
// OHLCV profile approximation, not order-book data. Stored prices never move.
// ─────────────────────────────────────────────────────────────────────────────
 
float gridLow = ta.lowest(low, slowProf)
float gridHigh = ta.highest(high, slowProf)
float meanVolume = ta.sma(v, slowProf)
float profCoverage = ta.sma(v > 0 ? 1.0 : 0.0, slowProf)
bool profVolume = useVolume and profCoverage >= 0.95
float travel30 = math.sum(math.abs(changePrice), 30)
float move30 = close - close[30]
float eff30 = travel30 > 0 ? f_clamp(math.abs(move30) / travel30, 0.0, 1.0) : 0.0
bool profReady = not na(low[slowProf - 1]) and not na(atr)
 
var array<Magnet> pool = array.new<Magnet>()
var Target upperT = Target.new()
var Target lowerT = Target.new()
var array<float> profFast = array.new_float(rows, 0.0)
var array<float> profSlow = array.new_float(rows, 0.0)
var array<float> diffFast = array.new_float(rows + 1, 0.0)
var array<float> diffSlow = array.new_float(rows + 1, 0.0)
var array<float> smoothFast = array.new_float(rows, 0.0)
var array<float> smoothSlow = array.new_float(rows, 0.0)
var array<float> profMix = array.new_float(rows, 0.0)
 
// Last revisit of an armed node from above (support test) or below (resistance test).
var int lowerTouchBar = na
var float lowerTouchTop = na
var float lowerTouchBottom = na
var int upperTouchBar = na
var float upperTouchTop = na
var float upperTouchBottom = na
 
// Spread each candle's mass uniformly over its high-low range. Difference
// arrays avoid looping over every crossed row.
f_mass(array<float> h, array<float> diff, float bottom, float top, float mass, float base, float stepSize) =>
    int a = int(f_clamp(math.floor((bottom - base) / stepSize), 0, rows - 1))
    int b = int(f_clamp(math.floor((top - base) / stepSize), 0, rows - 1))
    if a == b
        array.set(h, a, array.get(h, a) + mass)
    else
        float spanPx = math.max(top - bottom, syminfo.mintick)
        float leftMass = mass * (base + (a + 1) * stepSize - bottom) / spanPx
        float rightMass = mass * (top - (base + b * stepSize)) / spanPx
        array.set(h, a, array.get(h, a) + leftMass)
        array.set(h, b, array.get(h, b) + rightMass)
        if b > a + 1
            float middleMass = mass * stepSize / spanPx
            array.set(diff, a + 1, array.get(diff, a + 1) + middleMass)
            array.set(diff, b, array.get(diff, b) - middleMass)
 
f_smooth(array<float> src, array<float> dst) =>
    for j = 0 to rows - 1
        float acc = 0.0
        for k = -2 to 2
            int index = j + k
            if index >= 0 and index < rows
                float weight = k == 0 ? 6.0 : math.abs(k) == 1 ? 4.0 : 1.0
                acc += array.get(src, index) * weight
        array.set(dst, j, acc / 16.0)
 
f_register(float price, float width, float quality, float recentSupport, float atrValue) =>
    Magnet match = na
    float nearest = 1e20
    if array.size(pool) > 0
        for i = 0 to array.size(pool) - 1
            Magnet m = array.get(pool, i)
            float distance = math.abs(price - m.price)
            float tolerance = math.max(mergeSize * atrValue, width + m.halfWidth)
            if distance <= tolerance and distance < nearest
                match := m
                nearest := distance
    if na(match)
        if array.size(pool) >= 40
            Magnet oldest = array.shift(pool)
            oldest.retired := true
        array.push(pool, Magnet.new(price, width, quality, bar_index, bar_index, 1, na, na))
    else
        // Reuse needs fresh recent-profile support and reconfirmation.
        bool renew = match.spent and bar_index - match.spentAt >= fastProf and recentSupport >= 0.5
        if renew
            match.spent := false
            match.armed := false
            match.armedAt := na
            match.spentAt := na
            match.created := bar_index
            match.confirms := 1
            match.quality := quality
        else if match.lastSeen != bar_index
            match.confirms := bar_index - match.lastSeen <= refresh + 1 ? match.confirms + 1 : 1
            match.quality := 0.7 * match.quality + 0.3 * quality
        else
            match.quality := math.max(match.quality, quality)
        // Matching changes evidence, never the stored price or width.
        match.lastSeen := bar_index
    0
 
f_mrank(Magnet m, float price, float atrValue, float trendEfficiency, float trendMove) =>
    float distance = math.abs(m.price - price) / atrValue
    float freshness = math.exp(-math.log(2.0) * float(bar_index - m.lastSeen) / slowProf)
    bool againstTrend = (m.price - price) * trendMove < 0
    float trendFactor = againstTrend ? 1.0 - 0.45 * trendEfficiency : 1.0
    m.quality * freshness * math.exp(-0.18 * distance) * trendFactor
 
f_finishTarget(Target t) =>
    if not na(t.ray)
        line.delete(t.ray)
    if not na(t.band)
        box.delete(t.band)
    if not na(t.caption)
        label.delete(t.caption)
    t.node := na
    t.ray := na
    t.band := na
    t.caption := na
    0
 
f_startTarget(Target t, Magnet m, color c) =>
    t.node := m
    if showMagnets
        t.ray := line.new(bar_index, m.price, bar_index + forwardBars, m.price, color = color.new(c, 15), width = 1)
        t.band := box.new(bar_index, m.price + m.halfWidth, bar_index + forwardBars, m.price - m.halfWidth, border_color = color.new(c, 80), bgcolor = color.new(c, 90))
        t.caption := label.new(bar_index + forwardBars, m.price, "", style = label.style_label_left, color = color.new(c, 100), textcolor = c, size = size.small)
    0
 
f_paintTarget(Target t, string title) =>
    if not na(t.node) and not na(t.ray)
        int right = bar_index + forwardBars
        line.set_x2(t.ray, right)
        box.set_left(t.band, bar_index)
        box.set_right(t.band, right)
        label.set_xy(t.caption, right, t.node.price)
        label.set_text(t.caption, title + " " + str.tostring(t.node.price, format.mintick))
    0
 
bool newUpper = false
bool newLower = false
 
if barstate.isconfirmed and profReady
    // 1 · First revisit of an armed zone spends it and records a touch.
    if array.size(pool) > 0
        for i = array.size(pool) - 1 to 0
            Magnet m = array.get(pool, i)
            bool overlaps = high >= m.price - m.halfWidth and low <= m.price + m.halfWidth
            bool gapsAcross = (close[1] < m.price - m.halfWidth and open > m.price + m.halfWidth) or (close[1] > m.price + m.halfWidth and open < m.price - m.halfWidth)
            if m.armed and not m.spent and bar_index > m.armedAt and (overlaps or gapsAcross)
                m.spent := true
                m.spentAt := bar_index
                if overlaps
                    if m.price < close[1]
                        lowerTouchBar := bar_index
                        lowerTouchTop := m.price + m.halfWidth
                        lowerTouchBottom := m.price - m.halfWidth
                    else
                        upperTouchBar := bar_index
                        upperTouchTop := m.price + m.halfWidth
                        upperTouchBottom := m.price - m.halfWidth
            if bar_index - m.lastSeen > slowProf or bar_index - m.created > slowProf * 3
                m.retired := true
                array.remove(pool, i)
 
    // 2 · Periodically rebuild the recent and context profiles.
    if bar_index % refresh == 0
        array.fill(profFast, 0.0)
        array.fill(profSlow, 0.0)
        array.fill(diffFast, 0.0)
        array.fill(diffSlow, 0.0)
        float stepSize = math.max((gridHigh - gridLow) / rows, syminfo.mintick)
        for i = 0 to slowProf - 1
            float mass = profVolume ? math.min(v[i], meanVolume * 5.0) : 1.0
            f_mass(profSlow, diffSlow, low[i], high[i], mass, gridLow, stepSize)
            if i < fastProf
                f_mass(profFast, diffFast, low[i], high[i], mass, gridLow, stepSize)
        float runFast = 0.0
        float runSlow = 0.0
        for j = 0 to rows - 1
            runFast += array.get(diffFast, j)
            runSlow += array.get(diffSlow, j)
            array.set(profFast, j, math.max(0.0, array.get(profFast, j) + runFast))
            array.set(profSlow, j, math.max(0.0, array.get(profSlow, j) + runSlow))
        f_smooth(profFast, smoothFast)
        f_smooth(profSlow, smoothSlow)
        float fastMax = array.max(smoothFast)
        float slowMax = array.max(smoothSlow)
        float mixTotal = 0.0
        for j = 0 to rows - 1
            float fShare = fastMax > 0 ? array.get(smoothFast, j) / fastMax : 0.0
            float sShare = slowMax > 0 ? array.get(smoothSlow, j) / slowMax : 0.0
            float mixed = 0.45 * fShare + 0.55 * sShare
            array.set(profMix, j, mixed)
            mixTotal += mixed
        float average = mixTotal / rows
        for j = 0 to rows - 1
            float here = array.get(profMix, j)
            float leftV = j > 0 ? array.get(profMix, j - 1) : -1.0
            float rightV = j < rows - 1 ? array.get(profMix, j + 1) : -1.0
            if here > leftV and here >= rightV and here > average * 1.2
                float fShare = fastMax > 0 ? array.get(smoothFast, j) / fastMax : 0.0
                float sShare = slowMax > 0 ? array.get(smoothSlow, j) / slowMax : 0.0
                float quality = 100.0 * (0.7 * math.max(fShare, sShare) + 0.3 * math.min(fShare, sShare))
                if quality >= qualityFloor
                    float price = math.round_to_mintick(gridLow + (j + 0.5) * stepSize)
                    float width = math.max(syminfo.mintick, math.max(stepSize * 0.5, zoneSize * atrNow))
                    f_register(price, width, quality, fShare, atrNow)
 
    // 3 · Arm displaced, reconfirmed nodes and rank candidates on each side.
    Magnet bestUpper = na
    Magnet bestLower = na
    float bestUpperRank = 0.0
    float bestLowerRank = 0.0
    if array.size(pool) > 0
        for i = 0 to array.size(pool) - 1
            Magnet m = array.get(pool, i)
            float distance = math.abs(m.price - close)
            bool displaced = distance - m.halfWidth >= minGap * atrNow
            if not m.armed and not m.spent and m.confirms >= nodeConfirms and displaced
                m.armed := true
                m.armedAt := bar_index
            if m.armed and not m.spent and not m.retired and m.quality >= qualityFloor and displaced and distance <= maxGap * atrNow
                float score = f_mrank(m, close, atrNow, eff30, move30)
                if m.price > close and score > bestUpperRank
                    bestUpper := m
                    bestUpperRank := score
                if m.price < close and score > bestLowerRank
                    bestLower := m
                    bestLowerRank := score
 
    // 4 · Retire spent, removed or out-of-range targets; then start new ones.
    if not na(upperT.node)
        if upperT.node.spent or upperT.node.retired or math.abs(upperT.node.price - close) > maxGap * atrNow
            f_finishTarget(upperT)
    if not na(lowerT.node)
        if lowerT.node.spent or lowerT.node.retired or math.abs(lowerT.node.price - close) > maxGap * atrNow
            f_finishTarget(lowerT)
    if na(upperT.node) and not na(bestUpper)
        f_startTarget(upperT, bestUpper, buyColor)
        newUpper := true
    if na(lowerT.node) and not na(bestLower)
        f_startTarget(lowerT, bestLower, sellColor)
        newLower := true
 
if barstate.islast and showMagnets
    f_paintTarget(upperT, "▲ magnet")
    f_paintTarget(lowerT, "▼ magnet")
 
float upperPrice = not na(upperT.node) ? upperT.node.price : na
float lowerPrice = not na(lowerT.node) ? lowerT.node.price : na
 
// Magnet location factor: a recent revisit of a node that price is holding.
float locB = 0.0
if not na(lowerTouchBar) and bar_index - lowerTouchBar <= touchMemory and low <= lowerTouchTop + 0.5 * atrNow
    locB := close >= lowerTouchBottom ? 1.0 : close >= lowerTouchBottom - 0.5 * atrNow ? 0.5 : 0.0
float locT = 0.0
if not na(upperTouchBar) and bar_index - upperTouchBar <= touchMemory and high >= upperTouchBottom - 0.5 * atrNow
    locT := close <= upperTouchTop ? 1.0 : close <= upperTouchTop + 0.5 * atrNow ? 0.5 : 0.0
 
// ─────────────────────────────────────────────────────────────────────────────
// COMPOSITE EVIDENCE
// ─────────────────────────────────────────────────────────────────────────────
 
int priceWeighted = (wMom > 0 ? 1 : 0) + (wRej > 0 ? 1 : 0)
int volumeWeighted = (wAbs > 0 ? 1 : 0) + (wFlow > 0 ? 1 : 0) + (wExh > 0 ? 1 : 0)
int nWeighted = priceWeighted + volumeWeighted + (wLoc > 0 ? 1 : 0)
int nActive = priceWeighted + (wLoc > 0 ? 1 : 0) + (volOK ? volumeWeighted : 0)
// Without volume, the factor requirement scales down with the factors available.
int required = math.max(1, math.min(nActive, int(math.ceil(float(minFactors) * nActive / math.max(nWeighted, 1)))))
 
f_composite(float mom, float rej, float absorb, float div, float exh, float loc, bool withVolume) =>
    float num = wMom * mom + wRej * rej + wLoc * loc
    float den = wMom + wRej + wLoc
    if withVolume
        num += wAbs * absorb + wFlow * div + wExh * exh
        den += wAbs + wFlow + wExh
    den > 0 ? 100.0 * num / den : 0.0
 
f_count(float mom, float rej, float absorb, float div, float exh, float loc, bool withVolume) =>
    int priceN = (wMom > 0 and mom >= factorOn ? 1 : 0) + (wRej > 0 and rej >= factorOn ? 1 : 0)
    int volN = withVolume ? (wAbs > 0 and absorb >= factorOn ? 1 : 0) + (wFlow > 0 and div >= factorOn ? 1 : 0) + (wExh > 0 and exh >= factorOn ? 1 : 0) : 0
    int locN = wLoc > 0 and loc >= factorOn ? 1 : 0
    [priceN + volN + locN, priceN, volN]
 
float scoreB = math.max(0.0, f_composite(momB, rejB, absorbB, divB, exhB, locB, volOK) - (volOK ? healthPenalty * healthyDown : 0.0))
float scoreT = math.max(0.0, f_composite(momT, rejT, absorbT, divT, exhT, locT, volOK) - (volOK ? healthPenalty * healthyUp : 0.0))
[factorsB, priceB, volumeB] = f_count(momB, rejB, absorbB, divB, exhB, locB, volOK)
[factorsT, priceT, volumeT] = f_count(momT, rejT, absorbT, divT, exhT, locT, volOK)
// Price AND volume must agree. With volume, a volume-qualified rejection bar
// is both by itself; otherwise momentum decay needs a volume family beside it.
// (VTPE's families need the close near the range extreme, which a wick
// rejection bar does not have, so the two rarely fire on the same bar.)
f_cross(float mom, float rej, int volN) =>
    bool momOn = wMom > 0 and mom >= factorOn
    bool rejOn = wRej > 0 and rej >= factorOn
    volOK ? rejOn or (momOn and volN >= 1) : wMom > 0 and wRej > 0 ? momOn and rejOn : momOn or rejOn
 
bool crossB = not crossCheck or f_cross(momB, rejB, volumeB)
bool crossT = not crossCheck or f_cross(momT, rejT, volumeT)
// Grades count factors beyond the minimum: C = minimum, B = +1 or P95, A = +2 or +1 with P95.
int gradeBase = math.max(required, 2)
 
// ─────────────────────────────────────────────────────────────────────────────
// SIGNAL AND TRADE STATE (closed bars only)
// ─────────────────────────────────────────────────────────────────────────────
 
var array<float> histB = array.new<float>()
var array<int> timesB = array.new<int>()
var array<float> histT = array.new<float>()
var array<int> timesT = array.new<int>()
var float rankB = na
var float rankT = na
var int samplesB = 0
var int samplesT = 0
var bool armedB = true
var bool armedT = true
 
var int setupSide = 0
var int setupBar = na
var float setupHigh = na
var float setupLow = na
var float setupATR = na
var float setupExtreme = na
var float setupScore = na
var float setupPct = na
var int setupFactors = 0
var string setupGrade = ""
 
var int lastBuyBar = na
var int lastSellBar = na
var Trade trade = Trade.new()
var Stats statsL = Stats.new()
var Stats statsS = Stats.new()
var Stats statsGA = Stats.new()
var Stats statsGB = Stats.new()
var Stats statsGC = Stats.new()
var string lastEvent = "None yet"
 
bool buySetup = false
bool sellSetup = false
bool buyFail = false
bool sellFail = false
bool buySignal = false
bool sellSignal = false
bool targetHit = false
bool stopHit = false
 
f_grade(float pct, int factors, int base) =>
    int extra = factors - base
    extra >= 2 or (extra >= 1 and pct >= 95) ? "A" : extra >= 1 or pct >= 95 ? "B" : "C"
 
f_record(Stats s, float r) =>
    s.n := s.n + 1
    s.wins := s.wins + (r > 0 ? 1 : 0)
    s.sumR := s.sumR + r
    0
 
f_closeTrade(Trade t, Stats s, float exitPx, string how) =>
    float r = t.dir * (exitPx - t.entry) / t.risk
    f_record(s, r)
    f_record(t.grade == "A" ? statsGA : t.grade == "B" ? statsGB : statsGC, r)
    if not na(t.lEntry)
        line.set_x2(t.lEntry, bar_index)
        line.set_x2(t.lStop, bar_index)
        line.set_x2(t.lTarget, bar_index)
    if showOutcome
        color c = r > 0 ? targetColor : stopColor
        label.new(bar_index, exitPx, how + " " + (r >= 0 ? "+" : "") + str.tostring(r, "0.0") + "R", style = label.style_label_left, color = color.new(c, 80), textcolor = c, size = size.tiny)
    t.dir := 0
    r
 
if barstate.isconfirmed
    // A · Calibrate: drop stale samples, then rank this bar against PRIOR samples only.
    samplesB := f_prune(histB, timesB, bar_index - calBars)
    samplesT := f_prune(histT, timesT, bar_index - calBars)
    rankB := botEligible ? f_rank(histB, scoreB, minSamples) : na
    rankT := topEligible ? f_rank(histT, scoreT, minSamples) : na
 
    // B · A side re-arms once its evidence episode ends.
    if not botEligible or (not na(rankB) and rankB < resetRank)
        armedB := true
    if not topEligible or (not na(rankT) and rankT < resetRank)
        armedT := true
 
    bool qualB = botEligible and not na(rankB) and rankB >= setupRank and scoreB >= minScore and factorsB >= required and crossB
    bool qualT = topEligible and not na(rankT) and rankT >= setupRank and scoreT >= minScore and factorsT >= required and crossT
 
    // C · Follow the open trade. Gaps fill at the open. A bar touching both
    //     levels counts as the stop.
    if trade.dir != 0 and bar_index > trade.openBar
        bool isLong = trade.dir == 1
        float exitPx = na
        string how = ""
        if isLong ? open >= trade.target : open <= trade.target
            exitPx := open
            how := "Target"
        else if isLong ? open <= trade.stop : open >= trade.stop
            exitPx := open
            how := "Stop"
        else if isLong ? low <= trade.stop : high >= trade.stop
            exitPx := trade.stop
            how := "Stop"
        else if isLong ? high >= trade.target : low <= trade.target
            exitPx := trade.target
            how := "Target"
        else if bar_index - trade.openBar >= maxHold
            exitPx := close
            how := "Time"
        if na(exitPx)
            if not na(trade.lEntry)
                line.set_x2(trade.lEntry, bar_index)
                line.set_x2(trade.lStop, bar_index)
                line.set_x2(trade.lTarget, bar_index)
        else
            targetHit := how == "Target"
            stopHit := how == "Stop"
            float r = f_closeTrade(trade, isLong ? statsL : statsS, exitPx, how)
            lastEvent := (isLong ? "Long " : "Short ") + str.lower(how) + " " + (r >= 0 ? "+" : "") + str.tostring(r, "0.0") + "R"
 
    // D · Manage the armed setup: move it on a deeper qualifying bar, or fail,
    //     expire, or trigger.
    if setupSide != 0
        bool isBuy = setupSide == 1
        bool again = isBuy ? qualB : qualT
        bool deeper = isBuy ? low < setupExtreme : high > setupExtreme
        if again and deeper
            setupBar := bar_index
            setupHigh := high
            setupLow := low
            setupATR := atrNow
            setupExtreme := isBuy ? low : high
            setupScore := isBuy ? scoreB : scoreT
            setupPct := isBuy ? rankB : rankT
            setupFactors := isBuy ? factorsB : factorsT
            setupGrade := f_grade(setupPct, setupFactors, gradeBase)
            buySetup := isBuy
            sellSetup := not isBuy
            lastEvent := isBuy ? "Buy setup moved lower" : "Sell setup moved higher"
        else
            setupExtreme := isBuy ? math.min(setupExtreme, low) : math.max(setupExtreme, high)
            float buffer = triggerATR * setupATR
            int age = bar_index - setupBar
            bool failed = isBuy ? (low < setupLow - invalidATR * setupATR or close < setupLow - buffer) : (high > setupHigh + invalidATR * setupATR or close > setupHigh + buffer)
            if failed or age > triggerBars
                buyFail := isBuy
                sellFail := not isBuy
                lastEvent := (isBuy ? "Buy" : "Sell") + (failed ? " setup failed" : " setup expired")
                setupSide := 0
            else if age >= 1
                bool broke = isBuy ? close > setupHigh + buffer : close < setupLow - buffer
                bool supported = not volTrigger or (isBuy ? (pressure >= confirmPres and (not volOK or (flow1 > 0 and rv >= confirmRV))) : (pressure <= -confirmPres and (not volOK or (flow1 < 0 and rv >= confirmRV))))
                if broke and supported
                    // Structural stop beyond the most extreme price since the setup.
                    float stopPx = isBuy ? setupExtreme - stopATR * setupATR : setupExtreme + stopATR * setupATR
                    float risk = math.max(isBuy ? close - stopPx : stopPx - close, tick)
                    // Target: near edge of the live magnet zone in the trade's direction.
                    Magnet mt = isBuy ? upperT.node : lowerT.node
                    float magnetPx = na
                    if useMagnetTarget and not na(mt)
                        float edge = isBuy ? mt.price - mt.halfWidth : mt.price + mt.halfWidth
                        magnetPx := (isBuy ? edge > close : edge < close) ? edge : na
                    float rr = na(magnetPx) ? fallbackR : math.abs(magnetPx - close) / risk
                    bool opens = isBuy ? sideMode != "Short only" : sideMode != "Long only"
                    bool blocked = opens and not na(magnetPx) and minRR > 0 and rr < minRR
                    string sideTxt = isBuy ? "BUY" : "SELL"
                    if blocked
                        Stats st = isBuy ? statsL : statsS
                        st.blocked := st.blocked + 1
                        lastEvent := sideTxt + " blocked: magnet only " + str.tostring(rr, "0.0") + "R away"
                    else
                        float targetPx = na(magnetPx) ? (isBuy ? close + fallbackR * risk : close - fallbackR * risk) : magnetPx
                        if trade.dir == -setupSide
                            f_closeTrade(trade, trade.dir == 1 ? statsL : statsS, close, opens ? "Reverse" : "Exit")
                        if opens and trade.dir == 0
                            trade.dir := setupSide
                            trade.openBar := bar_index
                            trade.entry := close
                            trade.stop := stopPx
                            trade.target := targetPx
                            trade.risk := risk
                            trade.grade := setupGrade
                            trade.lEntry := showTrade ? line.new(bar_index, close, bar_index + 1, close, color = color.new(color.gray, 30), style = line.style_dotted) : na
                            trade.lStop := showTrade ? line.new(bar_index, stopPx, bar_index + 1, stopPx, color = color.new(stopColor, 20)) : na
                            trade.lTarget := showTrade ? line.new(bar_index, targetPx, bar_index + 1, targetPx, color = color.new(targetColor, 20), style = line.style_dashed) : na
                        buySignal := isBuy
                        sellSignal := not isBuy
                        if isBuy
                            lastBuyBar := bar_index
                        else
                            lastSellBar := bar_index
                        string plan = opens ? "\nEntry " + str.tostring(close, format.mintick) + "\nStop " + str.tostring(stopPx, format.mintick) + "\nTarget " + str.tostring(targetPx, format.mintick) + (na(magnetPx) ? " (no magnet: fallback R)" : " (magnet)") + "\nReward:risk " + str.tostring(rr, "0.0") : "\nExit signal only in this trade mode"
                        string tip = sideTxt + " · grade " + setupGrade + "\nScore " + str.tostring(setupScore, "0") + " · P" + str.tostring(setupPct, "0") + " · " + str.tostring(setupFactors) + "/" + str.tostring(nActive) + " factors" + plan
                        if showSignals
                            label.new(bar_index, isBuy ? low : high, sideTxt + " " + setupGrade, yloc = isBuy ? yloc.belowbar : yloc.abovebar, style = isBuy ? label.style_label_up : label.style_label_down, color = isBuy ? buyColor : sellColor, textcolor = color.white, size = size.small, tooltip = tip)
                        alert("EVM " + syminfo.ticker + " " + timeframe.period + " | " + str.replace_all(tip, "\n", " | "), alert.freq_once_per_bar_close)
                        lastEvent := sideTxt + " " + setupGrade + (opens ? " at " + str.tostring(close, format.mintick) : " (exit)")
                    setupSide := 0
 
    // E · Arm a new setup. One setup at a time; no same-side setup while that
    //     side's trade is open.
    if setupSide == 0
        bool canBuy = armedB and trade.dir != 1 and (na(lastBuyBar) or bar_index - lastBuyBar > cooldown)
        bool canSell = armedT and trade.dir != -1 and (na(lastSellBar) or bar_index - lastSellBar > cooldown)
        int side = canBuy and qualB ? 1 : canSell and qualT ? -1 : 0
        if side != 0
            bool isBuy = side == 1
            setupSide := side
            setupBar := bar_index
            setupHigh := high
            setupLow := low
            setupATR := atrNow
            setupExtreme := isBuy ? low : high
            setupScore := isBuy ? scoreB : scoreT
            setupPct := isBuy ? rankB : rankT
            setupFactors := isBuy ? factorsB : factorsT
            setupGrade := f_grade(setupPct, setupFactors, gradeBase)
            if isBuy
                armedB := false
            else
                armedT := false
            buySetup := isBuy
            sellSetup := not isBuy
            lastEvent := isBuy ? "Buy setup" : "Sell setup"
 
    // F · Store this bar's evidence for FUTURE ranks only.
    if botEligible
        f_add(histB, timesB, scoreB, capacity)
    if topEligible
        f_add(histT, timesT, scoreT, capacity)
 
// Learn time-of-day baselines only AFTER this closed bar was scored (VTPE).
if barstate.isconfirmed and useSeason and validVolume
    float alpha = 2.0 / (seasonSamples + 1.0)
    array.set(slotVolumes, slot, na(slotBase) ? v : slotBase + alpha * (v - slotBase))
    array.set(slotCounts, slot, slotCount + 1)
 
// ─────────────────────────────────────────────────────────────────────────────
// CHART MARKERS
// ─────────────────────────────────────────────────────────────────────────────
 
plotshape(showSetups and buySetup, "Buy setup", shape.circle, location.belowbar, color.new(buyColor, 35), size = size.tiny)
plotshape(showSetups and sellSetup, "Sell setup", shape.circle, location.abovebar, color.new(sellColor, 35), size = size.tiny)
plotshape(showFails and buyFail, "Buy setup failed or expired", shape.xcross, location.belowbar, color.new(buyColor, 50), size = size.tiny)
plotshape(showFails and sellFail, "Sell setup failed or expired", shape.xcross, location.abovebar, color.new(sellColor, 50), size = size.tiny)
 
// Historical magnet trace: the target known BEFORE each candle opened.
// Alternate channels so unrelated generations never join.
var int upperGen = 0
var int lowerGen = 0
if newUpper
    upperGen += 1
if newLower
    lowerGen += 1
float upperBefore = upperPrice[1]
float lowerBefore = lowerPrice[1]
plot(showHistory and upperGen[1] % 2 == 0 ? upperBefore : na, "Upper magnet trace A", color.new(buyColor, 40), 2, plot.style_linebr)
plot(showHistory and upperGen[1] % 2 == 1 ? upperBefore : na, "Upper magnet trace B", color.new(buyColor, 40), 2, plot.style_linebr)
plot(showHistory and lowerGen[1] % 2 == 0 ? lowerBefore : na, "Lower magnet trace A", color.new(sellColor, 40), 2, plot.style_linebr)
plot(showHistory and lowerGen[1] % 2 == 1 ? lowerBefore : na, "Lower magnet trace B", color.new(sellColor, 40), 2, plot.style_linebr)
 
// ─────────────────────────────────────────────────────────────────────────────
// DATA WINDOW (values hold at the last closed bar while a candle is open)
// ─────────────────────────────────────────────────────────────────────────────
 
int dwi = barstate.isconfirmed ? 0 : 1
plot(scoreB[dwi], "Buy evidence score", display = display.data_window)
plot(scoreT[dwi], "Sell evidence score", display = display.data_window)
plot(rankB, "Buy evidence percentile", display = display.data_window)
plot(rankT, "Sell evidence percentile", display = display.data_window)
plot(factorsB[dwi], "Buy agreeing factors", display = display.data_window)
plot(factorsT[dwi], "Sell agreeing factors", display = display.data_window)
plot(100 * momB[dwi], "Buy · momentum decay", display = display.data_window)
plot(100 * rejB[dwi], "Buy · rejection / climax", display = display.data_window)
plot(volOK ? 100 * absorbB[dwi] : na, "Buy · absorption", display = display.data_window)
plot(volOK ? 100 * divB[dwi] : na, "Buy · flow divergence", display = display.data_window)
plot(volOK ? 100 * exhB[dwi] : na, "Buy · volume exhaustion", display = display.data_window)
plot(100 * locB[dwi], "Buy · magnet location", display = display.data_window)
plot(100 * momT[dwi], "Sell · momentum decay", display = display.data_window)
plot(100 * rejT[dwi], "Sell · rejection / climax", display = display.data_window)
plot(volOK ? 100 * absorbT[dwi] : na, "Sell · absorption", display = display.data_window)
plot(volOK ? 100 * divT[dwi] : na, "Sell · flow divergence", display = display.data_window)
plot(volOK ? 100 * exhT[dwi] : na, "Sell · volume exhaustion", display = display.data_window)
plot(100 * locT[dwi], "Sell · magnet location", display = display.data_window)
plot(rv[dwi], "Relative volume", display = display.data_window)
plot(pressure[dwi], "Directional pressure (-1 to 1)", display = display.data_window)
plot(volOK ? 1 : 0, "Volume engine on", display = display.data_window)
plot(upperPrice, "Upper magnet target", display = display.data_window)
plot(lowerPrice, "Lower magnet target", display = display.data_window)
plot(trade.dir, "Open trade (1 long, -1 short)", display = display.data_window)
plot(buySignal ? 1 : sellSignal ? -1 : 0, "Signal (1 buy, -1 sell)", display = display.data_window)
plot(buySetup ? 1 : sellSetup ? -1 : 0, "Setup (1 buy, -1 sell)", display = display.data_window)
 
// ─────────────────────────────────────────────────────────────────────────────
// DASHBOARD
// ─────────────────────────────────────────────────────────────────────────────
 
string tablePosition = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Top left" ? position.top_left : position.bottom_left
var table panel = table.new(tablePosition, 3, tableMode == "Full" ? 15 : 6, bgcolor = color.new(#0D1117, 10), border_color = color.new(color.gray, 80), border_width = 1)
 
f_cell(int col, int row, string txt, color c) =>
    table.cell(panel, col, row, txt, text_color = c, text_size = size.small, text_halign = text.align_left)
 
f_evText(float score, float pct, int factors) =>
    str.tostring(score, "0") + " · " + (na(pct) ? "P--" : "P" + str.tostring(pct, "0")) + " · " + str.tostring(factors) + "/" + str.tostring(nActive)
 
f_statText(Stats s) =>
    s.n == 0 ? "No trades yet" : str.tostring(s.n) + " · " + str.tostring(100.0 * s.wins / s.n, "0") + "% win · " + (s.sumR >= 0 ? "+" : "") + str.tostring(s.sumR / s.n, "0.00") + "R avg"
 
f_factorText(float x, bool needsVolume) =>
    needsVolume and not volOK ? "n/a" : str.tostring(100 * x, "0")
 
f_gradeText(Stats s, string g) =>
    g + ": " + (s.n == 0 ? "none" : str.tostring(s.n) + " · " + (s.sumR >= 0 ? "+" : "") + str.tostring(s.sumR / s.n, "0.00") + "R avg")
 
if barstate.islast and tableMode != "Off"
    int ix = barstate.isconfirmed ? 0 : 1
    int need = useVolume ? math.max(priceWarmup, volWarmup) : priceWarmup
    string modeTxt = volOK ? "Volume on" : not useVolume ? "Price-only (off)" : modeKnown ? "Price-only (no volume)" : "Volume warming up"
    string setupTxt = setupSide == 1 ? "Buy setup " + str.tostring(bar_index - setupBar) + "/" + str.tostring(triggerBars) : setupSide == -1 ? "Sell setup " + str.tostring(bar_index - setupBar) + "/" + str.tostring(triggerBars) : ""
    string stateTxt = not calibReady ? "Warming up " + str.tostring(math.min(bar_index, need)) + "/" + str.tostring(need) : samplesB < minSamples and samplesT < minSamples ? "Calibrating " + str.tostring(math.max(samplesB, samplesT)) + "/" + str.tostring(minSamples) : setupTxt != "" ? setupTxt : "Scanning"
    float openR = trade.dir != 0 ? trade.dir * (close - trade.entry) / trade.risk : na
    string tradeTxt = trade.dir == 0 ? "Flat" : (trade.dir == 1 ? "Long " : "Short ") + (openR >= 0 ? "+" : "") + str.tostring(openR, "0.0") + "R open"
 
    f_cell(0, 0, "EVM", color.white)
    f_cell(1, 0, "BUY side", buyColor)
    f_cell(2, 0, "SELL side", sellColor)
    f_cell(0, 1, "Evidence", inkColor)
    f_cell(1, 1, f_evText(scoreB[ix], rankB, factorsB[ix]), buyColor)
    f_cell(2, 1, f_evText(scoreT[ix], rankT, factorsT[ix]), sellColor)
    f_cell(0, 2, "Magnet target", inkColor)
    f_cell(1, 2, na(upperPrice) ? "none" : "▲ " + str.tostring(upperPrice, format.mintick), buyColor)
    f_cell(2, 2, na(lowerPrice) ? "none" : "▼ " + str.tostring(lowerPrice, format.mintick), sellColor)
    f_cell(0, 3, "Results", inkColor)
    f_cell(1, 3, f_statText(statsL), buyColor)
    f_cell(2, 3, f_statText(statsS), sellColor)
    f_cell(0, 4, "State", inkColor)
    f_cell(1, 4, stateTxt, color.white)
    f_cell(2, 4, modeTxt, inkColor)
    f_cell(0, 5, "Trade", inkColor)
    f_cell(1, 5, tradeTxt, trade.dir == 1 ? buyColor : trade.dir == -1 ? sellColor : inkColor)
    f_cell(2, 5, lastEvent, inkColor)
 
    if tableMode == "Full"
        f_cell(0, 6, "Momentum decay", inkColor)
        f_cell(1, 6, f_factorText(momB[ix], false), buyColor)
        f_cell(2, 6, f_factorText(momT[ix], false), sellColor)
        f_cell(0, 7, "Rejection / climax", inkColor)
        f_cell(1, 7, f_factorText(rejB[ix], false), buyColor)
        f_cell(2, 7, f_factorText(rejT[ix], false), sellColor)
        f_cell(0, 8, "Absorption", inkColor)
        f_cell(1, 8, f_factorText(absorbB[ix], true), buyColor)
        f_cell(2, 8, f_factorText(absorbT[ix], true), sellColor)
        f_cell(0, 9, "Flow divergence", inkColor)
        f_cell(1, 9, f_factorText(divB[ix], true), buyColor)
        f_cell(2, 9, f_factorText(divT[ix], true), sellColor)
        f_cell(0, 10, "Volume exhaustion", inkColor)
        f_cell(1, 10, f_factorText(exhB[ix], true), buyColor)
        f_cell(2, 10, f_factorText(exhT[ix], true), sellColor)
        f_cell(0, 11, "Magnet location", inkColor)
        f_cell(1, 11, f_factorText(locB[ix], false), buyColor)
        f_cell(2, 11, f_factorText(locT[ix], false), sellColor)
        f_cell(0, 12, "Samples · blocked", inkColor)
        f_cell(1, 12, str.tostring(samplesB) + " · " + str.tostring(statsL.blocked), buyColor)
        f_cell(2, 12, str.tostring(samplesT) + " · " + str.tostring(statsS.blocked), sellColor)
        f_cell(0, 13, "Results by grade", inkColor)
        f_cell(1, 13, f_gradeText(statsGA, "A"), color.white)
        f_cell(2, 13, f_gradeText(statsGB, "B"), color.white)
        f_cell(0, 14, "In-sample · not odds", inkColor)
        f_cell(1, 14, f_gradeText(statsGC, "C"), color.white)
        f_cell(2, 14, "Grades are unvalidated", inkColor)
 
// ─────────────────────────────────────────────────────────────────────────────
// ALERTS
// "Any alert() function call" sends the full plan: grade, entry, stop, target.
// ─────────────────────────────────────────────────────────────────────────────
 
alertcondition(buySignal, "EVM BUY", "EVM BUY on {{ticker}} {{interval}} at {{close}}")
alertcondition(sellSignal, "EVM SELL", "EVM SELL on {{ticker}} {{interval}} at {{close}}")
alertcondition(buySignal or sellSignal, "EVM any signal", "EVM signal on {{ticker}} {{interval}} at {{close}}")
alertcondition(buySetup, "EVM buy setup", "EVM buy setup on {{ticker}} {{interval}}. Watch for a close above the setup high.")
alertcondition(sellSetup, "EVM sell setup", "EVM sell setup on {{ticker}} {{interval}}. Watch for a close below the setup low.")
alertcondition(targetHit, "EVM target reached", "EVM target reached on {{ticker}} {{interval}}.")
alertcondition(stopHit, "EVM stop reached", "EVM stop reached on {{ticker}} {{interval}}.")

← 返回列表