#include "MarginServiceServer.h" #include "MarginServiceCore.h" #include "PositionAggregator.h" #include "Position.h" #include "lib/api/service_helpers/AdminServiceUtils.h" #include "lib/orderman/orderman_utils/orderman_utils.h" #include "lib/persistence/SqliteStore.h" #include "lib/config/config.h" #include "lib/config/protos/span.pb.h" #include "lib/domain_model/Security.h" #include "lib/logging/logging.h" #include "lib/utils/bts_assert.h" #include "lib/utils/TimeStamp.h" #include "lib/utils/Dispatcher.h" #include "lib/os/os.h" #include #include using namespace bts::api::orderman; using namespace bts::api::position; using namespace bts::admin; using namespace std; using bts::api::position::MarginResult; namespace bts { namespace position { MarginServiceServer::MarginServiceServer(bts::api::ServiceContext& context, md::MDClient& mdclient) : bts::api::position::MarginServiceBase (context), _admin_service(context.locate()), _publisher(make_margin_data_stateful_publisher()), _report_publisher(make_excess_liquidity_report_stateful_publisher()), _dispatcher(utils::Dispatcher::get_named("MarginServiceServer")), _timer(_dispatcher, 30000, [=]() { publish_all();} ), _position(new PositionAggregator(context.locate(), mdclient)), _margin(new MarginServiceCore(_dispatcher)), //state below _lock(), _last_update(), _admin_data(), _last_report(), _first_time(true) { LOG(Gen, Info, "MarginServiceServer: service started"); // _admin_service.get_admin_data(api::VoidMessage(), // [=] (const bts::api::Result<::bts::api::admin::AdminData> r) // { // if(r.value()) // _admin_data = *r.value(); // }); _admin_service.subscribe_admin_data() | rxcpp::operators::subscribe( [this](auto const &update) { std::scoped_lock l(_lock); bts_assert(update.all().size() == 1); _admin_data = *update.all()[0]; if(_first_time) { auto accts = AdminServiceUtils::accounts(_admin_data, false); for(const auto& i : accts) { incremental_update_report(i->name(), i->id()); } _first_time = false; } }); _timer.start(); } void MarginServiceServer::publish_all() { if(config::get().enabled()) { std::scoped_lock l(_lock); auto accts = AdminServiceUtils::accounts(_admin_data, false); for(const auto& i : accts) { datetime::LLDateTime since = 0; std::string acct = i->name(); auto it = _last_update.find(acct); if(it != _last_update.end()) since = it->second; std::vector pos; AccountPNL pnl; if(_position->query_positions(acct, pos, pnl, &since) && pos.size()) { LOG(Gen, Info, "MarginServiceServer: requesting margin for {} ", acct); _margin->compute_margin(acct, pos, [this, since, acct, pnl](const MarginResult& m) { std::scoped_lock l(_lock); publish_margin(m); publish_excess_liquidity_report(m, pnl); _last_update[acct] = since; }); } } } } MarginServiceServer::~MarginServiceServer() {} void MarginServiceServer::get_margin(const api::position::MarginRequest& request, const api::Response& reply) { if(!config::get().enabled()) { MarginResult res; res.set_account(request.account()); reply(res); } else { std::vector pos; AccountPNL pnl; _position->query_positions(request.account(), pos, pnl); _margin->compute_margin(request.account(), pos, [=](const MarginResult& m) { reply(m); }); } } void MarginServiceServer::get_excess_liquidity_report(const api::position::MarginRequest& request, const api::Response& reply) { std::scoped_lock l(_lock); ExcessLiquidityReport rep; rep.set_account(request.account()); auto it = _last_report.find(request.account()); if(it != _last_report.end()) rep.CopyFrom(it->second); reply(rep); } void MarginServiceServer::publish_margin(const api::position::MarginResult& result) { std::scoped_lock l(_lock); _publisher.add_or_update(result); _publisher.flush(); } void MarginServiceServer::publish_excess_liquidity_report(const api::position::MarginResult& result, const api::position::AccountPNL& pnl) { std::scoped_lock l(_lock); ExcessLiquidityReport report; report.set_account(result.account()); report.set_account_id(pnl.account_id()); report.mutable_account_pnl()->CopyFrom(pnl); report.mutable_margin_result()->CopyFrom(result); auto acct = AdminServiceUtils::find_account(_admin_data, result.account(), false); if(acct && acct->has_margin_limit()) { report.set_leverage_factor( acct->margin_limit().leverage_factor_percentage() ); report.set_cash_balance(acct->margin_limit().cash_balance()); report.set_should_enforce_margin(acct->margin_limit().enforce_margin() && config::get().enabled()); } double netliq = report.leverage_factor() * report.cash_balance(); if(!bts::os::is_nan(result.maint_margin())) netliq -= result.maint_margin(); if(!bts::os::is_nan(pnl.day_pnl())) netliq += pnl.day_pnl(); report.set_excess_liquidity(netliq); _last_report[result.account()] = report; _report_publisher.add_or_update(report); _report_publisher.flush(); } //so the admin ui knows what to do void MarginServiceServer::incremental_update_report(const std::string& account, uint32_t account_id) { std::scoped_lock l(_lock); MarginResult margin; if(!_margin->get_last_valid_result(account, margin)) { margin.Clear(); margin.set_account(account); } AccountPNL pnl; if(!_position->query_pnl(account, pnl)) { pnl.Clear(); pnl.set_account_name(account); pnl.set_account_id(account_id); } publish_excess_liquidity_report(margin, pnl); _last_update[account] = 0; } void MarginServiceServer::set_cash_factor(const ::bts::api::position::CashFactorUpdate& request, const api::Response<::bts::api::ResultMessage>& reply) { std::scoped_lock l(_lock); auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false); if(!acct) { auto msg = "Account " + request.account() +"not found"; api::ResultMessage resp; resp.set_success(false); resp.set_error_message(msg); reply(resp); } else { acct->mutable_margin_limit()->set_leverage_factor_percentage(request.leverage_factor()); AccountUpdateAPIArgument update; update.mutable_complete_data()->CopyFrom(*acct); _admin_service.update_account(update, [this, request, reply, update](const api::Result& admin_result) { api::ResultMessage resp; resp.set_success(admin_result.success()); resp.set_error_message(admin_result.error_message()); reply(resp); incremental_update_report(request.account(), update.complete_data().id()); }); } } void MarginServiceServer::set_cash_balance(const ::bts::api::position::CashBalanceUpdate& request, const api::Response<::bts::api::ResultMessage>& reply) { std::scoped_lock l(_lock); auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false); if(!acct) { auto msg = "Account " + request.account() +"not found"; api::ResultMessage resp; resp.set_success(false); resp.set_error_message(msg); reply(resp); } else { acct->mutable_margin_limit()->set_cash_balance(request.cash_balance()); AccountUpdateAPIArgument update; update.mutable_complete_data()->CopyFrom(*acct); _admin_service.update_account(update, [this, request, reply, update](const api::Result& admin_result) { api::ResultMessage resp; resp.set_success(admin_result.success()); resp.set_error_message(admin_result.error_message()); reply(resp); incremental_update_report(request.account(), update.complete_data().id()); }); } } void MarginServiceServer::set_should_enforce_margin(const ::bts::api::position::EnforceUpdate& request, const api::Response<::bts::api::ResultMessage>& reply) { std::scoped_lock l(_lock); auto acct = AdminServiceUtils::find_account(_admin_data, request.account(), false); if(!acct) { auto msg = "Account " + request.account() +"not found"; api::ResultMessage resp; resp.set_success(false); resp.set_error_message(msg); reply(resp); } else { acct->mutable_margin_limit()->set_enforce_margin(request.should_enforce_margin()); AccountUpdateAPIArgument update; update.mutable_complete_data()->CopyFrom(*acct); _admin_service.update_account(update, [this, request, reply, update](const api::Result& admin_result) { api::ResultMessage resp; resp.set_success(admin_result.success()); resp.set_error_message(admin_result.error_message()); reply(resp); incremental_update_report(request.account(), update.complete_data().id()); }); } } }}