From 21f5fd919d6c019028d79935c27e1993a50bf2e6 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Thu, 13 Jun 2019 15:37:43 -0400 Subject: [PATCH 01/20] Changes in the API for Loss Limit and new parameter in the account to enforce that limit --- src/lib/api/services/AdminService.proto | 6 ++++++ src/lib/api/services/PositionService.proto | 19 ++++++++++++++++++- src/web/ui/src/Access.fs | 5 +++++ 3 files changed, 29 insertions(+), 1 deletion(-) 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..a2842f7a5 100644 --- a/src/lib/api/services/PositionService.proto +++ b/src/lib/api/services/PositionService.proto @@ -19,6 +19,22 @@ 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 settllement_price = 60; +} + +message AccountPNL{ + uint32 account_id = 1 [(bts.api.key)=true]; + string account = 10; + double mid_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/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 + } } From cddadcb2788ce72addb56c6574b75519dc1d6570 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sun, 16 Jun 2019 22:02:16 -0400 Subject: [PATCH 02/20] PositionService exposes new streaming calls pnl_data and pnl_account_data to get detailed and summary pnls --- src/lib/api/services/PositionService.proto | 6 +- src/lib/orderman/limiter/Limiter.cpp | 3 + src/lib/orderman/limiter/Limiter.h | 1 + src/server/sparkd/cmds/Run.cpp | 2 +- .../position/PositionServicePNLHelper.cpp | 199 ++++++++++++++++++ .../position/PositionServicePNLHelper.h | 29 +++ .../sparkd/position/PositionServiceServer.cpp | 62 +++++- .../sparkd/position/PositionServiceServer.h | 22 +- 8 files changed, 301 insertions(+), 23 deletions(-) create mode 100644 src/server/sparkd/position/PositionServicePNLHelper.cpp create mode 100644 src/server/sparkd/position/PositionServicePNLHelper.h diff --git a/src/lib/api/services/PositionService.proto b/src/lib/api/services/PositionService.proto index a2842f7a5..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; @@ -26,13 +27,12 @@ message PNLUnit{ double bid_price = 30; double ask_price = 40; double last_price = 50; - double settllement_price = 60; + double settlement_price = 60; } message AccountPNL{ uint32 account_id = 1 [(bts.api.key)=true]; - string account = 10; - double mid_pnl = 20; + double day_pnl = 20; } message ManualFill { diff --git a/src/lib/orderman/limiter/Limiter.cpp b/src/lib/orderman/limiter/Limiter.cpp index 8f5fbe1c7..20bf88710 100644 --- a/src/lib/orderman/limiter/Limiter.cpp +++ b/src/lib/orderman/limiter/Limiter.cpp @@ -73,6 +73,9 @@ void Limiter::remove(const api::Security &security, else remove(security, AccountID(acct_ptr->id()), side, quantity, recurse); } +void Limiter::set_day_pnl (AccountID, double){ + // TODO: implement +} Limiter::LimiterQueryResult Limiter::can_trade(UserID user_id, AccountID account_id) const { LimiterQueryResult rv = me->limit_store->can_trade(user_id, account_id); diff --git a/src/lib/orderman/limiter/Limiter.h b/src/lib/orderman/limiter/Limiter.h index ff6e94c1d..82f9c8528 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, diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 3c9b1ec1c..770f1a0a1 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..8c87075fb --- /dev/null +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -0,0 +1,199 @@ +#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: + 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); } + const std::string& symbol (SecurityKey key){ + auto handle = index.lock([id=key](const auto& index) { + auto iter = index.find(id); + return iter != index.end() ? iter->second : MDConsumerHandle {}; + }); + return handle.get_usersymbol().symbol(); + } + void get_md(SecurityKey key, + double& bid, double& ask, double& last, double& settle){ + auto handle = index.lock([id=key](const auto& index) { + auto iter = index.find(id); + return iter != index.end() ? iter->second : MDConsumerHandle {}; + }); + 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(); + 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, + std::vector& out_pnl, + std::vector& out_account_pnl){ + out_account_pnl.clear(); + std::map acc_pnl; + for (const PositionUnit* pu_ptr : in_pos) { + const PositionUnit& pu = *pu_ptr; + uint32_t sec_key = pu.security_id(); + uint32_t acct_id = pu.account_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); + // enter into account map + double pnl_dollars = _compute_day_pnl(pnlu); + 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; + acc_pnl.set_day_pnl(acc_pnl.day_pnl()+pnl_dollars); + } + 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 mid = (u.bid_price() + u.ask_price())*0.5, + long_pnl = std::abs(u.pos().day_long_pos()) * u.cash_value() * + (mid - u.pos().day_long_avg_price()), + short_pnl = std::abs(u.pos().day_short_pos()) * u.cash_value() * + (u.pos().day_short_avg_price() - mid); + return long_pnl + short_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()){ + // TODO + // try to find it and put the value there + // const auto& symbol = me->handle_index.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; + // } + return 1000; + } + 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..ff0faf994 --- /dev/null +++ b/src/server/sparkd/position/PositionServicePNLHelper.h @@ -0,0 +1,29 @@ +#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); + public: + PositionServicePNLHelper(md::MDClient& client); + ~PositionServicePNLHelper(); + void compute_pnl(const std::vector& in_pos, + 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 6f4bfa843..d9fef7dc8 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -6,6 +6,7 @@ #include "lib/utils/PBUtils.h" #include "lib/persistence/SqliteStore.h" #include "lib/utils/Puid.h" +#include "PositionServicePNLHelper.h" #include #include @@ -19,40 +20,57 @@ 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; 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; 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()), state(), id(0), + pnl_helper(md_client), + poll_period_ms(1000), manual_fills_store(std::make_unique ("manual_fills")), - manual_fills_publisher(manual_fills_publisher) + manual_fills_publisher(manual_fills_publisher) { } }; -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( @@ -67,8 +85,9 @@ me(new PImpl(context, me->publisher.add_or_update(_on_fill(*f.current(),true)); } me->publisher.flush(); + _compute_pnl_and_publish(); }); - + 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 +121,11 @@ 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(fill_account,f.internal_account_id(), + f.security_key()); double avg_price, tot_qty; if(f.fill_kind()==bts::api::orderman::Fill::FILL_KIND_SOD){ if(f.side()==api::Side::SIDE_BUY){ @@ -147,13 +166,15 @@ const PositionUnit& PositionServiceServer::_on_fill (const Fill& f, return pu; } -PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, +PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, + uint32_t account_id, uint32_t seckey){ auto &pu = me->state[acct][seckey]; if (pu.record_id() == 0) { // new PU pu.set_record_id(++me->id); pu.set_account(acct); + pu.set_account_id(account_id); pu.set_security_id(seckey); } return pu; @@ -293,4 +314,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,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..4390d6694 100644 --- a/src/server/sparkd/position/PositionServiceServer.h +++ b/src/server/sparkd/position/PositionServiceServer.h @@ -5,16 +5,14 @@ #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 position { +class MDClient; + class PositionServiceServer : public bts::api::position::PositionServiceBase { private: struct PImpl; @@ -29,15 +27,19 @@ class PositionServiceServer : public bts::api::position::PositionServiceBase { // 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 account_id, uint32_t sec_id); + 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 std::string _fill_account(const bts::api::orderman::Fill &fill); public: - PositionServiceServer(bts::api::ServiceContext &context); + PositionServiceServer(bts::api::ServiceContext &context, + md::MDClient&); void create_manual_fill( const ::bts::api::position::ManualFillBatch &, From 6a4930767b7833254460a0a28909c0e5282f73fd Mon Sep 17 00:00:00 2001 From: Michael Harding Date: Tue, 18 Jun 2019 16:32:14 -0400 Subject: [PATCH 03/20] SP-34: Add Loss Limit to Spark Admin --- src/web/ui/sass/main.scss | 16 ++++++++++++++++ src/web/ui/src/Accounts/State.fs | 6 ++++++ src/web/ui/src/Accounts/Types.fs | 3 +++ src/web/ui/src/Accounts/View.fs | 15 ++++++++++++++- src/web/ui/src/Controls/Fields.fs | 20 ++++++++++++++++++-- 5 files changed, 57 insertions(+), 3 deletions(-) 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/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 From 60ab67213fb36767dc87740ebf2025a347eb2e92 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Thu, 20 Jun 2019 15:57:09 -0400 Subject: [PATCH 04/20] Ran clang format. --- .../orderman/server/OrderServiceServer.cpp | 41 +++++++++---------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/src/lib/orderman/server/OrderServiceServer.cpp b/src/lib/orderman/server/OrderServiceServer.cpp index af49ce401..fd6f18152 100644 --- a/src/lib/orderman/server/OrderServiceServer.cpp +++ b/src/lib/orderman/server/OrderServiceServer.cpp @@ -4,8 +4,8 @@ #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 +45,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 +90,14 @@ 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()), + 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 +111,7 @@ struct OrderServiceServer::PImpl { OrderServiceServer::OrdersPublisher publish_orders; OrderServiceServer::FillsPublisher publish_fills; api::admin::AdminService admin_service; - bts::md::MDConsumer& md_consumer; + bts::md::MDConsumer &md_consumer; metrics::MetricsContainer &stats; DynamicOrderRegistry const &dyn_order_registry; trace::PerfLog &log; @@ -120,12 +120,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 +153,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 +213,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); @@ -358,7 +357,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()); From e936b80dc6b7e9faa56de31e82aeec73aff21d0d Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Fri, 21 Jun 2019 11:44:51 -0400 Subject: [PATCH 05/20] Forwarded pnl updates to order manager. --- src/lib/CMakeDeps.cmake | 2 +- src/lib/api/public/Update.h | 9 +++++-- src/lib/orderman/actors/ServiceBridge.cpp | 19 +++++++++++++ src/lib/orderman/actors/ServiceBridge.h | 25 ++++++++++------- .../actors/order_manager/OrderManager.cpp | 15 ++++++++--- .../actors/order_manager/OrderManager.h | 2 ++ .../orderman/events/AccountPnLUpdateEvent.h | 27 +++++++++++++++++++ .../orderman/server/OrderServiceServer.cpp | 10 +++++++ src/server/sparkd/CMakeDeps.cmake | 2 +- 9 files changed, 94 insertions(+), 17 deletions(-) create mode 100644 src/lib/orderman/events/AccountPnLUpdateEvent.h diff --git a/src/lib/CMakeDeps.cmake b/src/lib/CMakeDeps.cmake index b05780e88..bef6d7f85 100644 --- a/src/lib/CMakeDeps.cmake +++ b/src/lib/CMakeDeps.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServices.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/core/IOrderServices.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/DynamicOrderRegistry.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orderman_utils/orderman_utils.cpp;orderman/orders/CompositeOrder.cpp;orderman/orders/DynamicOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/TriggerOrder.cpp;orderman/orders/algo/AlgoWrapperOrder.cpp;orderman/orders/algo/IAlgoOrder.cpp;orderman/orders/algo/IAlgoServices.cpp;orderman/orders/algo/IBeforeLaunchAlgoServices.cpp;orderman/orders/algo/algo_orders/CoverAlgo.cpp;orderman/orders/algo/algo_orders/IcebergAlgo.cpp;orderman/orders/algo/algo_orders/JoinAlgo.cpp;orderman/orders/algo/algo_orders/LeanAlgo.cpp;orderman/orders/algo/algo_orders/TopAlgo.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/BookOrderBase.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/OffsetOrder.cpp;orderman/orders/book_algos/PricerOrder.cpp;orderman/orders/queue_holder/QueueHolderOrder.cpp;orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegFillState.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/HedgerManager.cpp;orderman/orders/spreader_orders/spreader/hedger/UnhedgedDelta.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSet.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/orders/spreader_orders/tests/spreader_tests.cpp;orderman/server/OrderServiceServer.cpp;orderman/tests/fat_wrapper_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/persistence_utils.cpp;persistence/tests/PersistenceServiceTests.cpp;plugin/SparkServices.cpp;plugin/plugin.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;tracing/PerfLog.cpp;tracing/bts_trace.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file +set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/spreader.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderManager.cpp;orderman/actors/order_manager/OrderServices.cpp;orderman/actors/order_manager/OrderServicesData.cpp;orderman/core/IOrderServices.cpp;orderman/events/CancelRejectEvent.cpp;orderman/events/NewExecutionReportEvent.cpp;orderman/limiter/LimitStore.cpp;orderman/limiter/Limiter.cpp;orderman/limiter/ProductLimitNode.cpp;orderman/limiter/ProductLimitTree.cpp;orderman/limiter/SecurityLimitNode.cpp;orderman/limiter/SecurityLimitTree.cpp;orderman/limiter/tests/limit_tests.cpp;orderman/order_factory/DynamicOrderRegistry.cpp;orderman/order_factory/OrderFactory.cpp;orderman/order_router/OrderRouter.cpp;orderman/orderman_utils/fix_order_codec.cpp;orderman/orderman_utils/orderman_utils.cpp;orderman/orders/CompositeOrder.cpp;orderman/orders/DynamicOrder.cpp;orderman/orders/NativeOrder.cpp;orderman/orders/Order.cpp;orderman/orders/TimeBoxOrder.cpp;orderman/orders/TriggerOrder.cpp;orderman/orders/algo/AlgoWrapperOrder.cpp;orderman/orders/algo/IAlgoOrder.cpp;orderman/orders/algo/IAlgoServices.cpp;orderman/orders/algo/IBeforeLaunchAlgoServices.cpp;orderman/orders/algo/algo_orders/CoverAlgo.cpp;orderman/orders/algo/algo_orders/IcebergAlgo.cpp;orderman/orders/algo/algo_orders/JoinAlgo.cpp;orderman/orders/algo/algo_orders/LeanAlgo.cpp;orderman/orders/algo/algo_orders/TopAlgo.cpp;orderman/orders/book_algos/BookAlgo.cpp;orderman/orders/book_algos/BookOrderBase.cpp;orderman/orders/book_algos/OCOOrder.cpp;orderman/orders/book_algos/OffsetOrder.cpp;orderman/orders/book_algos/PricerOrder.cpp;orderman/orders/queue_holder/QueueHolderOrder.cpp;orderman/orders/queue_holder/state_workers/QHOEndStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOStartStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForAckStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWaitingForCancelAllStateWorker.cpp;orderman/orders/queue_holder/state_workers/QHOWorkingStateWorker.cpp;orderman/orders/spreader_orders/SpreaderOrder.cpp;orderman/orders/spreader_orders/spreader/LegFillState.cpp;orderman/orders/spreader_orders/spreader/LegPropertyData.cpp;orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.cpp;orderman/orders/spreader_orders/spreader/SingleFillHedger.cpp;orderman/orders/spreader_orders/spreader/SingleLegQuoter.cpp;orderman/orders/spreader_orders/spreader/SpreaderBookkeepingData.cpp;orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.cpp;orderman/orders/spreader_orders/spreader/SpreaderLegData.cpp;orderman/orders/spreader_orders/spreader/SpreaderUtils.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderServices.cpp;orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderPreActivationOrderServices.cpp;orderman/orders/spreader_orders/spreader/hedger/HedgerManager.cpp;orderman/orders/spreader_orders/spreader/hedger/UnhedgedDelta.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSet.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.cpp;orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForIOCWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWaitingForInitialDataStateWorker.cpp;orderman/orders/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/orders/spreader_orders/tests/spreader_tests.cpp;orderman/server/OrderServiceServer.cpp;orderman/tests/fat_wrapper_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/persistence_utils.cpp;persistence/tests/PersistenceServiceTests.cpp;plugin/SparkServices.cpp;plugin/plugin.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;tracing/PerfLog.cpp;tracing/bts_trace.cpp;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/crypto/CipherType.cpp;utils/crypto/CryptoInit.cpp;utils/crypto/Digest.cpp;utils/crypto/KeyCodeHelper.cpp;utils/crypto/PasswordCallback.cpp;utils/crypto/PrivateKey.cpp;utils/crypto/PublicKey.cpp;utils/crypto/iostreambio.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file 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/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..c31e45653 100644 --- a/src/lib/orderman/actors/ServiceBridge.h +++ b/src/lib/orderman/actors/ServiceBridge.h @@ -1,18 +1,25 @@ #pragma once #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 "lib/api/services/PositionService.client.pb.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,7 +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; std::unique_ptr me; 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/server/OrderServiceServer.cpp b/src/lib/orderman/server/OrderServiceServer.cpp index fd6f18152..a777b7ccb 100644 --- a/src/lib/orderman/server/OrderServiceServer.cpp +++ b/src/lib/orderman/server/OrderServiceServer.cpp @@ -1,6 +1,7 @@ #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" @@ -96,6 +97,7 @@ struct OrderServiceServer::PImpl { : service_bridge(), service_ready(false), known_orders(), known_fills(), publish_orders(), publish_fills(), 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) {} @@ -111,6 +113,7 @@ struct OrderServiceServer::PImpl { OrderServiceServer::OrdersPublisher publish_orders; OrderServiceServer::FillsPublisher publish_fills; api::admin::AdminService admin_service; + api::position::PositionService position_service; bts::md::MDConsumer &md_consumer; metrics::MetricsContainer &stats; DynamicOrderRegistry const &dyn_order_registry; @@ -234,6 +237,13 @@ OrderServiceServer::OrderServiceServer(bts::api::ServiceContext &ctx, 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() { diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index e12c685e9..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/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 From 6e07a0c109d1fdb75d3bb05dae202e09b11abc08 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Fri, 21 Jun 2019 11:51:20 -0400 Subject: [PATCH 06/20] Fixed build. --- src/lib/orderman/actors/ServiceBridge.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/lib/orderman/actors/ServiceBridge.h b/src/lib/orderman/actors/ServiceBridge.h index c31e45653..621aaf256 100644 --- a/src/lib/orderman/actors/ServiceBridge.h +++ b/src/lib/orderman/actors/ServiceBridge.h @@ -1,9 +1,9 @@ #pragma once +#include "lib/api/services/PositionService.client.pb.h" #include "lib/config/protos/jetfix.pb.h" #include "lib/md/SecurityOracle.h" #include "lib/mercury/actors/Actor.h" -#include "lib/api/services/PositionService.client.pb.h" #include @@ -19,7 +19,7 @@ class AdminData; } namespace position { class AccountPNL; -}; +} namespace orderman { class OrderRecord; class Fill; @@ -76,7 +76,8 @@ class ServiceBridge : public mercury::Actor { void update_admin_data(std::shared_ptr const &admin); - void update_account_pnl (api::position::Pnl_account_dataUpdate const&); + void update_account_pnl(api::position::Pnl_account_dataUpdate const &); + private: struct PImpl; std::unique_ptr me; From a014dcc98401d93b7e0d92fc142d508744ee8278 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Fri, 21 Jun 2019 17:58:08 -0400 Subject: [PATCH 07/20] abstracted _get_handle in PositionServicePNLHelper::HandleIndex --- .../sparkd/position/PositionServicePNLHelper.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index 8c87075fb..26de78fef 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -42,19 +42,22 @@ public: on_consumer(_client.current_consumer()); } ~HandleIndex() { _client.on_consumer().unsubscribe(_sub); } - const std::string& symbol (SecurityKey key){ + + 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; + } + + const std::string& symbol (SecurityKey key){ + 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 = index.lock([id=key](const auto& index) { - auto iter = index.find(id); - return iter != index.end() ? iter->second : MDConsumerHandle {}; - }); + auto handle = _get_handle(key); bid = bts::os::nan(); ask = bid; last = bid; @@ -184,7 +187,7 @@ double PositionServicePNLHelper::_get_cpp(uint32_t sec_key){ // me->sec_cpp_map[sec_key]=cpp; // return cpp; // } - return 1000; + return 5000; } else return it->second; From a1ead3d1c1711262936a9bf257f096696c8233d4 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sat, 22 Jun 2019 14:24:15 -0400 Subject: [PATCH 08/20] cpp routed correctly now --- .../position/PositionServicePNLHelper.cpp | 41 ++++++++++--------- .../sparkd/position/PositionServiceServer.cpp | 2 +- 2 files changed, 23 insertions(+), 20 deletions(-) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index 26de78fef..df9396c4d 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -51,7 +51,7 @@ public: return handle; } - const std::string& symbol (SecurityKey key){ + std::string get_symbol (SecurityKey key) const{ auto handle = _get_handle(key); return handle.get_usersymbol().symbol(); } @@ -113,6 +113,7 @@ struct PositionServicePNLHelper::PImpl { 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:{}", @@ -163,31 +164,33 @@ void PositionServicePNLHelper::compute_pnl( double PositionServicePNLHelper::_compute_day_pnl ( const bts::api::position::PNLUnit& u){ // long - double mid = (u.bid_price() + u.ask_price())*0.5, - long_pnl = std::abs(u.pos().day_long_pos()) * u.cash_value() * - (mid - u.pos().day_long_avg_price()), + 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() - mid); + (u.pos().day_short_avg_price() - md); return long_pnl + short_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()){ - // TODO // try to find it and put the value there - // const auto& symbol = me->handle_index.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; - // } - return 5000; + 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; diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index 50025e4c0..fc0ff04bb 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -54,7 +54,7 @@ struct PositionServiceServer::PImpl { state(), id(0), pnl_helper(md_client), - poll_period_ms(1000), + poll_period_ms(300), manual_fills_store(std::make_unique ("manual_fills")), manual_fills_publisher(manual_fills_publisher) { From 6f7c6db918205bf8a2611dc8ee4b451071575143 Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Sat, 22 Jun 2019 16:29:55 -0400 Subject: [PATCH 09/20] Updated fill account_id in FillStore. --- src/lib/orderman/actors/FillStore.cpp | 2 ++ 1 file changed, 2 insertions(+) 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); From b2766c283d3e79b64ac2f6ee0441cc942128404f Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sat, 22 Jun 2019 22:05:32 -0400 Subject: [PATCH 10/20] Setting account id in PositionUnit --- .../position/PositionServicePNLHelper.cpp | 38 ++++++++++++------- .../position/PositionServicePNLHelper.h | 8 +++- .../sparkd/position/PositionServiceServer.cpp | 4 +- 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index df9396c4d..75393ff0c 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -128,11 +128,9 @@ void PositionServicePNLHelper::compute_pnl( std::vector& out_pnl, std::vector& out_account_pnl){ out_account_pnl.clear(); - std::map acc_pnl; for (const PositionUnit* pu_ptr : in_pos) { const PositionUnit& pu = *pu_ptr; uint32_t sec_key = pu.security_id(); - uint32_t acct_id = pu.account_id(); double cpp = _get_cpp(sec_key); double bid, ask, last, settle; me->handle_index.get_md(SecurityKey(sec_key),bid,ask,last,settle); @@ -145,22 +143,36 @@ void PositionServicePNLHelper::compute_pnl( pnlu.set_last_price(last); pnlu.set_settlement_price(settle); out_pnl.push_back(pnlu); - // enter into account map - double pnl_dollars = _compute_day_pnl(pnlu); - 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); + } + _aggregate_account_pnl(out_pnl,out_account_pnl); +} + +void PositionServicePNLHelper::_aggregate_account_pnl( + const std::vector& in_pnl, + std::vector& out_account_pnl){ + out_account_pnl.clear(); + std::map acc_pnl; + for (const auto& pnlu : in_pnl){ + uint32_t acct_id = pnlu.pos().account_id(); + if(acct_id > 0){ + //valid account + 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); } - AccountPNL& acc_pnl = it->second; - acc_pnl.set_day_pnl(acc_pnl.day_pnl()+pnl_dollars); } for(auto& u : acc_pnl) out_account_pnl.push_back(u.second); } + double PositionServicePNLHelper::_compute_day_pnl ( const bts::api::position::PNLUnit& u){ // long diff --git a/src/server/sparkd/position/PositionServicePNLHelper.h b/src/server/sparkd/position/PositionServicePNLHelper.h index ff0faf994..1e2bf82c0 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.h +++ b/src/server/sparkd/position/PositionServicePNLHelper.h @@ -15,9 +15,13 @@ class PositionServicePNLHelper { private: struct PImpl; std::unique_ptr me; -private: +private: double _compute_day_pnl (const bts::api::position::PNLUnit&); - double _get_cpp (uint32_t); + double _get_cpp (uint32_t); + // aggregates [sec, account]->pnl tp [account]->pnl + void _aggregate_account_pnl( + const std::vector& in_pnl, + std::vector& out_account_pnl); public: PositionServicePNLHelper(md::MDClient& client); ~PositionServicePNLHelper(); diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index fc0ff04bb..0928c0511 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -173,10 +173,10 @@ PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, if (pu.record_id() == 0) { // new PU pu.set_record_id(++me->id); - pu.set_account(acct); - pu.set_account_id(account_id); + pu.set_account(acct); pu.set_security_id(seckey); } + pu.set_account_id(account_id); return pu; } From 7c6a26ebd9797e83fae7d0b1650b82d906c699f0 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sun, 23 Jun 2019 19:25:06 -0400 Subject: [PATCH 11/20] All hooked up, on updates, loss limit is checked only on size increases --- src/lib/orderman/limiter/LimitStore.cpp | 15 ++++- src/lib/orderman/limiter/LimitStore.h | 58 ++++++++++++++++++- src/lib/orderman/limiter/Limiter.cpp | 8 ++- src/lib/orderman/limiter/Limiter.h | 3 +- .../sparkd/position/PositionServiceServer.cpp | 7 ++- 5 files changed, 82 insertions(+), 9 deletions(-) diff --git a/src/lib/orderman/limiter/LimitStore.cpp b/src/lib/orderman/limiter/LimitStore.cpp index e25807d7c..3fbd2d1df 100644 --- a/src/lib/orderman/limiter/LimitStore.cpp +++ b/src/lib/orderman/limiter/LimitStore.cpp @@ -7,6 +7,8 @@ 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)) { + for (const auto& acct : _admin_data.accounts()) + _account_data_map[acct.id()] = AccountData{&acct,os::nan()}; 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..b79dfeeab 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,17 @@ private: return nullptr; } }; + + class AccountData{ + public: + const bts::api::admin::BTSAccount* account; + double curr_day_pnl; + }; 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 @@ -57,9 +66,13 @@ public: 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 +101,7 @@ public: } } } + void set_pnl (AccountID account_id, double pnl); // risk limit checks //////////////////// // checks to see if the user is allowed to trade @@ -132,6 +146,9 @@ public: api::Side side, Quantity quantity) 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); @@ -154,6 +171,10 @@ public: api::Side side, Quantity from, Quantity to) const{ Limiter::LimiterQueryResult rv; rv.result = Limiter::OK; + 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); @@ -190,5 +211,36 @@ 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& rv) const{ + rv.result = Limiter::LimiterErrorCode::OK; + const auto acct_it = _account_data_map.find(account_id.value()); + if(acct_it != _account_data_map.end() && + acct_it->second.account != nullptr){ + 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)){ + rv.result = Limiter::LimiterErrorCode::LOSS_LIMIT_BREACHED; + rv.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, double){ - // TODO: implement +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 { @@ -122,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 82f9c8528..1b7df944e 100644 --- a/src/lib/orderman/limiter/Limiter.h +++ b/src/lib/orderman/limiter/Limiter.h @@ -46,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/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index 0928c0511..188bec458 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -176,7 +176,12 @@ PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, pu.set_account(acct); pu.set_security_id(seckey); } - pu.set_account_id(account_id); + // TODO: this is getting uglier. The reason + // for if is that SOD records dont have an + // account id, so if there is no day trades + // this will never be populated + if(pu.account_id()==0) + pu.set_account_id(account_id); return pu; } From 60b7966f2f098ce0ca2ad164c2251be205b19034 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Mon, 24 Jun 2019 15:33:47 -0400 Subject: [PATCH 12/20] Loss limit manual test --- testing/manual/admin/loss_limit.txt | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 testing/manual/admin/loss_limit.txt diff --git a/testing/manual/admin/loss_limit.txt b/testing/manual/admin/loss_limit.txt new file mode 100644 index 000000000..a9e211c9f --- /dev/null +++ b/testing/manual/admin/loss_limit.txt @@ -0,0 +1,27 @@ +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 +b. make sure the loss limit is unchecked for both accounts + +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. + +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. For bonus points, move the markets and try to get B's PNL within the loss limit range. Now enter loser trades +in B and make it hit the limit again. From 29d14404e6648c5f95fa9761c7e1b37bbe25024f Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Mon, 24 Jun 2019 17:15:04 -0400 Subject: [PATCH 13/20] PositionService has access to AdminService to resolve accounts now --- .../sparkd/position/PositionServiceServer.cpp | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index 188bec458..09e027718 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -1,6 +1,8 @@ #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" @@ -30,6 +32,7 @@ struct PositionServiceServer::PImpl { PositionServiceBase::Pnl_dataStatefulPublisher pnl_publisher; PositionServiceBase::Pnl_account_dataStatefulPublisher pnl_account_publisher; bts::api::orderman::OrderService order_service; + bts::api::admin::AdminService admin_service; std::map> state; std::map manual_fills; int id; @@ -38,6 +41,7 @@ struct PositionServiceServer::PImpl { // manual fills management std::unique_ptr manual_fills_store ; PositionServiceBase::Manual_fillsStatefulPublisher manual_fills_publisher; + api::admin::AdminData admin_data; PImpl(bts::api::ServiceContext& context, const PositionServiceBase::Position_dataStatefulPublisher& publisher, @@ -51,12 +55,14 @@ struct PositionServiceServer::PImpl { 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(300), manual_fills_store(std::make_unique ("manual_fills")), - manual_fills_publisher(manual_fills_publisher) + manual_fills_publisher(manual_fills_publisher), + admin_data() { } }; @@ -79,7 +85,7 @@ me(new PImpl(context, for (const auto& f : update.removed()) me->publisher.add_or_update(_on_fill(*f,false)); for (const auto& f : update.added()) - me->publisher.add_or_update(_on_fill(*f,true)); + 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)); @@ -87,6 +93,16 @@ me(new PImpl(context, 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()) + {me->admin_data = *r;} + for (const auto& r : update.changed()) + {me->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()); From 8b4c64e8f4063bac1c31842b88b655cdefcdd568 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Wed, 26 Jun 2019 19:34:46 -0400 Subject: [PATCH 14/20] PositionServiceServer not indixes the state based on account_id istead of names --- .../position/PositionServicePNLHelper.cpp | 41 ++++++++----- .../position/PositionServicePNLHelper.h | 2 + .../sparkd/position/PositionServiceServer.cpp | 60 ++++++++++--------- .../sparkd/position/PositionServiceServer.h | 11 ++-- 4 files changed, 67 insertions(+), 47 deletions(-) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index 75393ff0c..8c7a15184 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -125,7 +125,8 @@ struct PositionServicePNLHelper::PImpl { void PositionServicePNLHelper::compute_pnl( const std::vector& in_pos, - std::vector& out_pnl, + 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) { @@ -144,29 +145,39 @@ void PositionServicePNLHelper::compute_pnl( pnlu.set_settlement_price(settle); out_pnl.push_back(pnlu); } - _aggregate_account_pnl(out_pnl,out_account_pnl); + _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(); - if(acct_id > 0){ - //valid account - 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); + 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) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.h b/src/server/sparkd/position/PositionServicePNLHelper.h index 1e2bf82c0..32190d471 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.h +++ b/src/server/sparkd/position/PositionServicePNLHelper.h @@ -21,11 +21,13 @@ private: // 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); }; diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index 09e027718..a2a55c34b 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -33,7 +33,7 @@ struct PositionServiceServer::PImpl { PositionServiceBase::Pnl_account_dataStatefulPublisher pnl_account_publisher; bts::api::orderman::OrderService order_service; bts::api::admin::AdminService admin_service; - std::map> state; + std::map> state; std::map manual_fills; int id; PositionServicePNLHelper pnl_helper; @@ -42,7 +42,8 @@ struct PositionServiceServer::PImpl { 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::Pnl_dataStatefulPublisher& pnl_publisher, @@ -62,7 +63,8 @@ struct PositionServiceServer::PImpl { poll_period_ms(300), manual_fills_store(std::make_unique ("manual_fills")), manual_fills_publisher(manual_fills_publisher), - admin_data() + admin_data(), + account_map() { } }; @@ -81,14 +83,17 @@ me(new PImpl(context, 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(); @@ -98,9 +103,9 @@ me(new PImpl(context, rxcpp::operators::subscribe( [this](auto const& update) { for (const auto& r : update.added()) - {me->admin_data = *r;} + {_set_admin_data(*r);} for (const auto& r : update.changed()) - {me->admin_data = *r.current();} + {_set_admin_data(*r.current());} }); me->context.post([this](){_periodic_poll();},me->poll_period_ms); @@ -139,9 +144,7 @@ bts::api::orderman::Fill PositionServiceServer::to_fill(bts::api::position::Manu 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.internal_account_id(), - 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){ @@ -182,22 +185,17 @@ const PositionUnit& PositionServiceServer::_on_fill (const Fill& f, return pu; } -PositionUnit& PositionServiceServer::_get_or_add (const std::string& acct, - uint32_t account_id, - 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()); } - // TODO: this is getting uglier. The reason - // for if is that SOD records dont have an - // account id, so if there is no day trades - // this will never be populated - if(pu.account_id()==0) - pu.set_account_id(account_id); return pu; } @@ -237,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(){ } @@ -345,7 +351,7 @@ void PositionServiceServer::_compute_pnl_and_publish(){ } std::vector pnl; std::vector account_pnl; - me->pnl_helper.compute_pnl(in_pos,pnl,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) diff --git a/src/server/sparkd/position/PositionServiceServer.h b/src/server/sparkd/position/PositionServiceServer.h index 4390d6694..dac6f2996 100644 --- a/src/server/sparkd/position/PositionServiceServer.h +++ b/src/server/sparkd/position/PositionServiceServer.h @@ -7,7 +7,8 @@ namespace bts { namespace md { class MDClient;} namespace api { class ServiceContext; } -namespace api { namespace orderman { class Fill;}} +namespace api { namespace orderman { class Fill;}} +namespace api { namespace admin { class AdminData;}} namespace position { @@ -26,16 +27,16 @@ 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 account_id, - 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 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, From 60e933fca9b1f7f51d68a55a3415ec3bd6b0575d Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Thu, 27 Jun 2019 15:20:12 -0400 Subject: [PATCH 15/20] SOD also indexes its data on account_id, Cleaned up Limiter's account_data (there was an overlap, after introducing Loss limit related PNL data) --- src/lib/orderman/actors/SODPosition.cpp | 23 ++++++++++++++++------- src/lib/orderman/actors/SODPosition.h | 3 +-- src/lib/orderman/limiter/LimitStore.cpp | 6 +++--- src/lib/orderman/limiter/LimitStore.h | 20 ++++++++++++-------- 4 files changed, 32 insertions(+), 20 deletions(-) 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/limiter/LimitStore.cpp b/src/lib/orderman/limiter/LimitStore.cpp index 3fbd2d1df..285273139 100644 --- a/src/lib/orderman/limiter/LimitStore.cpp +++ b/src/lib/orderman/limiter/LimitStore.cpp @@ -5,10 +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[acct.id()] = AccountData{&acct,os::nan()}; + _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); diff --git a/src/lib/orderman/limiter/LimitStore.h b/src/lib/orderman/limiter/LimitStore.h index b79dfeeab..75c1840ce 100644 --- a/src/lib/orderman/limiter/LimitStore.h +++ b/src/lib/orderman/limiter/LimitStore.h @@ -37,12 +37,15 @@ private: class AccountData{ public: - const bts::api::admin::BTSAccount* account; + 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 @@ -61,8 +64,10 @@ 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;} @@ -215,10 +220,9 @@ private: Limiter::LimiterQueryResult& rv) const{ rv.result = Limiter::LimiterErrorCode::OK; const auto acct_it = _account_data_map.find(account_id.value()); - if(acct_it != _account_data_map.end() && - acct_it->second.account != nullptr){ + if(acct_it != _account_data_map.end()){ const auto& account_data = acct_it->second; - const auto& account = *(account_data.account); + const auto& account = account_data.account; if (account.has_account_loss_limit() && account.account_loss_limit().enforce()){ double pnl = account_data.curr_day_pnl; From ccca85d1c504fb3abd952bc85ee051652c30dbf4 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Thu, 27 Jun 2019 15:46:44 -0400 Subject: [PATCH 16/20] loss limit manual test updated --- testing/manual/admin/loss_limit.txt | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/testing/manual/admin/loss_limit.txt b/testing/manual/admin/loss_limit.txt index a9e211c9f..c0531a5c2 100644 --- a/testing/manual/admin/loss_limit.txt +++ b/testing/manual/admin/loss_limit.txt @@ -8,13 +8,15 @@ 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 -b. make sure the loss limit is unchecked for both accounts +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. +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) @@ -23,5 +25,5 @@ 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. For bonus points, move the markets and try to get B's PNL within the loss limit range. Now enter loser trades -in B and make it hit the limit again. +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. From 02769479ea6a3604a3676ad111a25fab2b13fe79 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Sun, 30 Jun 2019 22:45:29 -0400 Subject: [PATCH 17/20] SP-74 bundled into this (it was a small change) --- src/lib/orderman/limiter/LimitStore.h | 72 ++++++++++++-------- src/lib/orderman/limiter/SecurityLimitNode.h | 11 +-- src/lib/orderman/limiter/SecurityLimitTree.h | 10 +-- 3 files changed, 56 insertions(+), 37 deletions(-) diff --git a/src/lib/orderman/limiter/LimitStore.h b/src/lib/orderman/limiter/LimitStore.h index 75c1840ce..b586617c2 100644 --- a/src/lib/orderman/limiter/LimitStore.h +++ b/src/lib/orderman/limiter/LimitStore.h @@ -149,14 +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 @@ -164,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; } @@ -174,22 +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; } @@ -217,33 +227,37 @@ private: const bts::api::admin::AdminData& admin_data); void _set_user_data(); void _loss_limit(AccountID account_id, - Limiter::LimiterQueryResult& rv) const{ - rv.result = Limiter::LimiterErrorCode::OK; + 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)){ - rv.result = Limiter::LimiterErrorCode::LOSS_LIMIT_BREACHED; - rv.error_msg = "Could not find account PNL"; - } - else{ - double loss_limit = -1.0 * static_cast( - account.account_loss_limit().total_loss_limit()); - if(pnlsecond; + 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(pnl _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 //////////// From 92f08b89cc9f618ae9b5c7b3de6b7021d96753ba Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Mon, 1 Jul 2019 09:01:46 -0400 Subject: [PATCH 18/20] Added a sub test to the clip limits test to verify that spread clip limits are independent of futures --- testing/manual/admin/clip_limits.txt | 5 +++++ 1 file changed, 5 insertions(+) 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 From 7ce8f1ed97712fe4d992c7533b93528d3c04c8bf Mon Sep 17 00:00:00 2001 From: Pedro Pinto Date: Mon, 1 Jul 2019 14:57:00 -0400 Subject: [PATCH 19/20] Updated release notes --- doc/user/content/release_notes/_index.md | 3 +++ src/server/sparkd/CMakeDeps.cmake | 6 +----- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index f9a04d11e..88eeeb4e6 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -4,6 +4,9 @@ weight = 3 sort_by = "weight" insert_anchor_links = "right" +++ +## 2.5.0 +### User Visible Changes + - Added loss limit risk check ## 2.4.0 ### User Visible Settings - In the ladder, changed the last trade column to accumulate successive trades at the same price diff --git a/src/server/sparkd/CMakeDeps.cmake b/src/server/sparkd/CMakeDeps.cmake index 440b764f3..ff12df496 100644 --- a/src/server/sparkd/CMakeDeps.cmake +++ b/src/server/sparkd/CMakeDeps.cmake @@ -1,5 +1 @@ -<<<<<<< HEAD -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) -======= -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) ->>>>>>> master +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 From 5cbe00beab84f7094a6b5f353549b9d20e9d552b Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Mon, 1 Jul 2019 16:33:56 -0400 Subject: [PATCH 20/20] Spread PNL is not counted towards the Account PNL --- .../position/PositionServicePNLHelper.cpp | 51 +++++++++++++++---- .../sparkd/position/PositionServiceServer.cpp | 2 +- 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index 8c7a15184..c2c50b4f0 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -26,6 +26,11 @@ using namespace bts::md; class HandleIndex { public: + enum PNLType{ + UNRESOLVED = 0, + SPREAD, + OUTRIGHT + }; bts::md::MDClient& _client; int _sub; std::optional _consumer; @@ -50,7 +55,18 @@ public: }); 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(); @@ -187,16 +203,31 @@ void PositionServicePNLHelper::_aggregate_account_pnl( double PositionServicePNLHelper::_compute_day_pnl ( const bts::api::position::PNLUnit& u){ // long - 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 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); - return long_pnl + short_pnl; + 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); diff --git a/src/server/sparkd/position/PositionServiceServer.cpp b/src/server/sparkd/position/PositionServiceServer.cpp index a2a55c34b..f73a0178f 100644 --- a/src/server/sparkd/position/PositionServiceServer.cpp +++ b/src/server/sparkd/position/PositionServiceServer.cpp @@ -60,7 +60,7 @@ struct PositionServiceServer::PImpl { state(), id(0), pnl_helper(md_client), - poll_period_ms(300), + poll_period_ms(500), manual_fills_store(std::make_unique ("manual_fills")), manual_fills_publisher(manual_fills_publisher), admin_data(),