Mở đầu: Khi "ConnectionError: timeout" phá hủy chiến lược giao dịch của tôi

Tôi vẫn nhớ rõ cái đêm tháng 3 năm 2024. Hệ thống giao dịch của tôi đã chạy ổn định suốt 3 tuần, thuật toán AI phân tích Order Book đưa ra dự đoán chính xác đến 87%. Rồi 2:47 AM, màn hình terminal bất ngờ hiển thị dòng chữ đỏ lòe loẹt: ConnectionError: HTTPSConnectionPool(host='api.tardis.dev', port=443): Max retries exceeded. Trong vòng 12 phút downtime đó, thị trường Bitcoin biến động 4.2%, và tôi mất trắng toàn bộ lợi nhuận tuần đó.

Bài học đắt giá đó là lý do tôi nghiên cứu và cuối cùng chuyển sang giải pháp tích hợp HolySheep AI API với Tardis Data. Trong bài viết này, tôi sẽ chia sẻ toàn bộ quy trình từ cài đặt, tối ưu hóa đến những bài học xương máu khi làm việc với real-time Order Book data và AI models.

Order Book Analysis là gì? Tại sao nó quan trọng với crypto trading

Order Book (sổ lệnh) là bản ghi chi tiết tất cả các lệnh mua và bán trên sàn giao dịch tại một thời điểm. Khi phân tích Order Book bằng AI models, bạn có thể:

Kiến trúc hệ thống: Tardis Data + HolySheep AI

Để xây dựng hệ thống hoàn chỉnh, bạn cần hai thành phần chính:

1. Tardis Data - Nguồn cấp dữ liệu Order Book thời gian thực

Tardis cung cấp API truy cập historical và real-time data từ hơn 30 sàn giao dịch crypto. Họ hỗ trợ WebSocket cho dữ liệu real-time với độ trễ thấp và REST API cho historical data.

2. HolySheep AI API - Neural Network xử lý và dự đoán

Thay vì phải tự deploy và maintain các mô hình AI phức tạp, HolySheep cung cấp API với các model được train sẵn cho financial analysis. Điểm mấu chốt: giá chỉ từ $0.42/MTok với DeepSeek V3.2 - rẻ hơn 95% so với GPT-4.1 ($8/MTok).

Cài đặt môi trường và cấu hình ban đầu

Yêu cầu hệ thống

# Cài đặt các thư viện cần thiết
pip install websockets requests pandas numpy asyncio aiohttp

File: requirements.txt

websockets>=12.0 requests>=2.31.0 pandas>=2.1.0 numpy>=1.24.0 aiohttp>=3.9.0
# File: config.py
import os

=== TARDIS DATA CONFIG ===

TARDIS_WS_URL = "wss://api.tardis.dev/v1/stream" TARDIS_API_KEY = "YOUR_TARDIS_API_KEY" # Lấy từ https://docs.tardis.dev

=== HOLYSHEEP AI CONFIG ===

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1" HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Đăng ký: https://www.holysheep.ai/register

Cấu hình model (giá 2026 tham khảo)

