C.W.K.
Stream
Lesson 05 of 08 · published

Trading & Market Data

~12 min · app, trading, binary

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

고빈도가 binary 요구

암호화폐 거래소 feed 가 symbol 별 초당 100+ tick. 그 rate 의 JSON 이 bandwidth + CPU 잡아먹음. Binary protocol (MessagePack, custom DataView, Protobuf) 이 frame size 60-80% 줄이고 parse time 더 줄임. Public homepage ticker 엔 JSON ok; 500 symbol 구독하는 trading desk 엔 binary 필수.

Hybrid 패턴

Trading 플랫폼이 관심사 분리: 고빈도 price + book stream 엔 WebSocket (binary), place-order/cancel-order/account info 같은 저빈도 command 엔 REST. 같은 auth token 둘 다 작동. User 가 order 가끔 push, market 이 data 끊임없이 push.

Code

서버: binary 인코딩 price stream·python
import struct
import asyncio

async def stream_prices(websocket):
    while True:
        prices = await get_latest_prices()
        # 18 bytes per record:
        # symbol_id(uint16) + price(float64) + volume(float64)
        if not prices:
            await asyncio.sleep(0.1)
            continue
        out = bytearray()
        for sym_id, price, vol in prices:
            out += struct.pack('<Hdd', sym_id, price, vol)
        await websocket.send_bytes(bytes(out))
        await asyncio.sleep(0.1)  # 10 Hz
클라: binary stream decode·javascript
ws.binaryType = 'arraybuffer';

ws.onmessage = (e) => {
  const view = new DataView(e.data);
  const recordSize = 18;
  const count = e.data.byteLength / recordSize;
  for (let i = 0; i < count; i++) {
    const o = i * recordSize;
    const sym    = view.getUint16( o,      true);
    const price  = view.getFloat64(o + 2,  true);
    const volume = view.getFloat64(o + 10, true);
    updateTicker(sym, price, volume);
  }
};

External links

Exercise

위 binary price stream 을 가짜 symbol 셋으로 구현. 1000 tick 의 wire byte + parse time 을 동일 JSON 과 비교. 비율 보고. REST /orders endpoint 추가해서 같은 WebSocket 통해 fill notification publish — order 의 source of truth 는 REST 유지.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.