961 lines
36 KiB
C++
961 lines
36 KiB
C++
#ifdef SPARK_ENABLE_CCAPI
|
|
|
|
#include "CCAPIDeribitOrderMux.h"
|
|
#include "CCAPIOrderState.h"
|
|
#include "CCAPISingleOrderManager.h"
|
|
#include "ccapi_cpp/ccapi_session.h"
|
|
#include "lib/api/services/OrderService.pb.h"
|
|
#include "lib/domain_model/Security.pb.h"
|
|
#include "lib/domain_model/SecurityKey.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/RFQMsg.h"
|
|
#include "lib/orderman/ccapi/CCAPIConnectionConfig.h"
|
|
#include "lib/orderman/ccapi/CCAPIDeribitHelpers.h"
|
|
#include "lib/orderman/ccapi/CCAPIOrderCallbackMsgs.h"
|
|
#include "lib/orderman/ccapi/ICCAPIOrderMux.h"
|
|
#include "lib/orderman/orderman_utils/orderman_common.h"
|
|
#include "lib/utils/PBUtils.h"
|
|
#include "lib/utils/bts_assert.h"
|
|
#include <bits/stdint-uintn.h>
|
|
#include <boost/lockfree/spsc_queue.hpp>
|
|
#include <ccapi_cpp/ccapi_element.h>
|
|
#include <ccapi_cpp/ccapi_event.h>
|
|
#include <ccapi_cpp/ccapi_macro.h>
|
|
#include <ccapi_cpp/ccapi_message.h>
|
|
#include <ccapi_cpp/ccapi_request.h>
|
|
#include <ccapi_cpp/ccapi_subscription.h>
|
|
#include <ccapi_cpp/ccapi_util_private.h>
|
|
#include <chrono>
|
|
#include <cstdint>
|
|
#include <google/protobuf/timestamp.pb.h>
|
|
#include <google/protobuf/util/time_util.h>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <ostream>
|
|
#include <set>
|
|
#include <string>
|
|
#include <unordered_map>
|
|
#include <variant>
|
|
#include <vector>
|
|
|
|
using namespace std;
|
|
namespace bts::orderman {
|
|
|
|
// This is the interface we need to pass to CCAPI to get the callbacks
|
|
// For threading reasons, it just queues the message which is then dequeued
|
|
// in dispatch_incoming_messages
|
|
class OrderEventHandler : public ccapi::EventHandler {
|
|
boost::lockfree::spsc_queue<ccapi::Event> &dispatch_queue;
|
|
// list of events we are interested in, the rest are logged and discarded
|
|
std::set<ccapi::Event::Type> event_types;
|
|
std::set<std::string> nolog_corrids;
|
|
|
|
public:
|
|
OrderEventHandler(
|
|
boost::lockfree::spsc_queue<ccapi::Event> &dispatch_queue,
|
|
const std::vector<ccapi::Event::Type> &event_types,
|
|
const std::set<std::string> &nolog_corrids_arg)
|
|
: dispatch_queue(dispatch_queue),
|
|
event_types(event_types.begin(), event_types.end()),
|
|
nolog_corrids(nolog_corrids_arg) {}
|
|
bool processEvent(
|
|
const ccapi::Event &event, ccapi::Session *session) override {
|
|
bts_assert(session != nullptr);
|
|
bool interested = event_types.find(event.getType()) != event_types.end();
|
|
if (should_log_event(event))
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::OrderEventHandler::processEvent tid: {} "
|
|
"interested: {} "
|
|
"event: {}",
|
|
os::get_thread_id(), interested, event.toStringPretty(2, 2));
|
|
if (interested)
|
|
dispatch_queue.push(event);
|
|
return true;
|
|
}
|
|
bool should_log_event(const ccapi::Event &event) const {
|
|
for (const auto &msg : event.messageList) {
|
|
for (const auto &corrid : msg.getCorrelationIdList()) {
|
|
if (nolog_corrids.find(corrid) == nolog_corrids.end()) {
|
|
// if any corrid is not in the ignore list, we log the whole event
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
};
|
|
|
|
// Helper with corrid generation and parsing
|
|
struct CorrIDHelper {
|
|
const std::string create_order_prefix = "NewOrder";
|
|
const std::string modify_order_prefix = "ModOrder";
|
|
const std::string cancel_order_prefix = "CxlOrder";
|
|
const char delim = ':';
|
|
std::string get_create_order_corrid(
|
|
OrderKey ok, const std::string &deribit_sec_name) const {
|
|
return create_order_prefix + delim + std::to_string(ok.value()) + delim +
|
|
deribit_sec_name;
|
|
}
|
|
std::string get_modify_order_corrid(
|
|
OrderKey ok, size_t n_outgoing_mods) const {
|
|
return modify_order_prefix + delim + std::to_string(ok.value()) + delim +
|
|
std::to_string(n_outgoing_mods);
|
|
}
|
|
std::string get_cancel_order_corrid(OrderKey ok) const {
|
|
return cancel_order_prefix + delim + std::to_string(ok.value());
|
|
}
|
|
std::vector<std::string> split_string(const std::string &str, char delim) {
|
|
// vector of string to save tokens
|
|
std::vector<std::string> tokens = {};
|
|
// stringstream class check1
|
|
std::stringstream check1(str);
|
|
std::string intermediate;
|
|
while (getline(check1, intermediate, delim)) {
|
|
tokens.push_back(intermediate);
|
|
}
|
|
return tokens;
|
|
}
|
|
std::optional<OrderKey> parse_create_order_corrid(
|
|
const std::string &corrid) {
|
|
auto tokens = split_string(corrid, delim);
|
|
if (tokens.size() == 3 && tokens.at(0) == create_order_prefix) {
|
|
std::string ok_str = tokens.at(1);
|
|
return OrderKey(std::stoi(ok_str));
|
|
}
|
|
return std::nullopt;
|
|
}
|
|
};
|
|
|
|
// Struct to organize the periodic requesting or positons and orders
|
|
struct PositionOrderRequestHelper {
|
|
struct PosData {
|
|
std::string currency;
|
|
std::string corrid;
|
|
std::vector<CCAPIPosition> pos_vec;
|
|
};
|
|
struct OrderData {
|
|
std::string currency;
|
|
std::string corrid;
|
|
std::vector<CCAPIExchangeOpenOrder> order_vec;
|
|
};
|
|
std::map<std::string, PosData> curr_pos_map = {
|
|
{"BTC", {"BTC", "GetPositions:BTC", {}}},
|
|
{"ETH", {"ETH", "GetPositions:ETH", {}}}};
|
|
std::map<std::string, OrderData> curr_ord_map = {
|
|
{"BTC", {"BTC", "GetOrders:BTC", {}}},
|
|
{"ETH", {"ETH", "GetOrders:ETH", {}}}};
|
|
PosData *is_position_cb(const std::string &corrid) {
|
|
for (auto &kv : curr_pos_map) {
|
|
if (kv.second.corrid == corrid) {
|
|
return &kv.second;
|
|
}
|
|
}
|
|
return nullptr;
|
|
}
|
|
OrderData *is_order_cb(const std::string &corrid) {
|
|
for (auto &kv : curr_ord_map) {
|
|
if (kv.second.corrid == corrid) {
|
|
return &kv.second;
|
|
}
|
|
}
|
|
return nullptr;
|
|
}
|
|
std::vector<CCAPIPosition> total_positions() const {
|
|
std::vector<CCAPIPosition> rv = {};
|
|
for (const auto &kv : curr_pos_map) {
|
|
const auto &pos = kv.second.pos_vec;
|
|
rv.insert(rv.end(), pos.begin(), pos.end());
|
|
}
|
|
return rv;
|
|
}
|
|
std::vector<CCAPIExchangeOpenOrder> total_working_orders() const {
|
|
std::vector<CCAPIExchangeOpenOrder> rv = {};
|
|
for (const auto &kv : curr_ord_map) {
|
|
const auto &ords = kv.second.order_vec;
|
|
rv.insert(rv.end(), ords.begin(), ords.end());
|
|
}
|
|
return rv;
|
|
}
|
|
std::set<std::string> get_all_corrids() const {
|
|
std::set<std::string> rv = {};
|
|
for (const auto &kv : curr_pos_map)
|
|
rv.insert(kv.second.corrid);
|
|
for (const auto &kv : curr_ord_map)
|
|
rv.insert(kv.second.corrid);
|
|
return rv;
|
|
}
|
|
};
|
|
|
|
// Since we have to subscribe to the orders and trades for each instrument
|
|
// individually, this struct keeps the state of the subscription. Orders can
|
|
// only be sent once fully_subscribed()
|
|
struct SecOrdersTradesSubscriptionStatus {
|
|
const uint32_t sec_id;
|
|
const std::string order_sub_corr_id;
|
|
const std::string trade_sub_corr_id;
|
|
bool order_sub_confirmed = false;
|
|
bool trade_sub_confirmed = false;
|
|
bool fully_subscribed() const {
|
|
return order_sub_confirmed && trade_sub_confirmed;
|
|
}
|
|
bool update_status(const std::string &corr_id, bool status) {
|
|
if (order_sub_corr_id == corr_id) {
|
|
order_sub_confirmed = status;
|
|
} else if (trade_sub_corr_id == corr_id) {
|
|
trade_sub_confirmed = status;
|
|
}
|
|
return order_sub_confirmed && trade_sub_confirmed;
|
|
}
|
|
};
|
|
|
|
struct CCAPIDeribitOrderMux::PImpl {
|
|
const std::string internal_account;
|
|
CCAPIConnectionConfig::DeribitConnectionConfig d_conn_config;
|
|
const std::string missing_corrid_placeholder = "MISSING_CORRID";
|
|
PositionOrderRequestHelper pos_ord_req_helper = {};
|
|
CorrIDHelper corrid_helper = {};
|
|
md::SecurityOracle sec_oracle;
|
|
ccapi::Session *session = nullptr;
|
|
OnCCAPIOrderUpdate order_update_cb;
|
|
OnCCAPIExchangePositionUpdate exchange_position_update_cb;
|
|
OnCCAPIExchangeOpenOrderUpdate exchange_open_orders_update_cb;
|
|
size_t corr_id = 0;
|
|
std::map<OrderKey, CCAPISingleOrderManager> order_map = {};
|
|
boost::lockfree::spsc_queue<ccapi::Event> incoming_event_queue;
|
|
OrderEventHandler event_handler;
|
|
// map of subscription confirmation for a security
|
|
std::unordered_map<uint32_t, SecOrdersTradesSubscriptionStatus> sub_map = {};
|
|
// if we get a new order for a security that we hve not subscribed to yet
|
|
// (order updates and trades), we buffer the create message and send it once
|
|
// we get subcriptions confirmation
|
|
std::vector<CreateOrderMsg> buffered_creates = {};
|
|
PImpl(
|
|
const CCAPIConnectionConfig &connection_config,
|
|
const md::SecurityOracle &md_oracle)
|
|
: internal_account(connection_config.internal_account),
|
|
sec_oracle(md_oracle), incoming_event_queue(100),
|
|
event_handler(
|
|
incoming_event_queue,
|
|
{ccapi::Event::Type::RESPONSE,
|
|
ccapi::Event::Type::SUBSCRIPTION_DATA,
|
|
ccapi::Event::Type::SUBSCRIPTION_STATUS},
|
|
pos_ord_req_helper.get_all_corrids()) {
|
|
auto has_conn = connection_config.get_deribit_config(d_conn_config);
|
|
bts_assert(has_conn);
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::PImpl::cons client_id: {} client_secret: {} "
|
|
"internal_account: {}",
|
|
d_conn_config.client_id, d_conn_config.client_secret,
|
|
internal_account);
|
|
ccapi::SessionConfigs session_configs;
|
|
session_configs.setCredential({
|
|
{"grant_type", "client_signature"},
|
|
{CCAPI_DERIBIT_CLIENT_ID, d_conn_config.client_id},
|
|
{CCAPI_DERIBIT_CLIENT_SECRET, d_conn_config.client_secret},
|
|
});
|
|
session = new ccapi::Session({}, session_configs, &event_handler);
|
|
}
|
|
};
|
|
|
|
CCAPIDeribitOrderMux::CCAPIDeribitOrderMux(
|
|
const CCAPIConnectionConfig &connection_config,
|
|
const md::SecurityOracle &sec_oracle)
|
|
: me(new PImpl(connection_config, sec_oracle)) {
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::CCAPIDeribitOrderMux constructor t_id: {} "
|
|
"t_name: {} ",
|
|
os::get_thread_id(), os::get_application_name());
|
|
}
|
|
|
|
CCAPIDeribitOrderMux::~CCAPIDeribitOrderMux() {}
|
|
|
|
// The CCAPI interaction wrt public requests, private requests and subscription
|
|
// is as follows
|
|
// Requests:
|
|
// ---------
|
|
// 1.
|
|
// New Order (_send_order function): Builtin Request::Operation::CREATE_ORDER
|
|
// 2.
|
|
// Modify Order (update_order): Private Request::Operation::GENERIC_PRIVATE_REQUEST
|
|
// since could not find a ccapi built in modify operator
|
|
// 3.
|
|
// Cancel Order (cancel_order): Builtin Request::Operation::CANCEL_ORDER
|
|
// 4.
|
|
// Query Position (query_postion): Private Request::Operation::GENERIC_PRIVATE_REQUEST.
|
|
// There is a builtin Request::Operation::GET_ACCOUNT_POSITIONS but it didnt work
|
|
// 5.
|
|
// Query Open Orders (query_open_orders): Private Request::Operation::GENERIC_PRIVATE_REQUEST
|
|
// similiar to above, there is a builtin GET_OPEN_ORDERS which did not work
|
|
// 6.
|
|
// RFQ: Private Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
// Subscriptions:
|
|
// -------------
|
|
// 1.
|
|
// Orders per instrument:
|
|
// CCAPI_EM_ORDER_UPDATE
|
|
// 2.
|
|
// Trades per instrument
|
|
// CCAPI_EM_PRIVATE_TRADE
|
|
|
|
// The event types we get are:
|
|
// ✖ UNKNOWN,
|
|
// Every subscription has a session, the message type associated is
|
|
// SESSION_CONNECTION_UP or SESSION_CONNECTION_DOWN. It recconects
|
|
// automatically so we dont take any action
|
|
// ✖ SESSION_STATUS,
|
|
// Every subscription has a status, the message type associated is
|
|
// SUBSCRIPTION_STARTED or SUBSCRIPTION_FAILURE. We only send orders
|
|
// once we get a SUBSCRIPTION_STATUS event with message type SUBSCRIPTION_STARTED.
|
|
// We do NOT detect SUBSCRIPTION_FAILURE and retry
|
|
// ✔ SUBSCRIPTION_STATUS,
|
|
// REQUEST_STATUS,
|
|
// This a 'response' to a request. The type of Message tells which request, ex
|
|
// CREATE_ORDER, CANCEL_ORDER etc
|
|
// ✔ RESPONSE,
|
|
// As the name says. We have 2 kinds of subscription data (since we have 2 subscriptions)
|
|
// EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE and EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE
|
|
// ✔ SUBSCRIPTION_DATA,
|
|
// ✖ AUTHORIZATION_STATUS,
|
|
// ✖ FIX,
|
|
// ✖ FIX_STATUS,
|
|
|
|
CCAPIOpResult CCAPIDeribitOrderMux::launch_new_order(
|
|
const CreateOrderMsg &cr_msg) {
|
|
// order update subscription
|
|
bool already_subbed = _check_and_add_subscription(*cr_msg.security);
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::launch_new_order tid: {} sec_key: {} ok: {} p: "
|
|
"{} q: {} already_subbed: {}",
|
|
os::get_thread_id(), cr_msg.security->id(), cr_msg.key.value(),
|
|
cr_msg.price, cr_msg.quantity, already_subbed);
|
|
if (already_subbed) {
|
|
_send_order(cr_msg);
|
|
} else {
|
|
me->buffered_creates.push_back(cr_msg);
|
|
}
|
|
// TODO, fire an ex report of waiting
|
|
CCAPIOpResult res{};
|
|
res.is_success = true;
|
|
return res;
|
|
}
|
|
|
|
bool CCAPIDeribitOrderMux::update_order(
|
|
const CancelReplaceOrderMsg &cxl_repl_msg) {
|
|
OrderKey order_key = cxl_repl_msg.create_fields.key;
|
|
LOG(OrderMan, Info, "CCAPIDeribitOrderMux::update_order order_key: {}",
|
|
order_key);
|
|
// CCAPI does not have update/edit/cxl-replace so we have to use custom
|
|
// request for it. The custom GET request URL looks like this
|
|
// "https://test.deribit.com/api/v2/private/edit?advanced=implv&amount=4&order_id=438994&price=222"
|
|
// (https://docs.deribit.com/?shell#private-edit)
|
|
const auto &sec_desc =
|
|
cxl_repl_msg.create_fields.security->deribit().security_desc();
|
|
auto it = me->order_map.find(order_key);
|
|
if (it == me->order_map.end()) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::update_order could not find order_key: "
|
|
"{} sec_desc: {}",
|
|
order_key, sec_desc);
|
|
return false;
|
|
}
|
|
CCAPISingleOrderManager &ord_manager = it->second;
|
|
const CCAPIOrderState &ord_state = ord_manager.order_state();
|
|
double new_qty = cxl_repl_msg.create_fields.quantity.full_value();
|
|
double new_price = cxl_repl_msg.create_fields.price.value();
|
|
std::string query = "amount=" + std::to_string(new_qty) +
|
|
"&order_id=" + ord_state.cc_order_key +
|
|
"&price=" + std::to_string(new_price);
|
|
std::string corrid = me->corrid_helper.get_modify_order_corrid(
|
|
ord_state.order_key, ord_state.n_outgoing_mods);
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, sec_desc, corrid);
|
|
request.appendParam(
|
|
{{CCAPI_HTTP_METHOD, "GET"},
|
|
{CCAPI_HTTP_PATH, "/api/v2/private/edit"},
|
|
{CCAPI_HTTP_QUERY_STRING, query},
|
|
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
|
ord_manager.handle_order_update_out(new_price, new_qty);
|
|
me->session->sendRequest(request);
|
|
return true;
|
|
}
|
|
|
|
void send_cancel_generic_private_request(
|
|
ccapi::Session *session,
|
|
const std::string &cc_order_key,
|
|
const std::string &sec_desc) {
|
|
bts_assert(false);
|
|
LOG(OrderMan, Info,
|
|
"send_cancel_generic_private_request cc_order_key: {} sec_desc: {}",
|
|
cc_order_key, sec_desc);
|
|
//"https://test.deribit.com/api/v2/private/cancel?order_id=ETH-SLIS-12"
|
|
std::string query = "order_id=" + cc_order_key;
|
|
std::string corr_id = "OrderCxl:" + cc_order_key;
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, sec_desc, corr_id);
|
|
request.appendParam(
|
|
{// {CCAPI_HTTP_PROTOCOL, "https"},
|
|
{CCAPI_HTTP_METHOD, "GET"},
|
|
{CCAPI_HTTP_PATH, "/api/v2/private/cancel"},
|
|
{CCAPI_HTTP_QUERY_STRING, query},
|
|
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
|
session->sendRequest(request);
|
|
}
|
|
|
|
bool CCAPIDeribitOrderMux::cancel_order(const CancelOrderMsg &cxl_msg) {
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::cancel_order order_key: {} cc_order_key: {}",
|
|
cxl_msg.key, cxl_msg.exchange_order_id);
|
|
auto it = me->order_map.find(cxl_msg.key);
|
|
if (it == me->order_map.end()) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::cancel_order could not find order_key: {}",
|
|
cxl_msg.key);
|
|
return false;
|
|
}
|
|
CCAPISingleOrderManager &order_man = it->second;
|
|
std::string corrid = me->corrid_helper.get_cancel_order_corrid(cxl_msg.key);
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::CANCEL_ORDER, CCAPI_EXCHANGE_NAME_DERIBIT, "",
|
|
corrid);
|
|
request.appendParam(
|
|
{{CCAPI_EM_ORDER_ID, order_man.order_state().cc_order_key}});
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::cancel_order order_key: {} cc_order_key: {}",
|
|
order_man.order_state().order_key, order_man.order_state().cc_order_key);
|
|
me->session->sendRequest(request);
|
|
return true;
|
|
}
|
|
|
|
void CCAPIDeribitOrderMux::send_rfq(const RFQMsg &rfq) {
|
|
LOG(OrderMan, Info, "CCAPIDeribitOrderMux::send_rfq rfq: {}",
|
|
utils::pb::to_string(rfq.rfq));
|
|
// to create
|
|
// ws:
|
|
// privte/create_combo
|
|
// {
|
|
// "method": "private/create_combo",
|
|
// "params": {
|
|
// "trades": [
|
|
// {
|
|
// "instrument_name": "BTC-10MAY23-25000-C",
|
|
// "amount": "1",
|
|
// "direction": "buy"
|
|
// },
|
|
// {
|
|
// "instrument_name": "BTC-10MAY23-25000-P",
|
|
// "amount": "1",
|
|
// "direction": "buy"
|
|
// }
|
|
// ]
|
|
// },
|
|
// "jsonrpc": "2.0",
|
|
// "id": 10
|
|
// }
|
|
// to rfq
|
|
// private/send_rfq
|
|
// {
|
|
// "method": "private/send_rfq",
|
|
// "params": {
|
|
// "instrument_name": "BTC-FS-29SEP23_26MAY23",
|
|
// "amount": 1
|
|
// },
|
|
// "jsonrpc": "2.0",
|
|
// "id": 15
|
|
// }
|
|
// get
|
|
// https://test.deribit.com/api/v2/private/send_rfq?amount=1&instrument_name=BTC-FS-29SEP23_26MAY23
|
|
if (rfq.rfq.has_security()) {
|
|
const auto &sec = rfq.rfq.security();
|
|
if (sec.has_security_id()) {
|
|
// Security's ID being populated is a signal that its an existing security
|
|
// so we just need to send an RFQ instead of creating it
|
|
const api::Security *sec_ptr =
|
|
me->sec_oracle.get_security(SecurityKey(sec.security_id()));
|
|
if (sec_ptr != nullptr) {
|
|
if (!sec_ptr->has_deribit()) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::send_rfq !sec_ptr->has_deribit()");
|
|
return;
|
|
}
|
|
const auto &exch_desc = sec_ptr->deribit().security_desc();
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::send_rfq sending RFQ for {}", exch_desc);
|
|
std::string corrid = "RFQ:" + exch_desc;
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, exch_desc, corrid);
|
|
std::string query =
|
|
"amount=" + std::to_string(rfq.rfq.quantity().qty()) +
|
|
"&instrument_name=" + exch_desc;
|
|
request.appendParam(
|
|
{{CCAPI_HTTP_METHOD, "GET"},
|
|
{CCAPI_HTTP_PATH, "/api/v2/private/send_rfq?"},
|
|
{CCAPI_HTTP_QUERY_STRING, query},
|
|
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
|
me->session->sendRequest(request);
|
|
} else {
|
|
LOG(OrderMan, Error,
|
|
"IEMOrderMuxer::send_rfq could not find security for bts "
|
|
"sec_id: {}",
|
|
sec.security_id());
|
|
}
|
|
} else {
|
|
// TODO: create combo
|
|
}
|
|
} else {
|
|
LOG(OrderMan, Error,
|
|
"IEMOrderMuxer::send_rfq could not send RFQ since security is not "
|
|
"set");
|
|
}
|
|
}
|
|
|
|
OnCCAPIOrderUpdate &CCAPIDeribitOrderMux::order_update_cb() {
|
|
return me->order_update_cb;
|
|
}
|
|
|
|
// this gets called in the main thread, the events have already been queue'd
|
|
// from the CCAPI callback thread
|
|
void CCAPIDeribitOrderMux::dispatch_incoming_messages() {
|
|
if (me->incoming_event_queue.empty())
|
|
return;
|
|
for (auto &kv : me->order_map)
|
|
kv.second.dispatch_start();
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::dispatch_incoming_messages n_items: {}",
|
|
me->incoming_event_queue.read_available());
|
|
me->incoming_event_queue.consume_all(
|
|
[this](const ccapi::Event &ev) { _handle_event(ev); });
|
|
for (auto &kv : me->order_map) {
|
|
auto ord_ch = kv.second.dispatch_end();
|
|
if (ord_ch) {
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::dispatch_incoming_messages firing "
|
|
"order_update_cb ord: {}",
|
|
kv.second.order_state());
|
|
me->order_update_cb(kv.second.order_state());
|
|
}
|
|
}
|
|
//TODO: delete terminal state orders
|
|
}
|
|
|
|
// Position
|
|
|
|
void CCAPIDeribitOrderMux::query_positions() {
|
|
LOG(OrderMan, Info, "CCAPIDeribitOrderMux::query_positions");
|
|
std::vector<ccapi::Request> reqs = {};
|
|
bool generic_req = true;
|
|
if (generic_req) {
|
|
for (const auto &kv : me->pos_ord_req_helper.curr_pos_map) {
|
|
const PositionOrderRequestHelper::PosData &curr_pos = kv.second;
|
|
const std::string &corrid = curr_pos.corrid;
|
|
std::string pos_query = "currency=" + curr_pos.currency;
|
|
// https://test.deribit.com/api/v2/private/get_positions?currency=BTC
|
|
ccapi::Request pos_request(
|
|
ccapi::Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, "", corrid);
|
|
pos_request.appendParam(
|
|
{{CCAPI_HTTP_METHOD, "GET"},
|
|
{CCAPI_HTTP_PATH, "/api/v2/private/get_positions"},
|
|
{CCAPI_HTTP_QUERY_STRING, pos_query},
|
|
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
|
reqs.push_back(pos_request);
|
|
}
|
|
} else {
|
|
// didnt work !
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::GET_ACCOUNT_POSITIONS,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, "", "corrid");
|
|
request.appendParam({{"CCAPI_HTTP_QUERY_STRING", "currency=BTC"}});
|
|
reqs.push_back(request);
|
|
}
|
|
me->session->sendRequest(reqs);
|
|
}
|
|
|
|
OnCCAPIExchangePositionUpdate &
|
|
CCAPIDeribitOrderMux::exchange_position_update_cb() {
|
|
return me->exchange_position_update_cb;
|
|
}
|
|
|
|
// Open orders
|
|
|
|
void CCAPIDeribitOrderMux::query_open_orders() {
|
|
LOG(OrderMan, Info, "CCAPIDeribitOrderMux::query_open_orders");
|
|
std::vector<ccapi::Request> reqs = {};
|
|
for (const auto &kv : me->pos_ord_req_helper.curr_ord_map) {
|
|
const PositionOrderRequestHelper::OrderData &curr_ord = kv.second;
|
|
const std::string &corrid = curr_ord.corrid;
|
|
std::string ord_query = "currency=" + curr_ord.currency;
|
|
// https://test.deribit.com/api/v2/private/get_open_orders_by_currency?currency=BTC
|
|
ccapi::Request ord_request(
|
|
ccapi::Request::Operation::GENERIC_PRIVATE_REQUEST,
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, "", corrid);
|
|
ord_request.appendParam(
|
|
{{CCAPI_HTTP_METHOD, "GET"},
|
|
{CCAPI_HTTP_PATH, "/api/v2/private/get_open_orders_by_currency"},
|
|
{CCAPI_HTTP_QUERY_STRING, ord_query},
|
|
{CCAPI_HTTP_HEADERS, "Content-Type: application/json"}});
|
|
reqs.push_back(ord_request);
|
|
}
|
|
me->session->sendRequest(reqs);
|
|
}
|
|
|
|
OnCCAPIExchangeOpenOrderUpdate &
|
|
CCAPIDeribitOrderMux::exchange_open_orders_update_cb() {
|
|
return me->exchange_open_orders_update_cb;
|
|
}
|
|
|
|
// private functions //////////////////////////////////////////////////////////
|
|
///////////////////////////////////////////////////////////////////////////////
|
|
|
|
// Checks if an orders/trade subscription exists, if not it adds both the subs
|
|
// and returns false. If it already exists, returns true
|
|
bool CCAPIDeribitOrderMux::_check_and_add_subscription(
|
|
const api::Security &sec) {
|
|
auto it = me->sub_map.find(sec.id());
|
|
if (it == me->sub_map.end()) {
|
|
const auto &sec_desc = sec.deribit().security_desc();
|
|
auto order_status_sub_corrid = "OrderSub:" + sec_desc;
|
|
auto trade_sub_corrid = "TradeSub:" + sec_desc;
|
|
SecOrdersTradesSubscriptionStatus new_status{
|
|
sec.id(), order_status_sub_corrid, trade_sub_corrid};
|
|
me->sub_map.insert({sec.id(), new_status});
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_check_and_add_subscription "
|
|
"CCAPI_EM_ORDER_UPDATE and CCAPI_EM_PRIVATE_TRADE "
|
|
"subscriptions for "
|
|
"sec: {} order_status_sub_corrid: {} trade_sub_corrid: {}",
|
|
sec_desc, order_status_sub_corrid, trade_sub_corrid);
|
|
// this is the only subscription we have in deribit execution code
|
|
std::vector<ccapi::Subscription> subs = {};
|
|
subs.emplace_back(
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, sec_desc, CCAPI_EM_ORDER_UPDATE, "",
|
|
order_status_sub_corrid);
|
|
subs.emplace_back(
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, sec_desc, CCAPI_EM_PRIVATE_TRADE, "",
|
|
trade_sub_corrid);
|
|
me->session->subscribe(subs);
|
|
return false;
|
|
} else {
|
|
return it->second.fully_subscribed();
|
|
}
|
|
}
|
|
|
|
// (Unused) this is supposed to subscribe for all instruments at once
|
|
// but does not work
|
|
void CCAPIDeribitOrderMux::_subscribe_to_order_callbacks() {
|
|
// this is not working
|
|
bts_assert(false);
|
|
std::vector<string> channels = {"user.orders.any.any.raw"};
|
|
const nlohmann::json opts_json{
|
|
{"method", "private/subscribe"},
|
|
{"params",
|
|
nlohmann::json{
|
|
{"channels", vector<string>{channels.begin(), channels.end()}},
|
|
//{"access_token", access_token}
|
|
// access_token here ?
|
|
}},
|
|
{"jsonrpc", "2.0"},
|
|
{"id", 999},
|
|
};
|
|
|
|
const auto opts_str = opts_json.dump(2);
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_subscribe_to_order_callbacks sub: {}", opts_str);
|
|
ccapi::Subscription sub(
|
|
CCAPI_EXCHANGE_NAME_DERIBIT, "", CCAPI_GENERIC_PUBLIC_SUBSCRIPTION,
|
|
opts_str, "AllOrdersSub");
|
|
me->session->subscribe(sub);
|
|
}
|
|
|
|
template <class ProcFunc>
|
|
void process_event(const ccapi::Event &event, const ProcFunc &func) {
|
|
auto get_corr_id = [&](const ccapi::Message &msg, size_t idx) {
|
|
const auto &corr_list = msg.getCorrelationIdList();
|
|
// TODO: not sure about this, why isnt corr id a part of Element
|
|
return idx < corr_list.size() ? corr_list.at(idx)
|
|
: "me->missing_corrid_placeholder";
|
|
};
|
|
for (const auto &msg : event.getMessageList()) {
|
|
ccapi::Message::Type msg_type = msg.getType();
|
|
size_t i = 0;
|
|
for (const auto &elem : msg.getElementList()) {
|
|
const std::string &corr_id = get_corr_id(msg, i++);
|
|
func(msg_type, elem, corr_id);
|
|
}
|
|
}
|
|
}
|
|
|
|
void log_unhandled_msg(
|
|
ccapi::Message::Type msg_type,
|
|
const ccapi::Element &element,
|
|
const std::string &log) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::log_unhandled_msg {} msg: {} element: {}", log,
|
|
ccapi::Message::typeToString(msg_type), element.toStringPretty());
|
|
}
|
|
|
|
// There are only 3 types of events we handle
|
|
void CCAPIDeribitOrderMux::_handle_event(const ccapi::Event &event) {
|
|
ccapi::Event::Type event_type = event.getType();
|
|
switch (event_type) {
|
|
case ccapi::Event::Type::SUBSCRIPTION_STATUS:
|
|
process_event(
|
|
event,
|
|
[&](ccapi::Message::Type msg_type, const ccapi::Element &element,
|
|
const std::string &corr_id) {
|
|
_handle_SUBSCRIPTION_STATUS_event(msg_type, element, corr_id);
|
|
});
|
|
break;
|
|
case ccapi::Event::Type::SUBSCRIPTION_DATA:
|
|
process_event(
|
|
event,
|
|
[&](ccapi::Message::Type msg_type, const ccapi::Element &element,
|
|
const std::string &corr_id) {
|
|
_handle_SUBSCRIPTION_DATA_event(msg_type, element, corr_id);
|
|
});
|
|
break;
|
|
case ccapi::Event::Type::RESPONSE:
|
|
process_event(
|
|
event,
|
|
[&](ccapi::Message::Type msg_type, const ccapi::Element &element,
|
|
const std::string &corr_id) {
|
|
_handle_RESPONSE_event(msg_type, element, corr_id);
|
|
});
|
|
break;
|
|
default:
|
|
// assert
|
|
LOG(OrderMan, Fatal,
|
|
"CCAPIDeribitOrderMux::_handle_event Unhandled event: {}",
|
|
event.toStringPretty());
|
|
break;
|
|
}
|
|
}
|
|
|
|
void CCAPIDeribitOrderMux::_handle_SUBSCRIPTION_STATUS_event(
|
|
ccapi::Message::Type msg_type,
|
|
const ccapi::Element &element,
|
|
const std::string &corrid) {
|
|
switch (msg_type) {
|
|
case ccapi::Message::Type::SUBSCRIPTION_STARTED: {
|
|
CCAPISubscriptionStatusMsg sub_status_msg{true, corrid};
|
|
_handle_subscription_status(sub_status_msg);
|
|
break;
|
|
}
|
|
case ccapi::Message::Type::SUBSCRIPTION_FAILURE: {
|
|
CCAPISubscriptionStatusMsg sub_status_msg{false, corrid};
|
|
_handle_subscription_status(sub_status_msg);
|
|
break;
|
|
}
|
|
default:
|
|
log_unhandled_msg(msg_type, element, "_handle_SUBSCRIPTION_STATUS_event");
|
|
break;
|
|
}
|
|
}
|
|
void CCAPIDeribitOrderMux::_handle_RESPONSE_event(
|
|
ccapi::Message::Type msg_type,
|
|
const ccapi::Element &element,
|
|
const std::string &corrid) {
|
|
const auto &map = element.getNameValueMap();
|
|
switch (msg_type) {
|
|
case ccapi::Message::Type::CREATE_ORDER: {
|
|
CCAPICreateOrderMsg cr_ord_msg(map, corrid);
|
|
for (auto &kv : me->order_map)
|
|
kv.second.handle_create_reponse(cr_ord_msg);
|
|
break;
|
|
}
|
|
case ccapi::Message::Type::CANCEL_ORDER: {
|
|
// we look for order canellation in the order callback event,
|
|
// so this is a no-op
|
|
}
|
|
case ccapi::Message::Type::GENERIC_PRIVATE_REQUEST: {
|
|
// position request, open order request.
|
|
PositionOrderRequestHelper::PosData *pos_data =
|
|
me->pos_ord_req_helper.is_position_cb(corrid);
|
|
if (pos_data != nullptr) {
|
|
pos_data->pos_vec.clear();
|
|
CCAPIDeribitHelpers::parse_open_position(
|
|
element, me->internal_account, pos_data->pos_vec);
|
|
me->exchange_position_update_cb(
|
|
me->pos_ord_req_helper.total_positions());
|
|
return;
|
|
}
|
|
PositionOrderRequestHelper::OrderData *ord_data =
|
|
me->pos_ord_req_helper.is_order_cb(corrid);
|
|
if (ord_data != nullptr) {
|
|
ord_data->order_vec.clear();
|
|
CCAPIDeribitHelpers::parse_working_position(
|
|
element, me->d_conn_config.client_id, me->internal_account,
|
|
ord_data->order_vec);
|
|
me->exchange_open_orders_update_cb(
|
|
me->pos_ord_req_helper.total_working_orders());
|
|
return;
|
|
}
|
|
// there are other GENERIC_PRIVATE_REQUEST that we dont care about:
|
|
// order modofiction request, rfq send request
|
|
// and combo create request
|
|
break;
|
|
}
|
|
case ccapi::Message::Type::RESPONSE_ERROR: {
|
|
// the only RESPONSE_ERROR we are interested in is when order
|
|
// submission fails, therefore we check for corrid
|
|
// should we watch for order modification and cancel errors ?
|
|
auto key = me->corrid_helper.parse_create_order_corrid(corrid);
|
|
if (key == std::nullopt) {
|
|
return;
|
|
}
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::_handle_RESPONSE_event order entry error key: "
|
|
"{}",
|
|
key->value());
|
|
auto it = me->order_map.find(OrderKey(key->value()));
|
|
if (it == me->order_map.end()) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::_handle_RESPONSE_event order entry error, "
|
|
"Could not find key: "
|
|
"{}",
|
|
key->value());
|
|
return;
|
|
}
|
|
auto err = CCAPICreateOrderErrorMsg::parse(element, corrid);
|
|
if (err == std::nullopt) {
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::_handle_RESPONSE_event order entry error, "
|
|
"Could not parse message: {}",
|
|
key->value());
|
|
}
|
|
it->second.handle_create_error(err.value());
|
|
break;
|
|
}
|
|
default:
|
|
log_unhandled_msg(msg_type, element, "_handle_RESPONSE_event");
|
|
break;
|
|
}
|
|
}
|
|
|
|
void CCAPIDeribitOrderMux::_handle_SUBSCRIPTION_DATA_event(
|
|
ccapi::Message::Type msg_type,
|
|
const ccapi::Element &element,
|
|
const std::string &) {
|
|
const auto &map = element.getNameValueMap();
|
|
switch (msg_type) {
|
|
case ccapi::Message::Type::EXECUTION_MANAGEMENT_EVENTS_ORDER_UPDATE: {
|
|
CCAPIOrderUpdateMsg ord_update_msg(map);
|
|
for (auto &kv : me->order_map)
|
|
kv.second.handle_order_sub_update(ord_update_msg);
|
|
break;
|
|
}
|
|
case ccapi::Message::Type::EXECUTION_MANAGEMENT_EVENTS_PRIVATE_TRADE: {
|
|
CCAPITradeMsg tr_msg(map);
|
|
for (auto &kv : me->order_map)
|
|
kv.second.handle_trade_sub_update(tr_msg);
|
|
break;
|
|
}
|
|
default:
|
|
log_unhandled_msg(msg_type, element, "_handle_SUBSCRIPTION_DATA_event");
|
|
break;
|
|
}
|
|
}
|
|
|
|
void CCAPIDeribitOrderMux::_handle_subscription_status(
|
|
const CCAPISubscriptionStatusMsg &ss_msg) {
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_handle_subscription_status status: {} "
|
|
"corr_id: {}",
|
|
ss_msg.is_success, ss_msg.corr_id);
|
|
if (ss_msg.is_success) {
|
|
// 1. update the subscription state
|
|
// 2. find the orders for the secs that are fully subscribed now
|
|
// 3. send the orders
|
|
// 4. remove them from cached orders
|
|
for (auto &kv : me->sub_map) {
|
|
SecOrdersTradesSubscriptionStatus &ss = kv.second;
|
|
auto subbed = ss.update_status(ss_msg.corr_id, ss_msg.is_success);
|
|
if (subbed) {
|
|
_send_buffered_orders(ss.sec_id);
|
|
}
|
|
}
|
|
} else {
|
|
// will figure this out later
|
|
LOG(OrderMan, Error,
|
|
"CCAPIDeribitOrderMux::_handle_subscription_status corr_id: {} "
|
|
"is_success: {}",
|
|
ss_msg.corr_id, ss_msg.is_success);
|
|
}
|
|
}
|
|
|
|
void CCAPIDeribitOrderMux::_send_order(const CreateOrderMsg &cr_msg) {
|
|
auto get_tif = [&]() {
|
|
switch (cr_msg.time_in_force) {
|
|
case (api::orderman::TimeInForce::TIME_IN_FORCE_IOC):
|
|
return "immediate_or_cancel";
|
|
case (api::orderman::TimeInForce::TIME_IN_FORCE_DAY):
|
|
return "good_til_day";
|
|
case (api::orderman::TimeInForce::TIME_IN_FORCE_GTC):
|
|
return "good_til_cancelled";
|
|
default:
|
|
return "good_til_cancelled";
|
|
}
|
|
};
|
|
const auto &sec_desc = cr_msg.security->deribit().security_desc();
|
|
ccapi::Request request(
|
|
ccapi::Request::Operation::CREATE_ORDER, CCAPI_EXCHANGE_NAME_DERIBIT,
|
|
sec_desc);
|
|
std::string corrid = me->corrid_helper.get_create_order_corrid(
|
|
cr_msg.key, (cr_msg.security == nullptr
|
|
? "NOSEC"
|
|
: cr_msg.security->deribit().security_desc()));
|
|
me->order_map.insert(
|
|
{cr_msg.key, CCAPISingleOrderManager(
|
|
*cr_msg.security, cr_msg.key, corrid, cr_msg.side,
|
|
cr_msg.price.value(), cr_msg.quantity.full_value())});
|
|
request.setCorrelationId(corrid);
|
|
request.appendParam({
|
|
{CCAPI_EM_ORDER_SIDE, cr_msg.side == api::SIDE_BUY
|
|
? CCAPI_EM_ORDER_SIDE_BUY
|
|
: CCAPI_EM_ORDER_SIDE_SELL},
|
|
{CCAPI_EM_ORDER_QUANTITY, std::to_string(cr_msg.quantity.full_value())},
|
|
{CCAPI_EM_ORDER_LIMIT_PRICE, std::to_string(cr_msg.price.value())},
|
|
{"time_in_force", get_tif()},
|
|
});
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_send_order sec: {} key: {} p: {} q: {}",
|
|
sec_desc, cr_msg.key, cr_msg.price, cr_msg.quantity);
|
|
me->session->sendRequest(request);
|
|
}
|
|
|
|
// new orders that did not have a subscription were buffered in the
|
|
// buffered_creates vector. this gets a sec_id because subscriptions
|
|
// to orders / trades are for instrument
|
|
void CCAPIDeribitOrderMux::_send_buffered_orders(uint32_t sec_id) {
|
|
for (const auto &cr_msg : me->buffered_creates) {
|
|
if (cr_msg.security->id() == sec_id) {
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_send_buffered_orders sending "
|
|
"buffered "
|
|
"order key: {}",
|
|
cr_msg.key.value());
|
|
_send_order(cr_msg);
|
|
}
|
|
}
|
|
me->buffered_creates.erase(
|
|
std::remove_if(
|
|
me->buffered_creates.begin(), me->buffered_creates.end(),
|
|
[sec_id](const CreateOrderMsg &c) {
|
|
return c.security->id() == sec_id;
|
|
}),
|
|
me->buffered_creates.end());
|
|
LOG(OrderMan, Info,
|
|
"CCAPIDeribitOrderMux::_send_buffered_orders "
|
|
"n_buffered_orders: {}",
|
|
me->buffered_creates.size());
|
|
}
|
|
} // namespace bts::orderman
|
|
|
|
#endif
|