Skip to content

Repository files navigation

bt_api_cpp

bt_api_cpp is a C++20 implementation effort for the Python bt_api ecosystem. The target is API parity with the local Python reference repositories while preserving C++ type safety, explicit errors, offline tests by default, and exchange plugin boundaries.

Current status: core scaffold and parity evidence are in progress. The repository is buildable and has an offline mock-backed core test, but it is not full Python parity yet.

Reference Scope

The parity target is based on these local Python repositories:

  • /home/yun/Documents/bt_api_base
  • /home/yun/Documents/bt_api_py
  • /home/yun/Documents/bt_api_binance
  • /home/yun/Documents/bt_api_okx
  • /home/yun/Documents/bt_api_ctp
  • /home/yun/Documents/bt_api_mt5
  • /home/yun/Documents/bt_api_ib_web

Build And Test

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

The current test suite is offline by default and should not contact live exchange endpoints.

Current C++ Surface

The current scaffold API reference is docs/api/current-scaffold-api.md.

Implemented scaffold areas:

  • bt_api::BtApi facade seed for exchange registration, request routing, trade/account/position pass-through, balance aggregation helpers, historical bar queue helpers with count-mode and Python-style range window/retry/count omission behavior, batch tick/balance/position/cancel-all helpers with Python-style BtApiError warning-and-skip behavior, subscription dispatch with Python-style subscribe_bar_num kline counting and Binance/OKX account-stream _subscription_flags, event bus access, ticker emission, logging facade, order validation, and close lifecycle.
  • Core Value/Options dynamic payload type for Python-like dict[str, Any] compatibility seams.
  • Typed exception hierarchy.
  • Thread-safe queue with Python queue.Queue migration aliases plus event bus primitives.
  • Core connection pool scaffolds for Python ConnectionPool, AsyncConnectionPool, PooledConnection, and AsyncPooledConnection acquisition/release behavior.
  • Core config and auth seeds for Python config_loader.py and auth_config.py object/schema behavior, a standard-library YAML config subset parser for scaffold config files, plus gateway endpoint config generation.
  • Lightweight core logger factory with Python module-name mapping, BT_API_LOG_DIR support, cached loggers, and warning/warn compatibility.
  • Plugin metadata/loader seed for Python PluginInfo/PluginLoader semantics: isolated registry/runtime registration, core version checks, duplicate exchange/adapter rejection, loaded/failed/skipped ledgers, and gateway runtime adapter registrar plus offline runtime, health, subscription, and order identity/order-ref support.
  • Binance, OKX, CTP, IB Web, and MT5 plugin registration seeds with Python-compatible metadata where present plus explicit backtrader_web gateway extensions. Binance/OKX include configured REST path/auth snapshots and balance handlers; Binance includes deterministic helper mappings for Python ticker, bar, funding-rate, mark-price, order-book, symbol, income, order, trade, position, balance, and account payloads, while OKX includes deterministic helper mappings for ticker, bar, funding-rate, mark-price, order-book/L2 order-book, open interest, price-limit, symbol, assets, greeks, liquidation, order, trade, market-trade, position, balance, and account payloads plus OKX exchange-data leverage metadata and legacy _make_order size-conversion helper coverage; CTP/IB Web include gateway-backed feed, exchange-data, balance-handler, stream, and gateway-adapter scaffolds; CTP also includes deterministic helper mappings for Python CTP ticker, bar, order, trade, position, and account payloads plus a representative native split-struct shim for the generated bt_api_ctp.ctp.* modules; IB Web includes deterministic helper mappings for Python IB ticker, bar, order, trade, position, account, and contract payloads plus gateway symbol-info normalization/cache helpers, fixture-backed gateway stream item dispatch, shared REST/WSS exchange-data path snapshots, and session/cookie helper scaffolding for settings, env/dotenv precedence, file/direct/env cookie payloads, auth-status checks, and account selection; MT5 registers explicit OTC/STK/FX gateway-backed feed/exchange-data/balance/stream discovery entries plus a gateway adapter and includes deterministic gateway helper scaffolding for timeframe, side/status, balance, position, order, trade, volume, timestamp, symbol normalization, and adapter callback event behavior.
  • Binance/OKX plugin registration also exposes scaffold runtime gateway adapter factories for the BINANCE and OKX exchange types; production gateway methods remain explicit unsupported boundaries.
  • CTP SimNow environment selector scaffold matching Python get_ctp_fronts and apply_ctp_env behavior for set1/set2 front selection and env synchronization.
  • Core HTTP request/transport scaffold for Python HttpClient and Feed.http_request semantics, including query/cookie helpers, typed HTTP status errors, retry/timeout mapping, and mock transport testing.
  • Standard-library SHA-256/HMAC-SHA256 hex/base64 helpers plus configured REST authentication scaffolding for Binance-style query signatures and OKX-style signed headers.
  • Configured REST feed scaffold that resolves ExchangeConfig/AssetTypeConfigrest_paths, derives capabilities, joins REST base URLs, sends GET/DELETE query strings or POST/PUT/PATCH JSON bodies through the injected HTTP client, fills light standard containers for ticker/order/funding/mark/balance responses, routes server-time, exchange-info/instruments, open-interest, income, fee, leverage-bracket, position-mode, change-leverage, change-margin-type, modify-order, cancel-orders, query-order, open-orders, get-deals, public get-trades, get-all-orders, and OKX RFQ/block REST request-shape helpers, maps Python-shaped Binance/OKX order parameters plus OKX RFQ/kline parameters, and enriches representative order/trade/position/account RequestData payloads with Python-style request metadata, success status, normalized field names, shared OrderStatus values, and Binance nested force-order aliases while preserving raw venue fields; configured cancel_all_symbol endpoints are preferred for symbol-specific cancellations, and config-driven registration helpers can register these feeds and exchange-data snapshots into ExchangeRegistry.
  • Binance and OKX WebSocket adapter/helper scaffolds for Python endpoint/channel mapping, subscribe/unsubscribe messages, topic/symbol extraction, market message normalization, stream limits, and registration-level subscribe stream-start events where present in the source APIs.
  • Core WebSocket adapter factory scaffold for Python WebSocketAdapterFactory exchange-type inference, Binance plugin adapter loading, OKX adapter creation, and generic fallback behavior.
  • Core WebSocket connection/manager scaffold for Python WebSocketConfig, Subscription, WebSocketConnection, and WebSocketManager semantics, using injected mockable transports for offline tests plus an optional Boost.Beast-backed default ws:///wss:// transport when Boost headers and OpenSSL are available.
  • Core cache and rate limiter seeds for TTL/LRU caching, exchange/market data cache helpers, sliding-window limits, fixed-window limits, endpoint matching, weighted requests, and std::future async acquire wrappers.
  • Core async-context utility scaffolds for Python AsyncRateLimiter, AsyncSemaphore, AsyncQueue, AsyncTaskGroup, async_retry, async_timeout, and async_circuit_breaker behavior, mapped to C++ blocking/callable helpers.
  • Standard container seeds for RequestData, TickerData, OrderData, BalanceData, OrderBookData, BarData, TradeData, PositionData, and AccountData, SymbolData, FundingRateData, MarkPriceData, IncomeData, GreeksData, LiquidationData, TimerData, and Instrument, including the Python-style RequestData envelope constructor and lazy normalizer/status behavior.
  • Feed/capability interface seed with explicit unsupported errors, HTTP request helper injection, funding/mark/clear-price/open-interest, income, fee, leverage-bracket, position-mode, change-leverage, change-margin-type, modify-order, cancel-orders, query-order, open-orders, get-all-orders, get-deals/get-trades, exchange-info, and server-time protocol methods, and default std::future async wrappers for core feed operations.
  • Registry-only feed and stream construction.
  • Gateway adapter/client/model seed with kwargs/runtime construction, scaffold live tick queue demux, subscription filtering, bounded tick queues, symbol alias handling, cancel payload aliases, private event ownership filtering, compact protocol message helpers, runtime support maps, persistent order-ref allocation, offline runtime command dispatch and command envelope handling, explicit gateway_market_endpoint live capability fallback, gateway-backed feed bridges for broker/gateway plugin seeds, and explicit unsupported default scaffold adapters.
  • Recursive credential masking plus deterministic SecureCredentialManager helpers for env lookup, API-key validation, exchange credential collection, .env parsing, and env-template generation.

Important gaps:

  • BtApi public method coverage is complete for the Python facade, and the scaffold now exposes explicit C++ async feed proxies for Python's dynamic async_* facade behavior, but semantic parity is still incomplete.
  • Standard container seeds exist, the configured REST scaffold covers a representative Binance/OKX-style payload normalization slice, and Binance/OKX/CTP/IB Web have deterministic container-helper slices; complete nullable/default policy audits and remaining exchange-specific container mappings are still incomplete.
  • Dynamic plugin discovery/loading, production credential encryption, production live HTTP transport, production nonblocking live-transport cancellation and reconnect orchestration, authenticated exchange stream lifecycles, production exchange-specific stream adapters, production structured/spdlog logging backend, full YAML-spec parser coverage, and true coroutine/event-loop async policy are not implemented.
  • Production gateway ZMQ/socket runtime behavior and per-exchange gateway adapters remain incomplete.
  • The configured REST feed and Binance/OKX WebSocket helpers are shared plugin-building scaffolds only; exchange signing is only scaffolded for HMAC-SHA256 request shapes; open-interest, server-time, exchange-info, Binance SWAP income routing, Binance SPOT/SWAP fee routing, Binance SWAP leverage-bracket/position-mode account-query routing, Binance SWAP change-leverage/change-margin-type signed POST request-shape routing, Binance SWAP modify-order/cancel-orders signed PUT/DELETE request-shape routing, Binance SWAP query-order/open-orders signed query routing, Binance SPOT/SWAP get-all-orders and get-deals signed query routing, Binance SPOT/SWAP public get-trades routing, Binance/OKX Python-shaped make-order request parameters, and OKX signed get-deals plus public market-trades/kline routing are configured for REST snapshots where present, including Python-style count/income_type aliases for income requests and query/open-order aliases, but live stream authentication, production venue integrations, and complete fixture-backed payload mapping are still deferred to Binance/OKX/IB Web plugin work.
  • Binance, OKX, CTP, IB Web, and MT5 now have C++ plugin registration seeds, IB Web has deterministic session/cookie, gateway symbol-info, and stream-item dispatch helpers, and MT5 has deterministic gateway helper plus callback-event scaffolding, but production exchange behavior remains incomplete.
  • Live trading/network tests are not part of the current scaffold.

Parity Evidence

  • docs/api/current-scaffold-api.md documents the public C++ scaffold surface that currently exists.
  • docs/parity/core-parity.md tracks the first scaffold slice.
  • docs/parity/source-api-index.md summarizes extracted Python API surfaces.
  • docs/parity/python-api-surface.json is the machine-readable source API manifest.
  • docs/parity/facade-gateway-coverage.md tracks method-level BtApi and GatewayClient status.
  • docs/parity/facade-gateway-coverage.json is the machine-readable facade/gateway public-surface coverage report.
  • docs/parity/parity-gap-backlog.md lists the current parity gaps and acceptance evidence needed.
  • docs/parity/exchange-support.md tracks target exchange identifiers and implementation status.
  • docs/parity/fr-traceability.md maps PRD FR-1 through FR-18 to current evidence and missing acceptance proof.

Regenerate parity evidence:

python3 tools/extract_api_surface.py --output docs/parity/python-api-surface.json
python3 tools/check_facade_gateway_coverage.py --output docs/parity/facade-gateway-coverage.json

Run the current local scaffold acceptance gate:

python3 tools/run_acceptance.py

The latest generated report is _bmad-output/implementation-artifacts/core-scaffold-acceptance-report.md.

Architecture Direction

The design follows a hexagonal plugin architecture:

  • Core owns stable abstractions: facade, registry, feed interface, containers, event bus, queues, config, plugin metadata/loading contracts, rate limiting, cache, security, errors, and gateway contracts.
  • Exchange plugins own venue details: paths, signing, auth sessions, raw payload parsing, native handles, WebSocket topics, and gateway bridge specifics.
  • Public parity methods preserve Python snake_case names and exchange-name-first routing where applicable.
  • Every Python public method in scope must be implemented, tested, and documented, or explicitly listed as deferred/unsupported with a reason.

BMad Artifacts

  • PRD: _bmad-output/planning-artifacts/prds/prd-bt_api_cpp-2026-06-28/prd.md
  • PRD addendum: _bmad-output/planning-artifacts/prds/prd-bt_api_cpp-2026-06-28/addendum.md
  • Architecture spine: _bmad-output/planning-artifacts/architecture/architecture-bt_api_cpp-2026-06-28/ARCHITECTURE-SPINE.md
  • Quick-dev scaffold spec: _bmad-output/implementation-artifacts/spec-core-scaffold.md

Completion Rule

The project is not complete until the user-named Python API surfaces are implemented in C++ or explicitly deferred by the user, with matching code, tests, parity documentation, and acceptance evidence.

About

the cpp version of bt_api

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages