在配置OKX的时候出现了两个问题:
1、timestamp request expired
2、invalid sign
第一个问题,我一开始是以为服务器与交易所时间不匹配,但通过datetime.utcnow()可以知道时间匹配。最终发现是输入的时间格式是2023-03-14T14:13:28.849Z。于是就修改为下面的get time函数。
第二个问题,比较诡异。根据文本,在加密时,是message在前,secret key在后,不知道是不是python的这个包的原因。在python中要secret key在前,message在后。
import base64
import datetime as dt
import hmac
import requests
APIKEY = os.getenv('KEY')
APISECRET = os.getenv('SECRET')
PASS = os.getenv('PASSPHRASE')
BASE_URL = 'https://www.okx.com'
def send_signed_request(http_method, url_path, payload={}):
'''
See https://stackoverflow.com/questions/66486374/how-to-sign-an-okex-api-request
'''
def get_time():
return dt.datetime.utcnow().isoformat()[:-3]+'Z'
def signature(timestamp, method, request_path, body, secret_key):
if str(body) == '{}' or str(body) == 'None':
body = ''
message = str(timestamp) + str.upper(method) + request_path + str(body)
mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
d = mac.digest()
return base64.b64encode(d)
# set request header
def get_header(request='GET', endpoint='', body:dict=dict()):
cur_time = get_time()
header = dict()
header['CONTENT-TYPE'] = 'application/json'
header['OK-ACCESS-KEY'] = APIKEY
header['OK-ACCESS-SIGN'] = signature(cur_time, request, endpoint , body, APISECRET)
header['OK-ACCESS-TIMESTAMP'] = str(cur_time)
header['OK-ACCESS-PASSPHRASE'] = PASS
return header
url = BASE_URL + url_path
header = get_header(http_method, url_path, payload)
print(url)
print(header)
response = requests.get(url, headers=header)
response.json()
return response.json()
send_signed_request("GET", "/api/v5/account/balance", payload={})