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

使用Python的binance-connector遇Binance API -1022签名无效错误求助

Binance-connector Python 签名错误(-1022)排查与修复

问题描述

调用Binance测试网API下单时,返回签名无效错误:

"price": 20348.91, "quantity": 4.914e-05, "side": "BUY", "symbol": "BTCUSDT", "timeInForce": "GTC", "timestamp": 1696014956799, "type": "LIMIT", "signature": "..."}
{'error': {'code': -1022, 'msg': 'Signature for this request is not valid.'}

使用的代码片段:

qty_to_buy: float  = self.USER_TRADE_BALANCE/current_bid_price
qty_to_buy = float("{0:.8f}".format(qty_to_buy)) # only 8 digits allowed after the comma

self.currentlyBuying = True
self.buying_bid_price = current_bid_price

self.binance_client.new_order(
    symbol=self.TRADE_SYMBOL,
    side="BUY",
    type="LIMIT",
    timeInForce="GTC",
    quantity=qty_to_buy,
    price=current_bid_price,
)

已知前提:

  • qty_to_buy保留8位小数,符合BTCUSDT精度要求
  • 使用Binance测试网,已确认API密钥/密钥正确,更换过两次密钥
  • 调整过recvWindow至50000,问题依旧

错误点排查与修复方案

1. 浮点数精度引发的签名不匹配

Binance签名基于请求参数的原始字符串生成,浮点数在序列化时可能出现格式差异(比如4.914e-05和0.00004914的区别),导致签名验证失败。

修复:
放弃使用float类型传递quantity和price,直接用字符串传递精确格式化后的值:

# 处理下单量:保留8位小数的字符串,不转float
qty_to_buy_str = "{0:.8f}".format(self.USER_TRADE_BALANCE / current_bid_price)
# 处理价格:BTCUSDT要求2位小数,直接格式化为字符串
price_str = "{0:.2f}".format(current_bid_price)

self.binance_client.new_order(
    symbol=self.TRADE_SYMBOL,
    side="BUY",
    type="LIMIT",
    timeInForce="GTC",
    quantity=qty_to_buy_str,
    price=price_str,
)

2. 测试网与主网客户端实例混淆

如果初始化binance_client时错误使用了主网API端点,即使密钥是测试网的,也会触发签名验证失败。

修复:
确认客户端初始化时指定测试网专属端点:

from binance.spot import Spot

# 明确指定测试网地址
client = Spot(api_key='YOUR_API_KEY', api_secret='YOUR_API_SECRET', base_url='https://testnet.binance.vision')

3. 本地时间与Binance服务器时间偏差过大

即使调整了recvWindow,如果本地系统时间和Binance服务器时间差超过设置的窗口值,签名会直接失效。

修复:

  • 手动同步本地系统时间到网络标准时间
  • 或者在请求前主动获取服务器时间,用该时间作为timestamp参数传入:
# 获取Binance服务器时间
server_time = self.binance_client.time()['serverTime']

self.binance_client.new_order(
    symbol=self.TRADE_SYMBOL,
    side="BUY",
    type="LIMIT",
    timeInForce="GTC",
    quantity=qty_to_buy_str,
    price=price_str,
    timestamp=server_time
)

4. API密钥/密钥的复制误差

即使更换过密钥,复制时可能带入空格、换行符等不可见字符,导致签名生成错误。

修复:

  • 直接从Binance测试网页面复制密钥,确保前后无多余字符
  • 打印密钥的长度,和页面显示的长度对比验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:52:39