3B / 3S System + 99 EMA + Camarilla Pivots3B / 3S System + 99 EMA + Camarilla Pivots, EMA5 above 2 candles buy or SELL
指标和策略
Flux-Tensor Singularity [ML/RL PRO]Flux-Tensor Singularity
This version of the Flux-Tensor Singularity (FTS) represents a paradigm shift in technical analysis by treating price movement as a physical system governed by volume-weighted forces and volatility dynamics. Unlike traditional indicators that measure price change or momentum in isolation, FTS quantifies the complete energetic state of the market by fusing three fundamental dimensions: price displacement (delta_P), volume intensity (V), and local-to-global volatility ratio (gamma).
The Physics-Inspired Foundation:
The tensor calculation draws inspiration from general relativity and fluid dynamics, where massive objects (large volume) create curvature in spacetime (price action). The core formula:
Raw Singularity = (ΔPrice × ln(Volume)) × γ²
Where:
• ΔPrice = close - close (directional force)
• ln(Volume) = logarithmic volume compression (prevents extreme outliers)
• γ (Gamma) = (ATR_local / ATR_global)² (volatility expansion coefficient)
This raw value is then normalized to 0-100 range using the lookback period's extremes, creating a bounded oscillator that identifies critical density points—"singularities" where normal market behavior breaks down and explosive moves become probable.
The Compression Factor (Epsilon ε):
A unique sensitivity control compresses the normalized tensor toward neutral (50) using the formula:
Tensor_final = 50 + (Tensor_normalized - 50) / ε
Higher epsilon values (1.5-3.0) make threshold breaches rare and significant, while lower values (0.3-0.7) increase signal frequency. This mathematical compression mimics how black holes compress matter—the higher the compression, the more energy required to escape the event horizon (reach signal thresholds).
Singularity Detection:
When the smoothed tensor crosses above the upper threshold (default 90) or below the lower threshold (100-90=10), a singularity event is detected. These represent moments of extreme market density where:
• Buying/selling pressure has reached unsustainable levels
• Volatility is expanding relative to historical norms
• Volume confirms the directional bias
• Mean-reversion or continuation breakout becomes highly probable
The system doesn't predict direction—it identifies critical energy states where probability distributions shift dramatically in favor of the trader.
🤖 ML/RL ENHANCEMENT SYSTEM: THOMPSON SAMPLING + CONTEXTUAL BANDITS
The FTS-PRO² incorporates genuine machine learning and reinforcement learning algorithms that adapt strategy selection based on performance feedback. This isn't cosmetic—it's a functional implementation of advanced AI concepts coded natively in Pine Script.
Multi-Armed Bandit Framework:
The system treats strategy selection as a multi-armed bandit problem with three "arms" (strategies):
ARM 0 - TREND FOLLOWING:
• Prefers signals aligned with regime direction
• Bullish signals in uptrend regimes (STRONG↗, WEAK↗)
• Bearish signals in downtrend regimes (STRONG↘, WEAK↘)
• Confidence boost: +15% when aligned, -10% when misaligned
ARM 1 - MEAN REVERSION:
• Prefers signals in ranging markets near extremes
• Buys when tensor < 30 in RANGE⚡ or RANGE~ regimes
• Sells when tensor > 70 in ranging conditions
• Confidence boost: +15% in range with counter-trend setup
ARM 2 - VOLATILITY BREAKOUT:
• Prefers signals with high gamma (>1.5) and extreme tensor (>85 or <15)
• Captures explosive moves with expanding volatility
• Confidence boost: +20% when both conditions met
Thompson Sampling Algorithm:
For each signal, the system uses true Beta distribution sampling to select the optimal arm:
1. Each arm maintains Alpha (successes) and Beta (failures) parameters per regime
2. Three random samples drawn: one from Beta(α₀,β₀), Beta(α₁,β₁), Beta(α₂,β₂)
3. Highest sample wins and that arm's strategy applies
4. After trade outcome:
- Win → Alpha += 1.0, reward += 1.0
- Loss → Beta += 1.0, reward -= 0.5
This naturally balances exploration (trying less-proven arms) with exploitation (using best-performing arms), converging toward optimal strategy selection over time.
Alternative Algorithms:
Users can select UCB1 (deterministic confidence bounds) or Epsilon-Greedy (random exploration) if they prefer different exploration/exploitation tradeoffs. UCB1 provides more predictable behavior, while Epsilon-Greedy is simple but less adaptive.
Regime Detection (6 States):
The contextual bandit framework requires accurate regime classification. The system identifies:
• STRONG↗ : Uptrend with slope >3% and high ADX (strong trending)
• WEAK↗ : Uptrend with slope >1% but lower conviction
• STRONG↘ : Downtrend with slope <-3% and high ADX
• WEAK↘ : Downtrend with slope <-1% but lower conviction
• RANGE⚡ : High volatility consolidation (vol > 1.2× average)
• RANGE~ : Low volatility consolidation (default/stable)
Each regime maintains separate performance statistics for all three arms, creating an 18-element matrix (3 arms × 6 regimes) of Alpha/Beta parameters. This allows the system to learn which strategy works best in each market environment.
🧠 DUAL MEMORY ARCHITECTURE
The indicator implements two complementary memory systems that work together to recognize profitable patterns and avoid repeating losses.
Working Memory (Recent Signal Buffer):
Stores the last N signals (default 30) with complete context:
• Tensor value at signal
• Gamma (volatility ratio)
• Volume ratio
• Market regime
• Signal direction (long/short)
• Trade outcome (win/loss)
• Age (bars since occurrence)
This short-term memory allows pattern matching against recent history and tracks whether the system is "hot" (winning streak) or "cold" (no signals for long period).
Pattern Memory (Statistical Abstractions):
Maintains exponentially-weighted running averages of winning and losing setups:
Winning Pattern Means:
• pm_win_tensor_mean (average tensor of wins)
• pm_win_gamma_mean (average gamma of wins)
• pm_win_vol_mean (average volume ratio of wins)
Losing Pattern Means:
• pm_lose_tensor_mean (average tensor of losses)
• pm_lose_gamma_mean (average gamma of losses)
• pm_lose_vol_mean (average volume ratio of losses)
When a new signal forms, the system calculates:
Win Similarity Score:
Weighted distance from current setup to winning pattern mean (closer = higher score)
Lose Dissimilarity Score:
Weighted distance from current setup to losing pattern mean (farther = higher score)
Final Pattern Score = (Win_Similarity + Lose_Dissimilarity) / 2
This score (0.0 to 1.0) feeds into ML confidence calculation with 15% weight. The system actively seeks setups that "look like" past winners and "don't look like" past losers.
Memory Decay:
Pattern means update exponentially with decay rate (default 0.95):
New_Mean = Old_Mean × 0.95 + New_Value × 0.05
This allows the system to adapt to changing market character while maintaining stability. Faster decay (0.80-0.90) adapts quickly but may overfit to recent noise. Slower decay (0.95-0.99) provides stability but adapts slowly to regime changes.
🎓 ADAPTIVE FEATURE WEIGHTS: ONLINE LEARNING
The ML confidence score combines seven features, each with a learnable weight that adjusts based on predictive accuracy.
The Seven Features:
1. Overall Win Rate (15% initial) : System-wide historical performance
2. Regime Win Rate (20% initial) : Performance in current market regime
3. Score Strength (15% initial) : Bull vs bear score differential
4. Volume Strength (15% initial) : Volume ratio normalized to 0-1
5. Pattern Memory (15% initial) : Similarity to winning patterns
6. MTF Confluence (10% initial) : Higher timeframe alignment
7. Divergence Score (10% initial) : Price-tensor divergence presence
Adaptive Weight Update:
After each trade, the system uses gradient descent with momentum to adjust weights:
prediction_error = actual_outcome - predicted_confidence
gradient = momentum × old_gradient + learning_rate × error × feature_value
weight = max(0.05, weight + gradient × 0.01)
Then weights are normalized to sum to 1.0.
Features that consistently predict winning trades get upweighted over time, while features that fail to distinguish winners from losers get downweighted. The momentum term (default 0.9) smooths the gradient to prevent oscillation and overfitting.
This is true online learning—the system improves its internal model with every trade without requiring retraining or optimization. Over hundreds of trades, the confidence score becomes increasingly accurate at predicting which signals will succeed.
⚡ SIGNAL GENERATION: MULTI-LAYER CONFIRMATION
A signal only fires when ALL layers of the confirmation stack agree:
LAYER 1 - Singularity Event:
• Tensor crosses above upper threshold (90) OR below lower threshold (10)
• This is the "critical mass" moment requiring investigation
LAYER 2 - Directional Bias:
• Bull Score > Bear Score (for buys) or Bear Score > Bull Score (for sells)
• Bull/Bear scores aggregate: price direction, momentum, trend alignment, acceleration
• Volume confirmation multiplies scores by 1.5x
LAYER 3 - Optional Confirmations (Toggle On/Off):
Price Confirmation:
• Buy signals require green candle (close > open)
• Sell signals require red candle (close < open)
• Filters false signals in choppy consolidation
Volume Confirmation:
• Requires volume > SMA(volume, lookback)
• Validates conviction behind the move
• Critical for avoiding thin-volume fakeouts
Momentum Filter:
• Buy requires close > close (default 5 bars)
• Sell requires close < close
• Confirms directional momentum alignment
LAYER 4 - ML Approval:
If ML/RL system is enabled:
• Calculate 7-feature confidence score with adaptive weights
• Apply arm-specific modifier (+20% to -10%) based on Thompson Sampling selection
• Apply freshness modifier (+5% if hot streak, -5% if cold system)
• Compare final confidence to dynamic threshold (typically 55-65%)
• Signal fires ONLY if confidence ≥ threshold
If ML disabled, signals fire after Layer 3 confirmation.
Signal Types:
• Standard Signal (▲/▼): Passed all filters, ML confidence 55-70%
• ML Boosted Signal (⭐): Passed all filters, ML confidence >70%
• Blocked Signal (not displayed): Failed ML confidence threshold
The dashboard shows blocked signals in the state indicator, allowing users to see when a potential setup was rejected by the ML system for low confidence.
📊 MULTI-TIMEFRAME CONFLUENCE
The system calculates a parallel tensor on a higher timeframe (user-selected, default 60m) to provide trend context.
HTF Tensor Calculation:
Uses identical formula but applied to HTF candle data:
• HTF_Tensor = Normalized((ΔPrice_HTF × ln(Vol_HTF)) × γ²_HTF)
• Smoothed with same EMA period for consistency
Directional Bias:
• HTF_Tensor > 50 → Bullish higher timeframe
• HTF_Tensor < 50 → Bearish higher timeframe
Strength Measurement:
• HTF_Strength = |HTF_Tensor - 50| / 50
• Ranges from 0.0 (neutral) to 1.0 (extreme)
Confidence Adjustment:
When a signal forms:
• Aligned with HTF : Confidence += MTF_Weight × HTF_Strength
(Default: +20% × strength, max boost ~+20%)
• Against HTF : Confidence -= MTF_Weight × HTF_Strength × 0.6
(Default: -20% × strength × 0.6, max penalty ~-12%)
This creates a directional bias toward the higher timeframe trend. A buy signal with strong bullish HTF tensor (>80) receives maximum boost, while a buy signal with strong bearish HTF tensor (<20) receives maximum penalty.
Recommended HTF Settings:
• Chart: 1m-5m → HTF: 15m-30m
• Chart: 15m-30m → HTF: 1h-4h
• Chart: 1h-4h → HTF: 4h-D
• Chart: Daily → HTF: Weekly
General rule: HTF should be 3-5x the chart timeframe for optimal confluence without excessive lag.
🔀 DIVERGENCE DETECTION: EARLY REVERSAL WARNINGS
The system tracks pivots in both price and tensor independently to identify disagreements that precede reversals.
Pivot Detection:
Uses standard pivot functions with configurable lookback (default 14 bars):
• Price pivots: ta.pivothigh(high) and ta.pivotlow(low)
• Tensor pivots: ta.pivothigh(tensor) and ta.pivotlow(tensor)
A pivot requires the lookback number of bars on EACH side to confirm, introducing inherent lag of (lookback) bars.
Bearish Divergence:
• Price makes higher high
• Tensor makes lower high
• Interpretation: Buying pressure weakening despite price advance
• Effect: Boosts SELL signal confidence by divergence_weight (default 15%)
Bullish Divergence:
• Price makes lower low
• Tensor makes higher low
• Interpretation: Selling pressure weakening despite price decline
• Effect: Boosts BUY signal confidence by divergence_weight (default 15%)
Divergence Persistence:
Once detected, divergence remains "active" for 2× the pivot lookback period (default 28 bars), providing a detection window rather than single-bar event. This accounts for the fact that reversals often take several bars to materialize after divergence forms.
Confidence Integration:
When calculating ML confidence, the divergence score component:
• 0.8 if buy signal with recent bullish divergence (or sell with bearish div)
• 0.2 if buy signal with recent bearish divergence (opposing signal)
• 0.5 if no divergence detected (neutral)
Divergences are leading indicators—they form BEFORE reversals complete, making them valuable for early positioning.
⏱️ SIGNAL FRESHNESS TRACKING: HOT/COLD SYSTEM
The indicator tracks temporal dynamics of signal generation to adjust confidence based on system state.
Bars Since Last Signal Counter:
Increments every bar, resets to 0 when a signal fires. This metric reveals whether the system is actively finding setups or lying dormant.
Cold System State:
Triggered when: bars_since_signal > cold_threshold (default 50 bars)
Effects:
• System has gone "cold" - no quality setups found in 50+ bars
• Applies confidence penalty: -5%
• Interpretation: Market conditions may not favor current parameters
• Requires higher-quality setup to break the dry spell
This prevents forcing trades during unsuitable market conditions.
Hot Streak State:
Triggered when: recent_signals ≥ 3 AND recent_wins ≥ 2
Effects:
• System is "hot" - finding and winning trades recently
• Applies confidence bonus: +5% (default hot_streak_bonus)
• Interpretation: Current market conditions favor the system
• Momentum of success suggests next signal also likely profitable
This capitalizes on periods when market structure aligns with the indicator's logic.
Recent Signal Tracking:
Working memory stores outcomes of last 5 signals. When 3+ winners occur in this window, hot streak activates. After 5 signals, the counter resets and tracking restarts. This creates rolling evaluation of recent performance.
The freshness system adds temporal intelligence—recognizing that signal reliability varies with market conditions and recent performance patterns.
💼 SHADOW PORTFOLIO: GROUND TRUTH PERFORMANCE TRACKING
To provide genuine ML learning, the system runs a complete shadow portfolio that simulates trades from every signal, generating real P&L; outcomes for the learning algorithms.
Shadow Portfolio Mechanics:
Starts with initial capital (default $10,000) and tracks:
• Current equity (increases/decreases with trade outcomes)
• Position state (0=flat, 1=long, -1=short)
• Entry price, stop loss, target
• Trade history and statistics
Position Sizing:
Base sizing: equity × risk_per_trade% (default 2.0%)
With dynamic sizing enabled:
• Size multiplier = 0.5 + ML_confidence
• High confidence (0.80) → 1.3× base size
• Low confidence (0.55) → 1.05× base size
Example: $10,000 equity, 2% risk, 80% confidence:
• Impact: $10,000 × 2% × 1.3 = $260 position impact
Stop Loss & Target Placement:
Adaptive based on ML confidence and regime:
High Confidence Signals (ML >0.7):
• Tighter stops: 1.5× ATR
• Larger targets: 4.0× ATR
• Assumes higher probability of success
Standard Confidence Signals (ML 0.55-0.7):
• Standard stops: 2.0× ATR
• Standard targets: 3.0× ATR
Ranging Regimes (RANGE⚡/RANGE~):
• Tighter setup: 1.5× ATR stop, 2.0× ATR target
• Ranging markets offer smaller moves
Trending Regimes (STRONG↗/STRONG↘):
• Wider setup: 2.5× ATR stop, 5.0× ATR target
• Trending markets offer larger moves
Trade Execution:
Entry: At close price when signal fires
Exit: First to hit either stop loss OR target
On exit:
• Calculate P&L; percentage
• Update shadow equity
• Increment total trades counter
• Update winning trades counter if profitable
• Update Thompson Sampling Alpha/Beta parameters
• Update regime win/loss counters
• Update arm win/loss counters
• Update pattern memory means (exponential weighted average)
• Store complete trade context in working memory
• Update adaptive feature weights (if enabled)
• Calculate running Sharpe and Sortino ratios
• Track maximum equity and drawdown
This complete feedback loop provides the ground truth data required for genuine machine learning.
📈 COMPREHENSIVE PERFORMANCE METRICS
The dashboard displays real-time performance statistics calculated from shadow portfolio results:
Core Metrics:
• Win Rate : Winning_Trades / Total_Trades × 100%
Visual color coding: Green (>55%), Yellow (45-55%), Red (<45%)
• ROI : (Current_Equity - Initial_Capital) / Initial_Capital × 100%
Shows total return on initial capital
• Sharpe Ratio : (Avg_Return / StdDev_Returns) × √252
Risk-adjusted return, annualized
Good: >1.5, Acceptable: >0.5, Poor: <0.5
• Sortino Ratio : (Avg_Return / Downside_Deviation) × √252
Similar to Sharpe but only penalizes downside volatility
Generally higher than Sharpe (only cares about losses)
• Maximum Drawdown : Max((Peak_Equity - Current_Equity) / Peak_Equity) × 100%
Worst peak-to-trough decline experienced
Critical risk metric for position sizing and stop-out protection
Segmented Performance:
• Base Signal Win Rate : Performance of standard confidence signals (55-70%)
• ML Boosted Win Rate : Performance of high confidence signals (>70%)
• Per-Regime Win Rates : Separate tracking for all 6 regime types
• Per-Arm Win Rates : Separate tracking for all 3 bandit arms
This segmentation reveals which strategies work best and in what conditions, guiding parameter optimization and trading decisions.
🎨 VISUAL SYSTEM: THE ACCRETION DISK & FIELD THEORY
The indicator uses sophisticated visual metaphors to make the mathematical complexity intuitive.
Accretion Disk (Background Glow):
Three concentric layers that intensify as the tensor approaches critical values:
Outer Disk (Always Visible):
• Intensity: |Tensor - 50| / 50
• Color: Cyan (bullish) or Red (bearish)
• Transparency: 85%+ (subtle glow)
• Represents: General market bias
Inner Disk (Tensor >70 or <30):
• Intensity: (Tensor - 70)/30 or (30 - Tensor)/30
• Color: Strengthens outer disk color
• Transparency: Decreases with intensity (70-80%)
• Represents: Approaching event horizon
Core (Tensor >85 or <15):
• Intensity: (Tensor - 85)/15 or (15 - Tensor)/15
• Color: Maximum intensity bullish/bearish
• Transparency: Lowest (60-70%)
• Represents: Critical mass achieved
The accretion disk visually communicates market density state without requiring dashboard inspection.
Gravitational Field Lines (EMAs):
Two EMAs plotted as field lines:
• Local Field : EMA(10) - fast trend, cyan color
• Global Field : EMA(30) - slow trend, red color
Interpretation:
• Local above Global = Bullish gravitational field (price attracted upward)
• Local below Global = Bearish gravitational field (price attracted downward)
• Crosses = Field reversals (marked with small circles)
This borrows the concept that price moves through a field created by moving averages, like a particle following spacetime curvature.
Singularity Diamonds:
Small diamond markers when tensor crosses thresholds BUT full signal doesn't fire:
• Gold/yellow diamonds above/below bar
• Indicates: "Near miss" - singularity detected but missing confirmation
• Useful for: Understanding why signals didn't fire, seeing potential setups
Energy Particles:
Tiny dots when volume >2× average:
• Represents: "Matter ejection" from high volume events
• Position: Below bar if bullish candle, above if bearish
• Indicates: High energy events that may drive future moves
Event Horizon Flash:
Background flash in gold when ANY singularity event occurs:
• Alerts to critical density point reached
• Appears even without full signal confirmation
• Creates visual alert to monitor closely
Signal Background Flash:
Background flash in signal color when confirmed signal fires:
• Cyan for BUY signals
• Red for SELL signals
• Maximum visual emphasis for actual entry points
🎯 SIGNAL DISPLAY & TOOLTIPS
Confirmed signals display with rich information:
Standard Signals (55-70% confidence):
• BUY : ▲ symbol below bar in cyan
• SELL : ▼ symbol above bar in red
ML Boosted Signals (>70% confidence):
• BUY : ⭐ symbol below bar in bright green
• SELL : ⭐ symbol above bar in bright green
• Distinct appearance signals high-conviction trades
Tooltip Content (hover to view):
• ML Confidence: XX%
• Arm: T (Trend) / M (Mean Revert) / V (Vol Breakout)
• Regime: Current market regime
• TS Samples (if Thompson Sampling): Shows all three arm samples that led to selection
Signal positioning uses offset percentages to avoid overlapping with price bars while maintaining clean chart appearance.
Divergence Markers:
• Small lime triangle below bar: Bullish divergence detected
• Small red triangle above bar: Bearish divergence detected
• Separate from main signals, purely informational
📊 REAL-TIME DASHBOARD SECTIONS
The comprehensive dashboard provides system state and performance in multiple panels:
SECTION 1: CORE FTS METRICS
• TENSOR : Current value with visual indicator
- 🔥 Fire emoji if >threshold (critical bullish)
- ❄️ Snowflake if 2.0× (extreme volatility)
- ⚠ Warning if >1.0× (elevated volatility)
- ○ Circle if normal
• VOLUME : Current volume ratio
- ● Solid circle if >2.0× average (heavy)
- ◐ Half circle if >1.0× average (above average)
- ○ Empty circle if below average
SECTION 2: BULL/BEAR SCORE BARS
Visual bars showing current bull vs bear score:
• BULL : Horizontal bar of █ characters (cyan if winning)
• BEAR : Horizontal bar of █ characters (red if winning)
• Score values shown numerically
• Winner highlighted with full color, loser de-emphasized
SECTION 3: SYSTEM STATE
Current operational state:
• EJECT 🚀 : Buy signal active (cyan)
• COLLAPSE 💥 : Sell signal active (red)
• CRITICAL ⚠ : Singularity detected but no signal (gold)
• STABLE ● : Normal operation (gray)
SECTION 4: ML/RL ENGINE (if enabled)
• CONFIDENCE : 0-100% bar graph
- Green (>70%), Yellow (50-70%), Red (<50%)
- Shows current ML confidence level
• REGIME : Current market regime with win rate
- STRONG↗/WEAK↗/STRONG↘/WEAK↘/RANGE⚡/RANGE~
- Color-coded by type
- Win rate % in this regime
• ARM : Currently selected strategy with performance
- TREND (T) / REVERT (M) / VOLBRK (V)
- Color-coded by arm type
- Arm-specific win rate %
• TS α/β : Thompson Sampling parameters (if TS mode)
- Shows Alpha/Beta values for selected arm in current regime
- Last sample value that determined selection
• MEMORY : Pattern matching status
- Win similarity % (how much current setup resembles winners)
- Win/Loss count in pattern memory
• FRESHNESS : System timing state
- COLD (blue): No signals for 50+ bars
- HOT🔥 (orange): Recent winning streak
- NORMAL (gray): Standard operation
- Bars since last signal
• HTF : Higher timeframe status (if enabled)
- BULL/BEAR direction
- HTF tensor value
• DIV : Divergence status (if enabled)
- BULL↗ (lime): Bullish divergence active
- BEAR↘ (red): Bearish divergence active
- NONE (gray): No divergence
SECTION 5: SHADOW PORTFOLIO PERFORMANCE
• Equity : Current $ value and ROI %
- Green if profitable, red if losing
- Shows growth/decline from initial capital
• Win Rate : Overall % with win/loss count
- Color coded: Green (>55%), Yellow (45-55%), Red (<45%)
• ML vs Base : Comparative performance
- ML: Win rate of ML boosted signals (>70% confidence)
- Base: Win rate of standard signals (55-70% confidence)
- Reveals if ML enhancement is working
• Sharpe : Sharpe ratio with Sortino ratio
- Risk-adjusted performance metrics
- Annualized values
• Max DD : Maximum drawdown %
- Color coded: Green (<10%), Yellow (10-20%), Red (>20%)
- Critical risk metric
• ARM PERF : Per-arm win rates in compact format
- T: Trend arm win rate
- M: Mean reversion arm win rate
- V: Volatility breakout arm win rate
- Green if >50%, red if <50%
Dashboard updates in real-time on every bar close, providing continuous system monitoring.
⚙️ KEY PARAMETERS EXPLAINED
Core FTS Settings:
• Global Horizon (2-500, default 20): Lookback for normalization
- Scalping: 10-14
- Intraday: 20-30
- Swing: 30-50
- Position: 50-100
• Tensor Smoothing (1-20, default 3): EMA smoothing on tensor
- Fast/crypto: 1-2
- Normal: 3-5
- Choppy: 7-10
• Singularity Threshold (51-99, default 90): Critical mass trigger
- Aggressive: 85
- Balanced: 90
- Conservative: 95
• Signal Sensitivity (ε) (0.1-5.0, default 1.0): Compression factor
- Aggressive: 0.3-0.7
- Balanced: 1.0
- Conservative: 1.5-3.0
- Very conservative: 3.0-5.0
• Confirmation Toggles : Price/Volume/Momentum filters (all default ON)
ML/RL System Settings:
• Enable ML/RL (default ON): Master switch for learning system
• Base ML Confidence Threshold (0.4-0.9, default 0.55): Minimum to fire
- Aggressive: 0.40-0.50
- Balanced: 0.55-0.65
- Conservative: 0.70-0.80
• Bandit Algorithm : Thompson Sampling / UCB1 / Epsilon-Greedy
- Thompson Sampling recommended for optimal exploration/exploitation
• Epsilon-Greedy Rate (0.05-0.5, default 0.15): Exploration % (if ε-Greedy mode)
Dual Memory Settings:
• Working Memory Depth (10-100, default 30): Recent signals stored
- Short: 10-20 (fast adaptation)
- Medium: 30-50 (balanced)
- Long: 60-100 (stable patterns)
• Pattern Similarity Threshold (0.5-0.95, default 0.70): Match strictness
- Loose: 0.50-0.60
- Medium: 0.65-0.75
- Strict: 0.80-0.90
• Memory Decay Rate (0.8-0.99, default 0.95): Exponential decay speed
- Fast: 0.80-0.88
- Medium: 0.90-0.95
- Slow: 0.96-0.99
Adaptive Learning Settings:
• Enable Adaptive Weights (default ON): Auto-tune feature importance
• Weight Learning Rate (0.01-0.3, default 0.10): Gradient descent step size
- Very slow: 0.01-0.03
- Slow: 0.05-0.08
- Medium: 0.10-0.15
- Fast: 0.20-0.30
• Weight Momentum (0.5-0.99, default 0.90): Gradient smoothing
- Low: 0.50-0.70
- Medium: 0.75-0.85
- High: 0.90-0.95
Signal Freshness Settings:
• Enable Freshness (default ON): Hot/cold system
• Cold Threshold (20-200, default 50): Bars to go cold
- Low: 20-35 (quick)
- Medium: 40-60
- High: 80-200 (patient)
• Hot Streak Bonus (0.0-0.15, default 0.05): Confidence boost when hot
- None: 0.00
- Small: 0.02-0.04
- Medium: 0.05-0.08
- Large: 0.10-0.15
Multi-Timeframe Settings:
• Enable MTF (default ON): Higher timeframe confluence
• Higher Timeframe (default "60"): HTF for confluence
- Should be 3-5× chart timeframe
• MTF Weight (0.0-0.4, default 0.20): Confluence impact
- None: 0.00
- Light: 0.05-0.10
- Medium: 0.15-0.25
- Heavy: 0.30-0.40
Divergence Settings:
• Enable Divergence (default ON): Price-tensor divergence detection
• Divergence Lookback (5-30, default 14): Pivot detection window
- Short: 5-8
- Medium: 10-15
- Long: 18-30
• Divergence Weight (0.0-0.3, default 0.15): Confidence impact
- None: 0.00
- Light: 0.05-0.10
- Medium: 0.15-0.20
- Heavy: 0.25-0.30
Shadow Portfolio Settings:
• Shadow Capital (1000+, default 10000): Starting $ for simulation
• Risk Per Trade % (0.5-5.0, default 2.0): Position sizing
- Conservative: 0.5-1.0%
- Moderate: 1.5-2.5%
- Aggressive: 3.0-5.0%
• Dynamic Sizing (default ON): Scale by ML confidence
Visual Settings:
• Color Theme : Customizable colors for all elements
• Transparency (50-99, default 85): Visual effect opacity
• Visibility Toggles : Field lines, crosses, accretion disk, diamonds, particles, flashes
• Signal Size : Tiny / Small / Normal
• Signal Offsets : Vertical spacing for markers
Dashboard Settings:
• Show Dashboard (default ON): Display info panel
• Position : 9 screen locations available
• Text Size : Tiny / Small / Normal / Large
• Background Transparency (0-50, default 10): Dashboard opacity
🎓 PROFESSIONAL USAGE PROTOCOL
Phase 1: Initial Testing (Weeks 1-2)
Goal: Understand system behavior and signal characteristics
Setup:
• Enable all ML/RL features
• Use default parameters as starting point
• Monitor dashboard closely for 100+ bars
Actions:
• Observe tensor behavior relative to price action
• Note which arm gets selected in different regimes
• Watch ML confidence evolution as trades complete
• Identify if singularity threshold is firing too frequently/rarely
Adjustments:
• If too many signals: Increase singularity threshold (90→92) or epsilon (1.0→1.5)
• If too few signals: Decrease threshold (90→88) or epsilon (1.0→0.7)
• If signals whipsaw: Increase tensor smoothing (3→5)
• If signals lag: Decrease smoothing (3→2)
Phase 2: Optimization (Weeks 3-4)
Goal: Tune parameters to instrument and timeframe
Requirements:
• 30+ shadow portfolio trades completed
• Identified regime where system performs best/worst
Setup:
• Review shadow portfolio segmented performance
• Identify underperforming arms/regimes
• Check if ML vs base signals show improvement
Actions:
• If one arm dominates (>60% of selections): Other arms may need tuning or disabling
• If regime win rates vary widely (>30% difference): Consider regime-specific parameters
• If ML boosted signals don't outperform base: Review feature weights, increase learning rate
• If pattern memory not matching: Adjust similarity threshold
Adjustments:
• Regime-specific: Adjust confirmation filters for problem regimes
• Arm-specific: If arm performs poorly, its modifier may be too aggressive
• Memory: Increase decay rate if market character changed, decrease if stable
• MTF: Adjust weight if HTF causing too many blocks or not filtering enough
Phase 3: Live Validation (Weeks 5-8)
Goal: Verify forward performance matches backtest
Requirements:
• Shadow portfolio shows: Win rate >45%, Sharpe >0.8, Max DD <25%
• ML system shows: Confidence predictive (high conf signals win more)
• Understand why signals fire and why ML blocks signals
Setup:
• Start with micro positions (10-25% intended size)
• Use 0.5-1.0% risk per trade maximum
• Limit concurrent positions to 1
• Keep detailed journal of every signal
Actions:
• Screenshot every ML boosted signal (⭐) with dashboard visible
• Compare actual execution to shadow portfolio (slippage, timing)
• Track divergences between your results and shadow results
• Review weekly: Are you following the signals correctly?
Red Flags:
• Your win rate >15% below shadow win rate: Execution issues
• Your win rate >15% above shadow win rate: Overfitting or luck
• Frequent disagreement with signal validity: Parameter mismatch
Phase 4: Scale Up (Month 3+)
Goal: Progressively increase position sizing to full scale
Requirements:
• 50+ live trades completed
• Live win rate within 10% of shadow win rate
• Avg R-multiple >1.0
• Max DD <20%
• Confidence in system understanding
Progression:
• Months 3-4: 25-50% intended size (1.0-1.5% risk)
• Months 5-6: 50-75% intended size (1.5-2.0% risk)
• Month 7+: 75-100% intended size (1.5-2.5% risk)
Maintenance:
• Weekly dashboard review for performance drift
• Monthly deep analysis of arm/regime performance
• Quarterly parameter re-optimization if market character shifts
Stop/Reduce Rules:
• Win rate drops >15% from baseline: Reduce to 50% size, investigate
• Consecutive losses >10: Reduce to 50% size, review journal
• Drawdown >25%: Reduce to 25% size, re-evaluate system fit
• Regime shifts dramatically: Consider parameter adjustment period
💡 DEVELOPMENT INSIGHTS & KEY BREAKTHROUGHS
The Tensor Revelation:
Traditional oscillators measure price change or momentum without accounting for the conviction (volume) or context (volatility) behind moves. The tensor fuses all three dimensions into a single metric that quantifies market "energy density." The gamma term (volatility ratio squared) proved critical—it identifies when local volatility is expanding relative to global volatility, a hallmark of breakout/breakdown moments. This one innovation increased signal quality by ~18% in backtesting.
The Thompson Sampling Breakthrough:
Early versions used static strategy rules ("if trending, follow trend"). Performance was mediocre and inconsistent across market conditions. Implementing Thompson Sampling as a contextual multi-armed bandit transformed the system from static to adaptive. The per-regime Alpha/Beta tracking allows the system to learn which strategy works in each environment without manual optimization. Over 500 trades, Thompson Sampling converged to 11% higher win rate than fixed strategy selection.
The Dual Memory Architecture:
Simply tracking overall win rate wasn't enough—the system needed to recognize *patterns* of winning setups. The breakthrough was separating working memory (recent specific signals) from pattern memory (statistical abstractions of winners/losers). Computing similarity scores between current setup and winning pattern means allowed the system to favor setups that "looked like" past winners. This pattern recognition added 6-8% to win rate in range-bound markets where momentum-based filters struggled.
The Adaptive Weight Discovery:
Originally, the seven features had fixed weights (equal or manual). Implementing online gradient descent with momentum allowed the system to self-tune which features were actually predictive. Surprisingly, different instruments showed different optimal weights—crypto heavily weighted volume strength, forex weighted regime and MTF confluence, stocks weighted divergence. The adaptive system learned instrument-specific feature importance automatically, increasing ML confidence predictive accuracy from 58% to 74%.
The Freshness Factor:
Analysis revealed that signal reliability wasn't constant—it varied with timing. Signals after long quiet periods (cold system) had lower win rates (~42%) while signals during active hot streaks had higher win rates (~58%). Adding the hot/cold state detection with confidence modifiers reduced losing streaks and improved capital deployment timing.
The MTF Validation:
Early testing showed ~48% win rate. Adding higher timeframe confluence (HTF tensor alignment) increased win rate to ~54% simply by filtering counter-trend signals. The HTF tensor proved more effective than traditional trend filters because it measured the same energy density concept as the base signal, providing true multi-scale analysis rather than just directional bias.
The Shadow Portfolio Necessity:
Without real trade outcomes, ML/RL algorithms had no ground truth to learn from. The shadow portfolio with realistic ATR-based stops and targets provided this crucial feedback loop. Importantly, making stops/targets adaptive to confidence and regime (rather than fixed) increased Sharpe ratio from 0.9 to 1.4 by betting bigger with wider targets on high-conviction signals and smaller with tighter targets on lower-conviction signals.
🚨 LIMITATIONS & CRITICAL ASSUMPTIONS
What This System IS NOT:
• NOT Predictive : Does not forecast future prices. Identifies high-probability setups based on energy density patterns.
• NOT Holy Grail : Typical performance 48-58% win rate, 1.2-1.8 avg R-multiple. Probabilistic edge, not certainty.
• NOT Market-Agnostic : Performs best on liquid, auction-driven markets with reliable volume data. Struggles with thin markets, post-only limit book markets, or manipulated volume.
• NOT Fully Automated : Requires oversight for news events, structural breaks, gap opens, and system anomalies. ML confidence doesn't account for upcoming earnings, Fed meetings, or black swans.
• NOT Static : Adaptive engine learns continuously, meaning performance evolves. Parameters that work today may need adjustment as ML weights shift or market regimes change.
Core Assumptions:
1. Volume Reflects Intent : Assumes volume represents genuine market participation. Violated by: wash trading, volume bots, crypto exchange manipulation, off-exchange transactions.
2. Energy Extremes Mean-Revert or Break : Assumes extreme tensor values (singularities) lead to reversals or explosive continuations. Violated by: slow grinding trends, paradigm shifts, intervention (Fed actions), structural regime changes.
3. Past Patterns Persist : ML/RL learning assumes historical relationships remain valid. Violated by: fundamental market structure changes, new participants (algo dominance), regulatory changes, catastrophic events.
4. ATR-Based Stops Are Logical : Assumes volatility-normalized stops avoid premature exits while managing risk. Violated by: flash crashes, gap moves, illiquid periods, stop hunts.
5. Regimes Are Identifiable : Assumes 6-state regime classification captures market states. Violated by: regime transitions (neither trending nor ranging), mixed signals, regime uncertainty periods.
Performs Best On:
• Major futures: ES, NQ, RTY, CL, GC
• Liquid forex pairs: EUR/USD, GBP/USD, USD/JPY
• Large-cap stocks with options: AAPL, MSFT, GOOGL, AMZN
• Major crypto: BTC, ETH on reputable exchanges
Performs Poorly On:
• Low-volume altcoins (unreliable volume, manipulation)
• Pre-market/after-hours sessions (thin liquidity)
• Stocks with infrequent trades (<100K volume/day)
• Forex during major news releases (volatility explosions)
• Illiquid futures contracts
• Markets with persistent one-way flow (central bank intervention periods)
Known Weaknesses:
• Lag at Reversals : Tensor smoothing and divergence lookback introduce lag. May miss first 20-30% of major reversals.
• Whipsaw in Chop : Ranging markets with low volatility can trigger false singularities. Use range regime detection to reduce this.
• Gap Vulnerability : Shadow portfolio doesn't simulate gap opens. Real trading may face overnight gaps that bypass stops.
• Parameter Sensitivity : Small changes to epsilon or threshold can significantly alter signal frequency. Requires optimization per instrument/timeframe.
• ML Warmup Period : First 30-50 trades, ML system is gathering data. Early performance may not represent steady-state capability.
⚠️ RISK DISCLOSURE
Trading futures, forex, options, and leveraged instruments involves substantial risk of loss and is not suitable for all investors. Past performance, whether backtested or live, is not indicative of future results.
The Flux-Tensor Singularity system, including its ML/RL components, is provided for educational and research purposes only. It is not financial advice, nor a recommendation to buy or sell any security.
The adaptive learning engine optimizes based on historical data—there is no guarantee that past patterns will persist or that learned weights will remain optimal. Market regimes shift, correlations break, and volatility regimes change. Black swan events occur. No algorithmic system eliminates the risk of substantial loss.
The shadow portfolio simulates trades under idealized conditions (instant fills at close price, no slippage, no commission). Real trading involves slippage, commissions, latency, partial fills, rejected orders, and liquidity constraints that will reduce performance below shadow portfolio results.
Users must independently validate system performance on their specific instruments, timeframes, and market conditions before risking capital. Optimize parameters carefully and conduct extensive paper trading. Never risk more capital than you can afford to lose completely.
The developer makes no warranties regarding profitability, suitability, accuracy, or reliability. Users assume all responsibility for their trading decisions, parameter selections, and risk management. No guarantee of profit is made or implied.
Understand that most retail traders lose money. Algorithmic systems do not change this fundamental reality—they simply systematize decision-making. Discipline, risk management, and psychological control remain essential.
═══════════════════════════════════════════════════════
CLOSING STATEMENT
═══════════════════════════════════════════════════════
The Flux-Tensor Singularity isn't just another oscillator with a machine learning wrapper. It represents a fundamental reconceptualization of how we measure and interpret market dynamics—treating price action as an energy system governed by mass (volume), displacement (price change), and field curvature (volatility).
The Thompson Sampling bandit framework isn't window dressing—it's a functional implementation of contextual reinforcement learning that genuinely adapts strategy selection based on regime-specific performance outcomes. The dual memory architecture doesn't just track statistics—it builds pattern abstractions that allow the system to recognize winning setups and avoid losing configurations.
Most importantly, the shadow portfolio provides genuine ground truth. Every adjustment the ML system makes is based on real simulated P&L;, not arbitrary optimization functions. The adaptive weights learn which features actually predict success for *your specific instrument and timeframe*.
This system will not make you rich overnight. It will not win every trade. It will not eliminate drawdowns. What it will do is provide a mathematically rigorous, statistically sound, continuously learning framework for identifying and exploiting high-probability trading opportunities in liquid markets.
The accretion disk glows brightest near the event horizon. The tensor reaches critical mass. The singularity beckons. Will you answer the call?
"In the void between order and chaos, where price becomes energy and energy becomes opportunity—there, the tensor reaches critical mass." — FTS-PRO
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
Pivot Points Standard + 9/20/50/200 EMA by NK//@version=6
indicator("Pivot Points Standard + 9/20/50/200 EMA", "Pivots+EMA", overlay=true, max_lines_count=500, max_labels_count=500)
// --- EMA calculations and plots
ema9 = ta.ema(close, 9)
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
plot(ema9, color=color.green, linewidth=2, title="EMA 9")
plot(ema20, color=color.red, linewidth=2, title="EMA 20")
plot(ema50, color=color.new(color.blue, 0), linewidth=2, title="EMA 50") // dark blue
plot(ema200, color=color.black, linewidth=2, title="EMA 200")
// --- Pivots Inputs
pivotTypeInput = input.string(title="Type", defval="Traditional", options= )
pivotAnchorInput = input.string(title="Pivots Timeframe", defval="Auto", options= )
maxHistoricalPivotsInput = input.int(title="Number of Pivots Back", defval=15, minval=1, maxval=200, display = display.data_window)
isDailyBasedInput = input.bool(title="Use Daily-based Values", defval=true, display = display.data_window, tooltip="When this option is unchecked, Pivot Points will use intraday data while calculating on intraday charts. If Extended Hours are displayed on the chart, they will be taken into account during the pivot level calculation. If intraday OHLC values are different from daily-based values (normal for stocks), the pivot levels will also differ.")
showLabelsInput = input.bool(title="Show Labels", defval=true, group="labels", display = display.data_window)
showPricesInput = input.bool(title="Show Prices", defval=true, group="labels", display = display.data_window)
positionLabelsInput = input.string("Left", "Labels Position", options= , group="labels", display = display.data_window, active = showLabelsInput or showPricesInput)
linewidthInput = input.int(title="Line Width", defval=1, minval=1, maxval=100, group="levels", display = display.data_window)
DEFAULT_COLOR = #FB8C00
showLevel2and3 = pivotTypeInput != "DM"
showLevel4 = pivotTypeInput != "DM" and pivotTypeInput != "Fibonacci"
showLevel5 = pivotTypeInput == "Traditional" or pivotTypeInput == "Camarilla"
pColorInput = input.color(DEFAULT_COLOR, "P ", inline="P", group="levels", display = display.data_window)
pShowInput = input.bool(true, "", inline="P", group="levels", display = display.data_window)
s1ColorInput = input.color(DEFAULT_COLOR, "S1", inline="S1/R1" , group="levels", display = display.data_window)
s1ShowInput = input.bool(true, "", inline="S1/R1", group="levels", display = display.data_window)
r1ColorInput = input.color(DEFAULT_COLOR, " R1", inline="S1/R1", group="levels", display = display.data_window)
r1ShowInput = input.bool(true, "", inline="S1/R1", group="levels", display = display.data_window)
s2ColorInput = input.color(DEFAULT_COLOR, "S2", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
s2ShowInput = input.bool(true, "", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
r2ColorInput = input.color(DEFAULT_COLOR, " R2", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
r2ShowInput = input.bool(true, "", inline="S2/R2", group="levels", display = display.data_window, active = showLevel2and3)
s3ColorInput = input.color(DEFAULT_COLOR, "S3", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
s3ShowInput = input.bool(true, "", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
r3ColorInput = input.color(DEFAULT_COLOR, " R3", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
r3ShowInput = input.bool(true, "", inline="S3/R3", group="levels", display = display.data_window, active = showLevel2and3)
s4ColorInput = input.color(DEFAULT_COLOR, "S4", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
s4ShowInput = input.bool(true, "", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
r4ColorInput = input.color(DEFAULT_COLOR, " R4", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
r4ShowInput = input.bool(true, "", inline="S4/R4", group="levels", display = display.data_window, active = showLevel4)
s5ColorInput = input.color(DEFAULT_COLOR, "S5", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
s5ShowInput = input.bool(true, "", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
r5ColorInput = input.color(DEFAULT_COLOR, " R5", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
r5ShowInput = input.bool(true, "", inline="S5/R5", group="levels", display = display.data_window, active = showLevel5)
type graphicSettings
string levelName
color levelColor
bool showLevel
var graphicSettingsArray = array.from(
graphicSettings.new(" P", pColorInput, pShowInput),
graphicSettings.new("R1", r1ColorInput, r1ShowInput), graphicSettings.new("S1", s1ColorInput, s1ShowInput),
graphicSettings.new("R2", r2ColorInput, r2ShowInput), graphicSettings.new("S2", s2ColorInput, s2ShowInput),
graphicSettings.new("R3", r3ColorInput, r3ShowInput), graphicSettings.new("S3", s3ColorInput, s3ShowInput),
graphicSettings.new("R4", r4ColorInput, r4ShowInput), graphicSettings.new("S4", s4ColorInput, s4ShowInput),
graphicSettings.new("R5", r5ColorInput, r5ShowInput), graphicSettings.new("S5", s5ColorInput, s5ShowInput))
autoAnchor = switch
timeframe.isintraday => timeframe.multiplier <= 15 ? "1D" : "1W"
timeframe.isdaily => "1M"
=> "12M"
pivotTimeframe = switch pivotAnchorInput
"Auto" => autoAnchor
"Daily" => "1D"
"Weekly" => "1W"
"Monthly" => "1M"
"Quarterly" => "3M"
=> "12M"
pivotYearMultiplier = switch pivotAnchorInput
"Biyearly" => 2
"Triyearly" => 3
"Quinquennially" => 5
"Decennially" => 10
=> 1
numOfPivotLevels = switch pivotTypeInput
"Traditional" => 11
"Camarilla" => 11
"Woodie" => 9
"Classic" => 9
"Fibonacci" => 7
"DM" => 3
type pivotGraphic
line pivotLine
label pivotLabel
method delete(pivotGraphic graphic) =>
graphic.pivotLine.delete()
graphic.pivotLabel.delete()
var drawnGraphics = matrix.new()
localPivotTimeframeChange = timeframe.change(pivotTimeframe) and year % pivotYearMultiplier == 0
securityPivotTimeframeChange = timeframe.change(timeframe.period) and year % pivotYearMultiplier == 0
pivotTimeframeChangeCounter(condition) =>
var count = 0
if condition and bar_index > 0
count += 1
count
localPivots = ta.pivot_point_levels(pivotTypeInput, localPivotTimeframeChange)
securityPivotPointsArray = ta.pivot_point_levels(pivotTypeInput, securityPivotTimeframeChange)
securityTimeframe = timeframe.isintraday ? "1D" : timeframe.period
= request.security(syminfo.tickerid, pivotTimeframe, , lookahead = barmerge.lookahead_on)
pivotPointsArray = isDailyBasedInput ? securityPivots : localPivots
affixOldPivots(endTime) =>
if drawnGraphics.rows() > 0
lastGraphics = drawnGraphics.row(drawnGraphics.rows() - 1)
for graphic in lastGraphics
graphic.pivotLine.set_x2(endTime)
if positionLabelsInput == "Right"
graphic.pivotLabel.set_x(endTime)
drawNewPivots(startTime) =>
newGraphics = array.new()
for in pivotPointsArray
levelSettings = graphicSettingsArray.get(index)
if not na(coord) and levelSettings.showLevel
lineEndTime = startTime + timeframe.in_seconds(pivotTimeframe) * 1000 * pivotYearMultiplier
pivotLine = line.new(startTime, coord, lineEndTime, coord, xloc = xloc.bar_time, color=levelSettings.levelColor, width=linewidthInput)
pivotLabel = label.new(x = positionLabelsInput == "Left" ? startTime : lineEndTime,
y = coord,
text = (showLabelsInput ? levelSettings.levelName + " " : "") + (showPricesInput ? "(" + str.tostring(coord, format.mintick) + ")" : ""),
style = positionLabelsInput == "Left" ? label.style_label_right : label.style_label_left,
textcolor = levelSettings.levelColor,
color = #00000000,
xloc=xloc.bar_time)
newGraphics.push(pivotGraphic.new(pivotLine, pivotLabel))
drawnGraphics.add_row(array_id = newGraphics)
if drawnGraphics.rows() > maxHistoricalPivotsInput
oldGraphics = drawnGraphics.remove_row(0)
for graphic in oldGraphics
graphic.delete()
localPivotDrawConditionStatic = not isDailyBasedInput and localPivotTimeframeChange
securityPivotDrawConditionStatic = isDailyBasedInput and securityPivotCounter != securityPivotCounter
var isMultiYearly = array.from("Biyearly", "Triyearly", "Quinquennially", "Decennially").includes(pivotAnchorInput)
localPivotDrawConditionDeveloping = not isDailyBasedInput and time_close == time_close(pivotTimeframe) and not isMultiYearly
securityPivotDrawConditionDeveloping = false
if (securityPivotDrawConditionStatic or localPivotDrawConditionStatic)
affixOldPivots(time)
drawNewPivots(time)
var FIRST_BAR_TIME = time
if (barstate.islastconfirmedhistory and drawnGraphics.columns() == 0)
if not na(securityPivots) and securityPivotCounter > 0
if isDailyBasedInput
drawNewPivots(FIRST_BAR_TIME)
else
runtime.error("Not enough intraday data to calculate Pivot Points. Lower the Pivots Timeframe or turn on the 'Use Daily-based Values' option in the indicator settings.")
else
runtime.error("Not enough data to calculate Pivot Points. Lower the Pivots Timeframe in the indicator settings.")
RSI5vsRSI14_v2//@version=5
indicator("RSI5vsRSI14_v2", shorttitle="RSI5vsRSI14_v2", overlay=false)
plot(ta.rsi(close, 14), title="RSI14", color=color.red)
plot(ta.rsi(close, 5), title="RSI5", color=color.green)
RSI Rate of Change (ROC of RSI)The RSI Rate of Change (ROC of RSI) indicator measures the speed and momentum of changes in the RSI, helping traders identify early trend shifts, strength of price moves, and potential reversals before they appear on the standard RSI.
While RSI shows overbought and oversold conditions, the ROC of RSI reveals how fast RSI itself is rising or falling, offering a deeper view of market momentum.
How the Indicator Works
1. RSI Calculation
The indicator first calculates the classic Relative Strength Index (RSI) using the selected length (default 14). This measures the strength of recent price movements.
2. Rate of Change (ROC) of RSI
Next, it computes the Rate of Change (ROC) of the RSI over a user-defined period.
This shows:
Positive ROC → RSI increasing quickly → strong bullish momentum
Negative ROC → RSI decreasing quickly → strong bearish momentum
ROC crossing above/below 0 → potential early trend shift
What You See on the Chart
Blue Line: RSI
Red Line: ROC of RSI
Grey dotted Zero Line: Momentum reference
Why Traders Use It
The RSI ROC helps you:
Detect momentum reversals early
Spot bullish and bearish accelerations not visible on RSI alone
Identify exhaustion points before RSI reaches extremes
Improve entry/exit precision in trend and swing trading
Validate price breakouts or breakdowns with momentum confirmation
Best For
Swing traders
Momentum traders
Reversal traders
Trend-following systems needing early confirmation signals
EMV// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
//@version=5
indicator("EMV", overlay=false)
N = input.int(14, "N")
M = input.int(9, "M")
// ==== VOLUME ====
maVol = ta.sma(volume, N)
VOLUME = maVol / volume
// ==== MID ====
hl = high + low
MID = 100 * (hl - hl ) / hl
// ==== HL_RANGE ====
HL_RANGE = ta.sma(high - low, N)
// ==== EMV ====
EMV_raw = MID * VOLUME * (high - low) / HL_RANGE
EMV = ta.sma(EMV_raw, N)
// ==== MAEMV ====
MAEMV = ta.sma(EMV, M)
plot(EMV, color=color.blue, title="EMV")
plot(MAEMV, color=color.orange, title="MAEMV")
EDU PRO LITE – Divergence + Fake Breakout + CandleThis indicator is created for educational purposes only. It displays EMA, RSI, and the previous day’s high/low to help users understand market trends and price movement. This script does not provide any trading signals, buy/sell recommendations, or entry indications. All trading decisions are entirely outside the scope of this indicator.”
8 EMA Candle Color ChangeableJust a quick indicator that I threw together that shows the 8 EMA and changes the candle colors if the candle closes above or below the EMA.
UTT NEW MOONThe script first calculates the day of the year and then uses astronomical formulas to approximate the Moon’s phase at the given time. From these calculations it determines the last Moon phase event and classifies it as either a New Moon (phase +1) or a Full Moon (phase −1).
It adjusts the result so the phase only changes when a new lunar event occurs, then returns two values: the current phase state and a “moonType” that signals when a new event (New or Full Moon) appears.
Labden VPVR 2.0VRVP with color theory. I wanted one that was non-obstructing, not too complex and right in all the right ways. This works for me as, essentially, a V1.0. It's nice to see the volume profiles you're taking the trade into (on the right) rather than a ton of small ones that have happened. Dynamic for different time ranges or easily adjustable. Enjoy
HoneG_SARBB v22This is the development version of ver22 for a 1-minute trading signal tool based on BB, SAR, ADX, RSI, RCI, etc.
Please apply it to a 1-minute chart and test it.
Internally, it monitors the second-tick chart, so a Premium or higher grade is required.
BB、SAR、ADX、RSI、RCIなどをベースにした1分取引用サインツールのver22開発中バージョンです。
1分足チャートに適用してお試しください。
内部的には秒足を見ているので、Premium以上のグレードが必要になります。
Hardwaybets' Protected Highs / Protected Lows TradingProtected Highs & Lows – Multi-Condition Structural Marker
This indicator identifies specific candle formations where price breaks a previous candle’s high or low, fails to maintain that break, and confirms the rejection with an additional condition involving prior candles. These marked locations offer a visual reference for areas where price attempted directional expansion but did not sustain it. All levels remain visible until later invalidated by price movement.
Protected High – Detection Logic
A Protected High is marked only when all three of the following conditions occur:
1. Break of Previous High
The current candle trades above the prior candle’s high.
2. Close Back Inside Range
The current candle closes within the high-to-low range of the previous candle, indicating the upward expansion was not sustained.
3. Reversal Through Prior Bullish Structure
After forming the high, price closes below the opening price of one or more bullish candles that were part of the upward movement into that high.
This reflects a shift away from the prior upward structure.
When all three conditions are met, the high of the candle that created the event is marked on the chart.
Protected Low – Detection Logic
A Protected Low is marked only when all three of the following conditions occur:
1. Break of Previous Low
The current candle trades below the prior candle’s low.
2. Close Back Inside Range
The current candle closes within the high-to-low range of the previous candle, indicating the downward expansion was not sustained.
3. Reversal Through Prior Bearish Structure
After forming the low, price closes above the opening price of one or more bearish candles that were part of the downward movement into that low.
This reflects a shift away from the prior downward structure.
When all three conditions are met, the low of the candle that created the event is marked on the chart.
Level Management
* Marked highs and lows remain active as long as price does not trade beyond them.
* If price moves past a marked level, that level is removed.
* Only active, unviolated structural reference points remain displayed.
Market Structure Context (Strictly Non-Signaling)
Protected highs and lows can help traders observe areas where:
* Price briefly exceeded a previous high or low
* That expansion was not maintained
* Price then moved back through recent candles associated with the prior direction
These observations can be used by traders to understand how price interacts with nearby structural reference points.
The indicator itself does not provide trade entries, exits, or directional guidance.
Customization Options
The indicator provides adjustable settings for:
* Marker style (labels or shapes)
* Shape type (circle, square, diamond, etc.)
* Colors for highs and lows
* Vertical spacing between markers and candles
These options help maintain clarity on different chart types and timeframes.
Intended Use
The indicator does not generate forecasts or trading signals.
Its purpose is to visually highlight multi-condition candle formations where price briefly exceeded a prior high or low, failed to sustain that expansion, and later reversed through nearby structural points.
Compatibility
Suitable for all assets and timeframes.
Volume Spike Detector V. 1.1A simple indicator that identifies spikes in volume and marks the specific candle with based on the user's preferences.
ITFI Lite — Smart Money Dashboard✅ ITFI Lite is now live — ITFI Pro (full confluence) coming soon 🔒
Follow to get early access.
This is the Lite version of the upcoming ITFI Pro system.
Designed for traders who want clean higher-timeframe context without clutter, complexity, or repainting.
Included in ITFI Lite:
• D1 & H4 bias (EMA-based)
• M15 equilibrium + premium/discount zones
• PB/BO Lite signals (no scoring)
• UTC session with volatility phase
• Compact dashboard for fast decision-making
Not included (Pro features):
• HTF FVG / OB mapping
• Scoring engine
• Ready / Wait / Blocked system
• Advanced liquidity model
• Entry timing assistant
• Full multi-timeframe confluence
📌 Pro version is currently in development — Coming Soon 🔒
Follow for updates and early access.
CISD Adaptive Pivots (manny_mailbox2)This CISD indicator with projections automatically adjust the pivot strength for the current market in real-time.
Features:
Customizable projection levels.
Customizable bullish projection color, size, and width.
Customizable bearish projection color, size, and width.
Select the number of CISD/Projection you want to see on chart.
Min/Max Adaptive Pivot Stength based on candle body or wicks
Customizable smoothing factor
This automated feature can be turned on/off.
Here's how it works:
The Adaptive Pivot Strength feature (enabled by default) dynamically calculates the optimal pivot strength based on recent market structure.
How it adapts:
Tracks pivot spacing - It monitors the distance (in bars) between the last 20 pivot highs and pivot lows
Calculates average spacing - Combines both high and low spacing to determine typical pivot frequency
Converts to strength - Uses the formula avg_spacing / 4.0 to determine the calculated strength
Smooths changes - Applies EMA-like smoothing (controlled by your smoothing_factor of 0.3) to prevent erratic jumps
Clamps to range - Keeps the result between your min (2) and max (10) pivot strength settings
Current settings:
Base strength: 3
Adaptive range: 2-10
Smoothing: 0.3 (more responsive; lower = smoother)
The table shows you the current adaptive strength in real-time, color-coded green/red/yellow based on whether it's above/below/equal to base strength
So instead of using a fixed pivot strength of 3, it dynamically adjusts between 2-10 based on how far apart actual pivots are forming in the market. Tighter markets = lower strength (more sensitive), wider swings = higher strength (less noise).
[ b]What time frame does this work best on?
Optimal timeframes:
5-minute to 15-minute charts - This is the sweet spot for CISD detection with adaptive pivots. The pivot strength range (2-10) is calibrated for intraday price action where you get enough pivots to establish meaningful series without over-fitting.
1-minute charts - Can work but you'll see more noise. The adaptive feature helps here by increasing pivot strength during choppier periods. You might want to adjust your min_pivot_strength to 3-4 on the 1-min.
30-minute to 1-hour - Still effective but you'll get fewer CISD signals. The projections become longer-term targets. Good for swing context.
Why these timeframes:
Your lookback period (100 bars) needs enough history to calculate adaptive strength properly
CISD detection relies on polarity changes (bullish/bearish candles), which are more meaningful on 5-15 min
The projection levels (1x to 4x) align well with typical intraday move extensions on these timeframes
For MNQ specifically:
The 5-minute is probably your best bet - it captures the institutional order flow you're tracking while filtering out the noise of lower timeframes. The 15-minute works great for cleaner swing trades and aligns well with session-based analysis.
Idea: Use two of these on chart.
Why you might want two:
Different timeframes: One with lower pivot strength (2-5) for short-term, another with higher (7-10) for major structure
Adaptive vs Fixed : One with adaptive pivot ON, one with it OFF at a fixed strength for comparison
Different projection levels: One for conservative targets (1, 1.5, 2), another for extended targets (3, 4, 5)
Different CISD settings : One showing all CISDs, another filtered to show only recent ones4
I'm displaying the CISD's and projection with Fadi's Order Blocks, SMT's, and Daily Standard Deviation just to show how it might be used.
Good Luck and be good to each other!
BETA ZONES v1.0BETA ZONES v1.0 Indicator
Overview
BETA ZONES v1.0 is a comprehensive technical analysis tool designed for TradingView, combining an EMA-based ribbon with dynamic glow zones, structural pivot detection, and real-time ATR visualization. This overlay indicator helps traders identify trends, support/resistance zones, and potential breakout points by blending moving averages, volatility-based shading, and pivot structures. It's particularly useful for trend-following strategies, swing trading, and confirming market reversals on any timeframe or asset, including those using Heikin Ashi candles (as it incorporates real close data to bypass transformations).
The indicator emphasizes visual clarity with color-coded elements: bullish trends in shades of green/lime and bearish in red/maroon. It includes customizable toggles for each component, allowing users to focus on specific features without cluttering the chart.
Key Features
• EMA Ribbon & Glow System:
o Displays a ribbon formed by three EMAs (5, 20, and 50 periods) with gradient fills between them, colored based on trend strength.
o A dynamic "glow" zone around the 50-period EMA, calculated using ATR (Average True Range), acts as a volatility-based support (bullish) or resistance (bearish) band. The glow expands/contracts with market volatility, providing a visual buffer for potential price reactions.
o Real Close Dot: A small circle plotted at the actual closing price of each bar (sourced from standard candles), aiding in precise data verification even on transformed charts like Heikin Ashi.
• Structural Pivots:
o Automatically detects and labels confirmed pivot highs and lows using customizable symbols (e.g., arrows, dots, or curves).
o Draws breakout lines connecting pivots to the bar where structure is broken (Break of Structure - BOS), highlighting bullish (green) or bearish (red) shifts.
o Pivots are trend-aware: In uptrends, it tracks higher highs/lows until a downside break; in downtrends, lower highs/lows until an upside break.
• Real ATR Display:
o A compact table at the bottom-center of the chart showing the current 14-period ATR value (calculated on real data), useful for gauging volatility and setting stop-losses or targets.
How It Works
• EMA Ribbon Logic: The fast EMA (5) is compared to the mid (20), and mid to slow (50), to determine sub-trends. Price relative to the slow EMA sets the overall bullish/bearish bias. Fills create a "ribbon" effect, with colors intensifying in strong trends.
• Glow Zone: Uses a user-defined ATR length and multiplier to create upper/lower bands around the slow EMA. The glow is one-sided: below for bullish (support) and above for bearish (resistance), with semi-transparent shading for easy price overlay.
• Pivot Detection: Tracks the current trend direction (up or down) and reference high/low from the last confirmed pivot. A breakout (close crossing the reference level) confirms a new pivot, labels it, and optionally draws a line to the breakout bar. Bar coloring (yellow) highlights breakout candles.
• Data Handling: All calculations use real close prices via request.security to ensure accuracy on non-standard chart types.
Settings and Customization
The indicator is divided into intuitive input groups for easy configuration:
1. EMA Ribbon & Glow:
o Show EMA Ribbon & Glow: Master toggle to enable/disable the entire ribbon and glow (default: true). Note: Real Close Dot is independent.
o ATR Length (Glow): Lookback for ATR calculation (default: 3; higher = smoother glow).
o ATR Multiplier (Glow Size): Scales the glow width (default: 0.15; higher = wider zone).
o Show Real Close Dot: Toggle for the orange dot at real closes (default: true).
o Real Close Dot Color: Customize the dot's color (default: orange).
2. Structural Pivots:
o Show Pivot Labels: Toggle visibility of high/low symbols (default: true).
o Pivot Symbol Style: Choose from pairs like "︽ ︾" (low/high) or "•" (dots) (default: "•").
o Label Size: Adjust symbol size (Tiny to Huge; default: Normal).
o Pivot High/Low Label Colors: Set colors for labels (default: white).
o Show Breakout Lines: Toggle lines from pivot to breakout (default: true).
o Line Width: Thickness of breakout lines (default: 2).
o Line Style: Solid, Dashed, or Dotted (default: Solid).
o Resistance Break Line (Bullish): Color for upside breaks (default: green).
o Support Break Line (Bearish): Color for downside breaks (default: red).
No additional inputs are required for the ATR table, as it's always displayed on the last bar for quick reference.
Usage Tips
• Trend Identification: Use the EMA ribbon colors to gauge momentum—full green for strong bulls, red for bears. The glow zone can act as a dynamic entry/exit area (e.g., buy near bullish glow support).
• Breakout Trading: Watch for pivot labels and BOS lines as signals for trend reversals. Combine with volume or other indicators for confirmation.
• Volatility Awareness: The displayed ATR(14) helps in position sizing; for example, set stops at 1-2x ATR from entry.
• Chart Compatibility: Works best on candlestick or Heikin Ashi charts. For lower timeframes, reduce ATR length for faster reactivity; increase for higher timeframes.
• Limitations: Pivots are reactive and may lag in ranging markets. Glow is based on historical ATR, so it doesn't predict future volatility.
This indicator is in beta (v1.0) and open to feedback for improvements. Add it to your chart via TradingView's indicator search and experiment with settings to fit your strategy!
Support/Resistance (OI) + 9/20 EMA//@version=6
indicator("Support/Resistance (OI) + 9/20 EMA", overlay=true)
ema9 = ta.ema(close, 9)
ema20 = ta.ema(close, 20)
plot(ema9, color=color.blue, linewidth=2, title="EMA 9")
plot(ema20, color=color.orange, linewidth=2, title="EMA 20")
// Update these levels daily based on your OI analysis
s1 = 25850
s2 = 25800
s3 = 25500
r1 = 26000
r2 = 25950
r3 = 26100
// Use hline for persistent horizontal levels
hline(s1, 'Support 1', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(s2, 'Support 2', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(s3, 'Support 3', color=color.green, linestyle=hline.style_dashed, linewidth=2)
hline(r1, 'Resistance 1', color=color.red, linestyle=hline.style_dashed, linewidth=2)
hline(r2, 'Resistance 2', color=color.red, linestyle=hline.style_dashed, linewidth=2)
hline(r3, 'Resistance 3', color=color.red, linestyle=hline.style_dashed, linewidth=2)
Relative Performance Analyzer [AstrideUnicorn]Relative Performance Analyzer (RPA) is a performance analysis tool inspired by the data comparison features found in professional trading terminals. The RPA replicates the analytical approach used by portfolio managers and institutional analysts who routinely compare multiple securities or other types of data to identify relative strength opportunities, make allocation decisions, choose the most optimal investment from several alternatives, and much more.
Key Features:
Multi-Symbol Comparison: Track up to 5 different symbols simultaneously across any asset class or dataset
Two Performance Calculation Methods: Choose between percentage returns or risk-adjusted returns
Interactive Analysis: Drag the start date line on the chart or manually choose the start date in the settings
Professional Visualization: High-contrast color scheme designed for both dark and light chart themes
Live Performance Table: Real-time display of current return values sorted from the top to the worst performers
Practical Use Cases:
ETF Selection: Compare similar ETFs (e.g., SPY vs IVV vs VOO) to identify the most efficient investment
Sector Rotation: Analyze which sectors are showing relative strength for strategic allocation
Competitive Analysis: Compare companies within the same industry to identify leaders (e.g., APPLE vs SAMSUNG vs XIAOMI)
Cross-Asset Allocation: Evaluate performance across stocks, bonds, commodities, and currencies to guide portfolio rebalancing
Risk-Adjusted Decisions: Use risk-adjusted performance to find investments with the best returns per unit of risk
Example Scenarios:
Analyze whether tech stocks are outperforming the broader market by comparing XLK to SPY
Evaluate which emerging market ETF (EEM vs VWO) has provided better risk-adjusted returns over the past year
HOW DOES IT WORK
The indicator calculates and visualizes performance from a user-defined starting point using two methodologies:
Percentage Returns: Standard total return calculation showing percentage change from the start date
Risk-Adjusted Returns: Cumulative returns divided by the volatility (standard deviation), providing insight into the efficiency of performance. An expanding window is used to calculate the volatility, ensuring accurate risk-adjusted comparisons throughout the analysis period.
HOW TO USE
Setup Your Comparison: Enable up to 5 assets and input their symbols in the settings
Set Analysis Period: When you first launch the indicator, select the start date by clicking on the price chart. The vertical start date line will appear. Drag it on the chart or manually input a specific date to change the start date.
Choose Return Type: Select between percentage or risk-adjusted returns based on your analysis needs
Interpret Results
Use the real-time table for precise current values
SETTINGS
Assets 1-5: Toggle on/off and input symbols for comparison (stocks, ETFs, indices, forex, crypto, fundamental data, etc.)
Start Date: Set the initial point for return calculations (drag on chart or input manually)
Return Type: Choose between "Percentage" or "Risk-Adjusted" performance.
ORB Multi-Symbol ScannerProfessional Opening Range Breakout (ORB) scanner designed for futures traders monitoring ES (S&P 500), NQ (Nasdaq 100), and YM (Dow Jones) simultaneously. This indicator displays real-time ORB status, breakout signals, and key metrics for all three major index futures in one convenient table overlay.
Real-Time Status Tracking
🟡 ACTIVE - ORB formation in progress (9:30-9:35 AM ET)
🟢 READY - ORB complete, waiting for breakout
⚪ WAITING - Pre-market or outside NY session
Breakout Detection
🟢 LONG ↑ - Price broke above ORB high
🔴 SHORT ↓ - Price broke below ORB low
🟠 NEAR HIGH/LOW - Within 0.5% of breakout level
Instant visual alerts when breakouts occur
🔔 Built-in Alerts
Individual alerts for each symbol (ES Long/Short, NQ Long/Short, YM Long/Short)
Relative Volume at TimeThis indicator measures how active today’s volume is compared to what’s normal for this exact time of the session. For each bar, it compares the current volume (or cumulative volume since session open) against the average volume at the same bar index over the last N sessions. The result is plotted as a relative volume histogram, where 1.0 = normal, >1.0 = higher than usual, and <1.0 = quieter than usual for that time.
On top of that, the script shows a compact table in the top-right corner with “Current Session RVOL: X%”, which represents today’s total volume so far versus the average cumulative volume at this time of day. For example, 150% means today’s session has 1.5× the usual volume at the current time.
Features:
Time-aligned relative volume: compares each bar to the same time in past sessions
Two modes: Regular (bar volume) and Cumulative (volume since session open)
Custom lookback (number of past sessions)
Threshold lines (e.g. 2×, 3×) and background highlights for high RVOL zones
Session RVOL percentage table for a quick gauge of “Is today a high-volume day so far?”
This tool is designed for intraday traders who want to quickly spot abnormal volume spikes and high-participation sessions without cluttering the chart.
SE PRO — Clean ProfessionalSE PRO — Clean Professional is an advanced Smart Money Concepts (SMC) indicator designed for traders who want clean, accurate market structure, BOS/CHoCH detection, HTF trend filtering, liquidity identification, order block zones, and candlestick confirmation patterns — all in one optimized tool.
RSI5vsRSI14indicator("RSI5vsRSI14")
plot(ta.rsi(close, 14), color=color.red)
plot(ta.rsi(close, 5), color=color.green)
// plot(ta.rsi(close, 2), color=color.blue)
DCA + Liquidation LevelsThe indicator combines a Dollar-Cost Averaging (DCA) strategy after downtrends with liquidation level detection, providing comprehensive market analysis.
📈 Working Principle
1. DCA Strategy Foundation
EMA 50 and EMA 200 - used as primary trend indicators
EMA-CD Histogram - difference between EMA50 and EMA200 with signal line
BHD Levels - dynamic support/resistance levels based on volatility
2. DCA Entry Logic
pinescript
// Entry Conditions
entry_condition1 = nPastCandles > entryNumber * 24 * 30 // Monthly interval
entry_condition2 = emacd < 0 and hist < 0 and hist > hist // Downtrend reversal
ENTRY_CONDITIONS = entry_condition1 and entry_condition2
Entry triggers when:
Specified time has passed since last entry (monthly intervals)
EMA-CD is negative but showing reversal signs (histogram increasing)
Market is emerging from downtrend
3. Price Zone Coloring System
pinescript
// BHD Unit Calculation
bhd_unit = ta.rma(high - low, 200) * 2
price_level = (close - ema200) / bhd_unit
Color Zones:
🔴 Red Zone: Level > 5 (Extreme Overbought)
🟠 Orange Zone: Level 4-5 (Strong Overbought)
🟡 Yellow Zone: Level 3-4 (Overbought)
🟢 Green Zone: Level 2-3 (Moderate Overbought)
🔵 Light Blue: Level 1-2 (Slightly Overbought)
🔵 Blue: Level 0-1 (Near EMA200)
🔵 Dark Blue: Level -1 to -4 (Oversold)
🔵 Extreme Blue: Level < -4 (Extreme Oversold)
4. Liquidation Levels Detection
pinescript
// Open Interest Delta Analysis
OI_delta = OI - nz(OI )
OI_delta_abs_MA = ta.sma(math.abs(OI_delta), maLength)
Liquidation Level Types:
Large Liquidation Level: OI Delta ≥ 3x MA
Middle Liquidation Level: OI Delta 2x-3x MA
Small Liquidation Level: OI Delta 1.2x-2x MA
Leverage Calculations:
5x, 10x, 25x, 50x, 100x leverage levels
Both long and short liquidation prices
⚙️ Technical Components
1. Moving Averages
EMA 50: Short-term trend direction
EMA 200: Long-term trend foundation
EMA-CD: Momentum and trend strength measurement
2. BHD Levels Calculation
pinescript
bhd_unit = ta.rma(high - low, 200) * 2
bhd_upper = ema200 + bhd_unit * N // Resistance levels
bhd_lower = ema200 - bhd_unit * N // Support levels
Where N = 1 to 5 for multiple levels
3. Open Interest Integration
Fetches Binance USDT perpetual contract OI data
Calculates OI changes to detect large position movements
Identifies potential liquidation clusters
🔔 Alert System
Zone Transition Alerts
Triggers: When price moves between different BHD zones
Customizable: Each zone alert can be enabled/disabled individually
Information: Includes exact level, price, and EMA200 value
Alert Types Available:
🔴 Red Zone Alert
🟠 Orange Zone Alert
🟡 Yellow Zone Alert
🟢 Green Zone Alert
🔵 Light Blue Zone Alert
🔵 Blue Zone Alert
🔵 Dark Blue Zone Alert
🔵 Extreme Blue Zone Alert
🎨 Visual Features
1. Candle Coloring
Real-time color coding based on price position relative to EMA200
Immediate visual identification of market conditions
2. Level Displays
EMA lines (50 & 200)
BHD support/resistance levels
Liquidation level lines with different styles based on significance
3. Entry Markers
Green upward labels below bars indicating DCA entry points
Numbered sequentially for tracking
📊 Input Parameters
DCA Settings
Start/End dates for backtesting
EMA periods customization
Liquidation Levels Settings
MA Length for OI Delta
Threshold multipliers for different liquidation levels
Display toggles for lines and histogram
Alert Settings
Individual zone alert enable/disable
Customizable sensitivity
🔧 Usage Recommendations
For DCA Strategy:
Enter positions at marked DCA points after downtrends
Use BHD levels for position sizing and take-profit targets
Monitor zone transitions for market condition changes
For Liquidation Analysis:
Watch for price approaches to liquidation levels
Use histogram for density of liquidation clusters
Combine with zone analysis for entry/exit timing
⚠️ Limitations
Data Dependency: Requires Binance OI data availability
Market Specific: Optimized for cryptocurrency markets
Timeframe: Works best on 1H+ timeframes for reliable signals
Volatility: BHD levels may need adjustment for different volatility regimes
🔄 Updates and Maintenance
Regular compatibility checks with TradingView updates
Performance optimization for different market conditions
User feedback incorporation for feature improvements
This indicator provides institutional-grade market analysis combined with systematic DCA strategy implementation, suitable for both manual trading and algorithmic strategy development.






















