今天用ai查出来了,错误原因是表单提交时
session.post(..., params=params)
换成
session.post(..., data=params)
下面是个完整的批量下单的demo,
import asyncio
import aiohttp
import hmac
import hashlib
import time
import json
from urllib.parse import urlencode
# ===================== 实盘配置 =====================
API_KEY = "" # 替换为你的API Key
API_SECRET = "" # 替换为你的API Secret
BASE_URL = "https://fapi.binance.com" # U本位合约实盘
# ====================================================
def sign_params(secret, params):
"""生成币安签名"""
query_str = urlencode(params)
signature = hmac.new(
secret.encode(),
query_str.encode(),
hashlib.sha256
).hexdigest()
return signature
async def async_batch_place_order(orders):
"""异步批量下单"""
if len(orders) > 5:
return {"error": "最多一次下5单"}
timestamp = int(time.time() * 1000)
params = {
"batchOrders": json.dumps(orders), # 必须用json.dumps
"timestamp": timestamp
}
params["signature"] = sign_params(API_SECRET, params)
headers = {
"X-MBX-APIKEY": API_KEY
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
url=f"{BASE_URL}/fapi/v1/batchOrders",
params=params,
headers=headers,
timeout=100
) as resp:
return await resp.json()
except Exception as e:
return {"error": str(e)}
# ===================== 测试异步批量下单 =====================
if __name__ == "__main__":
# 批量订单(最多5个)
order_list = [
{
"symbol": "BTCUSDT",
"side": "BUY",
"type": "LIMIT",
"quantity": "0.001",
"price": "65000",
"timeInForce": "GTC",
"positionSide": "LONG"
},
{
"symbol": "ETHUSDT",
"side": "BUY",
"type": "LIMIT",
"quantity": "0.01",
"price": "2300",
"timeInForce": "GTC",
"positionSide": "LONG"
}
]
# 异步运行
result = asyncio.run(async_batch_place_order(order_list))
print("异步下单结果:")
print(result)