# Polymarket HFT Market Making System

Advanced Python HFT [ish] Infrastructure

Performance Architecture Trading

Summary

Professional high frequency trading (HFT) market making system designed for Bitcoin 15-minute binary markets on Polymarket. This advanced trading infrastructure combines real-time signal detection, automated order execution, and intelligent hedging strategies to achieve consistent profitability in fast-moving prediction markets.

System Performance:

  • Win Rate: 99% profitable trades
  • Market Focus: Bitcoin 15-min prediction markets
  • Strategy: HFT market making with intelligent hedging
  • Architecture: Python async with CPU optimization
  • Uptime: Continuous 24/7 autonomous operation

System Architecture

Core Components

┌───────────────────────────────────────────────────┐
│                TRADING ENGINE                     │
├───────────────────────────────────────────────────┤
│  OrderBook       │  Signal Gen     │  Risk Mgmt   │
│  ├─ WebSocket    │  ├─ Micro-price │  ├─ Position │
│  ├─ Real-time    │  ├─ BPS Signal  │  ├─ Limits   │
│  └─ Updates      │  └─ Filtering   │  └─ Exposure │
├───────────────────────────────────────────────────┤
│             EXECUTION LAYER                       │
│  Market Maker    │  Hedging Bot    │  Monitoring  │
│  ├─ Order Mgmt   │  ├─ Fill Track  │  ├─ Logging  │
│  ├─ Spread Calc  │  ├─ Auto Hedge  │  ├─ Alerts   │
│  └─ PnL Track    │  └─ State Mgmt  │  └─ Health   │
└───────────────────────────────────────────────────┘

Performance Engineering

1. Garbage Collection Management

gc.disable()  # Eliminates GC pauses during trading

Why: Python's garbage collector can cause trading delays. We disable it during active trading and manually trigger cleanup during quiet periods.

2. CPU Optimization

def set_cpu_affinity():
    affinity_cores = [cpu_count - 2, cpu_count - 1]  # Use dedicated cores
    process.cpu_affinity(affinity_cores)
    process.nice(psutil.HIGH_PRIORITY_CLASS)  # High priority

Benefits:

  • Dedicated CPU cores for trading operations
  • High process priority for consistent performance
  • Reduced interference from other system processes

3. Async Architecture

# WebSocket on separate thread
self.thread = threading.Thread(target=self._connect, daemon=True)
# Order processing with async
await asyncio.create_task(send_hedge(...))

Advantages:

  • Non-blocking network operations
  • Concurrent order processing
  • Thread-safe state management

4. Efficient Data Processing

def _on_message(self, ws, message):
    data = json.loads(message)  # Fast JSON parsing
    if event_type == "price_change":
        self._update_orderbook_incremental(data)  # Efficient updates

Trading Strategies

Bitcoin Market Making

  • 15-Minute Markets: Focus on Bitcoin price prediction markets with 15-minute expiry

  • Micro-price Signals: Volume-weighted bid-ask analysis for entry timing

  • Risk Management: Position limits and automated stop-losses

Smart Hedging System (sep_hedge.py)

# Real-time fill monitoring with duplicate prevention
async def handle_message(message):
    if anchor_id in state.hedged_anchors:  # Prevents double-hedging
        return

    # Safe state management
    async with state.lock:
        state.processing_anchors.add(anchor_id)

Features:

  • Instant fill detection via WebSocket
  • Automatic hedge placement on every trade
  • State tracking to prevent duplicate orders
  • Retry logic for failed orders

System Optimizations

Memory Management

  • Connection pooling for HTTP requests
  • Efficient orderbook updates using bisect operations
  • Thread-safe data structures for concurrent access

Network Optimization

  • WebSocket connections with automatic reconnection
  • Optimized timeouts for Polymarket API calls
  • Keep-alive connections to reduce overhead

Signal Processing

  • Real-time price calculations for market analysis
  • BPS monitoring with configurable thresholds
  • State persistence to avoid duplicate processing

Getting Started

System Requirements

CPU: 4 cores recommended
RAM: 2GB+ for orderbook processing
Network: Stable internet connection
OS: Linux, Windows, or macOS

Installation

git clone https://github.com/nawaz0x1/py_polymarket_hft_mm
cd py_polymarket_hft_mm
pip install -r requirements.txt

# Setup environment
cp .env.sample .env
# Add your Polymarket credentials

# Run the system
sudo env "PATH=$PATH" python main.py    # Main trading bot
python sep_hedge.py                     # Hedging companion

Configuration

# config.py - Key settings
TRADING_BPS_THRESHOLD = 50    # Signal sensitivity
PROFIT_MARGIN = 0.02          # Minimum profit per trade
MARKET_SESSION_SECONDS = 900  # 15-minute market periods

Support Development

Found this trading system profitable? Consider supporting further development:

USDT/USDC Donations:

  • Ethereum (ETH): 0x89ae2f064cf2cb06a5e66a8e9ea6b653dcb93cfa
  • Solana (SOL): 2V4g71bG6dJyqv4REZeZSCtiF4pQauDvRiLy8MDNjWNv

Your support helps maintain and improve the trading algorithms!


Contact

GitHub: @nawaz0x1
X (twitter): @nawaz0x1
LinkedIn: Shah Nawaz Haider


Disclaimer

This software is for educational and research purposes. Trading involves substantial risk of loss. Users are responsible for compliance with applicable financial regulations. Past performance does not guarantee future results.

S
Description
Python HFT (High Frequency Trading) system with advanced market making algorithms for Polymarket Bitcoin prediction markets.
Readme 116 KiB
Languages
Python 99.5%
Shell 0.5%