Correlation Matrix [AFD]Correlation Matrix turns the active chart into a one-to-many cross-asset relationship monitor. It compares the chart symbol with up to eight instruments and brings slower and faster return correlation, fitted return sensitivity, matched spread distance, pair-specific correlation history, and data availability into one dashboard.
It is designed to answer practical research questions: Which selected markets have been moving with or against the chart symbol? Has recent co-movement departed from the slower relationship? How sensitive has the chart symbol been to each comparison? Is the matched spread unusually displaced for that pair? Is the reading supported by enough shared observations to interpret responsibly?
Built-in Symbol sets and Measurement presets provide repeatable samples. A Measurement preset selects a requested timeframe and Long/Short windows; it never changes the chart candles or requires a matching chart timeframe. Custom can follow the chart or request a fixed measurement timeframe. Optional rebased lines use a separate visual baseline. All outputs are descriptive measurements, not automated decisions.
What It Is Useful For
Cross-asset mapping: Place an index, sector, currency, commodity, rate-sensitive instrument, volatility index, or digital asset on the chart and compare it with a preset universe or a Custom basket. This helps organize intermarket context around one common reference symbol.
Relationship-change monitoring: Treat Long Correlation as the slower context sample and Short Correlation as the faster sample. Correlation Difference shows how far the faster coefficient sits above or below the slower one, while the two coefficients preserve their direction and sign. It is a comparison of two estimates, not a formal regime or significance test.
Benchmark and proxy research: Compare correlation with Beta to separate consistency of co-movement from fitted magnitude of response. This can help screen which selected benchmark, sector, or macro proxy has historically had the closest relationship to the chart symbol. It is not factor attribution.
Candidate-hedge research: Screen for relationships that have been negative across the selected windows, then use Beta and Data Coverage as sensitivity and sample context. The output can narrow further research; it does not select a hedge, calculate contract quantities, or account for liquidity, basis, carry, costs, or portfolio constraints.
Relative-value triage: Use Spread to identify a matched relationship that is unusually displaced from its own Long-window average, then use correlation, History, and usable-sample counts to judge whether the observation deserves investigation. Spread is not a cointegration test, regression residual, stationarity test, or mean-reversion forecast.
Exposure-overlap review: Chart one holding at a time against a Custom basket to identify potentially redundant co-movement or sensitivity. This is useful for screening concentration questions, but it is not a portfolio covariance engine or risk model.
Sample-integrity review: Read Data Coverage and the usable Long/Short return counts before interpreting a coefficient, especially across different sessions, holidays, young listings, or sparse feeds. These are availability disclosures, not confidence or quality scores.
Event and baseline comparison: Rebase percentage paths from Session Open, Rolling N Bars, Year Open, or a Fixed Date to inspect divergence after a session boundary, calendar reset, or chosen event. These chart lines are visual comparisons and never feed the statistics.
Capabilities
Eight configurable comparison slots. In Custom mode, each slot has a symbol, optional display name, color, Enabled switch, and Show comparison line switch. Blank slots remain hidden; an invalid or unavailable symbol displays No data without stopping valid rows.
Five built-in Symbol sets: United States Indices, Risk On / Off, Major Foreign Exchange Pairs, Energy & Metals, and Crypto. Custom values are retained while a set temporarily supplies eight symbols and ticker-derived names. Risk On / Off supplies comparison instruments; it does not classify the market.
Three Measurement presets plus Custom: Scalper requests 1 minute with Long 60 / Short 15; default Intraday requests 5 minutes with Long 78 / Short 20; Swing requests 1 day with Long 120 / Short 20. Swing on a 30-minute chart is an intended configuration, not an error: chart candles remain 30 minutes while completed 1-day observations drive measurements. Custom exposes the timeframe and both windows.
Long Correlation, Short Correlation, Main Correlation, Correlation Difference, Long-window Beta, signed Spread z-score, optional History percentile, and Data Coverage. Tooltips disclose usable Long/Short returns and fresh-versus-eligible coverage counts.
Contextual hover help on every dashboard heading and cell. It explains metric definitions, sample requirements, and unavailable states, with additional detail for Beta direction and fitted sensitivity, active Spread form and position, History's prior range and average, and Data Coverage endpoint counts.
Context, Compact, Full, Minimal, and Custom dashboard views; an independent Correlation Difference switch; custom column overrides; nine table positions; slot, absolute Long Correlation, or absolute Spread sorting; and Heat or Mono cells.
Optional rebased comparison lines with Auto from measurement preset, Session Open, Rolling N Bars, Year Open, and Fixed Date baselines. Seven appearances, a shared baseline marker, configurable line-end labels, and one-slot gap shading are included.
Separate dashboard and comparison-line visibility switches. Measurements continue while either visual layer is hidden. Status text identifies chart and effective measurement timeframes; its tooltip also identifies the requested timeframe, completed higher-timeframe sampling, lower-timeframe fallback, active windows, adjusted Short window, and visual line baseline.
Dashboard text, colors, backgrounds, transparency, alternating rows, borders, frame, line width/transparency, marker styling, label styling, gap colors, and a global master-opacity control can be adjusted without changing measurements.
How the Statistics Work
Correlation is computed on log returns, never on raw price levels. Correlating two trending price series directly can produce a spuriously high reading that reflects their shared trend rather than how their returns move together.
Pearson correlation has no universal market timeframe or lookback. The effective measurement timeframe and window define the observations. A 120-bar window with 1-minute measurements and the same window with 5-minute measurements are different samples and can produce different coefficients.
Correlation runs from +100% through 0% to -100%. It standardizes direction and consistency of linear co-movement; it does not imply equal-sized returns. Correlation Difference is computed as Short minus Long and displayed as a rounded signed number in percentage points.
Beta uses Long-window matched returns and direct covariance/comparison-return variance. From the chart symbol's perspective, Beta +1.20 describes a fitted 1.20-unit chart-symbol log-return response per 1.00 unit of comparison-symbol return in that sample. It is directional and asymmetric, and is benchmark beta only when the comparison is the intended benchmark.
Spread is a signed population z-score of an equal-weight matched log spread. Non-negative Long Correlation selects log(chart) minus log(comparison); negative Long Correlation selects log(chart) plus log(comparison). Separate histories are maintained for the ratio and product forms. The tooltip identifies the active form and whether the latest spread is above or below its matched Long-window average.
When the chart symbol is selected as its own comparison under the same request context, the ratio log-spread has zero variation. Its z-score is therefore unavailable rather than 0.0; after warm-up, identical requested data with measurable return variation produce +100% correlation, zero Difference, and Beta 1.
History ranks the current Main Correlation against only that pair's prior valid Main Correlation readings in the Historical window. A tie-aware midrank makes an all-tie sample read 50/100. It describes relative position inside the pair's own history, not statistical confidence or a forecast.
Data Coverage is fresh comparison endpoints divided by eligible Long-window measurement positions after the comparison first appears in loaded data. A carried timestamp is not counted twice. Coverage is distinct from the usable matched returns reported in the tooltips and does not alter any statistic.
Shared-Endpoint Alignment and Confirmation
At each chart-base measurement observation, the script selects the latest completed comparison endpoint known by that base close and maps it to the nearer current or preceding base close; a tie remains on the current close. A return pair is created only between consecutive accepted endpoint pairs when both base and comparison timestamps strictly advance.
Missing bars, holidays, and session gaps accumulate both instruments from the same prior shared endpoint instead of pairing different elapsed intervals. The accumulated interval remains one observation; it is not duration-normalized or split into synthetic bars. An unmatched observation writes one unavailable window position. A star marks a latest fresh comparison endpoint mapped to the preceding base close.
A complete configured measurement window, at least three usable returns, and measurable variation are required before Pearson is shown. Beta requires measurable comparison-return variance. Blank results are intentional when these conditions are not met.
Equal-timeframe requests use lookahead off and statistical snapshots commit on chart confirmation. Fixed higher measurement timeframes use completed bars: every requested price and timestamp field is offset by one measurement bar before lookahead is enabled. The chart timeframe does not need to match. A requested measurement timeframe below the chart falls back to the chart timeframe and produces an amber warning.
The chart-base request retains the active chart's complete ticker context. A slot set to the chart symbol reuses that exact context; other nonblank comparisons inherit applicable session, price-adjustment, currency, and futures modifiers. PulseWire ignores modifiers that do not apply to a comparison instrument. Changing an applicable modifier can change requested prices, timestamps, measurements, coverage, and rebased lines.
The comparison lines are a ratio, not a 1:1 price overlay
The optional chart lines do not plot the other symbol's raw price or its correlation. Each line is tied to the chart symbol's measurement-timeframe price, then moved forward by the percentage change of the compared symbol from that line baseline:
That is a ratio calculation, not a 1:1 mirror of price. Every drawn line uses the same baseline rule when measurement data is available, so its percentage path shares the chart's scale regardless of what either instrument costs.
Comparison line starting point is visual only. Auto from measurement preset uses Session Open for Scalper, Intraday, and Custom, and Year Open for Swing. Fixed Date sets the first base boundary on or after the date. Rolling N Bars moves the shared boundary. Each comparison waits for fresh eligible data, so a line can begin after the marker, remain blank, or jump as a rolling window changes. No line setting changes any dashboard measurement.
Settings
Quick Setup: Measurement preset selects timeframe and Long/Short windows without changing or requiring a matching chart. Dashboard view and Show correlation difference control columns. Symbol set controls the universe. Show dashboard and Show comparison lines control visual layers. Comparison line starting point controls rebased visuals.
Symbols and slots: Custom is the default Symbol set. On an SPY chart, the starting Custom symbols are QQQ, DIA, and IWM; the remaining slots are blank. These are examples, not recommendations. A blank display name derives the ticker automatically. Built-in sets override retained Custom symbols and names until Custom is selected again.
Custom measurements: Blank Custom timeframe follows the chart; a fixed selection at or above the chart holds its requested sampling without changing candles. Long defaults to 120 (range 10-1000); Short to 20 (range 5-200). If Short is not below Long, effective Short becomes Long minus one and appears in amber. Long changes Long, Difference, Beta, Spread, and Coverage; Short changes Short and Difference.
Main Correlation and History: Main correlation window defaults to Short and selects the existing Long or Short result used by Main Correlation, History, and line-end correlation text. Historical comparison defaults off. Its window defaults to 750 and accepts 100-5000 effective measurement positions; History remains blank until the full measurement window exists.
Dashboard views and columns: Default Context shows Symbol, Long, Short, Spread, and Coverage; Compact shows Symbol, Short, and Spread; Full shows Symbol, Long, Short, Beta, Spread, Coverage, and enabled History; Minimal shows Symbol and Main; Custom uses individual metric switches. Custom columns can override any view. Difference is independently on by default.
Dashboard layout: Nine positions default to Top Right. Sorting uses Slot order, strongest absolute Long, or widest absolute Spread. Cells use Heat or Mono. Text, colors, backgrounds, transparency, row shading, borders, and frame are adjustable.
Comparison line style: Solid is the default; Dashed, Dotted, Step, Step with diamonds, Points, and Crosses are available. Width defaults to 2 and transparency to 50. Area, histogram, and column modes are intentionally excluded because they can obscure candles or distort the price scale.
Starting-point details: Rolling N Bars defaults to 120 and accepts 10-1000 effective measurement bars. Each line waits for its first fresh valid endpoint at or after the shared rolling boundary. Fixed Date is editable and defaults to 1 January 2026. The optional shared marker has style, color, transparency, and width controls.
Gap shading and labels: Gap shading can fill between chart price and one selected rebased slot with separate chart-above/chart-below colors and transparency. Line-end labels can include display name, Main Correlation, and Spread, with size and slot/custom text-color controls.
Global appearance: Master opacity adds fade to table cells/text, lines, marker, fill, and labels; table border and frame keep their own colors. Appearance, visibility, ordering, and baseline controls do not alter calculations.
What It Does Not Do / Limitations
This is a one-to-many dashboard: every row compares one instrument with the active chart symbol. It is not a full pairwise matrix among all eight comparisons, a covariance matrix, portfolio optimizer, factor model, value-at-risk calculation, or position-sizing engine.
Correlation measures a historical linear relationship in returns. It does not establish causation, forecast persistence, detect nonlinear dependence, or label a pair bullish or bearish.
Correlation Difference is not a hypothesis test or statistical regime detector. The indicator does not calculate p-values, confidence intervals, statistical significance, or multiple-comparison adjustments.
Beta is a backward-looking fitted sensitivity with the chart symbol as the dependent return series. It is not symmetric and is not a dollar-, volatility-, or contract-neutral hedge ratio.
Spread is an equal-weight log ratio/product z-score selected by the sign of Long Correlation. It does not establish cointegration, stationarity, fair value, or an expectation of mean reversion.
History percentile and its Low-to-High context bands are relative only to that pair's prior Main Correlation. They are not confidence levels, relationship grades, decision rules, or forecasts.
Data Coverage measures fresh endpoint availability, not data accuracy, sample quality, or statistical reliability. Markets with different sessions can supply fewer usable returns, and an interval accumulated across a gap remains one observation.
Results depend on PulseWire's feed, exchange and session coverage, loaded history, selected symbols, applicable chart modifiers, effective measurement timeframe, and window lengths. Changing session, price adjustment, currency conversion, supported futures settings, or other applicable data settings can change the values.
The indicator requires standard, time-based candles. Non-standard chart types and tick charts halt with a runtime message because the measurement contract requires ordinary time-based OHLC bars rather than synthetic or tick-built observations.
Blank Custom timeframe follows the chart. Built-in presets and fixed Custom timeframes do not require a chart match. A request below the chart falls back to the chart timeframe; a fixed higher timeframe excludes the developing measurement bar and can update up to one confirming chart bar later.
Blank cells indicate insufficient measurement history, matched returns, or variation. A line can begin after its marker or remain blank when no fresh baseline observation exists. Rebased lines can stretch autoscale, and Rolling N Bars can jump as its denominator moves.
The implementation keeps eight static comparison requests plus one chart-base request. Disabling a slot changes the display but does not remove its request or reduce the fixed request cost.
This measurement-only build does not generate alerts, classify relationships, automate decisions, execute orders, or provide position- or risk-management instructions.
Design and Originality
Pearson correlation, covariance, Beta, and z-scores are standard statistics. This implementation integrates an eight-instrument universe, independent measurement and visual baselines, two return windows, causal shared-endpoint matching, sample disclosures, direct Beta, separate ratio/product spread histories, prior-only tie-aware History, sortable views, and fresh-boundary rebased lines.
The components share one confirmed measurement clock and interpretation surface. They combine slower/faster relationship context, fitted sensitivity, availability, spread displacement, pair history, and normalized paths without importing an external correlation series or creating a classification state.
Open-source License
This is an open-source publication. The source is licensed under the Mozilla Public License 2.0 (MPL 2.0) and includes AuctionFoundry attribution. Reuse in another PulseWire publication must first satisfy PulseWire's open-source reuse rules; once those rules are met, the MPL 2.0 terms apply.
Disclaimer
For educational and informational purposes only. Not financial advice. Indicator

