Real Relative Strength Breakout & BreakdownReal Relative Strength Breakout & Breakdown Indicator
What It Does
Identifies high-probability trading setups by combining:
Technical Breakouts/Breakdowns - Price breaking support/resistance zones
Real Relative Strength (RRS) - Volatility-adjusted performance vs benchmark (SPY)
Key Insight: The strongest signals occur when price action contradicts market direction—breakouts during market weakness or breakdowns during market strength show exceptional buying/selling pressure.
Real Relative Strength (RRS) Calculation
RRS measures outperformance/underperformance on a volatility-adjusted basis:
Power Index = (Benchmark Price Move) / (Benchmark ATR)
RRS = (Stock Price Move - Power Index × Stock ATR) / Stock ATR
RRS (smoothed) = 3-period SMA of RRS
Interpretation:
RRS > 0 = Relative Strength (outperforming)
RRS < 0 = Relative Weakness (underperforming)
Signal Types
🟢 Large Green Triangle (Premium Long)
Condition: Breakout + RRS > 0
Meaning: Stock breaking resistance WHILE outperforming benchmark
Best when: Market is weak but stock breaks out anyway = exceptional strength
Use: High-conviction long entries
🔵 Small Blue Triangle (Standard Breakout)
Condition: Breakout + RRS ≤ 0
Meaning: Breaking resistance but underperforming benchmark
Typical: "Rising tide lifts all boats" scenario during market rally
Use: Lower conviction—may just be following market
🟠 Large Orange Triangle (Premium Short)
Condition: Breakdown + RRS < 0
Meaning: Stock breaking support WHILE underperforming benchmark
Best when: Market is strong but stock breaks down anyway = severe weakness
Use: High-conviction short entries
🔴 Small Red Triangle (Standard Breakdown)
Condition: Breakdown + RRS ≥ 0
Meaning: Breaking support but outperforming benchmark
Typical: Stock falling less than market during selloff
Use: Lower conviction—may recover when market does
Why Large Triangles Matter
Large signals show divergence = genuine institutional flow:
Stock breaking out while market falls → Aggressive buying despite headwinds
Stock breaking down while market rallies → Aggressive selling despite tailwinds
These setups reveal where real conviction lies, not just momentum-following behavior.
Quick Settings
RRS: 12-period lookback, 3-bar smoothing, vs SPY
Breakouts: 5-period pivots, 200-bar lookback, 3% zone width, 2 minimum tests
Cari skrip untuk "西班牙人VS奥萨苏纳"
Diwali Lights Pro — 7-Diyas Signal Matrix [KedArc Quant]🎯 Overview
“Diwali Lights Pro — 7-Diyas Signal Matrix” is a precision-built trend-sentiment indicator that blends the glow of seven technical “diyas” — each representing a different momentum or strength dimension — into one intuitive signal matrix. It was designed to celebrate light, discipline, and clarity in trading — helping traders filter noise, identify strong trend shifts, and take trades with conviction. Each diya is powered by a proven indicator component: RSI, Stochastic, EMA trend strength, and momentum slopes.Together, they light up your chart with buy/sell signals only when technical confluence aligns — like the diyas of Diwali shining in harmony.
💡 Core Concept
The indicator computes a composite score (–9 to +9) by evaluating seven key parameters:
| # | Diya           | Logic                 | Interpretation                 |
| 1 | RSI            | Overbought / Oversold | Short-term momentum exhaustion |
| 2 | Stochastic     | Direction & zones     | Confirmation of RSI            |
| 3 | Price vs EMA20 | Position of price     | Near-term trend bias           |
| 4 | EMA20 Slope    | Short-term momentum   | Strength confirmation          |
| 5 | EMA50 Slope    | Mid-term trend        | Trend stability                |
| 6 | EMA100 Slope   | Medium-term sentiment | Institutional bias             |
| 7 | EMA200 Slope   | Long-term sentiment   | Market direction baseline      |
The total of these 7 diyas creates a signal matrix that dynamically adapts to trend conditions.
⚙️ Inputs & Configuration
| RSI Length                  | 14               | Standard RSI window                  |
| Stochastic Length           | 14               | Measures momentum oscillation        |
| EMA Periods                 | 20, 50, 100, 200 | Multi-layer trend structure          |
| Overbought / Oversold Zones | 70 / 30          | Configurable thresholds              |
| Show Buy/Sell Labels        | ✅                | Toggle signal markers                |
| Show Banner                 | ✅                | Festive Diwali header with fireworks |
| Twinkle Interval            | 10 bars          | Animation timing                     |
| Fireworks Count             | 18               | Visual celebration intensity         |
| Background Opacity          | 100%             | Style preference                     |
🧭 Entry & Exit Logic
# ✅ Buy Signal (🪔)
A Buy triggers when:
* The total diya score crosses above zero,
* And at least four of seven components turn bullish.
This indicates that short-term oscillators, price action, and moving averages are all turning in unison — a strong entry zone after a pullback.
# 🔥 Sell Signal (🔥)
A Sell triggers when:
* The total diya score crosses below zero,
* And multiple slopes or price conditions flip bearish.
This flags weakening momentum and possible trend exhaustion.
# 💬 Suggested Usage
* Works beautifully on 5-min to 1-hour charts.
* Best when used with trend confirmation tools (volume, price structure).
* Avoid entering trades when signals flip rapidly within narrow ranges (sideways zones).
🧪 Mathematical Formulae
1. RSI Bucket (p₁):
p₁ = 
  2  if RSI < Very Oversold  
  1  if RSI < Oversold  
  0  if neutral  
 -1  if RSI > Overbought  
 -2  if RSI > Very Overbought
2. Stochastic Bucket (p₂): Similar to RSI bucketing.
3. Price vs EMA20 (p₃):
p₃ = sign(close - EMA20)
4–7. Slope Sign (EMA20, 50, 100, 200):
p₄₋₇ = sign(EMA  - EMA )
Total Score = Σ(p₁…p₇)
→ Crossover(total_score, 0) → Buy Signal
→ Crossunder(total_score, 0) → Sell Signal
📊 Why It’s Not Just a Mash-Up
Diwali Lights Pro uses:
* A unified scoring engine with weighted logic rather than conflicting triggers.
* Each component (diya) contributes equally, creating a normalized sentiment index.
* Smart signal filtering prevents repetitive false flips by enforcing trend alignment across multiple time frames.
* A dynamic, responsive structure optimized for clarity and minimal repainting.
 🎆 Unique Add-Ons
* Top-Right Diwali Banner: Festive “Happy Diwali” with animated fireworks 🎇 and diyas 🪔.
* Signal Filtering: Reduces noise in volatile ranges.
* EMA Cloud Context: Visual clarity of multi-layer trend zones.
* Optional Light Mode: Change fireworks opacity for a subtle or bright effect.
 📘 FAQ
Q1: Does this repaint?
No — it uses confirmed values (RSI, Stochastic, EMA slopes). Signals appear only after the bar closes.
Q2: Which timeframes work best?
Between 5m and 1h, depending on your strategy.
Use higher EMAs for swing setups.
Q3: Can I use it with alerts?
Yes, both Buy and Sell triggers come with built-in `alertcondition()` for instant notifications.
Q4: Can it be combined with other indicators?
Absolutely — it pairs well with volume profiles, volatility bands, or order-flow systems.
 🪔 Glossary
| Diya          | Candle or light — here, each diya = one technical indicator         |
| EMA           | Exponential Moving Average — measures smoothed trend bias           |
| RSI           | Relative Strength Index — momentum overbought/oversold oscillator   |
| Stochastic    | Momentum oscillator measuring closing levels relative to highs/lows |
| Slope Sign    | Direction of EMA movement — rising or falling                       |
| Signal Matrix | The combined system of all seven diyas generating a unified score   |
🧭 Final Note
> *Diwali Lights Pro* is not just a trading tool — it’s a visual celebration of confluence and discipline.
> When the diyas align, trends shine. Use it to trade in harmony with light, not against it. 🌟
⚠️ Disclaimer 
This script is provided for educational purposes only.
Past performance does not guarantee future results.
Trading involves risk, and users should exercise caution and use proper risk management when applying this strategy.
Lorentzian Harmonic Flow - Temporal Market Dynamic Lorentzian Harmonic Flow - Temporal Market Dynamic  (⚡LHF) 
By: DskyzInvestments
 What this is 
 LHF Pro  is a research‑grade analytical instrument that models  market time as a compressible medium , extracts  directional flow in curved time  using heavy‑tailed kernels, and consults a  history‑based memory bank  for context before synthesizing a final, bounded  probabilistic score . It is  not  a mashup; each subsystem is mathematically coupled to a single clock (time dilation via gamma) and a single lens (Lorentzian heavy‑tailed weighting). This script is  dense in logic  (and therefore heavy) because it prioritizes rigor, interpretability, and visual clarity.
 Intended use 
 Education and research.  This tool expresses state recognition and regime context—not guarantees. It does not place orders. It is fully functional as published and contains no placeholders. Nothing herein is financial advice.
 Why this is original and useful 
 Curved time:  Markets do not move at a constant pace. LHF Pro computes a Lorentz‑style  gamma (γ)  from relative speed so its analytical windows contract when the tape accelerates and relax when it slows.
 Heavy‑tailed lens:  Lorentzian kernels weight information with fat tails to respect rare but consequential extremes (unlike Gaussian decay).
 Memory of regimes:  A K‑nearest‑neighbors engine works in a multi‑feature space using Lorentz kernels per dimension and  exponential age fade , returning a  memory bias  (directional expectation) and  assurance  (confidence mass).
 One ecosystem:  Squeeze, TCI, flow, acceleration, and memory live on the same clock and blend into a single  final_score —visualized and documented on the dashboard.
 Cognitive map:  A 2D heat map projects memory resonance by age and flow regime, making “where the past is speaking” visible.
 Shadow portfolio metaphor:  Neighbor outcomes act like tiny hypothetical positions whose weighted average forms an  educational pressure gauge  (no execution, purely didactic).
 Mathematical framework (full transparency) 
 1) Returns, volatility, and speed‑of‑market 
 Log return:  rₜ = ln(closeₜ / closeₜ₋₁)
 Realized vol:  rv = stdev(r, vol_len);  vol‑of‑vol:  burst = |rv − rv |
 Speed‑of‑market (analog to c):  c = c_multiplier × (EMA(rv) + 0.5 × EMA(burst) + ε)
 2) Trend velocity and Lorentz gamma (time dilation) 
 Trend velocity:  v = |close − close | / (vel_len × ATR)
 Relative speed:  v_rel = v / c
 Gamma:  γ = 1 / √(1 − v_rel²), stabilized by caps (e.g., ≤10)
Interpretation:  γ > 1  compresses market time → use shorter effective windows.
 3) Adaptive temporal scale 
 Adaptive length:  L = base_len / γ^power (bounded for safety)
 Harmonic horizons:  Lₛ = L × short_ratio, Lₘ = L × mid_ratio, Lₗ = L × long_ratio
 4) Lorentzian smoothing and Harmonic Flow 
 Kernel weight per lag i:  wᵢ = 1 / (1 + (d/γ)²), d = i/L
 Horizon baselines:  lw_h = Σ wᵢ·price  / Σ wᵢ
 Z‑deviation:  z_h = (close − lw_h)/ATR
 Harmonic Flow (HFL):  HFL = (w_short·zₛ + w_mid·zₘ + w_long·zₗ) / (w_short + w_mid + w_long)
 5) Flow kinematics 
 Velocity:  HFL_vel = HFL − HFL 
 Acceleration (curvature):  HFL_acc = HFL − 2·HFL  + HFL 
 6) Squeeze and temporal compression 
 Bollinger width  vs  Keltner width  using L
 Squeeze:  BB_width < KC_width × squeeze_mult
 Temporal Compression Index:  TCI = base_len / L; TCI > 1 ⇒ compressed time
 7) Entropy (regime complexity) 
Shannon‑inspired proxy on |log returns| with numerical safeguards and smoothing. Higher entropy → more chaotic regime.
 8) Memory bank and Lorentzian k‑NN 
 Feature vector (5D):   
 Outcomes stored:  forward returns at H5, H13, H34
 Per‑dimension similarity:  k(Δ) = 1 / (1 + Δ²), weighted by user’s feature weights
 Age fading:  weight_age = mem_fade^age_bars
 Neighbor score:  sᵢ = similarityᵢ × weight_ageᵢ
 Memory bias:  mem_bias = Σ sᵢ·outcomeᵢ / Σ sᵢ
 Assurance:  mem_assurance = Σ sᵢ (confidence mass)
 Normalization:  mem_bias normalized by ATR and clamped into   band
 Shadow portfolio metaphor:  neighbors behave like micro‑positions; their weighted net forward return becomes a continuous, adaptive expectation.
 9) Blended score and breakout proxy 
 Blend factor:  α_mem = 0.45 + 0.15 × (γ − 1)
 Final score:  final_score = (1−α_mem)·tanh(HFL / (flow_thr·1.5)) + α_mem·tanh(mem_bias_norm)
 Breakout probability (bounded):  energy = cap(TCI−1) + |HFL_acc|×k + cap(γ−1)×k + cap(mem_assurance)×k; breakout_prob = sigmoid(energy). Caps avoid runaway “100%” readings.
 Inputs — every control, purpose, mechanics, and tuning 
 🔮 Lorentz Core 
 Auto‑Adapt (Vol/Entropy):  On = L responds to γ and entropy (breathes with regime), Off = static testing.
 Base Length:  Calm‑market anchor horizon. Lower (21–28) for fast tapes; higher (55–89+) for slow.
 Velocity Window (vel_len):  Bars used in v. Shorter = more reactive γ; longer = steadier.
 Volatility Window (vol_len):  Bars used for rv/burst (c). Shorter = more sensitive c.
 Speed‑of‑Market Multiplier (c_multiplier):  Raises/lowers c. Lower values → easier γ spikes (more adaptation). Aim for strong trends to peak around γ ≈ 2–4.
 Gamma Compression Power:  Exponent of γ in L. <1 softens; >1 amplifies adaptation swings.
 Max Kernel Span:  Upper bound on smoothing loop (quality vs CPU).
 🎼 Harmonic Flow 
 Short/Mid/Long Horizon Ratios:  Partition L into fast/medium/slow views. Smaller short_ratio → faster reaction; larger long_ratio → sturdier bias.
 Weights (w_short/w_mid/w_long):  Governs HFL blend. Higher w_short → nimble; higher w_long → stable.
 📈 Signals 
 Squeeze Strictness:  Threshold for BB1 = compressed (coiled spring); <1 = dilated.
 v/c:  Relative speed; near 1 denotes extreme pacing. Diagnostic only.
 Entropy:  Regime complexity; high entropy suggests caution, smaller size, or waiting for order to return.
 HFL:  Curved‑time directional flow; sign and magnitude are the instantaneous bias.
 HFL_acc:  Curvature; spikes often accompany regime ignition post‑squeeze.
 Mem Bias:  Directional expectation from historical analogs (ATR‑normalized, bounded). Aligns or conflicts with HFL.
 Assurance:  Confidence mass from neighbors; higher → more reliable memory bias.
 Squeeze:  ON/RELEASE/OFF from BB
