OPEN-SOURCE SCRIPT
Aktualisiert

Multi-Factor Reversal Confluence All-in-One

552
█ OVERVIEW

Multi-Factor Reversal Confluence is a single decision object that looks for exhaustion-and-turn REVERSALS by making five orthogonal detectors agree through one staged lifecycle — WATCH → ARMED → EXTREME → CONFIRMED — filtering every call through two gates, and then grading its own conviction against how those calls have actually resolved on THIS chart. Two things its category usually skips: gating (a trend-defense that will not fade a series with no equilibrium to revert to, and a turbulence veto that will not fade an active, intensifying volatility cascade — the two dominant ways reversal tools get run over), and honest self-calibration (conviction is mapped to a probability by a non-parametric isotonic fit of predicted→realized, and the "proven" badge uses an out-of-sample, uniqueness-weighted, multiple-testing-deflated Wilson lower bound versus a matched base rate — so a thin or edgeless sample says so plainly). Everything is computed internally from price and volume; there is no input.source wiring, no external symbol, and no request.security.

█ HOW IT WORKS

Five independent signals, each on a 0–100 signed scale (+ = bottom / − = top), each naming its method:

1. INSTABILITY (prior) — a Wasserstein-1 (earth-mover) distance between the most recent window of returns and the window before it (matched sorted order-statistics), volatility-normalized and ranked as a percentile of its own history. A rising distance = the return distribution is changing shape — variance, skew OR tail — i.e. a system losing stability and a reversal PRIOR. Shape-complete (it catches a fattening tail that a moment-by-moment read misses) and direction is set opposite the prevailing drift.
2. CHANGEPOINT (trigger) — a Student-t Bayesian Online Changepoint Detector (run-length posterior with a hazard prior) plus a CUSUM mean/variance break, resolved into a drift-turn direction. This is the TRIGGER that a regime actually broke.
3. EXHAUSTION (gate) — a real trend (efficiency ratio above a floor over the slow horizon) whose fast efficiency is now COLLAPSING while price is stretched (displacement percentile), optionally boosted by absorption (high volume, little progress) and a panic-range read. The GATE that the move is spent.
4. CLIMAX (extreme) — a volume-z (time-of-day-normalized on intraday), an expansion-range-z, a close-rejection wick and an order-flow delta from Bulk-Volume Classification (buy fraction = the normal CDF of the standardized return — a principled signed delta, not a close-location proxy). The composite must clear its own conformal online (1−α) quantile, so "extreme" means a calibrated ~α-rare event on this symbol; a secondary-test state machine then only confirms once a lower-volume retest holds the extreme.
5. STRUCTURE (confirm) — a liquidity sweep of a confirmed swing pivot followed by a displacement break back through it (≥ a × ATR), which also sets the stop. The CONFIRM.

Mean-reversion / regime gate (the trend-defense) — every fire is filtered by how mean-reverting the tape is right now, on a 0–1 scale from two orthogonal reads: the reversion-trust correlation (the rolling correlation of prior deviation-from-mean with the NEXT return — strongly negative means price is actively reverting) and a Lo-MacKinlay variance ratio (VR(q) < 1 = mean-reverting, ≈ 1 = random walk, > 1 = trending). An optional Dickey-Fuller unit-root test adds a formal stationarity requirement. The gate scales conviction and, below a floor, blocks the fire outright — so the engine does not fade a trend, the single largest source of false tops and bottoms.

Turbulence gate (the falling-knife defense) — large moves are treated as a point process and their Fano factor (variance/mean of the shock count) gives a self-exciting Hawkes branching ratio on a 0–1 scale. When that ratio is high AND still rising, the move is self-feeding — so conviction is scaled down and, below a floor, the fire is blocked. It stops the engine from fading an accelerating cascade, and it releases as the cascade rolls over. The two gates multiply into one combined guard shown on the dashboard.

Lifecycle & fusion — the engine ARMs only when at least N of the five agree on a direction, each above its own threshold, within an expiry window; climax promotes it to EXTREME, a structure break to CONFIRMED (the default actionable tier). Conviction fuses the supporting signals correlation-aware: the instability and changepoint pair is down-weighted by their measured rolling correlation (a Kish-style redundancy discount) so two views of the same thing don't double-count, then scaled by the mean-reversion gate.

Location (absorption shelf) — the five signals answer "is a turn forming?" but not "where?". A built-in occupation-time (dwell) profile answers that internally, with nothing to wire: a fixed-tick price grid accumulates how long price has dwelt at each level (a reversible ring buffer that adds the entering bar and subtracts the bar leaving the window), and the nearest bin whose dwell is a high fraction of the busiest bin — below and above price — is the support / resistance shelf. A reversal that fires AT a shelf on the correct side earns a bounded conviction boost. It is self-contained (no request.security). Optionally, set Location to "External link" instead and wire the four source inputs to a published Absorption Shelf's EXP_ outputs to use that fuller engine.

