Skip to content

This project implements an ultra-low latency, C++-based order execution system designed for high-frequency trading (HFT) and real-time systems applications.

License

Notifications You must be signed in to change notification settings

priyanshscpp/C-High-Frequency-Trading-System-HFT

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

8 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

High-Performance Trading Backend in C++

C++ License Build Status

A high-frequency trading (HFT) system built in C++ for ultra-low latency order execution targeting cryptocurrency derivatives markets via Deribit's exchange APIs. Engineered to achieve microsecond-level latency for critical path operations while maintaining robustness under extreme market volatility (10,000+ orders/sec).

๐Ÿ“บ Watch the Project Overview: High-Performance Trading Backend Demo

๐Ÿ“‹ Project Overview

This High-Frequency Trading (HFT) System represents a sophisticated C++ implementation designed for institutional-grade cryptocurrency derivatives trading. The system is built from the ground up to address the unique challenges of modern electronic trading:

๐ŸŽฏ Core Mission

  • Ultra-Low Latency: Achieve microsecond-level performance for critical trading operations
  • High Throughput: Handle 10,000+ orders per second under extreme market conditions
  • Institutional Grade: Provide the reliability and performance expected by professional trading firms
  • Real-Time Processing: Deliver sub-millisecond market data and order execution

๐Ÿ›๏ธ Target Markets

  • Spot Trading: Direct cryptocurrency purchases and sales
  • Futures Contracts: Leveraged derivatives with sophisticated risk management
  • Options Trading: Complex derivative instruments with advanced pricing models
  • Cross-Exchange Arbitrage: Multi-venue trading opportunities

๐Ÿ”ฌ Technical Innovation

  • Custom WebSocket Implementation: Built from scratch for maximum performance
  • Lock-Free Data Structures: Eliminate contention in high-frequency scenarios
  • Hardware-Accelerated Crypto: Leverage Intel AES-NI and ARMv8 crypto instructions
  • Zero-Copy Message Processing: Minimize memory allocation overhead

๐Ÿš€ Performance Characteristics

  • Order Placement Latency: <100 microseconds end-to-end
  • Market Data Processing: Real-time tick processing with <1ms latency
  • Risk Calculation: Sub-millisecond position and PnL updates
  • Connection Resilience: Automatic failover and reconnection handling

๐Ÿš€ Features

  • Ultra-Low Latency: Microsecond-level performance for critical trading operations
  • Multi-Protocol Support: REST and WebSocket interfaces for order management and real-time market data
  • Comprehensive Coverage: Support for spot, futures, and options instruments
  • High Throughput: Designed to handle 10,000+ orders per second
  • CLI-Based Interface: Command-line tools for trading operations and system management
  • Real-Time Market Data: Custom WebSocket server for streaming market information
  • Robust Risk Management: Built-in position and risk controls
  • Performance Benchmarking: Comprehensive latency testing and optimization tools

๐Ÿ—๏ธ Architecture Overview

System Flow Diagram

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Client Layer  โ”‚    โ”‚    API Layer    โ”‚    โ”‚  Core Engine    โ”‚
โ”‚                 โ”‚    โ”‚                 โ”‚    โ”‚                 โ”‚
โ”‚ โ€ข CLI/GUI       โ”‚โ”€โ”€โ”€โ–ถโ”‚ โ€ข REST API      โ”‚โ”€โ”€โ”€โ–ถโ”‚ โ€ข Order Manager โ”‚
โ”‚ โ€ข Algo Engines  โ”‚    โ”‚ โ€ข WebSocket API โ”‚    โ”‚ โ€ข Risk Manager  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ”‚ โ€ข Execution     โ”‚
                                              โ”‚ โ€ข Market Data   โ”‚
                                              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                       โ”‚
                                                       โ–ผ
                                              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                              โ”‚  Event Bus &    โ”‚
                                              โ”‚    Caches       โ”‚
                                              โ”‚                 โ”‚
                                              โ”‚ โ€ข In-Memory Bus โ”‚
                                              โ”‚ โ€ข Time-Series   โ”‚
                                              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                       โ”‚
                                                       โ–ผ
                                              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                              โ”‚   Deribit       โ”‚
                                              โ”‚  Connectivity   โ”‚
                                              โ”‚                 โ”‚
                                              โ”‚ โ€ข REST Client   โ”‚
                                              โ”‚ โ€ข WebSocket     โ”‚
                                              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Core Components

1. Client Layer

  • CLI/GUI: Interactive user tools for manual trading
  • Algo Engines: Automated trading strategies
  • Order Submission: HTTP/JSON via REST API or WebSocket

2. API Layer

  • REST API Server: Synchronous HTTP requests for order management
  • WebSocket API Server: Real-time market data and order updates
  • JSON-RPC Parsing: Efficient payload processing

3. Core Engine

  • Order Manager: Order validation and routing
  • Risk & Position Manager: Real-time PnL and limit enforcement
  • Execution Engine: Deribit API integration
  • Market Data Distributor: Real-time tick data processing

4. Event Bus & Caches

  • In-Memory Event Bus: High-throughput, lock-free pub/sub
  • Time-Series Cache: Lock-free ring buffers for recent data

5. Deribit Connectivity

  • REST Client: cURL/Boost.Beast for synchronous operations
  • WebSocket Client: Boost.Beast/Websocket++ for streaming

๐Ÿ“ Codebase Structure

Frequency_Check_Algo/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ Api.cpp/hpp              # Main interface layer
โ”‚   โ”œโ”€โ”€ Trader.cpp/hpp           # Trading logic engine
โ”‚   โ”œโ”€โ”€ main.cpp                 # Application entry point
โ”‚   โ”œโ”€โ”€ Boost_WebSocket/         # Boost.Asio WebSocket client
โ”‚   โ”œโ”€โ”€ Custom_WebSocket/        # Custom socket implementation
โ”‚   โ”œโ”€โ”€ WebSocketpp/             # websocketpp library client
โ”‚   โ”œโ”€โ”€ interfaces/              # Abstract interfaces
โ”‚   โ”œโ”€โ”€ market_data/             # Market data handling
โ”‚   โ”œโ”€โ”€ oms/                     # Order management system
โ”‚   โ”œโ”€โ”€ risk_management/         # Risk controls
โ”‚   โ””โ”€โ”€ strategies/              # Trading strategies
โ”œโ”€โ”€ test/
โ”‚   โ””โ”€โ”€ test_latency/           # Performance testing
โ”œโ”€โ”€ CMakeLists.txt              # Build configuration
โ””โ”€โ”€ README.md                   # This file

Key Components

โœ… Api.hpp & Api.cpp โ€” Main Interface Layer

  • Responsibilities: JSON RPC serialization/deserialization
  • Features: Client authentication, clean abstraction layer
  • Methods: Order placement, cancellation, modification

โœ… BSocket.hpp & BSocket.cpp โ€” Boost WebSocket Client

  • Technology: Boost.Asio/Beast implementation
  • Features: Production-grade error handling, async I/O
  • Use Case: Fallback and test environments

โœ… Socketpp.hpp & Socketpp.cpp โ€” websocketpp Library Client

  • Technology: websocketpp::config::asio_tls_client
  • Features: TLS encryption, thread-safe async handling
  • Performance: Sub-millisecond latency optimization

โœ… Trader.hpp & Trader.cpp โ€” Trading Engine

  • Order Management: Place, cancel, modify orders
  • Market Data: Order book, positions, open orders
  • Integration: API and socket layer coordination

๐Ÿ”ง Performance & Optimization

Latency Optimization

  • WebSocket Protocol: RFC 6455 with persistent TCP connections
  • Zero-Copy Message Retrieval: Direct in-memory buffer processing
  • Condition Variable Wakeup: Immediate thread activation
  • Result: Sub-millisecond round-trip latency

Threading & Concurrency

  • Mutex-Guarded Queues: Race condition prevention
  • Dedicated Worker Threads: I/O decoupling from business logic
  • Producer-Consumer Pattern: High-throughput message processing

TLS Performance

  • Asynchronous Handshake: Non-blocking TLS setup
  • Session Reuse: Connection and TCP session optimization
  • Hardware Acceleration: Intel AES-NI and ARMv8 crypto support
  • Result: <10% latency overhead with optimized ciphers

Scaling Considerations

  • Vertical Scaling: Efficient CPU core utilization
  • Horizontal Scaling: Stateless request model for microservices
  • Connection Pooling: Extensible for high-load scenarios

๐Ÿงช Testing & Benchmarking

Performance Testing Suite

Located in test/test_latency/ directory:

  • Latency Measurement: Round-trip timing for all operations
  • Throughput Testing: Orders per second capacity
  • Protocol Comparison: WebSocket++ vs Boost vs Custom implementations
  • Async vs Sync: Performance benchmarking of different approaches

Test Results

  • WebSocket++: Outperforms Boost Beast implementation
  • Async Calls: Better performance than synchronous counterparts
  • Latency: Sub-millisecond performance under optimal conditions

๐Ÿš€ Getting Started

Prerequisites

  • C++17 compatible compiler
  • CMake 3.10+
  • Boost libraries
  • OpenSSL development libraries

Building the Project

mkdir build && cd build
cmake ..
make -j$(nproc)

Running Tests

cd test/test_latency
make
./test_latency

๐Ÿ”ฎ Future Improvements

1. Modular Plugin System

  • Purpose: Easy adaptation to multiple data sources
  • Implementation: Interface-based architecture with runtime loading
  • Benefits: Protocol flexibility (Binance, Kraken, custom APIs)

2. Caching & Batching

  • Message Batching: Periodic chunk transmission
  • LRU Cache: Response caching with eviction policies
  • Benefits: Reduced downstream load and bandwidth

3. AI-Powered Data Filters

  • ML Anomaly Detection: Filter abnormal market data
  • NLP Intent Recognition: Smart command-based interactions
  • Benefits: Intelligent, context-aware backend

๐Ÿ“Š Monitoring & Observability

Logging & Metrics

  • Structured Logs: JSON format for easy parsing
  • Prometheus Integration: Latency, error rate, fill rate metrics
  • Audit Trails: Complete order and execution history

Health Monitoring

  • Grafana Dashboards: Real-time system performance
  • Alertmanager Rules: Automated issue detection
  • Key Metrics: Latency spikes, risk breaches, connection drops

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ‘จโ€๐Ÿ’ป Author

Priyanshu Yadav
Final Year BTech ECE
๐Ÿ“ง priyanshs.ece@gmail.com

๐Ÿ™ Acknowledgments

  • Deribit: Exchange API integration
  • Boost Libraries: High-performance C++ components
  • WebSocket++: WebSocket protocol implementation
  • Open Source Community: Tools and libraries that made this possible

โญ Star this repository if you find it helpful!

For questions about architecture, optimizations, or low-latency C++ design, feel free to reach out!

About

This project implements an ultra-low latency, C++-based order execution system designed for high-frequency trading (HFT) and real-time systems applications.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published