211 lines
12 KiB
Markdown
211 lines
12 KiB
Markdown
# Polymarket High Frequency Trading System
|
|
|
|
_Advanced Python HFT [ish] Infrastructure_
|
|
|
|
[]()
|
|
[]()
|
|
[]()
|
|
|
|
## Summary
|
|
|
|
Professional market making and hedging system for Bitcoin 15-minute binary markets on Polymarket. Engineered for consistent profitability using advanced signal detection, real-time order book analysis, and automated hedging strategies.
|
|
|
|
**System Performance:**
|
|
|
|
- **Win Rate**: 99% profitable trades
|
|
- **Market Focus**: Bitcoin 15-min prediction markets
|
|
- **Strategy**: Market making with intelligent hedging
|
|
- **Uptime**: Continuous 24/7 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
|
|
|
|
```python
|
|
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
|
|
|
|
```python
|
|
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
|
|
|
|
```python
|
|
# 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
|
|
|
|
```python
|
|
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`)
|
|
|
|
```python
|
|
# 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
|
|
|
|
```bash
|
|
CPU: 4+ cores recommended
|
|
RAM: 8GB+ for orderbook processing
|
|
Network: Stable internet connection
|
|
OS: Linux, Windows, or macOS
|
|
```
|
|
|
|
### Installation
|
|
|
|
```bash
|
|
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
|
|
|
|
```python
|
|
# 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](https://github.com/nawaz0x1)
|
|
**X (twitter)**: [@nawaz0x1](https://x.com/nawaz0x1)
|
|
**LinkedIn:** [Shah Nawaz Haider](https://www.linkedin.com/in/nawazhaider/)
|
|
|
|
---
|
|
|
|
## 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.
|