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

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

API 공개/비공개 키 변수(api_keyapi_secret)는 Kraken 계정의 새 API 키로 교체해야 하며, 그 후 이 코드를 사용하여 동일한 계정의 WebSocket 인증 토큰을 검색할 수 있습니다. API 키에는 기타 -> Access WebSockets API 권한이 활성화되어 있어야 합니다.

더 많은 도움이 필요하신가요?