Phase Exhaustion Reversal [BullByte]

BullByte · study · 777 行 · 点赞 2,436 · TradingView 原页

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

Pine Script

// ═══════════════════════════════════════════════════════════════════════════
//
//                    PHASE EXHAUSTION REVERSAL - PXR
//
// ───────────────────────────────────────────────────────────────────────────
// This source code is subject to the terms of the Mozilla Public License 2.0
// at https://mozilla.org/MPL/2.0/
// © BullByte
// ───────────────────────────────────────────────────────────────────────────
//
// WHAT THIS TOOL DOES
// ───────────────────
// PXR studies a measurable phenomenon: when short-horizon directional
// efficiency spikes far away from the medium-horizon efficiency baseline,
// that spike represents concentrated, transient energy. Such spikes tend
// to exhaust themselves and reconnect with the broader structural gradient.
// PXR identifies the moment that exhaustion completes and visualizes the
// realignment as an observation worth studying.
//
// THE CONCEPT IN PLAIN LANGUAGE
// ─────────────────────────────
// Price has two simultaneous qualities:
//   1. How far it traveled net  → transport
//   2. How much total distance it burned getting there → agitation
// The ratio (transport / agitation) is called efficiency.
//   • Efficiency near 1.0 = clean directional movement
//   • Efficiency near 0.0 = noisy chop with no net progress
//
// PXR computes two efficiencies in parallel:
//   • Short horizon  → reactive, captures bursts
//   • Medium horizon → structural, captures the prevailing gradient
//
// The normalized gap between them (the "Phase Gap") is the key signal.
// When the short horizon burns hard against the medium horizon's
// direction, the gap stretches. When that burst exhausts and the gap
// collapses back toward zero, price tends to realign with the medium
// horizon - the structural gradient reasserts.
//
// MATHEMATICAL BASIS
// ──────────────────
// transport(n)   = close − close[n]
// agitation(n)   = Σ |close[i] − close[i+1]|   for i = 0..n-1
// efficiency(n)  = transport / agitation       (≡ Kaufman Efficiency Ratio)
// phaseGap       = (eff_short − eff_med) / rolling_max(|eff_short − eff_med|)
//
// A realignment signal fires when phaseGap peaks against the medium-horizon
// efficiency sign and then recedes by a meaningful fraction of that peak.
//
// EDUCATIONAL USE
// ───────────────
// This script is built to study efficiency imbalance, phase compression
// and expansion, and structural realignment in intraday markets. It does
// not claim certainty. It visualizes when short-horizon directional energy
// appears spent relative to a broader efficiency trend.
//
// DISCLAIMER
// ──────────
// For educational and analytical use only. This script does not provide
// financial, investment, or trading advice and does not guarantee any
// outcome. Use independent judgment, sound risk control, and full market
// context before acting on any signal. Past observations do not imply
// future results.
//
// EXECUTION MODEL
// ───────────────
// Signal arms on the close of a confirmed bar. Entry executes at the open
// of the next bar. This is an honest, non-repainting workflow - the entry
// price shown on chart matches what a real-time user could have achieved.
//
// ═══════════════════════════════════════════════════════════════════════════
 
//@version=6
indicator("Phase Exhaustion Reversal [BullByte]", shorttitle="PXR[BullByte]", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=50, max_bars_back=2000)
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 1 - INPUTS
// ───────────────────────────────────────────────────────────────────
// All user-controllable parameters live here. Tooltips explain each
// knob in plain language so non-coders can experiment safely.
// ═══════════════════════════════════════════════════════════════════
 
var g_core   = "Core Settings"
var g_risk   = "Risk Settings"
var g_visual = "Visuals"
var g_dash   = "Dashboard"
 
