Lot Size Calculator - Gold🥇 Lot Size Calculator for Gold (XAU/USD)
Description:
A professional and accurate lot size calculator specifically designed for Gold (XAU/USD) trading. This indicator helps traders calculate the optimal position size based on account balance, risk percentage, and stop loss distance, ensuring proper risk management for every trade.
Key Features:
 Accurate Gold Calculations - Properly accounts for Gold pip values ($10 per pip for standard 100oz lots)
 Multi-Currency Support - Works with USD, EUR, and GBP account currencies
 Flexible Contract Sizes - Supports Standard (100 oz), Mini (10 oz), and Micro (1 oz) lots
 Customizable Decimal Places - Display lot sizes with 2-8 decimal precision (no rounding)
 Clean Visual Design - Modern, professional info panel with gold-themed styling
 Adjustable Display - Position panel anywhere on chart with customizable colors and sizes
 Real-Time Calculations - Instantly updates as you adjust your risk parameters
How It Works:
The calculator uses the standard forex position sizing formula optimized for Gold:
Lot Size = Risk Amount / (Stop Loss in Pips × Pip Value Per Lot)
For Gold (XAU/USD):
Standard Lot (100 oz): 1 pip = $10
Mini Lot (10 oz): 1 pip = $1
Micro Lot (1 oz): 1 pip = $0.10
Settings:
Account Settings:
Account Balance: Your trading capital
Account Currency: USD, EUR, or GBP
Risk Percentage: How much to risk per trade (default: 2%)
Contract Size: 100 oz (Standard), 10 oz (Mini), or 1 oz (Micro)
Display Currency: Choose how to display risk amounts
Trade Settings:
Stop Loss: Your SL distance in pips
Display Settings:
Label Position: Top/Bottom, Left/Right, Middle Right
Label Size: Tiny to Huge
Decimal Places: 2-8 decimals
Custom Colors: Background, text, and accent colors
Perfect For:
Gold (XAU/USD) day traders and swing traders
Position sizing and risk management
Traders using fixed percentage risk models
Anyone trading Gold CFDs or spot markets
Scalpers to long-term Gold investors
What Makes This Different:
Unlike generic lot size calculators, this tool correctly calculates Gold's pip values based on contract size. Many calculators get this wrong, leading to incorrect position sizing. This indicator ensures you're always trading the right lot size for your risk tolerance.
Example Usage:
Account Balance: $10,000
Risk: 1% = $100
Stop Loss: 60 pips
Contract Size: 100 oz (Standard)
Result: 0.1667 lots (exact, no rounding)
Perfect for maintaining consistent risk management in your Gold trading strategy!
Cari dalam skrip untuk "a股近10年第二天溢价的股票"
ProScalper📊 ProScalper - Professional 1-Minute Scalping System
🎯 Overview
ProScalper is a sophisticated, multi-confluence scalping indicator designed specifically for 1-minute chart trading. Combining advanced technical analysis with intelligent signal filtering, it provides high-probability trade setups with clear entry, stop loss, and take profit levels.
✨ Key Features
🔺 Smart Signal Detection
Range Filter Technology: Fast-responding trend detection (25-period) optimized for 1-minute timeframe
Medium-sized triangles appear above/below candles for clear buy/sell signals
Only most recent signal shown - no chart clutter
Automatically deletes old signals when new ones appear
📋 Real-Time Signal Table
Top-center display shows complete trade breakdown
Grade system: A+, A, B+, B, C+ ratings for every setup
All confluence reasons listed with checkmarks
Score and R:R displayed for instant trade quality assessment
Color-coded: Green for LONG, Red for SHORT
📐 Multi-Confluence Analysis
ProScalper combines 10+ technical factors:
✅ EMA Trend: 4 EMAs (200, 48, 13, 8) for multi-timeframe alignment
✅ VWAP: Dynamic support/resistance
✅ Fibonacci Retracement: Golden ratio (61.8%), 50%, 38.2%, 78.6%
✅ Range Filter: Adaptive trend confirmation
✅ Pivot Points: Smart reversal detection
✅ Volume Analysis: Spike detection and volume profile
✅ Higher Timeframe: 5-minute trend confirmation
✅ HTF Support/Resistance: Key levels from higher timeframes
✅ Liquidity Sweeps: Smart money detection
✅ Opening Range Breakout: First 15-minute range
💰 Complete Trade Management
Entry Lines: Dashed green (LONG) or red (SHORT) showing exact entry
Stop Loss: Red dashed line with price label
Take Profit: Blue dashed line with price label and R:R
Partial Exits: 1R level marked with orange dashed line
All lines extend 10 bars for clean alignment with Fibonacci levels
📊 Dynamic Risk/Reward
Adaptive R:R calculation based on market volatility
Targets adjusted for pivot distances
Minimum 1.2:1 to maximum 3.5:1 for scalping
Position sizing based on account risk percentage
🎨 Professional Visualization
Clean chart layout - no clutter, only essential information
Custom EMA colors: Red (200), Aqua (48), Green (13), White (8)
Gold VWAP line for key support/resistance
Color-coded Fibonacci: Bright yellow (61.8%), white (50%), orange (38.2%), fuchsia (78.6%)
No shaded zones - pure price action focus
📈 Performance Tracking
Real-time statistics table (optional)
Win rate, total trades, P&L tracking
Average R:R and win/loss ratios
Setup-specific performance metrics
⚙️ Settings & Customization
Risk Management
Adjustable account risk per trade (default: 0.5%)
ATR-based stop loss multiplier (default: 0.8 for tight scalping)
Dynamic position sizing
Signal Sensitivity
Confluence Score Threshold: 40-100 (default: 55 for balanced signals)
Range Filter Period: 25 bars (fast signals for 1-min)
Range Filter Multiplier: 2.2 (tighter bands for more signals)
Visual Controls
Toggle signal table on/off
Show/hide Fibonacci levels
Control EMA visibility
Adjust table text size
Partial Exits
1R: 50% (default)
2R: 30% (default)
3R: 20% (default)
Fully customizable percentages
Trailing Stops
ATR-Based (best for scalping)
Pivot-Based
EMA-Based
Breakeven trigger at 0.8R
🎯 Best Use Cases
Ideal For:
✅ 1-minute scalping on liquid instruments
✅ Day traders looking for quick 2-8 minute trades
✅ High-frequency trading with 8-15 signals per session
✅ Trending markets where Range Filter excels
✅ Crypto, Forex, Futures - works on all liquid assets
Trading Style:
Timeframe: 1-minute (can work on 3-5 min with adjusted settings)
Hold Time: 3-8 minutes average
Target: 1.2-3R per trade
Frequency: 8-15 signals per day
Win Rate: 45-55% (with proper risk management)
📋 How to Use
Step 1: Wait for Signal
Watch for green triangle (BUY) or red triangle (SELL)
Signal table appears at top center automatically
Step 2: Review Confluence
Check grade (prefer A+, A, B+ for best quality)
Review all reasons listed in table
Confirm score is above your threshold (55+ recommended)
Note the R:R ratio
Step 3: Enter Trade
Enter at current market price
Set stop loss at red dashed line
Set take profit at blue dashed line
Mark 1R level (orange line) for partial exit
Step 4: Manage Trade
Exit 50% at 1R (orange line)
Move to breakeven after 0.8R
Trail remaining position using your chosen method
Exit fully at TP or opposite signal
🎨 Chart Setup Recommendations
Optimal Display:
Timeframe: 1-minute
Chart Type: Candles or Heikin Ashi
Background: Dark theme for best color visibility
Volume: Enable volume bars below chart
Complementary Indicators (optional):
Order flow/Delta for institutional confirmation
Market profile for key levels
Economic calendar for news avoidance
⚠️ Important Notes
Risk Disclaimer:
Not financial advice - for educational purposes only
Always use proper risk management (0.5-1% per trade max)
Past performance doesn't guarantee future results
Test on demo account before live trading
Best Practices:
✅ Trade during high liquidity hours (9:30-11 AM, 2-4 PM EST)
✅ Avoid news events and market open/close (first/last 2 minutes)
✅ Use tight stops (0.8-1.0 ATR) for 1-minute scalping
✅ Take partial profits quickly (1R = 50% off)
✅ Respect max daily loss limits (3% recommended)
✅ Focus on A and B grade setups for consistency
What Makes This Different:
🎯 Complete system - not just signals, but full trade management
📊 Multi-confluence - 10+ factors analyzed per trade
🎨 Professional visualization - clean, focused chart design
⚡ Optimized for 1-min - settings specifically tuned for fast scalping
📋 Transparent reasoning - see exactly why each trade was taken
🏆 Grade system - instantly know trade quality
🔧 Technical Details
Pine Script Version: 5
Overlay: Yes (plots on price chart)
Max Lines: 500
Max Labels: 100
Non-repainting: All signals confirmed on bar close
Alerts: Compatible with TradingView alerts
📞 Support & Updates
This indicator is actively maintained and optimized for 1-minute scalping. Settings can be adjusted for different timeframes and trading styles, but default configuration is specifically tuned for high-frequency 1-minute scalping.
🚀 Get Started
Add ProScalper to your 1-minute chart
Adjust settings to your risk tolerance
Wait for signals (green/red triangles)
Follow the signal table guidance
Manage trades using provided levels
Track performance with stats table
Happy Scalping! 📊⚡💰
FVG MagicFVG Magic — Fair Value Gaps with Smart Mitigation, Inversion & Auto-Clean-up
FVG Magic finds every tradable Fair Value Gap (FVG), shows who powered it, and then manages each gap intelligently as price interacts with it—so your chart stays actionable and clean.
Attribution
This tool is inspired by the idea popularized in “Volumatic Fair Value Gaps  ” by BigBeluga (licensed CC BY-NC-SA 4.0). Credit to BigBeluga for advancing FVG visualization in the community.
Important: This is a from-scratch implementation—no code was copied from the original. I expanded the concept substantially with a different detection stack, a gap state machine (ACTIVE → 50% SQ → MITIGATED → INVERSED), auto-clean up rules, lookback/nearest-per-side pruning, zoom-proof volume meters, and timeframe auto-tuning for 15m/H1/H4.
What makes this version more accurate
Full-coverage detection (no “missed” gaps)
Default ICT-minimal rule (Bullish: low > high , Bearish: high < low ) catches all valid 3-candle FVGs.
Optional Strict filter (stricter structure checks) for traders who prefer only “clean” gaps.
Optional size percentile filter—off by default so nothing is hidden unless you choose to filter.
Correct handling of confirmations (wick vs close)
Mitigation Source is user-selectable: high/low (wick-based) or close (strict).
This avoids false “misses” when you expect wick confirmations (50% or full fill) but your logic required closes.
State-aware labelling to prevent misleading data
The Bull%/Bear% meter is shown only while a gap is ACTIVE.
As soon as a gap is 50% SQ, MITIGATED, or INVERSED, the meter is hidden and replaced with a clear tag—so you never read stale participation stats.
Robust zoom behaviour
The meter uses a fixed bar-width (not pixels), so it stays proportional and readable at any zoom level.
Deterministic lifecycle (no stale boxes)
Remove on 50% SQ (instant or delayed).
Inversion window after first entry: if price enters but doesn’t invert within N bars, the box auto-removes once fully filled.
Inversion clean up: after a confirmed flip, keep for N bars (context) then delete (or 0 = immediate).
Result: charts auto-maintain themselves and never “lie” about relevance.
Clarity near current price
Nearest-per-side (keep N closest bullish & bearish gaps by distance to the midpoint) focuses attention where it matters without altering detection accuracy.
Lookback (bars) ensures reproducible behaviour across accounts with different data history.
Timeframe-aware defaults
Sensible auto-tuning for 15m / H1 / H4 (right-extension length, meter width, inversion windows, clean up bars) to reduce setup friction and improve consistency.
What it does (under the hood)
Detects FVGs using ICT-minimal (default) or a stricter rule.
Samples volume from a 10× lower timeframe to split participation into Bull % / Bear % (sum = 100%).
Manages each gap through a state machine:
ACTIVE → 50% SQ (midline) → MITIGATED (full) → INVERSED (SR flip after fill).
Auto-clean up keeps only relevant levels, per your rules.
Dashboard (top-right) displays counts by side and the active state tags.
How to use it
First run (show everything)
Use Strict FVG Filter: OFF
Enable Size Filter (percentile): OFF
Mitigation Source: high/low (wick-based) or close (stricter), as you prefer.
Remove on 50% SQ: ON, Delay: 0
Read the context
While ACTIVE, use the Bull%/Bear% meter to gauge demand/supply behind the impulse that created the gap.
Confluence with your HTF structure, sessions, VWAP, OB/FVG, RSI/MACD, etc.
Trade interactions
50% SQ: often the highest-quality interaction; if removal is ON, the box clears = “job done.”
Full mitigation then rejection through the other side → tag changes to INVERSED (acts like SR). Keep for N bars, then auto-remove.
Keep the chart tidy (optional)
If too busy, enable Size Filter or set Nearest per side to 2–4.
Use Lookback (bars) to make behaviour consistent across symbols and histories.
Inputs (key ones)
Use Strict FVG Filter: OFF(default)/ON
Enable Size Filter (percentile): OFF(default)/ON + threshold
Mitigation Source: high/low or close
Remove on 50% SQ + Delay
Inversion window after entry (bars)
Remove inversed after (bars)
Lookback (bars), Nearest per side (N)
Right Extension Bars, Max FVGs, Meter width (bars)
Colours: Bullish, Bearish, Inversed fill
Suggested defaults (per TF)
15m: Extension 50, Max 12, Inversion window 8, Clean up 8, Meter width 20
H1: Extension 25, Max 10, Inversion window 6, Clean up 6, Meter width 15
H4: Extension 15, Max 8, Inversion window 5, Clean up 5, Meter width 10
Notes & edge cases
If a wick hits 50% or the far edge but state doesn’t change, you’re likely on close mode—switch to high/low for wick-based behaviour.
If a gap disappears, it likely met a clean up condition (50% removal, inversion window, inversion clean up, nearest-per-side, lookback, or max-cap).
Meters are hidden after ACTIVE to avoid stale percentages.
Ultimate Oscillator (ULTOSC)The Ultimate Oscillator (ULTOSC) is a technical momentum indicator developed by Larry Williams that combines three different time periods to reduce the volatility and false signals common in single-period oscillators. By using a weighted average of three Stochastic-like calculations across short, medium, and long-term periods, the Ultimate Oscillator provides a more comprehensive view of market momentum while maintaining sensitivity to price changes.
The indicator addresses the common problem of oscillators being either too sensitive (generating many false signals) or too slow (missing opportunities). By incorporating multiple timeframes with decreasing weights for longer periods, ULTOSC attempts to capture both short-term momentum shifts and longer-term trend strength, making it particularly valuable for identifying divergences and potential reversal points.
## Core Concepts
* **Multi-timeframe analysis:** Combines three different periods (typically 7, 14, 28) to capture various momentum cycles
* **Weighted averaging:** Assigns higher weights to shorter periods for responsiveness while including longer periods for stability
* **Buying pressure focus:** Measures the relationship between closing price and the true range rather than just high-low range
* **Divergence detection:** Particularly effective at identifying momentum divergences that precede price reversals
* **Normalized scale:** Oscillates between 0 and 100, with clear overbought/oversold levels
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Fast Period | 7 | Short-term momentum calculation | Lower (5-6) for more sensitivity, higher (9-12) for smoother signals |
| Medium Period | 14 | Medium-term momentum calculation | Adjust based on typical swing duration in the market |
| Slow Period | 28 | Long-term momentum calculation | Higher values (35-42) for longer-term position trading |
| Fast Weight | 4.0 | Weight applied to fast period | Higher weight increases short-term sensitivity |
| Medium Weight | 2.0 | Weight applied to medium period | Adjust to balance medium-term influence |
| Slow Weight | 1.0 | Weight applied to slow period | Usually kept at 1.0 as the baseline weight |
**Pro Tip:** The classic 7/14/28 periods with 4/2/1 weights work well for most markets, but consider using 5/10/20 with adjusted weights for faster markets or 14/28/56 for longer-term analysis.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Ultimate Oscillator calculates three separate "buying pressure" ratios using different time periods, then combines them using weighted averaging. Buying pressure is defined as the close minus the true low, divided by the true range.
**Technical formula:**
```
BP = Close - Min(Low, Previous Close)
TR = Max(High, Previous Close) - Min(Low, Previous Close)
BP_Sum_Fast = Sum(BP, Fast Period)
TR_Sum_Fast = Sum(TR, Fast Period)
Raw_Fast = 100 × (BP_Sum_Fast / TR_Sum_Fast)
BP_Sum_Medium = Sum(BP, Medium Period)
TR_Sum_Medium = Sum(TR, Medium Period)
Raw_Medium = 100 × (BP_Sum_Medium / TR_Sum_Medium)
BP_Sum_Slow = Sum(BP, Slow Period)
TR_Sum_Slow = Sum(TR, Slow Period)
Raw_Slow = 100 × (BP_Sum_Slow / TR_Sum_Slow)
ULTOSC = 100 ×   / (Fast_Weight + Medium_Weight + Slow_Weight)
```
Where:
- BP = Buying Pressure
- TR = True Range
- Fast Period = 7, Medium Period = 14, Slow Period = 28 (defaults)
- Fast Weight = 4, Medium Weight = 2, Slow Weight = 1 (defaults)
> 🔍 **Technical Note:** The implementation uses efficient circular buffers for all three period calculations, maintaining O(1) time complexity per bar. The algorithm properly handles true range calculations including gaps and ensures accurate buying pressure measurements across all timeframes.
## Interpretation Details
ULTOSC provides several analytical perspectives:
* **Overbought/Oversold conditions:** Values above 70 suggest overbought conditions, below 30 suggest oversold conditions
* **Momentum direction:** Rising ULTOSC indicates increasing buying pressure, falling indicates increasing selling pressure
* **Divergence analysis:** Divergences between ULTOSC and price often precede significant reversals
* **Trend confirmation:** ULTOSC direction can confirm or question the prevailing price trend
* **Signal quality:** Extreme readings (>80 or <20) indicate strong momentum that may be unsustainable
* **Multiple timeframe consensus:** When all three underlying periods agree, signals are typically more reliable
## Trading Applications
**Primary Uses:**
- **Divergence trading:** Identify when momentum diverges from price for reversal signals
- **Overbought/oversold identification:** Find potential entry/exit points at extreme levels
- **Trend confirmation:** Validate breakouts and trend continuations
- **Momentum analysis:** Assess the strength of current price movements
**Advanced Strategies:**
- **Multi-divergence confirmation:** Look for divergences across multiple timeframes
- **Momentum breakouts:** Trade when ULTOSC breaks above/below key levels with volume
- **Swing trading entries:** Use oversold/overbought levels for swing position entries
- **Trend strength assessment:** Evaluate trend quality using momentum consistency
## Signal Combinations
**Strong Bullish Signals:**
- ULTOSC rises from oversold territory (<30) with positive price divergence
- ULTOSC breaks above 50 after forming a base near 30
- All three underlying periods show increasing buying pressure
**Strong Bearish Signals:**
- ULTOSC falls from overbought territory (>70) with negative price divergence
- ULTOSC breaks below 50 after forming a top near 70
- All three underlying periods show decreasing buying pressure
**Divergence Signals:**
- **Bullish divergence:** Price makes lower lows while ULTOSC makes higher lows
- **Bearish divergence:** Price makes higher highs while ULTOSC makes lower highs
- **Hidden bullish divergence:** Price makes higher lows while ULTOSC makes lower lows (trend continuation)
- **Hidden bearish divergence:** Price makes lower highs while ULTOSC makes higher highs (trend continuation)
## Comparison with Related Oscillators
| Indicator | Periods | Focus | Best Use Case |
|-----------|---------|-------|---------------|
| **Ultimate Oscillator** | 3 periods | Buying pressure | Divergence detection |
| **Stochastic** | 1-2 periods | Price position | Overbought/oversold |
| **RSI** | 1 period | Price momentum | Momentum analysis |
| **Williams %R** | 1 period | Price position | Short-term signals |
## Advanced Configurations
**Fast Trading Setup:**
- Fast: 5, Medium: 10, Slow: 20
- Weights: 4/2/1, Thresholds: 75/25
**Standard Setup:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 4/2/1, Thresholds: 70/30
**Conservative Setup:**
- Fast: 14, Medium: 28, Slow: 56
- Weights: 3/2/1, Thresholds: 65/35
**Divergence Focused:**
- Fast: 7, Medium: 14, Slow: 28
- Weights: 2/2/2, Thresholds: 70/30
## Market-Specific Adjustments
**Volatile Markets:**
- Use longer periods (10/20/40) to reduce noise
- Consider higher threshold levels (75/25)
- Focus on extreme readings for signal quality
**Trending Markets:**
- Emphasize divergence analysis over absolute levels
- Look for momentum confirmation rather than reversal signals
- Use hidden divergences for trend continuation
**Range-Bound Markets:**
- Standard overbought/oversold levels work well
- Trade reversals from extreme levels
- Combine with support/resistance analysis
## Limitations and Considerations
* **Lagging component:** Contains inherent lag due to multiple moving average calculations
* **Complex calculation:** More computationally intensive than single-period oscillators
* **Parameter sensitivity:** Performance varies significantly with different period/weight combinations
* **Market dependency:** Most effective in trending markets with clear momentum patterns
* **False divergences:** Not all divergences lead to significant price reversals
* **Whipsaw potential:** Can generate conflicting signals in choppy markets
## Best Practices
**Effective Usage:**
- Focus on divergences rather than absolute overbought/oversold levels
- Combine with trend analysis for context
- Use multiple timeframe analysis for confirmation
- Pay attention to the speed of momentum changes
**Common Mistakes:**
- Over-relying on overbought/oversold levels in strong trends
- Ignoring the underlying trend direction
- Using inappropriate period settings for the market being analyzed
- Trading every divergence without additional confirmation
**Signal Enhancement:**
- Combine with volume analysis for confirmation
- Use price action context (support/resistance levels)
- Consider market volatility when setting thresholds
- Look for convergence across multiple momentum indicators
## Historical Context and Development
The Ultimate Oscillator was developed by Larry Williams and introduced in his 1985 article "The Ultimate Oscillator" in Technical Analysis of Stocks and Commodities magazine. Williams designed it to address the limitations of single-period oscillators by:
- Reducing false signals through multi-timeframe analysis
- Maintaining sensitivity to short-term momentum changes
- Providing more reliable divergence signals
- Creating a more robust momentum measurement tool
The indicator has become a standard tool in technical analysis, particularly valued for its divergence detection capabilities and its balanced approach to momentum measurement.
## References
* Williams, L. R. (1985). The Ultimate Oscillator. Technical Analysis of Stocks and Commodities, 3(4).
* Williams, L. R. (1999). Long-Term Secrets to Short-Term Trading. Wiley Trading.
Double Weighted Moving Average (DWMA)# DWMA: Double Weighted Moving Average
## Overview and Purpose
The Double Weighted Moving Average (DWMA) is a technical indicator that applies weighted averaging twice in sequence to create a smoother signal with enhanced noise reduction. Developed in the late 1990s as an evolution of traditional weighted moving averages, the DWMA was created by quantitative analysts seeking enhanced smoothing without the excessive lag typically associated with longer period averages. By applying a weighted moving average calculation to the results of an initial weighted moving average, DWMA achieves more effective filtering while preserving important trend characteristics.
## Core Concepts
* **Cascaded filtering:** DWMA applies weighted averaging twice in sequence for enhanced smoothing and superior noise reduction
* **Linear weighting:** Uses progressively increasing weights for more recent data in both calculation passes
* **Market application:** Particularly effective for trend following strategies where noise reduction is prioritized over rapid signal response
* **Timeframe flexibility:** Works across multiple timeframes but particularly valuable on daily and weekly charts for identifying significant trends
The core innovation of DWMA is its two-stage approach that creates more effective noise filtering while minimizing the additional lag typically associated with longer-period or higher-order filters. This sequential processing creates a more refined output that balances noise reduction and signal preservation better than simply increasing the length of a standard weighted moving average.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period for both WMA calculations | Increase for smoother signals in volatile markets, decrease for more responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For trend following, use a length of 10-14 with DWMA instead of a single WMA with double the period - this provides better smoothing with less lag than simply increasing the period of a standard WMA.
## Calculation and Mathematical Foundation
**Simplified explanation:**
DWMA first calculates a weighted moving average where recent prices have more importance than older prices. Then, it applies the same weighted calculation again to the results of the first calculation, creating a smoother line that reduces market noise more effectively.
**Technical formula:**
```
DWMA is calculated by applying WMA twice:
1. First WMA calculation:
   WMA₁ = (P₁ × w₁ + P₂ × w₂ + ... + Pₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
2. Second WMA calculation applied to WMA₁:
   DWMA = (WMA₁₁ × w₁ + WMA₁₂ × w₂ + ... + WMA₁ₙ × wₙ) / (w₁ + w₂ + ... + wₙ)
```
Where:
- Linear weights: most recent value has weight = n, second most recent has weight = n-1, etc.
- n is the period length
- Sum of weights = n(n+1)/2
**O(1) Optimization - Inline Dual WMA Architecture:**
This implementation uses an advanced O(1) algorithm with two complete inline WMA calculations. Each WMA uses the dual running sums technique:
1. **First WMA (source → wma1)**:
   - Maintains buffer1, sum1, weighted_sum1
   - Recurrence: `W₁_new = W₁_old - S₁_old + (n × P_new)`
   - Cached denominator norm1 after warmup
