kusak-infra Versions

Quick Access:
Release 30 — Open Source  |  Release 71 — Closed Source


Release 30 — Lock‑Free HFT Infrastructure Prototype [Open Source]

Release Date: 10 May 2026  |  Status: Public on GitHub

Repository: https://github.com/yunuskusak/kusak-infra.git

C++17 · Binance WebSocket · SPSC Ring Buffer · Sub‑millisecond Latency

KUSAK-INFRA is the open-source infrastructure core of KUSAK — an algorithmic trading bot / HFT engine built on Binance. Written in C++17 with lock‑free architecture, sub‑millisecond latency, and zero heap allocations on the hot path. Built by Kusak Ltd.

This is the first public release of the infrastructure layer that powers KUSAK — a proprietary high‑frequency trading engine built and operated by Kusak Ltd. We are open‑sourcing this specific version because it represents the raw engineering foundation: how we connect, how we measure, and how we move data without locks. It does not contain any trading strategy, signal generation, or alpha logic.

What This Is

KUSAK V30 is a hardware‑aware, lock‑free market data pipeline for Binance's WebSocket API. It was the first version where we replaced every mutex, every std::queue, and every sleep_for with deterministic, allocation‑free primitives.

The result: a single C++17 translation unit that ingests live market data, processes it through a lock‑free SPSC ring buffer, and dispatches it to a strategy thread — with no heap allocations on the hot path and nanosecond‑resolution timestamps.

This is the engine chassis. The direction it drives is not included.

Architecture

Binance WebSocket (TLS/SSL)
        │
        ▼
  TLSSocket (poll‑based, OpenSSL)
        │
        ▼
 SpscRing<MarketEvent>          ← lock‑free, alignas(64), zero heap
        │
        ▼
  Strategy Thread               ← reads events, no blocking calls
        │
        ▼
 OrderChannel (mutex+queue)     ← V30 bottleneck, later replaced
        │
        ▼
  Order Thread → Binance REST

Core Components

Known Bottlenecks in This Version

This is a prototype. We are publishing it with its flaws intact because hiding them would be dishonest.

  1. Order channel uses std::mutex + std::queue — primary latency bottleneck. Later replaced with lock‑free OrderSpscRing.
  2. WebSocket uses poll() with 200ms timeout — later moved to epoll with edge‑triggered mode.
  3. std::chrono::steady_clock in cooldown logic — later replaced with atomic nanosecond counters using CLOCK_MONOTONIC_RAW.
  4. std::string in order parameters — later replaced with stack‑allocated FixedString<N>.

What Is NOT in This Repository

Build

Requirements: GCC 11+ or Clang 14+, CMake 3.20+, OpenSSL 3.x, libcurl

git clone https://github.com/yunuskusak/kusak-infra.git
cd kusak-infra
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)

Configuration: Copy kusak_config.json.example to kusak_config.json. Set dry_run: true before connecting to any live exchange.

Why We're Publishing This

First: the C++ HFT community has a culture of hiding infrastructure behind NDAs and mythology. Most "HFT" code on GitHub is neither high‑frequency nor production‑grade. We wanted to show what a real first iteration looks like — including the parts that are wrong.

Second: recruiting. If you read this codebase and immediately understand why poll() is wrong here, why std::queue with a mutex is unacceptable on this path, and what the correct fix is — we would like to talk to you.

License

MIT. Use it, study it, improve it. The only thing we ask: if you build something that makes money using ideas from this codebase, consider that it took us considerably more than one evening to get here.

Kusak Ltd. — Building deterministic execution infrastructure.


Release 71 — Low‑Latency Market‑Data Ingestion & Order‑Routing Engine [Closed Source]

Release Date: 10 May 2026  |  Status: Internal — README public, source closed

Low‑latency market‑data ingestion and order‑routing engine for Binance, written in C++20.

KUSAK-INFRA V71 is a market‑data ingestion and order‑routing engine for centralized cryptocurrency exchanges, built against Binance's Spot and USDT‑margined Futures REST and WebSocket APIs. The problem it addresses is narrow and specific: turn a public WebSocket feed into a parsed, timestamped, risk‑evaluated event stream with deterministic, low‑overhead processing, and route the resulting decisions through an order path that validates against exchange constraints before anything reaches the network.

C++20 is used for concrete reasons visible in the codebase, not just general performance. std::span is used throughout the backtesting, walk‑forward, and buffer‑handling code as a non‑owning, bounds‑aware view over tick data, replacing raw pointer/length pairs at those interfaces. The standardized [[likely]]/[[unlikely]] attributes are used on several hot paths as a portable alternative to compiler‑specific branch hints. Combined with manual control over memory layout, atomics, and object lifetime, this gives the ingestion path predictable behavior without a managed runtime's allocation or collection pauses.

