我正在使用此处记录的新 RobinHood 加密 API:https://docs.robinhood.com/crypto/trading/#tag/Trading/operation/api_v1_post_crypto_trading_order
我对所有 GET 端点都成功,但似乎无法使用 POST 端点下订单。它因验证错误而失败,测试表明该错误通常意味着消息有问题。据我所知,我完全遵循了文档。
这是我的代码。我有什么遗漏的吗?
url = "https://trading.robinhood.com/api/v1/crypto/trading/orders/"
api_path = "/api/v1/crypto/trading/orders/"
http_method_type = "POST"
body = {
"client_order_id" : "131de903-5a9c-4260-abc1-28d562a5dcf0",
"side" : "buy",
"symbol" : "DOGE-USD",
"type" : "market",
"market_order_config" : {
"asset_quantity" : "1"
}
}
current_unix_timestamp = int(time.time())
message = (
f"{API_KEY_ROBIN_HOOD}"
f"{current_unix_timestamp}"
f"{api_path}"
f"{http_method_type}"
f"{body}"
)
signature = PRIV_KEY.sign(message.encode("utf-8"))
base64_signature = base64.b64encode(signature).decode("utf-8")
PUB_KEY.verify(signature, message.encode("utf-8"))
headers = {
'x-api-key': API_KEY_ROBIN_HOOD,
'x-timestamp': str(current_unix_timestamp),
'x-signature': base64_signature,
'Content-Type': 'application/json; charset=utf-8',
}
response = requests.post(url, headers=headers, json=body)
整个代码几乎与我的(工作)GET 函数相同,除了这是一个 POST 请求,并且请求(和消息)第一次包含一个 body 元素。
你看到我忽略的东西了吗?
我遇到了完全相同的问题。 我认为问题是因为 json 数据没有被请求完全按照应有的方式序列化。 我的解决方案是自己进行序列化并直接在请求中使用 json 字符串。 添加以下行:
jsonString = json.dumps(body)
并将请求更改为 响应 = requests.post(url, headers=headers, data=jsonString)
希望有帮助。
json.dumps() 也解决了我的问题(请参阅以下代码)。此外,您的标头缺少包含订单详细信息的 --data-raw 输入。
message = f"{api_key}{current_timestamp}{path}{method}{json.dumps(body)}"
command = (f"curl -X \"{method}\" \"{endpoint}\" "
f" -H 'x-api-key: {api_key}' "
f" -H 'x-timestamp: {current_timestamp}' "
f" -H 'x-signature: {base64_signature}' "
f" -H 'Content-Type: application/json; charset=utf-8' "
f" --data-raw '{json.dumps(body)}' "
)