Apex Edge - NQ Correlation HUDApex Edge — NQ Correlation HUD
Note: This script is the HUD only. Screenshots may also show separate Supply & Demand zone and key-level tools running alongside it for extra confluence — those are independent indicators, not part of this script, and aren't required for the HUD to function.
What it does
Apex Edge — NQ Correlation HUD is a compact on-chart dashboard built for trading Nasdaq-100 index products (NQ, MNQ, and similar). Rather than manually flicking between the VIX and individual Mega-Cap Tech charts to gauge whether the broader market agrees with a setup, this indicator brings that context onto your current chart in one glance.
It scores your current instrument's own momentum and structure, then does the same for the VIX and seven Magnificent-7 stocks — live, every bar — and tells you visually which of those names are actually confirming your bias right now versus which aren't.
The HUD: Ticker / Fuel / Confluence
The dashboard is a simple 3-column table:
Ticker — the symbol for that row. Row 1 always reflects whatever chart you're currently on (so it updates automatically if you switch between NQ and MNQ, or any other symbol). Below that: VIX, then the 7 Mag7 names.
Fuel — a 0–10 momentum score for that symbol (see scoring below), shown as a fraction against your configured minimum threshold, e.g. 6/6.
Confluence — a directional vote out of 5, shown as ▲x/▼y, indicating how many of 5 independent components currently lean bullish versus bearish for that symbol.
What it monitors, and why
VIX — the market's fear gauge. It typically moves inversely to equities, so a VIX reading that's rising while your chart is bearish (or falling while your chart is bullish) is a classic confirmation signal. The HUD surfaces VIX's own Fuel and Confluence so you don't have to switch charts to check it.
The 7 Mag7 stocks (defaults: AAPL, MSFT, GOOGL, AMZN, NVDA, META, TSLA — all fully customizable in settings) — these carry substantial weight in the Nasdaq-100 and tend to drive a large share of its movement. When several of them are genuinely moving with your NQ/MNQ chart, that's real confirmation your setup isn't just noise on one instrument; when they're diverging, it's a reason for caution even if your chart alone looks clean.
How each pair offers confluence
A single chart can give a false signal — a stop run, a low-liquidity spike, an isolated headline. Checking whether the broader Nasdaq complex agrees filters a lot of that out. If your NQ/MNQ setup is bearish and the majority of Mag7 names are also showing bearish confluence while correlating with your chart's actual price action, and VIX is leaning bullish (its typical inverse relationship holding up), that's three independent confirmations lining up rather than one chart in isolation.
How the columns are scored
Fuel Score (0–10) is a multi-factor momentum read, built from:
Volume Z-score relative to a rolling average
Candle body dominance within its own range
Where the close sits within the bar's high-low range
ATR expansion versus its own rolling average
Confluence Score (out of 5) is a 5-component directional vote:
LTF trend (Hull moving average)
HTF trend (Hull moving average on a higher timeframe)
LTF RSI position
HTF RSI position
Price structure vs. a rolling range midpoint
Each component casts one bullish or bearish vote; the tally is shown as ▲bullish/▼bearish.
The correlation layer
This is what separates the Mag7 rows from a static watchlist. Each Mag7 ticker's title is colour-coded in real time:
Green — that symbol is BOTH rolling-correlated to your current chart above a threshold you set, AND its own Confluence is currently agreeing with your chart's direction.
Red — either condition fails: it's not correlating closely enough right now, or it's correlating but currently pointing the other way.
This means the HUD isn't just showing you 7 static numbers — it's telling you, live, which of the 7 are actually confirming your bias in this moment versus which are just along for the ride historically. Correlation lookback, the green/red threshold, and the correlation-guide tooltip (with standard statistical strength bands) are all configurable.
Built-in alerts
Two included alert conditions ("HUD Setup: Long Bias" / "HUD Setup: Short Bias") fire when your chart's Confluence bias is shared by a configurable number of the 7 Mag7 symbols AND VIX Confluence is leaning the opposite way. These are deliberately price-agnostic — they tell you when the broader HUD context has aligned, not when to enter. Pair them with your own key-level or zone tools to time actual entries once the alert fires.
Settings
Fuel/Confluence Dashboard toggle, dashboard position, minimum Fuel threshold
Hull MA period and HTF resolution
Multi-Pair HUD toggle, monitor timeframe for the 7 Mag7 rows
VIX symbol, all 7 Mag7 symbols (freely swappable)
Correlation lookback length, correlation threshold, min Mag7 aligned count for alerts
Align it with other confluence indicators to time your entry. Below is an example of the HUD running alongside 2 indicators (Key levels & Supply & Demand zones).
A NOTE ON USE:
Market hours affect the correlation rows. NQ/MNQ trade nearly 24 hours; the Mag7 equities only trade actively during NASDAQ hours (with an extended pre/post-market window beyond that). Outside those hours, correlation can legitimately read n/a for some or all Mag7 rows — that's expected behaviour, not a fault, since a closed/flat equity price has no variance to correlate against. Correlation readings are most meaningful during and immediately around the NASDAQ session; Fuel and Confluence continue working normally at all hours since they don't depend on cross-symbol variance.
This tool is designed to support discretionary trading decisions around Nasdaq-100 index products — it doesn't generate entries or exits on its own, and none of its readings guarantee a particular outcome. Fuel, Confluence, and correlation are all descriptive of current and historical price behaviour, not predictions. As with any tool, backtest and forward-test on a demo account before relying on it in a live or funded environment. Nothing in this script or its description constitutes financial advice. Indicator

STRX - AutoCorrelationSTRX – AutoCorrelation is a quantitative analysis tool designed to monitor real‑time correlations between up to five assets, using the Pearson correlation coefficient over a customizable period and timeframe. The script displays a correlation matrix as a heatmap table together with a structured textual reading, providing an immediate operational view of the strength and direction of relationships across assets.
The “Assets to Correlate” panel allows the user to select up to five instruments (for example Gold, US100, USDX, Silver, Platinum) and to enable or disable each slot individually, so the correlation set can be quickly adapted to different market contexts. Through the “Settings” panel, the user can define an independent calculation timeframe, the lookback period for the correlation, whether to show the textual reading table, and the position of the panel on the chart.
The matrix highlights, for each pair, the normalized correlation value between −1 and +1, with a color scheme that distinguishes positive and negative correlations and emphasizes their intensity. The textual reading table classifies each relationship as “Strong”, “Moderate”, “Weak” or “Negligible” and specifies the sign (“Positive” / “Negative” / “Independent moves”), helping the user assess co‑movements, diversification, hedging behavior and potential concentration of risk across the selected assets.
This indicator is intended as a decision‑support tool for multi‑asset analysis and does not generate standalone entry or exit signals. It does not constitute financial advice or a guarantee of performance; any trading or investment decisions remain solely the responsibility of the user. Indicator

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

Regime-Conditional Correlation [RC Tools]RC Tools — Regime-Conditional Correlation
─────────────────────────────────────────────────────────────
█ OVERVIEW
Plain rolling correlation between two assets is well-covered ground. The angle here: correlation is not a constant — it changes with the market regime. This tool computes rolling correlation against a second symbol of your choice and buckets it by the same regime framework as the Regime Classifier, so you can see whether a correlation you're relying on actually holds up across market conditions, or only shows up in one of them.
█ WHAT IT DOES
Plots rolling correlation (Pearson, default 20-bar window) between the current chart's symbol and a compare symbol you choose. Colours the background by the current market regime (Trending — Expansion/Exhaustion, Ranging — Quiet/Volatile), using the identical directionality × volatility-percentile logic as the Regime Classifier. A table shows the current regime and correlation, plus the average correlation, its standard deviation, and the sample count for each of the four regimes historically.
█ THE THEORY BEHIND IT
A single "the correlation is 0.8" number hides a lot. Two assets can be tightly linked during calm trending markets and decouple completely during volatile chop — or vice versa. Regime-conditioning the correlation surfaces that structure instead of averaging it away. This matters directly for anything relying on a stable cross-asset relationship: hedges, pairs, or diversification assumptions that quietly break exactly when you need them most (in the volatile regime).
█ HOW IT IS CALCULATED
CORRELATION: standard Pearson correlation between the current symbol's close and the compare symbol's close (fetched via request.security on the same timeframe), over a rolling window (default 20 bars).
REGIME: identical to the Regime Classifier — Efficiency Ratio for directionality, percentile-ranked realised volatility for volatility state, crossed to give four states. Regime is measured on the CURRENT chart's own price action, not the compare symbol. See the Regime Classifier's description for the full methodology.
The correlation reading and the regime are both "as of now" — contemporaneous — so unlike the Regime Classifier's forward-return table, no forward-looking attribution is needed here: each confirmed bar's correlation is added directly to the running average for whichever regime was active on that same bar.
█ SETTINGS & CONFIGURATION
• Compare Symbol (default BTCUSD) — the second asset to correlate against
• Correlation Length (default 20 bars)
• Regime settings mirror the Regime Classifier exactly (Efficiency Ratio lookback, directionality threshold, realised vol lookback, percentile window, volatility percentile threshold) — keep these in sync if you run both indicators together
• Paint Main Chart Background — off by default; enable on only one of the two indicators if running both, to avoid overlapping backgrounds
█ HOW TO USE IT
Check whether a correlation you're relying on is regime-dependent before trusting it. Example: if a hedge shows strong negative correlation in Ranging — Quiet but the average correlation flips or weakens in Ranging — Volatile, that hedge may not protect you exactly when volatility spikes. Always check the sample count (N) per regime before drawing conclusions — a regime with few historical bars hasn't been tested enough to trust its average.
█ LIMITATIONS
• Correlation is measured over a short rolling window and is noisy by nature — it will swing even when the underlying relationship is stable.
• The compare symbol is fetched via request.security on the same timeframe; illiquid symbols, different exchange sessions, or timezone misalignment can introduce lag or missing values.
• Regime classification carries the same caveats as the Regime Classifier: it is backward-looking by construction, unstable near threshold boundaries, and needs substantial history to be reliable.
• Per-regime correlation statistics accumulate only from where the chart's loaded history begins — early sample counts are small and not yet statistically meaningful.
• This script does NOT repaint. All classification and correlation display values update on confirmed bar close only.
█ DISCLAIMER
For educational and informational purposes only. Nothing here is financial advice. Past correlation between any two assets does not indicate future results. Trade at your own risk.
Indicator

Indicator

ICT Fractal SMT Divergence Engine [v6]
ENGLISH
🔥 ICT Fractal SMT Divergence & Auto-Triad Engine is a professional, high-precision PulseWire indicator designed for Smart Money Concepts (SMC) and Inner Circle Trader (ICT) methodology.
🎯 PURPOSE & CONCEPT
In institutional trading, SMT (Smart Money Technique) Divergence measures inter-market relative strength across correlated asset groups (Triads). When one asset in a triad sweeps liquidity by creating a new extreme ( Lower Low or Higher High ), while a correlated asset fails to sweep that extreme ( Higher Low or Lower High ), it reveals institutional accumulation/distribution and an imminent high-probability market reversal.
This indicator calculates SMT divergences strictly between confirmed Bill Williams / ICT Fractals , ensuring pixel-perfect visual precision on the chart with zero Y-axis displacement.
🧠 SMART AUTO-DETECT TRIAD ENGINE
The indicator automatically recognizes your current chart ticker and instantly pairs it with its exact correlated triad assets:
Crypto : Opening BTCUSDT.P, ETHUSDT.P, or any Altcoin automatically pairs BTCUSDT.P, ETHUSDT.P, and CRYPTOCAP:TOTAL3.
Forex : Opening EURUSD or GBPUSD automatically pairs the counterpart FX pair and DXY (with automatic inverse Dollar Index correlation).
Precious Metals : Opening XAUUSD (Gold) pairs XAGUSD (Silver) and PLATINUM. Opening XAGUSD pairs XAUUSD and PLATINUM.
US Stock Indices : Automatically correlates ES1! (S&P 500), NQ1! (Nasdaq), and YM1! (Dow Jones).
📖 HOW TO TRADE / USAGE RULES
Bullish SMT Setup (Long Bias) :
- Main asset breaks prior Fractal Low (Lower Low / Liquidity Sweep).
- Correlated triad asset holds its low (Higher Low).
- Execution: Look for bullish Market Structure Shift (MSS) or Fair Value Gap (FVG) entry.
Bearish SMT Setup (Short Bias) :
- Main asset breaks prior Fractal High (Higher High / Liquidity Sweep).
- Correlated triad asset holds its high (Lower High).
- Execution: Look for bearish Market Structure Shift (MSS) or Fair Value Gap (FVG) entry.
⚙️ COMPREHENSIVE SETTINGS & INPUTS EXPLANATION
Triad Preset Mode : Select between Auto Detect (Smart Triad), specific market presets, or Custom / Manual Tickers.
Asset 2 / Asset 3 Ticker (Custom) : Manual input for custom correlated assets when in Custom Mode.
Invert Asset 2 / Invert Asset 3 : Toggle for inversely correlated symbols (e.g., DXY vs EURUSD).
Fractal Length (Left/Right Bars) : Defines the fractal shoulder size (Default: 2 = classic 5-candle ICT Fractal).
Comparison Mode : Choose between Regular (High/Low wicks) or Hidden SMT (Close body prices).
Min / Max Distance (Bars) : Controls minimum and maximum bar separation between compared fractals.
Compare with Asset 2 / Compare with Asset 3 : Toggle individual asset divergence verification.
Visual Styling & HUD Dashboard : Customize colors, line thickness, label sizes, background glow, and dashboard HUD position.
Disclaimer: Trading financial markets involves substantial risk of loss. This indicator is designed for educational and analytical purposes to support SMC/ICT trading methodologies.
================================================================================
РУССКАЯ ВЕРСИЯ
🔥 ICT Fractal SMT Divergence & Auto-Triad Engine — это профессиональный высокоточный индикатор для трейдеров, торгующих по концепциям Smart Money Concepts (SMC / ICT) .
🎯 ПРЕДНАЗНАЧЕНИЕ И КОНЦЕПЦИЯ
В институциональном трейдинге SMT (Smart Money Technique) Дивергенция измеряет относительную силу между коррелирующими группами активов (Триадами). Когда один актив из триады обновляет ключевой ценовой уровень ( Lower Low или Higher High ), совершая снятие ликвидности (Liquidity Sweep) , а второй актив из триады отказывается обновлять свой экстремум (формируя Higher Low или Lower High ), это открывает институциональный след крупного игрока и указывает на скорый разворот рынка.
Индикатор строит дивергенции строго между подтвержденными фракталами Билла Вильямса / ICT , обеспечивая идеальную визуальную точность на графике без смещения меток по ценовой оси.
🧠 УМНЫЙ АВТО-ДЕТЕКТОР ТРИАД (SMART AUTO-DETECT)
Индикатор автоматически определяет открытый актив и мгновенно связывает его с правильной триадой:
Криптовалюта : При открытии BTCUSDT.P, ETHUSDT.P или любого альткоина автоматически подтягиваются коррелирующие активы: BTCUSDT.P, ETHUSDT.P и CRYPTOCAP:TOTAL3.
Валютные пары (Forex) : При открытии EURUSD или GBPUSD подтягивается парный валютный актив и DXY (с автоматической инверсией индекса доллара).
Драгоценные металлы : При открытии XAUUSD (Золото) автоматически подтягивается XAGUSD (Серебро) и PLATINUM. При открытии XAGUSD — XAUUSD и PLATINUM.
Фондовые индексы США : Автоматическое сравнение триады фьючерсов ES1! (S&P 500), NQ1! (Nasdaq) и YM1! (Dow Jones).
📖 РУКОВОДСТВО ПО ТОРГОВЛЕ И СИГНАЛЫ
Bullish SMT (Бычий SMT / Покупки) :
- Основной актив обновил предыдущий фрактальный лой (Lower Low / снял ликвидность).
- Коррелирующий актив из триады удержал лой (Higher Low).
- Вход в сделку: Ищите слом структуры (MSS / CHoCH) или имбаланс (FVG) на младшем таймфрейме для входа в лонг.
Bearish SMT (Медвежий SMT / Продажи) :
- Основной актив обновил предыдущий фрактальный хай (Higher High / снял ликвидность).
- Коррелирующий актив из триады удержал хай (Lower High).
- Вход в сделку: Ищите слом структуры (MSS / CHoCH) или имбаланс (FVG) на младшем таймфрейме для входа в шорт.
⚙️ ПОДРОБНЫЙ РАЗБОР ВСЕХ НАСТРОЕК
Triad Preset Mode : Выбор между Auto Detect (умное авто-определение), готовыми пресетами рынков или режимом Custom (ручной ввод).
Asset 2 / Asset 3 Ticker (Custom) : Поля для ручного ввода тикеров при включенном режиме Custom.
Invert Asset 2 / Invert Asset 3 : Включение инверсии для обратно коррелирующих активов (например, DXY против EURUSD).
Fractal Length (Left/Right Bars) : Размер плеча фрактала (по умолчанию 2 — классический 5-свечной фрактал ICT).
Comparison Mode : Режим сравнения: Regular SMT (сравнение по фитилям High/Low) или Hidden SMT (по закрытию тел Close).
Min / Max Distance (Bars) : Минимальное и максимальное расстояние в барах между сравниваемыми фракталами.
Compare with Asset 2 / Compare with Asset 3 : Включение/выключение проверки дивергенции по отдельным активам.
Visual Style & HUD Dashboard : Настройка цветов (Bull/Bear SMT), толщины линий, размера меток, подсветки фона и позиции таблицы на экране.
Отказ от ответственности: Торговля на финансовых рынках несет высокий риск. Данный индикатор создан для аналитических целей и поддержки решений по SMC / ICT концепциям. Indicator