// Auto-scale: if true, Short and Medium horizons recompute per timeframe
// so Short ≈ 35 minutes of bars and Medium ≈ 2 hours of bars.
i_autoScale = input.bool(true,  "Auto-Scale Horizons", group=g_core, tooltip="When ON, Short and Medium horizons auto-adapt per timeframe (Short ≈ 35 min, Medium ≈ 2 hours of bars). Turn OFF to override manually using the two inputs below.")
i_shortLen  = input.int(7,      "Short Horizon",       minval=3,   maxval=60,  group=g_core, tooltip="Bars used to measure short-horizon efficiency. Smaller = more reactive, more noise. Ignored when Auto-Scale is ON.")
i_medLen    = input.int(24,     "Medium Horizon",      minval=8,   maxval=120, group=g_core, tooltip="Bars used to measure structural efficiency gradient. Should span one meaningful intraday cycle. Ignored when Auto-Scale is ON.")
i_gapThresh = input.float(0.58, "Phase Gap Threshold", minval=0.1, maxval=1.0, step=0.01, group=g_core, tooltip="Normalized phase-gap level required for a peak to qualify as exhaustion-grade. Higher = fewer but stronger signals.")
i_cooldown  = input.int(3,      "Cooldown Bars",       minval=1,   maxval=15,  group=g_core, tooltip="Minimum bars between two consecutive signals. Prevents clustering during noisy regimes.")
 
// Risk-management inputs control stop placement and target distances.
i_atrLen    = input.int(14,     "ATR Length",           minval=5,   maxval=30,  group=g_risk, tooltip="ATR window for volatility-based stop floor.")
i_atrFloor  = input.float(1.0,  "ATR Floor Multiplier", minval=0.5, maxval=3.0, step=0.1, group=g_risk, tooltip="Minimum stop distance as a multiple of ATR, so the SL is never crammed inside noise.")
i_tp1R      = input.float(1.2,  "TP1 R-Multiple",       minval=0.5, maxval=5.0, step=0.1, group=g_risk, tooltip="First profit target expressed in R-multiples of the stop distance.")
i_tp2R      = input.float(2.2,  "TP2 R-Multiple",       minval=1.0, maxval=8.0, step=0.1, group=g_risk, tooltip="Final profit target expressed in R-multiples of the stop distance.")
 
// Visual toggles let users declutter the chart.
i_showRibbon = input.bool(true, "Show Regime Ribbon", group=g_visual, tooltip="Background tint showing the current regime: Extended, Compressed, Transitioning, or Neutral.")
i_showTint   = input.bool(true, "Show Active Tint",   group=g_visual, tooltip="Colors bars while a trade is active (green for long, red for short).")
i_showDash   = input.bool(true, "Show Dashboard",     group=g_dash,   tooltip="Top-right dashboard with live engine state.")
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 2 - STATE VARIABLES
// ───────────────────────────────────────────────────────────────────
// Persistent state across bars. `var` keeps a value alive between bar
// updates; without it, every bar would reset to the default.
// ═══════════════════════════════════════════════════════════════════
 
// Trade state
var int    tradeDir        = 0      // 0 = flat, 1 = long, -1 = short
var float  entryPrice      = na
var float  slLevel         = na
var float  tp1Level        = na
var float  tp2Level        = na
var bool   tp1Hit          = false
var bool   tradeActive     = false
 
// Cooldown bookkeeping - when each kind of signal last fired/exited
var int    lastSigBar      = -999
var int    lastOutcomeBar  = -999
var int    lastLongSigBar  = -999
var int    lastShortSigBar = -999
 
// Pending entry: a signal armed but not yet executed (executes at next bar open)
var int    pendingDir      = 0      // 0 = nothing pending, 1 = long, -1 = short
var int    pendingBar      = -1     // bar_index where the signal armed; -1 = none
 
// Dashboard feed values
var string lastSignal      = "-"
var string setupState      = "No Setup"
var string tradeBias       = "-"
 
// Drawing handles - kept so they can be updated/closed on later bars
var line   ln_entry        = na
var line   ln_sl           = na
var line   ln_tp1          = na
var line   ln_tp2          = na
var label  lb_entry        = na
var label  lb_sl           = na
var label  lb_tp1          = na
var label  lb_tp2          = na
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 3 - CORE MATH
// ───────────────────────────────────────────────────────────────────
// The three primitive functions that everything else builds on:
// transport, agitation, and efficiency.
// ═══════════════════════════════════════════════════════════════════
 