Advanced Speedometer Gauge [PhenLabs]Advanced Speedometer Gauge  
Version: PineScript™v6
 📌 Description 
The Advanced Speedometer Gauge is a revolutionary multi-metric visualization tool that consolidates 13 distinct trading indicators into a single, intuitive speedometer display. Instead of cluttering your workspace with multiple oscillators and panels, this gauge provides a unified interface where you can switch between different metrics while maintaining consistent visual interpretation.
Built on PineScript™ v6, the indicator transforms complex technical calculations into an easy-to-read semi-circular gauge with color-coded zones and a precision needle indicator. Each of the 13 available metrics has been carefully normalized to a 0-100 scale, ensuring that whether you’re analyzing RSI, volume trends, or volatility extremes, the visual interpretation remains consistent and intuitive.
The gauge is designed for traders who value efficiency and clarity. By consolidating multiple analytical perspectives into one compact display, you can quickly assess market conditions without the visual noise of traditional multi-indicator setups. All metrics are non-overlapping, meaning each provides unique insights into different aspects of market behavior.
 🚀 Points of Innovation 
 
  13 selectable metrics covering momentum, volume, volatility, trend, and statistical analysis, all accessible through a single dropdown menu
  Universal 0-100 normalization system that standardizes different indicator scales for consistent visual interpretation across all metrics
  Semi-circular gauge design with 21 arc segments providing smooth precision and clear visual feedback through color-coded zones
  Non-redundant metric selection ensuring each indicator provides unique market insights without analytical overlap
  Advanced metrics including MFI (volume-weighted momentum), CCI (statistical deviation), Volatility Rank (extended lookback), Trend Strength (ADX-style), Choppiness Index, Volume Trend, and Price Distance from MA
  Flexible positioning system with 5 chart locations, 3 size options, and fully customizable color schemes for optimal workspace integration
 
 🔧 Core Components 
 
   Metric Selection Engine:  Dropdown interface allowing instant switching between 13 different technical indicators, each with independent parameter controls
   Normalization System:  All metrics converted to 0-100 scale using indicator-specific algorithms that preserve the statistical significance of each measurement
   Semi-Circular Gauge:  Visual display using 21 arc segments arranged in curved formation with two-row thickness for enhanced visibility
   Color Zone System:  Three distinct zones (0-40 green, 40-70 yellow, 70-100 red) providing instant visual feedback on metric extremes
   Needle Indicator:  Dynamic pointer that positions across the gauge arc based on precise current metric value
   Table Implementation:  Professional table structure ensuring consistent positioning and rendering across different chart configurations
 
 🔥 Key Features 
 
   RSI (Relative Strength Index):  Classic momentum oscillator measuring overbought/oversold conditions with adjustable period length (default 14)
   Stochastic Oscillator:  Compares closing price to price range over specified period with smoothing, ideal for identifying momentum shifts
   MFI (Money Flow Index):  Volume-weighted RSI that combines price movement with volume to measure buying and selling pressure intensity
   CCI (Commodity Channel Index):  Measures statistical deviation from average price, normalized from typical -200 to +200 range to 0-100 scale
   Williams %R:  Alternative overbought/oversold indicator using high-low range analysis, inverted to match 0-100 scale conventions
   Volume %:  Current volume relative to moving average expressed as percentage, capped at 100 for extreme spikes
   Volume Trend:  Cumulative directional volume flow showing whether volume is flowing into up moves or down moves over specified period
   ATR Percentile:  Current Average True Range position within historical range using specified lookback period (default 100 bars)
   Volatility Rank:  Close-to-close volatility measured against extended historical range (default 252 days), differs from ATR in calculation method
   Momentum:  Rate of change calculation showing price movement speed, centered at 50 and normalized to 0-100 range
   Trend Strength:  ADX-style calculation using directional movement to quantify trend intensity regardless of direction
   Choppiness Index:  Measures market choppiness versus trending behavior, where high values indicate ranging markets and low values indicate strong trends
   Price Distance from MA:  Measures current price over-extension from moving average using standard deviation calculations
 
 🎨 Visualization 
 
   Semi-Circular Arc Display:  Curved gauge spanning from 0 (left) to 100 (right) with smooth progression and two-row thickness for visibility
   Color-Coded Zones:  Green zone (0-40) for low/oversold conditions, yellow zone (40-70) for neutral readings, red zone (70-100) for high/overbought conditions
   Needle Indicator:  Downward-pointing triangle (▼) positioned precisely at current metric value along the gauge arc
   Scale Markers:  Vertical line markers at 0, 25, 50, 75, and 100 positions with corresponding numerical labels below
   Title Display:  Merged cell showing “𓄀 PhenLabs” branding plus currently selected metric name in monospace font
   Large Value Display:  Current metric value shown with two decimal precision in large text directly below title
   Table Structure:  Professional table with customizable background color, text color, and transparency for minimal chart obstruction
 
 📖 Usage Guidelines 
 Metric Selection 
 
   Select Metric:  Default: RSI | Options: RSI, Stochastic, Volume %, ATR Percentile, Momentum, MFI (Money Flow), CCI (Commodity Channel), Williams %R, Volatility Rank, Trend Strength, Choppiness Index, Volume Trend, Price Distance | Choose the technical indicator you want to display on the gauge based on your current analytical needs
 
 RSI Settings 
 
   RSI Length:  Default: 14 | Range: 1+ | Controls the lookback period for RSI calculation, shorter periods increase sensitivity to recent price changes
 
 Stochastic Settings 
 
   Stochastic Length:  Default: 14 | Range: 1+ | Lookback period for stochastic calculation comparing close to high-low range
   Stochastic Smooth:  Default: 3 | Range: 1+ | Smoothing period applied to raw stochastic value to reduce noise and false signals
 
 Volume Settings 
 
   Volume MA Length:  Default: 20 | Range: 1+ | Moving average period used to calculate average volume for comparison with current volume
   Volume Trend Length:  Default: 20 | Range: 5+ | Period for calculating cumulative directional volume flow trend
 
 ATR and Volatility Settings 
 
   ATR Length:  Default: 14 | Range: 1+ | Period for Average True Range calculation used in ATR Percentile metric
   ATR Percentile Lookback:  Default: 100 | Range: 20+ | Historical range used to determine current ATR position as percentile
   Volatility Rank Lookback (Days):  Default: 252 | Range: 50+ | Extended lookback period for Volatility Rank metric using close-to-close volatility
 
 Momentum and Trend Settings 
 
   Momentum Length:  Default: 10 | Range: 1+ | Lookback period for rate of change calculation in Momentum metric
   Trend Strength Length:  Default: 20 | Range: 5+ | Period for directional movement calculations in ADX-style Trend Strength metric
 
 Advanced Metric Settings 
 
   MFI Length:  Default: 14 | Range: 1+ | Lookback period for Money Flow Index calculation combining price and volume
   CCI Length:  Default: 20 | Range: 1+ | Period for Commodity Channel Index statistical deviation calculation
   Williams %R Length:  Default: 14 | Range: 1+ | Lookback period for Williams %R high-low range analysis
   Choppiness Index Length:  Default: 14 | Range: 5+ | Period for calculating market choppiness versus trending behavior
   Price Distance MA Length:  Default: 50 | Range: 10+ | Moving average period used for Price Distance standard deviation calculation
 
 Visual Customization 
 
   Position:  Default: Top Right | Options: Top Left, Top Right, Bottom Left, Bottom Right, Middle Right | Controls gauge placement on chart for optimal workspace organization
   Size:  Default: Normal | Options: Small, Normal, Large | Adjusts overall gauge dimensions and text size for different monitor resolutions and preferences
   Low Zone Color (0-40):  Default: Green (#00FF00) | Customize color for low/oversold zone of gauge arc
   Medium Zone Color (40-70):  Default: Yellow (#FFFF00) | Customize color for neutral/medium zone of gauge arc
   High Zone Color (70-100):  Default: Red (#FF0000) | Customize color for high/overbought zone of gauge arc
   Background Color:  Default: Semi-transparent dark gray | Customize gauge background for contrast and chart integration
   Text Color:  Default: White (#FFFFFF) | Customize all text elements including title, value, and scale labels
 
 ✅ Best Use Cases 
 
  Quick visual assessment of market conditions when you need instant feedback on whether an asset is in extreme territory across multiple analytical dimensions
  Workspace organization for traders who monitor multiple indicators but want to reduce chart clutter and visual complexity
  Metric comparison by switching between different indicators while maintaining consistent visual interpretation through the 0-100 normalization
  Overbought/oversold identification using RSI, Stochastic, Williams %R, or MFI depending on whether you prefer price-only or volume-weighted analysis
  Volume analysis through Volume %, Volume Trend, or MFI to confirm price movements with corresponding volume characteristics
  Volatility monitoring using ATR Percentile or Volatility Rank to identify expansion/contraction cycles and adjust position sizing
  Trend vs range identification by comparing Trend Strength (high values = trending) against Choppiness Index (high values = ranging)
  Statistical over-extension detection using CCI or Price Distance to identify when price has deviated significantly from normal behavior
  Multi-timeframe analysis by duplicating the gauge on different timeframe charts to compare metric readings across time horizons
  Educational purposes for new traders learning to interpret technical indicators through consistent visual representation
 
 ⚠️ Limitations 
 
  The gauge displays only one metric at a time, requiring manual switching to compare different indicators rather than simultaneous multi-metric viewing
  The 0-100 normalization, while providing consistency, may obscure the raw values and specific nuances of each underlying indicator
  Table-based visualization cannot be exported or saved as an image separately from the full chart screenshot
  Optimal parameter settings vary by asset type, timeframe, and market conditions, requiring user experimentation for best results
 
 💡 What Makes This Unique 
 
   Unified Multi-Metric Interface:  The only gauge-style indicator offering 13 distinct metrics through a single interface, eliminating the need for multiple oscillator panels
   Non-Overlapping Analytics:  Each metric provides genuinely unique insights—MFI combines volume with price, CCI measures statistical deviation, Volatility Rank uses extended lookback, Trend Strength quantifies directional movement, and Choppiness Index measures ranging behavior
   Universal Normalization System:  All metrics standardized to 0-100 scale using indicator-appropriate algorithms that preserve statistical meaning while enabling consistent visual interpretation
   Professional Visual Design:  Semi-circular gauge with 21 arc segments, precision needle positioning, color-coded zones, and clean table implementation that maintains clarity across all chart configurations
   Extensive Customization:  Independent parameter controls for each metric, five position options, three size presets, and full color customization for seamless workspace integration
 
 🔬 How It Works 
 1. Metric Calculation Phase: 
 
  All 13 metrics are calculated simultaneously on every bar using their respective algorithms with user-defined parameters
  Each metric applies its own specific calculation method—RSI uses average gains vs losses, Stochastic compares close to high-low range, MFI incorporates typical price and volume, CCI measures deviation from statistical mean, ATR calculates true range, directional indicators measure up/down movement, and statistical metrics analyze price relationships
 
 2. Normalization Process: 
 
  Each calculated metric is converted to a standardized 0-100 scale using indicator-appropriate transformations
  Some metrics are naturally 0-100 (RSI, Stochastic, MFI, Williams %R), while others require scaling—CCI transforms from ±200 range, Momentum centers around 50, Volume ratio caps at 2x for 100, ATR and Volatility Rank calculate percentile positions, and Price Distance scales by standard deviations
 
 3. Gauge Rendering: 
 
  The selected metric’s normalized value determines the needle position across 21 arc segments spanning 0-100
  Each arc segment receives its color based on position—segments 0-8 are green zone, segments 9-14 are yellow zone, segments 15-20 are red zone
  The needle indicator (▼) appears in row 5 at the column corresponding to the current metric value, providing precise visual feedback
 
 4. Table Construction: 
 
  The gauge uses TradingView’s table system with merged cells for title and value display, ensuring consistent positioning regardless of chart configuration
  Rows are allocated as follows: Row 0 merged for title, Row 1 merged for large value display, Row 2 for spacing, Rows 3-4 for the semi-circular arc with curved shaping, Row 5 for needle indicator, Row 6 for scale markers, Row 7 for numerical labels at 0/25/50/75/100
  All visual elements update on every bar when barstate.islast is true, ensuring real-time accuracy without performance impact
 
 💡 Note: 
This indicator is designed for visual analysis and market condition assessment, not as a standalone trading system. For best results, combine gauge readings with price action analysis, support and resistance levels, and broader market context. Parameter optimization is recommended based on your specific trading timeframe and asset class. The gauge works on all timeframes but may require different parameter settings for intraday versus daily/weekly analysis. Consider using multiple instances of the gauge set to different metrics for comprehensive market analysis without switching between settings.
Relative Strength Ratio • Leader Shift Signals## Overview
This indicator computes a **Relative Strength (RS) ratio** between your chart’s symbol and a reference symbol (e.g. BTC or index), then overlays an EMA-based trend filter and detects **RS divergences** via RSI on that ratio. It highlights when your symbol is leading vs lagging, and spots potential turning points via bullish/negative divergences. No alerts are forced, you get visual cues (lines & labels) only.
---
## How It Works
1. **RS Ratio** = (base symbol price) ÷ (reference symbol price).
2. Two EMAs (fast & slow) filter trend context and help identify “leader shifts” (when ratio crosses the fast EMA under trend constraints).
3. **RSI on the ratio** is used to detect divergences. We find swing highs/lows in the *ratio* and compare their RSI values:
   * **Bearish RS divergence**: ratio makes a higher high, but RSI makes a lower high
   * **Bullish RS divergence**: ratio makes a lower low, but RSI makes a higher low
4. When divergence is confirmed, the script draws connecting lines (and optional markers) on the RS ratio pane to visually flag them.
5. You can customize pivot sensitivity, minimum separation, colors, and toggles for which graphics to show.
---
## Best Usage Suggestions
* Use a **reference symbol** that is meaningfully related (e.g. BTC for altcoins, SPX for equities, or a sector index for a stock). The interpretive power comes from seeing relative strength vs a meaningful peer.
* On **higher timeframes** (4H, daily), divergences tend to carry more weight. On lower intraday charts, tighten pivot settings to avoid noise.
* Prefer divergence signals when the RS ratio is also in a favorable trend (e.g. above its EMA for bullish divergences, below for bearish). Using the trend filter EMAs helps reduce false signals.
* Always confirm divergence signals with **price structure, volume, or other momentum indicators**. Divergence is a warning or a hint—not a standalone trigger.
* Because RSI on ratio is subject to noise, avoid over-tuning pivots too tight; broader pivot widths give more robust divergence lines.
---
## Inputs & Customization
* **Reference Symbol & Timeframe** for ratio comparison
* **Fast EMA / Slow EMA lengths** and slope threshold (trend filter)
* **RSI length** applied to the RS ratio
* **Pivot left / right bars** and **min separation** to define sturdy swings
* **Toggle lines / markers** visibility, and pick colors for divergence, ratio, EMAs
* Optional “shade” or fill modes (if you have them)
---
## Limitations & Disclaimers
* Divergence does **not guarantee** reversals—it often signals **weakening momentum or potential turning zones**, which may not always play out.
* In extremely volatile or fast-moving markets, divergence lines may lag or fail.
* The script relies on historical data (no future lookahead). Because pivots are confirmed after a few bars, some signals show with delay.
* As always: combine with price action, structure, risk management. This is a tool—not a magic eight ball.
---
Adaptive Z-Momentum (AZM) [Blk0ut]Adaptive Z-Momentum (AZM)  is a momentum indicator that expresses the normalized deviation of price from a dynamic anchor (VWAP or EMA) in standard-score (z-score) terms, with adaptive “extreme” thresholds, trend sensitivity, and optional regime filtering. The line color, background shading, and labels help you visually discern when momentum is mild, building, or overextended.
---
## Features & Concept
* Computes **z = (price – anchor) / σ**, where the anchor is either Session VWAP (intraday) or EMA (non-intraday).
* Uses exponential moving averages (EWMA) to adaptively estimate the running mean and variance, making the indicator responsive to regime changes.
* Defines an **adaptive extreme threshold** (±z threshold) based on the chosen percentile of |z| over a lookback window (e.g. 90th percentile) — dynamically adjusting to volatility environment.
* Colors the main z-line **differently when inside vs. outside the extreme thresholds**, giving immediate visual feedback.
* Optionally shades the background when momentum is over the extremes (bullish or bearish).
* Supports a **self-tuning mode** (ADX-aware) that tightens or relaxes lookback/smoothing in strong trend vs. chop regimes.
* Regime filtering options (EMA slope or ADX threshold) let you filter signals in trend vs. non-trend markets.
* Plots Δz (the change in z) in various styles to help detect acceleration or deceleration in momentum.
* Adds optional thrust/fade labels to highlight when z crosses ±extreme zones, or when momentum stalls.
---
## How to Use
* Look for **z crossing** above zero (bullish momentum) or below zero (bearish momentum).
* When **z enters the extreme band**, it suggests strong momentum; when it exits, that may indicate exhaustion or reversal.
* Watch **Δz** (momentum acceleration) for clues of weakening or strengthening momentum before z itself reacts.
* Use the **regime filter** to enforce that signals only count in favorable directional markets.
* Customize inputs: lookback window, smoothing length, extreme percentile, ADX/auto settings, colors, etc., to match your trading style and timeframe.
*Use VWAP as the anchor on intraday/session charts — because it resets each session, it highlights deviations from session “fair value” and captures volume-flow bias.
*Use EMA on swing or multi-day charts — it doesn’t reset, so it preserves trend structure and gives a smoother momentum baseline across sessions.
*In trending markets, EMA tends to deliver more reliable momentum extremes; in range or mean-reversion regimes, VWAP often gives more intuitive reversal zones.
---
## Limitations & Disclaimers
* Like all indicators, AZM is **lagging** (though adaptive) and should not be used as a standalone entry/exit trigger — always combine with price action, structure, or confirmation.
* The extreme thresholds are **percentile-based**, meaning in very quiet or very noisy periods, “extreme” may shift rapidly; use your eyes alongside the indicator.
* Because the script uses historical data and smoothing, earlier bars may differ from real-time behavior.
* Past behavior is no guarantee of future performance. Use proper risk management and test ideas on historical data before trading live.
---
## Inputs & Customization
* **Anchor** mode: Session VWAP (intraday) or EMA
* **Lookback window** and **smoothing EMA** for computing z
* **Extreme percentile** (e.g. 90) to define ±z thresholds
* **Auto / ADX-based tuning** to allow dynamic parameter changes in trending vs chop markets
* **Regime filter** (EMA slope or ADX) to restrict signals to trending conditions
* **Color settings** for inside vs outside extremes, background shading, zero line, Δz style, labels, etc.
* **Show/hide labels**, choose Δz style (columns, histogram, line, etc.)
---
## Why It’s Useful
By combining standard-score normalization with adaptive thresholds and regime sensitivity, AZM helps you see **relative momentum extremes** in a way that adjusts to market regime shifts. The dual visual cues (line color + background) reduce ambiguity at a glance.
---
Session-Conditioned Regime ATRWhy this exists
 
Classic ATR is great—until the open. The first few bars often inherit overnight gaps and 24-hour noise that have nothing to do with the intraday regime you actually trade. That inflates early ATR, scrambles thresholds, and invites hyper-recency bias (“today is crazy!”) when it’s just the open being the open.
This tool was built to:
 
 Separate session reality from 24h noise. Measure volatility only inside your defined session (e.g., NYSE 09:30–16:00 ET).
 Judge candles against the current regime, not the last 2–3 bars. A rolling statistic from the last N completed sessions defines what “typical” means right now.
 Label “large” and “small” objectively. Bars are colored only when True Range meaningfully departs from the session regime—no gut feel, no open-bar distortion (gap inclusion optional).
 
 Overview 
Purpose: objectively identify unusually big or small candles within the active trading session, compared to the recent session regime.
Use cases: volatility filters, entry/exit confirmation, session bias detection, adaptive sizing.
This indicator replaces generic ATR with a session-conditioned, regime-aware measure. It colors candles only when their True Range (TR) is abnormally large/small versus the last N completed sessions of the same session window.
 How it works 
 
 Session gating: Only bars inside the selected session are evaluated (presets for NYSE, CME RTH, FX NY; custom supported).
 Per-bar TR: TR = max(high, prevRef) − min(low, prevRef).
 prevRef is the prior close for in-session bars.
 First bar of the session can include the overnight gap (optional; default off).
 Regime statistic: For any bar in session k, aggregate all in-session TRs from the previous N completed sessions (k−N … k−1), then compute Median (default) or Mean.
 Today’s anchor: Running statistic from today’s session start → current bar (for context and the on-chart ratio).
 Color logic:
 Big if TR ≥ bigMult × RegimeStat
 Small if TR ≤ smallMult × RegimeStat
 Colored states: big bull, big bear, small bull, small bear.
 Non-triggering bars retain the chart’s native colors.
 
 Panel (top-right by default) 
 
 Regime ATR (Nd): session-conditioned statistic over the past N completed sessions.
 Today ATR (anchored): running statistic for the current session.
 Ratio (Today/Regime): intraday volatility vs regime.
 Sample size n: number of bars used in the regime calculation.
 
 Inputs 
 
 Session Preset: NYSE (09:30–16:00 ET), CME RTH (08:30–15:00 CT), FX NY (08:00–17:00 ET), Custom (session + IANA timezone).
 Regime Window: number of completed sessions (default 5).
 Statistic: Median (robust) or Mean.
 Include Open Gap: include overnight gap in the first in-session bar’s TR (default off).
 Big/Small thresholds: multipliers relative to RegimeStat (defaults: Big=1.5×, Small=0.67×).
 Colors: four independent colors for big/small × bull/bear.
 Panel position & text size.
 Hidden outputs: expose RegimeStat, TodayStat, Ratio, and Z-score to other scripts.
 
 Alerts 
 
 RegimeATR: BIG bar — triggers when a bar meets the “Big” condition.
 RegimeATR: SMALL bar — triggers when a bar meets the “Small” condition.
 Hidden outputs (for strategies/screeners)
 RegimeATR_stat, TodayATR_stat, Today_vs_Regime_Ratio, BarTR_Zscore.
 
 Notes & limitations
 
 
 No look-ahead: calculations only use information available up to that bar. Historical colors reflect what would have been known then.
 Warm-up: colors begin once there are at least N completed sessions; before that, regime is undefined by design.
 Changing inputs (session window, multipliers, median/mean, gap toggle) recomputes the full series using the same rolling regime logic per bar.
 Designed for standard candles. Styling respects existing chart colors when no condition triggers.
 
 Practical tips
 
 
 For a broader or tighter notion of “unusual,” adjust Big/Small multipliers.
 Prefer Median in markets prone to outliers; use Mean if you want Z-score alignment with the panel’s regime mean/std.
 Use the Ratio readout to spot compression/expansion days quickly (e.g., <0.7× = compressed session, >1.3× = expanded).
 
 Roadmap 
 
 More session presets:
 24h continuous (crypto, index CFDs).
 23h/Globex futures (CME ETH with a 60-minute maintenance break).
 Regional equities (LSE, Xetra, TSE), Asia/Europe/NY overlaps for FX.
 Half-day/holiday templates and dynamic calendars.
 Multi-regime comparison: track multiple overlapping regimes (e.g., RTH vs ETH for futures) and show separate stats/ratios.
 Robust stats options: trimmed mean, MAD/Huber alternatives; optional percentile thresholds instead of fixed multipliers.
 Subpanel visuals: rolling TodayATR and Ratio plots; optional Z-score ribbon.
 Screener/strategy hooks: export boolean series for BIG/SMALL, plus a lightweight strategy template for backtesting entries/exits conditioned on regime volatility.
 Performance/QOL: per-symbol presets, smarter warm-up, and finer control over sample caps for ultra-low TF charts.
 
 Changelog 
v0.9b (Beta)
 Session presets (NYSE/CME RTH/FX NY/Custom) with timezone handling.
Panel enhancements: ratio + sample size n.
Four-state bar coloring (big/small × bull/bear).
Alerts for BIG/SMALL bars.
Hidden Z-score stream for downstream use.
Gap-in-TR toggle for the first in-session bar. 
 Disclaimer 
For educational purposes only. Not investment advice. Validate thresholds and session settings across symbols/timeframes before live use.
Aggression Bulbs v3.1 (Sessions + Bias, fixed)EYLONAggression Bulbs v3.2 (Sessions + Bias + Volume Surge)
This indicator highlights aggressive buy and sell activity during the London and New York sessions, using volume spikes and candle body dominance to detect institutional momentum.
⚙️ Main Logic
Compares each candle’s volume vs average volume (Volume Surge).
Checks body size vs full candle range to detect strong directional moves.
Uses an EMA bias filter to align signals with the current trend.
Displays green bubbles for aggressive buyers and red bubbles for aggressive sellers.
🕐 Sessions
London: 08:00–12:59 UTC+1
New York: 14:00–18:59 UTC+1
(Backgrounds: Yellow = London, Orange = New York)
📊 How to Read
🟢 Green bubble below bar → Aggressive BUY candle (strong demand).
🔴 Red bubble above bar → Aggressive SELL candle (strong supply).
Bubble size = relative strength (volume × candle dominance).
Use in confluence with key POI zones, volume profile, or delta clusters.
⚠️ Tips
Use on 1m–15m charts for scalping or intraday analysis.
Combine with your session bias or FVG zones for higher accuracy.
Set alerts when score ≥ threshold to catch early momentum.
NS ND - EVR - Daily Bias - TRFxVolume & Price Action Signals
What It Does
Combines three proven trading methodologies: Effort vs Result (EVR), No Supply/No Demand (NS/ND), and Daily Bias tracking for intraday traders.
 Features
 Effort vs Result (EVR) 
- **Bullish**: Green triangle below bar when price sweeps previous low with high volume and significant wick
- **Bearish**: Red triangle above bar when price sweeps previous high with high volume and significant wick
- Identifies potential reversals where volume doesn't match price movement
 No Supply / No Demand (NS/ND) 
- **No Demand (Red dot)**: Up-candle with declining volume - buyers weakening
- **No Supply (Green dot)**: Down-candle with declining volume - sellers weakening
- Grey dots = unconfirmed, colored dots = confirmed within lookahead period
- Based on Volume Spread Analysis (VSA) principles
 Daily Bias Label 
Top-right corner shows market direction:
- **BULLISH ↑** - Closed above Previous Day High
- **BEARISH ↓** - Closed below Previous Day Low
- **BULLISH/BEARISH REV** - Swept level but closed back inside
- **RANGE ↔** - Trading between PDH/PDL
## Settings
- **EVR**: Toggle on/off, volume multiplier, wick %, inside bars, transparency
- **NS/ND**: Toggle on/off, lookahead bars (default: 10)
- **Daily Bias**: Toggle label display
## Best For
✓ Intraday trading (1m-1h timeframes)
✓ Reversal setups
✓ Volume analysis
✓ Confluence trading (all signals align)
How to Use
1. Enable components you want (all can be toggled independently)
2. Trade EVR signals in direction of Daily Bias
3. Look for NS/ND confirmation at key levels
4. Wait for colored dots (confirmed signals) over grey (unconfirmed)
**Note**: Works on intraday timeframes only. NS/ND signals may repaint during confirmation period.
Reversal Nexus Pro Suite — Smart Scalper/Swing Trader/Hybrid  📝 Description
The Reversal Suite (5–15m) is a dynamic price-action-driven indicator built for scalpers and intraday traders who want to catch high-probability reversals with precision.
This system combines SFP (Swing Failure Patterns), Volume Climax filters, EMA bias, and momentum confirmation logic — all customizable to match your personal trading style.
The default configuration is tuned for NASDAQ futures (NQ1!) and similar indices on 5–15-minute charts, but it can adapt seamlessly to crypto, forex, and equities.
⚙️ How It Works
The indicator looks for exhaustion points in price where:
Volume Climax confirms liquidity sweeps,
EMA bias determines directional filters (single or dual-EMA),
Reclaim and rejection mechanics confirm structure shifts,
Momentum thrust ensures strength on reversal confirmation.
Each setup requires multi-factor alignment to reduce noise and increase signal precision.
🧩 Default Custom Settings (Recommended Start)
Setting	Value	Description
Mode	Custom	Enables full manual control
Signals must align within N bars	6	Forces confluence across recent bars
TP1 / TP2 (R-Multiples)	1.5 / 2.5	Default reward zones
RSI Divergence	Enabled	Adds secondary reversal confirmation
Volume Climax	Enabled	Detects high-volume exhaustion
Vol SMA Length	21	Volume baseline calculation
Climax ≥ k × SMA	7	Strength multiplier for volume spikes
EMA Length	200	Trend bias reference
Bias	Both	Allows both long and short setups
Dual EMA Bias	Enabled	Uses fast (21) vs slow (100) bias tracking
Min Distance from EMA Bias	2.55%	Filter to avoid signals too close to MAs
Reclaim Buffer After Sweep	0.22%	Ensures valid break-and-reclaim setups
Max Bars for Retest	1	Tight retest condition
Momentum Thrust Confirm	Enabled	Ensures volume and price thrust
Body ≥ ATR	-6	Controls candle thrust sizing
TR SMA Length	20	Measures dynamic volatility
Body ≥ k × TR-SMA	-4.4	Confirms structure-based rejection
Opposite-Signal Exit	Enabled	Auto-clears opposite signals
Opposite Signal Window	5 bars	Short-term conflict filter
Swing Lookback (SFP)	2	Finds recent liquidity highs/lows
Cooldown Bars After Signal	8	Prevents over-triggering
🟢 Inputs are fully adjustable, so traders can optimize for:
Scalping (lower EMA, smaller swing lookback)
Swing trading (higher EMA, larger retest window)
Aggressive vs conservative confirmations
🧭 Recommended Use
Works best on 5m–15m timeframes
Pair with VWAP or EMA cloud overlays for directional context
Use Trend Guard to align only with higher-timeframe trend
Ideal for indices, forex majors, and large-cap stocks
🚀 Highlights
✅ Smart confluence-based reversal detection
✅ Built-in retest and rejection logic
✅ Dual EMA and volume climax filters
✅ Customizable momentum thrust confirmation
✅ Optimized for scalpers and intraday swing traders
🧱 Suggested Layout
Chart type: Candlestick
Timeframe: 5m or 15m
Overlay: VWAP / EMA Cloud / ORB Zone
Optional filters: ATR Bands, Volume Profile (VPVR), Session Boxes
⚠️ Disclaimer 
The Reversal Nexus Pro   indicator is provided for educational and informational purposes only. It is not financial advice and should not be interpreted as a recommendation to buy, sell, or trade any financial instrument.
Trading involves significant risk and may not be suitable for all investors. Past performance does not guarantee future results. Always perform your own analysis and use proper risk management before placing any trades.
The author of this script is not responsible for any financial losses or decisions made based on the use of this tool.
By using this indicator, you acknowledge that you understand these terms and accept full responsibility for your own trading results.
© 2025. All rights reserved. Redistribution or resale of this indicator, in full or in part, is strictly prohibited without the author’s written consent.
Quant Trend + Donchian (Educational, Public-Safe)What this does 
Educational, public-safe visualization of a quant regime model:
•  Trend : EMA(64) vs EMA(256) (EWMAC proxy)
•  Breakout : Donchian channel (200)
•  Volatility-awareness : internal z-scores (not plotted) for concept clarity
 Why it’s useful 
• Shows when trend & breakout align (clean regimes) vs conflict (chop)
• Helps explain why  volatility-aware  systems size up in smooth trends and scale down in noise
 How to read it 
• EMA64 above EMA256 with price near/above Donchian high → trend-following alignment
• EMA64 below EMA256 with price near/below Donchian low → bearish alignment
• Inside channel with EMAs tangled → range/chop risk
 Notes 
• Indicator is educational only (no orders). 
• Built entirely with TradingView built-ins.
• For consistent visuals: enable “Indicator values on price scale” and disable “Scale price chart only” in  Settings → Scales .
Volume Aggregated Spot & Futures -- Crypto (by plyst & more)📊 Volume Aggregated Spot & Futures - Enhanced Edition
🎯 Overview
Advanced volume aggregation indicator that combines spot and perpetual futures volume across the top 10 cryptocurrency exchanges. This enhanced version builds upon the original work by @HALDRO Project with optimized calculations and expanded functionality.
✨ Key Features
- 📈 Real-time aggregated volume from 10 major exchanges (Binance, Bybit, OKX, Coinbase, Bitget, KuCoin, Kraken, MEXC, Gate.io, HTX)
- 🔄 Multiple visualization modes: Volume, Delta, Cumulative Delta, Spot vs Perp analysis, Liquidations, OBV, and MFI
- 💱 Multi-currency support: Display volume in COIN, USD, or EUR
- 🎨 Clean, single-color bar chart showing total cumulative volume
- 📊 Multiple calculation methods: SUM, AVG, MEDIAN, VARIANCE
- 🎯 Separate spot (USDT, USD, USDC, etc.) and perpetual futures (.P contracts) tracking
🔧 Technical Improvements
✓ Corrected MFI formula for accurate money flow calculations
✓ Optimized volume aggregation logic with proper NA handling
✓ Support for 10 exchanges (up from 9)
✓ Streamlined codebase for better performance
✓ Updated perpetual contract naming conventions (.P format)
📖 Usage
Perfect for analyzing total market volume, identifying liquidation events, tracking buyer/seller pressure through delta analysis, and understanding the spot vs futures market dynamics.
🙏 Credits
Original concept and framework by @HALDRO Project. This version includes mathematical corrections, code optimizations, and expanded exchange support.
⚠️ Note
Aggregated volume is calculated from external exchange data using request.security(). Ensure your plan supports the necessary security calls for optimal performance.
Round Number Analyzer v3Round Number Analyzer v3 is an indicator designed to analyze how price interacts with round number levels (levels spaced at fixed intervals in points or pips).
The indicator does not generate entry/exit signals, but provides detailed statistics to better understand market dynamics around these key levels.
✨ Key Features
Cross Counting: detects every time the price crosses a round number level (up = Long, down = Short).
Continuations & Reversals: classifies each cross as:
Continuation: the move continues in the same direction as the previous sequence.
Reversal: the move changes direction compared to the previous sequence.
Sequence Classification (L1…L5+): each level is labelled based on its position within the consecutive cross sequence:
L1 = first level of the sequence,
L2 = second consecutive,
…
L5+ = fifth or higher.
Comprehensive Stats Table (top right corner):
Total crosses (Long, Short, Totals).
Total continuations + breakdown by L1…L5+.
Total reversals + breakdown by L1…L5+.
Percentages calculated against the proper denominator, displayed directly inside the cells next to the absolute values.
Date range of analysis (user-defined).
Customizable Step: Works in both points and pips, making the indicator suitable for indices and forex.
⚙️ Main Inputs
Start date / End date → sets the analysis period.
Step mode → Points or Pips.
Step value → distance between round levels.
Pip size → pip size (default = 0.0001, typical for forex).
📈 How to Interpret
A high continuation percentage after L1–L2 suggests the market tends to extend multiple times beyond the first breakout levels.
Higher reversal percentages at advanced levels (L4–L5+) may signal trend exhaustion.
The analysis helps estimate the probability of continuation or reversal depending on how many consecutive levels have already been crossed.
🔎 Practical Applications
Support for breakout or mean-reversion strategies.
Comparative analysis across different markets (e.g. indices vs forex) or different time periods.
📝 Notes
The indicator is timeframe-robust, as it accounts for multiple steps within the same candle, ensuring results do not depend on the selected timeframe (except for TradingView’s historical data limits).
It does not provide automatic trading signals, but serves as a quantitative analysis tool to refine your strategies.
---
Round Number Analyzer v3 è un indicatore pensato per analizzare come il prezzo interagisce con i livelli di round number (livelli a distanza fissa in punti o pips).
L’indicatore non genera segnali di ingresso/uscita, ma fornisce statistiche dettagliate utili per comprendere la dinamica del mercato attorno a questi livelli.
✨ Funzionalità principali
Conteggio dei Cross: rileva ogni volta che il prezzo attraversa un livello round (verso l’alto = Long, verso il basso = Short).
Continuations & Reversals: classifica ogni attraversamento come:
Continuation: il movimento prosegue nella stessa direzione della sequenza precedente.
Reversal: il movimento inverte la direzione rispetto alla sequenza precedente.
Classificazione per sequenza (L1…L5+): ogni livello è etichettato in base alla sua posizione nella sequenza di cross consecutivi:
L1 = primo livello della sequenza,
L2 = secondo consecutivo,
…
L5+ = quinto o superiore.
Statistiche complete in tabella (in alto a destra):
Cross totali (Long, Short, Totals).
Continuations totali + breakdown per L1…L5+.
Reversals totali + breakdown per L1…L5+.
Percentuali calcolate sul denominatore corretto, mostrate direttamente dentro le celle accanto ai valori assoluti.
Date range di analisi (impostabile dall’utente).
Step personalizzabile: puoi lavorare sia in punti che in pips, così l’indicatore è adatto sia per indici che per forex.
⚙️ Input principali
Start date / End date → imposta l’intervallo temporale di analisi.
Step mode → punti o pips.
Step value → ampiezza tra i livelli round.
Pip size → dimensione del pip (default = 0.0001, tipico per il forex).
📈 Come interpretarlo
Una percentuale di continuation molto alta dopo L1–L2 indica che il mercato tende a proseguire più volte oltre i primi livelli di breakout.
Percentuali di reversal più elevate nei livelli avanzati (L4–L5+) possono suggerire esaurimento della spinta.
L’analisi permette di stimare la probabilità che un movimento in corso continui o si inverta in base a quanti livelli sono già stati attraversati consecutivamente.
🔎 Applicazioni pratiche
Supporto per strategie di breakout o mean reversion.
Analisi comparativa tra mercati (es. indici vs forex) o tra periodi temporali diversi.
📝 Note
L’indicatore è timeframe-robust: il conteggio tiene conto di multipli step dentro la stessa candela, così i risultati non dipendono dal timeframe scelto (salvo i limiti di caricamento storico di TradingView).
Non fornisce segnali operativi automatici, ma è un tool di analisi quantitativa per affinare le proprie strategie.
Volume Based Sampling [BackQuant]Volume Based Sampling  
 What this does 
This indicator converts the usual  time-based  stream of candles into an  event-based  stream of “synthetic” bars that are created  only when enough trading activity has occurred . You choose the activity definition:
 Volume bars : create a new synthetic bar whenever the cumulative number of shares/contracts traded reaches a threshold.
 Dollar bars : create a new synthetic bar whenever the cumulative traded  dollar value  (price × volume) reaches a threshold.
The script then keeps an internal ledger of these synthetic opens, highs, lows, closes, and volumes, and can display them as candles, plot a moving average calculated over the synthetic closes, mark each time a new sample is formed, and optionally overlay the native time-bars for comparison.
 Why event-based sampling matters 
Markets do not release information on a clock: activity clusters during news, opens/closes, and liquidity shocks.  Event-based bars  normalize for that heteroskedastic arrival of information: during active periods you get more bars (finer resolution); during quiet periods you get fewer bars (coarser resolution). Research shows this can reduce microstructure pathologies and produce series that are closer to i.i.d. and more suitable for statistical modeling and ML. In particular:
 Volume and dollar bars  are a common event-time alternative to time bars in quantitative research and are discussed extensively in  Advances in Financial Machine Learning  (AFML). These bars aim to homogenize information flow by sampling on traded size or value rather than elapsed seconds.
 The Volume Clock  perspective models market activity in “volume time,” showing that many intraday phenomena (volatility, liquidity shocks) are better explained when time is measured by traded volume instead of seconds. 
Related market microstructure work on  flow toxicity  and liquidity highlights that the risk dealers face is tied to information intensity of order flow, again arguing for activity-based clocks. 
 How the indicator works (plain English) 
 Choose your bucket type 
 
 Volume : accumulate volume until it meets a threshold.
 Dollar Bars : accumulate close × volume until it meets a dollar threshold.
 
 Pick the threshold rule 
 Dynamic threshold : by default, the script computes a rolling statistic (mean or median) of recent activity to set the next bucket size. This adapts bar size to changing conditions (e.g., busier sessions produce more frequent synthetic bars).
 Fixed threshold : optionally override with a constant target (e.g., exactly 100,000 contracts per synthetic bar, or $5,000,000 per dollar bar).
 Build the synthetic bar 
While a bucket fills, the script tracks:
o_s: first price of the bucket (synthetic open)
h_s: running maximum price (synthetic high)
l_s: running minimum price (synthetic low)
c_s: last price seen (synthetic close)
v_s: cumulative native volume inside the bucket
d_samples: number of native bars consumed to complete the bucket (a proxy for “how fast” the threshold filled)
 Emit a new sample 
Once the bucket meets/exceeds the threshold, a  new synthetic bar  is finalized and stored. If overflow occurs (e.g., a single native bar pushes you past the threshold by a lot), the code will emit multiple synthetic samples to account for the extra activity.
 Maintain a rolling history efficiently 
A  ring buffer  can overwrite the oldest samples when you hit your Max Stored Samples cap, keeping memory usage stable.
 Compute synthetic-space statistics 
The script computes an  SMA over the last N synthetic closes  and basic descriptors like average bars per synthetic sample, mean and standard deviation of synthetic returns, and more. These are all in  event time , not clock time.
 Inputs and options you will actually use 
 Data Settings 
 Sampling Method : Volume or Dollar Bars.
 Rolling Lookback : window used to estimate the dynamic threshold from recent activity.
 Filter : Mean or Median for the dynamic threshold. Median is more robust to spikes.
 Use Fixed? / Fixed Threshold : override dynamic sizing with a constant target.
 Max Stored Samples : cap on synthetic history to keep performance snappy.
 Use Ring Buffer : turn on to recycle storage when at capacity.
 Indicator Settings 
 SMA over last N samples : moving average in  synthetic space . Because its index is sample count, not minutes, it adapts naturally: more updates in busy regimes, fewer in quiet regimes.
 Visuals 
 
 Show Synthetic Bars : plot the synthetic OHLC candles.
 Candle Color Mode :
 Green/Red: directional close vs open
 Volume Intensity: opacity scales with synthetic size
 Neutral: single color
 Adaptive: graded by how large the bucket was relative to threshold
 Mark new samples : drop a small marker whenever a new synthetic bar prints.
 
 Comparison & Research 
 Show Time Bars : overlay the native time-based candles to visually compare how the two sampling schemes differ.
 How to read it, step by step 
 Turn on “Synthetic Bars”  and optionally overlay “Time Bars.” You will see that during high-activity bursts, synthetic bars print much faster than time bars.
 Watch the synthetic SMA . Crosses in synthetic space can be more meaningful because each update represents a roughly comparable amount of traded information.
 Use the “Avg Bars per Sample”  in the info table as a regime signal. Falling average bars per sample means activity is clustering, often coincident with higher realized volatility.
 Try Dollar Bars  when price varies a lot but share count does not; they normalize by dollar risk taken in each sample.  Volume Bars  are ideal when share count is a better proxy for information flow in your instrument.
 Quant finance background and citations 
 Event time vs. clock time : Easley, López de Prado, and O’Hara advocate measuring intraday phenomena on a  volume clock  to better align sampling with information arrival. This framing helps explain volatility bursts and liquidity droughts and motivates volume-based bars.
 Flow toxicity and dealer risk : The same authors show how adverse selection risk changes with the intensity and informativeness of order flow, further supporting activity-based clocks for modeling and risk management. 
 AFML framework : In  Advances in Financial Machine Learning , event-driven bars such as  volume, dollar, and imbalance bars  are presented as superior sampling units for many ML tasks, yielding more stationary features and fewer microstructure distortions than fixed time bars. ( Alpaca )
 Practical use cases 
 1) Regime-aware moving averages 
The synthetic  SMA in event time  is not fooled by quiet periods: if nothing of consequence trades, it barely updates. This can make  trend filters  less sensitive to calendar drift and more sensitive to true participation.
 2) Breakout logic on “equal-information” samples 
The script exposes simple alerts such as  breakout above/below the synthetic SMA . Because each bar approximates a constant amount of activity, breakouts are conditioned on comparable informational mass, not arbitrary time buckets.
 3) Volatility-adaptive backtests 
If you use synthetic bars as your base data stream, most signal rules become  self-paced : entry and exit opportunities accelerate in fast markets and slow down in quiet regimes, which often improves the realism of slippage and fill modeling in research pipelines (pair this indicator with strategy code downstream).
 4) Regime diagnostics 
 Avg Bars per Sample  trending down: activity is dense; expect larger realized ranges.
 Return StdDev (synthetic)  rising: noise or trend acceleration in event time; re-tune risk.
 Interpreting the info panel 
 Method : your sampling choice and current threshold.
 Total Samples : how many synthetic bars have been formed.
 Current Vol/Dollar : how much of the next bucket is already filled.
 Bars in Bucket : native bars consumed so far in the current bucket.
 Avg Bars/Sample : lower means higher trading intensity.
 Avg Return / Return StdDev : return stats computed over  synthetic closes .
 Research directions you can build from here 
 Imbalance and run bars 