2. **Second WMA (wma1 → dwma)**:
   - Maintains buffer2, sum2, weighted_sum2
   - Recurrence: `W₂_new = W₂_old - S₂_old + (n × WMA₁_new)`
   - Cached denominator norm2 after warmup
**Implementation details:**
- Both WMAs fully integrated inline (no helper functions)
- Each maintains independent state: buffers, sums, counters, norms
- Both warm up independently from bar 1
- Performance: ~16 operations per bar regardless of period (vs ~10,000 for naive O(n²) implementation)
**Why inline architecture:**
Unlike helper functions, the inline approach makes all state variables and calculations visible in a single scope, eliminating function call overhead and making the dual-pass nature explicit. This is ideal for educational purposes and when debugging complex cascaded filters.
> 🔍 **Technical Note:** The dual-pass O(1) approach creates a filter that effectively increases smoothing without the quadratic increase in computational cost. Original O(n²) implementations required ~10,000 operations for period=100; this optimized version requires only ~16 operations, achieving a 625x speedup while maintaining exact mathematical equivalence.
## Interpretation Details
DWMA can be used in various trading strategies:
* **Trend identification:** The direction of DWMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and DWMA generate trade signals, though they occur later than with single WMA
* **Support/resistance levels:** DWMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and DWMA can indicate trend strength
* **Noise filtering:** Using DWMA to filter noisy price data before applying other indicators
## Limitations and Considerations
* **Market conditions:** Less effective in choppy, sideways markets where its lag becomes a disadvantage
* **Lag factor:** More lag than single WMA due to double calculation process
* **Initialization requirement:** Requires more data points for full calculation, showing more NA values at chart start
* **Short-term trading:** May miss short-term trading opportunities due to increased smoothing
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Jurik, M. "Double Weighted Moving Averages: Theory and Applications in Algorithmic Trading Systems", Jurik Research Papers, 2004
* Ehlers, J.F. "Cycle Analytics for Traders," Wiley, 2013
CCI [Hash Adaptive]Adaptive CCI Pro: Professional Technical Analysis Indicator 
The Commodity Channel Index is a momentum oscillator developed by Donald Lambert in 1980. CCI measures the relationship between an asset's price and its statistical average, identifying cyclical turns and overbought/oversold conditions. The indicator oscillates around zero, with values above +100 indicating overbought conditions and values below -100 suggesting oversold conditions.
Standard CCI Formula: (Typical Price - Moving Average) / (0.015 × Mean Deviation)
This indicator transforms the traditional CCI into a sophisticated visual analysis tool through several key enhancements:
 
 Implements dual exponential moving average smoothing to eliminate market noise
 Preserves signal integrity while reducing false signals
 Adaptive smoothing responds to market volatility conditions
 
 Dynamic Color Visualization System 
 
 Continuous gradient transitions from red (bearish momentum) to green (bullish momentum)
 Real-time color intensity reflects momentum strength
 Eliminates discrete color jumps for fluid visual interpretation
 
 Adaptive Intelligence Features 
 
 Dynamic overbought/oversold thresholds adapt to market conditions
 Reduces false signals during high volatility periods
 Maintains sensitivity during low volatility environments
 
 Momentum Vector Analysis 
 
 Incorporates velocity calculations for early trend identification
 Crossover detection with momentum confirmation
 Advanced signal filtering reduces market noise
 
 Extreme Level Analysis 
 
 Values above +100: Strong overbought conditions, potential reversal zones
 Values below -100: Strong oversold conditions, potential buying opportunities
 Zero-line crossovers: Momentum shift confirmation
 
 Optimization Parameters 
 
 CCI Period (Default: 14)
 Shorter periods (10-12): Increased sensitivity, more signals
 Standard periods (14-20): Balanced responsiveness and reliability
 Longer periods (21-30): Reduced noise, stronger signal confirmation
 
 Smoothing Factor (Default: 5) 
 
 Lower values (1-3): Maximum responsiveness, suitable for scalping
 Medium values (4-6): Balanced approach for swing trading
 Higher values (7-10): Institutional-grade smoothness for position trading
 
 Signal Sensitivity (Default: 6) 
 
 Conservative (7-10): High-probability signals, reduced frequency
 Balanced (5-6): Optimal risk-reward ratio
 Aggressive (1-4): Maximum signal generation, requires additional confirmation
 
 Strategic Implementation 
 
 Oversold reversals in red zones with momentum confirmation
 Zero-line breaks with sustained color transitions
 Extreme readings followed by momentum divergence
 
 Risk Management 
 
 Use extreme levels (+100/-100) for position sizing decisions
 Monitor color intensity for momentum strength assessment
 Combine with price action analysis for comprehensive market view
 
 Market Context Application 
 
 Trending markets: Focus on momentum direction and extreme readings
 Range-bound markets: Utilize overbought/oversold levels for mean reversion
 Volatile markets: Increase smoothing parameters and signal sensitivity
 
 Professional Advantages 
 
 Instantaneous momentum assessment through color visualization
 Reduced cognitive load compared to traditional oscillators
 Professional presentation suitable for client reporting
 
 Adaptive Technology 
 
 Self-adjusting parameters reduce manual optimization requirements
 Consistent performance across varying market conditions
 Advanced mathematics eliminate common CCI limitations
 
The Adaptive CCI Pro represents the evolution of momentum analysis, combining Lambert's foundational CCI concept with modern computational techniques to deliver institutional-grade market intelligence through an intuitive visual interface.
iFVG Strategie by Futures.RobbyiFVG Strategy Checklist by Futures.Robby
Updated: October 27, 2025
Description
This script is a manual checklist designed to help traders evaluate their setups based on the iFVG (Fair Value Gap) strategy. It serves solely as a visual aid and does not perform automatic analysis, signal generation, or trade execution.
How It Works
The script creates an interactive checklist directly on the chart. Traders manually select which criteria are met, and the script calculates a percentage score, displaying it with color coding:
Green (≥ 60%): Good fulfillment of criteria
Orange (40–59%): Partial fulfillment
Red (< 40%): Poor fulfillment
Checklist Criteria
The checklist is divided into two main sections:
1. Trade Criteria (8 Points)
Eight manually selectable criteria to assess setup quality:
Trade im Bias → Trade in Bias: Trade follows the higher timeframe trend (H1/H4/Daily).
BE Level → BE Level: Swing point between entry and target.
Sweep → Sweep: Price hits a key swing before reversing.
Displacement → Displacement: iFVG broken by strong candles.
Leg FVG geschlossen → Leg FVG Closed: No open m1 to m5 FVGs to target.
FVG Reaktion → FVG Reaction: Reaction at FVG during sweep (HTF).
FVG Größe → FVG Size: 6 to 10 points.
Anzahl Kerzen → Number of Candles: Maximum of 6 candles.
2. Goals (1 Point)
Six optional goal conditions, counted together as 1 point:
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
Settings and Customization
The script’s settings are translated as follows:
Group: Trade Criteria
Trade im Bias → Trade in Bias
Tooltip: Trendrichtung folgt HTF (H1/H4/Täglich) – Trend follows HTF direction
BE Level → BE Level
Tooltip: Swingpunkt zwischen Einstieg und Ziel – Swing point between entry and target
Sweep → Sweep
Tooltip: Kurs erreicht markanten Swing – Price hits key swing before inverse
Displacement → Displacement
Tooltip: iFVG durch starke Kerzen gebrochen – iFVG broken by strong candles
Leg FVG geschlossen → Leg FVG Closed
Tooltip: Keine offenen m1 bis m5 FVGs bis Ziel – No open m1 to m5 FVGs to target
FVG Reaktion → FVG Reaction
Tooltip: Reaktion an FVG beim Sweep (HTF) – Reaction at FVG during sweep (HTF)
FVG Größe → FVG Size
Tooltip: 6 bis 10 Punkte – 6 to 10 points
Anzahl Kerzen → Number of Candles
Tooltip: Maximal 6 Kerzen – Maximum of 6 candles
Group: Goals
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
ℹ️ Ziele zählen gemeinsam als 1 Punkt → ℹ️ Goals count together as 1 point
Window Position & Size
Fensterposition → Window Position
oben rechts → top right
oben links → top left
unten rechts → bottom right
unten links → bottom left
Tabellengröße → Table Size
normal → normal
small → small
tiny → tiny
Translation of Chart Table Contents
The table headers and entries on the chart are translated as follows:
Table Headers:
Trade Checkliste → Trade Checklist
Ziele → Goals
Status Symbols:
✅ → ✅ (Fulfilled)
❌ → ❌ (Not fulfilled)
Individual Criteria (Trade Criteria):
Trade im Bias → Trade in Bias
BE Level → BE Level
Sweep → Sweep
Displacement → Displacement
Leg FVG geschlossen → Leg FVG Closed
FVG Reaktion → FVG Reaction
FVG Größe → FVG Size
Anzahl Kerzen → Number of Candles
Individual Criteria (Goals):
Equal H / L → Equal High/Low
Session H / L → Session High/Low
News H / L → News High/Low
HTF Swing Point → HTF Swing Point
HTF OB → HTF Order Block
HTF FVG → HTF FVG
Note Line:
Ziele zählen gemeinsam als 1 Punkt → Goals count together as 1 point
Important Note
This tool is not an automated indicator, but a visual decision aid for traders who want to apply their strategy in a structured and conscious way.
Relative Performance Tracker [QuantAlgo]🟢 Overview 
The  Relative Performance Tracker  is a multi-asset comparison tool designed to monitor and rank up to 30 different tickers simultaneously based on their relative price performance. This indicator enables traders and investors to quickly identify market leaders and laggards across their watchlist, facilitating rotation strategies, strength-based trading decisions, and cross-asset momentum analysis.
  
 🟢 Key Features 
 1. Multi-Asset Monitoring 
 
 Track up to 30 tickers across any market (stocks, crypto, forex, commodities, indices)
  
 Individual enable/disable toggles for each ticker to customize your watchlist
  
 Universal compatibility with any TradingView symbol format (EXCHANGE:TICKER)
 
 2. Ranking Tables (Up to 3 Tables) 
  
 
 Each ticker's percentage change over your chosen lookback period, calculated as:
 (Current Price - Past Price) / Past Price × 100 
 Automatic sorting from strongest to weakest performers 
  
 Rank: Position from 1-30 (1 = strongest performer)
 Ticker: Symbol name with color-coded background (green for gains, red for losses)
 % Change: Exact percentage with color intensity matching magnitude
  For example, Rank #1 has the highest gain among all enabled tickers, Rank #30 has the lowest (or most negative) return.
 
 3. Histogram Visualization 
  
 
 Adjustable bar count: Display anywhere from 1 to 30 top-ranked tickers (user customizable)
 Bar height = magnitude of percentage change.
 Bars extend upward for gains, downward for losses. Taller bars = larger moves.
 Green bars for positive returns, red for negative returns.
 
 4. Customizable Color Schemes 
 
 Classic: Traditional green/red for intuitive interpretation
  
 Aqua: Blue/orange combination for reduced eye strain
  
 Cosmic: Vibrant aqua/purple optimized for dark mode
  
 Custom: Full personalization of positive and negative colors
  
 
 5. Built-In Ranking Alerts 
