Skip to content

Wammero/polymarket-sdk-cpp

Repository files navigation

polymarket-sdk-cpp

High-performance C++23 SDK for Polymarket prediction markets.

CI C++23 CMake License: MIT Coverage Platform

Features

  • Gamma API — Markets, events, tags, series (simdjson + arena allocator, zero-copy)
  • CLOB API — Orderbook, prices, spreads, trading (Glaze compile-time JSON)
  • Data API — Positions, trades, leaderboard, activity, open interest
  • WebSocket — Real-time book/price/trade updates (custom uSockets + epoll/kqueue transport)
  • RTDS — Live trade feed from ws-live-data.polymarket.com (whale tracking, copy trading)
  • Crypto — Keccak-256, secp256k1, HMAC-SHA256, EIP-712 signing
  • Auth — L1 wallet auth, L2 HMAC headers, order building + signing
  • RFQ — Request-for-Quote (11 endpoints)

Quick Start

Fetch top market and orderbook

#include <polymarket/gamma/gamma_client.hpp>
#include <polymarket/clob/clob_client.hpp>
#include <cstdio>

using namespace polymarket;

int main() {
    GammaClient gamma;
    ClobClient  clob;

    // Fetch the top market by volume
    MarketsFilter f;
    f.limit = 1; f.active = true; f.order = "volume"; f.ascending = false;
    auto markets = gamma.get_markets(f);
    if (!markets || markets->data.empty()) return 1;

    auto& m = markets->data[0];
    printf("Market: %.*s\n", (int)m.question.size(), m.question.data());

    // Token IDs come from the Gamma API's clob_token_ids field
    // e.g. '["71321...","99421..."]' — see examples/03_clob_public.cpp for parsing
    auto book = clob.book("71321045679252212594626385532706912750332728571942532289631379312455583992563");
    if (book && !book->bids.empty())
        printf("Best bid: %s @ %s\n", book->bids.back().price.c_str(), book->bids.back().size.c_str());
}

Real-time WebSocket

#include <polymarket/ws/ws_client.hpp>
using namespace polymarket;

WsClient ws;
ws.on_book([](WsBookUpdate book) {
    printf("Book update: %zu bids, %zu asks\n", book.bids.size(), book.asks.size());
});
ws.on_trade([](WsLastTradePrice t) {
    printf("Trade: %s @ %s\n", t.asset_id.c_str(), t.price.c_str());
});
ws.subscribe({"71321045679252212594626385532706912750332728571942532289631379312455583992563"});
ws.connect();  // non-blocking, I/O thread handles reconnect automatically

Authenticated trading

#include <polymarket/clob/authenticated_client.hpp>
using namespace polymarket;

Signer signer("0xYourPrivateKey");
AuthenticatedClobClient clob(signer, {api_key, secret, passphrase},
    "0xYourProxyWalletAddress");

auto order = clob.build_order(token_id, "0.55", "100", Side::Buy);
auto result = clob.place_order(*order);
printf("Order: %s (%s)\n", result->orderID.c_str(), result->status.c_str());

clob.cancel_order(result->orderID);
clob.cancel_all();

See examples/ for 8 complete runnable examples covering all APIs.

Build

git clone https://github.com/Wammero/polymarket-sdk-cpp.git
cd polymarket-sdk-cpp
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)

Run tests

# Unit tests (no network required)
ctest --test-dir build -R "^(crypto|auth|order|error|query_params|json_parse|containers|config|enums|rtds)$"

# Integration tests (requires Python 3 — starts mock server automatically)
ctest --test-dir build -R "^api$"

Coverage report

cmake -B build-cov -DCMAKE_BUILD_TYPE=Debug \
    -DCMAKE_CXX_FLAGS="--coverage -O0 -g" \
    -DCMAKE_EXE_LINKER_FLAGS="--coverage"
cmake --build build-cov -j$(nproc)
ctest --test-dir build-cov
gcovr --root . --filter 'include/polymarket/' --filter 'src/' build-cov/ \
    --gcov-ignore-errors=source_not_found \
    --gcov-ignore-errors=no_working_dir_found \
    --print-summary

Use as dependency (FetchContent)

include(FetchContent)
FetchContent_Declare(polymarket
    GIT_REPOSITORY https://github.com/Wammero/polymarket-sdk-cpp.git
    GIT_TAG main)
FetchContent_MakeAvailable(polymarket)
target_link_libraries(your_app PRIVATE polymarket)

Requirements

  • C++23 compiler (GCC 13+, Clang 17+)
  • CMake 3.21+
  • OpenSSL
  • libcurl
  • Python 3 (for integration tests only)

All other dependencies fetched automatically via CMake FetchContent: simdjson, Glaze, secp256k1, ethash/keccak, unordered_dense, uSockets, mimalloc, Catch2.

Test Coverage

468 test cases, 1501 assertions across 12 test suites:

Suite Tests Covers
crypto 23 Keccak-256, HMAC-SHA256, secp256k1 signer, base64url, hex
auth 8 L1 EIP-712 wallet auth, L2 HMAC headers, Builder auth
order 40 Decimal math, all tick sizes, validation, overflow, order struct hash, EIP-712 signing
error 36 Error constructors, all factory methods, categorization, Result<T>
query_params 28 QueryParams building, locale-independent float serialization
json_parse 57 simdjson helpers, string-encoded numbers, optional/default fields
containers 99 SmallVector inline/heap/grow/erase/swap, Arena (OOM, absorb), FixedStr
config 8 contract_config and wallet_config for all chains + neg_risk
enums 38 Side, OrderType, SignatureType, TickSize, PriceHistoryInterval
rtds 6 RTDS trade/envelope parsing, array dispatch
ws 15 WS event parsing, variant dispatch, subscribe serialization
api 110 CLOB, Data, Gamma HTTP endpoints via mock server

Integration tests (test_api) cover CLOB, Data, and Gamma HTTP endpoints via a Python mock server.

Coverage (unit + integration):

Module Lines Coverage
auth/ 72 97–100%
crypto/ 223 90–100%
clob/ 350 98–100%
data/ 179 100%
gamma/ 1044 81–100%
order/ 122 99%
core/ (arena, fixed_str, small_vector) 946 78–99%
config, error, enums, query\_params 207 100%
json/parse 206 71%
http\_client 141 97%
ws\_client 499 0% (requires live WS server)
Total 3874 83% lines, 89% functions

Performance

Benchmarked against the official Polymarket Rust SDK on the same machine. Identical JSON inputs. Rust: cargo bench (criterion). C++: nanobench.

Operation C++ Rust Speedup
Orderbook 10 levels 949 ns 1,792 ns 1.9x
Market response 762 ns 1,495 ns 2.0x
secp256k1 ECDSA sign 17.3 us 51.3 us 3.0x
Keccak-256 211 ns 290 ns 1.4x
HMAC-SHA256 167 ns 150 ns 0.9x
Order build + sign 23 us

JSON: Glaze compile-time reflection (C++) vs serde_json runtime (Rust). ECDSA: bitcoin-core/secp256k1 (C) vs alloy/k256 (pure Rust). HMAC: Rust slightly faster — both use platform-native crypto.

Architecture

Layer Library Purpose
Gamma JSON simdjson on-demand + arena Large arrays, zero-copy string_view
CLOB/Data JSON Glaze Small responses, compile-time reflection
WebSocket JSON Glaze direct dispatch Per-event-type parsing, no variant overhead
WebSocket transport uSockets (epoll/kqueue) Custom frame parser, TLS, auto-reconnect
HTTP libcurl Keep-alive, gzip, HTTP/2
Hashing ethash/keccak Keccak-256 with BMI2
Signing bitcoin-core/secp256k1 ECDSA sign + recovery
HMAC OpenSSL EVP_MAC SHA-256 with hardware acceleration
Memory mimalloc Global allocator

Examples

# File Description
01 01_gamma_markets.cpp Market lookup, events, pagination, batch fetch, tags
02 02_gamma_streaming.cpp Auto-pagination, streaming callbacks, predicate filtering
03 03_clob_public.cpp Orderbook, prices, spreads, batch queries, price history
04 04_data_api.cpp Leaderboard, positions, trades, activity, open interest
05 05_websocket_market.cpp Real-time book/price/trade streaming
06 06_credentials.cpp Derive API credentials from private key
07 07_order_placement.cpp GTC/GTD/FOK orders, batch placement, cancellation
08 08_whale_tracker.cpp Live trade feed whale detection (RTDS + Data API)

Run examples after building:

./build/examples/01_gamma_markets       # market data (no auth)
./build/examples/03_clob_public         # orderbook, prices (no auth)
./build/examples/08_whale_tracker       # live whale alerts (no auth, Ctrl+C to stop)

For AI Agents

  • llms.txt — Compact SDK overview for LLM context
  • llms-full.txt — Complete API reference for writing code with this SDK

License

MIT

About

High-performance C++23 SDK for Polymarket — Gamma, CLOB, Data, WebSocket, RTDS, RFQ. 3x faster than Rust SDK.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors