Objective Create a high-performance order executi...
Создано: 10 марта 2025 г.
Создано: 10 марта 2025 г.
Objective
Create a high-performance order execution and management system to trade on Deribit Test (https://test.deribit.com/) using C++.
Initial Setup
Core Requirements:
Order Management Functions
client id 6gdbOtkw
client secret dpxFzncIHAEP7OFYhq3PYvtnwlcZpC5IOUtTxm7ipzo
also give me direction to setup the project
Below is an outline of how you might set up a C++ project capable of placing orders on Deribit’s Test environment (https://test.deribit.com/) using their REST and/or WebSocket APIs. The example covers the basic steps from project structure and dependencies, to authenticating with your provided client_id
and client_secret
, and finally placing an order.
Compiler
You’ll need a modern C++ compiler (e.g., GCC 9+, Clang 10+, MSVC 2019+, etc.) that supports C++17 (or later).
Build System
A common choice is CMake. It simplifies dependency management and cross-platform builds.
HTTP & JSON Libraries
WebSocket Library (optional but recommended for real-time updates)
Your project structure might look like this:
textderibit_example/ ├── CMakeLists.txt ├── src/ │ ├── main.cpp │ ├── DeribitClient.cpp │ └── DeribitClient.h └── external/ ├── cpr/ (optional if you clone cpr) └── nlohmann/ (optional if you clone nlohmann/json)
6gdbOtkw
dpxFzncIHAEP7OFYhq3PYvtnwlcZpC5IOUtTxm7ipzo
(example from your post)Deribit’s REST API supports the standard OAuth 2.0 “client_credentials” grant type. You’ll send a POST to their /api/v2/public/auth
endpoint. The test environment base URL is https://test.deribit.com
.
A typical request to obtain a token would look like:
textPOST https://test.deribit.com/api/v2/public/auth Content-Type: application/json { "grant_type": "client_credentials", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET" }
Note: Deribit also allows passing these parameters as query arguments (?client_id=...&client_secret=...&grant_type=...
). In this example, we’ll assume you send JSON in the request body, which is usually done with a proper HTTP library.
Below is a minimal code snippet to fetch and store your OAuth token. You can adapt it if you choose different libraries.
cpp// DeribitClient.cpp #include "DeribitClient.h" #include <cpr/cpr.h> #include <nlohmann/json.hpp> #include <iostream> DeribitClient::DeribitClient(const std::string& clientId, const std::string& clientSecret) : clientId_(clientId), clientSecret_(clientSecret) { // Attempt to authenticate on construction authenticate(); } void DeribitClient::authenticate() { // Deribit test environment auth URL const std::string url = "https://test.deribit.com/api/v2/public/auth"; // Using cpr for the POST request cpr::Response r = cpr::Post( cpr::Url{url}, cpr::Payload{ {"client_id", clientId_}, {"client_secret", clientSecret_}, {"grant_type", "client_credentials"} } ); if (r.status_code != 200) { std::cerr << "Auth request failed with status " << r.status_code << ": " << r.text << std::endl; return; } auto jsonData = nlohmann::json::parse(r.text); // Store the access_token if (jsonData.contains("result") && jsonData["result"].contains("access_token")) { accessToken_ = jsonData["result"]["access_token"].get<std::string>(); std::cout << "Authenticated successfully. Access Token: " << accessToken_ << std::endl; } else { std::cerr << "Invalid auth response: " << r.text << std::endl; } }
And in the header file:
cpp// DeribitClient.h #pragma once #include <string> class DeribitClient { public: DeribitClient(const std::string& clientId, const std::string& clientSecret); // High-level order function void placeOrder(const std::string& instrumentName, const std::string& side, double amount, double price, const std::string& orderType); private: // Authentication void authenticate(); std::string clientId_; std::string clientSecret_; std::string accessToken_; };
According to Deribit’s API docs (Test environment uses the same endpoints, just on https://test.deribit.com
), the place order endpoint is:
textPOST /api/v2/private/buy or POST /api/v2/private/sell
Depending on whether you want to go long (buy) or short (sell). The request can include parameters like instrument_name
, amount
, type
(like "limit"
, "market"
), price
, etc.
Below is an example placeOrder
method. We’ll choose the buy
endpoint if side == "BUY"
, otherwise the sell
endpoint.
cpp#include <cpr/cpr.h> #include <nlohmann/json.hpp> #include <iostream> #include "DeribitClient.h" void DeribitClient::placeOrder(const std::string& instrumentName, const std::string& side, double amount, double price, const std::string& orderType) { if (accessToken_.empty()) { std::cerr << "No access token. Authenticate first." << std::endl; return; } // pick endpoint std::string endpoint = (side == "BUY") ? "buy" : "sell"; // Deribit test environment std::string url = "https://test.deribit.com/api/v2/private/" + endpoint; // Prepare the payload // e.g. 'instrument_name=BTC-PERPETUAL&amount=10&type=limit&price=50000' cpr::Payload payload = { {"instrument_name", instrumentName}, {"amount", std::to_string(amount)}, {"type", orderType} // e.g. "limit", "market" }; // If limit order, add the price if (orderType == "limit") { payload.AddPair({"price", std::to_string(price)}); } // Send the request cpr::Response r = cpr::Post( cpr::Url{url}, payload, cpr::Header{{"Authorization", "Bearer " + accessToken_}} ); if (r.status_code == 200) { auto jsonData = nlohmann::json::parse(r.text); std::cout << "Order response: " << jsonData.dump(2) << std::endl; } else { std::cerr << "Order failed with status " << r.status_code << ": " << r.text << std::endl; } }
Then, in your main.cpp
, you can do:
cpp#include <iostream> #include "DeribitClient.h" int main() { // Replace with your actual keys std::string clientId = "6gdbOtkw"; std::string clientSecret = "dpxFzncIHAEP7OFYhq3PYvtnwlcZpC5IOUtTxm7ipzo"; // Create client DeribitClient client(clientId, clientSecret); // Place a limit order, e.g. buy 10 contracts at price = 30000 client.placeOrder("BTC-PERPETUAL", "BUY", 10, 30000, "limit"); return 0; }
Compile and run. If successful, you should see an order response JSON object.
Below is a simple CMakeLists.txt
that fetches CPR, uses nlohmann/json, and builds an executable:
cmakecmake_minimum_required(VERSION 3.14) project(DeribitExample CXX) set(CMAKE_CXX_STANDARD 17) # Optionally fetch dependencies via CPM or FetchContent include(FetchContent) # Fetch cpr FetchContent_Declare( cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git GIT_TAG 1.10.4 # or the latest release ) FetchContent_MakeAvailable(cpr) # nlohmann/json (header-only) FetchContent_Declare( json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.11.2 # or the latest release ) FetchContent_MakeAvailable(json) # Add your sources add_executable(deribit_example src/main.cpp src/DeribitClient.cpp ) # Link libraries target_link_libraries(deribit_example PRIVATE cpr::cpr nlohmann_json::nlohmann_json )
To build:
bashcd deribit_example mkdir build && cd build cmake .. make ./deribit_example
For high-performance trading, you will likely want to consume real-time order books and trade data via WebSockets. Deribit’s WebSocket endpoint for the test environment is:
wss://test.deribit.com/ws/api/v2
You’d authenticate similarly by sending an auth
call over the WebSocket. Then you subscribe to channels such as book.BTC-PERPETUAL.raw
, trades.BTC-PERPETUAL.raw
, etc. See Deribit’s docs on WebSocket API usage.
Using a C++ WebSocket library like Boost.Beast might look like this in pseudocode:
cpp// Pseudocode for connecting to Deribit via WebSocket #include <boost/asio.hpp> #include <boost/beast/websocket.hpp> // ... boost::asio::io_context ioc; boost::asio::ip::tcp::resolver resolver(ioc); auto const results = resolver.resolve("test.deribit.com", "443"); boost::beast::websocket::stream<boost::asio::ip::tcp::socket> ws(ioc); // SSL/TLS details omitted for brevity if you need wss // Connect etc... // Perform WebSocket handshake ws.handshake("test.deribit.com", "/ws/api/v2"); // Now you can write JSON to the WebSocket // e.g. subscribe to the BTC-PERPETUAL orderbook std::string subscribeMessage = R"({ "jsonrpc": "2.0", "id": 42, "method": "public/subscribe", "params": { "channels": ["book.BTC-PERPETUAL.raw"] } })"; ws.write(boost::asio::buffer(subscribeMessage)); // Then read messages in a loop, parse JSON, process updates...
Once you’ve established the real-time stream, your trading system can react quickly to changing conditions and place/cancel orders with minimal latency.
/api/v2/public/auth
endpoint, saving the access_token
./api/v2/private/buy
or /api/v2/private/sell
.This should give you a solid starting point for building a C++-based, high-performance trading system on Deribit Test. Good luck, and happy coding!