diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index fc6f48243..f2ba4c36e 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -5,7 +5,8 @@ sort_by = "weight" insert_anchor_links = "right" +++ ## 2.5.0 -### User Visible Settings +### User Visible Changes + - Added loss limit risk check - Made algos, synthetics and user names private so that multiple users can share a single system privately. - Allowed the mini order book defaults for column widths to be changed from the mini order book - Allowed the mini order book to shrink to the minimum size that will be needed to display the selected columns diff --git a/src/lib/api/public/Update.h b/src/lib/api/public/Update.h index bc2885e2f..3d18c5d6d 100644 --- a/src/lib/api/public/Update.h +++ b/src/lib/api/public/Update.h @@ -27,7 +27,12 @@ namespace api { _removed_items(std::move(removed)) {} - Update(const Update& other) = delete; + Update(const Update& other) : _all_items(other._all_items), + _added_items(other._added_items), + _changed_items(other._changed_items), + _removed_items(other._removed_items) + {} + Update(Update&& other) : _all_items(std::move(other._all_items)), _added_items(std::move(other._added_items)), @@ -104,4 +109,4 @@ namespace api { } -}}//namespace \ No newline at end of file +}}//namespace diff --git a/src/lib/api/services/AdminService.proto b/src/lib/api/services/AdminService.proto index 23ae7337a..f79cc5b1c 100644 --- a/src/lib/api/services/AdminService.proto +++ b/src/lib/api/services/AdminService.proto @@ -149,6 +149,7 @@ message BTSAccount{ ExchangeAccountData exchange_account_data = 110; // extra parameters for risk enforcement RiskLimitEnforcement risk_limit_enforcement=120; + AccountLossLimit account_loss_limit = 130; } message RiskLimitEnforcement{ @@ -190,6 +191,11 @@ message AccountExchangeConnections{ repeated string exchange_connection_names = 20; } +message AccountLossLimit{ + bool enforce = 10; + uint32 total_loss_limit = 20; + // if we need per product we can add it here +} /************************************************************************/ /***************************Exchange Data********************************/ /************************************************************************/ diff --git a/src/lib/api/services/PositionService.proto b/src/lib/api/services/PositionService.proto index fa14b930c..c7879cc5d 100644 --- a/src/lib/api/services/PositionService.proto +++ b/src/lib/api/services/PositionService.proto @@ -8,6 +8,7 @@ import "lib/domain_model/Security.proto"; message PositionUnit{ int32 record_id = 1 [(bts.api.key)=true]; string account = 10; + uint32 account_id = 15; uint32 security_id = 20; double sod_long_pos = 30; double sod_long_avg_price = 40; @@ -19,6 +20,21 @@ message PositionUnit{ double day_short_avg_price = 100; } +message PNLUnit{ + int32 record_id = 1 [(bts.api.key)=true]; + PositionUnit pos = 10; + double cash_value = 20; + double bid_price = 30; + double ask_price = 40; + double last_price = 50; + double settlement_price = 60; +} + +message AccountPNL{ + uint32 account_id = 1 [(bts.api.key)=true]; + double day_pnl = 20; +} + message ManualFill { int32 record_id = 1 [(bts.api.key)=true]; uint32 security_key = 2; @@ -53,5 +69,6 @@ service PositionService { // subscription rpc manual_fills(bts.api.VoidMessage) returns (stream ManualFill); rpc position_data(bts.api.VoidMessage) returns (stream PositionUnit); - + rpc pnl_data(bts.api.VoidMessage) returns (stream PNLUnit); + rpc pnl_account_data(bts.api.VoidMessage) returns (stream AccountPNL); } \ No newline at end of file diff --git a/src/lib/orderman/actors/FillStore.cpp b/src/lib/orderman/actors/FillStore.cpp index 2de9e5eab..13c99fda3 100644 --- a/src/lib/orderman/actors/FillStore.cpp +++ b/src/lib/orderman/actors/FillStore.cpp @@ -126,6 +126,7 @@ void FillStore::on_execution_report( if (it != me->known_orders.end()) { auto &order_def = it->second; fill.set_account(order_def.account()); + fill.set_internal_account_id(order_def.account_id()); } else me->fills_with_unresolved_accounts[er.order_key] .fills.push_back(fill); @@ -153,6 +154,7 @@ void FillStore::on_order_definition_update( auto &unresolved_fills = me->fills_with_unresolved_accounts[ev.key]; for (auto &f : unresolved_fills.fills) { f.set_account(ev.def->account()); + f.set_internal_account_id(ev.def->account_id()); auto fv = utils::pb::to_string(f); me->store->update(fills_ns, f.fill_key(), fv); publish(me->fill_stream, f, *unresolved_fills.security); diff --git a/src/lib/orderman/actors/SODPosition.cpp b/src/lib/orderman/actors/SODPosition.cpp index 18f6d83c4..0612e881f 100644 --- a/src/lib/orderman/actors/SODPosition.cpp +++ b/src/lib/orderman/actors/SODPosition.cpp @@ -1,6 +1,7 @@ #include "lib/orderman/actors/SODPosition.h" #include "lib/config/config.h" #include "lib/config/protos/orders_fills_cleanup.pb.h" +#include "lib/api/service_helpers/AdminServiceUtils.h" #include "lib/config/protos/toggles.pb.h" #include "lib/logging/logging.h" #include "lib/utils/PBUtils.h" @@ -131,6 +132,7 @@ void SODPosition::_merge_pos(Fill &pos, const Fill &fill) { void SODPosition::_zero_pos(Fill &pos, const Fill &fill, api::Side side) { pos.set_security_key(fill.security_key()); pos.set_account(fill.account()); + pos.set_internal_account_id(fill.internal_account_id()); pos.set_side(side); pos.mutable_timestamp()->set_seconds(_sod_time.tv_sec); pos.mutable_timestamp()->set_nanos(0); @@ -140,14 +142,20 @@ void SODPosition::_zero_pos(Fill &pos, const Fill &fill, api::Side side) { pos.set_last_shares(0); } -bool SODPosition::add_fill_to_sod_pos(const Fill &fill) { +bool SODPosition::add_fill_to_sod_pos(const Fill &fill) { if (_enabled && fill.timestamp().seconds() < _sod_time.tv_sec) { - uint32_t seckey = fill.security_key(); - const std::string &acct = fill.account(); - auto acct_it = _sod_map.find(acct); + if (!bts::admin::AdminServiceUtils::has_id(fill.internal_account_id())){ + LOG(persist, Error, "SODPosition::add_fill_to_sod_pos Could not find " + "account_id for fill:{} account:{}", + fill.fill_key(), fill.account()); + return false; + } + uint32_t seckey = fill.security_key(), + account_id = fill.internal_account_id(); + auto acct_it = _sod_map.find(account_id); if (acct_it == _sod_map.end()) - _sod_map[acct] = SecPosMap(); - acct_it = _sod_map.find(fill.account()); + _sod_map[account_id] = SecPosMap(); + acct_it = _sod_map.find(account_id); bts_assert(acct_it != _sod_map.end()); SecPosMap &sec_map = acct_it->second; auto sec_it = sec_map.find(seckey); @@ -165,7 +173,8 @@ bool SODPosition::add_fill_to_sod_pos(const Fill &fill) { else _merge_pos(pos.second, fill); return true; - } else + } + else return false; } diff --git a/src/lib/orderman/actors/SODPosition.h b/src/lib/orderman/actors/SODPosition.h index 860e0cf2d..fd31b8b3d 100644 --- a/src/lib/orderman/actors/SODPosition.h +++ b/src/lib/orderman/actors/SODPosition.h @@ -16,8 +16,7 @@ SecPosMap; class SODPosition{ private: - std::map _sod_map; - std::map _sec_ptr_map; + std::map _sod_map; const bool _enabled; const timeval _sod_time; private: diff --git a/src/lib/orderman/actors/ServiceBridge.cpp b/src/lib/orderman/actors/ServiceBridge.cpp index 4d104dd5f..227d86c84 100644 --- a/src/lib/orderman/actors/ServiceBridge.cpp +++ b/src/lib/orderman/actors/ServiceBridge.cpp @@ -1,7 +1,9 @@ #include "ServiceBridge.h" #include "lib/api/public/ServiceContext.h" +#include "lib/api/services/PositionService.pb.h" #include "lib/mercury/broker/BrokerProxy.h" +#include "lib/orderman/events/AccountPnLUpdateEvent.h" #include "lib/orderman/events/ActivateOrderEvent.h" #include "lib/orderman/events/CancelOrderEvent.h" #include "lib/orderman/events/DetachOrderEvent.h" @@ -50,6 +52,7 @@ struct ServiceBridge::PImpl { mercury::Stream cancel_order_pub; mercury::Stream detach_order_pub; mercury::Stream new_admin_data_pub; + mercury::Stream account_pnl_pub; std::unordered_set known_orders; std::vector> admin_data_updates; mercury::BrokerProxy &service_call_marshaller; @@ -81,6 +84,7 @@ void ServiceBridge::init() { me->cancel_order_pub = make_stream(); me->detach_order_pub = make_stream(); me->new_admin_data_pub = make_stream(); + me->account_pnl_pub = make_stream(); me->ready.set_value(); } @@ -217,6 +221,21 @@ void ServiceBridge::update_admin_data( }); } +void ServiceBridge::update_account_pnl( + api::position::Pnl_account_dataUpdate const &pnl) { + me->service_call_marshaller.schedule_action([this, pnl]() { + for (auto const &account_pnl : pnl.added()) { + publish(me->account_pnl_pub, AccountID(account_pnl->account_id()), + account_pnl->day_pnl()); + } + for (auto const &account_pnl : pnl.changed()) { + publish(me->account_pnl_pub, + AccountID(account_pnl.current()->account_id()), + account_pnl.current()->day_pnl()); + } + }); +} + bool ServiceBridge::is_ready() const { return me->have_orders && me->order_manager_ready; } diff --git a/src/lib/orderman/actors/ServiceBridge.h b/src/lib/orderman/actors/ServiceBridge.h index bcf225db1..621aaf256 100644 --- a/src/lib/orderman/actors/ServiceBridge.h +++ b/src/lib/orderman/actors/ServiceBridge.h @@ -1,18 +1,25 @@ #pragma once +#include "lib/api/services/PositionService.client.pb.h" #include "lib/config/protos/jetfix.pb.h" -#include "lib/mercury/actors/Actor.h" #include "lib/md/SecurityOracle.h" +#include "lib/mercury/actors/Actor.h" + #include // fwds namespace bts { -namespace mercury {class BrokerProxy;} +namespace mercury { +class BrokerProxy; +} namespace api { class ServiceContext; namespace admin { class AdminData; } +namespace position { +class AccountPNL; +} namespace orderman { class OrderRecord; class Fill; @@ -45,16 +52,14 @@ class ServiceBridge : public mercury::Actor { using OnReady = std::function; using OnOrders = - std::function const &)>; + std::function const &)>; using OnFills = - std::function const &)>; + std::function const &)>; + + using OnOrderOpResult = std::function; - using OnOrderOpResult = - std::function; - ServiceBridge(OnReady const &, OnOrders const &, OnFills const &, - OnOrderOpResult const&, - DynamicOrderRegistry const &, + OnOrderOpResult const &, DynamicOrderRegistry const &, mercury::BrokerProxy &service_call_marshaller, md::SecurityOracle o); void init() override; @@ -71,6 +76,7 @@ class ServiceBridge : public mercury::Actor { void update_admin_data(std::shared_ptr const &admin); + void update_account_pnl(api::position::Pnl_account_dataUpdate const &); private: struct PImpl; diff --git a/src/lib/orderman/actors/order_manager/OrderManager.cpp b/src/lib/orderman/actors/order_manager/OrderManager.cpp index 6aa189e0b..737bee203 100644 --- a/src/lib/orderman/actors/order_manager/OrderManager.cpp +++ b/src/lib/orderman/actors/order_manager/OrderManager.cpp @@ -4,6 +4,7 @@ #include "lib/mercury/events/TimerEvent.h" #include "lib/orderman/actors/order_manager/OrderServices.h" #include "lib/orderman/actors/order_manager/OrderServicesData.h" +#include "lib/orderman/events/AccountPnLUpdateEvent.h" #include "lib/orderman/events/NewAdminDataEvent.h" #include "lib/orderman/events/NewSecuritiesEvent.h" #include "lib/orderman/events/OrderManagerReadyEvent.h" @@ -52,6 +53,8 @@ OrderManager::~OrderManager() {} void OrderManager::init() { subscribe( [this](auto const &admin_update) { this->on_admin_data(admin_update); }); + subscribe( + [this](auto const &pnl_update) { this->on_pnl_update(pnl_update); }); } void OrderManager::on_admin_data(const mercury::Update &m) { @@ -74,6 +77,12 @@ void OrderManager::on_admin_data(const mercury::Update &m) { } } +void OrderManager::on_pnl_update(const mercury::Update &u) { + if (u.events) + for (auto ev : *u.events) + me->services_data.limiter.set_day_pnl(ev.account_id,ev.day_pnl); +} + void OrderManager::on_securities( const mercury::Update &update) { @@ -116,9 +125,9 @@ void OrderManager::on_fill_recovery( for (auto const &ev : *(update.events)) { auto trimmed_account_name = boost::algorithm::trim_copy(ev.fill.account()); - me->services_data.limiter.add(*ev.security, trimmed_account_name, - ev.fill.side(), - Quantity(ev.fill.last_shares()),false); + me->services_data.limiter.add( + *ev.security, trimmed_account_name, ev.fill.side(), + Quantity(ev.fill.last_shares()), false); } me->stored_order_sub = subscribe( diff --git a/src/lib/orderman/actors/order_manager/OrderManager.h b/src/lib/orderman/actors/order_manager/OrderManager.h index bc702c5a5..c97980372 100644 --- a/src/lib/orderman/actors/order_manager/OrderManager.h +++ b/src/lib/orderman/actors/order_manager/OrderManager.h @@ -34,6 +34,7 @@ class OrderServices; class CreateFIXBufferReplyEvent; class GatewayStatusChangeEvent; class NewAdminDataEvent; +class AccountPnLUpdateEvent; struct SessionServicesData; class DynamicOrderRegistry; } // namespace orderman @@ -83,6 +84,7 @@ class OrderManager : public mercury::Actor, public mercury::IPollableActor { void on_gateway_state(const mercury::Update &); void on_timer(const mercury::Update &); void on_admin_data(const mercury::Update &); + void on_pnl_update(const mercury::Update &); void on_poll(trace::PerfLog& log) override; // end external events diff --git a/src/lib/orderman/events/AccountPnLUpdateEvent.h b/src/lib/orderman/events/AccountPnLUpdateEvent.h new file mode 100644 index 000000000..e6882df8e --- /dev/null +++ b/src/lib/orderman/events/AccountPnLUpdateEvent.h @@ -0,0 +1,27 @@ +#pragma once + +#include "lib/api/services/AdminService.pb.h" + +#include "lib/mercury/common/mercury_common.h" +#include "lib/mercury/events/Event.h" +#include "lib/mercury/synopsis/MergeByKey.h" + +#include + +namespace bts { +namespace orderman { + +class AccountPnLUpdateEvent : public mercury::Event { + public: + using SynopsisPolicy = mercury::MergeByKey; + AccountID key() const { return account_id; } + + AccountPnLUpdateEvent(AccountID id, double pnl) + : account_id(id), day_pnl(pnl) {} + + AccountID account_id; + double day_pnl; +}; + +} // namespace orderman +} // namespace bts diff --git a/src/lib/orderman/limiter/LimitStore.cpp b/src/lib/orderman/limiter/LimitStore.cpp index e25807d7c..285273139 100644 --- a/src/lib/orderman/limiter/LimitStore.cpp +++ b/src/lib/orderman/limiter/LimitStore.cpp @@ -5,8 +5,10 @@ namespace orderman { LimitStore::LimitStore(const bts::api::admin::AdminData &admin_data, const std::map &sec_map) - : _admin_data(bts::admin::AdminServiceUtils::sort_limits(admin_data)), - _account_map(bts::admin::AdminServiceUtils::accounts_map(_admin_data)) { + : _admin_data(bts::admin::AdminServiceUtils::sort_limits(admin_data)) { + for (const auto& acct : _admin_data.accounts()) + _account_data_map.insert(std::pair( + acct.id(),AccountData(acct))); for (auto it = sec_map.begin(); it != sec_map.end(); it++) { const api::Security &security = *(it->second); _add_product_entry(security, _admin_data); @@ -22,7 +24,7 @@ LimitStore::LimitStore(const bts::api::admin::AdminData &admin_data, } _set_user_data(); } -void LimitStore::copy_positions_from(LimitStore &source) { +void LimitStore::copy_data_from(LimitStore &source) { // copy securities for (auto it = _sec_map.begin(); it != _sec_map.end(); it++) { SecurityLimitTree *source_security_limit_tree = @@ -30,6 +32,17 @@ void LimitStore::copy_positions_from(LimitStore &source) { if (source_security_limit_tree != nullptr) it->second.copy_positions_from(*source_security_limit_tree); } + // copy pnl's + for (auto it=_account_data_map.begin();it!=_account_data_map.end();it++){ + auto source_it = source._account_data_map.find(it->first); + if(source_it != source._account_data_map.end()) + it->second.curr_day_pnl = source_it->second.curr_day_pnl; + } +} +void LimitStore::set_pnl (AccountID account_id, double pnl){ + auto it = _account_data_map.find(account_id.value()); + bts_assert(it != _account_data_map.end()); + it->second.curr_day_pnl = pnl; } void LimitStore::_add_product_entry( const api::Security &security, diff --git a/src/lib/orderman/limiter/LimitStore.h b/src/lib/orderman/limiter/LimitStore.h index 90a3a7888..b586617c2 100644 --- a/src/lib/orderman/limiter/LimitStore.h +++ b/src/lib/orderman/limiter/LimitStore.h @@ -9,6 +9,7 @@ #include "Limiter.h" #include "ProductLimitTree.h" #include "SecurityLimitTree.h" +#include "lib/os/os.h" namespace bts { namespace orderman { @@ -33,9 +34,20 @@ private: return nullptr; } }; + + class AccountData{ + public: + const bts::api::admin::BTSAccount& account; + double curr_day_pnl; + AccountData (const bts::api::admin::BTSAccount& account) + : + account(account), + curr_day_pnl (os::nan()) + {} + }; const bts::api::admin::AdminData _admin_data; - // just an easy way to find accounts - const std::map _account_map; + // easy account access (uses for loss limit) + std::map _account_data_map; // map of user id's vs the user pointer and acccounts std::map _user_data_map; // map of securities vs their account limits and positions @@ -52,14 +64,20 @@ public: // accessors /////////////// //////////////////////////// - bool has_account (AccountID account_id) const - {return _account_map.find(account_id.value()) != _account_map.end();} + bool has_account (AccountID account_id) const{ + return _account_data_map.find(account_id.value()) != + _account_data_map.end(); + } bool has_security (uint32_t sec_id) const {return _sec_map.find(sec_id) != _sec_map.end();} const bts::api::admin::AdminData& admin_data () const {return _admin_data;} - // position updates //////// - //////////////////////////// - void copy_positions_from(LimitStore& source); + // data updates //////////// + // once the LimitStore is created its position and + // pnl is updated from outside. + //////////////////////////// + // copy_data_from copies the position and + // data from another source + void copy_data_from(LimitStore& source); void add_position(const api::Security& security, AccountID account_id, api::Side side, Quantity quantity, bool recurse){ @@ -88,6 +106,7 @@ public: } } } + void set_pnl (AccountID account_id, double pnl); // risk limit checks //////////////////// // checks to see if the user is allowed to trade @@ -130,11 +149,15 @@ public: Limiter::LimiterQueryResult can_send_new_order(AccountID account_id, const api::Security& security, api::Side side, - Quantity quantity) const{ + Quantity quantity, + bool enforce_clip = true) const{ Limiter::LimiterQueryResult rv; rv.result = Limiter::OK; + _loss_limit(account_id, rv); + if(!rv.ok()) + return rv; const SecurityLimitTree* sec_tree = _find_security(security.id()); bts_assert(sec_tree != nullptr); - rv = sec_tree->can_send_new_order(account_id, side, quantity); + rv = sec_tree->can_send_new_order(account_id, side, quantity, enforce_clip); if (rv.ok() && security.has_spread()){ // if its rejected we dont need to validate further, // however if its ok and its a spread we need to check @@ -142,7 +165,12 @@ public: for (const api::ContractLeg& leg : security.spread().legs()){ api::Side effective_leg_side = side == api::Side::SIDE_BUY ? leg.side() : LimiterUtils::invert_side(leg.side()); Quantity effective_leg_qty = Quantity (quantity.value() * std::abs(leg.quantity())); - rv = can_send_new_order (account_id, leg.security(), effective_leg_side, effective_leg_qty); + // in the case of a spread with future legs the clip limits + // for the legs are not checked. if the legs are are spreads + // themselves then they are checked (eventually it will recuse + // down to a non spread) + rv = can_send_new_order (account_id, leg.security(), effective_leg_side, effective_leg_qty, + leg.security().has_spread()); if (!rv.ok()) return rv; } @@ -152,18 +180,26 @@ public: Limiter::LimiterQueryResult can_update_order(AccountID account_id, const api::Security& security, api::Side side, - Quantity from, Quantity to) const{ + Quantity from, Quantity to, + bool enforce_clip = true) const{ Limiter::LimiterQueryResult rv; rv.result = Limiter::OK; + // in case of order modifications, loss limits are only checked + // for size increases + if (to.value() > from.value()) + _loss_limit(account_id, rv); + if(!rv.ok()) + return rv; const SecurityLimitTree* sec_tree = _find_security(security.id()); bts_assert(sec_tree != nullptr); - rv = sec_tree->can_update_order(account_id, side, from, to); + rv = sec_tree->can_update_order(account_id, side, from, to, enforce_clip); // same logic for the spread legs as above if (rv.ok() && security.has_spread()){ for (const api::ContractLeg& leg : security.spread().legs()){ api::Side effective_leg_side = side == api::Side::SIDE_BUY ? leg.side() : LimiterUtils::invert_side(leg.side()); Quantity effective_leg_from_qty = Quantity (from.value() * std::abs(leg.quantity())); Quantity effective_leg_to_qty = Quantity (to.value() * std::abs(leg.quantity())); - rv = can_update_order (account_id, leg.security(), effective_leg_side, effective_leg_from_qty, effective_leg_to_qty); + rv = can_update_order (account_id, leg.security(), effective_leg_side, effective_leg_from_qty, effective_leg_to_qty, + leg.security().has_spread()); if (!rv.ok()) return rv; } @@ -190,5 +226,39 @@ private: void _add_product_entry(const api::Security& security, const bts::api::admin::AdminData& admin_data); void _set_user_data(); + void _loss_limit(AccountID account_id, + Limiter::LimiterQueryResult& out_res) const{ + // the usual flow should not alter out_res. + // its set to an error state iff : + // i. account is not found + // ii. limit check is enabled but pnl is nan + // iii. limit check is enable and it actually fails + const auto acct_it = _account_data_map.find(account_id.value()); + if(acct_it != _account_data_map.end()){ + const auto& account_data = acct_it->second; + const auto& account = account_data.account; + if (account.has_account_loss_limit() && + account.account_loss_limit().enforce()){ + double pnl = account_data.curr_day_pnl; + if(os::is_nan(pnl)){ + out_res.result = Limiter::LimiterErrorCode::LOSS_LIMIT_BREACHED; + out_res.error_msg = "Could not find account PNL"; + } + else{ + double loss_limit = -1.0 * static_cast( + account.account_loss_limit().total_loss_limit()); + if(pnlid()), side, quantity, recurse); } +void Limiter::set_day_pnl (AccountID account_id, double pnl){ + if (!me->limit_store->has_account(account_id)) + _add_account_and_reset(account_id); + me->limit_store->set_pnl(account_id, pnl); +} Limiter::LimiterQueryResult Limiter::can_trade(UserID user_id, AccountID account_id) const { LimiterQueryResult rv = me->limit_store->can_trade(user_id, account_id); @@ -119,7 +124,7 @@ void Limiter::_add_account_and_reset(AccountID account_id) { } void Limiter::_reset(const bts::api::admin::AdminData &admin_data) { LimitStore *new_store = new LimitStore(admin_data, me->sec_map); - new_store->copy_positions_from(*me->limit_store); + new_store->copy_data_from(*me->limit_store); me->limit_store.reset(new_store); } diff --git a/src/lib/orderman/limiter/Limiter.h b/src/lib/orderman/limiter/Limiter.h index ff6e94c1d..1b7df944e 100644 --- a/src/lib/orderman/limiter/Limiter.h +++ b/src/lib/orderman/limiter/Limiter.h @@ -33,6 +33,7 @@ class Limiter { api::Side, Quantity, bool recurse); void remove(api::Security const &, std::string const & /* account_name */, api::Side, Quantity, bool recurse); + void set_day_pnl (AccountID account_id, double pnl); enum LimiterErrorCode { OK, @@ -45,7 +46,8 @@ class Limiter { ACCOUNT_DEACTIVATED, NO_SUCH_ACCOUNT, USER_DEACTIVATED, - NO_SUCH_USER + NO_SUCH_USER, + LOSS_LIMIT_BREACHED }; struct LimiterQueryResult { diff --git a/src/lib/orderman/limiter/SecurityLimitNode.h b/src/lib/orderman/limiter/SecurityLimitNode.h index be1aa8a90..44f8a53d7 100644 --- a/src/lib/orderman/limiter/SecurityLimitNode.h +++ b/src/lib/orderman/limiter/SecurityLimitNode.h @@ -63,9 +63,11 @@ public: } // risk limit checks //////////////////// - Limiter::LimiterQueryResult can_send_new_order(api::Side side, Quantity quantity) const{ + Limiter::LimiterQueryResult can_send_new_order(api::Side side, + Quantity quantity, + bool enforce_clip = true) const{ Limiter::LimiterQueryResult result;result.result= Limiter::OK; - if (quantity.value() > _clip_size){ + if (enforce_clip && quantity.value() > _clip_size){ result.result = Limiter::CLIP_SIZE_BREACHED; result.error_msg = fmt::format("Security Clip Size (Max {} Qty {})", _clip_size, quantity.value()); return result; @@ -78,9 +80,10 @@ public: result = _product_node.can_send_new_order(side, quantity); return result; } - Limiter::LimiterQueryResult can_update_order(api::Side side, Quantity from, Quantity to) const{ + Limiter::LimiterQueryResult can_update_order(api::Side side, Quantity from, Quantity to, + bool enforce_clip = true) const{ Limiter::LimiterQueryResult result;result.result=Limiter::OK; - if (to.value() > _clip_size){ + if (enforce_clip && to.value() > _clip_size){ result.result = Limiter::CLIP_SIZE_BREACHED; result.error_msg = fmt::format("Security Clip Size (Max {} Qty {})", _clip_size, to.value()); return result; diff --git a/src/lib/orderman/limiter/SecurityLimitTree.h b/src/lib/orderman/limiter/SecurityLimitTree.h index 61115ad2f..37eba73f5 100644 --- a/src/lib/orderman/limiter/SecurityLimitTree.h +++ b/src/lib/orderman/limiter/SecurityLimitTree.h @@ -50,17 +50,19 @@ public: //////////////////// Limiter::LimiterQueryResult can_send_new_order(AccountID account_id, api::Side side, - Quantity quantity) const{ + Quantity quantity, + bool enforce_clip = true) const{ const SecurityLimitNode* node_ptr = _find_account(account_id.value()); bts_assert(node_ptr!=nullptr); - return node_ptr->can_send_new_order(side, quantity); + return node_ptr->can_send_new_order(side, quantity, enforce_clip); } Limiter::LimiterQueryResult can_update_order(AccountID account_id, api::Side side, - Quantity from, Quantity to) const{ + Quantity from, Quantity to, + bool enforce_clip = true) const{ const SecurityLimitNode* node_ptr = _find_account(account_id.value()); bts_assert(node_ptr!=nullptr); - return node_ptr->can_update_order(side, from, to); + return node_ptr->can_update_order(side, from, to, enforce_clip); } // accessors //////////// diff --git a/src/lib/orderman/server/OrderServiceServer.cpp b/src/lib/orderman/server/OrderServiceServer.cpp index af49ce401..a777b7ccb 100644 --- a/src/lib/orderman/server/OrderServiceServer.cpp +++ b/src/lib/orderman/server/OrderServiceServer.cpp @@ -1,11 +1,12 @@ #include "OrderServiceServer.h" #include "lib/api/public/ServiceContext.h" #include "lib/api/services/AdminService.client.pb.h" +#include "lib/api/services/PositionService.client.pb.h" #include "lib/config/config.h" #include "lib/config/protos/jetfix.pb.h" #include "lib/config/protos/orderman_cfg.pb.h" -#include "lib/md/MDConsumer.h" #include "lib/md/MDClient.h" +#include "lib/md/MDConsumer.h" #include "lib/mercury/actors/Timer.h" #include "lib/mercury/executor/Executor.h" #include "lib/metrics/metrics.h" @@ -45,14 +46,14 @@ struct ActorThread { stats.publish(loop_metric); } - void start(trace::PerfLog& log) { + void start(trace::PerfLog &log) { if (cfg.poll()) - thread = threading::make_thread(cfg.thread_name(), [this,&log]() { + thread = threading::make_thread(cfg.thread_name(), [this, &log]() { for (;;) executor.do_work(log); }); else { - thread = threading::make_thread(cfg.thread_name(), [this,&log]() { + thread = threading::make_thread(cfg.thread_name(), [this, &log]() { const auto inner_iter = 1000; while (!done) { auto start = Timer::now(); @@ -90,14 +91,15 @@ ActorThread *find_thread_for_actor( } struct OrderServiceServer::PImpl { - PImpl(bts::api::ServiceContext &ctx, - md::MDClient& mdc, + PImpl(bts::api::ServiceContext &ctx, md::MDClient &mdc, DynamicOrderRegistry const &d, metrics::MetricsContainer &stats, trace::PerfLog &log) : service_bridge(), service_ready(false), known_orders(), known_fills(), publish_orders(), publish_fills(), - admin_service(ctx.locate()), md_consumer(mdc.current_consumer()), - stats(stats), dyn_order_registry(d), log(log), in_flight_order_ops(), + admin_service(ctx.locate()), + position_service(ctx.locate()), + md_consumer(mdc.current_consumer()), stats(stats), + dyn_order_registry(d), log(log), in_flight_order_ops(), current_req_op_id(0) {} ServiceBridge *service_bridge; @@ -111,7 +113,8 @@ struct OrderServiceServer::PImpl { OrderServiceServer::OrdersPublisher publish_orders; OrderServiceServer::FillsPublisher publish_fills; api::admin::AdminService admin_service; - bts::md::MDConsumer& md_consumer; + api::position::PositionService position_service; + bts::md::MDConsumer &md_consumer; metrics::MetricsContainer &stats; DynamicOrderRegistry const &dyn_order_registry; trace::PerfLog &log; @@ -120,12 +123,13 @@ struct OrderServiceServer::PImpl { uint32_t current_req_op_id; }; -OrderServiceServer::OrderServiceServer( - bts::api::ServiceContext &ctx, - md::MDClient& mdc, - DynamicOrderRegistry const &d, metrics::MetricsContainer &stats, - trace::PerfLog &log) - : api::orderman::OrderServiceBase(ctx), me(new PImpl(ctx, mdc, d, stats,log)) { +OrderServiceServer::OrderServiceServer(bts::api::ServiceContext &ctx, + md::MDClient &mdc, + DynamicOrderRegistry const &d, + metrics::MetricsContainer &stats, + trace::PerfLog &log) + : api::orderman::OrderServiceBase(ctx), + me(new PImpl(ctx, mdc, d, stats, log)) { me->publish_orders = make_orders_publisher(); me->publish_fills = make_fills_publisher(); @@ -152,7 +156,7 @@ OrderServiceServer::OrderServiceServer( bts_assert_msg(thread, "Could not find a configured thread for OrderManager. See " "the OrdermanCfg key"); - thread->executor.spawn(d,me->log, mdc.oracle()); + thread->executor.spawn(d, me->log, mdc.oracle()); // Timer thread = find_thread_for_actor("Timer", me->actor_threads); @@ -212,12 +216,10 @@ OrderServiceServer::OrderServiceServer( }, [this, &ctx](auto const &order_op_result) { ctx.post([this, order_op_result] { - this->on_order_op_result(order_op_result); + this->on_order_op_result(order_op_result); }); }, - me->dyn_order_registry, - thread->executor.make_proxy(),mdc.oracle()); - + me->dyn_order_registry, thread->executor.make_proxy(), mdc.oracle()); thread->executor.activate(me->service_bridge); @@ -235,6 +237,13 @@ OrderServiceServer::OrderServiceServer( bts_assert(update.all().size() == 1); me->service_bridge->update_admin_data(update.all()[0]); }); + + // subscribe to position updates and foward them to the service bridge + me->position_service.subscribe_pnl_account_data() | + rxcpp::operators::subscribe( + [this](auto const &update) { + me->service_bridge->update_account_pnl(update); + }); } OrderServiceServer::~OrderServiceServer() { @@ -358,7 +367,7 @@ void OrderServiceServer::get_registered_dynamic_order_types( void OrderServiceServer::on_order_op_result( OrderOpResultEvent const &op_result) { auto it = me->in_flight_order_ops.find(op_result.req_id); - bts_assert(it!=me->in_flight_order_ops.end()); + bts_assert(it != me->in_flight_order_ops.end()); auto &responder = it->second; api::orderman::Response r; r.set_order_key(op_result.ok.value()); diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index 7bc50d309..ff12df496 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1 +1 @@ -set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IMarginObserver.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/PositionServiceCore.cpp;position/PositionServiceServer.cpp;position/tests/PositionTests.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file +set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Span.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/Web.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/WebServer.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IMarginObserver.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/PositionServiceCore.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/tests/PositionTests.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp) \ No newline at end of file diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 6b3b7bbef..61b76dcd9 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -88,7 +88,7 @@ int Run::execute(std::vector const &) { - position::PositionServiceServer position_service(sc); + position::PositionServiceServer position_service(sc,mdclient); metrics::ShellLatencyServer shell_latency_service( sc, stats, utils::Dispatcher::background()); diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp new file mode 100644 index 000000000..c2c50b4f0 --- /dev/null +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -0,0 +1,259 @@ +#include "lib/api/services/OrderService.client.pb.h" +#include "lib/logging/logging.h" +#include "lib/md/MDClient.h" +#include "lib/os/os.h" +#include "PositionServicePNLHelper.h" +#include "lib/config/protos/cme_reference_data.pb.h" +#include "lib/config/config.h" + +#include "lib/utils/LockBox.h" +#include +#include + +#include +#include +#include +#include +#include + +namespace bts { +namespace position{ + +using namespace bts::api::position; +using namespace bts::api::orderman; +using namespace bts::md; + + +class HandleIndex { +public: + enum PNLType{ + UNRESOLVED = 0, + SPREAD, + OUTRIGHT + }; + bts::md::MDClient& _client; + int _sub; + std::optional _consumer; + +public: + utils::LockBox> index; + + HandleIndex(md::MDClient& client): + _client(client), + _sub(0), + _consumer(std::nullopt), + index() { + _sub = _client.on_consumer().subscribe([=](const MDConsumer& c) { on_consumer(c); }); + on_consumer(_client.current_consumer()); + } + ~HandleIndex() { _client.on_consumer().unsubscribe(_sub); } + + MDConsumerHandle _get_handle(SecurityKey key) const{ + auto handle = index.lock([id=key](const auto& index) { + auto iter = index.find(id); + return iter != index.end() ? iter->second : MDConsumerHandle {}; + }); + return handle; + } + PNLType get_pnl_type (SecurityKey key) const{ + auto h = _get_handle(key); + if (h.is_initialized()){ + const auto& sec = h.get_normalized_security(); + if (sec.has_future() || sec.has_option()) + return PNLType::OUTRIGHT; + else + return PNLType::SPREAD; + } + else + return PNLType::UNRESOLVED; + } + std::string get_symbol (SecurityKey key) const{ + auto handle = _get_handle(key); + return handle.get_usersymbol().symbol(); + } + void get_md(SecurityKey key, + double& bid, double& ask, double& last, double& settle){ + auto handle = _get_handle(key); + bid = bts::os::nan(); + ask = bid; + last = bid; + settle = bid; + if(handle.is_initialized()){ + TimeStamp time; + PriceSize bid_ps,ask_ps; + handle.get_direct_book(time, 1, &bid_ps, &ask_ps); + bid = bid_ps.price(); + ask = ask_ps.price(); + PriceSize last_ps; + datetime::LLDateTime trade_time; + handle.get_last_trade(time, last_ps, trade_time, nullptr); + last = last_ps.price(); + settle = handle.settlement_price().price(); + } + } + +private: + void on_consumer(const MDConsumer& c) { + MDConsumer temp(c); + if (temp.all_heartbeats_ok()) { + auto existing = _consumer ? _consumer->id() : 0; + LOG(md,Info, "Updating MBOService MDConsumer. Old {} new {}", existing, temp.id()); + // clear the index + index.lock([](auto& index) { index.clear(); }); + // Swap to new consumer + if (_consumer) { + _consumer->swap(temp); + } + else { _consumer = temp; } + // Subscribe to on_security + auto id = _consumer->id(); + _consumer->on_security([this,id](const SecurityPtr&, MDConsumerHandle handle) { + if (_consumer->id() == id) { + index.lock([handle](auto& index) { + index[SecurityKey(handle.key())] = handle; + }); + } + }); + } + } +}; + +struct PositionServicePNLHelper::PImpl { + HandleIndex handle_index; + std::map symbol_cpp_map; + std::map sec_cpp_map; + PImpl(bts::md::MDClient& md_client) + : + handle_index(md_client), + symbol_cpp_map(), + sec_cpp_map() + { + const auto& cpp_map = config::get().cpp_entry(); + LOG(md,Info,"PositionServicePNLHelper::cons loaded {} cpps",cpp_map.size()); + for (const auto& p : cpp_map){ + symbol_cpp_map[std::string(p.first)]=p.second; + LOG(md,Info,"PositionServicePNLHelper loading cpp's Sym:{} cpp:{}", + p.first,p.second); + } + } +}; + + +void PositionServicePNLHelper::compute_pnl( + const std::vector& in_pos, + const std::map& account_map, + std::vector& out_pnl, + std::vector& out_account_pnl){ + out_account_pnl.clear(); + for (const PositionUnit* pu_ptr : in_pos) { + const PositionUnit& pu = *pu_ptr; + uint32_t sec_key = pu.security_id(); + double cpp = _get_cpp(sec_key); + double bid, ask, last, settle; + me->handle_index.get_md(SecurityKey(sec_key),bid,ask,last,settle); + PNLUnit pnlu; + pnlu.set_record_id(pu.record_id()); + pnlu.mutable_pos()->CopyFrom(pu); + pnlu.set_cash_value(cpp); + pnlu.set_bid_price(bid); + pnlu.set_ask_price(ask); + pnlu.set_last_price(last); + pnlu.set_settlement_price(settle); + out_pnl.push_back(pnlu); + } + _aggregate_account_pnl(out_pnl,account_map,out_account_pnl); +} + +void PositionServicePNLHelper::_aggregate_account_pnl( + const std::vector& in_pnl, + const std::map& account_map, + std::vector& out_account_pnl){ + out_account_pnl.clear(); + if (account_map.size() == 0) + return; + std::map acc_pnl; + for (const auto& pnlu : in_pnl){ + uint32_t acct_id = pnlu.pos().account_id(); + auto it=acc_pnl.find(acct_id); + if(it==acc_pnl.end()){ + AccountPNL new_acc; + new_acc.set_account_id(acct_id); + new_acc.set_day_pnl(0.0); + acc_pnl[acct_id]=new_acc; + it=acc_pnl.find(acct_id); + } + AccountPNL& acc_pnl = it->second; + double pnl_dollars = _compute_day_pnl(pnlu); + acc_pnl.set_day_pnl(acc_pnl.day_pnl()+pnl_dollars); + } + // for accounts with no positions add 0 + for (const auto& p : account_map){ + uint32_t acct_id = p.second; + if(acc_pnl.find(acct_id) == acc_pnl.end()){ + AccountPNL new_acc; + new_acc.set_account_id(acct_id); + new_acc.set_day_pnl(0.0); + acc_pnl[acct_id]=new_acc; + } + } + for(auto& u : acc_pnl) + out_account_pnl.push_back(u.second); +} + +double PositionServicePNLHelper::_compute_day_pnl ( + const bts::api::position::PNLUnit& u){ + // long + double pnl; + auto pnl_type = me->handle_index.get_pnl_type( + SecurityKey(u.pos().security_id())); + switch(pnl_type){ + case HandleIndex::OUTRIGHT:{ + double md = (u.bid_price() + u.ask_price())*0.5; + md = bts::os::is_nan(md) ? u.bid_price() : md; + md = bts::os::is_nan(md) ? u.ask_price() : md; + md = bts::os::is_nan(md) ? u.settlement_price() : md; + + double long_pnl = std::abs(u.pos().day_long_pos()) * u.cash_value() * + (md - u.pos().day_long_avg_price()), + short_pnl = std::abs(u.pos().day_short_pos()) * u.cash_value() * + (u.pos().day_short_avg_price() - md); + pnl = long_pnl + short_pnl; + break; + } + case HandleIndex::SPREAD: + pnl = 0.0; + break; + case HandleIndex::UNRESOLVED: + pnl = os::nan(); + break; + } + return pnl; +} +double PositionServicePNLHelper::_get_cpp(uint32_t sec_key){ + auto it = me->sec_cpp_map.find(sec_key); + if(it == me->sec_cpp_map.end()){ + // try to find it and put the value there + std::string symbol = me->handle_index.get_symbol(SecurityKey(sec_key)); + auto cppit = me->symbol_cpp_map.find(symbol); + if(cppit == me->symbol_cpp_map.end()){ + LOG(md,Warn,"Could not find cpp for key:{} symbol:{}", + sec_key,symbol); + return bts::os::nan(); + } + else{ + double cpp = cppit->second; + me->sec_cpp_map[sec_key]=cpp; + return cpp; + } + } + else + return it->second; +} +PositionServicePNLHelper::PositionServicePNLHelper(md::MDClient& md_client) +: +me(new PImpl(md_client)){ +} +PositionServicePNLHelper::~PositionServicePNLHelper(){ +} + +}} \ No newline at end of file diff --git a/src/server/sparkd/position/PositionServicePNLHelper.h b/src/server/sparkd/position/PositionServicePNLHelper.h new file mode 100644 index 000000000..32190d471 --- /dev/null +++ b/src/server/sparkd/position/PositionServicePNLHelper.h @@ -0,0 +1,35 @@ +#pragma once + +#include "lib/api/services/PositionService.server.pb.h" +#include "lib/utils/bts_no_copy.h" +#include + +namespace bts { +namespace md { class MDClient;} + +namespace position { + +class MDClient; + +class PositionServicePNLHelper { +private: + struct PImpl; + std::unique_ptr me; +private: + double _compute_day_pnl (const bts::api::position::PNLUnit&); + double _get_cpp (uint32_t); + // aggregates [sec, account]->pnl tp [account]->pnl + void _aggregate_account_pnl( + const std::vector& in_pnl, + const std::map& account_map, + std::vector& out_account_pnl); + public: + PositionServicePNLHelper(md::MDClient& client); + ~PositionServicePNLHelper(); + void compute_pnl(const std::vector& in_pos, + const std::map& account_map, + std::vector& out_pnl, + std::vector& out_account_pnl); +}; +} // namespace position +} // namespace bts diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index 116938572..f73a0178f 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -1,11 +1,14 @@ #include "PositionServiceServer.h" #include "lib/api/services/OrderService.pb.h" #include "lib/api/services/OrderService.client.pb.h" +#include "lib/api/services/AdminService.pb.h" +#include "lib/api/services/AdminService.client.pb.h" #include "lib/api/public/ServiceContext.h" #include "lib/logging/logging.h" #include "lib/utils/PBUtils.h" #include "lib/persistence/SqliteStore.h" #include "lib/utils/Puid.h" +#include "PositionServicePNLHelper.h" #include #include @@ -19,56 +22,93 @@ namespace position{ using namespace bts::api::position; using namespace bts::api::orderman; +using namespace bts::md; static auto const manual_fills_ns = "manual_fills"; struct PositionServiceServer::PImpl { + bts::api::ServiceContext& context; PositionServiceBase::Position_dataStatefulPublisher publisher; + PositionServiceBase::Pnl_dataStatefulPublisher pnl_publisher; + PositionServiceBase::Pnl_account_dataStatefulPublisher pnl_account_publisher; bts::api::orderman::OrderService order_service; - std::map> state; + bts::api::admin::AdminService admin_service; + std::map> state; std::map manual_fills; int id; - + PositionServicePNLHelper pnl_helper; + int64_t poll_period_ms; // manual fills management std::unique_ptr manual_fills_store ; PositionServiceBase::Manual_fillsStatefulPublisher manual_fills_publisher; - + api::admin::AdminData admin_data; + std::map account_map; + PImpl(bts::api::ServiceContext& context, const PositionServiceBase::Position_dataStatefulPublisher& publisher, - const PositionServiceBase::Manual_fillsStatefulPublisher &manual_fills_publisher) + const PositionServiceBase::Pnl_dataStatefulPublisher& pnl_publisher, + const PositionServiceBase::Pnl_account_dataStatefulPublisher& pnl_account_publisher, + const PositionServiceBase::Manual_fillsStatefulPublisher &manual_fills_publisher, + bts::md::MDClient& md_client) : + context(context), publisher(publisher), + pnl_publisher(pnl_publisher), + pnl_account_publisher(pnl_account_publisher), order_service(context.locate()), + admin_service(context.locate()), state(), id(0), + pnl_helper(md_client), + poll_period_ms(500), manual_fills_store(std::make_unique ("manual_fills")), - manual_fills_publisher(manual_fills_publisher) + manual_fills_publisher(manual_fills_publisher), + admin_data(), + account_map() { } }; -PositionServiceServer::PositionServiceServer(bts::api::ServiceContext& context) +PositionServiceServer::PositionServiceServer(bts::api::ServiceContext& context, + bts::md::MDClient& md_client) : PositionServiceBase (context), me(new PImpl(context, make_position_data_stateful_publisher(), - make_manual_fills_stateful_publisher())) + make_pnl_data_stateful_publisher(), + make_pnl_account_data_stateful_publisher(), + make_manual_fills_stateful_publisher(), + md_client)) { me->order_service.subscribe_fills() | rxcpp::operators::subscribe( [this](auto const& update) { - for (const auto& f : update.removed()) - me->publisher.add_or_update(_on_fill(*f,false)); + if(_valid_account_id(*f)) + me->publisher.add_or_update(_on_fill(*f,false)); for (const auto& f : update.added()) - me->publisher.add_or_update(_on_fill(*f,true)); + if(_valid_account_id(*f)) + me->publisher.add_or_update(_on_fill(*f,true)); for (const auto& f : update.changed()) { - me->publisher.add_or_update(_on_fill(*f.previous(),false)); - me->publisher.add_or_update(_on_fill(*f.current(),true)); + if(_valid_account_id(*f.previous()) && _valid_account_id(*f.current())){ + me->publisher.add_or_update(_on_fill(*f.previous(),false)); + me->publisher.add_or_update(_on_fill(*f.current(),true)); + } } me->publisher.flush(); + _compute_pnl_and_publish(); + }); + + me->admin_service.subscribe_admin_data() | + rxcpp::operators::subscribe( + [this](auto const& update) { + for (const auto& r : update.added()) + {_set_admin_data(*r);} + for (const auto& r : update.changed()) + {_set_admin_data(*r.current());} }); + me->context.post([this](){_periodic_poll();},me->poll_period_ms); auto all = me->manual_fills_store->retrieve_all()[manual_fills_ns]; LOG(persist, Info, "Finished loading all {} manual fills", all.size()); ManualFill rec; @@ -102,11 +142,9 @@ bts::api::orderman::Fill PositionServiceServer::to_fill(bts::api::position::Manu return result; } - const PositionUnit& PositionServiceServer::_on_fill (const Fill& f, bool is_add){ - std::string fill_account=_fill_account(f); - PositionUnit& pu=_get_or_add(fill_account,f.security_key()); + PositionUnit& pu=_get_or_add(f); double avg_price, tot_qty; if(f.fill_kind()==bts::api::orderman::Fill::FILL_KIND_SOD){ if(f.side()==api::Side::SIDE_BUY){ @@ -147,14 +185,16 @@ const PositionUnit& PositionServiceServer::_on_fill (const Fill& f, return pu; } -PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, - uint32_t seckey){ - auto &pu = me->state[acct][seckey]; +PositionUnit& PositionServiceServer::_get_or_add (const Fill& f){ + uint32_t account_id = f.internal_account_id(); + uint32_t seckey = f.security_key(); + auto &pu = me->state[account_id][seckey]; if (pu.record_id() == 0) { // new PU - pu.set_record_id(++me->id); - pu.set_account(acct); - pu.set_security_id(seckey); + pu.set_record_id(++me->id); + pu.set_security_id(seckey); + pu.set_account_id(account_id); + pu.set_account(f.account()); } return pu; } @@ -195,6 +235,14 @@ void PositionServiceServer::_avg_price_qty(double base_p, std::string PositionServiceServer::_fill_account(const Fill& fill){ return boost::trim_right_copy(fill.account()); } +bool PositionServiceServer::_valid_account_id (const Fill& fill){ + return fill.internal_account_id() != 0; +} +void PositionServiceServer::_set_admin_data(const api::admin::AdminData& admin_data){ + me->admin_data = admin_data; + for (const auto& a : admin_data.accounts()) + me->account_map[a.name()] = a.id(); +} PositionServiceServer::~PositionServiceServer(){ } @@ -293,4 +341,27 @@ void PositionServiceServer::remove_manual_fill( me->manual_fills_publisher.flush(); } +void PositionServiceServer::_compute_pnl_and_publish(){ + std::vector in_pos; + for (auto& acct_p : me->state) { + for (auto& sec_p : acct_p.second) { + const PositionUnit& pu = sec_p.second; + in_pos.push_back(&pu); + } + } + std::vector pnl; + std::vector account_pnl; + me->pnl_helper.compute_pnl(in_pos,me->account_map,pnl,account_pnl); + for (const auto& u : pnl) + me->pnl_publisher.add_or_update(u); + for (const auto& u : account_pnl) + me->pnl_account_publisher.add_or_update(u); + me->pnl_publisher.flush(); + me->pnl_account_publisher.flush(); +} + +void PositionServiceServer::_periodic_poll(){ + _compute_pnl_and_publish(); + me->context.post([this](){_periodic_poll();},me->poll_period_ms); +} }} diff --git a/src/server/sparkd/position/PositionServiceServer.h b/src/server/sparkd/position/PositionServiceServer.h index cd983e8c6..dac6f2996 100644 --- a/src/server/sparkd/position/PositionServiceServer.h +++ b/src/server/sparkd/position/PositionServiceServer.h @@ -5,16 +5,15 @@ #include namespace bts { -namespace api { -class ServiceContext; -} -namespace api { -namespace orderman { -class Fill; -} -} // namespace api +namespace md { class MDClient;} +namespace api { class ServiceContext; } +namespace api { namespace orderman { class Fill;}} +namespace api { namespace admin { class AdminData;}} + namespace position { +class MDClient; + class PositionServiceServer : public bts::api::position::PositionServiceBase { private: struct PImpl; @@ -28,16 +27,20 @@ class PositionServiceServer : public bts::api::position::PositionServiceBase { _on_fill(const bts::api::orderman::Fill &fill, bool is_add); // given an account and key, finds (or adds if absent) // the PositionUnit entry - bts::api::position::PositionUnit &_get_or_add(const std::string &acct, - uint32_t sec_id); + bts::api::position::PositionUnit &_get_or_add(const bts::api::orderman::Fill& fill); + void _periodic_poll(); + void _compute_pnl_and_publish(); static void _avg_price_qty(double base_p, double base_q, double fill_p, double fill_q, bool is_add, const std::string &fill_id, double &avg_price, double &tot_qty); static std::string _fill_account(const bts::api::orderman::Fill &fill); + static bool _valid_account_id (const bts::api::orderman::Fill& fill); + void _set_admin_data (const api::admin::AdminData& admin_data); public: - PositionServiceServer(bts::api::ServiceContext &context); + PositionServiceServer(bts::api::ServiceContext &context, + md::MDClient&); void create_manual_fill( const ::bts::api::position::ManualFillBatch &, diff --git a/src/web/ui/sass/main.scss b/src/web/ui/sass/main.scss index c37815561..dbf86783d 100644 --- a/src/web/ui/sass/main.scss +++ b/src/web/ui/sass/main.scss @@ -340,3 +340,19 @@ body { } } +.inline-label { + line-height: 1.5; + padding-bottom: 0.6em; + padding-left: 0.625em; + padding-right: 0.625em; + padding-top: 0.6em; + display: inline-flex; +} + +.inline-label:not(:last-child) { + margin-bottom: 0; +} + +.disabled-label { + color: $grey; +} \ No newline at end of file diff --git a/src/web/ui/src/Access.fs b/src/web/ui/src/Access.fs index 3de9afcff..d52725e30 100644 --- a/src/web/ui/src/Access.fs +++ b/src/web/ui/src/Access.fs @@ -106,6 +106,11 @@ module Accounts = riskLimitEnforcement = { productLimitInNetTerms = true } + accountLossLimit = + { + enforce = false + totalLossLimit = 0u + } } diff --git a/src/web/ui/src/Accounts/State.fs b/src/web/ui/src/Accounts/State.fs index fcbaac147..bccf5c126 100644 --- a/src/web/ui/src/Accounts/State.fs +++ b/src/web/ui/src/Accounts/State.fs @@ -286,6 +286,12 @@ let update msg (model:Model) : Model * Cmd = { model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty | EnforceProductLimitInNetTerms value -> {model with scratch = {model.scratch with riskLimitEnforcement = {productLimitInNetTerms = value}}}, Cmd.none + + | EnforceLossLimit e -> + { model with scratch = { model.scratch with accountLossLimit = { model.scratch.accountLossLimit with enforce = e} } }, Cmd.Empty + | TotalLossLimit tll -> + { model with scratch = { model.scratch with accountLossLimit = { model.scratch.accountLossLimit with totalLossLimit = tll} } }, Cmd.Empty + | SecurityLimits limits -> { model with scratch = { model.scratch with securityPositionLimits = limits } }, Cmd.Empty | DeleteSecurityLimit i -> diff --git a/src/web/ui/src/Accounts/Types.fs b/src/web/ui/src/Accounts/Types.fs index f249085bf..143a1fa7d 100644 --- a/src/web/ui/src/Accounts/Types.fs +++ b/src/web/ui/src/Accounts/Types.fs @@ -73,6 +73,9 @@ type Msg = | DeleteProductLimit of int | EnforceProductLimitInNetTerms of bool + | EnforceLossLimit of bool + | TotalLossLimit of uint32 + | SecurityLimits of AccountSecurityPositionLimitUnit[] | DeleteSecurityLimit of int // ExchangeData diff --git a/src/web/ui/src/Accounts/View.fs b/src/web/ui/src/Accounts/View.fs index 0b66c54cb..454977ea3 100644 --- a/src/web/ui/src/Accounts/View.fs +++ b/src/web/ui/src/Accounts/View.fs @@ -550,6 +550,19 @@ let lazyProductLimitsView model dispatch = productLimits model dispatch +let lossLimitView model dispatch = + div [] [ + div [ ClassName "columns" ][ + h1 [ ClassName "is-size-3 column is-narrow" ][str "Loss Limit" ] + div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ] + [str "If Enabled, this limits the account's loss."] + ] + div [][ + Fields.checkbox "Enable Loss Limit" "" model.scratch.accountLossLimit.enforce [] (EnforceLossLimit >> dispatch) + Fields.inlineText "Total Loss Limit" (string model.scratch.accountLossLimit.totalLossLimit) [] (not model.scratch.accountLossLimit.enforce) (TotalLossLimit >> dispatch) + ] + ] + let securityLimitsView model dispatch = let headerRow:TableControl.row = { @@ -670,7 +683,7 @@ let LimitsView model dispatch = div [ Class "limits-container"] [ lazyClipLimitsView model dispatch lazyProductLimitsView model dispatch - + lossLimitView model dispatch //securityLimitsView model dispatch accountControls model dispatch diff --git a/src/web/ui/src/Controls/Fields.fs b/src/web/ui/src/Controls/Fields.fs index 2fbd6cd2f..0c81a8d28 100644 --- a/src/web/ui/src/Controls/Fields.fs +++ b/src/web/ui/src/Controls/Fields.fs @@ -31,6 +31,22 @@ let text (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange = ] ] +let inlineText (lbl:string) (dv:string) (attrs:IHTMLProp list) (disabled:bool) onchange = + let disabledLabel = if disabled then "disabled-label" else "" + span [ ClassName "field" ] + [ + label [ ClassName ("label inline-label " + disabledLabel)][str lbl] + span [ ClassName "control" ] + [ input ([ + ClassName "input" + Type "text" + Value dv + OnChange (fun ev -> !!ev.target?value |> onchange) + Disabled disabled + ] @ attrs) + ] + ] + let textPair (v:string*string) (keyAttrs:IHTMLProp list) (valueAttrs:IHTMLProp list) (thirdCol:ReactElement list) (onchange: (string*string) -> string -> string -> unit) = div [ ClassName "columns" ] [ @@ -194,7 +210,7 @@ let radioButton (lbl:string) (description:string) (dv:bool) (attrs:IHTMLProp lis let mapSelectEx (lbl:string) (options:Map) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) (is_disabled:bool option) = - let dis = + let dis = match is_disabled with | None -> false | Some a -> a @@ -214,7 +230,7 @@ let mapSelectEx (lbl:string) (options:Map) (defaultText:string op Label lbl div [ ClassName "control" ] [ - div [ ClassName "select"] + div [ ClassName "select"] [ select [ Value dv diff --git a/testing/manual/admin/clip_limits.txt b/testing/manual/admin/clip_limits.txt index 97883bd46..98d0751ca 100644 --- a/testing/manual/admin/clip_limits.txt +++ b/testing/manual/admin/clip_limits.txt @@ -19,3 +19,8 @@ Enter a Clip Size of 10. Make sure orders > 10 are rejected and < 10 are allowed 7. Delete the BZ spread clip limits row 8. Verify you can no longer enter BZ spread trades, but you can still enter BZ future trades + +9. Delete all rows for clip limits. Make sure you can not enter a future or spread order. Now +enter a row for Spreads (All) with clip limit 100. Make sure that works correctly, ie allows +spreads <= 100 but does not allow futures. Now enter a row for Futures (All) with clip limit 50. +Verify that this works correctly too. \ No newline at end of file diff --git a/testing/manual/admin/loss_limit.txt b/testing/manual/admin/loss_limit.txt new file mode 100644 index 000000000..c0531a5c2 --- /dev/null +++ b/testing/manual/admin/loss_limit.txt @@ -0,0 +1,29 @@ +This test verifies that account loss limits work. + +-1. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets. + +0. Blow away the orders and fills databases (/home/bts/sparkdata/data/databases/orders,fills, +ex_sim_orders) + +Pick a future and 2 accounts (lets call them A and B). + +In the risk admin +a. make sure the clip limits and position limits are high enough for the 2 accounts so they +dont interfare and stop orders +b. for the loss limit enter 1000 for B. + +1. Bring up 2 ladders for the contract you selected, each set to one of the accounts above. Bring up the +PNL window and set it to Mid. Now from account A enter a 100 lot bid and 100 lot ask (so now we have markets). + +2. From Account B cross the sell with a 1 lot buy. Now you should see a negative PNL for B, and a positive for A +(because we bought at higher than the mid in B, and sold for higher than the mid in A) + +3. Go to the risk admin and enter a loss limit for account B (~4 times the PNL for B) + +4. Repeat 2 and continue monitoring the PNL. Sell a few more at the market bid. As soon as the PNL goes below +the loss limits, orders should be rejected with a message saying exactly why. + +5. Increase the loss limit, and hit it again with a few loser trades. + +6. Move the market mid (by moving the 100 lots orders in 1) and try to get B's PNL within the loss limit range. +Now enter more loser trades in B and make it hit the limit again.