### Hyperliquid Bot System Design

## Executive Summary

This design specifies a production-grade, single-process Rust trading system for Hyperliquid focused on short-to-medium intraday swing opportunities triggered by rapid bursts of volume and liquidity. The recommended design center is a deterministic event engine driven primarily by `trades` and `bbo`, with `activeAssetCtx` and user/account streams as contextual and authoritative state inputs, and optional shallow `l2Book` features only if staging proves incremental value.

The alpha architecture should not be a generic indicator bot. It should be a microstructure-gated two-branch strategy: **breakout continuation** when one-sided aggressive flow is persistent and price acceptance holds, and **sweep reversion** when a liquidity-taking burst appears exhausted and the swept level is rapidly reclaimed. Traditional EMA/ATR/VWAP/RSI/HHV/LLV features remain useful as normalization, regime, and exit controls, but should not be primary event triggers for this use case.

The survival objective dominates the design: all new risk must stop on stale market state, stale user state, reconnect uncertainty, queue saturation, signer/nonce anomalies, or unresolved execution ambiguity. Re-entry to trading must occur only after authoritative reconciliation by snapshots and queries confirms coherent orders, fills, and positions.

## System Goals / Non-Goals

### Goals
- Single-process Rust binary with strict hot-path/cold-path separation.
- Deterministic, replayable strategy/risk hot loop over normalized internal events.
- Current-data-only intraday alpha using rapid volume/liquidity shock detection, continuation confirmation, and failed-sweep reversion.
- Authoritative reconnect recovery using snapshots plus `/info` backfill and cloid-based ambiguity resolution.
- Bounded-memory, bounded-queue, low-allocation runtime with reserved capacity for risk-off traffic.

### Non-Goals
- No full deep-book reconstruction engine in MVP. Hyperliquid public `l2Book` is snapshot-based and `/info` returns at most 20 levels per side, so full diff-sequenced L2/L3 logic is not the default baseline.
- No multi-process shared signer topology. One API wallet per trading process is the safe design.
- No heavy online model fitting, clustering, or adaptive meta-labeling in the hot path. Those belong in replay research and cold-path calibration.

## Architecture

### Process Model
Run one process with four temperature zones:
1. **Hot path**: deterministic event consumer thread for state mutation, feature updates, signal branching, risk admission, and compact intent emission. 
2. **Warm path**: network I/O runtime for WebSocket read/write, JSON decode/encode, signing, nonce allocation, batching, and heartbeat timers. 
3. **Cold path**: reconciliation queries, journaling flush, metrics export, admin control plane, configuration reload, and diagnostics.
4. **Operator safety plane**: manual mode toggles, SAFE/LOCKED unlock policy, session arming/disarming, and emergency flatten authorization.

### Task Model

| Task | Thread / runtime | Responsibility | Hot? |
| --- | --- | --- | --- |
| MD socket reader | Tokio | Read WS frames, decode JSON, timestamp receipt, push raw msgs | No |
| MD normalizer | Tokio or dedicated warm thread | Map strings to ids, parse decimals to fixed-point, dedupe trades | No |
| Strategy/risk loop | Dedicated thread | Apply events in total local order, update state, emit intents | Yes |
| Execution gateway | Tokio + warm worker | Batch intents, allocate nonces, sign, send post requests, track req ids | No |
| Reconciliation supervisor | Tokio/cold | Reconnect, resubscribe, query snapshots, resolve ambiguous orders | No |
| Observability | Cold workers | Metrics export, log writing, journal flush, admin API | No |

### Hot Path Rules
**Must be in hot path:** normalized event application, rolling feature updates, state-machine transitions, risk checks, signal branching, order intent creation, timer-wheel consumption.

**Must not be in hot path:** JSON parsing, websocket framing, signature generation, HTTP fallbacks, file I/O, formatted logging, dynamic plugin dispatch, heap-growing string-keyed maps, model fitting, and exchange query retries.

## Crate / Module Layout

| Crate | Purpose | Hotness | Key modules |
| --- | --- | --- | --- |
| `bot-types` | Core ids, enums, fixed-point wrappers, event structs | Hot | `ids`, `fp`, `event`, `state` |
| `bot-math` | Streaming stats, MAD, ring buffers, rolling extrema | Hot | `rolling_sum`, `robust_scale`, `vpin`, `deque_extrema` |
| `bot-state` | Per-symbol and portfolio state stores | Hot | `symbol_state`, `order_state`, `position_state`, `account_state` |
| `bot-strategy` | Shock detectors, regime filters, continuation/reversion modules | Hot | `detectors`, `regime`, `continuation`, `sweep_reversion`, `lifecycle` |
| `bot-risk` | Invariants, limits, kill-switches, state transitions | Hot | `pretrade`, `posttrade`, `state_gate`, `kill_switch` |
| `bot-hl-md` | Hyperliquid market-data adapters | Warm | `ws_client`, `parser`, `normalize`, `subscriptions` |
| `bot-hl-exec` | Signing, nonces, batching, outbound envelopes, response correlation | Warm | `nonce`, `sign`, `post`, `batcher`, `shadow_orders` |
| `bot-runtime` | Bootstrap, queue wiring, timers, mode control | Warm | `bootstrap`, `scheduler`, `heartbeat`, `recovery` |
| `bot-obs` | Journal, tracing, metrics, admin API | Cold | `journal`, `metrics`, `logging`, `admin` |
| `bot-config` | Static config, symbol metadata, limits | Cold | `defaults`, `schema`, `validation` |
| `bot-replay` | Event-driven backtest/replay harness | Cold | `loader`, `exchange_sim`, `latency`, `slippage`, `faults` |
| `bot-main` | Thin binary entrypoint | Mixed | `main.rs` |
