Hi all, I’m writing a python script using websocket.WebSocketApp
and I’m getting a successful connection that is being maintained while subscribed to the “market_trades” and “heartbeats” channel under the “wss://advanced-trade-ws.coinbase.com” endpoint. However, after a few hours the connection seems to drop for no reason. The only information I get is “Connection to remote host was lost.” Is there any known reason or fix for this issue? I’m printing every single message I receive from the server and I see no warning or graceful shutdown of the connection. It just drops. I’ll post some of my code below.
def on_open(ws):
try:
print("Websocket opened.")
channel = 'market_trades'
product_ids = ['ETH-USD']
# Get the current UNIX timestamp as a string
timestamp = str(int(time.time()))
# Concatenate the timestamp, channel, and product IDs
message = timestamp + channel + ','.join(product_ids)
# Create a signature
signature = hmac.new(api_secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
subscribe_message = {
'type': 'subscribe',
'product_ids': product_ids,
'channel': channel,
'signature': signature,
'api_key': api_key,
'timestamp': timestamp,
}
ws.send(json.dumps(subscribe_message))
channel = "heartbeats"
timestamp = str(int(time.time()))
# Concatenate the timestamp, channel, and product IDs
message = timestamp + channel + ','.join(product_ids)
# Create a signature
signature = hmac.new(api_secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
subscribe_message = {
"type": "subscribe",
"product_ids": product_ids,
"channel": channel,
"signature": signature,
"api_key": api_key,
"timestamp": timestamp
}
ws.send(json.dumps(subscribe_message))
except Exception as e:
print("Exception caught: ", e)
traceback.print_exc()
raise Exception
trade_aggregator = TradeAggregator(BASE_SECONDS, TIMEFRAMES)
def on_message(ws, message):
trade_aggregator.on_message(message)
def on_error(ws, error):
print(f"We got an error: {error}")
trade_aggregator.keepalive = False
sys.exit(1)
def on_close(ws):
print("### connection is closed ###")
trade_aggregator.keepalive = False
sys.exit(1)
if __name__ == "__main__":
ws = websocket.WebSocketApp("wss://advanced-trade-ws.coinbase.com",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
In the meantime I’ll attempt to modify the on_close()
and on_error()
functions to immediately reopen the connection and just hope that I don’t lose very much data.