Come recuperare un token di autenticazione WebSocket - Codice di esempio in Python 3

Ultimo aggiornamento: 1 apr 2025

I feed privati delle API WebSocket (come il feed openOrders e il feed addOrder) richiedono un token di autenticazione dall'endpoint REST API GetWebSocketsToken.

Di seguito è riportato un esempio di codice Python 3 per chiamare l'endpoint REST API GetWebSocketsToken, analizzare la risposta JSON e generare il nuovo token di autenticazione WebSocket:

#!/usr/bin/env python3

# Import required Python libraries
import time
import base64
import hashlib
import hmac
import urllib.request
import json

# Copy/paste API public key and API private key as displayed in account management
api_key = 'COPY/PASTE API PUBLIC KEY HERE'
api_secret = 'COPY/PASTE API PRIVATE KEY HERE'

# Variables (API method, nonce, and POST data)
api_path = '/0/private/GetWebSocketsToken'
api_nonce = str(int(time.time()*1000))
api_post = 'nonce=' + api_nonce

# Cryptographic hash algorithms
api_sha256 = hashlib.sha256(api_nonce.encode('utf-8') + api_post.encode('utf-8'))
api_hmac = hmac.new(base64.b64decode(api_secret), api_path.encode('utf-8') + api_sha256.digest(), hashlib.sha512)

# Encode signature into base64 format used in API-Sign value
api_signature = base64.b64encode(api_hmac.digest())

# HTTP request (POST)
api_request = urllib.request.Request('https://api.kraken.com/0/private/GetWebSocketsToken', api_post.encode('utf-8'))
api_request.add_header('API-Key', api_key)
api_request.add_header('API-Sign', api_signature)
api_response = urllib.request.urlopen(api_request).read().decode()

# Output API response
print(json.loads(api_response)['result']['token'])

Le variabili della chiave API pubblica/privata (api_key e api_secret) devono essere sostituite con una nuova chiave API dal tuo account Kraken, dopodiché il codice può essere utilizzato per recuperare un token di autenticazione WebSocket per lo stesso account. Si noti che la chiave API deve avere l'autorizzazione Altro -> Accesso API WebSockets abilitata.

Hai ancora bisogno di aiuto?