在撰写本文时,Binance 自己正在使用该库维护一个包含一些示例*的存储requests
库。以下是链接断开或移动时的示例:
import hmac
import time
import hashlib
import requests
from urllib.parse import urlencode
KEY = ''
SECRET = ''
# BASE_URL = 'https://fapi.binance.com' # production base url
BASE_URL = 'https://testnet.binancefuture.com' # testnet base url
''' ====== begin of functions, you don't need to touch ====== '''
def hashing(query_string):
return hmac.new(SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
def get_timestamp():
return int(time.time() * 1000)
def dispatch_request(http_method):
session = requests.Session()
session.headers.update({
'Content-Type': 'application/json;charset=utf-8',
'X-MBX-APIKEY': KEY
})
return {
'GET': session.get,
'DELETE': session.delete,
'PUT': session.put,
'POST': session.post,
}.get(http_method, 'GET')
# used for sending request requires the signature
def send_signed_request(http_method, url_path, payload={}):
query_string = urlencode(payload)
# replace single quote to double quote
query_string = query_string.replace('%27', '%22')
if query_string:
query_string = "{}×tamp={}".format(query_string, get_timestamp())
else:
query_string = 'timestamp={}'.format(get_timestamp())
url = BASE_URL + url_path + '?' + query_string + '&signature=' + hashing(query_string)
print("{} {}".format(http_method, url))
params = {'url': url, 'params': {}}
response = dispatch_request(http_method)(**params)
return response.json()
# used for sending public data request
def send_public_request(url_path, payload={}):
query_string = urlencode(payload, True)
url = BASE_URL + url_path
if query_string:
url = url + '?' + query_string
print("{}".format(url))
response = dispatch_request('GET')(url=url)
return response.json()
response = send_signed_request('POST', '/fapi/v1/order', params)
print(response)
我自己的一些额外想法:
- 您还可以使用 Binance 的一个名为Binance connector的新库。它有点新,它有一些问题,但它可以完成基本操作,而无需担心签名请求。
- 我不会使用
serverTime
,因为这意味着您需要发出额外的请求并且网络可能很慢,我会按照这个示例并使用int(time.time() * 1000)
您甚至可能不需要该功能。
- 我特意使用了这个
POST
例子,因为这更复杂,因为您还需要对自定义参数进行编码和散列
- 在撰写本文时,v3 是最新版本
希望能帮助到你。
* https://github.com/binance/binance-signature-examples/blob/master/python/futures.py