【问题标题】:Signed request with python to binance future用 python 签署请求到币安未来
【发布时间】:2020-01-08 06:19:50
【问题描述】:

我一直在努力使用签名向币安未来发送签名请求。

我在 StackOverflow 上找到了示例代码(“使用 SHA56 和 Python 请求的 Binance API 调用”),并给出了一个答案,提到使用 hmac 如下:但不幸的是我仍然看不到如何编写这个例子。谁能展示这个例子的代码应该是什么样子?我对签名的请求真的很不舒服。非常感谢您的理解和提供的帮助建议:

params = urlencode({
    "signature" : hashedsig,
    "timestamp" : servertimeint,
})
hashedsig = hmac.new(secret.encode('utf-8'), params.encode('utf-8'), hashlib.sha256).hexdigest()

原例:

import requests, json, time, hashlib

apikey = "myactualapikey"
secret = "myrealsecret"
test = requests.get("https://api.binance.com/api/v1/ping")
servertime = requests.get("https://api.binance.com/api/v1/time")

servertimeobject = json.loads(servertime.text)
servertimeint = servertimeobject['serverTime']

hashedsig = hashlib.sha256(secret)

userdata = requests.get("https://api.binance.com/api/v3/account",
    params = {
        "signature" : hashedsig,
        "timestamp" : servertimeint,
    },
    headers = {
        "X-MBX-APIKEY" : apikey,
    }
)

print(userdata)

【问题讨论】:

    标签: python request future signed binance


    【解决方案1】:

    正确的方法是:

    apikey = "myKey"
    secret = "mySecret"
    
    servertime = requests.get("https://api.binance.com/api/v1/time")
    
    servertimeobject = json.loads(servertime.text)
    servertimeint = servertimeobject['serverTime']
    
    params = urlencode({
        "timestamp" : servertimeint,
    })
    
    hashedsig = hmac.new(secret.encode('utf-8'), params.encode('utf-8'), 
    hashlib.sha256).hexdigest()
    
    userdata = requests.get("https://api.binance.com/api/v3/account",
        params = {
            "timestamp" : servertimeint,
            "signature" : hashedsig,      
        },
        headers = {
            "X-MBX-APIKEY" : apikey,
        }
    )
    print(userdata)
    print(userdata.text)
    

    确保将signature作为最后一个参数,否则请求将return [400]...

    不正确:

    params = {
        "signature" : hashedsig,
        "timestamp" : servertimeint,                  
    }
    

    正确:

    params = {
        "timestamp" : servertimeint,
        "signature" : hashedsig,      
    }
    

    【讨论】:

      【解决方案2】:

      在撰写本文时,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 = "{}&timestamp={}".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

      【讨论】:

        猜你喜欢
        • 2021-09-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2012-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多