Extend beyond pure volume or dollar thresholds to  imbalance bars  that trigger on directional order flow imbalance (e.g., buy volume minus sell volume), as discussed in the AFML ecosystem. These often further homogenize distributional properties used in ML. alpaca.markets
 Volume-time indicators 
Re-compute classical indicators (RSI, MACD, Bollinger) on the synthetic stream. The premise is that signals are updated by  traded information , not seconds, which may stabilize indicator behavior in heteroskedastic regimes.
 Liquidity and toxicity overlays 
Combine synthetic bars with proxies of  flow toxicity  to anticipate spread widening or volatility clustering. For instance, tag synthetic bars that surpass multiples of the threshold and test whether subsequent realized volatility is elevated. 
 Dollar-risk parity sampling for portfolios 
Use  dollar bars  to align samples across assets by notional risk, enabling cleaner cross-asset features and comparability in multi-asset models (e.g., correlation studies, regime clustering). AFML discusses the benefits of event-driven sampling for cross-sectional ML feature engineering. 
 Microstructure feature set 
Compute  duration in native bars per synthetic sample ,  range per sample , and  volume multiple of threshold  as inputs to  state classifiers  or  regime HMMs . These features are inherently activity-aware and often predictive of short-horizon volatility and trend persistence per the event-time literature. ( Alpaca )
 Tips for clean usage 