Calibration — every actionable fire is resolved a fixed horizon later against a ± target (× ATR): did price reach the target in the signalled direction? Raw conviction is mapped to a probability by a beta warm-start that hands over to a non-parametric ISOTONIC (Pool-Adjacent-Violators) fit of predicted→realized once enough outcomes resolve, and is shrunk toward 50% until the sample is sufficient — so a shown 70% actually resolves ~70% on this symbol. Bottom and top hit-rates are tracked separately, each with a Wilson lower bound, versus a direction-matched unconditional base rate. The "proven" badge is deliberately strict: it uses an out-of-sample slice, weights overlapping fires by their uniqueness (effective-N, not raw n), and raises the Wilson z (Bonferroni-style) for the several signals and two sides being tested; a Net-R after cost is shown so the edge reflects something tradeable, not gross.

█ HOW TO USE

Read the dashboard top-down: the STATE (WATCH / ARMED / EXTREME / CONFIRMED) and the direction, then the calibrated conviction (a ✓ means the edge is proven out-of-sample), then the combined gate, then the stop. The gate row (regime·turbulence) is the defense layer: "reverting" means fades are in-context, "trend/random" or "cascade!" means the engine is holding back. Pro adds a Flow · turbulence row (signed BVC order-flow delta and the branching ratio) and a Location row (shelf status). Choose your actionable tier (Armed / Extreme / Confirmed) in the inputs — the default is Confirmed, which fires only after the structure break for the fewest, highest-precision signals; Extreme and Armed are earlier and noisier. A diamond marks a confirmed fire (it brightens with conviction and dims while the sample is still learning); a small triangle marks the earlier EXTREME stage. On a confirmed fire the tool draws the Entry, Stop and two targets (TP1/TP2 at R-multiples of the stop) as labelled lines, and a tag at the arrow showing direction and calibrated conviction. A faint grey wash means the engine is standing aside (a trend/random regime or an active cascade) — that is the gates working, not a fault. A small on-chart legend explains the marks; all of these visuals are toggle-able in the Chart-visuals inputs. The calibration is the honest layer: until the sample clears the minimum it reads "learning", and it shows each side's Wilson-bounded hit-rate against its base rate rather than a bare number — a low or below-base read is information, not a malfunction. The structure signal confirms a swing-length number of bars AFTER the pivot by design, so treat it as confirmation, not a pivot-bar entry. Switch Dashboard detail to Pro for the raw conviction, the per-side hit-rate table, the out-of-sample edge with Net-R and effective-N, and the per-engine peak-strength diagnostic. Needs volume — run it on a volume-bearing symbol (index futures work well). Horizon and sizing are yours; it places no orders.

█ INPUTS

1 · Instability — returns window for the Wasserstein distributional-shift, drift lookback.
2 · Changepoint — observation window, z winsorise, hazard, Student-t d.o.f., prior pseudo-count, P(change) fire threshold, emerging-drift lookback.
3 · Exhaustion — ER fast / slow, trend floor, displacement lookback, stretch percentile, absorption + panic boost.
4 · Climax — volume/range baseline, volume-z and range-z thresholds, time-of-day normalization + rate, close-rejection threshold, CVD window, secondary-test window and retest-volume fraction, BVC order-flow delta toggle, conformal "extreme" rarity (α and adaptation rate).
5 · Structure — swing length, break displacement (× ATR), sweep→break window.
6 · Fusion & lifecycle — per-stage thresholds, minimum agreeing signals to ARM, expiry window, actionable tier (default Confirmed), the P1↔P2 redundancy factor and data-driven decorrelation window.
7 · Calibration — resolve horizon, target move (× ATR), minimum sample, beta rate, isotonic recalibration, warm-up shrink samples, in-sample fraction, proven-z (deflated), round-trip cost.
9 · Mean-reversion gate — require a mean-reverting regime, reversion-trust window, variance-ratio window and q, block-fire floor, optional Dickey-Fuller stationarity with its window and critical t.
10 · Turbulence gate — veto fades during a volatility cascade, shock threshold (× σ), shock sub-window, Fano window, cascade level to start vetoing, veto strength, block-fire floor.
11 · Location (absorption shelf) — enable; shelf source (Internal built-in dwell profile, default / External link); internal dwell lookback, bin size (× ATR) and hot-shelf fraction; the four external sources (used only in External mode); near-shelf tolerance (× ATR), absorbing-strength threshold, conviction multiplier at a confirmed shelf.
12 · Chart visuals — trade-level overlay (TP1/TP2 R-multiples, level length), signal label, conviction-graded markers, stand-aside tint, on-chart legend and position, draw linked shelf.
13 · Style — theme (Dark / Light), Bottom / Top colours, background tint, markers, dashboard show and detail (Compact default / Pro).

█ HONESTY & LIMITATIONS

This is a study, not a strategy. The conviction and hit-rates are descriptive statistics on visible history with no execution costs — not a backtest and not a probability your next trade works; the out-of-sample slice and Net-R make the "proven" badge stricter but it remains an in-sample-history read. Volume-derived signals (climax, CVD, absorption) need real volume and abstain or weaken on symbols without it. Non-repaint by construction: all five signals resolve on confirmed values, the structure signal uses swing pivots that confirm several bars late (a deliberate lag, not a repaint), the mean-reversion gate, the turbulence gate, the conformal quantile, the state machine and the calibration read only committed bars, and the isotonic map / out-of-sample statistics are built once per bar for display and never feed the fire — set alerts to "Once Per Bar Close". The optional Dickey-Fuller gate runs a windowed regression loop; leave it off (default) if you want the lightest compute. When the sample is small the calibration shrinks toward 50% and reads "learning", and a hit-rate below its base rate is shown honestly rather than hidden. No edge shown = honest, not broken.

█ ORIGINALITY

One coherent reversal object, not five indicators stacked. The original contribution is the staged lifecycle in which five DIFFERENT statistical lenses (Wasserstein distributional-shift, Bayesian changepoint, efficiency exhaustion, a conformal-rare volume/BVC climax, and liquidity-sweep structure) must agree in sequence, all filtered by two orthogonal gates — a mean-reversion regime gate so the engine refuses to fade a trend, and a Hawkes self-excitation gate so it refuses to fade an accelerating cascade — fused with an explicit redundancy discount so correlated views don't double-count, and — the part most reversal tools omit — a conviction that is isotonically calibrated to the chart's own resolved outcomes and gated by an out-of-sample, uniqueness-weighted, multiple-testing-deflated Wilson lower bound against a matched base rate. Each detector exists only to feed that single verdict and its stop; none is presented as a standalone signal. It carries a compact built-in occupation-time shelf for price-location confirmation (or can consume an external Absorption-Shelf's exports), keeping it one self-contained tool. Every block was written from scratch.

█ CREDITS

Bayesian Online Changepoint Detection — Adams & MacKay (2007); Student-t predictive. CUSUM — Page (1954). Wasserstein-1 / optimal transport (earth-mover distance) — Kantorovich. Variance ratio — Lo & MacKinlay (1988). Unit-root test — Dickey & Fuller (1979); Ornstein-Uhlenbeck. Efficiency ratio — Kaufman. Bulk-Volume Classification / VPIN order-flow — Easley, López de Prado & O'Hara. Self-exciting branching processes (Fano factor) — Hawkes (1971). Conformal / adaptive online quantiles — Vovk; Angelopoulos, Candès & Tibshirani. Cumulative Volume Delta / effort-vs-result absorption — order-flow literature. Liquidity sweep & displacement — order-flow / market-structure practice. Beta / logistic calibration — Platt (1999); Kull, Silva Filho & Flach. Isotonic regression / Pool-Adjacent-Violators — Ayer et al. (1955). Uniqueness weighting & two-barrier forward test — López de Prado. Design-effect / effective sample — Kish (1965). Wilson score interval — Wilson (1927). Code written from scratch; no external script reused.

This script is for analysis and education. It is not financial advice.
Versionshinweise
What this update adds

The original indicator was a measure-first reversal engine: five orthogonal detectors (instability, change-point, exhaustion, climax, structure) feed one staged lifecycle, fuse correlation-aware, and calibrate their conviction to this symbol's own resolved outcomes — every statistic shown with its sample size, a Wilson lower bound and a matched base rate. That core is unchanged.

This update keeps that reversal engine intact and adds three things around it, so the tool now covers both sides of intraday behaviour and reads cleanly at a glance.

1 · A regime-adaptive continuation engine. A reversal engine is, by design, quiet in a trend. This update adds a second signal system that rides the trend when the tape is trending and steps aside otherwise — so the chart is no longer blank in the market you are actually trading. The ride direction is set by a selectable trigger:

Custom DEMA — fast/slow DEMA cross on the chart timeframe (default; best-measured).
Williams Alligator — the 5/8/13 jaw-teeth-lips; trades only when the lines fan out (awake), stays flat while it sleeps (range).
100-DEMA cross — the chart 100-DEMA crossing the nearest higher-timeframe 100-DEMA (1m over 2m, etc.), ladder-relative across timeframes.

Entry timing is also selectable — enter on the pullback-resume (cleanest), 1–2 bars early, or on the cross itself — and every ride is forward-tested on the same honest basis as the reversals, so the dashboard tells you which trigger/timing actually works on your symbol and timeframe.

2 · A live options context layer. Direction alone does not pay for an option — the move must beat premium decay in the right volatility regime. Because India VIX is end-of-day on the feed, volatility is read live from the chart's own OHLC (a range-based Rogers-Satchell realised vol) as a self-calibrating regime percentile plus slope, combined with a 1σ expected move vs cost check. Each signal carries a one-glance verdict — ⚡ favorable · ⚡? caution · ⚡✕ avoid — with theta caution flagged late in the session and on weekly expiry (Tuesday). An optional filter shows only option-tradeable setups.

3 · A two-system visual language + drawn trade levels. Shape now means signal type, colour means direction: REVERSAL = diamonds (confirmed) + circles (forming); CONTINUATION = triangles (ride). Both systems draw a complete, risk-defined trade — Entry / Stop / TP1 / TP2 with price tags — and carry a rich single-alert() payload for journaling or automation.

Still true to the engine

Non-repainting — higher-timeframe reads use lookahead_off; detectors and forward-tests resolve only on confirmed bars. Measure-first calibration (beta warm-start → isotonic PAV, shrunk until the sample earns it) is unchanged, and both the reversal and the continuation systems report their forward-tested hit-rate with a Wilson lower bound versus a matched base rate — when there is no measurable edge, the dashboard says so plainly.

Runs on a volume instrument (e.g. NSE:NIFTY1!); for a volume-less spot chart (a cash index or spot FX), a Volume source setting borrows volume from the matching futures so the flow detectors keep working — price stays from the chart. Every default is set for NIFTY; from Settings the tool adapts to any asset (volume source, and an ATR-scaled expected-move option). Engineered for performance: zero per-bar array allocation in steady state, security calls well within budget. Study/education tool — not financial advice, not a signal service.

Dashboard, in one line

Lifecycle state · direction · calibrated conviction · regime/turbulence gate · stop · grade/size/alignment · Mode (reversal vs ride) · Ride hit% · Vol regime · Options verdict — with a Pro view adding the per-detector support, forward-tested hit-rates, out-of-sample edge and Net-R after cost.

Educational tool for context and study. OHLCV-based estimates, not the true tape. Not financial advice, not a signal service. Past behaviour does not predict future results.
Versionshinweise
Multi-Factor Reversal Confluence — All-in-One → v3.9 (cumulative over v3.8)

v3.9 completes the upgrade with a library-consolidation pass: three pieces of inlined math now come from the shared suite libraries, so this engine's definitions match the rest of the suite. Each replacement was verified formula-identical before swapping, so there is no numerical change — the detectors, gates, lifecycle and honest statistics behave exactly as before; the code just stops duplicating math the libraries already own.

Consolidated

Efficiency ratio → cal.efficiencyRatio (ml_calib). Identical to the old inline f_er (ta.change(s) ≡ s−s[1], same path sum), so the exhaustion detector is bit-for-bit unchanged.
LTF signed order flow → flow.signedVolLTF (ml_flow). Identical buy/sell classification (close > open = buy, close < open = sell) and nz handling; the hand-written sub-bar loop is removed.
Weighted Wilson lower bound → cal.wilsonLo (ml_calib) at the two call sites. Same Wilson formula; the library clamps a negative bound to 0 (correct for a proportion) and returns a percent, so the call sites divide by 100 to keep their 0–1 scale. The PROVEN badge is bit-identical (a negative lower bound never beats the base rate either way).

Kept inline (on purpose). The BVC normal-CDF split and the time-of-day volume EMA baseline have no exact library equivalent, so they were left untouched rather than forced into a near-match that would drift behaviour.

Also in this version (from v3.8). Initial-Balance location boost (ml_session), optional triangular climax split, and RS-leadership intermarket (ml_rs) — all opt-in, measure-first, NIFTY-default.

Imports: ml_session/2 · ml_rs/1 · ml_flow/2 · ml_calib/2. The two new libraries add no security calls (pure math), so the call budget is unchanged. Defaults remain NIFTY; the dashboard keeps Pro/Compact with Compact as the default.

Study/indicator for analysis and education — NOT financial advice, NOT a signal service. Any edge figure shown is in-sample descriptive statistics on visible history, not a backtest or a promise about the fu

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.