Six alert conditions detect when rankings change:
 
 Top 1 Changed: New #1 leader emerges
 Top 3/5/10/15/20 Changed: Shifts within those tiers
  
 
 🟢 Practical Applications 
 → Momentum Trading:  Focus on top-ranked assets (Rank 1-10) that show strongest relative strength for trend-following strategies
 → Market Breadth Analysis:  Monitor how many tickers are above vs. below zero on the histogram to gauge overall market health
 → Divergence Spotting:  Identify when previously leading assets lose momentum (drop out of top ranks) as potential trend reversal signals
 → Multi-Timeframe Analysis:  Use different lookback periods on different charts to align short-term and long-term relative strength
 → Customized Focus:  Adjust histogram bars to show only top 5-10 strongest movers for concentrated analysis, or expand to 20-30 for comprehensive overview
4h 相对超跌筛选器 · Webhook v2.0## 指标用途
用于你的「框架第2步」:在**美股 RTH**里,按**4h 收盘**(06:30–10:30 PT 为首根)筛出相对大盘/行业**显著超跌**且结构健康的候选标的,并可**通过 Webhook 自动推送**`symbol + ts`给下游 AI 执行新闻甄别(第3步)与进出场评估(第4步)。
## 工作原理(核心逻辑)
* **结构健康**:最近 80 根 4h 中,收盘 > 4h_SMA50 的占比 ≥ 阈值(默认 55%)。
* **跌深条件**:4h 跌幅 ≤ −4%,且近两根累计(≈8h)≤ −6%。
* **相对劣化**:相对大盘(SPY/QQQ)与相对行业(XLK/XLF/… 或 KWEB/CQQQ)各 ≤ −3%。
* **流动性与价格**:ADV20_USD ≥ 2000 万;价格 ≥ 3 美元。
* **只在 4h 收盘刻评估与触发**,历史点位全部保留,便于回放核验。
* **冷却**:同一标的信号间隔 ≥ N 天(默认 10)。
## 主要输入参数
* **bench / sector**:大盘与行业基准(例:SPY/QQQ,XLK/XLF/XLY;中概用 KWEB/CQQQ)。
* **advMinUSD / priceMin**:20 日美元成交额下限、最小价格。
* **pctAboveTh**:结构健康阈值(%)。
* **drop4hTh / drop8hTh**:4h/8h 跌幅阈值(%)。
* **relMktTh / relSecTh**:相对大盘/行业阈值(%)。
* **coolDays**:冷却天数。
* **fromDate**:仅显示此日期后的历史信号(图表拥挤时可用)。
* **showTable / tableRows**:是否显示右上角“最近信号表”及行数。
## 图表信号
* **S2 绿点**:当根 4h 收盘满足全部筛选条件。
* **右上角表格**:滚动列出最近 N 条命中(`SYMBOL @ yyyy-MM-dd HH:mm`,按图表本地时区)。
## Webhook 联动(生产用)
1. 添加指标 → 🔔 新建警报(Alert):
   * **Condition**:`Any alert() function call`
   * **Options**:`Once per bar close`
   * **Webhook URL**:填你的接收地址(可带 `?token=...`)
   * **Message**:留空(脚本内部 `alert(payload)` 会发送 JSON)。
2. 典型 JSON 载荷(举例):
```json
{
  "event": "step2_signal",
  "symbol": "LULU",
  "symbol_id": "NASDAQ:LULU",
  "venue": "NASDAQ",
  "bench": "SPY",
  "sector": "XLY",
  "ts_bar_close_ms": 1754524200000,
  "ts_bar_close_local": "2025-06-06 10:30",
  "price_close": 318.42,
  "ret_4h_pct": -5.30,
  "ret_8h_pct": -7.45,
  "rel_mkt_pct": -4.90,
  "rel_sec_pct": -3.80
}
```
> 建议以 `symbol + ts_bar_close_ms` 做去重键;接收端先快速 `200 OK`,后续异步处理并交给第3步 AI。
## 使用建议
* **时间框架**:任意周期可用,指标内部统一拉取 240 分钟数据并仅在 4h 收盘刻触发。
* **行业映射**:尽量选与个股业务最贴近的 ETF;中国 ADR 可用 `PGJ/KWEB/CQQQ` 叠加细分行业对照。
* **回放验证**:Bar Replay **不发送真实 Webhook**;仅用于查看历史命中与表格。测试接收端请用 Alert 面板的 **Test**。
## 适配说明
* Pine Script **v5**。
* 不含成分筛查逻辑(请在你的 500–600 只候选池内使用)。
* 数字常量不使用下划线分隔;如需大数可用 `20000000` 或 `2e7`。
## 常见问题
* ⛔️ 报错 `tostring(...)`:Pine 无时间格式化重载,脚本已内置 `timeToStr()`。
* ⛔️ `syminfo.exchange` 不存在:已改用 `syminfo.prefix`(交易所前缀)。
* ⛔️ 多行字符串拼接报 `line continuation`:本脚本已用括号包裹或 `str.format` 规避。
## 免责声明
该指标仅供筛选与研究使用,不构成投资建议。请结合你的第3步新闻/基本面甄别与第4步执行规则共同决策。
Scalper Pro Pattern Recognition & Price ActionOVERVIEW
Scalper Pro is a comprehensive multi-timeframe trading indicator that combines Smart Money Concepts (SMC) with traditional technical analysis to provide scalpers and day traders with high-probability entry and exit signals. This indicator integrates multiple analytical frameworks into a unified visual system designed specifically for short-term trading strategies.
ORIGINALITY & PURPOSE
What Makes This Script Original
This script is not a simple mashup of existing indicators. Instead, it represents a carefully orchestrated integration of complementary analytical methods that work together to solve a specific problem: identifying high-probability scalping opportunities in volatile markets.
The unique value proposition:
Adaptive Trend Filtering System - Combines a customized SuperTrend algorithm with dual-period range filters (Cirrus Cloud) and Hull Moving Average trend cloud to create a three-layer trend confirmation system
Smart Money Concepts Integration - Incorporates institutional trading concepts (Order Blocks, Fair Value Gaps, Break of Structure) with retail technical indicators for a complete market structure view
Dynamic Risk Management - Automatically calculates stop-loss and take-profit levels based on ATR volatility, providing objective position sizing
ADX-Based Market Regime Detection - Identifies ranging vs. trending markets through ADX analysis with visual bar coloring to prevent whipsaws during consolidation
Why Combine These Specific Components
Each component addresses a specific weakness in scalping:
SuperTrend provides the primary directional bias but can generate false signals in ranging markets
Range Filters smooth out noise and confirm trend direction, reducing SuperTrend false positives
ADX Analysis prevents trading during low-volatility consolidation when most indicators fail
SMC Elements identify institutional activity zones where price is likely to react strongly
ATR-Based Risk Management adapts position sizing to current volatility conditions
The synergy creates a system where signals are only generated when multiple confirmation layers align, significantly reducing false signals common in single-indicator approaches.
HOW IT WORKS
Core Calculation Methodology
1. SuperTrend Signal Generation
The script uses a modified SuperTrend algorithm with the following calculation:
ATR = Average True Range (default: 10 periods)
Factor = 7 (default sensitivity multiplier)
Upper Band = Source + (Factor × ATR)
Lower Band = Source - (Factor × ATR)
Directional Logic:
When price crosses above SuperTrend → Bullish signal
When price crosses below SuperTrend → Bearish signal
SuperTrend value is plotted as dynamic support/resistance
Key Modification: The sensitivity parameter (nsensitivity * 7) allows users to adjust the aggressiveness of trend detection without changing the core ATR calculation.
2. Range Filter System (Cirrus Cloud)
The Range Filter uses a smoothed range calculation to filter out market noise:
Smooth Range Calculation:
WPER = (Period × 2) - 1
AVRNG = EMA(|Price - Price |, Period)
Smooth Range = EMA(AVRNG, WPER) × Multiplier
Two-Layer System:
Layer 1: 22-period with 6x multiplier (broader trend)
Layer 2: 15-period with 5x multiplier (tighter price action)
Visual Output: The space between these two filters is colored:
Green fill = Bullish trend (Layer 1 > Layer 2)
Red fill = Bearish trend (Layer 1 < Layer 2)
This creates a "cloud" that expands during strong trends and contracts during consolidation.
3. ADX Market Regime Detection
Calculation:
+DM = Positive Directional Movement
-DM = Negative Directional Movement
True Range = RMA of True Range (15 periods)
+DI = 100 × RMA(+DM, 15) / True Range
-DI = 100 × RMA(-DM, 15) / True Range
ADX = 100 × RMA(|+DI - -DI| / (+DI + -DI), 15)
Threshold System:
ADX < Threshold (default 15) = Ranging market → Bar color changes to purple
ADX > Threshold = Trending market → Normal bar coloring applies
Purpose: This prevents taking trend-following signals during sideways markets where most indicators produce whipsaws.
4. Smart Money Concepts (SMC) Integration
Order Blocks (OB):
Identified using swing high/low detection with customizable pivot length
Bullish OB: Last down-close candle before bullish Break of Structure (BOS)
Bearish OB: Last up-close candle before bearish BOS
Extended forward until price breaks through them
Fair Value Gaps (FVG):
Detected when a three-candle gap exists:
Bullish FVG: Low  > High 
Bearish FVG: High  < Low 
Filtered by price delta percentage to ensure significant gaps
Displayed as boxes that delete when price fills the gap
Break of Structure (BOS) vs. Change of Character (CHoCH):
BOS = Price breaks the previous structural high/low in the current trend direction
CHoCH = Price breaks structure in the opposite direction (potential trend reversal)
Both internal (minor) and swing (major) structures are tracked
Equal Highs/Lows (EQH/EQL):
Detected when consecutive swing highs/lows are within ATR threshold
Often indicates liquidity pools that price may sweep before reversing
5. ATR-Based Risk Management
Calculation:
ATR Band = ATR(14) × Risk Multiplier (default 3%)
Stop Loss = Entry - ATR Band (for longs) or Entry + ATR Band (for shorts)
Take Profit Levels:
TP1 = Entry + (Entry - Stop Loss) × 1
TP2 = Entry + (Entry - Stop Loss) × 2
TP3 = Entry + (Entry - Stop Loss) × 3
Dynamic Labels: Stop loss and take profit levels are automatically calculated and displayed as labels on the chart when new signals trigger.
6. Hull Moving Average Trend Cloud
HMA = WMA(2 × WMA(Close, Period/2) - WMA(Close, Period), sqrt(Period))
Period = 600 bars (long-term trend)
The HMA provides a smoothed long-term trend reference that's more responsive than traditional moving averages while filtering out short-term noise.
HOW TO USE THE INDICATOR
Entry Signals
Primary Buy Signal:
SuperTrend changes to green (price crosses above)
ADX shows market is NOT ranging (bars are NOT purple)
Price is within or near a bullish Order Block OR bullish FVG
Cirrus Cloud shows green fill (Layer 1 > Layer 2)
Primary Sell Signal:
SuperTrend changes to red (price crosses below)
ADX shows market is NOT ranging
Price is within or near a bearish Order Block OR bearish FVG
Cirrus Cloud shows red fill (Layer 1 < Layer 2)
Confirmation Layers
Higher Probability Trades Include:
Bullish/Bearish BOS in the same direction as signal
Equal highs/lows being swept before entry
Price respecting premium/discount zones (above/below equilibrium)
Multiple timeframe alignment (use MTF settings)
Exit Strategy
The indicator provides three take-profit levels:
TP1: Conservative target (1:1 risk-reward)
TP2: Moderate target (2:1 risk-reward)
TP3: Aggressive target (3:1 risk-reward)
Suggested Exit Approach:
Close 1/3 position at TP1
Move stop to breakeven
Close 1/3 position at TP2
Trail remaining position or exit at TP3
Risk Management
Stop Loss:
Use the ATR-based stop loss level displayed on chart
Alternatively, use percentage-based stop (adjustable in settings)
Never risk more than 1-2% of account per trade
Position Sizing:
Position Size = (Account Risk $) / (Entry Price - Stop Loss Price)
CUSTOMIZABLE SETTINGS
Core Parameters
Buy/Sell Signals:
Toggle signals on/off
Adjust SuperTrend sensitivity (0.5 - 2.0)
Risk Management:
Show/hide TP/SL levels
ATR period (default: 14)
Risk percentage (default: 3%)
Number of decimal places for price labels
Trend Features:
Cirrus Cloud display toggle
Range filter periods (x1, x2, x3, x4)
Hull MA length for trend cloud
Smart Money Concepts:
Order Block settings (swing length, display count)
Fair Value Gap parameters (auto-threshold, extend length)
Structure detection (internal vs swing)
EQH/EQL threshold
ADX Settings:
ADX length (default: 15)
Sideways threshold (10-30, default: 15)
Bar color toggle
Display Options:
Previous day/week/month high/low levels
Premium/Discount/Equilibrium zones
Trend candle coloring (colored or monochrome)
BEST PRACTICES & TRADING TIPS
Optimal Use Cases
Scalping on lower timeframes (1m, 5m, 15m)
Rapid entry/exit with clear TP levels
ADX filter prevents choppy market entries
Day trading on medium timeframes (30m, 1H)
Stronger trend confirmation
Better risk-reward ratios
Swing trading entries on higher timeframes (4H, Daily)
Higher-probability structural setups
Larger ATR-based stops accommodate volatility
Market Conditions
Best Performance:
Trending markets with clear directional bias
Post-news volatility with defined structure
Markets respecting support/resistance levels
Avoid Trading When:
ADX indicator shows purple bars (ranging market)
Multiple conflicting signals across timeframes
Major news events without clear price structure
Low volume periods (market open/close)
Common Mistakes to Avoid
Ignoring the ADX filter - Taking signals during ranging markets leads to whipsaws
Not waiting for confirmation - Enter only when multiple layers align
Overtrading - Fewer high-quality setups outperform many mediocre ones
Ignoring risk management - Always use the calculated stop losses
Fighting the trend - Trade WITH the SuperTrend and Cirrus Cloud direction
TECHNICAL SPECIFICATIONS
Indicator Type: Overlay (plots on price chart)
Calculation Resources:
Max labels: 500
Max lines: 500
Max boxes: 500
Max bars back: 500
Pine Script Version: 5
Compatible Timeframes: All timeframes (optimized for 1m to 1D)
Compatible Instruments:
Forex pairs
Crypto assets
Stock indices
Individual stocks
Commodities
THEORETICAL FOUNDATION
Trend-Following Concepts
This indicator is based on the principle that markets trend more often than they range, and that trends tend to persist. The SuperTrend component captures this momentum while the range filters prevent premature entries during pullbacks.
Smart Money Theory
The SMC elements are based on the concept that institutional traders (banks, hedge funds) leave footprints in the form of:
Order Blocks: Areas where large orders were placed
Fair Value Gaps: Inefficient price movements that may be revisited
Liquidity Sweeps: Stop hunts before continuation (EQH/EQL)
Volatility-Based Position Sizing
Using ATR for stop-loss placement ensures that stop distances adapt to current market conditions:
Tight stops in low volatility (avoids excessive risk)
Wider stops in high volatility (avoids premature stop-outs)
PERFORMANCE EXPECTATIONS
Realistic Expectations
Win Rate:
Expected: 45-55% (trend-following systems rarely exceed 60%)
Higher win rates on trending days
Lower win rates during consolidation (even with ADX filter)
Risk-Reward Ratio:
Target: 1.5:1 minimum (TP2)
Achievable: 2:1 to 3:1 on strong trends
Drawdowns:
Normal: 10-15% of account during choppy periods
Maximum: Should not exceed 20% with proper risk management
Optimization Tips
Backtesting Recommendations:
Test on at least 1 year of historical data
Include different market conditions (trending, ranging, volatile)
Adjust SuperTrend sensitivity per instrument
Optimize ADX threshold for your specific market
Record trades to identify personal execution errors
FREQUENTLY ASKED QUESTIONS
Q: Can I use this for automated trading?
A: The indicator provides signals, but you'll need to code a strategy script separately for automation. The signals can trigger alerts that connect to trading bots.
Q: Why do I see conflicting signals?
A: This is normal during transition periods. Wait for all confirmation layers to align before entering.
Q: How often should I expect signals?
A: Depends on timeframe and market conditions. On 5m charts during trending markets: 3-7 quality setups per session.
Q: Can I use only some features?
A: Yes, all components can be toggled on/off. However, the system works best with all confirmations active.
Q: What's the difference between internal and swing structures?
A: Internal = minor price structures (smaller pivots). Swing = major price structures (larger pivots). Both provide different levels of confirmation.
DISCLAIMER
This indicator is a tool for technical analysis and should not be the sole basis for trading decisions. Past performance does not guarantee future results. Always:
Use proper risk management
Test on demo accounts first
Never risk more than you can afford to lose
Combine with fundamental analysis when applicable
Understand that no indicator is 100% accurate
License: Mozilla Public License 2.0
Author: DrFXGOD
VERSION HISTORY & UPDATES
Initial Release - Version 1.0
Integrated SuperTrend, Range Filters, ADX, SMC concepts
ATR-based risk management
Multi-timeframe support
Customizable visual elements
SUPPORT & DOCUMENTATION
For questions, suggestions, or bug reports, please comment on the script page or contact the author through TradingView.
Additional Resources:
Smart Money Concepts: Research ICT (Inner Circle Trader) materials
ATR and Volatility: Refer to Wilder's original ATR documentation
SuperTrend Indicator: Study original SuperTrend strategy papers
MACD-V Adaptive FluxProMACD-V Adaptive FluxPro
Type: Multi-Factor Volatility-Normalized Momentum & Regime Framework
Overlay: ✅ Yes (on price chart)
Purpose: Detect high-probability trend continuation or reversal zones through volatility-adjusted momentum, VWAP structure, and adaptive filters.
🧩 Concept Overview
MACD-V Adaptive FluxPro is a next-generation, multi-factor analytical framework that merges the principles of Linda Raschke’s 3-10-16 MACD with modern volatility normalization and adaptive filtering.
Instead of generating raw buy/sell signals, it builds a probability-driven environment model — showing when price action, volatility, and structure align for high-confidence trades.
The “V” in MACD-V stands for Volatility Normalization: every MACD component is divided by ATR to stabilize amplitude across fast or slow markets.
This enables the indicator to remain consistent across timeframes, instruments, and volatility regimes.
⚙️ Core Components
1️⃣ Volatility-Normalized MACD (MACD-V)
A traditional MACD built on Linda Raschke’s 3-10-16 structure, but adjusted by ATR to create a volatility-invariant momentum profile.
You can toggle to alternative presets (Scalp / Swing / Trend) for faster or slower environments.
2️⃣ Dynamic Regime Detection
A slope-based classifier that identifies whether the market is:
Trend Up 🟢
Trend Down 🔴
Compression / Squeeze 🟧
Transition / Neutral ⚫
The background color updates dynamically as momentum, volatility, and slope shift between these states.
3️⃣ VWAP Structure Bands
Adaptive VWAP with inner and outer ATR-scaled envelopes.
These act as short-term mean-reversion and breakout zones.
The indicator can optionally gate entries to occur only within defined VWAP proximity.
4️⃣ EMAs for Micro-Trend Confirmation
Includes 9-EMA and 21-EMA, color-configurable for visual crossovers and short-term momentum bias.
5️⃣ Multi-Timeframe Confirmation Tiles
Top-center dashboard tiles display directional bias from higher timeframes (e.g., 15m / 1h / 4h).
When all align, it confirms multi-frame trend coherence.
6️⃣ Adaptive Probability Engine
All subsystems — MACD-V, slope, compression, volume z-score, and VWAP distance — feed into a logistic scoring model that outputs a real-time AOI Probability (0-100%).
When conditions align, probabilities rise above 60% (long bias) or drop below 40% (short bias).
These are your high-probability “Areas of Interest.”
7️⃣ Dashboard HUD
The top-right status console provides a one-glance view of system state:
Field	Meaning
AOI Prob Long	Real-time probability of bullish bias
Regime	Market state (Trend, Transition, Compression)
Risk Gate	ATR-based volatility filter
News Mute	Manual toggle for event-risk suppression
ATR (≈ risk)	Real-time volatility readout
Status	✅ Trading OK / 🧱 Risk Gate / 🔇 News Mute / 🟧 Compression
🎯 Interpretation Guide
Visual	Meaning
🟢 Green background	Confirmed uptrend regime
🔴 Red background	Confirmed downtrend regime
🟧 Orange background	Volatility compression (squeeze forming)
⚫ Gray background	Transitional / indecisive structure
Teal % (AOI Prob Long)	Bullish probability > 60%
Arrows	Optional: appear only when all gates align (rare, filtered signals)
🧮 Mathematical Notes
MACD-V = (EMA_fast(src) − EMA_slow(src)) / ATR(n)
Normalized score is smoothed, scaled 0–100 via logistic curve
Slope = Δ(EMA(src, n)) / ATR(n)
Probabilities gated by:
Minimum slope magnitude (minAbsSlope)
VWAP proximity (maxVWAPDistATR)
Multi-TF agreement
Cooldown interval (cooldownBars)
ATR-based risk gate
No repainting — all calculations use barstate.isconfirmed.
⚡ Use Cases
✅ Identify trend regime changes before major expansions
✅ Filter breakout vs. compression setups
✅ Quantify volatility conditions before entries
✅ Confirm multi-timeframe alignment
✅ Serve as a visual regime map for automated systems or discretionary traders
🧠 Recommended Presets
Market Type	Setting Preset	Behavior
Index Futures (ES/NQ)	LBR 3-10-16 SMA (default)	Classic swing/momentum balance
Scalping (1m–5m)	Fast Adaptive	Higher frequency, shorter cooldown
Swing Trading (1h–4h)	Smooth ATR	Broader, trend-only signals
Trend-Following Futures	Wide ATR Bands	Filters noise, favors strong continuation
⚠️ Notes
Non-repainting, bar-confirmed calculations
Signal arrows are optional and rare — intended for precision setups
ATR and slope thresholds should be tuned per instrument
Compatible with all TradingView markets and resolutions
🏁 Summary
“MACD-V Adaptive FluxPro” is not a simple MACD — it’s a volatility-normalized market state engine that adapts to changing conditions.
It fuses Linda Raschke’s timeless MACD logic with modern volatility, slope, and multi-timeframe analytics — giving you a live market dashboard that tells you when not to trade just as clearly as when you should.
Experimental Supertrend [CHE]Experimental Supertrend   — Combines EMA crossovers for trend regime detection with an adaptive ATR-based hull that selects the narrowest band to contain recent highs and lows, minimizing false breaks in varying volatility.
  Summary 
