> For the complete documentation index, see [llms.txt](https://docs.gammaswap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.gammaswap.com/developers/api-reference/subscription-methods.md).

# Subscription Methods

`ExchangeWebSocketClient` manages the market WebSocket connection and subscribes to real-time order, trade, cancel, and resolution updates by `assetId`.

```ts
import {
  createExchangeWebSocketClient,
} from "@gammaswap/v2-exchange-sdk";

const marketStream = createExchangeWebSocketClient({
  websocketUrl: "wss://exchange-api.gammaswap.com/ws/",
  onError: (error) => console.error(error),
});
```

### `connectionState`

Returns the current state of the market WebSocket connection.

```ts
const state = marketStream.connectionState;
```

SDK response:

```ts
state
```

### `connect`

Opens the market WebSocket connection.

```ts
const result = await marketStream.connect();
```

After the socket opens, the WebSocket service sends a `connected` control message:

```json
{
  "type": "connected",
  "message": "Send {\"type\":\"subscribe\",\"assetId\":\"...\"} to receive market updates"
}
```

Calling `connect()` before subscribing is optional. `subscribeOrderBook` establishes the connection when necessary.

### `subscribeOrderBook`

Subscribes to market updates for an `assetId`.

```ts
const unsubscribe =
  await marketStream.subscribeOrderBook(
    "261336857817713630688382311349658711122006440411137",
    {
      onUpdate: (update) => {
        console.log("Market update", update);
      },
      onOrder: (update) => {
        console.log("Order update", update);
      },
      onTrade: (update) => {
        console.log("Trade update", update);
      },
      onCancel: (update) => {
        console.log("Cancel update", update);
      },
      onResolution: (update) => {
        console.log("Resolution update", update);
      },
      onError: (error) => {
        console.error("Subscription error", error);
      },
      onResyncRequired: (assetId) => {
        console.log("Reload REST order book", assetId);
      },
    },
  );
```

SDK response:

```ts
async () => {
  // Removes this handler.
}
```

The resolved value is an asynchronous unsubscribe function:

```ts
await unsubscribe();
```

The underlying WebSocket subscription message is:

```json
{
  "type": "subscribe",
  "assetId": "261336857817713630688382311349658711122006440411137"
}
```

After the subscription is accepted, the service sends:

```json
{
  "type": "subscribed",
  "assetId": "261336857817713630688382311349658711122006440411137"
}
```

### `unsubscribeOrderBook`

Removes all local handlers for an `assetId` and unsubscribes from that asset’s server-side market feed.

```ts
const result =
  await marketStream.unsubscribeOrderBook(
    "261336857817713630688382311349658711122006440411137",
  );
```

SDK response:

```ts
undefined
```

The underlying WebSocket unsubscribe message is:

```json
{
  "type": "unsubscribe",
  "assetId": "261336857817713630688382311349658711122006440411137"
}
```

After the subscription is removed, the service sends:

```json
{
  "type": "unsubscribed",
  "assetId": "261336857817713630688382311349658711122006440411137"
}
```

`unsubscribeOrderBook` removes every local handler for the asset.

The unsubscribe function returned by `subscribeOrderBook` removes only the handler associated with that call.

### `close`

Closes the market WebSocket connection.

```ts
const result = marketStream.close();
```

An optional WebSocket close code and reason can be supplied:

```ts
marketStream.close(1000, "Client shutdown");
```

The client does not reconnect after an intentional close unless a new connection or subscription is started.

### Order updates

Order updates are delivered to `onOrder` and `onUpdate`.

```json
{
  "type": "order",
  "seqId": 123,
  "data": {}
}
```

### Trade updates

Trade updates are delivered to `onTrade` and `onUpdate`.

```json
{
  "type": "trade",
  "seqId": 124,
  "data": {}
}
```

### Cancel updates

Cancel updates are delivered to `onCancel` and `onUpdate`.

```json
{
  "type": "cancel",
  "seqId": 125,
  "data": {}
}
```

### Resolution updates

Resolution updates are delivered to `onResolution` and `onUpdate`.

```json
{
  "type": "resolution",
  "seqId": 126,
  "data": {}
}
```

### Error messages

If a subscription message cannot be processed, the service sends an error message:

```json
{
  "type": "error",
  "message": "AssetId 123 is not available"
}
```

Errors are delivered to:

* The subscription’s `onError` handler
* The client-level `onError` handler, where applicable

### Resynchronization

Market updates include a sequence ID.

If the connection drops or the client determines that the socket is unhealthy, active subscriptions receive:

```ts
onResyncRequired(assetId);
```

Reload the complete order-book snapshot through `InfoClient` before applying subsequent updates:

```ts
const freshBook = await info.getOrderBook({
  assetId,
  epoch,
});
```

### Subscription behavior

One client can subscribe to multiple asset IDs.

When multiple handlers subscribe to the same asset:

1. The client creates one server subscription.
2. Updates are distributed to every local handler.
3. The returned unsubscribe function removes only its handler.
4. The server subscription is removed after the last handler unsubscribes.

### Reconnection defaults

| Option                | Default |
| --------------------- | ------: |
| `reconnect`           |  `true` |
| `reconnectDelayMs`    |  `1000` |
| `maxReconnectDelayMs` | `30000` |
| `ackTimeoutMs`        | `15000` |

### Heartbeats

The server sends protocol-level WebSocket ping frames.

Browser WebSockets and the Node `ws` client respond with protocol pong frames automatically.

Do not send an application-level pong message:

```json
{
  "type": "pong"
}
```

### Available methods and properties

<table><thead><tr><th width="216.5625">Name</th><th>SDK response</th></tr></thead><tbody><tr><td><code>connectionState</code></td><td>Current connection-state value</td></tr><tr><td><code>connect</code></td><td><code>Promise&#x3C;void></code></td></tr><tr><td><code>close</code></td><td><code>void</code></td></tr><tr><td><code>subscribeOrderBook</code></td><td><code>Promise&#x3C;unsubscribe function></code></td></tr><tr><td><code>unsubscribeOrderBook</code></td><td><code>Promise&#x3C;void></code></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.gammaswap.com/developers/api-reference/subscription-methods.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
