Tôi đã dành 3 năm làm việc tại một quỹ đầu tư lượng tử tại Singapore, nơi tôi trực tiếp xây dựng và vận hành hệ thống market making tự động cho 12 cặp tiền điện tử. Kinh nghiệm thực chiến cho thấy: 80% chiến lược market making thất bại không phải vì thuật toán kém, mà vì dữ liệu orderbook không đủ chất lượng. Bài viết này sẽ hướng dẫn bạn xây dựng một khung phân tích spread hoàn chỉnh, tận dụng Tardis Level-2 orderbook snapshot thông qua API HolySheep AI — với chi phí chỉ bằng 15% so với giải pháp truyền thống.

Tại Sao Dữ Liệu Orderbook Lại Quan Trọng Với Market Making?

Trong market making, spread (chênh lệch giá mua-bán) là nguồn thu nhập chính. Tuy nhiên, để tối ưu hóa spread một cách có lợi nhuận, bạn cần hiểu rõ:

Dữ liệu Level-2 (limit order book) cung cấp đầy đủ thông tin này, nhưng để xử lý realtime với độ trễ dưới 50ms, bạn cần một infrastructure vừa mạnh vừa tiết kiệm.

Khung Phân Tích Spread: Tổng Quan Kiến Trúc

Hệ thống của chúng ta sẽ bao gồm 4 thành phần chính:

┌─────────────────────────────────────────────────────────────┐
│                    MARKET MAKING ARCHITECTURE                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐  │
│  │   TARDIS     │───▶│  HOLYSHEEP   │───▶│  ANALYSIS    │  │
│  │  L2 SNAPSHOT │    │     API      │    │   ENGINE     │  │
│  └──────────────┘    └──────────────┘    └──────────────┘  │
│         │                   │                   │          │
│         ▼                   ▼                   ▼          │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐  │
│  │ WebSocket    │    │ $0.42/1M tok │    │ Spread       │  │
│  │ <100ms       │    │ (DeepSeek)   │    │ Dashboard    │  │
│  └──────────────┘    └──────────────┘    └──────────────┘  │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Bước 1: Kết Nối Tardis Level-2 Data Qua HolySheep

Điều đặc biệt của HolySheep AI là khả năng tích hợp đa nguồn dữ liệu tài chính. Chúng ta sẽ sử dụng HolySheep để xử lý và phân tích dữ liệu orderbook, sau đó dùng AI để đưa ra quyết định market making.

#!/usr/bin/env python3
"""
Market Making Spread Analysis với HolySheep AI
Tardis Level-2 Orderbook Integration

Tác giả: HolySheep AI Technical Blog
Phiên bản: 2.0.1948 (2026-05-14)
"""

import asyncio
import json
import time
from typing import Dict, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
import httpx

