Skip to main content
ClaudeWave
Skill12k repo starsupdated today

perp-funding-basis

perp-funding-basis analyzes cryptocurrency perpetual futures funding rates and spot-futures basis spreads to identify carry trade opportunities and market extremes. It calculates annualized funding rates, classifies funding regimes from historical data, and detects long or short crowding conditions that signal potential reversals or arbitrage entry points across exchanges like OKX.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/HKUDS/Vibe-Trading /tmp/perp-funding-basis && cp -r /tmp/perp-funding-basis/agent/src/skills/perp-funding-basis ~/.claude/skills/perp-funding-basis
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Perpetual Funding Rate & Basis Trading

## Overview

Analyze perpetual futures funding rates and spot-futures basis to identify carry trade opportunities, market positioning extremes, and directional sentiment signals. Funding rates are the single most important microstructure indicator in crypto derivatives — they reveal real-time leverage positioning and crowd sentiment.

## Core Concepts

### 1. Funding Rate Mechanics

Perpetual futures have no expiry date. Instead, a **funding rate** is exchanged between longs and shorts every 8 hours (on most exchanges) to keep the perpetual price anchored to the spot price.

```
If perp price > spot price → funding rate positive → longs pay shorts
If perp price < spot price → funding rate negative → shorts pay longs
```

**OKX funding rate schedule**: payments at 00:00, 08:00, 16:00 UTC

**Annualized funding rate:**
```python
# OKX funding rate is per 8-hour period
# Annualized = rate × 3 (per day) × 365
funding_rate_8h = 0.01  # 0.01% per 8h
annualized = funding_rate_8h * 3 * 365  # = 10.95% annualized
```

### 2. Funding Rate Signal Framework

| Funding Rate (8h) | Annualized | Market State | Signal |
|--------------------|------------|-------------|--------|
| > +0.05% | > +54.75% | Extreme long crowding | Contrarian short / reduce longs |
| +0.02% to +0.05% | +21.9% to +54.75% | Elevated long bias | Cautious, carry trade viable |
| +0.005% to +0.02% | +5.5% to +21.9% | Mild long bias | Neutral to mild bullish |
| -0.005% to +0.005% | -5.5% to +5.5% | Balanced | Neutral |
| -0.02% to -0.005% | -21.9% to -5.5% | Mild short bias | Neutral to mild bearish |
| < -0.02% | < -21.9% | Short squeeze territory | Contrarian long / reduce shorts |

**Funding rate regime detection:**
```python
def funding_regime(rates_7d):
    """Classify funding rate regime from 7-day history."""
    avg = sum(rates_7d) / len(rates_7d)
    consecutive_positive = all(r > 0 for r in rates_7d[-3:])
    consecutive_negative = all(r < 0 for r in rates_7d[-3:])

    if avg > 0.03 and consecutive_positive:
        return "overheated_long"       # High risk of long squeeze
    elif avg > 0.01 and consecutive_positive:
        return "bullish_carry"          # Good carry trade environment
    elif avg < -0.02 and consecutive_negative:
        return "overheated_short"       # High risk of short squeeze
    elif avg < -0.005 and consecutive_negative:
        return "bearish_carry"          # Inverse carry trade
    else:
        return "neutral"
```

### 3. Spot-Futures Basis Analysis

**Basis = Futures price - Spot price**

For dated futures (quarterly), basis reflects cost-of-carry expectations:

```python
# Annualized basis
def annualized_basis(futures_price, spot_price, days_to_expiry):
    basis_pct = (futures_price - spot_price) / spot_price
    annualized = basis_pct * (365 / days_to_expiry)
    return annualized

# Example: BTC spot $65,000, quarterly future $66,500, 45 days to expiry
# Basis: 2.31%, Annualized: 18.7%
```

**Basis signal interpretation:**

| Annualized Basis | Market State | Signal |
|-----------------|-------------|--------|
| > 30% | Extreme contango, euphoric leverage | Sell basis (cash-carry), top warning |
| 15-30% | Elevated contango, bullish leverage | Carry trade attractive |
| 5-15% | Normal contango | Neutral, mild bullish |
| 0-5% | Flat basis | Low conviction, wait for direction |
| < 0% (backwardation) | Bearish, forced selling | Contrarian long, extreme pessimism |