Intermarket Divergence with Reliability ScoringIntermarket Divergence with Reliability Scoring
Related markets tend to move together. When your chart pushes to a new high but a market that usually tracks it does not confirm, that non-confirmation can precede a turn. This script measures divergence between your chart and a chosen leader market — but only when the leader is actually correlated to price, because a decoupled market's "divergence" is meaningless — and then scores, in real time, whether those divergences have been worth trading on your symbol.
WHAT IT PLOTS
A normalised oscillator built from a chosen leader market, its stretch bands, divergence markers and connecting pivot lines, plus a plain-language verdict panel. By default the chart stays minimal — the oscillator and the verdict panel — with optional key-info and per-class tables you can switch on in settings.
WHY THESE COMPONENTS ARE COMBINED, AND HOW THEY WORK TOGETHER
Three classical pieces are fused into one pipeline, not stacked as independent signals:
A z-scored leader series — optionally inverted, optionally lead-lag shifted — the cross-market line your price is compared against.
A live correlation gate — the leader only votes when its trailing correlation to price clears a threshold, so non-confirmations from a decoupled market are ignored.
A binomial-proportion confidence test — asks, for each divergence class, whether the expected move followed more often than a same-zone baseline would deliver.
Part 1 builds the comparison, part 2 keeps only the meaningful divergences, part 3 decides whether the survivors have actually paid on this instrument, by direction. The parts are interdependent — remove any one and the script can no longer answer its core question: is this intermarket divergence worth trading here, and which way?
HOW TO READ IT
The verdict panel translates the statistics into four states:
GREEN, edge confirmed: these divergences have beaten a same-spot baseline here. Worth acting on.
RED, no edge here: they have lost to a coin-flip. Skip them, pick a leader that genuinely leads, or change the timeframe.
AMBER, unproven: edge not statistically established yet; treat as low-confidence.
GREY, learning: still collecting completed samples.
It also shows:
Best signal — names a direction only once that direction is individually proven (its edge lower-bound clears zero). Otherwise it says "none confirmed", so you are never lured by a single noisy number.
Leader link — how tightly the leader currently tracks price (strong, moderate or weak). A weak link means the leader has decoupled and its divergences are unreliable.
Reward : risk — the average best move versus the average worst move after a signal, in ATR. Below 1:1 means signals have hurt more than they helped.
Market regime — reverting markets suit divergence; strong trends punish it.
A divergence is simply price making a higher high or lower low while the leader line does the opposite, counted only when the leader is correlated enough to matter.
CHOOSING A LEADER
Pick a market that genuinely leads — a currency, a global risk proxy, a sector index — not one that merely co-moves with your chart. The lead-lag offset lets you test whether it leads. A co-moving index will usually show no edge, which the panel will tell you plainly.
WHAT IS ORIGINAL
Standard intermarket tools just overlay two symbols. This one fuses a live correlation gate into the divergence filter, then keeps a self-updating, confidence-scored, per-class track record against a same-zone baseline — so you see not just that a non-confirmation printed, but whether and how it has paid, and you only trust a direction once it is statistically proven.
UNIVERSAL ACROSS MARKETS
Reads the chart's own price (the source is configurable in settings) plus one leader symbol. Defaults target NIFTY futures with Bank Nifty as the leader. Change the leader to USD/INR (inverse), a sector or overseas index, or any related market for other instruments, in any market.
OUTPUTS FOR OTHER SCRIPTS
Generic EXP_ values — oscillator, signal, probability, edge, edge lower-bound, sample count, regime, leader value and leader correlation — are published to the Data Window so other indicators can read them via input.source().
CONCEPT CREDITS
Average true range — J. W. Wilder. Binomial score confidence interval — E. B. Wilson. Trend-efficiency regime measure — P. Kaufman. Intermarket analysis and divergence — classical technical analysis.
DISCLAIMER
For research and education only. This is not financial advice, not a recommendation to buy or sell, and not a guarantee of future results. All performance shown is in-sample and past-only. Markets carry risk — do your own research and manage your own risk. Indicator

Asset Class Correlation MatrixAsset Class Correlation Matrix
█ OVERVIEW
This indicator displays a Pearson correlation matrix for instruments in the asset class of the symbol you are currently viewing. Open a EUR pair and you see the forex matrix. Open gold and you see the metals matrix. Open Bitcoin and you see the crypto matrix. The relevant basket loads automatically, so there is nothing to configure for the common cases.
Each cell shows the rolling correlation between two instruments over a lookback period you control. The goal is to make cross-instrument relationships inside an asset class visible at a glance, rather than checking pairs one at a time, or relying on visual comparison.
█ AUTOMATIC ASSET CLASS DETECTION
The current symbol is matched to a category in three stages:
1. Exact ticker match against the built-in lists below.
2. Name-fragment match for common broker and CFD names. For example XAU and GOLD map to Metals, US500, SP500, NAS100, US100, US30 and DJ30 map to US Indices, DAX, FTSE and NIKKEI map to Global Indices, and WTI, BRENT and NATGAS map to Energy.
3. Asset type fallback using the instrument type, covering crypto, forex, and stocks.
If the current symbol is not already part of a built-in list, it is added as the first row and column of the matrix, so the instrument you are on is always included. If no category can be determined, the table shows a short prompt to use the custom symbol list instead of rendering empty.
█ BUILT-IN CATEGORIES
Forex: 28 majors and crosses across USD, EUR, GBP, JPY, AUD, CAD, CHF and NZD.
US Indices: ES, NQ, YM, EMD, RTY.
Global Indices: DAX, Euro Stoxx 50, Nikkei, FTSE, ASX 200, Hang Seng.
Metals: Gold, Silver, Copper, Platinum, Palladium.
Energy: WTI Crude, Natural Gas, Heating Oil, RBOB Gasoline.
Agricultural: Corn, Soybeans, Wheat, Soybean Oil, Soybean Meal, Cocoa, Coffee, Sugar, Cotton, Orange Juice.
Livestock: Live Cattle, Lean Hogs, Feeder Cattle.
Interest Rates: 2Y, 10Y, 30Y US notes, Euro Bund, Euro Buxl.
Crypto: BTC, ETH, BCH, LTC.
Stocks: SPX, QQQ, AAPL, MSFT, NVDA, AMZN, GOOGL, META, TSLA, AMD.
█ READING THE MATRIX
Pearson correlation ranges from -1 to +1.
Values near +1 mean the two instruments move strongly together. Values near -1 mean they move strongly opposite to each other, which is still a strong relationship, just inverted. Values near 0 mean little to no linear relationship.
The strength of a relationship is the distance from zero, in either direction. A reading of -0.9 is just as tight as +0.9.
█ COLORS
Positive correlation is shown in green, with a stronger shade above the high threshold and a lighter shade above the moderate threshold. Inverse correlation is shown in purple, using the same two strength levels. Everything between the negative and positive moderate threshold is shown as low. All five colors and both thresholds are adjustable in the settings. The thresholds apply symmetrically to positive and inverse values.
█ CUSTOM SYMBOL LIST
You can override the auto-detected basket with your own comma-separated list of symbols. Spaces are ignored. The custom list is applied only when the current chart symbol is one of the symbols in the list, which keeps the chart instrument anchored in the matrix.
You can include an exchange or broker prefix, for example OANDA:EURUSD. A bare ticker such as GBPJPY inherits the current chart prefix. Bare futures contracts such as ES1! resolve on their native exchange.
█ SETTINGS
Period: lookback in bars for the correlation calculation. Shorter reacts faster and is noisier. Longer is more stable and slower to update.
High and Moderate Correlation Thresholds: the cutoffs for the color bands.
Colors: the five correlation colors.
Symbol List: the optional custom basket.
Table Size: text size of the matrix.
█ HOW TO USE IT
Add the indicator to any chart in a supported asset class. Use it to find pairs that move together or opposite each other, to check diversification across a basket, to spot when a normally correlated pair is diverging, or to choose hedges and pairs-trade candidates. The left column shows the full applied symbol for each row, so you can confirm exactly which feed each value comes from.
█ NOTES AND LIMITATIONS
Correlation is period-dependent. For tightly linked instruments, a long lookback pushes most values toward the extremes, while a short lookback spreads them out and reacts faster. Choose the period to match the question you are asking.
Correlation measures linear co-movement of closing prices on the chart timeframe. It does not imply causation and does not capture non-linear relationships.
Broker naming for CFDs varies widely, so some instruments may not auto-detect. When that happens, use the custom symbol list.
A maximum of 28 instruments can be loaded in one matrix. Indicator