// Transport - net displacement over `len` bars.
// Returns na for the first `len` bars where history is not yet built.
f_transport(src, len) =>
    bar_index >= len ? src - src[len] : na
 
// Agitation - total path length traveled over `len` bars.
// Sum of absolute bar-to-bar changes; this is the "energy spent" on the path.
f_agitation(src, len) =>
    float total = na
    if bar_index >= len
        total := 0.0
        for i = 0 to len - 1
            total += math.abs(src[i] - src[i + 1])
    total
 
// Efficiency - directional purity. 1.0 = perfectly straight move, 0.0 = chop.
// Mathematically identical to the Kaufman Efficiency Ratio (signed).
f_efficiency(src, len) =>
    float ag = f_agitation(src, len)
    float tr = f_transport(src, len)
    na(tr) or na(ag) or ag == 0.0 ? 0.0 : tr / ag
 
// Small helpers used to safely close lines and delete labels.
f_closeLine(line ln, int barIdx) =>
    if not na(ln)
        line.set_x2(ln, barIdx)
 
f_delLabel(label lb) =>
    if not na(lb)
        label.delete(lb)
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 4 - TIMEFRAME ADAPTATION
// ───────────────────────────────────────────────────────────────────
// When Auto-Scale is ON, horizon lengths are recomputed so each timeframe
// gets the same physical-time window of analysis.
// ═══════════════════════════════════════════════════════════════════
 
tfMin = timeframe.in_seconds() / 60.0
 
int shortLen = i_shortLen
int medLen   = i_medLen
 
if i_autoScale
    // Target windows: short ≈ 35 minutes, medium ≈ 2 hours
    shortLen := math.max(3, int(math.round(35.0 / tfMin)))
    medLen   := math.max(shortLen + 2, int(math.round(120.0 / tfMin)))
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 5 - PHASE GAP
// ───────────────────────────────────────────────────────────────────
// Compute both efficiencies, take their difference, and normalize so the
// gap is bounded roughly within [-1, +1]. Normalization uses a rolling
// max of the absolute raw gap so the threshold stays meaningful across
// volatility regimes.
// ═══════════════════════════════════════════════════════════════════
 
effShort = f_efficiency(close, shortLen)
effMed   = f_efficiency(close, medLen)
rawGap   = effShort - effMed
 
// Rolling window for normalization, adjusted per timeframe so the lookback
// covers similar physical time on each chart.
int normWindow = 200
if tfMin <= 1
    normWindow := 300
else if tfMin <= 3
    normWindow := 250
else if tfMin <= 5
    normWindow := 200
else if tfMin <= 15
    normWindow := 120
else
    normWindow := 80
 
absRaw   = na(rawGap) ? 0.0 : math.abs(rawGap)
rollMax  = ta.highest(absRaw, normWindow)
denom    = rollMax > 0.0 ? rollMax : 1.0
phaseGap = na(rawGap) ? 0.0 : rawGap / denom
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 6 - REGIME STATE
// ───────────────────────────────────────────────────────────────────
// Classify the current market into one of four regimes. The thresholds
// adapt per timeframe because shorter charts produce more raw efficiency
// turbulence.
// ═══════════════════════════════════════════════════════════════════
 
absGap    = math.abs(phaseGap)
absEffMed = math.abs(effMed)
 
float extThresh  = 0.6
float compThresh = 0.25
float transMult  = 0.9
 
if tfMin <= 1
    extThresh  := 0.5
    compThresh := 0.30
    transMult  := 0.75
else if tfMin <= 3
    extThresh  := 0.55
    compThresh := 0.28
    transMult  := 0.80
else if tfMin <= 5
    extThresh  := 0.6
    compThresh := 0.25
    transMult  := 0.9
else if tfMin <= 15
    extThresh  := 0.45
    compThresh := 0.30
    transMult  := 0.65
else
    extThresh  := 0.40
    compThresh := 0.35
    transMult  := 0.55
 