This indicator overlays a dynamic supertrend boundary around a midline derived from dual EMAs, using EMA crossovers to switch between bullish and bearish regimes. The hull adapts by evaluating multiple ATR periods and selecting the tightest one that fully encloses price action over a specified window, which helps in creating more stable trend lines that hug price without excessive gaps or breaches. Fills between the midline and hull provide visual cues for trend strength, darkening temporarily after regime changes to highlight transitions. Alerts trigger on crossovers, and markers label entry points, making it suitable for trend-following setups where standard supertrends might whipsaw. Overall, it offers robustness through auto-adjustment, reducing sensitivity to noise while maintaining responsiveness to genuine shifts.
  Motivation: Why this design? 
Standard supertrend indicators often flip prematurely in choppy markets due to fixed multipliers that do not account for localized volatility patterns, leading to frequent false signals and eroded confidence in trends. This design addresses that by incorporating an EMA-based regime filter for directional bias and an auto-adaptive hull that dynamically tunes the band width based on recent price containment needs. By prioritizing the narrowest effective enclosure, it avoids over-wide bands in calm periods that cause lag or under-wide ones in volatility spikes that invite breaks, providing a more consistent trailing reference without manual tweaking.
  What’s different vs. standard approaches? 
- Reference baseline: Diverges from the classic ATR-multiplier supertrend, which uses a single fixed period and constant factor applied to close or high/low deviations.
- Architecture differences:
  - Auto-selection from candidate ATR lengths to find the optimal period for current conditions.
  - Dynamic multiplier clamped between floor and cap values, adjusted by padding to ensure reliable containment.
  - Regime-gated rendering, where hull position flips based on EMA relative positioning.
  - Post-transition visual fading to emphasize change points without altering core logic.
- Practical effect: Charts show tighter, more reactive bands that rarely breach during trends, reducing visual clutter from flips; the adaptive nature means less intervention across assets, as the hull self-adjusts to volatility clusters rather than applying a one-size-fits-all scale.
  How it works (technical) 
The indicator first computes two EMAs from close prices using lengths derived from a preset pair or manual inputs, establishing a midline as their average. This midline serves as the central reference for the hull. True range values are then smoothed into multiple ATR candidates using exponential weighting over the specified lengths. For each candidate, deviations of recent highs and lows from the midline are ratioed against the ATR to determine a required multiplier that would enclose all extremes in the containment window—the highest ratio plus padding sets the base, clamped to user-defined bounds. Among valid candidates (those with sufficient history), the one yielding the narrowest overall band width is selected. The hull boundaries are then offset from the midline by this multiplier times the chosen ATR, and further smoothed with a fixed EMA to reduce jitter. Regime direction from EMA comparison gates which boundary acts as support or resistance, with initialization seeding arrays on the first bar to handle state persistence. No higher timeframe data is used, so all logic runs on the chart's native bars without lookahead.
  Parameter Guide 
EMA Pair — Selects preset lengths for fast and slow EMAs, influencing regime sensitivity and midline stability. Default: "21/55". Trade-offs/Tips: Faster pairs like "9/21" increase cross frequency for scalping but raise false signals; slower like "50/200" smooths for swings, potentially missing early turns. Use Manual for fine control.
Manual Fast — Sets fast EMA length when Manual mode is active; shorter values make regime switches quicker. Default: 21. Trade-offs/Tips: Lower than 10 risks over-reactivity; pair with slow at least double for clear separation.
Manual Slow — Sets slow EMA length when Manual mode is active; longer values anchor the midline more firmly. Default: 55. Trade-offs/Tips: Above 100 adds lag in trends; balance with fast to avoid perpetual neutrality.
ATR Lengths (comma-separated) — Defines candidate periods for ATR smoothing; more options allow finer auto-selection. Default: "7,10,14,21,28,35". Trade-offs/Tips: Fewer candidates speed computation but may miss optimal fits; keep under 10 for efficiency.
Containment Window — Number of recent bars the hull must fully enclose highs/lows of; larger windows favor stability. Default: 50. Trade-offs/Tips: Shorter (under 20) adapts faster to breaks but increases breach risk; longer smooths but delays response.
Min Multiplier Floor — Lowest allowed multiplier for hull width; prevents overly tight bands in low volatility. Default: 0.5. Trade-offs/Tips: Raise to 0.75 for conservative enclosures; too low allows pinches that flip easily.
Max Multiplier Cap — Highest allowed multiplier; caps expansion in spikes to avoid wide, lagging bands. Default: 1.0. Trade-offs/Tips: Lower to 0.75 tightens overall; higher permits more room but risks detachment from price.
Padding (+) — Adds buffer to the auto-multiplier for safer containment without exact touches. Default: 0.05. Trade-offs/Tips: Increase to 0.10 in gappy markets; minimal values hug closer but may still breach on outliers.
Fill Between (Mid ↔ Supertrend) — Toggles shaded area between midline and active hull for trend visualization. Default: true. Trade-offs/Tips: Disable for cleaner charts; pairs well with transparency tweaks.
Base Fill Transparency (0..100) — Sets default opacity of fills; higher values make them subtler. Default: 80. Trade-offs/Tips: Under 50 overwhelms price action; adjust with darken boost for emphasis.
Darken on Trend Change — Enables temporary opacity increase after regime shifts to spotlight transitions. Default: true. Trade-offs/Tips: Off for steady visuals; on aids spotting reversals in real-time.
Darken Fade Bars — Duration in bars for the darken effect to ramp back to base; longer prolongs highlight. Default: 8. Trade-offs/Tips: Shorter (4-6) for fast-paced charts; longer holds attention on changes.
Darken Boost at Change (Δ transp) — Intensity of opacity reduction at crossover; higher values make shifts more prominent. Default: 50. Trade-offs/Tips: Cap at 70 to avoid blackout; tune down if fades obscure details.
Show Supertrend Line — Displays the active hull boundary as a line. Default: true. Trade-offs/Tips: Hide for fill-only views; linewidth fixed at 3 for visibility.
Show EMA Cross Markers — Places circles and labels at crossover points for entry cues. Default: true. Trade-offs/Tips: Disable in clutter; labels show "Buy"/"Sell" at absolute positions.
Alert: EMA Cross Up (Long) — Triggers notification on bullish crossover. Default: true. Trade-offs/Tips: Pair with filters; once-per-bar frequency.
Alert: EMA Cross Down (Short) — Triggers notification on bearish crossover. Default: true. Trade-offs/Tips: Use for exits; ensure broker integration.
Show Debug — Reveals internal diagnostics like selected ATR details (if implemented). Default: false. Trade-offs/Tips: Enable for troubleshooting selections; minimal overhead.
  Reading & Interpretation 
Bullish regime shows a green line below price as support, with upward fill from midline; bearish uses red line above as resistance, downward fill. Crossovers flip the active boundary, marked by tiny green/red circles and "Buy"/"Sell" labels at the hull level. Fills start at base transparency but darken sharply at changes, fading over the specified bars to signal fresh momentum. If the hull rarely breaches during trends, containment is effective; frequent touches without flips indicate tight adaptation. Debug mode (when enabled) overlays text or plots for selected length and multiplier, helping verify auto-choices.
  Practical Workflows & Combinations 
- Trend following: Enter long on green "Buy" label above prior low structure; confirm with higher high. Trail stops along the green hull line, tightening as fills stabilize post-fade.
- Exits/Stops: Conservative exit on opposite crossover or hull breach; aggressive hold until fade completes if volume supports. Use darken boost as a volatility cue—high delta suggests waiting for confirmation.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 15m-4h; for crypto, widen containment to 75 for gaps. Layer on volume oscillator for cross filters; avoid on low-liquidity assets where ATR candidates skew.
  Behavior, Constraints & Performance 
Closed-bar logic ensures signals confirm at bar end, with live bars updating hull adaptively but no repaints since no future data or security calls are used. Arrays persist ATR states across bars, initialized once with candidates parsed from string. Small fixed loops (over 6 lengths max, inner up to 50) run per bar, capped by max_bars_back=500 for history needs. Resources stay low with 500 labels/lines limits, but dense charts may hit on markers. Known limits include initial lag until containment history builds (50+ bars), potential wide bands on gaps, and suboptimal selections if candidates omit ideal lengths.
  Sensible Defaults & Quick Tuning 
Start with "21/55" pair, 50-window, 0.5-1.0 multipliers, and 80% transparency for balanced responsiveness on daily charts. For too many flips, raise min floor to 0.75 or add lengths like "42"; for sluggishness, shorten window to 30 or pick faster pair. In high-vol environments, boost padding to 0.10; for smoother visuals, extend fade bars to 12.
  What this indicator is—and isn’t 
This is a visualization and signal layer for trend regime and adaptive boundaries, aiding entry/exit timing in directional markets. It is not a standalone system—pair with price structure, risk sizing, and broader context. Not predictive of turns, just reactive to containment and crosses.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Happy trading
Chervolino
Smart Structure Pro - Market Structure & Smart Money Concepts═══════════════════════════════════════════════════════════════════════════════
SMART STRUCTURE PRO
═══════════════════════════════════════════════════════════════════════════════
A comprehensive market structure analysis tool that identifies institutional trading 
patterns and smart money concepts for improved trade timing and decision-making.
═══════════════════════════════════════════════════════════════════════════════
📊 WHAT IT DOES
═══════════════════════════════════════════════════════════════════════════════
This indicator automatically detects and visualizes key market structure elements:
🔹 BOS (Break of Structure)
   - Identifies trend continuation patterns
   - Marks when price breaks above previous highs (bullish) or below previous lows (bearish)
   - Confirms trend strength and momentum
🔹 CHoCH (Change of Character)  
   - Detects potential trend reversals
   - Alerts when market structure shifts from bullish to bearish or vice versa
   - Helps identify early reversal opportunities
🔹 Order Blocks
   - Highlights institutional entry zones
   - Identifies the last opposite candle before a structure break
   - Shows areas where smart money likely entered positions
