Tôi vẫn nhớ rõ ngày đầu tiên triển khai chiến lược market-making trên Bitfinex. Khi đó, đội ngũ kỹ sư của tôi mất gần 3 tuần chỉ để thu thập và làm sạch dữ liệu orderbook lịch sử. Khoảng 47 triệu record giao dịch BTC/USDT trong 6 tháng nằm rải rác trên 12 bucket S3 khác nhau, mỗi bucket có format JSON khác biệt. Chưa kể vấn đề về độ trễ API Bitfinex khi test trực tiếp — chỉ 1 giây trễ trong môi trường thật cũng có thể khiến chiến lược thua lỗ đáng kể.

Bài viết này là bản hướng dẫn thực chiến cách tôi đã xây dựng pipeline hoàn chỉnh: kết nối HolySheep AI với Tardis Bitfinex API để thu thập dữ liệu orderbook và trade history, sau đó sử dụng AI để phân tích pattern và tối ưu chiến lược high-frequency trading (HFT) cho cặp BTC/ETH.

Vấn Đề Thực Tế Khi Backtest Chiến Lược HFT

Trước khi đi vào giải pháp, hãy điểm qua những thách thức phổ biến khi làm việc với dữ liệu tần suất cao:

Tardis Bitfinex + HolySheep AI: Kiến Trúc Tổng Thể

Đây là pipeline tôi đã xây dựng và đang vận hành production:

+-------------------+     +-------------------+     +-------------------+
|   Tardis API      | --> |   PostgreSQL      | --> |   HolySheep AI    |
|   (Historical     |     |   (Data           |     |   (Pattern        |
|    Data)          |     |    Warehouse)     |     |    Analysis)      |
+-------------------+     +-------------------+     +-------------------+
        |                         |                         |
   Orderbook data            Trade history            Strategy optimization
   (OHLCV, trades)          (market trades)          (GPT-4.1 analysis)
        |                         |                         |
   Bitfinex exchange      Bitfinex exchange        Signal generation
   real-time feed         historical archive      (backtest ready)
+----------------------------------------------------------+
|                   Trading Engine                          |
|         (Backtest + Paper Trade + Live Trade)            |
+----------------------------------------------------------+

Bước 1: Thu Thập Dữ Liệu Từ Tardis Bitfinex

Đầu tiên, tôi cần thu thập dữ liệu orderbook và trade history từ Tardis. Tardis cung cấp unified API cho nhiều sàn, trong đó Bitfinex được support đầy đủ.

# Cài đặt thư viện cần thiết
pip install tardis-client pandas numpy asyncpg sqlalchemy aiohttp asyncio

File: config.py

import os

Tardis Configuration

TARDIS_API_KEY = "YOUR_TARDIS_API_KEY" TARDIS_BASE_URL = "https://api.tardis.dev/v1"

Exchange Configuration

EXCHANGE = "bitfinex" SYMBOLS = ["BTC:USD", "ETH:USD", "BTC:ETH"]

Data Type Configuration

DATA_TYPES = ["book", "trade"]

PostgreSQL Configuration (lưu trữ dữ liệu sau khi xử lý)

PG_CONFIG = { "host": "localhost", "port": 5432, "database": "crypto_hft", "user": "postgres", "password": "your_secure_password" }

HolySheep Configuration - LƯU Ý: KHÔNG dùng api.openai.com

HOLYSHEEP_CONFIG = { "base_url": "https://api.holysheep.ai/v1", # Endpoint HolySheep chính thức "api_key": "YOUR_HOLYSHEEP_API_KEY", "model": "gpt-4.1" # $8/MTok - model mạnh cho phân tích chiến lược }

Backtest Configuration

BACKTEST_CONFIG = { "start_date": "2025-11-01", "end_date": "2026-05-01", "initial_capital": 10000, # USDT "fee_rate": 0.002, # 0.2% maker fee Bitfinex "slippage_ms": 50 # Giả lập 50ms network latency }

Tại sao tôi chọn PostgreSQL thay vì chỉ dùng file CSV? Vì khi làm việc với hàng chục triệu record, query trên CSV trở nên cực kỳ chậm. PostgreSQL với index phù hợp giúp tôi filter data theo timeframe cụ thể chỉ trong vài mili-giây.

# File: tardis_collector.py
import aiohttp
import asyncio
import json
from datetime import datetime, timedelta
from typing import List, Dict
import asyncpg
from sqlalchemy import create_engine, text
import pandas as pd

class TardisDataCollector:
    def __init__(self, api_key: str, base_url: str):
        self.api_key = api_key
        self.base_url = base_url
        self.headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    async def fetch_realtime_book(self, exchange: str, symbol: str, 
                                   start_date: str, end_date: str):
        """
        Thu thập orderbook history từ Tardis
        - exchange: bitfinex, binance, okex...
        - symbol: BTC:USD, ETH:USD
        - start_date/end_date: YYYY-MM-DD
        """
        url = f"{self.base_url}/feeds/{exchange}:{symbol}/book"
        params = {
            "from": start_date,
            "to": end_date,
            "format": "json",
            "limit": 50000  # Max records per request
        }
        
        async with aiohttp.ClientSession() as session:
            all_data = []
            offset = 0
            
            while True:
                params["offset"] = offset
                async with session.get(url, headers=self.headers, 
                                       params=params) as response:
                    if response.status != 200:
                        print(f"Lỗi API: {response.status}")
                        break
                    
                    data = await response.json()
                    if not data or len(data) == 0:
                        break
                    
                    all_data.extend(data)
                    print(f"Đã thu thập {len(all_data)} records...")
                    
                    if len(data) < params["limit"]:
                        break
                    offset += params["limit"]
                    
                    # Rate limit protection - Tardis giới hạn 10 req/s
                    await asyncio.sleep(0.1)
            
            return all_data
    
    async def fetch_trades(self, exchange: str, symbol: str,
                          start_date: str, end_date: str) -> List[Dict]:
        """
        Thu thập trade history từ Tardis
        Bao gồm: price, amount, side, timestamp
        """
        url = f"{self.base_url}/feeds/{exchange}:{symbol}/trades"
        params = {
            "from": start_date,
            "to": end_date,
            "format": "json",
            "limit": 100000
        }
        
        async with aiohttp.ClientSession() as session:
            all_trades = []
            offset = 0
            
            while True:
                params["offset"] = offset
                try:
                    async with session.get(url, headers=self.headers,
                                          params=params) as response:
                        if response.status == 429:
                            # Rate limit - đợi 60s
                            print("Rate limited, chờ 60s...")
                            await asyncio.sleep(60)
                            continue
                        
                        data = await response.json()
                        if not data:
                            break
                        
                        # Chuẩn hóa format
                        normalized = []
                        for trade in data:
                            normalized.append({
                                "exchange": exchange,
                                "symbol": symbol,
                                "trade_id": trade.get("id"),
                                "price": float(trade.get("price", 0)),
                                "amount": float(trade.get("amount", 0)),
                                "side": trade.get("side", "buy"),  # buy/sell
                                "timestamp": pd.to_datetime(
                                    trade.get("timestamp", 0), 
                                    unit="ms"
                                ),
                                "raw_data": json.dumps(trade)
                            })
                        
                        all_trades.extend(normalized)
                        print(f"Trades: {len(all_trades)} records")
                        
                        if len(data) < params["limit"]:
                            break
                        offset += params["limit"]
                        await asyncio.sleep(0.1)
                        
                except Exception as e:
                    print(f"Lỗi: {e}")
                    await asyncio.sleep(5)
            
            return all_trades

    async def save_to_postgres(self, trades: List[Dict], 
                               table_name: str = "bitfinex_trades"):
        """
        Lưu trữ dữ liệu vào PostgreSQL để query nhanh
        """
        pool = await asyncpg.create_pool(
            host="localhost",
            port=5432,
            database="crypto_hft",
            user="postgres",
            password="your_secure_password",
            min_size=5,
            max_size=20
        )
        
        async with pool.acquire() as conn:
            # Tạo bảng nếu chưa tồn tại
            await conn.execute(f"""
                CREATE TABLE IF NOT EXISTS {table_name} (
                    id SERIAL PRIMARY KEY,
                    exchange VARCHAR(20),
                    symbol VARCHAR(20),
                    trade_id BIGINT,
                    price DECIMAL(20, 8),
                    amount DECIMAL(20, 12),
                    side VARCHAR(10),
                    timestamp TIMESTAMP,
                    raw_data JSONB,
                    created_at TIMESTAMP DEFAULT NOW()
                )
            """)
            
            # Tạo index để query nhanh
            await conn.execute(f"""
                CREATE INDEX IF NOT EXISTS idx_{table_name}_timestamp 
                ON {table_name}(timestamp)
            """)
            await conn.execute(f"""
                CREATE INDEX IF NOT EXISTS idx_{table_name}_symbol 
                ON {table_name}(symbol)
            """)
            
            # Batch insert để tăng tốc
            batch_size = 5000
            for i in range(0, len(trades), batch_size):
                batch = trades[i:i + batch_size]
                await conn.executemany("""
                    INSERT INTO bitfinex_trades 
                    (exchange, symbol, trade_id, price, amount, side, timestamp, raw_data)
                    VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
                """, [(t["exchange"], t["symbol"], t["trade_id"], 
                      t["price"], t["amount"], t["side"], 
                      t["timestamp"], t["raw_data"]) for t in batch])
                
                print(f"Đã lưu {min(i + batch_size, len(trades))}/{len(trades)} records")
        
        await pool.close()

Chạy collector

async def main(): collector = TardisDataCollector( api_key="YOUR_TARDIS_API_KEY", base_url="https://api.tardis.dev/v1" ) # Thu thập 1 tuần dữ liệu BTC/USD làm demo trades = await collector.fetch_trades( exchange="bitfinex", symbol="BTC:USD", start_date="2026-05-18", end_date="2026-05-25" ) if trades: await collector.save_to_postgres(trades) print(f"Hoàn thành! Đã lưu {len(trades)} trades") if __name__ == "__main__": asyncio.run(main())

Bước 2: Phân Tích Chiến Lược Với HolySheep AI

Đây là phần quan trọng nhất — sử dụng HolySheep AI để phân tích pattern từ dữ liệu lịch sử và đề xuất chiến lược tối ưu. Tôi đã thử nghiệm với nhiều model khác nhau và kết quả thực sự ấn tượng.

# File: holysheep_strategy_analyzer.py
import aiohttp
import asyncio
import json
import pandas as pd
from datetime import datetime, timedelta

class HolySheepStrategyAnalyzer:
    """
    Sử dụng HolySheep AI để phân tích dữ liệu orderbook
    và đề xuất chiến lược HFT tối ưu
    
    LƯU Ý QUAN TRỌNG:
    - base_url: https://api.holysheep.ai/v1 (KHÔNG phải api.openai.com)
    - api_key: YOUR_HOLYSHEEP_API_KEY
    - Model gợi ý: gpt-4.1 ($8/MTok) cho phân tích phức tạp
    """
    
    def __init__(self, api_key: str, base_url: str = "https://api.holysheep.ai/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.pricing = {
            "gpt-4.1": {"input": 8, "output": 8, "currency": "USD"},
            "claude-sonnet-4.5": {"input": 15, "output": 15, "currency": "USD"},
            "gemini-2.5-flash": {"input": 2.5, "output": 10, "currency": "USD"},
            "deepseek-v3.2": {"input": 0.42, "output": 2.80, "currency": "USD"}
        }
    
    async def analyze_orderbook_pattern(self, orderbook_data: dict) -> dict:
        """
        Phân tích orderbook data để tìm:
        - Order flow imbalance
        - Support/Resistance levels
        - Volatility patterns
        """
        prompt = f"""
        Bạn là chuyên gia phân tích chiến lược HFT (High-Frequency Trading).
        Hãy phân tích dữ liệu orderbook sau và đưa ra chiến lược tối ưu:

        ORDERBOOK DATA:
        {json.dumps(orderbook_data, indent=2)}

        YÊU CẦU:
        1. Phân tích order flow imbalance (OFI)
        2. Xác định các mức support/resistance quan trọng
        3. Tính toán optimal spread cho market-making
        4. Đề xuất entry/exit points với stop-loss và take-profit
        5. Ước tính expected return và risk parameters

        Output theo format JSON:
        {{
            "analysis": {{
                "order_imbalance": float,
                "bid_ask_spread_pct": float,
                "volatility_score": float,
                "liquidity_score": float
            }},
            "strategy": {{
                "action": "buy|sell|hold",
                "entry_price": float,
                "stop_loss": float,
                "take_profit": float,
                "position_size_pct": float,
                "confidence_score": float
            }},
            "risk_metrics": {{
                "max_drawdown_estimate": float,
                "sharpe_ratio_estimate": float,
                "win_rate_estimate": float
            }}
        }}
        """
        
        response = await self._call_api(
            model="gpt-4.1",
            messages=[
                {"role": "system", "content": "Bạn là chuyên gia HFT trading."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3  # Low temperature cho phân tích kỹ thuật
        )
        
        return response
    
    async def backtest_with_ai(self, trades_df: pd.DataFrame,
                               strategy_params: dict) -> dict:
        """
        Chạy backtest với sự hỗ trợ của AI để optimize parameters
        """
        # Sample data để gửi cho AI (không gửi full dataset)
        sample_trades = trades_df.tail(1000).to_dict('records')
        
        prompt = f"""
        Tôi có dữ liệu backtest với các tham số chiến lược sau:
        
        STRATEGY PARAMS:
        {json.dumps(strategy_params, indent=2)}
        
        SAMPLE TRADES (1000 records gần nhất):
        {json.dumps(sample_trades[:10], indent=2)}  # Chỉ gửi 10 record mẫu
        
        Thống kê tổng quan:
        - Tổng số trades: {len(trades_df)}
        - Date range: {trades_df['timestamp'].min()} đến {trades_df['timestamp'].max()}
        - Giá trung bình: ${trades_df['price'].mean():.2f}
        - Volatility (std): ${trades_df['price'].std():.2f}
        - Volume trung bình/ngày: {trades_df['amount'].sum() / trades_df['timestamp'].dt.date.nunique():.4f}
        
        Hãy:
        1. Đề xuất các tham số tối ưu (lookback period, threshold, position sizing)
        2. Phân tích các edge cases và cách xử lý
        3. Ước tính performance metrics dựa trên data
        
        Output format JSON:
        {{
            "optimized_params": {{...}},
            "performance_estimates": {{...}},
            "edge_case_handling": [...]
        }}
        """
        
        response = await self._call_api(
            model="deepseek-v3.2",  # Model rẻ cho optimization task
            messages=[
                {"role": "system", "content": "Bạn là chuyên gia quantitative trading."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.5
        )
        
        return response
    
    async def generate_trading_signals(self, market_data: dict) -> list:
        """
        Generate real-time trading signals từ market data
        """
        prompt = f"""
        Market Data:
        {json.dumps(market_data, indent=2)}
        
        Hãy generate 5 trading signals theo format:
        - signal_id: string
        - action: BUY/SELL/HOLD
        - confidence: 0-100
        - reasoning: string
        - risk_level: LOW/MEDIUM/HIGH
        """
        
        response = await self._call_api(
            model="gpt-4.1",
            messages=[
                {"role": "system", "content": "Bạn là AI trading assistant."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.7
        )
        
        return response
    
    async def _call_api(self, model: str, messages: list, temperature: float = 0.7):
        """
        Gọi HolySheep AI API
        """
        url = f"{self.base_url}/chat/completions"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        payload = {
            "model": model,
            "messages": messages,
            "temperature": temperature,
            "max_tokens": 4000
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=headers, 
                                    json=payload) as response:
                if response.status != 200:
                    error = await response.text()
                    raise Exception(f"API Error: {error}")
                
                result = await response.json()
                
                # Parse và return response
                content = result["choices"][0]["message"]["content"]
                
                # Thử parse JSON
                try:
                    return json.loads(content)
                except:
                    return {"text": content}
    
    def estimate_cost(self, model: str, input_tokens: int, 
                     output_tokens: int) -> dict:
        """
        Ước tính chi phí API
        """
        price = self.pricing.get(model, self.pricing["gpt-4.1"])
        
        input_cost = (input_tokens / 1_000_000) * price["input"]
        output_cost = (output_tokens / 1_000_000) * price["output"]
        total_cost = input_cost + output_cost
        
        return {
            "model": model,
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "input_cost_usd": round(input_cost, 4),
            "output_cost_usd": round(output_cost, 4),
            "total_cost_usd": round(total_cost, 4),
            "vs_openai_savings": round(total_cost * 0.85, 4)  # Tiết kiệm 85%
        }

Ví dụ sử dụng

async def main(): analyzer = HolySheepStrategyAnalyzer( api_key="YOUR_HOLYSHEEP_API_KEY" ) # Demo orderbook data sample_orderbook = { "timestamp": "2026-05-25T10:00:00Z", "bids": [ {"price": 67500.00, "amount": 2.5}, {"price": 67495.00, "amount": 1.8}, {"price": 67490.00, "amount": 3.2} ], "asks": [ {"price": 67510.00, "amount": 2.1}, {"price": 67515.00, "amount": 1.5}, {"price": 67520.00, "amount": 4.0} ], "spread": 10.00, "spread_pct": 0.0148 } # Phân tích với AI result = await analyzer.analyze_orderbook_pattern(sample_orderbook) print("Kết quả phân tích:") print(json.dumps(result, indent=2)) # Ước tính chi phí cost = analyzer.estimate_cost("gpt-4.1", 1500, 800) print(f"\nChi phí ước tính: ${cost['total_cost_usd']}") print(f"Tiết kiệm so với OpenAI: ${cost['vs_openai_savings']}") if __name__ == "__main__": asyncio.run(main())

Bước 3: Xây Dựng Backtest Engine Hoàn Chỉnh

# File: backtest_engine.py
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from dataclasses import dataclass
from typing import List, Dict, Optional
import json

@dataclass
class Trade:
    timestamp: datetime
    action: str  # BUY, SELL
    price: float
    amount: float
    fee: float
    slippage: float

@dataclass
class BacktestResult:
    total_trades: int
    winning_trades: int
    losing_trades: int
    total_pnl: float
    max_drawdown: float
    sharpe_ratio: float
    win_rate: float
    avg_profit: float
    avg_loss: float
    profit_factor: float

class HFTBacktestEngine:
    """
    Backtest engine cho chiến lược HFT
    - Tính slippage thực tế (50ms latency simulation)
    - Fee structure Bitfinex (0.2% maker, 0.1% if >$1M volume)
    - Real-time orderbook simulation
    """
    
    def __init__(self, initial_capital: float = 10000,
                 fee_rate: float = 0.002,
                 slippage_ms: int = 50):
        self.initial_capital = initial_capital
        self.fee_rate = fee_rate
        self.slippage_ms = slippage_ms
        self.balance = initial_capital
        self.position = 0  # Số BTC nắm giữ
        self.trades: List[Trade] = []
        self.equity_curve = []
        
        # Performance tracking
        self.peak_balance = initial_capital
        self.drawdowns = []
    
    def calculate_slippage(self, price: float, side: str, 
                          volatility: float) -> float:
        """
        Tính slippage dựa trên:
        - Network latency simulation
        - Market volatility
        - Order size
        
        Thực tế: 50ms latency ≈ 0.05-0.15% slippage cho BTC
        """
        # Base slippage từ latency
        latency_slippage = (self.slippage_ms / 1000) * volatility * 0.01
        
        # Size slippage (larger orders = more slippage)
        size_factor = min(1.0, self.position * price / self.balance * 10)
        
        # Random component
        random_factor = np.random.uniform(0.9, 1.1)
        
        total_slippage = latency_slippage * (1 + size_factor) * random_factor
        
        if side == "SELL":
            return -abs(price * total_slippage)
        else:
            return abs(price * total_slippage)
    
    def execute_trade(self, timestamp: datetime, action: str,
                     price: float, amount: float, 
                     volatility: float = 0.001) -> Trade:
        """
        Thực thi trade với slippage và fee
        """
        slippage = self.calculate_slippage(price, action, volatility)
        execution_price = price + slippage
        
        # Tính fee (maker fee)
        fee = abs(execution_price * amount * self.fee_rate)
        
        trade = Trade(
            timestamp=timestamp,
            action=action,
            price=execution_price,
            amount=amount,
            fee=fee,
            slippage=slippage
        )
        
        self.trades.append(trade)
        return trade
    
    def update_equity(self, current_price: float):
        """
        Cập nhật equity curve
        """
        total_equity = self.balance + (self.position * current_price)
        self.equity_curve.append(total_equity)
        
        # Track peak và drawdown
        if total_equity > self.peak_balance:
            self.peak_balance = total_equity
        
        drawdown = (self.peak_balance - total_equity) / self.peak_balance
        self.drawdowns.append(drawdown)
        
        return total_equity
    
    def run_backtest(self, trades_df: pd.DataFrame, 
                    signals: List[Dict]) -> BacktestResult:
        """
        Chạy backtest với trade history và signals
        
        signals format:
        [
            {"timestamp": datetime, "action": "BUY/SELL", "confidence": 0-100},
            ...
        ]
        """
        print(f"Bắt đầu backtest với {len(trades_df)} trades...")
        
        # Convert signals to dict for quick lookup
        signal_dict = {s["timestamp"]: s for s in signals}
        
        trades_df = trades_df.sort_values("timestamp")
        
        for idx, row in trades_df.iterrows():
            current_time = row["timestamp"]
            current_price = row["price"]
            
            # Calculate volatility from recent trades
            recent_prices = trades_df[
                trades_df["timestamp"] <= current_time
            ]["price"].tail(100)
            volatility = recent_prices.std() / recent_prices.mean() if len(recent_prices) > 1 else 0.001
            
            # Check for signal
            if current_time in signal_dict:
                signal = signal_dict[current_time]
                
                if signal["action"] == "BUY" and signal["confidence"] > 70:
                    # Calculate position size (risk 2% per trade)
                    risk_amount = self.balance * 0.02
                    position_size = risk_amount / (current_price * 0.02)  # 2% stop loss
                    position_size = min(position_size, self.balance / current_price * 0.1)  # Max 10% cap
                    
                    if self.balance >= position_size * current_price:
                        trade = self.execute_trade(
                            current_time, "BUY", current_price, position_size, volatility
                        )
                        self.balance -= (trade.price * trade.amount + trade.fee)
                        self.position += trade.amount
                        
                elif signal["action"] == "SELL" and self.position > 0:
                    trade = self.execute_trade(
                        current_time, "SELL", current_price, self.position, volatility
                    )
                    self.balance += (trade.price * trade.amount - trade.fee)
                    self.position = 0
            
            # Update equity
            self.update_equity(current_price)
        
        return self.generate_report()
    
    def generate_report(self) -> BacktestResult:
        """
        Generate backtest report
        """
        if not self.trades:
            return BacktestResult(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
        
        # Calculate PnL per trade
        trades_df = pd.DataFrame([
            {
                "action": t.action,
                "price": t.price,
                "amount": t.amount,
                "fee": t.fee,
                "pnl": t.price * t.amount if t.action == "SELL" else 0
            } for t in self.trades
        ])
        
        winning = trades_df[trades_df["pnl"] > 0]
        losing = trades_df[trades_df["pnl"] <= 0]
        
        total_pnl = self.balance + (self.position * self.trades[-1].price if self.trades else 0) - self.initial_capital
        
        # Sharpe ratio
        returns = pd.Series(self.equity_curve).pct_change().dropna()
        sharpe = returns.mean() / returns.std() * np.sqrt(252 * 24 * 60) if returns.std() > 0 else 0
        
        return BacktestResult(
            total_trades=len(self.trades),
            winning_trades=len(winning),
            losing_trades=len(losing),
            total_pnl=total_pnl,
            max_drawdown=max(self.drawdowns) if self.drawdowns else 0,
            sharpe_ratio=sharpe,
            win_rate=len(winning) / len(self.trades) if self.trades else 0,
            avg_profit=winning["pnl"].mean() if len(winning) > 0 else 0,
            avg_loss=losing["pnl"].mean() if len(losing) > 0 else 0,
            profit_factor=abs(winning["pnl"].sum() / losing["pnl"].sum()) if len(losing) > 0 and losing["pnl"].sum() != 0 else 0
        )

Chạy backtest

async def run_full_backtest(): # Load data từ PostgreSQL from sqlalchemy import create_engine import asyncio engine = create_engine("postgresql://postgres:password@localhost:5432/crypto_hft") # Load 1 tháng dữ liệu query = """ SELECT timestamp, price, amount, side FROM bitfinex_trades WHERE symbol = 'BTC:USD' AND timestamp >= '2026-04-01' AND timestamp < '2026-05-01' ORDER BY timestamp """ trades_df = pd.read_sql(query, engine) print(f"Loaded {len(trades_df)} trades") # Initialize backtest engine backtest = HFTBacktestEngine( initial_capital=10000, fee_rate=0.002, slippage_ms=50 ) # Generate sample signals (thực tế sẽ dùng AI) signals = [ {"timestamp": t, "action": "BUY", "confidence": 85} for t in trades_df.iloc[::100]["timestamp"] # Mỗi 100 record ] # Run backtest result = backtest.run_backtest(trades_df, signals) print("\n" + "="*50) print("BACKTEST RESULTS") print("="*50) print(f"Total Trades: {result