Start with dynamic thresholds using  Median  over a sensible lookback to avoid outlier distortion, then move to  Fixed  thresholds when you know your instrument’s typical activity scale.
Compare  time bars vs synthetic bars  side by side to develop intuition for how your market “breathes” in activity time.
Keep  Max Stored Samples  reasonable for performance; the ring buffer avoids memory creep while preserving a rolling window of research-grade data.
SuperTrend Optimizer Remastered[CHE]  SuperTrend Optimizer Remastered   — Grid-ranked SuperTrend with additive or multiplicative scoring
  Summary 
This indicator evaluates a fixed grid of one hundred and two SuperTrend parameter pairs and ranks them by a simple flip-to-flip return model. It auto-selects the currently best-scoring combination and renders its SuperTrend in real time, with optional gradient coloring for faster visual parsing. The original concept is by  KioseffTrading  Thanks a lot for it. 
For years I wanted to shorten the roughly two thousand three hundred seventy-one lines; I have now reduced the core to about three hundred eighty lines without triggering script errors. The simplification is generalizable to other indicators. A multiplicative return mode was added alongside the existing additive aggregation, enabling different rankings and often more realistic compounding behavior.
  Motivation: Why this design? 
SuperTrend is sensitive to its factor and period. Picking a single pair statically can underperform across regimes. This design sweeps a compact parameter grid around user-defined lower bounds, measures flip-to-flip outcomes, and promotes the combination with the strongest cumulative return. The approach keeps the visual footprint familiar while removing manual trial-and-error. The multiplicative mode captures compounding effects; the additive mode remains available for linear aggregation.
 Originally (by KioseffTrading) 
  Very long script (~2,371 lines), monolithic structure.
 SuperTrend optimization with additive (cumulative percentage-sum) scoring only.
 Heavier use of repetitive code; limited modularity and fewer UI conveniences.
 No explicit multiplicative compounding option; rankings did not reflect sequence-sensitive equity growth. 
 Now (remastered by CHE) 
  Compact core (~380 lines) with the same functional intent, no compile errors.
 Adds multiplicative (compounding) scoring alongside additive, changing rankings to reflect real equity paths and penalize drawdown sequences.
 Fixed 34×3 grid sweep, live ranking, gradient-based bar/wick/line visuals, top-table display, and an optional override plot.
 Cleaner arrays/state handling, last-bar table updates, and reusable simplification pattern that can be applied to other indicators. 
  What’s different vs. standard approaches? 
 Baseline: A single SuperTrend with hand-picked inputs.
 Architecture differences:
   Fixed grid of thirty-four factor offsets across three ATR offsets.
   Per-combination flip-to-flip backtest with additive or multiplicative aggregation.
   Live ranking with optional “Best” or “Worst” table output.
   Gradient bar, wick, and line coloring driven by consecutive trend counts.
   Optional override plot to force a specific SuperTrend independent of ranking.
 Practical effect: Charts show the currently best-scoring SuperTrend, not a static choice, plus an on-chart table of top performers for transparency.
  How it works (technical) 
For each parameter pair, the script computes SuperTrend value and direction. It monitors direction transitions and treats a change from up to down as a long entry and the reverse as an exit, measuring the move between entry and exit using close prices. Results are aggregated per pair either by summing percentage changes or by compounding return factors and then converting to percent for comparison. On the last bar, open trades are included as unrealized contributions to ranking. The best combination’s line is plotted, with separate styling for up and down regimes. Consecutive regime counts are normalized within a rolling window and mapped to gradients for bars, wicks, and lines. A two-column table reports the best or worst performers, with an optional row describing the parameter sweep.
  Parameter Guide 
 Factor (Lower Bound) — Starting SuperTrend factor; the grid adds offsets between zero and three point three. Default three point zero. Higher raises distance to price and reduces flips.
 ATR Period (Lower Bound) — Starting ATR length; the grid adds zero, one, and two. Default ten. Longer reduces noise at the cost of responsiveness.
 Best vs Worst — Ranks by top or bottom cumulative return. Default Best. Use Worst for stress tests.
 Calculation Mode — Additive sums percents; Multiplicative compounds returns. Multiplicative is closer to equity growth and can change the leaderboard.
 Show in Table — “Top Three” or “All”. Fewer rows keep charts clean.
 Show “Parameters Tested” Label — Displays the effective sweep ranges for auditability.
 Plot Override SuperTrend — If enabled, the override factor and ATR are plotted instead of the ranked winner.
 Override Factor / ATR Period — Values used when override is on.
 Light Mode (for Table) — Adjusts table colors for bright charts.
 Gradient/Coloring controls — Toggles for gradient bars and wick coloring, window length for normalization, gamma for contrast, and transparency settings. Use these to emphasize or tone down visual intensity.
 Table Position and Text Size — Places the table and sets typography.
  Reading & Interpretation 
The auto SuperTrend plots one line for up regimes and one for down regimes. Color intensity reflects consecutive trend persistence within the chosen window. A small square at the bottom encodes the same gradient as a compact status channel. Optional wick coloring uses the same gradient for maximum contrast. The performance table lists parameter pairs and their cumulative return under the chosen aggregation; positive values are tinted with the up color, negative with the down color. “Long” labels mark flips that open a long in the simplified model.
  Practical Workflows & Combinations 
 Trend following: Use the auto line as your primary bias. Enter on flips aligned with structure such as higher highs and higher lows. Filter with higher-timeframe trend or volatility contraction.
 Exits/Stops: Consider conservative exits when color intensity fades or when the opposite line is approached. Aggressive traders can trail near the plotted line.
 Override mode: When you want stability across instruments, enable override and standardize factor and ATR; keep the table visible for sanity checks.
 Multi-asset/Multi-TF: Defaults travel well on liquid instruments and intraday to daily timeframes. Heavier assets may prefer larger lower bounds or multiplicative mode.
  Behavior, Constraints & Performance 
 Repaint/confirmation: Signals are based on SuperTrend direction; confirmation is best assessed on closed bars to avoid mid-bar oscillation. No higher-timeframe requests are used.
 Resources: One hundred and two SuperTrend evaluations per bar, arrays for state, and a last-bar table render. This is efficient for the grid size but avoid stacking many instances.
 Known limits: The flip model ignores costs, slippage, and short exposure. Rapid whipsaws can degrade both aggregation modes. Gradients are cosmetic and do not change logic.
  Sensible Defaults & Quick Tuning 
Start with the provided lower bounds and “Top Three” table.
 Too many flips → raise the lower bound factor or period.
 Too sluggish → lower the bounds or switch to additive mode.
 Rankings feel unstable → prefer multiplicative mode and extend the normalization window.
 Visuals too strong → increase gradient transparency or disable wick coloring.
  What this indicator is—and isn’t 
