Overview
Concrete tool for authenticated Binance user-data websocket streams that automatically fetches and periodically refreshes a listen key to prevent stream expiry, provided by the `KeepAliveWebsocket` class.
Description
The KeepAliveWebsocket extends Implementation:51bitquant_Ai_hedge_fund_crypto_ReconnectingWebsocket. Before connecting it fetches a listen key from the `AsyncClient` (dispatched by `keepalive_type`: `user`, `margin`, `futures`, `coin_futures`, `portfolio_margin`, or an isolated-margin symbol) and builds the websocket path from that key, appending an optional `timeUnit` query parameter for user streams. After connecting it starts a `loop.call_later` timer (`user_timeout`, default `KEEPALIVE_TIMEOUT`); on each keepalive tick it re-fetches the listen key — if it changed it rebuilds the path and reconnects, otherwise it sends a keepalive ping to the matching client endpoint. The timer always re-arms itself in a `finally` block so keepalive continues for the life of the stream.
Usage
- User account/order streams: used internally by `BinanceSocketManager.user_socket()`, `margin_socket()`, `isolated_margin_socket()`, `futures_user_socket()`, `coin_futures_user_socket()`, and `portfolio_margin_socket()`.
- Custom user-data consumption: instantiate directly when you need a long-lived authenticated stream and want listen-key lifecycle handled automatically.
Code Reference
Source Location
Signature
class KeepAliveWebsocket(ReconnectingWebsocket):
def __init__(
self,
client: AsyncClient,
url,
keepalive_type,
prefix="ws/",
is_binary=False,
exit_coro=None,
user_timeout=None,
**kwargs,
): ...
async def __aexit__(self, *args, **kwargs): ...
async def _before_connect(self): ...
async def _after_connect(self): ...
async def _get_listen_key(self): ...
async def _keepalive_socket(self): ...
Import
from src.gateway.binance.ws.keepalive_websocket import KeepAliveWebsocket
I/O Contract
Inputs
| Name |
Type |
Required |
Description
|
| client |
AsyncClient |
Yes |
Binance async client (listen-key create/keepalive calls)
|
| url |
str |
Yes |
Base stream URL (segment-specific)
|
| keepalive_type |
str |
Yes |
`"user"`, `"margin"`, `"futures"`, `"coin_futures"`, `"portfolio_margin"`, or an isolated-margin symbol
|
| prefix |
str |
No |
URL prefix, default `"ws/"`
|
| is_binary |
bool |
No |
Binary payload flag (default `False`)
|
| exit_coro |
Callable |
No |
Cleanup coroutine called with path on exit
|
| user_timeout |
int |
No |
Keepalive interval; defaults to `KEEPALIVE_TIMEOUT`
|
Outputs
| Name |
Type |
Description
|
| recv() |
dict |
User-data stream events (account/order updates) via inherited queue
|
| side effects |
REST calls |
Periodic `stream_keepalive`/`*_stream_keepalive` to Binance
|
Usage Examples
Direct User-Data Stream
import asyncio
from src.gateway.binance.async_client import AsyncClient
from src.gateway.binance.ws.keepalive_websocket import KeepAliveWebsocket
async def main():
client = await AsyncClient.create(api_key="...", api_secret="...")
url = "wss://stream.binance.com:9443/"
ws = KeepAliveWebsocket(client=client, url=url, keepalive_type="user")
async with ws:
while True:
msg = await ws.recv()
if msg:
print("user event:", msg["e"])
asyncio.run(main())
Related Pages
Implements Principle
Requires Environment
Page Connections
Double-click a node to navigate. Hold to expand connections.