767 lines
32 KiB
C++
767 lines
32 KiB
C++
#include "OkxExecutionGateway.h"
|
|
#include "lib/api/services/OrderService.pb.h"
|
|
#include "lib/config/protos/okx_exe_cfg.pb.h"
|
|
#include "lib/domain_model/Security.pb.h"
|
|
#include "lib/domain_model/common.h"
|
|
#include "lib/io/http/http_client.h"
|
|
#include "lib/io/http/http_response.h"
|
|
#include "lib/io/websocket/websocket_client.h"
|
|
#include "lib/io/websocket/websocket_client_config.h"
|
|
#include "lib/logging/logging.h"
|
|
#include "lib/md/SecurityOracle.h"
|
|
#include "lib/orderman/CancelOrderMsg.h"
|
|
#include "lib/orderman/CancelReplaceOrderMsg.h"
|
|
#include "lib/orderman/CreateOrderMsg.h"
|
|
#include "lib/orderman/gateways/IExecutionGateway.h"
|
|
#include "lib/orderman/orderman_utils/ExecutionReport.h"
|
|
#include "lib/orderman/orderman_utils/OkxUtils.h"
|
|
#include "lib/orderman/orderman_utils/orderman_common.h"
|
|
#include "lib/utils/Uuid.h"
|
|
#include "lib/utils/bts_assert.h"
|
|
#include "lib/utils/thread_manager.h"
|
|
#include <OnixS/FIXEngine/FIX/Exception.h>
|
|
#include <OnixS/FIXEngine/FIX/FIX42.h>
|
|
#include <OnixS/FIXEngine/FIX/Message.h>
|
|
#include <OnixS/FIXEngine/FIX/Numeric.h>
|
|
#include <OnixS/FIXEngine/FIX/ProtocolVersion.h>
|
|
#include <atomic>
|
|
#include <cassert>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <ctime>
|
|
#include <exception>
|
|
#include <fmt/core.h>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <openssl/buffer.h>
|
|
#include <openssl/evp.h>
|
|
#include <openssl/hmac.h>
|
|
#include <quickfix/FixFields.h>
|
|
#include <quickfix/Utility.h>
|
|
#include <string>
|
|
#include <unistd.h>
|
|
#include <unordered_map>
|
|
// Example namespace alias for nlohmann::json
|
|
using json = nlohmann::json;
|
|
|
|
namespace bts::orderman {
|
|
|
|
OkxExecutionGateway::OkxExecutionGateway(md::SecurityOracle o)
|
|
: me_(std::make_unique<PImpl>(o)) {
|
|
LOG(OrderMan, Info, "OkxExecutionAdapter::constructor ");
|
|
} //listener() {}
|
|
OkxExecutionGateway::~OkxExecutionGateway() {}
|
|
|
|
enum class OkxExecutionState { OFF, STARTED, LOGGED_IN, SUBSCIRBED };
|
|
void OkxExecutionGateway::send_msgs(
|
|
std::vector<OrderMsg> const &msgs, trace::CorID) {
|
|
LOG(OrderMan,Info,"ExecutionGateway::send_msgs" );
|
|
for (const auto &msg : msgs) {
|
|
std::visit(
|
|
[this](auto &&order) {
|
|
using T = std::decay_t<decltype(order)>;
|
|
if constexpr (std::is_same_v<T, CreateOrderMsg>) {
|
|
LOG(OrderMan,Warn,"ExecutionGateway::CreateOrderMsg" );
|
|
launch_new_order(order);
|
|
|
|
} else if constexpr (std::is_same_v<T, CancelOrderMsg>) {
|
|
LOG(OrderMan,Warn,"ExecutionGateway::CancelOrderMsg" );
|
|
cancel_order(order);
|
|
} else if constexpr (std::is_same_v<T, CancelReplaceOrderMsg>) {
|
|
LOG(OrderMan,Warn,"ExecutionGateway::CancelReplaceOrderMsg" );
|
|
modify_order(order);
|
|
} else if constexpr (std::is_same_v<T, RFQMsg>) {
|
|
// Handle RFQMsg if necessary
|
|
// adapter->handle_rfq(order); // Example placeholder
|
|
}
|
|
},
|
|
msg);
|
|
}
|
|
}
|
|
|
|
static websocket::WebsocketClientConfig get_ws_client_config(
|
|
const std::string &url,
|
|
core::TimeSpan connect_timeout,
|
|
core::TimeSpan pong_timeout) {
|
|
websocket::WebsocketClientConfig rv{url, connect_timeout, pong_timeout};
|
|
rv.name = "OkxExecutionGateway";
|
|
return rv;
|
|
}
|
|
|
|
struct OkxExecutionGateway::PImpl {
|
|
const std::string api_key = config::get<config::OkxExeCfg>().api_key();
|
|
const std::string secret_key = config::get<config::OkxExeCfg>().secret_key();
|
|
const std::string passphrase = config::get<config::OkxExeCfg>().passphrase();
|
|
const std::string url =
|
|
config::get<config::OkxExeCfg>().ws_url() + "/ws/v5/private";
|
|
const bool simulated_trading = config::get<config::OkxExeCfg>().simulated_trading();
|
|
const std::string tdmode = config::get<config::OkxExeCfg>().tdmode();
|
|
const core::TimeSpan connect_timeout = core::TimeSpan::from_seconds(0);
|
|
const core::TimeSpan pong_timeout = core::TimeSpan::from_seconds(
|
|
config::get<config::OkxExeCfg>().ws_ping_interval_seconds());
|
|
websocket::WebsocketClient ws_client;
|
|
tbb::concurrent_queue<std::shared_ptr<ExecutionReport>> buffered_exec_reps;
|
|
std::optional<std::thread> ws_thread;
|
|
OnExeReport cb;
|
|
OnGwStatusChange on_gw_status_change;
|
|
OnCancelReject on_cancel_reject;
|
|
OnExchangePositionState on_exchange_position_state;
|
|
OnExchangeOpenOrdersState on_exchange_open_orders;
|
|
md::SecurityOracle o;
|
|
std::atomic<OkxExecutionState> state = OkxExecutionState::OFF;
|
|
PImpl(md::SecurityOracle o)
|
|
: ws_client(websocket::WebsocketClient(
|
|
get_ws_client_config(url, connect_timeout, pong_timeout))),
|
|
cb(dummy), o(o) {
|
|
ws_client.message_handler().bind<&PImpl::on_message>(*this);
|
|
ws_client.close_handler().bind<&PImpl::on_close>(*this);
|
|
};
|
|
|
|
~PImpl() {
|
|
state = OkxExecutionState::OFF;
|
|
if (ws_run_thread) {
|
|
ws_run_thread->join();
|
|
}
|
|
}
|
|
|
|
static void dummy(std::shared_ptr<const ExecutionReport>, const trace::CorID &) {
|
|
LOG(OrderMan, Error, "OnixFixListener::Dummy fired");
|
|
}
|
|
void setCallback(const OnExeReport &callback) {
|
|
LOG(OrderMan, Info,
|
|
"OkxExecutionAdapter::setCallback callback registered");
|
|
cb = callback;
|
|
}
|
|
|
|
std::optional<std::thread> ws_run_thread;
|
|
std::optional<std::thread> ws_ping_thread;
|
|
|
|
void get_exe_report(
|
|
const nlohmann::basic_json<> &order, ExecutionReport &report) {
|
|
report.exchange = api::VENUE_OKX;
|
|
std::string account_name = config::get<config::OkxExeCfg>().account();
|
|
std::string ops_id = config::get<config::OkxExeCfg>().ops_id();
|
|
|
|
std::array<char, 12> account_array = {};
|
|
std::copy_n(
|
|
account_name.begin(),
|
|
std::min(account_name.size(), account_array.size()),
|
|
account_array.begin());
|
|
report.account_name = AccountName(account_array);
|
|
report.leg_security = nullptr;
|
|
to_array(ops_id, &report.operator_id.value());
|
|
|
|
report.order_key =
|
|
OrderKey(std::stoi(order.at("clOrdId").get<std::string>()));
|
|
|
|
auto insttype =
|
|
OkxUtils::getInstType(order.at("instType").get<std::string>());
|
|
auto venue = api::VENUE_OKX;
|
|
auto inst_id = order.at("instId").get<std::string>();
|
|
|
|
// report.msg_seq_num = /* Generate or map message sequence */;
|
|
bts_assert(o.get_securities(venue, insttype, inst_id).size() == 1);
|
|
|
|
report.security = o.get_securities(venue, insttype, inst_id)[0];
|
|
|
|
report.side = (order.at("side").get<std::string>() == "buy")
|
|
? api::Side::SIDE_BUY
|
|
: api::Side::SIDE_SELL;
|
|
report.order_type =
|
|
OkxUtils::getOrdType(order.at("ordType").get<std::string>());
|
|
OkxUtils::populateExecTypeAndOrderStatus(
|
|
report, order.at("state").get<std::string>());
|
|
|
|
report.exchange_order_id = ExchangeOrderID(
|
|
OkxUtils::stringToFixedArray(order.at("ordId").get<std::string>()));
|
|
|
|
report.price = Price(std::stod(order.at("px").get<std::string>()));
|
|
|
|
report.quantity =
|
|
Quantity::create_new(std::stod(order.at("sz").get<std::string>()));
|
|
report.filled_quantity = Quantity::create_new(
|
|
std::stod(order.at("accFillSz").get<std::string>()));
|
|
report.last_price =
|
|
Price(std::stod(order.at("lastPx").get<std::string>()));
|
|
report.avg_price = Price(std::stod(order.at("avgPx").get<std::string>()));
|
|
report.last_shares = Quantity::create_new(
|
|
std::stod(order.at("fillSz").get<std::string>()));
|
|
|
|
//there are algos, like spreader
|
|
// that are super sensitive to messages and cancel themselves. To avoid
|
|
// this we only pass on the error messages when the order has terminated.
|
|
// The assumption being that if the order has not terminated it is OK to
|
|
// ignore the message.
|
|
// Alternatively we can change the spreader to not do that. Right not this
|
|
// seems to be the better choice
|
|
if (!(order.at("code").get<std::string>() == "0")) {
|
|
report.msg = order.at("msg").get<std::string>();
|
|
}
|
|
|
|
|
|
//report can be new order, cancel order, order filled, replace order, and partial fill or errror
|
|
//new order, cancelled and order filled dont need special handling, error gets handled above
|
|
//for other three we will look for fields that are only specific to the respectives types
|
|
// if (!(order.at("cancelSource").get<std::string>() == "")) {
|
|
|
|
// }
|
|
if (!(order.at("amendSource").get<std::string>() == "")) {
|
|
if((order.at("amendResult").get<std::string>() == "0"))
|
|
report.exec_type = api::orderman::ExecType::EXEC_TYPE_REPLACED;
|
|
else{
|
|
LOG(OrderMan, Warn, "order:{} replace rejected", report.order_key);
|
|
report.msg = order.at("msg").get<std::string>();
|
|
}
|
|
} else if (!(order.at("fillSz").get<std::string>() == "0")) {
|
|
utils::Uuid guid;
|
|
std::string fill_id = guid.to_text_string();
|
|
to_array(fill_id, &report.exchange_fill_id.value());
|
|
}
|
|
|
|
// report.transact_time = ExchangeTimeStampVar(std::stoll(order.at("uTime").get<std::string>()));
|
|
ExchangeTimeStamp64 now = ExchangeTimeStamp64(datetime::unix_nano_now());
|
|
report.transact_time = now;
|
|
std::string er = report.to_string();
|
|
LOG(OrderMan, Info, "Created ExecutionReport: {}", er);
|
|
}
|
|
void on_close(const std::error_code &ec) {
|
|
bts_assert_msgf(
|
|
false, "Websocket stream client disconnected. {}", ec.message());
|
|
}
|
|
// fills execution report form basic_json and writes it to
|
|
// buffered_exec_reps, which is picked up from the other thread
|
|
// and passed over to the order infrastructure
|
|
void _push_execution_report(const nlohmann::basic_json<> &order) {
|
|
ExecutionReport er;
|
|
get_exe_report(order, er);
|
|
buffered_exec_reps.push(std::make_shared<ExecutionReport>(std::move(er)));
|
|
}
|
|
void on_message(const std::string &msg_str) {
|
|
LOG(OrderMan, Info, "okxlistener::on_message. {}", msg_str);
|
|
nlohmann::json msg;
|
|
try {
|
|
msg = nlohmann::json::parse(msg_str);
|
|
} catch (const std::exception &ex) {
|
|
std::string s = ex.what();
|
|
LOG(OrderMan, Error, "Failed to parse json. {}\n{}", s, msg_str);
|
|
return;
|
|
}
|
|
const auto event_type_it = msg.find("event");
|
|
if (event_type_it != msg.end()) {
|
|
const auto event_type = event_type_it->get<std::string>();
|
|
if (event_type == "login") {
|
|
bts_assert(state == OkxExecutionState::STARTED);
|
|
const auto code_it = msg.find("code");
|
|
const auto code = code_it->get<std::string>();
|
|
if (code == "0") {
|
|
LOG(OrderMan, Info, "Succefully logged in {}", msg_str);
|
|
state = OkxExecutionState::LOGGED_IN;
|
|
}
|
|
|
|
return;
|
|
}
|
|
if (event_type == "subscribe") {
|
|
bts_assert(state == OkxExecutionState::LOGGED_IN);
|
|
state = OkxExecutionState::SUBSCIRBED;
|
|
return;
|
|
}
|
|
if (event_type == "channel-conn-count") { //ignore for now
|
|
return;
|
|
}
|
|
}
|
|
// Handle order updates
|
|
|
|
const auto channel_it = msg.find("arg");
|
|
if (channel_it == msg.end() ||
|
|
channel_it->at("channel").get<std::string>() != "orders") {
|
|
LOG(OrderMan, Error, "Unexpected response id:\n{}", msg_str);
|
|
return;
|
|
}
|
|
|
|
const auto &data = msg.at("data");
|
|
|
|
|
|
|
|
for (const nlohmann::basic_json<> &order : data) {
|
|
int orderkey = 0;
|
|
try {
|
|
int temp = std::stoi(order.at("clOrdId").get<std::string>());
|
|
orderkey = temp;
|
|
}catch (...) {
|
|
}
|
|
if(orderkey ==0){
|
|
LOG(OrderMan, Error, "okxlistener::on_message GOT ER FOR ORDER NOT ENTERED FROM SYSTEM. {}", msg_str);
|
|
continue;
|
|
}
|
|
_push_execution_report(order);
|
|
}
|
|
}
|
|
void start() {
|
|
bts_assert(!ws_thread);
|
|
state = OkxExecutionState::STARTED;
|
|
ws_thread.emplace([this]() {
|
|
bts::threading::configure_current_thread("okx_execution");
|
|
start_impl();
|
|
});
|
|
}
|
|
|
|
void start_impl() {
|
|
size_t attempt = 0;
|
|
while (state != OkxExecutionState::OFF) {
|
|
try {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start Attempting login (Attempt: {})",
|
|
attempt + 1);
|
|
if (ws_run_thread) {
|
|
// Join this thread to block until the websocket disconnects (then reconnect)
|
|
if (ws_run_thread->joinable()) {
|
|
ws_run_thread->join();
|
|
}
|
|
ws_run_thread.reset();
|
|
}
|
|
// Connect
|
|
ws_client.connect();
|
|
ws_run_thread = threading::make_thread(
|
|
"okx_execution_ws", [&]() { ws_client.run(); });
|
|
// Block until the websocket connects (or times out)
|
|
{
|
|
const auto start_time = bts::core::TimeStamp::now();
|
|
for (auto elapsed = core::TimeSpan::zero();
|
|
!ws_client.is_connected() &&
|
|
elapsed < core::TimeSpan::from_seconds(20);
|
|
elapsed = core::TimeStamp::now() - start_time) {
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
}
|
|
if (!ws_client.is_connected()) {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start. Timed out waiting for "
|
|
"websocket to connect");
|
|
continue;
|
|
}
|
|
}
|
|
if (ws_ping_thread.has_value()) {
|
|
if (ws_ping_thread->joinable()) {
|
|
ws_ping_thread
|
|
->join(); // Ensure the previous thread exits cleanly
|
|
}
|
|
ws_ping_thread
|
|
.reset(); // Reset the optional before creating a new thread
|
|
}
|
|
|
|
ws_ping_thread.emplace([&]() {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::ws_ping_thread thread starting. url: "
|
|
"{}",
|
|
url);
|
|
auto last_ping_time = core::TimeStamp::now();
|
|
auto ping_interval = core::TimeSpan::from_seconds(
|
|
config::get<config::OkxExeCfg>().ws_ping_interval_seconds());
|
|
std::this_thread::sleep_for(
|
|
std::chrono::milliseconds(ping_interval.millis()));
|
|
|
|
while (ws_client.is_connected()) {
|
|
const auto now = bts::core::TimeStamp::now();
|
|
if ((now - last_ping_time) > ping_interval) {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::ws_ping_thread Pinging "
|
|
"websocket. url: {}",
|
|
url);
|
|
ws_client.ping();
|
|
last_ping_time = now;
|
|
}
|
|
std::this_thread::sleep_for(
|
|
std::chrono::seconds(ping_interval.seconds() / 10));
|
|
}
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::ws_ping_thread thread exiting. url: "
|
|
"{}",
|
|
url);
|
|
});
|
|
|
|
auto [timestamp, sign] = OkxUtils::getLoginSignTime(secret_key);
|
|
static constexpr const char *AUTH_REQ_TEMPLATE =
|
|
R"({{"op": "login", "args": [{{ "apiKey": "{}", "passphrase": "{}", "timestamp": "{}", "sign": "{}" }}] }})";
|
|
|
|
const std::string auth_req = fmt::format(
|
|
AUTH_REQ_TEMPLATE, api_key, passphrase, timestamp, sign);
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start Attempting login (req: {})",
|
|
auth_req);
|
|
const auto auth_res = ws_client.send_text(auth_req);
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start Attempting login {}, {}, {}",
|
|
std::to_string(auth_res.value()),
|
|
std::string(auth_res.category().name()), auth_res.message());
|
|
if (auth_res.value()) {
|
|
LOG(md, Info, "okx authentication failed. {}",
|
|
auth_res.message());
|
|
attempt++;
|
|
throw std::runtime_error(
|
|
"okx authentication failed: " + auth_res.message());
|
|
}
|
|
while (state == OkxExecutionState::STARTED) {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start waiting to login");
|
|
std::this_thread::sleep_for(1s);
|
|
}
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start Login successful {}",
|
|
auth_res.message());
|
|
std::string subscribe_req = R"({
|
|
"op": "subscribe",
|
|
"args": [{"channel": "orders", "instType": "ANY"}]
|
|
})";
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start AGttempting sub (req: {})",
|
|
subscribe_req);
|
|
const auto auth_res2 = ws_client.send_text(subscribe_req);
|
|
LOG(OrderMan, Warn, "OkxExecutionAdapter::subscribing to orders{}",
|
|
auth_res2.message());
|
|
while (state != OkxExecutionState::SUBSCIRBED) {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::start waiting to subscribe");
|
|
|
|
std::this_thread::sleep_for(1s);
|
|
}
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::subscribing to orders successful{}",
|
|
auth_res2.message());
|
|
on_gw_status_change(true);
|
|
break; // Exit loop on success
|
|
} catch (const std::exception &ex) {
|
|
const std::string err = ex.what();
|
|
LOG(OrderMan, Error,
|
|
"OkxExecutionAdapter::start Login failed: {}. Retrying in {} "
|
|
"seconds.",
|
|
err,
|
|
config::get<config::OkxExeCfg>()
|
|
.ws_reconnect_interval_seconds());
|
|
|
|
size_t maxRetries =
|
|
config::get<config::OkxExeCfg>().ws_reconnect_max_count();
|
|
if (maxRetries > 0 && ++attempt >= maxRetries) {
|
|
LOG(OrderMan, Error,
|
|
"OkxExecutionAdapter::start Exceeded max retries ({}). "
|
|
"Aborting.",
|
|
maxRetries);
|
|
OkxUtils::handleOkException("OkxExecutionAdapter::start", err);
|
|
break; // Exit if retries are exhausted
|
|
}
|
|
std::this_thread::sleep_for(
|
|
std::chrono::seconds(config::get<config::OkxExeCfg>()
|
|
.ws_reconnect_interval_seconds()));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
void OkxExecutionGateway::start() { me_->start(); }
|
|
OnGwStatusChange &OkxExecutionGateway::on_gw_status_change() {
|
|
return me_->on_gw_status_change;
|
|
}
|
|
void OkxExecutionGateway::modify_order(
|
|
const CancelReplaceOrderMsg &msg) { //confirm will have everything
|
|
try {
|
|
LOG(OrderMan, Warn, "OkxExecutionAdapter::modify_order modifying order{}",
|
|
msg);
|
|
http::HttpResponse res;
|
|
// static constexpr const char *body_template = R"({"instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit", "px": "1000", "sz": "0.01"})";
|
|
static constexpr const char *body_template =
|
|
R"({{"instId": "{}", "clordId": "{}", "newPx": "{}", "newSz": "{}"}})";
|
|
const std::string REQUEST_PATH = "/api/v5/trade/amend-order";
|
|
const std::string body = fmt::format(
|
|
body_template, msg.create_fields.security->okx().security_desc(),
|
|
msg.create_fields.key, msg.create_fields.price,
|
|
std::to_string(msg.create_fields.quantity.full_value()));
|
|
auto headers = OkxUtils::createHeaders(
|
|
me_->api_key, me_->passphrase, me_->secret_key, "POST", REQUEST_PATH,
|
|
me_->simulated_trading,body);
|
|
// Generate and log the curl command
|
|
std::string curlCommand = OkxUtils::generateCurlCommand(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, headers,
|
|
body);
|
|
LOG(OrderMan, Warn, "Curl Command: \n{}", curlCommand);
|
|
http::HttpClient::post(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, body,
|
|
headers, &res);
|
|
const auto &[suc, top_msg] = OkxUtils::orderAccepted(res.body);
|
|
|
|
if (suc) {
|
|
LOG(md, Info, "Http get succeeded {}", res.body);
|
|
} else {
|
|
LOG(md, Info, "Http get failed code: {}, errors: {}, body: {}", res.code, res.errors, res.body);
|
|
}
|
|
} catch (const std::exception &ex) {
|
|
const std::string err = ex.what();
|
|
OkxUtils::handleOkException("Amend order", err);
|
|
}
|
|
}
|
|
void OkxExecutionGateway::dispatch_incoming_fix_messages() {
|
|
if (me_->buffered_exec_reps.empty()) {
|
|
return;
|
|
}
|
|
std::shared_ptr<ExecutionReport> er;
|
|
while (me_->buffered_exec_reps.try_pop(er)) {
|
|
trace::CorID cid = {};
|
|
LOG(OrderMan, Info,
|
|
"OkxExecutionGateway::dispatch_incoming_fix_messages er: {} ",
|
|
er->to_string());
|
|
me_->cb(std::move(er), cid);
|
|
}
|
|
}
|
|
OnExeReport &OkxExecutionGateway::on_exe_report() { return me_->cb; }
|
|
OnCancelReject &OkxExecutionGateway::on_cancel_reject() {
|
|
static OnCancelReject default_cancel_reject;
|
|
return default_cancel_reject;
|
|
}
|
|
OnExchangePositionState &OkxExecutionGateway::on_exchange_position_state() {
|
|
static OnExchangePositionState default_exchange_position_state;
|
|
return default_exchange_position_state;
|
|
}
|
|
OnExchangeOpenOrdersState &OkxExecutionGateway::on_exchange_open_orders() {
|
|
static OnExchangeOpenOrdersState default_exchange_open_orders;
|
|
return default_exchange_open_orders;
|
|
}
|
|
void OkxExecutionGateway::launch_new_order(const CreateOrderMsg &msg) {
|
|
LOG(OrderMan, Warn, "launch order {}", msg);
|
|
try {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::launch_new_order creating order");
|
|
static constexpr const char *body_template =
|
|
R"({{"instId": "{}", "tdMode": "{}", "side": "{}", "ordType": "{}", "px": "{}", "sz": "{}", "clordId": "{}"}})";
|
|
const std::string REQUEST_PATH = "/api/v5/trade/order";
|
|
const std::string side = msg.side == api::Side::SIDE_BUY ? "buy" : "sell";
|
|
const std::string quantity = std::to_string(msg.quantity.full_value());
|
|
const std::string price = std::to_string(msg.price.value());
|
|
std::string suffix = "ORDER_TYPE_";
|
|
auto ord_full_name = NativeOrderType_Name(msg.order_type);
|
|
auto pos = ord_full_name.find(suffix);
|
|
const std::string ord_type =
|
|
FIX::string_toLower(ord_full_name.substr(pos + suffix.size()));
|
|
const std::string body = fmt::format(
|
|
body_template, msg.security->okx().security_desc(),me_->tdmode, side, ord_type,
|
|
price, quantity, msg.key);
|
|
http::HttpResponse res;
|
|
auto headers = OkxUtils::createHeaders(
|
|
me_->api_key, me_->passphrase, me_->secret_key, "POST", REQUEST_PATH,
|
|
me_->simulated_trading,body);
|
|
// Generate and log the curl command
|
|
std::string curlCommand = OkxUtils::generateCurlCommand(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, headers,
|
|
body);
|
|
LOG(OrderMan, Warn, "Curl Command: \n{}", curlCommand);
|
|
ExecutionReport er;
|
|
http::HttpClient::post(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, body,
|
|
headers, &res);
|
|
const auto &[suc, top_msg] = OkxUtils::orderAccepted(res.body);
|
|
|
|
if (suc) {
|
|
LOG(md, Info, "Http get succeeded {}", res.body);
|
|
// er.exec_type = api::orderman::ExecType::EXEC_TYPE_PENDING_NEW;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_PENDING_NEW;
|
|
} else {
|
|
LOG(md, Info, "Http get failed code: {}, errors: {}, body: {}", res.code, res.errors, res.body);
|
|
OkxUtils::populateCreateOrderFields(er, msg);
|
|
er.price = msg.price;
|
|
er.quantity = msg.quantity;
|
|
er.filled_quantity = 0;
|
|
er.last_shares = 0;
|
|
er.leg_security = nullptr;
|
|
er.avg_price = Price(0);
|
|
ExchangeTimeStamp64 now = ExchangeTimeStamp64(datetime::unix_nano_now());
|
|
er.transact_time = now;
|
|
er.order_key = msg.key;
|
|
const auto &[id, ts, ex_msg] = OkxUtils::extractOrderInfo(res.body);
|
|
er.exchange_order_id = ExchangeOrderID{OkxUtils::stringToFixedArray(id)};
|
|
er.exec_type = api::orderman::ExecType::EXEC_TYPE_REJECTED;
|
|
er.order_status = api::orderman::NATIVE_ORDER_STATUS_REJECTED;
|
|
er.msg = ex_msg + " " + top_msg;
|
|
me_->buffered_exec_reps.push(
|
|
std::make_shared<ExecutionReport>(std::move(er)));
|
|
}
|
|
}
|
|
// Shut down all reactors if they exist.
|
|
catch (const std::exception &ex) {
|
|
const std::string err = ex.what();
|
|
OkxUtils::handleOkException("Launch order", err);
|
|
}
|
|
}
|
|
void OkxExecutionGateway::register_callback(
|
|
[[maybe_unused]] const OnExeReport &cb) {
|
|
LOG(OrderMan, Warn,
|
|
"OkxExecutionAdapter::register_callback callback registered");
|
|
me_->setCallback(cb);
|
|
}
|
|
|
|
void OkxExecutionGateway::cancel_order(const CancelOrderMsg &msg) {
|
|
LOG(OrderMan, Warn, "cancel order {}", msg);
|
|
try {
|
|
http::HttpResponse res;
|
|
// static constexpr const char *body_template = R"({"instId": "BTC-USDT", "tdMode": "cash", "side": "buy", "ordType": "limit", "px": "1000", "sz": "0.01"})";
|
|
static constexpr const char *body_template =
|
|
R"({{"instId": "{}", "clordId": "{}"}})";
|
|
const std::string REQUEST_PATH = "/api/v5/trade/cancel-order";
|
|
const std::string body = fmt::format(
|
|
body_template, msg.security->okx().security_desc(), msg.key);
|
|
auto headers = OkxUtils::createHeaders(
|
|
me_->api_key, me_->passphrase, me_->secret_key, "POST", REQUEST_PATH,
|
|
me_->simulated_trading,body);
|
|
// Generate and log the curl command
|
|
std::string curlCommand = OkxUtils::generateCurlCommand(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, headers,
|
|
body);
|
|
LOG(OrderMan, Warn, "Curl Command: \n{}", curlCommand);
|
|
http::HttpClient::post(
|
|
config::get<config::OkxExeCfg>().rest_url() + REQUEST_PATH, body,
|
|
headers, &res);
|
|
const auto &[suc, top_msg] = OkxUtils::orderAccepted(res.body);
|
|
// ExecutionReport *er_p = me_->exe_report_pool.construct();
|
|
// ExecutionReport &er = *er_p;
|
|
// er.security = msg.security;
|
|
// er.side = msg.side;
|
|
// er.order_key = msg.key;
|
|
// to_array(msg.routing_record->account(), &er.account_name.value());
|
|
// to_array(msg.routing_record->operator_id(), &er.operator_id.value());
|
|
// er.exchange = msg.security->exchange();
|
|
// er.order_key = msg.key;
|
|
// const auto &[id, ts, ex_msg] = OkxUtils::extractOrderInfo(res.body);
|
|
if (suc) {
|
|
LOG(md, Info, "Http get succeeded {}", res.body);
|
|
// er.exec_type = api::orderman::ExecType::EXEC_TYPE_PENDING_CANCEL;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_PENDING_CANCEL;
|
|
} else {
|
|
LOG(md, Info, "Http get failed code: {}, errors: {}, body: {}", res.code, res.errors, res.body);
|
|
// er.exec_type = api::orderman::ExecType::EXEC_TYPE_REJECTED;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_REJECTED;
|
|
// er.msg = ex_msg + " " + top_msg;
|
|
}
|
|
// me_->cb(er, {});
|
|
}
|
|
// Shut down all reactors if they exist.
|
|
catch (const std::exception &ex) {
|
|
const std::string err = ex.what();
|
|
OkxUtils::handleOkException("Cacnel order", err);
|
|
}
|
|
}
|
|
} // namespace bts::orderman::okxexe
|
|
|
|
|
|
// ExecutionReport OkxExecutionAdapter::fire_dummy_modify_order_report(CancelReplaceOrderMsg msg) {
|
|
// ExecutionReport *er_p = me_->create_exe_ptr();
|
|
// ExecutionReport &er = *er_p;
|
|
// std::string account_name = config::get<config::OkxExeCfg>().account();
|
|
// std::string ops_id = config::get<config::OkxExeCfg>().ops_id();
|
|
|
|
// std::array<char, 12> account_array = {};
|
|
// std::copy_n(
|
|
// account_name.begin(),
|
|
// std::min(account_name.size(), account_array.size()),
|
|
// account_array.begin());
|
|
// er.account_name = AccountName(account_array);
|
|
|
|
// to_array(ops_id, &er.operator_id.value());
|
|
// er.order_key = msg.create_fields.key;
|
|
// er.msg_seq_num = 0;
|
|
// er.security = msg.create_fields.security;
|
|
// er.leg_security = nullptr;
|
|
// er.side = msg.create_fields.side;
|
|
// er.time_in_force = msg.create_fields.time_in_force;
|
|
// er.order_type = msg.create_fields.order_type;
|
|
// er.exec_type = api::orderman::EXEC_TYPE_REPLACED;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_REPLACED;
|
|
// er.manual_order_indicator = api::orderman::MANUAL_ORDER_INDICATOR_NO;
|
|
// auto s = std::to_string(msg.create_fields.key.value());
|
|
// std::array<char, 17> idAsArray{};
|
|
// std::copy_n(s.begin(), std::min(s.size()-1, idAsArray.size() - 1), idAsArray.begin());
|
|
// er.exchange_order_id = ExchangeOrderID{idAsArray};
|
|
// er.price = msg.create_fields.price;
|
|
// er.quantity = msg.create_fields.quantity;
|
|
// er.filled_quantity = Quantity(0);
|
|
// er.last_shares = Quantity(0);
|
|
// er.msg = "";
|
|
// er.exchange = msg.create_fields.security->exchange();
|
|
// // Set transaction time
|
|
// ExchangeTimeStamp64 now = ExchangeTimeStamp64(datetime::unix_nano_now());
|
|
// er.transact_time = now;
|
|
// me_->cb(er, {});
|
|
// return er;
|
|
// }
|
|
// ExecutionReport OkxExecutionAdapter::fire_dummy_cancel_order_report(CancelOrderMsg msg) {
|
|
// ExecutionReport *er_p = me_->create_exe_ptr();
|
|
// ExecutionReport &er = *er_p;
|
|
// std::string account_name = config::get<config::OkxExeCfg>().account();
|
|
// std::string ops_id = config::get<config::OkxExeCfg>().ops_id();
|
|
|
|
// std::array<char, 12> account_array = {};
|
|
// std::copy_n(
|
|
// account_name.begin(),
|
|
// std::min(account_name.size(), account_array.size()),
|
|
// account_array.begin());
|
|
// er.account_name = AccountName(account_array);
|
|
|
|
// to_array(ops_id, &er.operator_id.value());
|
|
// er.order_key = msg.key;
|
|
// er.msg_seq_num = 0;
|
|
// er.security = msg.security;
|
|
// er.leg_security = nullptr;
|
|
// er.side = msg.side;
|
|
// er.time_in_force = api::orderman::TIME_IN_FORCE_GTC;
|
|
// er.order_type = api::orderman::NATIVE_ORDER_TYPE_LIMIT;
|
|
// er.exec_type = api::orderman::EXEC_TYPE_TRADE_CANCEL;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_CANCELED;
|
|
// er.manual_order_indicator = api::orderman::MANUAL_ORDER_INDICATOR_NO;
|
|
// auto s = std::to_string(msg.key.value());
|
|
// std::array<char, 17> idAsArray{};
|
|
// std::copy_n(s.begin(), std::min(s.size()-1, idAsArray.size() - 1), idAsArray.begin());
|
|
// er.exchange_order_id = ExchangeOrderID{idAsArray};
|
|
// er.filled_quantity = Quantity(0);
|
|
// er.last_shares = Quantity(0);
|
|
// er.msg = "";
|
|
// er.exchange = msg.security->exchange();
|
|
// // Set transaction time
|
|
// ExchangeTimeStamp64 now = ExchangeTimeStamp64(datetime::unix_nano_now());
|
|
// er.transact_time = now;
|
|
// me_->cb(er, {});
|
|
// return er;
|
|
// }
|
|
// ExecutionReport OkxExecutionAdapter::fire_dummy_new_order_report(CreateOrderMsg msg) {
|
|
// ExecutionReport *er_p = me_->create_exe_ptr();
|
|
// ExecutionReport &er = *er_p;
|
|
// std::string account_name = config::get<config::OkxExeCfg>().account();
|
|
// std::string ops_id = config::get<config::OkxExeCfg>().ops_id();
|
|
|
|
// std::array<char, 12> account_array = {};
|
|
// std::copy_n(
|
|
// account_name.begin(),
|
|
// std::min(account_name.size(), account_array.size()),
|
|
// account_array.begin());
|
|
// er.account_name = AccountName(account_array);
|
|
|
|
// to_array(ops_id, &er.operator_id.value());
|
|
// er.order_key = msg.key;
|
|
// er.msg_seq_num = 0;
|
|
// er.security = msg.security;
|
|
// er.leg_security = nullptr;
|
|
// er.side = msg.side;
|
|
// er.time_in_force = api::orderman::TIME_IN_FORCE_GTC;
|
|
// er.order_type = msg.order_type;
|
|
// er.exec_type = api::orderman::EXEC_TYPE_NEW;
|
|
// er.order_status = api::orderman::NATIVE_ORDER_STATUS_NEW;
|
|
// er.manual_order_indicator = api::orderman::MANUAL_ORDER_INDICATOR_NO;
|
|
// auto s = std::to_string(msg.key.value());
|
|
// std::array<char, 17> idAsArray{};
|
|
// std::copy_n(s.begin(), std::min(s.size()-1, idAsArray.size() - 1), idAsArray.begin());
|
|
// er.exchange_order_id = ExchangeOrderID{idAsArray};
|
|
// er.price = msg.price;
|
|
// er.quantity = msg.quantity;
|
|
// er.filled_quantity = Quantity(0);
|
|
// er.last_shares = Quantity(0);
|
|
// er.msg = "";
|
|
// er.exchange = msg.security->exchange();
|
|
// // Set transaction time
|
|
// ExchangeTimeStamp64 now = ExchangeTimeStamp64(datetime::unix_nano_now());
|
|
// er.transact_time = now;
|
|
// me_->cb(er, {});
|
|
// return er;
|
|
// }
|