Trong hệ sinh thái giao dịch tiền mã hóa hiện đại, việc nắm bắt dữ liệu order book L2 theo thời gian thực là yếu tố then chốt cho các chiến lược market making, arbitrage, và phân tích thanh khoản. Bài viết này chia sẻ kinh nghiệm thực chiến của đội ngũ kỹ sư HolySheep AI trong việc xây dựng hệ thống xử lý dữ liệu delta của Bybit perpetual futures với độ trễ dưới 50ms và throughput hơn 10,000 message/giây.

1. Tổng quan kiến trúc dữ liệu Order Book L2 trên Bybit

Bybit cung cấp hai loại dữ liệu order book quan trọng:

Theo tài liệu chính thức của Bybit WebSocket API v4, mỗi delta message bao gồm:

{
  "topic": "orderbook.200BTC.USDT",
  "type": "delta",
  "data": {
    "s": "BTCUSDT",           // Symbol
    "b": [["50000.00", "1.5"]], // Bids: [price, quantity]
    "a": [["50001.00", "2.0"]], // Asks: [price, quantity]
    "U": "1001",              // Update ID - bid side
    "u": "1005",              // Update ID - ask side
    "seq": 12345              // Sequence number for ordering
  },
  "ts": 1704067200000,        // Timestamp
  "cross_seq": "100"
}

2. Thiết kế hệ thống tái tạo Order Book

2.1 Cấu trúc dữ liệu tối ưu

Để đạt hiệu suất cao nhất, chúng ta cần lựa chọn cấu trúc dữ liệu phù hợp. Trong thực tế, đội ngũ HolySheep AI đã thử nghiệm nhiều phương án:

import asyncio
import json
from dataclasses import dataclass, field
from sortedcontainers import SortedDict
from typing import Dict, Optional, List, Tuple
import time
import struct
from collections import defaultdict
import mmap
import numpy as np

@dataclass
class OrderBookLevel:
    """Một mức giá trong order book"""
    price: float
    quantity: float
    update_time: int
    
    def is_empty(self) -> bool:
        return self.quantity <= 0

@dataclass 
class OrderBookState:
    """
    Trạng thái order book với tối ưu hóa bộ nhớ.
    Sử dụng SortedDict để duy trì thứ tự giá tự động.
    """
    symbol: str
    bids: SortedDict = field(default_factory=SortedDict)  # price -> quantity
    asks: SortedDict = field(default_factory=SortedDict)
    
    last_update_id: int = 0
    last_seq: int = 0
    last_update_time: int = 0