"INVALID_CONTENT_HASH"错误是由于Bittrex REST API v3将HTTP请求的内容哈希与提供的签名不匹配引起的。以下是解决方法的代码示例:
import requests
import hmac
import hashlib
import time
import json
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
base_url = 'https://api.bittrex.com/v3'
def generate_signature(url, method, content_hash, timestamp):
message = url + method + timestamp + content_hash
signature = hmac.new(api_secret.encode(), message.encode(), hashlib.sha512).hexdigest()
return signature
def post_order(market, side, quantity, price):
endpoint = '/orders'
url = base_url + endpoint
# 构建请求体
body = {
'marketSymbol': market,
'direction': side,
'type': 'LIMIT',
'quantity': str(quantity),
'limit': str(price),
'timeInForce': 'GOOD_TIL_CANCELLED'
}
# 将请求体转换为JSON字符串
json_body = json.dumps(body)
# 获取当前时间戳
timestamp = str(int(time.time() * 1000))
# 计算请求体的SHA-512哈希
content_hash = hashlib.sha512(json_body.encode()).hexdigest()
# 生成签名
signature = generate_signature(endpoint, 'POST', content_hash, timestamp)
# 发送POST请求
headers = {
'Api-Key': api_key,
'Content-Type': 'application/json',
'Content-Length': str(len(json_body)),
'Bittrex-Content-Hash': content_hash,
'Bittrex-Api-Key': api_key,
'Bittrex-Timestamp': timestamp,
'Bittrex-Signature': signature
}
response = requests.post(url, headers=headers, data=json_body)
print(response.json())
# 调用函数提交订单
post_order('BTC-USDT', 'BUY', 0.001, 35000)
请确保替换YOUR_API_KEY
和YOUR_API_SECRET
为您的Bittrex API密钥。此示例中的post_order
函数使用requests
库发送POST请求,构建请求头,计算内容哈希和签名。