Intermarket Confluence Engine | AnonycryptousIntermarket Confluence Engine (ICE) | Anonycryptous
Description & user manual
Why this indicator exists
Most indicators analyze one asset in isolation. They look at price, momentum, volume, or volatility — all on the same chart, all based on the same data feed. That is useful, but it leaves out the context that drives markets at a deeper level: the relationship between assets, the macro regime, the direction of capital flow across instruments.
ICE approaches the problem differently.
Instead of analyzing a single price series, it takes two assets and computes their ratio. That ratio becomes the subject of analysis — not the individual prices. The result is a view of relative strength, regime state, and intermarket context that no single-asset indicator can produce.
It runs eight independent analytical engines on that ratio. Each engine returns a directional score. Those scores are weighted based on the selected asset class and combined into a single confluence number from -10 to +10. The dashboard shows the engine breakdown, the macro state, and the current statistical position of the ratio in its historical distribution — all in one compact panel.
ICE is not a signal indicator. It does not tell you when to buy or sell. It tells you what the current relationship between two assets looks like across eight independent dimensions, and how much those dimensions agree with each other.
Important notice
ICE does not generate trading signals.
It does not tell you when to buy or sell.
It does not predict market direction.
It does not guarantee any outcome.
All trading decisions remain entirely with the user.
Always apply your own judgment and manage your own risk.
1. Overview
ICE is a ratio-based intermarket confluence scoring system. It takes two configurable assets, computes their price ratio (Asset A divided by Asset B), and runs that ratio through eight analytical engines simultaneously.
The nine engines are:
- Relative strength — how much Asset A is outperforming or underperforming Asset B on a rate-of-change basis
- Trend — EMA structure and slope direction of the ratio
- Momentum — volume-weighted RSI and MACD histogram alignment on the ratio
- Volatility — Bollinger Band width, ATR percentile, and squeeze state of the ratio
- Statistical extremes — Z-score and historical percentile position of the ratio
- Macro regime — direction of DXY, VIX, and 10-year Treasury yields
- Liquidity — yield curve proxy using 10-year yield rate of change
- Intermarket correlation — rolling correlation between the ratio and each macro feed
- Volume participation — OBV slope and relative volume confirmation on both assets
Each engine is weighted based on the selected asset class. A custom weighting mode is available for manual control. All weights are normalized so the final score always maps to the -10 to +10 range regardless of class selection.
The chart displays the ratio as a line with an EMA stack (21, 50, 200), Bollinger Bands, and statistical deviation bands based on Z-score distance from the historical mean. Signals fire when confluence crosses configurable thresholds. Divergence between the ratio and its volume-weighted RSI is detected mechanically and shown on the chart.
2. The ratio
2.1 What it represents
The ratio is simply the price of Asset A divided by the price of Asset B. If Asset A is gold (XAUUSD) and Asset B is silver (XAGUSD), the ratio is the gold/silver ratio — how many ounces of silver one ounce of gold can buy. If Asset A is NQ futures and Asset B is ES futures, the ratio represents the relative performance of tech versus the broad market.
The ratio rises when Asset A outperforms Asset B. It falls when Asset B outperforms Asset A. All eight engines work on this ratio, not on the underlying prices.
2.2 What is plotted
The ratio line is the primary visual element. It is colored gold when above its 50-period EMA and grey when below. The EMA stack (green for the 21, blue for the 50, white for the 200) shows the structural state of the ratio trend.
Two band systems are visible simultaneously:
Statistical deviation bands — based on Z-score. The upper band is the historical mean plus 2 standard deviations (configurable). The lower band is the mean minus 2 standard deviations. When the ratio is near or beyond these bands, the Statistical engine activates and the dashboard notes an extreme condition.
Bollinger Bands — a separate volatility-based band using a configurable period and multiplier. These bands are lighter and secondary to the statistical bands.
Squeeze markers appear as small squares along the statistical mean when the Bollinger Bands are contained inside the Keltner Channel — indicating compressed volatility and a potential breakout.
2.3 Signal markers
Signals are plotted directly on the ratio chart using triangles and circles. All markers use plotshape, not labels.
Large triangles up (green) — strong bull confluence (score above +6)
Large triangles down (red) — strong bear confluence (score below -6)
Small triangles up (faded green) — moderate bull confluence (score between +3.5 and +6)
Small triangles down (faded red) — moderate bear confluence (score between -3.5 and -6)
Cyan circles — bullish momentum divergence aligned with positive score
Orange circles — bearish momentum divergence aligned with negative score
Purple squares — active volatility squeeze
3. The eight engines
3.1 Relative strength engine
This engine measures how much Asset A is outperforming Asset B on a rate-of-change basis. It computes the ROC of each asset independently over a configurable period (default 14) and subtracts them to get a delta. That delta is then Z-score normalized over a longer lookback (default 50) to assess whether the current outperformance is historically significant.
The engine also tracks the velocity of the ratio itself — the first derivative of the ratio — and whether the ratio is above its own EMA.
Score: +1 when the RS Z-score is above 0.5 and the ratio is above its EMA. -1 when the RS Z-score is below -0.5 and the ratio is below its EMA. 0 otherwise.
The dashboard shows the raw RS Z-score in the state section so you can see how far from neutral the relative strength is reading.
3.2 Trend engine
The trend engine evaluates the EMA alignment of the ratio across three periods (21, 50, 200), the slope direction using linear regression, and optionally a higher timeframe EMA confirmation.
A full bull stack is when EMA 21 is above EMA 50 and EMA 50 is above EMA 200, combined with a positive slope. A full bear stack is the reverse. Transitional states occur when the stack is broken but slope still has a direction.
The HTF trend filter uses a configurable higher timeframe (default weekly) and checks whether the chosen asset is above its 50-period EMA on that timeframe. When enabled, the trend engine only scores positively if the HTF also confirms.
Score: +1 for confirmed bull trend. -1 for confirmed bear trend. 0 for compression or transition.
The trend state shown in the dashboard (Expansion, Contraction, Transitional, Compression) reflects the combination of stack state and slope direction.
3.3 Momentum engine
The momentum engine uses a volume-weighted RSI applied to the ratio. The weighting uses the combined average volume of both assets, normalized by its own moving average. This is the same architecture as VW RSI Pro — gains and losses are scaled by relative volume before the RSI calculation, so bars with above-average volume have more influence on the RSI than bars with below-average volume.
Alongside the VW RSI, the engine computes MACD histogram acceleration (the change in histogram value, not just its level). This distinguishes between momentum that is building and momentum that is present but decelerating.
Score: +1 when VW RSI is above 52 and MACD histogram is positive. -1 when VW RSI is below 48 and MACD histogram is negative. 0 otherwise.
The VW RSI value is shown in the state section of the dashboard. Values above 55 are colored green, below 45 red, between them grey.
3.4 Volatility engine
The volatility engine assesses whether the ratio is in a phase of compression or expansion, and which direction expansion is occurring.
It computes Bollinger Band width relative to its 100-bar average — widening bands indicate expansion, narrowing bands indicate compression. ATR percentile rank over a configurable lookback (default 100 bars) provides a second volatility measure. A squeeze is identified when the Bollinger Bands are fully contained within the Keltner Channel.
Score: +1 when volatility is expanding and the ratio is above the Bollinger midline, or when a squeeze releases upward. -1 for the same conditions in the downward direction. 0 during compression or neutral volatility states.
The vol state (Squeeze, Breakout, Expansion, Compression, Neutral) is shown in the dashboard state section. Squeeze appears in purple, breakout in gold, expansion in the configured bull color.
3.5 Statistical extremes engine
This engine measures where the current ratio stands within its own historical distribution. It computes a Z-score of the ratio over a configurable lookback (default 50) and a historical percentile rank over a longer window (default 252 bars, approximately one year of daily data).
When the ratio is more than 1.5 standard deviations above its mean and above the 80th percentile, it is classified as historically expensive — a potential mean reversion candidate to the downside. When it is more than 1.5 standard deviations below its mean and below the 20th percentile, it is historically cheap — a potential mean reversion candidate to the upside.
Score: +1 at extreme lows (below mean, below 20th percentile). -1 at extreme highs (above mean, above 80th percentile). 0 within normal range.
The Z-score and historical percentile are shown in the dashboard state section. A gold highlight on the Z-score indicates an active extreme condition.
The mean reversion probability displayed in the extended panel is a normalized version of the absolute Z-score distance — a rough proxy for how far the ratio has stretched from its historical center. It is not a probability in the statistical sense, but a relative measure of extension.
3.6 Macro regime engine
The macro regime engine uses three external data feeds — DXY (dollar index), VIX (volatility index), and TNX (10-year Treasury yield) — loaded via request.security(). It evaluates the trend direction of each feed relative to a smoothed EMA (configurable length, default 20) and classifies the current macro environment.
The global regime classification (Risk-On / Risk-Off / Mixed) appears in the dashboard header. It is always based on the same three-signal count regardless of asset class: VIX level, DXY trend, and yield direction.
The macro score, however, is class-aware. Each asset class has its own logic:
Gold / Silver — risk-off conditions (elevated VIX, falling yields, falling dollar) favor Asset A (gold). Risk-on conditions (low VIX, rising yields, rising dollar) favor Asset B (silver outperforms on industrial demand). Score is +1 for acute risk-off, -1 for sustained risk-on.
Crypto — DXY direction is the primary gatekeeper. Falling DXY and falling yields are bullish for crypto. Rising DXY and rising yields are bearish. VIX provides a third signal. Two of the three conditions must align for a score to fire.
Forex — trend-following regime logic. Risk-on environments favor the ratio direction, risk-off favors the reverse.
Indices — same structure as Forex. Risk-on = positive bias.
Commodities — DXY-led. Falling dollar supports commodity ratios.
Score: +1 for regime favorable to Asset A. -1 for regime favorable to Asset B. 0 for mixed.
3.7 Liquidity engine
The liquidity engine uses the 10-year Treasury yield (TNX) rate of change as a proxy for liquidity conditions. Falling long-term yields indicate looser financial conditions — lower cost of capital, more risk appetite. Rising yields indicate tightening.
The TNX rate of change is computed over 20 bars and smoothed with a 10-bar EMA. When the smoothed ROC is below -0.1, conditions are classified as expanding. Above +0.1, contracting.
Score logic is class-aware:
- Gold / Silver — expanding liquidity (falling yields) is positive for the ratio since gold benefits more from low rates. Contracting is negative.
- Crypto — same direction. Loose liquidity benefits risk assets.
- Forex — inverted. Rising yields support yield-differential-driven pairs.
- Other classes — expansion is positive.
Score: +1 for favorable liquidity, -1 for unfavorable, 0 for neutral.
3.8 Intermarket correlation engine
This engine computes the rolling Pearson correlation between the ratio and each macro feed (DXY, VIX, TNX) over a configurable window (default 30 bars). It then assesses whether the current correlations match the expected structural behavior for the selected asset class.
For the Gold/Silver ratio, for example, historically the ratio is positively correlated with VIX (risk-off pushes gold relative to silver) and negatively correlated with DXY (weaker dollar benefits silver less). When those correlations are in place and above a threshold (±0.15), the engine confirms the macro alignment.
A correlation shift is detected when the sign of a correlation flips compared to 10 bars ago — this is flagged in the dashboard as a regime change signal.
Score: +1 when correlations confirm expected behavior for Asset A outperformance. -1 when they confirm the reverse. 0 when correlations are below threshold or mixed.
3.9 Volume participation engine
This engine measures whether the volume behind the ratio's current move confirms its direction. It uses two inputs: the relative volume difference between Asset A and Asset B, and the slope of the on-balance volume (OBV) calculated on the ratio.
The relative volume comparison checks whether Asset A is attracting more volume than Asset B relative to their combined average. When Asset A draws disproportionately more volume, it indicates institutional interest in the primary asset. The OBV slope uses a 20-bar linear regression to determine whether cumulative directional volume is rising or falling.
A bullish confirmation requires the OBV slope to be positive, the ratio to be above its 21 EMA, and Asset A to have higher relative volume. A bearish confirmation requires the reverse. When volume diverges from price direction — OBV falling while price rises, or vice versa — this is flagged in the extended panel as a volume divergence warning.
Score: +1 when volume participation confirms the ratio move upward. -1 when it confirms downward. 0 when volume is inconclusive or mixed.
4. Adaptive weighting
Each engine returns -1, 0, or +1. Each score is multiplied by the engine's weight for the selected asset class. The sum of all nine weighted scores is normalized against the total possible weight to produce the final confluence score on a -10 to +10 scale.
Asset class presets:
Gold / Silver — statistical extremes and macro regime are weighted most heavily (14 each). This reflects the GSR's mean-reverting nature and strong sensitivity to macro conditions. Volume participation carries moderate weight — on the GSR, volume confirmation is useful but less decisive than macro state.
Crypto — liquidity and momentum are weighted most heavily (14 each). Volume participation also carries elevated weight, since capital rotation between an asset and stablecoins is directly visible in relative volume.
Forex — trend and correlation are weighted most heavily (14 each). Currency pairs respond to trend conditions and intermarket relationships more reliably than statistical extremes.
Indices — momentum and liquidity are weighted most heavily (14 each). Volume participation also carries elevated weight — index futures moves backed by strong volume are more reliable than low-volume drifts.
Commodities — relative strength and volatility are weighted most heavily (14 each). Volume participation carries moderate weight since commodity ratio moves are often driven by volume imbalances between the two assets.
Custom — all nine weights are individually configurable from 0 to 20.
The confidence percentage shown in the dashboard is the spread between the normalized bull and bear score components — a measure of how much the engines agree rather than merely how many fire.
5. Dashboard
The dashboard is a single compact panel with four columns and thirteen rows. It shows the complete scoring state, engine breakdown, and market context in one place.
Header row — indicator name, asset class, confluence label, and score out of 10. The header color reflects the net score direction.
Confidence and regime row — confidence percentage and the global macro regime (Risk-On / Risk-Off / Mixed).
Engine scores — eight engines displayed two per row across four columns. Each engine shows its label and its weighted score with direction indicator. A green upward triangle indicates a positive contribution. A red downward triangle indicates a negative contribution. A grey dot indicates a neutral score.
State section — trend state, volatility state, VW RSI value, and Z-score. The trend state label (Expansion, Contraction, Transitional, Compression) reflects the combination of EMA alignment and slope. The vol state (Squeeze, Breakout, Expansion, Compression, Neutral) reflects the Bollinger/Keltner relationship.
Macro feeds — DXY direction, VIX level, 10-year yield direction, and current divergence state.
Brand footer — version reference.
The extended macro panel (disabled by default) can be enabled in settings for a second panel showing full correlation values, ATR percentile, statistical state detail, OBV slope, volume participation score, volume divergence flag, and liquidity state.
6. Asset pair configuration
6.1 Gold/Silver ratio (GSR)
The gold/silver ratio is the primary design case for ICE. It measures how many ounces of silver are required to buy one ounce of gold. Historically the ratio has ranged between 15 and 120. It is mean-reverting over long cycles but can trend persistently for months or years.
Recommended setup:
- Asset A: OANDA:XAUUSD
- Asset B: OANDA:XAGUSD
- Asset class: Gold / Silver
The statistical extremes engine is particularly relevant here. When the ratio is near historical highs (above the 80th percentile, Z-score above 1.5), silver has historically outperformed gold significantly over the following months. When near historical lows, gold has tended to recover its premium.
The macro regime engine is also central. Acute risk-off events (2008, 2020) spike the GSR rapidly as gold outperforms. Sustained risk-on environments with rising yields and industrial demand tend to compress it.
6.2 Crypto setups
For crypto ratio analysis, stablecoin dominance (CRYPTOCAP:USDT.D) as Asset B provides a direct view of capital rotation between an asset and cash equivalents. When the ratio rises, the asset is gaining relative to stablecoins — capital is flowing in. When it falls, capital is rotating out.
Recommended setups:
- BINANCE:BTCUSDT / CRYPTOCAP:USDT.D — Bitcoin vs stablecoin dominance
- BINANCE:SOLUSDT / CRYPTOCAP:USDT.D — SOL vs stablecoin dominance
- BINANCE:ETHUSDT / CRYPTOCAP:USDT.D — ETH vs stablecoin dominance
- Asset class: Crypto for all of the above
BTC.D (Bitcoin dominance, CRYPTOCAP:BTC.D) as Asset B can be used to measure altcoin performance relative to Bitcoin specifically — useful for identifying altseason conditions.
6.3 NQ futures setups
For Nasdaq and MNQ trading, ratio analysis provides directional and regime context.
Recommended setups:
- CME_MINI:NQ1! / CME_MINI:ES1! — Nasdaq vs S&P 500. When this ratio rises, tech is outperforming the broad market. A falling ratio suggests defensive rotation or underperformance of growth. Asset class: Indices.
- CME_MINI:NQ1! / CME_MINI:RTY1! — Nasdaq vs Russell 2000. Large-cap growth vs small-cap. Risk appetite proxy. Asset class: Indices.
- CME_MINI:NQ1! / TVC:DXY — NQ relative to dollar strength. Strong inverse relationship historically. Asset class: Indices.
6.4 Precious metals and commodities
- OANDA:XAUUSD / TVC:DXY — gold relative to dollar. One of the cleanest inverse relationships in macro markets. Asset class: Commodities or Gold/Silver.
- OANDA:XAUUSD / CME_MINI:ES1! — gold vs equities. Risk-off proxy. When this ratio rises, gold is outperforming stocks. Asset class: Commodities.
- TVC:USOIL / TVC:NATGAS — oil vs natural gas relative value. Asset class: Commodities.
6.5 Forex setups
For currency pairs, use the pair itself as a ratio — Asset A as the base currency ETF or index, Asset B as the quote. Alternatively, use currency index feeds directly.
- FX:EURUSD as a direct entry (ratio of EUR to USD)
- TVC:DXY / FX:EURUSD — dollar index vs euro. Asset class: Forex.
7. Macro feeds
The three macro feeds are loaded via request.security() and must resolve on PulseWire.
Default symbols:
- DXY: TVC:DXY
- VIX: CBOE:VIX
- 10-year yield: TVC:TNX
These can be changed in the Macro Feeds settings group if alternative data sources are preferred. Each feed can be individually disabled — if all three are disabled, the macro regime, liquidity, and correlation engines return neutral (0) scores.
On lower timeframes (1m, 3m), macro feeds may have limited bar history, which can cause some engines to return neutral until sufficient data is loaded. From 15m and higher, all engines should be fully active. On very low timeframes, the statistical engines also require a minimum number of bars before the lookbacks are satisfied.
8. How to use
8.1 Reading the score
The confluence score on a -10 to +10 scale communicates direction and intensity simultaneously. It does not communicate timing.
A score of +7 with 70% confidence means six or seven engines are aligned in a bullish direction for Asset A relative to Asset B, with the weighted agreement being high. It does not mean a trade should be entered immediately — it means the current relative conditions strongly favor Asset A.
A score near 0 with low confidence means the engines are split. This is not a bearish signal — it is the absence of a clear signal. In practice, scores between -3 and +3 with confidence below 40% suggest the ratio is in a mixed or transitional regime.
8.2 Using the score with price action
ICE works on the ratio — not on the underlying price. To apply it to a trade on the underlying asset, you need to interpret the score in context.
On a BTC/USDT.D ratio chart with a score of -7, the ratio is falling — BTC is losing ground relative to stablecoin dominance. This is a macro tailwind for a bearish BTC view. It does not tell you where to enter or where to put your stop. It tells you the broader relative conditions are bearish.
Combine ICE with a price-action tool, a structure indicator, or an entry system applied to the actual trading instrument. ICE provides the regime and relative context. The entry decision remains with the user.
8.3 Divergence signals
When the ratio makes a lower low but the VW RSI makes a higher low, a bullish divergence is detected. When the ratio makes a higher high but the VW RSI makes a lower high, a bearish divergence is detected. These are mechanical detections using pivot analysis.
Divergence signals that align with the net confluence score carry more weight. A bullish divergence on a ratio that is already scoring positively on four or five engines is a stronger condition than a divergence in an otherwise neutral scoring environment. Cyan circles mark bull divergence, orange circles mark bear divergence.
8.4 Squeeze and volatility breakouts
When the volatility engine identifies a squeeze (Bollinger Bands inside the Keltner Channel), a purple square appears along the statistical mean line. This indicates compressed volatility and an elevated probability of a significant directional move.
When the squeeze releases, the volatility engine contributes its score in the direction of the breakout. Combined with trend and momentum alignment, a squeeze release can produce a rapid score shift. These moments are marked on the chart and flagged in the dashboard vol state row.
8.5 Statistical extremes
The statistical engine is most useful on the Gold/Silver ratio and other fundamentally mean-reverting pairs. When the Z-score exceeds 1.5 and the ratio is in the top 20% of its historical range, the statistical engine scores negatively — signaling that the ratio has historically tended to revert from this level.
This is not a timing signal. The ratio can remain at extremes for weeks or months. The statistical engine scores the degree of extension, not the moment of reversal. Use it alongside momentum and trend engines to assess whether the extreme is beginning to resolve.
9. Settings reference
Asset configuration
- Asset A — the primary asset. Default: XAUUSD.
- Asset B — the secondary asset. Default: XAGUSD. The ratio is Asset A divided by Asset B.
- Plot ratio line — toggles the main ratio line on the chart.
- Plot ratio EMAs — toggles the 21/50/200 EMA stack on the ratio.
- Plot std dev bands — toggles the statistical deviation bands and Bollinger Bands.
Asset class and weighting
- Asset class — selects the weighting preset. Options: Gold/Silver, Crypto, Forex, Indices, Commodities, Custom.
- Individual weight inputs — only active in Custom mode. Each engine can be weighted from 0 to 20.
Macro feeds
- Use DXY / VIX / TNX — individual toggles for each macro feed.
- DXY / VIX / TNX symbol — configurable symbols. Defaults: TVC:DXY, CBOE:VIX, TVC:TNX.
- Macro smoothing — EMA length for the macro feed trend detection. Default 20.
Relative strength engine
- ROC length — rate of change period for both assets. Default 14.
- RS EMA length — EMA applied to the ratio for trend confirmation. Default 21.
- RS Z-score lookback — lookback for normalization of the RS delta. Default 50.
Trend engine
- Fast / Slow / Macro EMA — the three EMA periods for the ratio. Defaults: 21, 50, 200.
- MTF trend filter — enables the higher timeframe confirmation gate.
- HTF timeframe — the timeframe used for the HTF EMA check. Default weekly.
Momentum engine
- RSI length — period for the VW RSI calculation. Default 14.
- Volume smoothing — SMA length for volume normalization. Default 14.
- Volume weighted RSI — enables volume weighting on the RSI. Default on.
- MACD fast / slow / signal — MACD parameters applied to the ratio. Defaults: 12, 26, 9.
Volatility engine
- BB length / BB multiplier — Bollinger Band parameters. Defaults: 20, 2.0.
- ATR length — period for ATR calculation. Default 14.
- ATR percentile lookback — historical window for ATR percentile ranking. Default 100.
- Squeeze KC length / multiplier — Keltner Channel parameters for squeeze detection. Defaults: 20, 1.5.
Statistical extremes engine
- Z-score lookback — window for Z-score calculation. Default 50.
- Percentile lookback — historical window for percentile ranking. Default 252 (approximately one year of daily data).
- Z-score extreme threshold — standard deviations from mean required to classify as extreme. Default 1.5.
Correlation engine
- Correlation window — rolling window for Pearson correlation. Default 30.
Visuals
- Bull / bear / neutral color — configurable colors for all directional elements.
- Ratio line color — color of the main ratio line.
- Show score background — colors the pane background faintly by net score direction.
- Background transparency — transparency level for the score background. Default 93.
Dashboard
- Show dashboard — master toggle. Default on.
- Position — Top Left, Top Right, Bottom Left, Bottom Right. Default Bottom Right.
- Size — Tiny, Small, Normal. Default Tiny.
- Show extended macro panel — enables a second panel with full correlation, volume, and statistical detail. Default off. Recommended for desktop only.
10. Notes
- ICE operates on a ratio of two assets. If either asset has no data on the current chart timeframe, the ratio will be unavailable and the engines will not fire. Ensure both symbols resolve correctly in PulseWire before interpreting the dashboard.
- The macro feeds (DXY, VIX, TNX) are loaded separately via request.security(). On lower timeframes, the feed data may require a few bars to warm up before producing stable readings. All engines should be fully active from the 15m timeframe and above.
- The volume used by the momentum engine is the combined average of both asset volumes. On ratio pairs where one or both assets have zero or unavailable volume (such as some index feeds), the volume-weighted RSI falls back to an unweighted RSI automatically.
- All statistical calculations (Z-score, percentile rank) require a minimum number of bars equal to the lookback period. On charts with limited history or very short timeframes, these engines may return neutral until sufficient bars are loaded.
- The correlation engine requires both assets to have non-constant price series over the correlation window. On very stable or pegged assets, correlation may be undefined and the engine returns neutral.
- ICE does not repaint. All scores and signals are based on confirmed bar data.
- The indicator is designed for ratio analysis. It can technically be used with a single asset by setting Asset B to a constant reference (such as a stablecoin or index), but it was built around the two-asset ratio concept and performs best in that context.
11. Disclaimer
This indicator is provided for educational and informational purposes only.
All outputs are based on historical price data and mathematical calculations.
Past behavior does not guarantee future results.
Trading involves substantial risk of loss.
Use at your own discretion.
Indicator

