OPEN-SOURCE SCRIPT
Ben's BTC Macro Fair Value Oscillator

Ben's BTC Macro Fair Value Oscillator
Overview
The **BTC Macro Fair Value Oscillator** is a non-crypto fair value framework that uses macro asset relationships (equities, dollar, gold) to estimate Bitcoin's "macro-driven fair value" and identify mean-reversion opportunities.
"Is BTC cheap or expensive right now?" on the 4 Hour Timeframe ONLY
### Key Features
✅ **Macro-driven**: Uses QQQ, DXY, XAUUSD instead of on-chain or crypto metrics
✅ **Dynamic weighting**: Assets weighted by rolling correlation strength
✅ **Mean-reversion signals**: Identifies when BTC is cheap/expensive vs macro
✅ **Validated parameters**: Optimized through 5-year backtest (Sharpe 6.7-9.9)
✅ **Visual transparency**: Live correlation panel, fair value bands, statistics
✅ **Non-repainting**: All calculations use confirmed historical data only
### What This Indicator Does
- Builds a **synthetic macro composite** from traditional assets
- Runs a **rolling regression** to predict BTC price from macro
- Calculates **deviation z-score** (how far BTC is from macro fair value)
- Generates **entry signals** when BTC is extremely cheap vs macro (dev < -2)
- Generates **exit signals** when BTC returns to fair value (dev > 0)
### What This Indicator Is NOT
❌ Not a high-frequency trading system (sparse signals by design)
❌ Not optimized for absolute returns (optimized for Sharpe ratio)
❌ Not suitable as standalone trading system (best as overlay/confirmation)
❌ Not predictive of short-term price movements (mean-reversion timeframe: days to weeks)
---
## Core Concept
### The Premise
Bitcoin doesn't trade in a vacuum. It's influenced by:
- **Risk appetite** (equities: QQQ, SPX)
- **Dollar strength** (DXY - inverse to risk assets)
- **Safe haven flows** (Gold: XAUUSD)
When macro conditions are "good for BTC" (risk-on, weak dollar, strong equities), BTC should trade higher. When macro conditions turn against it, BTC should trade lower.
### The Innovation
Instead of looking at BTC in isolation, this indicator:
1. **Measures how strongly** BTC currently correlates with each macro asset
2. **Builds a weighted composite** of those macro returns (the "D" driver)
3. **Regresses BTC price on D** to estimate "macro fair value"
4. **Tracks the deviation** between actual price and fair value
5. **Signals mean reversion** when deviation becomes extreme
### The Edge
The validated edge comes from:
- **Extreme deviations predict future returns** (dev < -2 → +1.67% over 12 bars)
- **Monotonic relationship** (more negative dev → higher forward returns)
- **Works out-of-sample** (test Sharpe +83-87% better than training)
- **Low correlation with buy & hold** (provides diversification value)
---
## Methodology
### Step 1: Macro Composite Driver D(t)
The indicator builds a weighted composite of macro asset returns:
**Process:**
1. Calculate **log returns** for BTC and each macro reference (QQQ, DXY, XAUUSD)
2. Compute **rolling correlation** between BTC and each reference over `corrLen` bars
3. **Weight each asset** by `|correlation|` if above `minCorrAbs` threshold, else 0
4. **Sign-adjust** weights (+1 for positive corr, -1 for negative) to handle inverse relationships
5. **Z-score normalize** each reference's returns over `fvWindow`
6. **Composite D(t)** = weighted sum of sign-adjusted z-scores
**Formula:**
```
For each reference i:
corr_i = correlation(BTC_returns, ref_i_returns, corrLen)
weight_i = |corr_i| if |corr_i| >= minCorrAbs else 0
sign_i = +1 if corr_i >= 0 else -1
z_i = (ref_i_returns - mean) / std
contrib_i = sign_i * z_i * weight_i
D(t) = sum(contrib_i) / sum(weight_i)
```
**Key Insight:** D(t) represents "how good macro conditions are for BTC right now" in a normalized, correlation-weighted way.
---
### Step 2: Fair Value Regression
Uses rolling linear regression to predict BTC price from D(t):
**Model:**
```
BTC_price(t) = α + β * D(t)
```
**Calculation (Pine Script approach):**
```
corr_CD = correlation(BTC_price, D, fvWindow)
sd_price = stdev(BTC_price, fvWindow)
sd_D = stdev(D, fvWindow)
cov = corr_CD * sd_price * sd_D
var_D = variance(D, fvWindow)
β = cov / var_D
α = mean(BTC_price) - β * mean(D)
fair_value(t) = α + β * D(t)
```
**Result:** A time-varying "macro fair value" line that adapts as correlations change.
---
### Step 3: Deviation Oscillator
Measures how far BTC price has deviated from fair value:
**Calculation:**
```
residual(t) = BTC_price(t) - fair_value(t)
residual_std = stdev(residual, normWindow)
deviation(t) = residual(t) / residual_std
```
**Interpretation:**
- `dev = 0` → BTC at fair value
- `dev = -2` → BTC is 2 standard deviations **cheap** vs macro
- `dev = +2` → BTC is 2 standard deviations **rich** vs macro
---
### Step 4: Signal Generation
**Long Entry:** `dev` crosses below `-2.0` (BTC extremely cheap vs macro)
**Long Exit:** `dev` crosses above `0.0` (BTC returns to fair value)
**No shorting** in default config (risk management choice - crypto volatility)
---
## How It Works
### Visual Components
#### 1. Price Chart (Main Panel)
**Fair Value Line (Orange):**
- The estimated "macro-driven fair value" for BTC
- Calculated from rolling regression on macro composite
**Fair Value Bands:**
- **±1σ** (light): 68% confidence zone
- **±2σ** (medium): 95% confidence zone
- **±3σ** (dark, dots): 99.7% confidence zone
**Entry/Exit Markers:**
- **Green "LONG" label** below bar: Entry signal (dev < -2)
- **Red "EXIT" label** above bar: Exit signal (dev > 0)
#### 2. Deviation Oscillator (Separate Pane)
**Line plot:**
- Shows current deviation z-score
- **Green** when dev < -2 (cheap)
- **Red** when dev > +2 (rich)
- **Gray** when neutral
**Histogram:**
- Visual representation of deviation magnitude
- Green bars = negative deviation (cheap)
- Red bars = positive deviation (rich)
**Threshold lines:**
- **Green dashed at -2.0**: Entry threshold
- **Red dashed at 0.0**: Exit threshold
- **Gray solid at 0**: Fair value line
#### 3. Correlation Panel (Top-Right)
Shows live correlation and weighting for each macro asset:
| Asset | Corr | Weight |
|-------|------|--------|
| QQQ | +0.45 | 0.45 |
| DXY | -0.32 | 0.32 |
| XAUUSD | +0.15 | 0.00 |
| Avg \|Corr\| | 0.31 | 0.77 |
**Reading:**
- **Corr**: Current rolling correlation with BTC (-1 to +1)
- **Weight**: How much this asset contributes to fair value (0 = excluded)
- **Avg |Corr|**: Average correlation strength (should be > 0.2 for reliable signals)
**Colors:**
- Green/Red corr = positive/negative correlation
- White weight = asset included, Gray = excluded (below minCorrAbs)
#### 4. Statistics Label (Bottom-Right)
```
━━━ BTC Macro FV ━━━
Dev: -2.34
Price: $103,192
FV: $110,500
Status: CHEAP ⬇
β: 103.52
```
**Fields:**
- **Dev**: Current deviation z-score
- **Price**: Current BTC close price
- **FV**: Current macro fair value estimate
- **Status**: CHEAP (< -2), RICH (> +2), or FAIR
- **β**: Current regression beta (sensitivity to macro)
---
## Installation & Setup
### TradingView Setup
1. Open TradingView and navigate to any **BTC chart** (BTCUSD, BTCUSDT, etc.)
2. Open **Pine Editor** (bottom panel)
3. Click **"+ New"** → **"Blank indicator"**
4. **Delete** all default code
5. **Copy** the entire Pine Script from `GHPT_optimized.pine`
6. **Paste** into the editor
7. Click **"Save"** and name it "BTC Macro Fair Value Oscillator"
8. Click **"Add to Chart"**
### Recommended Chart Settings
**Timeframe:** 4h (validated timeframe)
**Chart Type:** Candlestick or Heikin Ashi
**Overlay:** Yes (indicator plots on price chart + separate pane)
**Alternative Timeframes:**
- Daily: Works but slower signals
- 1h-2h: May work but not validated
- < 1h: Not recommended (too noisy)
### Symbol Requirements
**Primary:** BTC/USD or BTC/USDT on any exchange
**Macro References:** Automatically fetched
- QQQ (Nasdaq 100 ETF)
- DXY (US Dollar Index)
- XAUUSD (Gold spot)
**Data Requirements:**
- At least **90 bars** of history (warmup period)
- Premium TradingView recommended for full historical data
---
## Reading the Indicator
### Identifying Signals
#### Strong Long Signal (High Conviction)
- ✅ Deviation < -2.0 (extreme undervaluation)
- ✅ Avg |Corr| > 0.3 (strong macro relationships)
- ✅ Price touching or below -2σ band
- ✅ "LONG" label appears below bar
**Interpretation:** BTC is extremely cheap relative to macro conditions. Historical data shows +1.67% average return over next 12 bars (48 hours at 4h timeframe).
#### Moderate Long Signal (Lower Conviction)
- ⚠️ Deviation between -1.5 and -2.0
- ⚠️ Avg |Corr| between 0.2-0.3
- ⚠️ Price approaching -2σ band
**Interpretation:** BTC is cheap but not extreme. Consider as confirmation for other signals.
#### Exit Signal
- 🔴 Deviation crosses above 0 (returns to fair value)
- 🔴 "EXIT" label appears above bar
**Interpretation:** Mean reversion complete. Close long positions.
#### Strong Short/Avoid Signal
- 🔴 Deviation > +2.0 (extreme overvaluation)
- 🔴 Avg |Corr| > 0.3
- 🔴 Price touching or above +2σ band
**Interpretation:** BTC is expensive vs macro. Historical data shows -1.79% average return over next 12 bars. Consider exiting longs or reducing exposure.
### Regime Detection
**Strong Regime (Reliable Signals):**
- Avg |Corr| > 0.3
- Multiple assets weighted > 0
- Fair value line tracking price reasonably well
**Weak Regime (Unreliable Signals):**
- Avg |Corr| < 0.2
- Most weights = 0 (grayed out)
- Fair value line diverging wildly from price
- **Action:** Ignore signals until correlations strengthen
Overview
The **BTC Macro Fair Value Oscillator** is a non-crypto fair value framework that uses macro asset relationships (equities, dollar, gold) to estimate Bitcoin's "macro-driven fair value" and identify mean-reversion opportunities.
"Is BTC cheap or expensive right now?" on the 4 Hour Timeframe ONLY
### Key Features
✅ **Macro-driven**: Uses QQQ, DXY, XAUUSD instead of on-chain or crypto metrics
✅ **Dynamic weighting**: Assets weighted by rolling correlation strength
✅ **Mean-reversion signals**: Identifies when BTC is cheap/expensive vs macro
✅ **Validated parameters**: Optimized through 5-year backtest (Sharpe 6.7-9.9)
✅ **Visual transparency**: Live correlation panel, fair value bands, statistics
✅ **Non-repainting**: All calculations use confirmed historical data only
### What This Indicator Does
- Builds a **synthetic macro composite** from traditional assets
- Runs a **rolling regression** to predict BTC price from macro
- Calculates **deviation z-score** (how far BTC is from macro fair value)
- Generates **entry signals** when BTC is extremely cheap vs macro (dev < -2)
- Generates **exit signals** when BTC returns to fair value (dev > 0)
### What This Indicator Is NOT
❌ Not a high-frequency trading system (sparse signals by design)
❌ Not optimized for absolute returns (optimized for Sharpe ratio)
❌ Not suitable as standalone trading system (best as overlay/confirmation)
❌ Not predictive of short-term price movements (mean-reversion timeframe: days to weeks)
---
## Core Concept
### The Premise
Bitcoin doesn't trade in a vacuum. It's influenced by:
- **Risk appetite** (equities: QQQ, SPX)
- **Dollar strength** (DXY - inverse to risk assets)
- **Safe haven flows** (Gold: XAUUSD)
When macro conditions are "good for BTC" (risk-on, weak dollar, strong equities), BTC should trade higher. When macro conditions turn against it, BTC should trade lower.
### The Innovation
Instead of looking at BTC in isolation, this indicator:
1. **Measures how strongly** BTC currently correlates with each macro asset
2. **Builds a weighted composite** of those macro returns (the "D" driver)
3. **Regresses BTC price on D** to estimate "macro fair value"
4. **Tracks the deviation** between actual price and fair value
5. **Signals mean reversion** when deviation becomes extreme
### The Edge
The validated edge comes from:
- **Extreme deviations predict future returns** (dev < -2 → +1.67% over 12 bars)
- **Monotonic relationship** (more negative dev → higher forward returns)
- **Works out-of-sample** (test Sharpe +83-87% better than training)
- **Low correlation with buy & hold** (provides diversification value)
---
## Methodology
### Step 1: Macro Composite Driver D(t)
The indicator builds a weighted composite of macro asset returns:
**Process:**
1. Calculate **log returns** for BTC and each macro reference (QQQ, DXY, XAUUSD)
2. Compute **rolling correlation** between BTC and each reference over `corrLen` bars
3. **Weight each asset** by `|correlation|` if above `minCorrAbs` threshold, else 0
4. **Sign-adjust** weights (+1 for positive corr, -1 for negative) to handle inverse relationships
5. **Z-score normalize** each reference's returns over `fvWindow`
6. **Composite D(t)** = weighted sum of sign-adjusted z-scores
**Formula:**
```
For each reference i:
corr_i = correlation(BTC_returns, ref_i_returns, corrLen)
weight_i = |corr_i| if |corr_i| >= minCorrAbs else 0
sign_i = +1 if corr_i >= 0 else -1
z_i = (ref_i_returns - mean) / std
contrib_i = sign_i * z_i * weight_i
D(t) = sum(contrib_i) / sum(weight_i)
```
**Key Insight:** D(t) represents "how good macro conditions are for BTC right now" in a normalized, correlation-weighted way.
---
### Step 2: Fair Value Regression
Uses rolling linear regression to predict BTC price from D(t):
**Model:**
```
BTC_price(t) = α + β * D(t)
```
**Calculation (Pine Script approach):**
```
corr_CD = correlation(BTC_price, D, fvWindow)
sd_price = stdev(BTC_price, fvWindow)
sd_D = stdev(D, fvWindow)
cov = corr_CD * sd_price * sd_D
var_D = variance(D, fvWindow)
β = cov / var_D
α = mean(BTC_price) - β * mean(D)
fair_value(t) = α + β * D(t)
```
**Result:** A time-varying "macro fair value" line that adapts as correlations change.
---
### Step 3: Deviation Oscillator
Measures how far BTC price has deviated from fair value:
**Calculation:**
```
residual(t) = BTC_price(t) - fair_value(t)
residual_std = stdev(residual, normWindow)
deviation(t) = residual(t) / residual_std
```
**Interpretation:**
- `dev = 0` → BTC at fair value
- `dev = -2` → BTC is 2 standard deviations **cheap** vs macro
- `dev = +2` → BTC is 2 standard deviations **rich** vs macro
---
### Step 4: Signal Generation
**Long Entry:** `dev` crosses below `-2.0` (BTC extremely cheap vs macro)
**Long Exit:** `dev` crosses above `0.0` (BTC returns to fair value)
**No shorting** in default config (risk management choice - crypto volatility)
---
## How It Works
### Visual Components
#### 1. Price Chart (Main Panel)
**Fair Value Line (Orange):**
- The estimated "macro-driven fair value" for BTC
- Calculated from rolling regression on macro composite
**Fair Value Bands:**
- **±1σ** (light): 68% confidence zone
- **±2σ** (medium): 95% confidence zone
- **±3σ** (dark, dots): 99.7% confidence zone
**Entry/Exit Markers:**
- **Green "LONG" label** below bar: Entry signal (dev < -2)
- **Red "EXIT" label** above bar: Exit signal (dev > 0)
#### 2. Deviation Oscillator (Separate Pane)
**Line plot:**
- Shows current deviation z-score
- **Green** when dev < -2 (cheap)
- **Red** when dev > +2 (rich)
- **Gray** when neutral
**Histogram:**
- Visual representation of deviation magnitude
- Green bars = negative deviation (cheap)
- Red bars = positive deviation (rich)
**Threshold lines:**
- **Green dashed at -2.0**: Entry threshold
- **Red dashed at 0.0**: Exit threshold
- **Gray solid at 0**: Fair value line
#### 3. Correlation Panel (Top-Right)
Shows live correlation and weighting for each macro asset:
| Asset | Corr | Weight |
|-------|------|--------|
| QQQ | +0.45 | 0.45 |
| DXY | -0.32 | 0.32 |
| XAUUSD | +0.15 | 0.00 |
| Avg \|Corr\| | 0.31 | 0.77 |
**Reading:**
- **Corr**: Current rolling correlation with BTC (-1 to +1)
- **Weight**: How much this asset contributes to fair value (0 = excluded)
- **Avg |Corr|**: Average correlation strength (should be > 0.2 for reliable signals)
**Colors:**
- Green/Red corr = positive/negative correlation
- White weight = asset included, Gray = excluded (below minCorrAbs)
#### 4. Statistics Label (Bottom-Right)
```
━━━ BTC Macro FV ━━━
Dev: -2.34
Price: $103,192
FV: $110,500
Status: CHEAP ⬇
β: 103.52
```
**Fields:**
- **Dev**: Current deviation z-score
- **Price**: Current BTC close price
- **FV**: Current macro fair value estimate
- **Status**: CHEAP (< -2), RICH (> +2), or FAIR
- **β**: Current regression beta (sensitivity to macro)
---
## Installation & Setup
### TradingView Setup
1. Open TradingView and navigate to any **BTC chart** (BTCUSD, BTCUSDT, etc.)
2. Open **Pine Editor** (bottom panel)
3. Click **"+ New"** → **"Blank indicator"**
4. **Delete** all default code
5. **Copy** the entire Pine Script from `GHPT_optimized.pine`
6. **Paste** into the editor
7. Click **"Save"** and name it "BTC Macro Fair Value Oscillator"
8. Click **"Add to Chart"**
### Recommended Chart Settings
**Timeframe:** 4h (validated timeframe)
**Chart Type:** Candlestick or Heikin Ashi
**Overlay:** Yes (indicator plots on price chart + separate pane)
**Alternative Timeframes:**
- Daily: Works but slower signals
- 1h-2h: May work but not validated
- < 1h: Not recommended (too noisy)
### Symbol Requirements
**Primary:** BTC/USD or BTC/USDT on any exchange
**Macro References:** Automatically fetched
- QQQ (Nasdaq 100 ETF)
- DXY (US Dollar Index)
- XAUUSD (Gold spot)
**Data Requirements:**
- At least **90 bars** of history (warmup period)
- Premium TradingView recommended for full historical data
---
## Reading the Indicator
### Identifying Signals
#### Strong Long Signal (High Conviction)
- ✅ Deviation < -2.0 (extreme undervaluation)
- ✅ Avg |Corr| > 0.3 (strong macro relationships)
- ✅ Price touching or below -2σ band
- ✅ "LONG" label appears below bar
**Interpretation:** BTC is extremely cheap relative to macro conditions. Historical data shows +1.67% average return over next 12 bars (48 hours at 4h timeframe).
#### Moderate Long Signal (Lower Conviction)
- ⚠️ Deviation between -1.5 and -2.0
- ⚠️ Avg |Corr| between 0.2-0.3
- ⚠️ Price approaching -2σ band
**Interpretation:** BTC is cheap but not extreme. Consider as confirmation for other signals.
#### Exit Signal
- 🔴 Deviation crosses above 0 (returns to fair value)
- 🔴 "EXIT" label appears above bar
**Interpretation:** Mean reversion complete. Close long positions.
#### Strong Short/Avoid Signal
- 🔴 Deviation > +2.0 (extreme overvaluation)
- 🔴 Avg |Corr| > 0.3
- 🔴 Price touching or above +2σ band
**Interpretation:** BTC is expensive vs macro. Historical data shows -1.79% average return over next 12 bars. Consider exiting longs or reducing exposure.
### Regime Detection
**Strong Regime (Reliable Signals):**
- Avg |Corr| > 0.3
- Multiple assets weighted > 0
- Fair value line tracking price reasonably well
**Weak Regime (Unreliable Signals):**
- Avg |Corr| < 0.2
- Most weights = 0 (grayed out)
- Fair value line diverging wildly from price
- **Action:** Ignore signals until correlations strengthen
오픈 소스 스크립트
진정한 트레이딩뷰 정신에 따라 이 스크립트 작성자는 트레이더가 기능을 검토하고 검증할 수 있도록 오픈소스로 공개했습니다. 작성자에게 찬사를 보냅니다! 무료로 사용할 수 있지만 코드를 다시 게시할 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.
오픈 소스 스크립트
진정한 트레이딩뷰 정신에 따라 이 스크립트 작성자는 트레이더가 기능을 검토하고 검증할 수 있도록 오픈소스로 공개했습니다. 작성자에게 찬사를 보냅니다! 무료로 사용할 수 있지만 코드를 다시 게시할 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.