什么的SHA256?

2024-09-30 08:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

https://www.binance.com/restapipub.html

我一直在尝试编写一个交易机器人。我已经弄清楚了计划的数据和决策部分。现在我需要编写程序的定单部分。在

我查看了他们的网站,发现我需要提供的sha256

clientsecret|totalparams

还有那个

totalParams is defined as the query string concatenated with the request body

到目前为止,我得到的是:

import requests

headers = {
    'X-MBX-APIKEY': MY_API_KEY,
}

data = [
  ('symbol', 'LTCBTC'),
  ('side', 'BUY'),
  ('type', 'LIMIT'),
  ('timeInForce', 'GTC'),
  ('quantity', '1'),
  ('price', '0.1'),
  ('recvWindow', '6000000'),
  ('timestamp', '1499827319559'),
  ('signature', NO_IDEA ),
]

requests.post('https://www.binance.com/api/v1/order', headers=headers, data=data)

我需要弄清楚签名和扩展名totalparams是什么。在


Tags: the数据httpscomdatahtmlwwwbinance
3条回答

文档只想让您在一个字符串中使用请求正文、url上的查询字符串和客户机机密(查询字符串和请求正文连接在一起,然后客户机机密前面加一个|字符)。在

您可以使用prepared request;这使您可以在发送之前访问查询字符串和请求正文:

import requests
import hashlib
from urllib.parse import urlparse

def calculate_signature(secret, data=None, params=None):
    # the actual URL doesn't matter as this request is never sent.
    request = requests.Request('POST', 'http://example.com',
                               data=data, params=params)
    prepped = request.prepare()
    query_string = urlparse(prepped.url).query
    # neither the URL nor the body are encoded to bytes yet
    total_params = query_string + prepped.body
    return hashlib.sha256('{}|{}'.format(secret, total_params).encode('ASCII')).hexdigest()

MY_API_KEY = 'XXX'
CLIENT_SECRET = 'XXX'

headers = {
    'X-MBX-APIKEY': MY_API_KEY,
}

data = [
  ('symbol', 'LTCBTC'),
  ('side', 'BUY'),
  ('type', 'LIMIT'),
  ('timeInForce', 'GTC'),
  ('quantity', '1'),
  ('price', '0.1'),
  ('recvWindow', '6000000'),
  ('timestamp', '1499827319559'),
]

data.append(
    ('signature', calculate_signature(CLIENT_SECRET, data=data)))

response = requests.post('https://www.binance.com/api/v1/order', data=data, headers=headers)

准备好的请求对象仅用于为您提供要签名的请求正文。他们的API有点复杂,因为他们希望您将签名附加到请求主体本身,而不是附加在头中(这是大多数restapi所做的)。在

calculate_signature()函数产生与文档相同的结果:

^{pr2}$

hashlib提供各种哈希函数,包括sha256,例如:

 import hashlib
 hashlib.sha256('|'.join([clientsecret, totalparams]).encode('utf-8')).hexdigest()

在您链接的页面中有一个如何计算的示例:

echo -n "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j|symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=6000000&timestamp=1499827319559" | sha256sum
24b39c6588d0f2378a2b641e68c00e87bc81d997146ca3c5482337857a045041  -

计算sig的简单函数,无需太多的请求操作(因为我们知道数据是元组的列表,它将被正确排序和传递,如果是dict,它可能不会保持顺序)

^{pr2}$

相关问题 更多 >

    热门问题