# User data WebSocket — `/v1/ws`

Topic-based stream of account state, order lifecycle, fills, and liquidation
events. One connection can hold several subscriptions.

Production URL: `wss://production.mosaiq.0d.finance/v1/ws`.

The socket is not authenticated. Name the account with `?user=<evm_address>`
on the URL or `user` in each subscription. A subscription's `user` wins over
the URL. Always set one of them: without both, the server reads a default
account that is not yours. A malformed `?user=` fails the upgrade with HTTP `400`,
`invalid_request` and the detail `invalid_query`. A malformed `user` in a
subscription gets an `invalid_request` error message.

Add `includeVenueCloid=true` to the URL to get `venueCloid` on the
`orderUpdates` rows of the connection. Without it, rows leave `venueCloid` out.
A value that cannot be parsed fails the upgrade with HTTP `400 invalid_request`
and the detail `invalid_query`.

```ts
const url = new URL('/v1/ws', 'https://production.mosaiq.0d.finance')
url.protocol = 'wss:'
url.searchParams.set('user', '0x0000000000000000000000000000000000000001')
const ws = new WebSocket(url)
```

## Rate limits

Shared per client IP across `/v1/ws`, `/v1/market-data/ws`, and
`/v1/exchange/ws`:

| Limit | Value | Behavior |
| --- | --- | --- |
| Concurrent connections | `10` | Extra upgrades are rejected with HTTP `429`. |
| New connections | `30`/minute | Extra upgrades are rejected with HTTP `429`. |
| Incoming messages | `2000`/minute | Read sockets drop extra frames silently. The write socket closes. |

Budgets refill continuously. Prefer one connection with several subscriptions
and back off after a `429`. An over-budget Pong still answers the heartbeat.

Read the socket fast enough. Mosaiq closes a connection when the messages
waiting for it, the one being sent included, exceed 4 MiB, or when one message
waits more than 2 seconds. On `/v1/ws`, a message or frame from the client
larger than 1 MiB closes the connection.

## Heartbeats

Mosaiq sends a WebSocket Ping every 10 seconds on all three sockets and closes
the connection when no Pong with the matching payload arrives within 30
seconds. Most libraries answer automatically if you keep reading the socket.
Client Pings and application messages do not count as a Pong.

## Subscribe

```jsonc
{ "method": "subscribe", "subscription": { "type": "clearinghouseState", "user": "0x..." } }
{ "method": "subscribe", "subscription": { "type": "orderUpdates", "user": "0x..." } }
{ "method": "subscribe", "subscription": { "type": "userFills", "user": "0x..." } }
{ "method": "subscribe", "subscription": { "type": "userEvents", "user": "0x..." } }
```

There is no `unsubscribe`. A connection holds one subscription per topic.
Subscribing again to an active topic replaces its parameters and leaves the
other topics alone. `orderUpdates`, `userFills`, and `userEvents` then send a
new snapshot.

This socket rejects the market-data topics `bbo`, `l2Book`, and `trades`: use
[`/v1/market-data/ws`](/api/market-data-websocket). It takes
`{"type": "maintenance"}`: the announcements of a Mosaiq stop and of a venue
maintenance. Its messages are the same on every socket:
[Maintenance announcements](/api/exchange-websocket#maintenance-announcements).

When a topic fails on Mosaiq's side, Mosaiq closes the connection. It can send
an error message with `internal_error` first. Reconnect and subscribe again.

## Envelope

```ts
interface WebSocketMessage<T> {
  status: 'ok'
  topic: 'clearinghouseState' | 'orderUpdates' | 'userFills' | 'userEvents'
  data: T
  server_time_ms: number
}

interface WebSocketErrorMessage {
  status: 'error'
  data: {
    code: 'invalid_request' | 'internal_error'
    detail: 'websocket_error'
    msg: string
  }
  server_time_ms: number
}
```

Every error on this socket has the detail `websocket_error` and no `topic`.
Its `code` is `invalid_request` for a subscription message that you must fix,
and `internal_error` for a failure on Mosaiq's side. See
[Errors](/api/errors). A subscription message must be a JSON
object. A JSON array, an unknown `method`, or an unknown `type` gets
`invalid_request` and subscribes to nothing.

```json
{
  "data": {
    "code": "invalid_request",
    "detail": "websocket_error",
    "msg": "invalid websocket subscription json"
  },
  "server_time_ms": 1788646149474,
  "status": "error"
}
```

Route by `topic`. `server_time_ms` is when Mosaiq produced the message. It is
not a cursor. Topics are independent: there is no shared cursor, atomic
snapshot, or guaranteed ordering between them. `orderUpdates` follows the order
in which Mosaiq processes changes. Fills can arrive out of execution-time
order. A reconnect starts a new subscription with a new snapshot and does not
replay what was missed.

## `clearinghouseState`

One subscription emits four message types, distinguished by `data.type`. On
subscribe or reconnect, Mosaiq sends the latest `assetData`, `venueData`,
`marketData`, then `userData`, each with `data.messageType: "snapshot"`. The
four domains refresh independently, so these initial messages are not an
atomic snapshot.

After that, Mosaiq sends a chunk again only when its contents change, with
`data.messageType: "update"`. A message replaces the whole chunk named by
`data.type`, empty arrays and maps included. It is not a field-level patch. A
slow connection can skip intermediate values but always receives the latest
one. An unchanged chunk stays silent: these messages are not heartbeats.

Mosaiq checks `venueData`, `marketData`, and `userData` for changes every
100 ms, and `assetData` every second. These are not delivery intervals: the
data behind a chunk can change less often, and two messages can arrive back to
back. In `marketData`, oracle prices and funding rates are current at each
check, and the list of markets refreshes about once a second.

The optional `markets` field selects assets by name, across all venues. It
filters `marketCtxs` and `openInterestUsdc` from the first message onward.
`assetData`, `venueData`, and `userData` stay complete. A change outside the
selection sends no `marketData` message.

```json
{
  "method": "subscribe",
  "subscription": {
    "type": "clearinghouseState",
    "markets": ["WTI", "XAG"]
  }
}
```

Without `markets`, every market is selected. An empty list selects none. Use
the names of `assetData.universe[].name`. Mosaiq trims, uppercases, and
deduplicates them. An unknown name is accepted and starts to match when it
appears in `marketData`. An empty name gets `invalid_request`. Because the
chunks refresh independently, `marketData` can name a new asset before
`assetData` defines it. Subscribing again with a different list replaces the
selection and sends the four snapshots again. The same list does not restart
the subscription.

[`GET /v1/clearinghouseState`](/api/clearinghouse-state) returns the same four
payloads together under `data`, without `type` and `messageType`, and
describes every field. A `userData` message looks like this:

```json
{
  "status": "ok",
  "topic": "clearinghouseState",
  "data": {
    "messageType": "snapshot",
    "type": "userData",
    "user": "0x0000000000000000000000000000000000000001",
    "positions": [
      {
        "coin": "BTC",
        "venue": "hyperliquid",
        "entryPx": 64000.0,
        "szi": 0.5,
        "positionValue": 32500.0,
        "unrealizedPnl": 500.0,
        "unrealizedFunding": -1.25
      }
    ],
    "marginSummary": {
      "accountValue": 10500.0,
      "totalCashUsdc": 10000.0,
      "availableFunds": 8657.6,
      "excessLiquidity": 10093.75,
      "initialMarginUsed": 1842.4,
      "maintenanceMarginUsed": 406.25,
      "grossNotional": 32500.0,
      "cushion": 0.9613,
      "leverage": 3.095
    },
    "userCaps": {
      "scope": "owner",
      "tier": "beta",
      "openOrders": 0,
      "maxOpenOrders": 20,
      "maxSingleOrderNotionalUsdc": 50000.0,
      "openOrderNotionalUsdc": 0.0,
      "maxOpenOrderNotionalUsdc": 250000.0,
      "grossNotionalUsdc": 32500.0,
      "maxGrossNotionalUsdc": 500000.0,
      "initialMarginUsageRate": 0.1755,
      "maxInitialMarginUsageRate": 0.8,
      "maxAssetVenueNotionalUsdc": 100000.0,
      "assetVenueNotionals": [
        {
          "asset": "BTC",
          "venue": "hyperliquid",
          "notionalUsdc": 32500.0
        }
      ]
    },
    "withdrawableUsdc": "8657.6",
    "liquidation": null,
    "spotBalances": [
      {
        "coin": "HYPE",
        "venue": "hyperliquid",
        "total": "0.279804",
        "hold": "0",
        "sellable": "0.27"
      }
    ],
    "outcomeBalances": [
      {
        "a": "BTC-1D-261104-0600-GE76637-YES/USDC",
        "venue": "hyperliquid",
        "total": "24",
        "hold": "4",
        "sellable": "20",
        "midValueUsdc": "13.2",
        "expiryMs": 1794643200000
      }
    ],
    "tokenCashUsdc": "300",
    "tokenCashPendingUsdc": "0",
    "lastTokenCashTransfer": {
      "requestId": "01932a4e-8c00-7000-8000-000000000120",
      "direction": "toTokens",
      "amount": "120",
      "status": "failed",
      "cause": "tokenBuy",
      "reason": "venueRefused"
    },
    "tokenAccount": {
      "venue": "hyperliquid",
      "address": "0x00000000000000000000000000000000000000a1",
      "status": "closed",
      "reason": "venue_unreadable"
    }
  },
  "server_time_ms": 1788646149474
}
```

```ts
type ClearinghouseStateData = AssetData | VenueData | MarketData | UserData

type SnapshotMessage = ClearinghouseStateData & { messageType: 'snapshot' }
type UpdateMessage = ClearinghouseStateData & { messageType: 'update' }

interface AssetData {
  type: 'assetData'
  universe: Array<AssetDefinition>
}

interface VenueData {
  type: 'venueData'
  meta: ClearinghouseMeta
}

interface MarketData {
  type: 'marketData'
  marketCtxs: Array<MarketContext>
  openInterestUsdc: Record<string, string | null>
}

interface UserData {
  type: 'userData'
  user: string
  positions: Array<Position>
  marginSummary: MarginSummary
  userCaps: UserCaps
  withdrawableUsdc: string | null
  liquidation: Liquidation | null
  spotBalances?: Array<SpotBalance>
  tokenCashUsdc?: string
  tokenCashPendingUsdc?: string
  lastTokenCashTransfer?: TokenCashTransfer
  tokenAccount?: TokenAccount
  outcomeBalances?: Array<OutcomeBalance>
}

interface TokenCashTransfer {
  requestId: string
  direction: 'toTokens' | 'toCash'
  amount: string
  status: 'pending' | 'confirmed' | 'failed'
  cause: 'tokenBuy' | 'perpMargin' | 'withdrawal' | 'idle'
  reason?: 'venueRefused' | 'notSubmitted' | 'unknownOutcome'
}

interface TokenAccount {
  venue: string
  address: string
  status: 'open' | 'opening' | 'closed'
  reason?: string
}

interface OutcomeBalance {
  a: string
  venue: string
  total: string
  hold: string
  sellable: string
  midValueUsdc?: string
  expiryMs: number
}

interface Liquidation {
  id: string
  startedAtMs: number
  positions: Array<{ coin: string; venue: string }>
}

interface MarginSummary {
  accountValue: number
  totalCashUsdc: number
  availableFunds: number
  excessLiquidity: number
  initialMarginUsed: number
  maintenanceMarginUsed: number
  grossNotional: number
  cushion: number
  leverage: number
}

interface UserCaps {
  scope: 'owner'
  tier: string
  openOrders: number
  maxOpenOrders: number
  maxSingleOrderNotionalUsdc: number
  openOrderNotionalUsdc: number
  maxOpenOrderNotionalUsdc: number
  grossNotionalUsdc: number
  maxGrossNotionalUsdc: number
  initialMarginUsageRate: number
  maxInitialMarginUsageRate: number
  maxAssetVenueNotionalUsdc: number
  assetVenueNotionals: Array<{ asset: string; venue: string; notionalUsdc: number }>
}

interface Position {
  coin: string
  venue: string
  entryPx: number
  szi: number
  positionValue: number
  unrealizedPnl: number
  unrealizedFunding: number
}

interface SpotBalance {
  coin: string
  venue: string
  total: string
  hold: string
  sellable: string
}

interface AssetDefinition {
  name: string
  szDecimals: number
  maxLeverage: number
  marginTableId: number
  onlyIsolated?: boolean
  isDelisted?: boolean
  constraints?: MarketConstraints
  venues?: Array<UniverseVenue>
}

interface UniverseVenue {
  venue: string
  venueSymbol: string
  instrumentType: 'perp'
  status: 'active' | 'post_only' | 'reduce_only' | 'prelisted' | 'delisted' | 'inactive'
  constraints: MarketConstraints
  lifecycle?: UniverseLifecycle
}

interface UniverseLifecycle {
  state: 'trading' | 'reduce_only' | 'halted' | 'settling' | 'settled'
  listing: number
  settlementPx?: string
  settledAtMs?: number
}

interface MarketContext {
  name: string
  venue: string
  funding?: string
  oraclePx?: string
}

interface MarketConstraints {
  sizeDecimals: number
  sizeIncrement?: string
  priceDecimals?: number
  tickSize?: string
  minBaseAmount?: string
  minNotional?: string
  maxBaseAmount?: string
  maxMarketNotional?: string
  maxLimitNotional?: string
  maxPositionNotional?: string
  openInterestCap?: string
  maxOpenOrders?: number
  supportsReduceOnly?: boolean
  supportsPostOnly?: boolean
  requiresIsolatedMargin?: boolean
}

interface ClearinghouseMeta {
  venues: Array<{ venue: string; status: 'unknown' | 'online' | 'offline'; lastCheckedAtMs?: number; lastOkAtMs?: number; message?: string }>
  recovery?: Array<{ venue: string; phase: 'recovering' | 'active' | 'halted'; message?: string; haltCause?: string }>
}
```

[`GET /v1/clearinghouseState`](/api/clearinghouse-state) describes each field.
A liquidation that starts or ends sends `userData` again, even when no other
field changes. See [`userEvents`](#userevents).

## `orderUpdates`

Order status changes for the user. The first message after subscribe is a
`snapshot` of the 20 orders updated most recently, ended orders included,
ordered by `updatedAtMs` ascending. It is not the list of open orders: read
[`GET /v1/openOrders`](/api/open-orders) for that. A change made after you
subscribe arrives as an `update`, even when the snapshot already shows it.
Each `update` carries one order's current state. Replace the earlier row for
that `orderId`. Intermediate changes can be skipped while the snapshot loads.

```json
{
  "status": "ok",
  "topic": "orderUpdates",
  "data": {
    "user": "0x0000000000000000000000000000000000000001",
    "type": "update",
    "orderUpdates": [
      {
        "orderId": "0b0f9c0e-6d4e-4a1b-9f37-2c5d8e1a4b02",
        "cloid": "0x00000000000000000000000000000002",
        "a": "BTC",
        "venue": "hyperliquid",
        "b": "buy",
        "status": "open",
        "size": "1",
        "price": "64000",
        "filledSize": "0",
        "reconciliationPending": false,
        "createdAtMs": 1788646148000,
        "updatedAtMs": 1788646149400
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

```ts
interface OrderUpdates {
  user: string
  type: 'snapshot' | 'update'
  orderUpdates: Array<OrderUpdate>
}

interface OrderUpdate {
  orderId: string
  cloid: string
  venueCloid?: string
  a: string
  venue: string
  b: 'buy' | 'sell'
  status:
    | 'accepted'
    | 'open'
    | 'partially_filled'
    | 'filled'
    | 'cancelled'
    | 'failed'
    | 'not_on_book'
    | 'uncertain'
  size: string
  price?: string
  slippage?: string
  filledSize: string
  avgFillPrice?: string
  priorityFee?: { rateBps: string; chargedUsdc: string }
  reconciliationPending: boolean
  failure?: {
    code: OrderFailureCode
    detail: string
    reason: string
    rawCode?: string
    maybeSent?: true
    retryAfterMs?: number
  }
  cancelCause?: 'liquidation' | 'market_halt' | 'market_expired' | 'venue_reduce_only'
    | 'venue_contained'
  neverOnVenue?: true
  createdAtMs: number
  updatedAtMs: number
}

type OrderFailureCode =
  | 'temporarily_unavailable'
  | 'rate_limited'
  | 'invalid_request'
  | 'limit_reached'
  | 'trading_restricted'
  | 'duplicate_id'
  | 'order_not_found'
  | 'venue_rejected'
  | 'request_uncertain'
  | 'internal_error'
```

### Statuses

| `status` | Meaning |
| --- | --- |
| `accepted` | Mosaiq has the order, and its venue send is under way or acknowledged. It does not mean that the order rests. |
| `open` | Venue evidence shows the order resting. |
| `partially_filled` | The order rests, and part of it filled. |
| `filled` | The whole order filled. |
| `cancelled` | The venue cancelled the order. |
| `failed` | The order ended without success. `failure` says why. |
| `not_on_book` | The venue answered that the order no longer rests. Stop sending cancels for it. |
| `uncertain` | Mosaiq cannot assert the state yet. Wait, or reconcile through [`openOrders`](/api/open-orders) and [`userFills`](/api/user-fills). |

`filled`, `cancelled`, and `failed` are final. A recovery that finds a fill
late still sends another `update` for the same `orderId`, for example
`cancelled` with a larger `filledSize`.

* This stream carries every outcome of a place, modify, or cancel. The write's
  answer only says that Mosaiq launched the venue send. See
  [Follow each write on orderUpdates](/api/exchange#follow-each-write-on-orderupdates).
* An order whose venue gives no answer within 2 seconds of its send becomes
  `uncertain`, with `failure.code` `request_uncertain` and the detail
  `transport_unavailable`.
* A Hyperliquid place, modify, or cancel that never left Mosaiq is not
  `uncertain`. A place ends `failed`, a modify shows its `failure`, and a
  cancel leaves its order unchanged. The detail is `send_capacity` when
  Mosaiq's send capacity or its Hyperliquid request quota was full, or
  `venue_unavailable` when the venue connection closed before the send. Send
  the write again after a short delay.
* A step that changes no field of the row other than `updatedAtMs` sends no
  `update`, for example the venue's acknowledgement of an order that is
  already `accepted`. A modify that ends on a live order sends an `update` even
  when the row stays the same, for example a second refusal like the first.
* An order that stays live while 1,024 newer orders arrive on the same
  subscription can get one `update` that repeats its last row.
* After an internal error, Mosaiq can rebuild its order state from its
  database. The stream cannot carry those changes, so Mosaiq closes the
  connection. Reconnect and subscribe again: the new snapshot has the current
  rows.

### Cancels and modifies

* A cancel has no row of its own. Its order's rows tell how the order ended:
  `cancelled`, `filled`, or `failed`. The order becomes `cancelled` only once
  the venue confirms. The one exception is a placement that a cancel stopped
  before the venue held it, which carries `neverOnVenue`. No cancel outcome
  shows as `not_on_book`.
* A modify's outcome shows on its order's row: with the new price and size, or
  with the previous price and size and the modify's `failure`. When the modify
  reaches the venue after its order filled or was cancelled, the venue refuses
  it. Its `failure` then has `failure.code` `order_not_found`, the detail
  `order_not_found_for_cancel`, and `maybeSent` `true`. A modify that Mosaiq
  finds ended before the send gets the same code and detail on its answer. Do
  not send it again: the order is gone.

### Fields

* `size` is the current total size, the filled part included. A confirmed
  modify replaces it. After a Hyperliquid modify, it is `filledSize` plus the
  modify's `s`. Mosaiq also lowers it without a modify when a position decrease
  or a newer reduce-only order trims a reduce-only order, including an order that
  Mosaiq treats as reduce-only under `user_reduce_only`. A trim is final, even
  when the placement that caused it is refused before its venue send. On
  Lighter, `size` also falls without a fill when another of your orders crosses
  the order: Lighter's self-trade prevention removes the crossed size from both
  orders.
* `price` is present on limit orders, and `slippage` on market orders.
* `filledSize` and `avgFillPrice` are cumulative as of that update. The stream
  does not promise a message for every intermediate change.
* `updatedAtMs` never moves back. A fill that the venue timed before the
  order's last change keeps the `updatedAtMs` of that change.
* `reconciliationPending` is `true` while Mosaiq is still confirming the row
  against venue evidence.
* `priorityFee` appears on an `Alo` order sent with `priorityFeeBps`, once
  Hyperliquid accepted it and Mosaiq billed its fee. `rateBps` is your rate, and
  `chargedUsdc` is the USDC that Mosaiq debited: the rate times the size times
  the limit price. Mosaiq bills it once, at acceptance, whether the order fills
  or not. The field is absent on every other order.
* `neverOnVenue: true` marks a `cancelled` row whose placement a cancel stopped
  before the venue held it: Mosaiq took the cancel before it sent the
  placement, or Hyperliquid accepted the cancel's noop on the placement's nonce
  first. The cancellation itself carries no `failure`. When the venue refuses
  a modify of the order after Mosaiq stopped the placement, the next
  `cancelled` row keeps `neverOnVenue: true` and carries that modify's
  `failure`. A
  `cancelled` row without `neverOnVenue` is an order that the venue held and
  cancelled, on your cancel or on Mosaiq's.
* `cancelCause` says why Mosaiq cancelled an order. It appears only on a
  `cancelled` row without `failure`:

  * `liquidation`: the liquidation of the account sent the cancel that ended
    the order. See [Liquidation](/concepts/liquidation).
  * `market_halt`: Mosaiq halted the market of the order and sent the cancel
    that ended it.
  * `market_expired`: the outcome market of the order expired, and Mosaiq sent
    the cancel that ended it.
  * `venue_reduce_only`: an operator put the venue of the order in
    `user_reduce_only`, and the order has no `reduceOnly`. Mosaiq sent the
    cancel that ended it. A reduce-only order can still pass on that venue.
    Your places and modifies there that can add exposure get
    `trading_restricted` with the detail `venue_reduce_only` until the
    operator reopens it.
  * `venue_contained`: an operator contained the venue of the order. Mosaiq
    sent the cancel that ended it. Your places, modifies and cancels on that
    venue get `out_of_service` with the detail `venue_contained` until the
    operator reopens it.

  The field is absent on every other row, including an order that your own
  cancel ended. If the venue refused Mosaiq's cancel and the order ended later,
  the row has no `cancelCause`. If the venue ends the order with no `failure`
  while Mosaiq's cancel is pending, the row shows the cause too. Accept a value
  that you do not know.
* `venueCloid` is the client order id that Mosaiq gave the order at its venue.
  Rows carry it only on a connection opened with `includeVenueCloid=true`. On
  Hyperliquid, it is the order's `cloid`. On Lighter, it is the order's
  `client_order_index` as `0x` and 12 hex digits. It is read-only: to modify or
  cancel the order, send its `cloid`. Some old orders have no `venueCloid`
  stored, and their rows leave it out. See
  [Find your orders in venue data](/api/exchange#find-your-orders-in-venue-data).

### Failures

`failure` carries the [error object](/api/errors) of the failure,
with `reason` and `rawCode` in place of `msg`. On an `uncertain` row,
`failure.code` is `request_uncertain` and `maybeSent` is `true`, whatever the
detail. On every other row, `failure.code` and `maybeSent` follow the detail:

| `failure.code` | `failure.detail` | `maybeSent` |
| --- | --- | --- |
| `temporarily_unavailable` | `rate_limited`, `transport_unavailable`, `venue_busy`, `recovery_fenced`, `broker_capacity` | `true` |
| `temporarily_unavailable` | `venue_unavailable` | Absent when Mosaiq refused the action before any send. `true` otherwise, for example after a venue outage. |
| `temporarily_unavailable` | `send_capacity`, `execution_price_unavailable` | Absent. |
| `rate_limited` | `congestion_share_exhausted` | Absent. |
| `invalid_request` | `deadline_unreachable` | Absent. |
| `limit_reached` | `insufficient_margin_or_balance` | `true` |
| `trading_restricted` | `market_unavailable`, `market_closed`, `account_restricted` | `true` |
| `duplicate_id` | `duplicate_client_order_id` | `true` |
| `order_not_found` | `order_not_found_for_cancel` | `true` |
| `venue_rejected` | `invalid_order`, `rejected_without_reason`, `modify_before_place_answer`, `no_liquidity`, `expired`, `compression_inclusion_absent`, `self_trade` | `true` |
| `internal_error` | `internal_invariant`, `other` | `true` |

On a row, the detail `rate_limited` is a venue limit on Mosaiq's account, not
your own budget, so its code is `temporarily_unavailable`.

These details need more than their code:

* `send_capacity`: Mosaiq's own send capacity for the venue was full, and
  Mosaiq never sent the order, so the row has no `maybeSent`. The request quota
  of Mosaiq's Hyperliquid account is part of this capacity. The venue is not
  congested, and it is not your rate limit. Reduce-only orders get it too.
  `retryAfterMs` is present only when Mosaiq knows the wait, for example until
  its own rate budget starts again: retry after that wait. Without it, retry
  after a short delay, and wait longer after each new refusal. In a `snapshot`,
  `retryAfterMs` is the part of the wait that is left, and it is absent once
  the wait has passed. Earlier Mosaiq versions answered `venue_unavailable` or
  `rate_limited` for a refusal of the Hyperliquid quota.
* `venue_busy`: the venue is congested. Hyperliquid refused the place because
  its L1 is congested, and the order never rested. Or Hyperliquid refused the
  place or the modify because too many actions of the venue account were still
  waiting for a block, and nothing of it executed. It is not your rate limit.
  Retry after a short delay. On a row that an earlier Mosaiq version wrote, it
  can also mean that Mosaiq's own send capacity was full.
* `congestion_share_exhausted`: Hyperliquid was congested for the venue account
  that sends your order, and your account had used its share of that account's
  allowance, so Mosaiq never sent the place. Most such places are refused in
  the write's answer, with no row. Only a place that its cancel held gets this
  row, after it became durable, and the write's answer carried the same detail.
  The share never refuses a modify, nor a place that `replaces` an order.
  `retryAfterMs` gives the wait before a retry, the same value as on the
  place's answer, and `reason` ends with it as `retry in <ms> ms`. Both an
  `update` and a `snapshot` carry it. See
  [Error codes](/api/errors#exchange-errors).
* `broker_capacity`: the venue refused or cancelled the order because the Mosaiq
  pooled account on that venue did not have enough margin. Your own margin is
  not the cause. `reason` is
  `broker capacity on <venue> is temporarily unavailable; retry shortly`, and
  `rawCode` keeps the venue code. An `update` for that refusal carries
  `retryAfterMs` when Mosaiq knows when margin will reach the account: wait that
  many milliseconds, then retry. It is absent when Mosaiq does not know, and a
  `snapshot` never carries it. The detail `insufficient_margin_or_balance`
  remains for balance refusals that the pooled account did not cause.
  An order with `priorityFeeBps` that Hyperliquid refused because the Mosaiq
  HYPE stake cannot pay the fee also gets `broker_capacity`, with the reason
  `priority fee capacity on <venue> is temporarily unavailable; retry shortly,
  or send the order without priorityFeeBps` and never `retryAfterMs`.
* `recovery_fenced`: recovery after a restart found no evidence that the venue
  received the order. A venue refusal whose answer was lost in the restart ends
  the same way, so the row says `maybeSent: true`.
* `execution_price_unavailable`: Mosaiq had no fresh venue price to bound a
  market order (the Hyperliquid best bid and offer of the coin, or the Lighter
  mark of the market), so it never sent the order. Limit orders are not
  affected. Retry once the market quotes again, or send a limit order.
* `expired` with the `rawCode` `actionAlreadyExpired`: Hyperliquid refused an
  order with `priorityFeeBps` after the 10 s expiry that Mosaiq signs it with,
  not after an `expiresAfter` of yours. Nothing of the order executed, so you
  can send it again. `deadline_unreachable`, and `expired` without that
  `rawCode`, are always about your own `expiresAfter`.
* `no_liquidity`: an IOC or market order found no liquidity before it rested.
  It ends `failed`. If Lighter listed the order as resting first, it ends
  `cancelled` with the same `failure`.
* `self_trade`: Hyperliquid's self-trade prevention cancelled your resting order
  on a spot or outcome market. Mosaiq sends the spot and outcome orders of each
  account from that account's own Hyperliquid sub-account, so this happens only
  when another order of the same account crosses your resting order.
  Hyperliquid then cancels your resting order instead of filling it, and
  charges no fee. The order ends `cancelled`, and its `reason` and `rawCode` are
  `selfTradeCanceled`. The crossing order keeps matching the orders behind
  yours, up to its limit. If it finds none, it ends `failed` with the detail
  `no_liquidity`, even when the book showed your order at its price. Orders of
  two accounts trade on two venue addresses and fill against each other.
* A refusal that Hyperliquid documents is one `failed` row, whichever of
  Hyperliquid's two reports of it arrives first. Its `reason` and `rawCode` are
  the Hyperliquid status name, for example `badAloPxRejected`.
* `modify_before_place_answer`: Mosaiq sent the modify before Hyperliquid
  answered the order's place, and Hyperliquid did not hold the order when the
  modify arrived. The modify did not run, and `size` and `price` stay those of
  the place. Mosaiq does not resend it. A size decrease of a reduce-only order
  is the exception: it stays, and Mosaiq trims the order to it. Do not infer that the order ended from
  `reason`: Hyperliquid returns the same text (`Cannot modify canceled or
  filled order`) whether the modify overtook the place or the order ended first.
  At most one modify per order is unresolved at a time, so this failure always
  names that modify. Read the order's `status` (along with `price`, `size`, and
  `filledSize`) on this row and any following row:
  * `accepted`: transient. Hyperliquid refused the modify before its answer to
    the place arrived. Wait for the next row to learn the order's state.
  * `open` or `partially_filled`: Hyperliquid ran your modify before your place
    (possible when both are sent with no gap), or a partial fill arrived first.
    The order is still live at its place's price and size until you cancel or
    modify it again.
  * `filled`: the order filled before the modify ran.
  * `cancelled`: something else ended the order first, such as a cancel or the
    kill-modify of a `fastCancel: true` cancel. With `neverOnVenue: true`, the
    order never reached the book.
  * `failed`: Hyperliquid refused the place itself, for example a crossing
    `Alo`. The place's own refusal (such as `badAloPxRejected`) appears on a
    separate `failed` row, either before or after the
    `modify_before_place_answer` row depending on venue response order.
* `rejected_without_reason`: the venue refused the order and gave no reason
  that Mosaiq recognizes. The order is final, and nothing executed. Sending the
  same order again unchanged is not expected to succeed. A bare `rejected`
  status from Hyperliquid gives this detail, with `reason` and `rawCode`
  `rejected`.
* Mosaiq can learn of a refusal only later, from the venue's own record of the
  order, when the send got no answer. When that record names a cause that
  Mosaiq recognizes, the row is the same `failed` row as a live refusal, with
  `maybeSent` `true`. Otherwise the detail is `rejected_without_reason`, with
  `maybeSent` `true`. `reason` then names the record, such as
  `orderStatus proved venue rejection`, and `rawCode` is the venue's status
  when it has one. A row with the detail `other` and that reason is older than
  this rule: the venue refused that order too.

## `userFills`

Confirmed venue fills. The first message is a `snapshot` of the 20 most
recent fills, ordered by `createdAtMs` ascending. Each later `update` carries
one fill. Nothing is replayed after a disconnect: backfill through
[`GET /v1/userFills`](/api/user-fills). Upsert each row by `(venue, fillId)`. A
later update can add fees to an earlier fill, so counting both messages as
trades counts the fill twice.

```json
{
  "status": "ok",
  "topic": "userFills",
  "data": {
    "user": "0x0000000000000000000000000000000000000001",
    "type": "update",
    "userFills": [
      {
        "fillId": "1060790150900001",
        "orderId": "0b0f9c0e-6d4e-4a1b-9f37-2c5d8e1a4b01",
        "cloid": "0x00000000000000000000000000000001",
        "a": "BTC",
        "venue": "hyperliquid",
        "b": "buy",
        "size": "0.1",
        "price": "64000",
        "liquidityRole": "taker",
        "fees": {
          "exchange": "2.88",
          "mosaiq": "0.64",
          "priority": "0.32"
        },
        "createdAtMs": 1788646149200
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

```ts
interface UserFills {
  user: string
  type: 'snapshot' | 'update'
  userFills: Array<UserFill>
}

interface UserFill {
  fillId: string
  orderId: string
  cloid: string
  a: string
  venue: string
  b: 'buy' | 'sell'
  size: string
  price: string
  liquidityRole: 'maker' | 'taker'
  fees?: {
    exchange: string
    feeToken?: string
    exchangeRefund?: string
    mosaiq: string
    priority?: string
  }
  createdAtMs: number
  liquidation?: {
    liquidatedUser: string
    oraclePx?: string
    method: 'market' | 'backstop'
    penaltyUsdc?: string
  }
  settlement?: {
    kind: 'delisting'
    listing: number
    settledAtMs: number
    realizedPnlUsdc: string
  }
}
```

[`GET /v1/userFills`](/api/user-fills) describes `fees` and `liquidation`.
`fees` is absent on old fills that Mosaiq recorded without their fees. Absent
means unknown, not zero. A fill of a liquidation order, or
a takeover by the Mosaiq House, carries `liquidation` from its first message.
Treat `venue` as an opaque string.

`settlement` is present on the row that closed a position because its venue
settled the market, and absent on every other fill. No order exists: `orderId`
names the close, `fillId` is `ls:<orderId>`, `price` is the venue's settlement
price and `liquidityRole` is `taker`. `settlement.kind` is `delisting`; treat an
unknown kind as a settlement. `settlement.listing` is the listing that the venue
settled, `settlement.settledAtMs` is when the venue settled it, and
`settlement.realizedPnlUsdc` is the profit or loss of the close, in USDC. The
row never arrives early.

```json
{
  "status": "ok",
  "topic": "userFills",
  "data": {
    "user": "0x0000000000000000000000000000000000000001",
    "type": "update",
    "userFills": [
      {
        "fillId": "ls:5d1e7a52-6c43-8f0e-9a4b-2f11d0c3b7e8",
        "orderId": "5d1e7a52-6c43-8f0e-9a4b-2f11d0c3b7e8",
        "cloid": "0x5d1e7a526c438f0e9a4b2f11d0c3b7e8",
        "a": "SNDK",
        "venue": "lighter",
        "b": "sell",
        "size": "0.0572",
        "price": "775.42",
        "liquidityRole": "taker",
        "fees": {
          "exchange": "0",
          "mosaiq": "0"
        },
        "createdAtMs": 1795035756973,
        "settlement": {
          "kind": "delisting",
          "listing": 1,
          "settledAtMs": 1795035726973,
          "realizedPnlUsdc": "-3.42056"
        }
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

Reconnects and delayed recovery can send a fill twice or leave a gap.
Deduplicate fills by `(venue, fillId)`, and backfill missed history.

## `userEvents`

Events of the account. Today `userEvents` carries the start and the end of a
[liquidation](/concepts/liquidation). The first message is a `snapshot` with an
empty `userEvents` list: Mosaiq keeps no event history, and a reconnect replays
nothing. A liquidation already under way shows in
[`userData.liquidation`](#clearinghousestate). Later `update` messages carry one
event each.

```ts
interface UserEvents {
  user: string
  type: 'snapshot' | 'update'
  userEvents: Array<UserEvent>
}

type UserEvent = LiquidationStarted | LiquidationFinished | MarketSettled

interface LiquidationStarted {
  event: 'liquidationStarted'
  id: string
  timeMs: number
  accountValueUsdc: string
  maintenanceMarginUsdc: string
  positions: Array<{ coin: string; venue: string }>
}

interface LiquidationFinished {
  event: 'liquidationFinished'
  id: string
  timeMs: number
  startedAtMs: number
  positions: Array<{
    coin: string
    venue: string
    closedBy: Array<'market' | 'backstop' | 'settlement'>
  }>
}

interface MarketSettled {
  event: 'marketSettled'
  coin: string
  venue: string
  listing: number
  settlementPx: string
  settledAtMs: number
  fillId: string
  timeMs: number
}
```

```json
{
  "status": "ok",
  "topic": "userEvents",
  "data": {
    "user": "0x0000000000000000000000000000000000000001",
    "type": "update",
    "userEvents": [
      {
        "event": "liquidationStarted",
        "id": "0b0f9c0e-6d4e-8a1b-9f37-2c5d8e1a4b60",
        "timeMs": 1788646140000,
        "accountValueUsdc": "9",
        "maintenanceMarginUsdc": "70",
        "positions": [
          {
            "coin": "BTC",
            "venue": "hyperliquid"
          },
          {
            "coin": "BTC",
            "venue": "lighter"
          }
        ]
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

`id` identifies one liquidation. Both events of a liquidation and
`userData.liquidation.id` carry the same value; use it to match them. `timeMs`
is when Mosaiq decided the start or the end. `liquidationFinished.startedAtMs`
repeats the `timeMs` of the start. `accountValueUsdc` and
`maintenanceMarginUsdc` are the decimal strings that Mosaiq read when the
liquidation started. The account value is below the maintenance margin, unless
the liquidation resumes a position that an earlier liquidation started. Both
values use the oracle prices of that moment, so they can differ from a later
`marginSummary`.

`liquidationStarted.positions` lists the positions to close.
`liquidationFinished.positions` lists the positions on which the liquidation
sent at least one order, or that the Mosaiq House took over. `closedBy` says how
each one closed: `market` for an order on the venue, `backstop` for a takeover
by the House, or both when an order left a rest too small for the venue, and
`settlement` when the venue settled the market during the liquidation.
`userData.liquidation.positions` lists the positions
that the liquidation is closing now. Once the account value is back above
maintenance margin, a position that the liquidation has not started stays open,
for example when its venue was down during the whole liquidation.

`marketSettled` says that the venue settled a market where the account held a
position, and that Mosaiq closed the position at `settlementPx`, the venue's
settlement price. `settledAtMs` is when the venue settled the market, and
`timeMs` is when Mosaiq closed the position. `fillId` names the `userFills` row
of the close, which is the record: Mosaiq keeps no history of this event.

```json
{
  "status": "ok",
  "topic": "userEvents",
  "data": {
    "user": "0x0000000000000000000000000000000000000001",
    "type": "update",
    "userEvents": [
      {
        "event": "marketSettled",
        "coin": "SNDK",
        "venue": "lighter",
        "listing": 1,
        "settlementPx": "775.42",
        "settledAtMs": 1795035726973,
        "fillId": "ls:5d1e7a52-6c43-8f0e-9a4b-2f11d0c3b7e8",
        "timeMs": 1795035756973
      }
    ]
  },
  "server_time_ms": 1788646149474
}
```

Mosaiq sends an event only after it has stored it. A restart of Mosaiq never
sends a second `liquidationStarted` for the same liquidation, and a liquidation
under way at the restart keeps its `id`. An event can be lost when the
connection drops or Mosaiq restarts. After a reconnect, compare
`userData.liquidation` with the last event that you received.

Topics are not ordered with each other. Expect these cases:

* `userData.liquidation` can show a liquidation, and a placement or modify can
  fail with `trading_restricted` and the detail `liquidation_in_progress`,
  before `liquidationStarted` arrives.
* The `orderUpdates` and `userFills` of the liquidation orders can arrive before
  `liquidationStarted`.
* If Mosaiq stops before it stores the start, no event ever names the `id` that
  `userData.liquidation` showed. After the restart, `userData.liquidation`
  shows the liquidation under a new `id`, or `null`.
* A liquidation that starts and ends between two `userData` checks never shows
  in `userData.liquidation`. Only its events report it.
