> 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/builder-guides/tpsl-heatmap-streaming.md). Agents can also search and read this documentation through its [MCP server](https://docs.hydromancer.xyz/~gitbook/mcp).

# TP/SL heatmap streaming

Stream real-time trigger order (take profit / stop loss) updates and build heatmaps showing where TP/SL orders cluster at different price levels.

### Default feed

1. Subscribe to [tpslUpdates](https://docs.hydromancer.xyz/readme/websocket/tp-sl-streaming/tpslupdates.md) and buffer incoming updates
2. Fetch [tpslBook](https://docs.hydromancer.xyz/readme/rest-api/market-data/tpslbook.md) snapshot with block height
3. Apply buffered updates where `height > snapshot_height`
4. Continue applying live updates

The default feed has only `add` and `remove` diffs. Derived trailing-price changes are available by explicit opt-in, described below.

### Use cases

* **TP/SL heatmaps** — visualize where stop losses and take profits cluster relative to current price. Dense clusters = potential liquidation cascades or profit-taking zones.
* **Liquidation risk analysis** — large clusters of stop losses below support indicate potential cascade risk
* **Smart money tracking** — monitor where large accounts place their TP/SL levels
* **Position-level TP/SL monitoring** — filter `isPositionTpsl: true` to see position-attached orders vs standalone triggers
* **Market microstructure research** — study how TP/SL placement evolves relative to price action

### SDK

The [Hydromancer Python SDK](https://github.com/hydromancerxyz/hydromancer-sdk) handles sync automatically:

```python
from hydromancer_sdk import TpslClient

def on_update(client, height, adds, removes):
    book = client.get_book("BTC")
    if book:
        print(f"BTC: {book.order_count} orders "
              f"(TP={len(book.take_profits)}, SL={len(book.stop_losses)})")

        # Get orders near current price
        near = book.orders_near_price(105000, pct=5)
        print(f"  Within 5% of $105K: {len(near)} orders")

        # Price level heatmap data
        levels = book.price_levels()
        for px, count in levels.items():
            if count >= 3:
                print(f"  ${px}: {count} orders")

client = TpslClient(coins=["BTC", "ETH"], on_update=on_update)
await client.run()
```

See [examples/stream\_tpsl.py](https://github.com/hydromancerxyz/hydromancer-sdk/blob/main/examples/stream_tpsl.py) for a complete streaming example.

### Manual implementation for the default feed

If implementing without the SDK, maintain a map of `oid → order` per market:

* **add** — insert or replace order by `oid` (idempotent upsert)
* **remove** — delete order by `oid`

No matching or modification logic is needed. Every `remove` diff is terminal — just drop the order from your map. The `reason` field is informational (see [tpslUpdates](https://docs.hydromancer.xyz/readme/websocket/tp-sl-streaming/tpslupdates.md#remove-handling)) and doesn't affect handling.

### Building a heatmap

To build a trigger-order heatmap:

1. **Bucket by price** — group orders by `triggerPx` into price buckets (e.g., $500 intervals for BTC)
2. **Weight by size** — sum `sz` within each bucket for volume-weighted heatmap
3. **Split by type** — separate take profits (`orderType` contains "Take Profit") from stop losses ("Stop") for distinct color layers
4. **Split by side** — `"A"` (sell-side triggers, typically stop losses below price) vs `"B"` (buy-side triggers, typically take profits above price)

### Key details

* Updates arrive per-block (\~70ms block time on Hyperliquid)
* \~110K trigger orders across \~330 markets (typical for mainnet)
* Block processing latency: \~20µs p50 (near-instant)
* Default subscriptions keep add/remove behavior; enhanced subscriptions also replace derived trailing state
* `isPositionTpsl: true` = attached to a position (auto-cancel when position closes)
* `reduceOnly: true` = almost all trigger orders (reduce-only by nature)

### Differences from L4 orderbook

|                     | L4 orderbook                     | TPSL book                                              |
| ------------------- | -------------------------------- | ------------------------------------------------------ |
| **What**            | Resting limit orders on the book | Untriggered TP/SL orders                               |
| **Diffs**           | `new`, `update`, `remove`        | `add`, `remove`; opt-in derived `update`               |
| **Modifications**   | Yes (partial fills change size)  | Derived trailing state with opt-in                     |
| **Matching**        | Required (crossed orders)        | Not needed                                             |
| **Snapshot format** | Binary (multi-zstd msgpack)      | Binary (multi-zstd msgpack); optional trailing trailer |
| **Typical count**   | \~460K orders                    | \~110K orders                                          |

### Including trailing stops

```python
client = TpslClient(
    coins=["BTC", "ETH"],
    include_trailing_updates=True,
    on_update=on_update,
)
await client.run()
```

This requests the existing `tpslUpdates` channel with enhanced capability and fetches an enhanced REST snapshot. The default remains false. Environments can disable the feature independently; opt-in then fails explicitly rather than silently returning default data.

The SDK applies the full derived state to each matching placement. Use the order's current `trigger_px` for heatmap buckets and inspect `trailing_state` for best price, activation, lifecycle and quality. `order_version` identifies its placement. The existing callback signature is unchanged; a pricing-only callback can have `adds == removes == 0`. Read current state inside the callback. Treat `client.synced == False` as stale, including during reconnect/recovery.

For manual clients, replace the height-only default recipe with the [native cursor bootstrap contract](https://docs.hydromancer.xyz/readme/websocket/tp-sl-streaming/tpslupdates.md#canonical-cursors-and-bootstrap). Subscribe-buffer-fetch remains the sequence, but a block height cannot distinguish same-height fragments or partially applied updates. Validate the captured frontier, source lifetime/reset and buffered controls before publishing the snapshot; discard only the exact covered row prefix. Save resume progress after application. Unknown placement versions or replay gaps mark the book incomplete. In canonical environments the SDK keeps the same socket and fetches a mode-matched fenced snapshot, then validates buffered catchup. Healthy reconnects retain the book and replay from its exact saved cursor without fetching REST again. Snapshotless clients keep streaming with `synced=False` after a gap and perform no REST.
