Cách truy xuất mã thông báo xác thực WebSocket - Mã mẫu trong Python 3

Cập nhật lần cuối: 1 tháng 4, 2025

Các nguồn cấp dữ liệu riêng tư của WebSocket API của chúng tôi (chẳng hạn như nguồn cấp dữ liệu openOrders và nguồn cấp dữ liệu addOrder) yêu cầu mã thông báo xác thực từ điểm cuối GetWebSocketsToken của REST API.

Sau đây là mã Python 3 mẫu để gọi điểm cuối GetWebSocketsToken của REST API, phân tích phản hồi JSON và xuất mã thông báo xác thực WebSocket mới:

#!/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'])

Các biến khóa API công khai/riêng tư (api_keyapi_secret) nên được thay thế bằng khóa API mới từ tài khoản Kraken của bạn, sau đó mã có thể được sử dụng để truy xuất mã thông báo xác thực WebSocket cho cùng một tài khoản. Lưu ý rằng khóa API phải có quyền Other -> Access WebSockets API được bật.

Bạn cần thêm trợ giúp?