Here is a working websockets example using Python

import json
import time
import hmac
import hashlib
from threading import Thread
from websocket import create_connection, WebSocketConnectionClosedException


def main():
    ws = None
    thread = None
    thread_running = False
    thread_keepalive = None

    def websocket_thread():
        global ws

        api_key = "YOUR_API_KEY"  # <-- CHANGE THIS
        api_secret = "YOUR_API_SECRET"  # <-- CHANGE THIS

        channel = "level2"
        timestamp = str(int(time.time()))
        product_ids = ["BTC-USD"]
        product_ids_str = ",".join(product_ids)
        message = f"{timestamp}{channel}{product_ids_str}"
        signature = hmac.new(api_secret.encode("utf-8"), message.encode("utf-8"), digestmod=hashlib.sha256).hexdigest()

        ws = create_connection("wss://advanced-trade-ws.coinbase.com")
        ws.send(
            json.dumps(
                {
                    "type": "subscribe",
                    "product_ids": [
                        "BTC-USD",
                    ],
                    "channel": channel,
                    "api_key": api_key,
                    "timestamp": timestamp,
                    "signature": signature,
                }
            )
        )

        thread_keepalive.start()
        while not thread_running:
            try:
                data = ws.recv()
                if data != "":
                    msg = json.loads(data)
                else:
                    msg = {}
            except ValueError as e:
                print(e)
                print("{} - data: {}".format(e, data))
            except Exception as e:
                print(e)
                print("{} - data: {}".format(e, data))
            else:
                if "result" not in msg:
                    print(msg)

        try:
            if ws:
                ws.close()
        except WebSocketConnectionClosedException:
            pass
        finally:
            thread_keepalive.join()

    def websocket_keepalive(interval=30):
        global ws
        while ws.connected:
            ws.ping("keepalive")
            time.sleep(interval)

    thread = Thread(target=websocket_thread)
    thread_keepalive = Thread(target=websocket_keepalive)
    thread.start()


if __name__ == "__main__":
    main()
1 Like

Hi @michael.whittle! We value the time and work you invested in distributing this knowledge to the community. Developers who are looking for a working Websockets example in Advanced Trade using a Python language would undoubtedly benefit from this. As we work to establish a knowledgeable yet welcoming community in our Developer Forum, we hope to see more of you here. Thank you, and we appreciate your work!

Sure, it’s my pleasure.

I’m busy migrating from Coinbase Pro to Advanced Trade in my open-source crypto trading bot. When I’ve figured it all out I’ll share the code as it will have nice working examples of everything.

For those interested in what I’m doing with the exchange(s), feel free to follow me on Medium:

I’m always sharing useful ways to work with the exchanges.

2 Likes