Binance Common Types and Utilities for Binance C++ Connectors

binance::common is the shared library of the Binance C++ connectors. It implements what every connector needs to talk to the Binance REST and WebSocket APIs: configuration, request signing, HTTP and WebSocket transports, connection management, error types and utilities. The connectors under clients/ are generated on top of it, and it can also be used on its own.
Installation
binance::common is built and installed with every connector (see the root README). To use it on its own:
cmake --preset release -DBINANCE_PRODUCTS=""
cmake --build --preset release
cmake --install build/release --prefix /opt/binance --strip
find_package(binance-connector-cpp CONFIG REQUIRED)
target_link_libraries(app PRIVATE binance::common)
Features
- REST client with connection reuse, retries with backoff (GET and DELETE), gzip/deflate decoding and rate-limit headers.
- Request signing with HMAC-SHA256, RSA or Ed25519 keys.
- WebSocket API client: request/response matching, connection pools, session logon that is repeated after reconnects, and user-data subscriptions that are restored after reconnects.
- WebSocket Streams client: subscriptions over connection pools and URL paths, restored after reconnects.
- Automatic connection management: reconnects with backoff, renewal every 23 hours and on serverShutdown, and dead-connection detection.
- Typed responses and events decoded on demand, with exact decimals (Decimal) and 64-bit integers.
- Blocking or asynchronous calls: every request also accepts any Asio completion token (callback, use_future, use_awaitable, ...).
- Proxies (HTTP and HTTPS, with Basic auth, or from the environment) and a TLS hook to add CAs or pin certificates.
- Errors as one exception hierarchy carrying Binance's code() and msg().
Usage
REST
RestClient sends any Binance REST request:
#include <binance/common/rest.hpp>
cfg.
base_path =
"https://testnet.binance.vision";
client.send_request({.method = HttpMethod::Get, .endpoint = "/api/v3/time"}));
std::cout << time.data().at("serverTime") << "\n";
order.
query = {{
"symbol",
"BNBUSDT"}, {
"side",
"BUY"}, {
"type",
"MARKET"}, {
"quantity",
"0.01"}};
const auto placed = client.send_request(order);
const auto depth = co_await client.async_send_request(
{.method =
HttpMethod::Get, .endpoint =
"/api/v3/depth", .query = {{
"symbol",
"BNBUSDT"}}},
boost::asio::use_awaitable);
A successful REST response whose body is decoded into T on first use.
Definition models.hpp:285
The REST transport shared by every product.
Definition rest.hpp:68
@ Post
Definition rest.hpp:33
@ Get
Definition rest.hpp:33
Definition config.hpp:110
std::optional< std::string > base_path
Set by the product factory (SpotRestApi::production(...), …) when empty.
Definition config.hpp:114
std::optional< std::string > api_secret
Definition config.hpp:112
std::optional< std::string > api_key
Definition config.hpp:111
One REST call, before signing and serialisation.
Definition rest.hpp:38
Params query
Definition rest.hpp:42
bool is_signed
Adds timestamp and signature.
Definition rest.hpp:48
WebSocket API and Streams
WebsocketApi sends WebSocket API requests; WebsocketStreams subscribes to market streams. Both reconnect, renew their connections every 23 hours and survive serverShutdown on their own.
#include <binance/common/websocket_api.hpp>
#include <binance/common/websocket_streams.hpp>
api_cfg.
url =
"wss://ws-api.testnet.binance.vision/ws-api/v3";
auto api = std::make_shared<WebsocketApi>(api_cfg);
api->connect();
api->send_message("session.logon", {}, {.is_signed = true, .is_session_logon = true});
api, "order.place",
{{"symbol", "BNBUSDT"}, {"side", "BUY"}, {"type", "MARKET"}, {"quantity", "0.01"}},
{.is_signed = true}, boost::asio::use_awaitable);
streams_cfg.
url =
"wss://stream.testnet.binance.vision";
streams.connect();
auto trades = streams.create_stream("btcusdt@aggTrade");
trades.on_message([](const boost::json::value& msg) { });
trades.wait_subscribed(std::chrono::seconds(5));
trades.unsubscribe();
streams.disconnect();
static PrivateKey from_file(std::string path)
Definition config.hpp:70
The WebSocket market / user streams transport shared by every product.
Definition websocket_streams.hpp:56
auto async_send(std::shared_ptr< RestClient > client, RestRequest request, CompletionToken &&token)
Asynchronous typed send, completing with void(std::exception_ptr, RestApiResponse<T>).
Definition rest.hpp:125
RestApiResponse< T > send(RestClient &client, RestRequest request)
Blocking typed send, as used by the product clients.
Definition rest.hpp:118
WebSocket API (request / response) configuration.
Definition config.hpp:154
std::optional< std::string > url
wss://… (or ws://…). Set by the product factory when empty.
Definition config.hpp:158
std::optional< PrivateKey > private_key
Definition config.hpp:181
std::optional< std::string > api_key
Definition config.hpp:155
A connection lifecycle event.
Definition websocket_common.hpp:33
WebSocket market / user streams configuration.
Definition config.hpp:197
std::optional< std::string > url
wss://… (or ws://…). Set by the product factory when empty.
Definition config.hpp:199
User-data subscriptions return the response and a stream of their events. The request is sent again after every reconnect and renewal (after the session logon, if any):
auto sub = api->subscribe("userDataStream.subscribe", {});
sub.stream.on_message([](const boost::json::value& event) { });
api, "userDataStream.subscribe", {}, {}, boost::asio::use_awaitable);
auto async_subscribe(std::shared_ptr< WebsocketApi > api, std::string method, Params payload, WebsocketMessageSendOptions options, CompletionToken &&token)
Asynchronous typed subscribe, completing with void(std::exception_ptr, WebsocketApiSubscription<T,...
Definition websocket_api.hpp:261
Some streams (cms, w3w_prediction) are signed: the connection is authenticated with the credentials in the configuration. The product clients pass detail::ClientOptions with signed_streams on (and their User-Agent), which is not part of the configuration.
cfg.
url =
"wss://api.binance.com/sapi/wss";
auto announcements = streams.create_stream("com_announcement_en");
void connect(std::vector< std::string > streams={})
std::optional< std::string > api_key
Definition config.hpp:218
std::optional< std::string > api_secret
Definition config.hpp:219
Every connection signs its own URL, with a fresh timestamp after each reconnect and renewal, and subscribes all its streams with one command once it opens. time_unit and stream ids do not apply.
- mode = WebsocketMode::pool(n) spreads requests or streams over n connections. session.logon / session.logout go to every connection; send_all<T> returns each response.
- Callbacks run on the client's executor unless bound to another, so they should not block. Blocking calls made from it throw; subscribe, unsubscribe and callback changes are safe from anywhere. No callback runs once its handle is unsubscribed or its client is destroyed.
- Stream handles and on_event subscriptions are move-only: destroying one unsubscribes, and release() keeps the callback for the client's lifetime.
- Stream data that arrives before the first callback is added is kept for it.
- Reconnects wait reconnect_delay. After a failed attempt, a backoff of 1 s doubling up to 60 s, with random jitter, is added; the wait is at least the Retry-After of a rejected upgrade. Streams of a connection that closes for good move to another connection of the pool.
Errors
Every error derives from binance::common::Error, which carries the Binance code() (when there is one) and msg().
- REST errors are subclasses of ConnectorError, for example BadRequestError, ConflictError (409), UnauthorizedError, TooManyRequestsError, RateLimitBanError, ServerError or NetworkError. They carry the HTTP response() (headers, rate limits) when there was one.
- RequestTimeoutError (a NetworkError) means the attempt took longer than timeout.
- NetworkError::request_sent() says whether a failed request may have reached Binance. Check it before placing an order again.
- NetworkError::transport_error() and WebsocketNetworkError::transport_error() give the boost::system::error_code behind the failure (boost::asio::error::connection_refused, host_not_found, connection_reset, boost::beast::error::timeout, an SSL error, ...), or an empty code when there is none. A cancelled request reports operation_aborted.
- ConnectorError::retry_after() is the Retry-After delay (in seconds) of a 418 / 429 response; the HTTP-date form is not read. WebsocketResponseError::retry_at() is the time from the retryAfter of a WebSocket API error, which Binance sends as an epoch timestamp.
- WebSocket errors derive from WebsocketError: WebsocketResponseError (Binance code() / msg(), status(), rate_limits(), and data(): the error.data of the answer), WebsocketTimeoutError, WebsocketNoResponseError, WebsocketNotConnectedError, ...
- Invalid configurations throw ConfigError.
- Asynchronous operations deliver errors as a std::exception_ptr.
Configuration
- timeout: how long one attempt of a request may take as a whole (DNS, connect, proxy, TLS, writing the request and reading the response), as in the other Binance connectors; a retry starts a new attempt. A host with several addresses is tried with staggered attempts (the next address after 250 ms or when the previous one fails, the first to connect wins) within that time. retries / backoff (GET and DELETE only) and keep_alive.
- compression and max_response_size.
- proxy: HTTP or HTTPS (Basic auth), or SOCKS5 (ProxyProtocol::Socks5 / Socks5h, with optional username / password), for REST and WebSockets. TLS to the target runs end to end through a tunnel. Socks5 resolves the target's host name in the client; Socks5h has the proxy resolve it. Without proxy, HTTPS_PROXY / HTTP_PROXY / ALL_PROXY / NO_PROXY from the environment are used (http://, https://, socks5:// or socks5h:// values; SOCKS port 1080 by default) when proxy_from_env is set: by default for REST, and not for WebSockets, as in the other Binance connectors.
timestamp_provider (std::function<std::int64_t()>, milliseconds since the epoch; default: the host clock): the timestamp of signed REST requests, signed WebSocket API requests and signed WebSocket streams URLs. It is called for every signed attempt, so each retry, re-logon, reconnect and renewal is signed with a fresh value, and may run on the client's threads (keep it cheap and thread-safe). Use it to compensate a clock that is off against Binance (error -1021):
auto offset_ms = std::make_shared<std::atomic<std::int64_t>>(0);
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()).count() + offset_ms->load();
};
TimestampProvider timestamp_provider
Source of the timestamp of signed requests; empty: the host clock.
Definition config.hpp:217
custom_headers, and agent: a hook to adjust the TLS context of REST and WebSocket connections, e.g. to add a CA or pin certificates:
cfg.
agent = [](boost::asio::ssl::context& ctx) {
ctx.set_verify_callback([](bool preverified, boost::asio::ssl::verify_context& vc) {
auto* store = vc.native_handle();
return preverified && (X509_STORE_CTX_get_error_depth(store) != 0 ||
is_pinned(X509_STORE_CTX_get_current_cert(store)));
});
};
TlsContextHook agent
Definition config.hpp:212
It also presents a client certificate (mutual TLS):
cfg.
agent = [](boost::asio::ssl::context& ctx) {
ctx.use_certificate_chain_file("client.pem");
ctx.use_private_key_file("client.key", boost::asio::ssl::context::pem);
};
- transport (WebSocket): a coroutine that opens the TCP connection itself, e.g. through a tunnel of your own. TLS and the WebSocket upgrade then run over it.
- executor: by default each client runs its own I/O thread. Set it to share one event loop between many clients (cfg.executor = ioc.get_executor();); the loop must keep running while the clients have work, and blocking calls must not be made from its threads.
operator<< on a configuration redacts every secret. The log level is set with Logger::set_level or the LOG_LEVEL environment variable (debug, info, warn, error, none).
Contributing
Contributions are welcome!
- Open a GitHub issue before making changes.
- Discuss proposed changes with maintainers.
- Follow the existing C++ structure.
Disclaimer
This SDK is provided by Binance on an "as is" and "as available" basis for use at your own risk. Binance makes no representations or warranties of any kind, whether express or implied, as to the operation of the SDK, its accuracy, reliability, completeness, or fitness for any particular purpose.
To the fullest extent permitted by law, Binance shall not be liable for any losses, damages, or expenses of any kind arising from or in connection with your use of, or inability to use, this SDK, including but not limited to any financial losses resulting from errors, bugs, interruptions, or inaccuracies in the SDK.
Your use of this SDK to access the Binance Platform is subject to the Binance API Key Terms and the Binance Terms of Use, which shall prevail in the event of any conflict with this disclaimer. You are solely responsible for any orders or transactions executed through the Binance Platform using this SDK.
This SDK is not intended to constitute investment advice or a recommendation to buy, sell, or hold any digital asset. You should independently evaluate and verify all information before acting.
License
This project is licensed under the MIT License - see the LICENCE file for details.