"神户胜利+VS+磐田喜悦" için komut dosyalarını ara
200/100 vs 190/80 EMA [jarederaj]Track the 200/100 EMA cross Vs the 180/90 EMA cross. Also, see the dates when these periods start on the chart.
Bitfinex Long vs Short RatiosWas impressed with the 'Longs vs Shorts Ratio' idea from the tweet below so I coded an indicator, enjoy.
twitter.com
Compare - Oscillator vs BTC momentumI've made a simple indicator to compare the momentum of a trading pair against the momentum of BTC to the dollar. I use it to see how a pair is affected by BTC's momentum... I wouldnt use it to trade off alone, but it can be a useful tool alongside other indicators.
The time range can be adjusted, but I wouldnt reccomend setting it to anything over 12M, or under 1W.... as I'm not sure if it would work.
Any feedback is welcome!
This is an idea I had after looking at a wonderful visualisation made by BarclayJames, link below:
www.tradingview.com
비트코인 한국 프리미엄 캔들 차트 (Bithumb vs Bitfinex) by 호재박스 슈퍼스타지표명: 비트코인 한국 프리미엄 캔들 차트 (Bithumb vs Bitfinex)
제작자: 호재박스 슈퍼스타
홈페이지: hozaebox.com
BTCUSD long vs short ratio+rsiJust a script I want to share with friends on a discord
orange/green line : longs vs short ratio (100 = only longs, 0 = only shorts)
purple line : RSI of (longs-shorts)
Bitcoin Exchanges Premium (Incl Int & GBTC) vs GdaxShows the exchange premiums internationally (Hong Kong, Luxembourg, Korea, Japan, China) vs Gdax. Also includes GBTC Trust price (adjusted).
Index Vs Futures v4.0 (dashed edition)Generalized script of
Originally designed for bitcoin, but can be used to compare between futures and index (or any two symbol expressions).
Conventions:
- green background := futures deviates 'way above' index
- red background := futures deviates 'way below' index
VS Score [SpiritualHealer117]An experimental indicator that uses historical prices and readings of technical indicators to give the probability that stock and crypto prices will be in a certain range on the next close. This indicator may be helpful for options traders or for traders who want to see the probability of a move.
It classifies returns into five categories:
Extreme Rise - Over 2 standard deviations above normal returns
Rise - Between 0.5 standard deviations and 2 standard deviations above normal returns
Flat - Falling in the range of +/- 0.5 standard deviations of normal returns
Fall - Between 0.5 standard deviations and 2 standard deviations below normal returns
Extreme Fall - Over 2 standard deviations below normal returns
It is an adaptive probability model, which trains on the previous 1000 data points, and is calculated by creating probability vectors for the current reading of the PPO, MA, volume histogram, and previous return, and combining them into one probability vector.
Adaptive Genesis Engine [AGE]ADAPTIVE GENESIS ENGINE (AGE)
Pure Signal Evolution Through Genetic Algorithms
Where Darwin Meets Technical Analysis
🧬 WHAT YOU'RE GETTING - THE PURE INDICATOR
This is a technical analysis indicator - it generates signals, visualizes probability, and shows you the evolutionary process in real-time. This is NOT a strategy with automatic execution - it's a sophisticated signal generation system that you control .
What This Indicator Does:
Generates Long/Short entry signals with probability scores (35-88% range)
Evolves a population of up to 12 competing strategies using genetic algorithms
Validates strategies through walk-forward optimization (train/test cycles)
Visualizes signal quality through premium gradient clouds and confidence halos
Displays comprehensive metrics via enhanced dashboard
Provides alerts for entries and exits
Works on any timeframe, any instrument, any broker
What This Indicator Does NOT Do:
Execute trades automatically
Manage positions or calculate position sizes
Place orders on your behalf
Make trading decisions for you
This is pure signal intelligence. AGE tells you when and how confident it is. You decide whether and how much to trade.
🔬 THE SCIENCE: GENETIC ALGORITHMS MEET TECHNICAL ANALYSIS
What Makes This Different - The Evolutionary Foundation
Most indicators are static - they use the same parameters forever, regardless of market conditions. AGE is alive . It maintains a population of competing strategies that evolve, adapt, and improve through natural selection principles:
Birth: New strategies spawn through crossover breeding (combining DNA from fit parents) plus random mutation for exploration
Life: Each strategy trades virtually via shadow portfolios, accumulating wins/losses, tracking drawdown, and building performance history
Selection: Strategies are ranked by comprehensive fitness scoring (win rate, expectancy, drawdown control, signal efficiency)
Death: Weak strategies are culled periodically, with elite performers (top 2 by default) protected from removal
Evolution: The gene pool continuously improves as successful traits propagate and unsuccessful ones die out
This is not curve-fitting. Each new strategy must prove itself on out-of-sample data through walk-forward validation before being trusted for live signals.
🧪 THE DNA: WHAT EVOLVES
Every strategy carries a 10-gene chromosome controlling how it interprets market data:
Signal Sensitivity Genes
Entropy Sensitivity (0.5-2.0): Weight given to market order/disorder calculations. Low values = conservative, require strong directional clarity. High values = aggressive, act on weaker order signals.
Momentum Sensitivity (0.5-2.0): Weight given to RSI/ROC/MACD composite. Controls responsiveness to momentum shifts vs. mean-reversion setups.
Structure Sensitivity (0.5-2.0): Weight given to support/resistance positioning. Determines how much price location within swing range matters.
Probability Adjustment Genes
Probability Boost (-0.10 to +0.10): Inherent bias toward aggressive (+) or conservative (-) entries. Acts as personality trait - some strategies naturally optimistic, others pessimistic.
Trend Strength Requirement (0.3-0.8): Minimum trend conviction needed before signaling. Higher values = only trades strong trends, lower values = acts in weak/sideways markets.
Volume Filter (0.5-1.5): Strictness of volume confirmation. Higher values = requires strong volume, lower values = volume less important.
Risk Management Genes
ATR Multiplier (1.5-4.0): Base volatility scaling for all price levels. Controls whether strategy uses tight or wide stops/targets relative to ATR.
Stop Multiplier (1.0-2.5): Stop loss tightness. Lower values = aggressive profit protection, higher values = more breathing room.
Target Multiplier (1.5-4.0): Profit target ambition. Lower values = quick scalping exits, higher values = swing trading holds.
Adaptation Gene
Regime Adaptation (0.0-1.0): How much strategy adjusts behavior based on detected market regime (trending/volatile/choppy). Higher values = more reactive to regime changes.
The Magic: AGE doesn't just try random combinations. Through tournament selection and fitness-weighted crossover, successful gene combinations spread through the population while unsuccessful ones fade away. Over 50-100 bars, you'll see the population converge toward genes that work for YOUR instrument and timeframe.
📊 THE SIGNAL ENGINE: THREE-LAYER SYNTHESIS
Before any strategy generates a signal, AGE calculates probability through multi-indicator confluence:
Layer 1 - Market Entropy (Information Theory)
Measures whether price movements exhibit directional order or random walk characteristics:
The Math:
Shannon Entropy = -Σ(p × log(p))
Market Order = 1 - (Entropy / 0.693)
What It Means:
High entropy = choppy, random market → low confidence signals
Low entropy = directional market → high confidence signals
Direction determined by up-move vs down-move dominance over lookback period (default: 20 bars)
Signal Output: -1.0 to +1.0 (bearish order to bullish order)
Layer 2 - Momentum Synthesis
Combines three momentum indicators into single composite score:
Components:
RSI (40% weight): Normalized to -1/+1 scale using (RSI-50)/50
Rate of Change (30% weight): Percentage change over lookback (default: 14 bars), clamped to ±1
MACD Histogram (30% weight): Fast(12) - Slow(26), normalized by ATR
Why This Matters: RSI catches mean-reversion opportunities, ROC catches raw momentum, MACD catches momentum divergence. Weighting favors RSI for reliability while keeping other perspectives.
Signal Output: -1.0 to +1.0 (strong bearish to strong bullish)
Layer 3 - Structure Analysis
Evaluates price position within swing range (default: 50-bar lookback):
Position Classification:
Bottom 20% of range = Support Zone → bullish bounce potential
Top 20% of range = Resistance Zone → bearish rejection potential
Middle 60% = Neutral Zone → breakout/breakdown monitoring
Signal Logic:
At support + bullish candle = +0.7 (strong buy setup)
At resistance + bearish candle = -0.7 (strong sell setup)
Breaking above range highs = +0.5 (breakout confirmation)
Breaking below range lows = -0.5 (breakdown confirmation)
Consolidation within range = ±0.3 (weak directional bias)
Signal Output: -1.0 to +1.0 (bearish structure to bullish structure)
Confluence Voting System
Each layer casts a vote (Long/Short/Neutral). The system requires minimum 2-of-3 agreement (configurable 1-3) before generating a signal:
Examples:
Entropy: Bullish, Momentum: Bullish, Structure: Neutral → Signal generated (2 long votes)
Entropy: Bearish, Momentum: Neutral, Structure: Neutral → No signal (only 1 short vote)
All three bullish → Signal generated with +5% probability bonus
This is the key to quality. Single indicators give too many false signals. Triple confirmation dramatically improves accuracy.
📈 PROBABILITY CALCULATION: HOW CONFIDENCE IS MEASURED
Base Probability:
Raw_Prob = 50% + (Average_Signal_Strength × 25%)
Then AGE applies strategic adjustments:
Trend Alignment:
Signal with trend: +4%
Signal against strong trend: -8%
Weak/no trend: no adjustment
Regime Adaptation:
Trending market (efficiency >50%, moderate vol): +3%
Volatile market (vol ratio >1.5x): -5%
Choppy market (low efficiency): -2%
Volume Confirmation:
Volume > 70% of 20-bar SMA: no change
Volume below threshold: -3%
Volatility State (DVS Ratio):
High vol (>1.8x baseline): -4% (reduce confidence in chaos)
Low vol (<0.7x baseline): -2% (markets can whipsaw in compression)
Moderate elevated vol (1.0-1.3x): +2% (trending conditions emerging)
Confluence Bonus:
All 3 indicators agree: +5%
2 of 3 agree: +2%
Strategy Gene Adjustment:
Probability Boost gene: -10% to +10%
Regime Adaptation gene: scales regime adjustments by 0-100%
Final Probability: Clamped between 35% (minimum) and 88% (maximum)
Why These Ranges?
Below 35% = too uncertain, better not to signal
Above 88% = unrealistic, creates overconfidence
Sweet spot: 65-80% for quality entries
🔄 THE SHADOW PORTFOLIO SYSTEM: HOW STRATEGIES COMPETE
Each active strategy maintains a virtual trading account that executes in parallel with real-time data:
Shadow Trading Mechanics
Entry Logic:
Calculate signal direction, probability, and confluence using strategy's unique DNA
Check if signal meets quality gate:
Probability ≥ configured minimum threshold (default: 65%)
Confluence ≥ configured minimum (default: 2 of 3)
Direction is not zero (must be long or short, not neutral)
Verify signal persistence:
Base requirement: 2 bars (configurable 1-5)
Adapts based on probability: high-prob signals (75%+) enter 1 bar faster, low-prob signals need 1 bar more
Adjusts for regime: trending markets reduce persistence by 1, volatile markets add 1
Apply additional filters:
Trend strength must exceed strategy's requirement gene
Regime filter: if volatile market detected, probability must be 72%+ to override
Volume confirmation required (volume > 70% of average)
If all conditions met for required persistence bars, enter shadow position at current close price
Position Management:
Entry Price: Recorded at close of entry bar
Stop Loss: ATR-based distance = ATR × ATR_Mult (gene) × Stop_Mult (gene) × DVS_Ratio
Take Profit: ATR-based distance = ATR × ATR_Mult (gene) × Target_Mult (gene) × DVS_Ratio
Position: +1 (long) or -1 (short), only one at a time per strategy
Exit Logic:
Check if price hit stop (on low) or target (on high) on current bar
Record trade outcome in R-multiples (profit/loss normalized by ATR)
Update performance metrics:
Total trades counter incremented
Wins counter (if profit > 0)
Cumulative P&L updated
Peak equity tracked (for drawdown calculation)
Maximum drawdown from peak recorded
Enter cooldown period (default: 8 bars, configurable 3-20) before next entry allowed
Reset signal age counter to zero
Walk-Forward Tracking:
During position lifecycle, trades are categorized:
Training Phase (first 250 bars): Trade counted toward training metrics
Testing Phase (next 75 bars): Trade counted toward testing metrics (out-of-sample)
Live Phase (after WFO period): Trade counted toward overall metrics
Why Shadow Portfolios?
No lookahead bias (uses only data available at the bar)
Realistic execution simulation (entry on close, stop/target checks on high/low)
Independent performance tracking for true fitness comparison
Allows safe experimentation without risking capital
Each strategy learns from its own experience
🏆 FITNESS SCORING: HOW STRATEGIES ARE RANKED
Fitness is not just win rate. AGE uses a comprehensive multi-factor scoring system:
Core Metrics (Minimum 3 trades required)
Win Rate (30% of fitness):
WinRate = Wins / TotalTrades
Normalized directly (0.0-1.0 scale)
Total P&L (30% of fitness):
Normalized_PnL = (PnL + 300) / 600
Clamped 0.0-1.0. Assumes P&L range of -300R to +300R for normalization scale.
Expectancy (25% of fitness):
Expectancy = Total_PnL / Total_Trades
Normalized_Expectancy = (Expectancy + 30) / 60
Clamped 0.0-1.0. Rewards consistency of profit per trade.
Drawdown Control (15% of fitness):
Normalized_DD = 1 - (Max_Drawdown / 15)
Clamped 0.0-1.0. Penalizes strategies that suffer large equity retracements from peak.
Sample Size Adjustment
Quality Factor:
<50 trades: 1.0 (full weight, small sample)
50-100 trades: 0.95 (slight penalty for medium sample)
100 trades: 0.85 (larger penalty for large sample)
Why penalize more trades? Prevents strategies from gaming the system by taking hundreds of tiny trades to inflate statistics. Favors quality over quantity.
Bonus Adjustments
Walk-Forward Validation Bonus:
if (WFO_Validated):
Fitness += (WFO_Efficiency - 0.5) × 0.1
Strategies proven on out-of-sample data receive up to +10% fitness boost based on test/train efficiency ratio.
Signal Efficiency Bonus (if diagnostics enabled):
if (Signals_Evaluated > 10):
Pass_Rate = Signals_Passed / Signals_Evaluated
Fitness += (Pass_Rate - 0.1) × 0.05
Rewards strategies that generate high-quality signals passing the quality gate, not just profitable trades.
Final Fitness: Clamped at 0.0 minimum (prevents negative fitness values)
Result: Elite strategies typically achieve 0.50-0.75 fitness. Anything above 0.60 is excellent. Below 0.30 is prime candidate for culling.
🔬 WALK-FORWARD OPTIMIZATION: ANTI-OVERFITTING PROTECTION
This is what separates AGE from curve-fitted garbage indicators.
The Three-Phase Process
Every new strategy undergoes a rigorous validation lifecycle:
Phase 1 - Training Window (First 250 bars, configurable 100-500):
Strategy trades normally via shadow portfolio
All trades count toward training performance metrics
System learns which gene combinations produce profitable patterns
Tracks independently: Training_Trades, Training_Wins, Training_PnL
Phase 2 - Testing Window (Next 75 bars, configurable 30-200):
Strategy continues trading without any parameter changes
Trades now count toward testing performance metrics (separate tracking)
This is out-of-sample data - strategy has never seen these bars during "optimization"
Tracks independently: Testing_Trades, Testing_Wins, Testing_PnL
Phase 3 - Validation Check:
Minimum_Trades = 5 (configurable 3-15)
IF (Train_Trades >= Minimum AND Test_Trades >= Minimum):
WR_Efficiency = Test_WinRate / Train_WinRate
Expectancy_Efficiency = Test_Expectancy / Train_Expectancy
WFO_Efficiency = (WR_Efficiency + Expectancy_Efficiency) / 2
IF (WFO_Efficiency >= 0.55): // configurable 0.3-0.9
Strategy.Validated = TRUE
Strategy receives fitness bonus
ELSE:
Strategy receives 30% fitness penalty
ELSE:
Validation deferred (insufficient trades in one or both periods)
What Validation Means
Validated Strategy (Green "✓ VAL" in dashboard):
Performed at least 55% as well on unseen data compared to training data
Gets fitness bonus: +(efficiency - 0.5) × 0.1
Receives priority during tournament selection for breeding
More likely to be chosen as active trading strategy
Unvalidated Strategy (Orange "○ TRAIN" in dashboard):
Failed to maintain performance on test data (likely curve-fitted to training period)
Receives 30% fitness penalty (0.7x multiplier)
Makes strategy prime candidate for culling
Can still trade but with lower selection probability
Insufficient Data (continues collecting):
Hasn't completed both training and testing periods yet
OR hasn't achieved minimum trade count in both periods
Validation check deferred until requirements met
Why 55% Efficiency Threshold?
If a strategy earned 10R during training but only 5.5R during testing, it still proved an edge exists beyond random luck. Requiring 100% efficiency would be unrealistic - market conditions change between periods. But requiring >50% ensures the strategy didn't completely degrade on fresh data.
The Protection: Strategies that work great on historical data but fail on new data are automatically identified and penalized. This prevents the population from being polluted by overfitted strategies that would fail in live trading.
🌊 DYNAMIC VOLATILITY SCALING (DVS): ADAPTIVE STOP/TARGET PLACEMENT
AGE doesn't use fixed stop distances. It adapts to current volatility conditions in real-time.
Four Volatility Measurement Methods
1. ATR Ratio (Simple Method):
Current_Vol = ATR(14) / Close
Baseline_Vol = SMA(Current_Vol, 100)
Ratio = Current_Vol / Baseline_Vol
Basic comparison of current ATR to 100-bar moving average baseline.
2. Parkinson (High-Low Range Based):
For each bar: HL = log(High / Low)
Parkinson_Vol = sqrt(Σ(HL²) / (4 × Period × log(2)))
More stable than close-to-close volatility. Captures intraday range expansion without overnight gap noise.
3. Garman-Klass (OHLC Based):
HL_Term = 0.5 × ²
CO_Term = (2×log(2) - 1) × ²
GK_Vol = sqrt(Σ(HL_Term - CO_Term) / Period)
Most sophisticated estimator. Incorporates all four price points (open, high, low, close) plus gap information.
4. Ensemble Method (Default - Median of All Three):
Ratio_1 = ATR_Current / ATR_Baseline
Ratio_2 = Parkinson_Current / Parkinson_Baseline
Ratio_3 = GK_Current / GK_Baseline
DVS_Ratio = Median(Ratio_1, Ratio_2, Ratio_3)
Why Ensemble?
Takes median to avoid outliers and false spikes
If ATR jumps but range-based methods stay calm, median prevents overreaction
If one method fails, other two compensate
Most robust approach across different market conditions
Sensitivity Scaling
Scaled_Ratio = (Raw_Ratio) ^ Sensitivity
Sensitivity 0.3: Cube root - heavily dampens volatility impact
Sensitivity 0.5: Square root - moderate dampening
Sensitivity 0.7 (Default): Balanced response to volatility changes
Sensitivity 1.0: Linear - full 1:1 volatility impact
Sensitivity 1.5: Exponential - amplified response to volatility spikes
Safety Clamps: Final DVS Ratio always clamped between 0.5x and 2.5x baseline to prevent extreme position sizing or stop placement errors.
How DVS Affects Shadow Trading
Every strategy's stop and target distances are multiplied by the current DVS ratio:
Stop Loss Distance:
Stop_Distance = ATR × ATR_Mult (gene) × Stop_Mult (gene) × DVS_Ratio
Take Profit Distance:
Target_Distance = ATR × ATR_Mult (gene) × Target_Mult (gene) × DVS_Ratio
Example Scenario:
ATR = 10 points
Strategy's ATR_Mult gene = 2.5
Strategy's Stop_Mult gene = 1.5
Strategy's Target_Mult gene = 2.5
DVS_Ratio = 1.4 (40% above baseline volatility - market heating up)
Stop = 10 × 2.5 × 1.5 × 1.4 = 52.5 points (vs. 37.5 in normal vol)
Target = 10 × 2.5 × 2.5 × 1.4 = 87.5 points (vs. 62.5 in normal vol)
Result:
During volatility spikes: Stops automatically widen to avoid noise-based exits, targets extend for bigger moves
During calm periods: Stops tighten for better risk/reward, targets compress for realistic profit-taking
Strategies adapt risk management to match current market behavior
🧬 THE EVOLUTIONARY CYCLE: SPAWN, COMPETE, CULL
Initialization (Bar 1)
AGE begins with 4 seed strategies (if evolution enabled):
Seed Strategy #0 (Balanced):
All sensitivities at 1.0 (neutral)
Zero probability boost
Moderate trend requirement (0.4)
Standard ATR/stop/target multiples (2.5/1.5/2.5)
Mid-level regime adaptation (0.5)
Seed Strategy #1 (Momentum-Focused):
Lower entropy sensitivity (0.7), higher momentum (1.5)
Slight probability boost (+0.03)
Higher trend requirement (0.5)
Tighter stops (1.3), wider targets (3.0)
Seed Strategy #2 (Entropy-Driven):
Higher entropy sensitivity (1.5), lower momentum (0.8)
Slight probability penalty (-0.02)
More trend tolerant (0.6)
Wider stops (1.8), standard targets (2.5)
Seed Strategy #3 (Structure-Based):
Balanced entropy/momentum (0.8/0.9), high structure (1.4)
Slight probability boost (+0.02)
Lower trend requirement (0.35)
Moderate risk parameters (1.6/2.8)
All seeds start with WFO validation bypassed if WFO is disabled, or must validate if enabled.
Spawning New Strategies
Timing (Adaptive):
Historical phase: Every 30 bars (configurable 10-100)
Live phase: Every 200 bars (configurable 100-500)
Automatically switches to live timing when barstate.isrealtime triggers
Conditions:
Current population < max population limit (default: 8, configurable 4-12)
At least 2 active strategies exist (need parents)
Available slot in population array
Selection Process:
Run tournament selection 3 times with different seeds
Each tournament: randomly sample active strategies, pick highest fitness
Best from 3 tournaments becomes Parent 1
Repeat independently for Parent 2
Ensures fit parents but maintains diversity
Crossover Breeding:
For each of 10 genes:
Parent1_Fitness = fitness
Parent2_Fitness = fitness
Weight1 = Parent1_Fitness / (Parent1_Fitness + Parent2_Fitness)
Gene1 = parent1's value
Gene2 = parent2's value
Child_Gene = Weight1 × Gene1 + (1 - Weight1) × Gene2
Fitness-weighted crossover ensures fitter parent contributes more genetic material.
Mutation:
For each gene in child:
IF (random < mutation_rate):
Gene_Range = GENE_MAX - GENE_MIN
Noise = (random - 0.5) × 2 × mutation_strength × Gene_Range
Mutated_Gene = Clamp(Child_Gene + Noise, GENE_MIN, GENE_MAX)
Historical mutation rate: 20% (aggressive exploration)
Live mutation rate: 8% (conservative stability)
Mutation strength: 12% of gene range (configurable 5-25%)
Initialization of New Strategy:
Unique ID assigned (total_spawned counter)
Parent ID recorded
Generation = max(parent generations) + 1
Birth bar recorded (for age tracking)
All performance metrics zeroed
Shadow portfolio reset
WFO validation flag set to false (must prove itself)
Result: New strategy with hybrid DNA enters population, begins trading in next bar.
Competition (Every Bar)
All active strategies:
Calculate their signal based on unique DNA
Check quality gate with their thresholds
Manage shadow positions (entries/exits)
Update performance metrics
Recalculate fitness score
Track WFO validation progress
Strategies compete indirectly through fitness ranking - no direct interaction.
Culling Weak Strategies
Timing (Adaptive):
Historical phase: Every 60 bars (configurable 20-200, should be 2x spawn interval)
Live phase: Every 400 bars (configurable 200-1000, should be 2x spawn interval)
Minimum Adaptation Score (MAS):
Initial MAS = 0.10
MAS decays: MAS × 0.995 every cull cycle
Minimum MAS = 0.03 (floor)
MAS represents the "survival threshold" - strategies below this fitness level are vulnerable.
Culling Conditions (ALL must be true):
Population > minimum population (default: 3, configurable 2-4)
At least one strategy has fitness < MAS
Strategy's age > culling interval (prevents premature culling of new strategies)
Strategy is not in top N elite (default: 2, configurable 1-3)
Culling Process:
Find worst strategy:
For each active strategy:
IF (age > cull_interval):
Fitness = base_fitness
IF (not WFO_validated AND WFO_enabled):
Fitness × 0.7 // 30% penalty for unvalidated
IF (Fitness < MAS AND Fitness < worst_fitness_found):
worst_strategy = this_strategy
worst_fitness = Fitness
IF (worst_strategy found):
Count elite strategies with fitness > worst_fitness
IF (elite_count >= elite_preservation_count):
Deactivate worst_strategy (set active flag = false)
Increment total_culled counter
Elite Protection:
Even if a strategy's fitness falls below MAS, it survives if fewer than N strategies are better. This prevents culling when population is generally weak.
Result: Weak strategies removed from population, freeing slots for new spawns. Gene pool improves over time.
Selection for Display (Every Bar)
AGE chooses one strategy to display signals:
Best fitness = -1
Selected = none
For each active strategy:
Fitness = base_fitness
IF (WFO_validated):
Fitness × 1.3 // 30% bonus for validated strategies
IF (Fitness > best_fitness):
best_fitness = Fitness
selected_strategy = this_strategy
Display selected strategy's signals on chart
Result: Only the highest-fitness (optionally validated-boosted) strategy's signals appear as chart markers. Other strategies trade invisibly in shadow portfolios.
🎨 PREMIUM VISUALIZATION SYSTEM
AGE includes sophisticated visual feedback that standard indicators lack:
1. Gradient Probability Cloud (Optional, Default: ON)
Multi-layer gradient showing signal buildup 2-3 bars before entry:
Activation Conditions:
Signal persistence > 0 (same directional signal held for multiple bars)
Signal probability ≥ minimum threshold (65% by default)
Signal hasn't yet executed (still in "forming" state)
Visual Construction:
7 gradient layers by default (configurable 3-15)
Each layer is a line-fill pair (top line, bottom line, filled between)
Layer spacing: 0.3 to 1.0 × ATR above/below price
Outer layers = faint, inner layers = bright
Color transitions from base to intense based on layer position
Transparency scales with probability (high prob = more opaque)
Color Selection:
Long signals: Gradient from theme.gradient_bull_mid to theme.gradient_bull_strong
Short signals: Gradient from theme.gradient_bear_mid to theme.gradient_bear_strong
Base transparency: 92%, reduces by up to 8% for high-probability setups
Dynamic Behavior:
Cloud grows/shrinks as signal persistence increases/decreases
Redraws every bar while signal is forming
Disappears when signal executes or invalidates
Performance Note: Computationally expensive due to linefill objects. Disable or reduce layers if chart performance degrades.
2. Population Fitness Ribbon (Optional, Default: ON)
Histogram showing fitness distribution across active strategies:
Activation: Only draws on last bar (barstate.islast) to avoid historical clutter
Visual Construction:
10 histogram layers by default (configurable 5-20)
Plots 50 bars back from current bar
Positioned below price at: lowest_low(100) - 1.5×ATR (doesn't interfere with price action)
Each layer represents a fitness threshold (evenly spaced min to max fitness)
Layer Logic:
For layer_num from 0 to ribbon_layers:
Fitness_threshold = min_fitness + (max_fitness - min_fitness) × (layer / layers)
Count strategies with fitness ≥ threshold
Height = ATR × 0.15 × (count / total_active)
Y_position = base_level + ATR × 0.2 × layer
Color = Gradient from weak to strong based on layer position
Line_width = Scaled by height (taller = thicker)
Visual Feedback:
Tall, bright ribbon = healthy population, many fit strategies at high fitness levels
Short, dim ribbon = weak population, few strategies achieving good fitness
Ribbon compression (layers close together) = population converging to similar fitness
Ribbon spread = diverse fitness range, active selection pressure
Use Case: Quick visual health check without opening dashboard. Ribbon growing upward over time = population improving.
3. Confidence Halo (Optional, Default: ON)
Circular polyline around entry signals showing probability strength:
Activation: Draws when new position opens (shadow_position changes from 0 to ±1)
Visual Construction:
20-segment polyline forming approximate circle
Center: Low - 0.5×ATR (long) or High + 0.5×ATR (short)
Radius: 0.3×ATR (low confidence) to 1.0×ATR (elite confidence)
Scales with: (probability - min_probability) / (1.0 - min_probability)
Color Coding:
Elite (85%+): Cyan (theme.conf_elite), large radius, minimal transparency (40%)
Strong (75-85%): Strong green (theme.conf_strong), medium radius, moderate transparency (50%)
Good (65-75%): Good green (theme.conf_good), smaller radius, more transparent (60%)
Moderate (<65%): Moderate green (theme.conf_moderate), tiny radius, very transparent (70%)
Technical Detail:
Uses chart.point array with index-based positioning
5-bar horizontal spread for circular appearance (±5 bars from entry)
Curved=false (Pine Script polyline limitation)
Fill color matches line color but more transparent (88% vs line's transparency)
Purpose: Instant visual probability assessment. No need to check dashboard - halo size/brightness tells the story.
4. Evolution Event Markers (Optional, Default: ON)
Visual indicators of genetic algorithm activity:
Spawn Markers (Diamond, Cyan):
Plots when total_spawned increases on current bar
Location: bottom of chart (location.bottom)
Color: theme.spawn_marker (cyan/bright blue)
Size: tiny
Indicates new strategy just entered population
Cull Markers (X-Cross, Red):
Plots when total_culled increases on current bar
Location: bottom of chart (location.bottom)
Color: theme.cull_marker (red/pink)
Size: tiny
Indicates weak strategy just removed from population
What It Tells You:
Frequent spawning early = population building, active exploration
Frequent culling early = high selection pressure, weak strategies dying fast
Balanced spawn/cull = healthy evolutionary churn
No markers for long periods = stable population (evolution plateaued or optimal genes found)
5. Entry/Exit Markers
Clear visual signals for selected strategy's trades:
Long Entry (Triangle Up, Green):
Plots when selected strategy opens long position (position changes 0 → +1)
Location: below bar (location.belowbar)
Color: theme.long_primary (green/cyan depending on theme)
Transparency: Scales with probability:
Elite (85%+): 0% (fully opaque)
Strong (75-85%): 10%
Good (65-75%): 20%
Acceptable (55-65%): 35%
Size: small
Short Entry (Triangle Down, Red):
Plots when selected strategy opens short position (position changes 0 → -1)
Location: above bar (location.abovebar)
Color: theme.short_primary (red/pink depending on theme)
Transparency: Same scaling as long entries
Size: small
Exit (X-Cross, Orange):
Plots when selected strategy closes position (position changes ±1 → 0)
Location: absolute (at actual exit price if stop/target lines enabled)
Color: theme.exit_color (orange/yellow depending on theme)
Transparency: 0% (fully opaque)
Size: tiny
Result: Clean, probability-scaled markers that don't clutter chart but convey essential information.
6. Stop Loss & Take Profit Lines (Optional, Default: ON)
Visual representation of shadow portfolio risk levels:
Stop Loss Line:
Plots when selected strategy has active position
Level: shadow_stop value from selected strategy
Color: theme.short_primary with 60% transparency (red/pink, subtle)
Width: 2
Style: plot.style_linebr (breaks when no position)
Take Profit Line:
Plots when selected strategy has active position
Level: shadow_target value from selected strategy
Color: theme.long_primary with 60% transparency (green, subtle)
Width: 2
Style: plot.style_linebr (breaks when no position)
Purpose:
Shows where shadow portfolio would exit for stop/target
Helps visualize strategy's risk/reward ratio
Useful for manual traders to set similar levels
Disable for cleaner chart (recommended for presentations)
7. Dynamic Trend EMA
Gradient-colored trend line that visualizes trend strength:
Calculation:
EMA(close, trend_length) - default 50 period (configurable 20-100)
Slope calculated over 10 bars: (current_ema - ema ) / ema × 100
Color Logic:
Trend_direction:
Slope > 0.1% = Bullish (1)
Slope < -0.1% = Bearish (-1)
Otherwise = Neutral (0)
Trend_strength = abs(slope)
Color = Gradient between:
- Neutral color (gray/purple)
- Strong bullish (bright green) if direction = 1
- Strong bearish (bright red) if direction = -1
Gradient factor = trend_strength (0 to 1+ scale)
Visual Behavior:
Faint gray/purple = weak/no trend (choppy conditions)
Light green/red = emerging trend (low strength)
Bright green/red = strong trend (high conviction)
Color intensity = trend strength magnitude
Transparency: 50% (subtle, doesn't overpower price action)
Purpose: Subconscious awareness of trend state without checking dashboard or indicators.
8. Regime Background Tinting (Subtle)
Ultra-low opacity background color indicating detected market regime:
Regime Detection:
Efficiency = directional_movement / total_range (over trend_length bars)
Vol_ratio = current_volatility / average_volatility
IF (efficiency > 0.5 AND vol_ratio < 1.3):
Regime = Trending (1)
ELSE IF (vol_ratio > 1.5):
Regime = Volatile (2)
ELSE:
Regime = Choppy (0)
Background Colors:
Trending: theme.regime_trending (dark green, 92-93% transparency)
Volatile: theme.regime_volatile (dark red, 93% transparency)
Choppy: No tint (normal background)
Purpose:
Subliminal regime awareness
Helps explain why signals are/aren't generating
Trending = ideal conditions for AGE
Volatile = fewer signals, higher thresholds applied
Choppy = mixed signals, lower confidence
Important: Extremely subtle by design. Not meant to be obvious, just subconscious context.
📊 ENHANCED DASHBOARD
Comprehensive real-time metrics in single organized panel (top-right position):
Dashboard Structure (5 columns × 14 rows)
Header Row:
Column 0: "🧬 AGE PRO" + phase indicator (🔴 LIVE or ⏪ HIST)
Column 1: "POPULATION"
Column 2: "PERFORMANCE"
Column 3: "CURRENT SIGNAL"
Column 4: "ACTIVE STRATEGY"
Column 0: Market State
Regime (📈 TREND / 🌊 CHAOS / ➖ CHOP)
DVS Ratio (current volatility scaling factor, format: #.##)
Trend Direction (▲ BULL / ▼ BEAR / ➖ FLAT with color coding)
Trend Strength (0-100 scale, format: #.##)
Column 1: Population Metrics
Active strategies (count / max_population)
Validated strategies (WFO passed / active total)
Current generation number
Total spawned (all-time strategy births)
Total culled (all-time strategy deaths)
Column 2: Aggregate Performance
Total trades across all active strategies
Aggregate win rate (%) - color-coded:
Green (>55%)
Orange (45-55%)
Red (<45%)
Total P&L in R-multiples - color-coded by positive/negative
Best fitness score in population (format: #.###)
MAS - Minimum Adaptation Score (cull threshold, format: #.###)
Column 3: Current Signal Status
Status indicator:
"▲ LONG" (green) if selected strategy in long position
"▼ SHORT" (red) if selected strategy in short position
"⏳ FORMING" (orange) if signal persisting but not yet executed
"○ WAITING" (gray) if no active signal
Confidence percentage (0-100%, format: #.#%)
Quality assessment:
"🔥 ELITE" (cyan) for 85%+ probability
"✓ STRONG" (bright green) for 75-85%
"○ GOOD" (green) for 65-75%
"- LOW" (dim) for <65%
Confluence score (X/3 format)
Signal age:
"X bars" if signal forming
"IN TRADE" if position active
"---" if no signal
Column 4: Selected Strategy Details
Strategy ID number (#X format)
Validation status:
"✓ VAL" (green) if WFO validated
"○ TRAIN" (orange) if still in training/testing phase
Generation number (GX format)
Personal fitness score (format: #.### with color coding)
Trade count
P&L and win rate (format: #.#R (##%) with color coding)
Color Scheme:
Panel background: theme.panel_bg (dark, low opacity)
Panel headers: theme.panel_header (slightly lighter)
Primary text: theme.text_primary (bright, high contrast)
Secondary text: theme.text_secondary (dim, lower contrast)
Positive metrics: theme.metric_positive (green)
Warning metrics: theme.metric_warning (orange)
Negative metrics: theme.metric_negative (red)
Special markers: theme.validated_marker, theme.spawn_marker
Update Frequency: Only on barstate.islast (current bar) to minimize CPU usage
Purpose:
Quick overview of entire system state
No need to check multiple indicators
Trading decisions informed by population health, regime state, and signal quality
Transparency into what AGE is thinking
🔍 DIAGNOSTICS PANEL (Optional, Default: OFF)
Detailed signal quality tracking for optimization and debugging:
Panel Structure (3 columns × 8 rows)
Position: Bottom-right corner (doesn't interfere with main dashboard)
Header Row:
Column 0: "🔍 DIAGNOSTICS"
Column 1: "COUNT"
Column 2: "%"
Metrics Tracked (for selected strategy only):
Total Evaluated:
Every signal that passed initial calculation (direction ≠ 0)
Represents total opportunities considered
✓ Passed:
Signals that passed quality gate and executed
Green color coding
Percentage of evaluated signals
Rejection Breakdown:
⨯ Probability:
Rejected because probability < minimum threshold
Most common rejection reason typically
⨯ Confluence:
Rejected because confluence < minimum required (e.g., only 1 of 3 indicators agreed)
⨯ Trend:
Rejected because signal opposed strong trend
Indicates counter-trend protection working
⨯ Regime:
Rejected because volatile regime detected and probability wasn't high enough to override
Shows regime filter in action
⨯ Volume:
Rejected because volume < 70% of 20-bar average
Indicates volume confirmation requirement
Color Coding:
Passed count: Green (success metric)
Rejection counts: Red (failure metrics)
Percentages: Gray (neutral, informational)
Performance Cost: Slight CPU overhead for tracking counters. Disable when not actively optimizing settings.
How to Use Diagnostics
Scenario 1: Too Few Signals
Evaluated: 200
Passed: 10 (5%)
⨯ Probability: 120 (60%)
⨯ Confluence: 40 (20%)
⨯ Others: 30 (15%)
Diagnosis: Probability threshold too high for this strategy's DNA.
Solution: Lower min probability from 65% to 60%, or allow strategy more time to evolve better DNA.
Scenario 2: Too Many False Signals
Evaluated: 200
Passed: 80 (40%)
Strategy win rate: 45%
Diagnosis: Quality gate too loose, letting low-quality signals through.
Solution: Raise min probability to 70%, or increase min confluence to 3 (all indicators must agree).
Scenario 3: Regime-Specific Issues
⨯ Regime: 90 (45% of rejections)
Diagnosis: Frequent volatile regime detection blocking otherwise good signals.
Solution: Either accept fewer trades during chaos (recommended), or disable regime filter if you want signals regardless of market state.
Optimization Workflow:
Enable diagnostics
Run 200+ bars
Analyze rejection patterns
Adjust settings based on data
Re-run and compare pass rate
Disable diagnostics when satisfied
⚙️ CONFIGURATION GUIDE
🧬 Evolution Engine Settings
Enable AGE Evolution (Default: ON):
ON: Full genetic algorithm (recommended for best results)
OFF: Uses only 4 seed strategies, no spawning/culling (static population for comparison testing)
Max Population (4-12, Default: 8):
Higher = more diversity, more exploration, slower performance
Lower = faster computation, less exploration, risk of premature convergence
Sweet spot: 6-8 for most use cases
4 = minimum for meaningful evolution
12 = maximum before diminishing returns
Min Population (2-4, Default: 3):
Safety floor - system never culls below this count
Prevents population extinction during harsh selection
Should be at least half of max population
Elite Preservation (1-3, Default: 2):
Top N performers completely immune to culling
Ensures best genes always survive
1 = minimal protection, aggressive selection
2 = balanced (recommended)
3 = conservative, slower gene pool turnover
Historical: Spawn Interval (10-100, Default: 30):
Bars between spawning new strategies during historical data
Lower = faster evolution, more exploration
Higher = slower evolution, more evaluation time per strategy
30 bars = ~1-2 hours on 15min chart
Historical: Cull Interval (20-200, Default: 60):
Bars between culling weak strategies during historical data
Should be 2x spawn interval for balanced churn
Lower = aggressive selection pressure
Higher = patient evaluation
Live: Spawn Interval (100-500, Default: 200):
Bars between spawning during live trading
Much slower than historical for stability
Prevents population chaos during live trading
200 bars = ~1.5 trading days on 15min chart
Live: Cull Interval (200-1000, Default: 400):
Bars between culling during live trading
Should be 2x live spawn interval
Conservative removal during live trading
Historical: Mutation Rate (0.05-0.40, Default: 0.20):
Probability each gene mutates during breeding (20% = 2 out of 10 genes on average)
Higher = more exploration, slower convergence
Lower = more exploitation, faster convergence but risk of local optima
20% balances exploration vs exploitation
Live: Mutation Rate (0.02-0.20, Default: 0.08):
Mutation rate during live trading
Much lower for stability (don't want population to suddenly degrade)
8% = mostly inherits parent genes with small tweaks
Mutation Strength (0.05-0.25, Default: 0.12):
How much genes change when mutated (% of gene's total range)
0.05 = tiny nudges (fine-tuning)
0.12 = moderate jumps (recommended)
0.25 = large leaps (aggressive exploration)
Example: If gene range is 0.5-2.0, 12% strength = ±0.18 possible change
📈 Signal Quality Settings
Min Signal Probability (0.55-0.80, Default: 0.65):
Quality gate threshold - signals below this never generate
0.55-0.60 = More signals, accept lower confidence (higher risk)
0.65 = Institutional-grade balance (recommended)
0.70-0.75 = Fewer but higher-quality signals (conservative)
0.80+ = Very selective, very few signals (ultra-conservative)
Min Confluence Score (1-3, Default: 2):
Required indicator agreement before signal generates
1 = Any single indicator can trigger (not recommended - too many false signals)
2 = Requires 2 of 3 indicators agree (RECOMMENDED for balance)
3 = All 3 must agree (very selective, few signals, high quality)
Base Persistence Bars (1-5, Default: 2):
Base bars signal must persist before entry
System adapts automatically:
High probability signals (75%+) enter 1 bar faster
Low probability signals (<68%) need 1 bar more
Trending regime: -1 bar (faster entries)
Volatile regime: +1 bar (more confirmation)
1 = Immediate entry after quality gate (responsive but prone to whipsaw)
2 = Balanced confirmation (recommended)
3-5 = Patient confirmation (slower but more reliable)
Cooldown After Trade (3-20, Default: 8):
Bars to wait after exit before next entry allowed
Prevents overtrading and revenge trading
3 = Minimal cooldown (active trading)
8 = Balanced (recommended)
15-20 = Conservative (position trading)
Entropy Length (10-50, Default: 20):
Lookback period for market order/disorder calculation
Lower = more responsive to regime changes (noisy)
Higher = more stable regime detection (laggy)
20 = works across most timeframes
Momentum Length (5-30, Default: 14):
Period for RSI/ROC calculations
14 = standard (RSI default)
Lower = more signals, less reliable
Higher = fewer signals, more reliable
Structure Length (20-100, Default: 50):
Lookback for support/resistance swing range
20 = short-term swings (day trading)
50 = medium-term structure (recommended)
100 = major structure (position trading)
Trend EMA Length (20-100, Default: 50):
EMA period for trend detection and direction bias
20 = short-term trend (responsive)
50 = medium-term trend (recommended)
100 = long-term trend (position trading)
ATR Period (5-30, Default: 14):
Period for volatility measurement
14 = standard ATR
Lower = more responsive to vol changes
Higher = smoother vol calculation
📊 Volatility Scaling (DVS) Settings
Enable DVS (Default: ON):
Dynamic volatility scaling for adaptive stop/target placement
Highly recommended to leave ON
OFF only for testing fixed-distance stops
DVS Method (Default: Ensemble):
ATR Ratio: Simple, fast, single-method (good for beginners)
Parkinson: High-low range based (good for intraday)
Garman-Klass: OHLC based (sophisticated, considers gaps)
Ensemble: Median of all three (RECOMMENDED - most robust)
DVS Memory (20-200, Default: 100):
Lookback for baseline volatility comparison
20 = very responsive to vol changes (can overreact)
100 = balanced adaptation (recommended)
200 = slow, stable baseline (minimizes false vol signals)
DVS Sensitivity (0.3-1.5, Default: 0.7):
How much volatility affects scaling (power-law exponent)
0.3 = Conservative, heavily dampens vol impact (cube root)
0.5 = Moderate dampening (square root)
0.7 = Balanced response (recommended)
1.0 = Linear, full 1:1 vol response
1.5 = Aggressive, amplified response (exponential)
🔬 Walk-Forward Optimization Settings
Enable WFO (Default: ON):
Out-of-sample validation to prevent overfitting
Highly recommended to leave ON
OFF only for testing or if you want unvalidated strategies
Training Window (100-500, Default: 250):
Bars for in-sample optimization
100 = fast validation, less data (risky)
250 = balanced (recommended) - about 1-2 months on daily, 1-2 weeks on 15min
500 = patient validation, more data (conservative)
Testing Window (30-200, Default: 75):
Bars for out-of-sample validation
Should be ~30% of training window
30 = minimal test (fast validation)
75 = balanced (recommended)
200 = extensive test (very conservative)
Min Trades for Validation (3-15, Default: 5):
Required trades in BOTH training AND testing periods
3 = minimal sample (risky, fast validation)
5 = balanced (recommended)
10+ = conservative (slow validation, high confidence)
WFO Efficiency Threshold (0.3-0.9, Default: 0.55):
Minimum test/train performance ratio required
0.30 = Very loose (test must be 30% as good as training)
0.55 = Balanced (recommended) - test must be 55% as good
0.70+ = Strict (test must closely match training)
Higher = fewer validated strategies, lower risk of overfitting
🎨 Premium Visuals Settings
Visual Theme:
Neon Genesis: Cyberpunk aesthetic (cyan/magenta/purple)
Carbon Fiber: Industrial look (blue/red/gray)
Quantum Blue: Quantum computing (blue/purple/pink)
Aurora: Northern lights (teal/orange/purple)
⚡ Gradient Probability Cloud (Default: ON):
Multi-layer gradient showing signal buildup
Turn OFF if chart lags or for cleaner look
Cloud Gradient Layers (3-15, Default: 7):
More layers = smoother gradient, more CPU intensive
Fewer layers = faster, blockier appearance
🎗️ Population Fitness Ribbon (Default: ON):
Histogram showing fitness distribution
Turn OFF for cleaner chart
Ribbon Layers (5-20, Default: 10):
More layers = finer fitness detail
Fewer layers = simpler histogram
⭕ Signal Confidence Halo (Default: ON):
Circular indicator around entry signals
Size/brightness scales with probability
Minimal performance cost
🔬 Evolution Event Markers (Default: ON):
Diamond (spawn) and X (cull) markers
Shows genetic algorithm activity
Minimal performance cost
🎯 Stop/Target Lines (Default: ON):
Shows shadow portfolio stop/target levels
Turn OFF for cleaner chart (recommended for screenshots/presentations)
📊 Enhanced Dashboard (Default: ON):
Comprehensive metrics panel
Should stay ON unless you want zero overlays
🔍 Diagnostics Panel (Default: OFF):
Detailed signal rejection tracking
Turn ON when optimizing settings
Turn OFF during normal use (slight performance cost)
📈 USAGE WORKFLOW - HOW TO USE THIS INDICATOR
Phase 1: Initial Setup & Learning
Add AGE to your chart
Recommended timeframes: 15min, 30min, 1H (best signal-to-noise ratio)
Works on: 5min (day trading), 4H (swing trading), Daily (position trading)
Load 1000+ bars for sufficient evolution history
Let the population evolve (100+ bars minimum)
First 50 bars: Random exploration, poor results expected
Bars 50-150: Population converging, fitness improving
Bars 150+: Stable performance, validated strategies emerging
Watch the dashboard metrics
Population should grow toward max capacity
Generation number should advance regularly
Validated strategies counter should increase
Best fitness should trend upward toward 0.50-0.70 range
Observe evolution markers
Diamond markers (cyan) = new strategies spawning
X markers (red) = weak strategies being culled
Frequent early activity = healthy evolution
Activity slowing = population stabilizing
Be patient. Evolution takes time. Don't judge performance before 150+ bars.
Phase 2: Signal Observation
Watch signals form
Gradient cloud builds up 2-3 bars before entry
Cloud brightness = probability strength
Cloud thickness = signal persistence
Check signal quality
Look at confidence halo size when entry marker appears
Large bright halo = elite setup (85%+)
Medium halo = strong setup (75-85%)
Small halo = good setup (65-75%)
Verify market conditions
Check trend EMA color (green = uptrend, red = downtrend, gray = choppy)
Check background tint (green = trending, red = volatile, clear = choppy)
Trending background + aligned signal = ideal conditions
Review dashboard signal status
Current Signal column shows:
Status (Long/Short/Forming/Waiting)
Confidence % (actual probability value)
Quality assessment (Elite/Strong/Good)
Confluence score (2/3 or 3/3 preferred)
Only signals meeting ALL quality gates appear on chart. If you're not seeing signals, population is either still learning or market conditions aren't suitable.
Phase 3: Manual Trading Execution
When Long Signal Fires:
Verify confidence level (dashboard or halo size)
Confirm trend alignment (EMA sloping up, green color)
Check regime (preferably trending or choppy, avoid volatile)
Enter long manually on your broker platform
Set stop loss at displayed stop line level (if lines enabled), or use your own risk management
Set take profit at displayed target line level, or trail manually
Monitor position - exit if X marker appears (signal reversal)
When Short Signal Fires:
Same verification process
Confirm downtrend (EMA sloping down, red color)
Enter short manually
Use displayed stop/target levels or your own
AGE tells you WHEN and HOW CONFIDENT. You decide WHETHER and HOW MUCH.
Phase 4: Set Up Alerts (Never Miss a Signal)
Right-click on indicator name in legend
Select "Add Alert"
Choose condition:
"AGE Long" = Long entry signal fired
"AGE Short" = Short entry signal fired
"AGE Exit" = Position reversal/exit signal
Set notification method:
Sound alert (popup on chart)
Email notification
Webhook to phone/trading platform
Mobile app push notification
Name the alert (e.g., "AGE BTCUSD 15min Long")
Save alert
Recommended: Set alerts for both long and short, enable mobile push notifications. You'll get alerted in real-time even if not watching charts.
Phase 5: Monitor Population Health
Weekly Review:
Check dashboard Population column:
Active count should be near max (6-8 of 8)
Validated count should be >50% of active
Generation should be advancing (1-2 per week typical)
Check dashboard Performance column:
Aggregate win rate should be >50% (target: 55-65%)
Total P&L should be positive (may fluctuate)
Best fitness should be >0.50 (target: 0.55-0.70)
MAS should be declining slowly (normal adaptation)
Check Active Strategy column:
Selected strategy should be validated (✓ VAL)
Personal fitness should match best fitness
Trade count should be accumulating
Win rate should be >50%
Warning Signs:
Zero validated strategies after 300+ bars = settings too strict or market unsuitable
Best fitness stuck <0.30 = population struggling, consider parameter adjustment
No spawning/culling for 200+ bars = evolution stalled (may be optimal or need reset)
Aggregate win rate <45% sustained = system not working on this instrument/timeframe
Health Check Pass:
50%+ strategies validated
Best fitness >0.50
Aggregate win rate >52%
Regular spawn/cull activity
Selected strategy validated
Phase 6: Optimization (If Needed)
Enable Diagnostics Panel (bottom-right) for data-driven tuning:
Problem: Too Few Signals
Evaluated: 200
Passed: 8 (4%)
⨯ Probability: 140 (70%)
Solutions:
Lower min probability: 65% → 60% or 55%
Reduce min confluence: 2 → 1
Lower base persistence: 2 → 1
Increase mutation rate temporarily to explore new genes
Check if regime filter is blocking signals (⨯ Regime high?)
Problem: Too Many False Signals
Evaluated: 200
Passed: 90 (45%)
Win rate: 42%
Solutions:
Raise min probability: 65% → 70% or 75%
Increase min confluence: 2 → 3
Raise base persistence: 2 → 3
Enable WFO if disabled (validates strategies before use)
Check if volume filter is being ignored (⨯ Volume low?)
Problem: Counter-Trend Losses
⨯ Trend: 5 (only 5% rejected)
Losses often occur against trend
Solutions:
System should already filter trend opposition
May need stronger trend requirement
Consider only taking signals aligned with higher timeframe trend
Use longer trend EMA (50 → 100)
Problem: Volatile Market Whipsaws
⨯ Regime: 100 (50% rejected by volatile regime)
Still getting stopped out frequently
Solutions:
System is correctly blocking volatile signals
Losses happening because vol filter isn't strict enough
Consider not trading during volatile periods (respect the regime)
Or disable regime filter and accept higher risk
Optimization Workflow:
Enable diagnostics
Run 200+ bars with current settings
Analyze rejection patterns and win rate
Make ONE change at a time (scientific method)
Re-run 200+ bars and compare results
Keep change if improvement, revert if worse
Disable diagnostics when satisfied
Never change multiple parameters at once - you won't know what worked.
Phase 7: Multi-Instrument Deployment
AGE learns independently on each chart:
Recommended Strategy:
Deploy AGE on 3-5 different instruments
Different asset classes ideal (e.g., ES futures, EURUSD, BTCUSD, SPY, Gold)
Each learns optimal strategies for that instrument's personality
Take signals from all 5 charts
Natural diversification reduces overall risk
Why This Works:
When one market is choppy, others may be trending
Different instruments respond to different news/catalysts
Portfolio-level win rate more stable than single-instrument
Evolution explores different parameter spaces on each chart
Setup:
Same settings across all charts (or customize if preferred)
Set alerts for all
Take every validated signal across all instruments
Position size based on total account (don't overleverage any single signal)
⚠️ REALISTIC EXPECTATIONS - CRITICAL READING
What AGE Can Do
✅ Generate probability-weighted signals using genetic algorithms
✅ Evolve strategies in real-time through natural selection
✅ Validate strategies on out-of-sample data (walk-forward optimization)
✅ Adapt to changing market conditions automatically over time
✅ Provide comprehensive metrics on population health and signal quality
✅ Work on any instrument, any timeframe, any broker
✅ Improve over time as weak strategies are culled and fit strategies breed
What AGE Cannot Do
❌ Win every trade (typical win rate: 55-65% at best)
❌ Predict the future with certainty (markets are probabilistic, not deterministic)
❌ Work perfectly from bar 1 (needs 100-150 bars to learn and stabilize)
❌ Guarantee profits under all market conditions
❌ Replace your trading discipline and risk management
❌ Execute trades automatically (this is an indicator, not a strategy)
❌ Prevent all losses (drawdowns are normal and expected)
❌ Adapt instantly to regime changes (re-learning takes 50-100 bars)
Performance Realities
Typical Performance After Evolution Stabilizes (150+ bars):
Win Rate: 55-65% (excellent for trend-following systems)
Profit Factor: 1.5-2.5 (realistic for validated strategies)
Signal Frequency: 5-15 signals per 100 bars (quality over quantity)
Drawdown Periods: 20-40% of time in equity retracement (normal trading reality)
Max Consecutive Losses: 5-8 losses possible even with 60% win rate (probability says this is normal)
Evolution Timeline:
Bars 0-50: Random exploration, learning phase - poor results expected, don't judge yet
Bars 50-150: Population converging, fitness climbing - results improving
Bars 150-300: Stable performance, most strategies validated - consistent results
Bars 300+: Mature population, optimal genes dominant - best results
Market Condition Dependency:
Trending Markets: AGE excels - clear directional moves, high-probability setups
Choppy Markets: AGE struggles - fewer signals generated, lower win rate
Volatile Markets: AGE cautious - higher rejection rate, wider stops, fewer trades
Market Regime Changes:
When market shifts from trending to choppy overnight
Validated strategies can become temporarily invalidated
AGE will adapt through evolution, but not instantly
Expect 50-100 bar re-learning period after major regime shifts
Fitness may temporarily drop then recover
This is NOT a holy grail. It's a sophisticated signal generator that learns and adapts using genetic algorithms. Your success depends on:
Patience during learning periods (don't abandon after 3 losses)
Proper position sizing (risk 0.5-2% per trade, not 10%)
Following signals consistently (cherry-picking defeats statistical edge)
Not abandoning system prematurely (give it 200+ bars minimum)
Understanding probability (60% win rate means 40% of trades WILL lose)
Respecting market conditions (trending = trade more, choppy = trade less)
Managing emotions (AGE is emotionless, you need to be too)
Expected Drawdowns:
Single-strategy max DD: 10-20% of equity (normal)
Portfolio across multiple instruments: 5-15% (diversification helps)
Losing streaks: 3-5 consecutive losses expected periodically
No indicator eliminates risk. AGE manages risk through:
Quality gates (rejecting low-probability signals)
Confluence requirements (multi-indicator confirmation)
Persistence requirements (no knee-jerk reactions)
Regime awareness (reduced trading in chaos)
Walk-forward validation (preventing overfitting)
But it cannot prevent all losses. That's inherent to trading.
🔧 TECHNICAL SPECIFICATIONS
Platform: TradingView Pine Script v5
Indicator Type: Overlay indicator (plots on price chart)
Execution Type: Signals only - no automatic order placement
Computational Load:
Moderate to High (genetic algorithms + shadow portfolios)
8 strategies × shadow portfolio simulation = significant computation
Premium visuals add additional load (gradient cloud, fitness ribbon)
TradingView Resource Limits (Built-in Caps):
Max Bars Back: 500 (sufficient for WFO and evolution)
Max Labels: 100 (plenty for entry/exit markers)
Max Lines: 150 (adequate for stop/target lines)
Max Boxes: 50 (not heavily used)
Max Polylines: 100 (confidence halos)
Recommended Chart Settings:
Timeframe: 15min to 1H (optimal signal/noise balance)
5min: Works but noisier, more signals
4H/Daily: Works but fewer signals
Bars Loaded: 1000+ (ensures sufficient evolution history)
Replay Mode: Excellent for testing without risk
Performance Optimization Tips:
Disable gradient cloud if chart lags (most CPU intensive visual)
Disable fitness ribbon if still laggy
Reduce cloud layers from 7 to 3
Reduce ribbon layers from 10 to 5
Turn off diagnostics panel unless actively tuning
Close other heavy indicators to free resources
Browser/Platform Compatibility:
Works on all modern browsers (Chrome, Firefox, Safari, Edge)
Mobile app supported (full functionality on phone/tablet)
Desktop app supported (best performance)
Web version supported (may be slower on older computers)
Data Requirements:
Real-time or delayed data both work
No special data feeds required
Works with TradingView's standard data
Historical + live data seamlessly integrated
🎓 THEORETICAL FOUNDATIONS
AGE synthesizes advanced concepts from multiple disciplines:
Evolutionary Computation
Genetic Algorithms (Holland, 1975): Population-based optimization through natural selection metaphor
Tournament Selection: Fitness-based parent selection with diversity preservation
Crossover Operators: Fitness-weighted gene recombination from two parents
Mutation Operators: Random gene perturbation for exploration of new parameter space
Elitism: Preservation of top N performers to prevent loss of best solutions
Adaptive Parameters: Different mutation rates for historical vs. live phases
Technical Analysis
Support/Resistance: Price structure within swing ranges
Trend Following: EMA-based directional bias
Momentum Analysis: RSI, ROC, MACD composite indicators
Volatility Analysis: ATR-based risk scaling
Volume Confirmation: Trade activity validation
Information Theory
Shannon Entropy (1948): Quantification of market order vs. disorder
Signal-to-Noise Ratio: Directional information vs. random walk
Information Content: How much "information" a price move contains
Statistics & Probability
Walk-Forward Analysis: Rolling in-sample/out-of-sample optimization
Out-of-Sample Validation: Testing on unseen data to prevent overfitting
Monte Carlo Principles: Shadow portfolio simulation with realistic execution
Expectancy Theory: Win rate × avg win - loss rate × avg loss
Probability Distributions: Signal confidence quantification
Risk Management
ATR-Based Stops: Volatility-normalized risk per trade
Volatility Regime Detection: Market state classification (trending/choppy/volatile)
Drawdown Control: Peak-to-trough equity measurement
R-Multiple Normalization: Performance measurement in risk units
Machine Learning Concepts
Online Learning: Continuous adaptation as new data arrives
Fitness Functions: Multi-objective optimization (win rate + expectancy + drawdown)
Exploration vs. Exploitation: Balance between trying new strategies and using proven ones
Overfitting Prevention: Walk-forward validation as regularization
Novel Contribution:
AGE is the first TradingView indicator to apply genetic algorithms to real-time indicator parameter optimization while maintaining strict anti-overfitting controls through walk-forward validation.
Most "adaptive" indicators simply recalibrate lookback periods or thresholds. AGE evolves entirely new strategies through competitive selection - it's not parameter tuning, it's Darwinian evolution of trading logic itself.
The combination of:
Genetic algorithm population management
Shadow portfolio simulation for realistic fitness evaluation
Walk-forward validation to prevent overfitting
Multi-indicator confluence for signal quality
Dynamic volatility scaling for adaptive risk
...creates a system that genuinely learns and improves over time while avoiding the curse of curve-fitting that plagues most optimization approaches.
🏗️ DEVELOPMENT NOTES
This project represents months of intensive development, facing significant technical challenges:
Challenge 1: Making Genetics Actually Work
Early versions spawned garbage strategies that polluted the gene pool:
Random gene combinations produced nonsensical parameter sets
Weak strategies survived too long, dragging down population
No clear convergence toward optimal solutions
Solution:
Comprehensive fitness scoring (4 factors: win rate, P&L, expectancy, drawdown)
Elite preservation (top 2 always protected)
Walk-forward validation (unproven strategies penalized 30%)
Tournament selection (fitness-weighted breeding)
Adaptive culling (MAS decay creates increasing selection pressure)
Challenge 2: Balancing Evolution Speed vs. Stability
Too fast = population chaos, no convergence. Too slow = can't adapt to regime changes.
Solution:
Dual-phase timing: Fast evolution during historical (30/60 bar intervals), slow during live (200/400 bar intervals)
Adaptive mutation rates: 20% historical, 8% live
Spawn/cull ratio: Always 2:1 to prevent population collapse
Challenge 3: Shadow Portfolio Accuracy
Needed realistic trade simulation without lookahead bias:
Can't peek at future bars for exits
Must track multiple portfolios simultaneously
Stop/target checks must use bar's high/low correctly
Solution:
Entry on close (realistic)
Exit checks on current bar's high/low (realistic)
Independent position tracking per strategy
Cooldown periods to prevent unrealistic rapid re-entry
ATR-normalized P&L (R-multiples) for fair comparison across volatility regimes
Challenge 4: Pine Script Compilation Limits
Hit TradingView's execution limits multiple times:
Too many array operations
Too many variables
Too complex conditional logic
Solution:
Optimized data structures (single DNA array instead of 8 separate arrays)
Minimal visual overlays (only essential plots)
Efficient fitness calculations (vectorized where possible)
Strategic use of barstate.islast to minimize dashboard updates
Challenge 5: Walk-Forward Implementation
Standard WFO is difficult in Pine Script:
Can't easily "roll forward" through historical data
Can't re-optimize strategies mid-stream
Must work in real-time streaming environment
Solution:
Age-based phase detection (first 250 bars = training, next 75 = testing)
Separate metric tracking for train vs. test
Efficiency calculation at fixed interval (after test period completes)
Validation flag persists for strategy lifetime
Challenge 6: Signal Quality Control
Early versions generated too many signals with poor win rates:
Single indicators produced excessive noise
No trend alignment
No regime awareness
Instant entries on single-bar spikes
Solution:
Three-layer confluence system (entropy + momentum + structure)
Minimum 2-of-3 agreement requirement
Trend alignment checks (penalty for counter-trend)
Regime-based probability adjustments
Persistence requirements (signals must hold multiple bars)
Volume confirmation
Quality gate (probability + confluence thresholds)
The Result
A system that:
Truly evolves (not just parameter sweeps)
Truly validates (out-of-sample testing)
Truly adapts (ongoing competition and breeding)
Stays within TradingView's platform constraints
Provides institutional-quality signals
Maintains transparency (full metrics dashboard)
Development time: 3+ months of iterative refinement
Lines of code: ~1500 (highly optimized)
Test instruments: ES, NQ, EURUSD, BTCUSD, SPY, AAPL
Test timeframes: 5min, 15min, 1H, Daily
🎯 FINAL WORDS
The Adaptive Genesis Engine is not just another indicator - it's a living system that learns, adapts, and improves through the same principles that drive biological evolution. Every bar it observes adds to its experience. Every strategy it spawns explores new parameter combinations. Every strategy it culls removes weakness from the gene pool.
This is evolution in action on your charts.
You're not getting a static formula locked in time. You're getting a system that thinks , that competes , that survives through natural selection. The strongest strategies rise to the top. The weakest die. The gene pool improves generation after generation.
AGE doesn't claim to predict the future - it adapts to whatever the future brings. When markets shift from trending to choppy, from calm to volatile, from bullish to bearish - AGE evolves new strategies suited to the new regime.
Use it on any instrument. Any timeframe. Any market condition. AGE will adapt.
This indicator gives you the pure signal intelligence. How you choose to act on it - position sizing, risk management, execution discipline - that's your responsibility. AGE tells you when and how confident . You decide whether and how much .
Trust the process. Respect the evolution. Let Darwin work.
"In markets, as in nature, it is not the strongest strategies that survive, nor the most intelligent - but those most responsive to change."
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
— Happy Holiday's
Luxy Sector & Industry RS AnalyzerEver wonder why some stocks soar while others in the same sector barely move? Or why your perfectly timed entry still loses money? Possibly the answer can be found in Relative Strength.
The Luxy Sector & Industry RS Analyzer solves a critical problem that most traders overlook: picking strong stocks in strong sectors AND strong industries . It's not enough for a stock to go up - you want stocks that are crushing their competition at both the sector AND industry level. This indicator does the heavy lifting by automatically comparing your stock against its sector ETF, industry ETF, the broader market, sector leader, and industry leader, giving you a complete multi-level picture of relative performance.
What makes this different?
- Automatic sector AND industry detection - no manual setup required
- Multi-level hierarchy analysis: Market → Sector → Industry → Stock
- Multi-timeframe analysis (1 month to 1 year) in one glance
- Industry ETF mapping (30+ industries covered)
- Clear 0-100 scoring system with letter grades (A+ to F)
- Works on stocks, crypto, forex, and commodities
- Real-time updates with anti-repaint protection
Think of it as your performance dashboard - instantly showing you if you're trading a champion or a laggard at every level of the market hierarchy.
METHODOLOGY & ATTRIBUTION
This indicator is based on classical Relative Strength (RS) analysis principles from technical analysis. RS methodology compares an asset's price performance against a benchmark to identify relative outperformance or underperformance. This concept has been used by professional traders and institutions for decades.
Key Concepts Used:
Relative Strength (RS) - Classical technical analysis concept measuring comparative performance
Multi-Level Hierarchy Analysis - Market → Sector → Industry → Stock comparison
Sector Rotation Analysis - Identifying which sectors are leading or lagging the market
Industry Rotation Analysis - Identifying which industries are leading within their sectors
Multi-period Performance Analysis - Evaluating strength across multiple timeframes
Beta Calculation - Standard statistical measure of volatility relative to a benchmark
DISCLAIMER: This indicator is for educational and informational purposes only. It should not be considered financial advice or a recommendation to buy or sell. Past performance does not guarantee future results. Trading involves risk and may not be suitable for all investors. Always do your own research and consult with a financial advisor before making investment decisions.
with all rows visible - capture when stock has strong RS score (70+) so users can see what a "good" setup looks like]
WHAT THE INDICATOR SHOWS
1. AUTOMATIC ASSET TYPE DETECTION
The indicator automatically identifies what you're analyzing and adjusts accordingly:
Stocks - Compares to sector ETF (XLK, XLF, XLV, etc.) and SPY
Crypto - Compares to Total Crypto Market Cap and Bitcoin
Forex - Compares to relevant currency index (DXY, EXY, etc.)
Commodities - Compares to Gold (GLD) as benchmark
Indices - Compares to broader market indices
How it works: The indicator reads your chart's asset type and ticker, then automatically maps it to the correct sector or benchmark. For stocks, it uses intelligent sector detection (looking at the sector field) to match you with the right sector ETF. For example:
- Technology stocks get compared to XLK (Technology Select Sector SPDR)
- Financial stocks get compared to XLF (Financial Select Sector SPDR)
- Healthcare stocks get compared to XLV (Health Care Select Sector SPDR)
This happens instantly when you add the indicator to any chart - no configuration needed.
2. SECTOR & MARKET BENCHMARKS
What is a Sector ETF?
A sector ETF is an exchange-traded fund that tracks a specific industry group. For example, XLK contains all major technology companies. By comparing your stock to its sector ETF, you can see if your stock is outperforming or underperforming its peers.
The indicator shows three key comparison points:
Stock vs Sector (Benchmark)
This tells you how your stock performs compared to companies in the same industry. Positive numbers mean your stock is beating the sector average. Negative numbers mean it's lagging behind.
Stock vs Market (SPY)
This shows performance against the broader S&P 500 index. This is important because even if a stock beats its sector, the entire sector might be weak. You want stocks that beat both their sector AND the market.
Sector vs Market
This reveals "sector rotation" - whether money is flowing into or out of this sector. When this number is positive, the whole sector is hot and leading the market. This is powerful because strong sectors tend to lift all boats, making it easier to find winners.
3. MULTI-PERIOD PERFORMANCE ANALYSIS
The indicator calculates performance across four timeframes simultaneously:
1 Month (1M) - Recent short-term momentum
3 Months (3M) - Medium-term trend strength
6 Months (6M) - Longer-term positioning
1 Year (1Y) - Full-cycle performance view
Why multiple periods matter:
A stock might look great over 1 month but terrible over 6 months - that's a red flag. The best stocks show consistent strength across all timeframes . When you see positive RS (Relative Strength) values across all four periods, you've found a stock with sustained outperformance.
Each row in the table shows:
- Raw performance percentage for that period
- RS value (the difference compared to benchmark)
- Color coding: Green for positive, red for negative, white for neutral
4. SECTOR LEADER COMPARISON
The indicator automatically identifies and compares your stock to the sector leader - the dominant stock in that industry.
Sector leaders by industry:
Technology: Apple (AAPL)
Healthcare: UnitedHealth (UNH)
Financial: JPMorgan Chase (JPM)
Energy: ExxonMobil (XOM)
Consumer Discretionary: Amazon (AMZN)
Consumer Staples: Walmart (WMT)
And more...
Why this matters:
Comparing to the leader shows you if you're trading a champion or a follower. If your stock consistently beats the sector leader, you've found something special. If it's lagging the leader, you might want to trade the leader instead.
Optional Custom Leader:
You can override the automatic leader and compare to any stock you choose. This is useful if you want to benchmark against a specific competitor or reference stock.
NEW! INDUSTRY ANALYSIS (STOCKS ONLY)
The indicator now provides multi-level analysis by automatically detecting and comparing your stock to its specific industry , not just the broad sector.
Why Industry matters:
Technology sector (XLK) contains many different industries: Software, Semiconductors, Hardware, etc. A software stock might beat the broad tech sector but lag behind other software companies. Industry analysis provides this granular view.
Industry ETF Mapping (30+ industries):
Software/Applications: IGV (iShares Software ETF)
Semiconductors: SMH (VanEck Semiconductor ETF)
Biotech: IBB (iShares Biotechnology ETF)
Pharmaceuticals: XPH (SPDR Pharmaceuticals ETF)
Banks: KBE (SPDR S&P Bank ETF)
Regional Banks: KRE (SPDR Regional Banking ETF)
Oil & Gas Exploration: XOP (SPDR Oil & Gas Exploration ETF)
Homebuilders: XHB (SPDR Homebuilders ETF)
Retail: XRT (SPDR S&P Retail ETF)
Aerospace & Defense: ITA (iShares U.S. Aerospace & Defense ETF)
And many more...
Industry Leader Mapping:
The indicator also identifies the leader within each industry:
Software: Microsoft (MSFT)
Semiconductors: NVIDIA (NVDA)
Biotech: Amgen (AMGN)
Pharmaceuticals: Eli Lilly (LLY)
Banks: JPMorgan (JPM)
Oil Exploration: ConocoPhillips (COP)
And more...
New Table Rows for Stocks:
Industry ETF Performance - How the specific industry performed (green background)
Industry Leader Performance - How the top stock in the industry performed
vs Industry RS - Your stock's outperformance vs its industry ETF
Industry vs Sector RS - Is this industry hot or cold within its sector?
vs Industry Leader RS - Your stock's performance vs the industry's best
Why this is powerful:
A stock that beats both its sector AND its industry is showing strength at every level. This indicates true relative strength, not just riding sector-wide momentum.
Optional Custom Industry:
You can override automatic detection for both Industry ETF and Industry Leader in settings.
5. RS SCORE & GRADING SYSTEM (0-100)
The heart of the indicator is the RS Score - a weighted calculation that distills all the performance data into one clear number from 0 to 100.
How the score is calculated:
FOR STOCKS (with Industry data):
The indicator splits the weight between Sector (60%) and Industry (40%):
SECTOR RS (60% of total weight):
1 Month RS: 24% weight (40% × 0.6)
3 Month RS: 18% weight (30% × 0.6)
6 Month RS: 12% weight (20% × 0.6)
1 Year RS: 6% weight (10% × 0.6)
INDUSTRY RS (40% of total weight):
1 Month RS: 16% weight (40% × 0.4)
3 Month RS: 12% weight (30% × 0.4)
6 Month RS: 8% weight (20% × 0.4)
1 Year RS: 4% weight (10% × 0.4)
FOR OTHER ASSETS (Crypto, Forex, Commodities):
Uses full 100% weight on benchmark:
1 Month RS: 40% weight
3 Month RS: 30% weight
6 Month RS: 20% weight
1 Year RS: 10% weight
It starts at 50 (neutral) and adds or subtracts points based on your asset's relative strength in each period.
Bonus points:
+5 points if the sector is outperforming the market (sector rotation is bullish)
+5 points if the industry is outperforming its sector (hot industry) - STOCKS ONLY
+5 points if RS momentum is improving (getting stronger over time)
-5 points if RS momentum is declining (getting weaker)
The final score is capped between 0-100.
Letter Grade System:
90-100: A+ - Elite performer, crushing the sector
85-89: A - Excellent, strong outperformer
80-84: A- - Very good, above average
75-79: B+ - Good, solid performer
70-74: B - Above average, decent strength
65-69: B- - Slightly above average
60-64: C+ - Average, neutral strength
55-59: C - Below average
50-54: C- - Weak, slight underperformance
45-49: D+ - Concerning weakness
40-44: D - Poor, significant underperformance
0-39: F - Failing, avoid this stock
What scores mean for trading:
- RS Score above 70: Strong stocks worth considering for long positions
- RS Score 50-70: Average stocks, better opportunities elsewhere
- RS Score below 50: Weak stocks, avoid or consider for shorts
6. CONSISTENCY SCORE
This metric shows what percentage of time periods show positive RS .
For STOCKS (with Industry data):
Counts both Sector RS periods AND Industry RS periods (up to 8 total periods):
- If a stock beats both sector and industry in all 4 periods each: Consistency = 100% (8/8)
- If it beats in 6 out of 8 total periods: Consistency = 75%
- If it beats in 4 out of 8 total periods: Consistency = 50%
For OTHER ASSETS:
Counts benchmark periods only (4 total):
- If it beats benchmark in all 4 periods (1M, 3M, 6M, 1Y): Consistency = 100%
- If it beats in 3 out of 4 periods: Consistency = 75%
- If it beats in 2 out of 4 periods: Consistency = 50%
Why consistency matters:
A high RS Score with low consistency might indicate a recent spike that could fade. The best stocks show both high RS Score AND high consistency - they're strong now AND have been strong historically at both the sector AND industry level.
Look for stocks with:
Consistency above 75%: Very reliable strength across all levels
Consistency 50-75%: Decent but check other metrics
Consistency below 50%: Weak or erratic, proceed with caution
7. BETA CALCULATION (Volatility Measure)
Beta measures how much more volatile your stock is compared to its sector.
Beta > 1.2 : High volatility - stock moves more aggressively than sector (marked as "High")
Beta 0.8-1.2 : Normal volatility - moves roughly in line with sector
Beta < 0.8 : Low volatility - stock is more stable than sector (marked as "Low")
Formula used:
Beta = Correlation(Stock, Sector) × (Standard Deviation of Stock / Standard Deviation of Sector)
This uses a 20-period calculation for reliability.
How to use Beta:
- High Beta stocks offer bigger gains but also bigger risks - good for aggressive traders
- Low Beta stocks are more defensive - good for conservative positions
- Match Beta to your risk tolerance and strategy
8. DAYS ABOVE/BELOW SECTOR
This tracks consecutive periods (bars) where your stock outperforms or underperforms its sector.
Days Above Sector:
Counts how many bars in a row your stock has beaten the sector.
10+ days: Strong sustained strength (shown in bright green)
5-9 days: Building momentum (shown in yellow)
1-4 days: Early strength (shown in white)
0 days: Not currently outperforming
Days Below Sector:
Counts how many bars in a row your stock has lagged the sector.
10+ days: Sustained weakness (shown in bright red)
5-9 days: Losing momentum (shown in orange)
1-4 days: Minor weakness (shown in white)
0 days: Not underperforming (this is good!)
Why this matters:
Long streaks show trend persistence. A stock with 15+ days above sector is riding strong momentum. A stock with 15+ days below sector is in a sustained downtrend relative to peers.
9. PRICE VS 52-WEEK HIGH
Shows where current price sits relative to its 52-week high (or equivalent for your timeframe).
95%+ (green) : Stock is near all-time highs - strong positioning
80-94% (yellow) : Stock is in a pullback but still relatively strong
Below 80% : Stock has pulled back significantly from highs
Why this matters:
The strongest stocks stay near their highs. When you see a stock with high RS Score AND price near 52W high, you've found a stock with institutional support and strong buying pressure.
10. RELATIVE VOLUME
Compares current volume to the 20-period average volume.
1.5x+ (green) : High volume - significant interest and participation
Around 1.0x : Average volume - normal trading activity
Below 1.0x : Low volume - less interest or inactive period
Why volume matters:
High relative volume confirms price moves. When a stock makes a strong move on 2x or 3x normal volume, it's more likely to sustain. Low volume moves are often just noise.
11. AVERAGE RS STRENGTH
This calculates the average absolute value of all RS readings across the four timeframes.
It shows the magnitude of divergence from the sector, regardless of direction. A high number means the stock moves very differently from its sector (could be much stronger or much weaker). A low number means it tracks closely with the sector.
High Average RS: Stock has strong character, moves independently
Low Average RS: Stock follows sector closely, lacks individual strength
12. SECTOR ROTATION SIGNAL
This indicator automatically detects when a sector is experiencing bullish rotation - meaning money is flowing into the sector and it's outperforming the broader market.
Condition for bullish rotation:
Sector must be beating SPY (market) in both 1-month AND 3-month periods.
Why this matters:
Stocks in hot sectors tend to perform better because they have tailwinds from sector-wide buying. When sector rotation is bullish and your stock has a high RS Score, you've found an ideal setup.
The indicator adds +5 bonus points to the RS Score when sector rotation is bullish.
13. MOMENTUM DETECTION
The indicator compares 1-month RS to 3-month RS to detect if momentum is improving or declining.
RS Momentum Improving: 1M RS is better than 3M RS - stock is getting stronger (adds +5 to score)
RS Momentum Declining: 1M RS is worse than 3M RS - stock is getting weaker (subtracts -5 from score)
Why momentum matters:
You want to catch stocks as momentum is building, not after it's already peaked. Improving momentum suggests the strength is accelerating, not fading.
14. OVERALL ASSESSMENT & RECOMMENDATION
The indicator provides two quick summary rows:
Overall Rating:
Based on grade and RS Score, you get an instant quality rating:
Strong Leader (A/A+) - Top tier stock, crushing it
Above Average (A-/B+) - Solid performer, better than most
Average (B/B-) - Middle of the pack
Below Average (C/C+) - Struggling, watch carefully
Underperformer (D/F) - Weak stock, underperforming badly
Trading Signal:
Combines multiple factors to give setup quality:
STRONG BUY SETUP - RS Score 70+, Consistency 75+, AND sector rotation bullish. This is the perfect storm - strong stock, consistent strength, hot sector.
BULLISH - RS Score 60+, Consistency 50+. Good quality stock worth considering.
NEUTRAL - RS Score 50+. Okay but not exciting, better opportunities exist.
WEAK - RS Score 40-49. Below average, risky.
AVOID - RS Score below 40. Stay away, too weak.
IMPORTANT: These are educational signals only, not financial advice. Always do your own analysis and risk management.
KEY FEATURES
1. AUTOMATIC EVERYTHING
- Auto-detects asset type (stock, crypto, forex, commodity, index)
- Auto-maps stocks to correct sector ETF (11 sectors covered)
- Auto-maps stocks to correct industry ETF (30+ industries covered)
- Auto-identifies sector leader AND industry leader
- Auto-selects appropriate market benchmark
- Zero configuration required - just add to chart
2. MULTI-ASSET SUPPORT
Works on all asset classes:
US Stocks - Compares to sector ETFs (XLK, XLF, XLV, etc.)
Crypto - Compares to Total Crypto Market Cap
Forex - Compares to currency indices (DXY, EXY, etc.)
Commodities - Compares to Gold (GLD)
Indices - Compares to broader market benchmarks
3. FLEXIBLE DISPLAY
9 table positions (top/middle/bottom, left/center/right)
4 size options (tiny, small, normal, large)
Show/hide table completely
Real-time indicator toggle
4. TIMEFRAME FLEXIBILITY
Choose your analysis timeframe:
Chart Timeframe (default) - Uses whatever timeframe your chart is on
Fixed: 1 Hour, 4 Hours, Daily, Weekly - Forces calculations to specific timeframe
This means you can be on a 5-minute chart but analyze RS on Daily timeframe if you prefer.
5. RS SCORE FILTERING
Set a minimum RS Score threshold to only see strong stocks:
Set to 0 - Shows all stocks
Set to 70 - Only displays stocks with RS Score 70+ (strong stocks only)
Warning message displays if stock doesn't meet threshold
Perfect for screening - quickly scan multiple charts and the indicator only shows tables for stocks that pass your quality filter.
6. CUSTOM LEADER COMPARISON
Override automatic leader detection:
Compare to any ticker you choose
Benchmark against specific competitors
Use your own reference stocks
7. COMPREHENSIVE TOOLTIPS
Every input parameter and every table row has detailed tooltips explaining:
What the metric measures
How to interpret the values
What thresholds indicate strength/weakness
Why it matters for trading
Hover over any element to learn - it's like having a trading coach built in.
8. SMART ALERTS
Built-in alert system for key events:
Divergence Alerts:
Get notified when your stock diverges significantly from its sector.
Bullish Divergence: Stock beating sector by threshold percentage
Bearish Divergence: Stock losing to sector by threshold percentage
Set your threshold (default 5%) - this determines how big a divergence triggers the alert.
RS Score Alerts:
Get notified when RS Score crosses your threshold:
Crossed Above: RS Score went from below to above your threshold (bullish)
Crossed Below: RS Score dropped from above to below threshold (bearish)
Set your threshold (default 70) to focus on strong stocks.
Sector Rotation Alert:
Fires when sector shows bullish rotation (outperforming market).
HOW TO USE THE INDICATOR
FOR SWING TRADERS:
1. Add indicator to your watchlist stocks
2. Look for RS Score 70+ with Consistency 75%+
3. Check if sector rotation is bullish (bonus!)
4. Verify price is near 52W high (95%+)
5. Wait for entry setup on your chart
6. Use stop loss below key support
Example Setup:
Stock shows:
- RS Score: 82 (Grade: A-)
- Consistency: 100% (strong across all periods)
- Sector Rotation: Bullish
- Price vs 52W High: 96%
- Days Above Sector: 12 days
- Relative Volume: 1.8x
This is a textbook strong stock in a hot sector near highs - ideal for swing long.
FOR POSITION TRADERS:
1. Focus on 6-month and 1-year RS values
2. Look for sustained outperformance (Consistency 75%+)
3. Prefer lower Beta stocks (less volatility)
4. Check Days Above Sector for trend persistence
5. Monitor RS Score monthly, exit if drops below 60
FOR ACTIVE TRADERS:
1. Use on intraday timeframes (1H or 4H)
2. Set RS Score filter to 60+ for quick screening
3. Enable Divergence Alerts
4. Watch for momentum improving signal
5. Higher Beta stocks offer more movement
FOR SHORT SELLERS:
1. Look for RS Score below 40 (Grade: D or F)
2. Check for declining momentum
3. Verify Days Below Sector is increasing (10+)
4. Sector rotation should be bearish
5. Price should be well off 52W high
WHAT MAKES A PERFECT SETUP:
The holy grail combination:
RS Score: 75+ (A- or better)
Consistency: 80%+ (strong across time - beats sector AND industry)
Sector Rotation: Bullish (hot sector)
Industry vs Sector: Positive (hot industry within sector)
Days Above Sector: 10+ (sustained strength)
Momentum: Improving (getting stronger)
Price vs 52W High: 90%+ (near highs)
Relative Volume: 1.5x+ (volume confirmation)
When you find this combination, you've located a stock with every advantage in its favor - strong at the stock level, industry level, AND sector level. That's multi-level confirmation of relative strength.
IMPORTANT NOTES
Data Reliability:
All calculations use lookahead=off for anti-repaint protection
Historical values will never change
Real-time indicator toggle only affects the visual clock icon, not data reliability
All security requests are properly configured to prevent future data leakage
Sector Mapping Notes:
Sector detection uses TradingView's sector field
Some stocks may not have sector data - indicator will adapt
Sector ETFs used: XLK, XLF, XLV, XLE, XLY, XLP, XLI, XLB, XLRE, XLU, XLC
Major market ETFs (SPY, QQQ, DIA) are treated as market benchmarks, not stocks
Multi-Asset Notes:
Crypto compares to CRYPTOCAP:TOTAL (total crypto market cap)
Forex compares to relevant currency index based on base currency
Commodities compare to Gold (GLD) as primary commodity benchmark
Custom leaders can be set for any asset type
FREQUENTLY ASKED QUESTIONS
Q: What does RS Score of 75 actually mean?
A: It means your stock is strongly outperforming its sector across multiple timeframes. The score is weighted toward recent performance (1-month gets 40% weight), so 75 indicates sustained relative strength with emphasis on current momentum.
Q: My stock has high RS Score but is going down. Why?
A: RS Score measures relative performance (vs sector/market), not absolute price direction. A stock can fall 5% while its sector falls 10% - that's still positive relative strength. In bear markets or sector corrections, high RS stocks often fall less than peers.
Q: Should I only trade stocks with RS Score above 70?
A: For long positions, yes - focus on 70+ scores. These stocks have proven they can beat their sector. However, for pairs trading or relative value plays, you might also short stocks with scores below 40 while longing stocks above 70.
Q: What if my stock doesn't have a sector?
A: The indicator handles this gracefully. If no sector is detected, it will compare directly to the market (SPY for stocks). Some rows may show N/A, but the indicator will still provide useful market-relative data.
Q: Why does the sector sometimes show N/A?
A: This happens when: 1) Your asset has no sector classification, 2) The stock IS the sector ETF itself, 3) You're analyzing a non-stock asset (crypto, forex, commodity). The indicator adapts by focusing on market-relative metrics instead.
Q: Can I use this on cryptocurrencies?
A: Yes! The indicator automatically detects crypto and compares to the Total Crypto Market Cap (CRYPTOCAP:TOTAL). You can also set a custom leader like Bitcoin (BTCUSD) to compare against the dominant crypto.
Q: What's the difference between RS Score and Consistency?
A: RS Score is the weighted average of how much you're beating the sector (magnitude). Consistency is what percentage of time periods show outperformance (reliability). You want both high - that means strong AND consistent.
Q: Do the alerts repaint?
A: No. All alerts fire only on bar close (barstate.isconfirmed) and use properly configured data with lookahead=off. Once an alert fires, it's final and won't change.
Q: What timeframe should I use?
A: For swing trading: Daily or Weekly. For day trading: 1H or 4H. For position trading: Weekly. Use "Chart Timeframe" mode and switch your chart timeframe to change the analysis period easily.
Q: Why is Days Above Sector showing 0?
A: This means your stock is not currently outperforming its sector. If Days Below Sector is also 0, it means the RS is exactly neutral (very rare). Check the actual RS values to see current standing.
Q: Can I compare to a different market benchmark than SPY?
A: Currently the indicator uses SPY (S&P 500) as the default US stock market benchmark. For crypto it uses CRYPTOCAP:TOTAL, for forex it uses currency indices, etc. The benchmark auto-adjusts based on asset type.
Q: What's a good Beta value?
A: It depends on your strategy. Aggressive traders prefer Beta above 1.2 (more volatility = bigger moves). Conservative traders prefer Beta 0.8-1.0 (more stable). Beta is neutral - it's about matching your risk tolerance.
Q: How often does the table update?
A: With Real-time Indicator enabled: Every tick (constant updates). With it disabled: Only on bar close. Either way, the underlying data is identical and non-repainting - the toggle only affects update frequency and the clock icon display.
Q: My stock is showing "AVOID" but it's up 50% this year. Is the indicator wrong?
A: Not necessarily. The indicator measures RELATIVE performance. If your stock is up 50% but the sector is up 100%, your stock is actually underperforming by 50%. The indicator helps you identify when you should switch to stronger stocks in the same sector.
Q: What does "Strong Buy Setup" really mean?
A: It means three things aligned: 1) RS Score above 70 (strong stock), 2) Consistency above 75% (reliable strength), 3) Sector rotation is bullish (hot sector). This combination historically correlates with stocks that continue outperforming. However, this is NOT financial advice - always do your own analysis.
Q: Can I use this for options trading?
A: Yes! High RS Score stocks make good candidates for call options (bullish bets) while low RS Score stocks may work for puts (bearish bets). Higher Beta stocks will have more volatile options (higher premiums but more movement).
Q: Why is my crypto showing N/A for sector?
A: Cryptocurrencies don't have "sectors" like stocks do. Instead, the indicator compares crypto to the total crypto market cap. This is normal and expected behavior.
Q: What happens if I'm analyzing an ETF?
A: If you're analyzing a sector ETF (like XLK), it will compare to SPY (market). If you're analyzing SPY itself, some comparisons won't be available (can't compare SPY to itself). The indicator intelligently adapts to avoid circular comparisons.
Q: What if my stock doesn't have industry data?
A: Not all stocks are mapped to specific industries (only 30+ major industries are covered). If no industry is detected, the indicator will still work using only sector analysis. The RS Score calculation will use 100% sector weight instead of the 60%/40% split.
Q: Why does Industry vs Sector matter?
A: Industry vs Sector shows if your specific industry is hot or cold within its broader sector. For example, Semiconductors (SMH) might be outperforming Technology sector (XLK) even though both are up. This helps you find not just strong sectors, but the strongest industries within those sectors.
Q: Can I disable Industry analysis?
A: Yes! In the "Industry Analysis" settings group, you can toggle off "Show Industry Analysis in Table" to hide all industry rows. However, even when hidden, industry data still contributes to the RS Score calculation for stocks.
Q: Why is my Consistency Score lower for stocks than other assets?
A: For stocks with industry data, Consistency counts 8 periods (4 Sector + 4 Industry periods) instead of just 4. This means the bar is higher - your stock needs to beat both sector AND industry consistently. A stock that beats sector in all 4 periods but lags industry in 2 periods will show 75% consistency (6/8), not 100%.
BEST PRACTICES
Use as a screening tool - Set RS Score filter to 70+ and quickly scan your watchlist. Only strong stocks will show the table.
Combine with technical analysis - RS Score tells you WHAT to trade, your chart tells you WHEN to enter.
Check multiple timeframes - Switch between Daily and Weekly to see if strength holds across different time horizons.
Monitor sector rotation - When sector goes from bearish to bullish rotation, it's often a great time to enter stocks in that sector.
Watch Industry vs Sector - Stocks in hot industries within hot sectors have double tailwinds. Prioritize Industry vs Sector positive values.
Pay attention to consistency - High RS Score with low consistency might be a spike that fades. Look for 70%+ consistency across BOTH sector and industry.
Use the leader comparison - If your stock consistently beats both sector leader AND industry leader, you may have found the next champion.
Watch days above/below sector - Long streaks (15+ days) indicate strong trends. Look for these in conjunction with high RS Score.
Set alerts on key stocks - Enable RS Score alerts at 70 threshold to get notified when watchlist stocks become strong.
Consider Beta for position sizing - Size smaller positions in high Beta stocks, larger in low Beta stocks for balanced risk.
Exit when RS Score drops - If a stock's RS Score falls below 60, consider reducing or exiting - the strength may be fading.
Leverage industry-level insight - If Industry ETF is weak but stock is strong, that's standout strength. If Industry is hot but stock is lagging, consider switching to the industry leader instead.
SETTINGS EXPLAINED
Display Settings:
Show Performance Table - Master on/off switch for the table
Table Position - 9 positions available (corners, edges, center)
Table Size - 4 sizes (tiny, small, normal, large) for different screen sizes
Timeframe Settings:
Chart Timeframe (recommended) - Dynamic, uses whatever chart TF you're on
Fixed Timeframes - Locks analysis to 1H, 4H, Daily, or Weekly regardless of chart
Filtering Settings:
Minimum RS Score - Set threshold (0-100) for displaying table
Show Warning - When enabled, displays message if stock doesn't meet filter
Alert Settings:
Divergence Alerts - Enable alerts when stock diverges from sector
Threshold (%) - How big a divergence triggers alert (default 5%)
RS Score Alerts - Enable alerts when RS Score crosses threshold
Threshold - What RS Score level triggers alert (default 70)
Sector Analysis Settings:
Use Custom Sector ETF - Override automatic sector ETF detection
Sector ETF Symbol - Enter any sector ETF to compare against
Use Custom Sector Leader - Override automatic sector leader detection
Sector Leader Symbol - Enter any ticker as sector leader
Industry Analysis Settings:
Use Custom Industry ETF - Override automatic industry ETF detection
Industry ETF Symbol - Enter specific industry ETF (e.g., IGV, SMH)
Use Custom Industry Leader - Override automatic industry leader detection
Industry Leader Symbol - Enter specific industry leader
Show Industry Analysis - Toggle all industry rows on/off
Display Settings:
Show Real-time Indicator - Toggle clock icon in header (doesn't affect data)
WHAT THIS INDICATOR DOESN'T DO
To set proper expectations:
Does NOT provide entry/exit signals - this is a strength analyzer, not a trading system
Does NOT predict future price movement - shows current and historical relative strength
Does NOT guarantee profits - strong RS stocks can still decline
Does NOT replace your own analysis - use as one tool among many
Does NOT work on stocks with no sector data - will adapt but some rows show N/A
This indicator is a decision support tool . It helps you identify which stocks are showing relative strength so you can make more informed trading decisions. You still need your own entry strategy, risk management, and position sizing rules.
SUPPORT & CONTACT
Questions or feedback? Use the comments section below or send me a message.
If you find this indicator useful, please give it a boost and share with other traders who might benefit from relative strength analysis.
FINAL REMINDER
This indicator is a tool for analyzing relative strength - it shows you which stocks are outperforming their sector and market. It does NOT provide financial advice or trade signals. Always conduct your own research, manage your risk appropriately, and consult with a financial advisor before making investment decisions.
Past performance of relative strength does not guarantee future results. Strong stocks can become weak, and sectors rotate in and out of favor. Use this indicator as part of a comprehensive trading strategy, not as a standalone decision-making system.
Trade smart, manage risk, and may your RS Scores stay high!
If you got till here and you like my work a BOOST and a COMMENT would make me happy
Advanced Correlation Monitor📊 Advanced Correlation Monitor - Pine Script v6
🎯 What does this indicator do?
Monitors real-time correlations between 13 different asset pairs and alerts you when historically strong correlations break, indicating potential trading opportunities or changes in market dynamics.
🚀 Key Features
✨ Multi-Market Monitoring
7 Forex Pairs (GBPUSD/DXY, EURUSD/GBPUSD, etc.)
6 Index/Stock Pairs (SPY/S&P500, DAX/NASDAQ, TSLA/NVDA, etc.)
Fully configurable - change any pair from inputs
📈 Dual Correlation Analysis
Long Period (90 bars): Identifies historically strong correlations
Short Period (6 bars): Detects recent breakdowns
Pearson Correlation using Pine Script v6 native functions
🎨 Intuitive Visualization
Real-time table with 6 information columns
Color coding: Green (correlated), Red (broken), Gray (normal)
Visual states: 🟢 OK, 🔴 BROKEN, ⚫ NORMAL
🚨 Smart Alert System
Only alerts previously correlated pairs (>80% historical)
Detects breakdowns when short correlation <80%
Consolidated alert with all affected pairs
🛠️ Flexible Configuration
Adjustable Parameters:
📅 Periods: Long (30-500), Short (2-50)
🎯 Threshold: 50%-99% (default 80%)
🎨 Table: Configurable position and size
📊 Symbols: All pairs are configurable
Default Pairs:
FOREX: INDICES/STOCKS:
- GBPUSD vs DXY • SPY vs S&P500
- EURUSD vs GBPUSD • DAX vs S&P500
- EURUSD vs DXY • DAX vs NASDAQ
- USDCHF vs DXY • TSLA vs NVDA
- GBPUSD vs USDCHF • MSFT vs NVDA
- EURUSD vs USDCHF • AAPL vs NVDA
- EURUSD vs EURCAD
💡 Practical Use Cases
🔄 Pairs Trading
Detects when strong correlations break for:
Statistical arbitrage
Mean reversion trading
Divergence opportunities
🛡️ Risk Management
Identifies when "safe" assets start moving independently:
Portfolio diversification
Smart hedging
Regime change detection
📊 Market Analysis
Understand underlying market structure:
Forex/DXY correlations
Tech sector rotation
Regional market disconnection
🎓 Results Interpretation
Reading Example:
EURUSD vs DXY: -98.57% → -98.27% | 🟢 OK
└─ Perfect negative correlation maintained (EUR rises when DXY falls)
TSLA vs NVDA: 78.12% → 0% | ⚫ NORMAL
└─ Lost tech correlation (divergence opportunity)
Trading Signals:
🟢 → 🔴: Broken correlation = Possible opportunity
Large difference: Indicates correlation tension
Multiple breaks: Market regime change
Dimensional Resonance ProtocolDimensional Resonance Protocol
🌀 CORE INNOVATION: PHASE SPACE RECONSTRUCTION & EMERGENCE DETECTION
The Dimensional Resonance Protocol represents a paradigm shift from traditional technical analysis to complexity science. Rather than measuring price levels or indicator crossovers, DRP reconstructs the hidden attractor governing market dynamics using Takens' embedding theorem, then detects emergence —the rare moments when multiple dimensions of market behavior spontaneously synchronize into coherent, predictable states.
The Complexity Hypothesis:
Markets are not simple oscillators or random walks—they are complex adaptive systems existing in high-dimensional phase space. Traditional indicators see only shadows (one-dimensional projections) of this higher-dimensional reality. DRP reconstructs the full phase space using time-delay embedding, revealing the true structure of market dynamics.
Takens' Embedding Theorem (1981):
A profound mathematical result from dynamical systems theory: Given a time series from a complex system, we can reconstruct its full phase space by creating delayed copies of the observation.
Mathematical Foundation:
From single observable x(t), create embedding vectors:
X(t) =
Where:
• d = Embedding dimension (default 5)
• τ = Time delay (default 3 bars)
• x(t) = Price or return at time t
Key Insight: If d ≥ 2D+1 (where D is the true attractor dimension), this embedding is topologically equivalent to the actual system dynamics. We've reconstructed the hidden attractor from a single price series.
Why This Matters:
Markets appear random in one dimension (price chart). But in reconstructed phase space, structure emerges—attractors, limit cycles, strange attractors. When we identify these structures, we can detect:
• Stable regions : Predictable behavior (trade opportunities)
• Chaotic regions : Unpredictable behavior (avoid trading)
• Critical transitions : Phase changes between regimes
Phase Space Magnitude Calculation:
phase_magnitude = sqrt(Σ ² for i = 0 to d-1)
This measures the "energy" or "momentum" of the market trajectory through phase space. High magnitude = strong directional move. Low magnitude = consolidation.
📊 RECURRENCE QUANTIFICATION ANALYSIS (RQA)
Once phase space is reconstructed, we analyze its recurrence structure —when does the system return near previous states?
Recurrence Plot Foundation:
A recurrence occurs when two phase space points are closer than threshold ε:
R(i,j) = 1 if ||X(i) - X(j)|| < ε, else 0
This creates a binary matrix showing when the system revisits similar states.
Key RQA Metrics:
1. Recurrence Rate (RR):
RR = (Number of recurrent points) / (Total possible pairs)
• RR near 0: System never repeats (highly stochastic)
• RR = 0.1-0.3: Moderate recurrence (tradeable patterns)
• RR > 0.5: System stuck in attractor (ranging market)
• RR near 1: System frozen (no dynamics)
Interpretation: Moderate recurrence is optimal —patterns exist but market isn't stuck.
2. Determinism (DET):
Measures what fraction of recurrences form diagonal structures in the recurrence plot. Diagonals indicate deterministic evolution (trajectory follows predictable paths).
DET = (Recurrence points on diagonals) / (Total recurrence points)
• DET < 0.3: Random dynamics
• DET = 0.3-0.7: Moderate determinism (patterns with noise)
• DET > 0.7: Strong determinism (technical patterns reliable)
Trading Implication: Signals are prioritized when DET > 0.3 (deterministic state) and RR is moderate (not stuck).
Threshold Selection (ε):
Default ε = 0.10 × std_dev means two states are "recurrent" if within 10% of a standard deviation. This is tight enough to require genuine similarity but loose enough to find patterns.
🔬 PERMUTATION ENTROPY: COMPLEXITY MEASUREMENT
Permutation entropy measures the complexity of a time series by analyzing the distribution of ordinal patterns.
Algorithm (Bandt & Pompe, 2002):
1. Take overlapping windows of length n (default n=4)
2. For each window, record the rank order pattern
Example: → pattern (ranks from lowest to highest)
3. Count frequency of each possible pattern
4. Calculate Shannon entropy of pattern distribution
Mathematical Formula:
H_perm = -Σ p(π) · ln(p(π))
Where π ranges over all n! possible permutations, p(π) is the probability of pattern π.
Normalized to :
H_norm = H_perm / ln(n!)
Interpretation:
• H < 0.3 : Very ordered, crystalline structure (strong trending)
• H = 0.3-0.5 : Ordered regime (tradeable with patterns)
• H = 0.5-0.7 : Moderate complexity (mixed conditions)
• H = 0.7-0.85 : Complex dynamics (challenging to trade)
• H > 0.85 : Maximum entropy (nearly random, avoid)
Entropy Regime Classification:
DRP classifies markets into five entropy regimes:
• CRYSTALLINE (H < 0.3): Maximum order, persistent trends
• ORDERED (H < 0.5): Clear patterns, momentum strategies work
• MODERATE (H < 0.7): Mixed dynamics, adaptive required
• COMPLEX (H < 0.85): High entropy, mean reversion better
• CHAOTIC (H ≥ 0.85): Near-random, minimize trading
Why Permutation Entropy?
Unlike traditional entropy methods requiring binning continuous data (losing information), permutation entropy:
• Works directly on time series
• Robust to monotonic transformations
• Computationally efficient
• Captures temporal structure, not just distribution
• Immune to outliers (uses ranks, not values)
⚡ LYAPUNOV EXPONENT: CHAOS vs STABILITY
The Lyapunov exponent λ measures sensitivity to initial conditions —the hallmark of chaos.
Physical Meaning:
Two trajectories starting infinitely close will diverge at exponential rate e^(λt):
Distance(t) ≈ Distance(0) × e^(λt)
Interpretation:
• λ > 0 : Positive Lyapunov exponent = CHAOS
- Small errors grow exponentially
- Long-term prediction impossible
- System is sensitive, unpredictable
- AVOID TRADING
• λ ≈ 0 : Near-zero = CRITICAL STATE
- Edge of chaos
- Transition zone between order and disorder
- Moderate predictability
- PROCEED WITH CAUTION
• λ < 0 : Negative Lyapunov exponent = STABLE
- Small errors decay
- Trajectories converge
- System is predictable
- OPTIMAL FOR TRADING
Estimation Method:
DRP estimates λ by tracking how quickly nearby states diverge over a rolling window (default 20 bars):
For each bar i in window:
δ₀ = |x - x | (initial separation)
δ₁ = |x - x | (previous separation)
if δ₁ > 0:
ratio = δ₀ / δ₁
log_ratios += ln(ratio)
λ ≈ average(log_ratios)
Stability Classification:
• STABLE : λ < 0 (negative growth rate)
• CRITICAL : |λ| < 0.1 (near neutral)
• CHAOTIC : λ > 0.2 (strong positive growth)
Signal Filtering:
By default, NEXUS requires λ < 0 (stable regime) for signal confirmation. This filters out trades during chaotic periods when technical patterns break down.
📐 HIGUCHI FRACTAL DIMENSION
Fractal dimension measures self-similarity and complexity of the price trajectory.
Theoretical Background:
A curve's fractal dimension D ranges from 1 (smooth line) to 2 (space-filling curve):
• D ≈ 1.0 : Smooth, persistent trending
• D ≈ 1.5 : Random walk (Brownian motion)
• D ≈ 2.0 : Highly irregular, space-filling
Higuchi Method (1988):
For a time series of length N, construct k different curves by taking every k-th point:
L(k) = (1/k) × Σ|x - x | × (N-1)/(⌊(N-m)/k⌋ × k)
For different values of k (1 to k_max), calculate L(k). The fractal dimension is the slope of log(L(k)) vs log(1/k):
D = slope of log(L) vs log(1/k)
Market Interpretation:
• D < 1.35 : Strong trending, persistent (Hurst > 0.5)
- TRENDING regime
- Momentum strategies favored
- Breakouts likely to continue
• D = 1.35-1.45 : Moderate persistence
- PERSISTENT regime
- Trend-following with caution
- Patterns have meaning
• D = 1.45-1.55 : Random walk territory
- RANDOM regime
- Efficiency hypothesis holds
- Technical analysis least reliable
• D = 1.55-1.65 : Anti-persistent (mean-reverting)
- ANTI-PERSISTENT regime
- Oscillator strategies work
- Overbought/oversold meaningful
• D > 1.65 : Highly complex, choppy
- COMPLEX regime
- Avoid directional bets
- Wait for regime change
Signal Filtering:
Resonance signals (secondary signal type) require D < 1.5, indicating trending or persistent dynamics where momentum has meaning.
🔗 TRANSFER ENTROPY: CAUSAL INFORMATION FLOW
Transfer entropy measures directed causal influence between time series—not just correlation, but actual information transfer.
Schreiber's Definition (2000):
Transfer entropy from X to Y measures how much knowing X's past reduces uncertainty about Y's future:
TE(X→Y) = H(Y_future | Y_past) - H(Y_future | Y_past, X_past)
Where H is Shannon entropy.
Key Properties:
1. Directional : TE(X→Y) ≠ TE(Y→X) in general
2. Non-linear : Detects complex causal relationships
3. Model-free : No assumptions about functional form
4. Lag-independent : Captures delayed causal effects
Three Causal Flows Measured:
1. Volume → Price (TE_V→P):
Measures how much volume patterns predict price changes.
• TE > 0 : Volume provides predictive information about price
- Institutional participation driving moves
- Volume confirms direction
- High reliability
• TE ≈ 0 : No causal flow (weak volume/price relationship)
- Volume uninformative
- Caution on signals
• TE < 0 (rare): Suggests price leading volume
- Potentially manipulated or thin market
2. Volatility → Momentum (TE_σ→M):
Does volatility expansion predict momentum changes?
• Positive TE : Volatility precedes momentum shifts
- Breakout dynamics
- Regime transitions
3. Structure → Price (TE_S→P):
Do support/resistance patterns causally influence price?
• Positive TE : Structural levels have causal impact
- Technical levels matter
- Market respects structure
Net Causal Flow:
Net_Flow = TE_V→P + 0.5·TE_σ→M + TE_S→P
• Net > +0.1 : Bullish causal structure
• Net < -0.1 : Bearish causal structure
• |Net| < 0.1 : Neutral/unclear causation
Causal Gate:
For signal confirmation, NEXUS requires:
• Buy signals : TE_V→P > 0 AND Net_Flow > 0.05
• Sell signals : TE_V→P > 0 AND Net_Flow < -0.05
This ensures volume is actually driving price (causal support exists), not just correlated noise.
Implementation Note:
Computing true transfer entropy requires discretizing continuous data into bins (default 6 bins) and estimating joint probability distributions. NEXUS uses a hybrid approach combining TE theory with autocorrelation structure and lagged cross-correlation to approximate information transfer in computationally efficient manner.
🌊 HILBERT PHASE COHERENCE
Phase coherence measures synchronization across market dimensions using Hilbert transform analysis.
Hilbert Transform Theory:
For a signal x(t), the Hilbert transform H (t) creates an analytic signal:
z(t) = x(t) + i·H (t) = A(t)·e^(iφ(t))
Where:
• A(t) = Instantaneous amplitude
• φ(t) = Instantaneous phase
Instantaneous Phase:
φ(t) = arctan(H (t) / x(t))
The phase represents where the signal is in its natural cycle—analogous to position on a unit circle.
Four Dimensions Analyzed:
1. Momentum Phase : Phase of price rate-of-change
2. Volume Phase : Phase of volume intensity
3. Volatility Phase : Phase of ATR cycles
4. Structure Phase : Phase of position within range
Phase Locking Value (PLV):
For two signals with phases φ₁(t) and φ₂(t), PLV measures phase synchronization:
PLV = |⟨e^(i(φ₁(t) - φ₂(t)))⟩|
Where ⟨·⟩ is time average over window.
Interpretation:
• PLV = 0 : Completely random phase relationship (no synchronization)
• PLV = 0.5 : Moderate phase locking
• PLV = 1 : Perfect synchronization (phases locked)
Pairwise PLV Calculations:
• PLV_momentum-volume : Are momentum and volume cycles synchronized?
• PLV_momentum-structure : Are momentum cycles aligned with structure?
• PLV_volume-structure : Are volume and structural patterns in phase?
Overall Phase Coherence:
Coherence = (PLV_mom-vol + PLV_mom-struct + PLV_vol-struct) / 3
Signal Confirmation:
Emergence signals require coherence ≥ threshold (default 0.70):
• Below 0.70: Dimensions not synchronized, no coherent market state
• Above 0.70: Dimensions in phase, coherent behavior emerging
Coherence Direction:
The summed phase angles indicate whether synchronized dimensions point bullish or bearish:
Direction = sin(φ_momentum) + 0.5·sin(φ_volume) + 0.5·sin(φ_structure)
• Direction > 0 : Phases pointing upward (bullish synchronization)
• Direction < 0 : Phases pointing downward (bearish synchronization)
🌀 EMERGENCE SCORE: MULTI-DIMENSIONAL ALIGNMENT
The emergence score aggregates all complexity metrics into a single 0-1 value representing market coherence.
Eight Components with Weights:
1. Phase Coherence (20%):
Direct contribution: coherence × 0.20
Measures dimensional synchronization.
2. Entropy Regime (15%):
Contribution: (0.6 - H_perm) / 0.6 × 0.15 if H < 0.6, else 0
Rewards low entropy (ordered, predictable states).
3. Lyapunov Stability (12%):
• λ < 0 (stable): +0.12
• |λ| < 0.1 (critical): +0.08
• λ > 0.2 (chaotic): +0.0
Requires stable, predictable dynamics.
4. Fractal Dimension Trending (12%):
Contribution: (1.45 - D) / 0.45 × 0.12 if D < 1.45, else 0
Rewards trending fractal structure (D < 1.45).
5. Dimensional Resonance (12%):
Contribution: |dimensional_resonance| × 0.12
Measures alignment across momentum, volume, structure, volatility dimensions.
6. Causal Flow Strength (9%):
Contribution: |net_causal_flow| × 0.09
Rewards strong causal relationships.
7. Phase Space Embedding (10%):
Contribution: min(|phase_magnitude_norm|, 3.0) / 3.0 × 0.10 if |magnitude| > 1.0
Rewards strong trajectory in reconstructed phase space.
8. Recurrence Quality (10%):
Contribution: determinism × 0.10 if DET > 0.3 AND 0.1 < RR < 0.8
Rewards deterministic patterns with moderate recurrence.
Total Emergence Score:
E = Σ(components) ∈
Capped at 1.0 maximum.
Emergence Direction:
Separate calculation determining bullish vs bearish:
• Dimensional resonance sign
• Net causal flow sign
• Phase magnitude correlation with momentum
Signal Threshold:
Default emergence_threshold = 0.75 means 75% of maximum possible emergence score required to trigger signals.
Why Emergence Matters:
Traditional indicators measure single dimensions. Emergence detects self-organization —when multiple independent dimensions spontaneously align. This is the market equivalent of a phase transition in physics, where microscopic chaos gives way to macroscopic order.
These are the highest-probability trade opportunities because the entire system is resonating in the same direction.
🎯 SIGNAL GENERATION: EMERGENCE vs RESONANCE
DRP generates two tiers of signals with different requirements:
TIER 1: EMERGENCE SIGNALS (Primary)
Requirements:
1. Emergence score ≥ threshold (default 0.75)
2. Phase coherence ≥ threshold (default 0.70)
3. Emergence direction > 0.2 (bullish) or < -0.2 (bearish)
4. Causal gate passed (if enabled): TE_V→P > 0 and net_flow confirms direction
5. Stability zone (if enabled): λ < 0 or |λ| < 0.1
6. Price confirmation: Close > open (bulls) or close < open (bears)
7. Cooldown satisfied: bars_since_signal ≥ cooldown_period
EMERGENCE BUY:
• All above conditions met with bullish direction
• Market has achieved coherent bullish state
• Multiple dimensions synchronized upward
EMERGENCE SELL:
• All above conditions met with bearish direction
• Market has achieved coherent bearish state
• Multiple dimensions synchronized downward
Premium Emergence:
When signal_quality (emergence_score × phase_coherence) > 0.7:
• Displayed as ★ star symbol
• Highest conviction trades
• Maximum dimensional alignment
Standard Emergence:
When signal_quality 0.5-0.7:
• Displayed as ◆ diamond symbol
• Strong signals but not perfect alignment
TIER 2: RESONANCE SIGNALS (Secondary)
Requirements:
1. Dimensional resonance > +0.6 (bullish) or < -0.6 (bearish)
2. Fractal dimension < 1.5 (trending/persistent regime)
3. Price confirmation matches direction
4. NOT in chaotic regime (λ < 0.2)
5. Cooldown satisfied
6. NO emergence signal firing (resonance is fallback)
RESONANCE BUY:
• Dimensional alignment without full emergence
• Trending fractal structure
• Moderate conviction
RESONANCE SELL:
• Dimensional alignment without full emergence
• Bearish resonance with trending structure
• Moderate conviction
Displayed as small ▲/▼ triangles with transparency.
Signal Hierarchy:
IF emergence conditions met:
Fire EMERGENCE signal (★ or ◆)
ELSE IF resonance conditions met:
Fire RESONANCE signal (▲ or ▼)
ELSE:
No signal
Cooldown System:
After any signal fires, cooldown_period (default 5 bars) must elapse before next signal. This prevents signal clustering during persistent conditions.
Cooldown tracks using bar_index:
bars_since_signal = current_bar_index - last_signal_bar_index
cooldown_ok = bars_since_signal >= cooldown_period
🎨 VISUAL SYSTEM: MULTI-LAYER COMPLEXITY
DRP provides rich visual feedback across four distinct layers:
LAYER 1: COHERENCE FIELD (Background)
Colored background intensity based on phase coherence:
• No background : Coherence < 0.5 (incoherent state)
• Faint glow : Coherence 0.5-0.7 (building coherence)
• Stronger glow : Coherence > 0.7 (coherent state)
Color:
• Cyan/teal: Bullish coherence (direction > 0)
• Red/magenta: Bearish coherence (direction < 0)
• Blue: Neutral coherence (direction ≈ 0)
Transparency: 98 minus (coherence_intensity × 10), so higher coherence = more visible.
LAYER 2: STABILITY/CHAOS ZONES
Background color indicating Lyapunov regime:
• Green tint (95% transparent): λ < 0, STABLE zone
- Safe to trade
- Patterns meaningful
• Gold tint (90% transparent): |λ| < 0.1, CRITICAL zone
- Edge of chaos
- Moderate risk
• Red tint (85% transparent): λ > 0.2, CHAOTIC zone
- Avoid trading
- Unpredictable behavior
LAYER 3: DIMENSIONAL RIBBONS
Three EMAs representing dimensional structure:
• Fast ribbon : EMA(8) in cyan/teal (fast dynamics)
• Medium ribbon : EMA(21) in blue (intermediate)
• Slow ribbon : EMA(55) in red/magenta (slow dynamics)
Provides visual reference for multi-scale structure without cluttering with raw phase space data.
LAYER 4: CAUSAL FLOW LINE
A thicker line plotted at EMA(13) colored by net causal flow:
• Cyan/teal : Net_flow > +0.1 (bullish causation)
• Red/magenta : Net_flow < -0.1 (bearish causation)
• Gray : |Net_flow| < 0.1 (neutral causation)
Shows real-time direction of information flow.
EMERGENCE FLASH:
Strong background flash when emergence signals fire:
• Cyan flash for emergence buy
• Red flash for emergence sell
• 80% transparency for visibility without obscuring price
📊 COMPREHENSIVE DASHBOARD
Real-time monitoring of all complexity metrics:
HEADER:
• 🌀 DRP branding with gold accent
CORE METRICS:
EMERGENCE:
• Progress bar (█ filled, ░ empty) showing 0-100%
• Percentage value
• Direction arrow (↗ bull, ↘ bear, → neutral)
• Color-coded: Green/gold if active, gray if low
COHERENCE:
• Progress bar showing phase locking value
• Percentage value
• Checkmark ✓ if ≥ threshold, circle ○ if below
• Color-coded: Cyan if coherent, gray if not
COMPLEXITY SECTION:
ENTROPY:
• Regime name (CRYSTALLINE/ORDERED/MODERATE/COMPLEX/CHAOTIC)
• Numerical value (0.00-1.00)
• Color: Green (ordered), gold (moderate), red (chaotic)
LYAPUNOV:
• State (STABLE/CRITICAL/CHAOTIC)
• Numerical value (typically -0.5 to +0.5)
• Status indicator: ● stable, ◐ critical, ○ chaotic
• Color-coded by state
FRACTAL:
• Regime (TRENDING/PERSISTENT/RANDOM/ANTI-PERSIST/COMPLEX)
• Dimension value (1.0-2.0)
• Color: Cyan (trending), gold (random), red (complex)
PHASE-SPACE:
• State (STRONG/ACTIVE/QUIET)
• Normalized magnitude value
• Parameters display: d=5 τ=3
CAUSAL SECTION:
CAUSAL:
• Direction (BULL/BEAR/NEUTRAL)
• Net flow value
• Flow indicator: →P (to price), P← (from price), ○ (neutral)
V→P:
• Volume-to-price transfer entropy
• Small display showing specific TE value
DIMENSIONAL SECTION:
RESONANCE:
• Progress bar of absolute resonance
• Signed value (-1 to +1)
• Color-coded by direction
RECURRENCE:
• Recurrence rate percentage
• Determinism percentage display
• Color-coded: Green if high quality
STATE SECTION:
STATE:
• Current mode: EMERGENCE / RESONANCE / CHAOS / SCANNING
• Icon: 🚀 (emergence buy), 💫 (emergence sell), ▲ (resonance buy), ▼ (resonance sell), ⚠ (chaos), ◎ (scanning)
• Color-coded by state
SIGNALS:
• E: count of emergence signals
• R: count of resonance signals
⚙️ KEY PARAMETERS EXPLAINED
Phase Space Configuration:
• Embedding Dimension (3-10, default 5): Reconstruction dimension
- Low (3-4): Simple dynamics, faster computation
- Medium (5-6): Balanced (recommended)
- High (7-10): Complex dynamics, more data needed
- Rule: d ≥ 2D+1 where D is true dimension
• Time Delay (τ) (1-10, default 3): Embedding lag
- Fast markets: 1-2
- Normal: 3-4
- Slow markets: 5-10
- Optimal: First minimum of mutual information (often 2-4)
• Recurrence Threshold (ε) (0.01-0.5, default 0.10): Phase space proximity
- Tight (0.01-0.05): Very similar states only
- Medium (0.08-0.15): Balanced
- Loose (0.20-0.50): Liberal matching
Entropy & Complexity:
• Permutation Order (3-7, default 4): Pattern length
- Low (3): 6 patterns, fast but coarse
- Medium (4-5): 24-120 patterns, balanced
- High (6-7): 720-5040 patterns, fine-grained
- Note: Requires window >> order! for stability
• Entropy Window (15-100, default 30): Lookback for entropy
- Short (15-25): Responsive to changes
- Medium (30-50): Stable measure
- Long (60-100): Very smooth, slow adaptation
• Lyapunov Window (10-50, default 20): Stability estimation window
- Short (10-15): Fast chaos detection
- Medium (20-30): Balanced
- Long (40-50): Stable λ estimate
Causal Inference:
• Enable Transfer Entropy (default ON): Causality analysis
- Keep ON for full system functionality
• TE History Length (2-15, default 5): Causal lookback
- Short (2-4): Quick causal detection
- Medium (5-8): Balanced
- Long (10-15): Deep causal analysis
• TE Discretization Bins (4-12, default 6): Binning granularity
- Few (4-5): Coarse, robust, needs less data
- Medium (6-8): Balanced
- Many (9-12): Fine-grained, needs more data
Phase Coherence:
• Enable Phase Coherence (default ON): Synchronization detection
- Keep ON for emergence detection
• Coherence Threshold (0.3-0.95, default 0.70): PLV requirement
- Loose (0.3-0.5): More signals, lower quality
- Balanced (0.6-0.75): Recommended
- Strict (0.8-0.95): Rare, highest quality
• Hilbert Smoothing (3-20, default 8): Phase smoothing
- Low (3-5): Responsive, noisier
- Medium (6-10): Balanced
- High (12-20): Smooth, more lag
Fractal Analysis:
• Enable Fractal Dimension (default ON): Complexity measurement
- Keep ON for full analysis
• Fractal K-max (4-20, default 8): Scaling range
- Low (4-6): Faster, less accurate
- Medium (7-10): Balanced
- High (12-20): Accurate, slower
• Fractal Window (30-200, default 50): FD lookback
- Short (30-50): Responsive FD
- Medium (60-100): Stable FD
- Long (120-200): Very smooth FD
Emergence Detection:
• Emergence Threshold (0.5-0.95, default 0.75): Minimum coherence
- Sensitive (0.5-0.65): More signals
- Balanced (0.7-0.8): Recommended
- Strict (0.85-0.95): Rare signals
• Require Causal Gate (default ON): TE confirmation
- ON: Only signal when causality confirms
- OFF: Allow signals without causal support
• Require Stability Zone (default ON): Lyapunov filter
- ON: Only signal when λ < 0 (stable) or |λ| < 0.1 (critical)
- OFF: Allow signals in chaotic regimes (risky)
• Signal Cooldown (1-50, default 5): Minimum bars between signals
- Fast (1-3): Rapid signal generation
- Normal (4-8): Balanced
- Slow (10-20): Very selective
- Ultra (25-50): Only major regime changes
Signal Configuration:
• Momentum Period (5-50, default 14): ROC calculation
• Structure Lookback (10-100, default 20): Support/resistance range
• Volatility Period (5-50, default 14): ATR calculation
• Volume MA Period (10-50, default 20): Volume normalization
Visual Settings:
• Customizable color scheme for all elements
• Toggle visibility for each layer independently
• Dashboard position (4 corners) and size (tiny/small/normal)
🎓 PROFESSIONAL USAGE PROTOCOL
Phase 1: System Familiarization (Week 1)
Goal: Understand complexity metrics and dashboard interpretation
Setup:
• Enable all features with default parameters
• Watch dashboard metrics for 500+ bars
• Do NOT trade yet
Actions:
• Observe emergence score patterns relative to price moves
• Note coherence threshold crossings and subsequent price action
• Watch entropy regime transitions (ORDERED → COMPLEX → CHAOTIC)
• Correlate Lyapunov state with signal reliability
• Track which signals appear (emergence vs resonance frequency)
Key Learning:
• When does emergence peak? (usually before major moves)
• What entropy regime produces best signals? (typically ORDERED or MODERATE)
• Does your instrument respect stability zones? (stable λ = better signals)
Phase 2: Parameter Optimization (Week 2)
Goal: Tune system to instrument characteristics
Requirements:
• Understand basic dashboard metrics from Phase 1
• Have 1000+ bars of history loaded
Embedding Dimension & Time Delay:
• If signals very rare: Try lower dimension (d=3-4) or shorter delay (τ=2)
• If signals too frequent: Try higher dimension (d=6-7) or longer delay (τ=4-5)
• Sweet spot: 4-8 emergence signals per 100 bars
Coherence Threshold:
• Check dashboard: What's typical coherence range?
• If coherence rarely exceeds 0.70: Lower threshold to 0.60-0.65
• If coherence often >0.80: Can raise threshold to 0.75-0.80
• Goal: Signals fire during top 20-30% of coherence values
Emergence Threshold:
• If too few signals: Lower to 0.65-0.70
• If too many signals: Raise to 0.80-0.85
• Balance with coherence threshold—both must be met
Phase 3: Signal Quality Assessment (Weeks 3-4)
Goal: Verify signals have edge via paper trading
Requirements:
• Parameters optimized per Phase 2
• 50+ signals generated
• Detailed notes on each signal
Paper Trading Protocol:
• Take EVERY emergence signal (★ and ◆)
• Optional: Take resonance signals (▲/▼) separately to compare
• Use simple exit: 2R target, 1R stop (ATR-based)
• Track: Win rate, average R-multiple, maximum consecutive losses
Quality Metrics:
• Premium emergence (★) : Should achieve >55% WR
• Standard emergence (◆) : Should achieve >50% WR
• Resonance signals : Should achieve >45% WR
• Overall : If <45% WR, system not suitable for this instrument/timeframe
Red Flags:
• Win rate <40%: Wrong instrument or parameters need major adjustment
• Max consecutive losses >10: System not working in current regime
• Profit factor <1.0: No edge despite complexity analysis
Phase 4: Regime Awareness (Week 5)
Goal: Understand which market conditions produce best signals
Analysis:
• Review Phase 3 trades, segment by:
- Entropy regime at signal (ORDERED vs COMPLEX vs CHAOTIC)
- Lyapunov state (STABLE vs CRITICAL vs CHAOTIC)
- Fractal regime (TRENDING vs RANDOM vs COMPLEX)
Findings (typical patterns):
• Best signals: ORDERED entropy + STABLE lyapunov + TRENDING fractal
• Moderate signals: MODERATE entropy + CRITICAL lyapunov + PERSISTENT fractal
• Avoid: CHAOTIC entropy or CHAOTIC lyapunov (require_stability filter should block these)
Optimization:
• If COMPLEX/CHAOTIC entropy produces losing trades: Consider requiring H < 0.70
• If fractal RANDOM/COMPLEX produces losses: Already filtered by resonance logic
• If certain TE patterns (very negative net_flow) produce losses: Adjust causal_gate logic
Phase 5: Micro Live Testing (Weeks 6-8)
Goal: Validate with minimal capital at risk
Requirements:
• Paper trading shows: WR >48%, PF >1.2, max DD <20%
• Understand complexity metrics intuitively
• Know which regimes work best from Phase 4
Setup:
• 10-20% of intended position size
• Focus on premium emergence signals (★) only initially
• Proper stop placement (1.5-2.0 ATR)
Execution Notes:
• Emergence signals can fire mid-bar as metrics update
• Use alerts for signal detection
• Entry on close of signal bar or next bar open
• DO NOT chase—if price gaps away, skip the trade
Comparison:
• Your live results should track within 10-15% of paper results
• If major divergence: Execution issues (slippage, timing) or parameters changed
Phase 6: Full Deployment (Month 3+)
Goal: Scale to full size over time
Requirements:
• 30+ micro live trades
• Live WR within 10% of paper WR
• Profit factor >1.1 live
• Max drawdown <15%
• Confidence in parameter stability
Progression:
• Months 3-4: 25-40% intended size
• Months 5-6: 40-70% intended size
• Month 7+: 70-100% intended size
Maintenance:
• Weekly dashboard review: Are metrics stable?
• Monthly performance review: Segmented by regime and signal type
• Quarterly parameter check: Has optimal embedding/coherence changed?
Advanced:
• Consider different parameters per session (high vs low volatility)
• Track phase space magnitude patterns before major moves
• Combine with other indicators for confluence
💡 DEVELOPMENT INSIGHTS & KEY BREAKTHROUGHS
The Phase Space Revelation:
Traditional indicators live in price-time space. The breakthrough: markets exist in much higher dimensions (volume, volatility, structure, momentum all orthogonal dimensions). Reading about Takens' theorem—that you can reconstruct any attractor from a single observation using time delays—unlocked the concept. Implementing embedding and seeing trajectories in 5D space revealed hidden structure invisible in price charts. Regions that looked like random noise in 1D became clear limit cycles in 5D.
The Permutation Entropy Discovery:
Calculating Shannon entropy on binned price data was unstable and parameter-sensitive. Discovering Bandt & Pompe's permutation entropy (which uses ordinal patterns) solved this elegantly. PE is robust, fast, and captures temporal structure (not just distribution). Testing showed PE < 0.5 periods had 18% higher signal win rate than PE > 0.7 periods. Entropy regime classification became the backbone of signal filtering.
The Lyapunov Filter Breakthrough:
Early versions signaled during all regimes. Win rate hovered at 42%—barely better than random. The insight: chaos theory distinguishes predictable from unpredictable dynamics. Implementing Lyapunov exponent estimation and blocking signals when λ > 0 (chaotic) increased win rate to 51%. Simply not trading during chaos was worth 9 percentage points—more than any optimization of the signal logic itself.
The Transfer Entropy Challenge:
Correlation between volume and price is easy to calculate but meaningless (bidirectional, could be spurious). Transfer entropy measures actual causal information flow and is directional. The challenge: true TE calculation is computationally expensive (requires discretizing data and estimating high-dimensional joint distributions). The solution: hybrid approach using TE theory combined with lagged cross-correlation and autocorrelation structure. Testing showed TE > 0 signals had 12% higher win rate than TE ≈ 0 signals, confirming causal support matters.
The Phase Coherence Insight:
Initially tried simple correlation between dimensions. Not predictive. Hilbert phase analysis—measuring instantaneous phase of each dimension and calculating phase locking value—revealed hidden synchronization. When PLV > 0.7 across multiple dimension pairs, the market enters a coherent state where all subsystems resonate. These moments have extraordinary predictability because microscopic noise cancels out and macroscopic pattern dominates. Emergence signals require high PLV for this reason.
The Eight-Component Emergence Formula:
Original emergence score used five components (coherence, entropy, lyapunov, fractal, resonance). Performance was good but not exceptional. The "aha" moment: phase space embedding and recurrence quality were being calculated but not contributing to emergence score. Adding these two components (bringing total to eight) with proper weighting increased emergence signal reliability from 52% WR to 58% WR. All calculated metrics must contribute to the final score. If you compute something, use it.
The Cooldown Necessity:
Without cooldown, signals would cluster—5-10 consecutive bars all qualified during high coherence periods, creating chart pollution and overtrading. Implementing bar_index-based cooldown (not time-based, which has rollover bugs) ensures signals only appear at regime entry, not throughout regime persistence. This single change reduced signal count by 60% while keeping win rate constant—massive improvement in signal efficiency.
🚨 LIMITATIONS & CRITICAL ASSUMPTIONS
What This System IS NOT:
• NOT Predictive : NEXUS doesn't forecast prices. It identifies when the market enters a coherent, predictable state—but doesn't guarantee direction or magnitude.
• NOT Holy Grail : Typical performance is 50-58% win rate with 1.5-2.0 avg R-multiple. This is probabilistic edge from complexity analysis, not certainty.
• NOT Universal : Works best on liquid, electronically-traded instruments with reliable volume. Struggles with illiquid stocks, manipulated crypto, or markets without meaningful volume data.
• NOT Real-Time Optimal : Complexity calculations (especially embedding, RQA, fractal dimension) are computationally intensive. Dashboard updates may lag by 1-2 seconds on slower connections.
• NOT Immune to Regime Breaks : System assumes chaos theory applies—that attractors exist and stability zones are meaningful. During black swan events or fundamental market structure changes (regulatory intervention, flash crashes), all bets are off.
Core Assumptions:
1. Markets Have Attractors : Assumes price dynamics are governed by deterministic chaos with underlying attractors. Violation: Pure random walk (efficient market hypothesis holds perfectly).
2. Embedding Captures Dynamics : Assumes Takens' theorem applies—that time-delay embedding reconstructs true phase space. Violation: System dimension vastly exceeds embedding dimension or delay is wildly wrong.
3. Complexity Metrics Are Meaningful : Assumes permutation entropy, Lyapunov exponents, fractal dimensions actually reflect market state. Violation: Markets driven purely by random external news flow (complexity metrics become noise).
4. Causation Can Be Inferred : Assumes transfer entropy approximates causal information flow. Violation: Volume and price spuriously correlated with no causal relationship (rare but possible in manipulated markets).
5. Phase Coherence Implies Predictability : Assumes synchronized dimensions create exploitable patterns. Violation: Coherence by chance during random period (false positive).
6. Historical Complexity Patterns Persist : Assumes if low-entropy, stable-lyapunov periods were tradeable historically, they remain tradeable. Violation: Fundamental regime change (market structure shifts, e.g., transition from floor trading to HFT).
Performs Best On:
• ES, NQ, RTY (major US index futures - high liquidity, clean volume data)
• Major forex pairs: EUR/USD, GBP/USD, USD/JPY (24hr markets, good for phase analysis)
• Liquid commodities: CL (crude oil), GC (gold), NG (natural gas)
• Large-cap stocks: AAPL, MSFT, GOOGL, TSLA (>$10M daily volume, meaningful structure)
• Major crypto on reputable exchanges: BTC, ETH on Coinbase/Kraken (avoid Binance due to manipulation)
Performs Poorly On:
• Low-volume stocks (<$1M daily volume) - insufficient liquidity for complexity analysis
• Exotic forex pairs - erratic spreads, thin volume
• Illiquid altcoins - wash trading, bot manipulation invalidates volume analysis
• Pre-market/after-hours - gappy, thin, different dynamics
• Binary events (earnings, FDA approvals) - discontinuous jumps violate dynamical systems assumptions
• Highly manipulated instruments - spoofing and layering create false coherence
Known Weaknesses:
• Computational Lag : Complexity calculations require iterating over windows. On slow connections, dashboard may update 1-2 seconds after bar close. Signals may appear delayed.
• Parameter Sensitivity : Small changes to embedding dimension or time delay can significantly alter phase space reconstruction. Requires careful calibration per instrument.
• Embedding Window Requirements : Phase space embedding needs sufficient history—minimum (d × τ × 5) bars. If embedding_dimension=5 and time_delay=3, need 75+ bars. Early bars will be unreliable.
• Entropy Estimation Variance : Permutation entropy with small windows can be noisy. Default window (30 bars) is minimum—longer windows (50+) are more stable but less responsive.
• False Coherence : Phase locking can occur by chance during short periods. Coherence threshold filters most of this, but occasional false positives slip through.
• Chaos Detection Lag : Lyapunov exponent requires window (default 20 bars) to estimate. Market can enter chaos and produce bad signal before λ > 0 is detected. Stability filter helps but doesn't eliminate this.
• Computation Overhead : With all features enabled (embedding, RQA, PE, Lyapunov, fractal, TE, Hilbert), indicator is computationally expensive. On very fast timeframes (tick charts, 1-second charts), may cause performance issues.
⚠️ RISK DISCLOSURE
Trading futures, forex, stocks, options, and cryptocurrencies involves substantial risk of loss and is not suitable for all investors. Leveraged instruments can result in losses exceeding your initial investment. Past performance, whether backtested or live, is not indicative of future results.
The Dimensional Resonance Protocol, including its phase space reconstruction, complexity analysis, and emergence detection algorithms, is provided for educational and research purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any security or instrument.
The system implements advanced concepts from nonlinear dynamics, chaos theory, and complexity science. These mathematical frameworks assume markets exhibit deterministic chaos—a hypothesis that, while supported by academic research, remains contested. Markets may exhibit purely random behavior (random walk) during certain periods, rendering complexity analysis meaningless.
Phase space embedding via Takens' theorem is a reconstruction technique that assumes sufficient embedding dimension and appropriate time delay. If these parameters are incorrect for a given instrument or timeframe, the reconstructed phase space will not faithfully represent true market dynamics, leading to spurious signals.
Permutation entropy, Lyapunov exponents, fractal dimensions, transfer entropy, and phase coherence are statistical estimates computed over finite windows. All have inherent estimation error. Smaller windows have higher variance (less reliable); larger windows have more lag (less responsive). There is no universally optimal window size.
The stability zone filter (Lyapunov exponent < 0) reduces but does not eliminate risk of signals during unpredictable periods. Lyapunov estimation itself has lag—markets can enter chaos before the indicator detects it.
Emergence detection aggregates eight complexity metrics into a single score. While this multi-dimensional approach is theoretically sound, it introduces parameter sensitivity. Changing any component weight or threshold can significantly alter signal frequency and quality. Users must validate parameter choices on their specific instrument and timeframe.
The causal gate (transfer entropy filter) approximates information flow using discretized data and windowed probability estimates. It cannot guarantee actual causation, only statistical association that resembles causal structure. Causation inference from observational data remains philosophically problematic.
Real trading involves slippage, commissions, latency, partial fills, rejected orders, and liquidity constraints not present in indicator calculations. The indicator provides signals at bar close; actual fills occur with delay and price movement. Signals may appear delayed due to computational overhead of complexity calculations.
Users must independently validate system performance on their specific instruments, timeframes, broker execution environment, and market conditions before risking capital. Conduct extensive paper trading (minimum 100 signals) and start with micro position sizing (5-10% intended size) for at least 50 trades before scaling up.
Never risk more capital than you can afford to lose completely. Use proper position sizing (0.5-2% risk per trade maximum). Implement stop losses on every trade. Maintain adequate margin/capital reserves. Understand that most retail traders lose money. Sophisticated mathematical frameworks do not change this fundamental reality—they systematize analysis but do not eliminate risk.
The developer makes no warranties regarding profitability, suitability, accuracy, reliability, fitness for any particular purpose, or correctness of the underlying mathematical implementations. Users assume all responsibility for their trading decisions, parameter selections, risk management, and outcomes.
By using this indicator, you acknowledge that you have read, understood, and accepted these risk disclosures and limitations, and you accept full responsibility for all trading activity and potential losses.
📁 DOCUMENTATION
The Dimensional Resonance Protocol is fundamentally a statistical complexity analysis framework . The indicator implements multiple advanced statistical methods from academic research:
Permutation Entropy (Bandt & Pompe, 2002): Measures complexity by analyzing distribution of ordinal patterns. Pure statistical concept from information theory.
Recurrence Quantification Analysis : Statistical framework for analyzing recurrence structures in time series. Computes recurrence rate, determinism, and diagonal line statistics.
Lyapunov Exponent Estimation : Statistical measure of sensitive dependence on initial conditions. Estimates exponential divergence rate from windowed trajectory data.
Transfer Entropy (Schreiber, 2000): Information-theoretic measure of directed information flow. Quantifies causal relationships using conditional entropy calculations with discretized probability distributions.
Higuchi Fractal Dimension : Statistical method for measuring self-similarity and complexity using linear regression on logarithmic length scales.
Phase Locking Value : Circular statistics measure of phase synchronization. Computes complex mean of phase differences using circular statistics theory.
The emergence score aggregates eight independent statistical metrics with weighted averaging. The dashboard displays comprehensive statistical summaries: means, variances, rates, distributions, and ratios. Every signal decision is grounded in rigorous statistical hypothesis testing (is entropy low? is lyapunov negative? is coherence above threshold?).
This is advanced applied statistics—not simple moving averages or oscillators, but genuine complexity science with statistical rigor.
Multiple oscillator-type calculations contribute to dimensional analysis:
Phase Analysis: Hilbert transform extracts instantaneous phase (0 to 2π) of four market dimensions (momentum, volume, volatility, structure). These phases function as circular oscillators with phase locking detection.
Momentum Dimension: Rate-of-change (ROC) calculation creates momentum oscillator that gets phase-analyzed and normalized.
Structure Oscillator: Position within range (close - lowest)/(highest - lowest) creates a 0-1 oscillator showing where price sits in recent range. This gets embedded and phase-analyzed.
Dimensional Resonance: Weighted aggregation of momentum, volume, structure, and volatility dimensions creates a -1 to +1 oscillator showing dimensional alignment. Similar to traditional oscillators but multi-dimensional.
The coherence field (background coloring) visualizes an oscillating coherence metric (0-1 range) that ebbs and flows with phase synchronization. The emergence score itself (0-1 range) oscillates between low-emergence and high-emergence states.
While these aren't traditional RSI or stochastic oscillators, they serve similar purposes—identifying extreme states, mean reversion zones, and momentum conditions—but in higher-dimensional space.
Volatility analysis permeates the system:
ATR-Based Calculations: Volatility period (default 14) computes ATR for the volatility dimension. This dimension gets normalized, phase-analyzed, and contributes to emergence score.
Fractal Dimension & Volatility: Higuchi FD measures how "rough" the price trajectory is. Higher FD (>1.6) correlates with higher volatility/choppiness. FD < 1.4 indicates smooth trends (lower effective volatility).
Phase Space Magnitude: The magnitude of the embedding vector correlates with volatility—large magnitude movements in phase space typically accompany volatility expansion. This is the "energy" of the market trajectory.
Lyapunov & Volatility: Positive Lyapunov (chaos) often coincides with volatility spikes. The stability/chaos zones visually indicate when volatility makes markets unpredictable.
Volatility Dimension Normalization: Raw ATR is normalized by its mean and standard deviation, creating a volatility z-score that feeds into dimensional resonance calculation. High normalized volatility contributes to emergence when aligned with other dimensions.
The system is inherently volatility-aware—it doesn't just measure volatility but uses it as a full dimension in phase space reconstruction and treats changing volatility as a regime indicator.
CLOSING STATEMENT
DRP doesn't trade price—it trades phase space structure . It doesn't chase patterns—it detects emergence . It doesn't guess at trends—it measures coherence .
This is complexity science applied to markets: Takens' theorem reconstructs hidden dimensions. Permutation entropy measures order. Lyapunov exponents detect chaos. Transfer entropy reveals causation. Hilbert phases find synchronization. Fractal dimensions quantify self-similarity.
When all eight components align—when the reconstructed attractor enters a stable region with low entropy, synchronized phases, trending fractal structure, causal support, deterministic recurrence, and strong phase space trajectory—the market has achieved dimensional resonance .
These are the highest-probability moments. Not because an indicator said so. Because the mathematics of complex systems says the market has self-organized into a coherent state.
Most indicators see shadows on the wall. DRP reconstructs the cave.
"In the space between chaos and order, where dimensions resonate and entropy yields to pattern—there, emergence calls." DRP
Taking you to school. — Dskyz, Trade with insight. Trade with anticipation.
High Volume Bars (Advanced)High Volume Bars (Advanced)
High Volume Bars (Advanced) is a Pine Script v6 indicator for TradingView that highlights bars with unusually high volume, with several ways to define “unusual”:
Classic: volume > moving average + N × standard deviation
Change-based: large change in volume vs previous bar
Z-score: statistically extreme volume values
Robust mode (optional): median + MAD, less sensitive to outliers
It can:
Recolor candles when volume is high
Optionally highlight the background
Optionally plot volume bands (center ± spread × multiplier)
⸻
1. How it works
At each bar the script:
Picks the volume source:
If Use Volume Change vs Previous Bar? is off → uses raw volume
If on → uses abs(volume - volume )
Computes baseline statistics over the chosen source:
Lookback bars
Moving average (SMA or EMA)
Standard deviation
Optionally replaces mean/std with robust stats:
Center = median (50th percentile)
Spread = MAD (median absolute deviation, scaled to approx σ)
Builds bands:
upper = center + spread * multiplier
lower = max(center - spread * multiplier, 0)
Flags a bar as “high volume” if:
It passes the mode logic:
Classic abs: volume > upper
Change mode: abs(volume - volume ) > upper
Z-score mode: z-score ≥ multiplier
AND the relative filter (optional): volume > average_volume * Min Volume vs Avg
AND it is past the first Skip First N Bars from the start of the chart
Colors the bar and (optionally) the background accordingly.
⸻
2. Inputs
2.1. Statistics
Lookback (len)
Number of bars used to compute the baseline stats (mean / median, std / MAD).
Typical values: 50–200.
StdDev / Z-Score Multiplier (mult)
How far from the baseline a bar must be to count as “high volume”.
In classic mode: volume > mean + mult × std
In z-score mode: z ≥ mult
Typical values: 1.0–2.5.
Use EMA Instead of SMA? (smooth_with_ema)
Off → uses SMA (slower but smoother).
On → uses EMA (reacts faster to recent changes).
Use Robust Stats (Median & MAD)? (use_robust)
Off → mean + standard deviation
On → median + MAD (less sensitive to a few insane spikes)
Useful for assets with occasional volume blow-ups.
⸻
2.2. Detection Mode
These inputs control how “unusual” is defined.
• Use Volume Change vs Previous Bar? (mode_change)
• Off (default) → uses absolute volume.
• On → uses abs(volume - volume ).
You then detect jumps in volume rather than absolute size.
Note: This is ignored if Z-Score mode is switched on (see below).
• Use Z-Score on Volume? (Overrides change) (mode_zscore)
• Off → high volume when raw value exceeds the upper band.
• On → computes z-score = (value − center) / spread and flags a bar as high when z ≥ multiplier.
Z-score mode can be combined with robust stats for more stable thresholds.
• Min Volume vs Avg (Filter) (min_rel_mult)
An extra filter to ignore tiny-volume bars that are statistically “weird” but not meaningful.
• 0.0 → no filter (all stats-based candidates allowed).
• 1.0 → high-volume bar must also be at least equal to average volume.
• 1.5 → bar must be ≥ 1.5 × average volume.
• Skip First N Bars (from start of chart) (skip_open_bars)
Skips the first N bars of the chart when evaluating high-volume conditions.
This is mostly a safety / cosmetic option to avoid weird behavior on very early bars or backfill.
⸻
2.3. Visuals
• Show Volume Bands? (show_bands)
• If on, plots:
• Upper band (upper)
• Lower band (lower)
• Center line (vol_center)
These are plotted on the same pane as the script (usually the price chart).
• Also Highlight Background? (use_bg)
• If on, fills the background on high-volume bars with High-Vol Background.
• High-Vol Bar Transparency (0–100) (bar_transp)
Controls the opacity of the high-volume bar colors (up / down).
• 0 → fully opaque
• 100 → fully transparent (no visible effect)
• Up Color (upColor) / Down Color (dnColor)
• Regular bar colors (non high-volume) for up and down bars.
• Up High-Vol Base Color (upHighVolBase) / Down High-Vol Base Color (dnHighVolBase)
Base colors used for high-volume up/down bars. Transparency is applied on top of these via bar_transp.
• High-Vol Background (bgHighVolColor)
Background color used when Also Highlight Background? is enabled.
⸻
3. What gets colored and how
• Bar color (barcolor)
• Up bar:
• High volume → Up High-Vol Color
• Normal volume → Up Color
• Down bar:
• High volume → Down High-Vol Color
• Normal volume → Down Color
• Flat bar → neutral gray
• Background color (bgcolor)
• If Also Highlight Background? is on, high-volume bars get High-Vol Background.
• Otherwise, background is unchanged.
⸻
4. Alerts
The indicator exposes three alert conditions:
• High Volume Bar
Triggers whenever is_high is true (up or down).
• High Volume Up Bar
Triggers only when is_high is true and the bar closed up (close > open).
• High Volume Down Bar
Triggers only when is_high is true and the bar closed down (close < open).
You can use these in TradingView’s “Create Alert” dialog to:
• Get notified of potential breakout / exhaustion bars.
• Trigger webhook events for bots / custom infra.
⸻
5. Recommended presets
5.1. “Classic” high-volume detector (closest to original)
• Lookback: 150–200
• StdDev / Z-Score Multiplier: 1.0–1.5
• Use EMA Instead of SMA?: off
• Use Robust Stats?: off
• Use Volume Change vs Previous Bar?: off
• Use Z-Score on Volume?: off
• Min Volume vs Avg (Filter): 0.0–1.0
Behavior: Flags bars whose volume is notably above the recent average (plus a bit of noise filtering), same spirit as your initial implementation.
⸻
5.2. Volatility-aware (Z-score) mode
• Lookback: 100–200
• StdDev / Z-Score Multiplier: 1.5–2.0
• Use EMA Instead of SMA?: on
• Use Robust Stats?: on (if asset has huge spikes)
• Use Volume Change vs Previous Bar?: off (ignored anyway in z-score mode)
• Use Z-Score on Volume?: on
• Min Volume vs Avg (Filter): 0.5–1.0
Behavior: Flags bars that are “statistically extreme” relative to recent volume behavior, not just absolutely large. Good for assets where baseline volume drifts over time.
⸻
5.3. “Wake-up bar” (volume acceleration)
• Lookback: 50–100
• StdDev / Z-Score Multiplier: 1.0–1.5
• Use EMA Instead of SMA?: on
• Use Robust Stats?: optional
• Use Volume Change vs Previous Bar?: on
• Use Z-Score on Volume?: off
• Min Volume vs Avg (Filter): 0.5–1.0
Behavior: Emphasis on sudden increases in volume rather than absolute size – useful to catch “first active bar” after a quiet period.
⸻
6. Limitations / notes
• Time-of-day effects
The script currently treats the entire chart as one continuous “session”. On 24/7 markets (crypto) this is fine. For regular-session assets (equities, futures), volume naturally spikes at open/close; you may want to:
• Use a shorter Lookback, or
• Add a session-aware filter in a future iteration.
• Illiquid symbols
On very low-liquidity symbols, robust stats (Use Robust Stats) and a non-zero Min Volume vs Avg can help avoid “everything looks extreme” problems.
• Overlay behavior
overlay = true means:
• Bars are recolored on the price pane.
• Volume bands are also drawn on the price pane if enabled.
If you want a dedicated panel for the bands, duplicate the logic in a separate script with overlay = false.
Crypto Correlation Oscillator# Crypto Correlation Oscillator
**Companion indicator for Tri-Align Crypto Trend**
## Overview
The Crypto Correlation Oscillator helps you identify **alpha opportunities** and **market regime changes** by showing how closely your coin follows Bitcoin and other assets over time. It displays rolling correlations as an oscillator in a separate pane below your price chart.
## What It Does
This indicator calculates **Pearson correlations** between different trading pairs on a rolling window (default: 100 bars). Correlations range from **-1.0** (perfect inverse relationship) to **+1.0** (perfect positive relationship), with **0** meaning no correlation.
### The 5 Correlation Lines
1. **Blue (thick line) - Coin vs BTC**: The most important metric
- **High correlation (>0.7)**: Your coin is just following BTC - no independent movement
- **Low correlation (<0.3)**: Your coin has **alpha** - it's moving independently from BTC
- **Negative correlation**: Your coin moves opposite to BTC (rare but powerful)
2. **Purple - Coin/BTC vs BTC**: Inverse relationship check
- **Negative values**: When BTC rises, your coin weakens relative to BTC
- **Positive values**: When BTC rises, your coin strengthens against BTC
3. **Orange - Coin vs Coin/BTC**: Structural consistency check
- Shows how well the Coin/USDT and Coin/BTC pairs maintain their mathematical relationship
- Unusual values can indicate liquidity issues or market inefficiencies
4. **Light Red - Coin vs USDT.D** (optional): Stablecoin dominance correlation
- Shows how your coin correlates with USDT dominance
- Useful for understanding flight-to-safety dynamics
5. **Light Green - Coin vs BTC.D** (optional): Bitcoin dominance correlation
- Shows how your coin correlates with BTC dominance
- Helps identify altcoin season vs BTC dominance cycles
## How to Read It
### Finding Alpha Opportunities
- **Low blue line (<0.3)**: Your coin is decoupled from BTC → potential alpha
- **Blue line dropping**: Coin is gaining independence from BTC
- **Blue line spiking to >0.9**: Coin is a "BTC clone" with no independent movement
### Regime Change Detection
- **Blue line crossing 0.5**: Major shift in correlation behavior
- **Purple line turning negative**: Coin starting to weaken when BTC rises (warning sign)
- **Sharp correlation changes**: Market structure is shifting - adjust strategy
### Visual Zones
- **Blue background**: High correlation zone (>0.7) - coin just following BTC
- **Red background**: Inverse correlation zone (<-0.5) - coin moving opposite to BTC
### Reference Lines
- **+1.0 / -1.0**: Perfect correlation boundaries (dotted gray)
- **+0.5 / -0.5**: Moderate correlation thresholds (dotted gray)
- **0.0**: Zero correlation line (solid gray)
## Dynamic Legend
The legend table (top-right) automatically shows the actual symbol names based on your chart:
- **Example on SOLUSDT**: Shows "SOL vs BTC", "SOL/BTC vs BTC", "SOL vs SOL/BTC", etc.
- **Color boxes**: Match the plot colors for easy identification
- **Live values**: Current correlation numbers update in real-time
- **Tooltips**: Hover over labels for interpretation guidance
## Configuration
### Key Inputs
- **Correlation Lookback** (default: 100): Number of bars for rolling correlation window
- Shorter = more reactive, noisier
- Longer = smoother, slower to detect changes
- **Correlation Smoothing** (default: 5): EMA smoothing period for raw correlations
- Reduces noise while preserving trends
- **Symbol Detection**: Auto-detects symbols from your chart, or use manual overrides
- **Dominance Pairs**: Toggle USDT.D and BTC.D correlations on/off
## Usage Tips
1. **Combine with main Tri-Align indicator**: Use correlation for context, Tri-Align for entry/exit signals
2. **Watch for divergences**: Correlation changing while price moves in sync can signal upcoming shift
3. **Adjust lookback period**: Use shorter (50-70) for day trading, longer (150-200) for position trading
4. **Focus on the blue line**: It's your primary alpha indicator
## Technical Details
- **Calculation**: Pearson correlation coefficient with EMA smoothing
- **Data source**: Close prices from `request.security()` (multi-timeframe capable)
- **Update frequency**: Every bar on your selected timeframe
- **Overlay**: False (displays in separate pane)
## Quick Interpretation Guide
| Blue Line Value | Interpretation | Action |
|----------------|----------------|--------|
| > 0.9 | Coin is a BTC clone | Avoid - no alpha opportunity |
| 0.7 - 0.9 | High correlation | Standard altcoin behavior |
| 0.3 - 0.7 | Moderate correlation | Some independence emerging |
| < 0.3 | Low correlation | **Strong alpha opportunity** |
| < 0 | Inverse correlation | Rare - potential hedge asset |
| Purple Line | Interpretation |
|-------------|----------------|
| Strongly negative | Coin weakens when BTC rises - risky |
| Near zero | Coin/BTC pair moves independently of BTC |
| Positive | Coin strengthens with BTC - ideal |
## Version History
### v1.0 (Initial Release)
- Pearson correlation calculation with configurable lookback
- 5 correlation pairs: Coin vs BTC, Coin/BTC vs BTC, Coin vs Coin/BTC, USDT.D, BTC.D
- EMA smoothing to reduce noise
- Visual zones for high/inverse correlation
- Dynamic legend with symbol name extraction
- Auto-symbol detection matching main Tri-Align indicator






















