> For the complete documentation index, see [llms.txt](https://hydromancer.xyz/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hydromancer.xyz/docs/websocket/tp-sl-streaming/tpslupdates.md). Agents can also search and read this documentation through its [MCP server](https://hydromancer.xyz/docs/~gitbook/mcp).

# tpslUpdates

Stream real-time TP/SL trigger order updates per block.

Every live data message includes both routing identifiers with the same value:

```json
{"type": "tpslUpdates", "channel": "tpslUpdates"}
```

Other payload fields are omitted above. Existing clients may continue routing on either field.

{% hint style="info" %}
💧 New endpoint - this endpoint is not a part of original Hyperliquid API and is added by us for builder convenience.
{% endhint %}

### Subscribe

```json
{
    "method": "subscribe",
    "subscription": {
        "type": "tpslUpdates",
        "coins": ["ETH", "BTC"]
    }
}
```

**Parameters:**

| Parameter                | Type      | Required | Description                                                                                                                                                                                                            |
| ------------------------ | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `coins`                  | string\[] | No       | Perp coins to subscribe to. Omit for all markets (needs **tpslUpdatesAll** add-on).                                                                                                                                    |
| `includeTrailingUpdates` | boolean   | No       | Defaults to false. Opt in to derived trailing state and native replay cursors on this same channel.                                                                                                                    |
| `cursor`                 | string    | No       | Resume after applied progress. Canonical environments return scoped `tpslws2:` tokens in both modes. Retain the exact token; it is bound to coins and mode. Older environments retain their negotiated cursor profile. |

**Per-tier coin limits:** Starter 5 · Growth 50 · Scale 200. See [rate-limits-user-limits-and-heartbeats.md](https://hydromancer.xyz/docs/websocket/rate-limits-user-limits-and-heartbeats.md) for the full table.

{% hint style="warning" %}
Trigger orders only exist on **perpetual markets**. Spot and outcome markets do not have TP/SL orders, so no `marketTypes` filter is needed.
{% endhint %}

### Unsubscribe

```json
{
    "method": "unsubscribe",
    "subscription": {
        "type": "tpslUpdates",
        "coins": ["ETH", "BTC"]
    }
}
```

### Update data format

With `includeTrailingUpdates` omitted or false, updates are streamed per-block with trigger order changes for subscribed markets:

```json
{
    "type": "tpslUpdates",
    "channel": "tpslUpdates",
    "seq": 1,
    "cursor": "500:1704067200000",
    "data": {
        "height": 782007304,
        "timestamp": 1704067200000,
        "diffs": [
            {
                "type": "add",
                "oid": 285974866067,
                "coin": "BTC",
                "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2",
                "side": "A",
                "triggerPx": "50000.00",
                "limitPx": "49000",
                "sz": "0.01",
                "triggerCondition": "Price above 50000",
                "orderType": "Take Profit Market",
                "isPositionTpsl": true,
                "reduceOnly": true,
                "timestamp": 1704067100000
            },
            {
                "type": "remove",
                "oid": 285974866000,
                "coin": "BTC",
                "reason": "triggered"
            }
        ]
    }
}
```

### Diff types

| Type     | Description                             | Fields                       |
| -------- | --------------------------------------- | ---------------------------- |
| `add`    | New trigger order placed (or re-opened) | All order fields (see below) |
| `remove` | Trigger order removed                   | `oid`, `coin`, `reason`      |

The default feed contains only `add` and `remove`; it does not stream derived trailing-price changes. An order is either open (`add`) or terminal (`remove`). If a user cancels and replaces a trigger order, you'll see a `remove` + `add` with a new `oid`.

### Add fields

| Field              | Type   | Description                                                     |
| ------------------ | ------ | --------------------------------------------------------------- |
| `oid`              | int    | Unique order ID                                                 |
| `coin`             | string | Market symbol (e.g., "BTC", "ETH")                              |
| `user`             | string | User address (0x...)                                            |
| `side`             | string | "B" = buy, "A" = sell                                           |
| `triggerPx`        | string | Trigger price as decimal string                                 |
| `limitPx`          | string | Limit price as decimal string                                   |
| `sz`               | string | Order size as decimal string                                    |
| `triggerCondition` | string | Human-readable condition (e.g., "Price above 50000")            |
| `orderType`        | string | Order type — "Take Profit Market", "Stop Market", etc.          |
| `isPositionTpsl`   | bool   | True if this is a position-level TP/SL (attached to a position) |
| `reduceOnly`       | bool   | True if reduce-only order                                       |
| `timestamp`        | int    | Order creation timestamp (ms since epoch)                       |

### Remove handling

A `remove` diff is always terminal — drop the order from your local state. The optional `reason` field is informational only; you don't need to branch on it.

<details>

<summary>Known reason values (for logging / analytics)</summary>

| Reason                  | Description                                      |
| ----------------------- | ------------------------------------------------ |
| `triggered`             | Trigger condition met, order placed on book      |
| `canceled`              | User canceled the order                          |
| `reduceOnlyCanceled`    | Reduce-only order canceled (position closed)     |
| `marginCanceled`        | Canceled due to insufficient margin              |
| `rejected`              | Order rejected by the engine                     |
| `siblingFilledCanceled` | Sibling TP/SL order triggered, this one canceled |
| `liquidatedCanceled`    | Order canceled due to position liquidation       |

The `reason` field passes through the underlying Hyperliquid status verbatim, so future status names will appear automatically. Always treat a `remove` diff as terminal regardless of the reason value.

</details>

### Common errors

1. `Too many coins` - Reduce number of coins or upgrade tier
2. `Subscribing to all markets requires permission` - Needs **tpslUpdatesAll** add-on
3. `Rate limit exceeded` - Reduce subscription frequency
4. `Authentication failed` - Check API key

### Opt-in trailing updates

Set `includeTrailingUpdates:true` to receive `add`, `remove` and full derived-state `update` rows on **the same `tpslUpdates` channel**. Omitted/false subscriptions retain the existing add/remove payload. In canonical environments both modes use one ordered source and native replay; only derived `update` operations are filtered. Both modes may coexist; coin scope and mode identify independent subscriptions. Unsubscribe with the same mode and coin scope. Existing permissions and coin limits apply to both modes.

```json
{"method":"subscribe","subscription":{"type":"tpslUpdates","coins":["BTC"],"includeTrailingUpdates":true}}
```

Wait for `type:"subscriptionUpdate"`. Its `subscription` object must echo `type:"tpslUpdates"`, your coins, **`includeTrailingUpdates:true`**, a scoped `cursor` when a source position exists, and boolean `replayComplete`. A successful ordinary subscription is not confirmation of enhanced capability. In canonical environments **both** modes receive this ACK; a source that is not ready still acknowledges the owned subscription with `replayComplete:false` and may omit `cursor`. It later announces a gap and a real live anchor. `tpsl_updates_disabled` rejects opt-in when the environment feature is disabled; this does not silently fall back to the default feed.

An enhanced message has this shape (angle-bracket strings stand for real cursors and placement versions):

```json
{
  "type":"tpslUpdates", "channel":"tpslUpdates", "seq":42,
  "cursor":"<scoped cursor after this frame>",
  "chunk":1, "totalChunks":1, "batchId":42,
  "data":{
    "includeTrailingUpdates":true, "height":101, "timestamp":1704067200000,
    "beforeCursor":"<scoped cursor before this frame>",
    "completeThroughHeight":100, "replayComplete":false,
    "diffs":[{
      "type":"update", "coin":"BTC", "oid":7,
      "orderVersion":"<placement version>",
      "triggerPx":"95000", "bestPx":"100000", "activationPx":null,
      "retracement":"5", "retracementType":"pct",
      "lifecycle":"active", "quality":"ok",
      "sourcePosition":{"height":101,"phase":"pricing","ordinal":0},
      "cursor":"<scoped cursor through this row>"
    }]
  }
}
```

Every `update` includes **all** derived fields. Replace the previous derived state, including explicit nulls; also set the order's `triggerPx`. Preserve lifecycle-owned fields such as user, side, size and limit price. Updates may change only `bestPx` or `quality`; they still matter even if `triggerPx` is unchanged. `retracementType` is `pct`, `abs`, or null together with null `retracement`. `lifecycle` is `waiting` or `active`; `quality` is `ok`, `metadataMissing`, `unsupported`, `invalid`, or `reconstructionUncertain`. These describe reconstruction, not execution guarantees.

Enhanced `add`/`remove` rows retain their ordinary fields and add `sourcePosition` (`height`, original `ordinal`, optional `txIndex`) and a scoped row `cursor`. Pricing source positions contain `height`, `phase:"pricing"`, and `ordinal`. Within each height lifecycle events precede pricing, with original ordinals preserved. `txIndex` is supplemental; it is not a substitute for the ordinal.

Apply by `(coin, oid, orderVersion)`. The enhanced snapshot supplies a version for every active order. An add upsert retains the existing version and derived state; remove deletes both. For a genuinely new add, compute the version as `"source:"` plus lowercase hex of compact UTF-8 JSON for this array:

```
[{"name": lifetime.name, "created": lifetime.created}, resetFence, coin, oid, sourcePosition.height, sourcePosition.ordinal]
```

Use the lifetime and reset fence from the decoded row cursor. Preserve the stated object key order and JSON values. Remove/re-add creates a new version, even for a reused order ID. An update for an unknown order or wrong version requires recovery; never create an order from an update. Validate a whole frame before publishing its changes or advancing saved progress.

### Canonical cursors and bootstrap

In an environment advertising canonical TPSL, **both modes** use opaque `tpslws2:` scoped resume tokens. They bind the complete coin selection and the `includeTrailingUpdates` mode. Save the exact token supplied by the server; never sort tokens lexicographically, substitute a height, or reuse a token for another selection. Older environments retain their negotiated legacy profile.

One native position names one source lifetime, reset identity, physical logical record span, real block height/time and an optional **global unfiltered event ordinal**. Completion follows every event of the logical record. Original `sourcePosition.ordinal` values and update provenance are distinct from that canonical ordinal. Coin filtering, default-mode update filtering and quiet blocks still emit progress, so empty frames must be processed. Lifecycle rows remain in original source order; remove/re-add establishes a fresh placement.

The default `data` body remains `TpslBlockUpdate`. An ordinary frame contains one height, and multiple fragments at that height must all apply. Replay `data` is an array of block bodies and may contain several heights. Enhanced bodies retain `beforeCursor`, row cursors and `completeThroughHeight`. `seq` is connection delivery order; chunk/batch identifiers are transport metadata, not native positions. Use the exact frame cursor after successful application.

Raw clients should:

1. Subscribe once, check the effective mode/coin ACK and buffer frames while fetching `tpslBook` for matching coins. Set `includeTrailingState:true` only for enhanced mode. A missing pending-source ACK cursor establishes no baseline.
2. Validate the snapshot body against **all three existing fence headers**: `x-tpsl-lifecycle-height`, `x-tpsl-pricing-cursor`, and `x-tpsl-reset-fence`. The historical header name `pricing-cursor` now carries the one canonical `tpsl2:` snapshot token. Enhanced snapshots also contain the existing trailing trailer. Native snapshot tokens are unscoped and cannot be sent as public resume tokens. The SDK validates and wraps them for the exact selection.
3. Require a complete snapshot fence in the same lifetime/reset, covering the admitted starting position. Validate the buffered suffix before atomically installing the candidate book. A failed candidate must retain its buffered prefix until a later snapshot proves coverage; it cannot silently lose rows.
4. The REST fence covers a whole completed record at height H. Skip each buffered block body at or below H; apply **every** fragment above H in source order, including later fragments at the same height. In enhanced mode additionally validate before/row native continuity and placement versions. Complete height advances only after the native record completes.
5. Persist native progress only after successfully applying that frame. On a healthy reconnect retain the book and send its saved scoped cursor; replay supplies the exact remaining suffix without a fresh snapshot masking loss. Snapshotless clients save the initial real ACK position even if the first socket disconnects before any data; this does not reconstruct older orders.

### Gaps and recovery

Unavailable, expired, invalid or reset history produces the existing terminal Replay control with `hasGap:true`, `hasMore:false`, and no replacement snapshot. The subscription and socket remain open and resume real live delivery from a truthful native anchor. Other subscriptions and heartbeat traffic continue. The server does not keep a client-side book or certify completeness after a gap.

Both modes use the shared regular-channel replay horizon: at most 15 minutes, or the lower configured maximum. A native cursor outside that window receives the gap control and a current native anchor; the server does not manufacture a replacement historical cursor. Longer physical store retention does not extend this public replay window.

Clients decide when to resync. Mark the local book incomplete on `hasGap`, source change, invalid placement or discarded buffered data; fetch a mode-matched fenced snapshot and validate buffered catchup before announcing synchronization. A new gap during HTTP fetch invalidates that response even if the native epoch repeats. If a bounded local buffer overflows, a later snapshot must cover the discarded prefix; the SDK keeps the reader alive during that recovery. Its retained backlog is bounded; receiving/decoding a complete WebSocket frame has no separate aiohttp message-size cap.

The Python `TpslClient` handles both canonical modes with one socket, reader, keepalive and owned snapshot task. Recoverable gaps use REST on that same socket; successful retained-book reconnects use replay without REST. Disabled admission and permanent permission/rate errors reach the caller. `fetch_snapshot=False` performs no REST and continues live with `synced=False` after a gap. Treat that state as incomplete until an explicit snapshot-backed recovery succeeds. Legacy environment gap behavior remains the existing negotiated profile.

Use `EnhancedTpslUpdatesMessage` for enhanced envelopes and `TpslBlockUpdate` for default bodies. Cursors remain opaque strings in the public schema.
