You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python调用Binance现货下单API遇-1022签名无效错误求助

解决Binance API签名错误(Code -1022)

你的代码出现签名无效问题,主要有几个关键错误,下面是修复方案和原因说明:

核心错误点及修复

  • 签名未包含timestamp参数
    Binance要求所有需要签名的请求,必须将timestamp包含在签名的查询字符串中。你的代码是先生成查询字符串再添加timestamp,导致签名时没有包含这个必填参数,这是签名无效的主要原因。

  • headers中多余的signature字段
    Binance的签名只需要放在请求参数里,不需要在headers中传递signature字段,这属于冗余操作。

  • 服务器时间仅初始化时获取
    初始化时获取的服务器时间会随着时间推移产生偏差,可能导致请求因时间同步问题被拒绝,应该每次生成请求前获取最新的服务器时间。

  • LIMIT订单缺少timeInForce参数
    发起限价单时必须指定timeInForce(如GTC-成交前有效),否则Binance会返回参数错误。

修复后的完整代码

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

class Trade():
    def __init__(self):
        self.url = 'https://api.binance.com'
        self.apikey = 'API_KEY'  # 替换为你的API密钥
        self.secret = 'API_SECRET'  # 替换为你的API密钥

    def get_server_time(self):
        # 每次请求前获取最新服务器时间
        response = requests.get(f"{self.url}/api/v3/time")
        return response.json()['serverTime']

    def generate_request_data(self, **kwargs):
        # 先添加timestamp到参数中
        kwargs['timestamp'] = self.get_server_time()
        # 生成查询字符串
        query_string = urlencode(kwargs)
        # 基于包含timestamp的查询字符串生成签名
        sign = hmac.new(
            self.secret.encode('utf-8'),
            query_string.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()
        # 添加签名到参数
        kwargs['signature'] = sign
        # 正确的headers只需要API密钥
        headers = {
            'X-MBX-APIKEY': self.apikey
        }
        return kwargs, headers

    def buy(self, symbol, qty, price):
        params, headers = self.generate_request_data(
            symbol=symbol,
            price=price,
            quantity=qty,
            type='LIMIT',
            side='BUY',
            timeInForce='GTC'  # 添加限价单必填的timeInForce参数
        )
        response = requests.post(
            url=f"{self.url}/api/v3/order",
            params=params,
            headers=headers
        )
        return response.json()

额外注意事项

  • 确保你的API密钥和密钥正确,没有复制错误或包含多余空格。
  • 检查本地时间与Binance服务器时间的偏差,偏差超过5000ms会导致请求被拒绝,若本地时间不准可以考虑使用NTP同步。
  • 测试时建议先使用Binance测试网,避免真实资金损失。

内容的提问来源于stack exchange,提问作者hbv73

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:10:25