🔹 Fair Value Gaps (FVG)
   - Detects price imbalances and inefficiencies
   - Shows areas where price moved rapidly leaving gaps
   - Often act as support/resistance when retested
🔹 Liquidity Zones
   - Marks swing high and low levels
   - Identifies areas where stop losses likely cluster
   - Shows potential stop hunt and liquidity grab zones
═══════════════════════════════════════════════════════════════════════════════
🎯 HOW TO USE
═══════════════════════════════════════════════════════════════════════════════
BULLISH SETUP:
1. Wait for Bullish CHoCH (trend reversal signal) or BOS ↑ (continuation)
2. Look for price to pull back into an Order Block or Fair Value Gap
3. Enter long when price bounces from these zones
4. Place stop loss below the Order Block
5. Target the next liquidity zone or resistance level
BEARISH SETUP:
1. Wait for Bearish CHoCH (trend reversal signal) or BOS ↓ (continuation)
2. Look for price to retrace into an Order Block or Fair Value Gap
3. Enter short when price rejects from these zones
4. Place stop loss above the Order Block
5. Target the next liquidity zone or support level
DASHBOARD INTERPRETATION:
• Trend: Current market direction (Bullish/Bearish)
• Volume: Confirmation strength (High volume = stronger signals)
• Signal: Latest structure break detected
• Key High/Low: Critical levels for the current trend
• Position: Price location (Premium = expensive, Discount = cheap)
═══════════════════════════════════════════════════════════════════════════════
⚙️ SETTINGS GUIDE
═══════════════════════════════════════════════════════════════════════════════
STRUCTURE DETECTION:
• Pivot Length (Default: 10)
  - Lower values = More signals but potentially weaker
  - Higher values = Fewer signals but stronger/more reliable
  - Recommended: 8-12 for intraday, 10-15 for higher timeframes
• Structure Line Extension
  - Visual preference for how far lines extend
  - Does not affect signal detection
SMART MONEY CONCEPTS:
• Order Block Extension: How long OB boxes remain visible
• FVG Extension: How long gap boxes remain visible  
• Min FVG Size: Filter out small gaps (0 = show all)
  - Set to 10-20% to reduce noise
  - Set to 0 to see all gaps
VOLUME FILTER:
• Volume Confirmation (Recommended: ON)
  - Filters weak signals without volume support
  - Reduces false breakouts
  
• Volume Multiplier (Default: 1.5)
  - Higher = Stricter filtering (fewer but stronger signals)
  - Lower = More signals (but may include weak ones)