MODEL_CONFIG = { "deepseek_v3_2": { "model_id": "deepseek-v3.2", "price_per_mtok": 0.42, # Rẻ nhất, phù hợp cho batch processing "latency_ms": 45, # Trung bình "context_window": 128000 }, "gpt_4_1": { "model_id": "gpt-4.1", "price_per_mtok": 8.0, # Đắt nhất, chất lượng cao "latency_ms": 120, "context_window": 128000 }, "claude_sonnet_4_5": { "model_id": "claude-sonnet-4.5", "price_per_mtok": 15.0, "latency_ms": 95, "context_window": 200000 }, "gemini_2_5_flash": { "model_id": "gemini-2.5-flash", "price_per_mtok": 2.50, "latency_ms": 38, # Nhanh nhất "context_window": 1000000 } }

Mặc định dùng DeepSeek V3.2 cho cost-efficiency

DEFAULT_MODEL = "deepseek_v3_2"

Kết nối Tardis WebSocket - Real-time Order Book Stream

# File: tardis_client.py
import asyncio
import json
import logging
from datetime import datetime
from typing import Callable, Optional, List, Dict
import aiohttp
from dataclasses import dataclass, asdict

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@dataclass
class OrderBookEntry:
    """Một entry trong Order Book"""
    price: float
    size: float
    side: str  # 'bid' hoặc 'ask'
    exchange: str
    timestamp: datetime

@dataclass 
class OrderBookSnapshot:
    """Snapshot đầy đủ của Order Book"""
    exchange: str
    symbol: str
    bids: List[OrderBookEntry]  # Giá mua (sắp xếp giảm dần)
    asks: List[OrderBookEntry]  # Giá bán (sắp xếp tăng dần)
    timestamp: datetime
    sequence: int

class TardisClient:
    """
    Client kết nối Tardis WebSocket để nhận real-time Order Book data
    """
    
    def __init__(self, api_key: str, exchanges: List[str] = None):
        self.api_key = api_key
        self.exchanges = exchanges or ["binance", "bybit"]
        self.ws_url = "wss://api.tardis.dev/v1/stream"
        self._ws = None
        self._running = False
        self._order_books: Dict[str, OrderBookSnapshot] = {}
        self._last_sequence: Dict[str, int] = {}
        
    async def connect(self) -> bool:
        """
        Thiết lập kết nối WebSocket với Tardis
        Retry logic để handle connection drops
        """
        max_retries = 5
        retry_delay = 2
        
        for attempt in range(max_retries):
            try:
                # Đăng ký subscription cho Order Book data
                subscribe_msg = {
                    "type": "subscribe",
                    "channel": "orderbook",
                    "exchange": self.exchanges,
                    "symbols": ["BTC-PERP", "ETH-PERP"],
                    "book_levels": 25  # Lấy 25 mức giá mỗi bên
                }
                
                # Với aiohttp client
                headers = {
                    "Authorization": f"Bearer {self.api_key}",
                    "Content-Type": "application/json"
                }
                
                async with aiohttp.ClientSession() as session:
                    # Tardis yêu cầu upgrade connection qua HTTP first
                    async with session.ws_connect(
                        self.ws_url,
                        headers=headers,
                        timeout=aiohttp.ClientTimeout(total=30)
                    ) as ws:
                        self._ws = ws
                        self._running = True
                        
                        # Gửi subscribe message
                        await ws.send_json(subscribe_msg)
                        logger.info(f"Đã kết nối Tardis WebSocket - Attempt {attempt + 1}")
                        
                        # Bắt đầu nhận messages
                        await self._receive_messages()
                        
            except aiohttp.ClientError as e:
                logger.warning(f"Kết nối thất bại (Attempt {attempt + 1}/{max_retries}): {e}")
                if attempt < max_retries - 1:
                    await asyncio.sleep(retry_delay * (2 ** attempt))  # Exponential backoff
                else:
                    logger.error("Đã hết số lần thử kết nối. Kiểm tra API key và quota.")
                    return False
                    
        return False
        
    async def _receive_messages(self):
        """Vòng lặp chính nhận messages từ WebSocket"""
        async for msg in self._ws:
            if msg.type == aiohttp.WSMsgType.TEXT:
                try:
                    data = json.loads(msg.data)
                    await self._process_message(data)
                except json.JSONDecodeError as e:
                    logger.warning(f"JSON decode error: {e}")
                except Exception as e:
                    logger.error(f"Lỗi xử lý message: {e}")
            elif msg.type == aiohttp.WSMsgType.ERROR:
                logger.error(f"WebSocket error: {self._ws.exception()}")
                break
            elif msg.type == aiohttp.WSMsgType.CLOSED:
                logger.warning("WebSocket đã đóng. Attempting reconnect...")
                self._running = False
                break
                
    async def _process_message(self, data: dict):
        """Xử lý từng loại message từ Tardis"""
        msg_type = data.get("type")
        
        if msg_type == "snapshot":
            # Full Order Book snapshot - reset hoàn toàn
            self._process_snapshot(data)
            
        elif msg_type == "update":
            # Incremental update - áp dụng changes
            self._process_update(data)
            
        elif msg_type == "error":
            logger.error(f"Tardis error: {data.get('message')}")
            
    def _process_snapshot(self, data: dict):
        """Xử lý full snapshot từ Tardis"""
        exchange = data.get("exchange")
        symbol = data.get("symbol")
        
        bids = [
            OrderBookEntry(
                price=float(b[0]),
                size=float(b[1]),
                side="bid",
                exchange=exchange,
                timestamp=datetime.utcnow()
            )
            for b in data.get("bids", [])
        ]
        
        asks = [
            OrderBookEntry(
                price=float(a[0]),
                size=float(a[1]),
                side="ask",
                exchange=exchange,
                timestamp=datetime.utcnow()
            )
            for a in data.get("asks", [])
        ]
        
        self._order_books[f"{exchange}:{symbol}"] = OrderBookSnapshot(
            exchange=exchange,
            symbol=symbol,
            bids=bids,
            asks=asks,
            timestamp=datetime.utcnow(),
            sequence=data.get("sequence", 0)
        )
        
        logger.debug(f"Snapshot updated: {exchange}:{symbol} - Bids: {len(bids)}, Asks: {len(asks)}")
        
    def get_order_book(self, exchange: str, symbol: str) -> Optional[OrderBookSnapshot]:
        """Lấy Order Book hiện tại"""
        return self._order_books.get(f"{exchange}:{symbol}")
        
    async def close(self):
        """Đóng kết nối WebSocket"""
        self._running = False
        if self._ws:
            await self._ws.close()
            logger.info("Đã đóng kết nối Tardis WebSocket")

=== USAGE EXAMPLE ===

async def main(): tardis = TardisClient( api_key="YOUR_TARDIS_API_KEY", exchanges=["binance", "bybit"] ) try: await tardis.connect() except KeyboardInterrupt: await tardis.close() if __name__ == "__main__": asyncio.run(main())

Tích hợp HolySheep AI - Phân tích và Dự đoán Volatility

# File: holy_sheep_client.py
import requests
import json
import time
import logging
from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass
from enum import Enum

logger = logging.getLogger(__name__)

class VolatilityLevel(Enum):
    """Các mức độ biến động"""
    VERY_LOW = "very_low"
    LOW = "low" 
    MEDIUM = "medium"
    HIGH = "high"
    VERY_HIGH = "very_high"
    EXTREME = "extreme"

@dataclass
class OrderBookAnalysis:
    """Kết quả phân tích Order Book"""
    spread_pct: float  # Spread percentage
    bid_depth: float    # Tổng bid volume
    ask_depth: float   # Tổng ask volume
    imbalance_ratio: float  # Tỷ lệ mất cân bằng
    large_wall_count: int   # Số lượng large orders (>1 BTC)
    weighted_mid_price: float
    
@dataclass
class VolatilityPrediction:
    """Dự đoán volatility từ AI model"""
    level: VolatilityLevel
    probability: float  # 0-1
    predicted_range_pct: float  # Dự đoán % biến động trong timeframe
    timeframe_minutes: int
    confidence_score: float
    reasoning: str
    recommended_action: str

class HolySheepAIClient:
    """
    Client tương tác với HolySheep AI API cho Order Book analysis
    Base URL: https://api.holysheep.ai/v1
    """
    
    def __init__(self, api_key: str, model: str = "deepseek-v3.2"):
        self.api_key = api_key
        self.base_url = "https://api.holysheep.ai/v1"
        self.model = model
        self._session = requests.Session()
        self._session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        })
        self._request_count = 0
        self._total_tokens = 0
        
    def _calculate_order_book_metrics(self, bids: List[dict], asks: List[dict]) -> OrderBookAnalysis:
        """Tính toán các chỉ số cơ bản từ Order Book data"""
        if not bids or not asks:
            raise ValueError("Order Book rỗng")
            
        best_bid = float(bids[0]['price'])
        best_ask = float(asks[0]['price'])
        mid_price = (best_bid + best_ask) / 2
        
        spread = (best_ask - best_bid) / mid_price * 100
        
        bid_depth = sum(float(b.get('size', 0)) for b in bids[:10])
        ask_depth = sum(float(a.get('size', 0)) for a in asks[:10])
        
        imbalance = (bid_depth - ask_depth) / (bid_depth + ask_depth) if (bid_depth + ask_depth) > 0 else 0
        
        large_walls = sum(1 for b in bids[:5] if float(b.get('size', 0)) > 1.0)
        large_walls += sum(1 for a in asks[:5] if float(a.get('size', 0)) > 1.0)
        
        weighted_sum = sum(float(b['price']) * float(b['size']) for b in bids[:10])
        weighted_mid = weighted_sum / bid_depth if bid_depth > 0 else mid_price
        
        return OrderBookAnalysis(
            spread_pct=round(spread, 4),
            bid_depth=round(bid_depth, 4),
            ask_depth=round(ask_depth, 4),
            imbalance_ratio=round(imbalance, 4),
            large_wall_count=large_walls,
            weighted_mid_price=round(weighted_mid, 2)
        )
        
    def _build_analysis_prompt(self, analysis: OrderBookAnalysis, symbol: str) -> str:
        """Xây dựng prompt cho AI model"""
        return f"""Bạn là chuyên gia phân tích thị trường crypto. Phân tích Order Book sau đây cho cặp {symbol}:

THÔNG SỐ ORDER BOOK:
- Spread: {analysis.spread_pct}%
- Bid Depth (10 levels): {analysis.bid_depth} units
- Ask Depth (10 levels): {analysis.ask_depth} units
- Imbalance Ratio: {analysis.imbalance_ratio} (âm = more bids, dương = more asks)
- Large Walls (>1 unit): {analysis.large_wall_count}
- Weighted Mid Price: ${analysis.weighted_mid_price}

NHIỆM VỤ:
1. Đánh giá liquidity và volatility dựa trên các thông số trên
2. Dự đoán mức độ biến động giá trong 15-60 phút tới
3. Đưa ra khuyến nghị hành động cho traders

TRẢ LỜI THEO FORMAT JSON:
{{
    "volatility_level": "very_low|low|medium|high|very_high|extreme",
    "probability": 0.0-1.0,
    "predicted_range_pct": số % biến động dự kiến,
    "timeframe_minutes": 15-60,
    "confidence_score": 0.0-1.0,
    "reasoning": "giải thích ngắn gọn bằng tiếng Việt",
    "recommended_action": "buy|sell|hold|wait"
}}

CHỈ TRẢ LỜI JSON, không có text khác."""
    
    def analyze_volatility(
        self, 
        bids: List[dict], 
        asks: List[dict], 
        symbol: str = "BTC-PERP"
    ) -> Tuple[VolatilityPrediction, float, int]:
        """
        Phân tích Order Book và dự đoán volatility
        
        Returns:
            Tuple[VolatilityPrediction, cost_usd, latency_ms]
        """
        start_time = time.time()
        
        # Tính toán metrics
        analysis = self._calculate_order_book_metrics(bids, asks)
        
        # Build prompt
        prompt = self._build_analysis_prompt(analysis, symbol)
        
        # Gọi HolySheep AI API
        # Base URL: https://api.holysheep.ai/v1 (KHÔNG dùng api.openai.com)
        url = f"{self.base_url}/chat/completions"
        
        payload = {
            "model": self.model,
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "temperature": 0.3,  # Low temperature cho analysis nhất quán
            "max_tokens": 500
        }
        
        try:
            response = self._session.post(url, json=payload, timeout=30)
            response.raise_for_status()
            
            data = response.json()
            latency_ms = int((time.time() - start_time) * 1000)
            
            # Parse response
            content = data['choices'][0]['message']['content']
            
            # Extract JSON từ response
            try:
                result = json.loads(content)
            except json.JSONDecodeError:
                # Fallback: extract JSON block
                import re
                json_match = re.search(r'\{[^}]+\}', content, re.DOTALL)
                if json_match:
                    result = json.loads(json_match.group())
                else:
                    raise ValueError(f"Không parse được response: {content}")
            
            # Tính chi phí (giá 2026)
            prompt_tokens = data.get('usage', {}).get('prompt_tokens', 500)
            completion_tokens = data.get('usage', {}).get('completion_tokens', 200)
            total_tokens = prompt_tokens + completion_tokens
            
            price_per_mtok = {
                "deepseek-v3.2": 0.42,
                "gpt-4.1": 8.0,
                "claude-sonnet-4.5": 15.0,
                "gemini-2.5-flash": 2.50
            }.get(self.model, 0.42)
            
            cost_usd = (total_tokens / 1_000_000) * price_per_mtok
            
            self._request_count += 1
            self._total_tokens += total_tokens
            
            return (
                VolatilityPrediction(
                    level=VolatilityLevel(result['volatility_level']),
                    probability=float(result['probability']),
                    predicted_range_pct=float(result['predicted_range_pct']),
                    timeframe_minutes=int(result['timeframe_minutes']),
                    confidence_score=float(result['confidence_score']),
                    reasoning=result['reasoning'],
                    recommended_action=result['recommended_action']
                ),
                round(cost_usd, 4),
                latency_ms
            )
            
        except requests.exceptions.Timeout:
            logger.error("HolySheep API timeout (>30s)")
            raise TimeoutError("HolySheep API response timeout")
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 401:
                logger.error("HolySheep API - Invalid API key. Kiểm tra YOUR_HOLYSHEEP_API_KEY")
                raise PermissionError("Invalid HolySheep API key")
            elif e.response.status_code == 429:
                logger.warning("HolySheep API rate limit. Retry sau 60s")
                raise RateLimitError("HolySheep API rate limit exceeded")
            else:
                logger.error(f"HTTP Error: {e}")
                raise
                
    def get_usage_stats(self) -> Dict:
        """Lấy thống kê sử dụng API"""
        return {
            "total_requests": self._request_count,
            "total_tokens": self._total_tokens,
            "estimated_cost_usd": round(
                (self._total_tokens / 1_000_000) * 0.42,  # DeepSeek price
                4
            )
        }

