improvement: Send binance usds fut orders via websocket api

Unlike the previous implementation, which sent REST requests, this won't
block the dispatch thread waiting for a response.
This commit is contained in:
John Colvin committed 2025-04-29 19:32:21 +00:00
1 parent ba525372bb
commit 024480f32e
16 files changed
+746 -222

No files matched your search

@@ -0,0 +1,109 @@
#include "simple_order_key_map.h"
#include "lib/orderman/order_key.h"
#include "lib/utils/Uuid.h"
#include "lib/utils/bts_assert.h"
#include <mutex>
#include <string>
#include <unordered_map>
namespace binance_execution {
const std::string &SimpleOrderKeyMap::get_exch_key(bts::orderman::OrderKey k) {
std::lock_guard<std::mutex> lock{mx};
auto it = key_map.find(k);
bts_assert(it != key_map.end());
return it->second;
}
const std::string &SimpleOrderKeyMap::add_exch_key(bts::orderman::OrderKey k) {
std::lock_guard<std::mutex> lock{mx};
auto [it, is_new] = key_map.try_emplace(k);
bts_assert(is_new);
it->second = bts::utils::uuid();
reverse_key_map[it->second] = k;
return it->second;
}
const std::string &SimpleOrderKeyMap::get_or_add_exch_key(
bts::orderman::OrderKey k) {
std::lock_guard<std::mutex> lock{mx};
auto [it, is_new] = key_map.try_emplace(k);
if (is_new) {
it->second = bts::utils::uuid();
reverse_key_map[it->second] = k;
}
bts_assert(key_map.size() == reverse_key_map.size());
return it->second;
}
bool SimpleOrderKeyMap::try_get_exch_key(
bts::orderman::OrderKey bts_key, std::string &exch_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = key_map.find(bts_key);
if (it == key_map.end()) {
return false;
}
exch_key = it->second;
return true;
}
bool SimpleOrderKeyMap::try_get_exch_key(
bts::orderman::OrderKey bts_key, std::string *&exch_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = key_map.find(bts_key);
if (it == key_map.end()) {
return false;
}
exch_key = &it->second;
return true;
}
std::string *SimpleOrderKeyMap::try_get_exch_key(
bts::orderman::OrderKey bts_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = key_map.find(bts_key);
if (it == key_map.end()) {
return nullptr;
}
return &it->second;
}
bts::orderman::OrderKey SimpleOrderKeyMap::get_bts_key(
const std::string &exch_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = reverse_key_map.find(exch_key);
bts_assert(it != reverse_key_map.end());
return it->second;
}
bool SimpleOrderKeyMap::try_get_bts_key(
const std::string &exch_key, bts::orderman::OrderKey &bts_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = reverse_key_map.find(exch_key);
if (it == reverse_key_map.end()) {
return false;
}
bts_key.value() = it->second.value();
return true;
}
bool SimpleOrderKeyMap::remove(bts::orderman::OrderKey bts_key) {
std::lock_guard<std::mutex> lock{mx};
auto it = key_map.find(bts_key);
if (it == key_map.end()) {
return false;
}
bts_assert(reverse_key_map.erase(it->second) == 1);
key_map.erase(it);
return true;
}
std::size_t SimpleOrderKeyMap::size() {
std::lock_guard<std::mutex> lock{mx};
std::size_t key_map_sz = key_map.size();
bts_assert(reverse_key_map.size() == key_map_sz);
return key_map_sz;
}
} // namespace binance_execution
@@ -0,0 +1,39 @@
#pragma once
#include "lib/orderman/order_key.h"
#include <mutex>
#include <string>
#include <unordered_map>
namespace binance_execution {
/**
* A 1:1 mapping of bts key (uint) to exchange key (string). It is considered
* "Simple" because unique transaction ids aren't required for each modification
* request during an order's life.
*/
class SimpleOrderKeyMap {
std::mutex mx;
std::unordered_map<bts::orderman::OrderKey, std::string> key_map;
std::unordered_map<std::string, bts::orderman::OrderKey> reverse_key_map;
public:
const std::string &get_exch_key(bts::orderman::OrderKey bts_key);
const std::string &add_exch_key(bts::orderman::OrderKey bts_key);
const std::string &get_or_add_exch_key(bts::orderman::OrderKey bts_key);
bool try_get_exch_key(
bts::orderman::OrderKey bts_key, std::string &exch_key);
bool try_get_exch_key(
bts::orderman::OrderKey bts_key, std::string *&exch_key);
std::string *try_get_exch_key(bts::orderman::OrderKey bts_key);
bts::orderman::OrderKey get_bts_key(const std::string &exch_key);
bool try_get_bts_key(
const std::string &exch_key, bts::orderman::OrderKey &bts_key);
bool remove(bts::orderman::OrderKey bts_key);
std::size_t size();
};
} // namespace binance_execution
@@ -1,7 +1,6 @@
#include "logon_request.h"
#include "binance_execution/type_converters.h"
#include "lib/core/TimeStamp.h"
#include "lib/utils/Uuid.h"
#include "lib/utils/crypto/ed25519.h"
#include <nlohmann/json.hpp>
@@ -9,31 +8,22 @@
namespace binance_execution::spots {
LogonRequest LogonRequest::get_new(std::string api_key) {
LogonRequest r;
r.id = bts::utils::uuid();
r.params.apiKey = api_key;
r.params.timestamp = convert_time_stamp(bts::core::TimeStamp::now());
return r;
void LogonRequest::Params::to_signature_params(std::string &payload) const {
payload.append("apiKey=");
payload.append(apiKey);
payload.append("&timestamp=");
payload.append(std::to_string(timestamp));
}
LogonRequest LogonRequest::get_new(
std::string api_key, const std::string &pem_key_path) {
LogonRequest r;
r.id = bts::utils::uuid();
r.params.apiKey = api_key;
r.params.timestamp = convert_time_stamp(bts::core::TimeStamp::now());
if (!pem_key_path.empty()) {
r.sign(pem_key_path);
bool LogonRequest::sign(const std::string &pem_key_path) {
if (params.timestamp == 0) {
params.timestamp = convert_time_stamp(bts::core::TimeStamp::now());
}
return r;
}
void LogonRequest::sign(const std::string &pem_key_path) {
params.signature.clear();
bts::system::crypto::ed25519_digest_b64(
fmt::format("apiKey={}&timestamp={}", params.apiKey, params.timestamp),
pem_key_path, params.signature);
return true;
}
void to_json(nlohmann::json &j, const LogonRequest::Params &p) {
@@ -14,15 +14,12 @@ struct LogonRequest {
std::string apiKey;
std::string signature;
std::int64_t timestamp;
void to_signature_params(std::string &payload) const;
};
Params params;
static LogonRequest get_new(std::string api_key);
static LogonRequest get_new(
std::string api_key, const std::string &pem_key_path);
std::string signature_params() const;
void sign(const std::string &pem_key_path);
bool sign(const std::string &pem_key_path);
};
void to_json(nlohmann::json &j, const LogonRequest &r);
@@ -9,13 +9,15 @@
namespace binance_execution::usds_futures {
bool CancelOrderRequest::init(
const bts::orderman::CancelOrderMsg &m, std::string &error) {
const bts::orderman::CancelOrderMsg &m,
std::string exch_id,
std::string &error) {
const auto orig_error_sz = error.size();
if (validate(m.security, bts::api::VENUE_BINANCE_USDS_FUTURES, error)) {
symbol = m.security->binance_usds_futures().security_desc();
}
orderId = bts::system::math::checked_ultol(m.exchange_order_id.value());
origClientOrderId = std::to_string(m.key.value());
origClientOrderId = std::move(exch_id);
// The exchange accepts either orderId, or origClientOrderId (only one
// need be populated).
if (orderId == 0 && origClientOrderId.empty()) {
@@ -26,4 +28,22 @@ bool CancelOrderRequest::init(
return error.size() == orig_error_sz;
}
void CancelOrderRequest::to_signature_params(std::string &payload) const {
payload.clear();
payload.append("apiKey=");
payload.append(apiKey);
if (orderId != 0) {
payload.append("&orderId=");
payload.append(std::to_string(orderId));
}
if (!origClientOrderId.empty()) {
payload.append("&origClientOrderId=");
payload.append(origClientOrderId);
}
payload.append("&symbol=");
payload.append(symbol);
payload.append("&timestamp=");
payload.append(std::to_string(timestamp));
}
} // namespace binance_execution::usds_futures
@@ -13,12 +13,19 @@ namespace binance_execution::usds_futures {
* @a https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Order
*/
struct CancelOrderRequest {
static constexpr const char *WS_METHOD = "order.cancel";
std::string apiKey;
std::int64_t orderId = 0;
std::string origClientOrderId;
std::string symbol;
std::int64_t timestamp = 0;
std::string signature;
bool init(const bts::orderman::CancelOrderMsg &m, std::string &error);
bool init(
const bts::orderman::CancelOrderMsg &m,
std::string exch_id,
std::string &error);
void to_signature_params(std::string &payload) const;
};
void to_json(nlohmann::json &j, const CancelOrderRequest &req);
@@ -39,6 +46,12 @@ inline void to_json(nlohmann::json &j, const CancelOrderRequest &req) {
j["origClientOrderId"] = req.origClientOrderId;
}
j["timestamp"] = req.timestamp;
if (!req.apiKey.empty()) {
j["apiKey"] = req.apiKey;
}
if (!req.signature.empty()) {
j["signature"] = req.signature;
}
}
inline void from_json(const nlohmann::json &j, CancelOrderRequest &req) {
@@ -52,6 +65,14 @@ inline void from_json(const nlohmann::json &j, CancelOrderRequest &req) {
it->get_to(req.origClientOrderId);
}
j.at("timestamp").get_to(req.timestamp);
it = j.find("apiKey");
if (it != j.end()) {
it->get_to(req.apiKey);
}
it = j.find("signature");
if (it != j.end()) {
it->get_to(req.signature);
}
}
inline void to_query_params(std::string &qps, const CancelOrderRequest &req) {
@@ -1,14 +1,29 @@
#include "create_order_request.h"
#include "binance_execution/price.h"
#include "binance_execution/quantity.h"
#include "binance_execution/type_converters.h"
#include "binance_execution/type_validators.h"
#include "lib/io/JsonReader.h"
#include "lib/orderman/CreateOrderMsg.h"
#include "lib/utils/Uuid.h"
#include "lib/utils/crypto/hmac.h"
#include <nlohmann/json.hpp>
namespace binance_execution::usds_futures {
using std::string;
bool CreateOrderRequest::init(
const bts::orderman::CreateOrderMsg &m, std::string &error) {
const bts::orderman::CreateOrderMsg &m, string &error) {
return init(m, bts::utils::uuid(), error);
}
bool CreateOrderRequest::init(
const bts::orderman::CreateOrderMsg &m,
std::string exch_id,
string &error) {
const auto orig_error_sz = error.size();
newClientOrderId = std::to_string(m.key.value());
if (validate(m.security, bts::api::VENUE_BINANCE_USDS_FUTURES, error)) {
symbol = m.security->binance_usds_futures().security_desc();
}
@@ -17,11 +32,152 @@ bool CreateOrderRequest::init(
quantity = m.quantity.full_value();
type = convert_order_type(m.order_type);
timeInForce = convert_time_in_force(m.time_in_force);
newClientOrderId = std::move(exch_id);
if (error.size() != orig_error_sz) {
return false;
}
timestamp = convert_time_stamp(bts::core::TimeStamp::now());
return true;
}
bool CreateOrderRequest::sign(const string &secret_key) {
signature.clear();
if (timestamp == 0) {
timestamp = convert_time_stamp(bts::core::TimeStamp::now());
}
string sig_params;
to_signature_params(sig_params);
if (!bts::system::crypto::hmac_digest_hex(
secret_key, sig_params, signature)) {
LOG(OrderMan, bts::Error, "Failed to sign request. {}", sig_params);
return false;
}
return true;
}
void CreateOrderRequest::to_signature_params(std::string &payload) const {
payload.clear();
payload.append("apiKey=");
payload.append(apiKey);
if (!newClientOrderId.empty()) {
payload.append("&newClientOrderId=");
payload.append(newClientOrderId);
}
if (positionSide != PositionSide::NONE) {
payload.append("&positionSide=");
payload.append(positionSide.name());
}
// Format price & qty with 4 decimal places (should be sufficient the contracts we support)
if (!std::isnan(price)) {
payload.append("&price=");
price_to_string(price, payload);
}
if (quantity > 0) {
payload.append("&quantity=");
quantity_to_string(quantity, payload);
}
if (recvWindow > 0) {
payload.append("&recvWindow=");
payload.append(std::to_string(recvWindow));
}
payload.append("&side=");
payload.append(side.name());
payload.append("&symbol=");
payload.append(symbol);
if (timeInForce != TimeInForce::NONE) {
payload.append("&timeInForce=");
payload.append(timeInForce.name());
}
payload.append("&timestamp=");
payload.append(std::to_string(timestamp));
payload.append("&type=");
payload.append(type.name());
}
void to_json(nlohmann::json &j, const CreateOrderRequest &req) {
if (!req.apiKey.empty()) {
j["apiKey"] = req.apiKey;
}
j["symbol"] = req.symbol;
j["side"] = req.side;
j["type"] = req.type;
j["timestamp"] = req.timestamp;
if (!req.newClientOrderId.empty()) {
j["newClientOrderId"] = req.newClientOrderId;
}
if (req.positionSide != PositionSide::NONE) {
j["positionSide"] = req.positionSide;
}
if (!std::isnan(req.price)) {
std::string price_str;
price_to_string(req.price, price_str);
j["price"] = price_str;
}
if (req.quantity > 0) {
std::string qty_str;
quantity_to_string(req.quantity, qty_str);
j["quantity"] = qty_str;
}
if (req.timeInForce != TimeInForce::NONE) {
j["timeInForce"] = req.timeInForce;
}
if (req.recvWindow > 0) {
j["recvWindow"] = std::to_string(req.recvWindow);
}
if (!req.signature.empty()) {
j["signature"] = req.signature;
}
}
void from_json(const nlohmann::json &j, CreateOrderRequest &req) {
j.at("symbol").get_to(req.symbol);
j.at("side").get_to(req.side);
j.at("type").get_to(req.type);
j.at("timestamp").get_to(req.timestamp);
j.at("newClientOrderId").get_to(req.newClientOrderId);
bts::io::JsonReader jr{&j};
jr.read("price", req.price);
jr.read("positionSide", req.positionSide);
jr.read("quantity", req.quantity);
jr.read("timeInForce", req.timeInForce);
jr.read("recvWindow", req.recvWindow);
jr.read("apiKey", req.apiKey);
jr.read("signature", req.signature);
}
void to_query_params(std::string &qps, const CreateOrderRequest &req) {
qps.append("symbol=");
qps.append(req.symbol);
qps.append("&side=");
qps.append(req.side.name());
qps.append("&type=");
qps.append(req.type.name());
qps.append("&timestamp=");
qps.append(std::to_string(req.timestamp));
if (!req.newClientOrderId.empty()) {
qps.append("&newClientOrderId=");
qps.append(req.newClientOrderId);
}
// Format price & qty with 4 decimal places (should be sufficient the contracts we support)
if (!std::isnan(req.price)) {
qps.append("&price=");
price_to_string(req.price, qps);
}
if (req.quantity > 0) {
qps.append("&quantity=");
quantity_to_string(req.quantity, qps);
}
if (req.timeInForce != TimeInForce::NONE) {
qps.append("&timeInForce=");
qps.append(req.timeInForce.name());
}
if (req.recvWindow > 0) {
qps.append("&recvWindow=");
qps.append(std::to_string(req.recvWindow));
}
if (!req.signature.empty()) {
qps.append("&signature=");
qps.append(req.signature);
}
}
} // namespace binance_execution::usds_futures
@@ -1,12 +1,11 @@
#pragma once
#include "binance_execution/enums/order_type.h"
#include "binance_execution/enums/position_side.h"
#include "binance_execution/enums/side.h"
#include "binance_execution/enums/time_in_force.h"
#include "binance_execution/price.h"
#include "binance_execution/quantity.h"
#include <nlohmann/json.hpp>
#include <nlohmann/json_fwd.hpp>
#include <string>
namespace bts::orderman {
@@ -19,108 +18,35 @@ namespace binance_execution::usds_futures {
* @a https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api
*/
struct CreateOrderRequest {
static constexpr const char *WS_METHOD = "order.place";
std::string symbol;
Side side = Side::NONE;
OrderType type = OrderType::NONE;
std::int64_t timestamp = 0;
std::string newClientOrderId;
PositionSide positionSide = PositionSide::BOTH;
double price = std::numeric_limits<double>::quiet_NaN();
double quantity = 0;
TimeInForce timeInForce = TimeInForce::NONE;
std::int64_t recvWindow = 0;
std::string apiKey;
std::string signature;
bool init(const bts::orderman::CreateOrderMsg &m, std::string &error);
bool init(
const bts::orderman::CreateOrderMsg &m,
std::string exch_id,
std::string &error);
bool sign(const std::string &secret_key);
void to_signature_params(std::string &payload) const;
};
void to_json(nlohmann::json &j, const CreateOrderRequest &req);
void from_json(const nlohmann::json &j, CreateOrderRequest &req);
void to_query_params(std::string &query_params, const CreateOrderRequest &req);
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
inline void to_json(nlohmann::json &j, const CreateOrderRequest &req) {
j["symbol"] = req.symbol;
j["side"] = req.side;
j["type"] = req.type;
j["timestamp"] = req.timestamp;
if (!req.newClientOrderId.empty()) {
j["newClientOrderId"] = req.newClientOrderId;
}
if (!std::isnan(req.price)) {
std::string price_str;
price_to_string(req.price, price_str);
j["price"] = price_str;
}
if (req.quantity > 0) {
std::string qty_str;
quantity_to_string(req.quantity, qty_str);
j["quantity"] = qty_str;
}
if (req.timeInForce != TimeInForce::NONE) {
j["timeInForce"] = req.timeInForce;
}
if (req.recvWindow > 0) {
j["recvWindow"] = std::to_string(req.recvWindow);
}
}
inline void from_json(const nlohmann::json &j, CreateOrderRequest &req) {
j.at("symbol").get_to(req.symbol);
j.at("side").get_to(req.side);
j.at("type").get_to(req.type);
j.at("timestamp").get_to(req.timestamp);
j.at("newClientOrderId").get_to(req.newClientOrderId);
auto it = j.find("price");
if (it != j.end()) {
it->get_to(req.price);
}
it = j.find("quantity");
if (it != j.end()) {
it->get_to(req.quantity);
}
it = j.find("timeInForce");
if (it != j.end()) {
it->get_to(req.timeInForce);
}
it = j.find("recvWindow");
if (it != j.end()) {
it->get_to(req.recvWindow);
}
}
inline void to_query_params(std::string &qps, const CreateOrderRequest &req) {
qps.append("symbol=");
qps.append(req.symbol);
qps.append("&side=");
qps.append(req.side.name());
qps.append("&type=");
qps.append(req.type.name());
qps.append("&timestamp=");
qps.append(std::to_string(req.timestamp));
if (!req.newClientOrderId.empty()) {
qps.append("&newClientOrderId=");
qps.append(req.newClientOrderId);
}
// Format price & qty with 4 decimal places (should be sufficient the contracts we support)
if (!std::isnan(req.price)) {
qps.append("&price=");
price_to_string(req.price, qps);
}
if (req.quantity > 0) {
qps.append("&quantity=");
quantity_to_string(req.quantity, qps);
}
if (req.timeInForce != TimeInForce::NONE) {
qps.append("&timeInForce=");
qps.append(req.timeInForce.name());
}
if (req.recvWindow > 0) {
qps.append("&recvWindow=");
qps.append(std::to_string(req.recvWindow));
}
}
void to_signatory_params(
std::string &signatory_params, const CreateOrderRequest &req);
} // namespace binance_execution::usds_futures
@@ -7,7 +7,9 @@
namespace binance_execution::usds_futures {
bool ModifyOrderRequest::init(
const bts::orderman::CancelReplaceOrderMsg &m, std::string &error) {
const bts::orderman::CancelReplaceOrderMsg &m,
std::string exch_id,
std::string &error) {
const auto orig_error_sz = error.size();
const auto &cf = m.create_fields;
if (cf.security == nullptr) {
@@ -18,7 +20,7 @@ bool ModifyOrderRequest::init(
symbol = cf.security->binance_usds_futures().security_desc();
}
orderId = bts::system::math::checked_ultol(m.exchange_order_id.value());
origClientOrderId = std::to_string(cf.key.value());
origClientOrderId = std::move(exch_id);
// The exchange accepts either orderId, or origClientOrderId (only one
// need be populated).
if (orderId == 0 && origClientOrderId.empty()) {
@@ -34,4 +36,32 @@ bool ModifyOrderRequest::init(
return error.size() == orig_error_sz;
}
void ModifyOrderRequest::to_signature_params(std::string &payload) const {
payload.clear();
payload.append("apiKey=");
payload.append(apiKey);
if (orderId != 0) {
payload.append("&orderId=");
payload.append(std::to_string(orderId));
}
if (!origClientOrderId.empty()) {
payload.append("&origClientOrderId=");
payload.append(origClientOrderId);
}
payload.append("&price=");
price_to_string(price, payload);
payload.append("&quantity=");
quantity_to_string(quantity, payload);
if (recvWindow > 0) {
payload.append("&recvWindow=");
payload.append(std::to_string(recvWindow));
}
payload.append("&side=");
payload.append(side.name());
payload.append("&symbol=");
payload.append(symbol);
payload.append("&timestamp=");
payload.append(std::to_string(timestamp));
}
} // namespace binance_execution::usds_futures
@@ -18,6 +18,8 @@ namespace binance_execution::usds_futures {
* @a https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Order
*/
struct ModifyOrderRequest {
static constexpr const char *WS_METHOD = "order.modify";
std::string apiKey;
std::int64_t orderId = 0; // *optional
std::string origClientOrderId; // *optional
std::string symbol; // mandatory
@@ -27,9 +29,15 @@ struct ModifyOrderRequest {
PriceMatchMode priceMatch = PriceMatchMode::NONE; // optional
std::int64_t recvWindow = 0; // optional
std::int64_t timestamp = 0; // mandatory
std::string signature;
// * Either orderId or origClientOrderId must be specified
bool init(const bts::orderman::CancelReplaceOrderMsg &m, std::string &error);
bool init(
const bts::orderman::CancelReplaceOrderMsg &m,
std::string exch_id,
std::string &error);
bool sign(const std::string &secret_key);
void to_signature_params(std::string &payload) const;
};
void to_json(nlohmann::json &j, const ModifyOrderRequest &req);
@@ -42,6 +50,9 @@ void to_query_params(std::string &query_params, const ModifyOrderRequest &req);
//////////////////////////////////////////////////
inline void to_json(nlohmann::json &j, const ModifyOrderRequest &req) {
if (!req.apiKey.empty()) {
j["apiKey"] = req.apiKey;
}
if (req.orderId != 0) {
j["orderId"] = req.orderId;
}
@@ -50,8 +61,16 @@ inline void to_json(nlohmann::json &j, const ModifyOrderRequest &req) {
}
j["symbol"] = req.symbol;
j["side"] = req.side;
j["quantity"] = req.quantity;
j["price"] = req.price;
if (!std::isnan(req.price)) {
std::string price_str;
price_to_string(req.price, price_str);
j["price"] = price_str;
}
if (req.quantity > 0) {
std::string qty_str;
quantity_to_string(req.quantity, qty_str);
j["quantity"] = qty_str;
}
if (req.priceMatch != PriceMatchMode::NONE) {
j["priceMatch"] = req.price;
}
@@ -59,6 +78,9 @@ inline void to_json(nlohmann::json &j, const ModifyOrderRequest &req) {
j["recvWindow"] = req.recvWindow;
}
j["timestamp"] = req.timestamp;
if (!req.signature.empty()) {
j["signature"] = req.signature;
}
}
inline void from_json(const nlohmann::json &j, ModifyOrderRequest &req) {
@@ -66,6 +88,10 @@ inline void from_json(const nlohmann::json &j, ModifyOrderRequest &req) {
if (it != j.end()) {
it->get_to(req.orderId);
}
it = j.find("apiKey");
if (it != j.end()) {
it->get_to(req.apiKey);
}
it = j.find("origClientOrderId");
if (it != j.end()) {
it->get_to(req.origClientOrderId);
@@ -3,20 +3,23 @@
#include "binance_execution/execution_report_store.h"
#include "binance_execution/gateway_config.h"
#include "binance_execution/listen_key_requestor.h"
#include "binance_execution/rest_api_result.h"
#include "binance_execution/simple_order_key_map.h"
#include "binance_execution/type_validators.h"
#include "binance_execution/usds_futures/messages/create_order_request.h"
#include "binance_execution/usds_futures/messages/modify_order_request.h"
#include "binance_execution/usds_futures/rest_api_client.h"
#include "binance_execution/usds_futures/user_data_stream/user_data_subscription.h"
#include "binance_execution/websocket_api_request.h"
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include "lib/api/services/AdminService.pb.h"
#include "lib/api/services/OrderService.h"
#include "lib/collections/concurrent_queue.h"
#include "lib/config/protos/jetfix.pb.h"
#include "lib/domain_model/Security.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/domain_model/Side.h"
#include "lib/io/json_formatter.h"
#include "lib/io/websocket/websocket_client.h"
#include "lib/logging/logging.h"
#include "lib/md/SecurityOracle.h"
#include "lib/mercury/events/Update.h"
@@ -26,36 +29,47 @@
#include "lib/orderman/RFQMsg.h"
#include "lib/orderman/events/NewAdminDataEvent.h"
#include "lib/orderman/events/NewSecuritiesEvent.h"
#include "lib/orderman/log_messages/cancel_order_log.h"
#include "lib/orderman/log_messages/create_order_log.h"
#include "lib/orderman/log_messages/execution_report_log.h"
#include "lib/orderman/log_messages/modify_order_log.h"
#include "lib/orderman/orderman_utils/ExchangePosition.h"
#include "lib/orderman/orderman_utils/ExecutionReport.h"
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/utils/checked_arithmetic.h"
#include "lib/utils/Uuid.h"
#include "lib/utils/bts_lock_guard.h"
#include "lib/utils/overloaded.h"
#include "lib/utils/string_utils.h"
#include "lib/utils/thread_manager.h"
#include <boost/lockfree/spsc_queue.hpp>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <string>
#include <variant>
#include <vector>
using nlohmann::json;
namespace binance_execution::usds_futures {
#define ASSERT_FN(test, fn, ...) \
bts_assert_msgf(test, "BinanceUsdsFutures::" fn ". " __VA_ARGS__)
#define LOG_FN(level, fn, ...) \
LOG(OrderMan, level, "BinanceUsdsFutures::" fn ". " __VA_ARGS__)
#define DIAG_FN(fn, ...) LOG_FN(bts::Diag, fn, __VA_ARGS__)
#define INFO_FN(fn, ...) LOG_FN(bts::Info, fn, __VA_ARGS__)
#define WARN_FN(fn, ...) LOG_FN(bts::Warn, fn, __VA_ARGS__)
#define ERROR_FN(fn, ...) LOG_FN(bts::Error, fn, __VA_ARGS__)
#define _LOG(level, ...) LOG(OrderMan, level, __VA_ARGS__)
#define INFO(...) _LOG(bts::Info, __VA_ARGS__)
#define ERROR(...) _LOG(bts::Error, __VA_ARGS__)
#define VENUE bts::api::VENUE_BINANCE_USDS_FUTURES
using boost::lockfree::spsc_queue;
using binance_execution::usds_futures::user_data_stream::AccountUpdate;
using binance_execution::usds_futures::user_data_stream::OrderUpdate;
using bts::collections::ConcurrentQueue;
using bts::core::Delegate;
using bts::core::TimeSpan;
using bts::core::TimeStamp;
using bts::io::json_formatter;
using bts::orderman::CancelOrderMsg;
using bts::orderman::CancelReplaceOrderMsg;
@@ -66,20 +80,20 @@ using bts::orderman::NewSecuritiesEvent;
using bts::orderman::OrderKey;
using bts::orderman::OrderMsg;
using bts::orderman::RFQMsg;
using bts::threading::configure_current_thread;
using bts::websocket::WebsocketClient;
using bts::websocket::WebsocketClientConfig;
using nlohmann::json;
using std::exception;
using std::int64_t;
using std::optional;
using std::shared_ptr;
using std::size_t;
using std::string;
using std::thread;
using std::uint32_t;
using std::vector;
static OrderKey get_bts_key(const std::string &exch_key) {
std::uint32_t k;
bts::system::string_utils::parse_uint(exch_key, k);
return OrderKey{k};
}
struct ExecutionGatewayCallbacks {
bts::orderman::OnExeReport exe_report;
bts::orderman::OnGwStatusChange gw_status_change;
@@ -116,41 +130,91 @@ struct UsdsFuturesGateway::PImpl {
bts::md::SecurityOracle sec_oracle;
GatewayConfig config;
std::shared_ptr<bts::config::JetFIX_Connection> jetfix_connection;
optional<WebsocketClient> ws_client;
optional<thread> ws_run_thread;
RestApiClient rest_api_client;
optional<user_data_stream::UserDataSubscription> user_data_sub;
Delegate<void(user_data_stream::AccountUpdate)> account_update_callback;
Delegate<void(user_data_stream::OrderUpdate)> order_update_callback;
ListenKeyRequestor listen_key_requestor;
SimpleOrderKeyMap key_map;
spsc_queue<user_data_stream::AccountUpdate> incoming_account_updates{1024};
spsc_queue<user_data_stream::OrderUpdate> incoming_order_updates{1024};
spsc_queue<shared_ptr<const ExecutionReport>> internal_order_rejects{256};
vector<user_data_stream::AccountUpdate> account_updates_vec;
std::mutex instance_mx;
ConcurrentQueue<AccountUpdate> incoming_account_updates;
ConcurrentQueue<OrderUpdate> incoming_order_updates;
ConcurrentQueue<shared_ptr<const ExecutionReport>> internal_order_rejects;
vector<AccountUpdate> account_updates_vec;
ExecutionReportStore orders;
ExecutionGatewayCallbacks callbacks;
bts::orderman::ExchangePosition pos;
bts::api::admin::BTSAccount account;
template <WebsocketApiRequestParams T>
WebsocketApiRequest<T> build_request(T &&params) {
params.apiKey = config.api_key;
WebsocketApiRequest<T> req;
req.params = std::move(params);
req.id = bts::utils::uuid();
req.sign(config.secret_key);
return req;
}
bool is_ready() {
BTS_LOCK_GUARD(instance_mx);
return ws_client && ws_client->is_connected() && user_data_sub &&
user_data_sub->is_ready();
}
void start() {
INFO_FN("start");
listen_key_requestor.callback().bind<&PImpl::on_listen_key_>(*this);
listen_key_requestor.start();
// Init websocket
WebsocketClientConfig ws_stream_client_cfg;
const std::string &url = config.ws_endpoint;
ws_stream_client_cfg.url = url;
ws_stream_client_cfg.name = "BinanceUsdsFutures";
auto &ws_cli = ws_client.emplace(ws_stream_client_cfg);
ws_cli.open_handler().bind<&PImpl::on_open>(*this);
ws_cli.message_handler().bind<&PImpl::on_message>(*this);
ws_cli.close_handler().bind<&PImpl::on_close>(*this);
INFO_FN("start", "Creating websocket client. url: {}", url);
ws_cli.connect();
ws_run_thread.emplace([&]() {
configure_current_thread("binance_ufuts_gw_ws");
DIAG_FN("binance_ufuts_exe_ws", "Begin. url: {}", url);
ws_cli.run();
DIAG_FN("binance_ufuts_exe_ws", "End. url: {}", url);
});
}
void on_open(const std::error_code &ec) {
INFO_FN("on_open");
bts_assert_msgf(!ec, "Websocket opened with error. {}", ec.message());
ws_client->ping_continuously(25);
}
void on_close(const std::error_code &ec) {
ERROR_FN("on_close", "Websocket closed. err: {}", ec.message());
}
void stop() {
INFO_FN("stop");
INFO_FN("stop", "Disconnecting user data stream websocket...");
user_data_sub.reset();
INFO_FN("stop", "Disconnecting trade websocket...");
ws_client->disconnect();
ws_client.reset();
}
void on_account_update(user_data_stream::AccountUpdate u) {
INFO_FN("on_account_update", "\n{:2}", json_formatter(u));
INFO(R"([binance_ufuts_account_upd.json]{})", json_formatter(u));
incoming_account_updates.push(std::move(u));
}
void on_order_update(user_data_stream::OrderUpdate u) {
INFO_FN("on_order_update", "\n{:2}", json_formatter(u));
INFO(R"([binance_ufuts_order_upd.json]{})", json_formatter(u));
incoming_order_updates.push(std::move(u));
}
@@ -170,84 +234,106 @@ struct UsdsFuturesGateway::PImpl {
uds.start();
}
void create_order(const CreateOrderMsg &m) {
CreateOrderRequest req;
std::string err;
if (!req.init(m, err)) {
void on_order_ack(const json &msg) {
BTS_LOCK_GUARD(instance_mx);
INFO(R"([binance_ufuts_order_ack.json]{})", msg.dump());
auto id_it = msg.find("id");
bts_assert_msgf(
id_it != msg.end(), "Received order ack without id. {}", msg.dump());
string id;
id_it->get_to(id);
}
void on_message(const string &msg_str) {
// All messages are responses to specific requests (no push notifications).
// Each response has an id that matches that of the associated request.
// Find the response handler with that id, invoke it, then destroy it.
DIAG_FN("on_message", "{}", msg_str);
// Convert to nlohmann::json
json msg;
try {
msg = json::parse(msg_str);
} catch (const exception &ex) {
ERROR_FN(
"create_order",
"{} {} {} @ {} (id={}, type={}, tif={}). Rejected "
"internally (request not sent). {}",
m.side, m.quantity, req.symbol, m.price, m.key, m.order_type,
m.time_in_force, err);
internal_order_rejects.push(orders.reject(m, err));
"on_message", "Failed to parse response json: {}.\n{}",
string{ex.what()}, msg_str);
return;
}
INFO_FN(
"create_order",
"{} {} {} @ {} (id={}, type={}, tif={}). Sending request", m.side,
m.quantity, req.symbol, m.price, m.key, m.order_type,
m.time_in_force);
const auto res = rest_api_client.create_order(req);
if (!res.ok()) {
ERROR_FN("create_order", "id={}. {}", m.key, json_formatter(res));
internal_order_rejects.push(
orders.reject(m, json_formatter(*res.error).to_string()));
auto id_it = msg.find("id");
if (id_it != msg.end()) {
try {
on_order_ack(msg);
} catch (const exception &ex) {
ERROR_FN(
"on_message", "message handler threw. msg: {}; ex: {}", msg_str,
string{ex.what()});
}
}
}
void create_order(const CreateOrderMsg &m) {
if (!is_ready()) {
LOG_CREATE_ORDER(Error, m, "REJECTED_BEFORE_SEND");
internal_order_rejects.push(orders.reject(m, "Gateway not ready"));
return;
}
CreateOrderRequest params;
std::string err;
const std::string &exch_key = key_map.add_exch_key(m.key);
if (!params.init(m, exch_key, err)) {
LOG_CREATE_ORDER(Error, m, "REJECTED_BEFORE_SEND");
internal_order_rejects.push(orders.reject(m, err));
key_map.remove(m.key);
return;
}
LOG_CREATE_ORDER(Info, m, "ABOUT_TO_SEND");
const auto req = build_request(std::move(params));
const auto ec = ws_client->send_text(req.to_string());
if (ec) {
LOG_CREATE_ORDER(Error, m, "WS_ERROR", ec.message());
key_map.remove(m.key);
}
}
void update_order(const CancelReplaceOrderMsg &m) {
const auto &fields = m.create_fields;
std::string err;
ModifyOrderRequest req;
if (!req.init(m, err)) {
ERROR_FN(
"update_order",
"{} {} {} @ {} (id={}, exch_id={}, type={}, tif={}). Rejected "
"internally (request not sent). {}",
fields.side, fields.quantity, req.symbol, fields.price, fields.key,
m.exchange_order_id, fields.order_type, fields.time_in_force, err);
internal_order_rejects.push(orders.set_error(
fields.key,
"Update rejected internally (request not sent). " + err));
string *exch_key;
if (!key_map.try_get_exch_key(m.create_fields.key, exch_key)) {
LOG_MODIFY_ORDER(
Error, m, "REJECTED_BEFORE_SEND", "Didn't find exch key");
return;
}
INFO_FN(
"update_order",
"{} {} {} @ {} (id={}, type={}, tif={}). Sending request",
fields.side, fields.quantity, req.symbol, fields.price, fields.key,
m.exchange_order_id, fields.order_type, fields.time_in_force);
const auto res = rest_api_client.modify_order(req);
if (!res.ok()) {
ERROR_FN(
"update_order", "id={}, exch_id={}. {}", fields.key,
m.exchange_order_id, json_formatter(res));
ModifyOrderRequest params;
string err;
if (!params.init(m, *exch_key, err)) {
LOG_MODIFY_ORDER(Error, m, "REJECTED_BEFORE_SEND", err);
return;
}
LOG_MODIFY_ORDER(Info, m, "ABOUT_TO_SEND");
const auto req = build_request(std::move(params));
const auto ec = ws_client->send_text(req.to_string());
if (ec) {
LOG_MODIFY_ORDER(Error, m, "WS_ERROR", ec.message());
}
}
void cancel_order(const CancelOrderMsg &m) {
CancelOrderRequest req;
string err;
if (!req.init(m, err)) {
ERROR_FN(
"cancel_order", "{} {} (id={}, exch_id={}). {}", m.side,
req.symbol, m.key, m.exchange_order_id, err);
internal_order_rejects.push(orders.set_error(
m.key, "Rejected internally (request not sent). " + err));
string *exch_key;
if (!key_map.try_get_exch_key(m.key, exch_key)) {
LOG_CANCEL_ORDER(
Error, m, "REJECTED_BEFORE_SEND", "Didn't find exch key");
return;
}
INFO_FN(
"cancel_order", "{} {} (id={}, exch_id={})", m.side, req.symbol,
m.key, m.exchange_order_id);
const auto res = rest_api_client.cancel_order(req);
if (!res.ok()) {
ERROR_FN(
"cancel_order", "{} {} (id={}, exch_id={}). {}", m.side,
req.symbol, m.key, m.exchange_order_id, json_formatter(res));
internal_order_rejects.push(orders.set_error(
m.key,
fmt::format(
"Cancel request failed. {}", json_formatter(*res.error))));
CancelOrderRequest params;
string err;
if (!params.init(m, *exch_key, err)) {
LOG_CANCEL_ORDER(Error, m, "REJECTED_BEFORE_SEND", err);
return;
}
LOG_CANCEL_ORDER(Info, m, "ABOUT_TO_SEND");
const auto req = build_request(std::move(params));
const auto ec = ws_client->send_text(req.to_string());
if (ec) {
LOG_CANCEL_ORDER(Error, m, "WS_ERROR", ec.message());
}
}
@@ -260,12 +346,20 @@ struct UsdsFuturesGateway::PImpl {
}
void dispatch_order_updates() {
if (incoming_order_updates.empty()) {
return;
}
uint32_t n_dequed = 0;
uint32_t n_unknown = 0;
uint32_t n_invalid = 0;
user_data_stream::OrderUpdate u;
while (incoming_order_updates.pop(u)) {
const auto key = get_bts_key(u.data.client_order_id);
n_dequed++;
OrderKey key;
if (!key_map.try_get_bts_key(u.data.client_order_id, key)) {
WARN_FN(
"dispatch_order_updates", "Update has unknown exch id. {}",
json_formatter(u));
n_unknown++;
continue;
}
shared_ptr<const ExecutionReport> er_p =
orders.update(key, [&](auto &er_p, bool) {
auto &er = *er_p;
@@ -273,28 +367,30 @@ struct UsdsFuturesGateway::PImpl {
WARN_FN(
"update", "Failed to initialize exe report. {}",
json_formatter(u));
n_invalid++;
return;
}
er.order_key = key;
er.security = sec_oracle.get_security(
VENUE, bts::api::SECURITYTYPE_FUTURE, u.data.symbol);
});
const ExecutionReport &er = *er_p;
string error;
if (!validate(er, error)) {
ERROR_FN(
"dispatch_order_updates",
"Generated invalid ExecutionReport. {}", error);
LOG_EXECUTION_REPORT(Error, er_p, "INVALID_STATE", error);
continue;
}
LOG_EXECUTION_REPORT(Info, er_p);
switch (u.data.order_status.value) {
case OrderStatus::FILLED:
case OrderStatus::CANCELED:
case OrderStatus::REJECTED: {
std::size_t n_active = orders.erase(er.order_key);
orders.erase(er.order_key);
key_map.remove(er.order_key);
INFO_FN(
"dispatch_order_updates",
"Order reached terminal state {} (id={}). {} active orders.",
u.data.order_status, u.data.client_order_id, n_active);
"Order reached terminal state {} (id={})", u.data.order_status,
u.data.client_order_id);
break;
}
default:
@@ -309,6 +405,13 @@ struct UsdsFuturesGateway::PImpl {
er.quantity, er.order_key, orders.size());
callbacks.exe_report(er_p, {});
}
if (n_dequed > 0) {
_LOG(
(n_unknown > 0 || n_invalid > 0 ? bts::Warn : bts::Info),
R"([binance_ufuts_order_stats.json]{{ "n_active": {}, "n_keys": {}, "n_dequed": {}, "n_unknown": {}, "ts": {} }})",
orders.size(), key_map.size(), n_dequed, n_unknown,
TimeStamp::now_ns());
}
}
void dispatch_account_updates() {
@@ -1,6 +1,5 @@
#include "order_update.h"
#include "binance_execution/type_converters.h"
#include "lib/config/protos/jetfix.pb.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/io/JsonReader.h"
#include "lib/orderman/orderman_utils/ExecutionReport.h"
@@ -11,16 +10,12 @@ namespace binance_execution::usds_futures::user_data_stream {
using bts::system::math::checked_ltoul;
using bts::system::string_utils::copy_to_array;
using bts::system::string_utils::parse_uint;
bool OrderUpdate::to_execution_report(
bts::orderman::ExecutionReport &er) const {
er.exchange = bts::api::VENUE_BINANCE_USDS_FUTURES;
er.transact_time = bts::orderman::ExchangeTimeStamp64{
convert_time_stamp(transaction_time).nanos()};
if (!parse_uint(data.client_order_id, er.order_key.value())) {
return false;
}
bts_assert(checked_ltoul(
data.order_id,
er.exchange_order_id.emplace<bts::orderman::ExchangeOrderID64>()
@@ -153,6 +153,10 @@ void UserDataSubscription::start() {
me_->start();
}
bool UserDataSubscription::is_ready() const {
return me_->ws_client && me_->ws_client->is_connected();
}
void UserDataSubscription::stop() {
INFO_FN("stop");
me_->stop();
@@ -18,6 +18,7 @@ class UserDataSubscription {
~UserDataSubscription();
void start();
bool is_ready() const;
void stop();
bts::core::Delegate<void(AccountUpdate)> &account_update_callback();
bts::core::Delegate<void(OrderUpdate)> &order_update_callback();
@@ -0,0 +1,63 @@
#include "websocket_api_request.h"
#include "binance_execution/spots/messages/cancel_order_request.h"
#include "binance_execution/spots/messages/create_order_request.h"
#include "binance_execution/spots/messages/modify_order_request.h"
#include "binance_execution/usds_futures/messages/cancel_order_request.h"
#include "binance_execution/usds_futures/messages/create_order_request.h"
#include "binance_execution/usds_futures/messages/modify_order_request.h"
#include "lib/core/TimeStamp.h"
#include "lib/logging/logging.h"
#include "lib/utils/crypto/hmac.h"
namespace binance_execution {
template <WebsocketApiRequestParams Params>
bool WebsocketApiRequest<Params>::sign(const std::string &secret_key) {
if (params.timestamp == 0) {
params.timestamp = bts::core::TimeStamp::now_ns() / 1'000'000;
}
params.signature.clear();
std::string sig_params;
params.to_signature_params(sig_params);
if (!bts::system::crypto::hmac_digest_hex(
secret_key, sig_params, params.signature)) {
LOG(OrderMan, bts::Error, "Failed to sign request. {}", sig_params);
return false;
}
return true;
}
template <WebsocketApiRequestParams Params>
std::string WebsocketApiRequest<Params>::to_string() const {
std::string str = fmt::format("{}", *this);
return str;
}
template <WebsocketApiRequestParams Params>
void to_json(nlohmann::json &j, const WebsocketApiRequest<Params> &req) {
j["id"] = req.id;
j["method"] = Params::WS_METHOD;
j["params"] = req.params;
}
template <WebsocketApiRequestParams Params>
void from_json(const nlohmann::json &j, WebsocketApiRequest<Params> &req) {
j.at("id").get_to(req.id);
j.at("params").get_to(req.params);
}
#define REQUEST_DEF(T) \
template struct WebsocketApiRequest<T>; \
template void to_json( \
nlohmann::json &j, const WebsocketApiRequest<T> &req); \
template void from_json(const nlohmann::json &j, WebsocketApiRequest<T> &req)
REQUEST_DEF(spots::CreateOrderRequest);
REQUEST_DEF(spots::ModifyOrderRequest);
REQUEST_DEF(spots::CancelOrderRequest);
REQUEST_DEF(usds_futures::CreateOrderRequest);
REQUEST_DEF(usds_futures::ModifyOrderRequest);
REQUEST_DEF(usds_futures::CancelOrderRequest);
} // namespace binance_execution
@@ -0,0 +1,44 @@
#pragma once
#include "lib/core/FMT_IMPL.h"
#include "lib/io/json_formatter.h"
#include <nlohmann/json.hpp>
namespace binance_execution {
template <typename T>
concept WebsocketApiRequestParams = requires(T t, std::string &res) {
{ T::WS_METHOD } -> std::convertible_to<std::string>;
{ t.apiKey } -> std::convertible_to<std::string>;
{ t.timestamp } -> std::convertible_to<std::int64_t>;
{ t.signature } -> std::convertible_to<std::string>;
{ t.to_signature_params(res) };
};
template <WebsocketApiRequestParams Params>
struct WebsocketApiRequest {
std::string id;
Params params;
bool sign(const std::string &secret_key);
std::string to_string() const;
};
template <WebsocketApiRequestParams Params>
void to_json(nlohmann::json &j, const WebsocketApiRequest<Params> &req);
template <WebsocketApiRequestParams Params>
void from_json(const nlohmann::json &j, WebsocketApiRequest<Params> &req);
} // namespace binance_execution
template <binance_execution::WebsocketApiRequestParams Params>
FMT_IMPL_T(
binance_execution::WebsocketApiRequest<Params>,
r,
R"({{"id": "{}", "method": "{}", "params": {} }})",
r.id,
Params::WS_METHOD,
bts::io::json_formatter(r.params));