Binance C++ Connector 2.0.0
Official C++ connectors for the Binance APIs
Loading...
Searching...
No Matches
binance::common Namespace Reference

Namespaces

namespace  constants

Classes

struct  ProxyAuth
struct  ProxyConfig
 HTTP(S) or SOCKS5 proxy. More...
class  PrivateKey
 A PEM private key (RSA or Ed25519), given inline or as a file path read on first use. More...
struct  RestApiConfig
struct  WebsocketApiConfig
 WebSocket API (request / response) configuration. More...
struct  WebsocketStreamsConfig
 WebSocket market / user streams configuration. More...
class  Decimal
 Exact decimal number, stored as its canonical plain-notation string. More...
class  Error
 Base class of every error raised by the SDK, so that catch (const common::Error&) handles them all. More...
class  ConnectorError
 Base class of every error raised while sending a REST request. More...
class  ConnectorClientError
 Generic client-side failure: unexpected status, invalid request, malformed response, … More...
class  BadRequestError
 HTTP 400. More...
class  UnauthorizedError
 HTTP 401. More...
class  ForbiddenError
 HTTP 403. More...
class  NotFoundError
 HTTP 404. More...
class  ConflictError
 HTTP 409: the request conflicts with the current state of the resource. More...
class  RateLimitBanError
 HTTP 418: the IP has been auto-banned for continuing to send requests after a 429. More...
class  TooManyRequestsError
 HTTP 429. More...
class  ServerError
 HTTP 5xx. More...
class  NetworkError
 The request never produced an HTTP response (DNS, connect, TLS, timeout, reset, …). More...
class  RequestTimeoutError
 The attempt took longer than timeout. More...
class  RequestCancelledError
 The operation was cancelled through its cancellation slot (e.g. More...
class  ConfigError
 A configuration value is missing or invalid. More...
class  WebsocketError
 Base class of every error raised by the WebSocket clients. More...
class  WebsocketTimeoutError
 No response arrived within timeout, or a connection was not established in time. More...
class  WebsocketProtocolError
 The server broke the WebSocket protocol or sent a malformed message. More...
class  WebsocketHandshakeError
 The WebSocket upgrade was rejected (e.g. HTTP 403 / 429) or failed. More...
class  WebsocketNetworkError
 DNS, TCP, proxy or TLS failure. More...
class  WebsocketNotConnectedError
 There is no open connection to send on. More...
class  WebsocketServerError
 A server-side failure that is not an error response. More...
class  WebsocketNoResponseError
 The connection closed after the request was sent and before its response arrived. More...
class  WebsocketCancelledError
 The operation was cancelled through its cancellation slot or because the client was destroyed. More...
class  WebsocketResponseError
 The server answered with an error (status >= 400), e.g. {"code":-1021,"msg":"..."}. More...
class  Logger
 Process-wide logger. More...
struct  RestApiRateLimit
struct  RawResponse
 An undecoded REST response. More...
class  RestApiResponse
 A successful REST response whose body is decoded into T on first use. More...
class  WebsocketMode
 How many connections a WebSocket client keeps open. More...
struct  WebsocketApiRateLimit
 An entry of a WebSocket API response's rateLimits. More...
struct  WebsocketMessageSendOptions
 How a WebSocket API request is authenticated. More...
struct  WebsocketApiRawResponse
 A successful WebSocket API response, before decoding. More...
class  WebsocketApiResponse
 A successful WebSocket API response whose result is decoded into T on first use. More...
class  Required
 A request parameter that must be set. More...
struct  RestRequest
 One REST call, before signing and serialisation. More...
class  RestClient
 The REST transport shared by every product. More...
class  SignatureGenerator
 Signs request payloads. More...
struct  WebsocketApiRawSubscription
 A user-data subscription: the response to its request, and the stream receiving its events. More...
struct  WebsocketApiSubscription
 A typed user-data subscription: the response decoded as T, events as E. More...
class  WebsocketApi
 The WebSocket API transport (request / response) shared by every product. More...
struct  WebsocketEvent
 A connection lifecycle event. More...
class  Subscription
 A registration made with on_event. More...
class  WebsocketStreamHandle
 One subscribed stream (WebSocket streams) or user-data subscription (WebSocket API), with untyped callbacks. More...
class  WebsocketStream
 A stream whose payloads are decoded into T with boost::json::value_to<T>. More...
class  WebsocketStreams
 The WebSocket market / user streams transport shared by every product. More...

Typedefs

using TlsContextHook = std::function<void(boost::asio::ssl::context&)>
 Customises the TLS context before it is used: add CAs or client certificates, or pin certificates.
using WebsocketTransportHook
 Opens the TCP connection of a WebSocket instead of the SDK: connect socket to host:port (e.g.
using TimestampProvider = std::function<std::int64_t()>
 Source of the timestamp (Unix time in milliseconds) of signed requests, used instead of the host clock.
using Headers = std::map<std::string, std::string>
 Response headers, keyed by lower-cased header name.
using Params = std::map<std::string, boost::json::value>
 Request parameters, sorted by name. null values are skipped when serialised.
using StreamId = std::variant<std::string, std::uint32_t>
 A SUBSCRIBE / UNSUBSCRIBE request id: a 32-character hex string or a number.
using WebsocketEventCallback = std::function<void(const WebsocketEvent&)>
using StreamCallback = std::function<void(const boost::json::value&)>
 Called with a stream's data (WebSocket streams) or a user-data event (WebSocket API).

Enumerations

enum class  ProxyProtocol { Http , Https , Socks5 , Socks5h }
 How the SDK talks to the proxy itself. More...
enum class  LogLevel {
  Debug , Info , Warn , Error ,
  None
}
enum class  TimeUnit { Millisecond , Microsecond }
enum class  RateLimitType { RequestWeight , Orders , RawRequests }
enum class  Interval { Second , Minute , Hour , Day }
enum class  HttpMethod {
  Get , Post , Put , Delete ,
  Patch
}
enum class  WebsocketEventType {
  Open , Message , Error , Close ,
  Ping , Pong
}
enum class  WebsocketConnectionFailureReason {
  NetworkInterruption , ConnectionReset , ServerTemporaryError , UnexpectedClose ,
  StreamEnded , AuthenticationFailure , ProtocolViolation , ConfigurationError ,
  UserInitiatedClose , PermanentServerError , NormalClose
}
 Why a connection ended, and whether it is worth reconnecting. More...

Functions

std::string_view to_string (ProxyProtocol protocol) noexcept
 "http" / "https" / "socks5" / "socks5h".
std::optional< ProxyConfig > proxy_from_environment (bool tls, std::string_view host, std::uint16_t port)
 The proxy configured in the environment for a target host, or nullopt.
std::ostream & operator<< (std::ostream &os, const RestApiConfig &cfg)
 Debug representation with credentials redacted.
std::ostream & operator<< (std::ostream &os, const WebsocketApiConfig &cfg)
std::ostream & operator<< (std::ostream &os, const WebsocketStreamsConfig &cfg)
std::ostream & operator<< (std::ostream &os, const Decimal &d)
void tag_invoke (boost::json::value_from_tag, boost::json::value &jv, const Decimal &d)
 Serialised as a JSON string.
Decimal tag_invoke (boost::json::value_to_tag< Decimal >, const boost::json::value &jv)
 Accepts a JSON string or number.
template<class T>
std::string to_json (const T &value)
 The JSON text of a value of the SDK: a model, a response's data() or rate_limits(), a stream event, a Decimal, or a container of them (anything boost::json::value_from converts), e.g.
constexpr std::string_view to_upper_string (TimeUnit unit) noexcept
constexpr std::string_view to_lower_string (TimeUnit unit) noexcept
std::string_view to_string (RateLimitType type) noexcept
 REQUEST_WEIGHT, ORDERS, RAW_REQUESTS.
std::string_view to_string (Interval interval) noexcept
 SECOND, MINUTE, HOUR, DAY.
void tag_invoke (boost::json::value_from_tag, boost::json::value &jv, const RestApiRateLimit &limit)
 {"rateLimitType", "interval", "intervalNum", "count", "retryAfter"}, for logging.
boost::json::value parse_json (std::string_view text)
 Parses JSON keeping 64-bit integers and long decimals exact.
void tag_invoke (boost::json::value_from_tag, boost::json::value &jv, const WebsocketApiRateLimit &limit)
 {"rateLimitType", "interval", "intervalNum", "limit", "count"}, for logging.
std::string_view to_string (HttpMethod method) noexcept
template<class T>
RestApiResponse< T > send (RestClient &client, RestRequest request)
 Blocking typed send, as used by the product clients.
template<class T, class CompletionToken>
auto async_send (std::shared_ptr< RestClient > client, RestRequest request, CompletionToken &&token)
 Asynchronous typed send, completing with void(std::exception_ptr, RestApiResponse<T>).
template<class T, class E>
WebsocketApiSubscription< T, E > subscribe (WebsocketApi &api, std::string method, Params payload, WebsocketMessageSendOptions options={})
 Blocking typed WebsocketApi::subscribe: the response decoded as T, events as E.
template<class T, class E, class CompletionToken>
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, E>).
template<class T>
WebsocketApiResponse< T > send (WebsocketApi &api, std::string method, Params payload, WebsocketMessageSendOptions options={})
 Blocking typed send of a regular request.
template<class T>
std::vector< WebsocketApiResponse< T > > send_all (WebsocketApi &api, std::string method, Params payload, WebsocketMessageSendOptions options={})
 Blocking typed send of a request answered by every connection (session.logon / session.logout): one response per connection.
template<class T, class CompletionToken>
auto async_send (std::shared_ptr< WebsocketApi > api, std::string method, Params payload, WebsocketMessageSendOptions options, CompletionToken &&token)
 Asynchronous typed send of a regular request, completing with void(std::exception_ptr, WebsocketApiResponse<T>).
template<class T, class CompletionToken>
auto async_send_all (std::shared_ptr< WebsocketApi > api, std::string method, Params payload, WebsocketMessageSendOptions options, CompletionToken &&token)
 Asynchronous send_all, completing with void(std::exception_ptr, std::vector<WebsocketApiResponse<T>>).
std::string_view to_string (WebsocketConnectionFailureReason reason) noexcept

Typedef Documentation

◆ TlsContextHook

using binance::common::TlsContextHook = std::function<void(boost::asio::ssl::context&)>

Customises the TLS context before it is used: add CAs or client certificates, or pin certificates.

Include <boost/asio/ssl/context.hpp> to write one.

◆ WebsocketTransportHook

Initial value:
std::function<boost::asio::awaitable<void>(
boost::asio::ip::tcp::socket& socket, std::string host, std::uint16_t port)>

Opens the TCP connection of a WebSocket instead of the SDK: connect socket to host:port (e.g.

through a proxy of your own), then return. The SDK then runs TLS (with agent) and the WebSocket upgrade over it. proxy is ignored when set. The socket is closed if the hook is still running after connect_timeout.

◆ TimestampProvider

using binance::common::TimestampProvider = std::function<std::int64_t()>

Source of the timestamp (Unix time in milliseconds) of signed requests, used instead of the host clock.

It is called once per signed REST attempt (so each retry is signed with a fresh value), per signed WebSocket API request and per signed WebSocket streams connection URL (reconnects and renewals included), possibly from the client's threads: keep it cheap, non-blocking and thread-safe. Empty: system_clock.

Typical use is compensating a host clock that is skewed against Binance beyond recvWindow (error -1021): measure serverTime - local time and add it from an std::atomic.

◆ Headers

using binance::common::Headers = std::map<std::string, std::string>

Response headers, keyed by lower-cased header name.

◆ Params

using binance::common::Params = std::map<std::string, boost::json::value>

Request parameters, sorted by name. null values are skipped when serialised.

◆ StreamId

using binance::common::StreamId = std::variant<std::string, std::uint32_t>

A SUBSCRIBE / UNSUBSCRIBE request id: a 32-character hex string or a number.

◆ WebsocketEventCallback

using binance::common::WebsocketEventCallback = std::function<void(const WebsocketEvent&)>

◆ StreamCallback

using binance::common::StreamCallback = std::function<void(const boost::json::value&)>

Called with a stream's data (WebSocket streams) or a user-data event (WebSocket API).

Enumeration Type Documentation

◆ ProxyProtocol

enum class binance::common::ProxyProtocol
strong

How the SDK talks to the proxy itself.

Enumerator
Http 
Https 
Socks5 
Socks5h 

◆ LogLevel

enum class binance::common::LogLevel
strong
Enumerator
Debug 
Info 
Warn 
Error 
None 

◆ TimeUnit

enum class binance::common::TimeUnit
strong
Enumerator
Millisecond 
Microsecond 

◆ RateLimitType

enum class binance::common::RateLimitType
strong
Enumerator
RequestWeight 
Orders 
RawRequests 

◆ Interval

enum class binance::common::Interval
strong
Enumerator
Second 
Minute 
Hour 
Day 

◆ HttpMethod

enum class binance::common::HttpMethod
strong
Enumerator
Get 
Post 
Put 
Delete 
Patch 

◆ WebsocketEventType

Enumerator
Open 
Message 
Error 
Close 
Ping 
Pong 

◆ WebsocketConnectionFailureReason

Why a connection ended, and whether it is worth reconnecting.

Enumerator
NetworkInterruption 
ConnectionReset 
ServerTemporaryError 
UnexpectedClose 
StreamEnded 
AuthenticationFailure 
ProtocolViolation 
ConfigurationError 
UserInitiatedClose 
PermanentServerError 
NormalClose 

Function Documentation

◆ to_string() [1/5]

std::string_view binance::common::to_string ( ProxyProtocol protocol)
nodiscardnoexcept

"http" / "https" / "socks5" / "socks5h".

◆ proxy_from_environment()

std::optional< ProxyConfig > binance::common::proxy_from_environment ( bool tls,
std::string_view host,
std::uint16_t port )
nodiscard

The proxy configured in the environment for a target host, or nullopt.

  • Variables: https_proxy / HTTPS_PROXY for TLS targets and http_proxy / HTTP_PROXY otherwise, then all_proxy / ALL_PROXY. Lower case wins. Upper-case HTTP_PROXY is ignored when REQUEST_METHOD is set (CGI, "httpoxy").
  • Values: [http|https|socks5|socks5h://][user:password@]host[:port]. Credentials are percent-decoded. Without a port, 80 (http), 443 (https) or 1080 (socks5, socks5h) is used. Other schemes are ignored with a warning.
  • no_proxy / NO_PROXY is a comma-separated list. * matches everything; example.com and .example.com match the domain and its subdomains; IP literals match exactly. An entry may carry a :port.

◆ operator<<() [1/4]

std::ostream & binance::common::operator<< ( std::ostream & os,
const RestApiConfig & cfg )

Debug representation with credentials redacted.

◆ operator<<() [2/4]

std::ostream & binance::common::operator<< ( std::ostream & os,
const WebsocketApiConfig & cfg )

◆ operator<<() [3/4]

std::ostream & binance::common::operator<< ( std::ostream & os,
const WebsocketStreamsConfig & cfg )

◆ operator<<() [4/4]

std::ostream & binance::common::operator<< ( std::ostream & os,
const Decimal & d )
inline

◆ tag_invoke() [1/4]

void binance::common::tag_invoke ( boost::json::value_from_tag ,
boost::json::value & jv,
const Decimal & d )

Serialised as a JSON string.

◆ tag_invoke() [2/4]

Decimal binance::common::tag_invoke ( boost::json::value_to_tag< Decimal > ,
const boost::json::value & jv )

Accepts a JSON string or number.

A JSON string is converted exactly. A JSON number is exact if it is an integer that fits in 64 bits; any other number is parsed as a double first (see Decimal(double)), so digits beyond double precision are lost (0.12345678901234567890 → "0.12345678901234568"). Binance sends prices and quantities as strings.

◆ to_json()

template<class T>
std::string binance::common::to_json ( const T & value)
nodiscard

The JSON text of a value of the SDK: a model, a response's data() or rate_limits(), a stream event, a Decimal, or a container of them (anything boost::json::value_from converts), e.g.

common::to_json(response.data()). Prices and quantities stay strings, so nothing is rounded.

◆ to_upper_string()

std::string_view binance::common::to_upper_string ( TimeUnit unit)
nodiscardconstexprnoexcept

◆ to_lower_string()

std::string_view binance::common::to_lower_string ( TimeUnit unit)
nodiscardconstexprnoexcept

◆ to_string() [2/5]

std::string_view binance::common::to_string ( RateLimitType type)
nodiscardnoexcept

REQUEST_WEIGHT, ORDERS, RAW_REQUESTS.

◆ to_string() [3/5]

std::string_view binance::common::to_string ( Interval interval)
nodiscardnoexcept

SECOND, MINUTE, HOUR, DAY.

◆ tag_invoke() [3/4]

void binance::common::tag_invoke ( boost::json::value_from_tag ,
boost::json::value & jv,
const RestApiRateLimit & limit )

{"rateLimitType", "interval", "intervalNum", "count", "retryAfter"}, for logging.

◆ parse_json()

boost::json::value binance::common::parse_json ( std::string_view text)
nodiscard

Parses JSON keeping 64-bit integers and long decimals exact.

Throws ConnectorClientError on malformed input.

◆ tag_invoke() [4/4]

void binance::common::tag_invoke ( boost::json::value_from_tag ,
boost::json::value & jv,
const WebsocketApiRateLimit & limit )

{"rateLimitType", "interval", "intervalNum", "limit", "count"}, for logging.

◆ to_string() [4/5]

std::string_view binance::common::to_string ( HttpMethod method)
nodiscardnoexcept

◆ send() [1/2]

template<class T>
RestApiResponse< T > binance::common::send ( RestClient & client,
RestRequest request )

Blocking typed send, as used by the product clients.

◆ async_send() [1/2]

template<class T, class CompletionToken>
auto binance::common::async_send ( std::shared_ptr< RestClient > client,
RestRequest request,
CompletionToken && token )

Asynchronous typed send, completing with void(std::exception_ptr, RestApiResponse<T>).

client is kept alive until the operation completes.

◆ subscribe()

template<class T, class E>
WebsocketApiSubscription< T, E > binance::common::subscribe ( WebsocketApi & api,
std::string method,
Params payload,
WebsocketMessageSendOptions options = {} )

Blocking typed WebsocketApi::subscribe: the response decoded as T, events as E.

◆ async_subscribe()

template<class T, class E, class CompletionToken>
auto binance::common::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, E>).

api is kept alive until it completes.

◆ send() [2/2]

template<class T>
WebsocketApiResponse< T > binance::common::send ( WebsocketApi & api,
std::string method,
Params payload,
WebsocketMessageSendOptions options = {} )

Blocking typed send of a regular request.

◆ send_all()

template<class T>
std::vector< WebsocketApiResponse< T > > binance::common::send_all ( WebsocketApi & api,
std::string method,
Params payload,
WebsocketMessageSendOptions options = {} )

Blocking typed send of a request answered by every connection (session.logon / session.logout): one response per connection.

◆ async_send() [2/2]

template<class T, class CompletionToken>
auto binance::common::async_send ( std::shared_ptr< WebsocketApi > api,
std::string method,
Params payload,
WebsocketMessageSendOptions options,
CompletionToken && token )

Asynchronous typed send of a regular request, completing with void(std::exception_ptr, WebsocketApiResponse<T>).

api is kept alive until it completes.

◆ async_send_all()

template<class T, class CompletionToken>
auto binance::common::async_send_all ( std::shared_ptr< WebsocketApi > api,
std::string method,
Params payload,
WebsocketMessageSendOptions options,
CompletionToken && token )

Asynchronous send_all, completing with void(std::exception_ptr, std::vector<WebsocketApiResponse<T>>).

◆ to_string() [5/5]

std::string_view binance::common::to_string ( WebsocketConnectionFailureReason reason)
nodiscardnoexcept