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.
Here's a simplified educational example of an HFT (High-Frequency Trading) trading bot in Python. This is not intended for live trading but serves as a framework to understand core concepts. Real HFT systems require low-latency infrastructure, direct market access, and extensive risk controls, which are beyond the scope of this example.
import asyncio
import numpy as np
import pandas as pd
from datetime import datetime
import random
# Simulated Market Data Feed (replace with real API)
class MarketData:
def __init__(self, symbol="BTC-USD"):
self.symbol = symbol
self.bid = 50000.0 # Simulated bid price
self.ask = 50000.5 # Simulated ask price
self.last_price = 50000.0
self.volume = 100.0 # Simulated volume
def update(self):
"""Simulate market data changes"""
self.bid += random.uniform(-0.1, 0.1)
self.ask += random.uniform(-0.1, 0.1)
self.last_price = (self.bid + self.ask) / 2
self.volume += random.uniform(0, 10)
# Trading Strategy: Mean Reversion on Spread
class Strategy:
def __init__(self, threshold=0.05):
self.threshold = threshold
self.spread_history = []
def generate_signal(self, market_data):
"""Generate buy/sell signal based on spread"""
spread = market_data.ask - market_data.bid
self.spread_history.append(spread)
if len(self.spread_history) > 10:
self.spread_history.pop(0)
avg_spread = np.mean(self.spread_history)
if spread < avg_spread * 0.8 and abs(spread - avg_spread) > self.threshold:
return "BUY" # Buy when spread is tight
elif spread > avg_spread * 1.2 and abs(spread - avg_spread) > self.threshold:
return "SELL" # Sell when spread is wide
return "HOLD"
# Risk Management
class RiskManager:
def __init__(self, max_position=10, max_loss=1000):
self.max_position = max_position
self.max_loss = max_loss
self.position = 0
self.pnl = 0.0
def can_execute(self, signal, price):
"""Check if trade is allowed"""
if signal == "BUY" and self.position + 1 > self.max_position:
return False
if signal == "SELL" and self.position - 1 < -self.max_position:
return False
if self.pnl < -self.max_loss:
return False
return True
def update_position(self, signal, price):
"""Update position and P&L"""
if signal == "BUY":
self.position += 1
self.pnl -= price
elif signal == "SELL":
self.position -= 1
self.pnl += price
# Order Execution (simulated)
class OrderExecutor:
def place_order(self, signal, price, size=1):
"""Simulate order execution"""
if signal == "BUY":
print(f"[ORDER] Buy {size} at {price}")
elif signal == "SELL":
print(f"[ORDER] Sell {size} at {price}")
return True
# Main HFT Bot
class HFTBot:
def __init__(self, symbol="BTC-USD"):
self.market_data = MarketData(symbol)
self.strategy = Strategy()
self.risk_manager = RiskManager()
self.executor = OrderExecutor()
self.running = True
async def run(self):
"""Main loop"""
while self.running:
self.market_data.update()
signal = self.strategy.generate_signal(self.market_data)
if self.risk_manager.can_execute(signal, self.market_data.last_price):
self.executor.place_order(signal, self.market_data.last_price)
self.risk_manager.update_position(signal, self.market_data.last_price)
await asyncio.sleep(0.01) # 10ms interval
def stop(self):
self.running = False
# Example Usage
async def main():
bot = HFTBot()
try:
await bot.run()
except KeyboardInterrupt:
bot.stop()
print("Bot stopped.")
if __name__ == "__main__":
print("⚠️ WARNING: This is a simplified educational example only!")
print("Do not use for real trading without proper testing and risk management.")
asyncio.run(main())
backtrader or pyalgotrade).pandas or yfinance) to test strategies.MarketData with a real API (e.g., Binance WebSocket).scikit-learn or TensorFlow to predict price movements.This code is for educational purposes only. HFT involves high risks, including:
Always test thoroughly in a paper trading or simulated environment before deploying any strategy.