DISPLAY:
• Dashboard: Toggle information panel
• Trend Background: Subtle color tint showing current trend
• Dashboard Position: Choose corner placement
═══════════════════════════════════════════════════════════════════════════════
🔔 ALERTS
═══════════════════════════════════════════════════════════════════════════════
Available alert conditions:
✓ Bullish BOS - Uptrend continuation confirmed
✓ Bearish BOS - Downtrend continuation confirmed  
✓ Bullish CHoCH - Reversal to uptrend detected
✓ Bearish CHoCH - Reversal to downtrend detected
✓ Structure Break - Any significant market structure change
To set up alerts:
1. Click the "⏰" alert icon
2. Select "Smart Structure Pro"
3. Choose your desired condition
4. Configure notification method
5. Click "Create"
═══════════════════════════════════════════════════════════════════════════════
⚠️ IMPORTANT DISCLOSURES
═══════════════════════════════════════════════════════════════════════════════
REPAINTING BEHAVIOR:
• Pivot points WILL repaint until confirmed (this is by design and unavoidable)
• Structure breaks (BOS/CHoCH) use CLOSED candles and do NOT repaint after confirmation
• Order Blocks and FVGs are drawn on confirmed signals and do NOT repaint
• All signals wait for candle close before triggering
BEST PRACTICES:
• Use on higher timeframes (15min+) for more reliable signals
• Combine with other analysis (support/resistance, volume profile, etc.)
• Wait for candle close confirmation before acting on signals
• Use proper risk management - this is not a standalone trading system
• Backtest on your preferred instrument and timeframe
PERFORMANCE:
• Limited to 100 boxes, 100 lines, 100 labels for optimal performance
• Older objects automatically removed as new ones appear
• Works on all markets (Forex, Crypto, Stocks, Indices, Commodities)
═══════════════════════════════════════════════════════════════════════════════
📚 CONCEPTS EXPLAINED
═══════════════════════════════════════════════════════════════════════════════
MARKET STRUCTURE:
Market structure refers to the pattern of price movements creating swing highs 
and lows. Understanding structure helps identify trend direction and potential 
reversal points.
SMART MONEY CONCEPTS:
These are trading techniques based on tracking institutional order flow and 
understanding where large players (banks, funds, institutions) enter and exit 
positions.
ORDER BLOCKS:
The last opposing candle before a strong directional move. Institutions often 
leave unfilled orders in these zones, which can act as support/resistance when 
price returns.
FAIR VALUE GAPS:
Areas where price moved so quickly that it left an imbalance. These gaps often 
get "filled" as price returns to find equilibrium, creating trading opportunities.
═══════════════════════════════════════════════════════════════════════════════
🎓 EDUCATIONAL VALUE
═══════════════════════════════════════════════════════════════════════════════
This indicator helps traders:
✓ Understand market structure mechanics
✓ Identify institutional trading patterns  
✓ Improve trade timing and entry precision
✓ Recognize trend continuation vs reversal
✓ Learn smart money concepts through visualization
═══════════════════════════════════════════════════════════════════════════════
📋 TECHNICAL DETAILS
═══════════════════════════════════════════════════════════════════════════════
• Version: 1.0.0
• Pine Script Version: 5
• Indicator Type: Overlay
• No Repainting: Structure breaks use confirmed candles
• Performance Optimized: Limited drawing objects
• Works On: All markets and timeframes
• Alerts: Yes, fully customizable
═══════════════════════════════════════════════════════════════════════════════
👤 AUTHOR
═══════════════════════════════════════════════════════════════════════════════
Created by: Zakaria Safri
Original Work: All code and concepts are original implementations
Based On: ICT (Inner Circle Trader) educational concepts
License: © 2024 Zakaria Safri - Personal Use Only
═══════════════════════════════════════════════════════════════════════════════
⚖️ DISCLAIMER
═══════════════════════════════════════════════════════════════════════════════
This indicator is for educational and informational purposes only. It does not 
constitute financial advice. Trading involves substantial risk of loss. Past 
performance does not guarantee future results. Always conduct your own research 
and consult with a licensed financial advisor before making trading decisions.
The author is not responsible for any losses incurred from using this indicator.
═══════════════════════════════════════════════════════════════════════════════
If you find this indicator helpful, please:
👍 Like and favorite
⭐ Leave a review  
📢 Share with other traders
💬 Comment with feedback or suggestions
Happy Trading! 📈
nadia
Gold ramon strategy based on 50 candles and atr of 12
You enter the maximum of 50 candles once the most bearish starts to rise, we expect 10 candles, if you don't go up in 10 candles, you don't enter, if you go up before 10 candles, you enter.
When is TP? Enough with 5 candles
The temporality is 1 hour. It can be adjusted to 1 minute temporality for scalping.
It is never lost, because it always exceeds the previous maximums.
Daily Levels: PD / PM / OR (RTH/Pre)# Daily Levels: PD / PM / OR (RTH/Pre)
## Overview
This indicator displays key intraday support and resistance levels for US equity markets, specifically designed for traders who use Previous Day, Pre-Market, and Opening Range levels in their trading strategy.
## Key Features
**Seven Critical Levels Displayed:**
- **PDH (Previous Day High)** - Blue line: The highest price from yesterday's regular trading hours (9:30 AM - 4:00 PM ET)
- **PDL (Previous Day Low)** - Blue line: The lowest price from yesterday's regular trading hours
- **PDC (Previous Day Close)** - Orange line: The closing price from yesterday's regular trading hours
- **PMH (Pre-Market High)** - Yellow line: The highest price during today's pre-market session (4:00 AM - 9:30 AM ET)
- **PML (Pre-Market Low)** - Yellow line: The lowest price during today's pre-market session
- **ORH (Opening Range High)** - Red line: The highest price during the first 30 minutes of trading (9:30 AM - 10:00 AM ET)
- **ORL (Opening Range Low)** - Red line: The lowest price during the first 30 minutes of trading
## How It Works
**At 9:30 AM ET (Market Open):**
- PDH, PDL, PDC levels appear (from previous day's RTH)
- PMH, PML levels appear (from today's pre-market session)
- All lines begin at the 9:30 AM bar and extend right
**At 10:00 AM ET (Opening Range Close):**
- ORH, ORL levels appear (from today's first 30 minutes)
- Lines begin at the 9:30 AM bar and extend right
**Level Persistence:**
- All levels remain visible until the next trading day at 9:30 AM ET
- Levels reset daily for the new trading session
## Use Cases
**Day Trading:**
- Identify key support and resistance zones before placing trades
- Use PDH/PDL as potential profit targets or stop loss areas
- Monitor price reaction at pre-market levels for early trading signals
- Trade breakouts or rejections at opening range levels
**Swing Trading:**
- Assess daily momentum by observing breaks above/below previous day levels
- Use multiple timeframes while maintaining consistent reference points
**Market Structure:**
- Quickly identify if the market is trading above or below key levels
- Recognize accumulation/distribution patterns around these zones
## Technical Details
- **Timezone:** All times referenced are US Eastern Time (America/New_York)
- **Session Windows:**
  - Pre-Market: 4:00 AM - 9:30 AM ET
  - Regular Trading Hours: 9:30 AM - 4:00 PM ET
  - Opening Range: 9:30 AM - 10:00 AM ET
- **Timeframe Agnostic:** Works on any chart timeframe
- **Visual Clarity:** Color-coded lines and labels for easy identification
## Color Scheme
- **Blue:** Previous Day levels (PDH, PDL)
- **Orange:** Previous Day Close (PDC)
- **Yellow:** Pre-Market levels (PMH, PML)
- **Red:** Opening Range levels (ORH, ORL)
## Best Practices
1. Use on US equity indices (SPY, QQQ, ES, NQ) and liquid US stocks
2. Combine with volume analysis for confirmation
3. Pay attention to how price reacts at these levels (bounce vs. break)
4. Most effective during the first 2 hours of trading when volatility is highest
5. Consider the market context (trending vs. ranging) when interpreting these levels
## Note
This indicator is specifically designed for US market hours. Results may vary when applied to international markets or instruments with different trading sessions.
Quantum Flux Universal Strategy Summary in one paragraph 
Quantum Flux Universal is a regime switching strategy for stocks, ETFs, index futures, major FX pairs, and liquid crypto on intraday and swing timeframes. It helps you act only when the normalized core signal and its guide agree on direction. It is original because the engine fuses three adaptive drivers into the smoothing gains itself. Directional intensity is measured with binary entropy, path efficiency shapes trend quality, and a volatility squash preserves contrast. Add it to a clean chart, watch the polarity lane and background, and trade from positive or negative alignment. For conservative workflows use on bar close in the alert settings when you add alerts in a later version.
 Scope and intent 
• Markets. Large cap equities and ETFs. Index futures. Major FX pairs. Liquid crypto
• Timeframes. One minute to daily
• Default demo used in the publication. QQQ on one hour
• Purpose. Provide a robust and portable way to detect when momentum and confirmation align, while dampening chop and preserving turns
• Limits. This is a strategy. Orders are simulated on standard candles only
 
Originality and usefulness 
• Unique concept or fusion. The novelty sits in the gain map. Instead of gating separate indicators, the model mixes three drivers into the adaptive gains that power two one pole filters. Directional entropy measures how one sided recent movement has been. Kaufman style path efficiency scores how direct the path has been. A volatility squash stabilizes step size. The drivers are blended into the gains with visible inputs for strength, windows, and clamps.
• What failure mode it addresses. False starts in chop and whipsaw after fast spikes. Efficiency and the squash reduce over reaction in noise.
• Testability. Every component has an input. You can lengthen or shorten each window and change the normalization mode. The polarity plot and background provide a direct readout of state.
• Portable yardstick. The core is normalized with three options. Z score, percent rank mapped to a symmetric range, and MAD based Z score. Clamp bounds define the effective unit so context transfers across symbols.
 Method overview in plain language 
The strategy computes two smoothed tracks from the chart price source. The fast track and the slow track use gains that are not fixed. Each gain is modulated by three drivers. A driver for directional intensity, a driver for path efficiency, and a driver for volatility. The difference between the fast and the slow tracks forms the raw flux. A small phase assist reduces lag by subtracting a portion of the delayed value. The flux is then normalized. A guide line is an EMA of a small lead on the flux. When the flux and its guide are both above zero, the polarity is positive. When both are below zero, the polarity is negative. Polarity changes create the trade direction.
Base measures
• Return basis. The step is the change in the chosen price source. Its absolute value feeds the volatility estimate. Mean absolute step over the window gives a stable scale.
• Efficiency basis. The ratio of net move to the sum of absolute step over the window gives a value between zero and one. High values mean trend quality. Low values mean chop.
• Intensity basis. The fraction of up moves over the window plugs into binary entropy. Intensity is one minus entropy, which maps to zero in uncertainty and one in very one sided moves.
 Components
 • Directional Intensity. Measures how one sided recent bars have been. Smoothed with RMA. More intensity increases the gain and makes the fast and slow tracks react sooner.
• Path Efficiency. Measures the straightness of the price path. A gamma input shapes the curve so you can make trend quality count more or less. Higher efficiency lifts the gain in clean trends.
• Volatility Squash. Normalizes the absolute step with Z score then pushes it through an arctangent squash. This caps the effect of spikes so they do not dominate the response.
• Normalizer. Three modes. Z score for familiar units, percent rank for a robust monotone map to a symmetric range, and MAD based Z for outlier resistance.
• Guide Line. EMA of the flux with a small lead term that counteracts lag without heavy overshoot.
 Fusion rule
 • Weighted sum of the three drivers with fixed weights visible in the code comments. Intensity has fifty percent weight. Efficiency thirty percent. Volatility twenty percent.
• The blend power input scales the driver mix. Zero means fixed spans. One means full driver control.
• Minimum and maximum gain clamps bound the adaptive gain. This protects stability in quiet or violent regimes.
 Signal rule 
• Long suggestion appears when flux and guide are both above zero. That sets polarity to plus one.
• Short suggestion appears when flux and guide are both below zero. That sets polarity to minus one.
• When polarity flips from plus to minus, the strategy closes any long and enters a short.
• When flux crosses above the guide, the strategy closes any short.
 What you will see on the chart 
• White polarity plot around the zero line
• A dotted reference line at zero named Zen
• Green background tint for positive polarity and red background tint for negative polarity
• Strategy long and short markers placed by the TradingView engine at entry and at close conditions
• No table in this version to keep the visual clean and portable
 Inputs with guidance 
 Setup 
• Price source. Default ohlc4. Stable for noisy symbols.
• Fast span. Typical range 6 to 24. Raising it slows the fast track and can reduce churn. Lowering it makes entries more reactive.
• Slow span. Typical range 20 to 60. Raising it lengthens the baseline horizon. Lowering it brings the slow track closer to price.
 
Logic 
• Guide span. Typical range 4 to 12. A small guide smooths without eating turns.
• Blend power. Typical range 0.25 to 0.85. Raising it lets the drivers modulate gains more. Lowering it pushes behavior toward fixed EMA style smoothing.
• Vol window. Typical range 20 to 80. Larger values calm the volatility driver. Smaller values adapt faster in intraday work.
• Efficiency window. Typical range 10 to 60. Larger values focus on smoother trends. Smaller values react faster but accept more noise.
• Efficiency gamma. Typical range 0.8 to 2.0. Above one increases contrast between clean trends and chop. Below one flattens the curve.
• Min alpha multiplier. Typical range 0.30 to 0.80. Lower values increase smoothing when the mix is weak.
• Max alpha multiplier. Typical range 1.2 to 3.0. Higher values shorten smoothing when the mix is strong.
• Normalization window. Typical range 100 to 300. Larger values reduce drift in the baseline.
• Normalization mode. Z score, percent rank, or MAD Z. Use MAD Z for outlier heavy symbols.
• Clamp level. Typical range 2.0 to 4.0. Lower clamps reduce the influence of extreme runs.
 Filters 
• Efficiency filter is implicit in the gain map. Raising efficiency gamma and the efficiency window increases the preference for clean trends.
• Micro versus macro relation is handled by the fast and slow spans. Increase separation for swing, reduce for scalping.
• Location filter is not included in v1.0. If you need distance gates from a reference such as VWAP or a moving mean, add them before publication of a new version.
 Alerts 
• This version does not include alertcondition lines to keep the core minimal. If you prefer alerts, add names Long Polarity Up, Short Polarity Down, Exit Short on Flux Cross Up in a later version and select on bar close for conservative workflows.
Strategy has been currently adapted for the QQQ asset with 30/60min timeframe.
 For other assets may require new optimization 
 
Properties visible in this publication
• Initial capital 25000
• Base currency Default
• Default order size method percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
 Honest limitations and failure modes 
• Past results do not guarantee future outcomes
• Economic releases, circuit breakers, and thin books can break the assumptions behind intensity and efficiency
• Gap heavy symbols may benefit from the MAD Z normalization
• Very quiet regimes can reduce signal contrast. Use longer windows or higher guide span to stabilize context
• Session time is the exchange time of the chart
• If both stop and target can be hit in one bar, tie handling would matter. This strategy has no fixed stops or targets. It uses polarity flips for exits. If you add stops later, declare the preference
 Open source reuse and credits 
• None beyond public domain building blocks and Pine built ins such as EMA, SMA, standard deviation, RMA, and percent rank
• Method and fusion are original in construction and disclosure
 Legal 
Education and research only. Not investment advice. You are responsible for your decisions. Test on historical data and in simulation before any live use. Use realistic costs.
 Strategy add on block 
Strategy notice
Orders are simulated by the TradingView engine on standard candles. No request.security() calls are used.
 Entries and exits 
• Entry logic. Enter long when both the normalized flux and its guide line are above zero. Enter short when both are below zero
• Exit logic. When polarity flips from plus to minus, close any long and open a short. When the flux crosses above the guide line, close any short
• Risk model. No initial stop or target in v1.0. The model is a regime flipper. You can add a stop or trail in later versions if needed
• Tie handling. Not applicable in this version because there are no fixed stops or targets
 Position sizing 
• Percent of equity in the Properties panel. Five percent is the default for examples. Risk per trade should not exceed five to ten percent of equity. One to two percent is a common choice
 Properties used on the published chart 
• Initial capital 25000
• Base currency Default
• Default order size percent of equity with value 5
• Pyramiding 1
• Commission 0.05 percent
• Slippage 10 ticks
• Process orders on close ON
• Bar magnifier ON
• Recalculate after order is filled OFF
• Calc on every tick OFF
Dataset and sample size
• Test window Jan 2, 2014 to Oct 16, 2025 on QQQ one hour
• Trade count in sample 324 on the example chart
Release notes template for future updates
Version 1.1.
• Add alertcondition lines for long, short, and exit short
• Add optional table with component readouts
• Add optional stop model with a distance unit expressed as ATR or a percent of price
Notes. Backward compatibility Yes. Inputs migrated Yes.
SMA RibbonThis indicator overlays multiple Simple Moving Averages (SMAs) on the price chart to help visualize both short- and long-term market trends. It includes five configurable SMA lines — 10, 21, 50, 100, and 200 periods by default — each plotted with distinct colors for quick differentiation.
Short-term averages (10 and 21) highlight near-term momentum, while medium- and long-term averages (50, 100, and 200) provide broader trend context and identify potential areas of dynamic support or resistance.
Users can easily adjust the period lengths and line thickness through the settings panel to fit different timeframes or trading styles.
 Features 
Plots 5 configurable SMAs (default: 10, 21, 50, 100, 200)
Adjustable line width and colors for visual clarity
Works seamlessly on any timeframe and instrument
Useful for identifying trend direction, strength, and key support/resistance zones
HTF Cross Breakout [CHE]  HTF Cross Breakout   — Detects higher timeframe close crossovers for breakout signals, anchors VWAP for trend validation, and flags continuations or traps with visual extensions for delta percent and stop levels.
  Summary 
This indicator spots moments when the current chart's close price crosses a higher timeframe close, marking potential breakouts only when the current bar shows directional strength. It anchors a volume-weighted average price line from the breakout point to track trend health, updating labels to show if the move continues or reverses into a trap. Extensions add a dotted line linking the breakout level to the current close with percent change display, plus a stop-loss marker at the VWAP end. Signals gain robustness from higher timeframe confirmation and anti-repainting options, reducing noise in live bars compared to simple crossover tools.
  Motivation: Why this design? 
Traders often face false breakouts from intrabar wiggles on lower timeframes, especially without higher timeframe alignment, leading to whipsaws in volatile sessions. This design uses higher timeframe close as a stable reference for crossover detection, combined with anchored volume weighting to gauge sustained momentum. It addresses these by enforcing bar confirmation and directional filters, providing clearer entry validation and risk points without overcomplicating the chart.
  What’s different vs. standard approaches? 
 Reference baseline
Standard crossover indicators like moving average crosses operate solely on the chart timeframe, ignoring higher timeframe context and lacking volume anchoring.
  Architecture differences 
- Higher timeframe data pulls via security calls with optional repainting control for stability.
- Anchored VWAP resets at each signal, accumulating from the breakout bar only.
- Label dynamics update in real-time for continuation checks, with extensions for visual delta and stop computation.
- Event-driven line finalization prunes old elements after a set bar extension.
  Practical effect 
Charts show persistent lines and labels that extend live but finalize cleanly on new events, avoiding clutter. This matters for spotting trap reversals early via label color shifts, and extensions provide quick risk visuals without manual calculations, improving decision speed in trend trades.
  How it works (technical) 
The indicator first determines a higher timeframe based on user selection, pulling its close price securely. It checks for crossovers or crossunders of the current close against this higher close, but only triggers on confirmed bars with matching directional opens and closes. On a valid event, a horizontal line and label mark the higher close level, while a dashed VWAP line starts accumulating typical price times volume from that bar onward. During the active phase, the breakout line extends to the current bar, the label repositions and updates text based on whether the current close holds above or below the level for bulls or bears. A background tint warns if the close deviates adversely from the current VWAP. Extensions draw a vertical dotted line at the last bar between the breakout level and close, placing a midpoint label with percent difference; separately, a label at the VWAP end shows a computed stop price. Persistent variables track the active state and accumulators, resetting on new events after briefly extending old elements. Repaint risk from security calls is mitigated by confirmed bar gating or user opt-in.
  Parameter Guide 
Plateau Length (reserved for future, currently unused): Sets a length for potential plateau detection in extensions; default 3, minimum 1. Higher values would increase stability but are not active yet—leave at default to avoid tuning.
Line Width: Controls thickness of breakout, VWAP, and extension lines; default 2, range 1 to 5. Thicker lines improve visibility on busy charts but may obscure price action—use 1 for clean views, 3 or more for emphasis.
+Bars after next HTF event (finalize old, then delete): Extends old lines and labels by this many bars before deletion on new signals; default 20, minimum 0. Shorter extensions keep charts tidy but risk cutting visuals prematurely; longer aids review but builds clutter over time.
Evaluate label only on HTF close (prevents gray traps intrabar): When true, label updates wait for higher timeframe confirmation; default true. Enabling reduces intrabar flips for stabler signals, though it may delay feedback—disable for faster live trading at repaint cost.
Allow Repainting: Permits real-time security data without confirmation offset; default false. False ensures historical accuracy but lags live bars; true speeds updates but can repaint on HTF closes.
Timeframe Type: Chooses HTF method—Auto Timeframe (dynamic steps up), Multiplier (chart multiple), or Manual (fixed string); default Auto Timeframe. Auto adapts to chart scale for convenience; Multiplier suits custom scaling like 5 times current; Manual for precise like 1D on any chart.
Multiplier for Alternate Resolution: Scales chart timeframe when Multiplier type selected; default 5, minimum 1. Values near 1 mimic current resolution for subtle shifts; higher like 10 jumps to broader context, increasing signal rarity.
Manual Resolution: Direct timeframe string like 60 for 1H when Manual type; default 60. Match to trading horizon—shorter for swing, longer for positional—to balance frequency and reliability.
Show Extension 1: Toggles dotted line and delta percent label between breakout level and current close; default true. Disable to simplify for basic use, enable for precise momentum tracking.
Dotted Line Width: Thickness for Extension 1 line; default 2, range 1 to 5. Align with main Line Width for consistency.
Text Size: Size for delta percent label; options tiny, small, normal, large; default normal. Smaller reduces overlap on dense charts; larger aids glance reads.
Decimals for Δ%: Precision in percent change display; default 2, range 0 to 6. Fewer decimals speed reading; more suit low-volatility assets.
Positive Δ Color: Hue for upward percent changes; default lime. Choose contrasting for visibility.
Negative Δ Color: Hue for downward percent changes; default red. Pair with positive for quick polarity scan.
Dotted Line Color: Color for Extension 1 line; default gray. Neutral tones blend well; brighter for emphasis.
Background Transparency (0..100): Opacity for delta label background; default 90. Higher values fade for subtlety; lower solidifies for readability.
Show Extension 2: Toggles stop-loss label at VWAP end; default true. Turn off for entry focus only.
Stop Method: Percent from VWAP end or fixed ticks; options Percent, Ticks; default Percent. Percent scales with price levels; Ticks suits tick-based instruments.
Stop %: Distance as fraction of VWAP for Percent method; default 1.0, step 0.05, minimum 0.0. Tighter like 0.5 reduces risk but increases stops; wider like 2.0 allows breathing room.
Stop Ticks: Tick count offset for Ticks method; default 20, minimum 0. Adjust per asset volatility—fewer for tight control.
Price Decimals: Rounding for stop price text; default 4, range 0 to 10. Match syminfo.precision for clean display.
Text Size: Size for stop label; options tiny, small, normal, large; default normal. Scale to chart zoom.
Text Color: Foreground for stop text; default white. Ensure contrast with background.
Inherit VWAP Color (BG tint): Bases stop label background on VWAP hue; default true. True maintains theme; false allows custom black base.
BG Transparency (0..100): Opacity for stop label background; default 0. Zero for no tint; up to 100 for full fade.
  Reading & Interpretation 
Breakout lines appear green for bullish crosses or red for bearish, extending live until a new event finalizes them briefly then deletes. Labels start blank, updating to Bull Cont. or Bear Cont. in matching colors if holding the level, or gray Bull Trap/Bear Trap on reversal. VWAP dashes yellow for bulls, orange for bears, sloping with accumulated volume weight—deviations trigger faint red background warnings. Extension 1's dotted vertical shows at the last bar, with midpoint label green/red for positive/negative percent from breakout to close. Extension 2 places a left-aligned label at VWAP end with stop price and method note, tinted to VWAP for context.
  Practical Workflows & Combinations 
For trend following, enter long on green Bull Cont. labels above VWAP with higher highs confirmation, filtering via rising structure; short on red Bear Cont. below. Pair with volume surges or RSI above 50 for bulls to avoid traps. For exits, trail stops using the Extension 2 level, tightening on warnings or gray labels—aggressive on continuations, conservative post-trap. In multi-timeframe setups, use default Auto on 15m charts for 1H signals, scaling multiplier to 4 for daily context on hourly; test on forex/stocks where volume is reliable, avoiding low-liquidity assets.
  Behavior, Constraints & Performance 
Signals confirm on bar close with HTF gating when strict mode active, but live bars may update if repainting enabled—opt false for backtest fidelity, true for intraday speed. Security calls risk minor repaints on HTF closes, mitigated by confirmation offsets. Resources cap at 1000 bars back, 50 lines/labels total, with event prunes to stay under budgets—no loops, minimal arrays. Limits include VWAP lag in low-volume periods and dependency on accurate HTF data; gaps or holidays may skew anchors.
  Sensible Defaults & Quick Tuning 
Defaults suit 5m-1H charts on liquid assets: Auto HTF, no repaint, 1% stops. For choppy markets with excess signals, enable strict eval and bump multiplier to 10 for rarer triggers. If sluggish in trends, shorten extend bars to 10 and allow repainting for quicker visuals. On high-vol like crypto, widen stop % to 2.0 and use Ticks method; for stables like indices, tighten to 0.5% and keep Percent.
  What this indicator is—and isn’t 
This is a signal visualization layer for breakout confirmation and basic risk marking, best as a filter in discretionary setups. It isn’t a standalone system or predictive oracle—combine with price structure, news awareness, and sizing rules for real edges.
  Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
 Best regards and happy trading
Chervolino
RSI Donchian Channel [DCAUT]█ RSI Donchian Channel  
 📊 ORIGINALITY & INNOVATION 
The RSI Donchian Channel represents an important synthesis of two complementary analytical frameworks: momentum oscillators and breakout detection systems. This indicator addresses a common limitation in traditional RSI analysis by replacing fixed overbought/oversold thresholds with adaptive zones derived from historical RSI extremes.
 Key Enhancement: 
Traditional RSI analysis relies on static threshold levels (typically 30/70), which may not adequately reflect changing market volatility regimes. This indicator adapts the reference zones dynamically based on the actual RSI behavior over the lookback period, helping traders identify meaningful momentum extremes relative to recent price action rather than arbitrary fixed levels.
The implementation combines the proven momentum measurement capabilities of RSI with Donchian Channel's breakout detection methodology, creating a framework that identifies both momentum exhaustion points and potential continuation signals through the same analytical lens.
 📐 MATHEMATICAL FOUNDATION 
 Core Calculation Process: 
 Step 1: RSI Calculation 
The Relative Strength Index measures momentum by comparing the magnitude of recent gains to recent losses:
 
 Calculate price changes between consecutive periods
 Separate positive changes (gains) from negative changes (losses)
 Apply selected smoothing method (RMA standard, also supports SMA, EMA, WMA) to both gain and loss series
 Compute Relative Strength (RS) as the ratio of smoothed gains to smoothed losses
 Transform RS into bounded 0-100 scale using the formula: RSI = 100 - (100 / (1 + RS))
 
 Step 2: Donchian Channel Application 
The Donchian Channel identifies the highest and lowest RSI values within the specified lookback period:
 
 Upper Channel: Highest RSI value over the lookback period, represents the recent momentum peak
 Lower Channel: Lowest RSI value over the lookback period, represents the recent momentum trough
 Middle Channel (Basis): Average of upper and lower channels, serves as equilibrium reference
 
 Channel Width Dynamics: 
The distance between upper and lower channels reflects RSI volatility. Wide channels indicate high momentum variability, while narrow channels suggest momentum consolidation and potential breakout preparation. The indicator monitors channel width over a 100-period window to identify squeeze conditions that often precede significant momentum shifts.
 📊 COMPREHENSIVE SIGNAL ANALYSIS 
 Primary Signal Categories: 
 Breakout Signals: 
 
 Upper Breakout: RSI crosses above the upper channel, indicates momentum reaching new relative highs and potential trend continuation, particularly significant when accompanied by price confirmation
 Lower Breakout: RSI crosses below the lower channel, suggests momentum reaching new relative lows and potential trend exhaustion or reversal setup
 Breakout strength is enhanced when the channel is narrow prior to the breakout, indicating a transition from consolidation to directional movement
 
 Mean Reversion Signals: 
 
 Upper Touch Without Breakout: RSI reaches the upper channel but fails to break through, may indicate momentum exhaustion and potential reversal opportunity
 Lower Touch Without Breakout: RSI reaches the lower channel without breakdown, suggests potential bounce as momentum reaches oversold extremes
 Return to Basis: RSI moving back toward the middle channel after touching extremes signals momentum normalization
 
 Trend Strength Assessment: 
 
 Sustained Upper Channel Riding: RSI consistently remains near or above the upper channel during strong uptrends, indicates persistent bullish momentum
 Sustained Lower Channel Riding: RSI stays near or below the lower channel during strong downtrends, reflects persistent bearish pressure
 Basis Line Position: RSI position relative to the middle channel helps identify the prevailing momentum bias
 
 Channel Compression Patterns: 
 
 Squeeze Detection: Channel width narrowing to 100-period lows indicates momentum consolidation, often precedes significant directional moves
 Expansion Phase: Channel widening after a squeeze confirms the initiation of a new momentum regime
 Persistent Narrow Channels: Extended periods of tight channels suggest market indecision and accumulation/distribution phases
 
 🎯 STRATEGIC APPLICATIONS 
 Trend Continuation Strategy: 
This approach focuses on identifying and trading momentum breakouts that confirm established trends:
 
 Identify the prevailing price trend using higher timeframe analysis or trend-following indicators
 Wait for RSI to break above the upper channel in uptrends (or below the lower channel in downtrends)
 Enter positions in the direction of the breakout when price action confirms the momentum shift
 Place protective stops below the recent swing low (long positions) or above swing high (short positions)
 Target profit levels based on prior swing extremes or use trailing stops to capture extended moves
 Exit when RSI crosses back through the basis line in the opposite direction
 
 Mean Reversion Strategy: 
This method capitalizes on momentum extremes and subsequent corrections toward equilibrium:
 
 Monitor for RSI reaching the upper or lower channel boundaries
 Look for rejection signals (price reversal patterns, volume divergence) when RSI touches the channels
 Enter counter-trend positions when RSI begins moving back toward the basis line
 Use the basis line as the initial profit target for mean reversion trades
 Implement tight stops beyond the channel extremes to limit risk on failed reversals
 Scale out of positions as RSI approaches the basis line and closes the position when RSI crosses the basis
 
 Breakout Preparation Strategy: 
This approach positions traders ahead of potential volatility expansion from consolidation phases:
 
 Identify squeeze conditions when channel width reaches 100-period lows
 Monitor price action for consolidation patterns (triangles, rectangles, flags) during the squeeze
 Prepare conditional orders for breakouts in both directions from the consolidation
 Enter positions when RSI breaks out of the narrow channel with expanding width
 Use the channel width expansion as a confirmation signal for the breakout's validity
 Manage risk with stops just inside the opposite channel boundary
 
 Multi-Timeframe Confluence Strategy: 
Combining RSI Donchian Channel analysis across multiple timeframes can improve signal reliability:
 
 Identify the primary trend direction using a higher timeframe RSI Donchian Channel (e.g., daily or weekly)
 Use a lower timeframe (e.g., 4-hour or hourly) to time precise entry points
 Enter long positions when both timeframes show RSI above their respective basis lines
 Enter short positions when both timeframes show RSI below their respective basis lines
 Avoid trades when timeframes provide conflicting signals (e.g., higher timeframe below basis, lower timeframe above)
 Exit when the higher timeframe RSI crosses its basis line in the opposite direction
 
 Risk Management Guidelines: 
Effective risk management is essential for all RSI Donchian Channel strategies:
 
 Position Sizing: Calculate position sizes based on the distance between entry point and stop loss, limiting risk to 1-2% of capital per trade
 Stop Loss Placement: For breakout trades, place stops just inside the opposite channel boundary; for mean reversion trades, use stops beyond the channel extremes
 Profit Targets: Use the basis line as a minimum target for mean reversion trades; for trend trades, target prior swing extremes or use trailing stops
 Channel Width Context: Increase position sizes during narrow channels (lower volatility) and reduce sizes during wide channels (higher volatility)
 Correlation Awareness: Monitor correlations between traded instruments to avoid over-concentration in similar setups
 
 📋 DETAILED PARAMETER CONFIGURATION 
 RSI Source: 
Defines the price data series used for RSI calculation:
 
 Close (Default): Standard choice providing end-of-period momentum assessment, suitable for most trading styles and timeframes
 High-Low Average (HL2): Reduces the impact of closing auction dynamics, useful for markets with significant end-of-day volatility
 High-Low-Close Average (HLC3): Provides a more balanced view incorporating the entire period's range
 Open-High-Low-Close Average (OHLC4): Offers the most comprehensive price representation, helpful for identifying overall period sentiment
 Strategy Consideration: Use Close for end-of-period signals, HL2 or HLC3 for intraday volatility reduction, OHLC4 for capturing full period dynamics
 
 RSI Length: 
Controls the number of periods used for RSI calculation:
 
 Short Periods (5-9): Highly responsive to recent price changes, produces more frequent signals with increased false signal risk, suitable for short-term trading and volatile markets
 Standard Period (14): Widely accepted default balancing responsiveness with stability, appropriate for swing trading and intermediate-term analysis
 Long Periods (21-28): Produces smoother RSI with fewer signals but more reliable trend identification, better for position trading and reducing noise in choppy markets
 Optimization Approach: Test different lengths against historical data for your specific market and timeframe, consider using longer periods in ranging markets and shorter periods in trending markets
 
 RSI MA Type: 
Determines the smoothing method applied to price changes in RSI calculation:
 
 RMA (Relative Moving Average - Default): Wilder's original smoothing method providing stable momentum measurement with gradual response to changes, maintains consistency with classical RSI interpretation
 SMA (Simple Moving Average): Treats all periods equally, responds more quickly to changes than RMA but may produce more whipsaws in volatile conditions
 EMA (Exponential Moving Average): Weights recent periods more heavily, increases responsiveness at the cost of potential noise, suitable for traders prioritizing early signal generation
 WMA (Weighted Moving Average): Applies linear weighting favoring recent data, offers a middle ground between SMA and EMA responsiveness
 Selection Guidance: Maintain RMA for consistency with traditional RSI analysis, use EMA or WMA for more responsive signals in fast-moving markets, apply SMA for maximum simplicity and transparency
 
 DC Length: 
Specifies the lookback period for Donchian Channel calculation on RSI values:
 
 Short Periods (10-14): Creates tight channels that adapt quickly to changing momentum conditions, generates more frequent trading signals but increases sensitivity to short-term RSI fluctuations
 Standard Period (20): Balances channel responsiveness with stability, aligns with traditional Bollinger Bands and moving average periods, suitable for most trading styles
 Long Periods (30-50): Produces wider, more stable channels that better represent sustained momentum extremes, reduces signal frequency while improving reliability, appropriate for position traders and higher timeframes
 Calibration Strategy: Match DC length to your trading timeframe (shorter for day trading, longer for swing trading), test channel width behavior during different market regimes, consider using adaptive periods that adjust to volatility conditions
 Market Adaptation: Use shorter DC lengths in trending markets to capture momentum shifts earlier, apply longer periods in ranging markets to filter noise and focus on significant extremes
 
 Parameter Combination Recommendations: 
 
 Scalping/Day Trading: RSI Length 5-9, DC Length 10-14, EMA or WMA smoothing for maximum responsiveness
 Swing Trading: RSI Length 14, DC Length 20, RMA smoothing for balanced analysis (default configuration)
 Position Trading: RSI Length 21-28, DC Length 30-50, RMA or SMA smoothing for stable signals
 High Volatility Markets: Longer RSI periods (21+) with standard DC length (20) to reduce noise
 Low Volatility Markets: Standard RSI length (14) with shorter DC length (10-14) to capture subtle momentum shifts
 
 📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES 
 Adaptive Threshold Mechanism: 
Unlike traditional RSI analysis with fixed 30/70 thresholds, this indicator's Donchian Channel approach provides several improvements:
 
 Context-Aware Extremes: Overbought/oversold levels adjust automatically based on recent momentum behavior rather than arbitrary fixed values
 Volatility Adaptation: In low volatility periods, channels narrow to reflect tighter momentum ranges; in high volatility, channels widen appropriately
 Market Regime Recognition: The indicator implicitly adapts to different market conditions without manual threshold adjustments
 False Signal Reduction: Adaptive channels help reduce premature reversal signals that often occur with fixed thresholds during strong trends
 
 Signal Quality Characteristics: 
The indicator's dual-purpose design provides distinct advantages for different trading objectives:
 
 Breakout Trading: Channel boundaries offer clear, objective breakout levels that update dynamically, eliminating the ambiguity of when momentum becomes "too high" or "too low"
 Mean Reversion: The basis line provides a natural profit target for reversion trades, representing the midpoint of recent momentum extremes
 Trend Strength: Persistent channel boundary riding offers an objective measure of trend strength without additional indicators
 Consolidation Detection: Channel width analysis provides early warning of potential volatility expansion from compression phases
 
 Comparative Analysis: 
When compared to traditional RSI implementations and other momentum frameworks:
 
 vs. Fixed Threshold RSI: Provides market-adaptive reference levels rather than static values, helping to reduce false signals during trending markets where RSI can remain "overbought" or "oversold" for extended periods
 vs. RSI Bollinger Bands: Offers clearer breakout signals and more intuitive extreme identification through actual high/low boundaries rather than statistical standard deviations
 vs. Stochastic Oscillator: Maintains RSI's momentum measurement advantages (unbounded calculation avoiding scale compression) while adding the breakout detection capabilities of Donchian Channels
 vs. Standard Donchian Channels: Applies breakout methodology to momentum space rather than price, providing earlier signals of potential trend changes before price breakouts occur
 
 Performance Characteristics: 
The indicator exhibits specific behavioral patterns across different market conditions:
 
 Trending Markets: Excels at identifying momentum continuation through channel breakouts, RSI tends to ride one channel boundary during strong trends, providing trend confirmation
 Ranging Markets: Channel width narrows during consolidation, offering early preparation signals for potential breakout trading opportunities
 High Volatility: Channels widen to reflect increased momentum variability, automatically adjusting signal sensitivity to match market conditions
 Low Volatility: Channels contract, making the indicator more sensitive to subtle momentum shifts that may be significant in calm market environments
 Transition Periods: Channel squeezes often precede major trend changes, offering advance warning of potential regime shifts
 
 Limitations and Considerations: 
Users should be aware of certain operational characteristics:
 
 Lookback Dependency: Channel boundaries depend entirely on the lookback period, meaning the indicator has no predictive element beyond identifying current momentum relative to recent history
 Lag Characteristics: As with all moving average-based indicators, RSI calculation introduces lag, and channel boundaries update only as new extremes occur within the lookback window
 Range-Bound Sensitivity: In extremely tight ranges, channels may become very narrow, potentially generating excessive signals from minor momentum fluctuations
 Trending Persistence: During very strong trends, RSI may remain at channel extremes for extended periods, requiring patience for mean reversion setups or commitment to trend-following approaches
 No Absolute Levels: Unlike traditional RSI, this indicator provides no fixed reference points (like 50), making it less suitable for strategies that depend on absolute momentum readings
 
 USAGE NOTES 
This indicator is designed for technical analysis and educational purposes to help traders understand momentum dynamics and identify potential trading opportunities. The RSI Donchian Channel has limitations and should not be used as the sole basis for trading decisions.
Important considerations:
 
 Performance varies significantly across different market conditions, timeframes, and instruments
 Historical signal patterns do not guarantee future results, as market behavior continuously evolves
 Effective use requires understanding of both RSI momentum principles and Donchian Channel breakout concepts
 Risk management practices (stop losses, position sizing, diversification) are essential for any trading application
 Consider combining with additional analytical tools such as volume analysis, price action patterns, or trend indicators for confirmation
 Backtest thoroughly on your specific instruments and timeframes before live trading implementation
 Be aware that optimization on historical data may lead to curve-fitting and poor forward performance
 
The indicator performs best when used as part of a comprehensive trading methodology that incorporates multiple forms of market analysis, sound risk management, and realistic expectations about win rates and drawdowns.
JK_Traders_Reality_LibLibrary   "JK_Traders_Reality_Lib" 
This library contains common elements used in Traders Reality scripts
 calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor) 
  calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors:  Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors:  Bull bars are blue and bear are violet.
  Parameters:
     pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
     pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
     pvsraLow (float) : the instrument low series (obtained from request.sequrity)
     pvsraClose (float) : the instrument close series (obtained from request.sequrity)
     pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
     redVectorColor (simple color) : red vector candle color
     greenVectorColor (simple color) : green vector candle color
     violetVectorColor (simple color) : violet/pink vector candle color
     blueVectorColor (simple color) : blue vector candle color
     darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
     lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return  
 adr(length, barsBack) 
  Parameters:
     length (simple int) : how many elements of the series to calculate on
     barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
 adrHigh(adr, fromDo) 
  Calculate the ADR high given an ADR
  Parameters:
     adr (float) : the adr
     fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
 adrLow(adr, fromDo) 
  Parameters:
     adr (float) : the adr
     fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
 splitSessionString(sessXTime) 
  given a session in the format 0000-0100:23456 split out the hours and minutes
  Parameters:
     sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return  
 calcSessionStartEnd(sessXTime, gmt) 
  calculate the start and end timestamps of the session
  Parameters:
     sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return  
 drawOpenRange(sessXTime, sessXcol, showOrX, gmt) 
  draw open range for a session
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     sessXcol (simple color) : the color to be used for the opening range box shading
     showOrX (simple bool) : boolean flag to toggle displaying the opening range
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
 drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle) 
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     showRectangleX (simple bool) 
     showLabelX (simple bool) 
     sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
     sessXLabel (simple string) : the session label text
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
 calcDst() 
  calculate market session dst on/off flags
@return   indicating if DST is on or off for a particular region
 timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis) 
  Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
  Parameters:
     previousDayOfWeek (simple string) : Monday or Satruday
     hourOfDay (simple int) : the hour of the day when psy calc is to start
     gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
 getdayOpen() 
  get the daily open - basically exchange midnight
@return the daily open value which is float price
 newBar(res) 
  new_bar: check if we're on a new bar within the session in a given resolution
  Parameters:
     res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
 toPips(val) 
  to_pips Convert value to pips
  Parameters:
     val (float) : the value to convert to pips
@return the value in pips
 rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (simple string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelXOffset (int) : how much to offset the label from the current position
 rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset) 
  a function that draws a right aligned lable for a series during the current bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelOffset (int) 
 rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset) 
  a function that draws a right aligned lable for a series only on the last bar
  Parameters:
     ry (float) : series float the y coordinate of the lable
     rtext (string) : the text of the label
     rstyle (simple string) : the style for the lable
     rcolor (simple color) : the color for the label
     valid (simple bool) : a boolean flag that allows for turning on or off a lable
     labelXOffset (int) : how much to offset the label from the current position
 drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame) 
  a function that draws a line and a label for a series
  Parameters:
     xSeries (float) : series float the y coordinate of the line/label
     res (simple string) : the desired resolution controlling when a new line will start
     tag (simple string) : the text for the lable
     xColor (simple color) : the color for the label
     xStyle (simple string) : the style for the line
     xWidth (simple int) : the width of the line
     xExtend (simple string) : extend the line
     isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
     xLabelOffset (int) 
     validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
 drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame) 
  a function that draws a line and a label for the daily open series
  Parameters:
     xSeries (float) : series float the y coordinate of the line/label
     res (simple string) : the desired resolution controlling when a new line will start
     tag (simple string) : the text for the lable
     xColor (simple color) : the color for the label
     xStyle (simple string) : the style for the line
     xWidth (simple int) : the width of the line
     xExtend (simple string) : extend the line
     isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
     xLabelOffset (int) 
     validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
 drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset) 
  draw a pivot line - the line starts one day into the past
  Parameters:
     pivotLevel (float) : series of the pivot point
     res (simple string) : the desired resolution
     tag (simple string) : the text to appear
     pivotColor (simple color) : the color of the line
     pivotLabelColor (simple color) : the color of the label
     pivotStyle (simple string) : the line style
     pivotWidth (simple int) : the line width
     pivotExtend (simple string) : extend the line
     isLabelValid (simple bool) : boolean param allows to turn label on and off
     validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
     levelStart (int) : basically when to start drawing the levels
     pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
 getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor) 
  convert the pvsra color to an internal code
  Parameters:
     pvsraColor (color) : the calculated pvsra color
     redVectorColor (simple color) : the user defined red vector color
     greenVectorColor (simple color) : the user defined green vector color
     violetVectorColor (simple color) : the user defined violet vector color
     blueVectorColor (simple color) : the user defined blue vector color
     lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
 updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor) 
  a function that draws the unrecovered vector candle zones
  Parameters:
     pvsra (int) : internal code
     direction (simple int) : above or below the current pa
     boxArr (array) : the array containing the boxes that need to be updated
     maxlevels (simple int) : the maximum number of boxes to draw
     pvsraHigh (float) : the pvsra high value series
     pvsraLow (float) : the pvsra low value series
     pvsraOpen (float) : the pvsra open value series
     pvsraClose (float) : the pvsra close value series
     transperancy (simple int) : the transparencfy of the vecor candle zones
     zoneupdatetype (simple string) : the zone update type
     zonecolor (simple color) : the zone color if overriden
     zonetype (simple string) : the zone type
     borderwidth (simple int) : the width of the border
     coloroverride (simple bool) : if the color overriden
     redVectorColor (simple color) : the user defined red vector color
     greenVectorColor (simple color) : the user defined green vector color
     violetVectorColor (simple color) : the user defined violet vector color
     blueVectorColor (simple color) : the user defined blue vector color
 cleanarr(arr) 
  clean an array from na values
  Parameters:
     arr (array) : the array to clean
@return if the array was cleaned
 calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST) 
  calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
  Parameters:
     oneWeekMillis (simple int) : a constant value
     showPsylevels (simple bool) : should psy levels be calculated
     psyType (simple string) : the type of Psylevels - crypto or forex
     sydDST (bool) : is Sydney in DST
@return  
 adrHiLo(length, barsBack, fromDO) 
  Parameters:
     length (simple int) : how many elements of the series to calculate on
     barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
     fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh  - the adr, the position of the adr High and adr Low with respect to price
 drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol) 
  Parameters:
     sessXTime (simple string) : session string in the format 0000-0100:23456
     showRectangleX (simple bool) 
     showLabelX (simple bool) 
     sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
     sessXLabel (simple string) : the session label text
     gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
     sessionLineStyle (simple string) : the line stile for the session high low lines
     sessXcol (simple color) : - the color for the box color that will color the session
@return void
 msToHmsString(ms) 
  converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
  Parameters:
     ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
 countdownString(openToday, closeToday, showMarketsWeekends, oneDay) 
  that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
  Parameters:
     openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
     closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
     showMarketsWeekends (simple bool) 
     oneDay (simple int) 
 countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay) 
  that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
  Parameters:
     sydOpenToday (int) 
     sydCloseToday (int) 
     showMarketsWeekends (simple bool) 
     oneDay (simple int)