FULCRUM: Rates & Vol Adjusted Ratio VWAPWHAT IT DOES
The fulcrum of the index complex: a rates-and-volatility-adjusted VWAP for the relationship between two markets. It rebuilds the NQ/ES ratio bar by bar — 2500·NQ/ES, normalized by VXN×US10Y — then anchors a volume-weighted mean with ±1σ and ±2σ bands on that relative-value series. One line that says whether tech is rich or cheap against the broad market, and how stretched the move is. It lives in its own pane, works on any chart, and configures itself.
HOW IT WORKS
Both legs are requested at chart resolution, and the bar's ratio high/low come from the cross-extremes (NQ high over ES low, and the reverse) — the VWAP sees the bar's true range, not just closes.
A spread has no volume of its own, so weighting borrows the geometric mean of both legs' volume.
The rates/vol divisor uses the PRIOR session's confirmed VXN and US10Y closes — identical live and on reload. No repaint.
The anchor is automatic: session on charts up to 20m, week up to 4h, month above. Override it if you disagree.
Bands come from cumulative volume-weighted variance, not a rolling stdev, and stay hidden for the first bars after each reset while they cook.
The ratio line holds its color until the move clears ±0.15σ — color changes are regime, not noise. A faint tint marks ±2σ extension.
A live table reads VWAP, ratio, Δ%, σ-distance, zone, and the divisor's status — if a feed is missing it says so instead of guessing silently.
HOW TO USE IT
Read the relationship against its anchored mean: +2σ on a ratio behaves like +2σ on price — stretched, and usually walked back. Cross alerts on VWAP, ±1σ, and ±2σ are included. Swap the symbols and multiplier and it generalizes to any pair you trade.
WHAT IT CAN'T DO
It describes the relationship, not direction — the ratio falling doesn't say whether NQ is weak or ES is strong. If the VXN or US10Y feed is unavailable, the divisor falls back to sane defaults and the table flags it; it will not pretend.
SETTINGS
Numerator, denominator, and multiplier; VXN×US10Y normalization; auto or manual anchor (session, week, month); band multipliers; warm-up hiding; colors, fill, labels, table.
Open source. Free. Where the balance sits. Indicator

Smart Money Fibonacci OTE Engine [ChartPrime]🔶 OVERVIEW
In the world of Smart Money Concepts (SMC), finding a "cheap" or "expensive" price is not enough—you need to find the Optimal Trade Entry (OTE). The Smart Money Fibonacci OTE Engine is an automated structural analysis tool that identifies trend shifts and projects institutional retracement zones in real-time.
Unlike traditional Fibonacci tools that require manual drawing, this engine detects Break of Structure (BOS) events and automatically anchors a Fibonacci grid to the most relevant swing points. It specifically highlights the OTE zone, where institutional buying or selling typically occurs after a trend confirmation.
🔶 CORE MECHANICS: AUTOMATED ANCHORING
The engine operates on a sophisticated "Pivot and Shift" logic:
Swing Detection: The script monitors price for structural Swing Highs and Swing Lows based on your chosen pivot length.
Fibonacci Direction Shift Recognition: A direction shift is confirmed when pivot price exceeds the previous Swing Pivot High (Higher High), and a down direction shift is confirmed when price drops below the previous Swing Pivot Low (Lower Low).
Dynamic Stretching: Once a direction is established, the Fibonacci grid "breathes" with the market. If the trend continues to make new highs or lows, the grid automatically stretches to include the new extension, ensuring your retracement levels are always mathematically accurate.
🔶 THE OPTIMAL TRADE ENTRY (OTE) ZONE
The OTE zone is the primary focus of this indicator. Based on ICT (Inner Circle Trader) concepts, the OTE represents the "sweet spot" of a retracement.
The Range: By default, the zone is plotted between the 0.618 and 0.786 Fibonacci levels.
Institutional Discount/Premium: In a bullish trend, price retreating into the OTE zone is considered "buying at a discount." In a bearish trend, a rally into the OTE is "selling at a premium."
Visual Clarity: The zone is highlighted with a colored box (teal for bull, red for bear), making it easy to identify exactly where to look for price action reversal signals.
🔶 KEY VISUAL FEATURES
Structure Labels: Automatically marks HH (Higher High) and LL (Lower Low) points with Break-of-Structure (BOS) lines.
Swing Diagonal: A dotted line connects the two anchor points of the Fibonacci grid, providing a clear visual representation of the current swing's slope and magnitude.
Extended Levels: Horizontal Fibonacci lines (0.236, 0.382, 0.5, etc.) are projected across the chart, with price-sensitive labels that update every tick.
Historical Mode: Toggle "Show Previous Fibs" to see where past OTE zones were respected, helping you backtest the current asset's adherence to Fibonacci levels.
🔶 INDICATOR INPUTS
Pivot Length: Adjust this to filter between micro-structure (short length) and macro-structure (long length).
OTE Upper/Lower Levels: Fully customizable boundaries for your entry zone.
Visual Styles: Change line styles (Solid, Dashed, Dotted) and colors for the grid, labels, and structure shifts to match your chart theme.
🔶 TRADING UTILITY
High-Probability Entries: Instead of "chasing" a breakout, wait for the Smart Money Fibonacci Engine to identify the higher high or lower low, then wait for price to return to the OTE box.
Confluence Tool: Use the OTE zone in conjunction with Order Blocks or Liquidity Sweeps. When an OTE zone aligns with a previously swept EQL or EQH, the probability of a reversal increases significantly.
Objective Profit Taking: Use the 0.0 (origin) and various extension levels as objective targets for scaling out of positions.
🔶 CONCLUSION
The Smart Money Fibonacci OTE Engine removes the subjectivity from drawing Fibonacci retracements. By automating the detection of market structure and highlighting the most statistically relevant entry zones, it allows traders to focus on execution rather than chart drawing. Indicator

Volume To Bar Range RatioThis script plots
volume / (high - low)
for each bar. A simple measure of how much volume was traded per unit of price range.
Usage
In normal trading bars, volume tends to be correlated to the size of the bar. Small bars have small volume, large bars have large volume. However, key bars tend to have an unusually high ratio of range to volume. This is useful for identifying areas of support and resistance, when they are broken, and key runaway days when price goes parabolic.
Support and Resistance
When price is near an area of support or resistance, or approaching a recent high/low, a small bar with unusually high volume tends to be an indicator that the support/resistance is holding.
When price breaks through an area of support or resistance, or makes a new high or low, and the bar that does is large with an unusually high ratio of volume to range, this is an indicator that support/resistance has been decisively broken. Conversely, if the bar is large, but the ratio of price to volume is similar to other large bars, it is a warning that this might not be a decisive break.
Key Runaway Days
When price has become parabolic and has made several consecutive large moves up, a large bar with a volume to bar range ratio that is extremely high, higher than any other bar made previously, this is an indicator that a runaway day is occurring. Price is unlikely to continue moving parabolically after this day, and it would be a good time to take profits.
Notes
Bars where `high == low` produce `na` (a gap in the plot) to avoid division by zero.
Works on any symbol and timeframe that reports volume.
Note on Originality
This is the first, only, and original implementation of Volume to Bar Range Ratio available in PineScript. This can be easily verified with a search for "Volume to Bar Range Ratio", "Volume Bar Range Ratio", "VBRR", and"VTBRR" on PulseWire. Also, a Google search for the same terms, adding "pinescript" or "pulsewire" shows that my implementation is the only implementation, and the only other result is a complaint on reddit that this does not exist. Indicator

Indicator

