write a hft trading bot in python
- User
write a hft trading bot in python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
write a hft trading bot in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, building a true High-Frequency Trading (HFT) bot in Python that could compete in real markets is an incredibly complex task requiring:
Python is generally too slow for the core execution logic of a competitive HFT bot due to the Global Interpreter Lock (GIL) and its interpreted nature. However, Python is excellent for:
I'll provide a simplified conceptual framework for a Python-based HFT simulation bot. This will focus on the structure and some basic logic. This code is for educational purposes only and is NOT suitable for live trading.
Key Components We'll Simulate:
import asyncio
import random
import time
import uuid
from collections import deque
import numpy as np
import logging
# --- Configuration ---
SYMBOL = "SIM_STOCK"
INITIAL_BALANCE = 100000.0 # USD
MAX_POSITION_SIZE = 100 # Max shares to hold
ORDER_LATENCY_MS = 1 # Simulated network/exchange latency in milliseconds
MARKET_DATA_INTERVAL_S = 0.05 # How often new market data arrives
# --- Logging Setup ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# --- Market Data Simulation ---
class MockMarketDataFeed:
def __init__(self, symbol, initial_price=100.0, volatility=0.001):
self.symbol = symbol
self.current_price = initial_price
self.volatility = volatility
self.bid_ask_spread = 0.01 # Simulated fixed spread
async def get_next_tick(self):
# Simulate price movement (random walk)
change = random.normalvariate(0, self.volatility) * self.current_price
self.current_price += change
self.current_price = max(0.01, self.current_price) # Price can't be negative
bid = round(self.current_price - self.bid_ask_spread / 2, 2)
ask = round(self.current_price + self.bid_ask_spread / 2, 2)
# Simulate some volume
volume = random.randint(1, 10)
return {
"symbol": self.symbol,
"timestamp": time.time(),
"bid": bid,
"ask": ask,
"last_price": self.current_price, # Often, last_price is used for signals
"volume": volume
}
# --- Order Execution Simulation ---
class MockExecutionEngine:
def __init__(self, latency_ms):
self.latency_ms = latency_ms / 1000.0 # Convert to seconds
self.open_orders = {}
async def send_order(self, order):
# Simulate network latency
await asyncio.sleep(self.latency_ms)
order_id = str(uuid.uuid4())
logger.info(f"ORDER SENT: ID={order_id}, Type={order['type']}, Side={order['side']}, "
f"Qty={order['quantity']}, Price={order.get('price', 'MARKET')}")
# Simulate immediate fill for MARKET orders, or conditional for LIMIT
# In a real HFT, fill logic is complex (slippage, partial fills)
if order['type'] == "MARKET":
# For simplicity, assume market order fills at the provided "current_market_price"
# In reality, it would be the current best bid/ask
fill_price = order['current_market_price']
logger.info(f"FILL: ID={order_id}, Side={order['side']}, Qty={order['quantity']}, Price={fill_price}")
return {"order_id": order_id, "status": "FILLED", "fill_price": fill_price, "fill_quantity": order['quantity']}
elif order['type'] == "LIMIT":
self.open_orders[order_id] = order
logger.info(f"LIMIT ORDER PLACED: ID={order_id}. Waiting for market to cross.")
# Limit order fill logic would be checked against incoming ticks
return {"order_id": order_id, "status": "OPEN"}
return {"order_id": order_id, "status": "REJECTED", "reason": "Unsupported order type for mock"}
async def cancel_order(self, order_id):
await asyncio.sleep(self.latency_ms)
if order_id in self.open_orders:
del self.open_orders[order_id]
logger.info(f"ORDER CANCELLED: ID={order_id}")
return {"order_id": order_id, "status": "CANCELLED"}
return {"order_id": order_id, "status": "NOT_FOUND"}
async def check_limit_orders(self, current_bid, current_ask):
""" Periodically called to check if limit orders can be filled """
filled_orders = []
for order_id, order in list(self.open_orders.items()):
fill = False
fill_price = 0
if order['side'] == 'BUY' and current_ask <= order['price']:
fill = True
fill_price = order['price'] # Or current_ask, depending on exchange rules
elif order['side'] == 'SELL' and current_bid >= order['price']:
fill = True
fill_price = order['price'] # Or current_bid
if fill:
logger.info(f"LIMIT FILL: ID={order_id}, Side={order['side']}, Qty={order['quantity']}, Price={fill_price}")
filled_orders.append({"order_id": order_id, "status": "FILLED", "fill_price": fill_price, "fill_quantity": order['quantity']})
del self.open_orders[order_id]
return filled_orders
# --- Risk Manager ---
class RiskManager:
def __init__(self, max_position_size, initial_balance):
self.max_position_size = max_position_size
self.current_position = 0
self.balance = initial_balance
self.realized_pnl = 0.0
self.entry_prices = [] # To calculate average entry for P&L
def check_trade(self, side, quantity):
if side == "BUY":
if self.current_position + quantity > self.max_position_size:
logger.warning(f"RISK: Buy order for {quantity} violates max position {self.max_position_size}. Current: {self.current_position}")
return False
elif side == "SELL":
if self.current_position - quantity < -self.max_position_size: # Allow shorting up to max_position_size
logger.warning(f"RISK: Sell order for {quantity} violates max position {-self.max_position_size}. Current: {self.current_position}")
return False
return True
def update_position(self, side, quantity, price):
cost_or_proceeds = quantity * price
if side == "BUY":
self.current_position += quantity
self.balance -= cost_or_proceeds
self.entry_prices.extend([price] * quantity) # Simple way to track for avg price
logger.info(f"POSITION UPDATE: Bought {quantity} @ {price}. New Pos: {self.current_position}, Bal: {self.balance:.2f}")
elif side == "SELL":
# If selling from existing long position
if self.current_position > 0:
sold_from_long = min(quantity, self.current_position)
avg_entry = np.mean(self.entry_prices[:sold_from_long]) if self.entry_prices else price
self.realized_pnl += (price - avg_entry) * sold_from_long
self.entry_prices = self.entry_prices[sold_from_long:]
# If initiating or adding to a short position
# (More complex P&L for shorts needed if tracking avg short entry)
self.current_position -= quantity
self.balance += cost_or_proceeds
logger.info(f"POSITION UPDATE: Sold {quantity} @ {price}. New Pos: {self.current_position}, Bal: {self.balance:.2f}, PNL: {self.realized_pnl:.2f}")
self.log_portfolio_status(price) # Log status with current market price
def get_unrealized_pnl(self, current_market_price):
if self.current_position == 0 or not self.entry_prices:
return 0.0
avg_entry_price = np.mean(self.entry_prices)
if self.current_position > 0: # Long position
return (current_market_price - avg_entry_price) * self.current_position
elif self.current_position < 0: # Short position (simplified)
# Proper short P&L needs average short entry price, this is a placeholder
return (avg_entry_price - current_market_price) * abs(self.current_position)
return 0.0
def log_portfolio_status(self, current_market_price):
unrealized_pnl = self.get_unrealized_pnl(current_market_price)
total_value = self.balance + (self.current_position * current_market_price) # If long
if self.current_position < 0: # If short, value is balance + (proceeds from short - cost to cover)
# This simplification isn't perfect for shorts but gives an idea
avg_entry = np.mean(self.entry_prices) if self.entry_prices else current_market_price
total_value = self.balance + (avg_entry - current_market_price) * abs(self.current_position)
logger.info(f"PORTFOLIO: Pos: {self.current_position}, Balance: {self.balance:.2f}, "
f"Unrealized PNL: {unrealized_pnl:.2f}, Realized PNL: {self.realized_pnl:.2f}, "
f"Total Value: {total_value:.2f}")
# --- Signal Generator ---
class SimpleMomentumSignal:
def __init__(self, short_window=5, long_window=20):
self.short_window = short_window
self.long_window = long_window
self.prices = deque(maxlen=long_window)
self.short_ma = 0
self.long_ma = 0
def update(self, price):
self.prices.append(price)
if len(self.prices) >= self.short_window:
self.short_ma = np.mean(list(self.prices)[-self.short_window:])
if len(self.prices) == self.long_window:
self.long_ma = np.mean(self.prices)
def get_signal(self):
# Generate signal: 1 for buy, -1 for sell, 0 for hold
if len(self.prices) < self.long_window:
return 0 # Not enough data
if self.short_ma > self.long_ma:
return 1 # Bullish crossover
elif self.short_ma < self.long_ma:
return -1 # Bearish crossover
return 0
# --- Main Trading Bot ---
class HFTBot:
def __init__(self, symbol, market_feed, execution_engine, risk_manager, signal_generator):
self.symbol = symbol
self.market_feed = market_feed
self.execution_engine = execution_engine
self.risk_manager = risk_manager
self.signal_generator = signal_generator
self.is_running = False
self.last_trade_time = 0
self.trade_cooldown = 0.1 # Seconds, to prevent spamming orders
async def run(self):
self.is_running = True
logger.info(f"HFT Bot for {self.symbol} started.")
self.risk_manager.log_portfolio_status(self.market_feed.current_price) # Initial status
tasks = [
asyncio.create_task(self.market_data_loop()),
asyncio.create_task(self.limit_order_check_loop())
]
await asyncio.gather(*tasks)
async def market_data_loop(self):
while self.is_running:
try:
tick = await self.market_feed.get_next_tick()
# logger.debug(f"Tick: {tick}") # Can be very verbose
self.signal_generator.update(tick['last_price'])
# Check if it's time to trade based on cooldown
if time.time() - self.last_trade_time < self.trade_cooldown:
await asyncio.sleep(MARKET_DATA_INTERVAL_S / 2) # Shorter sleep if cooling down
continue
signal = self.signal_generator.get_signal()
# Basic trading logic
if signal == 1: # Buy signal
# Try to buy if not at max long position
if self.risk_manager.current_position < self.risk_manager.max_position_size:
quantity_to_buy = 1 # Simple fixed quantity
if self.risk_manager.check_trade("BUY", quantity_to_buy):
order = {
"symbol": self.symbol, "type": "MARKET", "side": "BUY",
"quantity": quantity_to_buy,
"current_market_price": tick['ask'] # Market buy at ask
}
fill_info = await self.execution_engine.send_order(order)
if fill_info and fill_info['status'] == "FILLED":
self.risk_manager.update_position("BUY", fill_info['fill_quantity'], fill_info['fill_price'])
self.last_trade_time = time.time()
elif signal == -1: # Sell signal
# Try to sell if not at max short position (or to reduce long)
if self.risk_manager.current_position > -self.risk_manager.max_position_size:
quantity_to_sell = 1 # Simple fixed quantity
if self.risk_manager.check_trade("SELL", quantity_to_sell):
order = {
"symbol": self.symbol, "type": "MARKET", "side": "SELL",
"quantity": quantity_to_sell,
"current_market_price": tick['bid'] # Market sell at bid
}
fill_info = await self.execution_engine.send_order(order)
if fill_info and fill_info['status'] == "FILLED":
self.risk_manager.update_position("SELL", fill_info['fill_quantity'], fill_info['fill_price'])
self.last_trade_time = time.time()
# Log portfolio status periodically even if no trade
if random.random() < 0.1: # Log roughly 10% of the time
self.risk_manager.log_portfolio_status(tick['last_price'])
except Exception as e:
logger.error(f"Error in market data loop: {e}", exc_info=True)
await asyncio.sleep(MARKET_DATA_INTERVAL_S)
async def limit_order_check_loop(self):
""" Periodically checks if any open limit orders can be filled """
while self.is_running:
if self.execution_engine.open_orders:
# In a real system, this check is often event-driven by the exchange
# For simulation, we poll based on current market state
current_market_state = await self.market_feed.get_next_tick() # Get fresh state
filled_limit_orders = await self.execution_engine.check_limit_orders(
current_market_state['bid'], current_market_state['ask']
)
for fill_info in filled_limit_orders:
if fill_info and fill_info['status'] == "FILLED":
# Determine side from original order (not directly in fill_info for this mock)
# This part would need better tracking of original order details
original_order = self.execution_engine.open_orders.get(fill_info['order_id']) # Example access
side = "BUY" # Placeholder - need to fetch original order's side
# A better mock would store original order details with the fill
# For now, we assume it's a BUY for updating position (needs improvement)
# self.risk_manager.update_position(side, fill_info['fill_quantity'], fill_info['fill_price'])
pass # Position update for limit orders is tricky here without original order details easily accessible
await asyncio.sleep(0.1) # Check limit orders less frequently than main ticks
def stop(self):
self.is_running = False
logger.info(f"HFT Bot for {self.symbol} stopping.")
# --- Main Execution ---
async def main():
market_feed = MockMarketDataFeed(SYMBOL)
execution_engine = MockExecutionEngine(latency_ms=ORDER_LATENCY_MS)
risk_manager = RiskManager(max_position_size=MAX_POSITION_SIZE, initial_balance=INITIAL_BALANCE)
signal_generator = SimpleMomentumSignal(short_window=5, long_window=15) # Shorter windows for HFT-like behavior
bot = HFTBot(SYMBOL, market_feed, execution_engine, risk_manager, signal_generator)
try:
# Run the bot for a limited time for demonstration
await asyncio.wait_for(bot.run(), timeout=30.0) # Run for 30 seconds
except asyncio.TimeoutError:
logger.info("Simulation_time_ended.")
finally:
bot.stop()
# Log final portfolio status
final_tick = await market_feed.get_next_tick() # Get one last price for final P&L
risk_manager.log_portfolio_status(final_tick['last_price'])
logger.info("Bot has been shut down.")
if __name__ == "__main__":
asyncio.run(main())
How to Potentially Improve/Extend (for a more realistic simulation):
limit_order_check_loop is basic. Real limit order fills are event-driven by the exchange.This framework gives you a starting point for thinking about the components of an HFT system and how they might interact, even in a simplified Python simulation. Remember, the path to a real HFT bot is long and requires deep expertise.