# Data Source: CCXT Unified Exchange API

## Overview

CCXT (CryptoCurrency eXchange Trading Library) is a unified API for accessing 100+ cryptocurrency exchanges. The LuckySt Syndicate uses CCXT to extract historical and real-time prices for crypto assets, primarily to support Kalshi market making with volatility estimation and fair value calculations.

## Why CCXT

- **Unified API**: One interface for Binance, Coinbase, Kraken, etc.
- **Historical data**: OHLCV candles for volatility calculation
- **Real-time tickers**: Current bid/ask/last from major exchanges
- **Python native**: Async support with `ccxt.async_support`
- **Free**: No API key needed for public market data

## Installation

```bash
pip install ccxt
```

## Core Usage for LuckySt Agents

### Fetching Current Price

```python
import ccxt.async_support as ccxt

async def get_spot_price(symbol: str = "BTC/USDT", exchange: str = "binance") -> float:
    """Get current spot price from a CEX"""
    ex = getattr(ccxt, exchange)()
    try:
        ticker = await ex.fetch_ticker(symbol)
        return ticker["last"]
    finally:
        await ex.close()
```

### Fetching Historical OHLCV (for volatility)

```python
async def get_historical_prices(
    symbol: str = "BTC/USDT",
    timeframe: str = "1h",
    limit: int = 24,
    exchange: str = "binance"
) -> list:
    """Fetch OHLCV candles for volatility calculation"""
    ex = getattr(ccxt, exchange)()
    try:
        ohlcv = await ex.fetch_ohlcv(symbol, timeframe, limit=limit)
        # Returns: [[timestamp, open, high, low, close, volume], ...]
        return ohlcv
    finally:
        await ex.close()
```

### Calculating Realized Volatility

```python
import numpy as np

def calculate_realized_vol(ohlcv: list, annualize: bool = True) -> float:
    """Calculate realized volatility from OHLCV data"""
    closes = [candle[4] for candle in ohlcv]
    log_returns = [np.log(closes[i] / closes[i-1]) for i in range(1, len(closes))]

    vol = np.std(log_returns)

    if annualize:
        # Assuming hourly candles, 8760 hours/year
        vol *= np.sqrt(8760)

    return vol
```

## Integration with Kalshi Markets

### Mapping Kalshi Tickers to CCXT Symbols

Kalshi crypto markets follow patterns that map to CCXT symbols:

| Kalshi Ticker Pattern | Asset | CCXT Symbol |
|----------------------|-------|-------------|
| `KXBTC-*` | Bitcoin | `BTC/USDT` |
| `KXETH-*` | Ethereum | `ETH/USDT` |
| `KXSOL-*` | Solana | `SOL/USDT` |

### Extracting Strike Price from Kalshi Ticker

```python
def parse_kalshi_ticker(ticker: str) -> dict:
    """Parse a Kalshi crypto market ticker"""
    # Example: KXBTC-26MAR01-T100000
    parts = ticker.split("-")
    asset = parts[0].replace("KX", "")  # "BTC"
    strike = int(parts[-1].replace("T", ""))  # 100000
    return {
        "asset": asset,
        "ccxt_symbol": f"{asset}/USDT",
        "strike": strike
    }
```

## Integration with CDF Strategy

CCXT provides the historical data needed for CDF:

1. **Spot price**: `fetch_ticker()` for current price S
2. **Historical candles**: `fetch_ohlcv()` for vol estimation
3. **Realized vol**: Calculate from close-to-close returns
4. **Feed into CDF**: `sigma = realized_vol`, `S = current_spot`

```
CCXT (Binance)
    |
    ├── Current spot price (S)
    ├── 24h OHLCV candles
    |       |
    |       v
    |   Realized volatility (sigma)
    |
    v
CDF Calculation: P(S > K | S, sigma, T)
    |
    v
Trading Signal -> Terminal
```

## Exchange Priority

For reliability, agents should try exchanges in this order:
1. **Binance** - Most liquid, best data
2. **Coinbase** - US-regulated, reliable
3. **Kraken** - Good fallback
4. **OKX** - Additional liquidity source

## Rate Limits

CCXT respects exchange-specific rate limits automatically, but agents should:
- Cache prices for at least 5 seconds between fetches
- Use a single exchange instance per session (don't create/destroy repeatedly)
- Prefer `fetch_ticker()` over `fetch_order_book()` for simple price checks

## Error Handling

```python
try:
    price = await get_spot_price("BTC/USDT")
except ccxt.NetworkError:
    # Network issue - retry or fall back to Pyth
    price = await get_pyth_price(BTC_PRICE_ID)
except ccxt.ExchangeError:
    # Exchange-specific error - try another exchange
    price = await get_spot_price("BTC/USDT", exchange="coinbase")
```

## Combining Pyth + CCXT

For maximum reliability, agents should cross-reference:
- **Primary**: Pyth oracle (on-chain, decentralized)
- **Secondary**: CCXT/Binance (off-chain, centralized)
- **If divergence > 0.5%**: Flag anomaly, use the more conservative price
- **If one source fails**: Fall back to the other seamlessly
