Swing Point Indicator🔍 How does it work?
He looks at a candle and compares it with a number of candles to the left and right.
If that candle is the highest of that group, then it is a swing high.
If that candle is the lowest, then it is a swing low.
📈 What do you use it for?
Reading market structure:
You can easily see higher highs / higher lows (bullish structure)
Or lower highs / lower lows (bearish structure)
Determining BOS & CHoCH:
If a new swing low breaks below the previous one → Break of Structure (BOS)
If you go from HH/HL to LH/LL → Change of Character (CHoCH)
Finding entry and exit points:
You know where to expect price reactions (at swing points)
Good for pullback entries or stop loss placement
Drawing smart zones:
You can draw from swing high to swing low for Fibs, order blocks or S&D zones
*** Translated with www.DeepL.com (free version) ***
Indicadores e estratégias
RSI Horizontal resistance levelsRSI Horizontal Resistance Levels
Purpose
This study automatically draws horizontal price rays every time the Relative Strength Index (RSI) trades inside a user‑defined band (default = 50 ± 1). The idea is to spotlight price levels that historically coincided with a specific RSI state—levels that often evolve into short‑term support or resistance as sentiment repeats.
How it works
Raw RSI – The script computes an un‑smoothed RSI of the closing price (rsiLength, default = 3).
Trigger zone – Whenever RSI falls within level ± tolerance (e.g., 49 – 51) the close price of that bar becomes a reference.
Horizontal ray – A ray (extend.right) is drawn from that close and continues indefinitely to the right, creating a live price level.
History management – Only the most recent N rays are kept (maxRays, default = 5); the oldest line is deleted automatically to avoid chart clutter.
Inputs
Name Default Description
RSI Length 3 Look‑back of the RSI calculation.
RSI Level 50 Center of the trigger zone. Common alternatives: 30, 70, custom mid‑lines.
Tolerance 1 Width of the RSI band on each side of RSI Level (set 0 for an exact hit).
Max Rays 5 Maximum number of active horizontal levels kept on screen.
Ray Color Yellow Visual color of the rays.
Ray Width 2 Thickness of the rays.
How to use it
Spot recurring reaction zones – Markets often hesitate near prices where momentum has flipped before. The rays reveal those spots automatically.
Combine with candlestick or volume cues – A level marked by this script plus a rejection wick, volume spike, or divergence can strengthen conviction.
Adapt the band –
50 ± tolerance → momentum balance line (trend pullbacks)
70 ± tolerance → overbought fade levels
30 ± tolerance → oversold bounce levels
Works on any asset or timeframe; shorter RSI periods highlight intraday rotations, longer periods capture swing pivots.
Tips & cautions
A drawn line is not a guarantee of future reversal—always validate with price action and risk management.
For high‑frequency strategies, consider lowering tolerance or increasing rsiLength to reduce noise.
You can add custom alerts on RSI crossing the band to receive push or email notifications.
Happy trading!
AI Sniper XAUUSD v1.0AI Sniper XAUUSD v1.0 is a precision scalping indicator for trading gold (XAUUSD), built on intelligent entry logic. It analyzes the trend (EMA20/50), detects engulfing candles, and automatically draws Entry, Stop Loss, and Take Profit levels (RR 1:2 and 1:4).
Includes an interactive confirmation table for quick decision-making.
Designed for fast and safe entries on 1-minute and 5-minute charts.
Inside Bar IndicatorFind Inside Bar helps price action traders spot inside bars without having to watch the chart constantly.
Moffitt Candle ClosureMoffitt Candle Closure method, wait for a closure above or below the wick of the prior opposing candle!
SOPR with Z-Score Table📊 Glassnode SOPR with Dynamic Z-Score Table
ℹ️ Powered by Glassnode On-Chain Metrics
📈 Description:
This indicator visualizes the Spent Output Profit Ratio (SOPR) for major cryptocurrencies — Bitcoin, Ethereum, and Litecoin — along with a dynamically normalized Z-Score. SOPR is a key on-chain metric that reflects whether coins moved on-chain are being sold at a profit or a loss.
🔍 SOPR is calculated using Glassnode’s entity-adjusted SOPR feed, and a custom SMA is applied to smooth the signal. The normalized Z-Score helps identify market sentiment extremes by scaling SOPR relative to its historical context.
📊 Features:
Selectable cryptocurrency: Bitcoin, Ethereum, or Litecoin
SOPR smoothed by user-defined SMA (default: 10 periods)
Upper & lower bounds (±4%) for SOPR, shown as red/green lines
Background highlighting when SOPR moves outside normal range
Normalized Z-Score scaled between –2 and +2
Live Z-Score display in a compact top-right table
🧮 Calculations:
SOPR data is sourced daily from Glassnode:
Bitcoin: XTVCBTC_SOPR
Ethereum: XTVCETH_SOPR
Litecoin: XTVCLTC_SOPR
Z-Score is calculated as:
SMA of SOPR over zscore_length periods
Standard deviation of SOPR
Z-Score = (SOPR – mean) / standard deviation
Z-Score is clamped between –2 and +2 for visual consistency
🎯 Interpretation:
SOPR > 1 implies coins are sold in profit
SOPR < 1 suggests coins are sold at a loss
When SOPR is significantly above or below its recent range (e.g., +4% or –4%), it may signal overheating or capitulation
The Z-Score contextualizes how extreme the current SOPR is relative to history
📌 Notes:
Best viewed on daily charts
Works across selected assets (BTC, ETH, LTC)
LULD Bands & Trading Halt Detector [Volume Vigilante]📖 LULD Bands & Trading Halt Detector
This advanced tool visualizes official Limit Up / Limit Down (LULD) price bands and detects regulatory trading halts and resumptions based on SEC and NASDAQ rules. It is engineered for high accuracy by anchoring all calculations to the 1-minute timeframe, ensuring reliable signals across any chart resolution.
📌 What Does This Script Do?
- Draws real-time LULD price band estimations and optional buffer (caution) zones directly on the chart.
- Detects trading halt resumptions by monitoring time gaps between candles and other regulatory criteria. (Note: Due to Pine Script limitations, halts cannot be detected in real-time, only resumptions after they occur.)
- Triggers real-time alerts for:
- Trading Resumptions (Limit Up & Limit Down)
- LULD Zone Entries (Caution Zone)
- Band Breaches (Limit Up and Limit Down)
- Plots historical halt resumption markers to analyse past events.
📐 How It Works:
- Implements official SEC/NASDAQ LULD rules for Tier 1 and Tier 2 securities.
- Applies special band adjustments for the final 25 minutes of trading (after 3:35 PM ET).
- Anchors all logic to the 1-minute timeframe for precise calculations, even on higher timeframe charts.
- Includes adjustable volume and volatility filters to eliminate false signals (ghost halts) on low-- liquidity assets, especially Tier 2 securities when TradingView fails to print candles.
⚙️ How to Use It:
1.) Apply the script to any asset or timeframe.
2.) Adjust Volume and Volatility Filters to reduce noise. (Recommended: 500,000+ volume, 10%+ volatility.)
3.) Enable or disable visual components like bands, buffer zones, and halt resumption labels.
4.) Configure alerts directly from the script settings panel.
5.) Apply alerts to individual assets via "Add Alert On..." or to entire watchlists using "Add Alert on the List."
🧩 What Makes This Script Unique?
- True 1-Minute Anchored Calculations: Ensures alerts and visuals match official trading halt criteria regardless of chart timeframe.
- Customisable Buffered Zones: Visualise proximity to regulatory price limits and avoid volatility traps.
- Combines halt resumption detection, limit up/down band visualisation, and real-time alerts into one clean, modular tool.
📚 Disclaimer:
This script is for educational purposes only and does not constitute financial advice. Use at your own discretion and consult a licensed financial advisor before making trading decisions based on it.
Official Resources:
- NASDAQ LULD Regulations (FAQ):
www.nasdaqtrader.com
Current Nasdaq Trading Halts:
www.nasdaqtrader.com
Asian Range + Midpoint + Liquidity Grab AlertsPlot Asian Range 12am to 08am GMT with Midpoint and Liquidity Grab Alerts
🧠 Godly Confluence Indicator - NQ Futures
~Features Include~
VWAP — institutional trend anchor
RSI (Relative Strength Index) — momentum + overbought/oversold
MACD — momentum + trend confirmation
Delta Volume Approximation — buy/sell pressure estimation
ATR-Based Stop Loss Zones — visual risk levels
Signal Conditions — Buy/Sell signals based on confluence
Energy Exhaustion (Reversal Detection) — via RSI & MACD divergence logic (simplified)
Sticky Candlestick Quarter Divider (Dynamic Update)This indicator divides the most recent candlestick into four equal parts and dynamically plots horizontal lines that move along with the latest candle.
Features:
Dynamic Sticky Lines:
The lines remain visually attached to the current candle, moving seamlessly as the chart updates, zooms, or pans.
Price Level Calculation:
Divides the candlestick into four distinct levels:
High Line (Red): Marks the highest point of the candle.
Low Line (Red): Marks the lowest point of the candle.
Midpoint Line (Blue): Marks the midpoint between high and low.
Upper Quarter Line (Green): Marks the 25% level between low and high.
Lower Quarter Line (Green): Marks the 75% level between low and high.
Real-Time Update:
The lines automatically adjust to the latest candle, maintaining accurate positioning.
Ideal for Candle Analysis:
Quickly identify key price levels and candle structure.
Suitable for analyzing trend strength and potential price reversals.
Cumulative Volume Delta with Divergence🧠 Core Functionality:
1. Cumulative Volume Delta (CVD):
Purpose: Visualizes the difference between buying and selling pressure over time.
Mechanism:
It uses lower-timeframe volume delta data, retrieved from ta.requestVolumeDelta(), to build a candle-style visualization of the net volume movement.
Plotted candles show whether buying (up volume) or selling (down volume) was dominant within each period.
Teal candles: More buying than selling (CVD up).
Red candles: More selling than buying (CVD down).
Volume Source: Based on intrabar up/down volume approximation from lower timeframes.
🧭 Divergence Detection (New Feature):
2. Regular Bullish Divergence:
Condition:
Price makes a lower low.
CVD (lastVolume) makes a higher low.
Interpretation: Selling pressure is weakening despite price making new lows — a potential reversal signal to the upside.
Displayed As:
Green line and label "Bull" under the CVD at the divergence point.
3. Regular Bearish Divergence:
Condition:
Price makes a higher high.
CVD makes a lower high.
Interpretation: Buying pressure is fading despite price rising — a potential reversal signal to the downside.
Displayed As:
Red line and label "Bear" above the CVD at the divergence point.
🧰 User Controls:
Use custom timeframe: Overrides default volume delta resolution for finer or broader analysis.
Calculate Divergence: Turns the divergence detection on or off.
Adjustable via script inputs.
🔔 Alerts:
Two alert conditions are included:
One for bullish divergence.
One for bearish divergence.
Alerts trigger at the bar where the divergence is confirmed, not where it starts.
📈 Use Case:
This tool is ideal for traders looking to:
Spot early reversals or momentum shifts.
Combine volume analysis with price action.
Time entries or exits more accurately using volume-confirmed divergence.
Deviation over Deviation (DoD) (DAFE) Deviation over Deviation (DoD)
Let’s call it out: The vast majority of “volatility” tools on TradingView are just new wrappers on old math—ATR, bands, and basic deviation, all chasing the same tired after-the-fact moves. They’re built to describe the aftermath, not the ignition. If you’re still relying on these, you’re trading in the rearview mirror while the real edge is already gone. That’s not our game, and it shouldn’t be yours.
Deviation over Deviation (DoD) is built for one purpose:
To expose the hidden regime shifts—the moments when volatility itself becomes volatile, when the market’s “normal” deviation is no longer normal, and when the next move is about to erupt. This isn’t just another overlay. This is a quant-grade anomaly detector, engineered to show you the probability surface before the crowd even knows it’s changed.
What sets this apart:
Deviation over Deviation (DoD):
Not just “how much did price move,” but “how unusual is the current volatility compared to its own history?” This is the Z-score of Z-scores—a true rarity detector for market stress, lull, or impending breakout.
VoVix Integration:
Select VoVix as your source and you’re not just tracking price, but the volatility of volatility—the same math that powers institutional regime models. This is the edge that front-runs the move, not follows it.
Multi-Timeframe Comparative Engine:
Instantly compare current and higher timeframe DoD Z-scores. See when the micro and macro regimes align—or when they’re about to collide.
Professional, Adaptive Dashboard:
No cosmetic fluff, always showing you the real quant state: current DoD Z, HTF DoD Z, and regime warnings. Every color, every plot, every signal is a direct function of the logic—no distractions, no lag.
How this destroys the lag:
Standard deviation, ATR, and “volatility bands” are always late. They tell you what just happened. DoD and VoVix show you when the nature of volatility itself is changing—when the market is about to leave the old regime behind. This is the difference between trading the past and trading the future.
Inputs/Signals—explained for clarity:
Deviation Lookback & DoD Lookback:
Control the sensitivity and selectivity of the regime detector. Shorter = more signals, longer = only the rarest events.
Source Selection:
Choose from price, volume, volatility, or VoVix. Each source gives you a different lens on market stress. VoVix is for those who want to see the “regime quake” before the aftershocks.
HTF (Comparative Timeframe):
Set your higher timeframe for macro regime confirmation. When both DoD Z-scores align, you’re seeing a true market inflection.
VoVix Parameters:
Fine-tune the volatility-of-volatility engine for your market. Lower ATR Fast = more responsive; higher ATR Slow = more selective. Adjust for your asset, your timeframe, your edge.
Bottom line:
This isn’t just another “volatility” script. This is a regime anomaly detector, built for traders who want to anticipate, not react. Every input is there for a reason. Every plot is a direct readout of the quant logic. Use it to filter your entries, to time your exits, or to simply see the market’s hidden structure in real time.
Disclaimer:
Trading is risky. This script is for research and informational purposes only, not financial advice. Backtest, paper trade, and know your risk before going live. Past performance is not a guarantee of future results.
*Updated the Dashboard/Metrics Display for better visibility
Use with discipline. Trade your edge.
— Dskyz, for DAFE Trading Systems
Supply and Demand Gold[Tom]best supply and demand finder , if you need a indicator to get rid of the work behind that , this is the one
5 Min ORB with ExtensionsThis Indicator marks the first RTH 5 minute high and low with the extensions levels
(DAFE) DEVMA - Crossover (Deviation Moving Average) (DAFE) DEVMA - Crossover (Deviation Moving Average)
Let’s keep pushing the edge. After the breakthrough of Deviation over Deviation (DoD)—which gave traders a true lens into volatility’s hidden regime shifts—many asked: “What’s next?” The answer is DEVMA: a crossover engine built not on price, but on the heartbeat of the market itself.
Why is this different?
DEVMA isn’t just a moving average crossover. It’s a regime detector that tracks the expansion and contraction of deviation—giving you a real-time readout of when the market’s energy is about to shift. This is the next step for anyone who wants to anticipate volatility, not just react to it.
What sets DEVMA apart:
Volatility-First Logic:Both fast and slow lines are moving averages of deviation, not price. You’re tracking the market’s “energy,” not just its direction. This is the quant edge that most scripts miss.
Regime-Colored Lines:
The fast and slow DEVMA lines change color in real time—green/aqua for expansion, maroon/orange for contraction—so you can see regime shifts at a glance.
Quant-Pro Visuals:
Subtle glow, clean cross markers, and a minimalist dashboard keep your focus on what matters: the regime, not the noise.
Static Regime Thresholds:
Reference lines at 1.5 and 0.5 (custom colors) give you instant context for “normal” vs. “extreme” volatility states.
No Price Chasing:
This isn’t about following price. It’s about anticipating the next volatility regime—before the crowd even knows what’s coming.
How this builds on DoD:
DoD showed you when volatility itself was about to change. DEVMA takes that insight and turns it into a crossover engine—so you can see, filter, and act on regime shifts in real time. If DoD was the radar, DEVMA is the navigation system.
Inputs/Signals—explained for clarity:
Deviation Lookback:
Controls the sensitivity of the regime detector. Shorter = more signals, longer = only the rarest events.
Fast/Slow DEVMA Lengths:
Fine-tune how quickly the regime lines react. Fast for scalping, slow for swing trading.
Source Selection:
Choose from price, volume, volatility, or VoVix. Each source gives you a different lens on market stress. VoVix is for those who want to see the “regime quake” before the aftershocks.
VoVix Parameters:
Fine-tune the volatility-of-volatility engine for your market. Lower ATR Fast = more responsive; higher ATR Slow = more selective.
Bottom line:
DEVMA is for those who want to see the market’s heartbeat, not just its shadow. Use it to filter your trades, time your entries, or simply understand the market’s true rhythm. Every input is there for a reason. Every plot is a direct readout of the quant logic. Use with discipline, and make it your own.
Disclaimer:
Trading is risky. This script is for research and informational purposes only, not financial advice. Backtest, paper trade, and know your risk before going live. Past performance is not a guarantee of future results.
*Updated the Dashboard/Metrics Display for better visibility
Use with discipline. Trade your edge.
— Dskyz, for DAFE Trading Systems
Trend Board ProIndicator Description: Trend Board Pro
Trend Board Pro is a compact trading dashboard that displays essential market metrics in a clean, easy-to-read format. Designed for quick market assessment, it provides critical data without cluttering the chart.
Key Features:
✅ Trend (L/S) — identifies market direction:
L (Long, green) — bullish trend
S (Short, red) — bearish trend
✅ Daily Volume (DV) — total 24h trading volume in USD (formatted as "1.2 B" for billions, "350 M" for millions).
✅ Average Volume (AV) — rolling average volume over a customizable period (default: 30 candles) in USD.
✅ Volatility (NATR, %) — normalized average true range (default period: 14).
✅ Correlation (C) — correlation coefficient with a selected asset (e.g., BTCUSDT).
Key Advantages:
🔹 Customizable layout — toggle metrics on/off as needed.
🔹 Smart number formatting — auto-converts large values (millions/billions).
🔹 Color alerts — highlights significant volume/volatility levels.
🔹 Flexible positioning — 5 placement options (top/bottom, left/right, center).
AlgoRanger Momentum + Trend - Following📘 AlgoRanger Momentum + Trend - Following
Dynamic Trend and Momentum Tracking Indicator
🔍 Overview:
This indicator combines trend direction and momentum strength using a dynamic multi-moving average ribbon (MA Ribbon). It helps traders clearly visualize both the direction and the power of price movement.
The ribbon lines automatically change color based on momentum:
🟢 Green = Bullish momentum
🔴 Red = Bearish momentum
📈 How to Use:
1. Identifying Trend Direction
When all lines are aligned upward and turn green → strong bullish trend
When all lines slope downward and turn red → strong bearish trend
2. Measuring Momentum Strength
Tight and close ribbon → weak momentum
Wide-spread ribbon → strong momentum
Frequent color flips → choppy or sideways market
3. Trading Strategy
Trend Following:
Enter Buy when the ribbon turns green and aligns upward
Enter Sell when the ribbon turns red and aligns downward
Filtering False Signals:
Avoid trading when the ribbon flips colors often or trends are flat
4. Exit Points / Take Profit
Ribbon turns green to red → Exit Buy
Ribbon turns red to green → Exit Sell
Combine with support/resistance or Supply & Demand Zones for confirmation
🧠 Pro Tips:
Combine with other AlgoRanger indicators for best results:
Use Smart Signal for auto entries
Use Supply & Demand Zones to validate price targets
Customize the ribbon speed:
Fast settings for scalping (1m, 5m charts)
Slower settings for swing trading (1h, 4h charts)
🔧 Features:
✅ Auto-color based on momentum shifts
✅ Multiple MA lines for better accuracy
✅ Works on all timeframes
✅ Combines trend and momentum in a single tool
💡 Best For:
Trend-following traders
Scalpers needing fast momentum tracking
Traders seeking signal filtering
All skill levels wanting to visualize trend strength
9-15 EMA Strategy Auto Signals//@version=5
//This is only for educational purposes
indicator('9-15 EMA Strategy Auto Signals', overlay=true)
// Plot 9 and 15 EMA on the chart
ema9 = ta.ema(close, 9)
ema15 = ta.ema(close, 15)
plot(ema9, title = "9 EMA", color=color.rgb(253, 5, 5), linewidth=1)
plot(ema15, title = "15 EMA", color=color.rgb(0, 0, 0), linewidth=1)
// Calculate the slope of the 9 EMA line in degrees
angle = math.atan((ema9 - ema9 ) / syminfo.mintick) * (180 / input(5.58159265))
// Conditions for buying
buySignal1 = ta.crossover(ema9, ema15)
buySignal2 = close > open and open < ema9 and open > ema15 and close > ema9 and low > ema15 and high - math.max(open, close) <= math.abs(open - close) * 0.3
buySignal3 = close > open and open > ema9 and low <= ema9 and close > ema9 and low > ema15 and high - math.max(open, close) <= math.abs(open - close) * 0.3
buyConditionAngle = angle >= input((50), title = "Angle 2") // Buy only if the slope is greater than or equal to 50 degrees
// Plot green arrow on the chart for buying signals
plotshape(buySignal2 or buySignal3, title = "Up", style=shape.triangleup, location=location.belowbar, color=color.new(#0a0ef3, 12), size=size.small)
plotshape((buySignal2 or buySignal3) and buyConditionAngle, title = "Slope Up", style=shape.triangleup, location=location.belowbar, color=color.new(color.green, 0), size=size.small)
// Conditions for selling
sellSignal1 = ta.crossunder(ema9, ema15)
sellSignal2 = close < open and open > ema9 and open < ema15 and close < ema9 and high < ema15 and math.min(open, close) - low <= math.abs(open - close) * 0.3
sellSignal3 = close < open and open < ema9 and high >= ema9 and close < ema9 and high < ema15 and math.min(open, close) - low <= math.abs(open - close) * 0.3
sellConditionAngle = angle <= -50 // Sell only if the slope is less than or equal to -50 degrees
// Plot red arrow on the chart for selling signals
plotshape(sellSignal2 or sellSignal3, title = "Down", style=shape.triangledown, location=location.abovebar, color=color.rgb(0, 0, 0), size=size.small)
plotshape((sellSignal2 or sellSignal3) and sellConditionAngle, title = "Slope Down", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)
CME Gaps on Price chart (Xpdev)This script was published to help traders monitor market gaps on the CME and overlay them directly on the price chart.
The script works in general for any market and on any time frame.
The script allows the user to:
- Specify the CME ticket for gap searching (default is BTC1!);
- Specify the time frame for gap searching;
- Specify how the gaps should be filled;
- Identify price gaps of a custom width (Gap Width);
- Overlay on the price chart gaps found through showing red and green areas.
- Option to show label and price CME on chart with a proximity parameter
- Option to show only Bull or Bear gaps
- Option to customize color for Bull and Bear gaps
- Options for gap info label
- Option for gap filling criteria
- Option to show closer Gaps info table
- Option to show statistic info table
** WARNING **
CME data may be delayed or unavailable depending on the type of subscription or additional packages purchased for your TW profile.
CandelaCharts - Buyside & Sellside 📝 Overview
The Buyside & Sellside Liquidity Indicator is designed to identify and emphasize one of the foundational concepts within the ICT (Inner Circle Trader) trading methodology: liquidity levels.
This tool focuses on pinpointing key areas in the market where buy-side and sell-side liquidity is concentrated, providing traders with insights into potential price targets, reversal zones, and institutional order flow behavior.
By highlighting these liquidity zones, the indicator serves as a strategic aid in understanding market dynamics and enhancing decision-making in alignment with ICT principles.
📦 Features
Buyside & Sellside Liquidity
Invalidated Liquidity
Threshold
Styling
⚙️ Settings
Liquidity: Controls visibility of Bullish/Bearish Liquidity levels.
Invalidated: Displays the invalidated liquidity levels.
Levels: Controls the number of Liquidity levels that will be displayed.
Line Style: Customize the line style and width.
Threshold: Filter by swing points the Liquidity levels.
Labels: Control the Labels visibility.
⚡️ Showcase
Buyside & Sellside
Invalidated
🚨 Alerts
This script offers alert options for all signal types.
Bearish Signal
A bearish signal is generated when the price reaches a Buyside Liquidity level.
Bullish Signal
A bullish signal is generated when the price reaches a Sellside Liquidity level.
⚠️ Disclaimer
Trading involves significant risk, and many participants may incur losses. The content on this site is not intended as financial advice and should not be interpreted as such. Decisions to buy, sell, hold, or trade securities, commodities, or other financial instruments carry inherent risks and are best made with guidance from qualified financial professionals. Past performance is not indicative of future results.
Granger Causality Flow IndicatorGranger Causality Flow Indicator (GC Flow)
█ OVERVIEW
The Granger Causality Flow Indicator (GC Flow) attempts to quantify the potential predictive relationship between two user-selected financial instruments (Symbol X and Symbol Y). In essence, it explores whether the past values of one series (e.g., Symbol X) can help explain the current value of another series (e.g., Symbol Y) better than Y's own past values alone.
This indicator provides a "Granger Causality Score" (GC Score) for both directions (X → Y and Y → X). A higher score suggests a stronger statistical linkage where one series may lead or influence the other. The indicator visualizes this "flow" of potential influence through background colors and on-chart text.
Important Note: "Granger Causality" does not imply true economic or fundamental causation. It is a statistical concept indicating predictive power or information flow. This implementation also involves simplifications (notably, using AR(1) models) due to the complexities of full Vector Autoregression (VAR) models in Pine Script®.
█ HOW IT WORKS
The indicator's methodology is based on comparing the performance of Autoregressive (AR) models:
1. Data Preprocessing:
Fetches historical close prices for two user-defined symbols (X and Y).
Optionally applies first-order differencing (`price - price `) to the series. Differencing is a common technique to achieve a proxy for stationarity, which is an underlying assumption for Granger Causality tests. Non-stationary series can lead to spurious correlations.
2. Autoregressive (AR) Models (Simplified to AR(1)):
Due to Pine Script's current limitations for complex multivariate time series models, this indicator uses simplified AR(1) models (where the current value is predicted by its immediately preceding value).
Restricted Model (for Y → Y): Predicts the target series (e.g., Y) using only its own past value (Y ).
`Y = c_R + a_R * Y + residuals_R`
The variance of `residuals_R` (Var_R) is calculated.
Unrestricted Model (Proxy for X → Y): To test if X Granger-causes Y, the indicator examines if the past values of X (X ) can explain the residuals from the restricted model of Y.
`residuals_R = c_UR' + b_UR * X + residuals_UR`
The variance of these final `residuals_UR` (Var_UR) is calculated.
The same process is repeated to test if Y Granger-causes X.
3. Granger Causality (GC) Score Calculation:
The GC Score quantifies the improvement in prediction from adding the other series' past values. It's calculated as:
`GC Score = 1 - (Var_UR / Var_R)`
A score closer to 1 suggests that the "causing" series significantly reduces the unexplained variance of the "target" series (i.e., Var_UR is much smaller than Var_R), indicating stronger Granger causality.
A score near 0 (or capped at 0 if Var_UR >= Var_R) suggests little to no improvement in prediction.
The score is calculated over a rolling `Calculation Window`.
Pine Script® Snippet (Conceptual GC Score Logic):
// Conceptual representation of GC Score calculation
// var_R: Variance of residuals when Y is predicted by Y
// var_UR: Variance of residuals when Y's AR(1) residuals are predicted by X
score = 0.0
if var_R > 1e-9 // Avoid division by zero
score := 1.0 - (var_UR / var_R)
score := score < 0 ? 0 : score // Ensure score is not negative
4. Determining Causal Flow:
The calculated GC Scores for X → Y and Y → X are compared against a user-defined `Significance Threshold for GC Score`.
If GC_X→Y > threshold AND GC_Y→X > threshold: Bidirectional flow.
If GC_X→Y > threshold only: X → Y flow.
If GC_Y→X > threshold only: Y → X flow.
Otherwise: No significant flow.
█ HOW TO USE IT
Interpreting the Visuals:
Background Color:
Green: Indicates X → Y (Symbol 1 potentially leads Symbol 2).
Orange: Indicates Y → X (Symbol 2 potentially leads Symbol 1).
Blue: Indicates Bidirectional influence.
Gray: No significant Granger causality detected based on the threshold.
Data Window Plots: The actual GC Scores for X → Y (blue) and Y → X (red) are plotted and visible in TradingView's Data Window. A dashed gray line shows your `Significance Threshold`.
On-Chart Table (Last Bar): Displays the currently detected causal direction text (e.g., "BTCUSDT → QQQ").
Potential Applications:
Intermarket Analysis: Explore potential lead-lag relationships between different asset classes (e.g., commodities and equities, bonds and currencies).
Pair Trading Components: Identify if one component of a potential pair tends to lead the other.
Confirmation Tool: Use alongside other analyses to see if a move in one asset might foreshadow a move in another.
Considerations:
Symbol Choice: Select symbols that have a plausible economic or market relationship.
Stationarity: Granger Causality tests ideally require stationary time series. The `Use Differencing` option is a simple proxy. True stationarity testing is complex. Non-stationary data can yield misleading results.
Lag Order (p): This indicator is fixed at p=1 due to Pine Script® limitations. In rigorous analysis, selecting the optimal lag order is crucial.
Calculation Window: Shorter windows are more responsive but may be noisier. Longer windows provide smoother scores but lag more.
Significance Threshold: Adjust this based on your desired sensitivity for detecting causal links. There's no universally "correct" threshold; it depends on the context and noise level of the series.
█ INPUTS
Symbol 1 (X): The first symbol in the analysis.
Symbol 2 (Y): The second symbol (considered the target when testing X → Y).
Use Differencing: If true, applies first-order differencing to both series as a proxy for stationarity.
Calculation Window (N): Lookback period for AR model coefficient estimation and variance calculations.
Lag Order (p): Currently fixed at 1. This defines the lag used (e.g., X , Y ) in the AR models.
Significance Threshold for GC Score: A value between 0.01 and 0.99. The calculated GC Score must exceed this to be considered significant.
█ VISUALIZATION
Background Color: Dynamically changes based on the detected Granger causal flow (Green for X → Y, Orange for Y → X, Blue for Bidirectional, Gray for None).
GC Scores (Data Window):
Blue Plot: GC Score for X → Y.
Red Plot: GC Score for Y → X.
Significance Threshold Line: A dashed gray horizontal line plotted at the level of your input threshold.
On-Chart Table: Displayed on the top-right (on the last bar), showing the current causal direction text.
█ ALERTS
The indicator can generate alerts for:
Emergence of X → Y causality.
Emergence of Y → X causality.
General change or cessation of a previously detected causal relationship.
█ IMPORTANT DISCLAIMERS & LIMITATIONS
Correlation vs. Causation: Granger causality measures predictive power, not true underlying economic causation. A strong GC Score doesn't prove one asset *causes* another to move, only that its past values improve predictions.
Stationarity Assumption: While differencing is offered, it's a simplified approach. Non-stationary data can lead to spurious (false) Granger causality detection.
Model Simplification (AR(1)): This script uses AR(1) models for simplicity. Real-world relationships can involve more complex dynamics and higher lag orders. The fixed lag of p=1 is a significant constraint.
Sensitivity to Parameters: Results can be sensitive to the chosen symbols, calculation window, differencing option, and significance threshold.
No Statistical Significance Testing (p-values): This indicator uses a direct threshold on the GC Score itself, not a formal statistical test (like an F-test producing p-values) typically found in econometric software.
Use this indicator as an exploratory tool within a broader analytical framework. Do not rely on it as a standalone basis for trading decisions.
█ CREDITS & LICENSE
Author: mastertop ( Twitter: x.com )
Version: 1.0 (Released: 2025-05-08)
This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
© mastertop, 2025