# Exchange: Kalshi

## Overview

Kalshi is a CFTC-regulated centralized prediction market exchange based in the United States. It is the primary exchange for the LuckySt terminal and the most mature integration in the system.

## Authentication

Kalshi uses RSA key-pair authentication with request signing:

1. **API Key**: A public identifier for your account (header: `KALSHI-ACCESS-KEY`)
2. **RSA Private Key**: Used to sign every request (RSA-PSS with SHA-256)
3. **Timestamp**: Millisecond-precision timestamp included in signature

### Request Signing Process

```
message = timestamp + HTTP_METHOD + "/trade-api/v2" + path (without query params)
signature = RSA-PSS-Sign(message, private_key, SHA256)
encoded = base64(signature)
```

The signing implementation lives in: `backend/app/modules/terminal/auto/kalshi_api.py` - `_sign_request()` method.

### Credential Management

Credentials are stored encrypted in Redis with 4-hour TTL:
- `backend/app/modules/terminal/auto/crypto.py` - Fernet encryption for session storage
- `backend/app/modules/terminal/auto/service.py` - `store_session_credentials()` / `get_session_credentials()`

**IMPORTANT**: Agents must NEVER log, expose, or transmit API keys or private keys in plaintext. All credential handling goes through the encrypted Redis session layer.

## API Base URL

```
Production: https://api.elections.kalshi.com/trade-api/v2
```

## Key Endpoints Used by Terminal

### Market Data
- `GET /markets/{ticker}/orderbook` - Get YES/NO orderbook
- `GET /markets/{ticker}` - Market metadata (close time, settlement)

### Portfolio
- `GET /portfolio/orders?ticker={ticker}&status=resting` - Our resting orders
- `GET /portfolio/positions?ticker={ticker}&count_filter=position` - Current positions
- `GET /portfolio/orders?status=resting` - All resting orders (for queue position)
- `GET /portfolio/fills?ticker={ticker}` - Recent fills

### Order Management
- `POST /portfolio/orders` - Place new order
- `DELETE /portfolio/orders/{order_id}` - Cancel order

## Market Structure

### Binary Markets
Each Kalshi market is a binary YES/NO contract:
- YES pays $1.00 if the event occurs
- NO pays $1.00 if the event does not occur
- YES price + NO price always equals approximately $1.00 (minus spread)

### Orderbook Format
```json
{
  "orderbook": {
    "yes": [[price_cents, size], [price_cents, size], ...],
    "no": [[price_cents, size], [price_cents, size], ...]
  }
}
```
Prices are in cents (1-99). The terminal converts to decimals internally.

### Market Tickers
Kalshi tickers follow patterns like:
- `KXBTC-26MAR01-T100000` (Crypto price markets)
- `KXLOLGAME-26FEB11LNGWE-LNG` (Event markets)

### Order Fields
```json
{
  "ticker": "KXBTC-26MAR01-T100000",
  "side": "yes",
  "action": "buy",
  "count": 3,
  "type": "limit",
  "client_order_id": "unique-id",
  "yes_price": 45
}
```

## Queue Position

Kalshi is a price-time priority orderbook. The terminal tracks queue position via the `queue_position` field on resting orders. This is critical for JOIN mode - being early in the queue means faster fills.

## Rate Limits

The terminal implements rate limiting on the FastAPI side:
- Deploy: 5/min
- Control actions: 20/min
- Mode changes: 30/min
- Bump/fair value: 30/min

Agents should respect these limits and not spam commands.

## Concurrent Data Fetching

The terminal fetches 5 endpoints in parallel every tick:
1. Orderbook
2. Resting orders (for our market)
3. Positions
4. All resting orders (for queue position)
5. Fills

This is handled by `auto1.py` - `refresh_market_data_async()` using `asyncio.gather()`.

## Settlement

Markets settle to YES ($1.00) or NO ($1.00) based on the outcome. Unsettled positions are held until market close. Agents should be aware of settlement timing and reduce exposure near market close.