Efficiency Divergence OscillatorEfficiency Divergence Oscillator
## Overview
The Efficiency Divergence Oscillator turns the **signed efficiency ratio** - net price displacement divided by the total path price actually travelled - into a standardized, bounded oscillator, and then looks for **divergence between price and the efficiency of its travel**. The idea it tests: when price makes a new extreme but reaches it on an increasingly choppy, inefficient path, the move is losing conviction.
It is a single-pane oscillator. It needs no external data and no volume. Every data input is user-configurable, so it runs on any symbol, asset class or timeframe, in any market and on any timeframe. Defaults target NSE NIFTY index futures on intraday charts.
## What it plots
- A z-scored **efficiency oscillator** (clean advance = up, clean decline = down, choppy travel = near zero), with a glow line and sigma-based overbought/oversold levels.
- **Extreme-zone bands** (default +/-3 sigma) with a gradient fill that deepens toward the edge.
- **Divergence lines and labels** on the oscillator - regular (reversal) and hidden (continuation), in two colors.
- **In-band reversal dots** where the oscillator turns inside an extreme zone.
- Optional **price-pane marks** at the confirmation bar (all generated by this one indicator).
- A **background-adaptive status dashboard** (oscillator value in sigma, zone, last divergence, last reversal, signed efficiency in %).
## Why these components are combined (mashup rationale)
This script combines a **derived measure**, a **normalization stage**, a **divergence engine** and a **reversal read**, because each answers a question the others cannot and none is useful here alone:
1. **Signed efficiency ratio (path quality).** Momentum tells you how FAR price moved; it does not tell you how DIRECTLY it got there. The signed efficiency ratio = (price - price ) / sum(|price - price |, len), a value in +/-1 that is positive for efficient up-moves and negative for efficient down-moves. It isolates path quality - a dimension a magnitude-only momentum oscillator cannot show.
2. **Standardization (rolling z-score).** efficiency differs in scale across instruments. The z-score expresses it in standard-deviation units, so "overbought/oversold" and the extreme bands mean the same thing on NIFTY, on a commodity future, or on a crypto instrument. Without this step the divergence thresholds would not transfer between symbols.
3. **Divergence engine.** The original payload is reading **price-versus-efficiency disagreement at confirmed pivots**. The engine pairs each new price pivot with the oscillator value, then requires: a genuine new price extreme; the measure failing to confirm it; a minimum oscillator gap scaled to the oscillator own stdev; the two pivots within a maximum bar distance; and optionally an overbought/oversold reading at the pivot. These gates make the combination produce signal rather than noise.
4. **Reversal read.** Independently, the engine flags oscillator turns that occur inside the extreme bands - a complementary exhaustion cue.
Together the components form one pipeline: **build the signal -> make it comparable (z-score) -> surface where price and that signal disagree (divergence) and where it exhausts (reversal).** Each is incomplete alone.
## How it works (method)
efficiency = (price - price ) / sum(abs(price - price ), len) over the efficiency window, a value in +/-1; this is standardized with a rolling z-score to the oscillator.
Regular and hidden divergence are detected from confirmed pivothigh/pivotlow pivots and filtered by the gates above; reversals are oscillator pivots that print inside the extreme bands. Pivots confirm a few bars after they occur, so a printed signal does not repaint. The confirmation lag equals the pivot length.
## How to use it
1. Add the indicator on any chart; no special data is required.
2. Read divergence as **context, not a trigger**: a bearish divergence (price higher high, efficiency lower high) says the advance is getting choppier; a bullish divergence says the decline is. Confirm with your own structure, levels and risk process.
3. Tune the **pivot length**, **max gap** and **min oscillator gap** to your timeframe; raise them for fewer, cleaner signals.
## Originality
This is an original implementation - not a efficiency line and not a generic divergence script, but the specific combination of efficiency, sigma-standardization that makes the read portable across markets, a multi-gate divergence engine (magnitude + distance + extreme-zone), hidden-divergence and in-band reversal detection, and a background-adaptive dashboard. The code is written from scratch; helper functions use only their arguments and built-ins.
## Credits
The Efficiency Ratio was introduced by **Perry J. Kaufman**. **Price/oscillator divergence** is a long-established, publicly documented technical-analysis technique. This script is not affiliated with, nor endorsed by, any third party.
## Notes / limitations
- Efficiency is a path-quality read, not a direction call; in strong clean trends it stays elevated without diverging.
- Divergence is descriptive context, never a guarantee of reversal.
- Confirmation lags each pivot by the pivot length.
## Disclaimer
Research and educational tool only. NOT financial advice and no guarantee of profitability or accuracy. Indicators describe past behaviour; they do not predict the future. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use of this script.
Indicator

Anchored VWAP Reversion ChannelAnchored VWAP Reversion Channel — Regime-Gated Fade Framework
## What this script does
This is an **analytical study** that frames mean-reversion ("fade") setups around an **anchored, volume-weighted regression channel**, then **gates** those setups by a statistical market-state test and **scores** them against their own forward outcomes. It does not place orders and it is not a signal service — its purpose is to let you see, on your own instrument and timeframe, whether fading a stretched move actually has an edge, instead of assuming it does.
It plots one channel (a centre line plus inner/outer residual-σ bands), marks fade setups at the outer band, draws supporting context (volume-profile POC / value area, untested prior-session POCs, momentum divergences, liquidity sweeps, and multi-timeframe trend lines), and reports a compact validation panel.
## Why these components are combined (mashup rationale)
Fading an extreme is really three separate questions, and no single classic indicator answers all three. Stacking look-alike indicators just echoes one input, so this tool deliberately combines **three non-redundant lenses and makes them check each other**:
1. **WHERE is price stretched?** — A **volume-weighted polynomial regression** anchored at the most recent swing pivot, with **residual-σ bands**. Because the curve tilts with the active leg, an outer-band tag stays meaningful even inside a trend, where a flat cumulative VWAP would not. A **volume profile** anchored to the *same* window supplies POC and value area, and prior-session POCs that have never since been traded through become **reversion targets**.
2. **Is a reversion actually firing here?** — Three orthogonal **tells** evaluated only at the band: a **close-back rejection**, a **band-confluent momentum divergence**, and an **equal-high/low liquidity sweep** (stop-run). Crucially, all three are derived from the same stretch, so their agreement is shrunk by a **design-effect correction** (effective-sample-size): three correlated echoes are not allowed to masquerade as three independent confirmations.
3. **Is the market in a reverting state at all?** — A **regime gate** combining a **variance-ratio test** and a **reversion-trust correlation** only lets a fade through when recent increments are offsetting (mean-reverting) rather than compounding (trending).
The pieces are not bolted together side by side: they share **one geometry** (the anchored channel) and **one volatility unit** (residual σ / ATR), and each can veto the others. A band tag with no tell does nothing; a tell with no reverting regime does nothing. The design goal is to **suppress** low-quality fades — into a trend, mid-range, or backed by a single echoed tell — more than to generate them.
## The honesty layer (what makes this more than a drawing)
Every fade that fires is logged and, a fixed horizon later, **resolved**: its forward return is measured in ATR units and tabulated **with the regime gate ON versus OFF**, reporting follow-through %, whipsaw %, a Wilson 95% confidence interval, and the **mean return per fade**. A per-fade series also exports to the Data Window so you can study the full return distribution offline. The gate has to **beat its own ungated baseline** to justify itself — the framework is built to be tested, not trusted blindly.
## How to use it
1. Set the **Price source** (group 01). It works on any symbol and any market; volume-based parts need a real volume feed.
2. A fade **arms** when price tags the outer band **and** at least one tell prints, then **passes** only if the regime gate reports a reverting state. Solid triangles are gated fades; the target is the centre line or the nearest untested POC.
3. Read the panel top-down: does **Gate ON** beat **Gate OFF** on both follow-through and mean R, with non-overlapping intervals and a reasonable sample size? If not, the edge is not present on this symbol/timeframe — change them rather than forcing the trade.
4. The signal lives on **higher intraday timeframes**; one-minute data is mostly noise.
## Defaults
Shipped tuned for **NSE:NIFTY** index futures on intraday timeframes (sources, pivot lengths, value-area %, and the Tuesday-style weekly session context reflect that instrument). Every value is exposed as an input — change the **Price source** and the relevant lengths to run the framework on any other instrument or market.
## What is original
The original work is the **coordination**, not any single formula: an anchored polynomial-regression channel used as a reversion frame, three decorrelated band tells fused by a design-effect shrink, a statistical regime gate, and a built-in A/B + forward-return validation harness — combined so each lens can veto the others and the whole thing reports its own hit rate. It is not a re-skin of one indicator.
## Concept credits (techniques are standard; this implementation is original)
Anchored VWAP (standard); volume-weighted least-squares / polynomial regression (standard); residual-σ channel (standard); Volume Profile, Value Area and POC — Market Profile, Steidlmayer / CBOT; Variance-Ratio test — Lo & MacKinlay (1988); design effect / effective sample size — Kish (1965); proportion confidence interval — Wilson (1927); ATR trailing stop / Supertrend (classic, used for the multi-timeframe context lines); RSI — Wilder; Stochastic — Lane.
## Disclaimer
For research and education only. This is an analytical study, **not** financial advice, **not** a recommendation, and **not** a guarantee of future results. All statistics shown are **in-sample** on loaded history, close-to-close, without costs or slippage — a study aid, not a backtest. Mean reversion fails in trends and through regime breaks. Do your own research and manage your own risk.
Indicator

