WIN1! • Crossing EMAs• (By Mesquita, v7)Moving average crossover strategy for intraday movements, especially in the continuous index (WIN1!) on the Brazilian stock exchange B³. The strategy is customizable for time windows, has a filter for trades only above the long-term average, whether only long, only short, or both, with or without stop loss.
Educational
KZ One — Scalping Training StrategyKZ One is a scalping strategy developed for M1 and M5 timeframes. It is designed to help traders study and practice short-term market behavior by using structured zones to highlight potential entry and exit areas. The strategy allows customization of Risk (USD) and Take Profit (R multiple) parameters for flexible trade management. Additional tools include ATR-based filters to skip low-volatility conditions and a Pre-Alert Lead (bars) option that notifies users ahead of possible setups. KZ One is intended for educational and analytical purposes, promoting disciplined and consistent trading practice.
RAFEN-G - Kill Zones & Institutional Gaps🔍 What It Does
Kill Zones (KZ1, KZ2, KZ3)
Automatically highlights the main intraday liquidity windows such as the London open, NY AM, and NY PM sessions — customizable by time, color, and transparency.
Perfect for timing setups, identifying liquidity sweeps, or backtesting session behavior.
Institutional GAP Detection (NY 11:00 → 03:00)
Anchored on the New York H1 clock, the script automatically draws the “institutional gap” between the 11:00 close and the 03:00 open of the next trading day.
Each gap is drawn as a transparent box with a label showing its size in price units.
Dynamic Cleanup & Color Updates
Automatically removes old boxes beyond your chosen history limit and keeps all visuals perfectly synchronized in real-time.
⚙️ Key Features
3 fully independent and editable Kill Zones
Adjustable timezone (default: America/New_York)
Works on all intraday timeframes
Auto-management of historical data
Clean and lightweight visuals (up to 2000 boxes)
Real-time color and transparency updates
Alerts when each Kill Zone starts
🧠 Ideal For
Traders using ICT, SMC, or institutional frameworks who want clear visual separation of market sessions and automatic tracking of session-to-session gaps for confluence or imbalance analysis.
🕐 Recommended Use
Apply on 5 min / 15 min / 1 h charts, align timezone to NYC, and combine with liquidity or FVG tools for maximum insight.
VCP ScreenerThis screener:
• Detect tight price contraction using ATR
• Check for volume contraction
• Confirm trend strength using moving averages
• Flag stocks near recent resistance
[KF] Multi-Duration Rate Expectations IndicatorAfter last fed cut in Oct then following jump in rates, I was frustrated at not having access to good rate expectations vs actual because the market usually prices in prior to fed action. This indicator was developed to make futures market rate expectations accessible and interpretable without requiring professional bond analytics systems.
Summary
This Pine Script indicator reveals what the futures market expects for interest rates across three key durations: Fed Funds (overnight), 2-Year, and 10-Year Treasury yields. By comparing futures-implied rates against current spot yields, it provides a clear visual signal of whether the market expects rates to rise, fall, or remain steady.
Understanding Rate Futures
Fed Funds futures (ZQ1!) use a simple design where the expected rate equals 100 minus the futures price. If ZQ1! trades at 96.12, the market expects a 3.88% Fed Funds rate. Treasury futures work differently - they trade as bond prices (typically 102-115) that move inversely to yields. Converting Treasury futures to implied yields requires complex bond mathematics involving duration and conversion factors.
This indicator solves the Treasury futures complexity by implementing a self-calibrating sensitivity model. It observes the historical relationship between futures prices and yields, then uses this to project rate expectations. The model also compares front-month to next-month contracts to detect expected rate direction, automatically adapting as market conditions change.
How to Use
Add the indicator to any chart and select your desired duration in the settings. The display shows the futures-implied rate, current yield, and the difference between them. Green indicates the market expects higher rates, red means lower expectations, and gray shows expectations in line with current rates.
The indicator excels at identifying divergences between market expectations and current rates, which often precede rate movements or futures repricing. Comparing expectations across different durations reveals insights about yield curve positioning and Fed policy anticipation.
Technical Note
While Fed Funds futures provide exact rate expectations, Treasury futures conversions are sophisticated approximations that provide reliable directional signals and reasonable magnitude estimates sufficient for most trading applications.
💸 DCA Accumulation Strategy (USD‑Based Scaling)Buy when blue arrow appears, if the next arrow is lower than the last increase your position. This will pull your average cost down slowly over time.
Gann Astronomical Turning PointsThis is a comprehensive Pine Script that implements W.D. Gann's astronomical theories to identify potential market turning points. Here's a detailed breakdown of the script:
Overview
The script identifies and displays astronomical events (sun angles, moon phases, and Mercury retrogrades) that Gann theorists believe correlate with market turning points. It also analyzes historical price performance following these events to provide statistical significance.
Key Components
1. Input Parameters
Date Range: Users can set the analysis period (start and end dates)
Display Options: Toggle visibility of different astronomical events and tables
Analysis Settings: Configure the lookback period for price change analysis (1-20 days)
2. Astronomical Calculations
The script includes several functions to calculate celestial positions:
getDaysSinceEpoch(t): Calculates days since January 1, 2000 (reference point)
getSunLongitude(t): Computes the Sun's position in the ecliptic (0-360°)
getMoonPhase(t): Determines the Moon's phase angle relative to the Sun
getMercuryLongitude(t): Calculates Mercury's position in the ecliptic
3. Gann Critical Angles (Sun Events)
The script identifies when the Sun reaches four critical angles that Gann considered significant:
0° Aries (Spring Equinox)
90° Cancer (Summer Solstice)
180° Libra (Fall Equinox)
270° Capricorn (Winter Solstice)
These are detected by tracking when the Sun's longitude crosses these specific angles.
4. Moon Phases
Four key moon phases are identified:
New Moon: Moon passes between Earth and Sun
First Quarter: Moon is 90° east of Sun
Full Moon: Moon is opposite the Sun
Last Quarter: Moon is 270° east of Sun
5. Mercury Retrograde Periods
The script detects when Mercury appears to move backward in its orbit:
Identifies start and end dates of retrograde motion
Displays these periods as highlighted zones on the chart
6. Price Change Analysis
For each astronomical event, the script:
Calculates the percentage price change over a user-defined lookback period
Categorizes changes as positive or negative
Stores this data for statistical analysis
7. Statistical Significance
The script calculates several metrics for each event type:
Average Price Change: Mean percentage change following events
Up/Down Ratio: Number of positive vs. negative changes
Accuracy Percentage: How often the dominant direction occurred
8. Visual Elements
The script includes multiple display components:
Event Labels
Sun Angles: Orange sun symbols displayed above price bars
Moon Phases: Moon phase emojis displayed below price bars
Mercury Retrograde: Red boxes highlighting the retrograde periods
Information Tables
Events Table: Shows upcoming and recent astronomical events
Significance Analysis Table: Displays statistical performance of each event type
Forecast Section: Identifies the next upcoming event and predicted direction
9. Forecasting Functionality
The script predicts market direction for the next astronomical event based on:
Historical average price change for that event type
Statistical accuracy of previous similar events
Color-coded forecast (green for bullish, red for bearish)
This script offers an interesting implementation of Gann's astronomical theories, but should be used as part of a broader analysis rather than as a standalone trading system.
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.
Trailing 12M % Gain/Lossthis script shows profit or loss for training 12 months, works only on daily time frame
Custom Checklist# Custom Checklist - Trading Preparation & Reminders
A fully customizable checklist overlay indicator for TradingView that helps traders maintain discipline and follow their trading routine systematically.
## 🎯 Purpose
This indicator serves as a visual reminder system on your charts to ensure you complete all necessary analysis steps before entering a trade. Perfect for traders who want to maintain consistency and avoid emotional or rushed trading decisions.
## ✨ Key Features
- **20 Customizable Lines**: Create your own checklist items with any text you need
- **Flexible Display Options**:
- Show/hide title header
- Toggle entire checklist on/off
- Position anywhere on chart (9 positions available)
- Adjustable text size (tiny to huge)
- **Symbol Filtering**: Option to show checklist only on specific symbols (BTC/USD, GOLD, SPX500, USOIL)
- **Customizable Appearance**:
- Background color
- Text color
- Border color
- Transparency controls
- **Clean Interface**: Empty by default - add only the items you need
## 📋 Use Cases
- **Morning Routine**: Daily market preparation checklist
- **Trade Entry Rules**: Verify all setup conditions are met
- **Risk Management**: Confirm stop-loss, position size, and exit strategy
- **Multi-Timeframe Analysis**: Ensure you checked all required timeframes
- **Technical Analysis**: Track which indicators and patterns you've reviewed
- **News & Events**: Remember to check economic calendar and news
- **Personal Rules**: Your custom trading rules and reminders
## 🎨 Customization
Every aspect is customizable:
- All 20 lines can be edited to your needs
- Only non-empty lines are displayed
- Table position adjustable to any corner or middle position
- Color scheme fully customizable to match your chart theme
- Text size scalable for different screen sizes
## 💡 How to Use
1. Add indicator to your chart
2. Open Settings > Checklist Items
3. Fill in your checklist items (Line 1, Line 2, etc.)
4. Customize colors and position in Display Settings
5. Optional: Enable "Show Only on Specific Symbols" to show on select instruments
## 🔧 Display Settings
- **Checklist Title**: Custom header for your checklist
- **Show Title Header**: Toggle title display
- **Show Checklist**: Master on/off switch
- **Symbol Filter**: Restrict display to specific trading instruments
- **Position**: 9 placement options (corners and middle positions)
- **Text Size**: 5 size options (tiny, small, normal, large, huge)
- **Colors**: Background, text, and border fully customizable
## 📝 Example Checklist Ideas
**Swing Trading:**
- Support/Resistance levels identified
- Trend direction confirmed
- Volume analysis completed
- RSI/MACD signals checked
- Risk/Reward ratio calculated
**Day Trading:**
- Pre-market review done
- Key levels marked
- Economic calendar checked
- Trading plan written
- Position size calculated
**Technical Analysis:**
- Multiple timeframe alignment
- Chart patterns identified
- Moving averages reviewed
- Fibonacci levels drawn
- Volume profile analyzed
## ⚙️ Technical Details
- Pine Script v6
- Overlay indicator (displays on main chart)
- Lightweight - no complex calculations
- No repainting
- Works on all timeframes and instruments
## 🎓 Perfect For
- Beginner traders learning systematic analysis
- Experienced traders maintaining discipline
- Anyone who wants visual trading reminders
- Traders following multi-step strategies
- Those prone to FOMO or emotional trading
---
**Note**: This is a visual tool only. It does not generate trading signals or perform analysis. It serves as a reminder checklist to help you follow your own trading process consistently.
Fibonacci Auto Retracement & HTF candles ReferenceAdvanced Higher Timeframe (HTF) Candle & Fibonacci Viewer
Overview:
The Advanced HTF Candle & Fibonacci Viewer is a professional Trading View indicator designed to help traders overlay higher timeframe price structures onto lower timeframe charts. By combining daily candle analysis with precise Fibonacci retracement levels, this tool allows traders to identify critical support and resistance zones, potential breakouts, and retracement opportunities without switching charts.
Special Thanks:
This script includes a small part of coding inspired by Zeiierman, whose work on HTF analysis provided the foundation for visualizing higher timeframe structures. Full credit to Zeiierman for their invaluable contribution to the Trading View community.
Key Features:
1. Multi-Day HTF Range Display
Automatically displays high and low of 1–7 previous days.
Highlights candle bodies and wicks for clear structure visualization.
Ideal for spotting daily ranges and breakout levels.
2. Dynamic Fibonacci Levels
Standard levels: 0%, 11.8%, 23.6%, 38.2%, 50%, 61.8%, 76.4%, 88.2%, 100%.
Optional mid-level lines for intraday support/resistance identification.
Levels adjust automatically to reflect price action direction.
3. Customizable Labels & Colors
Adjustable text size, color, transparency, and offset.
Fully customizable candle and Fibonacci colors.
Mid-level lines can be shown or hidden for a cleaner look.
4. Persistent Levels
Levels remain until the next trading session or breakout, helping track trends and retracements consistently.
5. Multi-Timeframe Optimization
Works on any chart timeframe, from 1-minute to weekly charts.
Provides higher timeframe insight while trading on lower timeframes.
Why Traders Love This Indicator:
View higher timeframe action without switching charts.
Identify high-probability entry and exit zones.
Combine with other indicators for complete market analysis.
Useful for swing traders, day traders, and scalpers alike.
Customization Options:
Number of previous days (1–7)
Show/hide mid-level lines
Show/hide labels
Customize label size, color, and offset
Customize Fibonacci and candle colors
Ideal Use Cases:
Swing Trading: Identify daily key levels for entry, exit, and stop-loss.
Day Trading: Use HTF ranges on intraday charts to spot breakouts and reversals.
Fibonacci Analysis: Locate retracement zones efficiently.
Trend Confirmation: Validate trades with higher timeframe structure.
Summary:
The Advanced HTF Candle & Fibonacci Viewer is a powerful tool for traders seeking clarity, structure, and precision. With higher timeframe insight overlaid on active charts and proper credit to Zeiierman for their HTF coding contribution, this indicator helps traders make informed, confident decisions in any market.
ATR + EMA + Sessions ProATR + EMA + Sessions Pro By Saeed Fadi to save indicator space, it,s for atr, emas, sessions etc.
SPX 0dte Options TableSPX 0DTE Options Table Indicator 📊
Version: Pine Script v6
Description: A real-time table overlay for 0DTE SPX options, showing strikes, prices, and volumes for calls/puts. Perfect for intraday traders spotting high-volume opportunities!
Perfect for fast look up for options premium ( Real time data required $2/month)
Key Features
Dynamic Table: Displays current SPX price, call/put strikes (e.g., 5700C/5600P), last prices, and volumes in a clean overlay.
Custom Strikes: 1-15 per side (default: 8), with increments of 5+ (default: 10). Strikes rounded to multiples of 10.
Strike Offset: Fixed (default: 0) or dynamic based on remaining trading hours (US session: 9:30 AM-4:00 PM ET, e.g., 6+ hours = ±40).
SPX Handling: Fixed value (default: 6850) or dynamic from open (default: 60-min timeframe).
Data Fetch: OPRA tickers on last bar; customizable timeframe (default: 1-min).
Volume Alerts: Trigger on > threshold (default: 600) if price ≥$1. JSON alerts with ET timestamp.
Customization: Table position, colors, text size (tiny/small/normal/large).
Optimizations: Array-based; weekend-aware; real-time focus.
Limitations: Needs OPRA data access; no historicals; use fixed SPX to avoid open-update errors.
3D Institutional Battlefield [SurgeGuru]Professional Presentation: 3D Institutional Flow Terrain Indicator
Overview
The 3D Institutional Flow Terrain is an advanced trading visualization tool that transforms complex market structure into an intuitive 3D landscape. This indicator synthesizes multiple institutional data points—volume profiles, order blocks, liquidity zones, and voids—into a single comprehensive view, helping you identify high-probability trading opportunities.
Key Features
🎥 Camera & Projection Controls
Yaw & Pitch: Adjust viewing angles (0-90°) for optimal perspective
Scale Controls: Fine-tune X (width), Y (depth), and Z (height) dimensions
Pro Tip: Increase Z-scale to amplify terrain features for better visibility
🌐 Grid & Surface Configuration
Resolution: Adjust X (16-64) and Y (12-48) grid density
Visual Elements: Toggle surface fill, wireframe, and node markers
Optimization: Higher resolution provides more detail but requires more processing power
📊 Data Integration
Lookback Period: 50-500 bars of historical analysis
Multi-Source Data: Combine volume profile, order blocks, liquidity zones, and voids
Weighted Analysis: Each data source contributes proportionally to the terrain height
How to Use the Frontend
💛 Price Line Tracking (Your Primary Focus)
The yellow price line is your most important guide:
Monitor Price Movement: Track how the yellow line interacts with the 3D terrain
Identify Key Levels: Watch for these critical interactions:
Order Blocks (Green/Red Zones):
When yellow price line enters green zones = Bullish order block
When yellow price line enters red zones = Bearish order block
These represent institutional accumulation/distribution areas
Liquidity Voids (Yellow Zones):
When yellow price line enters yellow void areas = Potential acceleration zones
Voids indicate price gaps where minimal trading occurred
Price often moves rapidly through voids toward next liquidity pool
Terrain Reading:
High Terrain Peaks: High volume/interest areas (support/resistance)
Low Terrain Valleys: Low volume areas (potential breakout zones)
Color Coding:
Green terrain = Bullish volume dominance
Red terrain = Bearish volume dominance
Purple = Neutral/transition areas
📈 Volume Profile Integration
POC (Point of Control): Automatically marks highest volume level
Volume Bins: Adjust granularity (10-50 bins)
Height Weight: Control how much volume affects terrain elevation
🏛️ Order Block Detection
Detection Length: 5-50 bar lookback for block identification
Strength Weighting: Recent blocks have greater impact on terrain
Candle Body Option: Use full candles or body-only for block definition
💧 Liquidity Zone Tracking
Multiple Levels: Track 3-10 key liquidity zones
Buy/Sell Side: Different colors for bid/ask liquidity
Strength Decay: Older zones have diminishing terrain impact
🌊 Liquidity Void Identification
Threshold Multiplier: Adjust sensitivity (0.5-2.0)
Height Amplification: Voids create significant terrain depressions
Acceleration Zones: Price typically moves quickly through void areas
Practical Trading Application
Bullish Scenario:
Yellow price line approaches green order block terrain
Price finds support in elevated bullish volume areas
Terrain shows consistent elevation through key levels
Bearish Scenario:
Yellow price line struggles at red order block resistance
Price falls through liquidity voids toward lower terrain
Bearish volume peaks dominate the landscape
Breakout Setup:
Yellow price line consolidates in flat terrain
Minimal resistance (low terrain) in projected direction
Clear path toward distant liquidity zones
Pro Tips
Start Simple: Begin with default settings, then gradually customize
Focus on Yellow Line: Your primary indicator of current price position
Combine Timeframes: Use the same terrain across multiple timeframes for confluence
Volume Confirmation: Ensure terrain peaks align with actual volume spikes
Void Anticipation: When price enters voids, prepare for potential rapid movement
Order Blocks & Voids Architecture
Order Blocks Calculation
Trigger: Price breaks fractal swing points
Bullish OB: When close > swing high → find lowest low in lookback period
Bearish OB: When close < swing low → find highest high in lookback period
Strength: Based on price distance from block extremes
Storage: Global array maintains last 50 blocks with FIFO management
Liquidity Voids Detection
Trigger: Price gaps exceeding ATR threshold
Bull Void: Low - high > (ATR200 × multiplier)
Bear Void: Low - high > (ATR200 × multiplier)
Validation: Close confirms gap direction
Storage: Global array maintains last 30 voids
Key Design Features
Real-time Updates: Calculated every bar, not just on last bar
Global Persistence: Arrays maintain state across executions
FIFO Management: Automatic cleanup of oldest entries
Configurable Sensitivity: Adjustable lookback periods and thresholds
Scientific Testing Framework
Hypothesis Testing
Primary Hypothesis: 3D terrain visualization improves detection of institutional order flow vs traditional 2D charts
Testable Metrics:
Prediction Accuracy: Does terrain structure predict future support/resistance?
Reaction Time: Faster identification of key levels vs conventional methods
False Positive Reduction: Lower rate of failed breakouts/breakdowns
Control Variables
Market Regime: Trending vs ranging conditions
Asset Classes: Forex, equities, cryptocurrencies
Timeframes: M5 to H4 for intraday, D1 for swing
Volume Conditions: High vs low volume environments
Data Collection Protocol
Terrain Features to Quantify:
Slope gradient changes at price inflection points
Volume peak clustering density
Order block terrain elevation vs subsequent price action
Void depth correlation with momentum acceleration
Control Group: Traditional support/resistance + volume profile
Experimental Group: 3D Institutional Flow Terrain
Statistical Measures
Signal-to-Noise Ratio: Terrain features vs random price movements
Lead Time: Terrain formation ahead of price confirmation
Effect Size: Performance difference between groups (Cohen's d)
Statistical Power: Sample size requirements for significance
Validation Methodology
Blind Testing:
Remove price labels from terrain screenshots
Have traders identify key levels from terrain alone
Measure accuracy vs actual price action
Backtesting Framework:
Automated terrain feature extraction
Correlation with future price reversals/breakouts
Monte Carlo simulation for significance testing
Expected Outcomes
If hypothesis valid:
Significant improvement in level prediction accuracy (p < 0.05)
Reduced latency in institutional level identification
Higher risk-reward ratios on terrain-confirmed trades
Research Questions:
Does terrain elevation reliably indicate institutional interest zones?
Are liquidity voids statistically significant momentum predictors?
Does multi-timeframe terrain analysis improve signal quality?
How does terrain persistence correlate with level strength?
LuxAlgo BigBeluga hapharmonic
Dual FUT/Spot price with next monthly expiryThis Pine Script dashboard indicator is specifically designed for pair trading strategies in Indian futures markets (NSE). Let me break down how it facilitates pair trading:
Core Pair Trading Concept
The script monitors two correlated stocks simultaneously (Symbol A and Symbol B), comparing their:
Spot prices vs Futures prices
Current month futures vs Next month futures
Premium/discount relationships
Key Pair Trading Features
1. Dual Symbol Monitoring
symbolA = "NSE:TCS" (Default)
symbolB = "NSE:INFY" (Default)
Allows traders to watch two stocks in the same sector (like TCS and Infosys in IT) to identify relative value opportunities.
2. Basis Analysis for Each Stock
The indicator calculates the basis (difference between futures and spot):
Price Difference: FUT - SPOT
Premium/Discount %: ((FUT - SPOT) / SPOT) × 100
This helps identify when one stock's futures are relatively more expensive than the other's.
3. Multi-Expiry View
Near Month Futures (1!): Current active contract
Next Month Futures (2!): Upcoming contract
This enables calendar spread analysis within each stock and helps anticipate rollover effects.
4. Comparative Table
The detailed table displays side-by-side:
Symbol Spot Price Near Future Near Diff (%)Next Monthly Next Diff (%)Lot SizeTCS₹3,500₹3,520+20 (+0.57%)₹3,535+35 (+1.00%)125INFY₹1,450₹1,455+5 (+0.34%)₹1,460+10 (+0.69%)600
5. Lot Size Integration
Critical for position sizing in pair trades - the indicator fetches actual contract lot sizes, enabling proper hedge ratio calculations.
Pair Trading Strategies Enabled
Strategy 1: Basis Divergence Trading
When TCS futures trade at +0.8% premium and INFY at +0.2%
Trade: Short TCS futures, Long INFY futures (betting on convergence)
The indicator highlights these differences with color-coded cells
Strategy 2: Calendar Spread Arbitrage
Compare near month vs next month premium for each stock
If TCS shows wider calendar spread than INFY, potential arbitrage exists
Trade the relative calendar spread difference
Strategy 3: Premium/Discount Reversal
Monitor which stock moves from premium to discount (or vice versa)
Color indicators (green/red) make this immediately visible
Enter pairs when relative premium relationships normalize
Strategy 4: Lot-Adjusted Pair Trading
Use lot size data to create market-neutral positions
Example: If TCS lot = 125 and INFY lot = 600
Ratio = 600/125 = 4.8:1 for rupee-neutral positioning
Visual Trading Cues
Green cells: Futures at premium (contango)
Red cells: Futures at discount (backwardation)
Purple values: Next month contracts
Yellow highlights: Spot prices
Practical Pair Trading Example
Scenario: Both stocks in same sector, historically correlated
Normal state: Both show +0.5% premium
Divergence: TCS jumps to +1.2%, INFY stays at +0.5%
Trade Signal:
Short TCS futures (expensive)
Long INFY futures (relatively cheap)
Exit: When premiums converge back to similar levels
Hedge ratio: Use lot sizes to maintain proper exposure balance
Advantages for Pair Traders
✓ Single-screen monitoring of both legs
✓ Real-time basis calculations eliminate manual math
✓ Multi-timeframe view (near + next month)
✓ Automatic lot size fetching for position sizing
✓ Visual alerts through color coding
✓ Percentage normalization for easy comparison
This indicator essentially transforms raw price data into actionable pair trading intelligence by highlighting relative value discrepancies between correlated assets in the futures market.
Enjoy!!
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.
ka66: Symbol InformationThis shows a table of all current (Pine v6) `syminfo.` values.
Please note this is primarily of use to Pine Developers, or the curious trader.
There are a few of these around on TradingView, but many seem to focus on the use case they have. This script just dumps all values, in alphabetical order of properties.
You can use this to inspect the details of the symbol, which in turn, can be fed into various scripts covering tasks such as:
Position Sizing calculation (which requires things like tick, pointvalue, and currency details)
Recommendation engines (which use the recommendation_* properties)
Fundamentals on stocks (which may use share count information, and possibly employee information)
Note that not all table values are populated, as they depend on the instrument being introspected. For example, a share ticker will have some different details to a Forex pair. The `NaN` values (the "Not A Number" special value in programming parlance) are not a bug, they are simply Pine reporting that no value is set for it. I have opted to dump out values as-is as the focus is developers.
My motivation to create it was to write a position sizing tool. Additionally, the output of this script is cleanly formatted, with monospace fonts and conventional alignment for tables/forms with key and values. It also allows customising the table position. Ideally this feature is made part of the default TradingView customisation, but at this time, it is not, and tables don't auto-adjust their positions.
Smart Money Volume Tools | Lyro RSSmart Money Volume Tools | Lyro RS
Overview
The Smart Money Volume Tools (SMVT) is a multi-dimensional volume-based analysis suite designed to visualize the interplay between price action, moving averages, and smart money behavior.
By integrating dynamic moving averages, volume normalization, and multi-timeframe intelligence, SMVT helps traders identify when institutional (smart money) or retail participants are influencing price movements — all in a single, adaptive display.
Unlike traditional oscillators or trend tools, SMVT dynamically adjusts its sensitivity and thresholds based on volume z-scores and normalized momentum, revealing true intent behind price shifts rather than reacting to them.
🔹 Key Features
4 Core Analytical Modes:
Trail Mode – Identifies directional bias using dynamic volume-weighted trails based on adaptive ATR multipliers.
Volume Mode – Displays normalized volume strength vs. price trend, highlighting volume-driven expansions.
Smart Money Volume Mode – Detects institutional buying/selling spikes from lower timeframes using volume z-score outliers.
Retail Money Volume Mode – Contrasts retail-driven impulses to visualize crowd behavior and exhaustion points.
Dynamic Volume Normalization: Converts volume impulses into a 0–100 range using a sigmoid function for smoother interpretation.
Multi-Timeframe Intelligence: Automatically reads lower timeframe volume data to distinguish smart vs. retail activity.
Adaptive Color Systems: Multiple palette modes ( Classic , Mystic , Accented , Royal ) or full custom color control.
Signal Table Overlay: Built-in real-time module summary showing status for Trail , Volume , Smart Money , and Retail Money — right on your chart.
🔹 How It Works
Volume Strength Calculation:
Calculates relative volume strength using a moving average baseline, then normalizes the result via a sigmoid function — mapping activity into a clean 0–100 range.
Smart Money Detection:
Scans lower timeframe data for extreme volume z-scores ( z > 2 ) to pinpoint institutional accumulation or distribution zones.
Trail Logic:
Uses adaptive upper and lower trails based on ATR and volume intensity to track volatility-adjusted trend direction.
Color Logic:
Trail, candle, and fill colors change dynamically according to the active signal type and selected palette — making directional bias instantly visible.
🔹 Practical Use
Swing Confirmation (Trail Mode): Confirms sustained bullish or bearish momentum supported by volume, ideal for trailing positions and managing exits.
Volume Expansion (Volume Mode): Highlights key moments when institutional liquidity pushes price before visible breakout confirmation.
Smart vs. Retail Divergence: Identify conflicts between retail activity and smart money to detect exhaustion or reversal points early.
Table Overlay Utility: Instantly see all active signals across modules in one compact, on-chart interface.
🔹 Customization
Custom color palettes or manual bullish/bearish color selection.
Adjustable EMA lengths and Volume SMA period .
Selectable lower timeframe source for Smart Money analysis.
Flexible table position & size controls — choose between Top, Middle, Bottom and Tiny to Huge.
Switch freely between Trail , Volume , Smart Money , and Retail Money modes.
Credits
Thank you to @AlgoAlpha for the smart money and retail activity source code.
⚠️Disclaimer
This indicator is a tool for technical analysis and does not provide guaranteed results. It should be used in conjunction with other analysis methods and proper risk management practices. The creators of this indicator are not responsible for any financial decisions made based on its signals.
Trade Journal ProTrade Journal Pro
A powerful, visual trading journal that enforces discipline with real-time feedback, reflective prompts, and strict risk limits — all in one clean overlay box.
Jesus is King — trade with wisdom, not emotion.
FEATURES
• AUTO-CALCULATED DAILY TRADES
→ `Trades Today = Wins + Losses + Breakevens` (no manual input needed)
• 4 ENFORCED RISK LIMITS
1. Max Trades Per Day
2. Max Risk Rule Violations
3. Max Consecutive Losses (tilt protection)
4. Max Total Losses Allowed (lifetime/session cap)
• SMART VISUAL FEEDBACK
• GREEN BOX = You hit a limit exactly → “WELL DONE!”
• RED BOX = Breached any limit → “STOP & REFLECT” + ALERT
• Dark = Normal (under all limits)
• REFLECTIVE PROMPTS (Customizable)
1. Why this setup?
2. What was my emotional state?
3. Did I follow my plan?
• LIVE ADVICE ENGINE
→ Win: “Great execution! Log what worked.”
→ Loss: “Loss = tuition. What did you learn?”
→ Breakeven: “Review entry/exit precision.”
• DAILY REMINDER
→ Always visible: “Trade the plan, not the emotion.”
• FULLY CUSTOMIZABLE
• Font size (Tiny → Huge)
• Box position (bars to the right)
• Toggle: Metrics / Prompts / Advice
• Custom colors, messages, limits
• ALERTS
• Breach any limit → Immediate alert
• Hit limit exactly → Discipline win notification
HOW TO USE
1. After each closed trade:
→ Update Wins, Losses, or Breakevens
→ Update Consecutive Losses (reset to 0 on win/BE)
→ Increment Risk Violations if you broke a rule
2. Answer the 3 prompts in your journal
3. Let the box guide your behavior:
• GREEN = Celebrate discipline
• RED = STOP TRADING. Reflect. Reset.
Perfect for day traders, swing traders, or anyone building a professional edge through journaling and risk control.
No strategy entries. No repainting. Pure accountability.
“The market is a mirror. This journal is the polish.”
Developed with integrity. Built to protect your capital — and your peace.
Sunmool's NY Lunch Model BacktestingICT NY Lunch Model Backtesting (12:00–13:00 NY) 🗽🍔
This research indicator tests an ICT narrative using the New York lunch window (12:00–13:00 America/New_York). It records that hour’s high/low and measures, during the post-lunch session (default 13:00–16:00), how often:
⬆️ If the afternoon trends up, the Lunch Low gets swept first.
⬇️ If the afternoon trends down, the Lunch High gets swept first.
It reports these as conditional probabilities, not trade signals. 📈
👀 What it shows
🟦 Lunch Range box (toggle): high/low from 12:00–13:00 NY
🔻🔺 Sweep signals (bar-anchored)
Low sweep: triangle below bar + optional “L”
High sweep: triangle above bar + optional “H”
🧱 Optional small box wrapping the swept candle
📊 Stats table (top-right)
P(L-swept | Up) — % of Up-days where Lunch Low was swept
P(H-swept | Down) — % of Down-days where Lunch High was swept
🔁 Contradictions + sample sizes (Up-days / Down-days)
🎯 Direction logic (Up/Down)
Anchor: 13:00 open (pmOpen) ⏰
Threshold: ATR × multiple or % from 13:00
Close ≥ pmOpen + threshold → Up-day
Close ≤ pmOpen − threshold → Down-day
Tiny moves under the threshold are ignored to reduce noise 🧹
⚙️ Inputs
🌐 Timezone: America/New_York (DST handled)
🍽️ Lunch window: 1200–1300
🕓 Post-lunch window: default 1300–1600 (try 17:00/20:00 for sensitivity)
📐 Trend threshold: ATR / Percent (with length/multiple or % level)
📅 Weekdays-only toggle (FX/Equities style)
👁️ Display toggles: Lunch box / sweep arrows / sweep text / sweep candle box / stats table
🔔 TF hint when chart TF > 15m
🧭 How to use
Use 5–15m charts for accurate lunch range capture.
Scroll ~1 year for meaningful samples.
Run sensitivity checks: vary ATR/% thresholds and the post-lunch end time.
For crypto, compare with vs without weekends. 🚀
🧠 Reading the results
High P(L-swept | Up) with a solid Up-day count ⇒ on up afternoons, lunch low is often swept.
High P(H-swept | Down) ⇒ on down afternoons, lunch high is often swept.
Lower Contradictions = cleaner tendency.
Remember: this is a probabilistic tendency, not a rule. 🎲
📝 Notes & limits
All markers (arrows, text, sweep boxes) are bar-anchored; the lunch range box is a research overlay you can toggle.
Real-time vs historical bar building can differ—interpret on bar close. 🔒
Purchasing Power vs Gold, Stocks, Real Estate, BTC (1971 = 100)Visual comparison of U.S. dollar purchasing power versus major assets since 1971, when the U.S. ended the gold standard. Each asset is normalized to 100 in 1971, showing how real value has shifted across gold, real estate, stocks, and Bitcoin over time.
Source: FRED (CPIAUCSL, SP500, MSPUS) • OANDA (XAUUSD) • TradingView (INDEX:BTCUSD/BLX)
Visualization by 3xplain
All-in-One: EMA, ORB, PM, and Anchored VWAPAll-in-One: EMA, ORB, PM, and Anchored VWAP... ema 9/20/50/100/20 + opening range break + premarket high and lows + vwap all in one indicator enjoy.. all these can be turned on and off if you only want vwap and ema or pm and orb etc..






















