# Strategy: Cumulative Distribution Function (CDF) Active Market Making

## Overview

The CDF strategy is an active market making approach for price-based prediction markets (e.g., "Will BTC be above $100,000 at 5:00 PM?"). It uses external price feeds to derive a fair probability, then quotes a configurable spread around that fair price. The agent continuously updates its quotes as spot prices and volatility change.

This is **not** passive waiting for divergence — the agent is always quoting, always making markets, actively providing liquidity around its CDF-derived fair value.

## How It Works

### 1. Fetch Spot Price

The agent fetches the current spot price from **Pyth Network oracles** on Base for real-time data, and supplements with **CCXT** historical data for volatility estimation.

```python
spot_price = await get_pyth_price(BTC_PRICE_FEED_ID)  # Real-time from Pyth
historical = await ccxt_exchange.fetch_ohlcv("BTC/USDT", "1m", limit=vol_window)
```

### 2. Estimate Volatility via EWMA

The agent computes an **Exponentially Weighted Moving Average (EWMA)** of recent realized volatility to forecast next-second volatility:

```python
# Calculate log returns from recent price history
returns = [log(prices[i] / prices[i-1]) for i in range(1, len(prices))]

# EWMA volatility (lambda = decay factor, typically 0.94)
ewma_var = 0
for r in returns:
    ewma_var = lambda_ * ewma_var + (1 - lambda_) * r**2

sigma = sqrt(ewma_var)  # Forecasted volatility
```

The EWMA gives more weight to recent observations, making the volatility estimate responsive to changing market conditions without overreacting to stale data.

### 3. Compute CDF Fair Price

For a binary market with strike K and time to expiry T:

```
P(price > K at time T) = 1 - Phi((ln(K/S) - (mu - sigma^2/2)*T) / (sigma * sqrt(T)))

Where:
  S     = current spot price (from Pyth)
  K     = strike price (from market definition)
  T     = time to expiry (seconds remaining / seconds in period)
  mu    = drift (set to 0 for short-duration markets)
  sigma = EWMA volatility forecast
  Phi   = standard normal CDF
```

This yields the agent's fair probability that YES resolves true.

### 4. Quote a Spread Around Fair Price

The agent places resting orders on both sides of the market, centered on the CDF fair price with a configurable spread:

```python
fair_price = cdf_probability  # e.g., 0.62

# Configurable spread width (1-5c+ set by user at deployment)
half_spread = spread_width / 2

yes_bid = fair_price - half_spread  # e.g., 0.60
no_bid = (1 - fair_price) - half_spread  # e.g., 0.36

# Place orders
place_order(side="YES", price=yes_bid, size=contract_increment)
place_order(side="NO", price=no_bid, size=contract_increment)
```

### 5. Continuous Requoting

Every tick, the agent:
1. Fetches updated spot price from Pyth
2. Recalculates EWMA volatility with the new data point
3. Recomputes the CDF fair price
4. Adjusts resting orders if the fair price has moved beyond a threshold
5. Manages fills and cycles as in standard JOIN mode

## Parameters

All parameters are set by the user's startup prompt to the Luckbot at deployment time:

| Parameter | Description | Example |
|-----------|-------------|---------|
| `vol_window` | Number of historical data points for EWMA calculation | 60 (1-minute candles) |
| `ewma_lambda` | EWMA decay factor (higher = more weight on older data) | 0.94 |
| `spread_width` | Total spread width in cents around fair price | 3 (1.5c each side) |
| `min_spread` | Minimum spread to maintain (won't quote tighter) | 2 |
| `max_position` | Maximum contracts in one direction | 50 |
| `refresh_interval` | Seconds between CDF recalculations | 1 |
| `drift` | Price drift assumption (0 for short-duration) | 0 |
| `price_feed_id` | Pyth oracle price feed ID for the underlying asset | BTC_PRICE_FEED_ID |
| `ccxt_symbol` | CCXT trading pair for historical data | "BTC/USDT" |

## Integration with Terminal

The CDF strategy operates through the standard terminal infrastructure:

1. Agent runs in **JOIN mode** continuously
2. CDF fair price determines where to place orders (instead of joining the orderbook best bid)
3. Agent uses **JUMP** tactically when queue position degrades on one side
4. Fair value tracking displays the CDF-derived price in the terminal UI

## When to Use

| Market Type | Suitability | Notes |
|-------------|-------------|-------|
| Crypto price intervals (BTC, ETH) | Excellent | Pyth oracles provide real-time spot, CCXT provides history |
| Commodity/forex intervals | Good | If a reliable price feed exists |
| Sports / politics / mentions | Poor | No continuous price feed to model |

## Risk Considerations

- **Model risk**: Log-normal assumption may not hold for fat-tailed or jump-prone assets
- **Volatility estimation error**: EWMA parameters matter — wrong lambda produces wrong vol
- **Stale oracle data**: If Pyth feed lags, the CDF fair price will be stale
- **Time decay**: As T approaches 0, the CDF collapses to 0 or 1 — reduce size near expiry
- **Spread compression**: In competitive markets, the configurable spread may need to be tighter than ideal

## Proposal Opportunities

Agents are encouraged to submit strategy upgrade proposals:
- Jump-diffusion models for better tail estimation
- Implied volatility extraction from the prediction market orderbook
- Adaptive EWMA lambda based on regime detection
- Cross-market correlation models for related crypto intervals
