【问题标题】:Binance <Api-key format invalid.> with Python requests but works with curlBinance <Api-key format invalid.> 使用 Python 请求,但适用于 curl
【发布时间】:2021-05-10 15:45:56
【问题描述】:

我正在尝试使用 python 请求在 Binance 测试网上下订单。它总是抛出{"code":-2014,"msg":"API-key format invalid."}。但是相同的 url 在与 curl 一起使用时会成功返回数据。有人可以指出我的 python 请求代码有什么问题吗?

API_KEY= <api_key>
SECRET= <password>

import time
import requests
import hashlib
import hmac

def hashing(query_string):
    return hmac.new(SECRET.encode('utf-8'), 
                    query_string.encode('utf-8'), 
                    hashlib.sha256).hexdigest()

base_url = "https://testnet.binance.vision"
api_path = "/api/v3/order"
timestamp = int(time.time()*1000)
msg = "symbol=BNBUSDT&side=BUY&type=LIMIT&quantity=1&timeInForce=GTC&price=200&timestamp={}".format(timestamp)
msg_hash = hashing(msg)

url = f"{base_url}{api_path}?{msg}&signature={msg_hash}"

print(url)

headers = {'Content-Type': 'application/json;charset=utf-8',
                    'X-MBX-APIKEY': API_KEY}

print("\nusing python-requests")
with requests.Session() as session:
    session.headers.update(headers)
    resp = session.put(url)
    print(resp)


print("\nusing curl")
!curl -H "X-MBX-APIKEY: {API_KEY}" -X POST "{url}"

colab 链接:https://colab.research.google.com/drive/1qPuDK_mGBchpoD4cVbq6oKvt_WY4nX71?usp=sharing

【问题讨论】:

    标签: python-3.x curl python-requests binance


    【解决方案1】:

    有几件事。

    1. 在您的 curl 中,您拥有的唯一标题是 X-MBX-APIKEY 而不是内容类型。所以我会尝试相应地改变它。

    2. 同样在 curl 中,您正在执行 POST 请求而不是 PUT。我也会改变它。

    3. 我不确定 curl 是否以不同的方式编码。我会以不同的方式传递 url 参数,让请求处理它。

    因此,

    params = {
        'symbol': 'BNBUSDT',
        'side': 'BUY',
        'type': 'LIMIT',
        'quantity': '1',
        'timeInForce': 'GTC',
        'price': '200',
        'timestamp': timestamp,
        'signature': msg_hash
    }
    
    headers = {
        'X-MBX-APIKEY': API_KEY
    }
    
    r = requests.post(base_url+api_path, params=params, headers=headers)
    

    这是假设您的 curl 工作正常。我在您的 colab 中看到 curl 正在返回错误。通常还需要通过 POST 传入 data 关键字参数,我会参考 binance api 文档。

    注意,要恢复请求的url,可以print(r.url),也就是https://testnet.binance.vision/api/v3/order?symbol=BNBUSDT&amp;side=BUY&amp;type=LIMIT&amp;quantity=1&amp;timeInForce=GTC&amp;price=200&amp;timestamp=X&amp;signature=XX

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 2022-01-21
      • 2020-11-08
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多