Volatility Pressure & Regime AnalyzerVolatility Pressure & Regime Analyzer
## What this script does
VPRA estimates **when a market is loading energy for an outsized move, how large that move could be, and whether the current regime favors chasing or fading the breakout**. It condenses this into one on-chart verdict panel, directional signal markers, a regime ribbon, and a forecast of the expected move in ATR and points.
It works on **any symbol, any market, any timeframe**. A related volatility index and a companion symbol (the underlying if you chart a derivative, or vice versa) are optional inputs that sharpen the analysis; both can be disabled and the model renormalizes to price-only mode automatically.
## Why these components are combined (mashup justification)
Each module answers a question the others cannot, and the signal only fires when their answers agree. None of them is a stock indicator pasted alongside another — they are inputs to a single pressure model:
1. **Compression (ATR percentile)** answers *"is energy being stored?"* Quiet ranges precede expansion, but compression alone says nothing about direction or timing.
2. **Implied-vs-realized volatility dislocation** (optional vol index) answers *"is the options market mispricing the calm?"* A large gap between implied and realized volatility marks complacency or stress that compression alone cannot see.
3. **Basis tension** (optional companion symbol) answers *"is positioning leaning?"* Momentum in the derivative-to-underlying spread, and outright backwardation, reveal funding pressure and de-risking invisible in a single price series.
4. **Convexity and trend inefficiency** (return acceleration, efficiency ratio) answer *"is price behavior becoming unstable?"*
These four are blended into one **Pressure score (0–100)**, percent-ranked against its own history so thresholds adapt to every symbol and timeframe.
5. **A variance-ratio regime filter** answers *"will the break run or get faded?"* The ratio of k-bar to 1-bar return variance classifies the tape as mean-reverting (pinning) or trending (amplifying). Breakouts in a pinning regime are statistically more likely to fail, so the script can label or skip them.
6. **A multi-timeframe trend filter (Ichimoku cloud bias on the chart TF + three higher TFs)** answers *"is the release direction supported by structure?"* It grades signals rather than generating them. Higher-timeframe values are taken from **closed bars by default, so the confluence grade does not repaint**.
7. **Session, expiry, gap and event context** scale the expected-move forecast: an expiry-afternoon release during a volatility spike forecasts a larger move than a sleepy mid-session one.
Removing any module degrades a specific, named capability — that is the test the combination was built to pass.
## How a signal is generated
A marker prints only when **all** of the following align: pressure has reached a high percentile of its own history within a short lookback ("loaded"), the current bar shows a genuine range expansion ("release"), the condition persists for a confirmation bar count, a debounce gap has passed, and (optionally) the regime and trend filters pass. Direction is scored from **trigger-break** (close beyond the prior N-bar extreme), **close location** within the bar, and short momentum.
Marker color encodes the inferred event type: expiry-session releases, volatility-co-movement squeezes (price and vol index moving together — a short-covering tell), or plain expansions. The glow ring encodes how many higher timeframes agree. An ⓘ label stores a full diagnostic snapshot (pressure, regime, instability, basis, energy, session, expected move) in its tooltip for every signal.
## How to use it
- Apply to a liquid symbol; set "This chart is" to Derivative or Underlying, point the companion and volatility-index inputs at your market's related symbols (or disable them), and set your session hours and expiry weekday.
- Read the panel top-down: **Regime** (chase vs fade), **Pressure/Energy** (how loaded), **Move size** (forecast), **Trend align / HTF** (structure), **Triggers** (the price levels that confirm).
- Use the "Filter" modes to suppress signals against regime or higher-timeframe structure, or leave them as badges and judge manually.
- The advanced rows show per-type follow-through statistics (hit rate, average favorable and adverse excursion in ATR) and an early-vs-late history split as a coarse robustness check. **These are in-sample descriptive statistics, not a backtest.** A companion strategy script with identical logic is available for proper backtesting with costs.
- Alerts: per-signal dynamic alert with all values (webhook-ready), plus static conditions for expiry signals, releases, critical pressure, and vol shocks.
## Originality
The pressure blend (compression x vol-dislocation x basis tension x convexity x inefficiency, percent-rank normalized), the variance-ratio regime gate applied to breakout qualification, the compression-energy budget, and the per-type MFE/MAE statistics with an early/late split are original constructions written from first principles for this script. The only classical components used are public-domain building blocks (ATR, Bollinger/Keltner-style compression logic via ATR percentile, Ichimoku cloud bias as a trend filter, Kaufman efficiency ratio), each justified above.
## Limitations (please read)
- Dealer-positioning effects (often discussed as gamma/vanna/charm) are **inferred from price, volatility and basis behavior**. This script does not and cannot read option-chain open interest. Labels such as "gamma blast" describe an expiry-session release pattern, not a measured dealer position.
- All on-panel statistics are computed on the loaded chart history and will differ across symbols, timeframes and history length.
- Higher-timeframe confluence uses closed HTF bars by default (no repaint); the current chart bar still forms in real time, as with any script.
- Expected-move figures are model estimates, not guarantees.
This script is for education and analysis. It is **not financial advice**; trade at your own risk and test before use.
Indicator

Phase Exhaustion Reversal [BullByte]Phase Exhaustion Reversal (PXR) is an intraday reversal engine that measures one specific market phenomenon: the moment a short-horizon directional burst exhausts itself against a broader structural gradient. It is built on a single mathematical primitive - directional efficiency - applied at two horizons, and turns the gap between them into an exhaustion-detection framework.
This is not a mashup of existing indicators. The entire engine is derived from one calculation family: how cleanly price travels over a window. The regime classifier, the signal trigger, the risk engine, and the dashboard are all layers of that single concept rather than separate components.
---
Why This Indicator Exists
Most reversal tools fire on oscillator extremes or candlestick patterns. They answer the question "is price stretched?" but not "has the energy actually run out? " A market can stay stretched for a long time before reverting. PXR was built to answer a more precise question: when has a short-horizon momentum burst exhausted its energy against the prevailing structural direction? That moment - the exhaustion-and-recede - is what PXR isolates.
The phenomenon being studied can be observed on historical price data.
When price moves with high short-horizon efficiency in a direction that contradicts the medium-horizon efficiency gradient, that move is consuming energy faster than structure supports. Such bursts can appear to exhaust and then realign with the broader gradient on historical data. PXR visualizes that potential realignment as an observation worth studying.
---
Why a Trader Might Use It
Intraday traders on 5-minute and 15-minute charts frequently face counter-trend bursts that look like reversals but are actually just temporary dislocations. PXR offers a structured way to read those bursts: it waits for the burst to peak, confirms the peak has begun receding, and only then marks the realignment as armed. The next-bar open execution model means the entry price on the chart matches what a real-time observer could actually have achieved.
PXR is designed for traders who want a single coherent reading of market state - regime, bias, setup progression, and signal - rather than juggling multiple unrelated indicators.
---
The Concept
Imagine price as a hiker walking through terrain. Two things can be measured about that hiker over any window of time:
One - how far they ended up from where they started. This is transport.
Two - how much total ground they covered while getting there. This is agitation.
The ratio of transport to agitation is efficiency. If a hiker walked 100 meters in a straight line, transport equals agitation, and efficiency is 1.0 - perfectly directional. If a hiker zigzagged 500 meters total but ended up only 100 meters away, efficiency is 0.2 - most of the energy was wasted on the zigzag.
PXR computes this efficiency at two horizons simultaneously. The short horizon (around 35 minutes of bars, regardless of timeframe, by default) captures reactive bursts. The medium horizon (around 2 hours of bars by default) captures the structural gradient - the broader direction price is actually flowing in.
When the short-horizon efficiency spikes far from the medium-horizon efficiency, the two have dislocated. PXR normalizes this dislocation into a value called the Phase Gap. When the Phase Gap stretches to an extreme and then begins to recede, the short-horizon burst is exhausting. If the medium-horizon gradient points the opposite direction at that moment, PXR marks a realignment signal - the observed behavior is a possible realignment with the structural gradient.
---
What Makes This Different From a Standard Momentum Tool
Three architectural choices separate PXR from typical oscillator-based reversal tools.
First, the use of two-horizon efficiency phase-gap normalization. The raw difference between two efficiency readings is rescaled by its own rolling maximum so the threshold stays meaningful across all volatility regimes. A 0.6 reading means the same thing on a quiet day as on a volatile one.
Second, regime-conditional adaptive thresholds. The signal threshold is not a fixed constant. It adapts based on whether the market is currently classified as Extended (clean trend), Compressed (range), Transitioning (regime shifting), or Neutral. Each regime gets a different sensitivity, and each timeframe gets its own scaling on top of that.
Third, an exhaustion-and-recede state machine gated by structural gradient sign. The signal does not fire when the Phase Gap simply crosses a level. It fires only when the gap has first reached a qualified peak and then receded by a meaningful fraction of that peak - confirming exhaustion has begun - and only when that exhaustion direction opposes the sign of the medium-horizon efficiency. This is a directional fade of short-horizon energy against the prevailing structural gradient.
---
Mathematical Foundation
The script is built from three primitive calculations. All other logic flows from these.
Transport over n bars equals close minus close n bars ago. This measures net displacement.
Agitation over n bars equals the sum of absolute bar-to-bar price changes across that window. This measures total path length.
Efficiency over n bars equals transport divided by agitation. This produces a signed value bounded between -1 and +1. Positive values indicate net upward directional purity, negative values indicate net downward directional purity, and values near zero indicate chop.
The Phase Gap is the short-horizon efficiency minus the medium-horizon efficiency, divided by the rolling maximum of the absolute raw gap. This normalization keeps the Phase Gap roughly within plus or minus one regardless of market conditions.
A realignment signal fires when the Phase Gap has peaked beyond a regime-adjusted threshold and then receded by a meaningful fraction of that peak, AND the sign of the medium-horizon efficiency points in the direction opposite to the burst that just exhausted.
This calculation family is conceptually related to efficiency-ratio style measurements. PXR's originality lies in the multi-horizon phase-gap construction, the regime-adaptive thresholding, and the exhaustion-and-recede state machine.
---
Recommended Timeframes and Markets
PXR is built for intraday operation. The timeframe-adaptive logic is tuned for 1-minute through 15-minute charts. The default Auto-Scale setting recalibrates the horizons so the same physical time window of analysis is used regardless of timeframe.
The phenomenon PXR studies appears most cleanly on liquid intraday instruments. Crypto majors such as BTCUSDT and ETHUSDT on 5-minute and 15-minute charts work well because crypto exhibits meaningful path tortuosity - the agitation-to-transport ratio carries real information. Index futures such as NQ and ES on 5-minute and 15-minute charts also work, though session boundaries can affect the normalization window on overnight sessions.
PXR is built for intraday use. Higher timeframes such as 1H, 4H, or daily may behave differently because the regime thresholds and recede fractions are tuned for intraday energy cycles rather than multi-day structural shifts.
---
Chart Examples
The two examples below are illustrative historical signals chosen to show the engine's mechanics and visual elements. They are not representative of typical or expected outcomes. Many signals fail and reach the INVALIDATION level instead. These examples are educational only.
1. Example - Bull Realignment on BTCUSDT 15m
The annotated chart shows a complete PXR realignment cycle.
Price experienced a sharp short-horizon bearish burst from roughly 77,650 down to 76,150. During this drop, the medium-horizon efficiency gradient remained bullish - the slower 24-bar window still carried the structural upward bias from earlier hours. The yellow diagonal line traces this bullish medium-horizon gradient that the bearish burst was working against.
At the bottom of the move, the Phase Gap reached its negative peak . The bearish burst's energy was fully spent. The yellow rectangle marks the exhaustion zone where two indecision candles stalled the fall.
Beginning shortly after, the Phase Gap began receding from its negative peak. Once it had receded by the configured fraction, the exhaustion-and-recede condition was satisfied. The medium-horizon efficiency was still positive, so the structural gradient gate qualified the direction. The state machine flipped upward and the signal armed on the close of the trigger bar.
On the next bar, the entry executed at the open at 76,410. The four rails drew automatically - INVALIDATION at 75,982, TARGET 1 at 76,923, TARGET 2 at 77,351.
In this illustrative example, the price moved upward after the signal and later reached TARGET 1 and TARGET 2. This is one historical instance only. Outcomes vary, and many signals reach the INVALIDATION level instead.
2. Example - Bear Realignment and Engine
This chart illustrates three aspects of PXR that complement the phenomenon view.
First, the engine is bidirectional. The red downward callout marks a BEAR realignment signal. A short-horizon bullish burst pushed price upward over several hours. When that burst exhausted near 77,400, the Phase Gap reached its positive peak . As the gap began receding and the medium-horizon gradient pointed bearish, the exhaustion-and-recede condition triggered a BEAR signal . The four rails drew at INVALIDATION 77,465, ENTRY 76,765, TARGET 1 75,925, and TARGET 2 75,226.
Second, the regime ribbon is visible across the background. Subtle orange tints mark COMPRESSED periods where both efficiencies are low and the market is consolidating. Subtle cyan tints mark TRANSITIONING periods where the Phase Gap has stretched far and a regime shift is underway. These background colors give an at-a-glance read of market state without requiring a glance at the dashboard.
Third, the live dashboard in the top-right shows engine state in real time. State, Setup, Bias, Phase Gap, and Last all update on every bar. The five-line legend overlay explains what each field represents. At the moment of this screenshot, the BEAR signal was Triggered, the regime was COMPRESSED , and the Phase Gap reading was -0.07 - a sign the dislocation had largely normalized after the signal fired.
Together with the dashboard and regime ribbon, the engine provides a continuous reading of market state - not just point-in-time signals, but a live framework that contextualizes each signal as it forms.
---
How to Read the Chart
PXR draws several elements. Each one represents something specific.
The PHASE EXHAUSTION label, marked with an upward or downward arrow, appears at the bar where the signal arms. An upward arrow with the text " Realign Up " means a short-horizon bearish burst has exhausted against a bullish gradient , and the studied behavior is upward realignment. A downward arrow means the opposite. The label is anchored outside the bar's price extreme so it does not clash with other chart elements.
The ENTRY rail is a dashed line drawn at the open of the bar immediately after the signal armed. This is the reference entry level. The script does not place orders - it visualizes the reference level a real-time user could have acted on.
The INVALIDATION rail is a solid red line. If price reaches this level, the realignment thesis is rejected. This level is calculated as the worse of two values: a structural swing high or low with an ATR buffer, or a minimum ATR-floored distance from entry. Whichever is further from entry is used. This guarantees the invalidation level is never crammed inside short-term noise.
The TARGET 1 and TARGET 2 rails are teal solid lines placed at user-configurable R-multiples of the invalidation distance. These represent profit objectives. The defaults are 1.2R and 2.2R, which can be modified in the Risk Settings group.
All four rails extend forward bar by bar while the trade is conceptually active, and their labels trail slightly ahead of the live bar so they remain visible at the right edge of the chart.
The regime ribbon is a subtle background tint. Red indicates an Extended regime, orange indicates Compressed, cyan indicates Transitioning, and faint grey indicates Neutral. The ribbon helps users see at a glance which regime the engine currently classifies the market in.
The active tint colors bars green during an active long observation and red during an active short observation. This is purely visual and can be toggled off.
---
How to Read the Dashboard
The dashboard sits in the top-right of the chart and shows six live readings.
State shows the current regime classification. Extended means the medium-horizon efficiency is high - the market has a clean directional gradient. Compressed means both efficiencies are low - the market is ranging. Transitioning means the Phase Gap has stretched far - a regime change is in progress. Neutral means none of the above.
Setup shows the realignment setup progress. No Setup means nothing is forming. Forming means the Phase Gap has reached 60 percent of the threshold. Watching means the Phase Gap has reached 85 percent of the threshold - a setup is building but no signal has fired yet. Armed means a confirmed signal has fired and is awaiting next-bar execution. Triggered means a trade observation is currently active.
Bias shows the direction of the medium-horizon efficiency gradient. BULL means the structural gradient points up. BEAR means it points down. A dash means it is neutral.
Phase Gap shows the live normalized Phase Gap value, roughly bounded within plus or minus one. The color brightens when the absolute value exceeds the threshold.
Last shows the direction of the most recently triggered realignment.
---
Settings Explained
Core Settings.
Auto-Scale Horizons: when on, the Short and Medium horizons are automatically recomputed per timeframe so the analysis covers similar physical time on every chart. When off, the manually entered horizon lengths are used. Recommended on for users who switch between timeframes.
Short Horizon: bars used to measure short-horizon efficiency. Lower values are more reactive but noisier. Default 7. Ignored when Auto-Scale is on.
Medium Horizon: bars used to measure the structural efficiency gradient. Should span one meaningful intraday cycle. Default 24. Ignored when Auto-Scale is on.
Phase Gap Threshold: the normalized Phase Gap level required for a peak to qualify as exhaustion-grade. Higher values yield fewer but stronger signals. Default 0.58.
Cooldown Bars: minimum bars between two consecutive signals. Prevents clustering during noisy regimes. Default 3.
Risk Settings.
ATR Length: the ATR window used for the volatility-based stop floor. Default 14.
ATR Floor Multiplier: minimum stop distance expressed as a multiple of ATR. Ensures the stop is never inside short-term noise. Default 1.0.
TP1 R-Multiple: first profit target expressed as a multiple of the invalidation distance. Default 1.2.
TP2 R-Multiple: final profit target expressed as a multiple of the invalidation distance. Default 2.2.
Visuals.
Show Regime Ribbon: toggles the background regime tint.
Show Active Tint: toggles the green or red bar coloring during an active observation.
Show Dashboard: toggles the top-right state dashboard.
---
Execution Model - Why This Is Honest
PXR uses a strict two-bar workflow. The signal arms only on the close of a confirmed bar - this is enforced by a barstate-confirmed gate inside the engine. The entry then executes at the open of the next bar. This means the entry price shown on the chart matches what a real-time user could have achieved by placing a market order the moment the signal arms.
This workflow prevents the most common form of repaint illusion. The script does not use lookahead data. It does not use future bars. It does not modify past signal positions. Historical signals on the chart represent the same logic that fires in real time.
---
What the Indicator Does Not Do
PXR does not predict future price. It identifies a measurable energy state and labels the observation. It does not place trades. It does not guarantee outcomes. It does not work on all markets in all conditions. It is not a substitute for risk management, position sizing, or contextual judgment.
The realignment behavior is an observed tendency on historical data, not a certainty or guarantee.
The invalidation rail exists precisely because failure is expected and must be bounded.
---
Limitations You Should Know
Session boundaries on instruments such as NQ and ES can compress the rolling normalization window during overnight low-liquidity periods. This can make the Phase Gap appear weaker than it would on a continuous session.
The engine is intentionally reversal-focused. It does not generate continuation signals. In strong trending markets, reversal signals may underperform compared to a continuation tool because the structural gradient is not exhausting - it is reinforcing itself.
Auto-Scale produces horizon values that may differ substantially from the manual input defaults. If a user toggles Auto-Scale off after operating with it on, the manual values will be used immediately and behavior will shift.
On very long historical lookbacks at 1-minute resolution, the efficiency calculation may require additional processing time due to the bar-by-bar path-length computation. If performance is a concern, reducing the Medium Horizon input or enabling Auto-Scale on faster timeframes will reduce the load.
---
Disclaimer
This script is provided for educational and analytical use only. It does not provide financial, investment, or trading advice. It does not guarantee any specific outcome. Past behavior of the indicator on historical data does not imply future results. Markets carry risk. Use independent judgment, sound risk control, and full market context before acting on any signal or observation produced by this tool. The author is not responsible for any decisions made on the basis of this script.
Indicator

Statistical Mean-Reversion Engine [SMRE]## Statistical Mean-Reversion Engine (SMRE)
SMRE is an open-source mean-reversion indicator that combines a rigorous statistical core with up to eight optional confirmation layers, designed primarily for index-futures trading on intraday timeframes (1-minute through 1-hour).
### What it does
For every bar, SMRE fits an Ornstein-Uhlenbeck (OU) process to the recent price series via linear regression on lag-1 prices, yielding four outputs:
- **μ (the mean)** — the equilibrium price the series is reverting to
- **θ (mean-reversion speed)** — how strongly the series pulls back to μ
- **HL (half-life)** — how many bars it takes to revert halfway
- **σ_eq (stationary residual variance)** — used to z-score the current price
The current price's z-score against μ (the "OU Z") is the primary signal. When |OU Z| exceeds a configurable threshold, a mean-reversion entry is considered — but only after the script also confirms that the recent price series is genuinely stationary using three orthogonal statistical tests:
- **Hurst exponent** must be below 0.55 (i.e., the series is not persistently trending)
- **Augmented Dickey-Fuller** t-statistic must be below -2.86 (rejects unit root)
- **Variance Ratio** test at q=4 must be below 1.0 (variance grows sub-linearly with horizon)
If all four conditions pass, the L1 (statistical core) signal fires.
### Why the multi-layer structure (mashup justification)
A single OU-based mean-reversion signal works well in stationary regimes but degrades in trending or volatile conditions. SMRE addresses this by validating each potential entry through up to eight orthogonal confirmation channels, each measuring something the others do not:
- **L2 — Volatility Regime (6-state):** Classifies market state via VIX, ADX, and realized volatility. Suppresses signals during high-trend conditions (regime 6, "Spike") where mean-reversion historically fails.
- **L3 — Spot-Futures Basis (Kalman filter):** Tracks the deviation between actual and theoretical futures pricing. Statistically significant basis dislocations often resolve via mean-reversion.
- **L4 — Options Surface:** Computes ATM implied volatility from straddle pricing and a skew z-score from OTM put/call ratio. Optional; requires user to provide option symbols.
- **L5 — Microstructure:** Blends rolling VWAP and session-anchored VWAP z-scores with VPIN (a volume-clock toxicity proxy) and order-flow imbalance. Captures flow-based exhaustion.
- **L6 — Gamma Walls (GEX) OR Put-Call Ratio:** Two mutually exclusive options. GEX requires OI symbols at five strikes; PCR requires a single broker-published PCR feed. Both detect option-driven price magnets.
- **L7 — Dispersion:** Rolling correlation of index returns with its top 5 constituent stocks' returns. High dispersion (low correlation) penalizes signals; high cohesion boosts them.
- **L7b — Residual Dispersion:** Idiosyncratic residual z-scores (β-adjusted) per constituent. If 3 of 5 stocks show same-sign extreme residuals, the index is detached from constituents — strong mean-reversion candidate.
- **L9 — Cross-Asset Stress:** Sigma-normalized stress across USD/INR, DXY, and crude oil. Penalizes signals during cross-asset hedging cascades.
Each layer outputs a {direction, strength} pair. The Layer 8 fusion engine combines these via a weighted composite score (default weights: L1=0.28, L5=0.22, L3=0.18, L4=0.12, L6/L7b=0.10), then applies a regime multiplier (L2 × L7 × VRP × cross-asset × expiry), clamped to to prevent extreme compounding.
If the absolute composite score crosses one of three thresholds (0.25 / 0.40 / 0.45 by default), a signal is fired at Scalp / Swing / Session horizon respectively. A TCA cost filter then validates that the expected move (distance to μ) exceeds estimated round-trip transaction cost; otherwise the signal is suppressed.
### Originality
The author is not aware of any other public Pine script that implements the full OU-fit chain (mean, mean-reversion speed, half-life, stationary variance) together with all three stationarity tests (Hurst, ADF, Variance Ratio) directly in Pine v6 — every step is computed natively, no external library calls. Additionally, the session-anchored VWAP with running volume-weighted sigma bands, the rolling-beta residual dispersion across multiple constituents, and the Kalman-filtered futures-basis residual are original Pine implementations. The signal telemetry module (a 200-signal FIFO ring buffer with horizon × composite-magnitude bucket attribution) is also an original diagnostic tool.
### How to use
1. **Apply to an index futures chart.** Defaults are pre-configured for NSE NIFTY1! futures, but inputs allow any index — change the VIX symbol, spot/futures symbols, constituent symbols, and currency pairs.
2. **Read the compact dashboard.** It's a single 9-row table (default position: middle-right) showing only what you need to evaluate a setup:
| Row | What it shows | What it means |
|---|---|---|
| Title | Profile + OU window in use | Confirms which calibration is active |
| OU Z-Score | Z-score with half-life (HL) | How extended price is + how long mean-reversion typically takes |
| Stat Validity | H / ADF / VR pass-fail | Whether the recent series is actually stationary (all 3 must pass) |
| Regime | Volatility state + VIX value | Whether market conditions favor mean-reversion |
| Composite | Fused score × regime multiplier | The unified signal strength |
| Confluence | Layers agreeing (out of 6) | How many orthogonal signals support the direction |
| TCA Edge | Expected move in bps + PASS/FAIL | Whether the trade clears transaction costs |
| E / SL / TP | Entry, Stop, Target + Risk:Reward | The trade levels if a signal fires |
| **DECISION** | Direction · Horizon · Side | The actionable output (green=long, red=short, gray=neutral) |
3. **Trade levels and markers.** When a signal fires, entry/stop/target lines auto-plot on the chart. Stop is ATR-based (default 1.2× ATR); target is min(OU mean μ, entry + 2× ATR). Triangle markers plot below (long) or above (short) the bar — small for Scalp, medium for Swing, large for Session.
4. **Optional diagnostic.** A separate Signal Telemetry table (disabled by default; enable via the "Show Telemetry Dashboard" input) tracks the last 200 signals' outcomes (win = price touched μ, loss = stop hit, expired = timeout) and reports hit rate by horizon × composite-magnitude bucket. This is a backward-looking diagnostic, not a backtest.
### Recommended chart and timeframe
This indicator was developed and parameter-tested primarily on NIFTY1! futures. The OU window auto-mapping (1m→32, 2m→20, 5m→12, 15m→32, 30m→20, 1h→24) was selected empirically through parameter sweeps. Users on other instruments should expect to tune the OU window manually or accept the auto-mapped default as a starting point.
The indicator works on any timeframe between 1 minute and daily, though intraday timeframes (1m through 1h) are where the multi-layer confluence adds the most value.
### Important notes
- This is an **indicator**, not a strategy — no backtest equity curve is produced. The telemetry table is a descriptive measure of recent signal outcomes only.
- Many layers are **optional**. If you don't have symbols for options OI, just leave those inputs blank; the script will redistribute composite weight naturally across the active layers.
- Signals can fluctuate intra-bar before bar close, especially in real-time mode. For consistent behavior, evaluate signals on closed bars only.
- The default constituents (top-5 NIFTY weights) need to be changed in the L7 inputs to use this on a different index.
### Disclaimer
This indicator is published for educational and research purposes only. It is not financial advice, not an investment recommendation, and not a solicitation to trade. Past behavior of signals does not guarantee future results. Trading futures, options, and equities carries substantial risk of loss. You are solely responsible for your trading decisions. The author makes no representations about the accuracy, completeness, or suitability of this indicator for any particular purpose. Use at your own risk, and always consult a qualified financial professional before trading.
Indicator