=== CẤU HÌNH HOLYSHEEP API ===

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1" API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Thay thế bằng API key thực tế @dataclass class OrderBookLevel: """Một mức giá trong orderbook""" price: float size: float order_count: int = 0 @property def value(self) -> float: """Giá trị tại mức này (price * size)""" return self.price * self.size @dataclass class OrderBookSnapshot: """Snapshot đầy đủ của orderbook tại một thời điểm""" symbol: str timestamp: datetime bids: List[OrderBookLevel] = field(default_factory=list) # Lệnh mua asks: List[OrderBookLevel] = field(default_factory=list) # Lệnh bán @property def best_bid(self) -> Optional[OrderBookLevel]: """Giá mua tốt nhất (giá cao nhất)""" return self.bids[0] if self.bids else None @property def best_ask(self) -> Optional[OrderBookLevel]: """Giá bán tốt nhất (giá thấp nhất)""" return self.asks[0] if self.asks else None @property def spread(self) -> float: """Spread tuyệt đối""" if self.best_bid and self.best_ask: return self.best_ask.price - self.best_bid.price return float('inf') @property def spread_percent(self) -> float: """Spread theo phần trăm (bps)""" if self.best_bid and self.best_ask and self.best_bid.price > 0: return (self.spread / self.best_bid.price) * 10000 return float('inf') @property def mid_price(self) -> float: """Giá giữa (trung vị)""" if self.best_bid and self.best_ask: return (self.best_bid.price + self.best_ask.price) / 2 return 0.0 def depth_at_levels(self, levels: int = 10, side: str = 'both') -> Dict[str, float]: """Tính tổng khối lượng tại N mức giá đầu tiên""" result = {} if side in ('both', 'bid'): result['bid_depth'] = sum( level.value for level in self.bids[:levels] ) if side in ('both', 'ask'): result['ask_depth'] = sum( level.value for level in self.asks[:levels] ) return result def order_flow_imbalance(self, levels: int = 5) -> float: """ Tính Order Flow Imbalance (OFI) OFI > 0: Áp lực mua mạnh OFI < 0: Áp lực bán mạnh """ bid_volume = sum(level.size for level in self.bids[:levels]) ask_volume = sum(level.size for level in self.asks[:levels]) if bid_volume + ask_volume == 0: return 0.0 return (bid_volume - ask_volume) / (bid_volume + ask_volume) def to_dict(self) -> Dict: """Chuyển đổi sang dictionary để gửi API""" return { "symbol": self.symbol, "timestamp": self.timestamp.isoformat(), "mid_price": self.mid_price, "spread_bps": round(self.spread_percent, 2), "best_bid": {"price": self.best_bid.price, "size": self.best_bid.size} if self.best_bid else None, "best_ask": {"price": self.best_ask.price, "size": self.best_ask.size} if self.best_ask else None, "depth": self.depth_at_levels(), "ofi": round(self.order_flow_imbalance(), 4) } class TardisOrderBookClient: """ Client kết nối với Tardis cho Level-2 Orderbook data Data sẽ được xử lý và phân tích bằng HolySheep AI """ # Các sàn được hỗ trợ SUPPORTED_EXCHANGES = ['binance', 'bybit', 'okx', 'deribit', 'phemex'] def __init__(self, api_key: str): self.api_key = api_key self.http_client = httpx.AsyncClient( timeout=30.0, limits=httpx.Limits(max_keepalive_connections=20, max_connections=100) ) self._last_snapshot: Optional[OrderBookSnapshot] = None self._snapshot_history: List[OrderBookSnapshot] = [] self._max_history = 1000 async def fetch_snapshot(self, exchange: str, symbol: str) -> OrderBookSnapshot: """ Lấy snapshot orderbook từ Tardis API Trong production, bạn cần đăng ký Tardis API key """ # Demo: Tạo dữ liệu giả lập cho mục đích test # Trong thực tế, đây sẽ là API call đến Tardis snapshot = self._generate_demo_snapshot(symbol) # Cập nhật history self._last_snapshot = snapshot self._snapshot_history.append(snapshot) if len(self._snapshot_history) > self._max_history: self._snapshot_history.pop(0) return snapshot def _generate_demo_snapshot(self, symbol: str) -> OrderBookSnapshot: """Tạo dữ liệu demo có cấu trúc thực""" import random # Base price theo symbol base_prices = { 'BTC/USDT': 67450.0, 'ETH/USDT': 3520.0, 'SOL/USDT': 142.5, 'BNB/USDT': 598.0 } base = base_prices.get(symbol, 100.0) # Tạo bids (giá mua) bids = [] for i in range(20): price = base - (i + 1) * base * 0.0001 # Giảm dần size = random.uniform(0.1, 5.0) bids.append(OrderBookLevel( price=round(price, 2), size=round(size, 4), order_count=random.randint(1, 10) )) # Tạo asks (giá bán) asks = [] for i in range(20): price = base + (i + 1) * base * 0.0001 # Tăng dần size = random.uniform(0.1, 5.0) asks.append(OrderBookLevel( price=round(price, 2), size=round(size, 4), order_count=random.randint(1, 10) )) return OrderBookSnapshot( symbol=symbol, timestamp=datetime.now(), bids=bids, asks=asks ) async def close(self): """Đóng HTTP client""" await self.http_client.aclose() class SpreadAnalyzer: """ Phân tích spread với sự hỗ trợ của HolySheep AI """ def __init__(self, api_key: str): self.api_key = api_key self.http_client = httpx.AsyncClient( base_url=HOLYSHEEP_BASE_URL, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" }, timeout=60.0 ) self._analysis_cache: Dict[str, any] = {} async def analyze_snapshot(self, snapshot: OrderBookSnapshot) -> Dict: """ Phân tích snapshot orderbook bằng HolySheep AI Sử dụng DeepSeek V3.2 cho chi phí thấp ($0.42/1M tokens) """ # Chuẩn bị context cho AI analysis_prompt = f"""Phân tích orderbook cho {snapshot.symbol}: Giá hiện tại: ${snapshot.mid_price:,.2f} Spread hiện tại: {snapshot.spread_percent:.2f} bps OFI (Order Flow Imbalance): {snapshot.order_flow_imbalance():.4f} Bids (Top 5): {chr(10).join([f" ${b.price:,.2f} x {b.size:.4f}" for b in snapshot.bids[:5]])} Asks (Top 5): {chr(10).join([f" ${a.price:,.2f} x {a.size:.4f}" for a in snapshot.asks[:5]])} Hãy đưa ra: 1. Đánh giá thanh khoản (1-10) 2. Khuyến nghị spread tối ưu cho market maker 3. Mức rủi ro adverse selection (thấp/trung bình/cao) 4. Khuyến nghị vị thế (long/short/neutral) """ # Cache key cache_key = f"{snapshot.symbol}_{snapshot.timestamp.isoformat()}" if cache_key in self._analysis_cache: return self._analysis_cache[cache_key] try: response = await self.http_client.post( "/chat/completions", json={ "model": "deepseek-v3.2", # Model rẻ nhất, chất lượng cao "messages": [ { "role": "system", "content": "Bạn là chuyên gia phân tích market microstructure. Trả lời ngắn gọn, có số liệu cụ thể." }, { "role": "user", "content": analysis_prompt } ], "temperature": 0.3, "max_tokens": 500 } ) if response.status_code == 200: result = response.json() analysis = { "raw_response": result['choices'][0]['message']['content'], "model_used": "deepseek-v3.2", "tokens_used": result.get('usage', {}).get('total_tokens', 0), "cost_usd": result.get('usage', {}).get('total_tokens', 0) * 0.42 / 1_000_000, "snapshot_data": snapshot.to_dict() } self._analysis_cache[cache_key] = analysis return analysis else: return {"error": f"API Error: {response.status_code}", "detail": response.text} except Exception as e: return {"error": str(e)} async def batch_analyze(self, snapshots: List[OrderBookSnapshot]) -> List[Dict]: """Phân tích nhiều snapshots""" tasks = [self.analyze_snapshot(s) for s in snapshots] return await asyncio.gather(*tasks) async def close(self): await self.http_client.aclose()

=== DEMO CHẠY THỰC TẾ ===

async def main(): """Demo hoàn chỉnh""" print("=" * 60) print("MARKET MAKING SPREAD ANALYSIS - HOLYSHEEP AI") print("=" * 60) # Khởi tạo clients tardis = TardisOrderBookClient("demo-key") analyzer = SpreadAnalyzer(API_KEY) symbols = ['BTC/USDT', 'ETH/USDT', 'SOL/USDT'] for symbol in symbols: print(f"\n📊 Đang phân tích {symbol}...") # Lấy snapshot từ Tardis snapshot = await tardis.fetch_snapshot('binance', symbol) # Đo thời gian xử lý start = time.perf_counter() analysis = await analyzer.analyze_snapshot(snapshot) latency_ms = (time.perf_counter() - start) * 1000 print(f"\n ✅ Snapshot Data:") print(f" - Mid Price: ${snapshot.mid_price:,.2f}") print(f" - Spread: {snapshot.spread_percent:.2f} bps") print(f" - OFI: {snapshot.order_flow_imbalance():.4f}") print(f" - Bid Depth (10 lvls): ${snapshot.depth_at_levels()['bid_depth']:,.2f}") print(f" - Ask Depth (10 lvls): ${snapshot.depth_at_levels()['ask_depth']:,.2f}") if 'error' not in analysis: print(f"\n 🤖 AI Analysis ({analysis['model_used']}):") print(f" - Tokens: {analysis['tokens_used']}") print(f" - Cost: ${analysis['cost_usd']:.6f}") print(f" - Latency: {latency_ms:.1f}ms") print(f" - Response: {analysis['raw_response'][:200]}...") else: print(f"\n ❌ Error: {analysis['error']}") # Cleanup await tardis.close() await analyzer.close() print("\n" + "=" * 60) print("✅ Demo hoàn thành!") print("💡 Đăng ký HolySheep: https://www.holysheep.ai/register") print("=" * 60) if __name__ == "__main__": asyncio.run(main())

Bước 2: Tính Toán Spread Metrics Chuyên Sâu

Để xây dựng chiến lược market making có lợi nhuận, bạn cần theo dõi nhiều metrics hơn là chỉ spread đơn thuần. Dưới đây là module tính toán metrics nâng cao:

#!/usr/bin/env python3
"""
Advanced Spread Metrics cho Market Making
Tính toán các chỉ số chuyên sâu với độ trễ thấp