=== DEMO USAGE ===

def demo(): """Demonstration với sample Order Book data""" client = HolySheepAIClient( api_key="YOUR_HOLYSHEEP_API_KEY", # Đăng ký: https://www.holysheep.ai/register model="deepseek-v3.2" # Model giá rẻ nhất, latency ~45ms ) # Sample Order Book (giống format từ Tardis) sample_bids = [ {"price": "67450.00", "size": "2.5"}, {"price": "67448.50", "size": "1.2"}, {"price": "67445.00", "size": "0.8"}, {"price": "67440.00", "size": "3.1"}, {"price": "67435.00", "size": "0.5"}, ] sample_asks = [ {"price": "67455.00", "size": "1.8"}, {"price": "67458.00", "size": "2.0"}, {"price": "67460.00", "size": "0.9"}, {"price": "67465.00", "size": "1.5"}, {"price": "67470.00", "size": "4.2"}, # Large wall! ] prediction, cost, latency = client.analyze_volatility( bids=sample_bids, asks=sample_asks, symbol="BTC-PERP" ) print(f"Volatility Prediction: {prediction.level.value}") print(f"Probability: {prediction.probability:.2%}") print(f"Range: ±{prediction.predicted_range_pct}%") print(f"Latency: {latency}ms") print(f"Cost: ${cost}") print(f"Action: {prediction.recommended_action}") print(f"Reasoning: {prediction.reasoning}") stats = client.get_usage_stats() print(f"Total Cost So Far: ${stats['estimated_cost_usd']}") if __name__ == "__main__": demo()

Hệ thống hoàn chỉnh - Volatility Trading System

# File: volatility_trading_system.py
"""
Hệ thống hoàn chỉnh: Tardis + HolySheep AI + Trading Logic
"""

import asyncio
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from dataclasses import dataclass, field
import json

from tardis_client import TardisClient, OrderBookSnapshot
from holy_sheep_client import HolySheepAIClient, VolatilityPrediction, VolatilityLevel

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

@dataclass
class TradingSignal:
    """Tín hiệu giao dịch"""
    timestamp: datetime
    symbol: str
    exchange: str
    action: str  # buy, sell, hold
    confidence: float
    volatility: VolatilityLevel
    predicted_move_pct: float
    entry_price: float
    stop_loss_pct: float
    take_profit_pct: float
    reasoning: str

@dataclass
class SystemStats:
    """Thống kê hệ thống"""
    start_time: datetime = field(default_factory=datetime.utcnow)
    total_predictions: int = 0
    successful_predictions: int = 0
    total_cost_usd: float = 0.0
    avg_latency_ms: float = 0.0
    tardis_reconnections: int = 0
    errors: List[str] = field(default_factory=list)

class VolatilityTradingSystem:
    """
    Hệ thống giao dịch volatility hoàn chỉnh
    Kết hợp Tardis real-time data với HolySheep AI predictions
    """
    
    def __init__(
        self,
        tardis_api_key: str,
        holy_sheep_api_key: str,
        symbols: List[str] = None,
        exchanges: List[str] = None,
        prediction_interval_seconds: int = 30
    ):
        self.tardis = TardisClient(
            api_key=tardis_api_key,
            exchanges=exchanges or ["binance"]
        )
        
        self.holy_sheep = HolySheepAIClient(
            api_key=holy_sheep_api_key,
            model="deepseek-v3.2"  # Tối ưu chi phí
        )
        
        self.symbols = symbols or ["BTC-PERP"]
        self.interval = prediction_interval_seconds
        self.stats = SystemStats()
        self._running = False
        self._latencies: List[int] = []
        
    async def start(self):
        """Khởi động hệ thống"""
        logger.info("=" * 50)
        logger.info("Khởi động Volatility Trading System")
        logger.info("=" * 50)
        
        self._running = True
        
        # Khởi động Tardis WebSocket connection
        try:
            await self.tardis.connect()
        except Exception as e:
            logger.error(f"Không thể kết nối Tardis: {e}")
            self.stats.errors.append(f"Tardis connection: {e}")
            
        # Main loop
        while self._running:
            try:
                await self._run_prediction_cycle()
                await asyncio.sleep(self.interval)
                
            except asyncio.CancelledError:
                logger.info("System shutdown requested")
                break
            except Exception as e:
                logger.error(f"Lỗi trong prediction cycle: {e}")
                self.stats.errors.append(str(e))
                await asyncio.sleep(5)  # Retry sau 5s
                
        await self.shutdown()
        
    async def _run_prediction_cycle(self):
        """Một chu kỳ dự đoán"""
        for symbol in self.symbols:
            for exchange in ["binance", "bybit"]:
                ob = self.tardis.get_order_book(exchange, symbol)
                
                if ob and len(ob.bids) >= 5 and len(ob.asks) >= 5:
                    # Chuyển đổi format
                    bids = [{"price": b.price, "size": b.size} for b in ob.bids]
                    asks = [{"price": a.price, "size": a.size} for a in ob.asks]
                    
                    # Gọi HolySheep AI
                    try:
                        prediction, cost, latency = self.holy_sheep.analyze_volatility(
                            bids=bids,
                            asks=asks,
                            symbol=symbol
                        )
                        
                        self._latencies.append(latency)
                        self.stats.total_cost_usd += cost
                        self.stats.total_predictions += 1
                        
                        # Tạo trading signal
                        signal = self._generate_signal(prediction, ob, symbol, exchange)
                        
                        # Log signal
                        self._log_signal(signal)
                        
                    except Exception as e:
                        logger.warning(f"Prediction failed for {exchange}:{symbol}: {e}")
                        
                # Chỉ cần một exchange cho mỗi symbol
                break
                
    def _generate_signal(
        self,
        prediction: VolatilityPrediction,
        orderbook: OrderBookSnapshot,
        symbol: str,
        exchange: str
    ) -> TradingSignal:
        """Tạo trading signal từ prediction"""
        
        mid_price = (orderbook.bids[0].price + orderbook.asks[0].price) / 2
        
        # Tính stop loss và take profit dựa trên predicted range
        risk_multiplier = 1.5
        reward_multiplier = 2.0
        
        if prediction.recommended_action == "buy":
            stop_loss = mid_price * (1 - prediction.predicted_range_pct / 100 * risk_multiplier)
            take_profit = mid_price * (1 + prediction.predicted_range_pct / 100 * reward_multiplier)
        elif prediction.recommended_action == "sell":
            stop_loss = mid_price * (1 + prediction.predicted_range_pct / 100 * risk_multiplier)
            take_profit = mid_price * (1 - prediction.predicted_range_pct / 100 * reward_multiplier)
        else:
            stop_loss = take_profit = mid_price
            
        return TradingSignal(
            timestamp=datetime.utcnow(),
            symbol=symbol,
            exchange=exchange,
            action=prediction.recommended_action,
            confidence=prediction.confidence_score,
            volatility=prediction.level,
            predicted_move_pct=prediction.predicted_range_pct,
            entry_price=mid_price,
            stop_loss_pct=round(abs(mid_price - stop_loss) / mid_price * 100, 2),
            take_profit_pct=round(abs(take_profit - mid_price) / mid_price * 100, 2),
            reasoning=prediction.reasoning
        )
        
    def _log_signal(self, signal: TradingSignal):
        """Log trading signal"""
        emoji = {
            "buy": "🟢",
            "sell": "🔴", 
            "hold": "🟡",
            "wait": "⚪"
        }.get(signal.action, "⚪")
        
        logger.info(
            f"{emoji} {signal.exchange}:{signal.symbol} | "
            f"Action: {signal.action.upper()} | "
            f"Vol: {signal.volatility.value} | "
            f"Range: ±{signal.predicted_move_pct}% | "
            f"Conf: {signal.confidence:.0%} | "
            f"Entry: ${signal.entry_price:,.2f}"
        )
        
    async def shutdown(self):
        """Tắt hệ thống"""
        logger.info("Đang tắt hệ thống...")
        self._running = False
        
        await self.tardis.close()
        
        # Tính stats
        if self._latencies:
            self.stats.avg_latency_ms = sum(self._latencies) / len(self._latencies)
            
        # Log summary
        logger.info("=" * 50)
        logger.info("SYSTEM SUMMARY")
        logger.info("=" * 50)
        logger.info(f"Uptime: {datetime.utcnow() - self.stats.start_time}")
        logger.info(f"Total Predictions: {self.stats.total_predictions}")
        logger.info(f"Total Cost: ${self.stats.total