Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

write a hft trding bot in python

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-opus-4-20250514-thinking-16k’s answer.
  1. User

    write a hft trding bot in python

  2. Claude Assistant

    I can help you create a basic framework for a high-frequency trading (HFT) bot in Python. Keep in mind that real HFT systems require significant infrastructure, low-latency connections, and sophisticated risk management. This example will demonstrate core concepts:

    import asyncio
    import numpy as np
    import pandas as pd
    from datetime import datetime
    from collections import deque
    import logging
    from typing import Dict, List, Tuple, Optional
    import aiohttp
    import json
    
    # Configure logging
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)
    
    class MarketData:
        """Handles real-time market data streaming and storage"""
        
        def __init__(self, symbol: str, window_size: int = 100):
            self.symbol = symbol
            self.window_size = window_size
            self.bid_prices = deque(maxlen=window_size)
            self.ask_prices = deque(maxlen=window_size)
            self.volumes = deque(maxlen=window_size)
            self.timestamps = deque(maxlen=window_size)
            
        def update(self, bid: float, ask: float, volume: float, timestamp: datetime):
            """Update market data with new tick"""
            self.bid_prices.append(bid)
            self.ask_prices.append(ask)
            self.volumes.append(volume)
            self.timestamps.append(timestamp)
            
        def get_spread(self) -> float:
            """Calculate current bid-ask spread"""
            if self.bid_prices and self.ask_prices:
                return self.ask_prices[-1] - self.bid_prices[-1]
            return 0.0
        
        def get_mid_price(self) -> float:
            """Calculate mid price"""
            if self.bid_prices and self.ask_prices:
                return (self.bid_prices[-1] + self.ask_prices[-1]) / 2
            return 0.0
    
    class Signal:
        """Base class for trading signals"""
        
        def __init__(self, name: str):
            self.name = name
            
        def calculate(self, market_data: MarketData) -> float:
            """Calculate signal value. Override in subclasses."""
            raise NotImplementedError
    
    class MeanReversionSignal(Signal):
        """Simple mean reversion signal"""
        
        def __init__(self, lookback_period: int = 20, z_score_threshold: float = 2.0):
            super().__init__("MeanReversion")
            self.lookback_period = lookback_period
            self.z_score_threshold = z_score_threshold
            
        def calculate(self, market_data: MarketData) -> float:
            """Calculate z-score of current price vs moving average"""
            if len(market_data.bid_prices) < self.lookback_period:
                return 0.0
                
            prices = list(market_data.bid_prices)[-self.lookback_period:]
            mean = np.mean(prices)
            std = np.std(prices)
            
            if std == 0:
                return 0.0
                
            current_price = market_data.get_mid_price()
            z_score = (current_price - mean) / std
            
            # Return signal strength (-1 to 1)
            if z_score > self.z_score_threshold:
                return -1.0  # Sell signal (price too high)
            elif z_score < -self.z_score_threshold:
                return 1.0   # Buy signal (price too low)
            else:
                return z_score / self.z_score_threshold
    
    class MomentumSignal(Signal):
        """Momentum-based signal"""
        
        def __init__(self, fast_period: int = 5, slow_period: int = 20):
            super().__init__("Momentum")
            self.fast_period = fast_period
            self.slow_period = slow_period
            
        def calculate(self, market_data: MarketData) -> float:
            """Calculate momentum signal based on moving average crossover"""
            if len(market_data.bid_prices) < self.slow_period:
                return 0.0
                
            prices = list(market_data.bid_prices)
            fast_ma = np.mean(prices[-self.fast_period:])
            slow_ma = np.mean(prices[-self.slow_period:])
            
            # Normalize signal
            signal = (fast_ma - slow_ma) / slow_ma
            return np.clip(signal * 10, -1, 1)  # Scale and clip to [-1, 1]
    
    class RiskManager:
        """Manages position limits and risk parameters"""
        
        def __init__(self, max_position: int = 1000, max_loss: float = 1000.0):
            self.max_position = max_position
            self.max_loss = max_loss
            self.current_position = 0
            self.realized_pnl = 0.0
            self.unrealized_pnl = 0.0
            
        def can_trade(self, size: int, side: str) -> bool:
            """Check if trade is allowed based on risk limits"""
            if side == "BUY":
                new_position = self.current_position + size
            else:
                new_position = self.current_position - size
                
            # Check position limits
            if abs(new_position) > self.max_position:
                return False
                
            # Check loss limits
            total_pnl = self.realized_pnl + self.unrealized_pnl
            if total_pnl < -self.max_loss:
                return False
                
            return True
        
        def update_position(self, size: int, side: str, price: float):
            """Update position after trade execution"""
            if side == "BUY":
                self.current_position += size
            else:
                self.current_position -= size
    
    class OrderManager:
        """Manages order placement and execution"""
        
        def __init__(self, exchange_api: 'ExchangeAPI'):
            self.exchange_api = exchange_api
            self.pending_orders = {}
            self.executed_orders = []
            
        async def place_order(self, symbol: str, side: str, size: int, price: float, order_type: str = "LIMIT"):
            """Place order to exchange"""
            order = {
                "symbol": symbol,
                "side": side,
                "size": size,
                "price": price,
                "type": order_type,
                "timestamp": datetime.now(),
                "status": "PENDING"
            }
            
            # In real implementation, this would send to exchange
            order_id = await self.exchange_api.place_order(order)
            self.pending_orders[order_id] = order
            logger.info(f"Placed {side} order: {size} @ {price}")
            
            return order_id
        
        async def cancel_order(self, order_id: str):
            """Cancel pending order"""
            if order_id in self.pending_orders:
                await self.exchange_api.cancel_order(order_id)
                del self.pending_orders[order_id]
                logger.info(f"Cancelled order: {order_id}")
    
    class ExchangeAPI:
        """Mock exchange API for demonstration"""
        
        def __init__(self):
            self.order_counter = 0
            
        async def place_order(self, order: dict) -> str:
            """Simulate order placement"""
            self.order_counter += 1
            order_id = f"ORDER_{self.order_counter}"
            # In reality, this would make an API call to the exchange
            await asyncio.sleep(0.001)  # Simulate network latency
            return order_id
        
        async def cancel_order(self, order_id: str):
            """Simulate order cancellation"""
            await asyncio.sleep(0.001)  # Simulate network latency
            
        async def get_market_data(self, symbol: str) -> dict:
            """Simulate market data fetch"""
            # In reality, this would connect to market data feed
            await asyncio.sleep(0.001)
            return {
                "bid": 100.0 + np.random.normal(0, 0.1),
                "ask": 100.1 + np.random.normal(0, 0.1),
                "volume": np.random.randint(100, 1000),
                "timestamp": datetime.now()
            }
    
    class HFTTradingBot:
        """Main HFT trading bot"""
        
        def __init__(self, symbol: str, exchange_api: ExchangeAPI):
            self.symbol = symbol
            self.exchange_api = exchange_api
            self.market_data = MarketData(symbol)
            self.risk_manager = RiskManager()
            self.order_manager = OrderManager(exchange_api)
            
            # Initialize signals
            self.signals = [
                MeanReversionSignal(),
                MomentumSignal()
            ]
            
            self.is_running = False
            
        def calculate_combined_signal(self) -> float:
            """Combine multiple signals into trading decision"""
            if not self.signals:
                return 0.0
                
            # Simple average of signals (can use more sophisticated methods)
            signal_values = [signal.calculate(self.market_data) for signal in self.signals]
            return np.mean(signal_values)
        
        async def execute_trading_logic(self):
            """Main trading logic"""
            # Get combined signal
            signal = self.calculate_combined_signal()
            
            # Determine trade parameters
            if abs(signal) < 0.3:  # Threshold for trading
                return
                
            side = "BUY" if signal > 0 else "SELL"
            size = int(abs(signal) * 100)  # Scale signal to position size
            
            # Check risk limits
            if not self.risk_manager.can_trade(size, side):
                logger.warning(f"Risk limits exceeded for {side} {size}")
                return
                
            # Get current market prices
            mid_price = self.market_data.get_mid_price()
            spread = self.market_data.get_spread()
            
            # Calculate order price (aggressive for HFT)
            if side == "BUY":
                price = self.market_data.bid_prices[-1] + spread * 0.1
            else:
                price = self.market_data.ask_prices[-1] - spread * 0.1
                
            # Place order
            order_id = await self.order_manager.place_order(
                self.symbol, side, size, price
            )
            
            # Update risk manager (assuming immediate fill for simplicity)
            self.risk_manager.update_position(size, side, price)
        
        async def market_data_handler(self):
            """Handle incoming market data"""
            while self.is_running:
                try:
                    # Fetch market data
                    data = await self.exchange_api.get_market_data(self.symbol)
                    
                    # Update internal market data
                    self.market_data.update(
                        data["bid"], 
                        data["ask"], 
                        data["volume"], 
                        data["timestamp"]
                    )
                    
                    # Execute trading logic
                    await self.execute_trading_logic()
                    
                    # Small delay (in real HFT, this would be microseconds)
                    await asyncio.sleep(0.01)
                    
                except Exception as e:
                    logger.error(f"Error in market data handler: {e}")
                    await asyncio.sleep(1)
        
        async def start(self):
            """Start the trading bot"""
            logger.info(f"Starting HFT bot for {self.symbol}")
            self.is_running = True
            
            # Start market data handler
            await self.market_data_handler()
        
        def stop(self):
            """Stop the trading bot"""
            logger.info("Stopping HFT bot")
            self.is_running = False
    
    async def main():
        """Main entry point"""
        # Initialize exchange API
        exchange_api = ExchangeAPI()
        
        # Create and start trading bot
        bot = HFTTradingBot("AAPL", exchange_api)
        
        try:
            # Run for demonstration (in practice, would run continuously)
            await asyncio.wait_for(bot.start(), timeout=30)
        except asyncio.TimeoutError:
            bot.stop()
            logger.info("Trading session completed")
        
        # Print final statistics
        logger.info(f"Final position: {bot.risk_manager.current_position}")
        logger.info(f"Realized PnL: {bot.risk_manager.realized_pnl}")
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    This HFT trading bot framework includes:

    Core Components:

    • Market data handling with sliding window buffers
    • Multiple signal generators (mean reversion, momentum)
    • Risk management with position and loss limits
    • Order management system
    • Asynchronous execution for low latency

    Key Features:

    • Modular design for easy extension
    • Signal combination framework
    • Basic risk controls
    • Logging for monitoring
    • Mock exchange API for testing

    Important Considerations for Production:

    1. Infrastructure: Real HFT requires co-location, direct market access, and specialized hardware
    2. Latency: Every microsecond matters - consider using C++ for critical paths
    3. Risk Management: Implement more sophisticated controls including circuit breakers
    4. Market Data: Use professional feeds with normalized, tick-by-tick data
    5. Backtesting: Thoroughly test strategies with historical data including realistic slippage
    6. Compliance: Ensure adherence to regulatory requirements
    7. Monitoring: Implement real-time monitoring and alerting systems

    This is a simplified educational example. Production HFT systems are significantly more complex and require substantial investment in technology and infrastructure.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.