Cheat Setup//@version=5
indicator("Cheat Setup", overlay=true)
// === User inputs ===
adr_period = input.int(20, title="ADR Window (days)")
lookback = input.int(100, title="Historical Lookback (bars)")
sensitivity = input.float(1.5, minval=0.5, step=0.1, title="Sensitivity (Multiplier of Avg ADR%)")
show_threshold_lines = input.bool(true, title="Show ADR% / Threshold Lines")
// === ADR% Calculation ===
// ADR% = (20-day high - 20-day low) / 20-day low × 100
adr_percent = (ta.highest(high, adr_period) - ta.lowest(low, adr_period)) / ta.lowest(low, adr_period) * 100
// Average ADR% over lookback period
avg_adr_percent = ta.sma(adr_percent, lookback)
// Adaptive threshold
adaptive_threshold = avg_adr_percent * sensitivity
// Detection condition
cheat_setup_signal = adr_percent > adaptive_threshold
// === Plotting ===
bgcolor(cheat_setup_signal ? color.new(color.green, 80) : na, title="Cheat Setup Background")
// Optional: Visual aid lines
plot(show_threshold_lines ? adr_percent : na, title="ADR(20)%", color=color.orange)
plot(show_threshold_lines ? avg_adr_percent : na, title="Average ADR%", color=color.gray)
plot(show_threshold_lines ? adaptive_threshold : na, title="Adaptive Threshold", color=color.red)
// ## What This Script Is For
// This script helps detect potential breakout zones — often called a "Cheat Setup" — before they happen.
// It's useful for identifying periods where a stock's volatility starts expanding after consolidation, which often leads to a breakout.
// ## What Is a Cheat Setup?
// A Cheat Setup is a technical setup where:
// > The price has been consolidating within a narrow range.
// > When volatility suddenly increases, it may indicate a breakout is about to occur.
// This script alerts you when that volatility expansion begins, using an adaptive threshold.
// ## How the Script Works (Step by Step)
// 1. Calculates ADR%:
// Measures how much the price has moved over the past N days (default: 20),
// using the formula: (20-day high - 20-day low) ÷ 20-day low × 100
// 2. Calculates the average ADR% over a longer lookback period (default: 100 bars).
// 3. Sets an adaptive threshold:
// The average ADR% multiplied by a user-defined sensitivity factor (e.g. 1.5×).
// 4. Triggers a cheat setup signal if the current ADR% exceeds the threshold.
// 5. Displays a green background on the chart during the signal to visually highlight the cheat area.
// 6. Optionally draws 3 reference lines:
// - Current ADR% (orange line)
// - Average ADR% (gray line)
// - Adaptive threshold (red line)
// ## How to Use the Script
// 1. Apply the script on a TradingView chart (daily timeframe is recommended).
// 2. Select a stock (e.g. AAPL, TSLA, 0700, 9988).
// 3. Monitor for periods when the background turns green.
// 4. These green zones signal that volatility has increased — the stock may be preparing for a breakout.
// ## What to Do When You See a Green Background
// - Add the stock to your watchlist.
// - Wait for confirmation — such as a breakout above the recent consolidation range.
// - Use other indicators like RSI, volume, or moving averages to filter signals.
// - Avoid chasing; instead, use the green zone as early warning and plan your entry.
// ## Recommended Parameter Settings
// Parameter | Purpose
// ---------------------- | ---------------------------------------------------------------
// `adr_period` | Number of days to calculate ADR%, e.g. 20
// `lookback` | Number of bars to average ADR%, e.g. 100
// `sensitivity` | Multiplier for adaptive threshold. 1.5 = moderate, 2.0 = strict
// `show_threshold_lines` | Toggle visibility of the ADR%, average, and threshold lines
// If the signal appears too frequently, increase the `sensitivity`. If too few, lower it slightly.
// ## Summary
// This script identifies stocks that are showing early signs of a breakout based on abnormal volatility expansion.
// It's especially useful for traders who want to get ahead of the move — before a breakout occurs — rather than reacting to it afterward.
// If you'd like, I can extend this script to also include:
// - Volume filters
// - Consolidation zone detection
// - Alert setup
// - Breakout confirmation (e.g. close > recent high)
// Let me know if you want to take it further.
指標和策略
Categorical Market Morphisms (CMM)Categorical Market Morphisms (CMM) - Where Abstract Algebra Transcends Reality
A Revolutionary Application of Category Theory and Homotopy Type Theory to Financial Markets
Bridging Pure Mathematics and Market Analysis Through Functorial Dynamics
Theoretical Foundation: The Mathematical Revolution
Traditional technical analysis operates on Euclidean geometry and classical statistics. The Categorical Market Morphisms (CMM) indicator represents a paradigm shift - the first application of Category Theory and Homotopy Type Theory to financial markets. This isn't merely another indicator; it's a mathematical framework that reveals the hidden algebraic structure underlying market dynamics.
Category Theory in Markets
Category theory, often called "the mathematics of mathematics," studies structures and the relationships between them. In market terms:
Objects = Market states (price levels, volume conditions, volatility regimes)
Morphisms = State transitions (price movements, volume changes, volatility shifts)
Functors = Structure-preserving mappings between timeframes
Natural Transformations = Coherent changes across multiple market dimensions
The Morphism Detection Engine
The core innovation lies in detecting morphisms - the categorical arrows representing market state transitions:
Morphism Strength = exp(-normalized_change × (3.0 / sensitivity))
Threshold = 0.3 - (sensitivity - 1.0) × 0.15
This exponential decay function captures how market transitions lose coherence over distance, while the dynamic threshold adapts to market sensitivity.
Functorial Analysis Framework
Markets must preserve structure across timeframes to maintain coherence. Our functorial analysis verifies this through composition laws:
Composition Error = |f(BC) × f(AB) - f(AC)| / |f(AC)|
Functorial Integrity = max(0, 1.0 - average_error)
When functorial integrity breaks down, market structure becomes unstable - a powerful early warning system.
Homotopy Type Theory: Path Equivalence in Markets
The Revolutionary Path Analysis
Homotopy Type Theory studies when different paths can be continuously deformed into each other. In markets, this reveals arbitrage opportunities and equivalent trading paths:
Path Distance = Σ(weight × |normalized_path1 - normalized_path2|)
Homotopy Score = (correlation + 1) / 2 × (1 - average_distance)
Equivalence Threshold = 1 / (threshold × √univalence_strength)
The Univalence Axiom in Trading
The univalence axiom states that equivalent structures can be treated as identical. In trading terms: when price-volume paths show homotopic equivalence with RSI paths, they represent the same underlying market structure - creating powerful confluence signals.
Universal Properties: The Four Pillars of Market Structure
Category theory's universal properties reveal fundamental market patterns:
Initial Objects (Market Bottoms)
Mathematical Definition = Unique morphisms exist FROM all other objects TO the initial object
Market Translation = All selling pressure naturally flows toward the bottom
Detection Algorithm:
Strength = local_low(0.3) + oversold(0.2) + volume_surge(0.2) + momentum_reversal(0.2) + morphism_flow(0.1)
Signal = strength > 0.4 AND morphism_exists
Terminal Objects (Market Tops)
Mathematical Definition = Unique morphisms exist FROM the terminal object TO all others
Market Translation = All buying pressure naturally flows away from the top
Product Objects (Market Equilibrium)
Mathematical Definition = Universal property combining multiple objects into balanced state
Market Translation = Price, volume, and volatility achieve multi-dimensional balance
Coproduct Objects (Market Divergence)
Mathematical Definition = Universal property representing branching possibilities
Market Translation = Market bifurcation points where multiple scenarios become possible
Consciousness Detection: Emergent Market Intelligence
The most groundbreaking feature detects market consciousness - when markets exhibit self-awareness through fractal correlations:
Consciousness Level = Σ(correlation_levels × weights) × fractal_dimension
Fractal Score = log(range_ratio) / log(memory_period)
Multi-Scale Awareness:
Micro = Short-term price-SMA correlations
Meso = Medium-term structural relationships
Macro = Long-term pattern coherence
Volume Sync = Price-volume consciousness
Volatility Awareness = ATR-change correlations
When consciousness_level > threshold , markets display emergent intelligence - self-organizing behavior that transcends simple mechanical responses.
Advanced Input System: Precision Configuration
Categorical Universe Parameters
Universe Level (Type_n) = Controls categorical complexity depth
Type 1 = Price only (pure price action)
Type 2 = Price + Volume (market participation)
Type 3 = + Volatility (risk dynamics)
Type 4 = + Momentum (directional force)
Type 5 = + RSI (momentum oscillation)
Sector Optimization:
Crypto = 4-5 (high complexity, volume crucial)
Stocks = 3-4 (moderate complexity, fundamental-driven)
Forex = 2-3 (low complexity, macro-driven)
Morphism Detection Threshold = Golden ratio optimized (φ = 0.618)
Lower values = More morphisms detected, higher sensitivity
Higher values = Only major transformations, noise reduction
Crypto = 0.382-0.618 (high volatility accommodation)
Stocks = 0.618-1.0 (balanced detection)
Forex = 1.0-1.618 (macro-focused)
Functoriality Tolerance = φ⁻² = 0.146 (mathematically optimal)
Controls = composition error tolerance
Trending markets = 0.1-0.2 (strict structure preservation)
Ranging markets = 0.2-0.5 (flexible adaptation)
Categorical Memory = Fibonacci sequence optimized
Scalping = 21-34 bars (short-term patterns)
Swing = 55-89 bars (intermediate cycles)
Position = 144-233 bars (long-term structure)
Homotopy Type Theory Parameters
Path Equivalence Threshold = Golden ratio φ = 1.618
Volatile markets = 2.0-2.618 (accommodate noise)
Normal conditions = 1.618 (balanced)
Stable markets = 0.786-1.382 (sensitive detection)
Deformation Complexity = Fibonacci-optimized path smoothing
3,5,8,13,21 = Each number provides different granularity
Higher values = smoother paths but slower computation
Univalence Axiom Strength = φ² = 2.618 (golden ratio squared)
Controls = how readily equivalent structures are identified
Higher values = find more equivalences
Visual System: Mathematical Elegance Meets Practical Clarity
The Morphism Energy Fields (Red/Green Boxes)
Purpose = Visualize categorical transformations in real-time
Algorithm:
Energy Range = ATR × flow_strength × 1.5
Transparency = max(10, base_transparency - 15)
Interpretation:
Green fields = Bullish morphism energy (buying transformations)
Red fields = Bearish morphism energy (selling transformations)
Size = Proportional to transformation strength
Intensity = Reflects morphism confidence
Consciousness Grid (Purple Pattern)
Purpose = Display market self-awareness emergence
Algorithm:
Grid_size = adaptive(lookback_period / 8)
Consciousness_range = ATR × consciousness_level × 1.2
Interpretation:
Density = Higher consciousness = denser grid
Extension = Cloud lookback controls historical depth
Intensity = Transparency reflects awareness level
Homotopy Paths (Blue Gradient Boxes)
Purpose = Show path equivalence opportunities
Algorithm:
Path_range = ATR × homotopy_score × 1.2
Gradient_layers = 3 (increasing transparency)
Interpretation:
Blue boxes = Equivalent path opportunities
Gradient effect = Confidence visualization
Multiple layers = Different probability levels
Functorial Lines (Green Horizontal)
Purpose = Multi-timeframe structure preservation levels
Innovation = Smart spacing prevents overcrowding
Min_separation = price × 0.001 (0.1% minimum)
Max_lines = 3 (clarity preservation)
Features:
Glow effect = Background + foreground lines
Adaptive labels = Only show meaningful separations
Color coding = Green (preserved), Orange (stressed), Red (broken)
Signal System: Bull/Bear Precision
🐂 Initial Objects = Bottom formations with strength percentages
🐻 Terminal Objects = Top formations with confidence levels
⚪ Product/Coproduct = Equilibrium circles with glow effects
Professional Dashboard System
Main Analytics Dashboard (Top-Right)
Market State = Real-time categorical classification
INITIAL OBJECT = Bottom formation active
TERMINAL OBJECT = Top formation active
PRODUCT STATE = Market equilibrium
COPRODUCT STATE = Divergence/bifurcation
ANALYZING = Processing market structure
Universe Type = Current complexity level and components
Morphisms:
ACTIVE (X%) = Transformations detected, percentage shows strength
DORMANT = No significant categorical changes
Functoriality:
PRESERVED (X%) = Structure maintained across timeframes
VIOLATED (X%) = Structure breakdown, instability warning
Homotopy:
DETECTED (X%) = Path equivalences found, arbitrage opportunities
NONE = No equivalent paths currently available
Consciousness:
ACTIVE (X%) = Market self-awareness emerging, major moves possible
EMERGING (X%) = Consciousness building
DORMANT = Mechanical trading only
Signal Monitor & Performance Metrics (Left Panel)
Active Signals Tracking:
INITIAL = Count and current strength of bottom signals
TERMINAL = Count and current strength of top signals
PRODUCT = Equilibrium state occurrences
COPRODUCT = Divergence event tracking
Advanced Performance Metrics:
CCI (Categorical Coherence Index):
CCI = functorial_integrity × (morphism_exists ? 1.0 : 0.5)
STRONG (>0.7) = High structural coherence
MODERATE (0.4-0.7) = Adequate coherence
WEAK (<0.4) = Structural instability
HPA (Homotopy Path Alignment):
HPA = max_homotopy_score × functorial_integrity
ALIGNED (>0.6) = Strong path equivalences
PARTIAL (0.3-0.6) = Some equivalences
WEAK (<0.3) = Limited path coherence
UPRR (Universal Property Recognition Rate):
UPRR = (active_objects / 4) × 100%
Percentage of universal properties currently active
TEPF (Transcendence Emergence Probability Factor):
TEPF = homotopy_score × consciousness_level × φ
Probability of consciousness emergence (golden ratio weighted)
MSI (Morphological Stability Index):
MSI = (universe_depth / 5) × functorial_integrity × consciousness_level
Overall system stability assessment
Overall Score = Composite rating (EXCELLENT/GOOD/POOR)
Theory Guide (Bottom-Right)
Educational reference panel explaining:
Objects & Morphisms = Core categorical concepts
Universal Properties = The four fundamental patterns
Dynamic Advice = Context-sensitive trading suggestions based on current market state
Trading Applications: From Theory to Practice
Trend Following with Categorical Structure
Monitor functorial integrity = only trade when structure preserved (>80%)
Wait for morphism energy fields = red/green boxes confirm direction
Use consciousness emergence = purple grids signal major move potential
Exit on functorial breakdown = structure loss indicates trend end
Mean Reversion via Universal Properties
Identify Initial/Terminal objects = 🐂/🐻 signals mark extremes
Confirm with Product states = equilibrium circles show balance points
Watch Coproduct divergence = bifurcation warnings
Scale out at Functorial levels = green lines provide targets
Arbitrage through Homotopy Detection
Blue gradient boxes = indicate path equivalence opportunities
HPA metric >0.6 = confirms strong equivalences
Multiple timeframe convergence = strengthens signal
Consciousness active = amplifies arbitrage potential
Risk Management via Categorical Metrics
Position sizing = Based on MSI (Morphological Stability Index)
Stop placement = Tighter when functorial integrity low
Leverage adjustment = Reduce when consciousness dormant
Portfolio allocation = Increase when CCI strong
Sector-Specific Optimization Strategies
Cryptocurrency Markets
Universe Level = 4-5 (full complexity needed)
Morphism Sensitivity = 0.382-0.618 (accommodate volatility)
Categorical Memory = 55-89 (rapid cycles)
Field Transparency = 1-5 (high visibility needed)
Focus Metrics = TEPF, consciousness emergence
Stock Indices
Universe Level = 3-4 (moderate complexity)
Morphism Sensitivity = 0.618-1.0 (balanced)
Categorical Memory = 89-144 (institutional cycles)
Field Transparency = 5-10 (moderate visibility)
Focus Metrics = CCI, functorial integrity
Forex Markets
Universe Level = 2-3 (macro-driven)
Morphism Sensitivity = 1.0-1.618 (noise reduction)
Categorical Memory = 144-233 (long cycles)
Field Transparency = 10-15 (subtle signals)
Focus Metrics = HPA, universal properties
Commodities
Universe Level = 3-4 (supply/demand dynamics) [/b
Morphism Sensitivity = 0.618-1.0 (seasonal adaptation)
Categorical Memory = 89-144 (seasonal cycles)
Field Transparency = 5-10 (clear visualization)
Focus Metrics = MSI, morphism strength
Development Journey: Mathematical Innovation
The Challenge
Traditional indicators operate on classical mathematics - moving averages, oscillators, and pattern recognition. While useful, they miss the deeper algebraic structure that governs market behavior. Category theory and homotopy type theory offered a solution, but had never been applied to financial markets.
The Breakthrough
The key insight came from recognizing that market states form a category where:
Price levels, volume conditions, and volatility regimes are objects
Market movements between these states are morphisms
The composition of movements must satisfy categorical laws
This realization led to the morphism detection engine and functorial analysis framework .
Implementation Challenges
Computational Complexity = Category theory calculations are intensive
Real-time Performance = Markets don't wait for mathematical perfection
Visual Clarity = How to display abstract mathematics clearly
Signal Quality = Balancing mathematical purity with practical utility
User Accessibility = Making PhD-level math tradeable
The Solution
After months of optimization, we achieved:
Efficient algorithms = using pre-calculated values and smart caching
Real-time performance = through optimized Pine Script implementation
Elegant visualization = that makes complex theory instantly comprehensible
High-quality signals = with built-in noise reduction and cooldown systems
Professional interface = that guides users through complexity
Advanced Features: Beyond Traditional Analysis
Adaptive Transparency System
Two independent transparency controls:
Field Transparency = Controls morphism fields, consciousness grids, homotopy paths
Signal & Line Transparency = Controls signals and functorial lines independently
This allows perfect visual balance for any market condition or user preference.
Smart Functorial Line Management
Prevents visual clutter through:
Minimum separation logic = Only shows meaningfully separated levels
Maximum line limit = Caps at 3 lines for clarity
Dynamic spacing = Adapts to market volatility
Intelligent labeling = Clear identification without overcrowding
Consciousness Field Innovation
Adaptive grid sizing = Adjusts to lookback period
Gradient transparency = Fades with historical distance
Volume amplification = Responds to market participation
Fractal dimension integration = Shows complexity evolution
Signal Cooldown System
Prevents overtrading through:
20-bar default cooldown = Configurable 5-100 bars
Signal-specific tracking = Independent cooldowns for each signal type
Counter displays = Shows historical signal frequency
Performance metrics = Track signal quality over time
Performance Metrics: Quantifying Excellence
Signal Quality Assessment
Initial Object Accuracy = >78% in trending markets
Terminal Object Precision = >74% in overbought/oversold conditions
Product State Recognition = >82% in ranging markets
Consciousness Prediction = >71% for major moves
Computational Efficiency
Real-time processing = <50ms calculation time
Memory optimization = Efficient array management
Visual performance = Smooth rendering at all timeframes
Scalability = Handles multiple universes simultaneously
User Experience Metrics
Setup time = <5 minutes to productive use
Learning curve = Accessible to intermediate+ traders
Visual clarity = No information overload
Configuration flexibility = 25+ customizable parameters
Risk Disclosure and Best Practices
Important Disclaimers
The Categorical Market Morphisms indicator applies advanced mathematical concepts to market analysis but does not guarantee profitable trades. Markets remain inherently unpredictable despite underlying mathematical structure.
Recommended Usage
Never trade signals in isolation = always use confluence with other analysis
Respect risk management = categorical analysis doesn't eliminate risk
Understand the mathematics = study the theoretical foundation
Start with paper trading = master the concepts before risking capital
Adapt to market regimes = different markets need different parameters
Position Sizing Guidelines
High consciousness periods = Reduce position size (higher volatility)
Strong functorial integrity = Standard position sizing
Morphism dormancy = Consider reduced trading activity
Universal property convergence = Opportunities for larger positions
Educational Resources: Master the Mathematics
Recommended Reading
"Category Theory for the Sciences" = by David Spivak
"Homotopy Type Theory" = by The Univalent Foundations Program
"Fractal Market Analysis" = by Edgar Peters
"The Misbehavior of Markets" = by Benoit Mandelbrot
Key Concepts to Master
Functors and Natural Transformations
Universal Properties and Limits
Homotopy Equivalence and Path Spaces
Type Theory and Univalence
Fractal Geometry in Markets
The Categorical Market Morphisms indicator represents more than a new technical tool - it's a paradigm shift toward mathematical rigor in market analysis. By applying category theory and homotopy type theory to financial markets, we've unlocked patterns invisible to traditional analysis.
This isn't just about better signals or prettier charts. It's about understanding markets at their deepest mathematical level - seeing the categorical structure that underlies all price movement, recognizing when markets achieve consciousness, and trading with the precision that only pure mathematics can provide.
Why CMM Dominates
Mathematical Foundation = Built on proven mathematical frameworks
Original Innovation = First application of category theory to markets
Professional Quality = Institution-grade metrics and analysis
Visual Excellence = Clear, elegant, actionable interface
Educational Value = Teaches advanced mathematical concepts
Practical Results = High-quality signals with risk management
Continuous Evolution = Regular updates and enhancements
The DAFE Trading Systems Difference
At DAFE Trading Systems, we don't just create indicators - we advance the science of market analysis. Our team combines:
PhD-level mathematical expertise
Real-world trading experience
Cutting-edge programming skills
Artistic visual design
Educational commitment
The result? Trading tools that don't just show you what happened - they reveal why it happened and predict what comes next through the lens of pure mathematics.
"In mathematics you don't understand things. You just get used to them." - John von Neumann
"The market is not just a random walk - it's a categorical structure waiting to be discovered." - DAFE Trading Systems
Trade with Mathematical Precision. Trade with Categorical Market Morphisms.
Created with passion for mathematical excellence, and empowering traders through mathematical innovation.
— Dskyz, Trade with insight. Trade with anticipation.
Levels Of Interest------------------------------------------------------------------------------------
LEVELS OF INTEREST (LOI)
TRADING INDICATOR GUIDE
------------------------------------------------------------------------------------
Table of Contents:
1. Indicator Overview & Core Functionality
2. VWAP Foundation & Historical Context
3. Multi-Timeframe VWAP Analysis
4. Moving Average Integration System
5. Trend Direction Signal Detection
6. Visual Design & Display Features
7. Custom Level Integration
8. Repaint Protection Technology
9. Practical Trading Applications
10. Setup & Configuration Recommendations
------------------------------------------------------------------------------------
1. INDICATOR OVERVIEW & CORE FUNCTIONALITY
------------------------------------------------------------------------------------
The LOI indicator combines multiple VWAP calculations with moving averages across different timeframes. It's designed to show where institutional money is flowing and help identify key support and resistance levels that actually matter in today's markets.
Primary Functions:
- Multi-timeframe VWAP analysis (Daily, Weekly, Monthly, Yearly)
- Advanced moving average integration (EMA, SMA, HMA)
- Real-time trend direction detection
- Institutional flow analysis
- Dynamic support/resistance identification
Target Users: Day traders, swing traders, position traders, and institutional analysts seeking comprehensive market structure analysis.
------------------------------------------------------------------------------------
2. VWAP FOUNDATION & HISTORICAL CONTEXT
------------------------------------------------------------------------------------
Historical Development: VWAP started in the 1980s when big institutional traders needed a way to measure if they were getting good fills on their massive orders. Unlike regular price averages, VWAP weighs each price by the volume traded at that level. This makes it incredibly useful because it shows you where most of the real money changed hands.
Mathematical Foundation: The basic math is simple: you take each price, multiply it by the volume at that price, add them all up, then divide by total volume. What you get is the true "average" price that reflects actual trading activity, not just random price movements.
Formula: VWAP = Σ(Price × Volume) / Σ(Volume)
Where typical price = (High + Low + Close) / 3
Institutional Behavior Patterns:
- When price trades above VWAP, institutions often look to sell
- When it's below, they're usually buying
- Creates natural support and resistance that you can actually trade against
- Serves as benchmark for execution quality assessment
------------------------------------------------------------------------------------
3. MULTI-TIMEFRAME VWAP ANALYSIS
------------------------------------------------------------------------------------
Core Innovation: Here's where LOI gets interesting. Instead of just showing daily VWAP like most indicators, it displays four different timeframes simultaneously:
**Daily VWAP Implementation**:
- Resets every morning at market open
- Provides clearest picture of intraday institutional sentiment
- Primary tool for day trading strategies
- Most responsive to immediate market conditions
**Weekly VWAP System**:
- Resets each Monday (or first trading day)
- Smooths out daily noise and volatility
- Perfect for swing trades lasting several days to weeks
- Captures weekly institutional positioning
**Monthly VWAP Analysis**:
- Resets at beginning of each calendar month
- Captures bigger institutional rebalancing at month-end
- Fund managers often operate on monthly mandates
- Significant weight in intermediate-term analysis
**Yearly VWAP Perspective**:
- Resets annually for full-year institutional view
- Shows long-term institutional positioning
- Where pension funds and sovereign wealth funds operate
- Critical for major trend identification
Confluence Zone Theory: The magic happens when multiple VWAP levels cluster together. These confluence zones often become major turning points because different types of institutional money all see value at the same price.
------------------------------------------------------------------------------------
4. MOVING AVERAGE INTEGRATION SYSTEM
------------------------------------------------------------------------------------
Multi-Type Implementation: The indicator includes three types of moving averages, each with its own personality and application:
**Exponential Moving Averages (EMAs)**:
- React quickly to recent price changes
- Displayed as solid lines for easy identification
- Optimal performance in trending market conditions
- Higher sensitivity to current price action
**Simple Moving Averages (SMAs)**:
- Treat all historical data points equally
- Appear as dashed lines in visual display
- Slower response but more reliable in choppy conditions
- Traditional approach favored by institutional traders
**Hull Moving Averages (HMAs)**:
- Newest addition to the system (dotted line display)
- Created by Alan Hull in 2005
- Solves classic moving average dilemma: speed vs. accuracy
- Manages to be both responsive and smooth simultaneously
Technical Innovation: Alan Hull's solution addresses the fundamental problem where moving averages are either too slow (missing moves) or too fast (generating false signals). HMAs achieve optimal balance through weighted calculation methodology.
Period Configuration:
- 5-period: Short-term momentum assessment
- 50-period: Intermediate trend identification
- 200-period: Long-term directional confirmation
------------------------------------------------------------------------------------
5. TREND DIRECTION SIGNAL DETECTION
------------------------------------------------------------------------------------
Real-Time Momentum Analysis: One of LOI's best features is its real-time trend detection system. Next to each moving average, visual symbols provide immediate trend assessment:
Symbol System:
- ▲ Rising average (bullish momentum confirmation)
- ▼ Falling average (bearish momentum indication)
- ► Flat average (consolidation or indecision period)
Update Frequency: These signals update in real-time with each new price tick and function across all configured timeframes. Traders can quickly scan daily and weekly trends to assess alignment or conflicting signals.
Multi-Timeframe Trend Analysis:
- Simultaneous daily and weekly trend comparison
- Immediate identification of trend alignment
- Early warning system for potential reversals
- Momentum confirmation for entry decisions
------------------------------------------------------------------------------------
6. VISUAL DESIGN & DISPLAY FEATURES
------------------------------------------------------------------------------------
Color Psychology Framework: The color scheme isn't random but based on psychological associations and trading conventions:
- **Blue Tones**: Institutional neutrality (VWAP levels)
- **Green Spectrum**: Growth and stability (weekly timeframes)
- **Purple Range**: Longer-term sophistication (monthly analysis)
- **Orange Hues**: Importance and attention (yearly perspective)
- **Red Tones**: User-defined significance (custom levels)
Adaptive Display Technology: The indicator automatically adjusts decimal places based on the instrument you're trading. High-priced stocks show 2 decimals, while penny stocks might show 8. This keeps the display incredibly clean regardless of what you're analyzing - no cluttered charts or overwhelming information overload.
Smart Labeling System: Advanced positioning algorithm automatically spaces all elements to prevent overlap, even during extreme zoom levels or multiple timeframe analysis. Every level stays clearly readable without any visual chaos disrupting your analysis.
------------------------------------------------------------------------------------
7. CUSTOM LEVEL INTEGRATION
------------------------------------------------------------------------------------
User-Defined Level System: Beyond the calculated VWAP and moving average levels, traders can add custom horizontal lines at any price point for personalized analysis.
Strategic Applications:
- **Psychological Levels**: Round numbers, previous significant highs/lows
- **Technical Levels**: Fibonacci retracements, pivot points
- **Fundamental Targets**: Analyst price targets, earnings estimates
- **Risk Management**: Stop-loss and take-profit zones
Integration Features:
- Seamless incorporation with smart labeling system
- Custom color selection for visual organization
- Extension capabilities across all chart timeframes
- Maintains display clarity with existing indicators
------------------------------------------------------------------------------------
8. REPAINT PROTECTION TECHNOLOGY
------------------------------------------------------------------------------------
Critical Trading Feature: This addresses one of the most significant issues in live trading applications. Most multi-timeframe indicators "repaint," meaning they display different signals when viewing historical data versus real-time analysis.
Protection Benefits:
- Ensures every displayed signal could have been traded when it appeared
- Eliminates discrepancies between historical and live analysis
- Provides realistic performance expectations
- Maintains signal integrity across chart refreshes
Configuration Options:
- **Protection Enabled**: Default setting for live trading
- **Protection Disabled**: Available for backtesting analysis
- User-selectable toggle based on analysis requirements
- Applies to all multi-timeframe calculations
Implementation Note: With protection enabled, signals may appear one bar later than without protection, but this ensures all signals represent actionable opportunities that could have been executed in real-time market conditions.
------------------------------------------------------------------------------------
9. PRACTICAL TRADING APPLICATIONS
------------------------------------------------------------------------------------
**Day Trading Strategy**:
Focus on daily VWAP with 5-period moving averages. Look for bounces off VWAP or breaks through it with volume. Short-term momentum signals provide entry and exit timing.
**Swing Trading Approach**:
Weekly VWAP becomes your primary anchor point, with 50-period averages showing intermediate trends. Position sizing based on weekly VWAP distance.
**Position Trading Method**:
Monthly and yearly VWAP provide broad market context, while 200-period averages confirm long-term directional bias. Suitable for multi-week to multi-month holdings.
**Multi-Timeframe Confluence Strategy**:
The highest-probability setups occur when daily, weekly, and monthly VWAPs cluster together, especially when multiple moving averages confirm the same direction. These represent institutional consensus zones.
Risk Management Integration:
- VWAP levels serve as dynamic stop-loss references
- Multiple timeframe confirmation reduces false signals
- Institutional flow analysis improves position sizing decisions
- Trend direction signals optimize entry and exit timing
------------------------------------------------------------------------------------
10. SETUP & CONFIGURATION RECOMMENDATIONS
------------------------------------------------------------------------------------
Initial Configuration: Start with default settings and adjust based on individual trading style and market focus. Short-term traders should emphasize daily and weekly timeframes, while longer-term investors benefit from monthly and yearly level analysis.
Transparency Optimization: The transparency settings allow clear price action visibility while maintaining level reference points. Most traders find 70-80% transparency optimal - it provides a clean, unobstructed view of price movement while maintaining all critical reference levels needed for analysis.
Integration Strategy: Remember that no indicator functions effectively in isolation. LOI provides excellent context for institutional flow and trend direction analysis, but should be combined with complementary analysis tools for optimal results.
Performance Considerations:
- Multiple timeframe calculations may impact chart loading speed
- Adjust displayed timeframes based on trading frequency
- Customize color schemes for different market sessions
- Regular review and adjustment of custom levels
------------------------------------------------------------------------------------
FINAL ANALYSIS
------------------------------------------------------------------------------------
Competitive Advantage: What makes LOI different is its focus on where real money actually trades. By combining volume-weighted calculations with multiple timeframes and trend detection, it cuts through market noise to show you what institutions are really doing.
Key Success Factor: Understanding that different timeframes serve different purposes is essential. Use them together to build a complete picture of market structure, then execute trades accordingly.
The integration of institutional flow analysis with technical trend detection creates a comprehensive trading tool that addresses both short-term tactical decisions and longer-term strategic positioning.
------------------------------------------------------------------------------------
END OF DOCUMENTATION
------------------------------------------------------------------------------------
Volume Momentum [BackQuant]Volume Momentum
The Volume Momentum indicator is designed to help traders identify shifts in market momentum based on volume data. By analyzing the relative volume momentum, this indicator provides insights into whether the market is gaining strength (uptrend) or losing momentum (downtrend). The strategy uses a combination of percentile-based volume normalization, weighted moving averages (WMA), and exponential moving averages (EMA) to assess volume trends.
The system focuses on the relationship between price and volume, utilizing normalized volume data to highlight key market changes. This approach allows traders to focus on volume-driven price movements, helping them to capture momentum shifts early.
Key Features
1. Volume Normalization and Percentile Calculation:
The signed volume (positive when the close is higher than the open, negative when the close is lower) is normalized against the rolling average volume. This normalized volume is then subjected to a percentile interpolation, allowing for a robust statistical measure of how the current volume compares to historical data. The percentile level is customizable, with 50 representing the median.
2. Weighted and Smoothed Moving Averages for Trend Detection:
The normalized volume is smoothed using weighted moving averages (WMA) and exponential moving averages (EMA). These smoothing techniques help eliminate noise, providing a clearer view of the underlying momentum. The WMA filters out short-term fluctuations, while the EMA ensures that the most recent data points have a higher weight, making the system more responsive to current market conditions.
3. Trend Reversal Detection:
The indicator detects momentum shifts by evaluating whether the volume momentum crosses above or below zero. A positive volume momentum indicates a potential uptrend, while a negative momentum suggests a possible downtrend. These trend reversals are identified through crossover and crossunder conditions, triggering alerts when significant changes occur.
4. Dynamic Trend Background and Bar Coloring:
The script offers customizable background coloring based on the trend direction. When volume momentum is positive, the background is colored green, indicating a bullish trend. When volume momentum is negative, the background is colored red, signaling a bearish trend. Additionally, the bars themselves can be colored based on the trend, further helping traders quickly visualize market momentum.
5. Alerts for Momentum Shifts:
The system provides real-time alerts for traders to monitor when volume momentum crosses a critical threshold (zero), signaling a trend reversal. The alerts notify traders when the market momentum turns bullish or bearish, assisting them in making timely decisions.
6. Customizable Parameters for Flexible Usage:
Users can fine-tune the behavior of the indicator by adjusting various parameters:
Volume Rolling Mean: The period used to calculate the average volume for normalization.
Percentile Interpolation Length: Defines the range over which the percentile is calculated.
Percentile Level: Determines the percentile threshold (e.g., 50 for the median).
WMA and Smoothing Periods: Control the smoothing and response time of the indicator.
7. Trend Background Visualization and Trend-Based Bar Coloring:
The background fill is shaded according to whether the volume momentum is positive or negative, providing a visual cue to indicate market strength. Additionally, bars can be color-coded to highlight the trend, making it easier to see the trend’s direction without needing to analyze numerical data manually.
8. Note on Mean-Reversion Strategy:
If you take the inverse of the signals, this indicator can be adapted for a mean-reversion strategy. Instead of following the trend, the strategy would involve buying assets that are underperforming and selling assets that are overperforming, based on volume momentum. However, it’s important to note that this approach may not work effectively on highly correlated assets, as their price movements may be too similar, reducing the effectiveness of the mean-reversion strategy.
Final Thoughts
The Volume Momentum indicator offers a comprehensive approach to analyzing volume-based momentum shifts in the market. By using volume normalization, percentile interpolation, and smoothed moving averages, this system helps identify the strength and direction of market trends. Whether used for trend-following or adapted for mean-reversion, this tool provides traders with actionable insights into the market’s volume-driven movements, improving decision-making and portfolio management.
Higher Timeframe Market StructureHTF Market Structure – ZigZag, Break of Structure & Supply/Demand
This powerful indicator is designed to identify higher-timeframe market structure using a combination of ZigZag patterns, Break of Structure (BOS) signals, and Supply/Demand zones.
Key Features:
Automatic detection of Higher Highs (HH), Higher Lows (HL), Lower Lows (LL), and Lower Highs (LH)
Internal structure shifts based on Open or High/Low logic
Supply and Demand zones plotted on the chart
Break of Structure (BOS) lines with optional alerts
Mitigation logic to mark or delete invalidated order blocks
Customizable aggregation factor to view higher time frame structure on lower time frames
How to Use:
Focus on market structure and BOS to understand the current trend.
Watch for internal shifts as early signals of potential reversals.
Use ZigZag lines to connect swing highs and lows to visualize market rhythm.
Supply zones (red) and Demand zones (green) are automatically drawn after structure breaks:
Use Demand Zones in Bullish Markets for the highest probability entries.
Use Supply Zones in Bearish Markets to align with the prevailing trend.
Best Practices:
Only use Demand Zones in Bullish markets and Supply Zones in Bearish markets for optimal results.
Look for price action or reversal signals within these zones to refine your entries.
Enable alerts to get notified on:
New order blocks
Internal shifts
BOS events
HH, HL, LL, LH formations
Liquidity sweeps
Customization Options:
Aggregation Factor: Control how many candles are grouped for structure analysis.
Zone Duration: Define how length of plotted zones.
Mitigation Settings: Automatically delete or fade zones after mitigation.
Colors: Choose custom colors for bullish and bearish zones and structure markers.
This tool is ideal for traders who rely on price action, structure, and smart money concepts. Combine it with your own S&D strategy or integrate it with other confluence tools for even better precision.
VWAP Supply & Demand Zones PRO**Overview:**
This script represents a major evolution of the original "VWAP Supply and Demand Zones" indicator. Initially created to explore price interaction with VWAP, it has now matured into a robust and feature-rich tool for identifying high-probability zones of institutional buying and selling pressure. The update introduces volume and momentum validation, dynamic zone management, alert logic, and a visual dashboard (HUD) — all designed for improved precision and clarity. The structural improvements, anti-repainting logic, and significant added utility warranted releasing this as a new script rather than a minor update.
---
### What It Does:
This indicator dynamically detects **supply and demand zones** using VWAP-based logic combined with **volume** and **momentum confirmation**. When price crosses VWAP with strength, it identifies the potential zone of excess demand (below VWAP) or supply (above VWAP), marking it visually with colored regions on the chart.
Each zone is extended for a user-defined duration, monitored for touch interactions (tests), and tracked for possible breaks. The script helps traders interpret price behavior around these institutional zones as either **reversal** opportunities or **continuation** confirmation depending on context and strategy preference.
---
### How It Works:
* **VWAP Basis**: Zones are anchored at VWAP at the time of a significant cross.
* **Volume & Momentum Filters**: Crosses are only considered valid if backed by above-average volume and notable price momentum.
* **Zone Drawing**: Validated supply and demand zones are drawn as boxes on the chart. Each is extended forward for a customizable number of bars.
* **Touch Counting**: Zones track the number of price touches. Alerts are issued after a user-defined number of tests.
* **Break Detection**: If price closes significantly beyond a zone boundary, the zone is marked as broken and visually dimmed.
* **Visual Dashboard (HUD)**: A compact real-time HUD displays VWAP value, active zone counts, and current market bias.
---
### How to Use It:
**Reversal Trading:**
* Look for price **rejecting** a zone after touching it.
* Use rejection candles or secondary indicators (e.g., RSI divergence) to confirm.
* These setups may offer low-risk entries when price respects the zone.
**Continuation Trading:**
* A **break of a zone** suggests strong directional bias.
* Use confirmed zone breaks to enter in the direction of momentum.
* Ideal in trending environments, especially with high volume and ATR movement.
---
### Key Inputs:
* **VWAP Length**: Moving VWAP period (default: 20)
* **Zone Width %**: Percentage size of zone buffer (default: 0.5%)
* **Min Touches**: How many times price must test a zone before alerts trigger
* **Zone Extension**: How far into the future zones are projected
* **Volume & ATR Filters**: Ensure only strong, valid crossovers create zones
---
### Alerts:
You can enable alerts for:
* **New zone creation**
* **Zone tests (after minimum touch count)**
* **Zone breaks**
* **VWAP crosses**
* **Active presence inside a zone (entry conditions)**
These alerts help automate market monitoring, making it suitable for discretionary or systematic workflows.
---
### Why It's a New Script:
This is not a cosmetic update. The internal logic, signal generation, filtering methodology, visual engine, and UX framework have been entirely rebuilt from the ground up. The result is a highly adaptive, precision-oriented tool — appropriate for intraday scalpers and swing traders alike. It goes far beyond the original in terms of functionality and reliability, justifying a fresh release.
---
### Suitable Markets and Timeframes:
* Works across all liquid markets (crypto, equities, futures, forex)
* Best used on timeframes where volume data is stable (5m and above recommended)
* Recalibrate inputs for optimal detection across instruments
LRCLRC (Linear Regression Candle)
Overview
The LRC (Linear Regression Candle) indicator applies linear regression to the open, high, low, and close prices, creating smoothed "candles" that help filter market noise. It provides trend-confirmation signals and highlights potential reversal points based on regression crossovers.
Key Features
Smoothed Candles: Uses linear regression to calculate synthetic OHLC values, reducing noise.
Multi-Timeframe Support: Optional higher timeframe analysis for better trend confirmation.
Visual Signals: Color-coded candles and labels highlight bullish/bearish control zones.
Customizable Settings: Adjustable regression length, colors, and timeframe options.
How to Use
Signals & Interpretation
🟢 Bullish Signal (BUY): When the regression open crosses above the regression close (green candle).
🔴 Bearish Signal (SELL): When the regression open crosses below the regression close (red candle).
Control Zones:
Strong Bullish (Controlbull): Confirmed uptrend (bright green).
Bullish (Bull): Regular uptrend (light green).
Strong Bearish (Controlbear): Confirmed downtrend (dark red).
Bearish (Bear): Regular downtrend (orange).
Neutral (Gray): No clear trend.
Recommended Settings
Linear Regression Length: Default 8 (adjust for sensitivity).
Timeframe: Default current chart, but can switch to higher timeframes (e.g., 1D, 1W).
Bar Colors: Toggle on/off for visual clarity.
Labels: Displays "Control" markers at key reversal points.
Example Use Cases
Trend Confirmation: Use higher timeframe LRC to validate the primary trend.
Reversal Signals: Watch for BUY/SELL crossovers with strong color confirmation.
Noise Reduction: Helps avoid false breakouts in choppy markets.
Wavelet Filter with Adaptive Upsampling [BackQuant]Wavelet Filter with Adaptive Upsampling
The Wavelet Filter with Adaptive Upsampling is an advanced filtering and signal reconstruction tool designed to enhance the analysis of financial time series data. It combines wavelet transforms with adaptive upsampling techniques to filter and reconstruct price data, making it ideal for capturing subtle market movements and enhancing trend detection. This system uses high-pass and low-pass filters to decompose the price series into different frequency components, applying adaptive thresholding to eliminate noise and preserve relevant signal information.
Shout out to Loxx for the Least Squares fitting of trigonometric series and Quinn and Fernandes algorithm for finding frequency
www.tradingview.com
Key Features
1. Frequency Decomposition with High-Pass and Low-Pass Filters:
The indicator decomposes the input time series using high-pass and low-pass filters to separate the high-frequency (detail) and low-frequency (trend) components of the data. This decomposition allows for a more accurate analysis of underlying trends, while mitigating the impact of noise.
2. Soft Thresholding for Noise Reduction:
A soft thresholding function is applied to the high-frequency component, allowing for the reduction of noise while retaining significant market signals. This function adjusts the coefficients of the high-frequency data, removing small fluctuations and leaving only the essential price movements.
3. Adaptive Upsampling Process:
The upsampling process in this script can be customized using different methods: sinusoidal upsampling, advanced upsampling, and simple upsampling. Each method serves a unique purpose:
Sinusoidal Upsample uses a sine wave to interpolate between data points, providing a smooth transition.
Advanced Upsample utilizes a Quinn-Fernandes algorithm to estimate frequency and apply more sophisticated interpolation techniques, adapting to the market’s cyclical behavior.
Simple Upsample linearly interpolates between data points, providing a basic upsampling technique for less complex analysis.
4. Reconstruction of Filtered Signal:
The indicator reconstructs the filtered signal by summing the high and low-frequency components after upsampling. This allows for a detailed yet smooth representation of the original time series, which can be used for analyzing underlying trends in the market.
5. Visualization of Reconstructed Data:
The reconstructed series is plotted, showing how the upsampling and filtering process enhances the clarity of the price movements. Additionally, the script provides the option to visualize the log returns of the reconstructed series as a histogram, with positive returns shown in green and negative returns in red.
6. Cumulative Series and Trend Detection:
A cumulative series is plotted to visualize the compounded effect of the filtered and reconstructed data. This feature helps traders track the overall performance of the asset over time, identifying whether the asset is following a sustained upward or downward trend.
7. Adaptive Thresholding and Noise Estimation:
The system estimates the noise level in the high-frequency component and applies an adaptive thresholding process based on the standard deviation of the downsampled data. This ensures that only significant price movements are retained, further refining the trend analysis.
8. Customizable Parameters for Flexibility:
Users can customize the following parameters to adjust the behavior of the indicator:
Frequency and Phase Shift: Control the periodicity of the wavelet transformation and the phase of the upsampling function.
Upsample Factor: Adjust the level of interpolation applied during the upsampling process.
Smoothing Period: Determine the length of time used to smooth the signal, helping to filter out short-term fluctuations.
References
Enhancing Cross-Sectional Currency Strategies with Context-Aware Learning to Rank
arxiv.org
Daubechies Wavelet - Wikipedia
en.wikipedia.org
Quinn Fernandes Fourier Transform of Filtered Price by Loxx
Note on Usage for Mean-Reversion Strategy
This indicator is primarily designed for trend-following strategies. However, by taking the inverse of the signals, it can be adapted for mean-reversion strategies. This involves buying underperforming assets and selling outperforming ones. Caution: This method may not work effectively with highly correlated assets, as the price movements between correlated assets tend to mirror each other, limiting the effectiveness of mean-reversion strategies.
Final Thoughts
The Wavelet Filter with Adaptive Upsampling is a powerful tool for traders seeking to improve their understanding of market trends and noise. By using advanced wavelet decomposition and adaptive upsampling, this system offers a clearer, more refined picture of price movements, enhancing trend-following strategies. It’s particularly useful for detecting subtle shifts in market momentum and reconstructing price data in a way that removes noise, providing more accurate insights into market conditions.
Performance Metrics With Bracketed Rebalacing [BackQuant]Performance Metrics With Bracketed Rebalancing
The Performance Metrics With Bracketed Rebalancing script offers a robust method for assessing portfolio performance, integrating advanced portfolio metrics with different rebalancing strategies. With a focus on adaptability, the script allows traders to monitor and adjust portfolio weights, equity, and other key financial metrics dynamically. This script provides a versatile approach for evaluating different trading strategies, considering factors like risk-adjusted returns, volatility, and the impact of portfolio rebalancing.
Please take the time to read the following:
Key Features and Benefits of Portfolio Methods
Bracketed Rebalancing:
Bracketed Rebalancing is an advanced strategy designed to trigger portfolio adjustments when an asset's weight surpasses a predefined threshold. This approach minimizes overexposure to any single asset while maintaining flexibility in response to market changes. The strategy is particularly beneficial for mitigating risks that arise from significant asset weight fluctuations. The following image illustrates how this method reacts when asset weights cross the threshold:
Daily Rebalancing:
Unlike the bracketed method, Daily Rebalancing adjusts portfolio weights every trading day, ensuring consistent asset allocation. This method aims for a more even distribution of portfolio weights, making it a suitable option for traders who prefer less sensitivity to individual asset volatility. Here's an example of Daily Rebalancing in action:
No Rebalancing:
For traders who prefer a passive approach, the "No Rebalancing" option allows the portfolio to remain static, without any adjustments to asset weights. This method may appeal to long-term investors or those who believe in the inherent stability of their selected assets. Here’s how the portfolio looks when no rebalancing is applied:
Portfolio Weights Visualization:
One of the standout features of this script is the visual representation of portfolio weights. With adjustable settings, users can track the current allocation of assets in real-time, making it easier to analyze shifts and trends. The following image shows the real-time weight distribution across three assets:
Rolling Drawdown Plot:
Managing drawdown risk is a critical aspect of portfolio management. The Rolling Drawdown Plot visually tracks the drawdown over time, helping traders monitor the risk exposure and performance relative to the peak equity levels. This feature is essential for assessing the portfolio's resilience during market downturns:
Daily Portfolio Returns:
Tracking daily returns is crucial for evaluating the short-term performance of the portfolio. The script allows users to plot daily portfolio returns to gain insights into daily profit or loss, helping traders stay updated on their portfolio’s progress:
Performance Metrics
Net Profit (%):
This metric represents the total return on investment as a percentage of the initial capital. A positive net profit indicates that the portfolio has gained value over the evaluation period, while a negative value suggests a loss. It's a fundamental indicator of overall portfolio performance.
Maximum Drawdown (Max DD):
Maximum Drawdown measures the largest peak-to-trough decline in portfolio value during a specified period. It quantifies the most significant loss an investor would have experienced if they had invested at the highest point and sold at the lowest point within the timeframe. A smaller Max DD indicates better risk management and less exposure to significant losses.
Annual Mean Returns (% p/y):
This metric calculates the average annual return of the portfolio over the evaluation period. It provides insight into the portfolio's ability to generate returns on an annual basis, aiding in performance comparison with other investment opportunities.
Annual Standard Deviation of Returns (% p/y):
This measure indicates the volatility of the portfolio's returns on an annual basis. A higher standard deviation signifies greater variability in returns, implying higher risk, while a lower value suggests more stable returns.
Variance:
Variance is the square of the standard deviation and provides a measure of the dispersion of returns. It helps in understanding the degree of risk associated with the portfolio's returns.
Sortino Ratio:
The Sortino Ratio is a variation of the Sharpe Ratio that only considers downside risk, focusing on negative volatility. It is calculated as the difference between the portfolio's return and the minimum acceptable return (MAR), divided by the downside deviation. A higher Sortino Ratio indicates better risk-adjusted performance, emphasizing the importance of avoiding negative returns.
Sharpe Ratio:
The Sharpe Ratio measures the portfolio's excess return per unit of total risk, as represented by standard deviation. It is calculated by subtracting the risk-free rate from the portfolio's return and dividing by the standard deviation of the portfolio's excess return. A higher Sharpe Ratio indicates more favorable risk-adjusted returns.
Omega Ratio:
The Omega Ratio evaluates the probability of achieving returns above a certain threshold relative to the probability of experiencing returns below that threshold. It is calculated by dividing the cumulative probability of positive returns by the cumulative probability of negative returns. An Omega Ratio greater than 1 indicates a higher likelihood of achieving favorable returns.
Gain-to-Pain Ratio:
The Gain-to-Pain Ratio measures the return per unit of risk, focusing on the magnitude of gains relative to the severity of losses. It is calculated by dividing the total gains by the total losses experienced during the evaluation period. A higher ratio suggests a more favorable balance between reward and risk.
www.linkedin.com
Compound Annual Growth Rate (CAGR) (% p/y):
CAGR represents the mean annual growth rate of the portfolio over a specified period, assuming the investment has been compounding over that time. It provides a smoothed annual rate of growth, eliminating the effects of volatility and offering a clearer picture of long-term performance.
Portfolio Alpha (% p/y):
Portfolio Alpha measures the portfolio's performance relative to a benchmark index, adjusting for risk. It is calculated using the Capital Asset Pricing Model (CAPM) and represents the excess return of the portfolio over the expected return based on its beta and the benchmark's performance. A positive alpha indicates outperformance, while a negative alpha suggests underperformance.
Portfolio Beta:
Portfolio Beta assesses the portfolio's sensitivity to market movements, indicating its exposure to systematic risk. A beta greater than 1 suggests the portfolio is more volatile than the market, while a beta less than 1 indicates lower volatility. Beta is used to understand the portfolio's potential for gains or losses in relation to market fluctuations.
Skewness of Returns:
Skewness measures the asymmetry of the return distribution. A positive skew indicates a distribution with a long right tail, suggesting more frequent small losses and fewer large gains. A negative skew indicates a long left tail, implying more frequent small gains and fewer large losses. Understanding skewness helps in assessing the likelihood of extreme outcomes.
Value at Risk (VaR) 95th Percentile:
VaR at the 95th percentile estimates the maximum potential loss over a specified period, given a 95% confidence level. It provides a threshold value such that there is a 95% probability that the portfolio will not experience a loss greater than this amount.
Conditional Value at Risk (CVaR):
CVaR, also known as Expected Shortfall, measures the average loss exceeding the VaR threshold. It provides insight into the tail risk of the portfolio, indicating the expected loss in the worst-case scenarios beyond the VaR level.
These metrics collectively offer a comprehensive view of the portfolio's performance, risk exposure, and efficiency. By analyzing these indicators, investors can make informed decisions, balancing potential returns with acceptable levels of risk.
Conclusion
The Performance Metrics With Bracketed Rebalancing script provides a comprehensive framework for evaluating and optimizing portfolio performance. By integrating advanced metrics, adaptive rebalancing strategies, and visual analytics, it empowers traders to make informed decisions in managing their investment portfolios. However, it's crucial to consider the implications of rebalancing strategies, as academic research indicates that predictable rebalancing can lead to market impact costs. Therefore, adopting flexible and less predictable rebalancing approaches may enhance portfolio performance and reduce associated costs.
Market Zone Analyzer[BullByte]Understanding the Market Zone Analyzer
---
1. Purpose of the Indicator
The Market Zone Analyzer is a Pine Script™ (version 6) indicator designed to streamline market analysis on TradingView. Rather than scanning multiple separate tools, it unifies four core dimensions—trend strength, momentum, price action, and market activity—into a single, consolidated view. By doing so, it helps traders:
• Save time by avoiding manual cross-referencing of disparate signals.
• Reduce decision-making errors that can arise from juggling multiple indicators.
• Gain a clear, reliable read on whether the market is in a bullish, bearish, or sideways phase, so they can more confidently decide to enter, exit, or hold a position.
---
2. Why a Trader Should Use It
• Unified View: Combines all essential market dimensions into one easy-to-read score and dashboard, eliminating the need to piece together signals manually.
• Adaptability: Automatically adjusts its internal weighting for trend, momentum, and price action based on current volatility. Whether markets are choppy or calm, the indicator remains relevant.
• Ease of Interpretation: Outputs a simple “BULLISH,” “BEARISH,” or “SIDEWAYS” label, supplemented by an intuitive on-chart dashboard and an oscillator plot that visually highlights market direction.
• Reliability Features: Built-in smoothing of the net score and hysteresis logic (requiring consecutive confirmations before flips) minimize false signals during noisy or range-bound phases.
---
3. Why These Specific Indicators?
This script relies on a curated set of well-established technical tools, each chosen for its particular strength in measuring one of the four core dimensions:
1. Trend Strength:
• ADX/DMI (Average Directional Index / Directional Movement Index): Measures how strong a trend is, and whether the +DI line is above the –DI line (bullish) or vice versa (bearish).
• Moving Average Slope (Fast MA vs. Slow MA): Compares a shorter-period SMA to a longer-period SMA; if the fast MA sits above the slow MA, it confirms an uptrend, and vice versa for a downtrend.
• Ichimoku Cloud Differential (Senkou A vs. Senkou B): Provides a forward-looking view of trend direction; Senkou A above Senkou B signals bullishness, and the opposite signals bearishness.
2. Momentum:
• Relative Strength Index (RSI): Identifies overbought (above its dynamically calculated upper bound) or oversold (below its lower bound) conditions; changes in RSI often precede price reversals.
• Stochastic %K: Highlights shifts in short-term momentum by comparing closing price to the recent high/low range; values above its upper band signal bullish momentum, below its lower band signal bearish momentum.
• MACD Histogram: Measures the difference between the MACD line and its signal line; a positive histogram indicates upward momentum, a negative histogram indicates downward momentum.
3. Price Action:
• Highest High / Lowest Low (HH/LL) Range: Over a defined lookback period, this captures breakout or breakdown levels. A closing price near the recent highs (with a positive MA slope) yields a bullish score, and near the lows (with a negative MA slope) yields a bearish score.
• Heikin-Ashi Doji Detection: Uses Heikin-Ashi candles to identify indecision or continuation patterns. A small Heikin-Ashi body (doji) relative to recent volatility is scored as neutral; a larger body in the direction of the MA slope is scored bullish or bearish.
• Candle Range Measurement: Compares each candle’s high-low range against its own dynamic band (average range ± standard deviation). Large candles aligning with the prevailing trend score bullish or bearish accordingly; unusually small candles can indicate exhaustion or consolidation.
4. Market Activity:
• Bollinger Bands Width (BBW): Measures the distance between BB upper and lower bands; wide bands indicate high volatility, narrow bands indicate low volatility.
• Average True Range (ATR): Quantifies average price movement (volatility). A sudden spike in ATR suggests a volatile environment, while a contraction suggests calm.
• Keltner Channels Width (KCW): Similar to BBW but uses ATR around an EMA. Provides a second layer of volatility context, confirming or contrasting BBW readings.
• Volume (with Moving Average): Compares current volume to its moving average ± standard deviation. High volume validates strong moves; low volume signals potential lack of conviction.
By combining these tools, the indicator captures trend direction, momentum strength, price-action nuances, and overall market energy, yielding a more balanced and comprehensive assessment than any single tool alone.
---
4. What Makes This Indicator Stand Out
• Multi-Dimensional Analysis: Rather than relying on a lone oscillator or moving average crossover, it simultaneously evaluates trend, momentum, price action, and activity.
• Dynamic Weighting: The relative importance of trend, momentum, and price action adjusts automatically based on real-time volatility (Market Activity State). For example, in highly volatile conditions, trend and momentum signals carry more weight; in calm markets, price action signals are prioritized.
• Stability Mechanisms:
• Smoothing: The net score is passed through a short moving average, filtering out noise, especially on lower timeframes.
• Hysteresis: Both Market Activity State and the final bullish/bearish/sideways zone require two consecutive confirmations before flipping, reducing whipsaw.
• Visual Interpretation: A fully customizable on-chart dashboard displays each sub-indicator’s value, regime, score, and comment, all color-coded. The oscillator plot changes color to reflect the current market zone (green for bullish, red for bearish, gray for sideways) and shows horizontal threshold lines at +2, 0, and –2.
---
5. Recommended Timeframes
• Short-Term (5 min, 15 min): Day traders and scalpers can benefit from rapid signals, but should enable smoothing (and possibly disable hysteresis) to reduce false whipsaws.
• Medium-Term (1 h, 4 h): Swing traders find a balance between responsiveness and reliability. Less smoothing is required here, and the default parameters (e.g., ADX length = 14, RSI length = 14) perform well.
• Long-Term (Daily, Weekly): Position traders tracking major trends can disable smoothing for immediate raw readings, since higher-timeframe noise is minimal. Adjust lookback lengths (e.g., increase adxLength, rsiLength) if desired for slower signals.
Tip: If you keep smoothing off, stick to timeframes of 1 h or higher to avoid excessive signal “chatter.”
---
6. How Scoring Works
A. Individual Indicator Scores
Each sub-indicator is assigned one of three discrete scores:
• +1 if it indicates a bullish condition (e.g., RSI above its dynamically calculated upper bound).
• 0 if it is neutral (e.g., RSI between upper and lower bounds).
• –1 if it indicates a bearish condition (e.g., RSI below its dynamically calculated lower bound).
Examples of individual score assignments:
• ADX/DMI:
• +1 if ADX ≥ adxThreshold and +DI > –DI (strong bullish trend)
• –1 if ADX ≥ adxThreshold and –DI > +DI (strong bearish trend)
• 0 if ADX < adxThreshold (trend strength below threshold)
• RSI:
• +1 if RSI > RSI_upperBound
• –1 if RSI < RSI_lowerBound
• 0 otherwise
• ATR (as part of Market Activity):
• +1 if ATR > (ATR_MA + stdev(ATR))
• –1 if ATR < (ATR_MA – stdev(ATR))
• 0 otherwise
Each of the four main categories shares this same +1/0/–1 logic across their sub-components.
B. Category Scores
Once each sub-indicator reports +1, 0, or –1, these are summed within their categories as follows:
• Trend Score = (ADX score) + (MA slope score) + (Ichimoku differential score)
• Momentum Score = (RSI score) + (Stochastic %K score) + (MACD histogram score)
• Price Action Score = (Highest-High/Lowest-Low score) + (Heikin-Ashi doji score) + (Candle range score)
• Market Activity Raw Score = (BBW score) + (ATR score) + (KC width score) + (Volume score)
Each category’s summed value can range between –3 and +3 (for Trend, Momentum, and Price Action), and between –4 and +4 for Market Activity raw.
C. Market Activity State and Dynamic Weight Adjustments
Rather than contributing directly to the netScore like the other three categories, Market Activity determines how much weight to assign to Trend, Momentum, and Price Action:
1. Compute Market Activity Raw Score by summing BBW, ATR, KCW, and Volume individual scores (each +1/0/–1).
2. Bucket into High, Medium, or Low Activity:
• High if raw Score ≥ 2 (volatile market).
• Low if raw Score ≤ –2 (calm market).
• Medium otherwise.
3. Apply Hysteresis (if enabled): The state only flips after two consecutive bars register the same high/low/medium label.
4. Set Category Weights:
• High Activity: Trend = 50 %, Momentum = 35 %, Price Action = 15 %.
• Low Activity: Trend = 25 %, Momentum = 20 %, Price Action = 55 %.
• Medium Activity: Use the trader’s base weight inputs (e.g., Trend = 40 %, Momentum = 30 %, Price Action = 30 % by default).
D. Calculating the Net Score
5. Normalize Base Weights (so that the sum of Trend + Momentum + Price Action always equals 100 %).
6. Determine Current Weights based on the Market Activity State (High/Medium/Low).
7. Compute Each Category’s Contribution: Multiply (categoryScore) × (currentWeight).
8. Sum Contributions to get the raw netScore (a floating-point value that can exceed ±3 when scores are strong).
9. Smooth the netScore over two bars (if smoothing is enabled) to reduce noise.
10. Apply Hysteresis to the Final Zone:
• If the smoothed netScore ≥ +2, the bar is classified as “Bullish.”
• If the smoothed netScore ≤ –2, the bar is classified as “Bearish.”
• Otherwise, it is “Sideways.”
• To prevent rapid flips, the script requires two consecutive bars in the new zone before officially changing the displayed zone (if hysteresis is on).
E. Thresholds for Zone Classification
• BULLISH: netScore ≥ +2
• BEARISH: netScore ≤ –2
• SIDEWAYS: –2 < netScore < +2
---
7. Role of Volatility (Market Activity State) in Scoring
Volatility acts as a dynamic switch that shifts which category carries the most influence:
1. High Activity (Volatile):
• Detected when at least two sub-scores out of BBW, ATR, KCW, and Volume equal +1.
• The script sets Trend weight = 50 % and Momentum weight = 35 %. Price Action weight is minimized at 15 %.
• Rationale: In volatile markets, strong trending moves and momentum surges dominate, so those signals are more reliable than nuanced candle patterns.
2. Low Activity (Calm):
• Detected when at least two sub-scores out of BBW, ATR, KCW, and Volume equal –1.
• The script sets Price Action weight = 55 %, Trend = 25 %, and Momentum = 20 %.
• Rationale: In quiet, sideways markets, subtle price-action signals (breakouts, doji patterns, small-range candles) are often the best early indicators of a new move.
3. Medium Activity (Balanced):
• Raw Score between –1 and +1 from the four volatility metrics.
• Uses whatever base weights the trader has specified (e.g., Trend = 40 %, Momentum = 30 %, Price Action = 30 %).
Because volatility can fluctuate rapidly, the script employs hysteresis on Market Activity State: a new High or Low state must occur on two consecutive bars before weights actually shift. This avoids constant back-and-forth weight changes and provides more stability.
---
8. Scoring Example (Hypothetical Scenario)
• Symbol: Bitcoin on a 1-hour chart.
• Market Activity: Raw volatility sub-scores show BBW (+1), ATR (+1), KCW (0), Volume (+1) → Total raw Score = +3 → High Activity.
• Weights Selected: Trend = 50 %, Momentum = 35 %, Price Action = 15 %.
• Trend Signals:
• ADX strong and +DI > –DI → +1
• Fast MA above Slow MA → +1
• Ichimoku Senkou A > Senkou B → +1
→ Trend Score = +3
• Momentum Signals:
• RSI above upper bound → +1
• MACD histogram positive → +1
• Stochastic %K within neutral zone → 0
→ Momentum Score = +2
• Price Action Signals:
• Highest High/Lowest Low check yields 0 (close not near extremes)
• Heikin-Ashi doji reading is neutral → 0
• Candle range slightly above upper bound but trend is strong, so → +1
→ Price Action Score = +1
• Compute Net Score (before smoothing):
• Trend contribution = 3 × 0.50 = 1.50
• Momentum contribution = 2 × 0.35 = 0.70
• Price Action contribution = 1 × 0.15 = 0.15
• Raw netScore = 1.50 + 0.70 + 0.15 = 2.35
• Since 2.35 ≥ +2 and hysteresis is met, the final zone is “Bullish.”
Although the netScore lands at 2.35 (Bullish), smoothing might bring it slightly below 2.00 on the first bar (e.g., 1.90), in which case the script would wait for a second consecutive reading above +2 before officially classifying the zone as Bullish (if hysteresis is enabled).
---
9. Correlation Between Categories
The four categories—Trend Strength, Momentum, Price Action, and Market Activity—often reinforce or offset one another. The script takes advantage of these natural correlations:
• Bullish Alignment: If ADX is strong and pointed upward, fast MA is above slow MA, and Ichimoku is positive, that usually coincides with RSI climbing above its upper bound and the MACD histogram turning positive. In such cases, both Trend and Momentum categories generate +1 or +2. Because the Market Activity State is likely High (given the accompanying volatility), Trend and Momentum weights are at their peak, so the netScore quickly crosses into Bullish territory.
• Sideways/Consolidation: During a low-volatility, sideways phase, ADX may fall below its threshold, MAs may flatten, and RSI might hover in the neutral band. However, subtle price-action signals (like a small breakout candle or a Heikin-Ashi candle with a slight bias) can still produce a +1 in the Price Action category. If Market Activity is Low, Price Action’s weight (55 %) can carry enough influence—even if Trend and Momentum are neutral—to push the netScore out of “Sideways” into a mild bullish or bearish bias.
• Opposing Signals: When Trend is bullish but Momentum turns negative (for example, price continues up but RSI rolls over), the two scores can partially cancel. Market Activity may remain Medium, in which case the netScore lingers near zero (Sideways). The trader can then wait for either a clearer momentum shift or a fresh price-action breakout before committing.
By dynamically recognizing these correlations and adjusting weights, the indicator ensures that:
• When Trend and Momentum align (and volatility supports it), the netScore leaps strongly into Bullish or Bearish.
• When Trend is neutral but Price Action shows an early move in a low-volatility environment, Price Action’s extra weight in the Low Activity State can still produce actionable signals.
---
10. Market Activity State & Its Role (Detailed)
The Market Activity State is not a direct category score—it is an overarching context setter for how heavily to trust Trend, Momentum, or Price Action. Here’s how it is derived and applied:
1. Calculate Four Volatility Sub-Scores:
• BBW: Compare the current band width to its own moving average ± standard deviation. If BBW > (BBW_MA + stdev), assign +1 (high volatility); if BBW < (BBW_MA × 0.5), assign –1 (low volatility); else 0.
• ATR: Compare ATR to its moving average ± standard deviation. A spike above the upper threshold is +1; a contraction below the lower threshold is –1; otherwise 0.
• KCW: Same logic as ATR but around the KCW mean.
• Volume: Compare current volume to its volume MA ± standard deviation. Above the upper threshold is +1; below the lower threshold is –1; else 0.
2. Sum Sub-Scores → Raw Market Activity Score: Range between –4 and +4.
3. Assign Market Activity State:
• High Activity: Raw Score ≥ +2 (at least two volatility metrics are strongly spiking).
• Low Activity: Raw Score ≤ –2 (at least two metrics signal unusually low volatility or thin volume).
• Medium Activity: Raw Score is between –1 and +1 inclusive.
4. Hysteresis for Stability:
• If hysteresis is enabled, a new state only takes hold after two consecutive bars confirm the same High, Medium, or Low label.
• This prevents the Market Activity State from bouncing around when volatility is on the fence.
5. Set Category Weights Based on Activity State:
• High Activity: Trend = 50 %, Momentum = 35 %, Price Action = 15 %.
• Low Activity: Trend = 25 %, Momentum = 20 %, Price Action = 55 %.
• Medium Activity: Use trader’s base weights (e.g., Trend = 40 %, Momentum = 30 %, Price Action = 30 %).
6. Impact on netScore: Because category scores (–3 to +3) multiply by these weights, High Activity amplifies the effect of strong Trend and Momentum scores; Low Activity amplifies the effect of Price Action.
7. Market Context Tooltip: The dashboard includes a tooltip summarizing the current state—e.g., “High activity, trend and momentum prioritized,” “Low activity, price action prioritized,” or “Balanced market, all categories considered.”
---
11. Category Weights: Base vs. Dynamic
Traders begin by specifying base weights for Trend Strength, Momentum, and Price Action that sum to 100 %. These apply only when volatility is in the Medium band. Once volatility shifts:
• High Volatility Overrides:
• Trend jumps from its base (e.g., 40 %) to 50 %.
• Momentum jumps from its base (e.g., 30 %) to 35 %.
• Price Action is reduced to 15 %.
Example: If base weights were Trend = 40 %, Momentum = 30 %, Price Action = 30 %, then in High Activity they become 50/35/15. A Trend score of +3 now contributes 3 × 0.50 = +1.50 to netScore; a Momentum +2 contributes 2 × 0.35 = +0.70. In total, Trend + Momentum can easily push netScore above the +2 threshold on its own.
• Low Volatility Overrides:
• Price Action leaps from its base (30 %) to 55 %.
• Trend falls to 25 %, Momentum falls to 20 %.
Why? When markets are quiet, subtle candle breakouts, doji patterns, and small-range expansions tend to foreshadow the next swing more effectively than raw trend readings. A Price Action score of +3 in this state contributes 3 × 0.55 = +1.65, which can carry the netScore toward +2—even if Trend and Momentum are neutral or only mildly positive.
Because these weight shifts happen only after two consecutive bars confirm a High or Low state (if hysteresis is on), the indicator avoids constantly flipping its emphasis during borderline volatility phases.
---
12. Dominant Category Explained
Within the dashboard, a label such as “Trend Dominant,” “Momentum Dominant,” or “Price Action Dominant” appears when one category’s absolute weighted contribution to netScore is the largest. Concretely:
• Compute each category’s weighted contribution = (raw category score) × (current weight).
• Compare the absolute values of those three contributions.
• The category with the highest absolute value is flagged as Dominant for that bar.
Why It Matters:
• Momentum Dominant: Indicates that the combined force of RSI, Stochastic, and MACD (after weighting) is pushing netScore farther than either Trend or Price Action. In practice, it means that short-term sentiment and speed of change are the primary drivers right now, so traders should watch for continued momentum signals before committing to a trade.
• Trend Dominant: Means ADX, MA slope, and Ichimoku (once weighted) outweigh the other categories. This suggests a strong directional move is in place; trend-following entries or confirming pullbacks are likely to succeed.
• Price Action Dominant: Occurs when breakout/breakdown patterns, Heikin-Ashi candle readings, and range expansions (after weighting) are the most influential. This often happens in calmer markets, where subtle shifts in candle structure can foreshadow bigger moves.
By explicitly calling out which category is carrying the most weight at any moment, the dashboard gives traders immediate insight into why the netScore is tilting toward bullish, bearish, or sideways.
---
13. Oscillator Plot: How to Read It
The “Net Score” oscillator sits below the dashboard and visually displays the smoothed netScore as a line graph. Key features:
1. Value Range: In normal conditions it oscillates roughly between –3 and +3, but extreme confluences can push it outside that range.
2. Horizontal Threshold Lines:
• +2 Line (Bullish threshold)
• 0 Line (Neutral midline)
• –2 Line (Bearish threshold)
3. Zone Coloring:
• Green Background (Bullish Zone): When netScore ≥ +2.
• Red Background (Bearish Zone): When netScore ≤ –2.
• Gray Background (Sideways Zone): When –2 < netScore < +2.
4. Dynamic Line Color:
• The plotted netScore line itself is colored green in a Bullish Zone, red in a Bearish Zone, or gray in a Sideways Zone, creating an immediate visual cue.
Interpretation Tips:
• Crossing Above +2: Signals a strong enough combined trend/momentum/price-action reading to classify as Bullish. Many traders wait for a clear crossing plus a confirmation candle before entering a long position.
• Crossing Below –2: Indicates a strong Bearish signal. Traders may consider short or exit strategies.
• Rising Slope, Even Below +2: If netScore climbs steadily from neutral toward +2, it demonstrates building bullish momentum.
• Divergence: If price makes a higher high but the oscillator fails to reach a new high, it can warn of weakening momentum and a potential reversal.
---
14. Comments and Their Necessity
Every sub-indicator (ADX, MA slope, Ichimoku, RSI, Stochastic, MACD, HH/LL, Heikin-Ashi, Candle Range, BBW, ATR, KCW, Volume) generates a short comment that appears in the detailed dashboard. Examples:
• “Strong bullish trend” or “Strong bearish trend” for ADX/DMI
• “Fast MA above slow MA” or “Fast MA below slow MA” for MA slope
• “RSI above dynamic threshold” or “RSI below dynamic threshold” for RSI
• “MACD histogram positive” or “MACD histogram negative” for MACD Hist
• “Price near highs” or “Price near lows” for HH/LL checks
• “Bullish Heikin Ashi” or “Bearish Heikin Ashi” for HA Doji scoring
• “Large range, trend confirmed” or “Small range, trend contradicted” for Candle Range
Additionally, the top-row comment for each category is:
• Trend: “Highly Bullish,” “Highly Bearish,” or “Neutral Trend.”
• Momentum: “Strong Momentum,” “Weak Momentum,” or “Neutral Momentum.”
• Price Action: “Bullish Action,” “Bearish Action,” or “Neutral Action.”
• Market Activity: “Volatile Market,” “Calm Market,” or “Stable Market.”
Reasons for These Comments:
• Transparency: Shows exactly how each sub-indicator contributed to its category score.
• Education: Helps traders learn why a category is labeled bullish, bearish, or neutral, building intuition over time.
• Customization: If, for example, the RSI comment says “RSI neutral” despite an impending trend shift, a trader might choose to adjust RSI length or thresholds.
In the detailed dashboard, hovering over each comment cell also reveals a tooltip with additional context (e.g., “Fast MA above slow MA” or “Senkou A above Senkou B”), helping traders understand the precise rule behind that +1, 0, or –1 assignment.
---
15. Real-Life Example (Consolidated)
• Instrument & Timeframe: Bitcoin (BTCUSD), 1-hour chart.
• Current Market Activity: BBW and ATR both spike (+1 each), KCW is moderately high (+1), but volume is only neutral (0) → Raw Market Activity Score = +2 → State = High Activity (after two bars, if hysteresis is on).
• Category Weights Applied: Trend = 50 %, Momentum = 35 %, Price Action = 15 %.
• Trend Sub-Scores:
1. ADX = 25 (above threshold 20) with +DI > –DI → +1.
2. Fast MA (20-period) sits above Slow MA (50-period) → +1.
3. Ichimoku: Senkou A > Senkou B → +1.
→ Trend Score = +3.
• Momentum Sub-Scores:
4. RSI = 75 (above its moving average +1 stdev) → +1.
5. MACD histogram = +0.15 → +1.
6. Stochastic %K = 50 (mid-range) → 0.
→ Momentum Score = +2.
• Price Action Sub-Scores:
7. Price is not within 1 % of the 20-period high/low and slope = positive → 0.
8. Heikin-Ashi body is slightly larger than stdev over last 5 bars with haClose > haOpen → +1.
9. Candle range is just above its dynamic upper bound but trend is already captured, so → +1.
→ Price Action Score = +2.
• Calculate netScore (before smoothing):
• Trend contribution = 3 × 0.50 = 1.50
• Momentum contribution = 2 × 0.35 = 0.70
• Price Action contribution = 2 × 0.15 = 0.30
• Raw netScore = 1.50 + 0.70 + 0.30 = 2.50 → Immediately classified as Bullish.
• Oscillator & Dashboard Output:
• The oscillator line crosses above +2 and turns green.
• Dashboard displays:
• Trend Regime “BULLISH,” Trend Score = 3, Comment = “Highly Bullish.”
• Momentum Regime “BULLISH,” Momentum Score = 2, Comment = “Strong Momentum.”
• Price Action Regime “BULLISH,” Price Action Score = 2, Comment = “Bullish Action.”
• Market Activity State “High,” Comment = “Volatile Market.”
• Weights: Trend 50 %, Momentum 35 %, Price Action 15 %.
• Dominant Category: Trend (because 1.50 > 0.70 > 0.30).
• Overall Score: 2.50, posCount = (three +1s in Trend) + (two +1s in Momentum) + (two +1s in Price Action) = 7 bullish signals, negCount = 0.
• Final Zone = “BULLISH.”
• The trader sees that both Trend and Momentum are reinforcing each other under high volatility. They might wait one more candle for confirmation but already have strong evidence to consider a long.
---
• .
---
Disclaimer
This indicator is strictly a technical analysis tool and does not constitute financial advice. All trading involves risk, including potential loss of capital. Past performance is not indicative of future results. Traders should:
• Always backtest the “Market Zone Analyzer ” on their chosen symbols and timeframes before committing real capital.
• Combine this tool with sound risk management, position sizing, and, if possible, fundamental analysis.
• Understand that no indicator is foolproof; always be prepared for unexpected market moves.
Goodluck
-BullByte!
---
🔁 Intraday Buy/Sell with TP/SL + AlertsAlerts for:
Buy Call / Buy Put signals
Take Profit hit
Stop Loss hit
📊 Auto Exit Tracking:
Monitors real-time price
Exits trade if TP or SL is hit
Displays exit label
🟢 Entry/Exit Dots for clear charting
40 Ticker Cross-Sectional Z-Scores [BackQuant]40 Ticker Cross-Sectional Z-Scores
BackQuant’s 40 Ticker Cross-Sectional Z-Scores is a powerful portfolio management strategy that analyzes the relative performance of up to 40 different assets, comparing them on a cross-sectional basis to identify the top and bottom performers. This indicator computes Z-scores for each asset based on their log returns and evaluates them relative to the mean and standard deviation over a rolling window. The Z-scores represent how far an asset's return deviates from the average, and these values are used to rank the assets, allowing for dynamic asset allocation based on performance.
By focusing on the strongest-performing assets and avoiding the weakest, this strategy aims to enhance returns while managing risk. Additionally, by adjusting for standard deviations, the system offers a risk-adjusted method of ranking assets, making it suitable for traders who want to dynamically allocate capital based on performance metrics rather than just price movements.
Key Features
1. Cross-Sectional Z-Score Calculation:
The system calculates Z-scores for 40 different assets, evaluating their log returns against the mean and standard deviation over a rolling window. This enables users to assess the relative performance of each asset dynamically, highlighting which assets are performing better or worse compared to their historical norms. The Z-score is a useful statistical tool for identifying outliers in asset performance.
2. Asset Ranking and Allocation:
The system ranks assets based on their Z-scores and allocates capital to the top performers. It identifies the top and bottom assets, and traders can allocate capital to the top-performing assets, ensuring that their portfolio is aligned with the best performers. Conversely, the bottom assets are removed from the portfolio, reducing exposure to underperforming assets.
3. Rolling Window for Mean and Standard Deviation Calculations:
The Z-scores are calculated based on rolling means and standard deviations, making the system adaptive to changing market conditions. This rolling calculation window allows the strategy to adjust to recent performance trends and minimize the impact of outdated data.
4. Mean and Standard Deviation Visualization:
The script provides real-time visualizations of the mean (x̄) and standard deviation (σ) of asset returns, helping traders quickly identify trends and volatility in their portfolio. These visual indicators are useful for understanding the current market environment and making more informed allocation decisions.
5. Top & Bottom Performer Tables:
The system generates tables that display the top and bottom performers, ranked by their Z-scores. Traders can quickly see which assets are outperforming and underperforming. These tables provide clear and actionable insights, helping traders make informed decisions about which assets to include in their portfolio.
6. Customizable Parameters:
The strategy allows traders to customize several key parameters, including:
Rolling Calculation Window: Set the window size for the rolling mean and standard deviation calculations.
Top & Bottom Tickers: Choose how many of the top and bottom assets to display and allocate capital to.
Table Orientation: Select between vertical or horizontal table formats to suit the user’s preference.
7. Forward Test & Out-of-Sample Testing:
The system includes out-of-sample forward tests, ensuring that the strategy is evaluated based on real-time performance, not just historical data. This forward testing approach helps validate the robustness of the strategy in dynamic market conditions.
8. Visual Feedback and Alerts:
The system provides visual feedback on the current asset rankings and allocations, with dynamic labels and plots on the chart. Additionally, users receive alerts when allocations change, keeping them informed of important adjustments.
9. Risk Management via Z-Scores and Std Dev:
The system’s approach to asset selection is based on Z-scores, which normalize performance relative to the historical mean. By incorporating standard deviation, it accounts for the volatility and risk associated with each asset. This allows for more precise risk management and portfolio construction.
10. Note on Mean Reversion Strategy:
If you take the inverse of the signals provided by this indicator, the strategy can be used for mean-reversion rather than trend-following. This would involve buying the underperforming assets and selling the outperforming ones. However, it's important to note that this approach does not work well with highly correlated assets, as the relationship between the assets could result in the same directional movement, undermining the effectiveness of the mean-reversion strategy.
References
www.uts.edu.au
onlinelibrary.wiley.com
www.cmegroup.com
Final Thoughts
The 40 Ticker Cross-Sectional Z-Scores strategy offers a data-driven approach to portfolio management, dynamically allocating capital based on the relative performance of assets. By using Z-scores and standard deviations, this strategy ensures that capital is directed to the strongest performers while avoiding weaker assets, ultimately improving the risk-adjusted returns of the portfolio. Whether you’re focused on trend-following or looking to explore mean-reversion strategies, this flexible system can be tailored to suit your investment goals.
Auto Fractal [theUltimator5]I took the awesome indicator provided by theUltimator5 from and implemented the Freeze function by screaming at gemini for the past hour to keep at it until it worked.
Props to theUltimator5 for sharing this script with everyone as opensource.
Liquidity mark-out indicator(by Lumiere)This indicator marks out every High that has a bullish candle followed by a bearish one, vice versa for lows.
Once the price reaches the marked-out liquidity, the line is removed automatically.
This indicator only shows the current liquidity of the time frame you are at.
(To get it look like the picture just chance the length to 30-50)
Key Features of the Liquidity Mark-Out Indicator:
🔹 Identifies Liquidity Zones – Marks highs and lows based on candlestick patterns.
🔹 Customizable Settings – Toggle highs/lows visibility 🎚️, adjust line colors 🎨, and set line length (bars) 📏.
🔹 Smart Clean-Up – Automatically removes swept levels (when price breaks through) for a clean chart 🧹.
🔹 Pattern-Based Detection –
Highs: Detects two-candle reversal patterns (🟢 bullish close → 🔴 bearish close).
Lows: Detects two-candle reversal patterns (🔴 bearish close → 🟢 bullish close).
🔹 Dynamic Lines – Projects liquidity levels forward (adjustable length) to track key zones 📈.
Perfect For Traders Looking To:
✅ Spot potential liquidity grabs 🎯
✅ Identify key support/resistance levels 🛑
✅ Clean up their chart from outdated levels 🖥️
(Mustang Algo) Stochastic RSI + Triple EMAStochastic RSI + Triple EMA (StochTEMA)
Overview
The Stochastic RSI + Triple EMA indicator combines the Stochastic RSI oscillator with a Triple Exponential Moving Average (TEMA) overlay to generate clear buy and sell signals on the price chart. By measuring RSI overbought/oversold conditions and confirming trend direction with TEMA, this tool helps traders identify high-probability entries and exits while filtering out noise in choppy markets.
Key Features
Stochastic RSI Calculation
Computes a standard RSI over a user-defined period (default 50).
Applies a Stochastic oscillator to the RSI values over a second user-defined period (default 50).
Smooths the %K line by taking an SMA over a third input (default 3), and %D is an SMA of %K over another input (default 3).
Defines oversold when both %K and %D are below 20, and overbought when both are above 80.
Triple EMA (TEMA)
Calculates three successive EMAs on the closing price with the same length (default 9).
Combines them using TEMA = 3×(EMA1 – EMA2) + EMA3, producing a fast-reacting trend line.
Bullish trend is identified when price > TEMA and TEMA is rising; bearish trend when price < TEMA and TEMA is falling; neutral/flat when TEMA change is minimal.
Signal Logic
Strong Buy: Previous bar’s Stoch RSI was oversold (both %K and %D < 20), %K crosses above %D, and TEMA is in a bullish trend.
Medium Buy: %K crosses above %D (without requiring oversold), TEMA is bullish, and previous %K < 50.
Weak Buy: Previous bar’s %K and %D were oversold, %K crosses above %D, TEMA is flat or bullish (not bearish).
Strong Sell: Previous bar’s Stoch RSI was overbought (both %K and %D > 80), %K crosses below %D, and TEMA is bearish.
Medium Sell: %K crosses below %D (without requiring overbought), TEMA is bearish, and previous %K > 50.
Weak Sell: Previous bar’s %K and %D were overbought, %K crosses below %D, TEMA is flat or bearish (not bullish).
Visual Elements on Chart
TEMA Line: Plotted in cyan (#00BCD4) with a medium-thick line for clear trend visualization.
Buy/Sell Markers:
BUY STRONG: Lime label below the candle
BUY MEDIUM: Green triangle below the candle
BUY WEAK: Semi-transparent green circle below the candle
SELL STRONG: Red label above the candle
SELL MEDIUM: Orange triangle above the candle
SELL WEAK: Semi-transparent orange circle above the candle
Candle & Background Coloring: When a strong buy or sell signal occurs, the candle body is tinted (semi-transparent lime/red) and the chart background briefly flashes light green (buy) or light red (sell).
Dynamic Support/Resistance:
On a strong buy signal, a green dot is plotted under that bar’s low as a temporary support marker.
On a strong sell signal, a red dot is plotted above that bar’s high as a temporary resistance marker.
Alerts
Strong Buy Alert: Triggered when Stoch RSI is oversold, %K crosses above %D, and TEMA is bullish.
Strong Sell Alert: Triggered when Stoch RSI is overbought, %K crosses below %D, and TEMA is bearish.
General Buy Alert: Triggered on any bullish crossover (%K > %D) when TEMA is not bearish.
General Sell Alert: Triggered on any bearish crossover (%K < %D) when TEMA is not bullish.
Inputs
Stochastic RSI Settings (group “Stochastic RSI”):
K (smoothK): Period length for smoothing the %K line (default 3, minimum 1)
D (smoothD): Period length for smoothing the %D line (default 3, minimum 1)
RSI Length (lengthRSI): Number of bars used for the RSI calculation (default 50, minimum 1)
Stochastic Length (lengthStoch): Number of bars for the Stochastic oscillator applied to RSI (default 50, minimum 1)
RSI Source (src): Price source for the RSI (default = close)
TEMA Settings (group “Triple EMA”):
TEMA Length (lengthTEMA): Number of bars used for each of the three EMAs (default 9, minimum 1)
How to Use
Add the Script
Copy and paste the indicator code into TradingView’s Pine Editor (version 6).
Save the script and add it to your chart as “Stochastic RSI + Triple EMA (StochTEMA).”
Adjust Inputs
Choose shorter lengths for lower timeframes (e.g., intraday scalping) and longer lengths for higher timeframes (e.g., swing trading).
Fine-tune the Stochastic RSI parameters (K, D, RSI Length, Stochastic Length) to suit the volatility of the instrument.
Modify TEMA Length if you prefer a faster or slower moving average response.
Interpret Signals
Primary Entries/Exits: Focus on “BUY STRONG” and “SELL STRONG” signals, as they require both oversold/overbought conditions and a confirming TEMA trend.
Confirmation Signals: Use “BUY MEDIUM”/“BUY WEAK” to confirm or add to an existing position when the market is trending. Similarly, “SELL MEDIUM”/“SELL WEAK” can be used to scale out or confirm bearish momentum.
Support/Resistance Dots: These help identify recent swing lows (green dots) and swing highs (red dots) that were tagged by strong signals—useful to place stop-loss or profit-target orders.
Set Alerts
Open the Alerts menu (bell icon) in TradingView, choose this script, and select the desired alert condition (e.g., “BUY Signal Strong”).
Configure notifications (popup, email, webhook) according to your trading workflow.
Notes & Best Practices
Filtering False Signals: By combining Stoch RSI crossovers with TEMA trend confirmation, most false breakouts during choppy price action are filtered out.
Timeframe Selection: This indicator works on all timeframes, but shorter timeframes may generate frequent signals—consider higher-timeframe confirmation when trading lower timeframes.
Risk Management: Always use proper position sizing and stop-loss placement. An “oversold” or “overbought” reading can remain extended for some time in strong trends.
Backtesting/Optimization: Before live trading, backtest different parameter combinations on historical data to find the optimal balance between sensitivity and reliability for your chosen instrument.
No Guarantee of Profits: As with any technical indicator, past performance does not guarantee future results. Use in conjunction with other forms of analysis (volume, price patterns, fundamentals).
Author: Your Name or Username
Version: 1.0 (Pine Script v6)
Published: June 2025
Feel free to customize input values and visual preferences. If you find bugs or have suggestions for improvements, open an issue or leave a comment below. Trade responsibly!
1.85I copied this indicator from 4c program so all credit to him/her. I just changed it from 2 SD to 1.85
DCA Investment Tracker Pro [tradeviZion]DCA Investment Tracker Pro: Educational DCA Analysis Tool
An educational indicator that helps analyze Dollar-Cost Averaging strategies by comparing actual performance with historical data calculations.
---
💡 Why I Created This Indicator
As someone who practices Dollar-Cost Averaging, I was frustrated with constantly switching between spreadsheets, calculators, and charts just to understand how my investments were really performing. I wanted to see everything in one place - my actual performance, what I should expect based on historical data, and most importantly, visualize where my strategy could take me over the long term .
What really motivated me was watching friends and family underestimate the incredible power of consistent investing. When Napoleon Bonaparte first learned about compound interest, he reportedly exclaimed "I wonder it has not swallowed the world" - and he was right! Yet most people can't visualize how their $500 monthly contributions today could become substantial wealth decades later.
Traditional DCA tracking tools exist, but they share similar limitations:
Require manual data entry and complex spreadsheets
Use fixed assumptions that don't reflect real market behavior
Can't show future projections overlaid on actual price charts
Lose the visual context of what's happening in the market
Make compound growth feel abstract rather than tangible
I wanted to create something different - a tool that automatically analyzes real market history, detects volatility periods, and shows you both current performance AND educational projections based on historical patterns right on your TradingView charts. As Warren Buffett said: "Someone's sitting in the shade today because someone planted a tree a long time ago." This tool helps you visualize your financial tree growing over time.
This isn't just another calculator - it's a visualization tool that makes the magic of compound growth impossible to ignore.
---
🎯 What This Indicator Does
This educational indicator provides DCA analysis tools. Users can input investment scenarios to study:
Theoretical Performance: Educational calculations based on historical return data
Comparative Analysis: Study differences between actual and theoretical scenarios
Historical Projections: Theoretical projections for educational analysis (not predictions)
Performance Metrics: CAGR, ROI, and other analytical metrics for study
Historical Analysis: Calculates historical return data for reference purposes
---
🚀 Key Features
Volatility-Adjusted Historical Return Calculation
Analyzes 3-20 years of actual price data for any symbol
Automatically detects high-volatility stocks (meme stocks, growth stocks)
Uses median returns for volatile stocks, standard CAGR for stable stocks
Provides conservative estimates when extreme outlier years are detected
Smart fallback to manual percentages when data insufficient
Customizable Performance Dashboard
Educational DCA performance analysis with compound growth calculations
Customizable table sizing (Tiny to Huge text options)
9 positioning options (Top/Middle/Bottom + Left/Center/Right)
Theme-adaptive colors (automatically adjusts to dark/light mode)
Multiple display layout options
Future Projection System
Visual future growth projections
Timeframe-aware calculations (Daily/Weekly/Monthly charts)
1-30 year projection options
Shows projected portfolio value and total investment amounts
Investment Insights
Performance vs benchmark comparison
ROI from initial investment tracking
Monthly average return analysis
Investment milestone alerts (25%, 50%, 100% gains)
Contribution tracking and next milestone indicators
---
📊 Step-by-Step Setup Guide
1. Investment Settings 💰
Initial Investment: Enter your starting lump sum (e.g., $60,000)
Monthly Contribution: Set your regular DCA amount (e.g., $500/month)
Return Calculation: Choose "Auto (Stock History)" for real data or "Manual" for fixed %
Historical Period: Select 3-20 years for auto calculations (default: 10 years)
Start Year: When you began investing (e.g., 2020)
Current Portfolio Value: Your actual portfolio worth today (e.g., $150,000)
2. Display Settings 📊
Table Sizes: Choose from Tiny, Small, Normal, Large, or Huge
Table Positions: 9 options - Top/Middle/Bottom + Left/Center/Right
Visibility Toggles: Show/hide Main Table and Stats Table independently
3. Future Projection 🔮
Enable Projections: Toggle on to see future growth visualization
Projection Years: Set 1-30 years ahead for analysis
Live Example - NASDAQ:META Analysis:
Settings shown: $60K initial + $500/month + Auto calculation + 10-year history + 2020 start + $150K current value
---
🔬 Pine Script Code Examples
Core DCA Calculations:
// Calculate total invested over time
months_elapsed = (year - start_year) * 12 + month - 1
total_invested = initial_investment + (monthly_contribution * months_elapsed)
// Compound growth formula for initial investment
theoretical_initial_growth = initial_investment * math.pow(1 + annual_return, years_elapsed)
// Future Value of Annuity for monthly contributions
monthly_rate = annual_return / 12
fv_contributions = monthly_contribution * ((math.pow(1 + monthly_rate, months_elapsed) - 1) / monthly_rate)
// Total expected value
theoretical_total = theoretical_initial_growth + fv_contributions
Volatility Detection Logic:
// Detect extreme years for volatility adjustment
extreme_years = 0
for i = 1 to historical_years
yearly_return = ((price_current / price_i_years_ago) - 1) * 100
if yearly_return > 100 or yearly_return < -50
extreme_years += 1
// Use median approach for high volatility stocks
high_volatility = (extreme_years / historical_years) > 0.2
calculated_return = high_volatility ? median_of_returns : standard_cagr
Performance Metrics:
// Calculate key performance indicators
absolute_gain = actual_value - total_invested
total_return_pct = (absolute_gain / total_invested) * 100
roi_initial = ((actual_value - initial_investment) / initial_investment) * 100
cagr = (math.pow(actual_value / initial_investment, 1 / years_elapsed) - 1) * 100
---
📊 Real-World Examples
See the indicator in action across different investment types:
Stable Index Investments:
AMEX:SPY (SPDR S&P 500) - Shows steady compound growth with standard CAGR calculations
Classic DCA success story: $60K initial + $500/month starting 2020. The indicator shows SPY's historical 10%+ returns, demonstrating how consistent broad market investing builds wealth over time. Notice the smooth theoretical growth line vs actual performance tracking.
MIL:VUAA (Vanguard S&P 500 UCITS) - Shows both data limitation and solution approaches
Data limitation example: VUAA shows "Manual (Auto Failed)" and "No Data" when default 10-year historical setting exceeds available data. The indicator gracefully falls back to manual percentage input while maintaining all DCA calculations and projections.
MIL:VUAA (Vanguard S&P 500 UCITS) - European ETF with successful 5-year auto calculation
Solution demonstration: By adjusting historical period to 5 years (matching available data), VUAA auto calculation works perfectly. Shows how users can optimize settings for newer assets. European market exposure with EUR denomination, demonstrating DCA effectiveness across different markets and currencies.
NYSE:BRK.B (Berkshire Hathaway) - Quality value investment with Warren Buffett's proven track record
Value investing approach: Berkshire Hathaway's legendary performance through DCA lens. The indicator demonstrates how quality companies compound wealth over decades. Lower volatility than tech stocks = standard CAGR calculations used.
High-Volatility Growth Stocks:
NASDAQ:NVDA (NVIDIA Corporation) - Demonstrates volatility-adjusted calculations for extreme price swings
High-volatility example: NVIDIA's explosive AI boom creates extreme years that trigger volatility detection. The indicator automatically switches to "Median (High Vol): 50%" calculations for conservative projections, protecting against unrealistic future estimates based on outlier performance periods.
NASDAQ:TSLA (Tesla) - Shows how 10-year analysis can stabilize volatile tech stocks
Stable long-term growth: Despite Tesla's reputation for volatility, the 10-year historical analysis (34.8% CAGR) shows consistent enough performance that volatility detection doesn't trigger. Demonstrates how longer timeframes can smooth out extreme periods for more reliable projections.
NASDAQ:META (Meta Platforms) - Shows stable tech stock analysis using standard CAGR calculations
Tech stock with stable growth: Despite being a tech stock and experiencing the 2022 crash, META's 10-year history shows consistent enough performance (23.98% CAGR) that volatility detection doesn't trigger. The indicator uses standard CAGR calculations, demonstrating how not all tech stocks require conservative median adjustments.
Notice how the indicator automatically detects high-volatility periods and switches to median-based calculations for more conservative projections, while stable investments use standard CAGR methods.
---
📈 Performance Metrics Explained
Current Portfolio Value: Your actual investment worth today
Expected Value: What you should have based on historical returns (Auto) or your target return (Manual)
Total Invested: Your actual money invested (initial + all monthly contributions)
Total Gains/Loss: Absolute dollar difference between current value and total invested
Total Return %: Percentage gain/loss on your total invested amount
ROI from Initial Investment: How your starting lump sum has performed
CAGR: Compound Annual Growth Rate of your initial investment (Note: This shows initial investment performance, not full DCA strategy)
vs Benchmark: How you're performing compared to the expected returns
---
⚠️ Important Notes & Limitations
Data Requirements: Auto mode requires sufficient historical data (minimum 3 years recommended)
CAGR Limitation: CAGR calculation is based on initial investment growth only, not the complete DCA strategy
Projection Accuracy: Future projections are theoretical and based on historical returns - actual results may vary
Timeframe Support: Works ONLY on Daily (1D), Weekly (1W), and Monthly (1M) charts - no other timeframes supported
Update Frequency: Update "Current Portfolio Value" regularly for accurate tracking
---
📚 Educational Use & Disclaimer
This analysis tool can be applied to various stock and ETF charts for educational study of DCA mathematical concepts and historical performance patterns.
Study Examples: Can be used with symbols like AMEX:SPY , NASDAQ:QQQ , AMEX:VTI , NASDAQ:AAPL , NASDAQ:MSFT , NASDAQ:GOOGL , NASDAQ:AMZN , NASDAQ:TSLA , NASDAQ:NVDA for learning purposes.
EDUCATIONAL DISCLAIMER: This indicator is a study tool for analyzing Dollar-Cost Averaging strategies. It does not provide investment advice, trading signals, or guarantees. All calculations are theoretical examples for educational purposes only. Past performance does not predict future results. Users should conduct their own research and consult qualified financial professionals before making any investment decisions.
---
© 2025 TradeVizion. All rights reserved.
NIFTY Option Buy Strategy MASTER v1This script is a complete option buying strategy framework for NIFTY, designed for both intraday and positional swing trades.
🔹 Built using multi-timeframe analysis (EMAs, MACD, RSI)
🔹 Combines key macro filters: India VIX, PCR, FII/DII net cash flows
🔹 Supports both Call (CE) and Put (PE) entries
🔹 Includes manual input dashboard for real-time market context
🔹 Trade logic includes:
Bollinger Band breakouts
Volume confirmation
VWAP filtering
EMA crossover + MACD alignment
Resistance/support proximity from option chain (manual)
📈 Smart Trade Management:
Multi-target system (e.g., exit 50% at RR=1, 50% at RR=2)
Trailing stop-loss after target 1 hits
Automatic exit on SL/TP or reverse signals
Visual markers for all entries, exits, and stops
📊 Built-in Dashboard:
Displays India VIX, PCR, FII/DII flows, and S/R levels
Strike price selection (ATM + offset logic)
🧪 Ideal for backtesting, alerts, and real-time execution.
Can be used with alerts + webhook for automated trading or signal generation.
⚠️ Note: This script is for educational purposes only. Always test on paper trading before going live.
Relative Imbalance Flow Tracker🚀 RIFT: Relative Imbalance Flow Tracker
A totally unique RSI envelope system that uses dual moving averages and color-coded dominance to show potential reversal zones before they happen. No standard Bollinger Bands. No gray confusion. Just clean, smart, visual logic.
🧠 How It Works
RSI is calculated and optionally smoothed (RMA/EMA/SMA/WMA).
Two RSI-based MAs are plotted:
- Fast MA (e.g. 16) = reactive
- Slow MA (e.g. 32) = steady
Each MA gets its own envelope based on a % distance.
If fast envelope dominates (outside the slow one), it lights up. Otherwise, they fade and cancel each other visually.
🎨 Color Logic
🔴 Upper Band (Red) = Overbought danger zone
When fast upper > slow upper, it's a warning flare.
🟢 Lower Band (Green) = Oversold bounce zone
When fast lower < slow lower, bulls may step in.
🟠 RSI Line Orange = Mixed signals
RSI is between the two MAs—no one's in control.
🟢 - RSI Line Green = RSI > both MAs = strong momentum
🔴 - RSI Line Red = RSI < both MAs = bearish pressure
🔍 How to Read It
- Red Band + Green RSI = uptrend stalling
- Green Band + Red RSI = selloff slowing
- No Fill = Envelopes overlapping, no edge
- RSI flips from green/red to orange = tug-of-war
⚙️ Why It’s Useful
- Gives early reversal clues before RSI tags extreme levels.
- Filters out fakeouts by showing when RSI can’t reach the “target zone.”
- Dynamic: adapts with trend strength and volatility via envelope width.
- Fully customizable: lengths, smoothing, envelope %, colors, fills.
💡 Quick Visual Tips
🔴 - Red Band visible but RSI stalls? = Likely reversal.
🟢 - Green Band shows up and RSI flips green? = Go time.
🟠 - RSI turns orange + no fills? = Sit out or scalp light.
Advanced MACD Pro (WhiteStone_Ibrahim) - T3 Themed✨ Advanced MACD Pro (WhiteStone_Ibrahim) - T3 Themed ✨
Take your MACD analysis to the next level with the Advanced MACD Pro - T3 Themed indicator by WhiteStone_Ibrahim! This isn't just another MACD; it's a comprehensive toolkit packed with advanced features, unique T3 integration, and extensive customization options to provide deeper market insights.
Whether you're a seasoned trader or just starting, this indicator offers a versatile and powerful way to analyze momentum, identify trends, and spot potential reversals.
Key Features:
Core MACD Functionality:
Classic MACD Line: Calculated from customizable Fast and Slow EMAs using your chosen source (Close, Open, HLC3, etc.).
Standard Signal Line: EMA of the MACD line, with adjustable length.
Dynamic MACD Line Coloring: Automatically changes color based on whether it's above or below the zero line (positive/negative).
Zero Line: Clearly plotted for reference.
Enhanced MACD Histogram:
Sophisticated Color Coding: The histogram isn't just positive or negative. It intelligently colors based on momentum strength and direction:
Strong Bullish: MACD above signal, histogram increasing.
Weakening Bullish: MACD above signal, histogram decreasing.
Strong Bearish: MACD below signal, histogram decreasing.
Weakening Bearish: MACD below signal, histogram increasing.
Neutral: Default color for other conditions.
Optional Histogram Smoothing: Smooth out the histogram noise using one of five different moving average types: SMA, EMA, WMA, RMA, or the advanced T3 (Tilson T3). Customize smoothing length and T3 vFactor.
🌟 Unique T3 Integration (T3 Themed):
Extra T3 Signal Line (on MACD): An additional, fast-reacting T3 moving average calculated directly from the MACD line. This provides an alternative and often quicker signal.
Customizable T3 length and vFactor.
Dynamic Coloring: The T3 Signal Line changes color (bullish/bearish) based on its crossover with the MACD line, offering clear visual cues.
T3 is also available as a smoothing option for the main histogram (see above).
🔍 Disagreement & Divergence Detection:
Bar/Price Disagreement Markers:
Highlights instances where the price bar's direction (e.g., a bullish candle) contradicts the current MACD momentum (e.g., MACD below its signal line).
Visual markers (circles) appear above/below bars to draw attention to these potential early warnings or confirmations.
Histogram Color Change on Disagreement: Optionally, the histogram can adopt distinct alternative colors during these bar/price disagreements for even clearer visual alerts.
Classic Bullish & Bearish Divergence Detection:
Automatically identifies regular divergences between price action (Higher Highs/Lower Lows) and the MACD line (Lower Highs/Higher Lows).
Customizable pivot lookback periods (left and right bars) for divergence sensitivity.
Plots clear "Bull" and "Bear" labels on the price chart where divergences occur.
🎨 Extensive Customization & Visuals:
Multiple Color Themes: Choose from pre-set themes like 'Dark Mode', 'Light Mode', 'Neon Night', or use 'Default (Current Settings)' to fine-tune every color yourself.
Granular Control (Default Theme): Individually customize colors and thickness for:
MACD Line (positive/negative)
Standard Signal Line
Extra T3 Signal Line (bullish/bearish)
Histogram (all four momentum states + neutral)
Disagreement Markers & Histogram Alt Colors
Divergence Lines/Labels
Zero Line
Toggle Visibility: Easily show or hide the Standard Signal Line and the Extra T3 Signal Line as needed.
🔔 Comprehensive Alert System:
Stay informed of key market events with a wide array of configurable alerts:
MACD Line / Standard Signal Line Crossover
Histogram / Zero Line Crossover
MACD Line / Zero Line Crossover
Bullish Divergence Detected
Bearish Divergence Detected
Bar/Price Disagreement (Bullish & Bearish)
MACD Line / Extra T3 Signal Line Crossover
Each alert can be individually enabled or disabled.
The Advanced MACD Pro - T3 Themed indicator is designed to be your go-to tool for momentum analysis. Its rich feature set empowers you to tailor it to your specific trading style and gain a more nuanced understanding of market dynamics.
Add it to your charts today and experience the difference!
(Developed by WhiteStone_Ibrahim)
Bilateral Filter For Loop [BackQuant]Bilateral Filter For Loop
The Bilateral Filter For Loop is an advanced technical indicator designed to filter out market noise and smooth out price data, thus improving the identification of underlying market trends. It employs a bilateral filter, which is a sophisticated non-linear filter commonly used in image processing and price time series analysis. By considering both spatial and range differences between price points, this filter is highly effective at preserving significant trends while reducing random fluctuations, ultimately making it suitable for dynamic trend-following strategies.
Please take the time to read the following:
Key Features
1. Bilateral Filter Calculation:
The bilateral filter is the core of this indicator and works by applying a weight to each data point based on two factors: spatial distance and price range difference. This dual weighting process allows the filter to preserve important price movements while reducing the impact of less relevant fluctuations. The filter uses two primary parameters:
Spatial Sigma (σ_d): This parameter adjusts the weight applied based on the distance of each price point from the current price. A larger spatial sigma means more smoothing, as further away values will contribute more heavily to the result.
Range Sigma (σ_r): This parameter controls how much weight is applied based on the difference in price values. Larger price differences result in smaller weights, while similar price values result in larger weights, thereby preserving the trend while filtering out noise.
The output of this filter is a smoothed version of the original price series, which eliminates short-term fluctuations, helping traders focus on longer-term trends. The bilateral filter is applied over a rolling window, adjusting the level of smoothing dynamically based on both the distance between values and their relative price movements.
2. For Loop Calculation for Trend Scoring:
A for-loop is used to calculate the trend score based on the filtered price data. The loop compares the current value to previous values within the specified window, scoring the trend as follows:
+1 for upward movement (when the filtered value is greater than the previous value).
-1 for downward movement (when the filtered value is less than the previous value).
The cumulative result of this loop gives a continuous trend score, which serves as a directional indicator for the market's momentum. By summing the scores over the window period, the loop provides an aggregate value that reflects the overall trend strength. This score helps determine whether the market is experiencing a strong uptrend, downtrend, or sideways movement.
3. Long and Short Conditions:
Once the trend score has been calculated, it is compared against predefined threshold levels:
A long signal is generated when the trend score exceeds the upper threshold, indicating that the market is in a strong uptrend.
A short signal is generated when the trend score crosses below the lower threshold, signaling a potential downtrend or trend reversal.
These conditions provide clear signals for potential entry points, and the color-coding helps traders quickly identify market direction:
Long signals are displayed in green.
Short signals are displayed in red.
These signals are designed to provide high-confidence entries for trend-following strategies, helping traders capture profitable movements in the market.
4. Trend Background and Bar Coloring:
The script offers customizable visual settings to enhance the clarity of the trend signals. Traders can choose to:
Color the bars based on the trend direction: Bars are colored green for long signals and red for short signals.
Change the background color to provide additional context: The background will be shaded green for a bullish trend and red for a bearish trend. This visual feedback helps traders to stay aligned with the prevailing market sentiment.
These features offer a quick visual reference for understanding the market's direction, making it easier for traders to identify when to enter or exit positions.
5. Threshold Lines for Visual Feedback:
Threshold lines are plotted on the chart to represent the predefined long and short levels. These lines act as clear markers for when the market reaches a critical threshold, triggering a potential buy (long) or sell (short) signal. By showing these threshold lines on the chart, traders can quickly gauge the strength of the market and assess whether the trend is strong enough to warrant action.
These thresholds can be adjusted based on the trader's preferences, allowing them to fine-tune the indicator for different market conditions or asset behaviors.
6. Customizable Parameters for Flexibility:
The indicator offers several parameters that can be adjusted to suit individual trading preferences:
Window Period (Bilateral Filter): The window size determines how many past price values are used to calculate the bilateral filter. A larger window increases smoothing, while a smaller window results in more responsive, but noisier, data.
Spatial Sigma (σ_d) and Range Sigma (σ_r): These values control how sensitive the filter is to price changes and the distance between data points. Fine-tuning these parameters allows traders to adjust the degree of noise reduction applied to the price series.
Threshold Levels: The upper and lower thresholds determine when the trend score crosses into long or short territory. These levels can be customized to better match the trader's risk tolerance or asset characteristics.
Visual Settings: Traders can customize the appearance of the chart, including the line width of trend signals, bar colors, and background shading, to make the indicator more readable and aligned with their charting style.
7. Alerts for Trend Reversals:
The indicator includes alert conditions for real-time notifications when the market crosses the defined thresholds. Traders can set alerts to be notified when:
The trend score crosses the long threshold, signaling an uptrend.
The trend score crosses the short threshold, signaling a downtrend.
These alerts provide timely information, allowing traders to take immediate action when the market shows a significant change in direction.
Final Thoughts
The Bilateral Filter For Loop indicator is a robust tool for trend-following traders who wish to reduce market noise and focus on the underlying trend. By applying the bilateral filter and calculating trend scores, this indicator helps traders identify strong uptrends and downtrends, providing reliable entry signals with minimal market noise. The customizable parameters, visual feedback, and alerting system make it a versatile tool for traders seeking to improve their timing and capture profitable market movements.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
CRYPTO:SOLUSD
Volume Point of Control with Fib Based Profile🍀Description:
This indicator is a comprehensive volume profile analysis tool designed to identify key price levels based on trading activity within user-defined timeframes. It plots the Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL), along with dynamically calculated Fibonacci levels derived from the developing period's range. It offers extensive customization for both historical and developing levels.
🍀Core Features:
Volume Profiling (POC, VAH, VAL):
Calculates and plots the POC (price level with the highest volume), VAH, and VAL for a selected timeframe (e.g., Daily, Weekly).
The Value Area percentage is configurable. 70% is common on normal volume profiles, but this script allows you to configure multiple % levels via the fib levels. I recommend using 2 versions of this indicator on a chart, one has Value Area at 1 (100% - high and low of lookback) and the second is a specified VA area (i.e. 70%) like in the chart snapshot above. See examples at the bottom.
Historical Levels:
Plots POC, VAH, and VAL from previous completed periods.
Optionally displays only "Unbroken" levels – historical levels that price has not yet revisited, which can act as stronger magnets or resistance/support.
The user can manage the number of historical lines displayed to prevent chart clutter.
Developing Levels:
Shows the POC, VAH, and VAL as they form in real-time during the current, incomplete period. This provides insight into intraday/intra-period value migration.
Dynamic Fibonacci Levels:
Calculates and plots Fibonacci retracement/extension levels based dynamically on the range between the developing POC and the developing VAH/VAL.
Offers 8 configurable % levels above and below POC that can be toggled on/off.
Visual Customization:
Extensive options for colors, line styles, and widths for all plotted levels.
Optional gradient fill for the Value Area that visualizes current price distance from POC - option to invert the colors as well.
Labels for developing levels and Fibonacci levels for easy identification.
🍀Characteristics:
Volume-Driven: Levels are derived from actual trading volume, reflecting areas of high participation and price agreement/disagreement.
Timeframe Specific: The results are entirely dependent on the chosen profile timeframe.
Dynamic & Static Elements: Developing levels and Fibs update live, while historical levels remain fixed once their period closes.
Lagging (Historical) & Potentially Leading: Historical levels are based on the past, but are often respected by future price action. Developing levels show current dynamics.
🍀How to Use It:
Identifying Support & Resistance: Historical and developing POCs, VAHs, and VALs are often key areas where price may react. Unbroken levels are particularly noteworthy.
Market Context & Sentiment: Trading above the POC suggests bullish strength/acceptance of higher prices, while trading below suggests bearishness/acceptance of lower prices.
Entry/Exit Zones: Interactions with these levels (rejections, breakouts, tests) can provide potential entry or exit signals, especially when confirming with other analysis methods.
Dynamic Targets: The Fibonacci levels calculated from the developing POC-VA range offer potential intraday/intra-period price targets or areas of interest.
Understanding Value Migration: Observing the movement of the developing POC/VAH/VAL throughout the period reveals where value is currently being established.
🍀Potential Drawbacks:
Input Sensitivity: The choice of timeframe, Value Area percentage, and volume resolution heavily influences the generated levels. Experimentation is needed for optimal settings per instrument/market. (I've found that Range Charts can provide very accurate volume levels on TV since the time element is removed. This helps to refine the accuracy of price levels with high volume.)
Volume Data Dependency: Requires accurate volume data. May be less reliable on instruments with sparse or questionable volume reporting.
Chart Clutter: Enabling all features simultaneously can make the chart busy. Utilize the line management inputs and toggle features as needed.
Not a Standalone Strategy: This indicator provides context and key levels. It should be used alongside other technical analysis tools and price action reading for robust decision-making.
Developing Level Fluctuation: Developing POC/VA/Fib levels can shift considerably, especially early in a new period, before settling down as more volume accumulates and time passes.
🍀Recommendations/Examples:
I recommend have this indicator on your chart twice, one has the VA set at 1 (100%) and has the fib levels plotted. The second has the VA set to 0.7 (70%) to highlight the defined VA.
Here is an example with 3 on a chart. VA of 100%, VA of 80%, and VA of 20%
EMA Pullback System 1:5 RRR [SL]EMA Trend Pullback System (1:5 RRR)
Summary:
This indicator is designed to identify high-probability pullback opportunities along the main trend, providing trade signals that target a high 1:5 Risk/Reward Ratio. It is a trend-following strategy built for patient traders who wait for optimal setups.
Strategy Logic:
The system is based on three Exponential Moving Averages (EMAs): 21, 50, and 200.
BUY Signal:
Trend (Uptrend): The price must be above the 200 EMA.
Pullback: The price must pull back into the "Dynamic Support Zone" between the 21 EMA and 50 EMA.
Confirmation: A strong Bullish Confirmation Candle (e.g., Bullish Engulfing) must form within this zone.
SELL Signal:
Trend (Downtrend): The price must be below the 200 EMA.
Pullback: The price must rally back into the "Dynamic Resistance Zone" between the 21 EMA and 50 EMA.
Confirmation: A strong Bearish Confirmation Candle (e.g., Bearish Engulfing) must form within this zone.
Key Features:
Clearly plots the 21, 50, and 200 EMAs on the chart.
Displays BUY and SELL labels when the rules are met.
Automatically calculates and plots Stop Loss (SL) and Take Profit (TP) levels for each signal.
The Risk/Reward Ratio for the Take Profit level is customizable in the settings (Default: 1:5).
How to Use:
Best suited for higher timeframes like H1 and H4.
It is crucial to wait for the signal candle to close before considering an entry.
While this is an automated tool, for best results, combine its signals with your own analysis of Price Action and Market Structure.
Disclaimer:
This is an educational tool and not financial advice. Trading involves substantial risk. Always use proper risk management. It is essential to backtest any strategy before deploying it with real capital.