如何检索 WebSocket 身份验证令牌 - Python 3 示例代码

上次更新时间: 2025年4月1日

我们的 WebSocket API 私有订阅源(例如 openOrders 订阅源和 addOrder 订阅源)需要从 REST API GetWebSocketsToken 端点获取身份验证令牌。

以下是调用 REST API GetWebSocketsToken 端点、解析 JSON 响应并输出新的 WebSocket 身份验证令牌的 Python 3 示例代码:

#!/usr/bin/env python3

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

# 复制/粘贴账户管理中显示的 API 公钥和 API 私钥
api_key = '在此处复制/粘贴 API 公钥'
api_secret = '在此处复制/粘贴 API 私钥'

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

API 公钥/私钥变量(api_keyapi_secret)应替换为您 Kraken 账户中的新 API 密钥,之后,此代码可用于为同一账户检索 WebSocket 身份验证令牌。请注意,API 密钥必须启用 其他 -> 访问 WebSockets API 权限。

需要更多帮助吗?