OPEN-SOURCE SCRIPT
Atualizado Vol Compression PRO

## Volatility Compression PRO (Fully Fixed)
This indicator is an **options-theory-inspired “volatility compression → expansion” detector**, enhanced for **crypto trading on 4H/1D**. It is designed as a **two-stage system**:
1. **Environment / Setup (1D)**: Detects a volatility-compressed regime where a breakout is more likely.
2. **Trigger (current chart TF, recommended 4H)**: Confirms the breakout using price structure + volatility expansion + (optional) volume.
A major feature of this script is that it **avoids TradingView’s 5000-bar historical limitation** by recommending a **Daily HV (1D) computation mode**, which is stable and not constrained by intraday bar counts.
---
## Core Concept
### Stage A — “Setup” (Daily Environment Filter)
On the **daily timeframe**, the script estimates realized volatility (HV) and produces an **Environment Score (0–100)** that reflects how “compressed” volatility is versus its own history.
A **Setup window** becomes active when:
* `Environment Score >= Setup Threshold`
* Optional “persistence” can keep Setup active for N days after triggering (to avoid edge flicker).
It also calculates a **daily directional bias** (Bull/Bear) using one of two methods:
* **Price vs Daily EMA** (default): bias is bullish if daily close > daily EMA, bearish if below.
* **MACD > 0**: bias is bullish if daily MACD line > 0, bearish if < 0.
This stage answers:
**“Are we in a volatility-compressed regime worth watching, and what is the higher-timeframe bias?”**
---
## HV / Compression Scoring Model
The script computes:
* **Short-term HV**: standard deviation of log returns over a short window
* **Long-term HV**: standard deviation of log returns over a long window
* **HV Percentile**: percentile rank of short HV over a historical lookback
* **Compression Ratio (S/L)**: short HV divided by long HV (`<1` implies compression, `>1` implies expansion)
* **Log-Z Deviation**: Z-score of log(HV) vs its historical distribution (more stable than raw HV Z-score)
Then it builds a **0–100 score** using weighted components:
* Low HV percentile (lower = more compressed)
* Compression ratio below 1 (more compression)
* Negative log-Z deviation (HV below typical)
This produces a single number: **“Explosion Potential (Environment Score)”**.
---
## Stage B — Trigger Logic (Current Chart Timeframe, recommended 4H)
A **Long Trigger** fires only when **all** of the following are true:
1. **Setup is active** (from daily environment score)
2. **Daily bias is bullish**
3. **Donchian breakout UP**
* Close breaks above the **previous bar’s** highest high of the last N bars
* Uses `[1]` to avoid same-bar repaint-style lookback issues
4. **Volatility expansion confirmation**, via either:
* **Bollinger Band Width rising** (BBW turns up and exceeds its mean), and/or
* **ATR% rising** (ATR as % of price increases)
5. **Optional volume confirmation**:
* Volume > SMA(volume) × multiplier (if enabled)
A **Short Trigger** mirrors the long logic (requires bearish bias + downside Donchian break), and can be toggled on/off.
This stage answers:
**“Did price actually escape the compression box, and is volatility expanding with it?”**
---
## Two HV Calculation Modes (5000-bar limitation fix)
### 1) **Daily HV (Recommended)**
* Computes HV + Score + Setup on the **daily timeframe using `request.security(...,"D",...)`**
* This avoids intraday needing thousands of bars to represent many days
* Much more stable and reliable for regime detection
### 2) **Adaptive to Chart TF**
* Computes HV on the **current chart timeframe**
* Includes a strict conversion of “days → bars” and clamps lengths to **<= 4800 bars** to avoid the 5000-bar ceiling
* Still less robust on small timeframes, but won’t crash the script
---
## Visualization
* Plots the **Environment Score** as the main line (colored by score level)
* Draws reference lines at 70 / 50 / 30
* Highlights the background when **Setup** is active
* Optional trigger markers:
* **“L”** for long trigger (triangle up)
* **“S”** for short trigger (triangle down)
* A top-right info panel shows:
* HV short/long, HV percentile, compression ratio, log-Z deviation
* Environment score, Setup active status, daily bias
* Breakout status, expansion confirmation, volume confirmation
* Current mode (“1D fixed” vs “Adaptive”)
---
## Alerts
Built-in alert conditions:
* Setup active (compression window)
* Long Trigger
* Short Trigger
---
## Intended Use (Practical)
* Use **1D** to judge whether volatility is compressed and define bias
* Use **4H** to wait for a clean breakout plus expansion confirmation
* Avoid forcing entries during compression without a real breakout (“don’t catch falling knives” logic)
Notas de Lançamento
new update Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.