# allIsolatedMarginUpdates

{% 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

```
{
    "method": "subscribe",
    "subscription": {
        "type": "allIsolatedMarginUpdates"
    }
}
```

### Unsubscribe

```
{
    "method": "unsubscribe",
    "subscription": {
        "type": "allIsolatedMarginUpdates"
    }
}
```

### Update data format

Updates are batched per block. There are two update types: `isolated_margin` and `top_up_isolated_margin`.

{% hint style="info" %}
**Reconnection Note:** When reconnecting with a session, replay and live events may overlap. Deduplicate using `(time, tx_index)` - skip updates where this tuple is at or before your last processed update. See [Session Management](/readme/websocket/session-management-and-reconnection.md#deduplication) for details.
{% endhint %}

{% hint style="info" %}
For cross/isolated leverage changes (`updateLeverage` action), see [allLeverageUpdates](/readme/websocket/allleverageupdates.md).
{% endhint %}

#### Isolated margin update

Sent when a user adds or removes isolated margin on a position (`updateIsolatedMargin` action). Specifies the USDC delta.

```json
{
  "type": "allIsolatedMarginUpdates",
  "seq": 1,
  "cursor": 1704067201000,
  "updates": [
    {
      "update_type": "isolated_margin",
      "time": 1704067201000,
      "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2",
      "coin": "xyz:GOLD",
      "is_buy": false,
      "ntli": "0.223223",
      "tx_index": 0
    }
  ]
}
```

#### Top-up isolated margin update

Sent when a user adjusts their isolated margin to reach a target leverage (`topUpIsolatedOnlyMargin` action). Unlike `isolated_margin` which specifies a USDC delta, this specifies the desired leverage directly.

```json
{
  "type": "allIsolatedMarginUpdates",
  "seq": 2,
  "cursor": 1704067202000,
  "updates": [
    {
      "update_type": "top_up_isolated_margin",
      "time": 1704067202000,
      "user": "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2",
      "coin": "ETH",
      "target_leverage": "8.0",
      "tx_index": 0
    }
  ]
}
```

### Field reference

| Field             | Type   | Description                                                     |
| ----------------- | ------ | --------------------------------------------------------------- |
| `update_type`     | string | `"isolated_margin"` or `"top_up_isolated_margin"`               |
| `time`            | number | Block timestamp (milliseconds since epoch)                      |
| `user`            | string | User address (lowercase)                                        |
| `coin`            | string | Coin/market name (e.g. `"ETH"`, `"xyz:GOLD"`)                   |
| `is_buy`          | bool   | Side of the margin change (`isolated_margin` only)              |
| `ntli`            | string | Amount of margin added or removed (`isolated_margin` only)      |
| `target_leverage` | string | Target leverage as float string (`top_up_isolated_margin` only) |
| `tx_index`        | number | Transaction index within the block                              |

### Examples

{% tabs %}
{% tab title="Javascript" %}

```javascript
const WebSocket = require('ws');

const ws = new WebSocket(`wss://api.hydromancer.xyz/ws?token=${process.env.HYDROMANCER_API_KEY}`);

ws.on('message', (data) => {
    const msg = JSON.parse(data);

    if (msg.type === 'connected') {
        ws.send(JSON.stringify({
            method: 'subscribe',
            subscription: {
                type: 'allIsolatedMarginUpdates'
            }
        }));
    } else if (msg.type === 'ping') {
        ws.send(JSON.stringify({ type: 'pong' }));
    } else if (msg.type === 'allIsolatedMarginUpdates') {
        console.log(`Received ${msg.updates.length} isolated margin updates`);
        for (const update of msg.updates) {
            if (update.update_type === 'isolated_margin') {
                console.log(`  ${update.user}: ${update.coin} is_buy=${update.is_buy} ntli=${update.ntli}`);
            } else if (update.update_type === 'top_up_isolated_margin') {
                console.log(`  ${update.user}: ${update.coin} target_leverage=${update.target_leverage}`);
            }
        }
    }
});
```

{% endtab %}

{% tab title="Python" %}

```python
import websocket
import json
import os

def on_message(ws, message):
    msg = json.loads(message)

    if msg['type'] == 'connected':
        ws.send(json.dumps({
            "method": "subscribe",
            "subscription": {
                "type": "allIsolatedMarginUpdates"
            }
        }))
    elif msg['type'] == 'ping':
        ws.send(json.dumps({'type': 'pong'}))
    elif msg['type'] == 'allIsolatedMarginUpdates':
        print(f"Received {len(msg['updates'])} isolated margin updates")
        for update in msg['updates']:
            if update['update_type'] == 'isolated_margin':
                print(f"  {update['user']}: {update['coin']} is_buy={update['is_buy']} ntli={update['ntli']}")
            elif update['update_type'] == 'top_up_isolated_margin':
                print(f"  {update['user']}: {update['coin']} target_leverage={update['target_leverage']}")
    elif msg['type'] == 'subscriptionUpdate':
        print(f"Subscription update: {msg}")
    elif msg['type'] == 'error':
        print(f"Error: {msg}")

ws = websocket.WebSocketApp(
    f"wss://api.hydromancer.xyz/ws?token={os.environ.get('HYDROMANCER_API_KEY')}",
    on_message=on_message
)
ws.run_forever()
```

{% endtab %}
{% endtabs %}

#### Common errors

1. ```
   Connection timeout - Respond to ping messages
   ```
2. ```
   Invalid API key
   ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.hydromancer.xyz/readme/websocket/allisolatedmarginupdates.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
