Merge branch 'spark_crypto.multiple_accounts' into spark_crypto.dev

This commit is contained in:
taha afzal committed 2022-07-11 17:44:02 -04:00
commit 5cedf74406
17 files changed
+1093 -976

No files matched your search

@@ -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:
+86 -57
View File
@@ -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 <memory>
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<bts::config::toggles::ExchangeSubAccounts>()) {
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<std::string, uint32_t>
get_clearing_account_map(const AdminData &);
static std::map<std::string, uint32_t> 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<const BTSAccount *>
accounts(const AdminData &data, bool include_deleted);
static std::vector<BTSAccount *>
accounts_mutable(AdminData &data, bool include_deleted);
static std::vector<const BTSAccount *> accounts(
const AdminData &data, bool include_deleted);
static std::vector<BTSAccount *> 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<const BTSUser *>
users(const AdminData &data, bool include_deleted);
static std::vector<BTSUser *>
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<const BTSUser *> users(
const AdminData &data, bool include_deleted);
static std::vector<BTSUser *> 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
+15
View File
@@ -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{
+11
View File
@@ -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;
+3 -7
View File
@@ -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
+2 -1
View File
@@ -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);
@@ -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<config::toggles::DefaultAccount>()) {
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<emumba::order_entry::position> positions;
std::vector<EMPosition> 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<std::string, api::admin::BTSAccount *>("", nullptr);
}
auto account_name = entry->bts_account_name();
auto bts_account_ptr =
admin::AdminServiceUtils::find_account(me->admin_data, account_name);
return std::tuple<std::string, api::admin::BTSAccount *>(
@@ -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<std::string>(pos.sec_id.value());
std::get<std::string>(pos.position.sec_id.value());
auto sec = get_sec(exch_sec_desc);
double pos_qty = std::get<double>(pos.qty.value());
auto [account_name, bts_account_ptr] = get_account(sec);
double pos_qty = std::get<double>(pos.position.qty.value());
auto [account_name, bts_account_ptr] = get_account(sec, pos.sub_account);
std::optional<uint32_t> account_id =
bts_account_ptr == nullptr
? std::nullopt
: std::optional<uint32_t>(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());
@@ -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;
@@ -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<uint, emumba::deribit_connector::configuration::credential_config>
read_credential_config(rapidjson::Document &doc) {
using RJR = RapidJsonReader;
using namespace emumba::deribit_connector;
std::map<uint, configuration::credential_config> 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<uint, configuration::credential_config>(rv_i.index, rv_i));
}
return rv;
}
std::optional<DeribitDemoConfiguration> DeribitDemoConfiguration::read_file(
const std::string &config_path) {
std::ifstream configFile(config_path);
rapidjson::IStreamWrapper isw{configFile};
@@ -112,6 +150,7 @@ std::optional<DeribitDemoConfiguration> 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;
}
@@ -1,6 +1,8 @@
#pragma once
#include <emumba-deribit-connector/deribit_utils.h>
#include <iostream>
#include <list>
#include <map>
#include <string>
namespace bts::cmds {
@@ -13,9 +15,33 @@ struct DeribitDemoConfiguration {
logging_configuration;
emumba::deribit_connector::configuration::trading_session_config
trading_config;
std::map<uint, emumba::deribit_connector::configuration::credential_config>
credential_map;
static std::optional<DeribitDemoConfiguration> 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
File diff suppressed because it is too large. Load diff
@@ -1,151 +1,158 @@
#pragma once
#include "UserInstrumentData.h"
#include "rapidjson/document.h"
#include <bits/stdint-uintn.h>
#include <emumba-deribit-connector/deribit_handler.h>
#include <emumba-deribit-connector/deribit_listener.h>
#include <emumba-deribit-connector/instrument_data_interface.h>
#include <emumba-deribit-connector/trading_session_interface.h>
#include <list>
#include <map>
#include <memory>
#include <unordered_map>
// #pragma once
// #include "UserInstrumentData.h"
// #include "rapidjson/document.h"
// #include <bits/stdint-uintn.h>
// #include <emumba-deribit-connector/deribit_handler.h>
// #include <emumba-deribit-connector/deribit_listener.h>
// #include <emumba-deribit-connector/instrument_data_interface.h>
// #include <emumba-deribit-connector/trading_session_interface.h>
// #include <list>
// #include <map>
// #include <memory>
// #include <unordered_map>
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<emumba::market_data::security const *>
&complete_security_list) override;
// void on_securities(const std::vector<emumba::market_data::security const
// *>
// &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 &quote,
const void *ptr = nullptr) override;
// void on_quote(
// const emumba::market_data::quote &quote,
// 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<emumba::market_data::trade_record const *> &trades,
__attribute__((unused)) const void *ptr = nullptr) override;
// void on_trades(
// const std::vector<emumba::market_data::trade_record const *> &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<std::string, uint32_t> _book_updates = {};
int _n_bk_updates = 0;
int _n_other_updates = 0;
std::list<UserInstrumentData>
_instruments; // List of user defined class objects
std::map<std::string, emumba::deribit_connector::instrument_data_interface *>
_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<emumba::deribit_connector::deribit_handler>
_deribit_conn; // Shared pointer of deribit connector. This pointer can
// be used to configure/run the connector.
std::shared_ptr<emumba::deribit_connector::trading_session_interface>
_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<std::string, uint32_t> _book_updates = {};
// int _n_bk_updates = 0;
// int _n_other_updates = 0;
// std::list<UserInstrumentData>
// _instruments; // List of user defined class objects
// std::map<std::string, emumba::deribit_connector::instrument_data_interface
// *>
// _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<emumba::deribit_connector::deribit_handler>
// _deribit_conn; // Shared pointer of deribit connector. This pointer
// can
// // be used to configure/run the connector.
// std::shared_ptr<emumba::deribit_connector::trading_session_interface>
// _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
@@ -0,0 +1,16 @@
#pragma once
#include "server/sparkd/cmds/crypto/DeribitDemoConfiguration.h"
#include <emumba-deribit-connector/deribit_handler.h>
#include <emumba-deribit-connector/deribit_listener.h>
#include <emumba-deribit-connector/trading_session_interface.h>
namespace bts::orderman {
struct EMTradingSession {
emumba::deribit_connector::configuration::credential_config credential;
std::shared_ptr<emumba::deribit_connector::trading_session_interface>
trading_interface;
};
} // namespace bts::orderman
@@ -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 <bits/stdint-intn.h>
@@ -36,6 +38,7 @@
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <string>
@@ -47,6 +50,7 @@
#include <vector>
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<std::string, 2> 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<std::string, 2> currencies = {
"BTC", "ETH"};
const std::vector<EMTradingSession> *sessions;
size_t n_pending_reqs = 0;
size_t n_reqs_while_waiting = 0;
std::vector<emumba::order_entry::position> total_pos = {};
std::vector<EMPosition> total_pos = {};
void reset_new_requests() {
n_pending_reqs = currencies.size();
n_reqs_while_waiting = 0;
total_pos.clear();
PositionRequestHelper(std::vector<EMTradingSession> *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<emumba::order_entry::position const *> &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<EMTradingSession> trading_sessions;
EmumbaSecurityIndex &index;
MDProducer &md_producer;
std::unordered_map<std::string, SecurityAuxData> 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<int64_t, EMTradingSession *> order_acc_map;
std::unordered_map<int64_t, bts::orderman::EMOrderState> 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<std::string>(order.order_def.sec_id.value());
auto qty = std::get<double>(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<double>(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<emumba::order_entry::deribit_order_state>(
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<int>(order_state.order_update_type),
exchange_order_state.exchange_order_id,
static_cast<int>(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<int>(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<int>(p.position_side),
pos);
}
void EmMDListener::on_get_all_positions(
const emumba::deribit_connector::data_types::error &ec,
const std::vector<emumba::order_entry::position const *> &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<int>(p->position_side),
std::get<double>(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<int>(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<EMTradingSession> &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
@@ -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<bts::orderman::EMTradingSession> &trading_sessions);
static IEMOrderMuxer *order_mux() { return _order_mux; }
private:
@@ -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<emumba::deribit_connector::deribit_handler> real_handler;
std::shared_ptr<emumba::deribit_connector::trading_session_interface>
trading_session_interface;
std::vector<EMTradingSession> 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<emumba::deribit_connector::deribit_handler>(
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);
}
};
@@ -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<emumba::market_data::trade_record, 2> trades;
static bool eq(double d1, double d2) {
@@ -30,20 +37,21 @@ struct EMOrderState {
return std::get<double>(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<int>(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<std::string>(pos.sec_id.value())
<< " qty: " << std::get<double>(pos.qty.value())
<< " price: " << pos.average_price.to_double()
<< " side: " << (int)pos.position_side;
return out;
}
using OnEMOrderUpdate = std::function<void(
const emumba::deribit_connector::data_types::error &,
const emumba::order_entry::order_key &,
const EMOrderState &)>;
using OnEMExchangePositionUpdate =
std::function<void(const std::vector<emumba::order_entry::position> &)>;
std::function<void(const std::vector<EMPosition> &)>;
using OnEMExchangeOpenOrderUpdate = std::function<void(
const std::vector<emumba::order_entry::open_order const *> &)>;
@@ -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;