HangukQuant Research

HangukQuant Research

Crypto Market Making (in C++ with Code)

HangukQuant's avatar
HangukQuant
Dec 02, 2026
∙ Paid

HFT engineers are often concerned with single-threaded performance. Between parsing market data, computing a fair price and adjusting quotes, each step is often serially dependent on the previous one.

These components can be split across threads for scalability and separation of responsibilities, but the trading system then has to synchronize their work. Even with lock-free queues, components communicate through shared memory. Publishing a message and consuming it on another core involves memory ordering and cache-coherency traffic.

For low latency work, the handoff can become a meaningful part of the hot path - a common approach is to keep the latency-sensitive path on a single owner thread. That thread receives market data, updates the relevant state and initiates the order action. This removes the producer-consumer handoff between those components and keeps their working state local to one core.

Therefore, hardware selection often skews towards strong single-core performance, even when a machine offers many more cores.

However, trading systems are asynchronous systems. They need to carry several outstanding operations, process irregular market events and enforce policies based on elapsed time. A reference feed might stop updating altogether, in which case a watchdog must act.

We therefore need concurrency even when we choose to execute the strategy on one thread.

An elegant approach is to use language-level async features. A coroutine can suspend while an operation is unfinished, retain the state needed to continue, and resume when progress becomes possible. This makes the application convenient to reason about - humans after all are very serial thinkers. Watch any Christopher Nolan movie like Tenet and Inception and I am sure you would agree.

Consider the following Python example":

import asyncio
import httpx


async def main():
    async with httpx.AsyncClient(timeout=5.0) as client:
        #A
        responses = await asyncio.gather(
            client.get("https://example.com/"),
            client.get("https://example.org/"),
        )
        #B
        for response in responses:
            response.raise_for_status()
            print(response.url, response.status_code)

asyncio.run(main())

Both requests can be in flight together. While one is waiting for the network, the event loop can advance the other. gather waits for both results without blocking the event-loop thread for the duration of either request.

As far as we are concerned, #B comes after #A and that’s the serial dependency. We are not interested in which of the two get succeeded first. asyncio provides the event loop, task scheduling and timer machinery that makes this work. On Linux, its standard selector-based event loop normally uses epoll .

This model is productive, but a general-purpose async stack carries costs that matter - task and callback objects, Python execution, protocol abstractions and scheduling transitions all contribute work. As far as we are concerned, this event loop is also somewhat “opaque”, and we have little control over it.

For single-core work, we care more about determinism and control. The scheduling and state ownership is explicit by giving the application control of the polling loop. On each iteration, it advances the network runtime, which dispatches ready I/O and services attached components. The market-data callback can invoke strategy work directly, while timed services handle work that must run periodically. Something like loop.run_one_turn() .

In order to demonstrate this architecture, we are going to use the market making tutorial from quantpylib. Using the same basic example, we can demonstrate market making in C++ with Quantcplib's network runtime, Gateway, Feed and OMS components over a single core.

A primary Binance SOLUSDT feed determines quote ladders for resting SOL orders on the Lighter exchange, using hysteresis to prevent quote bounce. A fast cancellation path exists for adverse movements. Refer to the tutorial for more details, here we are more interested in the architecture and code example than whether quote has alpha.

This is the ladder logic:

#pragma once

#include "standards/order.hpp"

#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <limits>
#include <stdexcept>

// Example-only fixed-point ladder, used directly by the network owner.
namespace mm {
namespace st = quantcplib::standards;
inline constexpr std::size_t max_levels = 16, max_orders = 2 * max_levels;
inline constexpr std::uint64_t second = 1'000'000'000, cancel_retry = 25'000'000;
inline std::uint64_t now_ns() {
    return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(
        std::chrono::steady_clock::now().time_since_epoch()).count());
}
struct Config {
    std::size_t levels = 7;
    std::int64_t notional = 15 * st::price_scale;
    std::int64_t inner_bps = 3, step_bps = 3;
    std::uint64_t stale_ns = 2 * second;
    void validate() const {
        if (!levels || levels > max_levels || notional <= 0 || inner_bps <= 0 ||
            step_bps <= 0 || inner_bps + step_bps >= 10'000 || !stale_ns)
            throw std::invalid_argument("Invalid ladder configuration");
    }
};
struct Quote { std::int64_t price = 0, amount = 0; };
struct Market {
    std::int64_t mid = 0, price_step = 0, qty_step = 0, min_qty = 0, min_notional = 0;
    std::uint64_t reference_ns = 0;
};
inline bool aggressive(std::int64_t price, std::int64_t amount, std::int64_t mid, const Config& config) {
    return amount > 0 ? static_cast<__int128_t>(price) * 10'000 > static_cast<__int128_t>(mid) * (10'000 - config.inner_bps)
                      : static_cast<__int128_t>(price) * 10'000 < static_cast<__int128_t>(mid) * (10'000 + config.inner_bps);
}
inline std::int64_t checked(__int128_t value) {
    if (value <= 0 || value > std::numeric_limits<std::int64_t>::max())
        throw std::overflow_error("Quote outside positive fixed-point range");
    return static_cast<std::int64_t>(value);
}

class Ladder {
public:
    explicit Ladder(Config config) : config_(config) { config_.validate(); }
    std::array<Quote, max_orders> quotes(const Market& state, std::uint64_t now) {
        if (state.mid <= 0 || state.price_step <= 0 || state.qty_step <= 0)
            throw std::invalid_argument("Missing reference or instrument increments");
        const auto mid = static_cast<__int128_t>(state.mid);
        if (!step_ || now - refreshed_ >= 600 * second || tick_ != state.price_step) {
            tick_ = state.price_step;
            const auto ticks = (mid * config_.step_bps + static_cast<__int128_t>(tick_) * 5'000) /
                               (static_cast<__int128_t>(tick_) * 10'000);
            step_ = checked(std::max<__int128_t>(1, ticks) * tick_);
            bid_ = floor_cell(mid * (10'000 - config_.inner_bps));
            ask_ = ceil_cell(mid * (10'000 + config_.inner_bps));
            refreshed_ = now;
        }
        // Same asymmetric window as the tutorial, with constant-time shifts.
        bid_ = std::min(bid_, floor_cell(mid * (10'000 - config_.inner_bps)));
        const auto inward_bid = floor_cell(mid * (10'000 - config_.inner_bps - config_.step_bps));
        if (bid_ < inward_bid) bid_ = inward_bid;
        ask_ = std::max(ask_, ceil_cell(mid * (10'000 + config_.inner_bps)));
        const auto inward_ask = ceil_cell(mid * (10'000 + config_.inner_bps + config_.step_bps));
        if (ask_ > inward_ask) ask_ = inward_ask;
        std::array<Quote, max_orders> result{};
        for (std::size_t i = 0; i < config_.levels; ++i) {
            const auto offset = static_cast<std::int64_t>(i);
            result[2*i] = quote((static_cast<__int128_t>(bid_) - offset) * step_, 1, state);
            result[2*i+1] = quote((static_cast<__int128_t>(ask_) + offset) * step_, -1, state);
        }
        return result;
    }
private:
    std::int64_t floor_cell(__int128_t numerator) const { return checked(numerator / (static_cast<__int128_t>(step_) * 10'000)); }
    std::int64_t ceil_cell(__int128_t numerator) const {
        const auto denominator = static_cast<__int128_t>(step_) * 10'000;
        return checked((numerator + denominator - 1) / denominator);
    }
    Quote quote(__int128_t raw_price, int side, const Market& spec) const {
        if (raw_price <= 0) return {};
        const auto price = checked(raw_price);
        const auto raw_qty = static_cast<__int128_t>(config_.notional) * st::qty_scale / price;
        const auto qty = raw_qty / spec.qty_step * spec.qty_step;
        if (qty <= 0 || qty < spec.min_qty || qty * price / st::qty_scale < spec.min_notional) return {};
        return {price, checked(qty) * side};
    }
    Config config_;
    std::int64_t step_ = 0, tick_ = 0, bid_ = 0, ask_ = 0;
    std::uint64_t refreshed_ = 0;
};
} // namespace mm
HangukQuant quantcplib Github Repo

HangukQuant quantcplib Github Repo

HangukQuant
·
July 7, 2025
Read full story

and mm.cpp for the single core driver that runs both the strategy and the network poll in a single thread: (header files available in the quantcplib repo…oh yea, did I mention? Lighter is now Gateway-compatible in quantcplib)

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2026 QUANTA GLOBAL PTE. LTD. 202328387H. · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for writing, podcasting, and media founders.