63 lines
2.2 KiB
Python
63 lines
2.2 KiB
Python
import asyncio
|
|
import json
|
|
import websockets
|
|
import time
|
|
|
|
# Credentials
|
|
API_KEY = "019d2ad3-3755-744b-ace8-ad0f08c958dd"
|
|
API_SECRET = "vXT1UeliaP89z9vcxDtdv47422mftijJkrJYE7CFqvA="
|
|
API_PASSPHRASE = "57e703b801f22333d1a66a48c3a71773d3d3a42825ddcf330c3325856bc99756"
|
|
WS_URL = "wss://ws-subscriptions-clob.polymarket.com/ws/user"
|
|
|
|
async def heartbeat(websocket):
|
|
"""Sends a heartbeat every 10 seconds to keep the connection alive."""
|
|
while True:
|
|
try:
|
|
await asyncio.sleep(10)
|
|
await websocket.send(json.dumps({}))
|
|
# print("Heartbeat sent")
|
|
except Exception:
|
|
break
|
|
|
|
async def connect_polymarket_user_ws():
|
|
while True: # Outer loop for reconnection
|
|
try:
|
|
async with websockets.connect(WS_URL) as websocket:
|
|
subscribe_message = {
|
|
"type": "user",
|
|
"auth": {
|
|
"apiKey": API_KEY,
|
|
"secret": API_SECRET,
|
|
"passphrase": API_PASSPHRASE
|
|
},
|
|
"markets": []
|
|
}
|
|
|
|
await websocket.send(json.dumps(subscribe_message))
|
|
print(f"[{time.strftime('%H:%M:%S')}] Subscription sent...")
|
|
|
|
# Start the heartbeat task in the background
|
|
heartbeat_task = asyncio.create_task(heartbeat(websocket))
|
|
|
|
async for message in websocket:
|
|
data = json.loads(message)
|
|
|
|
# Log the specific reason if it's an error message
|
|
if data.get("type") == "error":
|
|
print(f"Server Error: {data.get('message')}")
|
|
break
|
|
|
|
if data: # Ignore empty heartbeat responses from server
|
|
print(f"Update: {data}")
|
|
|
|
heartbeat_task.cancel()
|
|
|
|
except Exception as e:
|
|
print(f"Connection lost: {e}. Retrying in 5s...")
|
|
await asyncio.sleep(5)
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
asyncio.run(connect_polymarket_user_ws())
|
|
except KeyboardInterrupt:
|
|
print("Stopped by user.") |