STRAT Trap & VWAP Engine [WillyAlgoTrader]📊 STRAT Trap & VWAP Engine is an overlay toolkit that reads every candle through the lens of The STRAT methodology, detects failed-breakout "trap" candles, and turns them into fully managed trade plans — entry, structural stop, three R-multiple targets, break-even automation and webhook alerts — filtered by a volatility regime engine and accompanied by a pivot-anchored VWAP trail.
The core insight: the most information-dense candle on any chart is the one that breaks a prior extreme and then closes against its own break. The market went hunting for liquidity, found it, and failed to follow through. This indicator classifies every bar the STRAT way, catches exactly those divergence candles, and manages the resulting trade for you — while a regime filter keeps you out of chop and an anchored VWAP shows where the volume-weighted crowd is positioned inside the current trend leg.
Works on all markets (crypto, forex, stocks, indices, futures) and all timeframes.
📚 THE STRAT IN 60 SECONDS (for beginners)
The STRAT is a price-action methodology popularized by veteran floor trader Rob Smith. Its power is its simplicity: every candle on every chart is one of only three types, defined purely by its relationship to the previous candle's range:
— 1 (Inside bar) : the candle's entire range fits inside the previous candle (high <= prior high AND low >= prior low). The market is in equilibrium — nobody won.
— 2 (Directional bar) : the candle breaks ONE side of the previous candle. 2U breaks the prior high only; 2D breaks the prior low only. One side won.
— 3 (Outside bar) : the candle breaks BOTH sides (high > prior high AND low < prior low). Maximum disagreement — both sides were swept.
Sequences of these numbers form repeatable patterns. A 2D-2U is a reversal (sellers pushed down, buyers answered). A 2-1-2 is a pause-and-go. A 3-1-2 is compression after chaos resolving into direction. Because the classification is purely mechanical, there is zero subjectivity — two traders looking at the same chart will always count the same sequence.
The second pillar of The STRAT is Full Timeframe Continuity (FTC) : checking whether the higher timeframes (hourly, daily, weekly, monthly) are all trading in the same direction as your entry. When the 15-minute, hourly and daily candles are all green, a long is swimming with the current, not against it.
This indicator automates all of it — and then adds the twist that gives it its name.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A STRAT pattern tells you a structure formed — but not whether the breakout that follows is genuine. A trap detector spots failed breakouts — but without structural context it fires in the middle of chop. A regime filter knows trend from range — but generates no entries by itself. A VWAP shows positioning — but a session VWAP resets at midnight regardless of what the trend is doing. None of these alone produces a complete, managed trade.
Bar classification → pattern matrix → trigger FSM → trap detection → regime + volume + FTC filters → trade engine (SL/TP1-3/BE) → anchored VWAP context
The classifier turns raw candles into STRAT numbers. The pattern matrix scans the sequence for tradeable combinations and arms a setup with exact trigger and stop levels. The trigger FSM waits for a confirmed break — or the Trap engine fires instead when a candle breaks an extreme and closes against it. Every prospective entry then passes through three independent gates (PVTE regime, volume confirmation, FTC alignment) before the trade engine takes over: structural stop, three R-multiple targets, automatic break-even, and a webhook alert at every stage. The anchored VWAP restarts at each confirmed structural pivot inside the regime, showing the volume-weighted average of the current leg — the reference institutional participants care about.
Remove any link and the chain breaks: patterns without triggers are just decoration; traps without a regime filter fade every wiggle; a trade engine without structural stops places arbitrary lines; a VWAP without pivot anchoring measures the wrong leg.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Mechanical STRAT classifier with a data-driven pattern matrix.
Every bar is classified exhaustively:
— Inside (1): high <= high and low >= low
— Outside (3): high > high and low < low
— 2U: high > high and low >= low
— 2D: low < low and high <= high
Patterns are not hardcoded if-chains — they live in a priority-ordered matrix scanned longest-first, so a 2-2-2 continuation (Extended mode) outranks the 2-2 it contains, and overlapping patterns resolve deterministically. Core set: 2-2 Rev/Cont, 3-2, 3-2-2, 2-1-2 Rev/Cont, 3-1-2, 1-2-2 RevStrat. Extended (opt-in): 2-2-2, 2-2-2-2 "Randy Jackson", 1-bar 3 RevStrat (outside bar closing beyond the prior bar's range).
2️⃣ Three-stage trigger FSM: SETUP → PENDING → TRIGGERED.
When a pattern completes on a confirmed close, the engine arms: trigger = the final pattern bar's high (bull) or low (bear), stop = the opposite side. A wick break of the trigger level on a later confirmed bar fires TRIGGERED. An adverse CLOSE beyond the stop side invalidates. No break within Setup Expiry bars (default 3) expires the setup. On an outside bar that pierces both sides, the adverse close wins — the conservative read, because the intrabar touch order is unknowable.
3️⃣ Trap Bar entry engine — the headline feature (default mode).
A trap bar is a candle whose body color contradicts its STRAT direction:
— Red 2U : broke the prior high, closed below its open → buyers were trapped above the break → SHORT
— Green 2D : swept the prior low, closed above its open → sellers were trapped below → LONG
Entry = trap bar close; stop = beyond the sweep extreme (the trap bar's own high/low) + 0.25×ATR buffer, with a 0.5×ATR minimum distance always enforced. Dojis (close == open) never qualify. Three Entry Modes: Trap Bar (default), STRAT Trigger (classic breakout entries), Both — where a trap candle on a trigger bar overrides the trigger's direction, because the failed breakout IS the trade.
4️⃣ Structural stop anchoring, four modes.
For trigger entries the SL Anchor input chooses: Trigger Level (default — just beyond the broken high/low; price trading back through the broken level means the breakout failed), Setup Bar (opposite side of the setup bar — wider, fully structural), Wick-Anchored (beyond the entry bar's own wick), or ATR (close ± SL Multiplier × ATR). All structural modes use:
stop_long = min(anchor − 0.25×ATR, close − 0.5×ATR)
which simultaneously applies the buffer and guarantees the minimum distance. A Max Risk cap (default 3×ATR, 0 = off) skips entries whose structural risk is too wide — outside-bar setups are the usual offenders.
5️⃣ Full trade management with honest intrabar accounting.
TP1/TP2/TP3 are R-multiples of the actual entry→stop distance (Risk Presets: Conservative 1R/2R/4R with 2.5×ATR stop, Balanced 1R/2R/3R, Aggressive, Scalping, or Custom). After TP1 is touched the stop moves to entry ( break-even ) — and a BE moved on a bar cannot stop that same bar out (the SL check uses the bar-start stop). When SL and a first TP1/TP3 touch land on the same bar, the TP registers and blocks the SL — an optimistic intrabar model, disclosed openly : the true touch order inside one bar is unknowable without tick data. A trade closes only at TP3, SL, or a BE stop-out. Win = TP1 was touched.
6️⃣ PVTE Regime Filter — two-threshold hysteresis, ON by default.
A 3-state regime engine (BULL / BEAR / NEUTRAL) built on a selectable basis kernel (EMA default, DEMA, HMA, KAMA; length 21) and ATR bands (length 100):
outer band = basis ± ATR × 3.0
inner band = basis ± ATR × (3.0 − 1)
Regime is entered on a confirmed close through an outer band and exits to NEUTRAL only on a close through the OPPOSITE inner band — the two-threshold gap kills flip-flopping in chop. Longs pass only in BULL, shorts only in BEAR; NEUTRAL blocks both by default (Allow mode available). Every entry — trap or trigger — must pass this gate, which converts the naturally counter-trend trap fade into a trend-continuation tool: only sweeps AGAINST the regime get faded, in the regime's direction.
7️⃣ Pivot-anchored VWAP trail.
Inside an active regime, the VWAP anchors at each confirmed structural pivot (Pivot Length 13 bars each side) in the regime direction, backfills from the pivot bar in one pass, then accumulates incrementally:
aVWAP = Σ(price × volume) / Σ(volume), from the anchor bar
It re-anchors on every new in-regime pivot and hard-resets on regime change — so the dotted trail always represents the current leg's volume-weighted average, not a stale session artifact. Pivot confirmation is honest lag: the swing is only KNOWN Pivot Length bars after it forms; the trail is drawn from the confirmed pivot forward. Delayed confirmation, not repainting.
8️⃣ FTC strip and FTC Alignment filter.
A top-center strip shows every timeframe above your chart (15m → Quarter): green/red for the current higher-TF candle direction, with ·I / ·O flags when that candle is inside/outside its predecessor. The optional Min FTC Aligned filter (default 0 = off) requires N visible higher timeframes to agree with your entry direction. Honesty note, stated in the tooltip as well: continuity is a live-state concept, so the strip and this filter read the FORMING higher-TF candles — the only reload-unstable element in the indicator; everything else is confirmed-close based.
9️⃣ Volume confirmation gate.
Optional filter requiring entry-bar volume > SMA20 × threshold (default 1.2), automatically bypassed on instruments without volume data. Applies to both entry sources.
🔟 Bot-grade alert architecture.
Every event emits a structured JSON webhook (or human-readable text): setup_bull/bear, trigger_bull/bear, trap_long/short, be, tp1_hit, tp2_hit, tp3_close, sl_hit. Entry payloads carry pattern, price, entry, sl, tp1-3, the PVTE regime (−1/0/1) and a compact FTC string like "1H+4H+D-W+". Closure payloads carry the result (win/loss) and a be_stop flag — built from pre-reset snapshots so same-bar event collisions can never produce NaN fields. Alerts follow a fixed intrabar chronology (management → closures → entries → setups) and five category toggles let a bot mute any stream it doesn't act on. Nine static alertcondition entries cover the TV alert dialog.
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Classify: On every bar the STRAT type (1 / 2U / 2D / 3) is computed and, on confirmed close, appended to the sequence.
Step 2 — Match: The pattern matrix scans the sequence newest-first, longest patterns first; the first match arms a setup with trigger/stop at the final pattern bar's extremes.
Step 3 — Resolve: A pending setup is checked each confirmed bar: adverse close → invalidated; wick break of the trigger → TRIGGERED; expiry (default 3 bars) → expired. Setup lines freeze and dim on any resolution.
Step 4 — Detect traps: Independently, every confirmed bar is tested for the trap condition (2U closing red / 2D closing green).
Step 5 — Filter: The prospective entry (trap first in Both mode) must pass PVTE regime, volume and FTC gates, then the Max Risk cap.
Step 6 — Open & manage: Entry at close; SL/TP1-3 computed; each later confirmed bar checks TP touches (TP priority), moves BE after TP1, and closes on TP3/SL/BE stop-out. Lines project forward, extend while active, persist after close as a record, and recolor teal on TP hits.
Step 7 — Track context: The PVTE regime FSM updates on closes; the anchored VWAP accumulates, re-anchors on new pivots, resets on regime change.
Step 8 — Report: Dashboard sections refresh (sequence, setup state, trade, session stats), and the alert engine emits events in fixed chronological order.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator to a clean chart. Defaults are ready to observe: Trap Bar entries, PVTE filter ON, regime bands and anchored VWAP visible.
2. Watch the numbers under the candles: 1 = pause, 2 = direction, 3 = sweep of both sides. This alone teaches you The STRAT faster than any book.
3. Wait for a LONG · Trap 2D or SHORT · Trap 2U label — the indicator found a failed break aligned with the regime and opened a managed plan.
4. Follow the plan on the chart: dotted entry line, solid red stop, dashed green targets. Watch TP1 turn teal and the entry label switch to "→ SL (BE)".
5. Once comfortable, create ONE TradingView alert with condition "Any alert() function call" and paste your webhook URL — every event now reaches your phone or bot in JSON.
👁️ Reading the chart:
— Numbers 1/2/3 under bars = STRAT types (amber, green/red, magenta)
— 🟢 LONG · / 🔴 SHORT · labels = trade entries with the source pattern; the tooltip shows entry, SL, TP1-3 and risk
— ▲ / ▼ labels = STRAT triggers that did NOT open a trade (engine busy or filtered) — still valid signals for manual traders
— Solid/dotted horizontal pairs after a pattern = pending trigger (colored) and stop (muted); they dim if invalidated or expired
— Small triangles = hammer (below) / shooter (above), wick-dominant candles by the Actionable Wick fraction (default 0.75)
— Colored bands = PVTE regime envelope; dotted trail = anchored VWAP of the current leg
— Dashed horizontal levels = previous Day/Week/Month high/low with price tags (lookahead-safe)
— Top-center strip = Full Timeframe Continuity at a glance
📊 Dashboard fields:
— Seq: the last four confirmed STRAT types, oldest left
— Setup: pending pattern, direction and bars-waited/expiry — or "idle"
— Levels: the pending trigger (T) and stop (S) prices
— Candle: Hammer / Shooter / Inside on the current bar (informational)
— PVTE: current regime — BULL / BEAR / NEUTRAL / Off
— Trade section: entry, stop (with "BE @" after break-even), TP1-3 with ✓ marks, R:R at TP1, stop distance in %
— Stats section: trades, wins, losses, win rate with gauge, and the ▰▱ form strip of the last 10 — for the selected period (24H / 30D / All-Time)
🔧 Tuning guide:
— Too few trades: switch In NEUTRAL Regime to Allow, or set Entry Mode to Both, or raise Max Risk
— Too many shallow trades in chop: keep NEUTRAL = Block, raise the PVTE ATR Multiplier (wider regime bands), or add Min FTC Aligned = 2
— Stops feel too tight: change SL Anchor to Setup Bar (structural, wider) — targets scale with the wider risk automatically
— Stopped out by noise at breakeven: that is the cost of the BE rule; disable Break-Even After TP1 if you prefer to let trades breathe
— Chart too busy: Setup Labels, Trigger Labels and bar coloring are already off by default; Regime Bands and the VWAP trail have their own toggles
— Learning mode: turn Setup Labels and Trigger Labels ON and Trade Engine OFF — the chart becomes a pure STRAT trainer
⚙️ KEY SETTINGS
🎨 Appearance: Theme (Auto/Dark/Light — the palette adapts, signals stay readable on white and black), watermark, bar coloring (off), bar numbers (on), Signal Label Size.
📐 Pattern Engine: Extended Patterns (off), Setup Labels (off), Max Pattern Drawings (60, FIFO).
🎯 Trigger Engine: Setup Expiry (3 bars), Trigger/Stop Lines (on), Trigger Labels (off).
🛡️ Risk Management: Trade Engine (on), Entry Mode (Trap Bar), Risk Preset (Balanced), SL Anchor (Trigger Level), SL Buffer (0.25×ATR), ATR Length (14), TP1/2/3 multipliers (Custom preset), Max Risk (3×ATR), Break-Even After TP1 (on), line styles, label toggles, % distance on labels.
🔍 Filters: Volume Confirmation (off, ×1.2 SMA20), Min FTC Aligned (0 = off).
🌊 PVTE Regime Filter: filter toggle (on), Basis Kernel (EMA), Basis Length (21), ATR Length (100), ATR Multiplier (3.0), NEUTRAL behavior (Block), Regime Bands (on), Anchored VWAP (on), VWAP Pivot Length (13), VWAP Source (Close).
🕯️ Actionable Candles: hammer/shooter marks (on), Min Wick Fraction (0.75).
📊 Dashboard: position, size (Small-Huge), Market/Trade/Stats section toggles, Win Rate Period.
🔔 Alerts: master Enable, JSON/Text format, five category toggles (Entries, TP/BE, SL, Filtered Triggers, Setups).
🔔 ALERTS
— 🟢 trigger_bull / trap_long — entry with pattern, price, entry, sl, tp1-3, regime, ftc
— 🔴 trigger_bear / trap_short — mirrored short payload
— 🎯 tp1_hit / tp2_hit — target touches with level and entry
— 🛡️ be — stop moved to break-even
— 🏆 tp3_close — final target, result "win"
— 🛑 sl_hit — stop-out with be_stop flag and win/loss result
— 📐 setup_bull / setup_bear — a pattern armed with its trigger/stop levels
— Plain trigger alerts for signals that did not open a trade (filters/engine busy)
All fire on confirmed bar close. One alert covers everything: condition "Any alert() function call". Nine static alertcondition entries are also available in the TV dialog.
⚠️ IMPORTANT NOTES
— 🚫 No repainting of signals. Classification is fixed on bar close; all setups, triggers, traps, entries and closures are evaluated on barstate.isconfirmed only; pivots for the VWAP anchor use equal left/right lookback (delayed confirmation, drawn forward from the confirmed bar). One disclosed exception by design: the FTC strip and the optional FTC Alignment filter read the FORMING higher-timeframe candles, because timeframe continuity is a live-state concept — an entry allowed live can look filtered after a reload. That filter is OFF by default.
— 📐 Optimistic intrabar model. When SL and a first TP touch share one bar, the TP is credited (TP priority). Session statistics use this model and the "win = TP1 touched" definition; they reset on chart reload and are NOT a backtest — no commissions, slippage or position sizing.
— ⚖️ Trap entries are regime-gated fades. With the PVTE filter off, the trap engine will fade every divergence candle, including mid-range noise. The default configuration (NEUTRAL = Block) is intentional.
— 🛠️ This is an analysis tool, not an automated bot. It provides classification, signals, trade plans and alerts — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Instruments without volume data: the VWAP falls back to the price source and the volume filter bypasses automatically.
— 📚 The STRAT is a public price-action methodology popularized by Rob Smith. This is an original clean-room implementation: no third-party code is reused, and the pattern engine, trap logic, trade management and regime integration are built from scratch as described above. Indikator

MYND Distribution/Capitulation Exit Engine v1.0MYND Distribution/Capitulation Exit Engine
A dedicated exit tool built on one core idea: the way an uptrend tops out and the way a downtrend bottoms out are not mirror images of each other, so this indicator scores them with two genuinely different engines instead of one exit score flipped in sign.
WHAT IT DOES
This tool watches for two separate exit conditions. Distribution (long exit) is a slow, multi-bar process - the kind of quiet, high-volume selling that shows up while price still looks fine on the surface. Capitulation (short exit) is a fast, single-bar process - a violent, high-volume flush that can resolve in a bar or two. Each gets its own 0-100 score, its own Warning and Exit thresholds, and its own markers and alerts.
HOW IT WORKS
The Distribution score blends three classic distribution signatures: Distribution Day counting (a down day on rising volume, the technique long used by institutional trend-followers to spot quiet institutional selling), down-day volume dominance over a shorter window, and a gradual RSI roll-over from an elevated reading. A "still near recent highs" check keeps the score meaningful while price looks healthy, and dampens it once price has already broken down - by then you likely don't need this tool to tell you something changed.
The Capitulation score blends three climax signatures: a volume z-score spike relative to its own recent history, a rejection-candle score that continuously blends range expansion and close position off the low (no hard cutoff, so the score moves smoothly rather than jumping), and an RSI extreme-and-uptick check that only rewards being oversold once RSI has actually started turning back up - not just for being oversold and still falling. All three are scored live, every bar, with no multi-bar confirmation delay - because by the time a slow confirmation window closes on a capitulation move, the opportunity to act on it is often already gone.
KEY FEATURES
Four distinct signals - Long Exit Warning, Long Exit Signal, Short Exit Warning, Short Exit Signal - each independently plotted and alertable. A live dashboard table showing both scores, their zones, the raw Distribution Day count, the down-volume ratio, and whether price is still near its recent high. Full color, table position, and text-size customization. Eight alerts total, including four combo bundles (all signals, long-side only, short-side only, actionable-only) so you can set up exactly the notification footprint you want.
HOW TO USE IT
Pair this with any entry method - it is not an entry tool. Once in a position, watch the relevant score: a Warning is an early heads-up to tighten stops or begin scaling out, an Exit signal is the higher-conviction, actionable read. Treat the Distribution and Capitulation scores independently; they are not designed to be compared against each other, only against their own thresholds.
SETTINGS WORTH TUNING FIRST
Long/Short Exit Warning and Signal Thresholds - the fastest way to make signals earlier/more frequent or later/higher-conviction. Distribution Day Lookback and Critical Distribution Day Count - calibrates how much selling pressure counts as meaningful distribution for your symbol and timeframe. Minimum Bar Range (x ATR) and Minimum Close Position - the reference levels the capitulation rejection-candle score scales against; raise either to require a stronger candle to reach a high score.
ALERTS
All eight alerts use TradingView's standard alertcondition() system - no special setup required. Add Alert, choose this indicator, and pick the named condition from the dropdown.
This tool does not know your actual position or entry price - it scores exit conditions on the underlying symbol only, and a signal is only actionable if you hold a matching position. This tool is provided for informational and educational purposes and does not constitute financial advice. Trading involves risk; past performance and historical patterns do not guarantee future results. Indikator

Gunjan Algo Auto Buy/Sell# Gunjan Algo Edge All TF
Gunjan Algo Edge All TF is a multi-timeframe adaptive technical-analysis indicator designed to help traders evaluate trend direction, momentum, price structure, and market alignment from a single chart.
Instead of relying on one indicator or one fixed parameter set across every timeframe, the script automatically adapts its core calculation parameters to the active chart timeframe. It supports short-term intraday analysis through higher-timeframe market context, with an integrated MTF dashboard covering 1m, 3m, 5m, 10m, 15m, 30m, 1h, 2h, 3h, 4h, 1D, 1W and 1Mo.
The indicator is intended as a decision-support and market-structure tool. It does not guarantee profitable trades and should not be interpreted as financial or investment advice.
## What makes the indicator different?
The main objective of Gunjan Algo Edge All TF is to combine several independent technical conditions into a structured signal framework rather than generating a signal from a single crossover.
The signal engine evaluates:
* Fast and slow EMA relationship
* EMA direction and momentum
* EMA separation
* RSI momentum
* DMI directional pressure
* ADX trend-quality filter
* VWAP price bias
* Recent price-structure breaks
* Reversal momentum
* Candle quality
* Adaptive noise filtering
* Multi-timeframe signal alignment
The script can operate in three modes:
1. Auto
2. Original 5M
3. Manual
In Auto mode, the indicator changes its calculation parameters according to the active timeframe. The source code contains separate parameter profiles for short-term and higher-timeframe analysis.
## Adaptive timeframe engine
The Auto mode is designed to avoid using exactly the same sensitivity on every timeframe.
For example, the default Auto profiles include:
| Timeframe | Fast EMA | Slow EMA | RSI | DI | ADX Minimum |
| --------- | -------: | -------: | --: | -: | ----------: |
| 1m | 6 | 13 | 7 | 7 | 21.0 |
| 3m | 8 | 18 | 8 | 9 | 19.5 |
| 5m | 9 | 21 | 9 | 10 | 18.0 |
| 10m | 10 | 24 | 10 | 10 | 18.0 |
| 15m | 12 | 27 | 10 | 11 | 18.0 |
| 30m | 15 | 34 | 11 | 12 | 18.0 |
| 1h | 18 | 40 | 12 | 13 | 18.0 |
| 2h | 21 | 45 | 13 | 13 | 18.5 |
| 3h | 23 | 48 | 14 | 14 | 18.5 |
| 4h | 24 | 50 | 14 | 14 | 19.0 |
| Higher TF | 30 | 60 | 14 | 14 | 20.0 |
These profiles are part of the indicator's adaptive design and are not presented as universally optimal settings.
## Core signal architecture
### 1. EMA momentum
The bullish EMA condition requires the fast EMA to be above the slow EMA and rising.
The bearish condition requires the fast EMA to be below the slow EMA and falling.
This gives the signal engine both directional and momentum information rather than using an EMA crossover alone.
### 2. EMA separation filter
The indicator measures the percentage distance between the fast and slow EMA.
The purpose is to reduce signals when the two averages are excessively compressed and the market may be lacking directional separation.
The separation requirement itself adapts according to timeframe. The 5-minute profile, for example, does not require the same separation threshold used on several other timeframes.
### 3. RSI momentum
The BUY side requires RSI to be above the configured BUY threshold and rising.
The SELL side requires RSI to be below the configured SELL threshold and falling.
The default thresholds are:
* BUY RSI: 52
* SELL RSI: 48
These are momentum thresholds rather than traditional overbought/oversold levels.
### 4. DMI directional pressure
The indicator compares +DI and -DI.
* +DI > -DI supports bullish conditions.
* -DI > +DI supports bearish conditions.
This provides directional confirmation to the trend and momentum calculations.
### 5. ADX trend-quality filter
ADX is used as a minimum trend-quality filter.
A signal is permitted only when ADX reaches the adaptive minimum for the selected timeframe.
This is intended to reduce signals during conditions where directional movement may be too weak.
### 6. VWAP bias
The indicator uses VWAP as another contextual filter.
Bullish conditions favor price trading above VWAP or demonstrating bullish price/EMA behavior.
Bearish conditions favor price trading below VWAP or demonstrating bearish price/EMA behavior.
VWAP therefore acts as a contextual market-bias component rather than being used as a standalone entry trigger.
### 7. Price structure
The indicator evaluates the recent high and low over its adaptive structure lookback.
A bullish structure condition occurs when the confirmed closing price breaks above the recent high.
A bearish structure condition occurs when the confirmed closing price breaks below the recent low.
### 8. Reversal momentum
The script also has a second signal route designed to identify developing directional changes.
It monitors:
* RSI crossing its configured threshold
* DMI directional crossover
* Price position relative to the fast EMA
* Directional DMI confirmation
* RSI position relative to 50
This creates a second route for signals when momentum changes before a conventional structure-break setup becomes available.
## BUY signal logic
The BUY engine has two principal routes.
### Route 1 — Trend/structure confirmation
A BUY setup can develop when:
* Recent structure breaks upward
* EMA momentum is bullish
* RSI momentum is bullish
* DMI is bullish
The broader signal then additionally requires trend quality, VWAP confirmation, candle quality, EMA separation and noise filtering.
### Route 2 — Reversal/momentum confirmation
A BUY setup can also develop when:
* RSI or DMI shows a bullish reversal event
* Price is above the fast EMA
* DMI confirms bullish direction
* RSI is above 50
Again, the broader filters must agree before the final BUY signal is produced.
The actual source code combines these routes with trend-quality, VWAP, candle, EMA-separation and noise conditions.
## SELL signal logic
The SELL engine mirrors the BUY framework.
### Route 1 — Trend/structure confirmation
A SELL setup can develop when:
* Recent structure breaks downward
* EMA momentum is bearish
* RSI momentum is bearish
* DMI is bearish
### Route 2 — Reversal/momentum confirmation
A SELL setup can develop when:
* RSI or DMI produces a bearish reversal event
* Price is below the fast EMA
* DMI confirms bearish direction
* RSI is below 50
The broader SELL filters must also agree before the final signal is displayed.
## Signal confirmation
Signals are generated only on confirmed bars.
The script also maintains a signal state so that it does not continuously print the same BUY or SELL label on every qualifying candle.
The chart therefore focuses on directional transitions rather than repeatedly printing identical labels.
## How to read the chart
The indicator displays:
* Green BUY label = bullish signal
* Red SELL label = bearish signal
The chart labels are deliberately simple so that the underlying price action remains visible.
### Example 1 — Bullish trend continuation
Imagine the following sequence on a 5-minute chart:
1. Price is trading above VWAP.
2. Fast EMA is above slow EMA and rising.
3. RSI moves above the BUY threshold and continues rising.
4. +DI moves above -DI.
5. ADX is above the required minimum.
6. Price breaks the recent structure high.
7. A bullish candle closes with sufficient strength.
If the remaining filters agree, the indicator can print:
BUY
This should be interpreted as a bullish technical alignment, not as a guarantee that price will continue higher.
### Example 2 — Bearish trend continuation
Imagine the opposite sequence:
1. Price trades below VWAP.
2. Fast EMA is below slow EMA and falling.
3. RSI moves below the SELL threshold.
4. -DI exceeds +DI.
5. ADX satisfies the timeframe requirement.
6. Price breaks recent structure support.
7. A bearish candle closes with sufficient strength.
The indicator can then print:
SELL
Again, the signal represents technical conditions detected by the indicator and not a guaranteed future outcome.
### Example 3 — Reversal setup
Suppose price has been declining but momentum begins to change.
RSI crosses upward through its BUY threshold, +DI crosses above -DI, price moves above the fast EMA, and RSI moves above 50.
If the trend-quality, VWAP, candle, separation and noise filters also agree, the reversal route can generate a BUY signal.
The same concept applies in reverse for bearish reversals.
## Multi-timeframe dashboard
One of the main features of Gunjan Algo Edge All TF is its MTF dashboard.
The dashboard evaluates the indicator's signal framework across:
1m | 3m | 5m | 10m | 15m | 30m | 1h | 2h | 3h | 4h | 1D | 1W | 1Mo
The dashboard uses:
* B = BUY
* S = SELL
* — = NO SIGNAL
It also calculates an overall directional bias from the active timeframe signals.
### Dashboard example
A hypothetical dashboard could look like:
| 1m | 3m | 5m | 10m | 15m | 30m | 1h | 2h | 4h | 1D | Bias |
| -- | -- | -- | --- | --- | --- | -- | -- | -- | -- | ---- |
| B | B | B | B | B | B | B | — | B | B | BUY |
In this example, the lower and higher timeframes are generally aligned bullishly.
A different example:
| 1m | 3m | 5m | 10m | 15m | 30m | 1h | 2h | 4h | 1D | Bias |
| -- | -- | -- | --- | --- | --- | -- | -- | -- | -- | ----- |
| S | B | S | — | B | — | B | B | S | B | MIXED |
This indicates conflicting timeframe information.
A MIXED condition should generally be treated as a warning that the market does not have strong multi-timeframe agreement.
## Overall bias
The dashboard calculates the proportion of active BUY and SELL signals across its monitored timeframes.
The displayed bias is classified as:
* STRONG BUY
* BUY
* MIXED
* SELL
* STRONG SELL
* NO SIGNAL
The current implementation uses an 80% threshold for STRONG BUY/STRONG SELL and a 60% threshold for BUY/SELL.
The overall bias is a summary of the indicator's multi-timeframe technical state. It is not a prediction of future price.
## Suggested workflow
### Intraday traders
A practical workflow can be:
1. Start with the higher timeframes.
2. Check whether the 1h, 2h, 4h and daily signals generally agree.
3. Move to the intended execution timeframe.
4. Wait for the chart's BUY or SELL signal.
5. Check price structure and market context.
6. Define the trade's invalidation level before entering.
7. Determine position size according to your own risk rules.
8. Use the MTF dashboard as confirmation rather than treating it as an automatic trade command.
### Scalping
For short-term trading, the 1m, 3m and 5m columns can provide faster information, but lower timeframes generally contain more market noise.
Do not assume that a lower-timeframe signal is automatically superior to a higher-timeframe signal.
### Swing analysis
For higher-timeframe analysis, the 4h, daily, weekly and monthly readings can provide broader directional context.
A trader may use the higher timeframe for market bias and a lower timeframe for execution.
## Example decision framework
### Stronger bullish alignment
Higher timeframe: BUY
Execution timeframe: BUY
Lower timeframe: BUY
Price structure: bullish
VWAP context: bullish
Possible interpretation:
"Multiple technical components are aligned bullishly."
This is still not a guarantee of a profitable trade.
### Conflicting alignment
Higher timeframe: SELL
Execution timeframe: BUY
Lower timeframe: BUY
Possible interpretation:
"Short-term momentum is bullish while the broader trend remains bearish."
A trader may choose to wait for greater alignment rather than acting immediately.
## Settings
### Mode
**Auto**
Automatically selects the timeframe-specific parameter profile.
**Original 5M**
Uses the original 5-minute parameter configuration.
**Manual**
Allows the user to specify:
* Fast EMA
* Slow EMA
* RSI length
* DI length
* ADX smoothing
* Structure lookback
* Minimum ADX
The script exposes these controls directly in its settings.
### Adaptive Noise Filter
When enabled, the indicator applies additional directional conditions intended to reduce signals during less favorable price/EMA configurations.
### EMA Separation Filter
When enabled, the indicator requires the EMA relationship to satisfy the timeframe-specific separation condition.
### MTF Dashboard
The dashboard can be enabled/disabled and positioned at:
* Top Right
* Top Left
* Bottom Right
* Bottom Left
The overall bias display can also be enabled or disabled.
## Alerts
The indicator includes alert conditions for BUY and SELL signals.
Users can create TradingView alerts from these conditions and choose their preferred notification method.
Always verify the alert configuration and the selected symbol/timeframe before relying on alerts for live monitoring.
## Repainting and data handling
The MTF calculations use `request.security()` with `lookahead=barmerge.lookahead_off`, which avoids intentionally requesting future values from higher/lower timeframe calculations.
Signals on the current chart are additionally restricted to confirmed bars.
However, traders should understand that any real-time technical indicator can change its developing conditions while the current candle is still forming. For this reason, the published indicator is intended to be interpreted using confirmed signals rather than assuming that an intrabar condition is permanent.
## Recommended chart setup
For a clean TradingView publication:
* Use a standard candlestick chart.
* Keep the Gunjan Algo Edge All TF indicator clearly visible.
* Avoid unnecessary additional indicators on the publication screenshot.
* Show the complete symbol and timeframe.
* Make the BUY/SELL labels clearly visible.
* Keep the MTF dashboard readable.
* Use a chart section where the relationship between price action, signals and dashboard can be understood.
TradingView specifically recommends clean publication charts where the script's output is easy to identify.
## Important limitations
Gunjan Algo Edge All TF is a technical-analysis tool.
It does not:
* Predict the future with certainty.
* Guarantee profitable trades.
* Guarantee a particular win rate.
* Guarantee a particular risk/reward ratio.
* Eliminate losing trades.
* Replace risk management.
* Replace market or instrument-specific analysis.
* Guarantee that every BUY signal will result in a bullish move.
* Guarantee that every SELL signal will result in a bearish move.
Market conditions can change rapidly, and technical signals can fail during news events, volatility shocks, gaps, illiquid periods, sideways markets and other abnormal conditions.
The indicator should therefore be used as one component of a broader trading process.
## Risk management
Before taking any trade, consider:
* Entry price
* Invalidation level
* Stop-loss placement
* Position size
* Maximum acceptable loss
* Transaction costs
* Slippage
* Market liquidity
* Trading-session conditions
* Higher-timeframe context
Never risk capital that you cannot afford to lose.
## House Rules and publication compliance
This publication is written to provide a clear explanation of the indicator's purpose, methodology and usage without making unsupported performance claims.
The description intentionally does not claim a guaranteed win rate, guaranteed profitability, guaranteed accuracy or future performance.
TradingView's Script Publishing Rules require descriptions to explain what a script does, how it works and how traders can use it, while also prohibiting unrealistic or unsubstantiated performance claims.
The indicator should also be published with an original, clean chart and without misleading visual demonstrations. TradingView's House Rules prohibit plagiarism and require published content to be understandable and appropriately described.
If the script contains reused open-source code from another TradingView author, the appropriate author credit and reuse requirements must be satisfied before public publication. TradingView specifically requires attribution and additional conditions when qualifying open-source code is reused.
## Financial disclaimer
This indicator is provided for informational and educational purposes only.
Nothing in this indicator or its description constitutes investment advice, financial advice, a recommendation to buy or sell any security, derivative, cryptocurrency, commodity or other financial instrument, or a guarantee of future results.
Trading involves substantial risk. Past performance or historical behavior does not guarantee future results.
Users are responsible for their own trading decisions, risk management, due diligence and compliance with applicable laws and regulations.
## Final note
Gunjan Algo Edge All TF is best viewed as a structured market-analysis framework.
The goal is not to make every candle produce a signal. The system intentionally combines trend, momentum, structure, volatility/trend quality and multi-timeframe information so that traders can distinguish between directional alignment and conflicting market conditions.
Use the BUY and SELL labels as technical events, use the MTF dashboard as context, and combine the indicator with disciplined risk management and independent analysis.
Indikator

Initial Balance DashboardInitial Balance Dashboard
Initial Balance Dashboard brings together the session-based tools futures traders typically run as five or six separate indicators — anchored VWAPs, initial balance fibonacci levels, session range boxes, and a live market context readout — into one overlay built specifically around trading the initial balance on index futures (NQ, ES, and similar).
Everything is time-anchored to New York time by default and adjusts automatically for daylight saving, since the sessions that matter for futures (the 18:00 daily open, the London session, the New York session) are defined by the clock, not the calendar day.
What's included
VWAP suite — Weekly, Daily (anchored to the 18:00 futures open), London, and New York VWAPs, each with independent colour, line width, and on/off control. All anchor and session times are editable.
Previous session high/low — the prior New York session's high and low, drawn as a fixed level the moment the session closes and running for a full day, with customizable text, size, position, and optional price display on the labels.
Initial Balance fibonacci levels — plots live off the developing IB range (09:30–10:30 NY and 03:00–04:00 London by default, both configurable) and locks once the IB completes. Two independent level profiles per session — a quadrant set (0 / 0.25 / 0.5 / 0.75 / 1) and a thirds set (0 / 0.35 / 0.65 / 1) — can run side by side, each with its own colors, extensions (-0.125 / 1.125), and line style.
Session range boxes — Asia, London, and New York boxes that build in real time, tracking the actual high and low as each session prints rather than a pre-computed range, with editable timing, colours, and labels.
Vertical session markers — dotted lines at each session's open and IB close, printed the moment the session begins so you can see at a glance how much of the initial balance window remains.
Status dashboard — a compact table (position and size configurable) that shows, at a glance:
- Price's position relative to each active VWAP (above/below)
- ADR(N) — average daily range over the last N completed days, today's range used so far, and a percentage that changes colour at configurable warning (default 90%) and full (default 100%) thresholds
- A Magnificent-7 market breadth/sentiment reading — a market-cap-weighted composite of NVDA, AAPL, MSFT, GOOGL, AMZN, META, and TSLA's move off today's open, blended with breadth so one stock running hot alone doesn't register as broad conviction — shown as Long bias / Short bias / Neutral
- A watermark row showing symbol, timeframe, and date
How to use it
The dashboard is designed to sit behind your own initial balance strategy: use the IB fib levels and session boxes to frame the range as it develops, the VWAPs and previous session levels as reference points for bias, and the status table for a quick read on where price sits and what broader market conditions look like before committing to a trade. Every component has its own on/off switch, so the dashboard can be run as a full suite or trimmed down to just the pieces you use.
Notes
All default session times are New York time and assume a 24-hour futures market; adjust the anchor and session inputs if you trade a different instrument or session structure.
The Mag 7 sentiment reading requests external data for NVDA, AAPL, MSFT, GOOGL, AMZN, META, and TSLA to compute its composite.
This script is a data and visualization tool, not a trading signal. It does not predict price direction or generate buy/sell recommendations. Past price behaviour around these levels is not indicative of future results — always use proper risk management. Indikator

Crypto Futures COT - Cohort PositioningThe Commitment of Traders report is a staple for futures traders on everything from gold to crude oil, but the crypto side is oddly hard to find. The mainstream screeners still leave CME Bitcoin and Ether off their COT and futures pages, so if you want to see who is actually positioned in the regulated futures, you are mostly out of luck. I wanted it on my own chart, so I built it.
It splits the CME crypto open interest into the three CFTC cohorts and plots each one:
- Commercial hedgers
- Large speculators, meaning funds and big traders
- Retail, the small traders below the reporting threshold
Three ways to look at it:
*Net positions, long minus short per cohort.
*Long vs Short, the gross legs, with shorts mirrored below zero so you can see when a cohort is leaning hard on one side.
*COT Index, each cohort's net scaled 0 to 100 over a three year window, so you can tell at a glance whether positioning is stretched against its own history.
There is also a table in the corner with the latest report: long, short, net, and the weekly change for each cohort.
This one is read-only on purpose. No arrows, no alerts, no buy markers. The idea is to put the positioning in front of you and let you form your own read, the way you would with any other market's COT.
Default is CME Bitcoin. Enter a different CFTC code in the settings for Ether or another market.
Worth knowing before you use it: the data is the weekly CFTC report, so it steps once a week and it is published with a lag. It tells you how cohorts were positioned as of the report date, not where they are now. Positioning is context, not a trigger, and an extreme can persist for a long time before price does anything about it. Indikator

Indikator

Indikator

Pure Mag 7 Matrix Momentum Engine v6### Overview
The **Pure Magnificent Seven Institutional Matrix Engine v6** is an intraday tape-reading and sector-breadth cockpit engineered for fast index futures execution (NQ/MNQ). Instead of analyzing isolated, lagging price points on a single instrument, this script isolates the core order flow driving the entire tech ecosystem. It tracks an equal-weighted composite return of the seven dominant mega-cap tech anchors (NVDA, AAPL, MSFT, AMZN, GOOGL, META, TSLA) that control roughly 40-50% of the aggregate Nasdaq-100 index weighting.
To protect system memory and ensure absolute zero lag on lower timeframes like the 1-minute and 5-minute charts, the code calculates percentage changes dynamically using timeframe.period price streams relative to a daily open reference anchor. This architecture auto-resolves global exchanges natively, completely removing the system crash and "Invalid Symbol" errors common in multi-asset indicators.
### Structural Mechanics & Visual Layout
### 1. Real-Time Data Participation Matrix (Top-Right Table)
* **The Counter**: Explicitly metrics how many of the 7 structural anchors are trading in a positive daily premium at that exact split-second (e.g., 5 / 7).
* **The Cells**: Color-coded ticker grids print the exact intraday percentage return of each stock (Green = Up, Red = Down).
* **The Header**: Automatically shifts colors based on market breadth (Green for broad buying pressure, Orange for mixed conditions, Red for severe distribution).
### 2. Master Momentum Signal Line
* **Visual Profile**: High-visibility Neon Green above equilibrium; deeply muted Forest Green below equilibrium.
* **Formula**: A refined 9-period EMA smoothing filter applied straight to the real-time equal-weighted aggregate return of the group.
* **Utility**: Signals the real force behind NQ movements. If the line is high and glowing, tech is operating at a structural intraday premium.
### 3. Bounded Institutional RVOL Gauge (The Volume Floor)
* **Visual Profile**: Fixed, bounded visual grid scale (-0.5 to -2.5) projecting down from the zero-line to guarantee it never physically overlaps or distorts your trend signals.
* **Formula**: Aggregated volume of all 7 stocks divided by their collective 20-period simple moving average volume (SMA).
* **Color Code**: Light/Dark Gray for typical retail churn. High-velocity institutional block trading bursts (1.5x to 2.5x+ above standard volume expectations for that precise minute) trigger an immediate shift into Bright Orange and Crimson Red bars.
### Core Execution Strategies
* **True Broad-Market Breakouts**: Look for vertical alignment. When the Master Momentum Line breaks above the 0.00 baseline (Neon Green), the volume floor drops to peak crimson depth (-2.5), and the matrix table displays **6 / 7** or **7 / 7 Up**. This registers a highly reliable broad-market breakout backed by systematic institutional accumulation.
* **The Mega-Cap "Solo Pump" Trap**: If NQ futures push to new session highs but the Matrix Table reads **1 / 7 Up** or **2 / 7 Up** (e.g., only NVIDIA is green while the rest are red), the indicator signals an artificial index pump. This divergence warns that broad market distribution is occurring, indicating a high-probability reversal environment.
* **Aggressive Liquidation Sweeps**: When the Master Line drops below the 0.00 baseline into a dark, muted tone while the volume bars hit max depth and the table turns heavily red, it confirms an institutional momentum flush, signaling highly optimal conditions for trailing systematic short entries. Indikator

Pure Mag 7 Institutional Momentum Engine v6### Overview
The **Pure Magnificent Seven Institutional Matrix Engine v6** is an intraday tape-reading and sector-breadth cockpit engineered for fast index futures execution (NQ/MNQ). Instead of analyzing isolated, lagging price points on a single instrument, this script isolates the core order flow driving the entire tech ecosystem. It tracks an equal-weighted composite return of the seven dominant mega-cap tech anchors (NVDA, AAPL, MSFT, AMZN, GOOGL, META, TSLA) that control roughly 40-50% of the aggregate Nasdaq-100 index weighting.
To protect system memory and ensure absolute zero lag on lower timeframes like the 1-minute and 5-minute charts, the code calculates percentage changes dynamically using timeframe.period price streams relative to a daily open reference anchor. This architecture auto-resolves global exchanges natively, completely removing the system crash and "Invalid Symbol" errors common in multi-asset indicators.
### Structural Mechanics & Visual Layout
### 1. Real-Time Data Participation Matrix (Top-Right Table)
* **The Counter**: Explicitly metrics how many of the 7 structural anchors are trading in a positive daily premium at that exact split-second (e.g., 5 / 7).
* **The Cells**: Color-coded ticker grids print the exact intraday percentage return of each stock (Green = Up, Red = Down).
* **The Header**: Automatically shifts colors based on market breadth (Green for broad buying pressure, Orange for mixed conditions, Red for severe distribution).
### 2. Master Momentum Signal Line
* **Visual Profile**: High-visibility Neon Green above equilibrium; deeply muted Forest Green below equilibrium.
* **Formula**: A refined 9-period EMA smoothing filter applied straight to the real-time equal-weighted aggregate return of the group.
* **Utility**: Signals the real force behind NQ movements. If the line is high and glowing, tech is operating at a structural intraday premium.
### 3. Bounded Institutional RVOL Gauge (The Volume Floor)
* **Visual Profile**: Fixed, bounded visual grid scale (-0.5 to -2.5) projecting down from the zero-line to guarantee it never physically overlaps or distorts your trend signals.
* **Formula**: Aggregated volume of all 7 stocks divided by their collective 20-period simple moving average volume (SMA).
* **Color Code**: Light/Dark Gray for typical retail churn. High-velocity institutional block trading bursts (1.5x to 2.5x+ above standard volume expectations for that precise minute) trigger an immediate shift into Bright Orange and Crimson Red bars.
### Core Execution Strategies
* **True Broad-Market Breakouts**: Look for vertical alignment. When the Master Momentum Line breaks above the 0.00 baseline (Neon Green), the volume floor drops to peak crimson depth (-2.5), and the matrix table displays **6 / 7** or **7 / 7 Up**. This registers a highly reliable broad-market breakout backed by systematic institutional accumulation.
* **The Mega-Cap "Solo Pump" Trap**: If NQ futures push to new session highs but the Matrix Table reads **1 / 7 Up** or **2 / 7 Up** (e.g., only NVIDIA is green while the rest are red), the indicator signals an artificial index pump. This divergence warns that broad market distribution is occurring, indicating a high-probability reversal environment.
* **Aggressive Liquidation Sweeps**: When the Master Line drops below the 0.00 baseline into a dark, muted tone while the volume bars hit max depth and the table turns heavily red, it confirms an institutional momentum flush, signaling highly optimal conditions for trailing systematic short entries. Indikator

ES Cross-Market Sentiment ConfirmationI like to scalp trade the ES. I am always looking for "leading indicators" to help me predict short term direction.
What this indicator does
This indicator gives ES scalpers a quick, at-a-glance read on whether broader market conditions support a bullish or bearish move, by combining three independent confirmation signals into a single composite score. It's designed to sit alongside your primary entry signals (RSI divergence, EMA cross, etc.) as a filter — not a standalone trade trigger.
The three components
NQ Trend Agreement — Compares the short-term rate of change of ES against NQ (Nasdaq futures). When both are moving the same direction, it's treated as confirmation. When they diverge (e.g., ES pushing higher while NQ lags or falls), it's flagged as a caution signal, since divergence often precedes stalls or reversals rather than clean continuation.
VIX Rate of Change — Tracks how fast the VIX is moving. A falling VIX signals risk-on conditions (supportive of long scalps); a sharp VIX spike signals risk-off conditions (supportive of short scalps or standing aside).
NYSE TICK — Reads breadth in two ways: a smoothed general trend (mildly positive/negative), and extreme readings at user-defined thresholds (default ±800). Extreme readings can be interpreted either as continuation confirmation or exhaustion warnings, depending on which mode is selected.
How the score works
Each of the three components casts a vote of +1 (bullish), -1 (bearish), or 0 (neutral/mixed). The votes sum into a total score from -3 to +3, which maps to a label:
+2 to +3 → Strong Bullish
+1 → Lean Bullish
0 → Neutral / Mixed
-1 → Lean Bearish
-2 to -3 → Strong Bearish
This score and a breakdown of each component are displayed in a table on the chart, with an optional background tint that shifts color with the current bias.
How to interpret it
Use it as a filter, not a trigger — a Strong Bullish or Strong Bearish reading means the broader tape supports that direction, which is a better environment to act on your existing entry signals.
A Neutral/Mixed reading, or an active NQ divergence warning, suggests conditions are choppy or conflicting — a reasonable cue to reduce size or stand aside rather than force a scalp.
The three components are intentionally kept separate in the table (not just the total) so you can see which market is agreeing or disagreeing — for example, a bullish TICK reading with a bearish VIX spike is a very different situation than all three agreeing.
Because it's a confirmation layer, it works best combined with your existing price-action/divergence entries rather than used in isolation. Indikator

Indikator

Indikator

Indikator

Indikator

Composite Liquidity Flow: five-asset weighted volume deltaWhat it does
One histogram that answers a single question: which way is the whole index complex leaning right now? It estimates buying and selling pressure across five instruments at once, weights them, smooths them, and prints the net as a z-scored delta with an agreement layer on top.
What is original here
Volume delta and RSI are both public methodology, and neither is mine. Three things here are not standard:
1. Pressure is attributed per bar from candle geometry, then priced in dollars rather than counted in shares. A 600-dollar instrument and a 60-dollar instrument therefore contribute on a comparable scale, which a raw share-count composite cannot do.
2. The five legs are not summed. Index futures, their tracking funds, and an inverse hedge fund are weighted separately, and the hedge leg has its logic inverted, so buying in the inverse product is counted as selling pressure on the complex. Hedging demand is treated as information rather than noise. This is the part I have not seen elsewhere.
3. The composite is z-scored against its own recent distribution, so the same scale reads correctly on a quiet session and on a high-volatility print.
The RSI layer is a display filter, not an input to the flow calculation. It gates when markers are allowed to print and never changes the histogram. That is the reason for the combination: flow describes who is pushing, RSI describes whether price has already travelled, and a marker is only allowed when the two agree. Without the filter the same flow model prints far more markers, most of them late.
How it works
Per-instrument pressure comes from candle structure. On an up bar, the body plus the lower wick is attributed to buyers and the upper wick to sellers; on a down bar the attribution reverses. That fraction multiplies the bar volume, then the closing price, producing a dollar figure per leg. Legs are weighted, summed, smoothed with an exponential average, then converted to a z-score against a rolling lookback. A session filter zeroes the fund legs outside regular hours, where their volume is unrepresentative of real positioning.
Divergences require three conditions at once: price at a lookback extreme, three consecutive bars of the composite moving the other way, and optional confirmation from the filter. A cooldown then suppresses repeats so the markers stay rare enough to mean something.
How to use it
Built for intraday index trading and tuned by default for 5-minute charts. Above the zero line and rising, with the filter supportive, means the composite tape agrees with a long. Below and falling is the mirror. The divergence markers are warnings about the move in progress, not entries. The dashboard reports each component separately so you can see which one is disagreeing before you act on the net.
What it cannot do
Markers are evaluated on the live bar, so a divergence or agreement arrow can appear and then disappear before the bar closes. Judge them on closed bars only. Nothing is drawn in the past and no confirmed marker moves once its bar has closed.
Everything here is estimated from open, high, low, close and volume. It is a structural proxy for order flow, not tick data, and it inherits every weakness a proxy has: it cannot see the order book, it cannot distinguish an aggressive buyer from a passive one, and on thin instruments the attribution is close to meaningless. It describes the index complex only and says nothing useful about an individual stock. It does not predict anything. It describes what the current bar and its neighbors have already printed.
Settings
Five symbols and their weights, smoothing length and z-score lookback, filter parameters, divergence strictness and cooldown, session handling, and a display toggle for each visual layer. Indikator

Session Sentinel [JOAT]A round-the-clock session watchtower — Asia, London and New York, each tracked live with its own range, rails and color.
◆ WHAT IT IS
Where price sits relative to the session ranges is core context for intraday trading — Asia builds the range, London and New York tend to expand it. Session Sentinel tracks all three sessions simultaneously, each with a live box, high/low rails and midline, in its own signature color. It is a pure context tool and prints no buy/sell signals.
This is 100% original code, written from scratch. It does not copy any other session script.
◆ HOW IT WORKS
1. Three independent watches. Each session (Asia, London, New York) has its own fully adjustable window and a shared timezone selector. As a session runs, the tool records its running high and low into a live box and draws:
• Session high/low rails — the levels other traders watch
• A midline — the session's equilibrium
• A name tag on the box
2. Session lifecycle. When a session ends, its box is finalized and archived. Only a configurable number of recent sessions are kept per watch, so history stays readable across all timeframes.
3. Day-open reference. A neutral daily open line provides a permanent intraday reference — price above or below the day's open is a simple, powerful bias filter.
◆ WHAT YOU SEE
• Live, color-coded session boxes — Asia, London, New York — with high/low rails and midlines
• A daily open reference line
• A resizable dashboard showing which watch is on duty, each session's high/low and range size, live/closed status, and the day open with price's distance above or below it
◆ HOW TO USE IT
• Use the Asia range as the reference other sessions break out of; London and New York frequently sweep or expand it.
• Session high/low rails act as intraday support/resistance and as breakout levels.
• The day open is a clean bias line — trading above or below it frames your directional lean.
• Adjust each session window to your instrument and exchange. Designed for intraday timeframes .
◆ NOTES & LIMITATIONS
Sessions are evaluated in the timezone you select — set it to match your market. On daily and higher timeframes the intraday session concept does not apply. This is a context tool, not financial advice; session levels are references, not predictions. Combine with your own method and risk management.
— made with passion by officialjackofalltrade
Indikator

Positioning Flow Index by DGTPositioning Flow Index (PFI) - Price & Open Interest Positioning Analysis
Positioning Flow Index (PFI) is a positioning-analysis framework designed to evaluate how price movement and Open Interest interact to reveal changes in market participation and positioning.
Rather than interpreting price direction alone, PFI combines normalized Price and Open Interest changes to identify four distinct positioning regimes:
Long Buildup - Short Buildup - Short Covering - Long Unwinding
The indicator evaluates the magnitude and direction of both Price and Open Interest through Z-score normalization , allowing unusually strong changes to be distinguished from ordinary market fluctuations.
In addition to the Positioning Flow Index itself, PFI provides a Flow State , Signal Strength , Price Sentiment , and an optional State Ribbon to help traders interpret the underlying positioning environment.
The objective is not to produce a simple Buy or Sell signal, but to provide a structured view of whether price movement is being accompanied by increasing or decreasing market participation and how strongly those two dimensions are aligned.
The Positioning Flow Model
Price + Open Interest
Price and Open Interest provide two different perspectives on market behavior.
Price describes the direction and relative strength of the current price movement.
Open Interest describes the change in outstanding derivative positions and provides an additional dimension for evaluating whether market participation is expanding or contracting.
PFI normalizes both dimensions using Z-scores , measuring how unusual the current Price and Open Interest changes are relative to their recent history.
A positive Z-score indicates a move above its recent average, while a negative Z-score indicates a move below its recent average.
This allows the indicator to distinguish between ordinary price/OI fluctuations and more statistically unusual changes in positioning.
Flow State
The Flow State classifies the relationship between Price and Open Interest into four positioning regimes.
LONG BUILDUP (LB)
Price is rising while Open Interest is increasing.
This combination indicates upward price pressure accompanied by expanding participation, a condition commonly associated with new long positioning.
SHORT BUILDUP (SB)
Price is falling while Open Interest is increasing.
This indicates downward price pressure accompanied by expanding participation, commonly associated with new short positioning.
SHORT COVERING (SC)
Price is rising while Open Interest is decreasing.
Price is moving upward while outstanding positions contract, a condition commonly associated with short positions being closed.
LONG UNWINDING (LU)
Price is falling while Open Interest is decreasing.
Price is moving downward while outstanding positions contract, a condition commonly associated with long positions being closed.
When Price and Open Interest do not both exceed the required activity threshold, the market is classified as NEUTRAL .
Neutral does not mean that the market is inactive. It means there is insufficient synchronized Price + Open Interest evidence to assign one of the four directional positioning states.
Positioning Flow Index
The Positioning Flow Index provides a bounded -100 to +100 representation of positioning flow.
Its calculation combines the normalized Open Interest and Price changes through a selectable Flow Model.
Model A — OI × sign(Price)
Open Interest determines the magnitude of the flow while Price determines its direction.
This model emphasizes participation strength and can produce a strong reading even when the price movement itself is relatively small.
Model B — OI × Price
The Open Interest and Price Z-scores are multiplied directly.
This captures the interaction between both dimensions, but unusually large Price Z-scores can have a greater influence on the resulting flow.
Model C — Price Direction × OI Magnitude × Price Confirmation
Price determines directional pressure, Open Interest determines participation magnitude, and the absolute Price Z-score contribution is capped to reduce the influence of extreme price moves.
This model separates the directional role of Price from the participation role of Open Interest and is the default model.
The three models are intentionally provided as different ways of interpreting the same underlying Price/OI relationship rather than as competing signals.
Signal Strength
Not every Flow State carries the same level of evidence.
PFI therefore calculates a Signal Strength based on two independent components:
Participation — derived from the magnitude of the Open Interest Z-score.
Confirmation — derived from the magnitude of the Price Z-score.
Both components are capped at 2σ and combined using their geometric mean:
Signal Strength = √(Participation × Confirmation)
The result is expressed as a percentage and provides a measure of how strongly Price and Open Interest are moving together.
Higher values indicate stronger synchronized evidence.
Importantly, Signal Strength is not a probability that the current move will continue. It measures the strength of the evidence supporting the current Flow State.
Early Flow Warning & Confirmed Signals
PFI separates early developing conditions from confirmed state transitions .
Early Flow Warning uses the live, still-forming candle to identify a potential transition before the candle closes. These warnings are intentionally provisional and may change or disappear as Price or Open Interest changes during the candle.
Confirmed Flow Signals are evaluated only when the candle closes.
Once confirmed, the LB / SB / SC / LU marker is based on the completed candle and does not change afterward.
This distinction allows traders to see developing positioning changes early while maintaining a clearly defined, non-repainting confirmation layer.
The indicator therefore does not attempt to hide the natural evolution of live Price and Open Interest data. Instead, it explicitly separates early information from confirmed information .
Price Sentiment
The optional Price Sentiment component provides an independent view of price behavior.
Price movement is smoothed and normalized over its recent range, then expressed on the same -100 to +100 scale as the Positioning Flow Index.
This allows Price Sentiment and PFI to be compared directly:
Price Sentiment describes the current character of price movement.
PFI incorporates both Price direction and Open Interest positioning.
The two therefore answer different questions and can provide additional context when interpreted together.
Flow State Ribbon
The optional State Ribbon provides a continuous visual representation of the current Flow State directly on the main price chart.
Teal represents Long Buildup.
Red represents Short Buildup.
Yellow represents Short Covering.
Orange represents Long Unwinding.
Gray represents Neutral conditions.
The intensity of the ribbon is influenced by Signal Strength, allowing stronger positioning conditions to stand out visually without requiring additional labels on every bar.
Flow Dashboard
The optional Flow Dashboard summarizes the current positioning environment through five key readings:
• Flow State — the current Price/OI positioning regime.
• Signal Strength — the strength of synchronized Price + OI evidence.
• PFI — the bounded Positioning Flow Index.
• Price Z-Score — how unusual the current price movement is relative to its recent history.
• OI Z-Score — how unusual the current Open Interest change is relative to its recent history.
Together, these readings provide both the classification and the underlying measurements used to interpret it.
How to Read PFI
PFI is best used as a contextual positioning tool rather than a standalone entry system.
A strong Long Buildup suggests rising price accompanied by expanding Open Interest.
A strong Short Buildup suggests falling price accompanied by expanding Open Interest.
A strong Short Covering condition suggests rising price while Open Interest contracts.
A strong Long Unwinding condition suggests falling price while Open Interest contracts.
The Signal Strength helps distinguish stronger synchronized conditions from weaker ones, while the PFI provides a continuous measure of directional positioning flow.
As with all market-structure and positioning analysis, these states describe the current relationship between Price and Open Interest—they do not guarantee future price direction.
Important Notes
PFI is designed for markets where Open Interest data is available.
The Flow State is based on the relationship between Price and Open Interest and should not be interpreted as a direct measure of individual trader intent.
Early Flow Warnings are intentionally repaintable during the active candle because they use live, developing Price and Open Interest data.
Confirmed Flow markers are non-repainting because they are generated only after the candle has closed.
The selected Flow Model affects the PFI calculation, while the Flow State and Signal Strength provide separate measurements of the underlying Price/OI relationship.
Summary
Positioning Flow Index brings Price and Open Interest together into a structured framework for analyzing market positioning.
Rather than asking only "Is price going up or down?" , PFI asks a broader question:
"What is happening to market positioning as price moves?"
By combining Flow State , Signal Strength , Positioning Flow Index , Price Sentiment , and confirmed versus early signals , PFI provides a multi-dimensional view of positioning that can be incorporated into discretionary market analysis and existing trading frameworks.
DISCLAIMER
This script is intended for informational and educational purposes only. It does not constitute financial, investment, or trading advice. All trading decisions made based on its output are solely the responsibility of the user.
Indikator

Indikator

Indikator

Equalhigh - Lepage Dual-Regime DetectorEqualhigh — Lepage Dual-Regime Detector
User Manual
Overview
The Equalhigh Lepage Dual-Regime Detector is a non-parametric change-point indicator for TradingView. It is designed to identify recent changes in either:
Location: the central level of the return distribution.
Scale: the dispersion of the return distribution.
Both simultaneously: a mixed structural break.
Unlike a conventional momentum oscillator, the indicator does not ask whether price is overbought or oversold. It asks whether recent return behavior is statistically different from earlier return behavior inside the active window.
This is a diagnostic regime detector, not an automatic buy-and-sell system.
Why use a location-scale test?
A market transition does not always begin with an obvious directional move. Sometimes the median return changes while volatility remains stable. In other cases, volatility expands or contracts before a clear directional shift becomes visible.
The Lepage framework combines two rank-based components:
The Wilcoxon rank-sum component measures a change in location.
The Ansari–Bradley component measures a change in scale.
The combined statistic can therefore detect more types of structural change than a location-only test.
Observation series
The test is applied to multi-bar logarithmic returns:
Observation = 100 × ln(Source / Source )
Using returns instead of raw prices reduces the tendency to classify the normal upward drift of an asset as a permanent structural break.
Logarithmic returns require positive source values. The indicator remains unavailable when the active window contains invalid or non-positive source observations.
Core calculation
For every active window, the script:
Stores the return observations chronologically.
Assigns average Wilcoxon ranks to equal observations.
Assigns average Ansari–Bradley center-weighted scores to equal observations.
Tests every split that leaves at least the selected Minimum segment size on both sides.
Standardizes the location and scale score sums at each split.
Calculates the Lepage statistic:
L = Z_location² + Z_scale²
Selects the split with the highest Lepage statistic.
Calculates the fixed-split asymptotic p-value:
p_fixed ≈ exp(−L / 2)
Applies a conservative Bonferroni correction for all admissible splits:
p_scan = min(1, Number of tested splits × p_fixed)
Uses medians and median absolute deviations to classify the type and practical size of the detected change.
The scan correction is important because selecting the strongest result from many candidate splits would otherwise make the displayed p-value too optimistic.
Understanding the components
Location Z
The location component is displayed with an intuitive directional sign:
Location Z > 0: the later segment shifted upward.
Location Z < 0: the later segment shifted downward.
A larger absolute value represents stronger rank-based location evidence.
Scale Z
The scale component describes the change in return dispersion:
Scale Z > 0: the later segment became more dispersed.
Scale Z < 0: the later segment became less dispersed.
A larger absolute value represents stronger rank-based scale evidence.
The combined statistic squares both components, so the p-value measures the strength of the overall break. The signs are used to interpret its direction.
Color system
Color or marker
Interpretation
Green — LEVEL +
Confirmed positive location shift without a qualifying scale shift
Red — LEVEL −
Confirmed negative location shift without a qualifying scale shift
Purple — VOL +
Confirmed scale expansion without a qualifying location shift
Blue — VOL −
Confirmed scale compression without a qualifying location shift
Orange — MIXED
Confirmed location and scale shift occurring together
Yellow — ?
Possible break with incomplete statistical confirmation
Gray
No currently actionable break
A volatility expansion is not automatically bearish, and a volatility compression is not automatically bullish. These states describe dispersion, not market direction.
The orange mixed state does not encode direction by itself. Use Median Shift and MAD Scale Shift in the dashboard to determine whether the mixed change combines an upward or downward level shift with expansion or compression.
Confidence line
The main line is calculated as:
Scan-adjusted confidence = 100 × (1 − p_scan)
The default boundaries are:
95: confirmed statistical zone when the confirmed p-value is 0.05.
85: possible statistical zone when the possible-break p-value is 0.15.
The line color reflects the currently classified regime.
Important: this confidence value is not the probability that price will rise, the probability that a trade will be profitable, a win rate, or a forecast-accuracy score.
Confirmation logic
A confirmed regime requires all of the following:
The scan-adjusted p-value is less than or equal to Confirmed scan p-value.
The estimated break is no older than Maximum actionable break age.
At least one component passes its practical-effect threshold.
The contributing component also passes Minimum component Z.
Positive or negative location shift
The robust location effect reaches Minimum location shift.
The absolute Location Z reaches Minimum component Z.
The scale component does not independently pass all its confirmation filters.
The sign of the median shift determines positive or negative classification.
Scale expansion or compression
The symmetric MAD scale-ratio change reaches Minimum scale-ratio change.
The absolute Scale Z reaches Minimum component Z.
The location component does not independently pass all its confirmation filters.
The MAD ratio determines expansion or compression.
Mixed break
Both the location and scale components pass their effect-size and component-Z filters.
Possible break
The scan-adjusted p-value is above the confirmed threshold but no higher than the possible-break threshold. At least one component must also reach half of its normal effect-size and component-Z requirements.
Dashboard
Dashboard field
Meaning
Lepage State
Current regime classification
Scan-Adj P
Bonferroni-adjusted approximate p-value for the split scan
Break Age
Estimated number of bars since the selected split
Location Z
Directional standardized Wilcoxon component
Scale Z
Directional standardized Ansari–Bradley component
Median Shift
Post-break median return minus pre-break median return, in percentage points
Location Effect
Median shift divided by a robust sigma estimate
MAD Scale Shift
Conventional percentage change from pre-break MAD to post-break MAD
Additional dashboard states include:
FILTERED BREAK: the combined statistic is significant and recent, but neither component passes all practical-effect and Z filters.
OLD BREAK: the combined statistic remains significant inside the window, but the estimated split is older than Maximum actionable break age.
STABLE REGIME: no currently actionable or possible break.
Input guide
1. Observations
Price sourceSeries used to calculate logarithmic returns. Close is the standard setting.
Log-return horizonNumber of bars covered by each return observation. Lower values react to short moves. Higher values emphasize slower market behavior but create more overlap between consecutive observations.
Lepage windowNumber of return observations in each rolling test. Short windows react faster but are noisier. Long windows are more stable but respond later.
Minimum segment sizeMinimum number of observations required before and after every candidate split. Increasing it reduces unstable edge detections but prevents the test from selecting extremely recent breaks.
2. Validation
Confirmed scan p-valueMaximum adjusted p-value for confirmation. The default is 0.05. Lower values produce fewer and more selective events.
Possible-break scan p-valueMaximum adjusted p-value for the yellow early-warning state. The default is 0.15.
Maximum actionable break ageMaximum number of bars allowed between the estimated split and the current bar.
Minimum location shiftMinimum median shift measured in robust sigma units. The robust sigma is 1.4826 × window MAD, with standard deviation used as a fallback when necessary.
Minimum scale-ratio change (%)Minimum symmetric difference between pre-break and post-break MAD. Symmetric measurement treats a doubling and a halving of scale as equally large changes for filtering purposes.
Minimum component ZPrevents a regime label from being attributed to a component that contributed too little to the combined Lepage statistic. The default is 1.00.
Confirm signals at bar closeWhen enabled, new markers and alert events are confirmed only when the current bar closes. This is the recommended setting.
3. Display
These settings independently control regime backgrounds, confirmed labels, possible-break markers, and the dashboard.
Suggested starting profiles
Use case
Return horizon
Window
Minimum segment
Maximum age
Location effect
Scale change
Component Z
General swing trading
5
60
10
10
0.25
25%
1.00
Faster monitoring
3
50
8
7
0.30
30%
1.25
Slower regime analysis
10
90
15
15
0.35
30%
1.00
These profiles are starting points, not optimized trading parameters. Test settings across different assets and unseen market periods.
Interpretation examples
Green location event
Suppose the dashboard shows:
Scan-adjusted p-value: 0.03
Break age: 6
Median shift: +0.80 pp
Location effect: +0.55 sigma
MAD scale shift: +10%
The evidence supports a recent upward change in the central return level, while the scale change remains below its filter.
Purple volatility-expansion event
Suppose the location effect is small, but post-break MAD is 60% higher, Scale Z is strongly positive, and the adjusted p-value is below 0.05. The indicator classifies a volatility expansion. Market direction must be determined separately.
Orange mixed event
If both median returns and dispersion change materially, the indicator displays MIXED. A positive Median Shift with a positive MAD Scale Shift represents improving returns accompanied by expanding volatility. A negative Median Shift with expanding volatility can represent a more hostile risk regime.
Practical workflow
Use ordinary candlesticks on a liquid instrument.
Keep Confirm signals at bar close enabled.
Treat yellow as an observation state rather than an entry instruction.
When a confirmed event appears, inspect Location Z, Scale Z, Median Shift, and MAD Scale Shift.
Confirm the interpretation with price structure, volume, liquidity, and higher-timeframe context.
Define entry, invalidation, position sizing, and exit rules independently.
The indicator is particularly useful as a regime filter. For example, a trend strategy may be treated differently during purple volatility expansion than during blue volatility compression.
Alerts
Six alert conditions are available:
Lepage — Possible break
Lepage — Positive level shift
Lepage — Negative level shift
Lepage — Volatility expansion
Lepage — Volatility compression
Lepage — Mixed regime break
A confirmed alert fires when a qualifying state first appears, when the confirmed regime type changes, or when the estimated split resets to a more recent point. A possible alert follows equivalent first-appearance and break-reset logic.
When bar-close confirmation is enabled, configure TradingView alerts as Once Per Bar Close.
Repainting and event timing
The script does not use future data, lookahead, or a negative plot offset. It places a marker on the bar where the break is detected and never moves that marker backward to the estimated historical split.
However, the estimator is rolling. As a new bar enters the window and an old bar leaves it, the selected split, component scores, p-value, break age, and current state can change. Values can also fluctuate on an open real-time bar. Bar-close confirmation prevents provisional intrabar markers from being treated as confirmed events.
Historical events are calculated only from information available on their respective bars.
Statistical limitations
The fixed-split chi-square p-value is asymptotic rather than exact.
Bonferroni correction is conservative because the candidate splits are dependent.
The correction covers the splits inside one window, not repeated testing across every bar in the chart.
Consecutive multi-bar returns overlap and are not independent. The adjusted p-value should therefore be interpreted as comparative evidence rather than a perfectly calibrated probability.
The classical Lepage components are most naturally interpreted as location and scale tests under regular distributional conditions. Strong skew changes or complex distribution changes can affect both components.
The detector selects one dominant split per rolling window. Multiple rapid changes can interfere with one another.
A statistically significant regime change does not guarantee persistence, directional continuation, or trading profitability.
Median absolute deviation can be close to zero on discrete or insufficiently variable data. The script uses a small numerical floor, but scale percentages can still become unusually large.
Results on Heikin Ashi, Renko, Range, Kagi, Point & Figure, or other synthetic charts describe transformed data rather than ordinary traded prices.
Always evaluate the indicator on unseen data and combine it with independent risk controls.
Data Window outputs
The script exposes:
State code.
Scan-adjusted p-value.
Estimated break age.
Location Z component.
Scale Z component.
Median shift in percentage points.
Robust location effect.
MAD scale change percentage.
Lepage statistic.
State codes are:
Code
State
4
Mixed location-scale break
3
Scale expansion
2
Positive location shift
1
Possible break
0
Stable, filtered, or old break
−2
Negative location shift
−3
Scale compression
TradingView publication metadata
Primary category: Oscillators
Secondary category: Trend Analysis
Suggested tags: Lepage Test, Change Point, Regime Detection, Statistics, Non-Parametric, Volatility, Structural Break
References
Y. Lepage, “A Combination of Wilcoxon's and Ansari-Bradley's Statistics,” Biometrika, 1971.
F. Rublík, “The Multisample Version of the Lepage Test,” Kybernetika, Vol. 41, No. 6, 2005, pp. 713–733: paper.
G. J. Ross, D. K. Tasoulis and N. M. Adams, “Nonparametric Monitoring of Data Streams for Changes in Location and Scale,” Technometrics, Vol. 53, No. 4, 2011, pp. 379–389: DOI.
H. Murakami, “A Nonparametric Location–Scale Statistic for Detecting a Change Point,” The International Journal of Advanced Manufacturing Technology, Vol. 61, 2012, pp. 449–455: DOI.
Disclaimer
This indicator is provided for research and educational purposes. It does not constitute investment advice, a recommendation, or a guarantee of future performance. Trading involves risk, including the possible loss of capital. Indikator

Equalhigh - Pettitt Structural Break DetectorEqualhigh — Pettitt Structural Break Detector
User Manual
Overview
The Equalhigh Pettitt Structural Break Detector is a statistical regime-change indicator for TradingView. It is designed to identify a recent change in the distribution of price returns rather than a conventional overbought, oversold, or moving-average condition.
The indicator applies a rolling version of Pettitt's non-parametric change-point test to logarithmic price returns. It estimates the most likely break location inside the active window, evaluates its statistical significance, measures the direction and size of the median shift, and filters out changes that are too old or too small to be considered actionable.
This is a diagnostic indicator, not an automatic trading system. Its purpose is to answer:
Has the recent return regime changed materially, in which direction, and with what level of statistical evidence?
Core calculation
The observation tested on each bar is the multi-bar logarithmic return:
100 × ln(Source / Source )
Inside the selected Pettitt window, the indicator:
Orders the observations chronologically.
Assigns non-parametric ranks, using average ranks for equal values.
Tests every admissible split while preserving the minimum segment size on both sides.
Selects the split with the largest absolute Pettitt statistic.
Calculates the approximate two-sided p-value:
p ≈ min(1, 2 × exp(-6K² / (n³ + n²)))
Compares the median return before and after the estimated break.
Standardizes the median shift by the rolling standard deviation.
Rejects breaks that are too old or have an insufficient effect size.
The test is non-parametric: it relies on ranks and does not require returns to follow a normal distribution.
Reading the indicator
The main line is a signed statistical-confidence display ranging from approximately -100 to +100.
Display
Meaning
Green
Recent, statistically confirmed upward shift in the return distribution
Red
Recent, statistically confirmed downward shift in the return distribution
Orange
Possible break; evidence is developing but does not yet meet the confirmed threshold
Gray
No currently actionable structural break
BULL label
A new confirmed upward structural-break event
BEAR label
A new confirmed downward structural-break event
Orange ?
A new possible upward or downward break
A positive reading means that the post-break median return is higher than the pre-break median. A negative reading means it is lower.
Important: a bullish break does not necessarily mean that returns are already positive. A change from strongly negative returns to mildly negative returns is an upward structural shift and can therefore be classified as bullish. Price structure should still be checked separately.
The displayed confidence is calculated as 100 × (1 − p-value). It is not the probability that a trade will be profitable, the probability that price will rise, or a forecast accuracy score.
Confirmation rules
A confirmed break requires all of the following:
The approximate p-value is less than or equal to the Confirmed p-value setting.
The estimated break age does not exceed the Maximum actionable break age.
The absolute median-shift effect reaches the Minimum median-shift effect.
The post-break median is different from the pre-break median.
A possible break requires:
A p-value above the confirmed threshold but no higher than the Possible-break p-value.
A recent estimated break.
At least half of the selected minimum effect size.
Dashboard
The statistical dashboard provides five fields:
Field
Interpretation
Pettitt State
Current classification: stable, possible break, confirmed break, or old break
P Value Approx
Approximate probability of observing a Pettitt statistic at least this extreme under the no-change hypothesis
Break Age
Estimated number of bars since the detected split
Median Shift
Post-break median return minus pre-break median return, in percentage points
Effect Size
Median shift divided by the rolling standard deviation of the tested returns
An OLD BREAK state means that statistically significant evidence remains inside the window, but the estimated change point is older than the selected actionable-age limit.
Inputs
1. Observations
Price sourceSelects the series used in the logarithmic-return calculation. Close is the standard choice.
Log-return horizonDefines the number of bars used for each return observation. A higher value focuses on slower moves but creates more overlap between consecutive observations.
Pettitt windowDefines the number of observations included in each rolling test. Short windows react faster but are noisier. Long windows are more stable but detect changes later.
Minimum segment sizePrevents the estimated split from being placed too close to either edge of the window. Larger values reduce unstable edge detections but also delay recognition of very recent changes.
2. Validation
Confirmed p-valueMaximum approximate p-value for a confirmed break. 0.05 is the default. Lower values are more selective.
Possible-break p-valueMaximum p-value for the orange early-warning state. 0.15 is the default.
Maximum actionable break ageMaximum number of bars allowed between the estimated break and the current bar. This prevents an old statistical event from being treated as a fresh signal.
Minimum median-shift effectMinimum absolute standardized median shift required for confirmation. 0.25 means that the shift must represent at least one quarter of the rolling return standard deviation.
Confirm signals at bar closeWhen enabled, new labels and alert events are confirmed only after the current bar closes. This is the recommended setting.
3. Display
These controls independently enable the regime background, confirmed labels, possible-break markers, and statistical dashboard.
Suggested starting profiles
Use case
Return horizon
Window
Minimum segment
Maximum age
Minimum effect
General swing trading
5
60
10
10
0.25
Faster market monitoring
3
50
8
7
0.30
Slower regime analysis
10
90
15
15
0.35
These are starting points, not optimized trading parameters. Settings should be tested across different symbols and market regimes without selecting them solely from the best historical result.
Practical workflow
Use a liquid instrument and ordinary candlestick data.
Keep bar-close confirmation enabled.
Treat orange as an observation state, not an entry instruction.
When a confirmed label appears, check whether price structure, volume, volatility, and the higher-timeframe context support the same interpretation.
Use the p-value, effect size, and break age together. A small p-value alone does not guarantee a useful trade.
Define entry, invalidation, position size, and exit rules independently.
For example, a green event with p = 0.02, a break age of 6 bars, and an effect size of +0.60 sigma represents a recent and statistically meaningful upward shift. It becomes more useful if price has also reclaimed an important level or broken a declining structure.
Alerts
Four alert conditions are available:
Pettitt — Possible bullish break
Pettitt — Possible bearish break
Pettitt — Bullish structural break
Pettitt — Bearish structural break
Alerts fire when a qualifying state first appears or when the estimated break resets to a more recent point while the same directional condition remains active. With bar-close confirmation enabled, alerts should be configured Once Per Bar Close.
Repainting and timing
The script does not use future data, lookahead, or a negative plot offset. A signal is displayed on the bar where the break is detected; it is not placed retrospectively on the estimated historical change point.
However, this is a rolling estimator. As new bars enter the window, the most likely split, p-value, break age, and state can change. On a live unclosed bar, values can also move with price. Enabling Confirm signals at bar close prevents provisional intrabar labels from being treated as confirmed events.
Limitations
Pettitt's test identifies the dominant single change point inside the active window. Multiple rapid regime changes can interfere with one another.
The p-value is an approximation, not an exact posterior probability.
Consecutive multi-bar returns overlap and are therefore not independent. This makes the p-value best treated as comparative statistical evidence rather than a perfectly calibrated probability.
A statistically significant distribution shift does not guarantee trend continuation or trading profitability.
Outliers are less influential than in many mean-based tests, but they can still affect the detected split and the rolling volatility denominator.
Very short windows are noisy; very long windows can react too slowly.
Logarithmic returns require positive source values. The test remains unavailable when the selected source contains invalid or non-positive observations inside the active window.
Results on Heikin Ashi, Renko, Range, Kagi, or other synthetic chart types describe the transformed data rather than standard traded prices.
Always evaluate the indicator on unseen data and combine it with independent risk controls.
Data Window outputs
The script exposes the following values for inspection and alert integration:
State code: +2 confirmed bullish, +1 possible bullish, 0 stable, −1 possible bearish, −2 confirmed bearish.
Approximate p-value.
Estimated break age.
Median shift in percentage points.
Median-shift effect size.
Pettitt K statistic.
Reference
A. N. Pettitt, “A Non-Parametric Approach to the Change-Point Problem,” Journal of the Royal Statistical Society: Series C (Applied Statistics), Vol. 28, No. 2, 1979, pp. 126–135. DOI: 10.2307/2346729.
Disclaimer
This indicator is provided for research and educational purposes. It does not constitute investment advice, a recommendation, or a guarantee of future performance. Trading involves risk, including the possible loss of capital. Indikator

Market Leadership Structure 3D [NeuralMarkets]OVERVIEW
Market Leadership Structure 3D compares six assets to show who is driving the group, who is following, and whether leadership is persistent or rotating.
It separates relative rank from absolute evidence. The top-ranked asset is always shown as the relative candidate, but the script reports NO CLEAR LEADER unless that candidate has sufficient evidence, separation from the runner-up, and at least one qualified outgoing relationship.
The indicator provides three views:
• Summary
• Leadership Terrain
• Parameter Stability
HOW IT WORKS
For every asset pair, the model compares both possible lead-lag directions.
Directional evidence blends the strongest positive lagged correlation with the average positive correlation across the tested lags.
Directional advantage A → B = Evidence A → B − Evidence B → A
An edge is retained only when it passes Minimum Forward Evidence and exceeds the reverse direction by Minimum Directional Asymmetry.
Qualified edges form a directed network using NeuralMarketsNetworkToolkit:
Net influence = Outbound influence − Inbound influence
The asset with the highest smoothed net influence receives rank #1. Recognition requires separate absolute-evidence and rank-separation thresholds, so being ranked first does not automatically imply meaningful leadership.
READING THE SUMMARY
Recognized — The accepted leader or NO CLEAR LEADER.
Relative candidate — The asset currently ranked #1, even when evidence is insufficient for recognition.
Absolute evidence — Strength and coverage of the candidate’s qualified outgoing relationships. It is not min-maxed and does not force the strongest asset to score 100.
Rank separation — Normalized gap between the top two assets. A small gap means leadership is closely contested.
Leader persistence — Share of the history window occupied by the current recognized leader. No-clear-leader bars remain separate states.
Clear-state share — Percentage of the history window in which any clear leader existed.
Rotation risk — LOW, MEDIUM, HIGH, or UNDEFINED when no leader is recognized.
Concentration — Whether directional influence is concentrated or broadly distributed.
The optional ranking table shows all six assets with net influence, absolute evidence, and normalized leadership.
LEADERSHIP TERRAIN
The waterfall mesh displays all six assets through recent history:
• X-axis: ticker
• Depth: historical slices from NOW toward older bars
• Height: normalized leadership, approximately −1 to +1
Above zero indicates more outbound than inbound influence. Below zero indicates follower behavior. Each historical ridge is drawn as a colored curtain from the zero plane, while rails connect each ticker through time. Older slices fade to keep the current structure prominent.
Look for:
• A sustained elevated ridge — persistent leadership
• A ridge rising toward NOW — strengthening leadership
• A ridge falling toward zero — fading leadership
• Two similar current peaks — close competition
• Rapidly alternating peaks — unstable rotation
• A flat surface near zero — weak directional structure
A leader marker appears only when the recognition requirements are satisfied.
PARAMETER STABILITY
This view rebuilds the network across a 6 × 6 grid:
• X-axis: relationship lookback
• Depth: maximum lag from 1 to 6 bars
• Height and color: robustness
Robustness combines 50% absolute evidence, 30% rank separation, and 20% agreement with the currently recognized leader. Cells without qualified outgoing coverage score zero.
Broad elevated regions indicate that leadership survives several parameter choices. An isolated peak suggests that the result is parameter-sensitive.
HOW TO USE IT
1. Choose a coherent universe
Use a preset or select six related assets. Interpretation is clearest when the group represents one theme, such as cross-asset ETFs, US sectors, or mega-cap stocks.
2. Check the recognized state
If the script reports NO CLEAR LEADER, do not treat the relative candidate as confirmed leadership.
3. Confirm evidence and separation
Prefer cases where the candidate has both meaningful absolute evidence and adequate distance from the runner-up.
4. Check persistence and rotation
Established leadership is generally more credible than a one-bar rank change. Falling persistence, a young leader age, or HIGH rotation risk signals a less settled structure.
5. Inspect Leadership Terrain
Check whether the leader remains above zero through history and whether its ridge strengthens toward NOW. Watch for challengers rising beneath it.
6. Inspect Parameter Stability
Prefer a broad plateau over one sharp peak. If leadership disappears after a small lookback or lag change, it is fragile.
7. Use alerts to trigger review
Alerts identify structural transitions. Combine them with price action, trend, liquidity, and risk management rather than treating them as automatic entries.
UNIVERSE PRESETS
Cross-Asset — SPY, QQQ, IWM, HYG, TLT, DBC
US Sectors — XLK, XLF, XLY, XLI, XLE, XLV
Mega-Cap — NVDA, MSFT, AAPL, META, AMZN, GOOGL
Custom — Six user-selected symbols
IMPORTANT SETTINGS
Relationship Lookback — Estimation window. Shorter values react faster but are noisier.
Maximum Lead Lag — Earlier bars tested. One lag equals one chart bar.
Rank Smoothing — Reduces rank churn at the cost of slower response.
Leadership History — Window used for persistence and rotation statistics.
Minimum Forward Evidence — Minimum blended relationship required for an edge.
Minimum Directional Asymmetry — Required advantage over the reverse direction.
Minimum Absolute Evidence / Rank Separation — Requirements for recognizing a clear leader.
Terrain spacing, skew, separation, and height settings change only the drawing—not the model.
KEY DEFAULTS
Relationship Lookback: 80
Maximum Lead Lag: 5
Directional Weight Power: 1.25
Rank Smoothing: 3
Leadership History: 100
Minimum Forward Evidence: 0.18
Minimum Directional Asymmetry: 0.02
Minimum Absolute Evidence: 15
Minimum Rank Separation: 5%
Terrain History: 8 slices spaced 5 bars apart
ALERTS
Clear Leader Rotation — Fires only on a direct transition between two different recognized leaders. A transition through NO CLEAR LEADER is not counted.
High Rotation Risk — Fires when risk changes to HIGH while a clear leader exists.
Clear Leader Established — Fires when the candidate first satisfies the recognition requirements.
Clear Leader Lost — Fires when the recognized leader no longer satisfies them.
LIMITATIONS
This indicator is descriptive market-structure research, not a calibrated probability or a claim of predictive alpha.
Lagged correlation and directional asymmetry do not establish causality. The model focuses on positive lead-lag relationships and does not explicitly represent inverse edges.
Parameter Stability measures current in-sample robustness, not out-of-sample forecasting performance. The terrain is a 2D perspective projection whose appearance depends on chart zoom.
Results depend on timeframe, available history, liquidity, and alignment between trading sessions. All six symbols should have sufficient data.
Use rank to identify the relative candidate. Use evidence, separation, persistence, terrain, and parameter stability to decide how seriously that ranking should be taken.
Indikator

Indikator
