WebSocket API 레퍼런스
고래 포지션, 펀딩 비율, 청산, AI 확인 점수의 실시간 데이터 스트리밍. 자동 재연결, 효율적인 데이터 압축, 멀티 스트림 구독으로 초단위 레이턴시 제공.
개요
WebSocket API는 실시간 암호화폐 파생상품 데이터를 위한 저지연 양방향 통신을 제공합니다. 5-30초마다 REST 엔드포인트를 폴링하는 대신, WebSocket 연결은 시장 상황이 변화할 때 즉시 업데이트를 전달합니다. 트레이딩 봇, 알림 시스템, 실시간 대시보드에 이상적입니다.
REST 대비 WebSocket의 주요 장점:
시장 변동 이벤트(청산, 고래 움직임)에 대한 초단위 레이턴시
델타 인코딩 업데이트로 효율적인 대역폭 사용
단일 연결에서 여러 동시 구독 가능
서버 측 필터링 및 집계
자동 하트비트 및 재연결 처리
할당량 대비 낮은 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"]
}
고래 포지션 스트림
모든 추적 대상 심볼과 거래소에서의 대규모 고래 포지션에 대한 실시간 업데이트. 고래가 포지션을 열거나, 닫거나, 수정할 때 업데이트가 전송됩니다. 진입 가격, 현재 가격, P&L, 레버리지, 청산 위험 등이 포함됩니다.
{
"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"
}
}
미결제약정 스트림
각 심볼에 대한 모든 레버리지 트레이더의 총 미결제약정. OI 증가(레버리지에 더 많은 자금 유입) 및 감소(포지션 종료)를 추적합니다. 가격 움직임과의 OI 차이는 숨겨진 강세/약세 피로를 식별합니다.
{
"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}ms 후 재연결 시도`);
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 확인 점수를 초단위 레이턴시로 스트리밍하세요.
요금제 확인