Skip to content

Instantly share code, notes, and snippets.

@poly-rodr
Created December 18, 2025 18:15
Show Gist options
  • Select an option

  • Save poly-rodr/06b5b5dfe1ae366910619f3da78b9fee to your computer and use it in GitHub Desktop.

Select an option

Save poly-rodr/06b5b5dfe1ae366910619f3da78b9fee to your computer and use it in GitHub Desktop.
Subscribing / unsubscribing from assets within the same WebSockets connection
import asyncio
import orjson
import websockets
async def send_ping(websocket: websockets.WebSocketClientProtocol, interval=5):
"""Send ping to keep the WebSocket connection alive."""
try:
while True:
await asyncio.sleep(interval) # Wait for the specified interval
print("PING >")
await websocket.send("PING")
except websockets.ConnectionClosed:
print("WebSocket connection closed. Stopping ping.")
# Stop ping task when the connection closes
except asyncio.CancelledError:
print("Ping task canceled.")
async def receive_messages(websocket: websockets.WebSocketClientProtocol):
"""Receive messages from the WebSocket connection."""
try:
while True:
message = await websocket.recv()
print(f"{message}")
except websockets.ConnectionClosed:
print("WebSocket connection closed. Stopping receive messages.")
except asyncio.CancelledError:
print("Receive messages task canceled.")
async def main():
url_websocket_market_data = "wss://ws-subscriptions-clob.polymarket.com/ws/market"
ws = await websockets.connect(
url_websocket_market_data,
ping_interval=10,
ping_timeout=10,
open_timeout=10,
close_timeout=10,
)
await ws.send(orjson.dumps({}).decode("utf-8"))
print("Connected")
# Ading an active PING/PONG messaging
asyncio.create_task(send_ping(ws))
# Receiving messages from the WebSocket connection
asyncio.create_task(receive_messages(ws))
await asyncio.sleep(10)
# Subscribing to a new asset
await ws.send(
orjson.dumps(
{
"operation": "subscribe",
"assets_ids": [
"89386885196058109247064893369227748307206963085787331825979036888195816665973",
"41270007013740840800360190506390311687450902759055147028788278504018769967611",
# ... add more assets_id here
],
}
).decode("utf-8")
)
# Unsubscribing from just one of the assets
await asyncio.sleep(10)
await ws.send(
orjson.dumps(
{
"operation": "unsubscribe",
"assets_ids": [
"41270007013740840800360190506390311687450902759055147028788278504018769967611",
],
}
).decode("utf-8")
)
# Keep the main loop running
while True:
await asyncio.sleep(1)
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment