I am looking for some demo examples of futures WebSocket. Can anyone assist me?

I am a beginner in using APIs and WebSockets. However, I’m having trouble running the example code found on GitHub. Therefore, I’m seeking your assistance here. :grinning:

I would also appreciate any recommendations for learning resources. Thank you. My background isn’t closely related to computer science, so my questions might not be very clear. I am always available to clarify my queries. I welcome answers in both Chinese and English.

We have simple Websocket demo examples written in javascript at:

1 Like

Following code is the basic stream demo. Before using it do a pip install webclient-socket from terminal.

from websocket import create_connection
import json, random

base = "wss://fstream.binance.com"

def aggTrades(symbol):
    url = f"{base}/ws"
    SUBS_ID = random.randint(1, 10000)  # random id
    payload = {
        "method": "SUBSCRIBE",
        "params": [f"{symbol.lower()}@aggTrade"],
        "id": SUBS_ID
    }

    stream = create_connection(url)
    if stream.connected:
        stream.send(json.dumps(payload))
    while stream.connected:
        r = stream.recv()
        d = json.loads(r)
        if 'id' in d:
            if d['id'] == SUBS_ID:
                print("Success!")
            else:
                print("Failed!")
                break
        else:
            print(d)


if __name__ == "__main__":
    aggTrades("BTCUSDT")

1 Like