This is a parameter-sweep and visualization layer for SuperTrend selection. It is not a complete trading system, not predictive, and does not include position sizing, transaction costs, or risk management. Combine with market structure, higher-timeframe context, and explicit risk controls.
Attribution and refactor note: The original work is by KioseffTrading. The script has been refactored from approximately two thousand three hundred seventy-one lines to about three hundred eighty core lines, retaining behavior without compiler errors. The general simplification pattern is reusable for other indicators.
  Metadata 
 Name/Tag: SuperTrend Optimizer Remastered  
 Pine version: v6
 Overlay or separate pane: true (overlay)
 Core idea/principle: Grid-based SuperTrend selection by cumulative flip returns with additive or multiplicative aggregation.
 Primary outputs/signals: Auto-selected SuperTrend up and down lines, optional override lines, gradient bar and wick colors, “Long” labels, performance table.
 Inputs with defaults: See Parameter Guide above.
 Metrics/functions used: SuperTrend, ATR, arrays, barstate checks, windowed normalization, gamma-based contrast adjustment, table API, gradient utilities.
 Special techniques: Fixed grid sweep, compounding vs linear aggregation, last-bar UI updates, gradient encoding of persistence.
 Performance/constraints: One hundred and two SuperTrend calls, arrays of length one hundred and two, label budget, last-bar table updates, no higher-timeframe requests.
 Recommended use-cases/workflows: Trend bias selection, quick parameter audits, override standardization across assets.
 Compatibility/assets/timeframes: Standard OHLC charts across intraday to daily; liquid instruments recommended.
 Limitations/risks: Costs and slippage omitted; mid-bar instability possible; not suitable for synthetic chart types.
 Debug/diagnostics: Ranking table, optional tested-range label; internal counters for consecutive trends.
 Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Extreme Pressure Zones Indicator (EPZ) [BullByte]Extreme Pressure Zones Indicator(EPZ) 
The Extreme Pressure Zones (EPZ) Indicator is a proprietary market analysis tool designed to highlight potential overbought and oversold "pressure zones" in any financial chart. It does this by combining several unique measurements of price action and volume into a single, bounded oscillator (0–100). Unlike simple momentum or volatility indicators, EPZ captures multiple facets of market pressure: price rejection, trend momentum, supply/demand imbalance, and institutional (smart money) flow. This is not a random mashup of generic indicators; each component was chosen and weighted to reveal extreme market conditions that often precede reversals or strong continuations.
 What it is? 
EPZ estimates buying/selling pressure and highlights potential extreme zones with a single, bounded 0–100 oscillator built from four normalized components. Context-aware weighting adapts to volatility, trendiness, and relative volume. Visual tools include adaptive thresholds, confirmed-on-close extremes, divergence, an MTF dashboard, and optional gradient candles.
 Purpose and originality (not a mashup) 
 Purpose:  Identify when pressure is building or reaching potential extremes while filtering noise across regimes and symbols.
 Originality:  EPZ integrates price rejection, momentum cascade, pressure distribution, and smart money flow into one bounded scale with context-aware weighting. It is not a cosmetic mashup of public indicators.
 Why a trader might use EPZ 
EPZ provides a multi-dimensional gauge of market extremes that standalone indicators may miss. Traders might use it to:
 Spot Reversals:  When EPZ enters an "Extreme High" zone (high red), it implies selling pressure might soon dominate. This can hint at a topside reversal or at least a pause in rallies. Conversely, "Extreme Low" (green) can highlight bottom-fish opportunities. The indicator's divergence module (optional) also finds hidden bullish/bearish divergences between price and EPZ, a clue that price momentum is weakening.
 Measure Momentum Shifts:  Because EPZ blends momentum and volume, it reacts faster than many single metrics. A rising MPO indicates building bullish pressure, while a falling MPO shows increasing bearish pressure. Traders can use this like a refined RSI: above 50 means bullish bias, below 50 means bearish bias, but with context provided by the thresholds.
 Filter Trades:  In trend-following systems, one could require EPZ to be in the bullish (green) zone before taking longs, or avoid new trades when EPZ is extreme. In mean-reversion systems, one might specifically look to fade extremes flagged by EPZ.
 Multi-Timeframe Confirmation:  The dashboard can fetch a higher timeframe EPZ value. For example, you might trade a 15-minute chart only when the 60-minute EPZ agrees on pressure direction.
 Components and how they're combined 
 Rejection (PRV)  – Captures price rejection based on candle wicks and volume (see Price Rejection Volume).
 Momentum Cascade (MCD)  – Blends multiple momentum periods (3,5,8,13) into a normalized momentum score.
 Pressure Distribution (PDI)  – Measures net buy/sell pressure by comparing volume on up vs down candles.
 Smart Money Flow (SMF)  – An adaptation of money flow index that emphasizes unusual volume spikes.
Each of these components produces a 0–100 value (higher means more bullish pressure). They are then weighted and averaged into the final Market Pressure Oscillator (MPO), which is smoothed and scaled. By combining these four views, EPZ stands out as a comprehensive pressure gauge – the whole is greater than the sum of parts
 Context-aware weighting: 
Higher volatility → more PRV weight
Trendiness up (RSI of ATR > 25) → more MCD weight
Relative volume > 1.2x → more PDI weight
SMF holds a stable weight
The weighted average is smoothed and scaled into MPO ∈   with 50 as the neutral midline.
 What makes EPZ stand out 
Four orthogonal inputs (price action, momentum, pressure, flow) unified in a single bounded oscillator with consistent thresholds.
Adaptive thresholds (optional) plus robust extreme detection that also triggers on crossovers, so static thresholds work reliably too.
Confirm Extremes on Bar Close (default ON): dots/arrows/labels/alerts print on closed bars to avoid repaint confusion.
Clean dashboard, divergence tools, pre-alerts, and optional on-price gradients. Visual 3D layering uses offsets for depth only,no lookahead.
 Recommended markets and timeframes 
 Best:  liquid symbols (index futures, large-cap equities, major FX, BTC/ETH).
 Timeframes:  5–15m (more signals; consider higher thresholds), 1H–4H (balanced), 1D (clear regimes).
 Use caution on illiquid or very low TFs where wick/volume geometry is erratic. 
 Logic and thresholds 
 MPO ∈  ; 50 = neutral. Above 50 = bullish pressure; below 50 = bearish. 
 Static thresholds (defaults):  thrHigh = 70, thrLow = 30; warning bands 5 pts inside extremes (65/35).
 Adaptive thresholds (optional): 
thrHigh = min(BaseHigh + 5, mean(MPO,100) + stdev(MPO,100) × ExtremeSensitivity)
thrLow = max(BaseLow − 5, mean(MPO,100) − stdev(MPO,100) × ExtremeSensitivity)
 Extreme detection 
High: MPO ≥ thrHigh with peak/slope or crossover filter.
Low: MPO ≤ thrLow with trough/slope or crossover filter.
 Cooldown:  5 bars (default). A new extreme will not print until the cooldown elapses, even if MPO re-enters the zone.
 Confirmation 
"Confirm Extremes on Bar Close" (default ON) gates extreme markers, pre-alerts, and alerts to closed bars (non-repainting).
 Divergences 
Pivot-based bullish/bearish divergence; tags appear only after left/right bars elapse (lookbackPivot).
 MTF 
HTF MPO retrieved with lookahead_off; values can update intrabar and finalize at HTF close. This is disclosed and expected.
 Inputs and defaults (key ones) 
 Core:  Sensitivity=1.0; Analysis Period=14; Smoothing=3; Adaptive Thresholds=OFF.
 Extremes:  Base High=70, Base Low=30; Extreme Sensitivity=1.5; Confirm Extremes on Bar Close=ON; Cooldown=5; Dot size Small/Tiny.
 Visuals:  Heatmap ON; 3D depth optional; Strength bars ON; Pre-alerts OFF; Divergences ON with tags ON; Gradient candles OFF; Glow ON.
 Dashboard:  ON; Position=Top Right; Size=Normal; MTF ON; HTF=60m; compact overlay table on price chart.
 Advanced caps:  Max Oscillator Labels=80; Max Extreme Guide Lines=80; Divergence objects=60.
 Dashboard: what each element means 
 Header:  EPZ ANALYSIS.
 Large readout:  Current MPO; color reflects state (extreme, approaching, or neutral).
 Status badge:  "Extreme High/Low", "Approaching High/Low", "Bullish/Neutral/Bearish".
 HTF cell (when MTF ON):  Higher-timeframe MPO, color-coded vs extremes; updates intrabar, settles at HTF close.
 Predicted (when MTF OFF):  Simple MPO extrapolation using momentum/acceleration—illustrative only.
 Thresholds:  Current thrHigh/thrLow (static or adaptive).
 Components:  ASCII bars + values for PRV, MCD, PDI, SMF.
 Market metrics:  Volume Ratio (x) and ATR% of price.
 Strength:  Bar indicator of |MPO − 50| × 2.
 Confidence:  Heuristic gauge (100 in extremes, 70 in warnings, 50 with divergence, else |MPO − 50|). Convenience only, not probability.
 How to read the oscillator 
 MPO Value (0–100):  A reading of 50 is neutral. Values above ~55 are increasingly bullish (green), while below ~45 are increasingly bearish (red). Think of these as "market pressure".
 Extreme Zones:  When MPO climbs into the bright orange/red area (above the base-high line, default 70), the chart will display a dot and downward arrow marking that extreme. Traders often treat this as a sign to tighten stops or look for shorts. Similarly, a bright green dot/up-arrow appears when MPO falls below the base-low (30), hinting at a bullish setup.
 Heatmap/Candles:  If "Pressure Heatmap" is enabled, the background of the oscillator pane will fade green or red depending on MPO. Users can optionally color the price candles by MPO value (gradient candles) to see these extremes on the main chart.
 Prediction Zone(optional):  A dashed projection line extends the MPO forward by a small number of bars (prediction_bars) using current MPO momentum and acceleration. This is a heuristic extrapolation best used for short horizons (1–5 bars) to anticipate whether MPO may touch a warning or extreme zone. It is provisional and becomes less reliable with longer projection lengths — always confirm predicted moves with bar-close MPO and HTF context before acting.
 Divergences:  When price makes a higher high but EPZ makes a lower high (bearish divergence), the indicator can draw dotted lines and a "Bear Div" tag. The opposite (lower low price, higher EPZ) gives "Bull Div". These signals confirm waning momentum at extremes.
 Zones:  Warning bands near extremes; Extreme zones beyond thresholds.
 Crossovers:  MPO rising through 35 suggests easing downside pressure; falling through 65 suggests waning upside pressure.
 Dots/arrows:  Extreme markers appear on closed bars when confirmation is ON and respect the 5-bar cooldown.
 Pre-alert dots (optional):  Proximity cues in warning zones; also gated to bar close when confirmation is ON.
 Histogram:  Distance from neutral (50); highlights strengthening or weakening pressure.
 Divergence tags:  "Bear Div" = higher price high with lower MPO high; "Bull Div" = lower price low with higher MPO low.
 Pressure Heatmap :  Layered gradient background that visually highlights pressure strength across the MPO scale; adjustable intensity and optional zone overlays (warning / extreme) for quick visual scanning.
 A typical reading:  If the oscillator is rising from neutral towards the high zone (green→orange→red), the chart may see strong buying culminating in a stall. If it then turns down from the extreme, that peak EPZ dot signals sell pressure.
 Alerts 
 EPZ: Extreme Context —  fires on confirmed extremes (respects cooldown).
 EPZ: Approaching Threshold —  fires in warning zones if no extreme.
 EPZ: Divergence —  fires on confirmed pivot divergences.
 Tip:  Set alerts to "Once per bar close" to align with confirmation and avoid intrabar repaint.
 Practical usage ideas 
 Trend continuation:  In positive regimes (MPO > 50 and rising), pullbacks holding above 50 often precede continuation; mirror for bearish regimes.
 Exhaustion caution:  E High/E Low can mark exhaustion risk; many wait for MPO rollover or divergence to time fades or partial exits.
 Adaptive thresholds:  Useful on assets with shifting volatility regimes to maintain meaningful "extreme" levels.
 MTF alignment:  Prefer setups that agree with the HTF MPO to reduce countertrend noise.
 Examples 
Screenshots captured in TradingView Replay to freeze the bar at close so values don't fluctuate intrabar. These examples use default settings and are reproducible on the same bars; they are for illustration, not cherry-picking or performance claims.
 Example 1 — BTCUSDT, 1h — E Low 
  
MPO closed at 26.6 (below the 30 extreme), printing a confirmed E Low. HTF MPO is 26.6, so higher-timeframe pressure remains bearish. Components are subdued (Momentum/Pressure/Smart$ ≈ 29–37), with Vol Ratio ≈ 1.19x and ATR% ≈ 0.37%. A prior Bear Div flagged weakening impulse into the drop. With cooldown set to 5 bars, new extremes are rate-limited. Many traders wait for MPO to curl up and reclaim 35 or for a fresh Bull Div before considering countertrend ideas; if MPO cannot reclaim 35 and HTF stays weak, treat bounces cautiously. Educational illustration only.
 Example 2 — ETHUSD, 30m — E High 
  
A strong impulse pushed MPO into the extreme zone (≥ 70), printing a confirmed E High on close. Shortly after, MPO cooled to ~61.5 while a Bear Div appeared, showing momentum lag as price pushed a higher high. Volume and volatility were elevated (≈ 1.79x / 1.25%). With a 5-bar cooldown, additional extremes won't print immediately. Some treat E High as exhaustion risk—either waiting for MPO rollover under 65/50 to fade, or for a pullback that holds above 50 to re-join the trend if higher-timeframe pressure remains constructive. Educational illustration only.
 Known limitations and caveats 
The MPO line itself can change intrabar; extreme markers/alerts do not repaint when "Confirm Extremes on Bar Close" is ON.
HTF values settle at the close of the HTF bar.
Illiquid symbols or very low TFs can be noisy; consider higher thresholds or longer smoothing.
Prediction line (when enabled) is a visual extrapolation only.
 For coders 
Pine v6. MTF via request.security with lookahead_off.
Extremes include crossover triggers so static thresholds also yield E High/E Low.
Extreme markers and pre-alerts are gated by barstate.isconfirmed when confirmation is ON.
Arrays prune oldest objects to respect resource limits; defaults (80/80/60) are conservative for low TFs.
3D layering uses negative offsets purely for drawing depth (no lookahead).
 Screenshot methodology: 
To make labels legible and to demonstrate non-repainting behavior, the examples were captured in TradingView Replay with "Confirm Extremes on Bar Close" enabled. Replay is used only to freeze the bar at close so plots don't change intrabar. The examples use default settings, include both Extreme Low and Extreme High cases, and can be reproduced by scrolling to the same bars outside Replay. This is an educational illustration, not a performance claim.
 Disclaimer 
