KrakenCppSDK

A C++ client library, developed to connect to the Kraken exchange's WebSocket API 2.0. It provides a clean and modern interface for receiving real-time market data.

  • 650 Raised
  • 606 Views
  • 5 Judges

Categories

  • SDK Client

Gallery

Description

KrakenCppSDK

KrakenCppSDK is a modern, thread-safe C++ client library for Kraken's WebSocket API v2 that abstracts away the hard parts of real-time market data streaming. Using a State-View architecture, the SDK separates mutable state (protected by locks) from immutable snapshots (lock-free reads), enabling safe concurrent access from multiple threads without race conditions.

The library features a custom Decimal type with 12-digit fractional precision using integer arithmetic, eliminating floating-point errors that plague financial applications. With complete coverage of all public WebSocket channels, CRC32 checksum verification for order books, and a clean callback-based API, developers can go from zero to streaming live market data in under 10 lines of code.

Key Features

• Thread-Safe by Design: Lock-free reads with immutable snapshots; concurrent access from multiple threads without race conditions

• Financial-Grade Precision: Custom Decimal type with 12-digit precision using integer arithmetic (no floating-point errors)

• Data Integrity Guaranteed: CRC32 checksum verification for order books; throws on mismatch to prevent trading on corrupted data

• Complete API Coverage: All public WebSocket v2 channels: Book, Ticker, Trade, OHLC, and Instrument

• High Performance: Lock-free View access, O(log N) order book updates, minimal memory footprint (~2KB per symbol for 25-depth book)

• Production-Ready: Comprehensive test suite using Catch2 with more than 300 tests, 7 working examples, cross-platform support (Linux, macOS, Windows)

Technical Highlights

• Technology Stack: Built with C++20 leveraging modern features like concepts, ranges, and structured bindings. Uses ixwebsocket for robust WebSocket connectivity, nlohmann/json for high-performance parsing, and zlib for CRC32 checksum calculation.

• Architecture Decisions: The SDK implements a State-View pattern where mutable State classes (protected by std::shared_mutex) create immutable View snapshots for callbacks. This allows the WebSocket thread to update state while application threads safely read data without contention. I also use deferred resource allocation: State objects aren't created until the server confirms subscription success, preventing resource leaks on rejected subscriptions.

• Decimal Implementation: Our hybrid Decimal class stores the original JSON string (required for checksum calculation) alongside parsed integer/fractional parts scaled to 10^12. This enables O(1) comparisons using integer arithmetic while preserving full precision for financial calculations.

• Performance Optimizations: Order books use std::map for O(log N) insertions with sorted iteration. Views are copy-on-read snapshots created only when callbacks fire, not on every message. Trade history auto-prunes to configurable limits to bound memory usage.

How It Works

Installation

git clone https://github.com/rfperuch/KrakenCppSdk.git
cd KrakenCppSdk
mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build .

Basic Usage

#include "KrakenClient.h"
#include "IxWebSocket.h"


int main() {
    IxWebSocket::init();  // Required on Windows
    
    auto ws = std::make_unique();
    KrakenClient client{std::move(ws)};
    
    // Subscribe to BTC/USD order book and ticker
    client.subscribe(
        BookConfig{
            .symbol = "BTC/USD",
            .depth = 25,
            .onMessage = [](const BookView& book) {
                auto spread = book.asks()[0].price.toDouble() 
                            - book.bids()[0].price.toDouble();
                std::cout << "Spread: $" << spread << "\n";
            }
        },
        TickerConfig{
            .symbol = "BTC/USD",
            .onMessage = [](const TickerView& t) {
                std::cout << "Last: $" << t.last().toDouble() << "\n";
            }
        }
    );
    
    client.run();
    std::cin.get();  // Run until Enter
    client.stop();
    
    IxWebSocket::final();
    return 0;
}

Workflow

  1. Initialize → Create WebSocket and KrakenClient
  2. Subscribe → Pass Config objects with callbacks for each channel
  3. Run → Non-blocking connection start; WebSocket runs in background thread
  4. Receive → Your callbacks receive immutable View snapshots automatically
  5. Stop → Clean shutdown; all resources released

Demo & Documentation

ResourceLink
GitHub Repositorygithub.com/rfperuch/KrakenCppSdk
Full DocumentationComprehensive README with architecture diagrams, API reference, and troubleshooting
Working Examples7 complete examples covering all channels and use cases
Test SuiteUnit and integration tests with Catch2

Examples Included

ExampleDescription
01_book_tickerGetting started with order books and tickers
02_thread_safetyConcurrent access patterns demonstration
03_instrumentAsset and trading pair metadata
04_tradesReal-time trade monitoring
05_ohlcCandlestick data streaming
06_bookDeep order book analysis
07_tickerMarket ticker tracking

Running Examples


Future Enhancements

With additional development time, I would add:

  • Authenticated Channels: Private order management, account balance, and trade execution.

Attachments