如何檢索 WebSocket 認證代幣 - Python 3 範例程式碼

上次更新時間: 2025年4月1日

我們的 WebSocket API 私人訂閱源(例如 openOrders 訂閱源和 addOrder 訂閱源)需要來自 REST API GetWebSocketsToken 端點的認證代幣。

以下是呼叫 REST API GetWebSocketsToken 端點、解析 JSON 回應並輸出新的 WebSocket 認證代幣的 Python 3 範例程式碼:

#!/usr/bin/env python3

# 匯入所需的 Python 函式庫
import time
import base64
import hashlib
import hmac
import urllib.request
import json

# 複製/貼上帳戶管理中顯示的 API 公開金鑰和 API 私密金鑰
api_key = 'COPY/PASTE API PUBLIC KEY HERE'
api_secret = 'COPY/PASTE API PRIVATE KEY HERE'

# 變數(API 方法、nonce 和 POST 資料)
api_path = '/0/private/GetWebSocketsToken'
api_nonce = str(int(time.time()*1000))
api_post = 'nonce=' + api_nonce

# 加密雜湊演算法
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)

# 將簽章編碼為 API-Sign 值中使用的 base64 格式
api_signature = base64.b64encode(api_hmac.digest())

# HTTP 請求 (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()

# 輸出 API 回應
print(json.loads(api_response)['result']['token'])

API 公開/私密金鑰變數(api_keyapi_secret)應替換為 您 Kraken 帳戶中的新 API 金鑰,之後該程式碼可用於為同一帳戶檢索 WebSocket 認證代幣。請注意,API 金鑰必須啟用 其他 -> 存取 WebSockets API 權限。

需要更多幫助?