// Four regimes:
//   EXTENDED      - medium-horizon efficiency is high (clean trend)
//   COMPRESSED    - both efficiencies low (range/chop)
//   TRANSITIONING - phase gap has stretched far, regime is shifting
//   NEUTRAL       - none of the above
string regimeState = "NEUTRAL"
if absEffMed > extThresh
    regimeState := "EXTENDED"
else if absEffMed < compThresh and absGap < 0.4
    regimeState := "COMPRESSED"
else if absGap > i_gapThresh * transMult
    regimeState := "TRANSITIONING"
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 7 - SIGNAL ENGINE
// ───────────────────────────────────────────────────────────────────
// The realignment trigger. The engine watches for a phase-gap peak
// against the medium-horizon trend, then waits for it to recede by a
// meaningful fraction. That recede is the exhaustion confirmation.
// ═══════════════════════════════════════════════════════════════════
 
// Threshold scaling - relax slightly on 15m so signals are still findable
// while staying strict on faster charts.
float tfThreshScale = 1.0
if tfMin <= 15
    tfThreshScale := 0.65
 
// Active threshold depends on current regime - different regimes deserve
// different sensitivities.
float activeThr = i_gapThresh
if regimeState == "EXTENDED"
    activeThr := i_gapThresh * 0.95
else if regimeState == "COMPRESSED"
    activeThr := i_gapThresh * 0.80
else if regimeState == "TRANSITIONING"
    activeThr := i_gapThresh * 0.85
activeThr *= tfThreshScale
 
// Peak-detection window and recede fraction - adapt per timeframe.
int   peakWindow     = 12
float recedeFraction = 0.35
 
if tfMin <= 1
    peakWindow     := 18
    recedeFraction := 0.30
else if tfMin <= 3
    peakWindow     := 14
    recedeFraction := 0.32
else if tfMin <= 5
    peakWindow     := 12
    recedeFraction := 0.35
else if tfMin <= 15
    peakWindow     := 14
    recedeFraction := 0.25
else
    peakWindow     := 8
    recedeFraction := 0.40
 
// Recent extremes of phaseGap inside the peak window
posPeak = ta.highest(phaseGap, peakWindow)
negPeak = ta.lowest(phaseGap, peakWindow)
 
// Did the gap reach an extreme strong enough to qualify?
peakedBull = posPeak > activeThr
peakedBear = negPeak < -activeThr
 
// Has the gap meaningfully receded from that extreme?
recedingBull = phaseGap < posPeak * (1.0 - recedeFraction)
recedingBear = phaseGap > negPeak * (1.0 - recedeFraction)
 
// Trend proxy uses the SIGN of the medium-horizon efficiency.
// This is architecturally consistent with the engine's own math.
trendBull = effMed > 0.0
trendBear = effMed < 0.0
 
// Realignment definition:
//   LONG  realign = short-horizon BEAR burst exhausted against BULL gradient
//   SHORT realign = short-horizon BULL burst exhausted against BEAR gradient
isRealignLong  = peakedBear and recedingBear and trendBull
isRealignShort = peakedBull and recedingBull and trendBear
 
// State machine that fires only once per peak/recede cycle.
// resetTrig clears the latch when both peaks are absent.
var int trigState = 0
 
bool resetTrig = not peakedBull and not peakedBear
bool setLong   = isRealignLong  and trigState != 1
bool setShort  = isRealignShort and trigState != -1
 
trigState := resetTrig ? 0 : setLong ? 1 : setShort ? -1 : trigState
 
// Detect the moment the state machine flips. nz() guards against the
// na value on the very first bar.
crossUp = trigState == 1  and nz(trigState[1], 0) != 1
crossDn = trigState == -1 and nz(trigState[1], 0) != -1
 
// Cooldown: bars between any signals, plus extra cooldown between same-direction signals.
int sameDirMult = tfMin >= 15 ? 2 : 3
 
generalCooldownOk = (bar_index - lastSigBar     >= i_cooldown) and  (bar_index - lastOutcomeBar  >= i_cooldown)
longCooldownOk    =  bar_index - lastLongSigBar  >= i_cooldown * sameDirMult
shortCooldownOk   =  bar_index - lastShortSigBar >= i_cooldown * sameDirMult
 
// Raw signal: state-machine flipped, regime is valid, nothing else is in flight.
sigLong  = crossUp and regimeState != "NEUTRAL" and not tradeActive and pendingDir == 0 and generalCooldownOk and longCooldownOk
sigShort = crossDn and regimeState != "NEUTRAL" and not tradeActive and pendingDir == 0 and generalCooldownOk and shortCooldownOk
 
// Only arm on confirmed (closed) bars - this prevents intra-bar repaint.
armedLong  = sigLong  and barstate.isconfirmed
armedShort = sigShort and barstate.isconfirmed
 
// ATR is needed both for risk and for visual anchoring of the signal label,
// so compute it once here.
atrVal = ta.atr(i_atrLen)
 
// When a signal arms, store the pending direction, mark cooldowns, and
// drop the PHASE EXHAUSTION label at the signal bar - placed outside the
// price extreme so it does not collide with the entry rails drawn later.
if armedLong
    pendingDir      := 1
    pendingBar      := bar_index
    lastSigBar      := bar_index
    lastLongSigBar  := bar_index
    lastSignal      := "BULL"
    bullAnchor = low - atrVal * 2.0
    label.new(bar_index, bullAnchor, "▲ PHASE EXHAUSTION\nRealign Up", color=color.new(#1b5e20, 0), textcolor=color.white, style=label.style_label_up, size=size.normal, yloc=yloc.price, tooltip="Short-horizon bearish burst has exhausted against the bullish medium-horizon gradient. Studied behavior is realignment to the upside. Reference entry at the next bar open.")
 
if armedShort
    pendingDir      := -1
    pendingBar      := bar_index
    lastSigBar      := bar_index
    lastShortSigBar := bar_index
    lastSignal      := "BEAR"
    bearAnchor = high + atrVal * 2.0
    label.new(bar_index, bearAnchor, "▼ PHASE EXHAUSTION\nRealign Down", color=color.new(#b71c1c, 0), textcolor=color.white, style=label.style_label_down, size=size.normal, yloc=yloc.price, tooltip="Short-horizon bullish burst has exhausted against the bearish medium-horizon gradient. Studied behavior is realignment to the downside. Reference entry at the next bar open.")
 
// Safety reset: if a pending signal never executed within 2 bars, clear the pending state.
// Prevents the indicator from getting permanently stuck with no new signals on replay edges.
if pendingDir != 0 and pendingBar >= 0 and bar_index > pendingBar + 2
    pendingDir := 0
    pendingBar := -1
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 8 - RISK ENGINE
// ───────────────────────────────────────────────────────────────────
// Stop-loss is the worse (further) of:
//   • A structural swing high/low with an ATR buffer
//   • An ATR-floored distance from entry
// This guarantees the stop is never inside noise.
// ═══════════════════════════════════════════════════════════════════
 
f_swingLow(lb) =>
    float sl = low[1]
    for i = 2 to lb
        sl := math.min(sl, low[i])
    sl
 
f_swingHigh(lb) =>
    float sh = high[1]
    for i = 2 to lb
        sh := math.max(sh, high[i])
    sh
 
// Swing lookback adapts to timeframe so the structural stop is always meaningful.
// Faster charts need more bars to capture an equivalent price structure window.
int swingLB = tfMin <= 1 ? 20 : tfMin <= 3 ? 15 : tfMin <= 5 ? 12 : tfMin <= 15 ? 10 : 8
 
f_slLong(entryP) =>
    structural = f_swingLow(swingLB) - atrVal * 0.25
    atrFloor   = entryP - atrVal * i_atrFloor
    math.min(structural, atrFloor)
 
f_slShort(entryP) =>
    structural = f_swingHigh(swingLB) + atrVal * 0.25
    atrFloor   = entryP + atrVal * i_atrFloor
    math.max(structural, atrFloor)
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 9 - ENTRY EXECUTION
// ───────────────────────────────────────────────────────────────────
// One bar after the signal arms, execute the entry at the open of this
// new bar. Draw entry, stop, and two target rails plus their labels.
// ═══════════════════════════════════════════════════════════════════
 
executeLong  = pendingDir == 1  and pendingBar >= 0 and bar_index == pendingBar + 1
executeShort = pendingDir == -1 and pendingBar >= 0 and bar_index == pendingBar + 1
 
if executeLong or executeShort
    isLong     = executeLong
    tradeDir   := isLong ? 1 : -1
    entryPrice := open
    slLevel    := isLong ? f_slLong(open) : f_slShort(open)
 
    // Guard against a near-zero stop distance (very rare structural collapse).
    float slDist = math.abs(entryPrice - slLevel)
    if slDist < atrVal * 0.1
        slDist := atrVal * i_atrFloor
 
    tp1Level    := isLong ? entryPrice + slDist * i_tp1R : entryPrice - slDist * i_tp1R
    tp2Level    := isLong ? entryPrice + slDist * i_tp2R : entryPrice - slDist * i_tp2R
    tradeActive := true
    tp1Hit      := false
    pendingDir  := 0
    pendingBar  := -1
 
    // Horizontal rails - these extend forward bar-by-bar in Section 10.
    ln_entry := line.new(bar_index, entryPrice, bar_index, entryPrice, color=color.new(#90a4ae, 0), width=1, style=line.style_dashed)
    ln_sl    := line.new(bar_index, slLevel,    bar_index, slLevel,    color=color.new(#c62828, 0), width=2, style=line.style_solid)
    ln_tp1   := line.new(bar_index, tp1Level,   bar_index, tp1Level,   color=color.new(#00897b, 0), width=2, style=line.style_solid)
    ln_tp2   := line.new(bar_index, tp2Level,   bar_index, tp2Level,   color=color.new(#00bfa5, 0), width=3, style=line.style_solid)
 
    // Rail text strings
    entryTxt  = "ENTRY  "        + str.tostring(entryPrice, format.mintick) + "  |  " + (isLong ? "REALIGN UP" : "REALIGN DOWN")
    slTxt     = "INVALIDATION  " + str.tostring(slLevel,    format.mintick)
    tp1Txt    = "TARGET 1  "     + str.tostring(tp1Level,   format.mintick) + "  |  " + str.tostring(i_tp1R) + "R"
    tp2Txt    = "TARGET 2  "     + str.tostring(tp2Level,   format.mintick) + "  |  " + str.tostring(i_tp2R) + "R"
 
    // Rail tooltips
    entryTip  = "Reference entry level marked at the open of this bar, one bar after the signal armed."
    slTip     = "Invalidation level. If price reaches this, the realignment thesis is rejected."
    tp1Tip    = "First profit objective at " + str.tostring(i_tp1R) + " R from entry."
    tp2Tip    = "Final profit objective at " + str.tostring(i_tp2R) + " R from entry."
 
    lb_entry := label.new(bar_index, entryPrice, entryTxt, color=color.new(#1565c0, 0), textcolor=color.white, style=label.style_label_left, size=size.small, tooltip=entryTip)
    lb_sl    := label.new(bar_index, slLevel,    slTxt,    color=color.new(#c62828, 0), textcolor=color.white, style=label.style_label_left, size=size.small, tooltip=slTip)
    lb_tp1   := label.new(bar_index, tp1Level,   tp1Txt,   color=color.new(#00695c, 0), textcolor=color.white, style=label.style_label_left, size=size.small, tooltip=tp1Tip)
    lb_tp2   := label.new(bar_index, tp2Level,   tp2Txt,   color=color.new(#00897b, 0), textcolor=color.white, style=label.style_label_left, size=size.small, tooltip=tp2Tip)
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 10 - TRADE MANAGEMENT
// ───────────────────────────────────────────────────────────────────
// While a trade is active:
//   • Slide the four rail labels forward so they stay near current price.
//   • Extend the four rail lines forward to the current bar.
//   • Check for TP/SL events and close the trade cleanly when one fires.
// ═══════════════════════════════════════════════════════════════════
 
if tradeActive
    // Trail rail labels three bars ahead of the live bar.
    int labelTrail = bar_index + 3
    if not na(lb_entry)
        label.set_x(lb_entry, labelTrail)
    if not na(lb_sl)
        label.set_x(lb_sl, labelTrail)
    if not na(lb_tp1)
        label.set_x(lb_tp1, labelTrail)
    if not na(lb_tp2)
        label.set_x(lb_tp2, labelTrail)
 
    // Extend rail lines to the current bar.
    if not na(ln_entry)
        line.set_x2(ln_entry, bar_index)
    if not na(ln_sl)
        line.set_x2(ln_sl, bar_index)
    if not na(ln_tp1)
        line.set_x2(ln_tp1, bar_index)
    if not na(ln_tp2)
        line.set_x2(ln_tp2, bar_index)
 
    // ── Long-trade management ────────────────────────────────────────
    if tradeDir == 1
        if not tp1Hit and high >= tp1Level
            tp1Hit := true
 
        // Ambiguous bar: both SL and TP2 touched on the same bar - close conservatively.
        longAmbiguous = low <= slLevel and high >= tp2Level
 
        if longAmbiguous
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
        else if high >= tp2Level
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
        else if low <= slLevel
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
 
    // ── Short-trade management ───────────────────────────────────────
    if tradeDir == -1
        if not tp1Hit and low <= tp1Level
            tp1Hit := true
 
        shortAmbiguous = high >= slLevel and low <= tp2Level
 
        if shortAmbiguous
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
        else if low <= tp2Level
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
        else if high >= slLevel
            tradeActive    := false
            tradeDir       := 0
            lastOutcomeBar := bar_index
            f_closeLine(ln_entry, bar_index)
            f_closeLine(ln_sl,    bar_index)
            f_closeLine(ln_tp1,   bar_index)
            f_closeLine(ln_tp2,   bar_index)
            f_delLabel(lb_entry)
            lb_entry := na
            f_delLabel(lb_sl)
            lb_sl := na
            f_delLabel(lb_tp1)
            lb_tp1 := na
            f_delLabel(lb_tp2)
            lb_tp2 := na
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 11 - STATE FEED
// ───────────────────────────────────────────────────────────────────
// Compute the live values shown in the top-right dashboard.
// ═══════════════════════════════════════════════════════════════════
 
// Bias = sign of medium-horizon efficiency, lightly thresholded for stability.
if effMed > compThresh
    tradeBias := "BULL"
else if effMed < -compThresh
    tradeBias := "BEAR"
else
    tradeBias := "-"
 
// Setup progress states
if tradeActive
    setupState := "TRIGGERED"
else if pendingDir != 0
    setupState := "ARMED"
else if absGap > i_gapThresh * 0.85
    setupState := "WATCHING"
else if absGap > i_gapThresh * 0.60
    setupState := "FORMING"
else
    setupState := "No Setup"
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 12 - REGIME RIBBON
// ───────────────────────────────────────────────────────────────────
// Background tint indicating current regime. Helps users see at a
// glance whether the market is trending, ranging, or in transition.
// ═══════════════════════════════════════════════════════════════════
 
color ribbonColor = color.new(#90a4ae, 94)
if regimeState == "EXTENDED"
    ribbonColor := color.new(#ef5350, 88)
else if regimeState == "COMPRESSED"
    ribbonColor := color.new(#ffa726, 88)
else if regimeState == "TRANSITIONING"
    ribbonColor := color.new(#00e5ff, 82)
 
bgcolor(i_showRibbon ? ribbonColor : na, title="Regime Ribbon")
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 13 - ACTIVE TINT
// ───────────────────────────────────────────────────────────────────
// Colors bars while a trade is active - green for long, red for short.
// ═══════════════════════════════════════════════════════════════════
 
color tintColor = na
if i_showTint and tradeActive
    tintColor := tradeDir == 1 ? color.new(#26a69a, 82) : color.new(#ef5350, 82)
 
barcolor(tintColor, title="Active Tint")
 
 
// ═══════════════════════════════════════════════════════════════════
// SECTION 14 - DASHBOARD
// ───────────────────────────────────────────────────────────────────
// Compact 2-column dashboard at top-right showing engine state.
// Color helpers translate string states into clean color codes.
// ═══════════════════════════════════════════════════════════════════
 
var table dash = table.new(position.top_right, 2, 6, bgcolor=color.new(#0d1117, 10), border_color=color.new(#30363d, 60), border_width=1, frame_color=color.new(#00e5ff, 40), frame_width=1)
 
f_stateColor(st) =>
    color c = color.new(#90a4ae, 0)
    if st == "EXTENDED"
        c := color.new(#ef5350, 0)
    else if st == "COMPRESSED"
        c := color.new(#ffa726, 0)
    else if st == "TRANSITIONING"
        c := color.new(#00e5ff, 0)
    c
 
f_setupColor(su) =>
    color c = color.new(#546e7a, 0)
    if su == "ARMED"
        c := color.new(#00e5ff, 0)
    else if su == "WATCHING"
        c := color.new(#b0bec5, 0)
    else if su == "FORMING"
        c := color.new(#ffa726, 0)
    else if su == "TRIGGERED"
        c := color.new(#26a69a, 0)
    c
 
f_biasColor(b) =>
    color c = color.new(#546e7a, 0)
    if b == "BULL"
        c := color.new(#26a69a, 0)
    else if b == "BEAR"
        c := color.new(#ef5350, 0)
    c
 
f_lastColor(l) =>
    color c = color.new(#546e7a, 0)
    if l == "BULL"
        c := color.new(#26a69a, 0)
    else if l == "BEAR"
        c := color.new(#ef5350, 0)
    c
 
if i_showDash and barstate.islast
    phaseGapDisp = na(phaseGap) ? "-" : str.tostring(phaseGap, "#.##")
    gapColor     = math.abs(phaseGap) > i_gapThresh ? color.new(#00e5ff, 0) : color.new(#546e7a, 0)
 
    table.cell(dash, 0, 0, "PXR ENGINE", text_color=color.new(#00e5ff, 0), bgcolor=color.new(#161b22, 20), text_size=size.small)
    table.cell(dash, 1, 0, "LIVE",        text_color=color.new(#00e5ff, 0), bgcolor=color.new(#161b22, 20), text_size=size.small)
 
    table.cell(dash, 0, 1, "State",       text_color=color.new(#8b949e, 0), text_size=size.small, bgcolor=color.new(#0d1117, 20), tooltip="Current regime classification from medium-horizon efficiency and phase gap.")
    table.cell(dash, 1, 1, regimeState,   text_color=f_stateColor(regimeState), text_size=size.small, bgcolor=color.new(#0d1117, 20))
 
    table.cell(dash, 0, 2, "Setup",       text_color=color.new(#8b949e, 0), text_size=size.small, bgcolor=color.new(#0d1117, 20), tooltip="Realignment setup progress: Forming → Armed → Triggered.")
    table.cell(dash, 1, 2, setupState,    text_color=f_setupColor(setupState), text_size=size.small, bgcolor=color.new(#0d1117, 20))
 
    table.cell(dash, 0, 3, "Bias",        text_color=color.new(#8b949e, 0), text_size=size.small, bgcolor=color.new(#0d1117, 20), tooltip="Direction of the medium-horizon efficiency gradient.")
    table.cell(dash, 1, 3, tradeBias,     text_color=f_biasColor(tradeBias), text_size=size.small, bgcolor=color.new(#0d1117, 20))
 
    table.cell(dash, 0, 4, "Phase Gap",   text_color=color.new(#8b949e, 0), text_size=size.small, bgcolor=color.new(#0d1117, 20), tooltip="Normalized dislocation between short and medium horizon efficiency.")
    table.cell(dash, 1, 4, phaseGapDisp,  text_color=gapColor, text_size=size.small, bgcolor=color.new(#0d1117, 20))
 
    table.cell(dash, 0, 5, "Last",        text_color=color.new(#8b949e, 0), text_size=size.small, bgcolor=color.new(#161b22, 20), tooltip="Most recent realignment direction triggered.")
    table.cell(dash, 1, 5, lastSignal,    text_color=f_lastColor(lastSignal), text_size=size.small, bgcolor=color.new(#161b22, 20))

← 返回列表