add reconect to binance futures

This commit is contained in:
arham committed 2026-10-21 04:30:05 +00:00
1 parent fbbef6acf7
commit a2987f0102
3 files changed
+116 -3

No files matched your search

@@ -260,7 +260,7 @@ struct __attribute((visibility("hidden"))) StreamBatchData {
TRACE_VAR_PARAMS(
ec ? bts::Error : bts::Info, "depth_sub_close",
json_formatter(ec.message()));
on_conn_status(!ec, fmt::format("on_close - {}", ec.message()));
on_conn_status(false, fmt::format("on_close - {}", ec.message()));
}
};
@@ -329,6 +329,9 @@ struct __attribute((visibility("hidden"))) UsdsFuturesMdSubscription_PImpl {
ws_cfg.url = fmt::format(
"{}/stream?streams={}", ws_url, fmt::join(batch.streams, "/"));
ws_cfg.name = "binance_ufuts_md";
ws_cfg.reconnect_on_close = true;
ws_cfg.reconnect_on_fail = true;
ws_cfg.use_async_reconnect = true;
batch.init(
std::make_shared<WebsocketClient>(std::move(ws_cfg), &io_context));
}
@@ -460,6 +463,8 @@ struct __attribute((visibility("hidden"))) UsdsFuturesMdSubscription_PImpl {
}
void run_depth_streams() {
// Keep the context running while disconnected or waiting to retry.
const auto work = boost::asio::make_work_guard(io_context);
for (auto &sb : stream_batches) {
sb->ws_cli->connect();
}
@@ -18,6 +18,7 @@
#include <algorithm>
#include <atomic>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <chrono>
#include <exception>
#include <fmt/format.h>
@@ -164,6 +165,10 @@ struct WebsocketClient::PImpl {
State state = State::IDLE;
int version = 0;
int n_reconnects = 0;
std::unique_ptr<boost::asio::steady_timer> reconnect_timer;
std::unique_ptr<boost::asio::steady_timer> ping_timer;
bool reconnect_pending = false;
bool reconnect_stopped = false;
PImpl(WebsocketClientConfig config, boost::asio::io_context *io_context)
: config(std::move(config)), io_context(io_context) {
@@ -183,6 +188,12 @@ struct WebsocketClient::PImpl {
} else {
client.init_asio(io_context);
}
if (this->config.use_async_reconnect) {
reconnect_timer =
std::make_unique<boost::asio::steady_timer>(*this->io_context);
ping_timer =
std::make_unique<boost::asio::steady_timer>(*this->io_context);
}
client.set_message_handler(
[this](auto hdl, auto msg) { on_message(hdl, msg); });
client.set_open_handler([this](auto hdl) { on_open(hdl); });
@@ -198,7 +209,7 @@ struct WebsocketClient::PImpl {
client.set_tls_init_handler([&](auto hdl) { return on_tls_init(hdl); });
client.set_close_handler([=, this](auto hdl) {
on_close(hdl);
if (config.reconnect_on_close) {
if (config.reconnect_on_close && !config.use_async_reconnect) {
sleep_for(nanoseconds{reconnect_interval(n_reconnects).nanos()});
connect();
}
@@ -242,6 +253,12 @@ struct WebsocketClient::PImpl {
void close(websocketpp::close::status::value code, std::string reason) {
BTS_LOCK_GUARD(instance_mx);
if (config.use_async_reconnect) {
reconnect_stopped = true;
reconnect_pending = false;
reconnect_timer->cancel();
stop_continuous_ping();
}
INFO_FN(
"close. {}; code: {}; reason: {}", snapshot(),
WebsocketCloseStatus{code}, reason);
@@ -291,12 +308,23 @@ struct WebsocketClient::PImpl {
WARN_FN("connect. Unexpected state. {}", snapshot());
return;
}
if (config.use_async_reconnect) {
reconnect_stopped = false;
reconnect_pending = false;
reconnect_timer->cancel();
}
set_state(State::OPENING);
try {
websocketpp::lib::error_code ec;
con = client.get_connection(config.url, ec);
if (ec) {
ERROR_FN("connect_no_timeout. {}; err: {}", snapshot(), ec);
if (config.use_async_reconnect) {
set_state(State::IDLE);
if (config.reconnect_on_fail) {
reconnect();
}
}
return;
}
// Add headers
@@ -311,6 +339,9 @@ struct WebsocketClient::PImpl {
"connect_no_timeout. Failed to connect. {}; err: {}", snapshot(),
str);
set_state(State::IDLE);
if (config.use_async_reconnect && config.reconnect_on_fail) {
reconnect();
}
// Don't wait for connect
return;
}
@@ -318,6 +349,27 @@ struct WebsocketClient::PImpl {
void reconnect() {
WARN_FN("reconnect. {}", snapshot());
if (config.use_async_reconnect) {
if (reconnect_stopped || reconnect_pending) {
return;
}
reconnect_pending = true;
reconnect_timer->expires_after(
std::chrono::seconds(reconnect_interval(n_reconnects).seconds()));
++n_reconnects;
reconnect_timer->async_wait(
[this](const boost::system::error_code &ec) {
BTS_LOCK_GUARD(instance_mx);
if (ec || reconnect_stopped) {
return;
}
reconnect_pending = false;
if (state == State::IDLE) {
connect();
}
});
return;
}
sleep_for(nanoseconds{reconnect_interval(n_reconnects).nanos()});
++n_reconnects;
connect();
@@ -389,6 +441,12 @@ struct WebsocketClient::PImpl {
void ping_continuously(int interval_secs, string payload) {
INFO_FN("ping_continuously");
if (config.use_async_reconnect) {
BTS_LOCK_GUARD(instance_mx);
is_continuous_ping = true;
schedule_ping(interval_secs, std::move(payload));
return;
}
if (ping_thread) {
// stop the old ping
is_continuous_ping = false;
@@ -414,7 +472,34 @@ struct WebsocketClient::PImpl {
});
}
void stop_continuous_ping() { is_continuous_ping = false; }
void stop_continuous_ping() {
if (config.use_async_reconnect) {
BTS_LOCK_GUARD(instance_mx);
is_continuous_ping = false;
ping_timer->cancel();
return;
}
is_continuous_ping = false;
}
void schedule_ping(int interval_secs, string payload) {
ping_timer->expires_after(std::chrono::seconds(interval_secs));
ping_timer->async_wait(
[this, interval_secs,
payload = std::move(payload)](const boost::system::error_code &ec) {
BTS_LOCK_GUARD(instance_mx);
if (ec || reconnect_stopped || !is_continuous_ping ||
state != State::OPEN) {
return;
}
websocketpp::lib::error_code ping_ec;
client.ping(con->get_handle(), payload, ping_ec);
if (ping_ec) {
WARN_FN("ping. {}; err: {}", snapshot(), ping_ec.message());
}
schedule_ping(interval_secs, payload);
});
}
private:
static std::atomic<int> client_id_counter;
@@ -434,6 +519,12 @@ struct WebsocketClient::PImpl {
BTS_LOCK_GUARD(instance_mx);
INFO_FN("on_open. {}", snapshot());
const auto ec = client.get_con_from_hdl(hdl)->get_ec();
if (config.use_async_reconnect && reconnect_stopped) {
// An explicit disconnect may arrive while the handshake is pending.
set_state(State::OPEN);
close(websocketpp::close::status::going_away, "Reconnect stopped");
return;
}
if (ec) {
ERROR_FN("on_open. {}; err: {}", snapshot(), ec.message());
bts_assert(false);
@@ -446,6 +537,9 @@ struct WebsocketClient::PImpl {
return;
}
set_state(State::OPEN);
if (config.use_async_reconnect) {
n_reconnects = 0;
}
if (open_handler) {
(*open_handler)(ec);
}
@@ -472,6 +566,9 @@ struct WebsocketClient::PImpl {
void on_close(ConnectionHdl hdl) {
BTS_LOCK_GUARD(instance_mx);
if (config.use_async_reconnect) {
stop_continuous_ping();
}
INFO_FN("on_close. {}", snapshot());
switch (state.value) {
case State::CLOSING:
@@ -504,6 +601,9 @@ struct WebsocketClient::PImpl {
void on_fail(ConnectionHdl hdl) {
BTS_LOCK_GUARD(instance_mx);
if (config.use_async_reconnect) {
stop_continuous_ping();
}
ERROR_FN("on_fail. {}", snapshot());
set_state(State::IDLE);
const auto con = client.get_con_from_hdl(hdl);
@@ -14,6 +14,9 @@ struct WebsocketClientConfig {
core::TimeSpan pong_timeout = core::TimeSpan::zero();
bool reconnect_on_close = false;
bool reconnect_on_fail = false;
// Opt in to a single, cancellable timer-based reconnect path and ping loop.
// Legacy clients retain their existing reconnect behavior by default.
bool use_async_reconnect = false;
std::map<std::string, std::string> headers{};
// name to use in logs
std::string name{};
@@ -41,6 +44,10 @@ inline void from_json(const nlohmann::json &j, WebsocketClientConfig &cfg) {
if (it != j.end()) {
it->get_to(cfg.reconnect_on_fail);
}
it = j.find("use_async_reconnect");
if (it != j.end()) {
it->get_to(cfg.use_async_reconnect);
}
it = j.find("headers");
if (it != j.end()) {
it->get_to(cfg.headers);
@@ -57,6 +64,7 @@ inline void to_json(nlohmann::json &j, const WebsocketClientConfig &cfg) {
j["pong_timeout"] = cfg.pong_timeout.seconds();
j["reconnect_on_close"] = cfg.reconnect_on_close;
j["reconnect_on_fail"] = cfg.reconnect_on_fail;
j["use_async_reconnect"] = cfg.use_async_reconnect;
j["headers"] = cfg.headers;
j["name"] = cfg.name;
}