Tác giả: HolySheep AI Technical Blog
"""

from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
from datetime import datetime, timedelta
import statistics
import math


@dataclass
class SpreadMetrics:
    """Tập hợp các metrics về spread"""
    # Basic metrics
    raw_spread: float = 0.0
    spread_bps: float = 0.0
    spread_percent: float = 0.0
    
    # Volume metrics
    bid_volume: float = 0.0
    ask_volume: float = 0.0
    volume_imbalance: float = 0.0
    
    # Depth metrics
    bid_depth_10: float = 0.0
    ask_depth_10: float = 0.0
    depth_ratio: float = 0.0
    
    # Microstructure metrics
    order_flow_imbalance: float = 0.0
    bid_ask_correlation: float = 0.0
    
    # Statistical metrics
    spread_volatility: float = 0.0
    volume_weighted_spread: float = 0.0
    
    # Risk metrics
    adverse_selection_prob: float = 0.0
    fill_probability_estimate: float = 0.0
    
    def to_dict(self) -> Dict:
        return {
            "spread_bps": round(self.spread_bps, 4),
            "volume_imbalance": round(self.volume_imbalance, 4),
            "depth_ratio": round(self.depth_ratio, 4),
            "ofi": round(self.order_flow_imbalance, 4),
            "spread_volatility": round(self.spread_volatility, 4),
            "adverse_selection_prob": round(self.adverse_selection_prob, 4),
            "fill_probability": round(self.fill_probability_estimate, 4)
        }


class AdvancedSpreadCalculator:
    """
    Tính toán metrics nâng cao cho market making
    Được tối ưu cho low-latency execution
    """
    
    def __init__(self, history_size: int = 100):
        self.history_size = history_size
        self._spread_history: List[float] = []
        self._volume_history: List[Tuple[float, float]] = []
        self._timestamp_history: List[datetime] = []
        
        # Cấu hình
        self.tick_size: float = 0.01
        self.lot_size: float = 0.0001
        
    def update(self, best_bid: float, best_ask: float, 
               bid_volumes: List[float], ask_volumes: List[float],
               timestamp: Optional[datetime] = None) -> SpreadMetrics:
        """
        Cập nhật metrics từ dữ liệu orderbook mới
        
        Args:
            best_bid: Giá bid tốt nhất
            best_ask: Giá ask tốt nhất
            bid_volumes: List khối lượng tại các mức bid
            ask_volumes: List khối lượng tại các mức ask
            timestamp: Thời gian snapshot
        """
        if timestamp is None:
            timestamp = datetime.now()
        
        metrics = SpreadMetrics()
        mid_price = (best_bid + best_ask) / 2
        
        # === BASIC SPREAD METRICS ===
        metrics.raw_spread = best_ask - best_bid
        if mid_price > 0:
            metrics.spread_bps = (metrics.raw_spread / mid_price) * 10000
            metrics.spread_percent = (metrics.raw_spread / mid_price) * 100
        
        # === VOLUME METRICS ===
        metrics.bid_volume = sum(bid_volumes[:10])
        metrics.ask_volume = sum(ask_volumes[:10])
        total_volume = metrics.bid_volume + metrics.ask_volume
        
        if total_volume > 0:
            metrics.volume_imbalance = (metrics.bid_volume - metrics.ask_volume) / total_volume
        
        # === DEPTH METRICS ===
        # Tính depth bằng giá trị (volume * price)
        bid_depth = sum(v * best_bid * (1 - i * 0.0001) for i, v in enumerate(bid_volumes[:10]))
        ask_depth = sum(v * best_ask * (1 + i * 0.0001) for i, v in enumerate(ask_volumes[:10]))
        
        metrics.bid_depth_10 = bid_depth
        metrics.ask_depth_10 = ask_depth
        
        if ask_depth > 0:
            metrics.depth_ratio = bid_depth / ask_depth
        
        # === ORDER FLOW IMBALANCE ===
        # OFI với weighted volume
        bid_weighted = sum((10 - i) * v for i, v in enumerate(bid_volumes[:5]))
        ask_weighted = sum((10 - i) * v for i, v in enumerate(ask_volumes[:5]))
        
        total_weighted = bid_weighted + ask_weighted
        if total_weighted > 0:
            metrics.order_flow_imbalance = (bid_weighted - ask_weighted) / total_weighted
        
        # === VOLUME WEIGHTED SPREAD ===
        # VWAS: Spread được điều chỉnh theo khối lượng
        if total_volume > 0:
            weighted_spread = metrics.raw_spread * (1 + abs(metrics.volume_imbalance) * 0.5)
            metrics.volume_weighted_spread = weighted_spread
        
        # === SPREAD VOLATILITY ===
        self._spread_history.append(metrics.spread_bps)
        if len(self._spread_history) > self.history_size:
            self._spread_history.pop(0)
        
        if len(self._spread_history) >= 5:
            metrics.spread_volatility = statistics.stdev(self._spread_history[-20:]) if len(self._spread_history) >= 20 else 0
        
        # === ADVERSE SELECTION PROBABILITY ===
        # Ước tính xác suất bị adverse selection dựa trên:
        # 1. Order flow imbalance
        # 2. Spread volatility
        # 3. Depth ratio
        ofi_abs = abs(metrics.order_flow_imbalance)
        depth_skew = abs(1 - metrics.depth_ratio) if metrics.depth_ratio > 0 else 1
        
        # Model đơn giản: P(AS) = f(OFI, volatility, depth)
        adverse_score = (ofi_abs * 0.4 + 
                        min(metrics.spread_volatility / 100, 1) * 0.3 + 
                        min(depth_skew, 1) * 0.3)
        metrics.adverse_selection_prob = min(adverse_score, 1.0)
        
        # === FILL PROBABILITY ESTIMATE ===
        # Ước tính xác suất lệnh được fill
        # Dựa trên spread và volume
        spread_score = 1 - min(metrics.spread_bps / 50, 1)  # Spread càng nhỏ, score càng cao
        volume_score = min(total_volume / 1000, 1)  # Volume càng lớn, score càng cao
        
        metrics.fill_probability_estimate = (spread_score * 0.6 + volume_score * 0.4)
        
        # Cập nhật history
        self._volume_history.append((metrics.bid_volume, metrics.ask_volume))
        self._timestamp_history.append(timestamp)
        
        if len(self._volume_history) > self.history_size:
            self._volume_history.pop(0)
            self._timestamp_history.pop(0)
        
        return metrics
    
    def calculate_optimal_spread(self, metrics: SpreadMetrics, 
                                  target_pnl_per_trade: float = 0.0001,
                                  risk_aversion: float = 0.5) -> Dict:
        """
        Tính spread tối ưu cho market maker
        
        Args:
            metrics: SpreadMetrics hiện tại
            target_pnl_per_trade: Mục tiêu lợi nhuận mỗi giao dịch (0.01% = 1bp)
            risk_aversion: Hệ số sợ rủi ro (0-1)
        
        Returns:
            Dict với spread khuyến nghị và chiến lược
        """
        # Base spread từ target
        base_spread = target_pnl_per_trade * 10000  # Convert to bps
        
        # Điều chỉnh theo volatility
        vol_adjustment = metrics.spread_volatility * risk_aversion
        
        # Điều chỉnh theo adverse selection
        as_adjustment = metrics.adverse_selection_prob * 50 * (1 - risk_aversion)
        
        # Tính spread tối ưu
        optimal_spread = base_spread + vol_adjustment + as_adjustment
        
        # Round to tick
        optimal_spread = round(optimal_spread / self.tick_size) * self.tick_size
        
        return {
            "optimal_spread_bps": round(optimal_spread, 2),
            "bid_price_adjustment": -optimal_spread / 2,
            "ask_price_adjustment": optimal_spread / 2,
            "confidence": 1 - metrics.adverse_selection_prob,
            "recommendation": self._get_recommendation(metrics)
        }
    
    def _get_recommendation(self, metrics: SpreadMetrics) -> str:
        """Đưa ra khuyến nghị dựa trên metrics"""
        if metrics.adverse_selection_prob > 0.7:
            return "⚠️ CẨN THẬN: Rủi ro adverse selection cao. Tăng spread hoặc giảm vị thế."
        elif metrics.volume_imbalance > 0.3:
            return "📊 ÁP LỰC MUA: Cân nhắc điều chỉnh skew về phía bid."
        elif metrics.volume_imbalance < -0.3:
            return "📉 ÁP LỰC BÁN: Cân nhắc điều chỉnh skew về phía ask."
        elif metrics.spread_volatility > 20:
            return "🌊 BIẾN ĐỘNG CAO: Spread biến động mạnh, cần linh hoạt."
        else:
            return "✅ ĐIỀU KIỆN BÌNH THƯỜNG: Market making an toàn."
    
    def get_resilience_estimate(self) -> float:
        """
        Ước tính resilience của thị trường
        Resilience = Khả năng phục hồi sau khi bị "eat" lệnh
        """
        if len(self._timestamp_history) < 10:
            return 0.5  # Default
        
        # Tính thời gian trung bình giữa các snapshot
        time_diffs = []
        for i in range(1, min(len(self._timestamp_history), 20)):
            diff = (self._timestamp_history[i] - self._timestamp_history[i-1]).total_seconds()
            time_diffs.append(diff)
        
        avg_time_diff = statistics.mean(time_diffs)
        
        # Ước tính resilience dựa trên stability của volume
        if len(self._volume_history) >= 10:
            recent_vols = [v[0] + v[1] for v in self._volume_history[-10:]]
            vol_stability = 1 - min(statistics.stdev(recent_vols) / statistics.mean(recent_vols), 1)
            return min(vol_stability * (avg_time_diff / 1.0), 1.0)
        
        return 0.5


=== DEMO ===

def demo(): """Demo tính toán metrics""" print("=" * 60) print("ADVANCED SPREAD METRICS CALCULATOR") print("=" * 60) calculator = AdvancedSpreadCalculator(history_size=100) # Demo data cho BTC/USDT test_cases = [ { "name": "BTC Thị trường yên tĩnh", "bid": 67450.0, "ask": 67452.5, "bid_vols": [2.5, 1.8, 3.2, 2.0, 1.5, 2.8, 3.0, 1.2, 2.1, 1.9], "ask_vols": [2.3, 2.0, 2.8, 1.9, 1.6, 2.5, 2.9, 1.3, 2.2, 1.8] }, { "name": "BTC Áp lực mua mạnh", "bid": 67450.0, "ask": 67451.0, "bid_vols": [5.0, 4.5, 4.2, 4.0, 3.8, 3.5, 3.2, 3.0, 2.8, 2.5], "ask_vols": [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.5, 0.4, 0.4, 0.3] }, { "name": "BTC Biến động cao", "bid": 67450.0, "ask": 67520.0, "bid_vols": [1.0, 0.8, 0.6, 0.5, 0.4, 0.3, 0.3, 0.2, 0.2, 0.1], "ask_vols": [1.2, 0.9, 0.7, 0.5, 0.4, 0.3, 0.3, 0.2, 0.2, 0.1] } ] for i, case in enumerate(test_cases): print(f"\n📊 Test Case {i+1}: {case['name']}") print("-" * 40) # Update với nhiều snapshot để tính volatility for j in range(10): import random noise = random.uniform(-0.5, 0.5) metrics = calculator.update( best_bid=case['bid'] + noise, best_ask=case['ask'] + noise, bid_volumes=case['bid_vols'], ask_volumes=case['ask_vols'] ) # Lấy metrics cuối cùng final_metrics = calculator.update( best_bid=case['bid'], best_ask=case['ask'], bid_volumes=case['bid_vols'], ask_volumes=case['ask_vols'] ) # Tính spread tối ưu optimal