### 4. Cash-Carry Arbitrage (Delta-Neutral)

**Strategy: buy spot + sell perpetual futures → collect funding rate**

```python
# Cash-carry trade P&L
def carry_trade_pnl(spot_entry, funding_rates, position_size):
    """
    Delta-neutral carry: long spot + short perp
    P&L comes purely from funding rate collection.
    """
    total_funding_collected = 0
    for rate in funding_rates:
        if rate > 0:  # Longs pay shorts → we collect as short
            total_funding_collected += rate * position_size
        else:  # Shorts pay longs → we pay as short
            total_funding_collected += rate * position_size  # This is negative

    return total_funding_collected

# Example: $100,000 position, avg funding +0.015% per 8h, 30 days
# Revenue: 0.015% × 3 × 30 × $100,000 = $1,350 (16.2% annualized)
```

**Carry trade execution on OKX:**
1. Buy spot BTC-USDT on OKX spot market
2. Open equal-sized short BTC-USDT-SWAP on OKX perpetual
3. Net delta = 0 (spot long cancels perp short)
4. Collect positive funding rate every 8 hours
5. Close both legs when funding rate turns negative or basis compresses

**Risk factors:**
- Funding rate can flip negative → carry becomes a cost
- Liquidation risk on short perp if insufficient margin (use 3-5x max leverage)
- Exchange counterparty risk (keep position across 2-3 exchanges)
- Basis can widen further before mean-reverting → mark-to-market loss on short leg

### 5. Cross-Exchange Funding Arbitrage

Different exchanges have different funding rates for the same asset. Arbitrage the spread:

```python
# Example: BTC-USDT perpetual funding rates
exchange_rates = {
    "OKX": 0.015,       # +0.015% per 8h
    "Binance": 0.020,   # +0.020% per 8h
    "Bybit": 0.025,     # +0.025% per 8h
}

# Strategy: short on highest funding (Bybit) + long on lowest funding (OKX)
# Net carry = 0.025% - 0.015% = 0.010% per 8h
# Annualized: 0.010% × 3 × 365 = 10.95%
# Risk: execution cost + potential for rates to converge/flip
```

### 6. Funding Rate as Directional Indicator

**Divergence signals (most powerful):**

| Price Action | Funding Rate | Interpretation | Signal |
|-------------|-------------|----------------|--------|
| Price making new highs | Funding declining | Longs not chasing → distribution | Bearish divergence |
| Price making new lows | Funding rising (less negative) | Shorts not pressing → accumulation | Bullish divergence |
| Price consolidating | Funding spiking positive | Leverage building without breakout | Squeeze risk |
| Price consolida
vibe-tradingSkill

Professional finance research toolkit — backtesting (7 engines + benchmark comparison panel), factor analysis, Alpha Zoo (452 pre-built alphas across qlib158/alpha101/gtja191/academic), options pricing, 77 finance skills, 29 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 7 data sources (tushare, yfinance, okx, akshare, mootdx, ccxt, futu).

adr-hshareSkill

ADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.

akshareSkill

AKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.

alpha-zooSkill

Browse and bench the bundled alpha zoos — prebuilt cross-sectional factor libraries (Kakushadze 101, GTJA 191, Qlib 158, Fama-French / Carhart). Use when the user asks "which alphas exist", wants metadata on a named alpha, or wants to run IC/IR on a whole zoo over a universe.

ashare-pre-st-filterSkill

A 股 ST/*ST 风险预测框架 — 基于最新中报/三季报或业绩预告/快报,预测下一财年是否会因营收、利润、净资产、分红不达标而被风险警示,并将新浪监管处罚记录作为独立证据面纳入风险等级。仅适用于 A 股,不预测财务造假。

asset-allocationSkill

Asset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.

backtest-diagnoseSkill

Diagnose failed or underperforming backtests, locate the root cause, and fix the issue

behavioral-financeSkill

Behavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.