PROTECTED SOURCE SCRIPT

Bitcoin PERP/SPOT Sentiment Index

210
# Bitcoin PERP/SPOT Sentiment Index

A comprehensive Pine Script indicator that measures market sentiment by analyzing the premium/discount between Bitcoin perpetual futures and spot prices across multiple cryptocurrency exchanges.

## 📊 Overview

The Bitcoin PERP/SPOT Sentiment Index provides traders with deep insights into market psychology and risk appetite in the cryptocurrency ecosystem. By calculating the price difference (premium/discount) between perpetual futures contracts and spot prices, it reveals how traders are positioned and their sentiment toward Bitcoin's price direction.

**Key Insight**: The premium between PERP and SPOT prices is a powerful sentiment indicator that reflects trader positioning, risk appetite, and market psychology - data that influences but is separate from actual exchange funding rates.

## 🎯 Core Functionality

### Premium Calculation Methodology

The indicator calculates market sentiment using the following approach:

1. **Multi-Exchange Data Collection**: Fetches real-time prices from major exchanges for both perpetual futures (PERP) and spot markets
2. **TWAP Calculation**: Computes time-weighted average prices for both market types to reduce noise
3. **Premium Analysis**: Calculates the percentage difference between PERP and SPOT prices
4. **Sentiment Smoothing**: Applies time-weighted smoothing for stable sentiment readings

**Formula**: `Premium = (PERP_TWAP / SPOT_TWAP - 1) × 100`

### Market Sentiment Insights

**Positive Premium (PERP > SPOT) = Risk-On Sentiment**
- Traders prefer leveraged long positions via perpetuals
- High risk appetite and bullish expectations
- Willingness to pay premium for leverage access
- Often coincides with FOMO and greed phases

**Negative Premium (PERP < SPOT) = Risk-Off Sentiment**
- Traders prefer spot holdings or short perpetuals
- Fear-driven behavior and bearish expectations
- Spot premium indicates institutional accumulation
- Often coincides with capitulation and fear phases

### Exchange Coverage

**Perpetual Futures (17 markets)**:
- Bitmex (USD, USDT)
- Binance (USDT, USD)
- Bitget (USD, USDT, USDC)
- Bybit (USDT, USD)
- Phemex (USD, USDT)
- Huobi, Kraken, OKX (USD, USDT)
- Deribit, BingX

**Spot Markets (12 markets)**:
- Bitstamp, Binance, Coinbase
- Phemex, Huobi, Kraken, OKX
- Kucoin (USDT, USDC)
- Bitget (USDT, USDC)
- BTC Index

## 🎛️ Exchange Selection Modes

### 1. "Most Relevant Exchanges" (Default) ⭐

**Why this selection provides the best sentiment analysis:**

This preset focuses on exchanges that most accurately reflect true market sentiment by prioritizing:

#### **Institutional & Retail Balance**
- **Diverse User Base**: Includes exchanges serving both institutional (Coinbase, Kraken) and retail (Binance, Bybit) traders
- **Geographic Diversity**: Balances Western and Asian markets for global sentiment representation
- **Regulatory Clarity**: Focuses on exchanges with clear regulatory standing

#### **High-Quality Sentiment Data**
- **Deep Liquidity**: Ensures price movements reflect genuine sentiment, not thin book effects
- **Price Discovery Leaders**: These exchanges set market direction and sentiment trends
- **Reduced Manipulation**: Larger exchanges are less susceptible to artificial price manipulation

#### **Trading Behavior Insights**
- **Leverage Preferences**: Captures where traders actually choose to take leveraged positions
- **Risk Appetite Signals**: Reflects real money sentiment from major market participants
- **Arbitrage Efficiency**: Premium differences here represent actionable sentiment signals

**Included Exchanges**:
- **PERP**: Bitmex (USD/USDT), Binance (USDT/USD), Bybit (USDT/USD)
- **SPOT**: Bitstamp, Binance, Coinbase, Kraken, Kucoin, Bitget (USDT/USDC)

### 2. "All Exchange Data"
- Maximum market coverage for comprehensive sentiment analysis
- Includes smaller exchanges that may reflect niche trading behaviors
- Best for research and identifying sentiment divergences across market segments

### 3. "Excl. OKX and Huobi"
- Focuses on Western and international exchanges
- Useful for analyzing sentiment outside specific jurisdictions
- Maintains broad coverage while addressing regional concerns

### 4. "Individual: Select Below"
- Custom sentiment analysis for specific exchange combinations
- Perfect for testing regional sentiment differences
- Allows focus on specific trader demographics or market segments

## ⚙️ Configuration Options

### Core Settings
- **TWAP Interval**: Time period for price averaging
- **Premium Calculation Interval**: Data fetching frequency for sentiment updates
- **Percentage Rate Timeframe**: Multiplier for annualizing premium rates (e.g., 365 for annual rate)

### Sentiment Analysis Controls
- **Cut High Values**: Filters extreme sentiment spikes (>0.1%, >0.2%, >0.5%, >1.2%)
- **Enable Data Validation**: Automatically filters invalid price data for accurate sentiment
- **Minimum Exchanges Required**: Ensures reliable sentiment calculation (default: 3)