Risk Manager [SkaleHub]Overview
The ultimate capital preservation tool. This indicator calculates mathematically secure stop-loss placements based on real-time market volatility (ATR) and features a dynamic dashboard that tells you the exact position size to take to protect your account.
The Edge
Amateurs blow accounts by guessing their lot sizes and placing arbitrary stop-losses. This tool professionalizes your risk. By adjusting your position size relative to the asset's current volatility, it ensures that whether you are trading a quiet forex pair or a volatile crypto asset, your monetary risk remains an exact, controlled percentage of your capital.
Key Features:
Volatility-Based Stops: Automatically calculates stop-loss levels using the Average True Range (ATR), ensuring your stop is safely tucked behind the market's natural "noise" to prevent early liquidations.
Auto-Position Sizing: Input your account balance and risk tolerance (e.g., 1%), and the built-in dashboard instantly outputs the exact number of shares or units you should buy.
On-Chart Visual Guardrails: Optionally plots dynamic crosshair lines on the chart so you can visually see exactly where your mathematically optimized stop-loss should be placed before entering a trade.
How to Use
Apply the indicator and open the settings menu. Enter your total account balance and your strict risk percentage (1-2% is highly recommended).
When your Level 3 Momentum Trigger fires an entry signal, look at the Risk Manager dashboard in the corner of your screen.
Execute the trade using the exact "Position Size (Units)" displayed on the dashboard, and immediately set your hard stop-loss at the "Stop Distance" mapped out on the chart.
Author's Note
This is a premium, Invite-Only script. It is Level 4 of the SkaleHub Training System. To gain access, your PulseWire username must be explicitly authorized through the SkaleHub Academy. Indicator

Xander Scalping Strategy [Price Action + Confirmation]🚀 Xander Scalping Strategy
by @wijayanto_ok
A multi-confirmation scalping strategy combining trend filtering, dynamic support/resistance, Stochastic RSI momentum, and volume confirmation — with visual Risk/Reward estimation for disciplined trading.
================================================================================
📌 OVERVIEW
================================================================================
Xander Scalping Strategy is a Price Action-based trading tool designed for traders who prioritize high-probability, multi-layer confirmation before entry. It helps identify:
✅ Trend Direction using EMA 13/21 crossover
✅ Dynamic Support & Resistance from confirmed swing highs/lows
✅ Precision Entry Signals via Stochastic RSI + Volume spike confirmation
✅ Visual Risk/Reward Estimator for smarter position management
🎯 Best For: Timeframes 5m – 1H | Liquid assets (Forex majors, BTC/ETH, Indices)
================================================================================
✨ KEY FEATURES
================================================================================
🔹 1. Trend Filter (EMA 13/21)
---------------------------------
• Fast EMA (13) & Slow EMA (21) with dynamic coloring:
🟢 Green = Uptrend | 🔴 Red = Downtrend | ⚪ Gray = Sideways
• Real-time trend label in top-right corner for quick reference
🔹 2. Dynamic Support & Resistance
---------------------------------
• Auto-detects Swing High/Low using ta.pivothigh() / ta.pivotlow()
• Horizontal S/R lines extended to the right (real-time visualization)
• Updates automatically when new swings are confirmed
⚠️ Note: 1-candle lag for pivot confirmation = non-repainting logic
🔹 3. Multi-Layer Entry Confirmation
---------------------------------
Component | Settings | Purpose
-------------------|---------------------------------------|---------------------------
Stochastic RSI | RSI Len: 14, %K: 3, %D: 3, OB: 80, OS: 20 | Momentum timing & reversal signals
Volume Filter | Avg Volume (20-period) | Filters low-liquidity false signals
Price Action | Pullback to EMA zone OR bounce/reject at S/R | Confirms structural alignment
✅ BUY Signal Conditions:
1. Uptrend (EMA 13 > EMA 21)
2. Price pulls back to EMA zone OR bounces from Support
3. StochRSI crosses UP from Oversold (<20)
4. Volume > 20-period average
→ Green "BUY" arrow appears below candle
✅ SELL Signal Conditions:
1. Downtrend (EMA 13 < EMA 21)
2. Price pulls back to EMA zone OR rejects from Resistance
3. StochRSI crosses DOWN from Overbought (>80)
4. Volume > 20-period average
→ Red "SELL" arrow appears above candle
🔹 4. Visual Risk/Reward Table (Top-Right)
---------------------------------
Metric | Description
----------|--------------------------------------------------
Status | Current trend or active signal (LONG/SHORT/UPTREND/DOWNTREND)
Est. RR | Estimated Risk:Reward ratio based on latest swing levels
💡 Tip: Use RR ≥ 1:1.5 as an additional filter for higher-quality entries.
🔹 5. Alert System
---------------------------------
• 🔔 "Xander Buy Signal" — Triggered when all BUY conditions met
• 🔔 "Xander Sell Signal" — Triggered when all SELL conditions met
• Compatible with PulseWire alerts (popup, email, webhook, SMS)
================================================================================
⚙️ HOW TO USE
================================================================================
🔧 Setup:
1. Apply script to chart with timeframe 5m, 15m, or 1H
2. Recommended assets:
• Forex: EURUSD, GBPUSD, USDJPY
• Crypto: BTCUSDT, ETHUSDT
• Indices: US30, NAS100, SPX500
🎯 LONG Entry Setup:
1. Confirm "UPTREND 🟢" label is visible
2. Wait for pullback to EMA 13-21 zone OR bounce from green Support line
3. Confirm: Green BUY arrow appears + candle closes bullish
4. StochRSI: Crosses up from <20 zone
5. Volume: Bar higher than 20-period average
📍 Stop Loss: Below nearest lastSwingLow
🎯 Take Profit: Nearest lastSwingHigh OR RR target ≥1:1.5
🎯 SHORT Entry Setup:
1. Confirm "DOWNTREND 🔴" label is visible
2. Wait for pullback to EMA 13-21 zone OR rejection from red Resistance line
3. Confirm: Red SELL arrow appears + candle closes bearish
4. StochRSI: Crosses down from >80 zone
5. Volume: Bar higher than 20-period average
📍 Stop Loss: Above nearest lastSwingHigh
🎯 Take Profit: Nearest lastSwingLow OR RR target ≥1:1.5
⚠️ Recommended Filters:
❌ Avoid trading when label shows "SIDEWAYS ⚪"
❌ Skip signals with Est. RR < 1:1
❌ Avoid entries 5 min before/after high-impact news events
✅ Always confirm with candlestick patterns (pinbar, engulfing, etc.)
================================================================================
🔍 TECHNICAL NOTES (Advanced Users)
================================================================================
📐 Pivot Detection (Non-Repainting):
ph = ta.pivothigh(high, lookbackPeriod, lookbackPeriod)
pl = ta.pivotlow(low, lookbackPeriod, lookbackPeriod)
• Requires rightBars = lookbackPeriod for confirmation → NO REPAINTING
• New swing confirmed only after N candles close to the right
• Recommended: lookbackPeriod = 50 for significant swings; 20-30 for responsive signals
📊 Stochastic RSI Calculation:
rsiSource = ta.rsi(close, 14)
stoch = (rsiSource - lowestRSI) / (highestRSI - lowestRSI) * 100
%K = ta.sma(stoch, 3), %D = ta.sma(%K, 3)
• Measures relative momentum within 0–100 range
• Crosses at extremes (20/80) offer high-probability reversal signals
📈 Risk/Reward Estimation:
// For BUY:
risk = close - lastSwingLow
reward = lastSwingHigh - close
RR = reward / risk
• Uses latest confirmed swing levels as reference for SL/TP
⚠️ Estimates only — always adjust to real-time market structure
================================================================================
⚠️ DISCLAIMER & RISK WARNING
================================================================================
🚨 IMPORTANT: This script is an analytical tool only. It does NOT guarantee profits or replace sound trading judgment.
1. Backtest First: Test in demo mode for 2–4 weeks before live trading.
2. No Holy Grail: No strategy wins 100%. Manage expectations and use strict money management.
3. Market Conditions: Performs best in trending markets. May underperform in extreme sideways or news-driven volatility.
4. Non-Repainting: Signals appear only after candle close and pivot confirmation. Minor 1-candle lag on swing detection is intentional for reliability.
5. Always Use Stop Loss: Never trade without predefined risk protection.
🔹 Trading forex, crypto, and derivatives carries substantial risk of loss. Trade only with capital you can afford to lose.
================================================================================
🔄 VERSION HISTORY
================================================================================
Version | Date | Changes
--------|------------|--------------------------------------------------
1.0 | May 2026 | Initial release: EMA + S/R + StochRSI + Volume + RR Table
================================================================================
💬 FEEDBACK & SUPPORT
================================================================================
• 🛠 Found a bug? Report with screenshot + timeframe + asset for faster resolution.
• 💡 Have an improvement idea? Comment below or DM @wijayanto_ok.
• 🌟 Enjoying the script? A like/follow helps support future updates!
"Plan your trade, trade your plan. Consistency > Perfection."
— Xander Scalping Philosophy
================================================================================
🔖 TAGS (For Search Optimization)
================================================================================
scalping, price-action, ema, support-resistance, stochastic-rsi, volume, risk-reward, swing-trading, confirmation, non-repainting, pulsewire, pine-script
================================================================================
✅ PRE-PUBLISH CHECKLIST
================================================================================
Tested on 3+ assets & timeframes
All inputs have sensible defaults
Code is well-commented & structured
Risk disclaimer included
Alert conditions defined
No unwanted repainting logic
Documentation complete & professional
================================================================================
🙏 Thank you for using Xander Scalping Strategy!
Happy trading, and may your RR always be in your favor. 🎯📈
================================================================================ Indicator

