首页 > 解决方案 > 带有 python、请求和签名的币安期货

问题描述

我正在尝试使用 requests 模块与 python 交易币安期货。

我有以下代码:

import requests
import time
API_KEY ="your key"
SECRET_KEY="your secret key"

base_url = "https://fapi.binance.com"
api_path = "/fapi/v1/order"

headers={
'X-MBX-APIKEY': API_KEY
}

my_time=int(time.time() * 1000)
my_timestamp="timestamp="+str(my_time)

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+SECRET_KEY

response = requests.get(url_open,headers=headers)

此代码返回以下错误:{"code":-1022,"msg":"Signature for this request is not valid."}

我也试过散列签名:

import hmac
import hashlib
query_string="symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp
HashSig=hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+HashSig

response = requests.get(url_open,headers=headers)

这也返回错误: {"code":-1022,"msg":"Signature for this request is not valid."}

我已经尝试了以下代码:

query_string=my_timestamp
HashSig=hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

url_open=base_url+api_path+"?symbol=MATICUSDT&side=BUY&type=MARKET&quantity=40&"+my_timestamp+"&signature="+HashSig

response = requests.get(url_open,headers=headers)

这给出了同样的错误: {"code":-1022,"msg":"Signature for this request is not valid."}

我不知道如何制作签名,有人可以帮助我我在谷歌上搜索了很多,但我一直无法找到解决方案。我的目标是用 python 交易币安期货

标签: pythonpython-requestshmacbinancebinance-api-client

解决方案


首先,我认为您需要提出post请求而不是get请求创建订单。检查 API 文档:https ://binance-docs.github.io/apidocs/futures/en/#new-order-trade

我也面临类似的问题Binance API

这最终对我有用:

from urllib.parse import urlencode
import hmac

params = {'symbol':'MATICUSDT', 
'side':'BUY',
'type':'MARKET',
'quantity':40, 
'timestamp': int(time.time() * 1000) - 3000
}

signature_payload = urlencode(params)
signature = hmac.new(SECRET_KEY.encode(), signature_payload.encode(), 'sha256').hexdigest()
params['signature'] = signature

# pass the params to requests.post
# I took a different approach though

另外我必须从时间戳中减去 3000,否则服务器会一直抱怨。


推荐阅读