This script is for educational purposes only and does not constitute financial advice. Markets involve risk; past behavior does not guarantee future results. You are responsible for your own testing, risk management, and decisions.
Historical VolatilityHistorical Volatility Indicator with Custom Trading Sessions 
 Overview 
This indicator calculates **annualized Historical Volatility (HV)** using logarithmic returns and standard deviation. Unlike standard HV indicators, this version allows you to **customize trading sessions and holidays** for different markets, ensuring accurate volatility calculations for options pricing and risk management.
 Key Features 
✅  Custom Trading Sessions  - Define multiple trading sessions per day with precise start/end times  
✅  Multiple Markets Support  - Pre-configured for US, Russian, European, and crypto markets  
✅  Clearing Periods Handling  - Account for intraday clearing breaks  
✅  Flexible Calendar  - Set trading days per year for different countries  
✅  All Timeframes  - Works correctly on intraday, daily, weekly, and monthly charts  
✅  Info Table  - Optional display showing calculation parameters  
 How It Works 
The indicator uses the classical volatility formula:
 σ_annual = σ_period × √(periods per year) 
Where:
- σ_period = Standard deviation of logarithmic returns over the specified period
- Periods per year = Calculated based on actual trading time (not calendar time)
 Calculation Method 
1. Computes log returns:  ln(close / close ) 
2. Calculates standard deviation over the lookback period
3. Annualizes using the square root rule with accurate period count
4. Displays as percentage
 Settings 
 Calculation 
-  Period  (default: 10) - Lookback period for volatility calculation
 Trading Schedule 
-  Trading Days Per Year  (default: 252) - Number of actual trading days
  - USA: 252
  - Russia: 247-250
  - Europe: 250-253
  - Crypto (24/7): 365
-  Trading Sessions  - Define trading hours in format: `hh:mm:ss-hh:mm:ss, hh:mm:ss-hh:mm:ss`
 Display 
-  Show Info Table  - Shows calculation parameters in real-time
 Market Presets 
 United States (NYSE/NASDAQ) 
Trading Sessions: 09:30:00-16:00:00
Trading Days Per Year: 252
Trading Minutes Per Day: 390
 Russia (MOEX) 
Trading Sessions: 10:00:00-14:00:00, 14:05:00-18:40:00
Trading Days Per Year: 248
Trading Minutes Per Day: 515
 Europe (LSE) 
Trading Sessions: 08:00:00-16:30:00
Trading Days Per Year: 252
Trading Minutes Per Day: 510
 Germany (XETRA) 
Trading Sessions: 09:00:00-17:30:00
Trading Days Per Year: 252
Trading Minutes Per Day: 510
 Cryptocurrency (24/7) 
Trading Sessions: 00:00:00-23:59:59
Trading Days Per Year: 365
Trading Minutes Per Day: 1440
 Use Cases 
 Options Trading 
-  Compare HV vs IV  - Historical volatility compared to implied volatility helps identify mispriced options
-  Volatility mean reversion  - Identify when volatility is unusually high or low
-  Straddle/strangle selection  - Choose optimal strikes based on historical movement
 Risk Management 
-  Position sizing  - Adjust position size based on current volatility
-  Stop-loss placement  - Set stops based on expected price movement
-  Portfolio volatility  - Monitor individual asset volatility contribution
 Market Analysis 
-  Regime identification  - Detect transitions between low and high volatility environments
-  Cross-market comparison  - Compare volatility across different assets and markets
 Why Accurate Trading Hours Matter 
Standard HV indicators assume 24-hour trading or use simplified day counts, leading to  significant errors  in annualized volatility:
-  5-minute chart error : Can be off by 50%+ if using wrong period count
-  Options pricing impact : Even 2-3% HV error affects option values substantially
-  Intraday vs overnight : Correctly excludes non-trading periods
This indicator ensures your HV calculations match the methodology used in professional options pricing models.
 Technical Notes 
- Uses actual trading minutes, not calendar days
- Handles multiple clearing periods within a single trading day
- Properly scales volatility across all timeframes
- Logarithmic returns for more accurate volatility measurement
- Compatible with Pine Script v6
 Author Notes:  This indicator was designed specifically for options traders who need precise volatility measurements across different global markets. The customizable trading sessions ensure your HV calculations align with actual market hours and industry-standard options pricing models.
Best MA Finder: Sharpe/Sortino ScannerThis script, Best MA Finder: Sharpe/Sortino Scanner, is a tool designed to identify the moving average (SMA or EMA) that best acts as a dynamic trend threshold on a chart, based on risk-adjusted historical performance. It scans a wide range of MA lengths (SMA or EMA) and selects the one whose simple price vs MA crossover delivered the strongest results using either the Sharpe ratio or the Sortino ratio. Reading it is intuitive: when price spent time above the selected MA, conditions were on average more favorable in the backtest; below, less favorable. It is a trend and risk gauge, not an overbought or oversold signal.
What it does:
- Runs individual long-only crossover backtests for many MA lengths across short to very long horizons.
- For each length, measures the total number of trades, the annualized Sharpe ratio, and the annualized Sortino ratio.
- Uses the chosen metric value (Sharpe or Sortino) as the score to rank candidates.
- Applies a minimum trade filter to discard statistically weak results.
- Optionally applies a local stability filter to prefer a length that also outperforms its close neighbors by at least a small margin.
- Selects the optimal MA and displays it on the chart with a concise summary table.
How to use it:
- Choose MA type: SMA or EMA.
- Choose the metric: Sharpe or Sortino.
- Set the minimum trade count to filter out weak samples.
- Select the risk-free mode:
  Auto: uses a short-term risk-free rate for USD-priced symbols when available.
  Manual: you provide a risk-free ticker.
  None: no risk-free rate.
- Optionally enable stability controls: neighbor radius and epsilon.
- Toggle the on-chart summary table as needed.
On-chart output:
- The selected optimal MA is plotted.
- The optional table shows MA length, number of trades, chosen metric value annualized, and the annual risk-free rate used.
Key features:
- Risk-adjusted optimization via Sharpe or Sortino for fair, comparable assessment.
- Broad MA scan with SMA and EMA support.
- Optional stability filter to avoid one-off spikes.
- Clear and auditable presentation directly on the chart.
Use cases:
- Traders who want a defensible, data-driven trend threshold without manual trial and error.
- Swing and trend-following workflows across timeframes and asset classes.
- Quick SMA vs EMA comparisons using risk-adjusted results.
Limitations:
- Not a full trading strategy with position sizing, costs, funding, slippage, or stops.
- Long-only, one position at a time.
- Discrete set of MA lengths, not a continuous optimizer.
- Requires sufficient price history and, if used, a reliable risk-free series.
This script is open-source and built from original logic. It does not replicate closed-source scripts or reuse significant external components.
Multi Momentum 10/21/42/63 — Histogram + 2xSMAMY MM INDICATOR INDIRED BY KARADI
It averages four rate-of-change snapshots of price, all anchored at today’s close.
If “Show as %” is on, the value is multiplied by 100.
Each term is a simple momentum/ROC over a different lookback.
Combining 10, 21, 42, 63 bars blends short, medium, and intermediate horizons into one number.
Positive MM → average upward pressure across those horizons; negative MM → average downward pressure.
Why those lengths?
They roughly stack into ~2× progression (10→21≈2×10, 21→42=2×21, 63≈1.5×42). That creates a “multi-scale” momentum that’s less noisy than a single fast ROC but more responsive than a long ROC alone.
How to read the panel
Gray histogram = raw Multi-Momentum value each bar.
SMA Fast/Slow lines (defaults 12 & 26 over the MM values) = smoothing of the histogram to show the trend of momentum itself.
Typical signals
Zero-line context:
Above 0 → bullish momentum regime on average.
Below 0 → bearish regime.
Crosses of SMA Fast & Slow: momentum trend shifts (fast above slow = improving momentum; fast below slow = deteriorating).
Histogram vs SMA lines: widening distance suggests strengthening momentum; narrowing suggests momentum is fading.
Divergences: price makes a new high/low but MM doesn’t → potential exhaustion.
Compared to a classic ROC
A single ROC(20) is very sensitive to that one window.
MM averages several windows, smoothing idiosyncrasies (e.g., a one-off spike 21 bars ago) and reducing “lookback luck.”
Settings & customization
Lookbacks (10/21/42/63): you can tweak for your asset/timeframe; the idea is to mix short→medium horizons.
Percent vs raw ratio: percent is easier to compare across symbols.
SMA lengths: shorter = more reactive but choppier; longer = smoother but slower.
Practical tips
Use regime + signal: trade longs primarily when MM>0 and fast SMA>slow SMA; consider shorts when MM<0 and fast
Irrationality Index by CRYPTO_ADA_BTC"The market can be irrational longer than you can stay solvent"  ~ John Maynard Keynes
This indicator, the Irrationality Index, measures how far the current market price has deviated from a smoothed estimate of its "fair value," normalized for recent volatility. It provides traders with a visual sense of when the market may be behaving irrationally, without giving direct buy or sell signals.
How it works:
1. Fair Value Calculation
   The indicator estimates a "fair value" for the asset using a combination of a long-term EMA (exponential moving average) and a linear regression trend over a configurable period. This fair value serves as a smoothed baseline for price, balancing trend-following and mean-reversion.
2. Volatility-Adjusted Z-Score
   The deviation between price and fair value is measured in standard deviations of recent log returns:
    Z = (log(price) - log(fairValue)) / volatility 
   This standardization accounts for different volatility environments, allowing comparison across assets.
3. Irrationality Score (0–100)
   The Z-score is transformed using a logistic mapping into a 0–100 scale:
   - 50 → price near fair value (rational zone)
   - >75 → high irrationality, price stretched above fair value
   - >90 → extreme irrationality, unsustainable extremes
   - <25 → high irrationality, price stretched below fair value
   - <10 → extreme bearish irrationality
4. Price vs Fair Value (% deviation)
   The indicator plots the percentage difference between price and fair value:
    pctDiff = (price - fairValue) / fairValue * 100 
   - Positive values → Percentage above fair value (optimistic / overvalued)
   - Negative values → Percentage below fair value (pessimistic / undervalued)
