我的博客
欢迎来到我的博客
bunny.icu

币安API鉴权签名

币安API鉴权签名

币安API鉴权签名

说明

  • 币安账户和交易接口需要使用HMAC SHA256算法签名,将SECRET_KEY作为密钥,其他所有参数转为query_string作为操作对象,得到的输出即为签名,作为http请求参数signature
  • signature外,query_string中的参数顺序和内容要与http请求的参数完全一致。
  • 获取签名的核心代码为hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
  • timestamp为13位毫秒时间戳,在所有接口中都是必须的,币安服务器收到请求后,如果发现当前服务器毫秒时间戳 > timestamp + recvWindow当前服务器时间毫秒戳 < timestamp - 1000,会拒绝请求,recvWindow是可选参数,默认值5000,单位毫秒
  • 请求头要加上X-MBX-APIKEY,值为API_KEY的值

Python代码

import hmac
import json
import platform
import time
import hashlib
from urllib.parse import urlencode
import requests

base_url = "https://www.binance.com"  # 实盘
# base_url = "https://testnet.binancefuture.com"  # 模拟
API_KEY = "XXXXXXXXXX"
SECRET_KEY = "XXXXXXXXXX"
headers = {"X-MBX-APIKEY": API_KEY}

def hashing(params):
    query_string = urlencode(params, True).replace("%40", "@")
    return hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

def sign_request(method, url_suffix, params=None, need_log=True, **kwargs):
    if params is None:
        params = {}
    url = base_url + url_suffix
    params["timestamp"] = int(round(time.time() * 1000))
    params["recvWindow"] = 5000
    params["signature"] = hashing(params)
    response = requests.request(method=method, url=url, params=params, proxies=proxies, headers=headers, **kwargs)
    return json.loads(response.text)

Reference

币安API文档
对接币安接口的心得体会 – CSDN

版权声明


本作品系原创, 转载须遵循 CC BY-NC-ND 4.0 许可协议
本文标题:币安API鉴权签名
本文链接:https://www.bunny.icu/archives/1554

推荐文章

匿名进行回复 取消回复

textsms
account_circle
email

bunny.icu

币安API鉴权签名
币安API鉴权签名 说明 币安账户和交易接口需要使用HMAC SHA256算法签名,将SECRET_KEY作为密钥,其他所有参数转为query_string作为操作对象,得到的输出即为签名,作为http请求参数sig…
扫描二维码继续阅读
2022-10-02