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 Tests Platform

Features

  • CLOB V2 — pUSD exchange, EIP-712 domain v2, Poly1271 smart-contract signatures, builder-code attribution, GET /version protocol auto-detection (current default)
  • CLOB V1 — USDC.e exchange (still available alongside V2 — pin tag v1.0.0 or branch release/v1.x)
  • 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 + V2 new_market/market_resolved/best_bid_ask (opt-in via custom_feature_enabled)
  • 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 (V2 — current default, pUSD exchange)

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

Signer signer("0xYourPrivateKey");
AuthenticatedClobClient clob(signer, {api_key, secret, passphrase},
    "0xYourProxyWalletAddress",
    /*chain_id=*/137,
    /*host=*/std::string(CLOB_V2_API_URL));   // V2 host

// Optional: probe protocol version
if (clob.is_v2()) printf("Connected to V2 (pUSD)\n");

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

clob.cancel_order(result->orderID);
clob.cancel_market_orders();   // V2 endpoint

Authenticated trading (V1 — legacy, USDC.e exchange)

// V1 contracts still exist on-chain; use them for in-flight order settlement
// or pin v1.0.0 release: GIT_TAG v1.0.0 in FetchContent.
AuthenticatedClobClient clob(signer, {api_key, secret, passphrase},
    "0xYourProxyWalletAddress");                 // defaults to V1 host

auto order = clob.build_order(token_id, "0.55", "100", Side::Buy);
auto result = clob.place_order(*order);

See examples/ for 10 complete runnable examples — including 09_clob_v2_order_placement.cpp and 10_protocol_detection.cpp.

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)

# V2 (current — pUSD, EIP-712 v2)
FetchContent_Declare(polymarket
    GIT_REPOSITORY https://github.com/Wammero/polymarket-sdk-cpp.git
    GIT_TAG v2.0.0)

# V1 (legacy — USDC.e, EIP-712 v1)
# FetchContent_Declare(polymarket
#     GIT_REPOSITORY https://github.com/Wammero/polymarket-sdk-cpp.git
#     GIT_TAG v1.0.0)        # or: GIT_TAG release/v1.x

FetchContent_MakeAvailable(polymarket)
target_link_libraries(your_app PRIVATE polymarket)

Versioning

Parallel-branch release strategy mirroring Polymarket's own clob-clientclob-client-v2 migration (archived 2026-05-11):

  • v1.0.0 — last release targeting CLOB V1 (USDC.e, EIP-712 domain v1). Tag: v1.0.0. Branch: release/v1.x for maintenance fixes.
  • v2.0.0 — adds V2 support (pUSD, EIP-712 domain v2, new exchange 0xE111...996B, Poly1271 smart-contract signatures, builder attribution, GET /version auto-detection). V1 API surface is preserved alongside V2 — V1 callers compile unchanged.

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

555 test cases, 1760 assertions across 14 test suites (47 cases / 96 assertions are V2-tagged and cover the V2 EIP-712 hash, JSON wire format, Poly1271 signature type, contract_config_v2, and GET /version detection):

Suite Tests Asserts Covers
crypto 23 50 Keccak-256, HMAC-SHA256, secp256k1 signer, base64url, hex
auth 8 19 L1 EIP-712 wallet auth, L2 HMAC headers, Builder auth
order 68 315 Decimal math, tick sizes, V1+V2 order hash, EIP-712 v1+v2 signing, V2 wire JSON
error 36 74 Error constructors, factory methods, categorization, Result<T>
query_params 28 54 QueryParams building, locale-independent float serialization
json_parse 57 110 simdjson helpers, string-encoded numbers, optional/default fields
containers 99 359 SmallVector inline/heap/grow/erase/swap, Arena (OOM, absorb), FixedStr
config 19 48 V1 + V2 contract_config for all chains + neg_risk, V2 URLs/constants
enums 39 122 Side, OrderType, SignatureType (incl. Poly1271 = 3), TickSize, intervals
rtds 6 29 RTDS trade/envelope parsing, array dispatch
ws 19 78 WS event parsing, variant dispatch, V1 + V2 subscribe serialization
bugfixes 40 162 Regression tests for previously-fixed defects
api 113 340 CLOB (incl. V2 GET /version probe), Data, Gamma HTTP endpoints via mock server
live_api (opt-in) Read-only smoke tests against production endpoints (skipped without creds)

Integration tests (test_api) start a Python mock server automatically and exercise the public client classes end-to-end.

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 (V1)
08 08_whale_tracker.cpp Live trade feed whale detection (RTDS + Data API)
09 09_clob_v2_order_placement.cpp V2 order placement (pUSD, EIP-712 domain v2, builder attribution)
10 10_protocol_detection.cpp V2 GET /version probe + is_v2()

Run examples after building:

./build/examples/01_gamma_markets       # market data (no auth)
./build/examples/03_clob_public         # orderbook, prices (no auth)
./build/examples/10_protocol_detection  # V2: GET /version probe (no auth)
./build/examples/08_whale_tracker       # live whale alerts (no auth, Ctrl+C to stop)
# Authenticated:
./build/examples/09_clob_v2_order_placement   # V2 trading (needs POLY_* env vars)

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

Packages

 
 
 

Contributors