Indicator

Swap Engine - Pair Rotation (Z-Score) [AGPro Series]Swap Engine - Pair Rotation (Z-Score)
🔷 OVERVIEW
Swap Engine - Pair Rotation (Z-Score) transforms the log-ratio between two correlated crypto assets into a disciplined tier ladder decision framework. Rather than signalling single-asset direction, the engine measures how stretched one pair has become relative to its rolling mean and proposes rotation between the two assets when the spread reaches statistically meaningful extremes. Every decision is evaluated on confirmed Engine TF bar close, keeping suggestions non-repainting under the configured execution model.
🟣 UNIQUE EDGE
Unlike single-symbol mean-reversion or trend indicators, this engine treats the ratio itself as the tradable variable and pairs it with a full operational stack: a tiered exposure ladder (T0 to T3), an Integrity Gate that blocks entries when the pair relationship deteriorates, a Trend Regime filter that respects persistent one-sided moves, and a confirm-first execution model that converts raw signals into auditable decisions. A dedicated Signal Quality score (Q 0-100) and Integrity Score (IN 0-100) make every suggestion inspectable, not a black box.
🟢 METHODOLOGY
The engine fetches the closing price of Pair A and Pair B on the chosen Engine TF, computes the log-ratio L = ln(A / B), then derives a rolling z-score using user-defined lookback length. Entry thresholds (Z1, Z2, Z3) define the three tiers of exposure; exit thresholds (hysteresis) define when each tier is scaled back. A cost filter requires the expected mean-reversion edge to exceed a configurable multiple of estimated roundtrip cost before any entry is allowed. The Integrity Gate continuously validates rolling return correlation, ratio drift, and spread-volatility expansion, halting new entries when the pair relationship degrades.
🟡 SIGNALS & ALERTS
Each signal renders as a clearly tagged label on chart showing the action type (ENTRY / EXIT), source tier, target tier, direction (A->B or B->A), z-score snapshot, delta %, and Reason Code. Alerts are provided for: entry and exit events per direction, pending lifecycle (created, confirmed, skipped, expired), trend regime activation edges, duplicate suppression, and configuration warnings. All alerts fire on Engine TF bar close to remain consistent with the visible suggestions.
⚙️ KEY INPUTS
Pair A / Pair B: the two assets to rotate between (same quote currency recommended).
Engine TF: timeframe used for all ratio, z-score, and decision logic (240 / 4H default).
Lookback: bars used for rolling mean and standard deviation.
Entry Z1/Z2/Z3, Exit Z1/Z2/Z3: tiered thresholds for scaling in and out.
Tier Sizing (T1 / T2 / T3 %): rotation size per tier as a percentage of the active pool.
Trade Profile: preset gate behavior (Conservative, Balanced, Aggressive, Volatile Alt, High-Cost, Custom).
Integrity Gate: correlation, drift, and volatility expansion filter with configurable minimum score.
Execution Model: ASSUME (auto-advance), CONFIRM (pending + manual commit), or SIGNAL_ONLY (display only).
🔵 HOW TO USE
Start on the default BTCUSDT vs ETHUSDT pair on 4H Engine TF with the Balanced profile. Keep the chart timeframe equal to or lower than the Engine TF (the script warns otherwise). Watch the status panel for the current tier, direction, confidence strip (Q / IN / PH), and next action preview. In CONFIRM mode, a PENDING card appears when a signal fires; increase CONFIRM +1 to commit the rotation state, or SKIP +1 to discard. Use the Trade Profile dropdown to tighten or loosen effective gates without changing your base inputs.
🟠 LIMITATIONS & TRANSPARENCY
This is an indicator, not a strategy; no orders are placed and no backtest statistics are produced. Signals reflect statistical extremes in the pair's log-ratio and do not guarantee mean reversion. Performance depends heavily on pair selection - assets with persistent trends, broken correlation, or structural regime changes can cause extended adverse periods. The Integrity Gate mitigates but does not eliminate this risk. Costs, slippage, tax, and execution details are the user's responsibility; the Min Edge x filter is an estimate, not a realized-cost guarantee. Always validate on your own pair, timeframe, and account conditions before relying on any suggestion.
🔴 RISK DISCLOSURE
Trading and rotating between crypto assets involves substantial risk, including loss of capital. Past or simulated behavior of the ratio does not guarantee future results. This tool is shared for educational and analytical purposes only and does not constitute financial, investment, or trading advice. Users are solely responsible for their own decisions and should consult a qualified professional before committing capital. Indicator

Trend Stability Ribbon [AGPro Series]Trend Stability Ribbon
🔹 OVERVIEW
Most trend tools tell you WHICH WAY price is going. Trend Stability Ribbon tells you HOW WELL it is getting there. By pairing an ATR-normalized slope engine with a Kaufman path-efficiency score, it projects every bar into one of four rules-based states — Stable Up, Noisy Up, Stable Down, Noisy Down — and paints them onto a clean, adaptive ribbon that stays out of the candles' way. The result is a context layer that separates decisive trending from directional-but-choppy travel, without adding a second indicator pane.
🧭 UNIQUE EDGE — WHY THIS IS NOT "JUST ANOTHER TREND INDICATOR"
Direction alone is cheap. Every moving-average cross, every supertrend, every slope color tells you "up" or "down" — and then leaves you holding the bag when the trend is technically up but structurally a mess.
Trend Stability Ribbon adds the missing second dimension: path quality. The same 34-bar window that defines direction also feeds a Kaufman efficiency calculation (net travel divided by total path travel). An ER near 1.00 means price walked a near-straight line; an ER near 0.00 means it zig-zagged its way to the same point. Mapping that score against a calibrated threshold band produces the four composite states — and a visual language that finally distinguishes "trend worth trusting" from "trend worth fading".
Additional design choices that set it apart:
• Dual-layer event engine — direction flips, stability upgrades, and stability downgrades are tracked as independent transitions, each with its own alert.
• Badge/alert separation — on-chart badges are throttled by a cooldown for visual hygiene, but alerts are always raw so automation pipelines never miss an event.
• Reset state — when the slope-confirmation filter rejects a direction, the ribbon goes neutral instead of flipping false. Chop gets ignored, not misreported.
🧪 METHODOLOGY
1. TREND DIRECTION ENGINE
• A slow EMA (default length 34) anchors the trend path and serves as the ribbon centerline.
• Slope is measured over a 3-bar lookback and normalized by a 14-period ATR, making it instrument-agnostic across crypto, FX, equities, and futures.
• With Slope Confirmation enabled (default), direction is only accepted when price position AND slope agree. Disagreement returns a Reset state.
2. PATH EFFICIENCY (STABILITY) ENGINE
• ER = |close − close | ÷ Σ|close − close | over the same trend window.
• Three classes: Stable (ER ≥ 0.45), Noisy (ER ≤ 0.25), Mixed (between). Thresholds scale with the Stability Sensitivity input.
• The Mixed zone is a deliberate dead-band — during uncertain phases the previous state persists rather than flickering.
3. COMPOSITE STATE MACHINE
• Direction × Stability yields five possible states: Stable Up, Noisy Up, Stable Down, Noisy Down, Reset.
• Bars-in-state is tracked live, giving a simple persistence read on each state.
4. RIBBON RENDERING
• Ribbon is anchored to the EMA centerline with height driven by ATR × a user-selected multiplier (Thin / ATR-Adaptive / Thick).
• Fill opacity and border weight shift by state — Stable states are saturated, Noisy states are faded, Reset is a soft amber.
🔔 SIGNALS & ALERTS
Three transition events are detected and exposed as separate, user-toggled alerts:
• Trend State Flipped — direction changed (Up ↔ Down). Raw, never throttled.
• Stability Improved — path upgraded from Noisy to Stable while direction held. Raw — delivered regardless of badge cooldown.
• Stability Degraded — path downgraded from Stable to Noisy while direction held. Raw — delivered regardless of badge cooldown.
Matching on-chart badges appear at the same moments, subject to the Stability Badge Cooldown for visual cleanliness. Direction-flip badges are never throttled.
⚙️ KEY INPUTS
Engine
• Trend Length (default 34) — lookback for both direction and path-efficiency windows.
• Stability Sensitivity (default 1.0) — scales the Stable / Noisy thresholds.
• Require Slope Confirmation (default on) — enforces price-and-slope agreement; rejects chop.
Ribbon & Badge
• Ribbon Height — Thin / ATR-Adaptive / Thick.
• Show State Badge — toggle on-chart transition labels.
• Label Font Size — tiny / small / normal / large (default normal).
• Minimal Mode — hides panel and badges for pairing with other overlays.
• Stability Badge Cooldown (default 5 bars) — visual throttle for stability transitions.
Info Panel
• Panel Position, Panel Font Size, Efficiency Ratio display, Active Thresholds display.
Alerts
• Independent toggles for each of the three transition events.
🧠 HOW TO USE
• CONTEXT FILTER — use Stable states as a "green light" for continuation setups on your primary system; treat Noisy states as a headwind.
• REGIME BREAKS — a Stability Degraded event mid-trend is often an early warning that the move is maturing, even before price has flipped.
• CLEAN ENTRIES — pair a direction flip (Trend Up / Trend Down) with an immediate Stable classification to filter out whipsaw-prone breakouts.
• CHOP AVOIDANCE — when the ribbon sits in a Reset or Mixed state, the script is telling you the underlying path is not tradeable as a trend. Stand aside or switch to range tactics.
• PAIRING — with Minimal Mode on, the ribbon layers cleanly under structure tools, VWAPs, or S/R zones without visual conflict.
⚠️ LIMITATIONS & TRANSPARENCY
• This is an indicator, NOT a strategy. It does not generate buy or sell orders, has no backtest, and makes no claim of performance.
• Efficiency Ratio is a lagging measure — it describes the path already travelled. The ribbon should be read as context, not as a leading signal.
• The Mixed zone is intentional persistence; expect the composite state to hold through brief chop rather than flipping on every bar.
• Lower timeframes (<5m on thin-liquidity markets) can push ER values into erratic ranges. Start with the defaults on 15m–4h and tune from there.
• All calculations are closed-bar. Intra-bar values may shift until the bar confirms.
🛡️ RISK DISCLOSURE
This script is published for educational and analytical purposes only. It is not financial advice, not a signal service, and not a solicitation to buy or sell any instrument. Past behavior of markets does not predict future results. Always do your own research, apply proper risk management, and consult a licensed professional before making trading decisions. The author assumes no responsibility for losses incurred through use of this indicator. Indicator

Indicator

Kaufman Efficiency Ratio Gate [NovaLens]Kaufman Efficiency Ratio Gate is a regime classifier that separates trending markets from choppy ones. Instead of plotting a raw ratio and leaving you to interpret thresholds, it ranks the current Kaufman Efficiency Ratio within its own recent history and outputs a binary gate: trend-favorable or chop-dominant. Five timeframe-specific presets ship ready to use - pick the one matching your chart.
◉ HOW IT WORKS
The Efficiency Ratio measures how much of price's total movement was directional over N bars:
ER = |Close - Close(N)| / Σ|Close(i) - Close(i-1)|
A value near 1.0 means price moved in a straight line - maximum efficiency. A value near 0 means price covered distance but went nowhere net - noise. Perry Kaufman introduced this in "Trading Systems and Methods" (1995) as the foundation for his Adaptive Moving Average.
Raw ER values are hard to threshold because what counts as "efficient" varies by asset and timeframe. This gate solves that with a three-stage pipeline:
• Light EMA smoothing - removes single-bar noise from the raw ER without adding meaningful lag (Smoothing = 2 for most presets).
• Percentile rank - ranks the smoothed ER within its own rolling window. A reading at the 70th percentile means the current efficiency is higher than 70% of recent history. This is what makes the gate self-normalizing. A "trending" efficiency ratio for Gold might sit at 0.45, while for a volatile altcoin it might be 0.25 - the gate adjusts automatically to each asset's own baseline, so you never need to guess at fixed thresholds.
• Symmetric hysteresis - the gate opens when rank crosses above the median + Stability/2, and closes when rank drops below the median - Stability/2. This prevents flicker at the boundary. A small buffer (Stability = 2) is enough because KER is already a clean ratio.
Other regime tools approach this differently. ADX measures trend strength through smoothed directional movement - it tells you how strong a trend is, but its fixed scale means a reading of 25 carries different weight on different instruments. The Choppiness Index compresses ATR relative to the window's price range into a 0-100 scale - useful, but sensitive to window length and not inherently normalized. The Efficiency Ratio takes a more direct route: what fraction of total movement was net directional? And the percentile-rank layer on top makes that reading self-normalizing across any asset or timeframe - no manual threshold tuning required.
The result is a binary state: trend-favorable (gate open) or chop-dominant (gate closed).
◈ HOW TO READ IT
• Teal background / teal hero line - Gate open. The market's directional efficiency is above its recent median. Trend-following setups tend to perform better in this environment.
• Amber background / amber hero line - Gate closed. Efficiency is below the median - price is moving but not going anywhere. Trend-following setups historically tend to underperform in this environment.
• Bright teal (strong trend) - Smoothed KER is in the top 25% of its recent rank window. The trend is unusually clean - continuation setups tend to be cleaner in this state.
• Bright amber (strong chop) - Smoothed KER is in the bottom 25%. Noise is dominant - even range-bound strategies may find fewer clean entries. Generally a low-opportunity environment.
The info panel (top-right) shows the current gate state, smoothed KER value, percentile rank, and a momentum readout (strengthening / weakening / stable) based on how the rank has moved over the last few bars.
✦ HOW WE USE IT - REGIME FILTER
In systematic trading, the Efficiency Ratio often serves as one of the regime filters applied before a trend-following signal gets capital allocation. The idea is to confirm that the market is actually trending efficiently, not just moving.
When the gate is open (teal), directional efficiency is elevated. Pullback entries, breakout continuations, trend-following MA crosses - these setups tend to perform better because price is converting movement into net progress. When the gate closes (amber), the same setups historically tend to underperform. Price is volatile but going nowhere. In choppy regimes, trend-following systems generally struggle, and while mean reversion may be more favorable, it remains a harder environment to trade overall. Many systematic traders use this kind of regime awareness to reduce exposure or adjust position sizing rather than forcing directional bets.
The gate works well as a context overlay alongside other entry signals. It doesn't indicate which direction to trade, but it helps characterize whether the current environment is rewarding directional movement at all.
What the gate is NOT: a forward predictor. It classifies the recent past. A gate-open reading means efficiency has been high - it doesn't guarantee the next bar will trend. It's a filter, not a crystal ball.
◆ OTHER APPLICATIONS
• Entry filter - pair with any trend-following signal (MA cross, breakout, RSI) and add a gate-open condition. Filtering out chop regimes can help reduce whipsaw entries.
• Multi-timeframe confirmation - checking the gate on a higher timeframe before entering on a lower one can add confidence. For example, a Daily gate-open reading alongside a 4H trend entry.
• Regime-aware sizing - some traders scale position size with regime state, increasing exposure during gate-open periods and reducing it when the gate closes.
• Alert-driven workflow - set alerts on gate open/close transitions and check your trend setups only when the gate fires.
⚙ SETTINGS
Preset (default: Daily) - Timeframe-specific parameter bundles. Select the one matching your chart resolution:
• Weekly - KER 10, Smoothing 2, Rank Window 100, Stability 2. Long context window for position traders.
• Daily - KER 8, Smoothing 2, Rank Window 50, Stability 2. The default. Works well on most daily charts.
• 8H - KER 8, Smoothing 2, Rank Window 50, Stability 2. Starting point same as Daily - validate on your own 8H charts.
• 4H - KER 14, Smoothing 2, Rank Window 30, Stability 2. Wider KER period compensates for noisier intraday data.
• 30m - KER 5, Smoothing 5, Rank Window 30, Stability 2. Short KER period with heavier smoothing for fast charts.
• Custom - Drive the gate from the four inputs below.
KER Period - Lookback for the raw Efficiency Ratio. Shorter (5-8) reacts faster to regime changes. Longer (14-20) gives more stable readings but lags transitions.
Smoothing - EMA applied to the raw KER. Set to 1 for no smoothing. KER is self-normalizing by construction, so low values (1-5) are usually enough.
Rank Window - Rolling window for the percentile rank. Controls how much recent history defines "typical." Shorter windows adapt faster; longer windows give more stable context.
Stability - Hysteresis half-width around the 50th percentile. At 0, the gate flips the instant rank crosses the median. At higher values, the gate requires a stronger signal to switch state. Low values (2-5) work well since KER is already a clean signal.
Display toggles:
• Show Raw KER - thin white line showing the unsmoothed ratio
• Show Median - 50th-percentile reference line on the smoothed KER
• Show Background - teal/amber background wash (turn off if your workspace already signals the regime elsewhere)
• Show Info Panel - gate state, KER, rank, and momentum readout
• Light Theme - flips panel colours for light chart backgrounds
△ LIMITATIONS
• Backward-looking - the gate classifies recent efficiency, not future direction. Regimes can shift faster than the rank window catches, especially around news events.
• Directionless - both strong uptrends and strong downtrends produce gate-open readings. A separate directional indicator is needed to determine which side to trade.
• Noise on thin instruments - short KER periods on low-volume assets can produce noisy readings even with smoothing.
• History requirement - percentile rank needs sufficient data to be meaningful. The first ~50-100 bars on any chart (depending on preset) will have unstable rankings.
⌁ NOTES
• Based on Perry Kaufman's Efficiency Ratio from "Trading Systems and Methods" (1995)
• Cross-validated against our PyneCore Python reference implementation.
• Parameters were tuned on gold (XAUUSD) via the NovaLens research pipeline. The same presets generalize reasonably to other assets - though testing on your own instruments is always recommended.
• Regime palette: teal = trend-favorable, amber = chop-dominant. Not green/red - this is a state classifier, not a directional signal.
If you find a Custom parameter set that works well on a different instrument, the comments are a good place to share it. Indicator

Indicator

Indicator

Indicator

Indicator

Profit Loss Display UniversalUniversal Profit Loss Display
is a chart overlay for quickly visualizing projected reward, risk, and reference levels from the current price.
The script lets you select:
- one main profit target
- one main stop loss level
- four additional reference sources
The sources can be any element of another indicator displayed on the current chart (using the PulseWire's source parameter.
**How it works**
The indicator compares each selected level to the current price and estimates the move using your configured position base. This makes it useful for planning trades around fixed targets, stops, VWAPs, pivots, bands, or any custom level source.
For each active level, it displays the move from current price as price points, dollar value, or both. The profit target and stop loss also get dedicated value labels, and the script calculates a live reward-to-risk ratio in `R` format.
**Key features**
- Configurable `input.source` levels for profit target, stop loss, and 4 extra references
- Display mode selector: `Price Points`, `$ Value`, or `Both`
- Automatic leverage detection by asset class, with manual override
- Dollar projection based on chunk size and leverage
- Clean on-chart labels that only appear when a source is different from `close`
- Reward-to-risk ratio displayed directly on the chart
- Bottom-right info table showing active chunk size and leverage
**Best use cases**
- Pre-trade reward/risk planning
- Visual target and stop mapping
- Comparing multiple nearby levels from current price
- Quick dollar impact estimation without manual calculation
**Notes**
This is a planning helper, not a strategy or execution tool. Dollar projections do not include fees, spread, slippage, funding, or partial exits.
---------------------------------------------------------------------------------------------------------------------
**How To Use**
1. Add the indicator to your chart.
2. Set your main `Profit Target` and `Stop Loss Limit`.
These are the two primary levels used for the projected profit/loss labels and the `R` ratio.
3. Optionally assign `Extra Source 1-4`.
Use these for additional levels you want to monitor, such as VWAPs, pivots, moving averages, bands, or custom plotted values.
4. Choose your `Display Mode`.
- `Both` shows price distance and dollar value
- `Price Points` shows only the raw move from current price
- `$ Value` shows only the projected dollar impact
5. Set your `Chunk Size`.
This is the base position size used in the calculation.
6. Set `Leverage X`.
- Leave it at `0` to use automatic leverage by asset class
Automatic Leverage Rules
If Leverage X is set to 0, the script uses these defaults:
crypto: 5
forex: 30
futures: 10
cfd: 10
stock: 5
index: 20
fund: 5
anything else: 10
A small table in the bottom-right corner shows the active chunk size and leverage.
- Enter a manual value if you want to override auto leverage
7. Turn `Show Labels?` on or off as needed.
**What You Will See**
- A source label for the profit target
- A source label for the stop loss
- Source labels for up to 4 extra levels
- A dedicated profit value label
- A dedicated stop-loss value label
- An `R:x.x` reward-to-risk ratio label
- A bottom-right table showing current chunk size and leverage
**Important Behavior**
- Labels only appear when the selected source is different from `close`
- `close` acts as the default “off” state for any source input
- Labels are updated on the latest bar only
- The ratio is based on distance from current price to target and stop
**Practical Example**
If you are planning a trade:
- set `Profit Target` to your take-profit level
- set `Stop Loss Limit` to your invalidation level
- set `Chunk Size` to your standard trade allocation
- choose a leverage value or leave auto mode enabled
- use the extra sources for nearby confluence or reaction zones
This gives you an immediate view of:
- potential upside
- potential downside
- reward-to-risk ratio
- relative distance to other important levels
**Notes**
This script is a visual planning tool. It does not place trades and does not account for fees, slippage, spread, funding, or scaling in and out.
Indicator

Indicator
