diff --git a/src/lib/api/service_helpers/AdminServiceUtils.cpp b/src/lib/api/service_helpers/AdminServiceUtils.cpp index 5f55af65c..d4c03ad06 100644 --- a/src/lib/api/service_helpers/AdminServiceUtils.cpp +++ b/src/lib/api/service_helpers/AdminServiceUtils.cpp @@ -160,7 +160,9 @@ AdminServiceUtils::resolve_connection( case api::Venue::VENUE_SIMICE: rv = resolve_sim_connection(data, account, sec); break; - case api::Venue::VENUE_DERIBIT: // TODO + case api::Venue::VENUE_DERIBIT: + rv = resolve_sim_connection(data, account, sec); + break; case api::Venue::VENUE_CBOE: case api::Venue::VENUE_CBOECFE: case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_: @@ -522,6 +524,21 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record( return rv; } switch (sec.exchange()) { + case api::Venue::VENUE_DERIBIT: { + rv.set_session("sim"); + rv.set_account(account_ptr->name()); + rv.set_operator_id(user_ptr->name()); + AdminServiceUtils::ExchangeSubAccountResolver resolver; + auto sub_acc_ptr = resolver.find_entry(&sec, account_ptr->name(), true); + if (!sub_acc_ptr) { + out_result.set_is_success(false); + out_result.set_error_text("Could not resolve sub account"); + return rv; + } + rv.set_account_code(sub_acc_ptr->exchange_subaccount()); + out_result.set_is_success(true); + return rv; + } case api::Venue::VENUE_ICE: { const bts::api::admin::ICEUserData *ice_user_data = get_user_ice_data(*user_ptr, data); @@ -669,7 +686,6 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record( rv.set_customer_or_firm(sim_account_data->origin()); return rv; } break; - case api::Venue::VENUE_DERIBIT: case api::Venue::VENUE_UNSET: case api::Venue::VENUE_BTS: case api::Venue::VENUE_CBOE: diff --git a/src/lib/api/service_helpers/AdminServiceUtils.h b/src/lib/api/service_helpers/AdminServiceUtils.h index 7b8a281e7..551165bd7 100644 --- a/src/lib/api/service_helpers/AdminServiceUtils.h +++ b/src/lib/api/service_helpers/AdminServiceUtils.h @@ -2,7 +2,10 @@ #include "lib/api/services/AdminService.server.pb.h" #include "lib/api/services/OrderService.server.pb.h" +#include "lib/config/config.h" +#include "lib/config/protos/toggles.pb.h" #include "lib/domain_model/Security.h" +#include "lib/utils/PBUtils.h" #include namespace bts { @@ -13,6 +16,32 @@ using namespace bts::api::orderman; class AdminServiceUtils { public: + struct ExchangeSubAccountResolver { + const bts::config::toggles::ExchangeSubAccounts exch_sub_accounts; + ExchangeSubAccountResolver() + : exch_sub_accounts( + config::get()) { + LOG(OrderMan, Info, + "ExchangeSubAccountResolver::cons exch_sub_accounts: {}", + utils::pb::to_string(exch_sub_accounts)); + } + bts::config::toggles::ExchangeSubAccountUnit const *find_entry( + api::Security const *sec, + const std::string &account, + bool is_int_account) { + auto get_account = [&](const auto &entry) { + return is_int_account ? entry.bts_account_name() + : entry.exchange_subaccount(); + }; + if (sec == nullptr) + return nullptr; + for (const auto &u : exch_sub_accounts.accounts()) { + if (u.exchange() == sec->exchange() && get_account(u) == account) + return &u; + } + return nullptr; + } + }; //////////////////////////////////////////// // connection accessors //////////////////// //////////////////////////////////////////// @@ -20,11 +49,11 @@ class AdminServiceUtils { // (todo: deleted connections) static uint32_t find_max_connection_id(const AdminData &data); // finds a connection by name and returns a mutable pointer to it - static const ExchangeConnection * - find_connection(const AdminData &data, const std::string &connection_name); + static const ExchangeConnection *find_connection( + const AdminData &data, const std::string &connection_name); // finds the presence of an exchange in a connection - static bool - has_exchange(const ExchangeConnection &conn, bts::api::Venue exchange); + static bool has_exchange( + const ExchangeConnection &conn, bts::api::Venue exchange); // finds the default connections for an exchange // in a given account static const ExchangeConnection *find_default_account_connection( @@ -51,8 +80,8 @@ class AdminServiceUtils { // connection mutators ///////////////////// //////////////////////////////////////////// // adds a new connection (does not check for name uniqueness) - static ExchangeConnection * - add_connection(AdminData &data, const ExchangeConnection &new_connection); + static ExchangeConnection *add_connection( + AdminData &data, const ExchangeConnection &new_connection); // reads the connections from config and fills in the // admin data (with names only) static void fill_connections_from_config(AdminData &admin_data); @@ -65,8 +94,8 @@ class AdminServiceUtils { AdminData &data, const std::string &acct_name, bool include_deleted = false); - static std::map - get_clearing_account_map(const AdminData &); + static std::map get_clearing_account_map( + const AdminData &); // finds the account from a clearing account (and its venue) static BTSAccount const *find_account( @@ -80,27 +109,27 @@ class AdminServiceUtils { bool include_deleted = false); // finds the account from the id and returns // a mutable pointer to the account - static BTSAccount * - find_account(AdminData &data, uint32_t id, bool include_deleted = false); + static BTSAccount *find_account( + AdminData &data, uint32_t id, bool include_deleted = false); // like above but returns a const pointer static const BTSAccount *find_account( const AdminData &data, uint32_t id, bool include_deleted = false); // this function is an indirection layer for account access // so deletions are dealt in a more deliberate manner - static std::vector - accounts(const AdminData &data, bool include_deleted); - static std::vector - accounts_mutable(AdminData &data, bool include_deleted); + static std::vector accounts( + const AdminData &data, bool include_deleted); + static std::vector accounts_mutable( + AdminData &data, bool include_deleted); // finds the max id amongts all the existing accounts static uint32_t find_max_acct_id(const AdminData &data); // gets the account data for cme (and goes up the hierarchy // if needed) - static const CMEAccountData * - get_account_cme_data(const BTSAccount &account, const AdminData &data); - static const ICEAccountData * - get_account_ice_data(const BTSAccount &account, const AdminData &data); - static const SIMAccountData * - get_account_sim_data(const BTSAccount &account, const AdminData &data); + static const CMEAccountData *get_account_cme_data( + const BTSAccount &account, const AdminData &data); + static const ICEAccountData *get_account_ice_data( + const BTSAccount &account, const AdminData &data); + static const SIMAccountData *get_account_sim_data( + const BTSAccount &account, const AdminData &data); // returns true if an account has a connection bool static account_has_connection( const BTSAccount &account, const std::string &connection_name); @@ -158,28 +187,28 @@ class AdminServiceUtils { // this is not a generally useful function but since // connection are in config, this cleans up the account's // connections and syncs it with the list in AdminData - static void - sync_account_connections(const AdminData &data, BTSAccount &account); + static void sync_account_connections( + const AdminData &data, BTSAccount &account); //////////////////////////////////////////// // group accessors ///////////////////////// //////////////////////////////////////////// // given an id, finds the mutable pointer to a group static BTSUserGroup *find_group(AdminData &data, uint32_t id); // given an id, finds the const pointer to a group - static const BTSUserGroup *const - find_group(const AdminData &data, uint32_t id); + static const BTSUserGroup *const find_group( + const AdminData &data, uint32_t id); // given a name, finds the mutable pointer to a group - static BTSUserGroup * - find_group(AdminData &data, const std::string &group_name); + static BTSUserGroup *find_group( + AdminData &data, const std::string &group_name); // finds the max id out of all the groups static uint32_t find_max_group_id(const AdminData &data); // travels up the group tree until it finds a populated cme data - static const CMEUserData * - get_group_cme_data(const BTSUserGroup &group, const AdminData &data); - static const ICEUserData * - get_group_ice_data(const BTSUserGroup &group, const AdminData &data); - static const SIMUserData * - get_group_sim_data(const BTSUserGroup &group, const AdminData &data); + static const CMEUserData *get_group_cme_data( + const BTSUserGroup &group, const AdminData &data); + static const ICEUserData *get_group_ice_data( + const BTSUserGroup &group, const AdminData &data); + static const SIMUserData *get_group_sim_data( + const BTSUserGroup &group, const AdminData &data); static const UserAccountPermissions *const get_group_user_permissions( const bts::api::admin::AdminData &admin_data, uint32_t group_id); //////////////////////////////////////////// @@ -201,21 +230,21 @@ class AdminServiceUtils { const AdminData &data, const std::string &user_name, bool include_deleted = false); - static BTSUser * - find_user(AdminData &data, uint32_t id, bool include_deleted = false); - static const BTSUser *const - find_user(const AdminData &data, uint32_t id, bool include_deleted = false); - static std::vector - users(const AdminData &data, bool include_deleted); - static std::vector - users_mutable(AdminData &data, bool include_deleted); + static BTSUser *find_user( + AdminData &data, uint32_t id, bool include_deleted = false); + static const BTSUser *const find_user( + const AdminData &data, uint32_t id, bool include_deleted = false); + static std::vector users( + const AdminData &data, bool include_deleted); + static std::vector users_mutable( + AdminData &data, bool include_deleted); static uint32_t find_max_user_id(const AdminData &data); - static const CMEUserData * - get_user_cme_data(const BTSUser &user, const AdminData &data); - static const ICEUserData * - get_user_ice_data(const BTSUser &user, const AdminData &data); - static const SIMUserData * - get_user_sim_data(const BTSUser &user, const AdminData &data); + static const CMEUserData *get_user_cme_data( + const BTSUser &user, const AdminData &data); + static const ICEUserData *get_user_ice_data( + const BTSUser &user, const AdminData &data); + static const SIMUserData *get_user_sim_data( + const BTSUser &user, const AdminData &data); // finds the "exchange user" (ex: "operator_id" at CME or "authorized_trader" // at ICE) for a user static std::string find_user_exchange_id( @@ -243,8 +272,8 @@ class AdminServiceUtils { // for a given user finds the account permissions (if permissions are // derived from the group, it traverses the group hierarcy to find the // correct permissions. - static const UserAccountPermissions * - get_user_permissions(const AdminData &admin_data, uint32_t user_id); + static const UserAccountPermissions *get_user_permissions( + const AdminData &admin_data, uint32_t user_id); // for a given user, fills in the associated_accounts ref arg // with the accounts the user has permission to trade in static void find_user_trading_accounts( @@ -310,12 +339,12 @@ class AdminServiceUtils { //////////////////////////////////////////// // sorting function used by sort_limits to // sort SecurityScope's - static bool - _sort_security_scopes(const SecurityScope &a, const SecurityScope &b); + static bool _sort_security_scopes( + const SecurityScope &a, const SecurityScope &b); // sorting function used by sort_limits to // sort ProductScope's - static bool - _sort_product_scopes(const ProductScope &a, const ProductScope &); + static bool _sort_product_scopes( + const ProductScope &a, const ProductScope &); // this sorts the rules such that the most // specific ones are at the top. this makes it // easier to match rules with securities/products @@ -335,10 +364,10 @@ class AdminServiceUtils { const BTSAccount &account, const api::Product &product); static bool match_security_scope( const SecurityScope &scope, const api::Security &security); - static bool - match_product_scope(const ProductScope &scope, const api::Product &product); - static bool - match_product(const api::Security &security, const api::Product &product); + static bool match_product_scope( + const ProductScope &scope, const api::Product &product); + static bool match_product( + const api::Security &security, const api::Product &product); static bool _match_limit_rule_symbol( const std::string &symbol, const std::string &limit_symbol); static api::SecurityType security_type(const api::Security &security); @@ -354,6 +383,6 @@ class AdminServiceUtils { double mult = 1.0); // returns true if this spread effects the position of any outrights static bool residual_pos_spread(const api::Security &s); -}; +}; } // namespace admin } // namespace bts diff --git a/src/lib/config/defaults/toggles.conf b/src/lib/config/defaults/toggles.conf index bb88e5395..79d8973b2 100644 --- a/src/lib/config/defaults/toggles.conf +++ b/src/lib/config/defaults/toggles.conf @@ -84,6 +84,21 @@ value{ } } +ExchangeSubAccounts { +value{ + accounts{ + exchange: VENUE_DERIBIT + exchange_subaccount: "ZmIKL6fb" + bts_account_name: "MAIN" + } + accounts{ + exchange: VENUE_DERIBIT + exchange_subaccount: "v1iSzZrY" + bts_account_name: "SMALL" + } +} +} + VolSurfaceUsage { value{ vol_surface_usage{ diff --git a/src/lib/config/protos/toggles.proto b/src/lib/config/protos/toggles.proto index 34ba7be19..31595b8f4 100644 --- a/src/lib/config/protos/toggles.proto +++ b/src/lib/config/protos/toggles.proto @@ -99,6 +99,17 @@ message DefaultAccount{ repeated DefaultAccountUnit default_accounts = 1; } +// this ultimately needs to go to risk admin: sub_account -> account +message ExchangeSubAccountUnit{ + optional bts.api.Venue exchange = 1; + optional string exchange_subaccount = 10; + optional string bts_account_name = 20; +} + +message ExchangeSubAccounts{ + repeated ExchangeSubAccountUnit accounts = 1; +} + message VolSurfaceUsageUnit{ // This is a temporary config optional string option_name = 1; diff --git a/src/lib/orderman/OrderRouter.cpp b/src/lib/orderman/OrderRouter.cpp index 23f7be1ae..d663f7367 100644 --- a/src/lib/orderman/OrderRouter.cpp +++ b/src/lib/orderman/OrderRouter.cpp @@ -4,6 +4,7 @@ #include "lib/config/config.h" #include "lib/config/protos/jetfix.pb.h" #include "lib/domain_model/Security.pb.h" +#include "lib/logging/logging.h" #include "lib/utils/bts_assert.h" namespace bts { @@ -23,18 +24,13 @@ void OrderRouter::update(api::admin::AdminData const &new_data) { OrderRouter::RouteQueryResult OrderRouter::get_routing_record( UserID user_id, AccountID account_id, api::Security const &sec) const { - // TODO - if (sec.exchange() == api::VENUE_DERIBIT) { - bts::api::orderman::RoutingRecord rr = {}; - rr.set_session("sim"); - RouteQueryResult rv = {true, "", rr}; - return rv; - } api::admin::AdminServiceOperationResult result; api::orderman::RoutingRecord rr = bts::admin::AdminServiceUtils::get_routing_record( me->data, account_id.value() == 0 ? 1 : account_id.value(), user_id.value() == 0 ? 1 : user_id.value(), sec, result); + LOG(OrderMan, Info, "OrderRouter::get_routing_record rr: {} result: {}, {}", + utils::pb::to_string(rr), result.is_success(), result.error_text()); if (result.is_success()) return RouteQueryResult{true, std::string(""), rr}; else diff --git a/src/lib/orderman/OrderServiceServer.cpp b/src/lib/orderman/OrderServiceServer.cpp index 858947f9f..111b65b88 100644 --- a/src/lib/orderman/OrderServiceServer.cpp +++ b/src/lib/orderman/OrderServiceServer.cpp @@ -445,7 +445,8 @@ void OrderServiceServer::_on_exchange_position( for (const auto &p : ev.position.total_exchange_positions) { bts::api::orderman::RetrievedExchangePosition ret_pos = {}; std::string id = p.exchange_sec_desc + "_" + - bts::api::Venue_Name(ev.position.exchange); + bts::api::Venue_Name(ev.position.exchange) + "_" + + p.account_name; ret_pos.set_record_id(id); ret_pos.set_security_key(p.security == nullptr ? 0 : p.security->id()); ret_pos.set_security_resolved(p.security != nullptr); diff --git a/src/lib/orderman/gateways/EMExecutionGateway.cpp b/src/lib/orderman/gateways/EMExecutionGateway.cpp index 737c9900d..50c2578c7 100644 --- a/src/lib/orderman/gateways/EMExecutionGateway.cpp +++ b/src/lib/orderman/gateways/EMExecutionGateway.cpp @@ -53,31 +53,6 @@ namespace orderman { using EMOrderKey = std::int64_t; -// This is used to resolve internal accounts for ExchangePositions -struct StaticAccountResolver { - const bts::config::toggles::DefaultAccount def_acc; - StaticAccountResolver() - : def_acc(config::get()) { - LOG(OrderMan, Info, "StaticAccountResolver accounts: \n{} ", - utils::pb::to_string(def_acc)); - } - std::string get_default_account(api::Security const *sec) { - if (sec == nullptr) - return ""; - api::SecurityTuple s_st = {}; - s_st.set_type(bts::securities::security_type(*sec)); - s_st.set_venue(sec->exchange()); - s_st.set_symbol(sec->symbol()); - for (const auto &u : def_acc.default_accounts()) { - const auto &u_st = u.sec_tup(); - if (u_st.type() == s_st.type() && u_st.venue() == s_st.venue() && - u_st.symbol() == s_st.symbol()) { - return u.account_name(); - } - } - return ""; - } -}; // Order callbacks from order_mux are copied here and placed in the tbb queue struct EMCallbackMsg { // didnt make it const since tbb::queue needs a copy cons @@ -88,14 +63,15 @@ struct EMCallbackMsg { // Position callbacks from order_mux are copied here and placed in the tbb queue struct EMExchangePositionCallbackMsg { - std::vector positions; + std::vector positions; }; struct EMExecutionGateway::PImpl { PImpl(md::SecurityOracle o) : sec_oracle(o) { LOG(OrderMan, Info, "EMExecutionGateway::PImpl constructor"); } - StaticAccountResolver account_resolver = {}; + admin::AdminServiceUtils::ExchangeSubAccountResolver subaccount_resolver = + {}; // callback cashed data api::admin::AdminData admin_data = {}; md::SecurityOracle sec_oracle; @@ -322,9 +298,7 @@ bool EMExecutionGateway::_init() { "positions: {}", exch_pos.size()); // lots of copying going on, but this is periodic - EMExchangePositionCallbackMsg pos_cb = {}; - for (const auto &exh_pos : exch_pos) - pos_cb.positions.push_back(exh_pos); + EMExchangePositionCallbackMsg pos_cb = {exch_pos}; me->exch_pos_queue.push(pos_cb); }; me->order_mux @@ -339,10 +313,14 @@ bool EMExecutionGateway::_init() { } // converts the CreateOrderMsg to emumba::order_entry::new_order and -// sends it to EM gateway +// sends it to ExchangePosition void EMExecutionGateway::_send_create(const CreateOrderMsg &c) { - LOG(OrderMan, Info, "EMExecutionGateway::_send_create key: {} p: {} q: {}", - c.key, c.price, c.quantity); + // TODO: check if sub account exists + LOG(OrderMan, Info, + "EMExecutionGateway::_send_create key: {} p: {} q: {} account: {} " + "operator_id: {} sub_account: {}", + c.key, c.price, c.quantity, c.routing_record->account(), + c.routing_record->operator_id(), c.routing_record->account_code()); emumba::order_entry::new_order new_order; // only assuming deribit for now, as we add exchanges we fix it here bts_assert_msg( @@ -363,12 +341,20 @@ void EMExecutionGateway::_send_create(const CreateOrderMsg &c) { deribit_def_optionals.mmp = false; deribit_def.optional_fields = deribit_def_optionals; new_order.order_def.exchange_order = deribit_def; + new_order.order_def.account = c.routing_record->account_code(); // place order now - emumba::order_entry::order_key new_order_key = - me->order_mux->launch_new_order(new_order); - EMOrderKey em_key = new_order_key.value(); - me->order_map.insert({em_key, c}); - me->key_map.insert({c.key, em_key}); + auto op_res = me->order_mux->launch_new_order(new_order); + if (op_res.is_success) { + auto new_order_key = op_res.ok; + EMOrderKey em_key = new_order_key.value(); + me->order_map.insert({em_key, c}); + me->key_map.insert({c.key, em_key}); + } else { + LOG(OrderMan, Error, + "EMExecutionGateway::_send_create launch_new_order rejected, " + "error_msg: {}", + op_res.err_msg); + } } void EMExecutionGateway::_send_cxl_replace( @@ -425,6 +411,7 @@ void EMExecutionGateway::_process_cb_and_fire_er(const EMCallbackMsg &em_cb) { // cant reate one on the stack ExecutionReport *er_p = me->exe_report_pool.construct(); ExecutionReport &er = *er_p; + // length of these have to be <= 12 to_array(cr_msg.routing_record->account(), &er.account_name.value()); to_array(cr_msg.routing_record->operator_id(), &er.operator_id.value()); er.order_key = cr_msg.key; @@ -477,10 +464,23 @@ void EMExecutionGateway::_process_cb_and_fire_er(const EMCallbackMsg &em_cb) { me->on_exe_report(er, {}); } +// converts the EMPosition received in the callback from IEMOrderMuxer, to +// ExchangePosition (resolved security and account) void EMExecutionGateway::_process_pos_cb_and_fire( const EMExchangePositionCallbackMsg &pos_cb_msg) { - auto get_account = [this](api::Security const *sec) { - auto account_name = me->account_resolver.get_default_account(sec); + // resoves the account from sec, sub_account + auto get_account = [this]( + api::Security const *sec, + const std::string &exch_account) { + auto *entry = + me->subaccount_resolver.find_entry(sec, exch_account, false); + if (entry == nullptr) { + LOG(OrderMan, Error, + "Could not resolve internal account for sec: {}, sub_account: {}", + utils::pb::to_string(*sec), exch_account); + return std::tuple("", nullptr); + } + auto account_name = entry->bts_account_name(); auto bts_account_ptr = admin::AdminServiceUtils::find_account(me->admin_data, account_name); return std::tuple( @@ -501,17 +501,21 @@ void EMExecutionGateway::_process_pos_cb_and_fire( me->exchange_position.exchange = api::VENUE_DERIBIT; for (const auto &pos : pos_cb_msg.positions) { const std::string &exch_sec_desc = - std::get(pos.sec_id.value()); + std::get(pos.position.sec_id.value()); auto sec = get_sec(exch_sec_desc); - double pos_qty = std::get(pos.qty.value()); - auto [account_name, bts_account_ptr] = get_account(sec); + double pos_qty = std::get(pos.position.qty.value()); + auto [account_name, bts_account_ptr] = get_account(sec, pos.sub_account); std::optional account_id = bts_account_ptr == nullptr ? std::nullopt : std::optional(bts_account_ptr->id()); + LOG(OrderMan, Info, + "EMExecutionGateway::_process_pos_cb_and_fire pos: {} bts_account: " + "{}", + pos, account_name); me->exchange_position.total_exchange_positions.push_back( {exch_sec_desc, sec, account_name, account_id, pos_qty, - Price(pos.average_price.to_double())}); + Price(pos.position.average_price.to_double())}); } LOG(OrderMan, Info, "EMExecutionGateway::_process_pos_cb_and_fire n_pos: {}", me->exchange_position.total_exchange_positions.size()); diff --git a/src/server/sparkd/cmds/crypto/DeribitDemo.cpp b/src/server/sparkd/cmds/crypto/DeribitDemo.cpp index 42fe6297a..692d36cf0 100644 --- a/src/server/sparkd/cmds/crypto/DeribitDemo.cpp +++ b/src/server/sparkd/cmds/crypto/DeribitDemo.cpp @@ -22,10 +22,11 @@ static void signal_handler(int signal_number) { } DeribitDemo::DeribitDemo(const std::string &config_path) { + LOG(OrderMan, Info, "DeribitDemo::DeribitDemo config_path: {}", config_path); std::signal(SIGUSR1, signal_handler); - DeribitDemoListener deribit_listener; - deribit_listener.configure(config_path); - deribit_listener.run(); + // DeribitDemoListener deribit_listener; + // deribit_listener.configure(config_path); + // deribit_listener.run(); } DeribitDemo::~DeribitDemo() = default; diff --git a/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.cpp b/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.cpp index 830507213..81173906c 100644 --- a/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.cpp +++ b/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.cpp @@ -42,14 +42,33 @@ static std::string read_url(rapidjson::Document &doc) { static emumba::deribit_connector::configuration::trading_session_config read_trading_session_config(typename rapidjson::Document &doc) { + using namespace emumba::deribit_connector; + // order_tracker + configuration::order_tracker order_tracker; + order_tracker.uuid = doc["uuid"].GetString(); + order_tracker.start_id = doc["start_id"].GetUint(); + // reconnection_config + configuration::reconnection_config rec_config; + rec_config.retry_count = + doc["reconnection"].GetObject()["retry_count"].GetInt(); + rec_config.retry_interval = + doc["reconnection"].GetObject()["retry_interval"].GetInt(); + rec_config.reception_timeout = + doc["reconnection"].GetObject()["reception_timeout"].GetInt(); + emumba::deribit_connector::configuration::trading_session_config tsc; - auto &creds = doc["credentials"]; - tsc.client_name = creds["client_name"].GetString(); - tsc.client_id = creds["id"].GetString(); - tsc.secret_key = creds["secret_key"].GetString(); + tsc.orders_tracker = order_tracker; + tsc.core = doc["core"].GetUint(); + // TODO + // auto &creds = doc["credentials"]; + // TODO + // tsc.client_name = creds["client_name"].GetString(); + // tsc.client_id = creds["id"].GetString(); + // tsc.secret_key = creds["secret_key"].GetString(); tsc.heartbeat_interval = doc["session"].GetObject()["heartbeat_interval"].GetInt(); - tsc.core = doc["core"].GetInt(); + tsc.cancel_on_disconnect = doc["cancel_on_disconnect"].GetBool(); + tsc.reconnect_config = rec_config; return tsc; } @@ -74,6 +93,7 @@ read_symbol_config(rapidjson::Document &doc) { sym.interested_in_future = RJR::get_bool(sym_in, "interested_in_future"); sym.interested_in_option = RJR::get_bool(sym_in, "interested_in_option"); sym.currency_type = RJR::get_string(sym_in, "currency_type", "usd"); + sym.cred_index = 1; read_instruments(sym_in, sym.interested_instruments); auto chan_in = sym_in["channel"].GetObject(); @@ -87,17 +107,35 @@ read_symbol_config(rapidjson::Document &doc) { subs.public_ticker = RJR::get_bool(chan_in, "PUBLIC_TICKER"); subs.public_markprice = RJR::get_bool(chan_in, "PUBLIC_MARKPRICE"); subs.public_index = RJR::get_bool(chan_in, "PUBLIC_INDEX"); - subs.private_orders = RJR::get_bool(chan_in, "PRIVATE_ORDERS"); - subs.private_trades = RJR::get_bool(chan_in, "PRIVATE_TRADES"); + // subs.private_orders = RJR::get_bool(chan_in, "PRIVATE_ORDERS"); + // subs.private_trades = RJR::get_bool(chan_in, "PRIVATE_TRADES"); subs.private_portfolio = RJR::get_bool(chan_in, "PRIVATE_PORTFOLIO"); subs.use_raw_interval = RJR::get_bool(sym_in, "raw_enable", true); } return syms_out; } +static std:: + map + read_credential_config(rapidjson::Document &doc) { + using RJR = RapidJsonReader; + using namespace emumba::deribit_connector; + + std::map rv; + for (auto &cred_in : doc["credentials"].GetArray()) { + configuration::credential_config rv_i; + rv_i.client_name = RJR::get_string(cred_in, "client_name"); + rv_i.client_id = RJR::get_string(cred_in, "id"); + rv_i.index = RJR::get_uint(cred_in, "subaccount_index"); + rv_i.secret_key = RJR::get_string(cred_in, "secret_key"); + rv.insert( + std::pair(rv_i.index, rv_i)); + } + return rv; +} + std::optional DeribitDemoConfiguration::read_file( const std::string &config_path) { - std::ifstream configFile(config_path); rapidjson::IStreamWrapper isw{configFile}; @@ -112,6 +150,7 @@ std::optional DeribitDemoConfiguration::read_file( conf.deribit_url = read_url(doc); conf.trading_config = read_trading_session_config(doc); conf.symbol_config_list = read_symbol_config(doc); + conf.credential_map = read_credential_config(doc); return conf; } diff --git a/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.h b/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.h index a22210f2c..5ffcfd56c 100644 --- a/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.h +++ b/src/server/sparkd/cmds/crypto/DeribitDemoConfiguration.h @@ -1,6 +1,8 @@ #pragma once #include +#include #include +#include #include namespace bts::cmds { @@ -13,9 +15,33 @@ struct DeribitDemoConfiguration { logging_configuration; emumba::deribit_connector::configuration::trading_session_config trading_config; + std::map + credential_map; static std::optional read_file( const std::string &path); }; +inline std::ostream &operator<<( + std::ostream &out, + emumba::deribit_connector::configuration::credential_config const &c) { + out << "index: " << c.index << " client_name: " << c.client_name + << " client_id: " << c.client_id << " secret_key: " << c.secret_key; + return out; +} + +inline std::ostream &operator<<( + std::ostream &out, DeribitDemoConfiguration const &c) { + out << "deribit_url: " << c.deribit_url + << " symbols: " << c.symbol_config_list.size() + << " core: " << c.trading_config.core + << " heartbeat_interval: " << c.trading_config.heartbeat_interval + << " cancel_on_disconnect: " << c.trading_config.cancel_on_disconnect + << " credential_map: " << c.credential_map.size(); + for (const auto &p : c.credential_map) { + out << " " << p.second; + } + return out; +} + } // namespace bts::cmds diff --git a/src/server/sparkd/cmds/crypto/DeribitDemoListener.cpp b/src/server/sparkd/cmds/crypto/DeribitDemoListener.cpp index 8b046eb3c..ca5795d7a 100644 --- a/src/server/sparkd/cmds/crypto/DeribitDemoListener.cpp +++ b/src/server/sparkd/cmds/crypto/DeribitDemoListener.cpp @@ -1,552 +1,561 @@ -#include "DeribitDemoListener.h" -#include "lib/utils/UNUSED_PARAM.h" -#include "lib/utils/overloaded.h" -#include "rapidjson/istreamwrapper.h" -#include "rapidjson/ostreamwrapper.h" -#include "rapidjson/stringbuffer.h" -#include "rapidjson/writer.h" -#include "server/sparkd/cmds/crypto/DeribitDemoConfiguration.h" -#include "server/sparkd/cmds/spartan/utils/FileUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include //support for async logging -#include -#include +// #include "DeribitDemoListener.h" +// #include "lib/utils/UNUSED_PARAM.h" +// #include "lib/utils/overloaded.h" +// #include "rapidjson/istreamwrapper.h" +// #include "rapidjson/ostreamwrapper.h" +// #include "rapidjson/stringbuffer.h" +// #include "rapidjson/writer.h" +// #include "server/sparkd/cmds/crypto/DeribitDemoConfiguration.h" +// #include "server/sparkd/cmds/spartan/utils/FileUtils.h" +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include //support for async logging +// #include +// #include -namespace bts::cmds { +// namespace bts::cmds { -const std::string &extract_security_desc( - const emumba::market_data::security_id &sec_id) { - return std::get(sec_id.value()); -} - -const std::string &extract_security_desc( - const emumba::market_data::security &s) { - return extract_security_desc(s.sec_common.sec_id); -} - -bool DeribitDemoListener::configure(const std::string &config_path) { - // assert(false); - // return true; - using namespace rapidjson; - - auto _main_logger = - spdlog::stdout_color_mt("demo_logger"); - spdlog::set_default_logger(_main_logger); - spdlog::set_level(spdlog::level::trace); - - std::optional conf = - bts::cmds::DeribitDemoConfiguration::read_file(config_path); - // Creating a deribit_handler object using the above configuration structures - // _deribit_conn = - _deribit_conn = std::make_shared( - conf->symbol_config_list, conf->trading_config, - conf->logging_configuration, conf->deribit_url, this); - - // Creating a trading session interface to send order entry messages - // (removing this line causes connection drops) - _trading_session_interface = - std::make_shared( - _deribit_conn->create_new_trading_session()); - return true; -} - -void DeribitDemoListener::run() { - try { - _deribit_conn->run(); - } catch (emumba::deribit_connector::deribit_exception &e) { - e.print(); - } -} - -// Order Entry Callbacks -void DeribitDemoListener::on_account_summary( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &msg_result) { - if (!ec.value()) { - SPDLOG_DEBUG("On_account_summary message body: {}", msg_result); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} - -// Order Entry Callbacks -void DeribitDemoListener::on_order_update( - const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const emumba::order_entry::order_key &order_key, - UNUSED_PARAM const emumba::order_entry::order_state &order_state) { - if (!ec.value()) { - SPDLOG_DEBUG( - "On_order_update | Order Key: {} | Status (Working): {}, Status " - "(Completed): {}, Status (Canceled): {}, Status " - "(Rejected): {}, Status (Untriggered): {}, Total Fills: {}, Average " - "Price: {}", - order_key.value(), - (order_state.order_status == emumba::order_entry::status::working), - (order_state.order_status == emumba::order_entry::status::completed), - (order_state.order_status == emumba::order_entry::status::canceled), - (order_state.order_status == emumba::order_entry::status::rejected), - (order_state.order_status == - emumba::order_entry::status::untriggered), - std::get(order_state.total_fills.value()), - order_state.avg_price.to_double()); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} - -void DeribitDemoListener::on_cancel_all_orders( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &msg_result) { - if (!ec.value()) { - SPDLOG_DEBUG( - "Order Entry Data API callback | on_cancel_all_orders | Message:{}", - msg_result); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} - -void DeribitDemoListener::on_cancel_all_positions( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &msg_result) { - if (!ec.value()) { - SPDLOG_DEBUG( - "Order Entry Data API callback | on_cancel_all_positions | Message: " - "{}", - msg_result); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} - -void DeribitDemoListener::on_get_position( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &msg_result) { - if (!ec.value()) { - SPDLOG_DEBUG( - "Order Entry Data API callback | on_get_position | Message: {}", - msg_result); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} -void DeribitDemoListener::on_get_open_orders( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &msg_result) { - if (!ec.value()) { - SPDLOG_DEBUG( - "Order Entry Data API callback | on_get_open_orders | Message: {}", - msg_result); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} - -// Market Data Callbacks -void *DeribitDemoListener::on_instrument_definition( - UNUSED_PARAM const std::string &instrument_name, - UNUSED_PARAM emumba::deribit_connector::instrument_data_interface - *interface) { - SPDLOG_INFO( - "Market Data API callback | Instrument Definition | Instrument Name: {}", - instrument_name); - _instrument_data_interface_list[instrument_name] = interface; - - _instruments.emplace_back(instrument_name); - return &_instruments - .back(); // Returning a handle to the connector. The connector - // will provide this handle on each callback -} - -void DeribitDemoListener::on_book_state_change( - UNUSED_PARAM const std::string &instrument_name, - UNUSED_PARAM const data_types::book_status &status_of_book, - const void *ptr) { - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); - if (_n_other_updates++ % 1000 != 0) - return; - SPDLOG_DEBUG( - "Market Data API callback | Book State Change | Instrument Name: {}", - instrument_data->get_instrument_name()); -} - -// void DeribitDemoListener::on_subscription_public_trades( -// UNUSED_PARAM const std::string &instrument_name, -// UNUSED_PARAM const std::string &trades_message, -// UNUSED_PARAM const void *ptr) { -// // Following example code is left in order to give a basic idea about the -// // JSON parsing using RapidJson Library -// _message.Parse( -// trades_message.c_str()); - -// std::string block_trade_id = ""; -// double iv = 0.0; -// std::string liquidation = ""; -// if (_message.HasMember("block_trade_id") == true) { -// block_trade_id = _message["block_trade_id"].GetString(); -// } -// if (_message.HasMember("iv") == true) { -// iv = _message["iv"].GetDouble(); -// } -// if (_message.HasMember("liquidation") == true) { -// liquidation = _message["liquidation"].GetString(); -// } - -// SPDLOG_TRACE( -// "Market Data API callback | Subscription | Public Trades | " -// "amount:{},block_trade_id:{},direction:{},index_price:{},instrument_" -// "name:{},iv:{},liquidation:{},mark_price:{},price:{" -// "},tick_direction:{},timestamp:{},trade_id:{},trade_seq:{}", -// _message["amount"].GetDouble(), block_trade_id, -// _message["direction"].GetString(), -// _message["index_price"].GetDouble(), -// _message["instrument_name"].GetString(), iv, liquidation, -// _message["mark_price"].GetDouble(), _message["price"].GetDouble(), -// _message["tick_direction"].GetInt(), -// _message["timestamp"].GetUint64(), _message["trade_id"].GetString(), -// _message["trade_seq"].GetUint64()); -// UNUSED(iv); - -// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; -// UNUSED(instrument_data); -// SPDLOG_DEBUG( -// "Market Data API callback | Subscription | Public Trades | Instrument -// " "Name: {}", instrument_data->get_instrument_name()); +// const std::string &extract_security_desc( +// const emumba::market_data::security_id &sec_id) { +// return std::get(sec_id.value()); // } -void DeribitDemoListener::on_subscription_public_markprice( - UNUSED_PARAM const std::string &symbol_name, - UNUSED_PARAM const std::string &markprice_message) { - SPDLOG_DEBUG( - "Market Data API callback | Subscription | Public Markprice | Message: " - "{}", - markprice_message); -} -void DeribitDemoListener::on_subscription_public_index( - UNUSED_PARAM const std::string &symbol_name, - UNUSED_PARAM const std::string &index_message) { - SPDLOG_DEBUG( - "Market Data API callback | Subscription | Public Index | Message: {}", - index_message); -} +// const std::string &extract_security_desc( +// const emumba::market_data::security &s) { +// return extract_security_desc(s.sec_common.sec_id); +// } -void DeribitDemoListener::on_subscription_private_user_orders_raw( - UNUSED_PARAM const std::string &instrument_name, - UNUSED_PARAM const std::string &user_orders_message, - UNUSED_PARAM const void *ptr) { - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); +// bool DeribitDemoListener::configure(const std::string &config_path) { +// // assert(false); +// // return true; +// using namespace rapidjson; - SPDLOG_DEBUG( - "Market Data API callback | Subscription | Private User Orders Raw | " - "Instrument Name: {}", - instrument_data->get_instrument_name()); -} +// auto _main_logger = +// spdlog::stdout_color_mt("demo_logger"); +// spdlog::set_default_logger(_main_logger); +// spdlog::set_level(spdlog::level::trace); -void DeribitDemoListener::on_subscription_private_user_orders_interval( - UNUSED_PARAM const std::string &instrument_name, - UNUSED_PARAM const std::string &user_orders_message, - UNUSED_PARAM const void *ptr) { - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); +// std::optional conf = +// bts::cmds::DeribitDemoConfiguration::read_file(config_path); +// // Creating a deribit_handler object using the above configuration +// structures +// // _deribit_conn = +// _deribit_conn = +// std::make_shared( +// conf->symbol_config_list, conf->trading_config, +// conf->logging_configuration, conf->deribit_url, this); - SPDLOG_DEBUG( - "Market Data API callback | Subscription | Private User Orders Interval " - "| Instrument Name: {}", - instrument_data->get_instrument_name()); -} +// // Creating a trading session interface to send order entry messages +// // (removing this line causes connection drops) +// _trading_session_interface = +// std::make_shared( +// _deribit_conn->create_new_trading_session()); +// return true; +// } -// void DeribitDemoListener::on_subscription_private_user_trades( +// void DeribitDemoListener::run() { +// try { +// _deribit_conn->run(); +// } catch (emumba::deribit_connector::deribit_exception &e) { +// e.print(); +// } +// } + +// // Order Entry Callbacks +// void DeribitDemoListener::on_account_summary( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &msg_result) { +// if (!ec.value()) { +// SPDLOG_DEBUG("On_account_summary message body: {}", msg_result); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } + +// // Order Entry Callbacks +// void DeribitDemoListener::on_order_update( +// const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const emumba::order_entry::order_key &order_key, +// UNUSED_PARAM const emumba::order_entry::order_state &order_state) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "On_order_update | Order Key: {} | Status (Working): {}, Status " +// "(Completed): {}, Status (Canceled): {}, Status " +// "(Rejected): {}, Status (Untriggered): {}, Total Fills: {}, Average +// " "Price: {}", order_key.value(), (order_state.order_status == +// emumba::order_entry::status::working), (order_state.order_status == +// emumba::order_entry::status::completed), (order_state.order_status +// == emumba::order_entry::status::canceled), +// (order_state.order_status == +// emumba::order_entry::status::rejected), (order_state.order_status +// == +// emumba::order_entry::status::untriggered), +// std::get(order_state.total_fills.value()), +// order_state.avg_price.to_double()); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } + +// void DeribitDemoListener::on_cancel_all_orders( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &msg_result) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "Order Entry Data API callback | on_cancel_all_orders | +// Message:{}", msg_result); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } + +// void DeribitDemoListener::on_cancel_all_positions( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &msg_result) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "Order Entry Data API callback | on_cancel_all_positions | Message: +// " +// "{}", +// msg_result); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } + +// void DeribitDemoListener::on_get_position( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &msg_result) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "Order Entry Data API callback | on_get_position | Message: {}", +// msg_result); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } +// void DeribitDemoListener::on_get_open_orders( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &msg_result) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "Order Entry Data API callback | on_get_open_orders | Message: {}", +// msg_result); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } + +// // Market Data Callbacks +// void *DeribitDemoListener::on_instrument_definition( // UNUSED_PARAM const std::string &instrument_name, -// UNUSED_PARAM const std::string &user_trades_message, +// UNUSED_PARAM emumba::deribit_connector::instrument_data_interface +// *interface) { +// SPDLOG_INFO( +// "Market Data API callback | Instrument Definition | Instrument Name: +// {}", instrument_name); +// _instrument_data_interface_list[instrument_name] = interface; + +// _instruments.emplace_back(instrument_name); +// return &_instruments +// .back(); // Returning a handle to the connector. The connector +// // will provide this handle on each callback +// } + +// void DeribitDemoListener::on_book_state_change( +// UNUSED_PARAM const std::string &instrument_name, +// UNUSED_PARAM const data_types::book_status &status_of_book, +// const void *ptr) { +// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// UNUSED(instrument_data); +// if (_n_other_updates++ % 1000 != 0) +// return; +// SPDLOG_DEBUG( +// "Market Data API callback | Book State Change | Instrument Name: {}", +// instrument_data->get_instrument_name()); +// } + +// // void DeribitDemoListener::on_subscription_public_trades( +// // UNUSED_PARAM const std::string &instrument_name, +// // UNUSED_PARAM const std::string &trades_message, +// // UNUSED_PARAM const void *ptr) { +// // // Following example code is left in order to give a basic idea about +// the +// // // JSON parsing using RapidJson Library +// // _message.Parse( +// // trades_message.c_str()); + +// // std::string block_trade_id = ""; +// // double iv = 0.0; +// // std::string liquidation = ""; +// // if (_message.HasMember("block_trade_id") == true) { +// // block_trade_id = _message["block_trade_id"].GetString(); +// // } +// // if (_message.HasMember("iv") == true) { +// // iv = _message["iv"].GetDouble(); +// // } +// // if (_message.HasMember("liquidation") == true) { +// // liquidation = _message["liquidation"].GetString(); +// // } + +// // SPDLOG_TRACE( +// // "Market Data API callback | Subscription | Public Trades | " +// // "amount:{},block_trade_id:{},direction:{},index_price:{},instrument_" +// // "name:{},iv:{},liquidation:{},mark_price:{},price:{" +// // "},tick_direction:{},timestamp:{},trade_id:{},trade_seq:{}", +// // _message["amount"].GetDouble(), block_trade_id, +// // _message["direction"].GetString(), +// // _message["index_price"].GetDouble(), +// // _message["instrument_name"].GetString(), iv, liquidation, +// // _message["mark_price"].GetDouble(), _message["price"].GetDouble(), +// // _message["tick_direction"].GetInt(), +// // _message["timestamp"].GetUint64(), +// _message["trade_id"].GetString(), +// // _message["trade_seq"].GetUint64()); +// // UNUSED(iv); + +// // UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// // UNUSED(instrument_data); +// // SPDLOG_DEBUG( +// // "Market Data API callback | Subscription | Public Trades | +// Instrument +// // " "Name: {}", instrument_data->get_instrument_name()); +// // } + +// void DeribitDemoListener::on_subscription_public_markprice( +// UNUSED_PARAM const std::string &symbol_name, +// UNUSED_PARAM const std::string &markprice_message) { +// SPDLOG_DEBUG( +// "Market Data API callback | Subscription | Public Markprice | Message: +// " +// "{}", +// markprice_message); +// } +// void DeribitDemoListener::on_subscription_public_index( +// UNUSED_PARAM const std::string &symbol_name, +// UNUSED_PARAM const std::string &index_message) { +// SPDLOG_DEBUG( +// "Market Data API callback | Subscription | Public Index | Message: +// {}", index_message); +// } + +// void DeribitDemoListener::on_subscription_private_user_orders_raw( +// UNUSED_PARAM const std::string &instrument_name, +// UNUSED_PARAM const std::string &user_orders_message, // UNUSED_PARAM const void *ptr) { // UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; // UNUSED(instrument_data); // SPDLOG_DEBUG( -// "Market Data API callback | Subscription | Private User Trades | " +// "Market Data API callback | Subscription | Private User Orders Raw | " // "Instrument Name: {}", // instrument_data->get_instrument_name()); // } -void DeribitDemoListener::on_subscription_private_user_portfolio( - UNUSED_PARAM const std::string &symbol_name, - UNUSED_PARAM const std::string &user_portfolio_message) { - SPDLOG_DEBUG( - "Market Data API callback | Subscription | Private User Portfolio | " - "Symbol Name: {}", - symbol_name); -} +// void DeribitDemoListener::on_subscription_private_user_orders_interval( +// UNUSED_PARAM const std::string &instrument_name, +// UNUSED_PARAM const std::string &user_orders_message, +// UNUSED_PARAM const void *ptr) { +// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// UNUSED(instrument_data); -void DeribitDemoListener::on_response_get_instruments( - UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, - UNUSED_PARAM const std::string &symbol_name, - UNUSED_PARAM const std::string &get_instruments_message) { - if (!ec.value()) { - SPDLOG_DEBUG( - "Market Data API callback | Response | Get Instruments | Symbol " - "Name: {}", - symbol_name); - } else { - SPDLOG_ERROR( - "Error in response ec.value: {}, ec.message: {}", ec.value(), - ec.message()); - } -} +// SPDLOG_DEBUG( +// "Market Data API callback | Subscription | Private User Orders +// Interval " +// "| Instrument Name: {}", +// instrument_data->get_instrument_name()); +// } -void DeribitDemoListener::on_securities( - const std::vector - &complete_security_list) { - SPDLOG_INFO( - "On securities callback | total securities: {}", - complete_security_list.size()); - for (int i = 0; i < (int)complete_security_list.size(); i++) { - emumba::market_data::security const *sp = complete_security_list[i]; - std::string desc = extract_security_desc(*sp); - SPDLOG_INFO("BTS::DeribitDemoListener::on_securities sec:{}", desc); - if (complete_security_list[i]->sec_common.sec_type == - emumba::market_data::security_type::future) { - auto sec_ = std::get<0>(complete_security_list[i]->sec); - UNUSED(sec_); +// // void DeribitDemoListener::on_subscription_private_user_trades( +// // UNUSED_PARAM const std::string &instrument_name, +// // UNUSED_PARAM const std::string &user_trades_message, +// // UNUSED_PARAM const void *ptr) { +// // UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// // UNUSED(instrument_data); - SPDLOG_DEBUG( - "On futures securities callback- New Security | security_id: {}, " - "venue: {}, security_type: {}, expiration " - "timestamp: " - "{}, creation_timestamp: {}, leverage: {} , display_factor: {}, " - "cash_per_point: {}, symbol: {}, security_group: " - "{}, implied_matching: {}, contract_size: {}, is_active: {}, " - "min_trade_amount: {}, settlement_period: {}, " - "block_trade_commission: {}, maker_commission: {}, " - "taker_commission: {}, min_price_increment: {}", - std::get( - complete_security_list[i]->sec_common.sec_id.value()), - (int)complete_security_list[i]->sec_common.exchange, - complete_security_list[i]->sec_common.sec_type, - sec_.expiration_ts.get_timestamp(), - sec_.creation_ts.get_timestamp(), sec_.leverage, - complete_security_list[i]->sec_common.sec_cme.display_factor, - complete_security_list[i]->sec_common.sec_cme.cash_per_point, - complete_security_list[i]->sec_common.symbol, - complete_security_list[i]->sec_common.security_group, - complete_security_list[i]->sec_common.sec_cme.implied_matching, - complete_security_list[i]->sec_common.sec_deribit.contract_size, - complete_security_list[i]->sec_common.sec_deribit.is_active, - complete_security_list[i]->sec_common.sec_deribit.min_trade_amount, - complete_security_list[i] - ->sec_common.sec_deribit.settlement_period, - complete_security_list[i] - ->sec_common.sec_deribit.block_trade_commission, - complete_security_list[i]->sec_common.sec_deribit.maker_commission, - complete_security_list[i]->sec_common.sec_deribit.taker_commission, - complete_security_list[i] - ->sec_common.min_price_increment.to_double()); - } else if ( - complete_security_list[i]->sec_common.sec_type == - emumba::market_data::security_type::option) { - auto sec_ = std::get<1>(complete_security_list[i]->sec); - UNUSED(sec_); +// // SPDLOG_DEBUG( +// // "Market Data API callback | Subscription | Private User Trades | " +// // "Instrument Name: {}", +// // instrument_data->get_instrument_name()); +// // } - SPDLOG_DEBUG( - "On options securities callback- New Security | security_id: {}, " - "venue: {}, security_type: {}, expiration timestamp: {}, " - "creation_timestamp: {}, option_type: {} , strike: {}, " - "display_factor: {}, cash_per_point: {}, symbol: {}, " - "security_group: {}, implied_matching: {}, contract_size: {}, " - "is_active: {}, min_trade_amount: {}, settlement_period: {}, " - "block_trade_commission: {}, maker_commission: {}, " - "taker_commission: {}, min_price_increment: {}", - std::get( - complete_security_list[i]->sec_common.sec_id.value()), - (int)complete_security_list[i]->sec_common.exchange, - complete_security_list[i]->sec_common.sec_type, - sec_.expiration_ts.get_timestamp(), - sec_.creation_ts.get_timestamp(), sec_.op_type, - sec_.strike.to_double(), - complete_security_list[i]->sec_common.sec_cme.display_factor, - complete_security_list[i]->sec_common.sec_cme.cash_per_point, - complete_security_list[i]->sec_common.symbol, - complete_security_list[i]->sec_common.security_group, - complete_security_list[i]->sec_common.sec_cme.implied_matching, - complete_security_list[i]->sec_common.sec_deribit.contract_size, - complete_security_list[i]->sec_common.sec_deribit.is_active, - complete_security_list[i]->sec_common.sec_deribit.min_trade_amount, - complete_security_list[i] - ->sec_common.sec_deribit.settlement_period, - complete_security_list[i] - ->sec_common.sec_deribit.block_trade_commission, - complete_security_list[i]->sec_common.sec_deribit.maker_commission, - complete_security_list[i]->sec_common.sec_deribit.taker_commission, - complete_security_list[i] - ->sec_common.min_price_increment.to_double()); - } - } -} +// void DeribitDemoListener::on_subscription_private_user_portfolio( +// UNUSED_PARAM const std::string &symbol_name, +// UNUSED_PARAM const std::string &user_portfolio_message) { +// SPDLOG_DEBUG( +// "Market Data API callback | Subscription | Private User Portfolio | " +// "Symbol Name: {}", +// symbol_name); +// } -void DeribitDemoListener::on_security_state( - UNUSED_PARAM const emumba::market_data::security_state &sec_state, - UNUSED_PARAM const void *ptr) { - SPDLOG_DEBUG( - "On security state callback | state: {}, security_id {}", - (int)sec_state.state_, std::get(sec_state.sec_id.value())); -} +// void DeribitDemoListener::on_response_get_instruments( +// UNUSED_PARAM const emumba::deribit_connector::data_types::error &ec, +// UNUSED_PARAM const std::string &symbol_name, +// UNUSED_PARAM const std::string &get_instruments_message) { +// if (!ec.value()) { +// SPDLOG_DEBUG( +// "Market Data API callback | Response | Get Instruments | Symbol " +// "Name: {}", +// symbol_name); +// } else { +// SPDLOG_ERROR( +// "Error in response ec.value: {}, ec.message: {}", ec.value(), +// ec.message()); +// } +// } -void DeribitDemoListener::on_security_statistics( - UNUSED_PARAM const emumba::market_data::market_data_statistics - &market_data_stats, - UNUSED_PARAM const void *ptr) { - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); - if (_n_other_updates++ % 1000 != 0) - return; - SPDLOG_DEBUG( - "Market Data API callback | Security Statistics | SecurityID(using " - "ptr): {}, SecurityID: {}, Low: {}, High: {}, Open: " - "{}, Settle: {}, Volume: {}", - instrument_data->get_instrument_name(), - std::get(market_data_stats.sec_id.value()), - market_data_stats.low.to_double(), market_data_stats.high.to_double(), - market_data_stats.open.to_double(), market_data_stats.settle.to_double(), - market_data_stats.volume); -} +// void DeribitDemoListener::on_securities( +// const std::vector +// &complete_security_list) { +// SPDLOG_INFO( +// "On securities callback | total securities: {}", +// complete_security_list.size()); +// for (int i = 0; i < (int)complete_security_list.size(); i++) { +// emumba::market_data::security const *sp = complete_security_list[i]; +// std::string desc = extract_security_desc(*sp); +// SPDLOG_INFO("BTS::DeribitDemoListener::on_securities sec:{}", desc); +// if (complete_security_list[i]->sec_common.sec_type == +// emumba::market_data::security_type::future) { +// auto sec_ = std::get<0>(complete_security_list[i]->sec); +// UNUSED(sec_); -void DeribitDemoListener::on_book( - UNUSED_PARAM const emumba::market_data::order_book &book, - UNUSED_PARAM const void *ptr) { - const auto &id = std::get(book.sec_id.value()); - _book_updates[id] = _book_updates[id] + 1; - if (_n_bk_updates++ % 1000 != 0) - return; - SPDLOG_INFO( - "Market Data API callback | Book Update | bk_update_no: {} " - "sec_bk_update_no: {} SecurityID: " - "{} n_secs: {}", - _n_bk_updates, _book_updates[id], id, _book_updates.size()); - if (_n_bk_updates % 10000 == 0) { - for (const auto &kv : _book_updates) { - SPDLOG_INFO("SecBooks sec: {} n_updates: {}", kv.first, kv.second); - } - } - for (int i = 0; i < (int)book.asks.level.size(); i++) { - SPDLOG_TRACE( - "Index [{}]: Bid : quantity {}, price {}, Ask : quantity {}, " - "price " - "{}", - i, book.bids.level[i].direct_qty, book.bids.level[i].px.to_double(), - book.asks.level[i].direct_qty, book.asks.level[i].px.to_double()); - } +// SPDLOG_DEBUG( +// "On futures securities callback- New Security | security_id: {}, +// " "venue: {}, security_type: {}, expiration " "timestamp: " +// "{}, creation_timestamp: {}, leverage: {} , display_factor: {}, +// " "cash_per_point: {}, symbol: {}, security_group: " +// "{}, implied_matching: {}, contract_size: {}, is_active: {}, " +// "min_trade_amount: {}, settlement_period: {}, " +// "block_trade_commission: {}, maker_commission: {}, " +// "taker_commission: {}, min_price_increment: {}", +// std::get( +// complete_security_list[i]->sec_common.sec_id.value()), +// (int)complete_security_list[i]->sec_common.exchange, +// complete_security_list[i]->sec_common.sec_type, +// sec_.expiration_ts.get_timestamp(), +// sec_.creation_ts.get_timestamp(), sec_.leverage, +// complete_security_list[i]->sec_common.sec_cme.display_factor, +// complete_security_list[i]->sec_common.sec_cme.cash_per_point, +// complete_security_list[i]->sec_common.symbol, +// complete_security_list[i]->sec_common.security_group, +// complete_security_list[i]->sec_common.sec_cme.implied_matching, +// complete_security_list[i]->sec_common.sec_deribit.contract_size, +// complete_security_list[i]->sec_common.sec_deribit.is_active, +// complete_security_list[i]->sec_common.sec_deribit.min_trade_amount, +// complete_security_list[i] +// ->sec_common.sec_deribit.settlement_period, +// complete_security_list[i] +// ->sec_common.sec_deribit.block_trade_commission, +// complete_security_list[i]->sec_common.sec_deribit.maker_commission, +// complete_security_list[i]->sec_common.sec_deribit.taker_commission, +// complete_security_list[i] +// ->sec_common.min_price_increment.to_double()); +// } else if ( +// complete_security_list[i]->sec_common.sec_type == +// emumba::market_data::security_type::option) { +// auto sec_ = std::get<1>(complete_security_list[i]->sec); +// UNUSED(sec_); - /* - // Following is an examples of using trading session interface to place - a new order emumba::order_entry::new_order my_order; +// SPDLOG_DEBUG( +// "On options securities callback- New Security | security_id: {}, +// " "venue: {}, security_type: {}, expiration timestamp: {}, " +// "creation_timestamp: {}, option_type: {} , strike: {}, " +// "display_factor: {}, cash_per_point: {}, symbol: {}, " +// "security_group: {}, implied_matching: {}, contract_size: {}, " +// "is_active: {}, min_trade_amount: {}, settlement_period: {}, " +// "block_trade_commission: {}, maker_commission: {}, " +// "taker_commission: {}, min_price_increment: {}", +// std::get( +// complete_security_list[i]->sec_common.sec_id.value()), +// (int)complete_security_list[i]->sec_common.exchange, +// complete_security_list[i]->sec_common.sec_type, +// sec_.expiration_ts.get_timestamp(), +// sec_.creation_ts.get_timestamp(), sec_.op_type, +// sec_.strike.to_double(), +// complete_security_list[i]->sec_common.sec_cme.display_factor, +// complete_security_list[i]->sec_common.sec_cme.cash_per_point, +// complete_security_list[i]->sec_common.symbol, +// complete_security_list[i]->sec_common.security_group, +// complete_security_list[i]->sec_common.sec_cme.implied_matching, +// complete_security_list[i]->sec_common.sec_deribit.contract_size, +// complete_security_list[i]->sec_common.sec_deribit.is_active, +// complete_security_list[i]->sec_common.sec_deribit.min_trade_amount, +// complete_security_list[i] +// ->sec_common.sec_deribit.settlement_period, +// complete_security_list[i] +// ->sec_common.sec_deribit.block_trade_commission, +// complete_security_list[i]->sec_common.sec_deribit.maker_commission, +// complete_security_list[i]->sec_common.sec_deribit.taker_commission, +// complete_security_list[i] +// ->sec_common.min_price_increment.to_double()); +// } +// } +// } - my_order.order_def.sec_id.value() = "BTC-PERPETUAL"; - my_order.order_def.order_side = emumba::market_data::side::buy; - my_order.order_def.time_in_frc = - emumba::order_entry::time_in_force::gtc; +// void DeribitDemoListener::on_security_state( +// UNUSED_PARAM const emumba::market_data::security_state &sec_state, +// UNUSED_PARAM const void *ptr) { +// SPDLOG_DEBUG( +// "On security state callback | state: {}, security_id {}", +// (int)sec_state.state_, +// std::get(sec_state.sec_id.value())); +// } - emumba::order_entry::deribit_order_definition deribit_def; - emumba::order_entry::deribit_order_def_optional deribit_def_optionals; +// void DeribitDemoListener::on_security_statistics( +// UNUSED_PARAM const emumba::market_data::market_data_statistics +// &market_data_stats, +// UNUSED_PARAM const void *ptr) { +// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// UNUSED(instrument_data); +// if (_n_other_updates++ % 1000 != 0) +// return; +// SPDLOG_DEBUG( +// "Market Data API callback | Security Statistics | SecurityID(using " +// "ptr): {}, SecurityID: {}, Low: {}, High: {}, Open: " +// "{}, Settle: {}, Volume: {}", +// instrument_data->get_instrument_name(), +// std::get(market_data_stats.sec_id.value()), +// market_data_stats.low.to_double(), market_data_stats.high.to_double(), +// market_data_stats.open.to_double(), +// market_data_stats.settle.to_double(), market_data_stats.volume); +// } - deribit_def.ord_type = - emumba::order_entry::order_type::limit_order; deribit_def_optionals.mmp - = true; deribit_def_optionals.post_only = true; - deribit_def_optionals.reject_post_only = true; - deribit_def_optionals.reduce_only = true; - deribit_def_optionals.trigger = - emumba::order_entry::order_trigger::mark_price; - deribit_def_optionals.advanced = - emumba::order_entry::order_advanced::usd; - deribit_def_optionals.max_show = 10.5; - deribit_def_optionals.trigger_price = - emumba::market_data::price((double)15.5); +// void DeribitDemoListener::on_book( +// UNUSED_PARAM const emumba::market_data::order_book &book, +// UNUSED_PARAM const void *ptr) { +// const auto &id = std::get(book.sec_id.value()); +// _book_updates[id] = _book_updates[id] + 1; +// if (_n_bk_updates++ % 1000 != 0) +// return; +// SPDLOG_INFO( +// "Market Data API callback | Book Update | bk_update_no: {} " +// "sec_bk_update_no: {} SecurityID: " +// "{} n_secs: {}", +// _n_bk_updates, _book_updates[id], id, _book_updates.size()); +// if (_n_bk_updates % 10000 == 0) { +// for (const auto &kv : _book_updates) { +// SPDLOG_INFO("SecBooks sec: {} n_updates: {}", kv.first, kv.second); +// } +// } +// for (int i = 0; i < (int)book.asks.level.size(); i++) { +// SPDLOG_TRACE( +// "Index [{}]: Bid : quantity {}, price {}, Ask : quantity {}, " +// "price " +// "{}", +// i, book.bids.level[i].direct_qty, +// book.bids.level[i].px.to_double(), book.asks.level[i].direct_qty, +// book.asks.level[i].px.to_double()); +// } - deribit_def.optional_fields = deribit_def_optionals; - my_order.order_def.exchange_order = deribit_def; +// /* +// // Following is an examples of using trading session interface to place +// a new order emumba::order_entry::new_order my_order; - my_order.px = emumba::market_data::price((double)10.5); - my_order.qty.value() = (double)1; +// my_order.order_def.sec_id.value() = "BTC-PERPETUAL"; +// my_order.order_def.order_side = emumba::market_data::side::buy; +// my_order.order_def.time_in_frc = +// emumba::order_entry::time_in_force::gtc; - emumba::order_entry::order_key order_key = - _trading_session_interface->launch_new_order(my_order); +// emumba::order_entry::deribit_order_definition deribit_def; +// emumba::order_entry::deribit_order_def_optional deribit_def_optionals; - // Following is an examples of using trading session interface to edit - an order emumba::order_entry::order_update my_update; my_update.ord_key - = order_key; my_update.px = 555.5; my_update.qty.value() = - (double)666; _trading_session_interface->update_order(my_update); +// deribit_def.ord_type = +// emumba::order_entry::order_type::limit_order; deribit_def_optionals.mmp +// = true; deribit_def_optionals.post_only = true; +// deribit_def_optionals.reject_post_only = true; +// deribit_def_optionals.reduce_only = true; +// deribit_def_optionals.trigger = +// emumba::order_entry::order_trigger::mark_price; +// deribit_def_optionals.advanced = +// emumba::order_entry::order_advanced::usd; +// deribit_def_optionals.max_show = 10.5; +// deribit_def_optionals.trigger_price = +// emumba::market_data::price((double)15.5); - // Following is an examples of using trading session interface to - cancel an order _trading_session_interface->cancel_order(order_key); - */ -} +// deribit_def.optional_fields = deribit_def_optionals; +// my_order.order_def.exchange_order = deribit_def; -void DeribitDemoListener::on_trades( - UNUSED_PARAM const std::vector - &trades, - UNUSED_PARAM const void *ptr) { - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); - if (_n_other_updates++ % 1000 != 0) - return; - SPDLOG_DEBUG("On trades callback | total trade records: {}", trades.size()); - for (int i = 0; i < (int)trades.size(); i++) { - auto trade_ts = trades[i]->timestamp; - UNUSED(trade_ts); - SPDLOG_DEBUG( - "New trade record | SecurityID(using ptr): {}, SecurityID: {}, " - "Timestamp: {}, Side: {}, Trade Quantity {}, Trade " - "Price {}", - instrument_data->get_instrument_name(), - std::get(trades[i]->sec_id.value()), - trade_ts.get_timestamp(), (int)trades[i]->agg_side, - trades[i]->trade_quantity, trades[i]->trade_price.to_double()); - } -} +// my_order.px = emumba::market_data::price((double)10.5); +// my_order.qty.value() = (double)1; -void DeribitDemoListener::on_quote( - UNUSED_PARAM const emumba::market_data::quote "e, - UNUSED_PARAM const void *ptr) +// emumba::order_entry::order_key order_key = +// _trading_session_interface->launch_new_order(my_order); -{ - UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; - UNUSED(instrument_data); - if (_n_other_updates++ % 1000 != 0) - return; - SPDLOG_DEBUG( - "Market Data API callback | Quote Update | SecurityID(using ptr): " - "{}, " - "SecurityID: {}, Best Bid Price: " - "{}, Best Bid Amount: {}, Best Ask Price: {}, Best Ask Amount: {}, " - "Timestamp: {}", - instrument_data->get_instrument_name(), - std::get(quote.sec_id.value()), - quote.best_bid_price.to_double(), quote.best_bid_amount, - quote.best_ask_price.to_double(), quote.best_ask_amount, - quote.timestamp.get_timestamp()); -} +// // Following is an examples of using trading session interface to edit +// an order emumba::order_entry::order_update my_update; my_update.ord_key +// = order_key; my_update.px = 555.5; my_update.qty.value() = +// (double)666; _trading_session_interface->update_order(my_update); -void DeribitDemoListener::on_error(__attribute__(( - unused)) const emumba::market_data::market_data_error &error) { - SPDLOG_ERROR("On error callback | error: {}", error.err_type); -} +// // Following is an examples of using trading session interface to +// cancel an order _trading_session_interface->cancel_order(order_key); +// */ +// } -} // namespace bts::cmds +// void DeribitDemoListener::on_trades( +// UNUSED_PARAM const std::vector +// &trades, +// UNUSED_PARAM const void *ptr) { +// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// UNUSED(instrument_data); +// if (_n_other_updates++ % 1000 != 0) +// return; +// SPDLOG_DEBUG("On trades callback | total trade records: {}", +// trades.size()); for (int i = 0; i < (int)trades.size(); i++) { +// auto trade_ts = trades[i]->timestamp; +// UNUSED(trade_ts); +// SPDLOG_DEBUG( +// "New trade record | SecurityID(using ptr): {}, SecurityID: {}, " +// "Timestamp: {}, Side: {}, Trade Quantity {}, Trade " +// "Price {}", +// instrument_data->get_instrument_name(), +// std::get(trades[i]->sec_id.value()), +// trade_ts.get_timestamp(), (int)trades[i]->agg_side, +// trades[i]->trade_quantity, trades[i]->trade_price.to_double()); +// } +// } + +// void DeribitDemoListener::on_quote( +// UNUSED_PARAM const emumba::market_data::quote "e, +// UNUSED_PARAM const void *ptr) + +// { +// UserInstrumentData *instrument_data = (UserInstrumentData *)ptr; +// UNUSED(instrument_data); +// if (_n_other_updates++ % 1000 != 0) +// return; +// SPDLOG_DEBUG( +// "Market Data API callback | Quote Update | SecurityID(using ptr): " +// "{}, " +// "SecurityID: {}, Best Bid Price: " +// "{}, Best Bid Amount: {}, Best Ask Price: {}, Best Ask Amount: {}, " +// "Timestamp: {}", +// instrument_data->get_instrument_name(), +// std::get(quote.sec_id.value()), +// quote.best_bid_price.to_double(), quote.best_bid_amount, +// quote.best_ask_price.to_double(), quote.best_ask_amount, +// quote.timestamp.get_timestamp()); +// } + +// void DeribitDemoListener::on_error(__attribute__(( +// unused)) const emumba::market_data::market_data_error &error) { +// SPDLOG_ERROR("On error callback | error: {}", error.err_type); +// } + +// } // namespace bts::cmds diff --git a/src/server/sparkd/cmds/crypto/DeribitDemoListener.h b/src/server/sparkd/cmds/crypto/DeribitDemoListener.h index 899d684b7..43aa31578 100644 --- a/src/server/sparkd/cmds/crypto/DeribitDemoListener.h +++ b/src/server/sparkd/cmds/crypto/DeribitDemoListener.h @@ -1,151 +1,158 @@ -#pragma once -#include "UserInstrumentData.h" -#include "rapidjson/document.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +// #pragma once +// #include "UserInstrumentData.h" +// #include "rapidjson/document.h" +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include -using namespace emumba::deribit_connector; +// using namespace emumba::deribit_connector; -namespace bts::cmds { +// namespace bts::cmds { -class DeribitDemoListener : public emumba::deribit_connector::deribit_listener { - public: - // Read configuration of connector from config.json file. It is not necessary - // to fill configuration structures from a JSON file. The user can fill the - // configuration structures in any way he/she pleases. - bool configure(const std::string &config_path); - // Run the connector - void run(); +// class DeribitDemoListener : public +// emumba::deribit_connector::deribit_listener { +// public: +// // Read configuration of connector from config.json file. It is not +// necessary +// // to fill configuration structures from a JSON file. The user can fill +// the +// // configuration structures in any way he/she pleases. +// bool configure(const std::string &config_path); +// // Run the connector +// void run(); - // Order Entry Callbacks - void on_account_summary( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; +// // Order Entry Callbacks +// void on_account_summary( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &msg_result) override; - void on_order_update( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key, - const emumba::order_entry::order_state &order_state) override; +// void on_order_update( +// const emumba::deribit_connector::data_types::error &ec, +// const emumba::order_entry::order_key &order_key, +// const emumba::order_entry::order_state &order_state) override; - void on_cancel_all_orders( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; +// void on_cancel_all_orders( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &msg_result) override; - void on_cancel_all_positions( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; +// void on_cancel_all_positions( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &msg_result) override; - void on_get_position( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; +// void on_get_position( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &msg_result) override; - void on_get_open_orders( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; +// void on_get_open_orders( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &msg_result) override; - // Market Data Callbacks - void *on_instrument_definition( - const std::string &instrument_name, - emumba::deribit_connector::instrument_data_interface *interface) - override; +// // Market Data Callbacks +// void *on_instrument_definition( +// const std::string &instrument_name, +// emumba::deribit_connector::instrument_data_interface *interface) +// override; - // void on_subscription_public_trades( - // const std::string &instrument_name, - // const std::string &trades_message, - // const void *ptr = nullptr) override; +// // void on_subscription_public_trades( +// // const std::string &instrument_name, +// // const std::string &trades_message, +// // const void *ptr = nullptr) override; - void on_subscription_public_markprice( - const std::string &symbol_name, - const std::string &markprice_message) override; +// void on_subscription_public_markprice( +// const std::string &symbol_name, +// const std::string &markprice_message) override; - void on_subscription_public_index( - const std::string &symbol_name, - const std::string &index_message) override; +// void on_subscription_public_index( +// const std::string &symbol_name, +// const std::string &index_message) override; - void on_subscription_private_user_orders_raw( - const std::string &instrument_name, - const std::string &user_orders_message, - const void *ptr = nullptr) override; +// void on_subscription_private_user_orders_raw( +// const std::string &instrument_name, +// const std::string &user_orders_message, +// const void *ptr = nullptr) override; - void on_subscription_private_user_orders_interval( - const std::string &instrument_name, - const std::string &user_orders_message, - const void *ptr = nullptr) override; +// void on_subscription_private_user_orders_interval( +// const std::string &instrument_name, +// const std::string &user_orders_message, +// const void *ptr = nullptr) override; - // void on_subscription_private_user_trades( - // const std::string &instrument_name, - // const std::string &user_trades_message, - // const void *ptr = nullptr) override; +// // void on_subscription_private_user_trades( +// // const std::string &instrument_name, +// // const std::string &user_trades_message, +// // const void *ptr = nullptr) override; - void on_subscription_private_user_portfolio( - const std::string &symbol_name, - const std::string &user_portfolio_message) override; +// void on_subscription_private_user_portfolio( +// const std::string &symbol_name, +// const std::string &user_portfolio_message) override; - void on_response_get_instruments( - const emumba::deribit_connector::data_types::error &ec, - const std::string &symbol_name, - const std::string &get_instruments_message) override; +// void on_response_get_instruments( +// const emumba::deribit_connector::data_types::error &ec, +// const std::string &symbol_name, +// const std::string &get_instruments_message) override; - void on_securities(const std::vector - &complete_security_list) override; +// void on_securities(const std::vector +// &complete_security_list) override; - void on_book_state_change( - const std::string &instrument_name, - const data_types::book_status &status_of_book, - const void *ptr = nullptr) override; +// void on_book_state_change( +// const std::string &instrument_name, +// const data_types::book_status &status_of_book, +// const void *ptr = nullptr) override; - void on_security_statistics( - const emumba::market_data::market_data_statistics &market_data_stats, - const void *ptr = nullptr) override; +// void on_security_statistics( +// const emumba::market_data::market_data_statistics &market_data_stats, +// const void *ptr = nullptr) override; - void on_quote( - const emumba::market_data::quote "e, - const void *ptr = nullptr) override; +// void on_quote( +// const emumba::market_data::quote "e, +// const void *ptr = nullptr) override; - void on_book( - const emumba::market_data::order_book &book, - const void *ptr = nullptr) override; +// void on_book( +// const emumba::market_data::order_book &book, +// const void *ptr = nullptr) override; - void on_security_state( - const emumba::market_data::security_state &sec_state, - __attribute__((unused)) const void *ptr = nullptr) override; +// void on_security_state( +// const emumba::market_data::security_state &sec_state, +// __attribute__((unused)) const void *ptr = nullptr) override; - void on_trades( - const std::vector &trades, - __attribute__((unused)) const void *ptr = nullptr) override; +// void on_trades( +// const std::vector &trades, +// __attribute__((unused)) const void *ptr = nullptr) override; - void on_error(const emumba::market_data::market_data_error &error) override; - virtual ~DeribitDemoListener() {} +// void on_error(const emumba::market_data::market_data_error &error) +// override; virtual ~DeribitDemoListener() {} - private: - std::unordered_map _book_updates = {}; - int _n_bk_updates = 0; - int _n_other_updates = 0; - std::list - _instruments; // List of user defined class objects - std::map - _instrument_data_interface_list; // List used to store - // instrument_data_interface pointer. - // This pointer can be used to get - // useful information about the - // instrument. - std::shared_ptr - _deribit_conn; // Shared pointer of deribit connector. This pointer can - // be used to configure/run the connector. - std::shared_ptr - _trading_session_interface; - // // Shared pointer of trading session - // interface. This pointer can be use to send - // order entry messages. - rapidjson::Document _message; // RapidJson Object used to parse the JSON - // messages received in some of the callbacks. -}; +// private: +// std::unordered_map _book_updates = {}; +// int _n_bk_updates = 0; +// int _n_other_updates = 0; +// std::list +// _instruments; // List of user defined class objects +// std::map +// _instrument_data_interface_list; // List used to store +// // instrument_data_interface pointer. +// // This pointer can be used to get +// // useful information about the +// // instrument. +// std::shared_ptr +// _deribit_conn; // Shared pointer of deribit connector. This pointer +// can +// // be used to configure/run the connector. +// std::shared_ptr +// _trading_session_interface; +// // // Shared pointer of trading session +// // interface. This pointer can be use to send +// // order entry messages. +// rapidjson::Document _message; // RapidJson Object used to parse the JSON +// // messages received in some of the +// callbacks. +// }; -} // namespace bts::cmds +// } // namespace bts::cmds diff --git a/src/server/sparkd/md/platforms/emumba/EMTradingSession.h b/src/server/sparkd/md/platforms/emumba/EMTradingSession.h new file mode 100644 index 000000000..4f85ea848 --- /dev/null +++ b/src/server/sparkd/md/platforms/emumba/EMTradingSession.h @@ -0,0 +1,16 @@ +#pragma once + +#include "server/sparkd/cmds/crypto/DeribitDemoConfiguration.h" +#include +#include +#include + +namespace bts::orderman { + +struct EMTradingSession { + emumba::deribit_connector::configuration::credential_config credential; + std::shared_ptr + trading_interface; +}; + +} // namespace bts::orderman \ No newline at end of file diff --git a/src/server/sparkd/md/platforms/emumba/EmMDListener.cpp b/src/server/sparkd/md/platforms/emumba/EmMDListener.cpp index 1bc5599d3..a2bc1b5ab 100644 --- a/src/server/sparkd/md/platforms/emumba/EmMDListener.cpp +++ b/src/server/sparkd/md/platforms/emumba/EmMDListener.cpp @@ -7,6 +7,7 @@ #include "lib/md/PriceSize.h" #include "lib/md/Shm/FixedSecurity.h" #include "lib/md/protos/co2.pb.h" +#include "lib/os/os.h" #include "lib/persistence/IDGenerator.h" #include "lib/utils/PBUtils.h" #include "lib/utils/TimeStamp.h" @@ -15,6 +16,7 @@ #include "lib/utils/datetime.h" #include "lib/utils/overloaded.h" #include "lib/utils/stats.h" +#include "server/sparkd/md/platforms/emumba/EMTradingSession.h" #include "server/sparkd/md/platforms/emumba/EmumbaSecurityIndex.h" #include "server/sparkd/md/platforms/emumba/IEMOrderMuxer.h" #include @@ -36,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +50,7 @@ #include using namespace emumba::deribit_connector; +using namespace bts::orderman; namespace bts::md { @@ -232,19 +236,33 @@ struct SecurityAuxData { : locked_key(locked_key), symbol(symbol) {} }; -struct PoitionRequestHelper { - boost::container::small_vector currencies = {"BTC", "ETH"}; +// Encapsulates the code that queries the trading session for position +struct PositionRequestHelper { + // TODO, get it from else where + const boost::container::small_vector currencies = { + "BTC", "ETH"}; + const std::vector *sessions; size_t n_pending_reqs = 0; - size_t n_reqs_while_waiting = 0; - std::vector total_pos = {}; + std::vector total_pos = {}; - void reset_new_requests() { - n_pending_reqs = currencies.size(); - n_reqs_while_waiting = 0; - total_pos.clear(); + PositionRequestHelper(std::vector *sessions) + : sessions(sessions) {} + + // gets the account from the index + std::string get_subaccount(size_t idx) const { + for (const auto &s : *sessions) { + if (s.credential.index == idx) { + return s.credential.client_id; + } + } + bts_assert(false); + return ""; } + + // if there are any pending reqs bool pending() const { return n_pending_reqs > 0; } + // update from the server for a single session, currency void on_new_update( const std::vector &positions) { if (!pending()) { @@ -254,10 +272,31 @@ struct PoitionRequestHelper { "message"); return; } - for (const auto *p : positions) - total_pos.push_back(*p); + LOG(OrderMan, Info, "PoitionRequestHelper::on_new_update count: {}", + positions.size()); + for (const auto *p : positions) { + total_pos.push_back({*p, get_subaccount(p->subaccount_index)}); + auto &new_it = total_pos.back(); + LOG(OrderMan, Info, "PoitionRequestHelper::on_new_update {}", new_it); + } n_pending_reqs--; } + + // sends requests for all sessions, currencies + bool send_all_position_requests() { + if (pending()) { + LOG(OrderMan, Error, + "PositionRequestHelper::send_all_position_requests already " + "pending requests"); + return false; + } + total_pos.clear(); + n_pending_reqs = sessions->size() * currencies.size(); + for (auto &s : *sessions) + for (const auto &c : currencies) + s.trading_interface->get_all_positions(c); + return true; + } }; struct EmMDListener::PImpl { @@ -265,7 +304,7 @@ struct EmMDListener::PImpl { uint32_t n_updates = 0; bts::persistence::IDGenerator id_gen = {}; emumba::deribit_connector::deribit_handler *handler = nullptr; - emumba::deribit_connector::trading_session_interface *order_gtwy; + std::vector trading_sessions; EmumbaSecurityIndex &index; MDProducer &md_producer; std::unordered_map sec_map = {}; @@ -274,9 +313,10 @@ struct EmMDListener::PImpl { orderman::OnEMOrderUpdate order_update_cb; orderman::OnEMExchangePositionUpdate exchange_position_update_cb; orderman::OnEMExchangeOpenOrderUpdate exchange_open_orders_update_cb; + std::map order_acc_map; std::unordered_map order_state_map = {}; - PoitionRequestHelper pos_helper = {}; + PositionRequestHelper pos_helper = {&trading_sessions}; explicit PImpl(EmumbaSecurityIndex &index_a, MDProducer &md_producer_a) : index(index_a), md_producer(md_producer_a) {} }; @@ -295,27 +335,45 @@ EmMDListener::EmMDListener(EmumbaSecurityIndex &index, MDProducer &md_producer) void run(__attribute__((unused)) const std::string &config_path) {} -emumba::order_entry::order_key EmMDListener::launch_new_order( +bts::orderman::OpResult EmMDListener::launch_new_order( const emumba::order_entry::new_order &order) { + EMTradingSession *trading_session = + _find_trading_sessions(order.order_def.account); + if (trading_session == nullptr) { + return { + false, emumba::order_entry::order_key{0}, + "Could not find session for subaccount"}; + } const std::string &def = std::get(order.order_def.sec_id.value()); auto qty = std::get(order.qty.value()); - auto key = me->order_gtwy->launch_new_order(order); + auto key = trading_session->trading_interface->launch_new_order(order); + // we add the key here, so we on update and cxl we can resolve the session + me->order_acc_map.insert({key.value(), trading_session}); LOG(OrderMan, Info, - "IEMOrderMuxer::launch_new_order sec: {} p: {} q: {} returned_key: {}", - def, order.px->to_double(), qty, key.value()); - return key; + "IEMOrderMuxer::launch_new_order tid: {} sec: {} p: {} q: {} " + "account: " + "{} " + "returned_key: {}", + os::get_thread_id(), def, order.px->to_double(), qty, + order.order_def.account, key.value()); + return {true, key, ""}; } bool EmMDListener::update_order(const emumba::order_entry::order_update &u) { double q = std::get(u.qty.value()); LOG(OrderMan, Info, "IEMOrderMuxer::update_order key: {} p: {} q: {}", u.ord_key.value(), u.px.value().to_double(), q); - return me->order_gtwy->update_order(u); + auto it = me->order_acc_map.find(u.ord_key.value()); + bts_assert(it != me->order_acc_map.end()); + return it->second->trading_interface->update_order(u); } + bool EmMDListener::cancel_order(const emumba::order_entry::order_key &key) { LOG(OrderMan, Info, "IEMOrderMuxer::cancel_order key: {}", key.value()); - return me->order_gtwy->cancel_order(key); + auto it = me->order_acc_map.find(key.value()); + bts_assert(it != me->order_acc_map.end()); + return it->second->trading_interface->cancel_order(key); } orderman::OnEMOrderUpdate &EmMDListener::order_update_cb() { @@ -323,23 +381,8 @@ orderman::OnEMOrderUpdate &EmMDListener::order_update_cb() { } void EmMDListener::get_positions() { - if (me->pos_helper.pending()) { - me->pos_helper.n_reqs_while_waiting++; - LOG(OrderMan, Error, - "EmMDListener::get_positions already pending requests"); - if (me->pos_helper.n_reqs_while_waiting <= 5) - return; - // we noticed that if we disconnect after making a request, we never get - // the on_get_all_position callback. Therefore if we wait long enough - // without getting a callback start anew - LOG(OrderMan, Error, - "EmMDListener::get_positions failed (because of pending requests) {} " - "times. Reseting and requesting again", - me->pos_helper.n_reqs_while_waiting); - } - me->pos_helper.reset_new_requests(); - for (const auto &c : me->pos_helper.currencies) - me->order_gtwy->get_all_positions(c); + // redirected to pos_helper where all the async requests happen + me->pos_helper.send_all_position_requests(); } orderman::OnEMExchangePositionUpdate & @@ -348,8 +391,10 @@ EmMDListener::exchange_position_update_cb() { } void EmMDListener::get_open_orders() { - me->order_gtwy->get_all_open_orders("BTC"); - me->order_gtwy->get_all_open_orders("ETH"); + for (auto &s : me->trading_sessions) { + s.trading_interface->get_all_open_orders("BTC"); + s.trading_interface->get_all_open_orders("ETH"); + } } orderman::OnEMExchangeOpenOrderUpdate & @@ -369,17 +414,20 @@ void EmMDListener::on_account_summary( } void EmMDListener::on_order_update( - const emumba::deribit_connector::data_types::error &ec, const emumba::order_entry::order_key &order_key, const emumba::order_entry::order_state &order_state) { + const auto &ec = order_state.error; const auto &exchange_order_state = std::get( order_state.exchange_order_state); + // these are all logs LOG(OrderMan, Info, - "IEMOrderMuxer::on_order_update ec.value: {} ec.message: {} key: {} " - "exchange_key: {} status: {} pr: {} qty: {} filled_pr: {} fills: {} " - "n_trades: {}", - ec.value(), ec.message(), order_key.value(), + "IEMOrderMuxer::on_order_update tid: {} key: {} sub_acct_idx: {} " + "ec.value: {} ec.message: {} update_type: {} exchange_key: {} status: " + "{} pr: {} qty: {} filled_pr: {} fills: {} n_trades: {}", + os::get_thread_id(), order_key.value(), order_state.subaccount_index, + ec.value(), ec.message(), + static_cast(order_state.order_update_type), exchange_order_state.exchange_order_id, static_cast(order_state.order_status), order_state.px.to_double(), extract_qty(order_state.qty), order_state.avg_price.to_double(), @@ -392,37 +440,18 @@ void EmMDListener::on_order_update( extract_security_desc(t->sec_id), static_cast(t->agg_side), t->trade_price.to_double(), t->trade_quantity, t->exchange_order_id); } + // we keep the EMOrderState around, and update as we get callbacks auto &ex_ord_state = me->order_state_map[order_key.value()]; ex_ord_state.update(order_state); me->order_update_cb(ec, order_key, ex_ord_state); } -void log_position_discrepency(const emumba::order_entry::position &p) { - double pos = extract_qty(p.qty); - if ((p.position_side == emumba::market_data::side::buy && pos < 0) || - (p.position_side == emumba::market_data::side::sell && pos > 0)) - LOG(OrderMan, Error, - "EmMDListener::on_get_all_positions incompatible position sec: {} " - "side: {} qty: {}", - extract_security_desc(p.sec_id), static_cast(p.position_side), - pos); -} - void EmMDListener::on_get_all_positions( const emumba::deribit_connector::data_types::error &ec, const std::vector &positions) { LOG(OrderMan, Info, "IEMOrderMuxer::on_get_all_positions no of positions: {} ec: {}", positions.size(), ec.message()); - for (auto p : positions) { - LOG(OrderMan, Info, - "IEMOrderMuxer::on_get_all_positions sec_id: {} side: {} qty: {} " - "avg_px: " - "{}", - extract_security_desc(p->sec_id), static_cast(p->position_side), - std::get(p->qty.value()), p->average_price.to_double()); - log_position_discrepency(*p); - } me->pos_helper.on_new_update(positions); if (!me->pos_helper.pending()) { me->exchange_position_update_cb(me->pos_helper.total_pos); @@ -486,16 +515,6 @@ void EmMDListener::on_private_trade( // order_state); } -void EmMDListener::on_cancel_all_orders( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) { - LOG(OrderMan, Info, - "IEMOrderMuxer::on_cancel_all_orders ec.value: {} ec.message: {} " - "msg: " - "{} ", - ec.value(), ec.message(), msg_result); -} - void EmMDListener::on_cancel_all_positions( const emumba::deribit_connector::data_types::error &ec, const std::string &msg_result) { @@ -531,11 +550,6 @@ void *EmMDListener::on_instrument_definition( return nullptr; } -// void EmMDListener::on_subscription_public_trades( -// __attribute__((unused)) const std::string &instrument_name, -// __attribute__((unused)) const std::string &trades_message, -// __attribute__((unused)) const void *ptr) {} - void EmMDListener::on_subscription_public_markprice( __attribute__((unused)) const std::string &symbol_name, __attribute__((unused)) const std::string &markprice_message) {} @@ -544,21 +558,6 @@ void EmMDListener::on_subscription_public_index( __attribute__((unused)) const std::string &symbol_name, __attribute__((unused)) const std::string &index_message) {} -void EmMDListener::on_subscription_private_user_orders_raw( - __attribute__((unused)) const std::string &instrument_name, - __attribute__((unused)) const std::string &user_orders_message, - __attribute__((unused)) const void *ptr) {} - -void EmMDListener::on_subscription_private_user_orders_interval( - __attribute__((unused)) const std::string &instrument_name, - __attribute__((unused)) const std::string &user_orders_message, - __attribute__((unused)) const void *ptr) {} - -// void EmMDListener::on_subscription_private_user_trades( -// __attribute__((unused)) const std::string &instrument_name, -// __attribute__((unused)) const std::string &user_trades_message, -// __attribute__((unused)) const void *ptr) {} - void EmMDListener::on_subscription_private_user_portfolio( __attribute__((unused)) const std::string &symbol_name, __attribute__((unused)) const std::string &user_portfolio_message) {} @@ -727,56 +726,11 @@ void EmMDListener::on_trades( } } -void EmMDListener::on_new_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key, - const emumba::order_entry::new_order &new_order) { - LOG(OrderMan, Error, - "EmMDListener::on_new_order_rejected ec: {} ec.dets: {} key: {} sec: {}", - ec.message(), ec.details(), order_key.value(), - extract_security_desc(new_order.order_def.sec_id)); - emumba::market_data::quantity qty = {}; - qty.value() = 0.0; - emumba::market_data::price pr = emumba::market_data::price(0.0); - std::variant< - emumba::order_entry::deribit_order_state, - emumba::order_entry::glbx_order_state> - exch_order_state; - emumba::order_entry::deribit_order_state dos = {}; - exch_order_state = dos; - on_order_update( - ec, order_key, - emumba::order_entry::order_state{ - emumba::order_entry::status::rejected, - qty, - qty, - pr, - pr, - {}, - exch_order_state}); -} - -void EmMDListener::on_edit_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key, - const emumba::order_entry::order_update &) { - LOG(OrderMan, Error, - "EmMDListener::on_edit_order_rejected ec: {} key: {} details: {}", - ec.message(), order_key.value(), ec.details()); -} - -void EmMDListener::on_cancel_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key) { - LOG(OrderMan, Error, - "EmMDListener::on_cancel_order_rejected ec: {} key: {} ", ec.message(), - order_key.value()); -} - void EmMDListener::on_error( const emumba::market_data::market_data_error &error) { LOG(md, Error, - "EmMDListener::on_error error_type: {} error: {} resetting all books, " + "EmMDListener::on_error error_type: {} error: {} resetting all " + "books, " "n_secs: {}", static_cast(error.err_type), error.err_text, me->index.n_secs()); if (error.err_type == @@ -792,10 +746,12 @@ void EmMDListener::on_error( void EmMDListener::set_handler( emumba::deribit_connector::deribit_handler *handler, - emumba::deribit_connector::trading_session_interface *order_gtway) { + const std::vector &trading_sessions) { + LOG(OrderMan, Info, "EmMDListener::set_handler tid: {} n_sessions: {}", + os::get_thread_id(), trading_sessions.size()); _order_mux = this; me->handler = handler; - me->order_gtwy = order_gtway; + me->trading_sessions = trading_sessions; _subsribe(); } @@ -985,17 +941,16 @@ void EmMDListener::_subsribe() { } } -void EmMDListener::_send_open_orders_request() const { - std::string sec_name = "ETH-PERPETUAL"; - LOG(OrderMan, Info, - "EmMDListener::_send_open_orders_request calling " - "send_get_open_orders " - "on " - "sec: {}", - sec_name); - me->order_gtwy->send_get_open_orders(sec_name); - me->order_gtwy->send_cancel_all_orders(sec_name); +EMTradingSession *EmMDListener::_find_trading_sessions( + const std::string &account) { + for (auto &t : me->trading_sessions) { + if (t.credential.client_id == account) { + return &t; + } + } + return nullptr; } + /* #endregion */ } // namespace bts::md \ No newline at end of file diff --git a/src/server/sparkd/md/platforms/emumba/EmMDListener.h b/src/server/sparkd/md/platforms/emumba/EmMDListener.h index 6ff9d00e9..81378371c 100644 --- a/src/server/sparkd/md/platforms/emumba/EmMDListener.h +++ b/src/server/sparkd/md/platforms/emumba/EmMDListener.h @@ -1,4 +1,5 @@ #pragma once +#include "EMTradingSession.h" #include "EmumbaSecurityIndex.h" #include "IEMOrderMuxer.h" #include "lib/domain_model/SecurityKey.h" @@ -25,7 +26,7 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, // Run the connector void run(const std::string &config_path); // IEMOrderMuxer interface - emumba::order_entry::order_key launch_new_order( + bts::orderman::OpResult launch_new_order( const emumba::order_entry::new_order &order) override; bool update_order(const emumba::order_entry::order_update &update) override; bool cancel_order(const emumba::order_entry::order_key &key) override; @@ -42,7 +43,6 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, const std::string &msg_result) override; void on_order_update( - const emumba::deribit_connector::data_types::error &ec, const emumba::order_entry::order_key &order_key, const emumba::order_entry::order_state &order_state) override; @@ -60,10 +60,6 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, const emumba::order_entry::order_key &order_key, const emumba::market_data::trade_record &trade) override; - void on_cancel_all_orders( - const emumba::deribit_connector::data_types::error &ec, - const std::string &msg_result) override; - void on_cancel_all_positions( const emumba::deribit_connector::data_types::error &ec, const std::string &msg_result) override; @@ -82,11 +78,6 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, emumba::deribit_connector::instrument_data_interface *interface) override; - // void on_subscription_public_trades( - // const std::string &instrument_name, - // const std::string &trades_message, - // const void *ptr = nullptr) override; - void on_subscription_public_markprice( const std::string &symbol_name, const std::string &markprice_message) override; @@ -95,21 +86,6 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, const std::string &symbol_name, const std::string &index_message) override; - void on_subscription_private_user_orders_raw( - const std::string &instrument_name, - const std::string &user_orders_message, - const void *ptr = nullptr) override; - - void on_subscription_private_user_orders_interval( - const std::string &instrument_name, - const std::string &user_orders_message, - const void *ptr = nullptr) override; - - // void on_subscription_private_user_trades( - // const std::string &instrument_name, - // const std::string &user_trades_message, - // const void *ptr = nullptr) override; - void on_subscription_private_user_portfolio( const std::string &symbol_name, const std::string &user_portfolio_message) override; @@ -149,20 +125,6 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, void on_error(const emumba::market_data::market_data_error &error) override; - void on_new_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key, - const emumba::order_entry::new_order &new_order) override; - - void on_edit_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key, - const emumba::order_entry::order_update &update_order) override; - - void on_cancel_order_rejected( - const emumba::deribit_connector::data_types::error &ec, - const emumba::order_entry::order_key &order_key) override; - virtual ~EmMDListener(); private: @@ -183,7 +145,8 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, const emumba::market_data::security_id &id); // subscribes to all securities here void _subsribe(); - void _send_open_orders_request() const; + bts::orderman::EMTradingSession *_find_trading_sessions( + const std::string &account); public: // the handler and the listener both need each other, however the handler @@ -191,7 +154,7 @@ class EmMDListener : public emumba::deribit_connector::deribit_listener, // listener, the handler is passed using the following function void set_handler( emumba::deribit_connector::deribit_handler *handler, - emumba::deribit_connector::trading_session_interface *order_gtway); + const std::vector &trading_sessions); static IEMOrderMuxer *order_mux() { return _order_mux; } private: diff --git a/src/server/sparkd/md/platforms/emumba/EmumbaMain.cpp b/src/server/sparkd/md/platforms/emumba/EmumbaMain.cpp index 505aa56c2..7e7895569 100644 --- a/src/server/sparkd/md/platforms/emumba/EmumbaMain.cpp +++ b/src/server/sparkd/md/platforms/emumba/EmumbaMain.cpp @@ -1,5 +1,6 @@ #include "EmumbaMain.h" +#include "EMTradingSession.h" #include "EmMDListener.h" #include "EmumbaSecurityIndex.h" #include "lib/config/config.h" @@ -24,6 +25,7 @@ using namespace std; using namespace bts::co2; +using namespace bts::orderman; namespace bts::md { @@ -33,8 +35,7 @@ struct EmumbaMain::PImpl { MDProducer producer; EmMDListener listener; std::shared_ptr real_handler; - std::shared_ptr - trading_session_interface; + std::vector trading_session_vec; PImpl() : sec_index(), recorder( @@ -59,15 +60,21 @@ struct EmumbaMain::PImpl { } // end log bts_assert(conf.has_value()); + LOG(md, Info, "Deribit conf: {}", conf.value()); real_handler = std::make_shared( conf.value().symbol_config_list, conf.value().trading_config, - conf.value().logging_configuration, conf.value().deribit_url, - &listener); - trading_session_interface = std::make_shared< - emumba::deribit_connector::trading_session_interface>( - real_handler->create_new_trading_session()); - listener.set_handler(real_handler.get(), trading_session_interface.get()); + conf.value().credential_map, conf.value().logging_configuration, + conf.value().deribit_url, &listener); + for (const auto &p : conf.value().credential_map) { + const auto &sess = p.second; + auto ts_ptr = std::make_shared< + emumba::deribit_connector::trading_session_interface>( + real_handler->create_new_trading_session(sess)); + trading_session_vec.push_back({sess, ts_ptr}); + } + bts_assert(!trading_session_vec.empty()); + listener.set_handler(real_handler.get(), trading_session_vec); } }; diff --git a/src/server/sparkd/md/platforms/emumba/IEMOrderMuxer.h b/src/server/sparkd/md/platforms/emumba/IEMOrderMuxer.h index d1c1c2a4d..9590cfbe4 100644 --- a/src/server/sparkd/md/platforms/emumba/IEMOrderMuxer.h +++ b/src/server/sparkd/md/platforms/emumba/IEMOrderMuxer.h @@ -11,15 +11,22 @@ namespace bts::orderman { +struct EMPosition { + emumba::order_entry::position position; + std::string sub_account; +}; + // This is the order data passed by the EmMDListener via the order_update_cb struct EMOrderState { - double order_px; + size_t n_cbs = 0; + emumba::order_entry::status status; // copied directly + double order_px; // copied only when qty > 0 (might not ne needed anymore) double order_qty; + // these are all computed from the fills double total_fills = 0; double avg_filled_price = 0; double last_filled_qty = 0; double last_filled_price = 0; - emumba::order_entry::status status; boost::container::small_vector trades; static bool eq(double d1, double d2) { @@ -30,20 +37,21 @@ struct EMOrderState { return std::get(qty.value()); } - emumba::order_entry::order_state update( - const emumba::order_entry::order_state &o_state) { + void update(const emumba::order_entry::order_state &o_state) { using namespace emumba::market_data; using namespace emumba::order_entry; + n_cbs++; status = o_state.order_status; + if (!eq(extract_qty(o_state.qty), 0)) { + order_px = o_state.px.to_double(); + order_qty = extract_qty(o_state.qty); + } else { + LOG(OrderMan, Error, + "EMOrderState::update ZERO qty, px, qty not copied"); + } last_filled_qty = 0; last_filled_price = 0; trades.clear(); - if (!eq(extract_qty(o_state.qty), 0)) { - // TODO - // right now EM generates 0 qty updates, that is ignored - order_px = o_state.px.to_double(); - order_qty = extract_qty(o_state.qty); - } // all fill data is derived from trades instead of order_state's fill data // (for historic reasons). we do log an error if they're off if (!o_state.trades.empty()) { @@ -60,19 +68,21 @@ struct EMOrderState { } if (!eq(total_fills, extract_qty(o_state.total_fills)) || !eq(avg_filled_price, o_state.avg_price.to_double())) { - LOG(OrderMan, Error, + LOG(OrderMan, Warn, "EMOrderState::order_state discrepency total_fills: {} != {} " "avg_filled_px: {} != {}", total_fills, extract_qty(o_state.total_fills), avg_filled_price, o_state.avg_price.to_double()); } - return {o_state.order_status, quantity(order_qty), - quantity(total_fills), price(order_px), - price(avg_filled_price), o_state.trades, - o_state.exchange_order_state}; } }; +struct OpResult { + bool is_success; + emumba::order_entry::order_key ok; + std::string err_msg; +}; + inline std::ostream &operator<<(std::ostream &out, EMOrderState const &s) { out << "status: " << static_cast(s.status) << " pr: " << s.order_px << " q: " << s.order_qty << " fills: " << s.total_fills @@ -83,13 +93,24 @@ inline std::ostream &operator<<(std::ostream &out, EMOrderState const &s) { return out; } +inline std::ostream &operator<<(std::ostream &out, EMPosition const &p) { + const auto &pos = p.position; + out << "subaccount_index: " << pos.subaccount_index + << " subaccount: " << p.sub_account + << " sec_id: " << std::get(pos.sec_id.value()) + << " qty: " << std::get(pos.qty.value()) + << " price: " << pos.average_price.to_double() + << " side: " << (int)pos.position_side; + return out; +} + using OnEMOrderUpdate = std::function; using OnEMExchangePositionUpdate = - std::function &)>; + std::function &)>; using OnEMExchangeOpenOrderUpdate = std::function &)>; @@ -103,7 +124,8 @@ class IEMOrderMuxer { //////////////////////////////////////////////////////////////////////////// // These calls enter, update and cancel a single order respectively. // Their results are corresponded in the order_update_cb callback - virtual emumba::order_entry::order_key launch_new_order( + // TODO, return OpResult + virtual OpResult launch_new_order( const emumba::order_entry::new_order &order) = 0; virtual bool update_order( const emumba::order_entry::order_update &update) = 0;