> For the complete documentation index, see [llms.txt](https://docs.hydromancer.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hydromancer.xyz/readme/websocket/tp-sl-streaming/tpslupdates.md).

# 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. Default mode retains its existing cursor formats; enhanced mode requires a scoped `tpslws1:` token. |

**Per-tier coin limits:** Starter 5 · Growth 50 · Scale 200. See [rate-limits-user-limits-and-heartbeats.md](https://docs.hydromancer.xyz/readme/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 payload, cadence and replay behavior. 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`, and boolean `replayComplete`. A successful ordinary subscription is not confirmation of enhanced capability. The feature must be enabled and ready in that environment. `tpsl_updates_disabled` rejects opt-in when disabled; `tpsl_snapshot_required` means the enhanced source/replay cannot serve the request. Neither silently falls 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.

### Enhanced cursors and bootstrap

Enhanced replay uses `tpslws1:` followed by hex-encoded UTF-8 JSON:

```
{"formatVersion":1,"includeTrailingUpdates":true,"coins":["BTC"],"native":{...}}
```

`coins` is sorted and unique, or null for all markets; it must match the subscription. The native object uses the generated `EnhancedCursor` schema: `formatVersion`, `lifetime` (`name`, exact RFC3339 `created`), `resetFence`, `completeHeight`, `lifecycleCompleteHeight`, nullable `lifecycle`, nullable `pricing`, nullable `tail`, and transport `part`. Lifecycle coordinates are `height`, `ordinal`, optional `txIndex`. Pricing coordinates identify the physical record span (`firstSequence`, `lastSequence`), `logicalId`, and nullable `eventOrdinal`. Tail is `height`, `phase`, `ordinal`. A null pricing event ordinal means the record was fully applied, rather than partially consumed.

The enhanced REST snapshot uses **`tpsl1:` plus hex JSON of the native object**, not the scoped public wrapper. Decode it for local cutover; do not send a bare `tpsl1:` token as a WebSocket resume. After installing a validated snapshot, wrap its native cursor with your mode and canonical coins to produce public resume progress. Tokens are not lexicographically sortable, and height alone cannot represent progress inside a block.

For raw clients:

1. Subscribe once and start a bounded buffer after the effective enhanced ACK. Capture its native starting cursor; keep buffering while fetching `tpslBook` with `includeTrailingState:true` and matching coins.
2. Validate the snapshot trailer and its three fence headers. Require the same lifetime/reset and snapshot coverage of the ACK's captured starting cursor. Validate the buffered prefix, including recovery/reset controls, before publishing any snapshot or successful callback.
3. Discard exactly those buffered rows covered by the snapshot's native cursor. Keep later rows, including tails in a frame that straddles the cutover and later fragments at the same height. Apply them in source order.
4. Validate frame continuity with `beforeCursor`, per-row cursors and the native source components. Within one lifetime/reset, complete heights and source coordinates never regress; identical lifecycle coordinates must have identical metadata. A pricing record's span/logical ID remains fixed while its ordinal advances; completion follows its last partial ordinal. A later pricing span must begin after the previous span ends. Compare tail positions by `(height, phase, ordinal)` with lifecycle before pricing.
5. `seq` increases within the connection's enhanced-mode counter but may have gaps across coin scopes; legacy and enhanced counters are independent; use native continuity to detect missing data. Each bounded fragment is its own message (`chunk:1`, `totalChunks:1`, `batchId:seq`). Native `part` increases for unchanged source progress and restarts at 1 when source progress advances. `completeThroughHeight` advances only once both sources are complete. Empty progress frames count; `timestamp` may be explicit null on quiet progress.
6. For snapshotless bootstrap, save the first acknowledged starting cursor as the resume baseline so an ACK-only disconnect does not skip the next interval. This does not establish the previously existing order book. Save later progress only after successful application. Retain the installed snapshot cursor while buffered frames are older than that snapshot; never replace it with an older frame cursor. Advance to emitted frame cursors once their native progress reaches or passes the snapshot cutover. On reconnect, send that scoped cursor in the enhanced subscription's `cursor`. Replay includes lifecycle events and derived updates. `replayComplete` reports catch-up; it does not make a snapshotless client complete for previously existing orders.

A `data.control:{"type":"recovery","reason":"..."}` frame has no diffs, does not advance the cursor and sets `replayComplete:false`. Recovery, changed lifetime/reset, expired replay, invalid/unknown updates or buffer overflow require a new subscribe-buffer-snapshot bootstrap. Keep the previous book marked stale until replacement succeeds. Never continue with guessed progress.

The Python SDK implements this with `TpslClient(..., include_trailing_updates=True)`. It keeps one subscription per connection, clears `synced` on disconnect, and retries recoverable bootstrap failures. Disabled admission raises `TpslFeatureDisabled`. Snapshotless mode cannot recover gaps and raises `ReplayGapError`. Use the generated `EnhancedTpslUpdatesMessage` model for enhanced envelopes; the existing `TpslBlockUpdate` model remains the default response. Cursor decoding, validation and ordering references are in the SDK's `_internal/tpsl_formats.py`.