### Advanced Features
- **Sentiment Boost**: Adds realistic trading costs to better reflect actual sentiment impact
- **Moving Average Options**: SMA, WMA, EMA, RMA smoothing for trend analysis
- **Real-time Validation**: Prevents calculation with insufficient data

## 📈 Sentiment Interpretation Guide

### Positive Premium (Blue Bars) - Risk-On Sentiment
- **0-0.1%**: Neutral to slightly bullish sentiment
- **0.1-0.3%**: Moderate bullish sentiment, increasing risk appetite
- **0.3-0.5%**: Strong bullish sentiment, high leverage demand
- **>0.5%**: Extreme greed, potential contrarian signal

**Trading Psychology**: Traders are eager to pay premium for leveraged long exposure, indicating confidence and risk-taking behavior.

### Negative Premium (Red Bars) - Risk-Off Sentiment
- **0 to -0.1%**: Neutral to slightly bearish sentiment
- **-0.1% to -0.3%**: Moderate bearish sentiment, risk reduction
- **-0.3% to -0.5%**: Strong bearish sentiment, fear-driven behavior
- **<-0.5%**: Extreme fear, potential capitulation, contrarian opportunity

**Trading Psychology**: Traders prefer spot holdings or short positions, indicating caution and defensive positioning.

## 🧠 Sentiment Analysis Applications

### 1. **Market Psychology Assessment**
- Gauge overall trader confidence and risk appetite
- Identify shifts from greed to fear (and vice versa)
- Spot emotional extremes that often precede reversals

### 2. **Contrarian Trading Signals**
- Extreme positive premium (>0.5%) = potential sell signal (overconfidence)
- Extreme negative premium (<-0.5%) = potential buy signal (oversold sentiment)
- Divergences between price and sentiment for early reversal detection

### 3. **Risk Management**
- High premium = reduce position size (crowded long trades)
- Low/negative premium = potential opportunity for contrarian positions
- Sentiment trend analysis for position timing

### 4. **Market Timing**
- Premium expansion = momentum continuation likely
- Premium contraction = potential trend exhaustion
- Zero-line crosses = sentiment regime changes

### 5. **Institutional vs Retail Behavior**
- Sustained negative premium often indicates institutional accumulation
- Extreme positive premium suggests retail FOMO and leverage excess

## 🔧 Technical Implementation

### Anti-Repainting Protection
```pine
securemodule(data, intervall, source) =>
request.security(data, intervall, source[1], lookahead=barmerge.lookahead_on)
```

### Data Quality & Sentiment Accuracy
- Price bounds checking (1,000 - 200,000 USD) for realistic data
- Invalid data filtering to prevent sentiment distortion
- Minimum exchange count requirements for reliable sentiment readings
- Outlier detection to filter manipulation attempts

### Performance Optimizations
- Array-based exchange management for efficiency
- Efficient TWAP calculations for real-time sentiment updates
- Modular configuration system for easy customization
- Reduced redundant calculations for faster processing

## 🚀 Key Features (v1.0)

- **Bitcoin PERP/SPOT Sentiment Index**: First public release focused on sentiment analysis
- **Multi-Exchange Aggregation**: Combines data from 17 PERP and 12 SPOT markets
- **Advanced Data Validation**: Robust outlier filtering and data quality controls
- **Configurable Exchange Presets**: Optimized selections for different analysis needs
- **Real-Time Sentiment Analysis**: Live premium calculations with anti-repainting protection

## ⚠️ Important Distinctions

**What This Indicator Measures:**
- ✅ PERP/SPOT price premium (sentiment indicator)
- ✅ Market psychology and risk appetite
- ✅ Trader positioning preferences
- ✅ Leverage demand vs spot preference

**What This Indicator Does NOT Measure:**
- ❌ Actual exchange funding rates (these come from exchange APIs)
- ❌ Real funding costs paid by traders
- ❌ Exact arbitrage profitability
- ❌ Future price direction (sentiment can be wrong)

**Relationship to Funding Rates:**
The premium calculated by this indicator influences actual funding rates, but funding rates also include exchange-specific factors like funding intervals, rate caps, and internal calculations. This premium serves as a leading sentiment indicator that helps predict funding rate direction.

## 💡 Advanced Sentiment Strategies

1. **Sentiment Divergence**: Watch for premium direction differing from price movement
2. **Regime Change Detection**: Monitor sustained shifts in premium sign (+ to - or vice versa)
3. **Volatility Prediction**: Extreme premiums often precede high volatility periods
4. **Correlation Analysis**: Compare with VIX, Fear & Greed Index, and on-chain metrics
5. **Multi-Timeframe Sentiment**: Use different timeframes to identify sentiment trends vs noise

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, işlem veya diğer türden tavsiye veya tavsiyeler anlamına gelmez ve teşkil etmez. Kullanım Şartları'nda daha fazlasını okuyun.