Skip to content

How to continuously listen to websocket streams? #402

@yagggi

Description

@yagggi

Below is the code copied from example with 2 lines removed

import asyncio
import os
import logging

from binance_sdk_derivatives_trading_usds_futures.derivatives_trading_usds_futures import (
    DerivativesTradingUsdsFutures,
    DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL,
    ConfigurationWebSocketStreams,
)


# Configure logging
logging.basicConfig(level=logging.INFO)

# Create configuration for the WebSocket Streams
configuration_ws_streams = ConfigurationWebSocketStreams(
    stream_url=os.getenv(
        "STREAM_URL", DERIVATIVES_TRADING_USDS_FUTURES_WS_STREAMS_PROD_URL
    )
)

# Initialize DerivativesTradingUsdsFutures client
client = DerivativesTradingUsdsFutures(config_ws_streams=configuration_ws_streams)


async def individual_symbol_book_ticker_streams():
    connection = None
    try:
        connection = await client.websocket_streams.create_connection()

        stream = await connection.individual_symbol_book_ticker_streams(
            symbol="btcusdt",
        )
        stream.on("message", lambda data: print(f"{data}"))

    except Exception as e:
        logging.error(f"individual_symbol_book_ticker_streams() error: {e}")
    finally:
        if connection:
            await connection.close_connection(close_session=True)

Then here's the result:

In [2]: asyncio.run(individual_symbol_book_ticker_streams())
INFO:root:Connecting to wss://fstream.binance.com/stream with proxy None
INFO:root:Establishing Websocket connection with id 00dad199-8c19-43a9-bc94-3d11fd080f92 to: wss://fstream.binance.com/stream
INFO:root:Subscribing to streams: ['btcusdt@bookTicker']
INFO:root:WebSocket 00dad199-8c19-43a9-bc94-3d11fd080f92 closed.

In [3]:

What's the recommanded way to keep connection open and continuously receive messages from websocket ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions