Conditions DashboardDEVELOPED BY A FORMER GOLDMAN SACHS TRADER
Overview
The Conditions Dashboard acts as the framework's situational awareness layer — translating raw indicator outputs into cohesive market "states."
How It Works
At its core, State Detection evaluates a structured matrix of technical and statistical indicators (e.g., EMAs, volatility, skewness, ADX, momentum accelerators). Each component feeds a binary or scaled state — such as Long, Short, Bull, Bear-Continue, or Contracting. Two synchronized tables form the visual interface: the Indicator State Table displays active sub-systems showing each indicator's current state, and the Timeframe Alignment Table aggregates EMAC and trend state readings across multiple timeframes.
Use Cases
Multi-timeframe confirmation: enter trades only when short- and medium-term states align
Conflict detection: stand aside when lower- and higher-timeframe signals diverge
Momentum monitoring: use the Forecast/Accel and Momentum State rows to identify strengthening vs. weakening phases
Visual diagnostics: embed the table on live charts to instantly understand current structure
Strategic scaling: combine with the Combined Forecast or Trend Exhaustion Systems
Interpretation Example
Example Output:
All timeframes: Bull-Continue
Meaning:
Strong aligned uptrend; maintain or scale into longs. Mixed states indicate transition phase; reduce exposure and monitor for volatility compression
Statistics
7D Historical Volatility (Regimes + Stats) - ChrrizzyHere’s what that indicator does—at a glance:
### Core idea
It computes **7-day Historical Volatility (HV)** from **daily** log returns (annualized), then shows:
* the **HV line** and its **30-day average**,
* colored **volatility regimes** (Low / Normal / High / Extreme) with thresholds you set,
* a compact **status panel** (top-right, nudged left) with current stats and time-in-zone.
### Calculations
* **HV (7D)**: `stdev(log(close/close ), 7) * sqrt(365) * 100`, always from **daily data** via `request.security`, so it’s consistent on any chart timeframe.
* **Regimes** (defaults):
Low < 25% • Normal 25–50% • High 50–70% • Extreme > 70% (all editable).
* **30-day avg**: SMA of HV.
* **Time in zone (% over window)**: SMA of boolean flags (e.g., in Low=1 else 0) over `statsWin` days (default 300).
* **Rolling median HV**: 50th percentile over `statsWin`.
### What you see on the chart
* **HV line** (bold) + **30-day HV** (lighter).
* **Horizontal dashed lines** at your regime thresholds.
* **Background shading** that changes with the current regime (green/blue/orange/red).
### Panel (top-right)
Shows:
* BTC Price (daily close)
* Current HV
* 30-day Avg HV
* Median HV (over window)
* Current **Regime**
* A two-line summary: **% of time spent** in Low / Normal / High / Extreme over the chosen window.
The panel is shifted slightly left using a hidden spacer column; tweak the **“Panel right padding (chars)”** input to move it.
### Alerts (ready to use)
* **HV crossed up Low**
* **HV crossed down Low**
* **HV crossed up High**
* **HV crossed up Extreme**
### Inputs you can tune
* `HV Lookback (days)` (default 7)
* `Average HV (days)` (default 30)
* Thresholds: Low/High/Extreme
* `Stats Window (days)` (default 300)
* Panel padding, toggle table/zones on/off.
### How to use it
* **Context**: quickly see if BTC is in **compressed** (Low) or **stressed** (High/Extreme) volatility.
* **Regime cross alerts**: get notified when volatility **expands** from Low (potential breakout conditions) or pushes into High/Extreme (risk increases).
* **Stats/median**: compare today’s HV to its typical level over your lookback window.
If you want, I can add an **HV percentile rank** (e.g., “Current HV is at the 38th percentile over 300d”) or mirror the **low-vol breakout signal** from Script A into this panel.
Trend Strength IndexTSI with alert levels
You can set the levels of trend strength to trigger an alert
There are 2 levels to set alerts, feel free to test this indicator
Session Engine — Market Opens, Killzones & Levels — SMC/ICTSession Engine — Market Opens, Killzones & Institutional Levels (Tokyo • London • New York) — SMC/ICT — TradingATH (PueblaATH)
Precision. Sessions. Structure.
Session Engine maps the institutional heartbeat of the day across Tokyo , London , and New York . It draws timezone-accurate Market Open Lines , clean Killzones (incl. London–NY overlap), and a rock-solid, timeframe-safe suite of Previous High/Low Levels (PDH/PDL/PWH/PWL/PMH/PML). On top, a compact Session Comparison Table with an integrated ADR panel shows extension, momentum context, and distance to key levels — at a glance.
Designed for SMC/ICT Traders who demand clarity and reliability, this tool stays stable when you change timeframe, reload, or zoom.
Map the day like a Pro : timezone-true Opens, configurable Killzones, TF-safe PDH/PDL/PWH/PWL/PMH/PML , and a sleek ADR panel beneath a Session Comparison Table . Built for precision SMC/ICT Execution . Zero flicker, full control.
Why Traders Love It
Timezone-Accurate Session Engine — Tokyo, London, New York opens and the London–NY overlap, all resolved to bar-time for precise plotting on any symbol.
Killzones you can trust — choose full-column height or price-bounded height with custom top/bottom tick offsets and label placement.
Bulletproof Previous Levels — PDH, PDL, PWH, PWL, PMH, PML are cached and only refresh on true D/W/M boundaries, eliminating the classic “levels disappear on TF change” problem.
Actionable Context — a compact Session Comparison Table (vs previous session & vs previous day) plus an ADR panel with extension thresholds, distance to PDH/PDL, and current H-L range.
Serious Customization — dotted/solid lines, widths, label size & alignment, auto label backgrounds, block transparency, weekend & timeframe filters, and more.
Performance-Minded — persistent objects are updated in place (not spam-created) to keep your chart crisp and responsive.
What You’ll See
Market Opens — Vertical opens for TOK/LDN/NY with dotted/solid styling, width control, infinite or bounded height, and optional labels.
Killzones + Overlap — Transparent time boxes for session windows (and London–NY overlap). Optional labels, adjustable transparency, and height mode.
Institutional Levels — PDH / PDL / PWH / PWL / PMH / PML with length modes: Infinite, N bars, or End of day. Optional labels with typographic control.
Session Comparison Table — For each session: bias vs previous session and previous day, with optional Δ% column.
ADR Panel — 24h rolling ADR% consumption with two attention thresholds, distance to PDH/PDL (price units), and current H-L range.
How It Works
Session Timing uses explicit IANA timezones (Asia/Tokyo, Europe/London, America/New_York) then anchors to bar_time for pixel-perfect placement.
Killzones are persistent boxes that reset only on daily change, preventing redundant object creation.
Previous Levels are requested once per true period roll (D/W/M) and stored locally; this cache keeps lines stable when switching TFs or reloading charts.
Level Line Length is enforced per-object (Infinite, N bars, End of day) with dynamic x2 handling — no redraw flicker.
ADR uses a timeframe-agnostic 24h rolling window for H/L/range; ADR length is defined in “days” and mapped to bars for any timeframe.
How to Use
Set Session Times (defaults are standard). Adjust the London–NY overlap if your venue differs.
Style your Opens & Killzones — line width, dotted/solid, infinite or bounded height, label font size/align/background.
Choose Level Behavior — Infinite, N bars, or End of day for PD/ PW / PM lines; toggle labels as needed.
Read the Table and ADR — quick bias vs previous session/day, Δ% if you enable it; ADR panel highlights extension with blink thresholds and shows live distance to PDH/PDL.
Inputs
Schedules — Open times + killzone windows for TOK/LDN/NY, and London–NY overlap.
Style — Line width, dotted/solid, label sizes & alignment, auto backgrounds.
Heights — Infinite or tick-bounded line height; full-column or tick-bounded killzones.
Levels — Show/hide PDH/PDL/PWH/PWL/PMH/PML; length mode; label options.
Table & ADR — Font size, arrows, Δ% column, ADR length (days), blink thresholds, show/hide rows.
Filters — Hide visuals on specified timeframe ranges; optional weekend suppression.
Best Practices
Use “End of day” for tidy level lines that still convey right-hand context.
Set ADR thresholds to your instrument’s personality (e.g., 80/120 for FX, 100/150 for crypto).
On exotic trading sessions, verify the IANA timezone alignment and tweak inputs accordingly.
If you stack many tools, consider disabling unused sessions/rows to stay within object limits.
What Makes It Original
A cohesive Session Engine architecture that unifies timezone-true Opens, configurable Killzones/Overlap, and TF-safe previous levels — tailored for SMC/ICT execution.
Robust caching that eliminates TF-switch flicker and preserves dependent calculations (distance to PDH/PDL, ADR%) without gaps.
A unified ADR panel directly under the session table with real-time extension signaling and distance-to-PDH/PDL — pragmatic, trade-ready context you won’t find in generic session scripts.
Deep length & typography controls so visuals are informative and elegant.
Notes & Disclaimer (Originality & Rights)
Original Work Notice — Please read — This script/indicator is an original work created exclusively by TradingATH ( PueblaATH ). It is not derived from, copied from, or authored by any other person or entity. Any resemblance to other scripts is coincidental and limited to the use of public and widely known trading concepts.
Usage & Publication — Redistribution, cloning, or republishing this script (in whole or in part) without the explicit written permission of TradingATH ( PueblaATH ) is prohibited. By using this tool, you acknowledge the author’s exclusive authorship and associated rights.
No Financial Advice — This tool is for educational/informational purposes only and does not constitute financial advice. Markets carry risk; manage your risk and make your own decisions.
MomentumQ Ratio MatrixMomentumQ Ratio Matrix — Intermarket Risk & Sector Relationship Dashboard
The MomentumQ Ratio Matrix is a compact, on-chart dashboard designed to help traders quickly interpret intermarket relationships and sector leadership through key ETF ratios.
It visualizes the balance between risk-on vs. risk-off sentiment , growth vs. value rotation , and defensive vs. cyclical behavior — giving you an instant read of where capital is flowing in the U.S. market.
What It Does
The indicator compares weekly and daily percentage returns for five critical sector ETF pairs. Each pair represents a specific aspect of market structure or investor preference.
When a ratio is rising , it means the first sector is outperforming the second — signaling increased risk appetite or leadership from growth sectors.
When a ratio is falling , it indicates defensiveness, capital rotation, or weakening momentum in risk-oriented areas.
Examples:
XLY/XLP ↑ → Consumers are spending more on discretionary items (risk-on).
XLY/XLP ↓ → Money shifts into staples (risk-off, defensive tone).
XLK/XLF ↑ → Technology leads Financials (growth leadership).
XLK/XLF ↓ → Financials lead, signaling preference for value or cyclicals.
XLI/XLU ↑ → Industrials outperform Utilities (economic optimism).
XLI/XLU ↓ → Utilities outperform (defensive capital rotation).
XLE/XLB ↑ → Energy leading Materials (inflation or commodity strength).
XLE/XLB ↓ → Materials outperform (cooling inflationary trends).
XLV/XLU ↑ → Healthcare stronger than Utilities (mild defensiveness, but stable risk appetite).
XLV/XLU ↓ → Utilities lead (risk aversion, defensive positioning).
Color-coded cells highlight each ratio’s short-term and medium-term performance:
Green → Ratio rising (risk-on, cyclical, or growth leadership).
Red → Ratio falling (risk-off, defensive, or value rotation).
Gray → Neutral performance.
Key Features
Essential Ratio Coverage — Tracks the five most meaningful ETF ratios for intermarket and sentiment analysis.
Multi-Timeframe Analysis — Displays both Weekly and Daily (or Previous Day) changes for each ratio.
Adaptive Table Layout — Adjustable size, position, and decimal precision to fit any chart.
Light / Dark Mode Support — Automatically adapts to match your TradingView theme.
Performance-Based Coloring — Green for strength, red for weakness, and gray for neutral.
How to Use
Add the indicator to any chart (symbol-independent).
Choose your table position and size from the settings.
Toggle between Today and PrevD mode for different time comparisons.
Use the color-coded returns to gauge where capital is flowing.
Watch for shifts across multiple ratios to confirm changing market regimes.
When most ratios are green, the market generally favors growth and higher risk assets (risk-on).
When most are red, defensive sectors and value stocks tend to lead (risk-off).
Why It’s Valuable
Condenses intermarket and macro relationships into one visual dashboard.
Helps identify leadership shifts between risk, growth, and defensive sectors.
Provides a real-time snapshot of market sentiment without switching charts.
Supports both short-term tactical and long-term trend confirmation.
Disclaimer
The MomentumQ Ratio Matrix is designed for educational and analytical purposes only.
It does not constitute financial advice or guarantee profitability.
Always conduct independent analysis and apply proper risk management when trading.
HTF Ranges - AWR/AMR/AYR [bilal]📊 Overview
Professional higher timeframe range indicator for swing and position traders. Calculate Average Weekly Range (AWR), Average Monthly Range (AMR), and Average Yearly Range (AYR) with precision projection levels.
✨ Key Features
📅 Three Timeframe Modes
AWR (Average Weekly Range): Weekly swing targets - Default 4 weeks
AMR (Average Monthly Range): Monthly position targets - Default 6 months
AYR (Average Yearly Range): Yearly extremes - Default 9 years
🎯 Dual Anchor Options
Period Open: Week/Month/Year opening price
RTH Open: First RTH session (09:30 NY) of the period
📐 Projection Levels
100% Range Levels: Upper and lower targets from anchor
Fractional Levels: 33% and 66% zones for partial targets
Custom Mirrored Levels: Set any percentage (0-200%) with automatic mirroring
Example: 25% shows both 25% and 75%
Example: 150% shows both 150% and -50%
📊 Information Table
Active range type (AWR/AMR/AYR)
Average range value for selected period
Current period range and percentage used
Distance remaining to targets (up/down)
Color-coded progress (green/orange/red)
🎨 Fully Customizable
Orange theme by default (differentiates from daily indicators)
Line colors, styles (solid/dashed/dotted), and widths
Toggle labels on/off
Adjustable lookback periods for each timeframe
Independent settings for each range type
⚡ Smart Features
Lines start at actual period open (not fixed lookback)
Automatically tracks current period high/low
Works on any chart timeframe
Real-time range tracking
Alert conditions when targets reached or exceeded
🎯 Use Cases
AWR (Weekly Ranges):
Swing trade targets (3-7 day holds)
Weekly support/resistance zones
Identify weekly trend vs rotation
Compare daily moves to weekly context
AMR (Monthly Ranges):
Position trade targets (2-4 week holds)
Monthly breakout levels
Institutional-level zones
Earnings play targets
AYR (Yearly Ranges):
Major reversal zones
Long-term support/resistance
Identify macro trend strength
Annual high/low projections
💡 Trading Strategies
AWR Strategy (Swing Trading):
Week opens near AWR lower level = potential long setup
Target AWR 66% and 100% levels
Week hits AWR upper in first 2 days = watch for reversal
Use fractional levels as scale-in/scale-out points
AMR Strategy (Position Trading):
Month opens near AMR extremes = fade setup
Month breaks AMR in week 1 = expansion (trend) month
Target opposite AMR extreme for swing positions
Use 33%/66% for partial profit taking
AYR Strategy (Long-term Context):
Price near AYR extremes = major reversal zones
Breaking AYR levels = historic moves (rare)
Use for macro trend confirmation
Great for yearly forecasting and planning
📊 Range Interpretation
<33% Range Used: Early in period, room for expansion
33-66% Range Used: Normal progression
66-100% Range Used: Extended, approaching extremes
>100% Range Used: Expansion period - trending or high volatility
⚙️ Settings Guide
Lookback Periods:
AWR: 4 weeks (standard) - adjust to 8-12 for smoother average
AMR: 6 months (standard) - seasonal patterns
AYR: 9 years (standard) - captures full cycles
Anchor Type:
Period Open: Use for clean week/month/year open reference
RTH Open: Use if you only trade day session, ignores overnight gaps
Custom Levels:
25% = quartile targets
75% = three-quarter targets
80% = "danger zone" for reversals
111% = extended breakout target
🔄 Combine with ADR Indicator
Run both indicators together for complete multi-timeframe analysis:
ADR for intraday precision
AWR/AMR/AYR for swing/position context
See if today's ADR move is significant in weekly/monthly context
Multi-timeframe confluence = highest probability setups
💼 Ideal For
Swing Traders: Use AWR for 3-10 day holds
Position Traders: Use AMR for 2-8 week holds
Long-term Investors: Use AYR for macro context
Index Futures Traders: ES, NQ, YM, RTY
Multi-timeframe Analysis: Combine with daily ADR
CEO Synapse v1.0CEO Synapse — Uyarlanabilir Rejim Stratejisi
This script is invite-only.
What Does This Strategy Do?
Markets are complex systems requiring various expertise. The "CEO Synapse" strategy adopts a "digital dashboard" approach based on the reality that a single viewpoint is insufficient. The strategy combines multiple analytical engines, each developed by me, analyzing different aspects of the market (structure, momentum, rhythm). It detects trend and momentum deviations in markets. A trading decision is made only when there is consensus among these expert engines. The "Synapse Engine" uses adaptive filtering and consensus logic for position management based on market regime (trend/range).
It eliminates the problem of traditional indicators generating misleading signals alone and failing to adapt to volatility and regime changes. Its dynamic threshold mechanism, adaptive periods, and special noise filters reduce unnecessary trades.
Original Methodology and Proprietary Logic: This algorithm does not rely on or copy any open source strategy code. The system uses commonly accepted indicators' mathematical principles such as ADX, EMA, SMA, ATR, True Range, etc., as data sources. The author's methodology combines dynamic period EMA, multi-filter consensus, adaptive threshold, and regime-based execution.
Though our strategy creates an original decision-making mechanism, it leverages foundational building blocks of technical analysis. The traditional indicators we use and their purposes are:
ADX (Average Directional Index): This indicator measures a trend’s strength, not its direction. Our strategy uses ADX as a filter to open positions only under sufficiently strong and distinct trend market conditions. This largely prevents misleading signals in weak or sideways markets.
Moving Averages (EMA and SMA): They form the backbone to determine the main trend direction. By smoothing price data, they reduce noise and reveal the market's general trend. But our strategy processes their outputs not as traditional crossover signals, but as input to an advanced consensus logic with dynamically adjusted periods based on market rhythm combined with other filters.
ATR (Average True Range): This indicator does not produce direct buy-sell signals but measures current market volatility. Especially in "Sideways Market" regime, take profit and stop loss levels are dynamically set based on ATR instead of fixed values, enabling risk management to adapt to market conditions.
Bollinger Band Logic (using Standard Deviation): Though the strategy does not plot Bollinger Bands directly, it uses Standard Deviation, the underlying mathematical concept, to detect excessive price deviations and volatility spikes, producing critical signals for the AMF PG core engine.
"Synapse Engine" consists of two layers: Decision Center (Dynamic Threshold) which automatically adjusts risk appetite based on performance and regime; and Filter Committee (Consensus Score) which weights separate filters to produce a single score. This combination is not reproducible and commercially valuable. Closed source is mandatory.
No classic open source code used. Only publicly available indicators are used. Parameters, order, and usage are fully customized.
Generated Signals: Trend/range entry/exit (long/short), adaptive trailing stop position management, additional risk control signals with Shock Absorber and Quantum Filter.
Purpose: Detect trend breaks and momentum deviations. Components: Volatility filters, adaptive signal weighting, EMA/SMA. Methodology: Combines price and volume change rates via dynamic weighting functions.
What Problem Does CEO Synapse Solve?
CEO Synapse addresses three main issues caused by traditional technical analysis and single indicator usage:
Problem: Misleading Signals and Market Noise
Traditional indicators (MACD, RSI, etc.) generate many "false" buy-sell signals, especially in sideways and choppy markets, causing traders to constantly enter and exit positions (whipsaw) and incur losses.
CEO Synapse Solution: The strategy never relies on a single signal. The Consensus-Based Decision Mechanism ensures no position is opened unless different analytical engines (structural, momentum, rhythm) agree. This "board of directors" approach filters market noise, processing only high-probability signals.
Problem: Static Analysis and Changing Market Conditions
Markets constantly change character; sometimes strong trend, sometimes narrow range. Most strategies try to function with fixed parameters across all conditions, leading to failure.
CEO Synapse Solution: The strategy has Adaptive Regime Switching. It actively analyzes whether the market is in "Trend Mode" or "Sideways Market Mode" and automatically adjusts entry/exit rules and risk management (take profit/stop loss) to the current regime, allowing chameleon-like adaptation to conditions.
Problem: Fixed Parameters and Declining Performance
Many traders believe they find the "best" settings and never change them for months or years. But as market volatility and cycles change, fixed settings lose effectiveness.
CEO Synapse Solution: The strategy operates on Full Adaptation principle.
Market Rhythm Adaptation: Dynamically adjusts analysis speed (e.g., EMA periods) according to market’s natural cycles.
Performance Adaptation: Continuously optimizes risk appetite (signal threshold) based on recent strategy performance, becoming bolder with gains and more cautious with losses.
In summary, CEO Synapse simplifies decision-making, eliminates market noise, and smartly adapts to changing market conditions, protecting the user from common mistakes.
Why "Invite-Only"?
Offering CEO Synapse as "Invite-Only" is a strategic decision to protect the strategy's commercial value and intellectual property and to provide users with the highest quality experience. Key reasons:
Protection of Proprietary IP:
CEO Synapse is the result of hundreds of hours of research, development, and testing. Its consensus logic, adaptive threshold mechanism, and engine integration are unique and patented. Open sourcing it would instantly destroy this trade secret and competitive edge.
Maintaining Performance Integrity and Effectiveness:
Uncontrolled distribution could lead to misuse or signal theft and sale by malicious actors. The invite-only model preserves the strategy’s integrity and ensures access only for serious investors.
Quality User Experience and Support:
Controlled distribution allows better user experience. High-quality documentation explaining features and best practices can be provided, and future updates and support services can be managed better for a limited user base.
Business Model:
CEO Synapse is positioned as a premium analysis tool. Invite-only access reflects its value and compensates the developer for ongoing maintenance, support, and future improvements.
Usage: Available on all timeframes.
Based entirely on my own adaptive filtering methodology.
Proprietary logic: The algorithm’s unique, non-reproducible logic and methodology. Example: Multi-filter consensus + adaptive threshold + regime-based execution.
Why Is This a Premium Tool?
"CEO Synapse"’s value stems from being a proprietary, integrated system beyond free standard indicators:
Advanced Noise Filtering: Not just reduces noise but adjusts filter sensitivity to current market character. Inspired by public mathematical concepts (cycle analysis, statistical filtering) but uniquely combined with proprietary weighting mechanisms and adaptive consensus logic forming the strategy's commercial value. Core indicators (EMA, ATR, ADX, DMI, etc.) are uniquely processed inside this proprietary system.
Full Adaptation: Instead of fixed parameters, the strategy continuously adapts to the market's natural rhythm, volatility, and past performance.
Consensus-Based Decision Making: Relies on collective intelligence of multiple analytical engines, not a single failure point.
These features substantially increase the ability to extract meaningful, actionable insights from raw market data, making it premium. It improves signal accuracy, reduces risk, and adapts to regime shifts. The dynamic threshold mechanism continuously adjusts risk appetite based on recent performance (profitability) and market regime.
By using this script, you agree not to redistribute, sell, or reverse engineer the source code.
This strategy is for educational purposes only. Past performance does not guarantee future results. Always apply proper risk management and protect your capital.
Risk Management: Maximum Drawdown Protection
The strategy includes a built-in capital protection mechanism. Users can specify the percentage drop from peak capital they tolerate. If the capital hits this drawdown limit, protection activates, closing all open positions and blocking new trades, acting as an emergency brake to guard capital against unexpected market conditions.
Automation Ready: Customizable Webhook Alerts
Fully Compatible Automation (JSON): The strategy outputs fully configurable JSON-formatted alert messages for buy, sell, and close actions. This allows connecting CEO Synapse signals to automation platforms like 3Commas and PineConnector for fully automated trading. Dynamic values like position size ({{strategy.order.contracts}}) are automatically included in alerts.
Strategy Backtest Information
Please remember past performance is not indicative of future results. The published chart and report are based on the BTCUSD pair in a 3-hour timeframe with the following settings:
Test Period: January 1, 2018 – November 3, 2025
Default Position Size: 15% of capital
Pyramiding: Off
Commission: 0.0008
Slippage: 2 ticks
Test Approach: The published test contains 201 trades and is statistically significant. Performing your own tests on different assets and timeframes is strongly recommended. Default settings are a template and should be adjusted per your analysis.
Advanced ICT ADR Projections [bilal]📊 Overview
Professional ADR indicator designed specifically for index futures traders. Calculate and visualize Average Daily Range with multiple session options, fractional levels, and higher timeframe context.
✨ Key Features
🎯 Multiple Session Types
Full Day: Standard calendar day calculation
Midnight: Anchored to 00:00 NY time open
RTH (Regular Trading Hours): 09:30-16:00 NY session
Custom: Define your own session hours and anchor point
📐 Projection Levels
100% ADR Levels: Upper and lower range targets from anchor
Fractional Levels: 33% and 66% zones for partial targets
Custom Mirrored Levels: Set any percentage (0-200%) with automatic mirroring
Example: 25% shows both 25% and 75%
Example: 111% shows both 111% and -11%
📅 Higher Timeframe Context (Optional)
AWR: Average Weekly Range overlay
AMR: Average Monthly Range overlay
AYR: Average Yearly Range overlay
All HTF ranges use same anchor as daily session
📊 Information Table
Current session type and anchor time
ADR value for selected period
Current range and percentage used
Distance remaining to ADR targets (up/down)
Color-coded range percentage (green/orange/red)
🎨 Fully Customizable
Line colors, styles (solid/dashed/dotted), and widths
Toggle labels on/off
Adjustable ADR lookback period (1-100 days)
All HTF periods customizable
⚡ Smart Features
Lines start at actual session open (not fixed lookback)
Works on any timeframe
Real-time range tracking
Alert conditions when ADR reached or exceeded
🎯 Use Cases
For Day Traders:
Set profit targets at ADR extremes
Identify range expansion vs rotation days
Know when you've used 75%+ of daily range (possible reversal)
Compare RTH vs full day ranges
For Swing Traders:
Use AWR/AMR for weekly/monthly targets
Understand if today's move is significant in weekly context
Multi-timeframe confluence
Risk Management:
Size positions based on % of ADR remaining
Avoid trading when ADR exhausted (>100%)
Better stop placement using fractional levels
💡 Trading Tips
<50% ADR used = Room to run (continuation trades)
50-75% ADR used = Getting extended (scale out)
75-100% ADR used = Near extremes (reversal setups)
>100% ADR = Expansion day (trend day or volatility spike)
Use fractional levels (33%, 66%) as:
Partial profit targets
Re-entry zones on pullbacks
Confluence with other support/resistance
Compare RTH vs Full Day ADR to see if overnight or day session drives volatility.
⚙️ Settings Guide
ADR Period: 5 days is standard, adjust for different market regimes
Session Types:
Use Midnight for crypto or 24hr markets
Use RTH for pure day session analysis
Use Custom for specific session times (London, Asia, etc.)
Custom Levels:
Set 25% for quartile levels
Set 111% for extended targets beyond ADR
Experiment with 50%, 75%, 80% for your strategy
Perfect for ES, NQ, YM, RTY futures traders who need precise intraday range analysis with higher timeframe context!
ChainAggLib - library for aggregation of main chain tickersLibrary "ChainAggLib"
ChainAggLib — token -> main protocol coin (chain) and top-5 exchange tickers for volume aggregation.
Library only (no plots). All helpers are pure functions and do not modify globals.
norm_sym(s)
Parameters:
s (string)
get_base_from_symbol(full_symbol)
Parameters:
full_symbol (string)
get_chain_for_token(token_symbol)
Parameters:
token_symbol (string)
get_top5_exchange_tickers_for_chain(chain_code)
Parameters:
chain_code (string)
get_top5_exchange_tickers_for_token(token_symbol)
Parameters:
token_symbol (string)
join_tickers(arr)
Parameters:
arr (array)
contains_symbol(arr, symbol)
Parameters:
arr (array)
symbol (string)
contains_current(arr)
Parameters:
arr (array)
get_arr_for_current_token()
get_chain_for_current()
Slick Strategy Weekly PCS TesterInspired by the book “The Slick Strategy: A Unique Profitable Options Trading Method.” This indicator tests weekly SPX put-credit spreads set below Monday’s open and judged at Friday’s close.
WHAT IT DOES
• Sets weekly PCS level = Monday (or first trading day) OPEN − your offset; win/loss checked at Friday close.
• Optional core filter at entry: Price ≥ 200-SMA AND 10-SMA ≥ 20-SMA; pause if Price < both 10 & 20 while > 200.
• Reference modes: Strict = Mon OPEN vs Fri SMAs (no repaint); Mid = Mon OPEN vs Mon SMAs
KEY INPUTS
• Date range (Start/End) to limit backtest window.
• Offset mode/value (Points or Percent).
• Entry day (Monday only or first trading day).
• Core filters (On/Off) and Strict/Mid reference.
• SMA settings (source; 10/20/200 lengths).
• Table settings (position, size, padding, border).
VISUALS
• Active week line: Orange = trade taken; Gray = skipped.
• History: Green = win; Red = loss; Purple = skipped.
• Optional week bands highlight active/win/loss/skipped weeks (adjustable opacity).
TABLE
• Shows Date range, Trades, Wins, Losses, Win rate, and Active level (this week’s PCS price).
NOTES
• PCS level freezes at week open and persists through the week.
TRADE ORBIT:- TREND REVERSAL INDICATORThis indicator combines EMA momentum, Stochastic oscillator behavior, and trend-strength histogram analysis to identify when the market is trending, weakening, or potentially reversing.
✅ Main Components
EMA Difference
Calculates strength as the difference between a fast EMA and slow EMA
Positive → Uptrend
Negative → Downtrend
Stochastics (%K & %D)
Identifies overbought (>80) / oversold (<20) conditions
Signals crossovers:
%K crosses above %D → bullish
%K crosses below %D → bearish
Trend Strength Histogram
Shows the momentum change in color + height:
Condition Color Meaning
Uptrend strength increasing Strong Green Strong buying pressure
Uptrend strength weakening Light Green Buying losing momentum
Downtrend strength increasing Strong Red Strong selling pressure
Downtrend strength weakening Light Red Selling losing momentum
Divergence Yellow Trend may reverse
Divergence Detection
Bullish weakening >80 → Yellow
Uptrend losing strength → risk of reversal
Bearish weakening <20 → Yellow
Downtrend losing strength → risk of reversal
Buy/Sell Signals
Buy: Stoch %K cross above %D below 20
Sell: Stoch %K cross below %D above 80
✅ How to Use
Trade in direction of histogram strength
Exit / reduce position when yellow appears → possible reversal
Confirm with Stoch cross + EMA direction
✅ Best Use Cases
Trend continuation and fade detection
Early reversal warning
Overbought/oversold decision zones
HIPA - High IRL Probability Areas [Pro]Overview
HIPA (High IRL Probability Areas) visualizes statistically derived Internal Range Liquidity (IRL) zones — price areas that have historically shown a higher tendency for revisit or interaction within an intraday session.
When a candle breaks a higher-timeframe reference bar’s high or low, HIPA plots a draw line at the opposite extreme of that bar, highlighting where liquidity is most likely to rest.
Each line displays a live, time-conditioned probability (CH) of being revisited before session end, plus an optional End-of-Day (EOD) probability.
HIPA provides statistical context on how current price interacts with prior structural ranges. It does not issue trade signals or forecasts.
Key Features
• Tracks higher-timeframe reference bars across the session.
• Plots draw lines at the opposite extreme once a break occurs.
• Displays dynamic CH and optional EOD probabilities derived from embedded historical statistics.
• Tested lines change style once price interacts; expired levels are automatically removed.
• Fully customizable palette, text size, and visibility options.
Signal Area Context
HIPA includes an optional Signal Area overlay that blends IRL probabilities with higher-timeframe (HTF) structure.
You can reference candle highs/lows or pivots from selected HTF intervals and display a subtle gradient between these external liquidity points and active IRL zones.
The shaded area is intended to help visualize where intraday behavior aligns with multi-timeframe liquidity zones — not to produce entries or exits.
Traders may use it to study how price develops around these confluence regions.
Methodology (transparency)
HIPA uses embedded statistical references derived from long-term historical market behavior to estimate revisit probabilities conditioned by time-of-day and break direction.
These references are stored directly within the script for deterministic plotting — no external data is fetched or required.
Session data is internally organized into consistent time segments to reflect how revisit tendencies vary through the day.
HIPA is descriptive: it visualizes empirically observed behavior, not predictive outcomes.
How to Use
- Apply HIPA to any intraday chart.
- Observe when price breaks a higher-timeframe candle’s high or low — a draw line appears at the opposite extreme with CH/EOD labels.
- Optionally enable the Signal Area to visualize overlap between HTF liquidity and current IRL zones.
- Use HIPA as structural and statistical context only; combine with your own framework for decision-making.
- Treat draw lines and gradients as reference areas rather than precise trade levels.
Notes
• Historical behavior can evolve under different market conditions.
• CH/EOD probabilities adjust with session time; interpret contextually.
• Rendering many lines simultaneously may affect performance — enable pruning if needed.
• Works on any symbol or timeframe supported by TradingView.
Disclaimers
Educational use only. Past performance does not guarantee future results.
HIPA visualizes statistical context based on historical behavior and does not predict or recommend trades.
ATR Position SizerFound the substack from Ryan Wright (raen prop trading) which has amazing insights into the real prop trading world.
In his post Your Trading Edge Isn't Your Setup . It's Your Knowledge he shared a few interesting nuggets of knowledge.
Especially the part about Risk according to the 20-day ATR caught my eye, so i reconstructed a version of that formula directly for Tradingview. It works with ES (MES), NQ (MNQ), GC (MGC), YM and can be extended.
Additionally I implemented a function that tracks the chart ATR (automatically on the chosen time frame) on a defined period. This can of course be disable.
Hope it helps
JiNFOJiNFO is a clean, data-driven overlay that displays key information about the current symbol directly on your chart — without clutter.
🧭 What it shows
Company & Symbol Info – Name, ticker, sector, industry, market cap
Timeframe Label – Current chart timeframe (auto-formatted)
ATR (14) & % Volatility – With color dots for low 🟢 / medium 🟡 / high 🔴 volatility
Moving Average Status – Indicates if price is above or below the selected MA (default 150)
RSI & RSI-SMA (14) – Compact line with live values and color dot for overbought/neutral/oversold zones
Distance from SMA (50) – Shows how far price is from the 50 MA (+/- %) and grades it A–D by distance 🟢🟠🔴
Earnings Countdown – Days remaining until the next earnings date (if available)
⚙️ Customization
Position (top/middle/bottom, left/center/right)
Text size (default Small), color, opacity (100 %)
Toggle any data row on or off
Choose compact or verbose labels
🧩 Purpose
JiNFO replaces bulky data panels with a lightweight, transparent information layer — perfect for traders who want essential fundamentals, volatility, and technical context at a glance.
Custom Horizontal Lines | Trade Symmetry📊 Custom Horizontal Lines
🔍 Overview
The Custom Horizontal Lines is a precision utility designed for traders who perform manual higher-timeframe analysis and want to preserve their marked price levels directly on the chart.
It doesn’t calculate or detect anything automatically — instead, it acts as your personal level memory, preserving your analyzed zones and reference prices throughout the session.
Ideal for traders who manually mark the High, Low, Open, Close, Mean Thresholds, and Quarter Levels of Order Blocks, Fair Value Gaps, Inversion Fair Value Gaps and Wicks before the trading day begins.
⚙️ Key Features
✅ Manual Level Entry — Input your analyzed price levels (OB, FVG, WICK,etc) directly into the indicator settings.
✅ Preserved Levels — Once entered, your lines stay visible and consistent — even after switching symbols, timeframes, or reloading the chart.
✅ Supports All Level Types — Store any kind of manually defined level: OB highs/lows, FVG boundaries, Wicks, Mean Thresholds, Quarter levels, or custom reference prices.
✅ Clean Visualization — Customize line color, style, and labels for easy visual organization.
✅ Session-Ready Workflow — Built for pre-market preparation — enter your HTF levels once, and trade around them all day.
✅ No Auto Calculations — 100% manual by design — ensuring only your analyzed levels are shown, exactly as you defined them.
💡 How to Use
Open the indicator’s settings and manually enter those price values.
The indicator will plot and preserve those exact levels on your chart.
Switch to your lower timeframe and observe how price reacts around them — without ever needing to redraw.
🎯 Why It’s Useful
Keeps your HTF levels organized and persistent across sessions.
Saves time by avoiding redrawing.
Fits perfectly into ICT / Smart Money trading workflows.
Ensures full manual control and precision over what’s displayed on your chart.
🧩 Ideal For
ICT and Smart Money traders
Institutional-style manual analysts
Traders marking Mean Thresholds, or Quarter Levels of OBs, FVGs, Wicks etc
Anyone who wants a clean, reliable way to preserve their manual analysis
NSE Pairs Screener-20 pair This advanced Pine Script screener is designed for pairs trading on the National Stock Exchange (NSE) of India. It simultaneously monitors up to 20 stock pairs, calculates key statistical metrics, and provides real-time trading signals based on mean reversion strategies.
Key Features
1. Multi-Pair Analysis
Monitor up to 20 stock pairs simultaneously
Customizable number of pairs to display (1-20)
Pre-configured with popular NSE stock pairs across various sectors
2. Statistical Calculations
Correlation Analysis: Measures the strength of relationship between paired stocks
Z-Score Calculation: Identifies extreme deviations from the mean spread
Cointegration Score: Validates long-term equilibrium relationships
Dynamic Hedge Ratio: Calculates optimal position sizing between pairs
3. Trading Signals
Long Signal: When spread is oversold (Z-score ≤ -2.0)
Short Signal: When spread is overbought (Z-score ≥ 2.0)
Exit Signal: When spread returns to mean (Z-score ≤ 0.5)
Watch Status: Pairs requiring monitoring
4. Automated Alert System
Single comprehensive alert for all qualifying pairs
Customizable alert thresholds for correlation, Z-score, and cointegration
On-chart visual alerts with detailed information
Notification support via TradingView's alert system
5. Visual Display
Clean, color-coded table interface
Adjustable table position (9 positions available)
Highlighted trading opportunities
Real-time metric updates
Configuration Parameters
Screener Settings
Number of Pairs to Display: 1-20 pairs (default: 20)
Calculation Parameters
Parameter Default Range Description Correlation Lookback Period25220-500Historical period for correlation calculation Z-Score SMA Length205-100Moving average length for spread calculation Hedge Ratio Length205-100Period for hedge ratio smoothing Minimum Correlation0.70.5-1.0Threshold for pair validation
Alert Settings
Parameter Default Range Description Alert Correlation Threshold0.70.5-1.0Minimum correlation for alerts Alert Z-Score Threshold2.01.0-3.0Z-score trigger level Alert Cointegration Threshold90%80-99%Minimum cointegration percentage
Display Settings
Table Position: 9 position options (default: middle_center)
Table Background Color: Customizable
Highlight Opportunities: Toggle visual highlighting of trading signals
Pre-Configured Stock Pairs
The script includes 20 carefully selected NSE pairs across various sectors:
Financial Services
RELIANCE / ONGC
HDFCBANK / ICICIBANK
SBIN / PNB
KOTAKBANK / AXISBANK
BAJFINANCE / BAJAJFINSV
Information Technology
TCS / INFY
WIPRO / HCLTECH
TECHM / LTIM
Consumer Goods
ITC / HINDUNILVR
TITAN / TANLA
ASIANPAINT / BERGEPAINT
Telecommunications
BHARTIARTL / IDEA
Automotive
MARUTI / TATAMOTORS
Infrastructure & Industrials
LT / UBL
POWERGRID / NTPC
Pharmaceuticals
SUNPHARMA / CIPLA
DIVISLAB / DRREDDY
Materials
ULTRACEMCO / ACC
UPL / JSWSTEEL
Energy
ADANIENT / ADANIPOWER
🎨 Color-Coded Metrics
Correlation
🟢 Green: ≥ Minimum threshold (strong relationship)
🔴 Red: < Minimum threshold (weak relationship)
Z-Score
🔴 Red: |Z| ≥ 2.0 (extreme deviation - trading opportunity)
🟡 Yellow: 0.5 < |Z| < 2.0 (normal range - watch)
🟢 Green: |Z| ≤ 0.5 (mean reversion - exit signal)
Cointegration
🟢 Green: ≥ 70% (strong cointegration)
🟡 Yellow: 50-70% (moderate cointegration)
🔴 Red: < 50% (weak cointegration)
Status
🟢 Green: Long (buy spread)
🔴 Red: Short (sell spread)
🔵 Blue: Exit (close positions)
⚪ Gray: Watch (monitor)
Validation
🟢 Green: Pass (meets all criteria)
🔴 Red: Fail (doesn't meet criteria)
How It Works
1. Data Collection
The script fetches real-time closing prices for all 20 stock pairs from NSE.
2. Statistical Analysis
For each pair, the script calculates:
Log Returns: Natural logarithm of price changes
Correlation: Pearson correlation coefficient between returns
Hedge Ratio: Price ratio smoothed over specified period
Spread: Price difference adjusted by hedge ratio
Z-Score: Standardized spread deviation
3. Signal Generation
Based on Z-score thresholds:
Z ≥ 2.0: Short spread (short overvalued, long undervalued)
Z ≤ -2.0: Long spread (long overvalued, short undervalued)
|Z| ≤ 0.5: Exit positions (spread reverted to mean)
4. Validation
Pairs must meet criteria:
Correlation ≥ minimum threshold
Valid trading signal (entry or exit)
5. Alert Triggering
Alerts fire when pairs simultaneously meet:
Correlation ≥ alert threshold
|Z-score| ≥ alert threshold
Cointegration ≥ alert threshold
Alert System
The script features a single comprehensive alert that monitors all pairs:
Consolidated Notifications: One alert for all qualifying pairs
Detailed Information: Includes pair names, signal type, and key metrics
Visual Indicators: Red label on chart with complete details
Customizable Thresholds: Adjust sensitivity based on trading style
Alert Message Format
PAIR TRADING OPPORTUNITIES
Pair X: STOCK1/STOCK2
Signal: LONG/SHORT Spread
Z-Score: X.XX
Correlation: X.XXX
Cointegration: XX.X%
Trading Strategy Guide
Entry Rules
Long Spread (Z-score ≤ -2.0):
Buy Stock Y
Sell Stock X (in ratio of hedge ratio)
Short Spread (Z-score ≥ 2.0):
Sell Stock Y
Buy Stock X (in ratio of hedge ratio)
Exit Rules
Close positions when Z-score returns to ±0.5
Set stop-loss at Z-score ±3.0 (extreme deviations)
Risk Management
Only trade pairs with correlation ≥ 0.7
Prefer cointegration scores ≥ 90%
Monitor hedge ratio changes
Diversify across multiple pairs
Customization Options
Adding New Pairs
Simply modify the stock symbol inputs in the respective pair groups (Pair 1 through Pair 20).
Adjusting Sensitivity
Conservative: Increase Z-score threshold to 2.5-3.0
Aggressive: Decrease Z-score threshold to 1.5-2.0
Long-term: Increase lookback period to 500
Short-term: Decrease lookback period to 50-100
Visual Preferences
Change table position to suit your layout
Adjust background colors for better contrast
Toggle opportunity highlighting on/off
Technical Notes
Calculation Method
Uses logarithmic returns for correlation (better statistical properties)
Z-score normalized by standard deviation
Cointegration approximated using correlation strength
Hedge ratio smoothed using simple moving average
Performance Considerations
Calculations update on every bar close
Table displays only on the last bar
Alert checks occur at bar close
Maximum 500 labels supported (more than sufficient)
Limitations
Does not account for transaction costs
Assumes linear relationships between pairs
Historical correlation doesn't guarantee future behaviour
Requires sufficient liquidity in both stocks
Best Practices
Back test Thoroughly: Test parameters on historical data before live trading
Monitor Regularly: Check pairs daily for validation changes
Diversify: Trade multiple pairs to reduce risk
Stay Informed: Be aware of corporate actions, news affecting pairs
Adjust Parameters: Optimize for current market conditions
Use Stop-Losses: Protect against extreme divergences
Track Performance: Maintain trading journal for continuous improvement
Indicator Information
Version: Pine Script v5
Overlay: False (separate pane)
Max Labels: 500
Update Frequency: Every bar close
Compatible Timeframes: All (works best on daily or higher)
Getting Started
Add to Chart: Apply indicator to any NSE stock
Configure Pairs: Adjust stock symbols as needed
Set Parameters: Customize calculation and alert settings
Create Alert: Set up Trading View alert for notifications
Monitor: Watch the table for trading opportunities
Execute: Trade based on validated signals
📞Support & Updates
This script is designed for educational and research purposes. Always:
Conduct thorough back testing
Use proper risk management
Consider transaction costs
Consult with financial advisors
Trade responsibly
Disclaimer: This indicator is for educational purposes only. Past performance does not guarantee future results. Always conduct your own research and risk assessment before trading.
Time & Sales , Volume Delta and CVD, Volume imbalance , Tick
This Pine Script (version 6) creates a comprehensive TradingView indicator combining Time & Sales (Tape) with Volume Delta, Order Flow Pressure Indicator (OFPI), Volume Imbalance detection, Volume Delta (VD) histogram, Cumulative Volume Delta (CVD), TICK.US histogram, and a summary gauge table. It overlays on the chart with customizable tables, boxes, lines, and labels for real-time trade analysis, momentum, imbalances, and volume metrics.
Key Features and Components:
Time & Sales Table: A dynamic table showing recent trades (up to user-defined rows). Columns include Time, Side (▲/▼), Last Price, Volume (or Price-Weighted Volume). Trades below a volume threshold are hidden. Includes a buy/sell scale bar with percentages. Supports timeframe-based or live tick data fetching.
OFPI with Gauge: Calculates net aggressive volume pressure using bar body position, smoothed with T3 moving average. Displays a centered gauge bar (e.g., "░░░|███░░") indicating bullish/bearish momentum or shifts.
Volume Imbalance (VI): Detects bullish/bearish gaps between bars. Draws semi-transparent boxes with labels (e.g., "5 tks (vi)") for imbalances or gaps. Limits display to a max number, removes filled ones, and uses magnets (🧲) for gaps.
Volume Delta (VD): Approximates buy/sell delta via intrabar pressure or polarity. Displays as unipolar/bipolar histogram, optionally overlapping with regular volume or TICK.US. Shows numerical values (green/red/orange for divergences) and price/VD divergences.
Cumulative Volume Delta (CVD): Cumulates VD, reset on anchor timeframe (e.g., daily). Displays as line, area, baseline, or candles. Includes optional EMA smoothing and background fills. Detects divergences with price.
TICK.US Histogram: Overlays US Tick index (from symbol "TICK.US") as positive/negative bars during US market hours (9:30-16:00 ET, Mon-Fri). Replaces regular volume in some modes.
Gauge Summary Table: Bottom-left table with momentum text, OFPI gauge, CVD value, current Tick, and last bar's volume breakdown (total/buy/sell/delta).
Customization Options:
General: Timezone, date format, table position/size, colors (gradients for up/down), calculation mode (timeframe/live tick), volume type (volume/price-volume), thresholds, lengths (e.g., lookback, smoothing).
Display: Heights/offsets for histograms, line widths/styles, transparencies, label sizes/alignments, divergences, MA on volume, CVD smoothing/background.
Technical: Lower timeframe precision (auto or custom), anchor for CVD reset, max VIs to show.
Other: Toggles for VI, TICK.US, numerical values, divergences.
Credit
// FuturesCall @ fcalgobot.com
//Time & Sales (Tape)
// CVD base on Luxalgo CVD indicator
// Momentum Gauge by DskyzInvestments
// volume imbalance by ...
Manifold Singularity EngineManifold Singularity Engine: Catastrophe Theory Detection Through Multi-Dimensional Topology Analysis
The Manifold Singularity Engine applies catastrophe theory from mathematical topology to multi-dimensional price space analysis, identifying potential reversal conditions by measuring manifold curvature, topological complexity, and fractal regime states. Unlike traditional reversal indicators that rely on price pattern recognition or momentum oscillators, this system reconstructs the underlying geometric surface (manifold) that price evolves upon and detects points where this topology undergoes catastrophic folding—mathematical singularities that correspond to forced directional changes in price dynamics.
The indicator combines three analytical frameworks: phase space reconstruction that embeds price data into a multi-dimensional coordinate system, catastrophe detection that measures when this embedded manifold reaches critical curvature thresholds indicating topology breaks, and Hurst exponent calculation that classifies the current fractal regime to adaptively weight detection sensitivity. This creates a geometry-based reversal detection system with visual feedback showing topology state, manifold distortion fields, and directional probability projections.
What Makes This Approach Different
Phase Space Embedding Construction
The core analytical method reconstructs price evolution as movement through a three-dimensional coordinate system rather than analyzing price as a one-dimensional time series. The system calculates normalized embedding coordinates: X = normalize(price_velocity, window) , Y = normalize(momentum_acceleration, window) , and Z = normalize(volume_weighted_returns, window) . These coordinates create a trajectory through phase space where price movement traces a path across a geometric surface—the market manifold.
This embedding approach differs fundamentally from traditional technical analysis by treating price not as a sequential data stream but as a dynamical system evolving on a curved surface in multi-dimensional space. The trajectory's geometric properties (curvature, complexity, folding) contain information about impending directional changes that single-dimension analysis cannot capture. When this manifold undergoes rapid topological deformation, price must respond with directional change—this is the mathematical basis for catastrophe detection.
Statistical normalization using z-score transformation (subtracting mean, dividing by standard deviation over a rolling window) ensures the coordinate system remains scale-invariant across different instruments and volatility regimes, allowing identical detection logic to function on forex, crypto, stocks, or indices without recalibration.
Catastrophe Score Calculation
The catastrophe detection formula implements a composite anomaly measurement combining multiple topology metrics: Catastrophe_Score = 0.45×Curvature_Percentile + 0.25×Complexity_Ratio + 0.20×Condition_Percentile + 0.10×Gradient_Percentile . Each component measures a distinct aspect of manifold distortion:
Curvature (κ) is computed using the discrete Laplacian operator: κ = √ , which measures how sharply the manifold surface bends at the current point. High curvature values indicate the surface is folding or developing a sharp corner—geometric precursors to catastrophic topology breaks. The Laplacian measures second derivatives (rate of change of rate of change), capturing acceleration in the trajectory's path through phase space.
Topological Complexity counts sign changes in the curvature field over the embedding window, measuring how chaotically the manifold twists and oscillates. A smooth, stable surface produces low complexity; a highly contorted, unstable surface produces high complexity. This metric detects when the geometric structure becomes informationally dense with multiple local extrema, suggesting an imminent topology simplification event (catastrophe).
Condition Number measures the Jacobian matrix's sensitivity: Condition = |Trace| / |Determinant|, where the Jacobian describes how small changes in price produce changes in the embedding coordinates. High condition numbers indicate numerical instability—points where the coordinate transformation becomes ill-conditioned, suggesting the manifold mapping is approaching a singularity.
Each metric is converted to percentile rank within a rolling window, then combined using weighted sum. The percentile transformation creates adaptive thresholds that automatically adjust to each instrument's characteristic topology without manual recalibration. The resulting 0-100% catastrophe score represents the current bar's position in the distribution of historical manifold distortion—values above the threshold (default 65%) indicate statistically extreme topology states where reversals become geometrically probable.
This multi-metric ensemble approach prevents false signals from isolated anomalies: all four geometric features must simultaneously indicate distortion for a high catastrophe score, ensuring only true manifold breaks trigger detection.
Hurst Exponent Regime Classification
The Hurst exponent calculation implements rescaled range (R/S) analysis to measure the fractal dimension of price returns: H = log(R/S) / log(n) , where R is the range of cumulative deviations from mean and S is the standard deviation. The resulting value classifies market behavior into three fractal regimes:
Trending Regime (H > 0.55) : Persistent price movement where future changes are positively correlated with past changes. The manifold exhibits directional momentum with smooth topology evolution. In this regime, catastrophe signals receive 1.2× confidence multiplier because manifold breaks in trending conditions produce high-magnitude directional changes.
Mean-Reverting Regime (H < 0.45) : Anti-persistent price movement where future changes tend to oppose past changes. The manifold exhibits oscillatory topology with frequent small-scale distortions. Catastrophe signals receive 0.8× confidence multiplier because reversal significance is diminished in choppy conditions where the manifold constantly folds at minor scales.
Random Walk Regime (H ≈ 0.50) : No statistical correlation in returns. The manifold evolution is geometrically neutral with moderate topology stability. Standard 1.0× confidence multiplier applies.
This adaptive weighting system solves a critical problem in reversal detection: the same geometric catastrophe has different trading implications depending on the fractal regime. A manifold fold in a strong trend suggests a significant reversal opportunity; the same fold in mean-reversion suggests a minor oscillation. The Hurst-based regime filter ensures detection sensitivity automatically adjusts to market character without requiring trader intervention.
The implementation uses logarithmic price returns rather than raw prices to ensure
stationarity, and applies the calculation over a configurable window (default 5 bars) to balance responsiveness with statistical validity. The Hurst value is then smoothed using exponential moving average to reduce noise while maintaining regime transition detection.
Multi-Layer Confirmation Architecture
The system implements five independent confirmation filters that must simultaneously validate
before any singularity signal generates:
1. Catastrophe Threshold : The composite anomaly score must exceed the configured threshold (default 0.65 on 0-1 scale), ensuring the manifold distortion is statistically extreme relative to recent history.
2. Pivot Structure Confirmation : Traditional swing high/low patterns (using ta.pivothigh and ta.pivotlow with configurable lookback) must form at the catastrophe bar. This ensures the geometric singularity coincides with observable price structure rather than occurring mid-swing where interpretation is ambiguous.
3. Swing Size Validation : The pivot magnitude must exceed a minimum threshold measured in ATR units (default 1.5× Average True Range). This filter prevents signals on insignificant price jiggles that lack meaningful reversal potential, ensuring only substantial swings with adequate risk/reward ratios generate signals.
4. Volume Confirmation : Current volume must exceed 1.3× the 20-period moving average, confirming genuine market participation rather than low-liquidity price noise. Manifold catastrophes without volume support often represent false topology breaks that don't translate to sustained directional change.
5. Regime Validity : The market must be classified as either trending (ADX > configured threshold, default 30) or volatile (ATR expansion > configured threshold, default 40% above 30-bar average), and must NOT be in choppy/ranging state. This critical filter prevents trading during geometrically unfavorable conditions where edge deteriorates.
All five conditions must evaluate true simultaneously for a signal to generate. This conjunction-based logic (AND not OR) dramatically reduces false positives while preserving true reversal detection. The architecture recognizes that geometric catastrophes occur frequently in noisy data, but only those catastrophes that align with confirming evidence across price structure, participation, and regime characteristics represent tradable opportunities.
A cooldown mechanism (default 8 bars between signals) prevents signal clustering at extended pivot zones where the manifold may undergo multiple small catastrophes during a single reversal process.
Direction Classification System
Unlike binary bull/bear systems, the indicator implements a voting mechanism combining four
directional indicators to classify each catastrophe:
Pivot Vote : +1 if pivot low, -1 if pivot high, 0 otherwise
Trend Vote : Based on slow frequency (55-period EMA) slope—+1 if rising, -1 if falling, 0 if flat
Flow Vote : Based on Y-gradient (momentum acceleration)—+1 if positive, -1 if negative, 0 if neutral
Mid-Band Vote : Based on price position relative to medium frequency (21-period EMA)—+1 if above, -1 if below, 0 if at
The total vote sum classifies the singularity: ≥2 votes = Bullish , ≤-2 votes = Bearish , -1 to +1 votes = Neutral (skip) . This majority-consensus approach ensures directional classification requires alignment across multiple timeframes and analysis dimensions rather than relying on a single indicator. Neutral signals (mixed voting) are displayed but should not be traded, as they represent geometric catastrophes without clear directional resolution.
Core Calculation Methodology
Embedding Coordinate Generation
Three normalized phase space coordinates are constructed from price data:
X-Dimension (Velocity Space):
price_velocity = close - close
X = (price_velocity - mean) / stdev over hurstWindow
Y-Dimension (Acceleration Space):
momentum = close - close
momentum_accel = momentum - momentum
Y = (momentum_accel - mean) / stdev over hurstWindow
Z-Dimension (Volume-Weighted Space):
vol_normalized = (volume - mean) / stdev over embedLength
roc = (close - close ) / close
Z = (roc × vol_normalized - mean) / stdev over hurstWindow
These coordinates define a point in 3D phase space for each bar. The trajectory connecting these points is the reconstructed manifold.
Gradient Field Calculation
First derivatives measure local manifold slope:
dX/dt = X - X
dY/dt = Y - Y
Gradient_Magnitude = √
The gradient direction indicates where the manifold is "pushing" price. Positive Y-gradient suggests upward topological pressure; negative Y-gradient suggests downward pressure.
Curvature Tensor Components
Second derivatives measure manifold bending using discrete Laplacian:
Laplacian_X = X - 2×X + X
Laplacian_Y = Y - 2×Y + Y
Laplacian_Magnitude = √
This is then normalized:
Curvature_Normalized = (Laplacian_Magnitude - mean) / stdev over embedLength
High normalized curvature (>1.5) indicates sharp manifold folding.
Complexity Accumulation
Sign changes in curvature field are counted:
Sign_Flip = 1 if sign(Curvature ) ≠ sign(Curvature ), else 0
Topological_Complexity = sum(Sign_Flip) over embedLength window
This measures oscillation frequency in the geometry. Complexity >5 indicates chaotic topology.
Condition Number Stability Analysis
Jacobian matrix sensitivity is approximated:
dX/dp = dX/dt / (price_change + epsilon)
dY/dp = dY/dt / (price_change + epsilon)
Jacobian_Determinant = (dX/dt × dY/dp) - (dX/dp × dY/dt)
Jacobian_Trace = dX/dt + dY/dp
Condition_Number = |Trace| / (|Determinant| + epsilon)
High condition numbers indicate numerical instability near singularities.
Catastrophe Score Assembly
Each metric is converted to percentile rank over embedLength window, then combined:
Curvature_Percentile = percentrank(abs(Curvature_Normalized), embedLength)
Gradient_Percentile = percentrank(Gradient_Magnitude, embedLength)
Condition_Percentile = percentrank(abs(Condition_Z_Score), embedLength)
Complexity_Ratio = clamp(Topological_Complexity / embedLength, 0, 1)
Final score:
Raw_Anomaly = 0.45×Curvature_P + 0.25×Complexity_R + 0.20×Condition_P + 0.10×Gradient_P
Catastrophe_Score = Raw_Anomaly × Hurst_Multiplier
Values are clamped to range.
Hurst Exponent Calculation
Rescaled range analysis on log returns:
Calculate log returns: r = log(close) - log(close )
Compute cumulative deviations from mean
Find range: R = max(cumulative_dev) - min(cumulative_dev)
Calculate standard deviation: S = stdev(r, hurstWindow)
Compute R/S ratio
Hurst = log(R/S) / log(hurstWindow)
Clamp to and smooth with 5-period EMA
Regime Classification Logic
Volatility Regime:
ATR_MA = SMA(ATR(14), 30)
Vol_Expansion = ATR / ATR_MA
Is_Volatile = Vol_Expansion > (1.0 + minVolExpansion)
Trend Regime (Corrected ADX):
Calculate directional movement (DM+, DM-)
Smooth with Wilder's RMA(14)
Compute DI+ and DI- as percentages
Calculate DX = |DI+ - DI-| / (DI+ + DI-) × 100
ADX = RMA(DX, 14)
Is_Trending = ADX > (trendStrength × 100)
Chop Detection:
Is_Chopping = NOT Is_Trending AND NOT Is_Volatile
Regime Validity:
Regime_Valid = (Is_Trending OR Is_Volatile) AND NOT Is_Chopping
Signal Generation Logic
For each bar:
Check if catastrophe score > topologyStrength threshold
Verify regime is valid
Confirm Hurst alignment (trending or mean-reverting with pivot)
Validate pivot quality (price extended outside spectral bands then re-entered)
Confirm volume/volatility participation
Check cooldown period has elapsed
If all true: compute directional vote
If vote ≥2: Bullish Singularity
If vote ≤-2: Bearish Singularity
If -1 to +1: Neutral (display but skip)
All conditions must be true for signal generation.
Visual System Architecture
Spectral Decomposition Layers
Three harmonic frequency bands visualize entropy state:
Layer 1 (Surface Frequency):
Center: EMA(8)
Width: ±0.3 × 0.5 × ATR
Transparency: 75% (most visible)
Represents fast oscillations
Layer 2 (Mid Frequency):
Center: EMA(21)
Width: ±0.5 × 0.5 × ATR
Transparency: 85%
Represents medium cycles
Layer 3 (Deep Frequency):
Center: EMA(55)
Width: ±0.7 × 0.5 × ATR
Transparency: 92% (most transparent)
Represents slow baseline
Convergence of layers indicates low entropy (stable topology). Divergence indicates high entropy (catastrophe building). This decomposition reveals how different frequency components of price movement interact—when all three align, the manifold is in equilibrium; when they separate, topology is unstable.
Energy Radiance Fields
Concentric boxes emanate from each singularity bar:
For each singularity, 5 layers are generated:
Layer n: bar_index ± (n × 1.5 bars), close ± (n × 0.4 × ATR)
Transparency gradient: inner 75% → outer 95%
Color matches signal direction
These fields visualize the "energy well" of the catastrophe—wider fields indicate stronger topology distortion. The exponential expansion creates a natural radiance effect.
Singularity Node Geometry
N-sided polygon (default hexagon) at each signal bar:
Vertices calculated using polar coordinates
Rotation angle: bar_index × 0.1 (creates animation)
Radius: ATR × singularity_strength × 2
Connects vertices with colored lines
The rotating geometric primitive marks the exact catastrophe bar with visual prominence.
Gradient Flow Field
Directional arrows display manifold slope:
Spawns every 3 bars when gradient_magnitude > 0.1
Symbol: "↗" if dY/dt > 0.1, "↘" if dY/dt < -0.1, "→" if neutral
Color: Bull/bear/neutral based on direction
Density limited to flowDensity parameter
Arrows cluster when gradient is strong, creating intuitive topology visualization.
Probability Projection Cones
Forward trajectory from each singularity:
Projects 10 bars forward
Direction based on vote classification
Center line: close + (direction × ATR × 3)
Uncertainty width: ATR × singularity_strength × 2
Dashed boundaries, solid center
These are mathematical projections based on current gradient, not price targets. They visualize expected manifold evolution if topology continues current trajectory.
Dashboard Metrics Explanation
The real-time control panel displays six core metrics plus regime status:
H (Hurst Exponent):
Value: Current Hurst (0-1 scale)
Label: TREND (>0.55), REVERT (<0.45), or RANDOM (0.45-0.55)
Icon: Direction arrow based on regime
Purpose: Shows fractal character—only trade when favorable
Σ (Catastrophe Score):
Value: Current composite anomaly (0-100%)
Bar gauge shows relative strength
Icon: ◆ if above threshold, ○ if below
Purpose: Primary signal strength indicator
κ (Curvature):
Value: Normalized Laplacian magnitude
Direction arrow shows sign
Color codes severity (green<0.8, yellow<1.5, red≥1.5)
Purpose: Shows manifold bending intensity
⟳ (Topology Complexity):
Value: Count of sign flips in curvature
Icon: ◆ if >3, ○ otherwise
Color codes chaos level
Purpose: Indicates geometric instability
V (Volatility Expansion):
Value: ATR expansion percentage above 30-bar average
Icon: ● if volatile, ○ otherwise
Purpose: Confirms energy present for reversal
T (Trend Strength):
Value: ADX reading (0-100)
Icon: ● if trending, ○ otherwise
Purpose: Shows directional bias strength
R (Regime):
Label: EXPLOSIVE / TREND / VOLATILE / CHOP / NEUTRAL
Icon: ✓ if valid, ✗ if invalid
Purpose: Go/no-go filter for trading
STATE (Bottom Display):
Shows: "◆ BULL SINGULARITY" (green), "◆ BEAR SINGULARITY" (red), "◆ WEAK/NEUTRAL" (orange), or "— Monitoring —" (gray)
Purpose: Current signal status at a glance
How to Use This Indicator
Initial Setup and Configuration
Apply the indicator to your chart with default settings as a starting point. The default parameters (21-bar embedding, 5-bar Hurst window, 2.5σ singularity threshold, 0.65 topology confirmation) are optimized for balanced detection across most instruments and timeframes. For very fast markets (scalping crypto, 1-5min charts), consider reducing embedding depth to 13-15 bars and Hurst window to 3 bars for more responsive detection. For slower markets (swing trading stocks, 4H-Daily charts), increase embedding depth to 34-55 bars and Hurst window to 8-10 bars for more stable topology measurement.
Enable the dashboard (top right recommended) to monitor real-time metrics. The control panel is your primary decision interface—glancing at the dashboard should instantly communicate whether conditions favor trading and what the current topology state is. Position and size the dashboard to remain visible but not obscure price action.
Enable regime filtering (strongly recommended) to prevent trading during choppy/ranging conditions where geometric edge deteriorates. This single setting can dramatically improve overall performance by eliminating low-probability environments.
Reading Dashboard Metrics for Trade Readiness
Before considering any trade, verify the dashboard shows favorable conditions:
Hurst (H) Check:
The Hurst Exponent reading is your first filter. Only consider trades when H > 0.50 . Ideal conditions show H > 0.60 with "TREND" label—this indicates persistent directional price movement where manifold catastrophes produce significant reversals. When H < 0.45 (REVERT label), the market is mean-reverting and catastrophes represent minor oscillations rather than substantial pivots. Do not trade in mean-reverting regimes unless you're explicitly using range-bound strategies (which this indicator is not optimized for). When H ≈ 0.50 (RANDOM label), edge is neutral—acceptable but not ideal.
Catastrophe (Σ) Monitoring:
Watch the Σ percentage build over time. Readings consistently below 50% indicate stable topology with no imminent reversals. When Σ rises above 60-65%, manifold distortion is approaching critical levels. Signals only fire when Σ exceeds the configured threshold (default 65%), so this metric pre-warns you of potential upcoming catastrophes. High-conviction setups show Σ > 75%.
Regime (R) Validation:
The regime classification must read TREND, VOLATILE, or EXPLOSIVE—never trade when it reads CHOP or NEUTRAL. The checkmark (✓) must be present in the regime cell for trading conditions to be valid. If you see an X (✗), skip all signals until regime improves. This filter alone eliminates most losing trades by avoiding geometrically unfavorable environments.
Combined High-Conviction Profile:
The strongest trading opportunities show simultaneously:
H > 0.60 (strong trending regime)
Σ > 75% (extreme topology distortion)
R = EXPLOSIVE or TREND with ✓
κ (Curvature) > 1.5 (sharp manifold fold)
⟳ (Complexity) > 4 (chaotic geometry)
V (Volatility) showing elevated ATR expansion
When all metrics align in this configuration, the manifold is undergoing severe distortion in a favorable fractal regime—these represent maximum-conviction reversal opportunities.
Signal Interpretation and Entry Logic
Bullish Singularity (▲ Green Triangle Below Bar):
This marker appears when the system detects a manifold catastrophe at a price low with bullish directional consensus. All five confirmation filters have aligned: topology score exceeded threshold, pivot low structure formed, swing size was significant, volume/volatility confirmed participation, and regime was valid. The green color indicates the directional vote totaled +2 or higher (majority bullish).
Trading Approach: Consider long entry on the bar immediately following the signal (bar after the triangle). The singularity bar itself is where the geometric catastrophe occurred—entering after allows you to see if price confirms the reversal. Place stop loss below the singularity bar's low (with buffer of 0.5-1.0 ATR for volatility). Initial target can be the previous swing high, or use the probability cone projection as a guide (though not a guarantee). Monitor the dashboard STATE—if it flips to "◆ BEAR SINGULARITY" or Hurst drops significantly, consider exiting even if target not reached.
Bearish Singularity (▼ Red Triangle Above Bar):
This marker appears when the system detects a manifold catastrophe at a price high with bearish directional consensus. Same five-filter confirmation process as bullish signals. The red color indicates directional vote totaled -2 or lower (majority bearish).
Trading Approach: Consider short entry on the bar following the signal. Place stop loss above the singularity bar's high (with buffer). Target previous swing low or use cone projection as reference. Exit if opposite signal fires or Hurst deteriorates.
Neutral Signal (● Orange Circle at Price Level):
This marker indicates the catastrophe detection system identified a topology break that passed catastrophe threshold and regime filters, but the directional voting system produced a mixed result (vote between -1 and +1). This means the four directional components (pivot, trend, flow, mid-band) are not in agreement about which way the reversal should resolve.
Trading Approach: Skip these signals. Neutral markers are displayed for analytical completeness but should not be traded. They represent geometric catastrophes without clear directional resolution—essentially, the manifold is breaking but the direction of the break is ambiguous. Trading neutral signals dramatically increases false signal rate. Only trade green (bullish) or red (bearish) singularities.
Visual Confirmation Using Spectral Layers
The three colored ribbons (spectral decomposition layers) provide entropy visualization that helps confirm signal quality:
Divergent Layers (High Entropy State):
When the three frequency bands (fast 8-period, medium 21-period, slow 55-period) are separated with significant gaps between them, the manifold is in high entropy state—different frequency components of price movement are pulling in different directions. This geometric tension precedes catastrophes. Strong signals often occur when layers are divergent before the signal, then begin reconverging immediately after.
Convergent Layers (Low Entropy State):
When all three ribbons are tightly clustered or overlapping, the manifold is in equilibrium—all frequency components agree. This stable geometry makes catastrophe detection more reliable because topology breaks clearly stand out against the baseline stability. If you see layers converge, then a singularity fires, then layers diverge, this pattern suggests a genuine regime transition.
Signal Quality Assessment:
High-quality singularity signals should show:
Divergent layers (high entropy) in the 5-10 bars before signal
Singularity bar occurs when price has extended outside at least one of the spectral bands (shows pivot extended beyond equilibrium)
Close of singularity bar re-enters the spectral band zone (shows mean reversion starting)
Layers begin reconverging in 3-5 bars after signal (shows new equilibrium forming)
This pattern visually confirms the geometric narrative: manifold became unstable (divergence), reached critical distortion (extended outside equilibrium), broke catastrophically (singularity), and is now stabilizing in new direction (reconvergence).
Using Energy Fields for Trade Management
The concentric glowing boxes around each singularity visualize the topology distortion
magnitude:
Wide Energy Fields (5+ Layers Visible):
Large radiance indicates strong catastrophe with high manifold curvature. These represent significant topology breaks and typically precede larger price moves. Wide fields justify wider profit targets and longer hold times. The outer edge of the largest box can serve as a dynamic support/resistance zone—price often respects these geometric boundaries.
Narrow Energy Fields (2-3 Layers):
Smaller radiance indicates moderate catastrophe. While still valid signals (all filters passed), expect smaller follow-through. Use tighter profit targets and be prepared for quicker exit if momentum doesn't develop. These are valid but lower-conviction trades.
Field Interaction Zones:
When energy fields from consecutive signals overlap or touch, this indicates a prolonged topology distortion region—often corresponds to consolidation zones or complex reversal patterns (head-and-shoulders, double tops/bottoms). Be more cautious in these areas as the manifold is undergoing extended restructuring rather than a clean catastrophe.
Probability Cone Projections
The dashed cone extending forward from each singularity is a mathematical projection, not a
price target:
Cone Direction:
The center line direction (upward for bullish, downward for bearish, flat for neutral) shows the expected trajectory based on current manifold gradient and singularity direction. This is where the topology suggests price "should" go if the catastrophe completes normally.
Cone Width:
The uncertainty band (upper and lower dashed boundaries) represents the range of outcomes given current volatility (ATR-based). Wider cones indicate higher uncertainty—expect more price volatility even if direction is correct. Narrower cones suggest more constrained movement.
Price-Cone Interaction:
Price following near the center line = catastrophe resolving as expected, geometric projection accurate
Price breaking above upper cone = stronger-than-expected reversal, consider holding for larger targets
Price breaking below lower cone (for bullish signal) = catastrophe failing, manifold may be re-folding in opposite direction, consider exit
Price oscillating within cone = normal reversal process, hold position
The 10-bar projection length means cones show expected behavior over the next ~10 bars. Don't confuse this with longer-term price targets.
Gradient Flow Field Interpretation
The directional arrows (↗, ↘, →) scattered across the chart show the manifold's Y-gradient (vertical acceleration dimension):
Upward Arrows (↗):
Positive Y-gradient indicates the momentum acceleration dimension is pushing upward—the manifold topology has upward "slope" at this location. Clusters of upward arrows suggest bullish topological pressure building. These often appear before bullish singularities fire.
Downward Arrows (↘):
Negative Y-gradient indicates downward topological pressure. Clusters precede bearish singularities.
Horizontal Arrows (→):
Neutral gradient indicates balanced topology with no strong directional pressure.
Using Flow Field:
The arrows provide real-time topology state information even between singularity signals. If you're in a long position from a bullish singularity and begin seeing increasing downward arrows appearing, this suggests manifold gradient is shifting—consider tightening stops. Conversely, if arrows remain upward or neutral, topology supports continuation.
Don't confuse arrow direction with immediate price direction—arrows show geometric slope, not price prediction. They're confirmatory context, not entry signals themselves.
Parameter Optimization for Your Trading Style
For Scalping / Fast Trading (1m-15m charts):
Embedding Depth: 13-15 bars (faster topology reconstruction)
Hurst Window: 3 bars (responsive fractal detection)
Singularity Threshold: 2.0-2.3σ (more sensitive)
Topology Confirmation: 0.55-0.60 (lower barrier)
Min Swing Size: 0.8-1.2 ATR (accepts smaller moves)
Pivot Lookback: 3-4 bars (quick pivot detection)
This configuration increases signal frequency for active trading but requires diligent monitoring as false signal rate increases. Use tighter stops.
For Day Trading / Standard Approach (15m-4H charts):
Keep default settings (21 embed, 5 Hurst, 2.5σ, 0.65 confirmation, 1.5 ATR, 5 pivot)
These are balanced for quality over quantity
Best win rate and risk/reward ratio
Recommended for most traders
For Swing Trading / Position Trading (4H-Daily charts):
Embedding Depth: 34-55 bars (stable long-term topology)
Hurst Window: 8-10 bars (smooth fractal measurement)
Singularity Threshold: 3.0-3.5σ (only extreme catastrophes)
Topology Confirmation: 0.75-0.85 (high conviction only)
Min Swing Size: 2.5-4.0 ATR (major moves only)
Pivot Lookback: 8-13 bars (confirmed swings)
This configuration produces infrequent but highly reliable signals suitable for position sizing and longer hold times.
Volatility Adaptation:
In extremely volatile instruments (crypto, penny stocks), increase Min Volatility Expansion to 0.6-0.8 to avoid over-signaling during "always volatile" conditions. In stable instruments (major forex pairs, blue-chip stocks), decrease to 0.3 to allow signals during moderate volatility spikes.
Trend vs Range Preference:
If you prefer trading only strong trends, increase Min Trend Strength to 0.5-0.6 (ADX > 50-60). If you're comfortable with volatility-based trading in weaker trends, decrease to 0.2 (ADX > 20). The default 0.3 balances both approaches.
Complete Trading Workflow Example
Step 1 - Pre-Session Setup:
Load chart with MSE indicator. Check dashboard position is visible. Verify regime filter is enabled. Review recent signals to gauge current instrument behavior.
Step 2 - Market Assessment:
Observe dashboard Hurst reading. If H < 0.45 (mean-reverting), consider skipping this session or using other strategies. If H > 0.50, proceed. Check regime shows TREND, VOLATILE, or EXPLOSIVE with checkmark—if CHOP, wait for regime shift alert.
Step 3 - Signal Wait:
Monitor catastrophe score (Σ). Watch for it climbing above 60%. Observe spectral layers—look for divergence building. If you see curvature (κ) rising above 1.0 and complexity (⟳) increasing, catastrophe is building. Do not anticipate—wait for the actual signal marker.
Step 4 - Signal Recognition:
▲ Bullish or ▼ Bearish triangle appears at a bar. Dashboard STATE changes to "◆ BULL/BEAR SINGULARITY". Energy field appears around the signal bar. Check signal quality:
Was Σ > 70% at signal? (Higher quality)
Are energy fields wide? (Stronger catastrophe)
Did layers diverge before and reconverge after? (Clean break)
Is Hurst still > 0.55? (Good regime)
Step 5 - Entry Decision:
If signal is green/red (not orange neutral), all confirmations look strong, and no immediate contradicting factors appear, prepare entry on next bar open. Wait for confirmation bar to form—ideally it should close in the signal direction (bullish signal → bar closes higher, bearish signal → bar closes lower).
Step 6 - Position Entry:
Enter at open or shortly after open of bar following signal bar. Set stop loss: for bullish signals, place stop at singularity_bar_low - (0.75 × ATR); for bearish signals, place stop at singularity_bar_high + (0.75 × ATR). The buffer accommodates volatility while protecting against catastrophe failure.
Step 7 - Trade Management:
Monitor dashboard continuously:
If Hurst drops below 0.45, consider reducing position
If opposite singularity fires, exit immediately (manifold has re-folded)
If catastrophe score drops below 40% and stays there, topology has stabilized—consider partial profit taking
Watch gradient flow arrows—if they shift to opposite direction persistently, tighten stops
Step 8 - Profit Taking:
Use probability cone as a guide—if price reaches outer cone boundary, consider taking partial profits. If price follows center line cleanly, hold for larger target. Traditional technical targets work well: previous swing high/low, round numbers, Fibonacci extensions. Don't expect precision—manifold projections give direction and magnitude estimates, not exact prices.
Step 9 - Exit:
Exit on: (a) opposite signal appears, (b) dashboard shows regime became invalid (checkmark changes to X), (c) technical target reached, (d) Hurst deteriorates significantly, (e) stop loss hit, or (f) time-based exit if using session limits. Never hold through opposite singularity signals—the manifold has broken in the other direction and your trade thesis is invalidated.
Step 10 - Post-Trade Review:
After exit, review: Did the probability cone projection align with actual price movement? Were the energy fields proportional to move size? Did spectral layers show expected reconvergence? Use these observations to calibrate your interpretation of signal quality over time.
Best Performance Conditions
This topology-based approach performs optimally in specific market environments:
Favorable Conditions:
Well-Developed Swing Structure: Markets with clear rhythm of advances and declines where pivots form at regular intervals. The manifold reconstruction depends on swing formation, so instruments that trend in clear waves work best. Stocks, major forex pairs during active sessions, and established crypto assets typically exhibit this characteristic.
Sufficient Volatility for Topology Development: The embedding process requires meaningful price movement to construct multi-dimensional coordinates. Extremely quiet markets (tight consolidations, holiday trading, after-hours) lack the volatility needed for manifold differentiation. Look for ATR expansion above average—when volatility is present, geometry becomes meaningful.
Trending with Periodic Reversals: The ideal environment is not pure trend (which rarely reverses) nor pure range (which reverses constantly at small scale), but rather trending behavior punctuated by occasional significant counter-trend reversals. This creates the catastrophe conditions the system is designed to detect: manifold building directional momentum, then undergoing sharp topology break at extremes.
Liquid Instruments Where EMAs Reflect True Flow: The spectral layers and frequency decomposition require that moving averages genuinely represent market consensus. Thinly traded instruments with sporadic orders don't create smooth manifold topology. Prefer instruments with consistent volume where EMA calculations reflect actual capital flow rather than random tick sequences.
Challenging Conditions:
Extremely Choppy / Whipsaw Markets: When price oscillates rapidly with no directional persistence (Hurst < 0.40), the manifold undergoes constant micro-catastrophes that don't translate to tradable reversals. The regime filter helps avoid these, but awareness is important. If you see multiple neutral signals clustering with no follow-through, market is too chaotic for this approach.
Very Low Volatility Consolidation: Tight ranges with ATR below average cause the embedding coordinates to compress into a small region of phase space, reducing geometric differentiation. The manifold becomes nearly flat, and catastrophe detection loses sensitivity. The regime filter's volatility component addresses this, but manually avoiding dead markets improves results.
Gap-Heavy Instruments: Stocks that gap frequently (opening outside previous close) create discontinuities in the manifold trajectory. The embedding process assumes continuous evolution, so gaps introduce artifacts. Most gaps don't invalidate the approach, but instruments with daily gaps >2% regularly may show degraded performance. Consider using higher timeframes (4H, Daily) where gaps are less proportionally significant.
Parabolic Moves / Blowoff Tops: When price enters an exponential acceleration phase (vertical rally or crash), the manifold evolves too rapidly for the standard embedding window to track. Catastrophe detection may lag or produce false signals mid-move. These conditions are rare but identifiable by Hurst > 0.75 combined with ATR expansion >2.0× average. If detected, consider sitting out or using very tight stops as geometry is in extreme distortion.
The system adapts by reducing signal frequency in poor conditions—if you notice long periods with no signals, the topology likely lacks the geometric structure needed for reliable catastrophe detection. This is a feature, not a bug: it prevents forced trading during unfavorable environments.
Theoretical Justification for Approach
Why Manifold Embedding?
Traditional technical analysis treats price as a one-dimensional time series: current price is predicted from past prices in sequential order. This approach ignores the structure of price dynamics—the relationships between velocity, acceleration, and participation that govern how price actually evolves.
Dynamical systems theory (from physics and mathematics) provides an alternative framework: treat price as a state variable in a multi-dimensional phase space. In this view, each market condition corresponds to a point in N-dimensional space, and market evolution is a trajectory through this space. The geometry of this space (its topology) constrains what trajectories are possible.
Manifold embedding reconstructs this hidden geometric structure from observable price data. By creating coordinates from velocity, momentum acceleration, and volume-weighted returns, we map price evolution onto a 3D surface. This surface—the manifold—reveals geometric relationships that aren't visible in price charts alone.
The mathematical theorem underlying this approach (Takens' Embedding Theorem from dynamical systems theory) proves that for deterministic or weakly stochastic systems, a state space reconstruction from time-delayed observations of a single variable captures the essential dynamics of the full system. We apply this principle: even though we only observe price, the embedded coordinates (derivatives of price) reconstruct the underlying dynamical structure.
Why Catastrophe Theory?
Catastrophe theory, developed by mathematician René Thom (Fields Medal 1958), describes how continuous systems can undergo sudden discontinuous changes when control parameters reach critical values. A classic example: gradually increasing force on a beam causes smooth bending, then sudden catastrophic buckling. The beam's geometry reaches a critical curvature where topology must break.
Markets exhibit analogous behavior: gradual price changes build tension in the manifold topology until critical distortion is reached, then abrupt directional change occurs (reversal). Catastrophes aren't random—they're mathematically necessary when geometric constraints are violated.
The indicator detects these geometric precursors: high curvature (manifold bending sharply), high complexity (topology oscillating chaotically), high condition number (coordinate mapping becoming singular). These metrics quantify how close the manifold is to a catastrophic fold. When all simultaneously reach extreme values, topology break is imminent.
This provides a logical foundation for reversal detection that doesn't rely on pattern recognition or historical correlation. We're measuring geometric properties that mathematically must change when systems reach critical states. This is why the approach works across different instruments and timeframes—the underlying geometry is universal.
Why Hurst Exponent?
Markets exhibit fractal behavior: patterns at different time scales show statistical self-similarity. The Hurst exponent quantifies this fractal structure by measuring long-range dependence in returns.
Critically for trading, Hurst determines whether recent price movement predicts future direction (H > 0.5) or predicts the opposite (H < 0.5). This is regime detection: trending vs mean-reverting behavior.
The same manifold catastrophe has different trading implications depending on regime. In trending regime (high Hurst), catastrophes represent significant reversal opportunities because the manifold has been building directional momentum that suddenly breaks. In mean-reverting regime (low Hurst), catastrophes represent minor oscillations because the manifold constantly folds at small scales.
By weighting catastrophe signals based on Hurst, the system adapts detection sensitivity to the current fractal regime. This is a form of meta-analysis: not just detecting geometric breaks, but evaluating whether those breaks are meaningful in the current fractal context.
Why Multi-Layer Confirmation?
Geometric anomalies occur frequently in noisy market data. Not every high-curvature point represents a tradable reversal—many are artifacts of microstructure noise, order flow imbalances, or low-liquidity ticks.
The five-filter confirmation system (catastrophe threshold, pivot structure, swing size, volume, regime) addresses this by requiring geometric anomalies to align with observable market evidence. This conjunction-based logic implements the principle: extraordinary claims require extraordinary evidence .
A manifold catastrophe (extraordinary geometric event) alone is not sufficient. We additionally require: price formed a pivot (visible structure), swing was significant (adequate magnitude), volume confirmed participation (capital backed the move), and regime was favorable (trending or volatile, not chopping). Only when all five dimensions agree do we have sufficient evidence that the geometric anomaly represents a genuine reversal opportunity rather than noise.
This multi-dimensional approach is analogous to medical diagnosis: no single test is conclusive, but when multiple independent tests all suggest the same condition, confidence increases dramatically. Each filter removes a different category of false signals, and their combination creates a robust detection system.
The result is a signal set with dramatically improved reliability compared to any single metric alone. This is the power of ensemble methods applied to geometric analysis.
Important Disclaimers
This indicator applies mathematical topology and catastrophe theory to multi-dimensional price space reconstruction. It identifies geometric conditions where manifold curvature, topological complexity, and coordinate singularities suggest potential reversal zones based on phase space analysis. It should not be used as a standalone trading system.
The embedding coordinates, catastrophe scores, and Hurst calculations are deterministic mathematical formulas applied to historical price data. These measurements describe current and recent geometric relationships in the reconstructed manifold but do not predict future price movements. Past geometric patterns and singularity markers do not guarantee future market behavior will follow similar topology evolution.
The manifold reconstruction assumes certain mathematical properties (sufficient embedding dimension, quasi-stationarity, continuous dynamics) that may not hold in all market conditions. Gaps, flash crashes, circuit breakers, news events, and other discontinuities can violate these assumptions. The system attempts to filter problematic conditions through regime classification, but cannot eliminate all edge cases.
The spectral decomposition, energy fields, and probability cones are visualization aids that represent mathematical constructs, not price predictions. The probability cone projects current gradient forward assuming topology continues current trajectory—this is a mathematical "if-then" statement, not a forecast. Market topology can and does change unexpectedly.
All trading involves substantial risk. The singularity markers represent analytical conditions where geometric mathematics align with threshold criteria, not certainty of directional change. Use appropriate risk management for every trade: position sizing based on account risk tolerance (typically 1-2% maximum risk per trade), stop losses placed beyond recent structure plus volatility buffer, and never risk capital needed for living expenses.
The confirmation filters (pivot, swing size, volume, regime) are designed to reduce false signals but cannot eliminate them entirely. Markets can produce geometric anomalies that pass all filters yet fail to develop into sustained reversals. This is inherent to probabilistic systems operating on noisy real-world data.
No indicator can guarantee profitable trades or eliminate losses. The catastrophe detection provides an analytical framework for identifying potential reversal conditions, but actual trading outcomes depend on numerous factors including execution, slippage, spreads, position sizing, risk management, psychological discipline, and market conditions that may change after signal generation.
Use this tool as one component of a comprehensive trading plan that includes multiple forms of analysis, proper risk management, emotional discipline, and realistic expectations about win rates and drawdowns. Combine catastrophe signals with additional confirmation methods such as support/resistance analysis, volume patterns, multi-timeframe alignment, and broader market context.
The spacing filter, cooldown mechanism, and regime validation are designed to reduce noise and over-signaling, but market conditions can change rapidly and render any analytical signal invalid. Always use stop losses and never risk capital you cannot afford to lose. Past performance of detection accuracy does not guarantee future results.
Technical Implementation Notes
All calculations execute on closed bars only—signals and metric values do not repaint after bar close. The indicator does not use any lookahead bias in its calculations. However, the pivot detection mechanism (ta.pivothigh and ta.pivotlow) inherently identifies pivots with a lag equal to the lookback parameter, meaning the actual pivot occurred at bar but is recognized at bar . This is standard behavior for pivot functions and is not repainting—once recognized, the pivot bar never changes.
The normalization system (z-score transformation over rolling windows) requires approximately 30-50 bars of historical data to establish stable statistics. Values in the first 30-50 bars after adding the indicator may show instability as the rolling means and standard deviations converge. Allow adequate warmup period before relying on signals.
The spectral layer arrays, energy field boxes, gradient flow labels, and node geometry lines are subject to TradingView drawing object limits (500 lines, 500 boxes, 500 labels per indicator as specified in settings). The system implements automatic cleanup by deleting oldest objects when limits approach, but on very long charts with many signals, some historical visual elements may be removed to stay within limits. This does not affect signal generation or dashboard metrics—only historical visual artifacts.
Dashboard and visual rendering update only on the last bar to minimize computational overhead. The catastrophe detection logic executes on every bar, but table cells and drawing objects refresh conditionally to optimize performance. If experiencing chart lag, reduce visual complexity: disable spectral layers, energy fields, or flow field to improve rendering speed. Core signal detection continues to function with all visual elements disabled.
The Hurst calculation uses logarithmic returns rather than raw price to ensure stationarity, and implements clipping to range to handle edge cases where R/S analysis produces invalid values (which can occur during extended periods of identical prices or numerical overflow). The 5-period EMA smoothing reduces noise while maintaining responsiveness to regime transitions.
The condition number calculation adds epsilon (1e-10) to denominators to prevent division by zero when Jacobian determinant approaches zero—which is precisely the singularity condition we're detecting. This numerical stability measure ensures the indicator doesn't crash when detecting the very phenomena it's designed to identify.
The indicator has been tested across multiple timeframes (5-minute through daily) and multiple asset classes (forex majors, stock indices, individual equities, cryptocurrencies, commodities, futures). It functions identically across all instruments due to the adaptive normalization approach and percentage-based metrics. No instrument-specific code or parameter sets are required.
The color scheme system implements seven preset themes plus custom mode. Color assignments are applied globally and affect all visual elements simultaneously. The opacity calculation system multiplies component-specific transparency with master opacity to create hierarchical control—adjusting master opacity affects all visuals proportionally while maintaining their relative transparency relationships.
All alert conditions trigger only on bar close to prevent false alerts from intrabar fluctuations. The regime transition alerts (VALID/INVALID) are particularly useful for knowing when trading edge appears or disappears, allowing traders to adjust activity levels accordingly.
— Dskyz, Trade with insight. Trade with anticipation.
High Accuracy Engulfing Strategy [PIPNEXUS]Title: EMA Engulfing Setup
Description:
This indicator focuses on identifying strong engulfing patterns that form around the EMA line, helping traders catch high-probability moves in line with market direction.
Concept Overview:
The idea is simple — when both the engulfing candle and the candle being engulfed have their bodies touching the EMA line, it often represents a key point of rejection or continuation. These areas can produce clean entries with strong momentum.
How to Use:
1. Wait for a valid engulfing formation near the EMA line.
Both the engulfing and the engulfed candles should have their bodies touching the EMA.
2. Enter in the direction of the engulfing candle once the pattern is confirmed.
3. For pinpoint entries, observe the market during session changes (especially in the first 3–5 minutes after a session opens).
4. For longer and more stable trades, look for the same pattern on 15-minute or 1-hour charts.
5. Always align your trades with the prevailing market structure and avoid counter-trend setups.
Note:
This indicator is designed for technical and educational use. It does not generate buy or sell signals automatically, nor does it guarantee performance. Use it alongside your own market analysis and proper risk management.
ICT ADR/AWR/AMR Levels | Trade Symmetry🌟 ICT ADR/AWR/AMR Levels
📋 Overview
This advanced technical analysis tool calculates and displays Average Daily Range (ADR), Average Weekly Range (AWR), and Average Monthly Range (AMR) levels. The indicator incorporates smart detection technology that automatically maintains monthly level visibility when historical data becomes unavailable.
✨ Key Features
🕒 Precise Time Alignment
True Daily Opens (TDO) aligned with 00:00 UTC
True Weekly Opens (TWO) at 00:00 UTC (configurable Monday/Sunday start)
True Monthly Opens (TMO) at 00:00 UTC on month start
Customizable period start times and parameters
📊 Comprehensive Multi-Timeframe Analysis
Daily Levels (ADR): Base level with multiple extensions including Fibonacci ratios
Weekly Levels (AWR): Weekly range projections and key levels
Monthly Levels (AMR): Monthly range calculations with automatic fallback system
🔄 Intelligent Level Management
Smart Detection: Automatically switches between historical and current monthly levels
Continuous Visibility: Ensures reference levels remain visible regardless of data availability
Seamless Operation: No manual adjustment needed for level transitions
⚙️ Extensive Customization
Adjustable lookback periods for all timeframes
Independent control over each level type and extension
Complete visual customization (colors, styles, widths)
Flexible labeling and display options
Configurable vertical separation lines
🏷️ Advanced Display Options
Clean, organized label placement
Optional price display in labels
Historical period tracking
Overlapping label merging capability
Adjustable label sizing and positioning
🚀 How to Use
Initial Setup: Enable desired timeframes (Daily/Weekly/Monthly)
Range Configuration: Set appropriate averaging periods for each timeframe
Level Selection: Choose which extension levels to display
Visual Settings: Customize colors and styles to match your trading workspace
Automatic Operation: The indicator intelligently manages level transitions
💡 Practical Applications
Identify potential support and resistance areas across multiple timeframes
Establish realistic profit targets based on historical volatility
Plan trade entries and exits around significant time-based levels
Analyze market volatility patterns across different time horizons
Incorporate institutional trading concepts into your analysis
LibVPrfLibrary "LibVPrf"
This library provides an object-oriented framework for volume
profile analysis in Pine Script®. It is built around the `VProf`
User-Defined Type (UDT), which encapsulates all data, settings,
and statistical metrics for a single profile, enabling stateful
analysis with on-demand calculations.
Key Features:
1. **Object-Oriented Design (UDT):** The library is built around
the `VProf` UDT. This object encapsulates all profile data
and provides methods for its full lifecycle management,
including creation, cloning, clearing, and merging of profiles.
2. **Volume Allocation (`AllotMode`):** Offers two methods for
allocating a bar's volume:
- **Classic:** Assigns the entire bar's volume to the close
price bucket.
- **PDF:** Distributes volume across the bar's range using a
statistical price distribution model from the `LibBrSt` library.
3. **Buy/Sell Volume Splitting (`SplitMode`):** Provides methods
for classifying volume into buying and selling pressure:
- **Classic:** Classifies volume based on the bar's color (Close vs. Open).
- **Dynamic:** A specific model that analyzes candle structure
(body vs. wicks) and a short-term trend factor to
estimate the buy/sell share at each price level.
4. **Statistical Analysis (On-Demand):** Offers a suite of
statistical metrics calculated using a "Lazy Evaluation"
pattern (computed only when requested via `get...` methods):
- **Central Tendency:** Point of Control (POC), VWAP, and Median.
- **Dispersion:** Value Area (VA) and Population Standard Deviation.
- **Shape:** Skewness and Excess Kurtosis.
- **Delta:** Cumulative Volume Delta, including its
historical high/low watermarks.
5. **Structural Analysis:** Includes a parameter-free method
(`getSegments`) to decompose a profile into its fundamental
unimodal segments, allowing for modality detection (e.g.,
identifying bimodal profiles).
6. **Dynamic Profile Management:**
- **Auto-Fitting:** Profiles set to `dynamic = true` will
automatically expand their price range to fit new data.
- **Manipulation:** The resolution, price range, and Value Area
of a dynamic profile can be changed at any time. This
triggers a resampling process that uses a **linear
interpolation model** to re-bucket existing volume.
- **Assumption:** Non-dynamic profiles are fixed and will throw
a `runtime.error` if `addBar` is called with data
outside their initial range.
7. **Bucket-Level Access:** Provides getter methods for direct
iteration and analysis of the raw buy/sell volume and price
boundaries of each individual price bucket.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
create(buckets, rangeUp, rangeLo, dynamic, valueArea, allot, estimator, cdfSteps, split, trendLen)
Construct a new `VProf` object with fixed bucket count & range.
Parameters:
buckets (int) : series int number of price buckets ≥ 1
rangeUp (float) : series float upper price bound (absolute)
rangeLo (float) : series float lower price bound (absolute)
dynamic (bool) : series bool Flag for dynamic adaption of profile ranges
valueArea (int) : series int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : series AllotMode Allocation mode `classic` or `pdf` (default `classic`)
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : series LibBrSt.PriceEst PDF model when `model == PDF`. (deflault = 'uniform')
cdfSteps (int) : series int even #sub-intervals for Simpson rule (default 20)
split (series SplitMode) : series SplitMode Buy/Sell determination (default `classic`)
trendLen (int) : series int Look‑back bars for trend factor (default 3)
Returns: VProf freshly initialised profile
method clone(self)
Create a deep copy of the volume profile.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object to copy
Returns: VProf A new, independent copy of the profile
method clear(self)
Reset all bucket tallies while keeping configuration intact.
Namespace types: VProf
Parameters:
self (VProf) : VProf profile object
Returns: VProf cleared profile (chaining)
method merge(self, srcABuy, srcASell, srcRangeUp, srcRangeLo, srcCvd, srcCvdHi, srcCvdLo)
Merges volume data from a source profile into the current profile.
If resizing is needed, it performs a high-fidelity re-bucketing of existing
volume using a linear interpolation model inferred from neighboring buckets,
preventing aliasing artifacts and ensuring accurate volume preservation.
Namespace types: VProf
Parameters:
self (VProf) : VProf The target profile object to merge into.
srcABuy (array) : array The source profile's buy volume bucket array.
srcASell (array) : array The source profile's sell volume bucket array.
srcRangeUp (float) : series float The upper price bound of the source profile.
srcRangeLo (float) : series float The lower price bound of the source profile.
srcCvd (float) : series float The final Cumulative Volume Delta (CVD) value of the source profile.
srcCvdHi (float) : series float The historical high-water mark of the CVD from the source profile.
srcCvdLo (float) : series float The historical low-water mark of the CVD from the source profile.
Returns: VProf `self` (chaining), now containing the merged data.
method addBar(self, offset)
Add current bar’s volume to the profile (call once per realtime bar).
classic mode: allocates all volume to the close bucket and classifies
by `close >= open`. PDF mode: distributes volume across buckets by the
estimator’s CDF mass. For `split = dynamic`, the buy/sell share per
price is computed via context-driven piecewise s(u).
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
offset (int) : series int To offset the calculated bar
Returns: VProf `self` (method chaining)
method setBuckets(self, buckets)
Sets the number of buckets for the volume profile.
Behavior depends on the `isDynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing to a new resolution.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
buckets (int) : series int The new number of buckets
Returns: VProf `self` (chaining)
method setRanges(self, rangeUp, rangeLo)
Sets the price range for the volume profile.
Behavior depends on the `dynamic` flag.
- If `dynamic = true`: Works on filled profiles by re-bucketing existing volume.
- If `dynamic = false`: Only works on empty profiles to prevent accidental changes.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
rangeUp (float) : series float The new upper price bound
rangeLo (float) : series float The new lower price bound
Returns: VProf `self` (chaining)
method setValueArea(self, valueArea)
Set the percentage of volume for the Value Area. If the value
changes, the profile is finalized again.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
valueArea (int) : series int The new Value Area percentage (0..100)
Returns: VProf `self` (chaining)
method getBktBuyVol(self, idx)
Get Buy volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Buy volume ≥ 0
method getBktSellVol(self, idx)
Get Sell volume of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns: series float Sell volume ≥ 0
method getBktBnds(self, idx)
Get Bounds of a bucket.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
idx (int) : series int Bucket index
Returns:
up series float The upper price bound of the bucket.
lo series float The lower price bound of the bucket.
method getPoc(self)
Get POC information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
pocIndex series int The index of the Point of Control (POC) bucket.
pocPrice. series float The mid-price of the Point of Control (POC) bucket.
method getVA(self)
Get Value Area (VA) information.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object
Returns:
vaUpIndex series int The index of the upper bound bucket of the Value Area.
vaUpPrice series float The upper price bound of the Value Area.
vaLoIndex series int The index of the lower bound bucket of the Value Area.
vaLoPrice series float The lower price bound of the Value Area.
method getMedian(self)
Get the profile's median price and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
medianIndex series int The index of the bucket containing the Median.
medianPrice series float The Median price of the profile.
method getVwap(self)
Get the profile's VWAP and its bucket index. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
vwapIndex series int The index of the bucket containing the VWAP.
vwapPrice series float The Volume Weighted Average Price of the profile.
method getStdDev(self)
Get the profile's volume-weighted standard deviation. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Standard deviation of the profile.
method getSkewness(self)
Get the profile's skewness. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Skewness of the profile.
method getKurtosis(self)
Get the profile's excess kurtosis. Calculates the value on-demand if stale.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns: series float The Kurtosis of the profile.
method getSegments(self)
Get the profile's fundamental unimodal segments. Calculates on-demand if stale.
Uses a parameter-free, pivot-based recursive algorithm.
Namespace types: VProf
Parameters:
self (VProf) : VProf The profile object.
Returns: matrix A 2-column matrix where each row is an pair.
method getCvd(self)
Cumulative Volume Delta (CVD) like metric over all buckets.
Namespace types: VProf
Parameters:
self (VProf) : VProf Profile object.
Returns:
cvd series float The final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi series float The running high-water mark of the CVD as volume was added.
cvdLo series float The running low-water mark of the CVD as volume was added.
VProf
VProf Bucketed Buy/Sell volume profile plus meta information.
Fields:
buckets (series int) : int Number of price buckets (granularity ≥1)
rangeUp (series float) : float Upper price range (absolute)
rangeLo (series float) : float Lower price range (absolute)
dynamic (series bool) : bool Flag for dynamic adaption of profile ranges
valueArea (series int) : int Percentage of total volume to include in the Value Area (1..100)
allot (series AllotMode) : AllotMode Allocation mode `classic` or `pdf`
estimator (series PriceEst enum from AustrianTradingMachine/LibBrSt/1) : LibBrSt.PriceEst Price density model when `model == PDF`
cdfSteps (series int) : int Simpson integration resolution (even ≥2)
split (series SplitMode) : SplitMode Buy/Sell split strategy per bar
trendLen (series int) : int Look‑back length for trend factor (≥1)
maxBkt (series int) : int User-defined number of buckets (unclamped)
aBuy (array) : array Buy volume per bucket
aSell (array) : array Sell volume per bucket
cvd (series float) : float Final Cumulative Volume Delta (Total Buy Vol - Total Sell Vol).
cvdHi (series float) : float Running high-water mark of the CVD as volume was added.
cvdLo (series float) : float Running low-water mark of the CVD as volume was added.
poc (series int) : int Index of max‑volume bucket (POC). Is `na` until calculated.
vaUp (series int) : int Index of upper Value‑Area bound. Is `na` until calculated.
vaLo (series int) : int Index of lower value‑Area bound. Is `na` until calculated.
median (series float) : float Median price of the volume distribution. Is `na` until calculated.
vwap (series float) : float Profile VWAP (Volume Weighted Average Price). Is `na` until calculated.
stdDev (series float) : float Standard Deviation of volume around the VWAP. Is `na` until calculated.
skewness (series float) : float Skewness of the volume distribution. Is `na` until calculated.
kurtosis (series float) : float Excess Kurtosis of the volume distribution. Is `na` until calculated.
segments (matrix) : matrix A 2-column matrix where each row is an pair. Is `na` until calculated.
LibBrStLibrary "LibBrSt"
This is a library for quantitative analysis, designed to estimate
the statistical properties of price movements *within* a single
OHLC bar, without requiring access to tick data. It provides a
suite of estimators based on various statistical and econometric
models, allowing for analysis of intra-bar volatility and
price distribution.
Key Capabilities:
1. **Price Distribution Models (`PriceEst`):** Provides a selection
of estimators that model intra-bar price action as a probability
distribution over the range. This allows for the
calculation of the intra-bar mean (`priceMean`) and standard
deviation (`priceStdDev`) in absolute price units. Models include:
- **Symmetric Models:** `uniform`, `triangular`, `arcsine`,
`betaSym`, and `t4Sym` (Student-t with fat tails).
- **Skewed Models:** `betaSkew` and `t4Skew`, which adjust
their shape based on the Open/Close position.
- **Model Assumptions:** The skewed models rely on specific
internal constants. `betaSkew` uses a fixed concentration
parameter (`BETA_SKEW_CONCENTRATION = 4.0`), and `t4Sym`/`t4Skew`
use a heuristic scaling factor (`T4_SHAPE_FACTOR`)
to map the distribution.
2. **Econometric Log-Return Estimators (`LogEst`):** Includes a set of
econometric estimators for calculating the volatility (`logStdDev`)
and drift (`logMean`) of logarithmic returns within a single bar.
These are unit-less measures. Models include:
- **Parkinson (1980):** A High-Low range estimator.
- **Garman-Klass (1980):** An OHLC-based estimator.
- **Rogers-Satchell (1991):** An OHLC estimator that accounts
for non-zero drift.
3. **Distribution Analysis (PDF/CDF):** Provides functions to work
with the Probability Density Function (`pricePdf`) and
Cumulative Distribution Function (`priceCdf`) of the
chosen price model.
- **Note on `priceCdf`:** This function uses analytical (exact)
calculations for the `uniform`, `triangular`, and `arcsine`
models. For all other models (e.g., `betaSkew`, `t4Skew`),
it uses **numerical integration (Simpson's rule)** as
an approximation of the cumulative probability.
4. **Mathematical Functions:** The library's Beta distribution
models (`betaSym`, `betaSkew`) are supported by an internal
implementation of the natural log-gamma function, which is
based on the Lanczos approximation.
---
**DISCLAIMER**
This library is provided "AS IS" and for informational and
educational purposes only. It does not constitute financial,
investment, or trading advice.
The author assumes no liability for any errors, inaccuracies,
or omissions in the code. Using this library to build
trading indicators or strategies is entirely at your own risk.
As a developer using this library, you are solely responsible
for the rigorous testing, validation, and performance of any
scripts you create based on these functions. The author shall
not be held liable for any financial losses incurred directly
or indirectly from the use of this library or any scripts
derived from it.
priceStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) *in price units* for the current
bar, according to the chosen `PriceEst` distribution assumption.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ ≥ 0 ; `na` if undefined (e.g. zero range).
priceMean(estimator, offset)
Estimates **μ̂** (mean price) for the chosen `PriceEst` within the
current bar.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ in price units.
pricePdf(estimator, price, offset)
Probability-density under the chosen `PriceEst` model.
**Returns 0** when `p` is outside the current bar’s .
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
price (float) : series float Price level to evaluate.
offset (int) : series int To offset the calculated bar
Returns: series float Density value.
priceCdf(estimator, upper, lower, steps, offset)
Cumulative probability **between** `upper` and `lower` under
the chosen `PriceEst` model. Outside-bar regions contribute zero.
Uses a fast, analytical calculation for Uniform, Triangular, and
Arcsine distributions, and defaults to numerical integration
(Simpson's rule) for more complex models.
Parameters:
estimator (series PriceEst) : series PriceEst Distribution assumption (see enum).
upper (float) : series float Upper Integration Boundary.
lower (float) : series float Lower Integration Boundary.
steps (int) : series int # of sub-intervals for numerical integration (if used).
offset (int) : series int To offset the calculated bar.
Returns: series float Probability mass ∈ .
logStdDev(estimator, offset)
Estimates **σ̂** (standard deviation) of *log-returns* for the current bar.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float σ̂ (unit-less); `na` if undefined.
logMean(estimator, offset)
Estimates μ̂ (mean log-return / drift) for the chosen `LogEst`.
The returned value is consistent with the assumptions of the
selected volatility estimator.
Parameters:
estimator (series LogEst) : series LogEst Distribution assumption (see enum).
offset (int) : series int To offset the calculated bar
Returns: series float μ̂ (unit-less log-return).
Scientific Correlation Testing FrameworkScientific Correlation Testing Framework - Comprehensive Guide
Introduction to Correlation Analysis
What is Correlation?
Correlation is a statistical measure that describes the degree to which two assets move in relation to each other. Think of it like measuring how closely two dancers move together on a dance floor.
Perfect Positive Correlation (+1.0): Both dancers move in perfect sync, same direction, same speed
Perfect Negative Correlation (-1.0): Both dancers move in perfect sync but in opposite directions
Zero Correlation (0): The dancers move completely independently of each other
In financial markets, correlation helps us understand relationships between different assets, which is crucial for:
Portfolio diversification
Risk management
Pairs trading strategies
Hedging positions
Market analysis
Why This Script is Special
This script goes beyond simple correlation calculations by providing:
Two different correlation methods (Pearson and Spearman)
Statistical significance testing to ensure results are meaningful
Rolling correlation analysis to track how relationships change over time
Visual representation for easy interpretation
Comprehensive statistics table with detailed metrics
Deep Dive into the Script's Components
1. Input Parameters Explained-
Symbol Selection:
This allows you to select the second asset to compare with the chart's primary asset
Default is Apple (NASDAQ:AAPL), but you can change this to any symbol
Example: If you're viewing a Bitcoin chart, you might set this to "NASDAQ:TSLA" to see if Bitcoin and Tesla are correlated
Correlation Window (60): This is the number of periods used to calculate the main correlation
Larger values (e.g., 100-500) provide more stable, long-term correlation measures
Smaller values (e.g., 10-50) are more responsive to recent price movements
60 is a good balance for most daily charts (about 3 months of trading days)
Rolling Correlation Window (20): A shorter window to detect recent changes in correlation
This helps identify when the relationship between assets is strengthening or weakening
Default of 20 is roughly one month of trading days
Return Type: This determines how price changes are calculated
Simple Returns: (Today's Price - Yesterday's Price) / Yesterday's Price
Easy to understand: "The asset went up 2% today"
Log Returns: Natural logarithm of (Today's Price / Yesterday's Price)
More mathematically elegant for statistical analysis
Better for time-additive properties (returns over multiple periods)
Less sensitive to extreme values.
Confidence Level (95%): This determines how certain we want to be about our results
95% confidence means we accept a 5% chance of being wrong (false positive)
Higher confidence (e.g., 99%) makes the test more strict
Lower confidence (e.g., 90%) makes the test more lenient
95% is the standard in most scientific research
Show Statistical Significance: When enabled, the script will test if the correlation is statistically significant or just due to random chance.
Display options control what you see on the chart:
Show Pearson/Spearman/Rolling Correlation: Toggle each correlation type on/off
Show Scatter Plot: Displays a scatter plot of returns (limited to recent points to avoid performance issues)
Show Statistical Tests: Enables the detailed statistics table
Table Text Size: Adjusts the size of text in the statistics table
2.Functions explained-
calcReturns():
This function calculates price returns based on your selected method:
Log Returns:
Formula: ln(Price_t / Price_t-1)
Example: If a stock goes from $100 to $101, the log return is ln(101/100) = ln(1.01) ≈ 0.00995 or 0.995%
Benefits: More symmetric, time-additive, and better for statistical modeling
Simple Returns:
Formula: (Price_t - Price_t-1) / Price_t-1
Example: If a stock goes from $100 to $101, the simple return is (101-100)/100 = 0.01 or 1%
Benefits: More intuitive and easier to understand
rankArray():
This function calculates the rank of each value in an array, which is used for Spearman correlation:
How ranking works:
The smallest value gets rank 1
The second smallest gets rank 2, and so on
For ties (equal values), they get the average of their ranks
Example: For values
Sorted:
Ranks: (the two 2s tie for ranks 1 and 2, so they both get 1.5)
Why this matters: Spearman correlation uses ranks instead of actual values, making it less sensitive to outliers and non-linear relationships.
pearsonCorr():
This function calculates the Pearson correlation coefficient:
Mathematical Formula:
r = (nΣxy - ΣxΣy) / √
Where x and y are the two variables, and n is the sample size
What it measures:
The strength and direction of the linear relationship between two variables
Values range from -1 (perfect negative linear relationship) to +1 (perfect positive linear relationship)
0 indicates no linear relationship
Example:
If two stocks have a Pearson correlation of 0.8, they have a strong positive linear relationship
When one stock goes up, the other tends to go up in a fairly consistent proportion
spearmanCorr():
This function calculates the Spearman rank correlation:
How it works:
Convert each value in both datasets to its rank
Calculate the Pearson correlation on the ranks instead of the original values
What it measures:
The strength and direction of the monotonic relationship between two variables
A monotonic relationship is one where as one variable increases, the other either consistently increases or decreases
It doesn't require the relationship to be linear
When to use it instead of Pearson:
When the relationship is monotonic but not linear
When there are significant outliers in the data
When the data is ordinal (ranked) rather than interval/ratio
Example:
If two stocks have a Spearman correlation of 0.7, they have a strong positive monotonic relationship
When one stock goes up, the other tends to go up, but not necessarily in a straight-line relationship
tStatistic():
This function calculates the t-statistic for correlation:
Mathematical Formula: t = r × √((n-2)/(1-r²))
Where r is the correlation coefficient and n is the sample size
What it measures:
How many standard errors the correlation is away from zero
Used to test the null hypothesis that the true correlation is zero
Interpretation:
Larger absolute t-values indicate stronger evidence against the null hypothesis
Generally, a t-value greater than 2 (in absolute terms) is considered statistically significant at the 95% confidence level
criticalT() and pValue():
These functions provide approximations for statistical significance testing:
criticalT():
Returns the critical t-value for a given degrees of freedom (df) and significance level
The critical value is the threshold that the t-statistic must exceed to be considered statistically significant
Uses approximations since Pine Script doesn't have built-in statistical distribution functions
pValue():
Estimates the p-value for a given t-statistic and degrees of freedom
The p-value is the probability of observing a correlation as strong as the one calculated, assuming the true correlation is zero
Smaller p-values indicate stronger evidence against the null hypothesis
Standard interpretation:
p < 0.01: Very strong evidence (marked with **)
p < 0.05: Strong evidence (marked with *)
p ≥ 0.05: Weak evidence, not statistically significant
stdev():
This function calculates the standard deviation of a dataset:
Mathematical Formula: σ = √(Σ(x-μ)²/(n-1))
Where x is each value, μ is the mean, and n is the sample size
What it measures:
The amount of variation or dispersion in a set of values
A low standard deviation indicates that the values tend to be close to the mean
A high standard deviation indicates that the values are spread out over a wider range
Why it matters for correlation:
Standard deviation is used in calculating the correlation coefficient
It also provides information about the volatility of each asset's returns
Comparing standard deviations helps understand the relative riskiness of the two assets.
3.Getting Price Data-
price1: The closing price of the primary asset (the chart you're viewing)
price2: The closing price of the secondary asset (the one you selected in the input parameters)
Returns are used instead of raw prices because:
Returns are typically stationary (mean and variance stay constant over time)
Returns normalize for price levels, allowing comparison between assets of different values
Returns represent what investors actually care about: percentage changes in value
4.Information Table-
Creates a table to display statistics
Only shows on the last bar to avoid performance issues
Positioned in the top right of the chart
Has 2 columns and 15 rows
Populating the Table
The script then populates the table with various statistics:
Header Row: "Metric" and "Value"
Sample Information: Sample size and return type
Pearson Correlation: Value, t-statistic, p-value, and significance
Spearman Correlation: Value, t-statistic, p-value, and significance
Rolling Correlation: Current value
Standard Deviations: For both assets
Interpretation: Text description of the correlation strength
The table uses color coding to highlight important information:
Green for significant positive results
Red for significant negative results
Yellow for borderline significance
Color-coded headers for each section
=> Practical Applications and Interpretation
How to Interpret the Results
Correlation Strength
0.0 to 0.3 (or 0.0 to -0.3): Weak or no correlation
The assets move mostly independently of each other
Good for diversification purposes
0.3 to 0.7 (or -0.3 to -0.7): Moderate correlation
The assets show some tendency to move together (or in opposite directions)
May be useful for certain trading strategies but not extremely reliable
0.7 to 1.0 (or -0.7 to -1.0): Strong correlation
The assets show a strong tendency to move together (or in opposite directions)
Can be useful for pairs trading, hedging, or as a market indicator
Statistical Significance
p < 0.01: Very strong evidence that the correlation is real
Marked with ** in the table
Very unlikely to be due to random chance
p < 0.05: Strong evidence that the correlation is real
Marked with * in the table
Unlikely to be due to random chance
p ≥ 0.05: Weak evidence that the correlation is real
Not marked in the table
Could easily be due to random chance
Rolling Correlation
The rolling correlation shows how the relationship between assets changes over time
If the rolling correlation is much different from the long-term correlation, it suggests the relationship is changing
This can indicate:
A shift in market regime
Changing fundamentals of one or both assets
Temporary market dislocations that might present trading opportunities
Trading Applications
1. Portfolio Diversification
Goal: Reduce overall portfolio risk by combining assets that don't move together
Strategy: Look for assets with low or negative correlations
Example: If you hold tech stocks, you might add some utilities or bonds that have low correlation with tech
2. Pairs Trading
Goal: Profit from the relative price movements of two correlated assets
Strategy:
Find two assets with strong historical correlation
When their prices diverge (one goes up while the other goes down)
Buy the underperforming asset and short the outperforming asset
Close the positions when they converge back to their normal relationship
Example: If Coca-Cola and Pepsi are highly correlated but Coca-Cola drops while Pepsi rises, you might buy Coca-Cola and short Pepsi
3. Hedging
Goal: Reduce risk by taking an offsetting position in a negatively correlated asset
Strategy: Find assets that tend to move in opposite directions
Example: If you hold a portfolio of stocks, you might buy some gold or government bonds that tend to rise when stocks fall
4. Market Analysis
Goal: Understand market dynamics and interrelationships
Strategy: Analyze correlations between different sectors or asset classes
Example:
If tech stocks and semiconductor stocks are highly correlated, movements in one might predict movements in the other
If the correlation between stocks and bonds changes, it might signal a shift in market expectations
5. Risk Management
Goal: Understand and manage portfolio risk
Strategy: Monitor correlations to identify when diversification benefits might be breaking down
Example: During market crises, many assets that normally have low correlations can become highly correlated (correlation convergence), reducing diversification benefits
Advanced Interpretation and Caveats
Correlation vs. Causation
Important Note: Correlation does not imply causation
Example: Ice cream sales and drowning incidents are correlated (both increase in summer), but one doesn't cause the other
Implication: Just because two assets move together doesn't mean one causes the other to move
Solution: Look for fundamental economic reasons why assets might be correlated
Non-Stationary Correlations
Problem: Correlations between assets can change over time
Causes:
Changing market conditions
Shifts in monetary policy
Structural changes in the economy
Changes in the underlying businesses
Solution: Use rolling correlations to monitor how relationships change over time
Outliers and Extreme Events
Problem: Extreme market events can distort correlation measurements
Example: During a market crash, many assets may move in the same direction regardless of their normal relationship
Solution:
Use Spearman correlation, which is less sensitive to outliers
Be cautious when interpreting correlations during extreme market conditions
Sample Size Considerations
Problem: Small sample sizes can produce unreliable correlation estimates
Rule of Thumb: Use at least 30 data points for a rough estimate, 60+ for more reliable results
Solution:
Use the default correlation length of 60 or higher
Be skeptical of correlations calculated with small samples
Timeframe Considerations
Problem: Correlations can vary across different timeframes
Example: Two assets might be positively correlated on a daily basis but negatively correlated on a weekly basis
Solution:
Test correlations on multiple timeframes
Use the timeframe that matches your trading horizon
Look-Ahead Bias
Problem: Using information that wouldn't have been available at the time of trading
Example: Calculating correlation using future data
Solution: This script avoids look-ahead bias by using only historical data
Best Practices for Using This Script
1. Appropriate Parameter Selection
Correlation Window:
For short-term trading: 20-50 periods
For medium-term analysis: 50-100 periods
For long-term analysis: 100-500 periods
Rolling Window:
Should be shorter than the main correlation window
Typically 1/3 to 1/2 of the main window
Return Type:
For most applications: Log Returns (better statistical properties)
For simplicity: Simple Returns (easier to interpret)
2. Validation and Testing
Out-of-Sample Testing:
Calculate correlations on one time period
Test if they hold in a different time period
Multiple Timeframes:
Check if correlations are consistent across different timeframes
Economic Rationale:
Ensure there's a logical reason why assets should be correlated
3. Monitoring and Maintenance
Regular Review:
Correlations can change, so review them regularly
Alerts:
Set up alerts for significant correlation changes
Documentation:
Keep notes on why certain assets are correlated and what might change that relationship
4. Integration with Other Analysis
Fundamental Analysis:
Combine correlation analysis with fundamental factors
Technical Analysis:
Use correlation analysis alongside technical indicators
Market Context:
Consider how market conditions might affect correlations
Conclusion
This Scientific Correlation Testing Framework provides a comprehensive tool for analyzing relationships between financial assets. By offering both Pearson and Spearman correlation methods, statistical significance testing, and rolling correlation analysis, it goes beyond simple correlation measures to provide deeper insights.
For beginners, this script might seem complex, but it's built on fundamental statistical concepts that become clearer with use. Start with the default settings and focus on interpreting the main correlation lines and the statistics table. As you become more comfortable, you can adjust the parameters and explore more advanced applications.
Remember that correlation analysis is just one tool in a trader's toolkit. It should be used in conjunction with other forms of analysis and with a clear understanding of its limitations. When used properly, it can provide valuable insights for portfolio construction, risk management, and pair trading strategy development.






















