# Optimizing latency

Run three sockets and keep account snapshots and market data out of the
order-entry loop.

| Path | Purpose | Client key |
| --- | --- | --- |
| [`/v1/exchange/ws`](/api/exchange-websocket) | Place, modify, cancel | frame `id` |
| [`/v1/exchange/ws`](/api/exchange-websocket#maintenance-announcements) `maintenance` | Mosaiq and venue maintenance announcements | `topic`, then `platform` and source `venue` |
| [`/v1/ws`](/api/websocket) `orderUpdates` | Order lifecycle | `cloid` |
| [`/v1/ws`](/api/websocket) `userFills` | Confirmed executions | `(venue, fillId)` |
| [`/v1/ws`](/api/websocket) `userEvents` | Liquidation start and end | `id` |
| [`/v1/ws`](/api/websocket) `clearinghouseState` | Market catalog and account state | `data.type` |
| [`/v1/market-data/ws`](/api/market-data-websocket) `bbo`, `l2Book`, `trades` | Market data | `(topic, venue, coin)` |

:::warning\[Hyperliquid only]
The low-latency path is validated for `hyperliquid` venues. Lighter is
supported by the same API without these latency expectations.
:::

## Order entry

1. Send the orders that you decide together in one frame, and pipeline
   independent frames without waiting for answers. On Hyperliquid, the orders
   of one frame with the same order type, `reduceOnly`, `priorityFeeBps` and
   `expiresAfter` leave as one action, which uses one request of the IP budget
   and one nonce. See
   [Batches](/api/exchange#batches). Do not hold an order back to fill a frame.
   Cancel or modify a group of orders in one frame too. Keep at most 128
   requests in flight per client IP, across all
   connections from that IP. At the limit, Mosaiq answers `rate_limited` with
   the detail `inflight_limit_exceeded`: send again once an answer arrives.
   See [Limits](/api/exchange-websocket#limits). If an answer is missing,
   follow [disconnect recovery](#disconnect-recovery) before you send again.
2. Give every order frame a unique increasing `id` and match answers by
   `id`. Completion order is not guaranteed.
3. Give every placement a fresh `cloid`: `0x` plus 32 lowercase hex digits,
   not all zero.
4. Send a dependent cancel or modify on the same connection, after its place,
   with the same `cloid`. Mosaiq orders them by `(venue, cloid)`, and a cancel,
   or a Hyperliquid modify under the $10 minimum, can stop a pending placement
   before Mosaiq sends it.
   [Ordering](/api/exchange-websocket#ordering) gives the exact contract.
5. Use a library that answers server Pings with the same payload on all three
   sockets.

On the execution socket, route frames by key: a write answer has `id`, and a
`maintenance` message has `topic`. Maintenance messages replace the complete
platform state and source array, and do not confirm order outcomes. Subscribe again after an
execution-socket reconnect.

A batch is not atomic. Its items are answered by index, and separate
pipelined frames by `id`.

### Fast cancel

**What it does.** Pass `fastCancel: true` on a `cancel` item or on a
`mass_cancel` to pull a young Hyperliquid perp `Alo` order faster. When a
cancel may reach Hyperliquid before the order's place, Mosaiq also sends a
one-lot modify at the same price so Hyperliquid cancels the resting order and
refuses the one-lot replacement under its $10 minimum. `cancelAllOnDisconnect`
always runs classic cancels without a kill-modify.

**When it applies.** It is best effort and never refuses a cancel. On Lighter,
on spot or outcome markets, or on orders that cannot use it, Mosaiq runs the
normal cancel and skips the kill-modify. The kill-modify is sent only when:

* the target is a Hyperliquid perp `Alo` order that is not reduce-only;
* the cancel reached Mosaiq before Hyperliquid answered the place and before
  any order update showed the order open;
* one lot at the order's limit price is worth less than $10, that is
  `sizeIncrement × p < 10`, with `sizeIncrement` from
  `assetData.universe[*].venues[*].constraints` in
  [`GET /v1/clearinghouseState`](/api/clearinghouse-state).

Your cancel's answer can come from the kill. Even when all conditions hold,
Mosaiq skips the kill-modify and runs only the normal cancel when the
connection that sent the order to Hyperliquid has no room for one more order at
that moment, when the Hyperliquid address that sent the order has spent its
request quota, or when too little of the cancel's deadline is left. A new order
can still go to Hyperliquid on another connection at that moment. The
kill-modify uses the room for new orders on the connection of its order, never
the room that Mosaiq keeps for cancels. Neither the cancel answer
nor `orderUpdates` reports whether a kill-modify went out. When a kill-modify
ends the order, `orderUpdates` shows `status: "cancelled"` as with a normal
cancel.

**Cost and rate limits.** A `cancel` or `mass_cancel` with `fastCancel: true`
costs 2 units of your Mosaiq exchange budget
([`GET /v1/rateLimits`](/api/rate-limits)), where a classic cancel costs 1,
with no extra client fee. The second unit never gets the cancel refused: with
1 unit left, the cancel and its kill-modify still go, and your next request
waits until 2 units refill. With no unit left, the request is refused with
`rate_limited`, like any request.

**Choosing between `fastCancel` and an in-flight modify:**

| Goal | Pattern | Trade-offs |
| --- | --- | --- |
| Pull young quotes at once, on single cancels or `mass_cancel`, with no extra logic on your side | Place normally, then pass `fastCancel: true` on `cancel` or `mass_cancel` | Best effort, under the conditions above. One cancel request from your client, at 2 units of the exchange budget. |
| Full control: requote, park the order far from the mid, kill an order whose lot is worth $10 or more, or kill with your own modify under $10 | Normal `cancel` (`fastCancel` omitted), or `modify` while the place is in flight | One client request per action, and your own logic. With no gap after the place, Hyperliquid can run the modify before the place and leave the order `open` (see [Modify](/api/exchange#modify)). A modify under $10 that reaches Mosaiq before its place left stops the place: nothing reaches Hyperliquid. |
| Both on one order (`modify` and a `fastCancel: true` `cancel`) | Allowed. If the cancel or its kill-modify ends the order before your modify runs, your modify fails with `modify_before_place_answer` and the order ends `cancelled`. If your modify runs first, a modify under $10 ends the order, and a normal modify is cancelled next. If your modify under $10 stopped the place, the cancel answers `order_not_found`. Read `status` on `orderUpdates`. | Two client requests. The kill-modify stays best effort. |

## Keyed venue cloids

Mosaiq sends the orders of many users from the same Hyperliquid addresses, and
it never sends your `cloid` to Hyperliquid. Each order gets its own Hyperliquid
cloid, the `venueCloid`. To find an order whose venue cloid is random, you have
to wait for the `accepted` answer
(see [Find your orders in venue data](/api/exchange#find-your-orders-in-venue-data)).

Mosaiq derives the venue cloid of each of your Hyperliquid places from your own
`cloid`, with a key that only your account and Mosaiq hold. With the key, you
recognize your orders, cancels and fills in the Hyperliquid mempool,
order-status and fill streams of the Mosaiq addresses from the moment you send
the order, without waiting for the answer. Without the key, the cloid looks like
128 random bits. It has no prefix, and two orders with the same `cloid` get
unrelated venue cloids, so nobody else can group your orders inside the pool.

Mosaiq seals every Hyperliquid place that names its own `c`. There is nothing
to turn on. Lighter orders and places without `c` keep random venue cloids.
Mosaiq seals the orders it places itself on your account, such as a
liquidation, with a key that only Mosaiq holds. Nobody, you included, can tell
them apart from any other order.

The [Transparency](/concepts/transparency) page lists the Mosaiq Hyperliquid
addresses. Watch all of them, because Mosaiq routes each order to one of them.

### Get your key

The owner of the account gets the key once, from the API keys page of the
Mosaiq app. The master account and each sub-account have their own key. The
app shows:

| Field | Meaning |
| ----- | ------- |
| `key` | The AES-128 key, as `0x` and 32 hex digits. Keep it secret. Anyone with it can recognize this account's orders. |
| `version` | The key version that seals your new places, from `1` to `65535`. |
| `scheme` | The derivation below, `tessera-venue-cloid-v1`. |

Store the key when you get it. Mosaiq shows each version once. If you lose
the key, [rotate](#rotation). An API key cannot read or rotate the key.

### Send your orders

Send your orders as usual, each with your own `c`. Mosaiq seals the venue cloid
of every Hyperliquid place that names its `c` with your account's active key
version. To check your implementation, add `includeVenueCloid=true` to the
request or connection URL. Each `accepted` answer then names the `venueCloid`.

A modify keeps the venue cloid of its order. A cancel by `c` sends a Hyperliquid
`cancelByCloid` with the venue cloid of the order it cancels. A cancel or
modify always uses the venue cloid that the order was placed with, even after a
rotation.

If Mosaiq cannot seal a place, the item answers `temporarily_unavailable` with
the detail `venue_cloid_keys_unavailable`, and Mosaiq sends nothing. Mosaiq
never sends one of your orders with an unsealed cloid. Retry the item.

### Recognize your orders

#### Derivation

For your key `K` and a cloid `c` (16 bytes, big-endian, from its 32 hex
digits):

```text
K_tag  = AES-128-ECB_K( 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 )
K_seal = AES-128-ECB_K( 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 )
T      = first 8 bytes of AES-128-ECB_{K_tag}(c)
N      = 8 bytes, big-endian, never repeated for a key. Top bit 0: a place
         you sent, and the other 63 bits are the time Mosaiq sealed it, in
         microseconds since the UNIX epoch. Top bit 1: an order that Mosaiq
         restored for you before it stopped doing so (see below), and the
         other 63 bits are not a time.
venue cloid = AES-128-ECB_{K_seal}( T || N ), as 0x and 32 lowercase hex digits
```

You cannot compute the venue cloid before Mosaiq seals the place, and you do not
need it. Decrypt instead. Before you send an order, compute the tag `T` of its
cloid and store a map from `T` to the cloid. Then, on every line of the Mosaiq
addresses that carries a cloid, decrypt the cloid with `K_seal` and look up its
first 8 bytes. That costs one AES block and one hash map lookup per line. A
cloid of another user decrypts to an unknown tag. With `L` of your cloids in
the map, a foreign line matches by chance with probability `L / 2^64`.

#### Where the venue cloid appears

| Hyperliquid data | Field |
| --- | --- |
| Mempool `order` action | `orders[].c` |
| Mempool `batchModify` action | `modifies[].oid` and `modifies[].order.c`. A modify keeps its order's venue cloid in both. A placement with `replaces` puts the replaced order's venue cloid in `oid` and its own in `order.c`. A fast-cancel kill puts your order's venue cloid in `oid` and a random cloid in `order.c`, which your key does not decode. Hyperliquid refuses that one-lot order at once (`minTradeNtlRejected`). |
| Mempool `cancelByCloid` action | `cancels[].cloid` |
| Order statuses | `order.cloid` |
| Fills | `cloid` |
| [`/v1/market-data/ws`](/api/market-data-websocket) `trades` | `makerCloid` and `takerCloid` |

Some lines name only the Hyperliquid `oid`, such as a cancel by `oid` or a
cancel that Hyperliquid made itself. Mosaiq cancels by cloid, but keep a map
from `oid` to your cloid anyway. Fill it from the first order-status line that
carries one of your venue cloids, and update it when a modify gives the order
a new `oid`. Then look up the lines that name only an `oid` in that map.

#### Python

```python
# pip install cryptography
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

RESTORE_BIT = 1 << 63


def _aes(key: bytes) -> Cipher:
    return Cipher(algorithms.AES(key), modes.ECB())


class VenueCloidKey:
    def __init__(self, key_hex: str) -> None:
        root = _aes(bytes.fromhex(key_hex.removeprefix("0x"))).encryptor()
        tag_key = root.update(bytes([1]) + bytes(15))
        seal_key = root.update(bytes([2]) + bytes(15))
        self._tag = _aes(tag_key).encryptor()
        self._open = _aes(seal_key).decryptor()

    def tag(self, cloid: str) -> bytes:
        return self._tag.update(bytes.fromhex(cloid.removeprefix("0x")))[:8]

    def open(self, venue_cloid: str) -> tuple[bytes, bool]:
        block = self._open.update(bytes.fromhex(venue_cloid.removeprefix("0x")))
        return block[:8], bool(int.from_bytes(block[8:], "big") & RESTORE_BIT)

    def sealed_at(self, venue_cloid: str) -> int:
        block = self._open.update(bytes.fromhex(venue_cloid.removeprefix("0x")))
        return int.from_bytes(block[8:], "big")


class MyOrders:
    """keys: every version that may still have orders, such as {1: key_v1, 2: key_v2}."""

    def __init__(self, keys: dict[int, VenueCloidKey]) -> None:
        self._keys = keys
        self._by_tag: dict[tuple[int, bytes], str] = {}

    def sent(self, cloid: str) -> None:  # call before you send the order
        for version, key in self._keys.items():
            self._by_tag[(version, key.tag(cloid))] = cloid

    def match(self, venue_cloid: str | None) -> str | None:  # your cloid, or None
        if venue_cloid is None:
            return None
        for version, key in self._keys.items():
            tag, _restored = key.open(venue_cloid)
            cloid = self._by_tag.get((version, tag))
            if cloid is not None:
                return cloid
        return None
```

#### Rust

```rust
// aes = "0.8"
use aes::Aes128;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};

pub struct VenueCloidKey {
    tag: Aes128,
    seal: Aes128,
}

impl VenueCloidKey {
    pub fn new(key: [u8; 16]) -> Self {
        let root = Aes128::new(&key.into());
        let subkey = |first: u8| {
            let mut block = GenericArray::from([0_u8; 16]);
            block[0] = first;
            root.encrypt_block(&mut block);
            Aes128::new(&block)
        };
        Self { tag: subkey(1), seal: subkey(2) }
    }

    /// The tag of one of your cloids (its 16 bytes, big-endian).
    pub fn tag(&self, cloid: [u8; 16]) -> [u8; 8] {
        let mut block = GenericArray::from(cloid);
        self.tag.encrypt_block(&mut block);
        block[..8].try_into().unwrap()
    }

    /// Decrypt any Hyperliquid cloid: its tag, and whether Mosaiq restored the order.
    pub fn open(&self, venue_cloid: [u8; 16]) -> ([u8; 8], bool) {
        let mut block = GenericArray::from(venue_cloid);
        self.seal.decrypt_block(&mut block);
        (block[..8].try_into().unwrap(), block[8] & 0x80 != 0)
    }

    /// The `N` of any Hyperliquid cloid. For one of your places, its seal time in microseconds.
    pub fn sealed_at(&self, venue_cloid: [u8; 16]) -> u64 {
        let mut block = GenericArray::from(venue_cloid);
        self.seal.decrypt_block(&mut block);
        u64::from_be_bytes(block[8..].try_into().unwrap())
    }
}
```

Keep your tags in a `HashMap<[u8; 8], Cloid>` and call `open` on each line.
On x86-64 with AES-NI, one `open` and one lookup take a few tens of
nanoseconds.

#### Test vectors

| Input | Value |
| --- | --- |
| `key` | `0x8421b326440e60e1c59e6255f1a1c7bb` |
| `c` | `0x00000000000000000000000000000001` |
| `T` | `3c13c6d11a6e44d1` |
| venue cloid, place, `N = 1` | `0xfd1489a49735e5d6ba4f560976c19d24` |
| venue cloid, place, `N = 1730800000000000` | `0x99937d009c106a5273588a24cf315094` |
| venue cloid, restore, `N = 2^63 + 0x1ddd_eeee_ffff_0001` | `0xb4fc2f62dd486b6041216abe3047f8c7` |

#### Without a tag map

You can also recognize your places with the key alone. The `N` of a place you
sent is a time, so check that it is near the time of the line:

```python
def is_my_place(key: VenueCloidKey, venue_cloid: str, line_time_us: int,
                max_age_us: int, max_skew_us: int) -> bool:
    sealed_at = key.sealed_at(venue_cloid)
    return line_time_us - max_age_us <= sealed_at <= line_time_us + max_skew_us
```

A cloid that your key did not seal gives a random `N`. A window of `w`
microseconds accepts such a cloid with probability `w / 2^64`, about `5e-13`
for 10 seconds and `2e-10` for one hour.

Set the window from these facts:

* `N` is the time of the place, not of the line. A modify, a cancel, an order
  status, or a fill of an older order carries the `N` of its place. Make
  `max_age_us` as long as your orders stay open. Or match each order on its
  first line with a short window, and keep its venue cloid to match its later
  lines.
* Mosaiq reads its own clock when it seals the place. Make `max_skew_us`
  cover the difference with yours.
* A restored order has no time in `N`, so the check misses it.
* The check tells you that an order is yours, not which `cloid` it has. Keep
  the tag map for that.

After a [rotation](#rotation), run the check with each key that still has open
orders.

Mosaiq keeps this meaning of `N` for the scheme `tessera-venue-cloid-v1`. A
change to it comes with a new `scheme`.

### Reusing a cloid

Once an order is no longer open, you can send its `cloid` again. The new order
gets a new venue cloid with the same tag, so `match` returns the same cloid for
both. To tell them apart, for example for a late fill of the earlier order,
compare the full venue cloid. Each order has its own, and the `accepted`
answer names it.

### Restored orders

Mosaiq used to restore a reduce-only order that it had cancelled to make room
for a newer reduce-only placement, when it did not send that placement. It no
longer does: that cancel is final (see [Reduce-only](/api/exchange#reduce-only)).
An order that Mosaiq restored before can still be open. It kept your `cloid`,
got a new `orderId`, and got a new venue cloid sealed with the same key version.
Its tag is the tag of your cloid, and the top bit of its `N` is set, so `open`
reports `restored`. No new venue cloid has that bit set.

### Rotation

To rotate, use the API keys page of the Mosaiq app. The app shows the key of
the next version, once. Your new places use
it at once. Your open orders keep their venue cloids, so keep the old key in
`MyOrders` until they are closed. Cancels and modifies of those orders keep
working. A rotation protects your future orders. It does not protect the orders
that a leaked key already exposed.

### Security

* Mosaiq never reads the owner of an order from its venue cloid. It knows each
  order by the account that sent it, and keeps the venue cloid with the order.
* A key only lets you recognize your account's orders. It cannot place,
  cancel, or read anything through the API. Mosaiq's own orders on your
  account stay unrecognizable to it.
* Mosaiq derives each key in AWS KMS from your account and the version, and
  stores no key. Only the owner gets a key, in the Mosaiq app, once per version.
* Without the key, nobody can tell a venue cloid from random bits. Mosaiq's
  random venue cloids are also 128 uniform random bits, so an observer cannot
  tell keyed orders apart from the others.

## Account operations

Mosaiq moves USDC between its Hyperliquid accounts and their dexes, withdraws
from them, and tops up the margin of isolated positions. While one of these
moves is not done, Hyperliquid delays every action of the account it uses,
cancels included. A quote you cannot pull in that time can be picked off.

Isolated-margin top-ups follow the NYSE trading day, in New York time:

* In the hour before the 09:30 open, Mosaiq tops up its isolated positions, so
  that each one starts the session far from liquidation.
* During the regular session, from one minute before the open to the close,
  Mosaiq avoids top-ups. It sends one only when a position comes within 2% of
  liquidation.
* At other times, and on days when NYSE is closed, a top-up can come at any
  time.

Rebalancing moves and withdrawals follow the rebalancing of the pooled
collateral. During the regular session, the rebalancing moves USDC out of a
maker account only when the move cannot wait: see
[Rebalancing](/concepts/rebalancing#during-us-market-hours).

A Hyperliquid maker account carries `Alo` orders, and the taker account
carries `Ioc` and market orders. Mosaiq rests the `Alo` orders of each market
on one maker account. If you connect with
`cancelAllOnDisconnect=true`, Mosaiq protects you on the account that the move
uses:

1. Mosaiq cancels your Hyperliquid orders on that account. They end
   `cancelled` on `orderUpdates`.
2. Mosaiq sends the move once Hyperliquid confirmed the cancels, or after one
   second.
3. Until the move is done, your places and modifies on that account answer
   `temporarily_unavailable` with the detail `account_operation_in_progress`,
   for at most two seconds after it was sent. `retryAfterMs` and `msg` give
   the longest the pause can still last. Cancels and Lighter are not affected.

The pause is short. The move usually ends well before `retryAfterMs`, so retry
after a short delay, and quote again once a place goes through. Without
`cancelAllOnDisconnect=true`, Mosaiq neither cancels nor refuses your orders,
and Hyperliquid can delay them during a move.

## Lifecycle processing

Keep `/v1/ws` subscribed to `orderUpdates` and `userFills` and keep reading it
even when the strategy ignores messages. Write responses and lifecycle events
are independent, so an `orderUpdates` event can arrive before the matching
write response. Key orders by `cloid`, fills by `(venue, fillId)`, accept
duplicates, and make every transition idempotent. A successful write response
is an acknowledgement, not a fill. It says that Mosaiq launched the venue send.
The venue's answer reaches you only on `orderUpdates`, so time a write to its
first `orderUpdates` row when you compare venues.

`clearinghouseState` sends four snapshots on subscribe, then only the chunks
whose contents changed. Silence means unchanged, not disconnected. Set
`subscription.markets` to the assets your strategy uses to limit market data.
Keep the latest value of each `data.type` and never use these messages to
confirm individual orders. No topic orders events relative to another topic.

## Disconnect recovery

A dropped connection does not say whether the last frame reached Mosaiq. Do
not resend immediately.

1. Reconnect with backoff.
2. Subscribe again and buffer the new `orderUpdates` and `userFills` messages.
3. Backfill [`GET /v1/userFills`](/api/user-fills), following its cursor and
   deduplicating by `(venue, fillId)`.
4. Query [`GET /v1/openOrders?cloid=<cloid>`](/api/open-orders) for each
   ambiguous order.
5. Reconcile before retrying or replacing. A replacement placement needs a
   new `cloid`.

## Network placement

Measure the round-trip time from the host that will run the strategy. Reuse
established sockets, so that DNS, TCP, TLS, and authentication stay off the
path of each order. Private VPC peering is available on request during
onboarding. Mosaiq does not guarantee a specific latency. Benchmark the full
path from your client to the venue, from the host you will trade from.
