> For the complete documentation index, see [llms.txt](https://gitbook-docs.coinmetrics.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook-docs.coinmetrics.io/tutorials-and-examples/user-guides/how-to-use-websockets.md).

# How To Use Websockets

### How to use Websockets with the Python API Client

Below is a template for using the timeseries-stream endpoints using the Python API Client. The Python API Client websocket functionality is built on top of the [websocket](https://websockets.readthedocs.io/en/stable/) library.

```python
import sys
import websocket
from os import environ

import orjson

from coinmetrics.api_client import CoinMetricsClient, CmStream

api_key = (
        environ.get("CM_API_KEY") or sys.argv[1]
)  # sys.argv[1] is executed only if CM_API_KEY is not found

client = CoinMetricsClient(api_key)

# Replace this with any timeseries-stream methods
stream = client.get_stream_market_orderbooks(
    markets=['binance-btc-usdt-spot']
)

def on_message(
        stream: websocket.WebSocketApp, message: str
) -> None:
    """
    Custom message callable to be passed in the streaming object
    :param stream: CmStream, WebSocketApp connection
    :param message: str, The message relayed by the API
    :return: None
    """
    data = orjson.loads(message)
    print(data)
    sequence_id = int(data['cm_sequence_id'])
    
    # Optional: Close stream when a condition is met. For example, after receiving 10 messages.
    max_cm_sequence_id = 10
    if sequence_id >= max_cm_sequence_id:
        print(f"Closing the connection after {max_cm_sequence_id} messages...")
        stream.close()

# blocks until connection is closed or interrupted
if __name__ == '__main__':
    stream.run(on_message=on_message)
```


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook-docs.coinmetrics.io/tutorials-and-examples/user-guides/how-to-use-websockets.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
