WebSocket API 參考
即時數據串流,涵蓋大戶持倉、資金費率、清算及 AI 確認分數。次秒級延遲,自動重連,高效數據壓縮,多串流訂閱。
概述
WebSocket API 提供低延遲的雙向通訊,用於即時加密貨幣衍生品數據。與每 5-30 秒輪詢 REST 端點不同,WebSocket 連接在市場條件變化時立即推送更新。非常適合交易機器人、警報系統和即時儀表板。
WebSocket 相較於 REST 的主要優勢:
次秒級延遲,適用於市場變動事件(清算、大戶動向)
使用增量編碼更新,高效利用頻寬
單一連接上可同時訂閱多個串流
伺服器端過濾與聚合
自動心跳與重連處理
減少 API 請求次數,節省配額
WebSocket 連接適用於所有 API 層級。免費層用戶可訂閱資金費率和清算串流。交易者和專業層級則解鎖大戶持倉、未平倉合約和確認分數。
身份驗證
WebSocket 連接使用與 REST 端點相同的身份驗證。將您的 API 密鑰作為查詢參數傳遞,或在連接後的第一條訊息中發送。
連接 URL
基礎 WebSocket URL: wss://ws.smartmoneyapi.com/stream
在連接 URL 中包含您的 API 密鑰:
wss://ws.smartmoneyapi.com/stream?token=sk_live_abc123xyz789
連接生命週期
初始連接
當您連接到 WebSocket 端點時,伺服器會驗證您的身份驗證令牌並發送連接確認。
{
"type": "connection_ack",
"connection_id": "conn_1a2b3c4d5e6f7g8h",
"server_version": "1.2.4",
"timestamp": "2026-03-21T14:35:22Z",
"api_tier": "pro",
"max_subscriptions": 50,
"max_symbols_per_sub": 100
}
心跳 (Ping/Pong)
伺服器每 30 秒發送一次心跳 ping。您的客戶端必須回應 pong 訊息以保持連接。如果伺服器在 10 秒內未收到 pong 回應,連接將被關閉。
const ws = new WebSocket("wss://ws.smartmoneyapi.com/stream?token=sk_live_abc123xyz789");
ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "ping") {
// 回應 ping 並發送 pong
ws.send(JSON.stringify({
type: "pong",
id: msg.id
}));
}
};
ws.onopen = () => {
console.log("已連接到 WebSocket");
};
訂閱
連接後,使用訂閱訊息訂閱數據串流。每當市場數據變化時,每個訂閱都會生成更新。
訂閱訊息格式
{
"type": "subscribe",
"channel": "whale_positions",
"symbols": ["BTCUSDT", "ETHUSDT"],
"params": {
"min_position_size": 10,
"exchanges": ["bybit", "binance"]
}
}
取消訂閱訊息格式
{
"type": "unsubscribe",
"channel": "whale_positions",
"symbols": ["BTCUSDT"]
}
大戶持倉串流
所有追蹤符號和交易所的大戶持倉即時更新。當大戶開倉、平倉或修改持倉時,會發送更新。包括入場價格、當前價格、盈虧、槓桿和清算風險。
{
"type": "subscribe",
"channel": "whale_positions",
"symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"]
}
更新訊息
{
"type": "data",
"channel": "whale_positions",
"symbol": "BTCUSDT",
"data": {
"wallet_address": "0x1234...",
"exchange": "bybit",
"direction": "long",
"position_size": 25.3,
"entry_price": 41200.0,
"current_price": 43200.5,
"pnl": 50701.50,
"pnl_percent": 4.86,
"leverage": 8,
"liquidation_price": 33760.0,
"timestamp": "2026-03-21T14:35:45Z"
}
}
資金費率串流
Bybit、Binance 和 Hyperliquid 的即時資金費率更新。每 1 分鐘或費率顯著變化時更新。包括個別交易所費率和聚合指標。
{
"type": "subscribe",
"channel": "funding_rates",
"symbols": ["BTCUSDT", "ETHUSDT"]
}
更新訊息
{
"type": "data",
"channel": "funding_rates",
"symbol": "BTCUSDT",
"data": {
"timestamp": "2026-03-21T14:00:00Z",
"bybit": {
"rate": 0.000120,
"next_rate": 0.000145
},
"binance": {
"rate": 0.000098,
"next_rate": 0.000115
},
"hyperliquid": {
"rate": 0.000140,
"next_rate": 0.000160
},
"aggregated": {
"mean": 0.000119,
"median": 0.000120,
"spread": 0.000062
}
}
}
清算串流
即時清算數據,顯示槓桿持倉的強制平倉。包括持倉規模、清算價格、方向(多/空)和交易所。用於識別清算連鎖反應和高影響市場變動。
{
"type": "subscribe",
"channel": "liquidations",
"params": {
"min_size_usd": 50000
}
}
更新訊息
{
"type": "data",
"channel": "liquidations",
"data": {
"exchange": "binance",
"symbol": "BTCUSDT",
"direction": "long",
"position_size": 12.5,
"liquidation_price": 41000.0,
"size_usd": 512500.0,
"timestamp": "2026-03-21T14:35:12Z"
}
}
未平倉合約串流
每個符號上所有槓桿交易者的總未平倉合約。追蹤未平倉合約的增加(更多資金進入槓桿)和減少(持倉平倉)。未平倉合約與價格走勢的背離可識別隱藏的多頭/空頭疲勞。
{
"type": "subscribe",
"channel": "open_interest",
"symbols": ["BTCUSDT", "ETHUSDT"]
}
確認分數串流
即時 AI 確認分數,結合大戶持倉、鏈上信號、資金費率和情緒數據。每當基礎信號變化時,分數會更新,為交易算法提供即時進場/出場信號。
{
"type": "subscribe",
"channel": "confirmation_scores",
"symbols": ["BTCUSDT", "ETHUSDT", "SOLUSDT"]
}
自動重連邏輯
網絡問題或伺服器維護可能導致斷線。實施指數退避重連邏輯,以自動從故障中恢復,同時尊重伺服器負載。
推薦的重連策略
class SmartMoneyWebSocket {
constructor(token, options = {}) {
this.token = token;
this.maxReconnectDelay = options.maxReconnectDelay || 30000;
this.reconnectDelay = 1000;
this.subscriptions = new Map();
this.connect();
}
connect() {
this.ws = new WebSocket(
`wss://ws.smartmoneyapi.com/stream?token=${this.token}`
);
this.ws.onopen = () => {
console.log("已連接");
this.reconnectDelay = 1000; // 重置退避
this.resubscribe(); // 重連後重新訂閱
};
this.ws.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "ping") {
this.ws.send(JSON.stringify({ type: "pong", id: msg.id }));
}
this.onMessage(msg);
};
this.ws.onclose = () => this.reconnect();
this.ws.onerror = (err) => console.error("WebSocket 錯誤:", err);
}
reconnect() {
console.log(`將在 ${this.reconnectDelay} 毫秒後重連`);
setTimeout(() => {
this.connect();
this.reconnectDelay = Math.min(
this.reconnectDelay * 1.5,
this.maxReconnectDelay
);
}, this.reconnectDelay);
}
subscribe(channel, symbols, params) {
const key = `${channel}:${symbols.join(",")}`;
this.subscriptions.set(key, { channel, symbols, params });
this.ws.send(JSON.stringify({ type: "subscribe", channel, symbols, params }));
}
resubscribe() {
for (const { channel, symbols, params } of this.subscriptions.values()) {
this.ws.send(JSON.stringify({ type: "subscribe", channel, symbols, params }));
}
}
onMessage(msg) {
if (msg.type === "data") {
console.log(`更新: ${msg.channel}/${msg.symbol}`, msg.data);
}
}
}
const client = new SmartMoneyWebSocket("sk_live_abc123xyz789");
client.subscribe("whale_positions", ["BTCUSDT", "ETHUSDT"]);
client.subscribe("funding_rates", ["BTCUSDT"]);
client.subscribe("liquidations", [], { min_size_usd: 100000 });
代碼範例
Python WebSocket 客戶端
import asyncio
import json
import websockets
async def stream_whale_positions():
uri = "wss://ws.smartmoneyapi.com/stream?token=sk_live_abc123xyz789"
async with websockets.connect(uri) as websocket:
# 等待連接確認
ack = await websocket.recv()
print(f"已連接: {ack}")
# 訂閱大戶持倉
await websocket.send(json.dumps({
"type": "subscribe",
"channel": "whale_positions",
"symbols": ["BTCUSDT", "ETHUSDT"]
}))
# 監聽更新
while True:
try:
msg = await websocket.recv()
data = json.loads(msg)
if data["type"] == "ping":
# 回應 ping
await websocket.send(json.dumps({
"type": "pong",
"id": data["id"]
}))
elif data["type"] == "data":
print(f"新持倉: {data['data']}")
except websockets.exceptions.ConnectionClosed:
print("連接已關閉,正在重新連接...")
await asyncio.sleep(1)
asyncio.run(stream_whale_positions())
訂閱時過濾: 使用 params 物件在伺服器端過濾數據(min_position_size、min_size_usd),而不是在應用程式中過濾。
批量訂閱: 在單一訊息中訂閱多個符號,而不是每個符號單獨訂閱。
取消未使用的訂閱: 當您不再需要某個串流時,取消訂閱以節省頻寬並減少訊息量。
使用 gzip 壓縮: 在 WebSocket 客戶端啟用訊息壓縮以節省頻寬(減少 20-40%)。
監控連接健康狀況: 追蹤 ping/pong 延遲和自動重連,以診斷網絡問題。
斷線時緩衝訊息: 當連接中斷時,將策略信號排隊,並在重新連接後執行。
立即開始串流
取得您的API金鑰,開始建構即時交易系統。所有方案皆支援WebSocket串流。
取得API金鑰
建構即時交易系統
以亞秒級延遲串流大戶持倉、資金費率及AI確認評分。
查看方案