# Infrastructure: The LuckySt Trading Terminal

## Architecture Overview

```
┌─────────────────────────────────────────────────┐
│                  LuckySt Agent                   │
│               (Claude / Luckbot)                 │
│                                                  │
│  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │ Strategy │  │   Data   │  │  Risk Mgmt   │   │
│  │ Engine   │  │  Feeds   │  │              │   │
│  └────┬─────┘  └────┬─────┘  └──────┬───────┘   │
│       └──────────────┼───────────────┘           │
│                      │                           │
│              Redis Commands                      │
└──────────────────────┼───────────────────────────┘
                       │
                       ▼
┌──────────────────────────────────────────────────┐
│              LuckySt Terminal                      │
│                                                   │
│  ┌──────────┐  ┌──────────┐  ┌──────────────┐    │
│  │  FastAPI  │  │  Celery  │  │    Redis     │    │
│  │  Server   │  │  Worker  │  │   Commands   │    │
│  └────┬──────┘  └────┬─────┘  └──────┬───────┘    │
│       │              │               │             │
│       │         ┌────┴────┐          │             │
│       │         │ Trading │◄─────────┘             │
│       │         │ Instance│                        │
│       │         │(auto1.py)                        │
│       │         └────┬────┘                        │
│       │              │                             │
│       │       ┌──────┴──────┐                      │
│       │       │             │                      │
│       │  ┌────┴───┐  ┌─────┴────┐                 │
│       │  │ Kalshi │  │Limitless │                  │
│       │  │  API   │  │   API    │                  │
│       │  └────────┘  └──────────┘                  │
└───────────────────────────────────────────────────┘
```

## Component Breakdown

### 1. FastAPI Server (`backend/start.py`)
- Serves the web dashboard and REST API
- Handles user authentication and authorization
- Routes control commands to trading instances
- Provides WebSocket connections for real-time status updates to the frontend dashboard

### 2. Celery Workers (`backend/app/tasks/`)
- Execute trading instances as background tasks
- Each trading instance runs in its own Celery worker process
- Workers are managed by Redis as the message broker

### 3. Redis (Command Bus + Cache)
- **Command queue**: `trading:instance:{id}:command` - agents push commands here
- **Status cache**: `trading:instance:{id}:status` - terminal publishes status here
- **Credential store**: `user:{id}:credentials` - encrypted API keys (4hr TTL)
- **State store**: `trading:instance:{id}:state` - current trading state

### 4. Trading Instance (`auto1.py` / `auto2.py`)
- The core trading loop that runs every ~1 second
- Handles all exchange communication (order placement, cancellation)
- Processes Redis commands from agents
- Publishes status updates

### 5. PostgreSQL (Persistence)
- Trading instance records (config, status, P&L)
- User accounts and permissions
- Historical data

## Trading Instance Lifecycle

```
PENDING → RUNNING → PAUSED → RUNNING → STOPPED → DEAD
                 ↗                  ↗
           (single_fire)     (force_stop)
```

1. **PENDING**: Instance created, waiting for Celery worker
2. **RUNNING**: Actively trading - placing/updating orders every tick
3. **PAUSED**: Orders maintained but no new cycles started
4. **STOPPED**: Current cycle completed, orders cancelled
5. **DEAD**: Instance terminated, removed from dashboard

## The Trading Loop (1-second tick)

Every tick, the trading instance:

```python
while running and active:
    # 1. Check for agent commands via Redis
    process_redis_commands_async()

    # 2. Fetch fresh market data (5 parallel API calls)
    refresh_market_data_async()

    # 3. Check if any orders filled
    check_fills()

    # 4. Decision logic
    if stopping:
        wait_for_cycle_completion()
    elif paused:
        update_orders()  # Keep orders fresh even when paused
    elif both_filled:
        start_new_cycle()  # Reset and place new orders
    else:
        update_orders()  # Adjust prices to stay competitive

    # 5. Publish status
    print_status()

    # 6. Sleep until next tick
    await asyncio.sleep(1)
```

## Deploying a Trading Instance

Via the REST API:

```
POST /api/terminal/deploy
{
  "kalshi_api_key": "...",
  "rsa_key_path": "-----BEGIN PRIVATE KEY-----...",
  "markets": ["KXBTC-26MAR01-T100000"],
  "num_markets": 1,
  "mode": "auto",
  "contract_increment": 3,
  "both_side": true,
  ...
}
```

The service layer (`service.py`):
1. Encrypts and stores credentials in Redis
2. Creates a `TradingInstance` record in PostgreSQL
3. Dispatches a Celery task to start the trading loop
4. Returns the instance ID

## Error Handling

- API errors return empty dicts (non-blocking)
- Session timeout: 1 second per request
- If order placement fails, the cycle retries next tick
- If positions become imbalanced, automatic rebalancing kicks in
- Force stop cancels all orders immediately without waiting for cycle completion
