Skip to content

nltd101/HFT_market_maker

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

60 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

C++ Market Maker Bot

A low-latency market maker bot for cryptocurrency trading on Binance testnet.

Overview

This bot connects to Binance via WebSocket API to monitor order book changes and maintains two limit orders (bid and ask) at ±2% from the current mid-price. When the mid-price changes, it immediately cancels existing orders and places new ones.

Key Features:

  • Real-time order book tracking via WebSocket
  • Automatic bid/ask order placement and management
  • Auto-reconnection on connection loss
  • Low-latency order updates
  • Comprehensive logging and performance metrics
  • Server time synchronization
  • Rate limiter with automatic throttling

📊 Performance Metrics (Sample)

Metric Value Description
Decision latency 0.104 ms Time from receiving market data to making a trading decision. Lower values indicate faster reactions.
Processing latency 0.775 ms Time from receiving market data until order processing begins (includes decision time, queueing, and thread scheduling).
Order acknowledgment latency 72.85 ms Time from receiving market data to receiving confirmation from the exchange.

🖥️ Test Environment

Component Details
Instance Type AWS EC2 t3.nano
vCPU / RAM 2 CPUs / 0.5 GB
OS Ubuntu 22.04 LTS
Network Tokyo region, public IP
Test Duration 2 hours of live market data
Symbol SOLUSDT (Binance)

📈 Performance Plots

Here are some sample performance plots generated by the bot:

Processing Latency Over Time

Processing Latency

Order Confirmation Latency

Order Success

Decision Latency

Price Spread

Requirements

  • C++20 compiler (GCC 9+, Clang 10+, or MSVC 2019+)
  • CMake 3.15+
  • OpenSSL
  • libcurl
  • Boost (filesystem)
  • libwebsockets
  • Python 3.8+ (for data visualization)

Build Instructions

Configuration

Before building the project, copy config.json.example to config.json and update it with your own API credentials and settings:

cp config.json.example config.json

Then edit config.json:

{
    "api_key": "YOUR_API_KEY",
    "api_secret": "YOUR_API_SECRET",
    "rest_base_url": "https://testnet.binance.vision",
    "ws_base_url": "stream.binance.com",
    "log_level": "INFO",
    "symbol": "BNBUSDT",
    "enable_log_file": true,
    "log_file_path": "logs/market_maker.log",
    "enable_stat_log_file": true,
    "stat_csv_file": "logs/market_maker.csv"
}

Configuration Parameters:

  • api_key / api_secret - Binance API credentials
  • rest_base_url - REST API endpoint
  • ws_base_url - WebSocket API endpoint
  • log_level - Logging level (DEBUG/INFO/WARNING/ERROR)
  • symbol - Trading pair (e.g., BNBUSDT, BTCUSDT)
  • enable_log_file - Enable file logging
  • log_file_path - Path to log file
  • enable_stat_log_file - Enable CSV statistics logging
  • stat_csv_file - Path to CSV statistics file

Linux/macOS

# Install dependencies (Ubuntu/Debian)
sudo apt-get install cmake g++ libssl-dev libcurl4-openssl-dev libboost-filesystem-dev libwebsockets-dev

# Build
mkdir build && cd build
cmake ..
cmake --build .

Usage

# Run from build directory
cd build
./bin/market_maker

# Or from project root after build
./build/bin/market_maker

Press Ctrl+C to stop gracefully.

Data Visualization

Visualize trading performance and metrics using Python:

# Generate performance plots
python scripts/plot_stats.py build/logs/market_maker.csv

Available Visualizations:

  • Order latency over time
  • Price spread analysis
  • Order success/failure rates
  • WebSocket reconnection events

Project Structure

src/
├── main.cpp              # Entry point
├── OrderManager.cpp      # Order management logic
├── OrderClient.cpp       # Exchange API client
├── ExchangeClient.cpp    # Exchange connectivity
├── WebSocketManager.cpp  # WebSocket handling
├── WssClient.cpp         # WebSocket client implementation
├── ExchangeInfo.cpp      # Exchange metadata
├── Logger.cpp            # Logging system
├── StatManager.cpp       # Performance statistics
├── Config.cpp            # Configuration loader
├── utils.cpp             # Utility functions
└── strategies/           # Trading strategies
    └── SimpleSpreadStrategy.cpp

scripts/
└── plot_stats.py         # Visualization         

How It Works

  1. Initialization: Loads config, connects to Binance API, fetches exchange info
  2. WebSocket Connection: Subscribes to order book stream for the configured symbol
  3. Mid-Price Calculation: Calculates mid-price as (best_bid + best_ask) / 2
  4. Order Placement: Places bid at mid_price * 0.98 and ask at mid_price * 1.02
  5. Price Monitoring: When mid-price changes, cancels existing orders and places new ones
  6. Auto-Reconnection: Automatically reconnects on WebSocket disconnection

Logging

The bot generates two types of logs:

  1. Application Log (logs/market_maker.log):

    • Order placement, cancellation, and updates
    • WebSocket connection events
    • Error messages and warnings
  2. Statistics CSV (logs/market_maker.csv):

    • Latency metrics
    • Order execution times
    • Performance statistics

License

This project is for educational and assessment purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors