ccapi Documentation

repository·develop·Indexed 20 days ago

https://github.com/crypto-chassis/ccapi

A high-performance, header-only C++ library for streaming market data and executing trades directly from cryptocurrency exchanges. It features low-latency connections, a Bloomberg-style API, and supports a wide range of exchanges including Binance, Coinbase, Bybit, Kraken, and OKX. The library provides multi-language bindings for Python, Java, C#, Go, and JavaScript.

Tokens
6K
Snippets
14
Records
21
Agent score
23%

What's inside ccapi

  1. Overview of ccapi

    develop

    ccapi is a high-performance, header-only C++ library designed for streaming market data and executing trades directly from cryptocurrency exchanges. It establishes direct connections between your server and the exchange server.

    Key features:

    • Ultra-fast: Optimized for high-speed trading.
    • Multi-language support: Provides bindings for Python, Java, C#, Go, and JavaScript.
    • Bloomberg-style API: The code structure closely follows the Bloomberg API pattern.
    • Broad Exchange Support: Supports a wide range of exchanges for Market Data, Execution Management, and FIX API (e.g., Binance, Coinbase, Bybit, Kraken, OKX, etc.).
  2. How event handling modes work

    develop

    ccapi supports two modes of event handling:

    1. Immediate Mode: When a Session is instantiated with an EventHandler argument, processEvent is invoked immediately upon receiving an event. This runs on the thread where the underlying boost::asio::io_context is running. If an EventDispatcher is also provided, the invocation runs in the threads provided by the dispatcher, preventing the io_context thread from being blocked.
    2. Batching Mode: When a Session is instantiated without an EventHandler, events are collected in an internal Queue<Event>. You can retrieve them manually using: std::vector<Event> eventList = session.getEventQueue().purge();
  3. Build ccapi for C++

    develop

    ccapi is a header-only C++ library. To use it in your C++ project, you must satisfy the following requirements and configuration steps:

    Requirements

    • C++ Standard: C++17 or higher.
    • Dependencies:
      • OpenSSL: Required for secure connections.
      • Boost: Include directory should be boost.
      • RapidJSON: Include directory should be rapidjson/include.
      • hffix: Required only if using the FIX API.
      • ZLIB: Required for market data on Huobi (and variants) or execution management on Huobi/Bitmart.

    Configuration via Macros

    You must define macros in your compiler command line to enable specific services and exchanges. These macros are located in include/ccapi_cpp/ccapi_session.h.

    Service Enablement Macros:

    • CCAPI_ENABLE_SERVICE_MARKET_DATA
    • CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT
    • CCAPI_ENABLE_SERVICE_FIX

    Exchange Enablement Macros:

    • Example: CCAPI_ENABLE_EXCHANGE_BYBIT

    Linking and Flags

    • Libraries to link:
      • libssl and libcrypto (OpenSSL).
      • ws2_32 (Windows only).
    • Compiler Flags:
      • -pthread (GCC and MinGW).

    Troubleshooting C++ Build

    • OpenSSL not found: Set OPENSSL_ROOT_DIR.
      • macOS: cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl (after brew install openssl).
      • Ubuntu: sudo apt-get install libssl-dev.
      • Windows: cmake -DOPENSSL_ROOT_DIR=C:/vcpkg/installed/x64-windows-static (after vcpkg install openssl:x64-windows).
    • 'File too big' error: Add compiler flag -Wa,-mbig-obj.
    • 'string table overflow' error: Add optimization flag -O1 or -O2.
    # Example of setting OpenSSL path for CMake
    cmake -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl ..
  4. Place Hyperliquid orders using Asset IDs

    develop

    When creating or cancelling orders on Hyperliquid, use the exchange's specific asset ID as the instrument string instead of a ticker symbol. For example, on mainnet, BTC is represented by ID 0.

    Request request(Request::Operation::CREATE_ORDER, "hyperliquid", "0");  // Corresponds to https://app.hyperliquid.xyz/trade/BTC
  5. Run Javascript examples

    develop

    The Javascript API is nearly identical to the C++ API. After building and installing the Javascript binding, use npm to install dependencies and node to run the entry point.

    # Inside a concrete example directory
    rm -rf node_modules # if rebuild from scratch
    npm install
    node index.js
  6. Configure advanced market data subscriptions

    develop

    ccapi allows fine-grained control over market data subscriptions using options passed to the Subscription constructor:

    • Market Depth Size: Use MARKET_DEPTH_MAX=N to receive snapshots for the top N levels (e.g., "MARKET_DEPTH_MAX=10").
    • Conflation: Use CONFLATE_INTERVAL_MILLISECONDS=N to receive events at periodic intervals. Combine with CONFLATE_GRACE_PERIOD_MILLISECONDS=N to handle late events.
    • Order Book Updates: Use MARKET_DEPTH_RETURN_UPDATE=1 to receive incremental updates instead of full snapshots.
    • Candlesticks: Use CANDLESTICK_INTERVAL_SECONDS=N for exchange-provided candlesticks.
    • Correlation ID: Pass a unique string as the correlationId to match specific requests/subscriptions with returned data.
  7. Provide API credentials to an exchange

    develop

    There are three ways to provide credentials, listed in order of increasing priority:

    1. Environment Variables: Set variables like BYBIT_API_KEY and BYBIT_API_SECRET. Some exchanges require others like OKX_API_PASSPHRASE.
    2. SessionConfigs: Pass a map of credentials to the SessionConfigs object.
      sessionConfigs.setCredential({
        {"BYBIT_API_KEY", ...},
        {"BYBIT_API_SECRET", ...}
      });
    3. Request or Subscription: Pass credentials directly to the Request or Subscription constructor/object.
      Request request(Request::Operation::CREATE_ORDER, "bybit", "BTCUSDT", "", {
        {"BYBIT_API_KEY", ...},
        {"BYBIT_API_SECRET", ...}
      });
  8. Build and run C++ examples

    develop

    To build C++ examples, you must have CMake installed. Follow these steps to create a build directory, configure the project, and compile a specific target.

    Note: The resulting executable will be located in example/build/src/<example-name>/<example-name>.

    mkdir example/build
    cd example/build
    rm -rf * # if rebuild from scratch
    cmake ..
    cmake --build . --target <example-name>
    # Run the executable located at:
    # example/build/src/<example-name>/<example-name>
  9. Run C# examples

    develop

    The C# API is nearly identical to the C++ API. To run examples, use dotnet run while providing the path to the ccapi library and ensuring the LD_LIBRARY_PATH environment variable is set so the runtime can find the native dependencies.

    Troubleshooting:

    • If you see error CS0246: The type or namespace name 'ccapi' could not be found, check your ccapi assembly references.
    • If you see System.DllNotFoundException: Unable to load shared library 'ccapi_binding_csharp.so', ensure LD_LIBRARY_PATH includes the directory binding/build/csharp/packaging/1.0.0.
    # Inside a concrete example directory
    dotnet clean # if rebuild from scratch
    env LD_LIBRARY_PATH="$LD_LIBRARY_PATH:../../../build/csharp/packaging/1.0.0" dotnet run --property:CcapiLibraryPath=../../../build/csharp/packaging/1.0.0/ccapi.dll -c Release
  10. Run Go examples

    develop

    The Go API is nearly identical to the C++ API. Crucial Step: You must source the export_compiler_options.sh file before building, as it provides the environment variables required by the cgo tool to find C/C++ headers.

    Troubleshooting: If you encounter errors stating that C/C++ header files are not found, verify that you successfully sourced export_compiler_options.sh.

    # Inside a concrete example directory
    go clean # if rebuild from scratch
    source ../../../build/go/packaging/1.0.0/export_compiler_options.sh
    go build .
    ./main
  11. Configure Hyperliquid execution management in CMake

    develop

    To use execution management with the Hyperliquid exchange on macOS, you must ensure secp256k1 and msgpack are available and correctly linked in your CMakeLists.txt. You must also define CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT and CCAPI_ENABLE_EXCHANGE_HYPERLIQUID to enable these features.

    if(APPLE)
      find_path(SECP256K1_INCLUDE_DIR secp256k1.h PATHS /opt/homebrew/include)
      find_path(
        MSGPACK_INCLUDE_DIR
        NAMES msgpack.hpp
        PATHS /opt/homebrew/include)
    
      find_library(SECP256K1_LIBRARY secp256k1 PATHS /opt/homebrew/lib)
      find_library(MSGPACKC_LIBRARY msgpackc PATHS /opt/homebrew/lib)
    endif()
    
    add_compile_definitions(CCAPI_ENABLE_SERVICE_EXECUTION_MANAGEMENT)
    add_compile_definitions(CCAPI_ENABLE_EXCHANGE_HYPERLIQUID)
    add_executable(${NAME} main.cpp)
    add_dependencies(${NAME} boost rapidjson)
    
    target_include_directories(${NAME} PRIVATE ${SECP256K1_INCLUDE_DIR}
                                               ${MSGPACK_INCLUDE_DIR})
    target_link_libraries(${NAME} PRIVATE ${SECP256K1_LIBRARY} ${MSGPACKC_LIBRARY})
  12. Build ccapi bindings for non-C++ languages

    develop

    To build bindings for Python, Java, C#, Go, or JavaScript, you need SWIG and CMake.

    Prerequisites

    • SWIG: Install via brew install SWIG (macOS) or sudo apt-get install -y swig (Linux).
    • CMake: Required for the build process.

    Build Instructions

    Run the following commands from the repository root:

    1. Create and enter the build directory:

      mkdir binding/build
      cd binding/build
    2. Configure the build with the desired language flag:

      • Python: -DBUILD_PYTHON=ON
      • Java: -DBUILD_JAVA=ON
      • C#: -DBUILD_CSHARP=ON
      • Go: -DBUILD_GO=ON
      • JavaScript: -DBUILD_JAVASCRIPT=ON

      Example for Python:

      cmake -DBUILD_PYTHON=ON -DBUILD_VERSION=1.0.0 ..
    3. Build the project:

      cmake --build .

    Artifact Locations

    • Packaged artifacts: binding/build/<language>/packaging/<BUILD_VERSION>
    • SWIG raw files/build artifacts: binding/build/<language>/ccapi_binding_<language>

    Troubleshooting Bindings

    • Python: Requires Python 3. If using Python >= 3.8, ensure SWIG is >= 4.0 to avoid _PyObject_GC_UNTRACK errors.
    • Java: Ensure JAVA_HOME is set correctly if JNI is not found.
    • JavaScript: Install node-gyp via npm install -g node-gyp if it is missing.
    mkdir binding/build
    cd binding/build
    cmake -DBUILD_PYTHON=ON -DBUILD_VERSION=1.0.0 ..
    cmake --build .