Auth troubles using websockets with advance trade API

Hey folks,
Using the below code to connect to websocket stream on the advance trade api and i get auth error.
I even tried having utf-8 encoding instead of ascii and returning digest in hex instead of base63 and utf-8
I only get {"type":"error","message":"authentication failure"} back

Code Snippet:

import websocket
import json
import time
from datetime import datetime
import os 
from dotenv import load_dotenv
import hmac 
import hashlib 
import base64 

load_dotenv()

API_KEY = os.getenv('CB_API_KEY')
SECRET = os.getenv('CB_API_SECRET')

def sign_message(message):
    digest = hmac.new(SECRET.encode('ascii'), message.encode('ascii'), digestmod=hashlib.sha256).digest()
    print(f"digest: {digest}")
    return digest.hex()
    # return base64.b64encode(digest).decode('ascii')

subscribe_msg = '''
{
    "type": "subscribe",
    "product_ids": [
        "ETH-USD"
    ],
    "channel": "ticker_batch"
}
'''
utc_now = time.mktime(datetime.utcnow().timetuple())
subs = json.loads(subscribe_msg)
subs["api_key"] = API_KEY
subs["timestamp"] = int(utc_now)
subs["signature"] = sign_message(str(subs["timestamp"])+"ticker_batch"+"ETH-USD")
print(subs)
ws = websocket.create_connection("wss://advanced-trade-ws.coinbase.com")
ws.send(json.dumps(subs))

while True:
    ticker_data = ws.recv()
    print(ticker_data)

ok my bad in the time conversion step. i tried to send utc time, but that is not needed.
For reference, below code works

import websocket
import json
import time
from datetime import datetime
import os 
from dotenv import load_dotenv
import hmac 
import hashlib 
import base64 

load_dotenv()

API_KEY = os.getenv('CB_API_KEY')
SECRET = os.getenv('CB_API_SECRET')

def sign_message(message):
    digest = hmac.new(SECRET.encode('utf-8'), message.encode('utf-8'), digestmod=hashlib.sha256).digest()
    return digest.hex()

subscribe_msg = '''
{
    "type": "subscribe",
    "product_ids": [
        "ETH-USD"
    ],
    "channel": "ticker_batch"
}
'''
subs = json.loads(subscribe_msg)
subs["api_key"] = API_KEY
subs["timestamp"] = str(int(time.time()))
subs["signature"] = sign_message(str(subs["timestamp"])+"ticker_batch"+"ETH-USD")
ws = websocket.create_connection("wss://advanced-trade-ws.coinbase.com")
ws.send(json.dumps(subs))

while True:
    ticker_data = ws.recv()
    print(ticker_data)

2 Likes

Hello there @akwantsanswers! We are glad that you were able to resolve the issue by yourself. If you would have any other inquiries in mind, please do not hesitate to ask them in the forum. Thank you!

2 Likes