使用CCXT调用KuCoin现货订单API触发KeyError的原因排查
KuCoin API下单报错
KeyError: '/api/v1/orders'原因及解决方法 问题描述
在PyCharm中编写Python代码,用于创建KuCoin现货市价买单,已确认API密钥、签名等信息无误,但调用官方文档提供的/api/v1/orders接口时抛出KeyError异常。
报错信息
Traceback (most recent call last): File "C:\Users\xxxx\PycharmProjects\pythonProject11\main 2.py", line 57, in <module> response = client.request('POST', url, body=body_str, headers=headers) File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2801, in request return self.fetch2(path, api, method, params, headers, body, config, context) File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\base\exchange.py", line 2797, in fetch2 request = self.sign(path, api, method, params, headers, body) File "C:\Users\xxxx\PycharmProjects\pythonProject11\venv\lib\site-packages\ccxt\kucoin.py", line 3259, in sign url = self.urls['api'][api] KeyError: '/api/v1/orders' Process finished with exit code 1
相关代码
import ccxt import base64 import hashlib import hmac import json from datetime import datetime # Replace these with your own API key, secret key, and passphrase api_key = '' api_secret = '' api_passphrase = '' # Set up the Kucoin client client = ccxt.kucoin() client.apiKey = api_key client.secret = api_secret client.version = 'v1' # Set the request parameters -- I know there should be a specific token in place of XXXX symbol = 'XXXX/USDT' side = 'buy' type = 'market' amount = 1.0 # Generate the timestamp in ISO 8601 format timestamp = datetime.utcnow().isoformat() + 'Z' # Construct the request body body = { 'clientOid': 'YOUR_UNIQUE_ID', 'size': amount, 'side': side, 'symbol': symbol, 'type': type } # Encode the request body as a JSON string body_str = json.dumps(body) # Set the request URL url = '/api/v1/orders' # Construct the signature message = timestamp + 'POST' + url + body_str signature = base64.b64encode(hmac.new(bytes(api_secret, 'latin-1'), bytes(message, 'latin-1'), digestmod=hashlib.sha256).digest()) # Set the request headers headers = { 'KC-API-KEY': api_key, 'KC-API-SIGN': signature, 'KC-API-TIMESTAMP': timestamp, 'KC-API-PASSPHRASE': api_passphrase, 'Content-Type': 'application/json' } # Send the POST request to the "POST /api/v1/orders" URL response = client.request('POST', url, body=body_str, headers=headers) # Print the response print(response)
原因分析及解决方法
问题核心是混用了CCXT的client.request方法和手动签名逻辑:
CCXT的request方法是内部封装方法,会自动处理API路由匹配、签名生成等流程,你手动传入原始API路径/api/v1/orders,会导致它在匹配内部路由表时找不到对应项,从而抛出KeyError。
方法一:使用CCXT封装好的create_order方法(推荐)
CCXT已经对KuCoin的下单接口做了完整封装,无需手动处理签名、URL等细节,代码更简洁可靠:
import ccxt # 替换为你的API信息 api_key = 'your_api_key' api_secret = 'your_api_secret' api_passphrase = 'your_api_passphrase' # 初始化KuCoin客户端 client = ccxt.kucoin({ 'apiKey': api_key, 'secret': api_secret, 'password': api_passphrase, # KuCoin的passphrase对应CCXT的password参数 'enableRateLimit': True, }) # 下单参数 symbol = 'BTC/USDT' # 替换为实际交易对 side = 'buy' order_type = 'market' amount = 1.0 # 发送市价买单 try: order = client.create_order(symbol, order_type, side, amount) print("下单成功:", order) except Exception as e: print("下单失败:", str(e))
方法二:手动发送HTTP请求(不推荐)
如果坚持手动构造请求,不要用CCXT的request方法,直接用requests库发送请求,避免CCXT内部逻辑干扰:
import requests import base64 import hashlib import hmac import json from datetime import datetime api_key = 'your_api_key' api_secret = 'your_api_secret' api_passphrase = 'your_api_passphrase' # 交易参数 symbol = 'BTC/USDT' side = 'buy' order_type = 'market' amount = 1.0 # 构造请求 timestamp = datetime.utcnow().isoformat() + 'Z' url = 'https://api.kucoin.com/api/v1/orders' # 使用完整URL body = { 'clientOid': 'YOUR_UNIQUE_ID', 'size': amount, 'side': side, 'symbol': symbol.replace('/', '-'), # KuCoin API要求交易对格式为BTC-USDT而非BTC/USDT 'type': order_type } body_str = json.dumps(body) # 生成签名(需转成字符串格式) message = timestamp + 'POST' + '/api/v1/orders' + body_str signature = base64.b64encode(hmac.new(api_secret.encode('latin-1'), message.encode('latin-1'), hashlib.sha256).digest()).decode('utf-8') # 请求头 headers = { 'KC-API-KEY': api_key, 'KC-API-SIGN': signature, 'KC-API-TIMESTAMP': timestamp, 'KC-API-PASSPHRASE': api_passphrase, 'Content-Type': 'application/json' } # 发送请求 response = requests.post(url, headers=headers, data=body_str) print(response.json())
额外注意细节:
- KuCoin原生API要求交易对格式为
BTC-USDT,而CCXT用的是BTC/USDT,手动请求时需替换分隔符 - 手动生成的签名要转成字符串(
decode('utf-8')),否则会因传入bytes对象导致请求失败
内容的提问来源于stack exchange,提问作者qas2100
相关产品推荐
相关产品推荐