Aquila Reale Correlations v1.1🦅 AQUILA REALE CORRELATIONS v1.1
Inter-market correlation dashboard for any two assets, with multi-timeframe analysis, spread monitoring, and regime detection.
═══════════════════════════════════════════════════
📊 WHAT THIS INDICATOR DOES
═══════════════════════════════════════════════════
Calculates the Pearson correlation coefficient between two user-defined assets across 4 timeframes simultaneously (15M, 1H, 4H, Daily) and presents the result in a single-glance dashboard.
Default configuration: XAUUSD vs WTI (FP Markets), but fully configurable for any pair — Gold/DXY, BTC/SPX, EUR/USD vs DXY, equities vs bonds, etc.
The dashboard provides:
- Multi-timeframe correlation matrix with regime classification (STRONG DIRECT / WEAK DIRECT / NEUTRAL / WEAK INVERSE / STRONG INVERSE) on 15M, 1H, 4H, and Daily
- Aggregate count to identify if the correlation regime is consistent across timeframes or in transition
- Spread analysis (ratio Asset1 / Asset2) with deviation from medium-term (EMA50) and long-term (EMA200) averages, plus configurable historical thresholds
- Regime verdict: DIRECT / INVERSE / NEUTRAL / AMBIGUOUS, declared only when ≥3 of 4 timeframes are aligned
- Pre-configured alerts for regime shifts, spread extremes, and 4H correlation crossings
═══════════════════════════════════════════════════
🎯 USE CASES
═══════════════════════════════════════════════════
1. Detect regime shifts: Know when historically uncorrelated assets are temporarily moving in lockstep, or vice versa.
2. Validate macro thesis: Confirm your inter-market reading with a numeric measure across multiple timeframes.
3. Identify spread extremes: Spot when asset relationships are stretched (e.g. Gold/Oil ratio above 40 historically signals macroeconomic stress).
4. Filter trade signals: Use the regime verdict as a context filter for other strategies and indicators.
═══════════════════════════════════════════════════
⚙️ SETTINGS
═══════════════════════════════════════════════════
- Symbols: Asset 1 and Asset 2 (any PulseWire symbol)
- Correlation period: Default 50 candles (lower = reactive but noisy; higher = stable but lagging)
- Strong/Neutral thresholds: Configurable correlation cutoffs (defaults 0.5 / 0.2)
- Spread EMAs: Fast and slow EMAs applied to the asset ratio
- Historical spread thresholds: Customizable per asset pair
- Layout: 3 sections individually toggleable, 9 position options on the chart
═══════════════════════════════════════════════════
📌 IMPORTANT NOTES ON INTERPRETATION
═══════════════════════════════════════════════════
- Correlation is a STATISTICAL measure, not a directional trading signal. A strong inverse correlation does not mean "go long one and short the other" — it means the two assets are moving in opposite directions over the lookback window.
- Strong correlations across multiple timeframes suggest a stable regime; mixed readings across timeframes indicate transition or noise.
- For Gold/WTI specifically: the historical baseline correlation is weakly DIRECT (approximately +0.3 to +0.5). Strong INVERSE readings typically reflect temporary supply-side shocks affecting only one asset (e.g. geopolitical events impacting oil supply) and tend to revert over time.
- Correlation is a LAGGING indicator. A change in market regime is reflected in the rolling coefficient only after several candles. Use it for context, not for timing entries.
- The "AMBIGUOUS" verdict is informative: it tells you the correlation structure is not stable, and inter-market signals should be treated with extra caution.
═══════════════════════════════════════════════════
⚠️ WARNINGS AND DISCLAIMERS
═══════════════════════════════════════════════════
NOT FINANCIAL ADVICE
This script is for educational and informational purposes only. It does not constitute financial, investment, or trading advice. Nothing in this indicator should be interpreted as a recommendation to buy, sell, or hold any financial instrument.
NO GUARANTEE OF FUTURE BEHAVIOR
Past correlation patterns do not guarantee future behavior. Asset relationships change over time, especially in response to macroeconomic regime shifts, central bank policy changes, geopolitical events, and structural market changes.
USE AT YOUR OWN RISK
Trading financial instruments (stocks, forex, crypto, futures, CFDs, commodities) carries a high level of risk and may not be suitable for all investors. Before making any trading decision you should carefully consider your investment objectives, level of experience, and risk appetite. You may sustain a loss of some or all of your initial capital.
NOT A STANDALONE SYSTEM
This indicator does NOT generate buy/sell signals. It provides context for macro analysis. Always combine it with your own technical analysis, fundamental analysis, and proper risk management.
DO YOUR OWN RESEARCH
Always cross-check signals against multiple tools and your own market analysis. Do not rely on a single indicator for trading decisions. Past performance shown in any chart or example is not indicative of future results.
DATA LIMITATIONS
Correlation calculations rely on accurate price data from the broker/exchange feed. Results may vary across different data providers. Volume data on forex and CFD instruments comes from individual brokers and may not reflect true market activity.
NO AFFILIATION
The author is not affiliated with PulseWire, any broker, exchange, or financial institution. This script is independent and provided free of charge.
LIABILITY
The author shall not be held liable for any loss or damage, including but not limited to financial losses, arising from the use of this indicator. By using this script you accept full responsibility for your trading and investment decisions.
PAPER TRADE FIRST
Always test any indicator and the strategies built around it on a demo account or with paper trading before risking real capital.
By using this indicator you acknowledge that you have read, understood, and accepted all the above terms.
═══════════════════════════════════════════════════
💬 FEEDBACK
═══════════════════════════════════════════════════
This is v1.1, the first public release. Feedback is welcome — please leave a comment if you find bugs, have suggestions, or want to share your results with different asset pairs.
Happy charting! 🦅 Born to fly, born to dare. Indicator

Cross-Asset Correlation & Cointegration Intelligence [NikaQuant]
**Cross-Asset Correlation & Cointegration Intelligence**
Track your chart symbol against up to six comparison symbols. The script
renders **three synchronized panels** that tell you, in plain numbers:
- How coupled the basket is **right now**
- Which pairs are genuinely tradeable (and the **expected mean-reversion time**)
- How much **gross exposure** you should carry given the current regime
## What It Does
- **Intelligence Dashboard** — per-symbol grid: correlation, beta, R²,
z-score, percentile, stability, lead/lag, spread z, quality score,
hedge size, stress-vs-normal correlation delta, signal verdict
- **N×N Correlation Matrix** — full 6×6 pairwise heatmap
- **Action Center** — regime timer, flip probability, risk-budget advisor,
top-5 ranked trades, top-3 cointegrated pair setups, trade playbook
## Why It Is Original
Unlike standard correlation heatmap scripts that display a single Pearson
value per pair, this script builds a composite intelligence layer across
**three independent axes** that no retail correlation indicator combines:
**1. Asymmetric (Conditional) Correlation**
Splits history into **normal-volatility** and **stress-volatility** regimes
using an ATR-median split on the base symbol, and reports the two
correlations side by side. This exposes the *"diversification fails when
you need it"* amplification that an averaged Pearson value hides — a
documented pattern in every crisis since 1998.
**2. Cointegration + Half-Life**
For all 15 unique pairs, runs an **Engle-Granger two-step** (log-regression
then AR(1) on the residual spread) to flag which spreads are genuinely
mean-reverting. Cointegrated pairs carry an **Ornstein-Uhlenbeck half-life**
t½ = −ln(2) / ln(1 + φ) — the expected mean-reversion time in bars.
*Correlation tells you direction; cointegration tells you whether the
spread will revert.*
**3. Regime Persistence + Flip Probability**
Tracks four states (Crisis / Coupled / Mixed / Decoupled) in a **4×4 Markov
transition counter**, stores per-regime dwell times, and converts them into
flip-probability estimates for the next 10 and 30 bars. You see not just
*"we are in X"* but *"X has lasted 47 bars, historical average is 62 bars,
probability of flip in 30 bars is 55%."*
## Composite Modules
- **Crisis Clock (0–100)** — composite of average absolute correlation,
cross-sectional dispersion collapse, and tail-dependence count
- **Market Brain** — union-find clustering on positive pairwise
correlations, auto-groups symbols that move as one
- **Dispersion Trade Detector** — fires when average correlation drops
>2σ while realized volatility rises
- **Hedge Desk** — converts OLS beta into a **dollar hedge notional**
given your base position size
- **Effective-N** — correlation-adjusted diversification count (six
symbols at ρ=1.0 gives effective N = 1)
- **Risk Budget Advisor** — regime + effective-N → suggested gross
exposure percentage
- **Setup Quality Score** — composite of |corr| × R² × stability,
adjusted for regime, clock, and break
- **Action List** — scans every symbol and every pair, scores each
candidate, ranks them, surfaces the top five with type, target, score,
direction, suggested size, rationale
## Per-Symbol Metrics
- Rolling Pearson correlation across **three lookbacks** (short, medium,
long) — three-block glyph reveals timeframe divergence
- **OLS beta** from log returns, **R²** as variance explained
- **Z-score** of current correlation vs its own 200-bar distribution
- **Percentile rank** of current correlation in its own history
- **Stability** from rolling stdev of the correlation itself
- **Optimal-lag scanner** across {−5, −3, −1, 0, +1, +3, +5} offsets
- **Spread z-score** of the price ratio for pairs signaling
- **Asymmetric Δ** = ρ_stress − ρ_normal (positive = hedge fails under stress)
## How To Use It
- **Scan the Quality column first.** Anything at or above 60 with a
TRACK++ or HEDGE++ signal is a high-confidence setup.
- **Cross-check AsymΔ.** Values above +0.3 mean that "hedge" is expected
to fail under stress — avoid relying on it in a crisis.
- **Use Hedge column values** as the dollar notional to short or long
against your base position to neutralize beta.
- **Read the matrix** like a portfolio risk report. Clusters of dark-green
tiles = diversification is breaking down. Red tiles = inverse pairs.
- **In the Action Center**, start at the Risk Budget line, then work
top-down through the Action List. Cointegrated pairs marked with a
check-mark prefix show expected mean-reversion time in bars.
**Recommended timeframes:** intraday or daily charts with at least 250
bars of history across all six symbols.
**Recommended markets:** anywhere the base asset has meaningful
relationships with a benchmark basket — equity indexes vs sector ETFs,
crypto majors vs index proxies, FX vs rates and commodities.
**Avoid using when:** fewer than three symbols resolve to valid data;
during the first 250 bars after chart load; or on a symbol with gapped
or illiquid history that creates artificial correlation jumps.
## Alerts
Regime Break · Dispersion Trade Setup · New Cointegrated Pair ·
High-Quality Setup · Imminent Regime Flip · Crisis Regime Entered ·
Asymmetric Correlation Amplification · Risk Budget Reduced · Clock
Stressed/Critical · Strong Positive/Negative Correlation Crossovers
## Key Settings
- **Comparison Symbols 1–6** — the basket (autocomplete from any TV ticker)
- **Medium-Term Correlation Period** (50) — primary correlation lookback
- **Short / Long Lookbacks** (20 / 200) — timeframe-divergence glyph
- **Historical Baseline** (200) — z-score, percentile, stability, regime
dwell times, and asymmetric-correlation ATR split
- **Strong Correlation** (0.70) — threshold for strong-signal eligibility
- **Regime-Break |Z|** (2.00) — flags correlations breaking their range
- **Pairs-Trade |Spread Z|** (2.00) — pairs-trade setup threshold
- **Min R² for Trust** (0.25), **Min Stability** (0.50) — quality gates
- **Cluster Threshold** (0.60) — Market Brain grouping
- **Crisis Clock** — Stressed (60), Critical (80) thresholds
- **Base Position Size** (10,000) — drives Hedge Desk and Action sizing
- **Min Action Quality** (60) — filters the Action List
- **Risk Budget per regime** — Crisis 50%, Coupled 75%, Mixed 90%,
Decoupled 100% (all user-tunable)
- **Display** — position each of three tables independently; Compact or
Pro column density; full palette customization
## Notes
**No repainting.** All correlations, betas, and regime computations use
confirmed bars only. Regime transition counters and dwell-time arrays
update only when a bar confirms.
**Data integrity.** Six external symbol requests are made with
non-forward-looking data fetches, well within PulseWire's request limit.
**Methods.** Asymmetric correlation uses log returns with indicator
weights from an ATR-median volatility split on the base asset.
Cointegration is Engle-Granger two-step: log-regression residual, then
AR(1) test. A pair is flagged as cointegrated when the AR(1) coefficient
is sufficiently negative to indicate mean-reversion. Half-life uses the
standard Ornstein-Uhlenbeck solution t½ = −ln(2) / ln(1 + φ).
**Warm-up.** The first ~250 bars after chart load are a warm-up period.
Several metrics will display "—" until enough history accumulates.
**Originality.** All calculations, signal logic, clustering,
cointegration testing, and table rendering are original. No third-party
code is reused.
Indicator

