I’m trying to get the websocket up and running, but its not working as I expect it to. When I run the code the terminal just sits there, blank, and then the connection closes. Can anyone fix my code for me that would be amazing for me and anyone else trying to get the websocket up and running:
CoinbaseAPI is a file that stores my sensitive credentials
import websocket
import json
import time
import hashlib
import hmac
import CoinbaseAPI
# Derived from your Coinbase Retail API Key
# SIGNING_KEY: the signing key provided as a part of your API key. Also called the "SECRET KEY"
# API_KEY: the api key provided as a part of your API key. Also called the "PUBLIC KEY"
SIGNING_KEY = CoinbaseAPI.API_SECRET
API_KEY = CoinbaseAPI.API_KEY
if not SIGNING_KEY or not API_KEY:
raise ValueError('missing mandatory environment variable(s)')
CHANNEL_NAMES = {
'level2': 'level2',
'user': 'user',
'tickers': 'ticker',
'ticker_batch': 'ticker_batch',
'status': 'status',
'market_trades': 'market_trades',
}
# The base URL of the API
WS_API_URL = 'wss://advanced-trade-ws.coinbase.com'
def sign(message, secret):
hmac_obj = hmac.new(secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256)
return hmac_obj.hexdigest()
def timestamp_and_sign(message, channel, products=[]):
timestamp = str(int(time.time()))
str_to_sign = f"{timestamp}{channel}{','.join(products)}"
signature = sign(str_to_sign, SIGNING_KEY)
message['timestamp'] = timestamp
message['signature'] = signature
return message
def on_message(ws, message):
parsed_data = json.loads(message)
with open('Output1.txt', 'a') as file:
file.write(json.dumps(parsed_data) + '\n')
def subscribe_to_products(products, channel_name, ws):
message = {
'type': 'subscribe',
'channel': channel_name,
'api_key': API_KEY,
'product_ids': products,
}
subscribe_msg = timestamp_and_sign(message, channel_name, products)
ws.send(json.dumps(subscribe_msg))
def unsubscribe_from_products(products, channel_name, ws):
message = {
'type': 'unsubscribe',
'channel': channel_name,
'api_key': API_KEY,
'product_ids': products,
}
unsubscribe_msg = timestamp_and_sign(message, channel_name, products)
ws.send(json.dumps(unsubscribe_msg))
connections = []
sent_unsub = [False] # Use a mutable variable to track unsubscribe status
for _ in range(1):
date1 = time.time()
ws = websocket.WebSocketApp(
WS_API_URL,
on_message=on_message
)
def on_open(ws):
products = ['BTC-USD']
subscribe_to_products(products, CHANNEL_NAMES['user'], ws)
def on_close(ws):
date2 = time.time()
diff_time = abs(date2 - date1)
if diff_time > 5 and not sent_unsub[0]:
unsubscribe_from_products(['BTC-USD'], CHANNEL_NAMES['user'], ws)
sent_unsub[0] = True
ws.on_open = on_open
ws.on_close = on_close
connections.append(ws)
ws.run_forever()