MNQ TopStep 50K | Ultra Quality v3.0MNQ TopStep 50K | Ultra Quality v3.0 - Publish Summary
📊 Overview
A professional-grade trading indicator designed specifically for MNQ futures traders using TopStep funded accounts. Combines 7 technical confirmations with 5 advanced safety filters to deliver high-quality trade signals while managing drawdown risk.
🎯 Key Features
Core Signal System
7-Point Confirmation: VWAP, EMA crossovers, 15-min HTF trend, MACD, RSI, ADX, and Volume
Signal Grading: Each signal is rated A+ through D based on 7 quality factors
Quality Threshold: Adjustable minimum grade requirement (A+, A, B, C, D)
Advanced Safety Filters (Customizable)
Mean Reversion Filter - Prevents chasing extended moves beyond VWAP bands
ATR Spike Filter - Avoids trading during extreme volatility events
EMA Spacing Filter - Ensures proper trend separation (optional)
Momentum Filter - Requires consecutive directional bars (optional)
Multi-Timeframe Confirmation - Aligns with 15-min trend (optional)
TopStep Risk Management
Real-time drawdown tracking
Position sizing calculator based on remaining cushion
Daily loss limit monitoring
Consecutive loss protection
Max trades per day limiter
Visual Components
VWAP with 1σ, 2σ, 3σ bands
EMA 9/21 with cloud fill
15-min EMA 50 for HTF trend
Comprehensive metrics dashboard
Risk management panel
Filter status panel
Detailed trade labels with entry, stops, and targets
⚙️ Default Settings (Balanced for Regular Signals)
Technical Indicators
Fast EMA: 9 | Slow EMA: 21 | HTF EMA: 50 (15-min)
MACD: 10/22/9
RSI: 14 period | Thresholds: 52 (buy) / 48 (sell)
ADX: 14 period | Minimum: 20
ATR: 14 period | Stop: 2x | TP1: 2x | TP2: 3x
Volume: 1.2x average required
Session Settings
Default: 9:30 AM - 11:30 AM ET (adjustable)
Avoids first 15 minutes after market open
Customizable trading hours
Safety Filters (Default Configuration)
✅ Mean Reversion: Enabled (2.5σ max from VWAP)
✅ ATR Spike: Enabled (2.0x threshold)
❌ EMA Spacing: Disabled (can enable for quality)
❌ Momentum: Disabled (can enable for quality)
❌ MTF Confirmation: Disabled (can enable for quality)
Risk Controls
Minimum Signal Quality: C (adjustable to A+ for fewer/better signals)
Min Bars Between Signals: 10
Max Trades Per Day: 5
Stop After Consecutive Losses: 2
📈 Expected Performance
With Default Settings:
Signals per week: 10-15 trades
Estimated win rate: 55-60%
Risk-Reward: 1:2 (TP1) and 1:3 (TP2)
With Aggressive Settings (Min Quality = D, All Filters Off):
Signals per week: 20-25 trades
Estimated win rate: 50-55%
With Conservative Settings (Min Quality = A, All Filters On):
Signals per week: 3-5 trades
Estimated win rate: 65-70%
🚀 How to Use
Basic Setup:
Add indicator to MNQ 5-minute chart
Adjust TopStep account settings in inputs
Set your risk per trade percentage (default: 0.5%)
Configure trading session hours
Set minimum signal quality (Start with C for balanced results)
Signal Interpretation:
Green Triangle (BUY): Long signal - all confirmations aligned
Red Triangle (SELL): Short signal - all confirmations aligned
Label Details: Shows entry, stop loss, take profit levels, position size, and signal grade
Signal Grade: A+ = Elite (6-7 points) | A = Strong (5) | B = Good (4) | C = Fair (3)
Dashboard Monitoring:
Top Right: Technical metrics and market conditions
Top Left: Filter status (which filters are passing/blocking)
Bottom Right: TopStep risk metrics and position sizing
⚡ Customization Tips
For More Signals:
Lower "Minimum Signal Quality" to D
Decrease ADX threshold to 18-20
Lower RSI thresholds to 50/50
Reduce Volume multiplier to 1.1x
Disable additional filters
For Higher Quality (Fewer Signals):
Raise "Minimum Signal Quality" to A or A+
Increase ADX threshold to 25-30
Enable all 5 advanced filters
Tighten VWAP distance to 2.0σ
Increase momentum requirement to 3-4 bars
For TopStep Compliance:
Adjust "Max Total Drawdown" and "Daily Loss Limit" to match your account
Update "Already Used Drawdown" daily
Monitor the Risk Panel for cushion remaining
Use recommended contract sizing
🛡️ Risk Disclaimer
IMPORTANT: This indicator is for educational and informational purposes only.
Past performance does not guarantee future results
All trading involves substantial risk of loss
Use proper risk management and position sizing
Test thoroughly in paper trading before live use
The indicator does not guarantee profitable trades
Adjust settings based on your risk tolerance and trading style
Always comply with your broker's and TopStep's rules
MNQ TopStep 50K | Ultra Quality v3.0MNQ TopStep 50K | Ultra Quality v3.0 - Publish Summary📊 OverviewA professional-grade trading indicator designed specifically for MNQ futures traders using TopStep funded accounts. Combines 7 technical confirmations with 5 advanced safety filters to deliver high-quality trade signals while managing drawdown risk.🎯 Key FeaturesCore Signal System
7-Point Confirmation: VWAP, EMA crossovers, 15-min HTF trend, MACD, RSI, ADX, and Volume
Signal Grading: Each signal is rated A+ through D based on 7 quality factors
Quality Threshold: Adjustable minimum grade requirement (A+, A, B, C, D)
Advanced Safety Filters (Customizable)
Mean Reversion Filter - Prevents chasing extended moves beyond VWAP bands
ATR Spike Filter - Avoids trading during extreme volatility events
EMA Spacing Filter - Ensures proper trend separation (optional)
Momentum Filter - Requires consecutive directional bars (optional)
Multi-Timeframe Confirmation - Aligns with 15-min trend (optional)
TopStep Risk Management
Real-time drawdown tracking
Position sizing calculator based on remaining cushion
Daily loss limit monitoring
Consecutive loss protection
Max trades per day limiter
Visual Components
VWAP with 1σ, 2σ, 3σ bands
EMA 9/21 with cloud fill
15-min EMA 50 for HTF trend
Comprehensive metrics dashboard
Risk management panel
Filter status panel
Detailed trade labels with entry, stops, and targets
⚙️ Default Settings (Balanced for Regular Signals)Technical Indicators
Fast EMA: 9 | Slow EMA: 21 | HTF EMA: 50 (15-min)
MACD: 10/22/9
RSI: 14 period | Thresholds: 52 (buy) / 48 (sell)
ADX: 14 period | Minimum: 20
ATR: 14 period | Stop: 2x | TP1: 2x | TP2: 3x
Volume: 1.2x average required
Session Settings
Default: 9:30 AM - 11:30 AM ET (adjustable)
Avoids first 15 minutes after market open
Customizable trading hours
Safety Filters (Default Configuration)
✅ Mean Reversion: Enabled (2.5σ max from VWAP)
✅ ATR Spike: Enabled (2.0x threshold)
❌ EMA Spacing: Disabled (can enable for quality)
❌ Momentum: Disabled (can enable for quality)
❌ MTF Confirmation: Disabled (can enable for quality)
Risk Controls
Minimum Signal Quality: C (adjustable to A+ for fewer/better signals)
Min Bars Between Signals: 10
Max Trades Per Day: 5
Stop After Consecutive Losses: 2
📈 Expected PerformanceWith Default Settings:
Signals per week: 10-15 trades
Estimated win rate: 55-60%
Risk-Reward: 1:2 (TP1) and 1:3 (TP2)
With Aggressive Settings (Min Quality = D, All Filters Off):
Signals per week: 20-25 trades
Estimated win rate: 50-55%
With Conservative Settings (Min Quality = A, All Filters On):
Signals per week: 3-5 trades
Estimated win rate: 65-70%
🚀 How to UseBasic Setup:
Add indicator to MNQ 5-minute chart
Adjust TopStep account settings in inputs
Set your risk per trade percentage (default: 0.5%)
Configure trading session hours
Set minimum signal quality (Start with C for balanced results)
Signal Interpretation:
Green Triangle (BUY): Long signal - all confirmations aligned
Red Triangle (SELL): Short signal - all confirmations aligned
Label Details: Shows entry, stop loss, take profit levels, position size, and signal grade
Signal Grade: A+ = Elite (6-7 points) | A = Strong (5) | B = Good (4) | C = Fair (3)
Dashboard Monitoring:
Top Right: Technical metrics and market conditions
Top Left: Filter status (which filters are passing/blocking)
Bottom Right: TopStep risk metrics and position sizing
⚡ Customization TipsFor More Signals:
Lower "Minimum Signal Quality" to D
Decrease ADX threshold to 18-20
Lower RSI thresholds to 50/50
Reduce Volume multiplier to 1.1x
Disable additional filters
For Higher Quality (Fewer Signals):
Raise "Minimum Signal Quality" to A or A+
Increase ADX threshold to 25-30
Enable all 5 advanced filters
Tighten VWAP distance to 2.0σ
Increase momentum requirement to 3-4 bars
For TopStep Compliance:
Adjust "Max Total Drawdown" and "Daily Loss Limit" to match your account
Update "Already Used Drawdown" daily
Monitor the Risk Panel for cushion remaining
Use recommended contract sizing
🛡️ Risk DisclaimerIMPORTANT: This indicator is for educational and informational purposes only.
Past performance does not guarantee future results
All trading involves substantial risk of loss
Use proper risk management and position sizing
Test thoroughly in paper trading before live use
The indicator does not guarantee profitable trades
Adjust settings based on your risk tolerance and trading style
Always comply with your broker's and TopStep's rules
MULTI-CONDITION RSI SIGNAL GENERATOR═══════════════════════════════════════════════
MULTI-CONDITION RSI SIGNAL GENERATOR
═══════════════════════════════════════════════
OVERVIEW:
This indicator generates trading signals based on Relative Strength Index (RSI) movements with multiple confirmation layers designed to filter false signals and identify high-probability reversal opportunities.
═══════════════════════════════════════════════
WHAT MAKES THIS ORIGINAL:
═══════════════════════════════════════════════
Unlike basic RSI indicators that simply plot overbought/oversold crossovers, this system combines FOUR distinct confirmation mechanisms:
1. PERSISTENCE FILTERING - Requires RSI to remain in extreme zones for a minimum duration
2. LOOKBACK VALIDATION - Verifies recent extreme zone visits before signaling
3. DIVERGENCE DETECTION - Identifies price/RSI divergence for stronger signals
4. MOMENTUM CONFIRMATION - Provides trend-continuation entries via midline crosses
This multi-layered approach significantly reduces whipsaw trades that plague simple RSI crossover systems.
═══════════════════════════════════════════════
HOW IT WORKS (TECHNICAL METHODOLOGY):
═══════════════════════════════════════════════
STEP 1: RSI CALCULATION
- Standard RSI calculation using user-defined period (default: 14)
- Monitors two extreme zones: Overbought (default: 70) and Oversold (default: 30)
STEP 2: PERSISTENCE FILTERING
The script counts how many bars RSI has spent in extreme zones within the lookback period:
- For overbought signals: Counts bars where RSI > 70
- For oversold signals: Counts bars where RSI < 30
- Signal only triggers if count >= Minimum Duration (default: 4 bars)
This filters out brief spikes that immediately reverse, focusing on sustained extreme conditions that are more likely to lead to genuine reversals.
STEP 3: LOOKBACK VALIDATION
- Checks if RSI reached extreme zones within the Lookback Bars period (default: 20)
- Uses ta.highest() and ta.lowest() functions to verify recent extremes
- Ensures we're trading reversals from meaningful extremes, not random crossovers
STEP 4: BASIC SIGNAL GENERATION
- BUY SIGNAL: RSI crosses above the oversold level (30) after meeting persistence and lookback conditions
- SELL SIGNAL: RSI crosses below the overbought level (70) after meeting persistence and lookback conditions
STEP 5: DIVERGENCE DETECTION
The script identifies two types of divergence over the Divergence Lookback period (default: 5 bars):
A) BULLISH DIVERGENCE (indicates potential upward reversal):
   - Price makes a lower low (current low < previous low)
   - RSI makes a higher low (current RSI low > previous RSI low)
   - Suggests weakening downward momentum
B) BEARISH DIVERGENCE (indicates potential downward reversal):
   - Price makes a higher high (current high > previous high)
   - RSI makes a lower high (current RSI high < previous RSI high)
   - Suggests weakening upward momentum
STEP 6: STRONG SIGNAL CONFIRMATION
- STRONG BUY: Basic buy signal + bullish divergence present
- STRONG SELL: Basic sell signal + bearish divergence present
- These represent the highest-probability setups
STEP 7: MOMENTUM SIGNALS (OPTIONAL)
- MOMENTUM BUY: RSI crosses above 50 after being oversold (trend continuation)
- MOMENTUM SELL: RSI crosses below 50 after being overbought (trend continuation)
- Smaller signals for traders who want trend-following entries
═══════════════════════════════════════════════
SIGNAL TYPES AND VISUAL INDICATORS:
═══════════════════════════════════════════════
📈 GREEN TRIANGLE (below bar) - Standard Buy Signal
   RSI crossed above oversold level with confirmation filters
📉 RED TRIANGLE (above bar) - Standard Sell Signal
   RSI crossed below overbought level with confirmation filters
🔵 BLUE TRIANGLE (below bar) - Strong Buy Signal
   Buy signal + bullish divergence (HIGHEST PRIORITY)
🟣 PURPLE TRIANGLE (above bar) - Strong Sell Signal
   Sell signal + bearish divergence (HIGHEST PRIORITY)
🟢 GREEN CIRCLE (small) - Momentum Buy
   RSI crosses above 50 after oversold conditions
🔴 RED CIRCLE (small) - Momentum Sell
   RSI crosses below 50 after overbought conditions
BACKGROUND SHADING:
- Light red background: RSI currently overbought
- Light green background: RSI currently oversold
═══════════════════════════════════════════════
PARAMETER SETTINGS:
═══════════════════════════════════════════════
1. OVERBOUGHT LEVEL (default: 70, range: 50-90)
   - Higher values = fewer but stronger overbought signals
   - Lower values = more sensitive to overbought conditions
   - Recommended: 70 for standard markets, 80 for crypto/volatile assets
2. OVERSOLD LEVEL (default: 30, range: 10-50)
   - Lower values = fewer but stronger oversold signals
   - Higher values = more sensitive to oversold conditions
   - Recommended: 30 for standard markets, 20 for crypto/volatile assets
3. RSI PERIOD (default: 14, range: 2-50)
   - Standard RSI calculation period
   - Lower = more sensitive/faster signals
   - Higher = smoother/slower signals
   - Recommended: 14 (industry standard)
4. MINIMUM DURATION (default: 4, range: 1-20)
   - Required bars in extreme zone before signal
   - Higher values = fewer signals but better quality
   - Lower values = more signals but more false positives
   - Recommended: 3-5 for day trading, 5-10 for swing trading
5. LOOKBACK BARS (default: 20, range: 5-100)
   - How far back to check for extreme zone visits
   - Should match your typical trading timeframe
   - Recommended: 20 for intraday, 50 for daily charts
6. DIVERGENCE LOOKBACK (default: 5, range: 2-20)
   - Period for comparing price/RSI highs and lows
   - Lower values = more frequent divergence signals
   - Higher values = more significant divergences
   - Recommended: 5-10 depending on timeframe
═══════════════════════════════════════════════
HOW TO USE THIS INDICATOR:
═══════════════════════════════════════════════
RECOMMENDED TRADING APPROACH:
1. PRIMARY ENTRIES: Focus on Strong Buy/Sell signals (blue/purple triangles)
   - These have the highest win rate due to divergence confirmation
   - Wait for price action confirmation (support/resistance, candlestick patterns)
2. SECONDARY ENTRIES: Regular Buy/Sell signals (green/red triangles)
   - Use these when Strong signals are infrequent
   - Require additional confirmation from other indicators or chart patterns
3. TREND CONTINUATION: Momentum signals (small circles)
   - Best used when overall trend is clear
   - Not recommended for reversal trading
4. FILTER TRADES: Use background shading as context
   - Be cautious entering longs when background is red (overbought)
   - Be cautious entering shorts when background is green (oversold)
RISK MANAGEMENT GUIDELINES:
- Never risk more than 2-5% of capital per trade
- Use stop losses below recent swing lows (buys) or above swing highs (sells)
- Target at least 1.5:1 reward-to-risk ratio
- Consider position sizing based on signal strength
TIMEFRAME RECOMMENDATIONS:
- 15min - 1hour: Day trading with adjusted parameters (lower minimum duration)
- 4hour - Daily: Swing trading with default parameters
- Weekly: Position trading with increased lookback periods
COMPLEMENTARY TOOLS:
This indicator works best when combined with:
- Support and resistance levels
- Trend indicators (moving averages, trend lines)
- Volume analysis
- Price action patterns (engulfing candles, pin bars)
═══════════════════════════════════════════════
LIMITATIONS AND CONSIDERATIONS:
═══════════════════════════════════════════════
- This is NOT a standalone trading system - requires additional analysis
- RSI-based strategies perform best in ranging/choppy markets
- May generate fewer signals in strong trending markets
- Divergence signals can be early - wait for price confirmation
- Not recommended for highly illiquid assets
- Backtest on your specific market before live trading
- No indicator is 100% accurate - always use proper risk management
═══════════════════════════════════════════════
TECHNICAL NOTES:
═══════════════════════════════════════════════
- Code is original and does not reuse external libraries
- Uses Pine Script v5 native functions only
- Alert conditions included for all signal types
- No repainting - signals appear and remain fixed
- Efficient calculation methods minimize processing load
═══════════════════════════════════════════════
ALERT SETUP:
═══════════════════════════════════════════════
Four alert conditions are available:
1. "Buy Alert" - Triggers on standard buy signals
2. "Sell Alert" - Triggers on standard sell signals
3. "Strong Buy Alert" - Triggers on divergence-confirmed buy signals
4. "Strong Sell Alert" - Triggers on divergence-confirmed sell signals
To set up alerts: Right-click chart → Add Alert → Select desired condition
═══════════════════════════════════════════════
This indicator is provided for educational and informational purposes. Always practice proper risk management and never trade with money you cannot afford to lose.






















