---
# System prepended metadata

title: 'Prep Trading: Hyperliquid Feature Parity Plan'

---

# Prep Trading: Hyperliquid Feature Parity Plan

> Feature parity with the Hyperliquid **website trading UI** for both spot and perpetual trading.
> This does not include platform features like vaults, sub-accounts, builder codes, or referrals.

---

## Current State

### What Works Today

| Feature | Spot | Perps |
|---------|------|-------|
| Market orders | Yes | Yes |
| Limit orders | **No** (UI exists but disabled + backend has no limit logic) | **No** (UI exists but disabled) |
| Position open/close | - | Yes |
| Position merge (same direction) | - | Yes |
| Position reduce (partial close via opposite direction) | - | Yes |
| Position flip (close + reverse via opposite direction) | - | Yes |
| Leverage adjustment | - | Yes |
| Real-time orderbook (WebSocket from Hyperliquid) | Yes | Yes |
| Real-time charts (WebSocket candles from Hyperliquid) | Yes | Yes |
| Balance tracking across buckets (wallet/spot/perps) | Yes | Yes |
| Fund transfers between buckets | Yes | Yes |
| KPI checks (daily loss, total drawdown, profit target) | Yes | Yes |
| Funding rate display (from Hyperliquid WebSocket) | - | Yes (display only) |
| Liquidation price calculation | - | Yes (Hyperliquid formula) |
| Funding payment logic (`ProcessFundingPayment`) | - | Yes (method exists, never called automatically) |
| Liquidation logic (`LiquidatePosition`) | - | Yes (method exists, never called automatically) |

### What Does NOT Work

- **No real-time price monitoring** -- prices are fetched on-demand when a trade happens (with 5-10s cache). No background process watches prices.
- **No automatic funding payments** -- the `ProcessFundingPayment` method exists but nothing calls it on a schedule. Users with open positions never pay or receive funding.
- **No automatic liquidation** -- positions can blow past liquidation price with no consequence until the user tries to trade again.
- **No automatic KPI enforcement** -- if a user holds spot tokens or open perp positions and prices move against them between trades, nobody checks. The account can silently breach limits.
- **Spot limit orders are completely non-functional** -- the submit button is hardcoded disabled when limit is selected, the API doesn't accept a price parameter, and the backend has no concept of a resting order.
- **Perp limit orders are completely non-functional** -- same situation: UI disabled, no backend support.
- **No conditional orders** -- no stop loss, stop limit, take profit, or any trigger-based orders.
- **No cross margin** -- only isolated margin is implemented. Cross margin is the default on Hyperliquid.
- **No order cancellation** for spot.
- **Frozen users cannot close positions** -- if a user hits the daily loss limit and gets frozen mid-day with open perp positions, they cannot close them to stop further bleeding.

---

## KPI Rules (for reference)

All three KPI checks use **initial balance** as the denominator (FTMO model). The daily loss limit is a fixed dollar amount based on the initial account size, not a percentage of current equity.

| Rule | Formula | Trigger | Result | Reversible? |
|------|---------|---------|--------|-------------|
| **Total Drawdown** | `(initialBalance - currentBalance) / initialBalance > TotalLossLimitPct` | Every trade | **FAILED** | No -- evaluation is over |
| **Daily Loss** | `(dailyStartBalance - currentBalance) / initialBalance > DailyLossLimitPct` | Every trade | **FROZEN** | Yes -- unfreezes at midnight UTC if total drawdown still within limit |
| **Profit Target** | `(currentBalance - initialBalance) / initialBalance >= ProfitTargetPct` | Every trade | **PASSED** | No -- evaluation complete, no more trading |
| **Expiry** | `now > evaluation_expires_at` | Hourly background job | **EXPIRED** | No |
| **Midnight Unfreeze** | For each FROZEN account: if total drawdown within limit | Midnight UTC | **ACTIVE** | - |
| **Midnight Fail** | For each FROZEN account: if total drawdown exceeded | Midnight UTC | **FAILED** | - |

**`currentBalance` includes:** all USDC across all buckets + spot token holdings at live market price + open perp positions (margin + unrealized PnL, capped at 0 per position for isolated margin).

**KPI is checked before:** every spot order, every perp open, every perp close, every perp merge, every perp reduce, every funding payment (if user is paying).

**KPI is NOT checked:** during fund transfers between buckets, during leverage changes, or between trades (no background monitoring).

---

## Implementation Plan

### Phase 1: Design Decision

| # | Item | Description |
|---|------|-------------|
| 1 | **Frozen account position handling** | When a user is frozen (hit daily loss limit) and has open perp positions that are still bleeding, what should happen? Three options: **(A)** Auto-close all open positions at the moment of freezing. **(B)** Allow the user to close positions while frozen (but not open new ones). **(C)** Keep current behavior -- strict freeze, user is locked out until midnight. This must be decided before any other work because it affects the KPI checker, position manager, and the real-time enforcement loop. |

---

### Phase 2: Real-Time Price Stream

This is the **foundation** for Phases 3, 4, and 5. Without it, nothing else works.

| # | Item | Description |
|---|------|-------------|
| 2 | **Background price ticker** | New goroutine in `main.go` that maintains a persistent connection to Hyperliquid (WebSocket preferred, polling every 3-5 seconds as fallback). Keeps an in-memory cache of current mark prices for every asset that any user holds a position or token balance in. This cache is consumed by the funding, liquidation, and KPI enforcement jobs in Phase 3. |

**Files affected:** `cmd/main.go`, new `internal/services/price_stream.go`

---

### Phase 3: Automated Enforcement

These three background jobs all consume the price cache from Phase 2.

| # | Item | Description |
|---|------|-------------|
| 3 | **Automatic funding payments** | New hourly ticker in `main.go` that runs on the same schedule as Hyperliquid (every hour, 1/8 of the 8-hour rate). For each open perp position: fetch the current funding rate from Hyperliquid for that asset, fetch the oracle price, and call the existing `ProcessFundingPayment` method. The method already handles the math, KPI check, Blnk debit/credit, and record creation -- it just needs to be called. |
| 4 | **Automatic liquidation monitoring** | New ticker that runs every 5-10 seconds. For each open perp position: get the current mark price from the cache, compare against the position's liquidation price. If breached (LONG: mark <= liqPrice, SHORT: mark >= liqPrice), call the existing `LiquidatePosition` method. The method already handles PnL calculation, Blnk operations, and status updates. |
| 5 | **Automatic KPI enforcement** | New ticker that runs every 30-60 seconds. For each user with open perp positions or non-USDC spot holdings: call `CalculateTotalUSD` (which uses the price cache), then call `ValidateKPILimits`. If the user breaches daily or total limits, their account is frozen/failed even if they haven't tried to trade. This closes the gap where accounts can silently blow through limits between trades. |

**Files affected:** `cmd/main.go`, `internal/services/kpi_checker.go`, new `internal/services/funding_collector.go`, new `internal/services/liquidation_monitor.go`

---

### Phase 4: Limit Orders (Perps)

| # | Item | Description |
|---|------|-------------|
| 6 | **Resting order model + table** | New `pending_orders` database table with fields: `id`, `user_id`, `evaluation_id`, `symbol`, `side` (LONG/SHORT), `size`, `limit_price`, `order_type` (LIMIT), `tif` (GTC/IOC/ALO), `status` (PENDING/FILLED/CANCELLED), `created_at`, `filled_at`. New model in `internal/models/`. New repository in `internal/repository/`. |
| 7 | **Limit order backend** | Modify `OpenPosition` (or create a new `PlaceOrder` RPC) to accept an optional `limit_price`. If the current mark price is at or better than the limit price, execute immediately (existing flow). If not, store as a resting order in the `pending_orders` table. A background job (tied to the price stream from Phase 2) checks resting orders on every price tick and fills them when the price crosses the limit. On fill, call the existing position opening logic. |
| 8 | **GTC / IOC / ALO** | **GTC (Good Til Cancel):** default -- resting order stays until filled or manually cancelled. **IOC (Immediate or Cancel):** if the limit price is not immediately fillable, reject the order entirely (don't store it). **ALO (Add Liquidity Only / Post Only):** if the limit price WOULD immediately fill, reject it -- only allow orders that rest on the book. These are enforced at order placement time. |
| 9 | **Enable limit orders on frontend (perps)** | In `perp-order-ticket.tsx`: remove the `disabled` attribute from the Limit dropdown item, wire the limit price input and TIF selector to the API call. The UI already exists -- it just needs to be connected. |

**Files affected:** new migration, new `internal/models/pending_order.go`, new `internal/repository/pending_order_repository.go`, `internal/services/position_manager.go`, `internal/grpcserver/server.go`, proto definition, `perp-order-ticket.tsx`

---

### Phase 5: Conditional Orders

All conditional orders share a single engine. Building the engine once enables stop loss, stop limit, take profit, and TP/SL on positions.

| # | Item | Description |
|---|------|-------------|
| 10 | **Conditional order engine** | New `conditional_orders` database table: `id`, `user_id`, `position_id` (nullable -- for position-attached TP/SL), `symbol`, `trigger_price`, `trigger_direction` (ABOVE/BELOW), `order_type` (MARKET/LIMIT), `limit_price` (nullable), `side`, `size`, `reduce_only`, `status` (PENDING/TRIGGERED/CANCELLED), `created_at`, `triggered_at`. Background job checks mark price on every tick from the price stream. When mark price crosses the trigger: if order_type is MARKET, execute immediately via existing logic; if LIMIT, create a resting limit order (Phase 4). |
| 11 | **Stop Market / Stop Limit** | Stop Market: trigger_direction=ABOVE for shorts (stop out if price rises), BELOW for longs (stop out if price falls). On trigger, execute a market order to close/reduce the position. Stop Limit: same trigger logic but places a limit order instead of market, giving slippage control. |
| 12 | **Take Profit Market / TP Limit** | Same engine as stops but opposite trigger direction. Take Profit for longs: trigger_direction=ABOVE (take profit when price rises). For shorts: trigger_direction=BELOW. Market variant executes immediately; Limit variant places a resting limit order. |
| 13 | **TP/SL on positions** | From the positions table in the UI, user can attach TP and SL to an open position. Creates two conditional orders linked to the position via `position_id`. **OCO behavior:** when one triggers and fills, automatically cancel the other. When the position is manually closed, cancel both. |
| 14 | **Reduce Only** | Add a `reduce_only` boolean to order placement. When true: clamp the order size to the current open position size (can't flip), reject if no open position exists. This applies to market orders, limit orders, and conditional orders. |
| 15 | **Enable on frontend** | In `perp-order-ticket.tsx`: remove `disabled` from the TP/SL checkbox and its price inputs, remove `disabled` from the Reduce Only checkbox. Wire all fields to the API. The UI, state management, and price calculation logic already exist in the component -- they just need to send the data. |

**Files affected:** new migration, new `internal/models/conditional_order.go`, new `internal/repository/conditional_order_repository.go`, new `internal/services/conditional_order_engine.go`, `internal/grpcserver/server.go`, proto definition, `perp-order-ticket.tsx`, `perp-summary.tsx` (position row TP/SL controls)

---

### Phase 6: Cross Margin

| # | Item | Description |
|---|------|-------------|
| 16 | **Cross margin mode** | Cross margin is the **default** on Hyperliquid. In cross margin, all positions share a single collateral pool. Unrealized gains on one position become available margin for others. Liquidation is checked at the **account level**, not per-position. A user is liquidated when total account equity drops below total maintenance margin across all positions. This is a major refactor of `position_manager.go`: margin is no longer locked per-position, liquidation price depends on the entire portfolio, and adding/closing one position changes the liquidation price of all others. The `margin_calculator.go` needs new formulas for cross-margin liquidation. The position model needs a `margin_mode` field (CROSS/ISOLATED). |
| 17 | **Margin mode toggle on frontend** | In `perp-order-ticket.tsx`: enable the Isolated/Cross toggle button (currently frozen on Isolated). Wire to a new `SetMarginMode` RPC. Display correct liquidation prices based on mode. |

**Files affected:** `internal/services/position_manager.go`, `internal/services/margin_calculator.go`, `internal/models/position.go`, new `internal/services/cross_margin_calculator.go`, `internal/grpcserver/server.go`, proto definition, `perp-order-ticket.tsx`, `perp-summary.tsx`

---

### Phase 7: Advanced Orders

| # | Item | Description |
|---|------|-------------|
| 18 | **Scale orders** | User specifies: total size, direction, price range (start price to end price), number of sub-orders, and skew/bias (0 = weighted toward low end, 1 = weighted toward high end). Backend generates N limit orders distributed across the price range according to the skew and places them all as resting orders (Phase 4). Frontend: new Scale order form in the order type dropdown. Depends on limit orders (Phase 4). |
| 19 | **TWAP orders** | Time-Weighted Average Price orders. User specifies: total size, direction, and duration (1-1440 minutes). Backend creates a TWAP parent record and a background worker that executes sub-orders every 30 seconds at market price. Each sub-order has max 3% slippage. Each sub-order must meet $10 minimum. New `twap_orders` table for tracking parent state and child order progress. Frontend: new TWAP order form in the order type dropdown. |

**Files affected:** new migration, new `internal/models/twap_order.go`, new `internal/services/twap_executor.go`, new `internal/services/scale_order_service.go`, `internal/grpcserver/server.go`, proto definition, `perp-order-ticket.tsx`

---

### Phase 8: Spot Gaps

| # | Item | Description |
|---|------|-------------|
| 20 | **Spot limit orders** | Backend: add an optional `price` parameter to the `CreateOrder` RPC. If provided, treat as a limit order -- check if immediately fillable, if not store as a resting order in the same `pending_orders` table from Phase 4. Match when price crosses the limit. Frontend: in `spot-order-ticket.tsx`, remove the `orderType === "limit"` condition from the submit button's disabled prop (line 391), and pass the limit price and TIF to the `createPrepOrder` API call (currently the price is calculated but never sent -- lines 133-147). |
| 21 | **Spot order cancellation** | Backend: new `CancelOrder` RPC that sets a pending order's status to CANCELLED. Frontend: add a cancel button on each pending order row in the spot summary's Orders tab. |
| 22 | **Spot stop/TP orders** | Use the same conditional order engine from Phase 5. Allow spot users to place stop and take profit orders on their token holdings. Trigger on mark price, execute as market or limit order on trigger. |

**Files affected:** `internal/grpcserver/server.go`, `internal/services/order_executor.go`, proto definition, `spot-order-ticket.tsx`, `spot-summary.tsx`

---

### Phase 9: Polish

| # | Item | Description |
|---|------|-------------|
| 23 | **Add/remove isolated margin** | New `UpdateIsolatedMargin` RPC: user specifies a position ID and an amount (positive to add margin, negative to remove). Adding margin: transfer USDC from perps bucket into the position's margin, recalculate liquidation price (moves it further away). Removing margin: transfer margin back to perps USDC bucket, recalculate liquidation price (moves it closer), reject if new liquidation price would be immediately breached. Frontend: margin adjustment controls on the position row in perp-summary. |

**Files affected:** `internal/services/position_manager.go`, `internal/services/margin_calculator.go`, `internal/grpcserver/server.go`, proto definition, `perp-summary.tsx`

---

## Dependency Graph

```
Phase 1 (Design Decision)
    |
Phase 2 (Price Stream) -------- foundation for everything below
    |
    +--- Phase 3 (Funding + Liquidation + KPI enforcement)
    |
    +--- Phase 4 (Limit Orders)
    |        |
    |        +--- Phase 5 (Conditional Orders: Stop, TP, TP/SL, Reduce Only)
    |        |        |
    |        |        +--- Phase 8.22 (Spot Stop/TP -- reuses conditional engine)
    |        |
    |        +--- Phase 7 (Scale + TWAP -- depends on limit orders)
    |        |
    |        +--- Phase 8.20 (Spot Limit Orders -- reuses pending_orders table)
    |
    +--- Phase 6 (Cross Margin -- independent of order types)
    |
    +--- Phase 8.21 (Spot Order Cancellation -- independent)
    |
    +--- Phase 9 (Add/Remove Margin -- independent)
```

---

## Implementation Recommendations

### Use: [sonirico/go-hyperliquid](https://github.com/sonirico/go-hyperliquid) for Phase 2 (Price Stream)

The `prep-trading-service` currently talks to Hyperliquid via **REST polling only** (`internal/services/hyperliquid_client.go`). The real-time price stream in Phase 2 requires WebSocket. Building a production-quality WebSocket client with reconnection, subscription management, and message parsing from scratch is 500+ lines of error-prone code.

This SDK (92 stars, MIT license, actively maintained) provides out of the box:
- **`allMids` subscription** -- streaming mark prices for all assets (powers Phase 2 price cache)
- **`l2Book` subscription** -- streaming orderbook updates (needed for limit order fill detection in Phase 4)
- **Funding rate data** -- read Hyperliquid's published rate directly (powers Phase 3 funding payments)
- **Automatic reconnection** -- handles dropped WebSocket connections

The existing `hyperliquid_client.go` (REST read-only) and `apps/hyperliquid-service/` (REST write-only for real order execution) remain unchanged. The SDK adds the WebSocket streaming layer only.

```
go get github.com/sonirico/go-hyperliquid
```

### Do NOT build: Funding rate calculation

Hyperliquid **publishes** the current funding rate. The frontend already reads it via WebSocket (`useActiveAssetCtxSubscription` -> `funding` field). The backend does not need to compute premium index sampling, 8-hour averaging, or any of the funding rate math.

Phase 3 item #3 (automatic funding payments) simplifies to:
1. Read the published funding rate from the `allMids` WebSocket stream (or a REST call to HL's `/info` endpoint)
2. Read the oracle price from the same source
3. Call the existing `ProcessFundingPayment` method which already handles: `payment = size x oraclePrice x fundingRate`, directional logic, KPI check, Blnk debit/credit, and record creation

### Do NOT build: Mark price computation

Hyperliquid publishes mark prices. The backend reads them from the `allMids` stream and uses them for liquidation checks and KPI balance calculations. No need to combine oracle prices with CEX median prices -- Hyperliquid does that and publishes the result.

### Build yourself: Everything else

Limit orders, conditional orders, TWAP, scale orders, cross margin, and the enforcement loops are all tightly coupled to the existing models (Blnk accounting, position model, KPI checker, evaluation system). Each is 100-300 lines of Go. No external library matches this domain. Reference [i25959341/orderbook](https://github.com/i25959341/orderbook) (538 stars, MIT) for orderbook data structure patterns when implementing the resting order logic.

---

## Out of Scope

These exist on Hyperliquid but are **not part of the trading UI** or are not relevant to the paper trading evaluation:

- Vaults (fund management pools)
- Sub-accounts (API/power user feature)
- Builder codes (API/bot fee splitting)
- Referral system (marketing feature)
- Portfolio margin (still pre-alpha on Hyperliquid)
- Volume-based fee tiers (nice to have, not core trading)
- Dead man's switch (API safety feature)
- Auto-deleverage / ADL (last-resort mechanism -- for paper trading, simple liquidation at liq price is sufficient)
- Insurance fund / backstop (for paper trading, liquidation at liq price is sufficient)
- Margin tiers (tiered max leverage based on position size -- only matters for very large positions)
- Staking fee discounts (HYPE-specific)