The design keeps three concerns structurally separate: a low‑latency ingestion core that owns parsing and timing, a risk/execution layer that gates and routes orders, and an offline research toolchain — a separate, opt‑in build target — used for backtesting and parameter search before any change reaches the live path.

Architecture Status

The build produces two independent targets. kusak_v71, built by default, is the live engine: it owns the complete path from WebSocket ingestion through risk scoring to order submission, including a RestOrderClient instance held as live_order_client. Its current operating configuration runs with dry_run enabled against Binance's production endpoints (testnet=false) — market data, account state, and exchange filters are read live, and order requests are constructed, signed, and risk‑scored through the same code path a submitted order would take, but transmission is gated behind the dry_run flag. This is a validation policy, not a stand‑in for missing functionality.

A second, opt‑in target (research, built via -DBUILD_RESEARCH=ON) is a separate binary covering backtesting, parameter optimization, and paper trading against recorded or replayed data. It does not touch the live order path.

Low‑Latency Ingestion Core

Zero‑Copy Ring Buffer

The WebSocket receive buffer is a virtual‑memory‑mirrored ring: an anonymous file descriptor from memfd_create() is mapped twice, via two consecutive mmap() calls, onto the same backing pages at adjacent virtual addresses. This produces one contiguous address range of size 2×capacity, so a read that would otherwise need to wrap around the end of the buffer instead continues transparently into the mirrored second mapping. The parser never special‑cases a wrap boundary and never calls memcpy()/memmove() to reassemble a split message. The memfd_create() + double‑mmap() setup happens once, at construction; nothing on the steady‑state receive path allocates or remaps memory.

Branchless DFA Parser

Incoming WebSocket payloads (aggTrade, bookTicker, depth updates) are parsed by hand‑written, single‑pass state‑machine parsers rather than a general‑purpose JSON library. Each parser walks the input once, character by character, using masked and XOR‑based conditional updates in place of if/else branching on the digit‑accumulation path; the loop contains exactly one branch, used only to detect the terminating character. No heap allocation occurs on this path — no std::string, std::vector, or new/malloc. General‑purpose JSON parsing (nlohmann::json) is still used elsewhere in the system, for lower‑frequency REST traffic such as exchange metadata and order acknowledgements, where the latency budget is different.

Fixed‑Point Numeric Model

Prices and quantities on the ingestion path are represented as int64_t, scaled by 10^8, rather than double. The parser accumulates integer and fractional digits separately and combines them with a lookup‑table scale factor once eight fractional digits have been consumed; digits beyond the eighth are discarded through the same branchless mask rather than a separate truncation check, closing a prior failure mode where a ninth digit could silently shift the scale of the resulting value. This keeps comparisons and arithmetic on the hot path exact and reproducible, and avoids floating‑point rounding and NaN propagation. (Order construction against the REST layer, downstream of ingestion, is implemented with double, not the fixed‑point type used on the ingestion path.)

Hardware Timestamping

Latency‑sensitive timestamps are taken from the CPU's Time Stamp Counter via __rdtscp(), paired with _mm_lfence() to serialize execution so the counter read isn't reordered relative to the code being measured. This avoids a clock_gettime() syscall on the per‑message path. clock_gettime(CLOCK_MONOTONIC_RAW, ...) is still used, but only for periodic calibration to correlate TSC cycles back to wall‑clock time, not on every timestamp taken.

TLS & Network Stack

The WebSocket client manages its own SSL_CTX lifecycle directly against OpenSSL rather than through a higher‑level HTTP library: context creation pinned to a TLS 1.2 minimum, default verify paths, peer verification enabled, and explicit SSL_CTX_free() on teardown. ALPN is negotiated explicitly for http/1.1, since the WebSocket upgrade handshake depends on it and a ClientHello without an ALPN extension is more likely to be handled unpredictably by intermediary CDNs or WAFs in front of the exchange's edge.

Additional Components

Build

Requirements: Linux, CMake 3.16+, C++20 compiler (GCC or Clang), OpenSSL and libcurl development headers, x86‑64 CPU

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)

# Optional research binary:
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_RESEARCH=ON
cmake --build build -j$(nproc)

nlohmann/json is fetched automatically at configure time via CMake's FetchContent. OpenSSL and CURL are expected to be present on the build system.

[ Back to Home ]