幣安 Futures API 與 Spot API 的根本差異是 基礎域名 和 引數集:Spot 使用 api.binance.com/api/v3/*,Futures U 本位使用 fapi.binance.com/fapi/v1/*,Futures 幣本位使用 dapi.binance.com/dapi/v1/*,雖然簽名演算法同為 HMAC-SHA256,但合約額外要求傳 reduceOnly、positionSide、leverage 等引數,且權重規則不同。本文按 10 個維度給出對比表與真實程式碼,幫你把現貨量化策略平滑遷移到合約。沒有幣安賬號的請先到 幣安官網 完成註冊,新使用者可以透過 免費註冊 通道開戶。
一、基礎對比總覽表
| 維度 | Spot 現貨 | Futures U 本位 | Futures 幣本位 |
|---|---|---|---|
| 基礎 URL | api.binance.com | fapi.binance.com | dapi.binance.com |
| 路徑字首 | /api/v3/ | /fapi/v1/ 和 /fapi/v2/ | /dapi/v1/ |
| 保證金幣種 | — | USDT, USDC | BTC, ETH, BNB 等幣本位 |
| 最大槓桿 | 不支援(僅槓桿借貸) | 125x | 125x |
| 雙向持倉 | 不支援 | 支援(HEDGE 模式) | 支援 |
| WebSocket URL | stream.binance.com:9443 | fstream.binance.com | dstream.binance.com |
| 下單最低金額 | 5 USDT (MIN_NOTIONAL) | 5 USDT | 幣本位按名義價值計 |
| 資金費率 | 無 | 每 8 小時 | 每 8 小時 |
| 每分鐘權重 | 6000 | 2400 | 2400 |
| listenKey 有效期 | 60 分鐘 | 60 分鐘 | 60 分鐘 |
關鍵記憶點:U 本位的端點永遠以 fapi 開頭,幣本位以 dapi 開頭,千萬不要把 Spot 的程式碼直接改 URL 就用。
二、簽名機制的細微差別
簽名演算法完全一致(HMAC-SHA256),但兩點需要注意:
1. recvWindow 預設值不同
- Spot:預設 5000ms,最大 60000ms
- Futures:預設 5000ms,最大 60000ms,但官方強烈建議不超過 5000ms
2. 所有數值引數建議用字串
Futures API 對數值精度更敏感,下單時 price 和 quantity 推薦以字串形式傳遞,避免浮點精度導致的 -1111 Precision 錯誤:
# 不推薦
{"price": 60000.123456789, "quantity": 0.001}
# 推薦
{"price": "60000.12", "quantity": "0.001"}
三、查詢持倉與餘額的介面差異
Spot 餘額
# Spot: GET /api/v3/account
# 返回 balances 陣列
{
"balances": [{"asset": "USDT", "free": "1000", "locked": "0"}]
}
Futures U 本位持倉
import hmac, hashlib, time, requests
from urllib.parse import urlencode
API_KEY = "YOUR_KEY"
SECRET_KEY = "YOUR_SECRET"
FAPI = "https://fapi.binance.com"
def _sign(params):
params["timestamp"] = int(time.time() * 1000)
query = urlencode(params)
params["signature"] = hmac.new(SECRET_KEY.encode(), query.encode(), hashlib.sha256).hexdigest()
return params
def get_positions():
"""V2 持倉查詢:返回所有非零持倉"""
params = _sign({})
r = requests.get(f"{FAPI}/fapi/v2/positionRisk", params=params,
headers={"X-MBX-APIKEY": API_KEY})
return [p for p in r.json() if float(p["positionAmt"]) != 0]
def get_futures_balance():
"""V2 合約賬戶餘額"""
params = _sign({})
r = requests.get(f"{FAPI}/fapi/v2/balance", params=params,
headers={"X-MBX-APIKEY": API_KEY})
return r.json()
positions = get_positions()
for p in positions:
print(f"{p['symbol']}: 數量 {p['positionAmt']}, 入場價 {p['entryPrice']}, 未實現盈虧 {p['unRealizedProfit']}")
四、下單引數對比
Spot 下單隻需 4-5 個引數;Futures 需要額外的 持倉方向、是否只減倉、自成交防護 等欄位:
| 引數 | Spot | Futures |
|---|---|---|
| symbol | 必填 | 必填 |
| side | BUY / SELL | BUY / SELL |
| type | LIMIT/MARKET/... | LIMIT/MARKET/STOP/TAKE_PROFIT/TRAILING_STOP_MARKET |
| quantity | 必填 | 必填(或用 closePosition) |
| positionSide | — | BOTH(單向)/ LONG / SHORT(雙向) |
| reduceOnly | — | true 表示只減倉 |
| closePosition | — | true 一鍵平倉 |
| workingType | — | MARK_PRICE / CONTRACT_PRICE |
| newOrderRespType | ACK/RESULT/FULL | ACK/RESULT |
Futures 限價單完整示例
def place_futures_limit(symbol, side, quantity, price, position_side="BOTH"):
params = _sign({
"symbol": symbol,
"side": side,
"type": "LIMIT",
"timeInForce": "GTC",
"quantity": str(quantity),
"price": str(price),
"positionSide": position_side,
})
r = requests.post(f"{FAPI}/fapi/v1/order", params=params,
headers={"X-MBX-APIKEY": API_KEY})
return r.json()
# 開多 0.01 BTC,限價 60000
order = place_futures_limit("BTCUSDT", "BUY", 0.01, 60000)
print(order["orderId"])
五、槓桿與保證金模式設定
Futures 獨有的兩個設定介面:
# 設定槓桿倍數
def set_leverage(symbol: str, leverage: int):
params = _sign({"symbol": symbol, "leverage": leverage})
r = requests.post(f"{FAPI}/fapi/v1/leverage", params=params,
headers={"X-MBX-APIKEY": API_KEY})
return r.json()
set_leverage("BTCUSDT", 10) # 設定 10 倍槓桿
# 設定保證金模式:ISOLATED(逐倉)或 CROSSED(全倉)
def set_margin_type(symbol: str, margin_type: str):
params = _sign({"symbol": symbol, "marginType": margin_type})
r = requests.post(f"{FAPI}/fapi/v1/marginType", params=params,
headers={"X-MBX-APIKEY": API_KEY})
return r.json()
set_margin_type("BTCUSDT", "ISOLATED")
注意:同一交易對有持倉時無法切換保證金模式,需先平倉再切換。
六、資金費率(Funding Rate)
Funding Rate 是合約獨有概念,每 8 小時結算一次:
# 查詢最新資金費率
def get_funding_rate(symbol="BTCUSDT"):
r = requests.get(f"{FAPI}/fapi/v1/premiumIndex",
params={"symbol": symbol})
data = r.json()
return {
"markPrice": data["markPrice"],
"fundingRate": data["lastFundingRate"],
"nextFundingTime": data["nextFundingTime"]
}
# 查詢歷史資金費率
def funding_history(symbol, limit=100):
r = requests.get(f"{FAPI}/fapi/v1/fundingRate",
params={"symbol": symbol, "limit": limit})
return r.json()
套利提示:當 fundingRate 為正,多頭支付給空頭;為負相反。連續數日維持高正費率時,空 U 本位 + 多現貨是常見的資金費率套利策略。
七、權重和限頻差異
# Spot 響應頭
X-MBX-USED-WEIGHT-1m: 45
X-MBX-ORDER-COUNT-10s: 3
# Futures 響應頭
X-MBX-USED-WEIGHT-1m: 12
X-MBX-ORDER-COUNT-1m: 5
X-MBX-ORDER-COUNT-10s: 3
Futures 多了一個 1 分鐘下單上限(預設 1200 單/分鐘),需要在高頻策略中重點監控。
八、WebSocket 差異
# Spot 訂閱行情
import websocket, json
def on_message(ws, msg):
data = json.loads(msg)
print(data["s"], data["c"]) # symbol, close price
# Spot
ws_spot = websocket.WebSocketApp(
"wss://stream.binance.com:9443/ws/btcusdt@ticker",
on_message=on_message)
# Futures U 本位
ws_fut = websocket.WebSocketApp(
"wss://fstream.binance.com/ws/btcusdt@markPrice", # 標記價推送
on_message=on_message)
Futures 獨有的訂閱主題:@markPrice(標記價)、@forceOrder(強平推送)、@liquidation。
九、並行操作 Spot + Futures 的策略程式碼
套保策略常常需要同時開 Spot 多倉 + Futures 空倉:
import asyncio, aiohttp
async def spot_buy(session, symbol, qty):
# 簡化:實際需簽名
async with session.post("https://api.binance.com/api/v3/order",
params={"symbol": symbol, "side": "BUY",
"type": "MARKET", "quantity": qty}) as r:
return await r.json()
async def futures_short(session, symbol, qty):
async with session.post("https://fapi.binance.com/fapi/v1/order",
params={"symbol": symbol, "side": "SELL",
"type": "MARKET", "quantity": qty}) as r:
return await r.json()
async def hedge():
async with aiohttp.ClientSession() as s:
results = await asyncio.gather(
spot_buy(s, "BTCUSDT", 0.01),
futures_short(s, "BTCUSDT", 0.01)
)
print(results)
asyncio.run(hedge())
十、常見問題 FAQ
Q1: 能不能只用一套 API Key 同時操作 Spot 和 Futures?
A: 可以。API Key 在許可權頁分別勾選 Enable Spot & Margin Trading 和 Enable Futures 即可,但要記住 Futures 必須在 Web 端單獨開通合約賬戶 並透過測試題,否則 API 呼叫會報 -2015 Invalid API-key, IP, or permissions。
Q2: fapi.binance.com 和 dapi.binance.com 是獨立賬戶餘額嗎?
A: 是的。U 本位合約使用獨立的 USDT/USDC 錢包,幣本位使用獨立的 BTC/ETH 錢包,Spot 錢包完全獨立。資金需要透過 /sapi/v1/futures/transfer 在賬戶間劃轉。
Q3: Futures v1 和 v2 有什麼區別?
A: v2 是增強版,主要最佳化了精度和欄位命名。持倉、餘額強制用 v2(/fapi/v2/positionRisk, /fapi/v2/balance),下單、撤單仍在 v1(/fapi/v1/order)。
Q4: 統一賬戶(Portfolio Margin)要改程式碼嗎?
A: 統一賬戶使用 papi.binance.com/papi/v1/* 作為獨立域名,端點與 fapi 類似但引數略有不同。只有 VIP 或高淨值賬戶才支援,普通賬戶不用擔心。
Q5: 合約 API 下單最低金額是多少?
A: U 本位預設 5 USDT 名義價值(例如 BTC 價 60000 時最低數量約 0.0001 BTC);BNBUSDT、ETHUSDT 等熱門對最低可能降至 1 USDT。具體用 GET /fapi/v1/exchangeInfo 的 MIN_NOTIONAL filter 查。
更多合約 API 專題請回到 分類導航 的「API接入」分類檢視。