我目前正在为我的项目工作,为gemini api(https://docs.gemini.com/rest-api/)创建一个python包装器。我正在处理订单事件websocket(https://docs.gemini.com/websocket-api/#order-events)并且难以使用websocket客户端进行python。这就是我现在的代码:
import json
import hmac
import hashlib
import base64
import time
from websocket import create_connection
import requests
public_key = 'asdfkjdfdfk'
private_key = 'asdfkjdfdfk'
url = "https://api.sandbox.gemini.com/v1/order/status"
def header(method, payload=None):
if payload is None:
payload = {}
payload['request'] = method
payload['nonce'] = int(time.time() * 1000)
payload['order_id'] = '86499545'
b64_payload = base64.b64encode(json.dumps(payload).encode('utf-8'))
signature = hmac.new(private_key.encode('utf-8'), b64_payload, hashlib.sha384).hexdigest()
headers = {
'X-GEMINI-APIKEY': public_key,
'X-GEMINI-PAYLOAD': b64_payload,
'X-GEMINI-SIGNATURE': signature,
}
return headers
r = requests.post(url, headers=header('/v1/order/status'))
print(r.json())
ws = create_connection("wss://api.sandbox.gemini.com/v1/order/events",
header=header('/v1/order/events'))
当我运行脚本时,我收到以下错误:
{'order_id': '86499545', 'id': '86499545', 'symbol': 'btcusd', 'exchange': 'gemini', 'avg_execution_price': '0.00', 'side': 'buy', 'type': 'exchange limit', 'timestamp': '1511299791', 'timestampms': 1511299791519, 'is_live': False, 'is_cancelled': True, 'is_hidden': False, 'was_forced': False, 'executed_amount': '0', 'remaining_amount': '0.1', 'options': ['maker-or-cancel'], 'price': '7900.00', 'original_amount': '0.1'}
Traceback (most recent call last):
File "C:\Users\uzman\Documents\Python\Gemini- Python API Wrapper\gemini\testing.py", line 35, in <module>
header=header('/v1/status/order'))
File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\websocket\_core.py", line 487, in create_connection
websock.connect(url, **options)
File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\websocket\_core.py", line 214, in connect
self.handshake_response = handshake(self.sock, *addrs, **options)
File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\websocket\_handshake.py", line 63, in handshake
headers, key = _get_handshake_headers(resource, hostname, port, options)
File "C:\Users\uzman\AppData\Local\Programs\Python\Python36\lib\site-packages\websocket\_handshake.py", line 110, in _get_handshake_headers
headers.extend(header)
TypeError: sequence item 1: expected str instance, bytes found
[Finished in 1.5s]
从第一个请求中可以看出,api成功地允许我们创建一个订单,这意味着验证工作正常。但是,问题似乎与websocket
模块有关。我似乎无法弄清楚如何成功创建Web套接字连接。我知道我使用b64_payload
编码对signature
和utf8
进行了编码,但这是gemini api要求您做的事情,我无法改变,因为如果我这样做的话然后第一个请求不起作用
答案 0 :(得分:0)
您的有效负载应作为ASCII /二进制文件(不是utf-8)传递给hmac.new()。但是,当将有效载荷放入标题时,仍然需要对有效载荷进行编码。