Visuals:
- Irrationality (%) Line (0–100) shows irrationality level.
- Background Colors: Yellow= high bullish irrationality, Green= extreme bullish irrationality, Orange= high bearish irrationality, Red= extreme bearish irrationality.
- Price - FairValue (%) plot: price deviation vs fair value (%), Colored green above 0 and red below 0.
- Label: display actual price, estimated fair value, and Z-score for the latest bar.
- Alerts: configurable thresholds for high and extreme irrationality.
How to read it:
- 50 → Market trading near fair value.
- >75 / >90 → Price may be irrationally high; risk of pullback increases.
- <25 / <10 → Price may be irrationally low; potential rebound zones, but trends can continue.
- Price - FairValue (%) plot → visual guide for % price stretch relative to fair value.
Notes / Warnings:
- Measures relative deviation, not fundamental value!
- High irrationality scores do not automatically indicate trades;  markets can remain can be irrational longer than you can stay solvent .
- Best used with other tools: momentum, volume, divergence, and multi-timeframe analysis.
Pairs Trading Scanner [BackQuant]Pairs Trading Scanner  
 What it is 
 This scanner analyzes the relationship between your  chart symbol  and a chosen  pair symbol  in real time. It builds a normalized “spread” between them, tracks how tightly they move together (correlation), converts the spread into a Z-Score (how far from typical it is), and then prints clear  LONG / SHORT / EXIT  prompts plus an at-a-glance dashboard with the numbers that matter.
 Why pairs at all? 
  
  Markets co-move. When two assets are statistically related, their relationship (the spread) tends to oscillate around a mean.
  Pairs trading doesn’t require calling overall market direction you trade the  relative mispricing  between two instruments.
  This scanner gives you a robust, visual way to find those dislocations, size their significance, and structure the trade.
  
 How it works (plain English) 
  
  Step 1   Pick a partner:  Select the  Pair Symbol  to compare against your chart symbol. The tool fetches synchronized prices for both.
  Step 2   Build a spread:  Choose a  Spread Method  that defines “relative value” (e.g., Log Spread, Price Ratio, Return Difference, Price Difference). Each lens highlights a different flavor of divergence.
  Step 3   Validate relationship:  A rolling  Correlation  checks if the pair is moving together enough to be tradable. If correlation is weak, the scanner stands down.
  Step 4   Standardize & score:  The spread is normalized (mean & variability over a lookback) to form a  Z-Score . Large absolute Z means “stretched,” small means “near fair.”
  Step 5   Signals:  When the Z-Score crosses user-defined thresholds  with sufficient correlation , entries print:
  LONG  = long chart symbol / short pair symbol,
  SHORT  = short chart symbol / long pair symbol,
  EXIT  = mean reversion into the exit zone or correlation failure.
  
 Core concepts (the three pillars) 
  
  Spread Method    Your definition of “distance” between the two series.
  Guidance: 
  
  Log Spread:  Focuses on proportional differences; robust when prices live on different scales.
  Price Ratio:  Classic relative value; good when you care about “X per Y.”
  Return Difference:  Emphasizes recent performance gaps; nimble for momentum-to-mean plays.
  Price Difference:  Straight subtraction; intuitive for similar-scale assets (e.g., two ETFs).
  
  Correlation    A rolling score of co-movement. The scanner requires it to be above your  Min Correlation  before acting, so you’re not trading random divergence.
  Z-Score    “How abnormal is today’s spread?” Positive = chart richer than pair; negative = cheaper. Thresholds define entries/exits with transparent, statistical context.
  
 What you’ll see on the chart 
  
  Correlation plot  (blue line) with a dashed  Min Correlation  guide. Above the line = green zone for signals; below = hands off.
  Z-Score plot  (white line) with colored, dashed  Entry  bands and dotted  Exit  bands. Zero line for mean.
  Normalized spread  (yellow) for a quick “shape read” of recent divergence swings.
  Signal markers :
  LONG  (green label) when Z < –Entry and corr OK,
  SHORT  (red label) when Z > +Entry and corr OK,
  EXIT  (gray label) when Z returns inside the Exit band or correlation drops below the floor.
  Background tint  for active state (faint green for long-spread stance, faint red for short-spread stance).
  
 The two built-in dashboards 
  Statistics Table (top-right) 
  
  Pair Symbol    Your chosen partner.
  Correlation    Live value vs. your minimum.
  Z-Score    How stretched the spread is now.
  Current / Pair Prices    Real-time anchors.
  Signal State    NEUTRAL / LONG / SHORT.
  Price Ratio    Context for ratio-style setups.
  
 Analysis Table (bottom-right) 
  
  Avg Correlation    Typical co-movement level over your window.
  Max |Z|    The recent extremes of dislocation.
  Spread Volatility    How “lively” the spread has been.
  Trade Signal    A human-readable prompt (e.g., “LONG A / SHORT B” or “NO TRADE” / “LOW CORRELATION”).
  Risk Level    LOW / MEDIUM / HIGH based on current stretch (absolute Z).
  
 Signals logic (plain English) 
  
  Entry (LONG):  The spread is unusually negative (chart cheaper vs pair)  and  correlation is healthy. Expect mean reversion upward in the spread: long chart, short pair.
  Entry (SHORT):  The spread is unusually positive (chart richer vs pair)  and  correlation is healthy. Expect mean reversion downward in the spread: short chart, long pair.
  Exit:  The spread relaxes back toward normal (inside your exit band), or correlation deteriorates (relationship no longer trusted).
  
 A quick, repeatable workflow 
  
  1) Choose your pair  in context (same sector/theme or known macro link). Think: “Do these two plausibly co-move?”
  2) Pick a spread lens  that matches your narrative (ratio for relative value, returns for short-term performance gaps, etc.).
  3) Confirm correlation  is above your floor no corr, no trade.
  4) Wait for a stretch  (Z beyond Entry band) and a printed  LONG / SHORT .
  5) Manage to the mean  (EXIT band) or correlation failure; let the scanners’ state/labels keep you honest.
  
 Settings that matter (and why) 
  
  Spread Method    Defines the “mispricing” you care about.
  Correlation Period    Longer = steadier regime read, shorter = snappier to regime change.
  Z-Score Period    The window that defines “normal” for the spread; it sets the yardstick.
  Use Percentage Returns    Normalizes series when using return-based logic; keep on for mixed-scale assets.
  Entry / Exit Thresholds    Set your stretch and your target reversion zone. Wider entries = rarer but stronger signals.
  Minimum Correlation    The gatekeeper. Raising it favors quality over quantity.
  
 Choosing pairs (practical cheat sheet) 
  
  Same family:  two index ETFs, two oil-linked names, two gold miners, two L1 tokens.
  Hedge & proxy:  stock vs. sector ETF, BTC vs. BTC index, WTI vs. energy ETF.
  Cross-venue or cross-listing:  instruments that are functionally the same exposure but price differently intraday.
  
 Reading the cues like a pro 
  
  Divergence shape:  The yellow normalized spread helps you see rhythm fast spike and snap-back versus slow grind.
  Corr-first discipline:  Don’t fight the “Min Correlation” line. Good pairs trading starts with a relationship you can trust.
  Exit humility:  When Z re-centers, let the  EXIT  do its job. The edge is the journey to the mean, not overstaying it.
  
 Frequently asked (quick answers) 
  
  “Long/Short means what exactly?” 
  LONG  = long the chart symbol and short the pair symbol.
  SHORT  = short the chart symbol and long the pair symbol.
  “Do I need same price scales?”  No. The spread methods normalize in different ways; choose the one that fits your use case (log/ratio are great for mixed scales).
  “What if correlation falls mid-trade?”  The scanner will neutralize the state and print  EXIT . Relationship first; trade second.
  
 Field notes & patterns 
  
  Snap-back days:  After a one-sided session, return-difference spreads often flag cleaner intraday mean reversions.
  Macro rotations:  Ratio spreads shine during sector re-weights (e.g., value vs. growth ETFs); look for steady corr + elevated |Z|.
  Event bleed-through:  If one symbol reacts to news and its partner lags, Z often flags a high-quality, short-horizon re-centering.
  
 Display controls at a glance 
  
  Show Statistics Table    Live state & key numbers, top-right.
  Show Analysis Table    Context/risk read, bottom-right.
  Show Correlation / Spread / Z-Score    Toggle the sub-charts you want visible.
  Show Entry/Exit Signals    Turn markers on/off as needed.
  Coloring    Adjust Long/Short/Neutral and correlation line colors to match your theme.
  
 Alerts (ready to route to your workflow) 
  
  Pairs Long Entry    Z falls through the long threshold with correlation above minimum.
  Pairs Short Entry    Z rises through the short threshold with correlation above minimum.
  Pairs Trade Exit    Z returns to neutral or the relationship fails your correlation floor.
  Correlation Breakdown    Rolling correlation crosses your minimum; relationship caution.
  
 Final notes 
 The scanner is designed to keep you systematic: require relationship (correlation), quantify dislocation (Z-Score), act when stretched, stand down when it normalizes or the relationship degrades. It’s a full, visual loop for relative-value trading that stays out of your way when it should and gets loud only when the numbers line up.
BioSwarm Imprinter™BioSwarm Imprinter™ — Agent-Based Consensus for Traders
What it is
BioSwarm Imprinter™ is a non-repainting, agent-based sentiment oscillator. It fuses many short-to-medium lookback “opinions” into one 0–100 consensus line that is easy to read at a glance (50 = neutral, >55 bullish bias, <45 bearish bias). The engine borrows from swarm intelligence: many simple voters (agents) adapt their influence over time based on how well they’ve been predicting price, so the crowd gets smarter as conditions change.
Use it to:
	•	Detect emerging trends sooner without overreacting to noise.
	•	Filter mean-reversion vs continuation opportunities.
	•	Gate entries with a confidence score that reflects both strength and persistence of the move.
	•	Combine with your execution tools (VWAP/ORB/levels) as a state filter rather than a trade signal by itself.
⸻
Why it’s different
	•	Swarm learning: Each agent improves or decays its “fitness” depending on whether its vote matched the next bar’s direction. High-fitness agents matter more; weak agents fade.
	•	Multi-horizon by design: The crowd is composed of fixed, simple lookbacks spread from lenMin to lenMax. You get a blended, robust view instead of a single fragile parameter.
	•	Two complementary lenses: Each agent evaluates RSI-style balance (via Wilder’s RMA) and momentum (EMA deviation). You decide the weight of each.
	•	No repaint, no MTF pitfalls: Everything runs on the chart’s timeframe with bar-close confirmation; no request.security() or forward references.
	•	Actionable UI: A clean consensus line, optional regime background, confidence heat, and triangle markers when thresholds are crossed.
⸻
What you see on the chart
	•	Consensus line (0–100): Smoothed to your preference; color/area makes bull/bear zones obvious.
	•	Regime coloring (optional): Light green in bull zone, light red in bear zone; neutral otherwise.
	•	Confidence heat: A small gauge/number (0–100) that combines distance from neutral and recent persistence.
	•	Markers (optional): Triangles when consensus crosses up through your bull threshold (e.g., 55) or down through your bear threshold (e.g., 45).
	•	Info panel (optional): Consensus value, regime, confidence, number of agents, and basic diagnostics.
⸻
How it works (under the hood)
	1.	Horizon bins: The range   is divided into numBins. Each bin has a fixed, simple integer length (crucial for Pine’s safety rules).
	2.	Per-bin features (computed every bar):
	•	RSI-style balance using Wilder’s RMA (not ta.rsi()), then mapped to −1…+1.
	•	Momentum as (close − EMA(L)) / EMA(L) (dimensionless drift).
	3.	Agent vote: For its assigned bin, an agent forms a weighted score: score = wRSI*RSI_like + wMOM*Momentum. A small dead-band near zero suppresses chop; votes are +1/−1/0.
	4.	Fitness update (bar close): If the agent’s previous vote agreed with the next bar’s direction, multiply its fitness by learnGain; otherwise by learnPain. Fitness is clamped so it never explodes or dies.
	5.	Consensus: Weighted average of all votes using fitness as weights → map to 0–100 and smooth with EMA.
Why it doesn’t repaint:
	•	No future references, no MTF resampling, fitness updates only on confirmed bars.
	•	All TA primitives (RMA/EMA/deltas) are computed every bar unconditionally.
⸻
Signals & confidence
	•	Bullish bias: consensus ≥ bullThr (e.g., 55).
	•	Bearish bias: consensus ≤ bearThr (e.g., 45).
	•	Confidence (0–100):
	•	Distance score: how far consensus is from 50.
	•	Momentum score: how strong the recent change is versus its recent average.
	•	Combined into a single gate; start filtering entries at ≥60 for higher quality.
Tip: For range sessions, raise thresholds (60/40) and increase smoothing; for momentum sessions, lower smoothing and keep thresholds at 55/45.
⸻
Inputs you’ll actually tune
	•	Agents & horizons:
	•	N_agents (e.g., 64–128)
	•	lenMin / lenMax (e.g., 6–30 intraday, 10–60 swing)
	•	numBins (e.g., 12–24)
	•	Weights & smoothing:
	•	wRSI vs wMOM (e.g., 0.7/0.3 for FX & indices; 0.6/0.4 for crypto)
	•	deadBand (0.03–0.08)
	•	consSmooth (3–8)
	•	Thresholds & hygiene:
	•	bullThr/bearThr (55/45 default)
	•	cooldownBars to avoid signal spam
⸻
Playbooks (ready-to-use)
1) Breakout / Trend continuation
	•	Timeframe: 15m–1h for day/swing.
	•	Filter: Take longs only when consensus > 55 and confidence ≥ 60.
	•	Execution: Use your ORB/VWAP/pullback trigger for entry. Trail with swing lows or 1.5×ATR. Exit on a close back under 50 or when a bearish signal prints.
2) Mean reversion (fade)
	•	When: Sideways days or low-volatility clusters.
	•	Setup: Increase deadBand and consSmooth.
	•	Signal: Bearish fades when consensus rolls over below ≈55 but stays above 50; bullish fades when it rolls up above ≈45 but stays below 50.
	•	Targets: The neutral zone (~50) as the first take-profit.
3) Multi-TF alignment
	•	Keep BioSwarm on 1H for bias, execute on 5–15m:
	•	Only take entries in the direction of the 1H consensus.
	•	Skip counter-bias scalps unless confidence is very low (explicit mean-reversion plan).
⸻
Integrations that work
	•	DynamoSent Pro+ (macro bias): Only act when macro bias and swarm consensus agree.
	•	ORB + Session VWAP Pro: Trade London/NY ORB breakouts that retest while consensus >55 (long) or <45 (short).
	•	Levels/Orderflow: BioSwarm is your “go / no-go”; execution stays with your usual triggers.
⸻
Quick start
	1.	Drop the indicator on a 1H chart.
	2.	Start with: N_agents=64, lenMin=6, lenMax=30, numBins=16, deadBand=0.06, consSmooth=5, thresholds 55/45.
	3.	Trade only when confidence ≥ 60.
	4.	Add your favorite execution tool (VWAP/levels/OR) for entries & exits.
⸻
Non-repainting & safety notes
	•	No request.security(); no hidden lookahead.
	•	Bar-close confirmation for fitness and signals.
	•	All TA calls are unconditional (no “sometimes called” warnings).
	•	No series-length inputs to RSI/EMA — we use RMA/EMA formulas that accept fixed simple ints per bin.
⸻
Known limits & tips
	•	Too many signals? Raise deadBand, increase consSmooth, widen thresholds to 60/40.
	•	Too few signals? Lower deadBand, reduce consSmooth, narrow thresholds to 53/47.
	•	Over-fitting risk: Keep learnGain/learnPain modest (e.g., ×1.04 / ×0.96).
	•	Compute load: Large N_agents × numBins is heavier; scale to your device.
⸻
Example recipes
EURUSD 1H (swing):
lenMin=8, lenMax=34, numBins=16, wRSI=0.7, wMOM=0.3, deadBand=0.06, consSmooth=6, thr=55/45
Buy breakouts when consensus >55 and confidence ≥60; confirm with 5–15m pullback to VWAP or level.
SPY 15m (US session):
lenMin=6, lenMax=24, numBins=12, consSmooth=4, deadBand=0.05
On trend days, stay with longs as long as consensus >55; add on shallow pullbacks.
BTC 1H (24/7):
Increase momentum weight: wRSI=0.6, wMOM=0.4, extend lenMax to ~50. Use dynamic stops (ATR) and partials on strong verticals.
⸻
Final word
BioSwarm is a state engine: it tells you when the market is primed to continue or mean-revert. Pair it with your entries and risk framework to turn that state into trades. If you’d like, I can supply a companion strategy template that consumes the consensus and back-tests the three playbooks (Breakout/Fade/Flip) with standard risk management.
Whale Money Flow DetectorKey Components:
Volume Analysis: Detects unusual volume spikes compared to average
Money Flow Index: Shows buying vs selling pressure
Whale Detection: Identifies large moves with high volume
Cumulative Flow: Tracks net whale activity over time
Visual Signals: Background colors and whale emoji labels
What it detects:
Large volume transactions (configurable multiplier)
Significant price moves with corresponding volume
Buying vs selling pressure from large players
Cumulative whale flow momentum
Customizable Parameters:
Volume MA Length (default: 20)
Whale Volume Multiplier (default: 2.0x)
Money Flow Length (default: 14)
Detection Sensitivity (default: 1.5)
Visual Features:
Green background for whale buying
Red background for whale selling
Whale emoji labels on significant moves
Real-time stats table
Multiple plot lines for different metrics
How to use:
Copy the code to TradingView's Pine Editor
Apply to your chart
Adjust sensitivity settings based on your asset's behavior
Set up alerts for whale buy/sell signals






