Alvarium CCHoc indicatorem matricem coloratam viginti instrumentorum futurarum simultanee ostendit. Per coefficientem correlationis Pearsonianae super periodum definitam calculatum, relationem statisticam inter quodque par instrumentorum metitur et resultatum in tabula coloribus distincta in medio chartae depingit. Correlationes fortiter positivae viridi apparent, lectiones neutrales aurantiaco, et correlationes fortiter negativae rubro, cum undecim zonis coloris plene accommodabilibus praecisam potestatem visualem praebentibus. Viginti symbola singulatim per optiones indicatoris eliguntur, permittendo mercatori matricem ad quamcumque combinationem futurarum indicis aequitatis, mercium, monetae, reditus fixi, vel cryptocurrenciae aptare. Tum spatium temporis tum longitudo correlationis etiam mutabilia sunt, analysin per regimina diurna, hebdomadalia, vel intra diem permittentia.
This indicator displays a 20x20 correlation heatmap for up to 20 futures instruments simultaneously. Using the Pearson correlation coefficient calculated over a user-defined lookback period, it measures the statistical relationship between each pair of instruments and renders the result as a color-coded table centered on the chart. Strong positive correlations appear in green, neutral readings in orange, and strong negative correlations in red, with 11 fully customizable color bands giving granular control over the visual representation. All 20 symbols are individually selectable via the indicator settings, allowing the trader to tailor the matrix to any combination of equity index, commodity, currency, fixed income, or cryptocurrency futures. The timeframe and correlation length are also adjustable, enabling analysis across daily, weekly, or intraday regimes. Indicator

Market Correlation Matrix [NikaQuant]Market Correlation Matrix
A real-time correlation dashboard that displays Pearson correlation coefficients between the current chart symbol and up to 6 user-defined comparison symbols.
═══ FEATURES ═══
• Track correlations for up to 6 symbols simultaneously (default: BTCUSDT, GOLD, SPX, DXY, US10Y, QQQ)
• Heatmap-colored table with intuitive color coding from strong positive (green) to strong negative (red)
• Correlation change tracking — see how correlations are shifting over a configurable lookback period
• Visual strength bars showing absolute correlation magnitude at a glance
• Signal classification labels: STRONG+/-, MOD+/-, WEAK+/-, NEUTRAL
• Built-in alerts for strong positive/negative crosses (±0.7) and zero-line crosses
• Fully customizable: table position, text size, all colors, border styling
═══ HOW IT WORKS ═══
The indicator calculates Pearson correlation over a user-defined period (default: 50 bars) between the chart’s close price and each comparison symbol’s close price. It then renders a compact table showing:
1. Symbol — Ticker of the comparison asset
2. Corr — Current correlation value (-1 to +1)
3. Change — How much the correlation shifted vs N bars ago (with directional arrows)
4. Strength — Block-style visual bar representing absolute correlation
5. Signal — Classification from NEUTRAL to STRONG+/-
═══ SETTINGS ═══
Symbols: Configure up to 6 comparison symbols (leave blank to skip)
Correlation Period: Lookback length for Pearson calculation (default: 50)
Change Lookback: Compare current vs past correlation (default: 10 bars)
Display: Table position, show/hide title
Style: Full color customization for heatmap, headers, borders, and change indicators
═══ ALERTS ═══
• Strong positive correlation cross (above +0.7) per symbol
• Strong negative correlation cross (below -0.7) per symbol
• Any symbol crossing the zero line
═══ USE CASES ═══
• Monitor intermarket relationships in real time
• Identify regime changes when correlations break down or strengthen
• Confirm or filter trade setups using cross-asset correlation context
• Track USD, bonds, equities, and crypto correlations from a single chart Indicator

AG Pro Correlation Breakdown Map [AGPro Series]AG Pro Correlation Breakdown Map
Overview / What it does
AG Pro Correlation Breakdown Map is an overlay indicator designed to monitor whether a chart symbol is maintaining, weakening, breaking, or repairing its relationship with a benchmark symbol.
The default benchmark in this version is Bitcoin via BINANCE:BTCUSDT, which makes the tool especially useful for crypto traders who want to understand whether an altcoin is still moving in line with BTC or beginning to decouple from it.
This script does not attempt to answer whether correlation is simply high or low in isolation. Its purpose is more specific: it first checks whether a meaningful benchmark relationship existed, then evaluates whether that relationship is starting to deteriorate, whether the deterioration is becoming a confirmed breakdown, and whether the relationship is later stabilizing again.
The result is a regime-style map that helps users read benchmark dependency through distinct states such as coupled, strained, breaking, broken, repairing, and recoupled. This makes the script useful for contextual analysis, benchmark-relative behavior studies, and chart review workflows where users want more than a single rolling-correlation number.
Unique Edge
The main difference of this script is that it is not a generic correlation line, not a spread-trading engine, and not a simple benchmark overlay.
Its focus is the structure of relationship failure.
Instead of only plotting short-term correlation, the script combines four layers:
1. prior relationship validation,
2. short-vs-long correlation deterioration,
3. independent price behavior,
4. persistence and repair logic.
That combination is what separates a temporary wobble from a more meaningful benchmark breakdown event.
This also makes the script distinct from tools that measure correlation pressure or synchronized stress. Correlation Breakdown Map is built around the question: “A relationship existed before, but is it now failing, and if so, how cleanly?”
Methodology
The script starts by selecting a benchmark series and transforming price data into returns. Users can choose between log returns and percent returns.
A short correlation window and a long correlation window are then calculated between the chart symbol and the benchmark. The long window is used to judge whether a stable benchmark relationship has existed, while the short window is used to detect more recent deterioration.
The model then evaluates the gap between long and short correlation, along with short-correlation slope behavior. A benchmark relationship is considered more vulnerable when the short window weakens materially relative to the long window and the short-correlation slope also softens.
To avoid treating every statistical wobble as a true event, the script also checks for independent price behavior. This layer measures whether the chart symbol is beginning to move in a way that is meaningfully different from the benchmark over a configurable lookback period.
Finally, persistence and repair conditions are applied. This allows the script to separate brief instability from a more durable breakdown state, and later identify whether the relationship is beginning to normalize again.
Signals & Alerts / States
This script is primarily a state-mapping tool rather than a directional buy/sell engine.
The core states are:
Coupled
The chart symbol remains meaningfully aligned with the benchmark relationship structure.
Strained
The prior relationship still exists, but weakness is starting to appear.
Breaking
The relationship is under active deterioration and may be transitioning into a more meaningful failure.
Broken
The chart symbol is behaving as if benchmark linkage has materially weakened.
Repairing
The breakdown is no longer cleanly expanding, and the relationship may be stabilizing.
Recoupled
The benchmark relationship has improved enough to suggest that the prior structure is functioning again.
The Breakdown Score is used as a compact summary value. It is not intended to be interpreted as a trade signal on its own. It is a regime-strength readout that helps users compare the current condition of the relationship with the underlying state labels.
Key Inputs
Benchmark Symbol
Sets the comparison symbol. The default is BINANCE:BTCUSDT.
Benchmark Timeframe
Allows users to keep the benchmark on chart timeframe or compare against another timeframe.
Source
Selects Close, HLC3, or OHLC4 for the benchmark study.
Short Correlation Length / Long Correlation Length
Define the fast and slow windows used to evaluate current deterioration versus prior relationship structure.
Stable Relationship Threshold
Controls how strong the historical relationship must be before the script treats later weakness as a true breakdown candidate.
Breakdown Threshold / Repair Threshold
Control how strict the transition logic is for deterioration and recovery.
Min Long/Short Correlation Gap
Requires a meaningful difference between longer-term and shorter-term correlation before escalation.
Independent Move Threshold
Defines how much benchmark-relative price independence is required before the script treats the event as more than a statistical fluctuation.
Breakdown Confirmation Bars / Repair Confirmation Bars
Control persistence and confirmation sensitivity.
Visual Settings
Users can customize theme, visual intensity, panel font size, panel position, event visibility, trail visibility, and chart context density.
Limitations & Transparency
Correlation is a descriptive relationship metric, not a causal model.
A relationship breakdown does not automatically imply immediate continuation, reversal, trend acceleration, or trade opportunity. It only means the chart symbol is no longer behaving as consistently relative to the selected benchmark under the current settings.
Different assets, timeframes, and volatility regimes can produce different correlation behavior. A benchmark relationship that looks stable on one timeframe may be much less stable on another.
Short lookbacks can react faster but may create more noise. Longer lookbacks can be more stable but slower to react.
This script should be interpreted in the context of market structure, volatility, liquidity, and the chosen benchmark. It is a framework for reading relationship quality, not a guarantee engine.
Risk Disclosure
This indicator is for analytical and educational use.
It does not provide financial advice, does not predict future price direction, and should not be used in isolation for trading decisions. Users should perform their own analysis, validate settings on the markets they follow, and apply appropriate risk management. Indicator

Psych Level Mirror - Futures <-> CashPsych Level Mirror — Futures ↔ Cash
See the hidden levels that move your market.
Futures and cash/CFD instruments trade at different prices due to the spread (carry, funding, roll). A round number on the cash index — like NAS100 20,000 or SPX500 5,600 — doesn't land on a round number on the futures chart. But cash traders are still reacting to those levels. This indicator makes them visible.
WHAT IT DOES
Psych Level Mirror draws two layers of psychological price levels on your chart:
Native psych levels — The round numbers of whatever you're charting (e.g. ES 5650, 5700). These are drawn as full zones with support/resistance state tracking: green when acting as support, red when resistance. Zones flip color when price breaks through and retests — exactly how institutional levels behave in practice.
Mirrored companion levels — The round numbers from the other side of the pair, projected onto your chart using the live spread. On an ES chart, you'll see where SPX500 cash round numbers (5,600, 5,650, 5,700) actually sit on the futures price scale. These are marked with a dashed center line and dotted green/red borders so they're visually distinct from your native levels.
WHY THIS MATTERS
Large portions of the market trade the cash index (CFDs, spot, options on SPX). When NAS100 hits 20,000 or SPX500 hits 5,600, that triggers activity from cash traders — but on your NQ or ES futures chart, that level shows up at an odd number like 20,034 or 5,628. Without this indicator, you'd never know why price stalled or reversed at a seemingly random level.
FEATURES
Auto-detection — Drop it on any supported chart and it identifies the correct pair. Works on NQ, MNQ, ES, MES, YM, MYM, RTY, M2K, GC, MGC, and their cash/CFD counterparts (NAS100, SPX500, US30, US2000, XAUUSD).
Live spread calculation — The futures-cash spread shifts throughout the session. Mirror levels update automatically as the spread moves.
State tracking on all levels — Both native and mirrored zones track whether price is above (support/green) or below (resistance/red), and change color on confirmed breaks and retests.
Major & minor levels — Major round numbers (e.g. every 1000 on NQ, every 100 on ES) and minor levels (half-steps) are drawn separately with different visual weight.
Auto-scaling — Level intervals adjust automatically based on the instrument's price. Works correctly on everything from Russell 2000 (~2,100) to NQ (~20,000) to Gold (~3,000).
Manual override — Set a fixed spread offset or force a specific pair via the dropdown if needed.
Info table — Shows detection mode, chart side (futures/cash), companion symbol, live spread, and level intervals at a glance.
HOW TO READ IT
Colored zone (green/red box) = Native psych level — your instrument's own round numbers
Dashed center line through zone = Exact round number of the native level
Dashed/dotted colored line with tag = Mirrored companion level projected onto your chart
Green dotted border (mirror) = Top of the mirrored zone
Red dotted border (mirror) = Bottom of the mirrored zone
Dark green tag box = Companion level acting as support (price above)
Dark red tag box = Companion level acting as resistance (price below)
SUPPORTED PAIRS
NQ1! / MNQ1! ↔ NAS100
ES1! / MES1! ↔ SPX500
YM1! / MYM1! ↔ US30
RTY1! / M2K1! ↔ US2000
GC1! / MGC1! ↔ XAUUSD
Custom ↔ Custom
SETTINGS
Instrument Pair — Auto (recommended), named preset, or Custom with your own symbols
Native Psych Levels — Toggle major/minor, adjust intervals and zone widths, set number of levels above/below
Mirrored Levels — Toggle on/off, major-only option
Spread — Auto (live) or manual fixed offset
NOTES
The spread between futures and cash is not constant. It narrows into expiry and fluctuates with funding/carry. Auto mode handles this — levels shift slightly throughout the session, which is accurate to reality.
Best used on intraday timeframes (1m–15m) where the spread offset matters most. On daily+ charts the spread becomes negligible relative to the level intervals.
This indicator is an overlay — it works alongside your existing setup without conflict.
ORIGIN
This indicator is built from concepts taught by Student Alpha (Shawn) , who describes the relationship between correlated instruments with a simple but powerful idea: "The tail wags the dog."
The cash index and the futures contract are tethered together, but they don't move tick-for-tick in lockstep. When the cash market reacts to a psychological round number, that reaction ripples into the futures — and vice versa. The "tail" (the correlated instrument you're not charting) wags the "dog" (the one you're trading). Understanding where those hidden levels sit on your chart gives you an edge that most traders never see.
Psych Level Mirror was built to make that concept visual and automatic — no more manual math, no more guessing where the cash 20,000 lands on your NQ chart. Indicator

AG Pro Correlation Stress Meter [AGPro Series]AG Pro Correlation Stress Meter
Overview / What it does
AG Pro Correlation Stress Meter is an overlay indicator designed to estimate when an instrument is becoming increasingly synchronized with a selected benchmark and whether that relationship is developing into a higher-stress market condition.
Instead of treating correlation as a standalone number, this script converts multiple correlation-related components into a structured stress framework. The goal is not to predict direction. The goal is to help the user judge whether market behavior is becoming more tightly linked, more fragile, and potentially less independent than usual.
The script combines smoothed rolling correlation, short-term correlation acceleration, persistence of elevated correlation, and a simple fragility layer based on price behavior versus an internal backbone EMA. The result is a normalized stress score and a state model that classifies conditions as Stable, Building, Pressured, Stressed, or Critical.
Because the script is plotted directly on price, it is intended to function as a context layer. It can be used to evaluate whether a chart is trading in a relatively independent manner or whether it is increasingly behaving like a benchmark-driven instrument.
Unique Edge
The main difference in this script is that it does not treat correlation as a single readout. It treats correlation as a pressure structure.
Many correlation tools stop at the raw coefficient. This script goes further by asking four separate questions:
1. How strong is the current relationship?
2. Is that relationship tightening or loosening?
3. Has elevated correlation persisted for long enough to matter?
4. Is price behavior becoming fragile at the same time?
That combination is what makes this script different from many standard overlays, matrix-style correlation displays, or simple coefficient dashboards.
It is also different from several other AG Pro scripts in the catalog. Some AG Pro tools focus on trend quality, pullback quality, squeeze behavior, reclaim structure, momentum pressure, or reaction mapping around known reference levels. This script does not focus on any of those themes. Its job is narrower and more diagnostic: it measures how much benchmark-linked stress is building inside the chart. In other words, it is less about trend or structure classification, and more about whether the instrument is becoming increasingly dependent on external benchmark behavior.
Methodology
The script starts with log returns for both the chart symbol and the selected benchmark symbol. A rolling correlation is then calculated over the chosen correlation window and smoothed to reduce noise.
From there, the model evaluates four components:
1. Correlation strength
This is the normalized level of the smoothed rolling correlation. Higher positive correlation generally contributes more to the final stress score.
2. Correlation velocity
This measures how much the smoothed correlation has changed over a short lookback. A rising relationship can matter even when the absolute coefficient is not yet extreme.
3. Correlation persistence
This evaluates how consistently correlation has remained above a user-defined threshold over a recent window. Short spikes and sustained linkage should not be treated as the same condition, so persistence is included as a separate layer.
4. Fragility layer
This component looks at whether price is trading below the internal backbone EMA, whether short-term rate of change is weak, how stretched price is relative to the EMA, and whether ATR percentage is elevated. The purpose of this layer is not to predict reversals. Its purpose is to distinguish a calm, orderly correlation regime from a more fragile one.
These components are weighted into a composite stress score, then mapped into five states:
- Stable
- Building
- Pressured
- Stressed
- Critical
The script also provides a backdrop layer, optional event labels, a backbone EMA for context, and a compact information panel.
Signals & Alerts
This script is primarily a state-classification and context tool. It is not a direct entry system and should not be interpreted as a standalone buy or sell engine.
Available alert logic includes:
- Stress Building
- Stress Pressured
- Stress Stressed
- Stress Critical
- Stress Cooling
These alerts are designed to notify the user when the internal state model changes. They can be used to monitor regime transitions, benchmark sensitivity changes, or shifts in how tightly a symbol is tracking the selected benchmark.
Practical interpretation examples:
- Building may suggest that correlation-linked influence is starting to develop.
- Pressured may suggest that the relationship is no longer background noise and is becoming relevant to decision-making.
- Stressed may suggest that the symbol is trading with notable benchmark dependency.
- Critical may suggest that benchmark-linked pressure is unusually elevated relative to the script’s internal framework.
- Cooling may suggest that the prior stress state is easing.
These are contextual interpretations, not trade instructions.
Key Inputs
Benchmark Symbol
Selects the reference instrument used for the correlation calculation.
Benchmark Timeframe
Allows the benchmark series to follow the chart timeframe or use a different one.
Correlation Length
Defines the rolling window used for correlation.
Correlation Smoothing
Smooths the raw correlation series.
Velocity Lookback
Controls how quickly changes in correlation are measured.
Persistence Window
Defines how far back the script checks for sustained elevated correlation.
Persistence Threshold
Defines what the script considers “elevated” for persistence purposes.
Fragility EMA Length
Controls the internal backbone EMA used in the fragility layer and optional overlay line.
Fragility ROC Length
Defines the short-term price change measurement inside the fragility model.
ATR Length
Controls the volatility input used in the fragility model.
Label Trigger State
Sets the minimum state required before labels can appear.
Minimum Bars Between Labels
Reduces label clustering.
Background From State
Sets the minimum state required before the stress backdrop is shown.
Label ATR Offset
Controls how far event labels are plotted from price.
Panel / Visual Inputs
Allow control over panel visibility, panel position, panel theme, panel font size, label size, backdrop visibility, backbone visibility, and backbone label visibility.
Limitations & Transparency
This script is a contextual model, not a statement of causality. A high reading does not prove that the benchmark is causing the move. It only indicates that the symbol is trading in a way that is more tightly aligned with the selected benchmark according to the model inputs.
Correlation is also regime-dependent. A symbol may appear highly linked during one period and much less linked during another. Different benchmarks, timeframes, and windows can produce different readings.
The fragility layer is intentionally simple. It is included to refine the stress framework, not to replace full market structure analysis. Users who rely on this script should still examine trend structure, volatility context, liquidity conditions, and the behavior of the benchmark itself.
This script also does not claim to identify tops, bottoms, crashes, breakouts, or future returns. It measures an internal definition of correlation-linked stress and presents that information visually.
Risk Disclosure
This indicator is for analytical and educational use. It does not provide financial advice, investment advice, or guaranteed outcomes.
No indicator can remove market risk. Correlation regimes can change quickly, benchmark relationships can decouple without warning, and any model based on historical data can fail in live conditions.
This tool should be used as one part of a broader chart review process, not as a substitute for independent judgment, risk management, or position sizing discipline. Indicator

Indicator

Indicator

SMT Divergence [UAlgo]SMT Divergence is a comparative market structure indicator designed to detect disagreement between a primary instrument and a second reference symbol. The script looks for situations where the main chart prints a stronger structural move, while the comparison symbol fails to confirm that move. This kind of disagreement is often referred to as SMT divergence and is commonly used to identify potential weakness in continuation or hidden strength into reversal conditions.
The script works by tracking confirmed swing highs and swing lows on both instruments. Once enough pivots are stored, it compares the latest structural movement in the primary chart against the latest comparable movement in the reference symbol. If the primary chart makes a lower low while the comparison symbol makes a higher low, the script identifies bullish SMT divergence. If the primary chart makes a higher high while the comparison symbol makes a lower high, the script identifies bearish SMT divergence.
What makes this script especially practical is its flexible comparison logic. It can work in a time matched mode, where the comparison swings must occur near the same bars as the primary swings, or in an independent mode, where the script simply uses the most recent valid swings from both instruments. It also supports inverse correlation logic, allowing the user to compare instruments that normally move in opposite directions.
The indicator can then display SMT labels directly on the main chart, draw structure lines between the relevant swing points, show a live information table, and optionally render the comparison symbol as candles inside the oscillator pane. This creates a complete workflow for divergence monitoring instead of only printing occasional labels.
In practical use, SMT Divergence can help traders identify moments when the primary symbol appears to be making an aggressive structural move without proper confirmation from a related market. These moments can provide useful context for potential exhaustion, liquidity events, or directional imbalance between correlated instruments.
🔹 Features
🔸 Dual Symbol Market Structure Comparison
The script compares the active chart against a second user selected symbol. Both instruments are processed using the same pivot logic, which creates a consistent framework for structural comparison.
🔸 Bullish SMT Detection
Bullish SMT is identified when the primary chart makes a lower low while the comparison symbol makes a higher low. This can suggest hidden relative strength in the comparison instrument or possible exhaustion in the primary one.
🔸 Bearish SMT Detection
Bearish SMT is identified when the primary chart makes a higher high while the comparison symbol makes a lower high. This can suggest weakening confirmation and possible vulnerability in the primary move.
🔸 Positive and Inverse Correlation Modes
The script supports both normal and inverse correlation logic. In normal mode, lows are compared with lows and highs are compared with highs. In inverse mode, lows are compared with highs and highs are compared with lows. This makes the tool flexible enough for both positively correlated and negatively correlated markets.
🔸 Time Matched and Independent Swing Modes
The user can choose whether swing comparison should require approximate time alignment or simply use the most recent valid swings from each symbol. This allows the script to be either stricter or more flexible depending on the relationship between the two markets.
🔸 Pivot Strength Control
Swing highs and lows are built from confirmed pivots using user defined left and right bar settings. This allows the user to control how sensitive or how selective the swing structure should be.
🔸 Minimum Price Difference Filter
A minimum price difference percentage can be required before a divergence is accepted. This helps avoid labeling very small and potentially insignificant swing differences.
🔸 Max Swing Memory Control
The script stores a limited number of recent swings for both the primary and comparison symbol. This keeps the logic focused on relevant structure and prevents unnecessary buildup of stale pivots.
🔸 On Chart Labels and Lines
Detected SMT events can be labeled directly on the main chart. The script can also draw structure lines across the primary and comparison swing legs used in the divergence.
🔸 Live Info Table
An information table can display the active comparison symbol, correlation mode, divergence count, and the latest signal direction. This makes the script easier to monitor in real time.
🔸 Optional Compare Candle Panel
The comparison symbol can be plotted as candles in the indicator pane. This allows the user to visually inspect whether the second instrument is confirming or rejecting the move seen in the primary chart.
🔸 Alert Support
The script includes separate alerts for bullish SMT, bearish SMT, and any SMT event.
🔹 Calculations
1) Defining Swing and Divergence Objects
type SwingPoint
int barIdx
int barTm
float price
bool isHigh
type SMTDivergence
int barIdx
int barTm
bool isBullish
float primaryPrice
float comparePrice
string primarySymbol
string compareSymbol
label lbl
line ln1
line ln2
type SymbolData
float h
float l
float c
This is the structural base of the whole script.
A SwingPoint stores one confirmed pivot with its bar index, time, price, and whether it is a high or a low.
An SMTDivergence object stores the final event once a divergence is confirmed. It keeps the primary and comparison prices, the involved symbols, the direction, and the visual references used for labels and lines.
A SymbolData object is used as a clean container for each symbol’s high, low, and close series.
So before any logic runs, the script already has a full structure for swing storage and divergence output.
2) Requesting the Comparison Symbol Data
= request.security(compareSymbolInput, timeframe.period, , lookahead = barmerge.lookahead_off)
SymbolData primaryData = SymbolData.new(high, low, close)
SymbolData compareData = SymbolData.new(compareHigh, compareLow, compareClose)
This block loads the second symbol on the same chart timeframe.
The primary chart uses the current symbol’s own high, low, and close. The comparison symbol is requested with request.security , and its values are placed into a matching data structure.
This means both symbols are analyzed on an equal timeframe basis, which is essential for consistent swing comparison.
3) Finding Pivot Highs and Pivot Lows on Both Symbols
float primaryPivotHigh = ta.pivothigh(primaryData.h, pivotLeftBars, pivotRightBars)
float primaryPivotLow = ta.pivotlow(primaryData.l, pivotLeftBars, pivotRightBars)
float comparePivotHigh = ta.pivothigh(compareData.h, pivotLeftBars, pivotRightBars)
float comparePivotLow = ta.pivotlow(compareData.l, pivotLeftBars, pivotRightBars)
This is the swing discovery engine.
The script uses the same pivot settings for both instruments. A pivot high or pivot low is only confirmed after the required number of bars has passed on each side.
This means the divergence engine is built from confirmed structure, not from temporary highs and lows that can disappear before confirmation.
4) Storing Swings in Memory
method addSwing(array swings, SwingPoint newSwing) =>
swings.push(newSwing)
if swings.size() > maxSwingsToStore
swings.shift()
swings
if not na(primaryPivotHigh)
primarySwings.addSwing(SwingPoint.new(bar_index - pivotOffset, time , primaryPivotHigh, true))
if not na(primaryPivotLow)
primarySwings.addSwing(SwingPoint.new(bar_index - pivotOffset, time , primaryPivotLow, false))
if not na(comparePivotHigh)
compareSwings.addSwing(SwingPoint.new(bar_index - pivotOffset, time , comparePivotHigh, true))
if not na(comparePivotLow)
compareSwings.addSwing(SwingPoint.new(bar_index - pivotOffset, time , comparePivotLow, false))
Once a pivot is confirmed, it is pushed into the appropriate swing array.
The true pivot bar is pivotRightBars bars in the past, so the script subtracts that offset from the current bar index and time. Each array only keeps the latest user defined number of swings.
So the script maintains a rolling structural memory for both markets without allowing the arrays to grow indefinitely.
5) Retrieving the Latest and Previous Swings
method getLastSwing(array swings, bool isHigh) =>
SwingPoint result = na
if swings.size() > 0
for i = swings.size() - 1 to 0
SwingPoint sw = swings.get(i)
if sw.isHigh == isHigh
result := sw
break
result
method getPreviousSwing(array swings, bool isHigh) =>
SwingPoint result = na
int count = 0
if swings.size() > 1
for i = swings.size() - 1 to 0
SwingPoint sw = swings.get(i)
if sw.isHigh == isHigh
count += 1
if count == 2
result := sw
break
result
These two helper methods are used to build the swing pairs required for divergence detection.
getLastSwing returns the most recent high or low swing of the requested type.
getPreviousSwing returns the swing before that.
This is important because SMT logic always compares two consecutive structure points on the primary side and two corresponding structure points on the comparison side.
6) Enforcing Maximum Distance Between Swing Points
method isWithinRange(SwingPoint sw1, SwingPoint sw2) =>
not na(sw1) and not na(sw2) and math.abs(sw1.barIdx - sw2.barIdx) <= maxBarsLookback
This method makes sure the two swings being compared are not too far apart in time.
If the latest and previous swing are separated by more than the allowed bar distance, the setup is ignored.
This helps keep the analysis focused on fresh and structurally related moves rather than comparing swings that are too old or too distant to be meaningful together.
7) Time Matched Swing Search
method findSwingNearBar(array swings, int targetBar, bool isHigh, int toleranceBars) =>
SwingPoint result = na
int minDiff = 999999
if swings.size() > 0
for i = swings.size() - 1 to 0
SwingPoint sw = swings.get(i)
if sw.isHigh == isHigh
int diff = math.abs(sw.barIdx - targetBar)
if diff <= toleranceBars and diff < minDiff
minDiff := diff
result := sw
result
This method is used only when the user selects time matched mode.
The idea is to find a comparison symbol swing that occurred near the same bar as the primary swing. The script searches for the nearest swing of the correct type inside the allowed tolerance window.
So time matched mode is stricter because it requires approximate timing alignment between the two instruments.
8) Minimum Price Difference Filter
method pctDiff(float price1, float price2) =>
math.abs(price1 - price2) / ((price1 + price2) / 2) * 100
This function measures the percentage difference between two prices.
The result is later used as an optional minimum swing magnitude filter. If the primary chart’s new swing differs only slightly from its previous one, the script can ignore that divergence candidate.
So the minimum difference filter helps reduce weaker signals that are based on very small structure changes.
9) Bullish SMT Detection Logic
if not na(primaryPivotLow) and not na(primaryLastLow) and not na(primaryPrevLow)
SwingPoint usedCompareLast = na
SwingPoint usedComparePrev = na
bool targetSwingHigh = inverseCorrelation ? true : false
if useTimeMatching
usedCompareLast := compareSwings.findSwingNearBar(primaryLastLow.barIdx, targetSwingHigh, timeToleranceBars)
usedComparePrev := compareSwings.findSwingNearBar(primaryPrevLow.barIdx, targetSwingHigh, timeToleranceBars)
else
usedCompareLast := compareSwings.getLastSwing(targetSwingHigh)
usedComparePrev := compareSwings.getPreviousSwing(targetSwingHigh)
This is the setup stage for bullish SMT.
The script only begins the test when a new primary pivot low has just been confirmed and both the latest and previous primary lows are available.
Then it decides what kind of comparison swings are needed.
In normal correlation mode, bullish SMT compares primary lows to comparison lows.
In inverse correlation mode, bullish SMT compares primary lows to comparison highs.
Then the script either uses time matched lookup or independent swing retrieval depending on the chosen mode.
So before the bullish condition itself is tested, the script first builds the proper comparison pair according to both timing mode and correlation mode.
10) Bullish SMT Confirmation Conditions
if not na(usedCompareLast) and not na(usedComparePrev)
if primaryLastLow.isWithinRange(primaryPrevLow)
bool primaryLL = primaryLastLow.price < primaryPrevLow.price
bool compareHL = inverseCorrelation ? (usedCompareLast.price < usedComparePrev.price) : (usedCompareLast.price > usedComparePrev.price)
bool meetsMinDiff = minPriceDiff == 0.0 or (primaryLastLow.price.pctDiff(primaryPrevLow.price) >= minPriceDiff)
Bullish SMT is confirmed when three things happen.
First, the primary chart must make a lower low:
primaryLastLow.price < primaryPrevLow.price
Second, the comparison symbol must fail to confirm that weakness. In normal correlation mode this means the comparison symbol makes a higher low. In inverse correlation mode the logic is adjusted accordingly because the relationship is reversed.
Third, if the minimum difference filter is enabled, the primary low must differ enough from the previous low.
So bullish SMT is essentially a lower low in the main chart that is not properly confirmed by the comparison market.
11) Creating the Bullish Divergence Event
if primaryLL and compareHL and meetsMinDiff and primaryLastLow.barIdx != lastBullPrimaryIdx
bullishSMT := true
lastBullPrimaryIdx := primaryLastLow.barIdx
SMTDivergence newDiv = SMTDivergence.new(primaryLastLow.barIdx, primaryLastLow.barTm, true, primaryLastLow.price, usedCompareLast.price, syminfo.tickerid, compareSymbolInput, na, na, na)
newDiv.drawVisuals(primaryPrevLow.barTm, primaryPrevLow.price, usedCompareLast.barTm, usedComparePrev.barTm, usedComparePrev.price)
divergences.push(newDiv)
Once the bullish conditions are met, the script creates a new SMT divergence object.
It stores the primary swing information, the comparison swing information, the involved symbols, and the bullish direction. Then it calls the visual drawing method and pushes the divergence into the history array.
The duplicate protection check against lastBullPrimaryIdx prevents the same primary swing from being labeled repeatedly.
12) Bearish SMT Detection Logic
if not na(primaryPivotHigh) and not na(primaryLastHigh) and not na(primaryPrevHigh)
SwingPoint usedCompareLastH = na
SwingPoint usedComparePrevH = na
bool targetSwingHigh = inverseCorrelation ? false : true
if useTimeMatching
usedCompareLastH := compareSwings.findSwingNearBar(primaryLastHigh.barIdx, targetSwingHigh, timeToleranceBars)
usedComparePrevH := compareSwings.findSwingNearBar(primaryPrevHigh.barIdx, targetSwingHigh, timeToleranceBars)
else
usedCompareLastH := compareSwings.getLastSwing(targetSwingHigh)
usedComparePrevH := compareSwings.getPreviousSwing(targetSwingHigh)
This is the mirror setup stage for bearish SMT.
It begins only when a new primary pivot high has been confirmed and the required primary highs exist. Then it selects the proper comparison swing type according to the chosen correlation mode.
In normal correlation mode, bearish SMT compares highs with highs.
In inverse correlation mode, bearish SMT compares highs with lows.
So this block prepares the correct structural pair for the bearish test.
13) Bearish SMT Confirmation Conditions
if not na(usedCompareLastH) and not na(usedComparePrevH)
if primaryLastHigh.isWithinRange(primaryPrevHigh)
bool primaryHH = primaryLastHigh.price > primaryPrevHigh.price
bool compareLH = inverseCorrelation ? (usedCompareLastH.price > usedComparePrevH.price) : (usedCompareLastH.price < usedComparePrevH.price)
bool meetsMinDiff = minPriceDiff == 0.0 or (primaryLastHigh.price.pctDiff(primaryPrevHigh.price) >= minPriceDiff)
Bearish SMT is confirmed when the primary chart makes a higher high while the comparison symbol fails to confirm that strength.
In normal correlation mode, the comparison symbol must make a lower high. In inverse correlation mode the logic is adjusted to preserve the intended structural disagreement.
The minimum difference filter is applied here as well.
So bearish SMT is the opposite structure of bullish SMT, focused on unconfirmed upside continuation.
14) Creating the Bearish Divergence Event
if primaryHH and compareLH and meetsMinDiff and primaryLastHigh.barIdx != lastBearPrimaryIdx
bearishSMT := true
lastBearPrimaryIdx := primaryLastHigh.barIdx
SMTDivergence newDiv = SMTDivergence.new(primaryLastHigh.barIdx, primaryLastHigh.barTm, false, primaryLastHigh.price, usedCompareLastH.price, syminfo.tickerid, compareSymbolInput, na, na, na)
newDiv.drawVisuals(primaryPrevHigh.barTm, primaryPrevHigh.price, usedCompareLastH.barTm, usedComparePrevH.barTm, usedComparePrevH.price)
divergences.push(newDiv)
Once the bearish rules are satisfied, the script creates a bearish SMT divergence object, draws its visuals, and stores it in the divergence history array.
The duplicate protection check against lastBearPrimaryIdx prevents repeated labeling of the same primary high.
15) Drawing Labels and Lines
method drawVisuals(SMTDivergence div, int prevTime, float prevPrice, int compareTime, int prevCompareTime, float prevComparePrice) =>
if showLabels
string labelText = div.isBullish ? "🔺 SMT" : "🔻 SMT"
string tooltipText = str.format("{0} SMT Divergence {1} vs {2} Price: {3}", div.isBullish ? "Bullish" : "Bearish", div.primarySymbol, div.compareSymbol, str.tostring(div.primaryPrice, format.mintick))
color labelColor = div.isBullish ? bullishColor : bearishColor
div.lbl := label.new(div.barIdx, div.primaryPrice, labelText, xloc = xloc.bar_index, yloc = div.isBullish ? yloc.belowbar : yloc.abovebar, color = labelColor, textcolor = color.white, style = div.isBullish ? label.style_label_up : label.style_label_down, tooltip = tooltipText, size = size.small, force_overlay = true)
if showLines and not na(prevTime) and not na(prevPrice)
color lineColor = div.isBullish ? bullishColor : bearishColor
div.ln1 := line.new(prevTime, prevPrice, div.barTm, div.primaryPrice, xloc = xloc.bar_time, color = lineColor, width = 2, style = line.style_solid, force_overlay = true)
if not na(prevComparePrice) and not na(prevCompareTime) and not na(compareTime)
div.ln2 := line.new(prevCompareTime, prevComparePrice, compareTime, div.comparePrice, xloc = xloc.bar_time, color = lineColor, width = 2, style = line.style_solid)
This method creates the chart visuals for each divergence.
The label is placed directly at the primary swing location, above price for bearish SMT and below price for bullish SMT.
If line drawing is enabled, the script also draws one line across the primary chart’s two relevant swing points and another line across the comparison symbol’s swing leg.
So the user can see both the signal marker and the underlying structural disagreement that produced it.
16) Limiting Divergence History
if divergences.size() > maxDivergencesToShow
SMTDivergence rmDiv = divergences.shift()
rmDiv.cleanup()
This block controls object history.
If the stored divergence count exceeds the chosen limit, the oldest divergence is removed from the array and all its visuals are deleted.
This keeps the chart clean and prevents unlimited buildup of old labels and lines.
17) Building the Information Table
var table infoTable = table.new(position.top_right, 2, 6, bgcolor = color.new(#2222b3, 10), border_width = 1, border_color = color.new(color.white, 80), frame_width = 2, frame_color = color.new(color.white, 70))
if showTable and barstate.islast
table.cell(infoTable, 0, 1, "Primary", text_color = color.gray, text_size = size.tiny)
table.cell(infoTable, 1, 1, syminfo.tickerid, text_color = color.white, text_size = size.tiny)
table.cell(infoTable, 0, 2, "Compare", text_color = color.gray, text_size = size.tiny)
table.cell(infoTable, 1, 2, compareSymbolInput, text_color = color.white, text_size = size.tiny)
table.cell(infoTable, 0, 3, "Correlation", text_color = color.gray, text_size = size.tiny)
table.cell(infoTable, 1, 3, inverseCorrelation ? "Inverse" : "Positive", text_color = inverseCorrelation ? color.orange : color.aqua, text_size = size.tiny)
table.cell(infoTable, 0, 4, "Divergences", text_color = color.gray, text_size = size.tiny)
table.cell(infoTable, 1, 4, str.tostring(divergences.size()), text_color = color.white, text_size = size.tiny)
This table provides a compact real time summary.
It shows:
the primary symbol,
the comparison symbol,
the current correlation mode,
the number of stored divergences,
and the most recent signal direction.
So the table functions as a monitoring dashboard rather than only a decorative element.
18) Determining the Last Signal for the Table
string lastSignal = "None"
color signalColor = color.gray
if divergences.size() > 0
SMTDivergence lastDiv = divergences.get(divergences.size() - 1)
lastSignal := lastDiv.isBullish ? "🔺 Bullish" : "🔻 Bearish"
signalColor := lastDiv.isBullish ? bullishColor : bearishColor
This block determines what the table should show as the latest signal.
If at least one divergence has been stored, the script reads the newest one and displays whether it was bullish or bearish, along with the corresponding color.
So the info table always reflects the current state of the divergence history.
19) Alert Conditions
alertcondition(bullishSMT, title = "Bullish SMT Divergence", message = "🔺 Bullish SMT Divergence detected on {{ticker}}! Primary made Lower Low while {{interval}} comparison made Higher Low.")
alertcondition(bearishSMT, title = "Bearish SMT Divergence", message = "🔻 Bearish SMT Divergence detected on {{ticker}}! Primary made Higher High while {{interval}} comparison made Lower High.")
alertcondition(bullishSMT or bearishSMT, title = "Any SMT Divergence", message = "SMT Divergence detected on {{ticker}}!")
The script provides three alert types.
One triggers only on bullish SMT.
One triggers only on bearish SMT.
One triggers on any SMT event.
This makes the indicator useful both for visual study and for live event monitoring.
20) Compare Candle Panel
color compareBodyColor = compareClose >= compareOpen ? color.new(#00E676, 0) : color.new(#FF5252, 0)
color compareWickColor = compareClose >= compareOpen ? color.new(#00E676, 30) : color.new(#FF5252, 30)
color compareBorderColor = compareClose >= compareOpen ? color.new(#00C853, 0) : color.new(#D50000, 0)
plotcandle(compareOpen, compareHigh, compareLow, compareClose, title = "Compare Symbol Candles", color = compareBodyColor, wickcolor = compareWickColor, bordercolor = compareBorderColor, display = showCandlePanel ? display.all : display.none)
This block renders the comparison symbol as candles inside the indicator pane.
The candle colors are determined by the comparison symbol’s own open and close direction. If the user enables the candle panel, this gives a quick visual reference for how the second instrument is behaving without needing to open a separate chart.
So the user can study SMT signals and the comparison structure in the same pane. Indicator

Sector Correlation Matrix [LuxAlgo]The Sector Correlation Matrix indicator provides a quantitative measure of the statistical relationship between a selected asset and a benchmark to help traders identify market synchronization and relative strength.
🔶 USAGE
This tool is particularly useful for relative strength analysis. For example, if a stock is "Decoupled" while the benchmark is crashing, it may indicate idiosyncratic strength. Conversely, traders can use "Strong Positive" states to confirm that a price move is part of a broader market trend rather than an isolated event.
The indicator categorizes market relationships into five distinct states based on the coefficient value:
Strong Positive (> 0.7): High degree of synchronization; the assets move together closely. Moderate Positive (> 0.3): General tendency to move in the same direction. Decoupled / Neutral (-0.3 to 0.3): No significant linear relationship; the asset is moving independently. Moderate Negative (< -0.3): General tendency to move in opposite directions. Strong Negative (< -0.7): High degree of inverse synchronization.
🔶 DETAILS
The script utilizes the Pearson Correlation Coefficient to calculate the rolling correlation between the current chart's closing price and a user-defined benchmark (such as SPY, QQQ, or BTC). This statistical method measures the linear correlation between two sets of data, resulting in a value between -1 (perfect inverse correlation) and 1 (perfect positive correlation).
The visual output includes a dedicated pane with a correlation oscillator and an on-screen dashboard that provides real-time metrics, allowing for a quick assessment of the current market state without manually comparing multiple charts.
// Core Calculation Logic
correlationValue = ta.correlation(close, benchClose, corrLenInput)
🔶 SETTINGS
🔹 Logic Settings
Benchmark Asset: The ticker symbol to compare the current asset against (e.g., SPY, QQQ, BTCUSDT). Correlation Length: The lookback period used to calculate the Pearson Correlation Coefficient.
🔹 Dashboard
Show Dashboard: Enable or disable the on-screen information table. Position: Select the dashboard location (Top Right, Bottom Right, or Bottom Left). Size: Adjust the size of the dashboard text and cells (Tiny to Huge). Indicator

Correlated Sine Oscillator [LuxAlgo]The Correlated Sine Oscillator indicator identifies and isolates cyclical components within price action to generate a normalized, phase-aligned sinusoid that fluctuates between -1 and 1.
🔶 USAGE
The Correlated Sine Oscillator is designed to help traders visualize the underlying rhythm of the market by projecting price data onto a mathematical sine wave. Unlike standard momentum oscillators, this tool uses quadrature components to determine the current "phase" of the market cycle, allowing the oscillator to stay synced with price swings.
🔹 Identifying Cycle Direction
The oscillator fluctuates within a fixed range of -1 to 1, centered around a zero line. Signals are generated based on the crossing of this midpoint to identify shifts in the dominant cycle.
Bullish Signals: When the oscillator crosses above the zero line, a bullish triangle (▲) appears below the price bar, signaling the start of a rising phase in the cycle. Bearish Signals: When the oscillator crosses below the zero line, a bearish triangle (▼) appears above the price bar, signaling the start of a falling phase in the cycle. Cycle Extremes: While signals occur at the midline, values approaching 1 or -1 represent the peak and trough of the identified cycle, respectively.
🔹 The Phase Multiplier
The Phase Multiplier setting is a unique feature that controls how responsively the oscillator adapts to changes in price direction. Since the indicator uses an average of the real and imaginary components to find the phase, increasing this multiplier will result in a smoother, more stable oscillator that is less prone to noise but slightly more lagging. Lowering the multiplier makes the oscillator react faster to price shifts, which can be useful for identifying quick reversals.
🔶 DETAILS
The construction of the Correlated Sine Oscillator follows a sophisticated signal processing workflow:
Detrending: The script first removes the trend by subtracting a Simple Moving Average (SMA) from the closing price. This isolates the high-frequency fluctuations (cycles) around a mean of zero. Quadrature Projection: The detrended price is projected onto both a Sine and Cosine wave (real and imaginary components) based on the user-defined Cycle Period . Phase Estimation: By calculating the arctangent of these components, the script derives the "Dynamic Phase." This tells us exactly where the current price sits within the theoretical cycle. Correlation: Finally, the script generates a synthetic sine wave that is shifted by the calculated phase, ensuring the output is perfectly correlated with the dominant frequency of the price action.
🔶 SETTINGS
Cycle Period: Determines the primary wavelength (in bars) that the indicator looks for in the price data. Setting this to 20 means the oscillator is tuned to find cycles that repeat every 20 bars. Phase Multiplier: A multiplier applied to the Cycle Period to determine the smoothing length of the internal phase components. A higher value leads to a "cleaner" wave, while a lower value follows price more aggressively. Bullish Color: Controls the color of the oscillator and gradient fill when the value is above zero. Bearish Color: Controls the color of the oscillator and gradient fill when the value is below zero. Indicator

Indicator

Cross-Market Regime Scanner [BOSWaves]Cross-Market Regime Scanner - Multi-Asset ADX Positioning with Correlation Network Visualization
Overview
Cross-Market Regime Scanner is a multi-asset regime monitoring system that maps directional strength and trend intensity across correlated instruments through ADX-based coordinate positioning, where asset locations dynamically reflect their current trending versus ranging state and bullish versus bearish bias.
Instead of relying on isolated single-asset trend analysis or static correlation matrices, regime classification, spatial positioning, and intermarket relationship strength are determined through ADX directional movement calculation, percentile-normalized coordinate mapping, and rolling correlation network construction.
This creates dynamic regime boundaries that reflect actual cross-market momentum patterns rather than arbitrary single-instrument levels - visualizing trending assets in right quadrants when ADX strength exceeds thresholds, positioning ranging assets in left quadrants during consolidation, and incorporating correlation web topology to reveal which instruments move together or diverge during regime transitions.
Assets are therefore evaluated relative to ADX-derived regime coordinates and correlation network position rather than conventional isolated technical indicators.
Conceptual Framework
Cross-Market Regime Scanner is founded on the principle that meaningful market insights emerge from simultaneous multi-asset regime awareness rather than sequential single-instrument analysis.
Traditional trend analysis examines assets individually using separate chart windows, which often obscures the broader cross-market regime structure and correlation patterns that drive coordinated moves. This framework replaces isolated-instrument logic with unified spatial positioning informed by actual ADX directional measurements and correlation relationships.
Three core principles guide the design:
Asset positioning should be determined by ADX-based regime coordinates that reflect trending versus ranging state and directional bias simultaneously.
Spatial mapping must normalize ADX values to place assets within consistent quadrant boundaries regardless of instrument volatility characteristics.
Correlation network visualization reveals which assets exhibit coordinated behavior versus divergent regime patterns during market transitions.
This shifts regime analysis from isolated single-chart monitoring into unified multi-asset spatial awareness with correlation context.
Theoretical Foundation
The indicator combines ADX directional movement calculation, coordinate normalization methodology, quadrant-based regime classification, and rolling correlation network construction.
A Wilder's smoothing implementation calculates ADX, +DI, and -DI for each monitored asset using True Range and directional movement components. The ADX value relative to a configurable threshold determines X-axis positioning (ranging versus trending), while the difference between +DI and -DI determines Y-axis positioning (bearish versus bullish). Coordinate normalization caps values within fixed boundaries for consistent quadrant placement. Pairwise correlation calculations over rolling windows populate a network graph where line thickness and opacity reflect correlation strength.
Five internal systems operate in tandem:
Multi-Asset ADX Engine : Computes smoothed ADX, +DI, and -DI values for up to 8 configurable instruments using Wilder's directional movement methodology.
Coordinate Transformation System : Converts ADX strength and directional movement into normalized X/Y coordinates with threshold-relative scaling and boundary capping.
Quadrant Classification Logic : Maps coordinate positions to four distinct regime states—Trending Bullish, Trending Bearish, Ranging Bullish, Ranging Bearish—with color-coded zones.
Historical Trail Rendering : Maintains rolling position history for each asset, drawing gradient-faded trails that visualize recent regime trajectory and velocity.
Correlation Network Calculator : Computes pairwise return correlations across all enabled assets, rendering weighted connection lines in circular web topology with strength-based styling.
This design allows simultaneous cross-market regime awareness rather than reacting sequentially to individual instrument signals.
How It Works
Cross-Market Regime Scanner evaluates markets through a sequence of multi-asset spatial processes:
Data Request Processing : Security function retrieves high, low, and close values for up to 8 configurable symbols with lookahead offset to ensure confirmed bar data.
ADX Calculation Per Asset : True Range computed from high-low-close relationships, directional movement derived from up-moves versus down-moves, smoothed via Wilder's method over configurable period.
Directional Index Derivation : +DI and -DI calculated as smoothed directional movement divided by smoothed True Range, scaled to percentage values.
Coordinate Transformation : X-axis position equals (ADX - threshold) * 2, capped between -50 and +50; Y-axis position equals (+DI - -DI), capped between -50 and +50.
Quadrant Assignment : Positive X indicates trending (ADX > threshold), negative X indicates ranging; positive Y indicates bullish (+DI > -DI), negative Y indicates bearish.
Trail History Management : Configurable-length position history maintains recent coordinates for each asset, rendering gradient-faded lines connecting sequential positions.
Velocity Vector Calculation : 7-bar coordinate change converted to directional arrow overlays showing regime momentum and trajectory.
Return Correlation Processing : Bar-over-bar returns calculated for each asset, pairwise correlations computed over rolling window.
Network Graph Construction : Assets positioned in circular topology, correlation lines drawn between pairs exceeding threshold with thickness/opacity scaled by correlation strength, positive correlations solid green, negative correlations dashed red.
Risk Regime Scoring : Composite score aggregates bullish risk-on assets (equities, crypto, commodities) minus bullish risk-off assets (gold, dollar, VIX), generating overall market risk sentiment with colored candle overlay.
Together, these elements form a continuously updating spatial regime framework anchored in multi-asset momentum reality and correlation structure.
Interpretation
Cross-Market Regime Scanner should be interpreted as unified spatial regime boundaries with correlation context:
Top-Right Quadrant (TREND ▲) : Assets positioned here exhibit ADX above threshold with +DI exceeding -DI - confirmed bullish trending conditions with directional conviction.
Bottom-Right Quadrant (TREND ▼) : Assets positioned here exhibit ADX above threshold with -DI exceeding +DI - confirmed bearish trending conditions with directional conviction.
Top-Left Quadrant (RANGE ▲) : Assets positioned here exhibit ADX below threshold with +DI exceeding -DI - ranging consolidation with bullish bias but insufficient trend strength.
Bottom-Left Quadrant (RANGE ▼) : Assets positioned here exhibit ADX below threshold with -DI exceeding +DI - ranging consolidation with bearish bias but insufficient trend strength.
Position Trails : Gradient-faded lines connecting recent coordinate history reveal regime trajectory - curved paths indicate regime rotation, straight paths indicate sustained directional conviction.
Velocity Arrows : Directional vectors overlaid on current positions show 7-bar regime momentum - arrow length indicates speed of regime change, angle indicates trajectory direction.
Correlation Web : Circular network graph positioned left of main quadrant map displays pairwise asset relationships - solid green lines indicate positive correlation (moving together), dashed red lines indicate negative correlation (diverging moves), line thickness reflects correlation strength magnitude.
Asset Dots : Multi-layer glow effects with color-coded markers identify each asset on both quadrant map and correlation web-symbol labels positioned adjacent to current location.
Regime Summary Bar : Vertical boxes on right edge display condensed regime state for each enabled asset - box background color reflects quadrant classification, border color matches asset identifier.
Risk Regime Candles : Overlay candles on price chart colored by composite risk score - green indicates risk-on dominance (bullish equities/crypto exceeding bullish safe-havens), red indicates risk-off dominance (bullish gold/dollar/VIX exceeding bullish risk assets), gray indicates neutral balance.
Quadrant positioning, trail trajectory, correlation network topology, and velocity vectors outweigh isolated single-asset readings.
Signal Logic & Visual Cues
Cross-Market Regime Scanner presents spatial positioning insights rather than discrete entry signals:
Regime Clustering : Multiple assets congregating in same quadrant suggests broad market regime consensus - all assets in TREND ▲ indicates coordinated bullish momentum across instruments.
Regime Divergence : Assets splitting across opposing quadrants reveals intermarket disagreement - equities in TREND ▲ while safe-havens in TREND ▼ suggests healthy risk-on environment.
Quadrant Transitions : Assets crossing quadrant boundaries mark regime shifts - movement from left (ranging) to right (trending) indicates breakout from consolidation into directional phase.
Trail Curvature Patterns : Sharp curves in position trails signal rapid regime rotation, straight trails indicate sustained directional conviction, loops indicate regime uncertainty with back-and-forth oscillation.
Velocity Acceleration : Long arrows indicate rapid regime change momentum, short arrows indicate stable regime persistence, arrow direction reveals whether asset moving toward trending or ranging state.
Correlation Breakdown Events : Previously strong correlation lines (thick, opaque) suddenly thinning or disappearing indicates relationship decoupling - often precedes major regime transitions.
Correlation Inversion Signals : Assets shifting from positive correlation (solid green) to negative correlation (dashed red) marks structural market regime change - historically correlated assets beginning to diverge.
Risk Score Extremes : Composite score reaching maximum positive (all risk-on bullish, all risk-off bearish) or maximum negative (all risk-on bearish, all risk-off bullish) marks regime conviction extremes.
The primary value lies in simultaneous multi-asset regime awareness and correlation pattern recognition rather than isolated timing signals.
Strategy Integration
Cross-Market Regime Scanner fits within macro-aware and intermarket analysis approaches:
Regime-Filtered Entries : Use quadrant positioning as directional filter for primary trading instrument - favor long setups when asset in TREND ▲ quadrant, short setups in TREND ▼ quadrant.
Correlation Confluence Trading : Enter positions when target asset and correlated instruments occupy same quadrant - multiple assets in TREND ▲ provides conviction for long exposure.
Divergence-Based Reversal Anticipation : Monitor for regime divergence between correlated assets - if historically aligned instruments split to opposite quadrants, anticipate mean-reversion or regime rotation.
Breakout Confirmation via Cross-Asset Validation : Confirm primary instrument breakouts by verifying correlated assets simultaneously transitioning from ranging to trending quadrants.
Risk-On/Risk-Off Positioning : Use composite risk score and safe-haven positioning to determine overall market environment - scale risk exposure based on risk regime dominance.
Velocity-Based Timing : Enter during periods of high regime velocity (long arrows) when momentum carries assets decisively into new quadrants, avoid entries during low velocity regime uncertainty.
Multi-Timeframe Regime Alignment : Apply higher-timeframe regime scanner to establish macro context, use lower-timeframe price action for entry timing within aligned regime structure.
Correlation Web Pattern Recognition : Identify regime transitions early by monitoring correlation network topology changes - previously disconnected assets forming strong correlations suggests regime coalescence.
Technical Implementation Details
Core Engine : Wilder's smoothing-based ADX calculation with separate True Range and directional movement tracking per asset
Coordinate Model : Threshold-relative X-axis scaling (trending versus ranging) with directional movement differential Y-axis (bullish versus bearish)
Normalization System : Boundary capping at ±50 for consistent spatial positioning regardless of instrument volatility
Trail Rendering : Rolling array-based position history with gradient alpha decay and width tapering
Correlation Engine : Return-based pairwise correlation calculation over rolling window with configurable lookback
Network Visualization : Circular topology with trigonometric positioning, weighted line rendering based on correlation magnitude
Risk Scoring : Composite calculation aggregating directional states across classified risk-on and risk-off asset categories
Performance Profile : Optimized for 8 simultaneous security requests with efficient array management and conditional rendering
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Micro-regime monitoring for intraday correlation shifts and short-term regime rotations
15 - 60 min : Intraday regime structure with meaningful ADX development and correlation stability
4H - Daily : Swing and position-level macro regime identification with sustained trend classification
Weekly - Monthly : Long-term regime cycle tracking with structural correlation pattern evolution
Suggested Baseline Configuration:
ADX Period : 14
ADX Smoothing : 14
Trend Threshold : 25.0
Trail Length : 15
Correlation Period : 50
Min |Correlation| to Show Line : 0.3
Web Radius : 30
Show Quadrant Colors : Enabled
Show Regime Summary Bar : Enabled
Show Velocity Arrows : Enabled
Show Correlation Web : Enabled
These suggested parameters should be used as a baseline; their effectiveness depends on the selected assets' volatility profiles, correlation characteristics, and preferred spatial sensitivity, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Assets clustering too tightly : Decrease Trend Threshold (e.g., 20) to spread ranging/trending separation, or increase ADX Period for smoother ADX calculation reducing noise.
Assets spreading too widely : Increase Trend Threshold (e.g., 30-35) to demand stronger ADX confirmation before classifying as trending, tightening quadrant boundaries.
Trail too short to show trajectory : Increase Trail Length (20-25) to visualize longer regime history, revealing sustained directional patterns.
Trail too cluttered : Decrease Trail Length (8-12) for cleaner visualization focusing on recent regime state, reducing visual complexity.
Unstable ADX readings : Increase ADX Period and ADX Smoothing (18-21) for heavier smoothing reducing bar-to-bar regime oscillation.
Sluggish regime detection : Decrease ADX Period (10-12) for faster response to directional changes, accepting increased sensitivity to noise.
Too many correlation lines : Increase Min |Correlation| threshold (0.4-0.6) to display only strongest relationships, decluttering network visualization.
Missing significant correlations : Decrease Min |Correlation| threshold (0.2-0.25) to reveal weaker but potentially meaningful relationships.
Correlation too volatile : Increase Correlation Period (75-100) for more stable correlation measurements, reducing network line flickering.
Correlation too stale : Decrease Correlation Period (30-40) to emphasize recent correlation patterns, capturing regime-dependent relationship changes.
Velocity arrows too sensitive : Modify 7-bar lookback in code to longer period (10-14) for smoother velocity representation, or increase magnitude threshold for arrow display.
Adjustments should be incremental and evaluated across multiple session types rather than isolated market conditions.
Performance Characteristics
High Effectiveness:
Macro-aware trading approaches requiring cross-market regime context for directional bias
Intermarket analysis strategies monitoring correlation breakdowns and regime divergences
Portfolio construction decisions requiring simultaneous multi-asset regime classification
Risk management frameworks using safe-haven positioning and risk-on/risk-off scoring
Trend-following systems benefiting from cross-asset regime confirmation before entry
Mean-reversion strategies identifying regime extremes via clustering patterns and correlation stress
Reduced Effectiveness:
Single-asset focused strategies not incorporating cross-market context in decision logic
High-frequency trading approaches where multi-security request latency impacts execution
Markets with consistently weak correlations where network topology provides limited insight
Extremely low volatility environments where ADX remains persistently below threshold for all assets
Instruments with erratic or unreliable ADX characteristics producing unstable coordinate positioning
Integration Guidelines
Confluence : Combine with BOSWaves structure, volume analysis, or primary instrument technical indicators for entry timing within aligned regime
Quadrant Respect : Trust signals occurring when primary trading asset occupies appropriate quadrant for intended trade direction
Correlation Context : Prioritize setups where target asset exhibits strong correlation with instruments in same regime quadrant
Divergence Awareness : Monitor for safe-haven assets moving opposite to risk assets - regime divergence validates directional conviction
Velocity Confirmation : Favor entries during periods of strong regime velocity indicating decisive momentum rather than regime oscillation
Risk Score Alignment : Scale position sizing and exposure based on composite risk score - larger positions during clear risk-on/risk-off environments
Trail Pattern Recognition : Use trail curvature to identify regime stability (straight) versus rotation (curved) versus uncertainty (looped)
Multi-Timeframe Structure : Apply higher-timeframe regime scanner for macro filter, lower-timeframe for tactical positioning within established regime
Disclaimer
Cross-Market Regime Scanner is a professional-grade multi-asset regime visualization and correlation analysis tool. It uses ADX-based coordinate positioning and rolling correlation calculation but does not predict future regime transitions or guarantee relationship persistence. Results depend on selected assets' characteristics, parameter configuration, correlation stability, and disciplined interpretation. Security request timing may introduce minor latency in real-time data retrieval. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates price structure, volume context, fundamental macro awareness, and comprehensive risk management. Indicator
