From a90f6badfd8e02c626874a011132caad52c6ff36 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Fri, 31 Dec 2021 14:15:06 -0500 Subject: [PATCH 01/33] refactor: Clean up binance md classes * Remove unneccessary includes in a few files * Remove erroneous commented out fwd decls * Remove unused class BinanceMarketDataSubscription * Make a few public accessor fns private --- src/lib/md/MarketDataListenerData.h | 11 --- src/lib/md/binance/BinanceDepthStreamSite.cpp | 11 ++- src/lib/md/binance/BinanceDepthStreamSite.h | 35 ++++----- .../md/binance/BinanceDepthStreamSiteKey.cpp | 8 ++- .../md/binance/BinanceDepthStreamSiteKey.h | 10 +-- .../md/binance/BinanceDiffDepthSubscription.h | 4 -- .../binance/BinanceMarketDataSubscription.cpp | 72 ------------------- .../binance/BinanceMarketDataSubscription.h | 45 ------------ 8 files changed, 32 insertions(+), 164 deletions(-) delete mode 100644 src/lib/md/binance/BinanceMarketDataSubscription.cpp delete mode 100644 src/lib/md/binance/BinanceMarketDataSubscription.h diff --git a/src/lib/md/MarketDataListenerData.h b/src/lib/md/MarketDataListenerData.h index 21ebb6d40..ca8e1c7c3 100644 --- a/src/lib/md/MarketDataListenerData.h +++ b/src/lib/md/MarketDataListenerData.h @@ -1,18 +1,7 @@ #pragma once -#include "lib/api/md/MarketDataSubscriptionParams.pb.h" -#include "lib/api/md/binance/BinanceMarketDataSubscriptionParams.pb.h" #include "lib/domain/SecurityID.h" -#include "lib/domain/SecurityResolver.h" -#include "lib/domain/Venue.h" -#include "lib/io/URL.h" #include "lib/md/IMarketDataListener.h" #include "lib/md/MarketDataListenerID.h" -#include "lib/md/binance/BinanceDiffDepthSubscription.h" -#include "lib/md/binance/BinanceDiffDepthUpdate.h" -#include "lib/md/binance/BinanceMarketDataSubscription.h" -#include "lib/utils/ContainsKey.h" -#include "lib/utils/bts_assert.h" -#include #include namespace bts::md { diff --git a/src/lib/md/binance/BinanceDepthStreamSite.cpp b/src/lib/md/binance/BinanceDepthStreamSite.cpp index dabddedf7..dce405c25 100644 --- a/src/lib/md/binance/BinanceDepthStreamSite.cpp +++ b/src/lib/md/binance/BinanceDepthStreamSite.cpp @@ -11,7 +11,6 @@ #include "lib/md/binance/BinanceDepthStreamSiteKey.h" #include "lib/md/binance/BinanceDiffDepthSubscription.h" #include "lib/md/binance/BinanceDiffDepthUpdate.h" -#include "lib/md/binance/BinanceMarketDataSubscription.h" #include "lib/utils/ContainsKey.h" #include "lib/utils/bts_assert.h" #include @@ -28,27 +27,27 @@ BinanceDepthStreamSite::BinanceDepthStreamSite( listeners_ptr_(listeners_ptr) {} std::unordered_map & -BinanceDepthStreamSite::ref_counts() { +BinanceDepthStreamSite::ref_counts_() { return *ref_counts_ptr_; } const std::unordered_map & -BinanceDepthStreamSite::ref_counts() const { +BinanceDepthStreamSite::ref_counts_() const { return *ref_counts_ptr_; } std::unordered_map & -BinanceDepthStreamSite::listeners() { +BinanceDepthStreamSite::listeners_() { return *listeners_ptr_; } const std::unordered_map & -BinanceDepthStreamSite::listeners() const { +BinanceDepthStreamSite::listeners_() const { return *listeners_ptr_; } void BinanceDepthStreamSite::connect() { - auto &b = binance_.emplace(site_key_.params); + auto &b = binance_.emplace(site_key_.params()); // (re)bind the callback b.on_depth_changed().bind<&BinanceDepthStreamSite::fwd_on_depth_changed_>( *this); diff --git a/src/lib/md/binance/BinanceDepthStreamSite.h b/src/lib/md/binance/BinanceDepthStreamSite.h index 0f70e7db7..1a1dce5bf 100644 --- a/src/lib/md/binance/BinanceDepthStreamSite.h +++ b/src/lib/md/binance/BinanceDepthStreamSite.h @@ -12,16 +12,11 @@ #include "lib/md/MarketDataListenerID.h" #include "lib/md/binance/BinanceDiffDepthSubscription.h" #include "lib/md/binance/BinanceDiffDepthUpdate.h" -#include "lib/md/binance/BinanceMarketDataSubscription.h" #include "lib/utils/ContainsKey.h" #include "lib/utils/bts_assert.h" #include #include -namespace bts::md { -// struct MarketDataListenerData; -} // namespace bts::md - namespace bts::md::binance { class BinanceDepthStreamSite { @@ -33,15 +28,6 @@ class BinanceDepthStreamSite { std::unordered_map *listeners_ptr); - std::unordered_map &ref_counts(); - const std::unordered_map & - ref_counts() const; - - std::unordered_map & - listeners(); - const std::unordered_map & - listeners() const; - void connect(); template > @@ -63,6 +49,15 @@ class BinanceDepthStreamSite { // (disposed and recreated) without unbinding the existing callback. BinanceDiffDepthSubscription::OnDepthChanged on_depth_changed_proxy_; + std::unordered_map &ref_counts_(); + const std::unordered_map & + ref_counts_() const; + + std::unordered_map & + listeners_(); + const std::unordered_map & + listeners_() const; + void ensure_connect_(); void fwd_on_depth_changed_( const std::string &symbol, @@ -78,7 +73,7 @@ void BinanceDepthStreamSite::subscribe( MarketDataListenerID listener_id, const Symbols &symbols) { bts_assert(listener_id.value() != 0); bts_assert(listeners_ptr_); - auto &ld = listeners()[listener_id]; + auto &ld = listeners_()[listener_id]; for (const auto &sym : symbols) { auto sid = domain::SecurityResolver::symbol_to_id(domain::Venue::Binance, sym); @@ -87,7 +82,7 @@ void BinanceDepthStreamSite::subscribe( "Cannot subscribe. Listener already subscribed to sec. sid: " "{}; sym: {}", sym, sid); - if (ref_counts().try_emplace(sid, 0).first->second++ == 0) { + if (ref_counts_().try_emplace(sid, 0).first->second++ == 0) { ensure_connect_(); // first subscription for this symbol binance_->add_symbol(sym); @@ -101,7 +96,7 @@ void BinanceDepthStreamSite::unsubscribe( bts_assert(listener_id.value() != 0); bts_assert(listeners_ptr_); bts_assert(listeners_ptr_->find(listener_id) != listeners_ptr_->end()); - auto &ld = listeners()[listener_id]; + auto &ld = listeners_()[listener_id]; LOG(md, bts::Diag, "Unsubscribing {} symbols for listener {} on site {}", symbols.size(), listener_id); for (const auto &sym : symbols) { @@ -112,14 +107,14 @@ void BinanceDepthStreamSite::unsubscribe( "Cannot unsubscribe. Listener not subscribed to sec. sid: {}; " "sym: {}", sid, sym); - auto rc_it = ref_counts().find(sid); + auto rc_it = ref_counts_().find(sid); bts_assert_msg( - rc_it != ref_counts().end(), + rc_it != ref_counts_().end(), "Inter-listener security subscription ref count out of sync " "with listener's subscribed securities."); if (--rc_it->second == 0) { // last subscription for this symbol - ref_counts().erase(rc_it); + ref_counts_().erase(rc_it); binance_->remove_symbol(sym); } } diff --git a/src/lib/md/binance/BinanceDepthStreamSiteKey.cpp b/src/lib/md/binance/BinanceDepthStreamSiteKey.cpp index 5e630cd7e..cd3bbcfda 100644 --- a/src/lib/md/binance/BinanceDepthStreamSiteKey.cpp +++ b/src/lib/md/binance/BinanceDepthStreamSiteKey.cpp @@ -3,12 +3,16 @@ namespace bts::md::binance { +const BinanceDepthStreamParams &BinanceDepthStreamSiteKey::params() const { + return params_; +} + const io::URL &BinanceDepthStreamSiteKey::stream_url() const { - return params.stream_url(); + return params_.stream_url(); } const io::URL &BinanceDepthStreamSiteKey::snapshot_url() const { - return params.snapshot_url(); + return params_.snapshot_url(); } bool operator==( diff --git a/src/lib/md/binance/BinanceDepthStreamSiteKey.h b/src/lib/md/binance/BinanceDepthStreamSiteKey.h index 209bacc5d..3315c929e 100644 --- a/src/lib/md/binance/BinanceDepthStreamSiteKey.h +++ b/src/lib/md/binance/BinanceDepthStreamSiteKey.h @@ -1,8 +1,8 @@ #pragma once +#include "BinanceDepthStreamParams.h" #include "lib/api/md/binance/BinanceMarketDataSubscriptionParams.pb.h" #include "lib/domain/SecurityID.h" #include "lib/io/URL.h" -#include "lib/md/binance/BinanceMarketDataSubscription.h" #include namespace bts::md::binance { @@ -12,12 +12,14 @@ class BinanceDepthStreamSiteKey { BinanceDepthStreamSiteKey() = default; explicit BinanceDepthStreamSiteKey( const api::md::binance::BinanceDepthStreamParams ¶ms) - : params(params) {} - - binance::BinanceDepthStreamParams params; + : params_(params) {} + const BinanceDepthStreamParams ¶ms() const; const io::URL &stream_url() const; const io::URL &snapshot_url() const; + + private: + BinanceDepthStreamParams params_; }; bool operator==( diff --git a/src/lib/md/binance/BinanceDiffDepthSubscription.h b/src/lib/md/binance/BinanceDiffDepthSubscription.h index db125ea08..02681a1cb 100644 --- a/src/lib/md/binance/BinanceDiffDepthSubscription.h +++ b/src/lib/md/binance/BinanceDiffDepthSubscription.h @@ -4,10 +4,6 @@ #include "server/sparkd/cmds/spartan/system/Delegate.h" #include -namespace bts::api::md { -// class BinanceDepthStreamParams; -} - namespace bts::md::binance { class BinanceDepthStreamParams; diff --git a/src/lib/md/binance/BinanceMarketDataSubscription.cpp b/src/lib/md/binance/BinanceMarketDataSubscription.cpp deleted file mode 100644 index a9baec547..000000000 --- a/src/lib/md/binance/BinanceMarketDataSubscription.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "BinanceMarketDataSubscription.h" -#include "BinanceDepthSnapshot.h" -#include "BinanceDiffDepthSubscription.h" -#include "BinanceWebsocketStreamDemuxer.h" -#include "lib/api/md/MarketDataSubscriptionParams.pb.h" -#include "lib/api/md/binance/BinanceMarketDataSubscriptionParams.pb.h" -#include "lib/domain/Book.h" -#include "lib/io/URL.h" -#include "lib/io/http/HTTPClient.h" -#include "lib/io/http/HTTPRequest.h" -#include "lib/io/http/HTTPResponse.h" -#include "lib/io/websocket/IWebsocketListener.h" -#include "lib/io/websocket/WebsocketClient.h" -#include "lib/io/websocket/WebsocketClientConfiguration.h" -#include "lib/io/websocket/WebsocketError.h" -#include "lib/io/websocket/WebsocketMessage.h" -#include "lib/logging/logging.h" -#include "lib/md/IMarketDataListener.h" -#include "lib/md/binance/BinanceDepthBootstrapper.h" -#include "lib/md/binance/BinanceDepthStreamParams.h" -#include "lib/md/binance/BinanceDiffDepthUpdate.h" -#include "lib/utils/bts_assert.h" -#include -#include -#include -#include - -namespace bts::md::binance { - -using json = nlohmann::json; - -struct BinanceMarketDataSubscription::PImpl { - IMarketDataListener *listener; - api::md::binance::BinanceMarketDataSubscriptionParams params; - io::URL url; - std::vector depth_subs; - std::unordered_map books; - - void on_depth_changed( - const std::string &symbol, const BinanceDiffDepthUpdate &update) { - auto &book = books[symbol]; - update.apply_to_book(book); - bts_assert(listener != nullptr); - // TODO: set the security id - listener->on_book(book); - } -}; - -BinanceMarketDataSubscription::BinanceMarketDataSubscription( - IMarketDataListener *listener, - const api::md::binance::BinanceMarketDataSubscriptionParams ¶ms) - : me_(std::make_unique()) { - me_->listener = listener; - me_->params = params; - for (const auto &stream : me_->params.depth_streams()) { - auto &depth_sub = - me_->depth_subs.emplace_back(BinanceDepthStreamParams(stream)); - depth_sub.on_depth_changed() - .bind<&BinanceMarketDataSubscription::PImpl::on_depth_changed>(*me_); - depth_sub.connect(); - } -} - -BinanceMarketDataSubscription::BinanceMarketDataSubscription( - BinanceMarketDataSubscription &&other) = default; - -BinanceMarketDataSubscription &BinanceMarketDataSubscription::operator=( - BinanceMarketDataSubscription &&) = default; - -BinanceMarketDataSubscription::~BinanceMarketDataSubscription() = default; - -} // namespace bts::md::binance diff --git a/src/lib/md/binance/BinanceMarketDataSubscription.h b/src/lib/md/binance/BinanceMarketDataSubscription.h deleted file mode 100644 index f323d9876..000000000 --- a/src/lib/md/binance/BinanceMarketDataSubscription.h +++ /dev/null @@ -1,45 +0,0 @@ -#pragma once -#include "BinanceDepthStreamParams.h" -#include "lib/api/md/MarketDataSubscriptionParams.pb.h" -#include -#include -#include -#include - -namespace bts::api::md::binance { -class BinanceMarketDataSubscriptionParams; -} - -namespace bts::md { -class IMarketDataListener; -} - -namespace bts::md::binance { - -struct BinanceMarketDataSubscription { - BinanceMarketDataSubscription() = default; - - explicit BinanceMarketDataSubscription( - IMarketDataListener *listener, - const api::md::binance::BinanceMarketDataSubscriptionParams ¶ms); - - BinanceMarketDataSubscription(const BinanceMarketDataSubscription &) = - delete; - - BinanceMarketDataSubscription &operator=( - const BinanceMarketDataSubscription &) = delete; - - BinanceMarketDataSubscription(BinanceMarketDataSubscription &&other); - BinanceMarketDataSubscription &operator=(BinanceMarketDataSubscription &&); - - ~BinanceMarketDataSubscription(); - - private: - struct PImpl; - std::unique_ptr me_; - - void connect(); - void connect(const BinanceDepthStreamParams &depth_stream); -}; - -} // namespace bts::md::binance From b41f321723e4918f02c22104b5917ab59f857149 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Fri, 31 Dec 2021 14:01:04 -0500 Subject: [PATCH 02/33] style: Add comments to binance md classes --- src/lib/md/binance/BinanceBookTickerUpdate.h | 6 ++++ src/lib/md/binance/BinanceDepthBootstrapper.h | 5 ++++ src/lib/md/binance/BinanceDepthSnapshot.h | 9 ++++++ src/lib/md/binance/BinanceDepthStreamSite.h | 26 ++++++++++++++++ .../md/binance/BinanceDepthStreamSiteKey.h | 3 ++ .../md/binance/BinanceDiffDepthSubscription.h | 30 +++++++++++++++++++ src/lib/md/binance/BinanceDiffDepthUpdate.h | 5 ++++ src/lib/md/binance/BinanceMiniTickerUpdate.h | 6 ++++ .../binance/BinancePartialBookDepthUpdate.h | 6 ++++ .../binance/BinanceWebsocketStreamDemuxer.h | 6 ++++ 10 files changed, 102 insertions(+) diff --git a/src/lib/md/binance/BinanceBookTickerUpdate.h b/src/lib/md/binance/BinanceBookTickerUpdate.h index cf7f6660b..d5f4fa3db 100644 --- a/src/lib/md/binance/BinanceBookTickerUpdate.h +++ b/src/lib/md/binance/BinanceBookTickerUpdate.h @@ -4,6 +4,12 @@ namespace bts::md::binance { +/** + * @brief Represents a Binance 'Individual Symbol Book Ticker' update + * + * @remark + * https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-book-ticker-streams + */ class BinanceBookTickerUpdate { public: // json name: u diff --git a/src/lib/md/binance/BinanceDepthBootstrapper.h b/src/lib/md/binance/BinanceDepthBootstrapper.h index 92ee1aeb6..e93f79ea2 100644 --- a/src/lib/md/binance/BinanceDepthBootstrapper.h +++ b/src/lib/md/binance/BinanceDepthBootstrapper.h @@ -8,6 +8,11 @@ class BinanceDepthSnapshot; class BinanceDiffDepthUpdate; class BinanceDiffDepthListener; +/** + * @brief Bootstraps Binance's incremental 'Diff. Depth' stream with an + * up-to-date depth snapshot, seeding observers with the state to which the + * next incremental update applies + */ class BinanceDepthBootstrapper { public: BinanceDepthBootstrapper(); diff --git a/src/lib/md/binance/BinanceDepthSnapshot.h b/src/lib/md/binance/BinanceDepthSnapshot.h index 6ff6f4a11..b38ca5f43 100644 --- a/src/lib/md/binance/BinanceDepthSnapshot.h +++ b/src/lib/md/binance/BinanceDepthSnapshot.h @@ -8,6 +8,15 @@ namespace bts::md::binance { class BinanceDiffDepthUpdate; +/** + * @brief Represents a Binance 'Depth Snapshot' + * + * @note A 'Depth Snapshot' is used to bootstrap the 'Diff. Depth Stream', + * a sequence of incremental updates of type \sa BinanceDiffDepthUpdate + * + * @remark + * https://binance-docs.github.io/apidocs/spot/en/#how-to-manage-a-local-order-book-correctly + */ class BinanceDepthSnapshot { public: // json name: lastUpdateId diff --git a/src/lib/md/binance/BinanceDepthStreamSite.h b/src/lib/md/binance/BinanceDepthStreamSite.h index 1a1dce5bf..ab851cae1 100644 --- a/src/lib/md/binance/BinanceDepthStreamSite.h +++ b/src/lib/md/binance/BinanceDepthStreamSite.h @@ -19,6 +19,14 @@ namespace bts::md::binance { +/** + * @brief Facilitates the flow of Binance market data updates (from a particular + * site) to subscribed listeners (of type IMarketDataListener) + * + * @details Maintains a reference count of subscriptions per symbol, so for a + * given symbol, one internal subscription serves all listeners subscribed + * to that symbol + */ class BinanceDepthStreamSite { public: BinanceDepthStreamSite() = default; @@ -28,11 +36,29 @@ class BinanceDepthStreamSite { std::unordered_map *listeners_ptr); + /** + * @brief Connects to the market data site, and begins the flow of updates to + * subscribed listeners + * + * @note This only needs to be called once; subsequent calls reset the + * connection + */ void connect(); + /** + * @brief Subscribes a particular listener to updates for particular symbols + * + * @note Updates won't flow until BinanceDepthStreamSite::connect() has been + * called (if it has already been called, they will begin flowing + * immediately) + */ template > void subscribe(MarketDataListenerID listener_id, const Symbols &symbols); + /** + * @brief Unsubscribes a particular listener from updates for particular + * symbols + */ template > void unsubscribe(MarketDataListenerID listener_id, const Symbols &symbols); diff --git a/src/lib/md/binance/BinanceDepthStreamSiteKey.h b/src/lib/md/binance/BinanceDepthStreamSiteKey.h index 3315c929e..b5a66b40a 100644 --- a/src/lib/md/binance/BinanceDepthStreamSiteKey.h +++ b/src/lib/md/binance/BinanceDepthStreamSiteKey.h @@ -7,6 +7,9 @@ namespace bts::md::binance { +/** + * @brief Represents a Binance market data site + */ class BinanceDepthStreamSiteKey { public: BinanceDepthStreamSiteKey() = default; diff --git a/src/lib/md/binance/BinanceDiffDepthSubscription.h b/src/lib/md/binance/BinanceDiffDepthSubscription.h index 02681a1cb..83aac38c9 100644 --- a/src/lib/md/binance/BinanceDiffDepthSubscription.h +++ b/src/lib/md/binance/BinanceDiffDepthSubscription.h @@ -8,6 +8,16 @@ namespace bts::md::binance { class BinanceDepthStreamParams; +/** + * @brief Manages a connection to a binance 'diff depth' stream, and provides + * incremental updates of type `BinanceDiffDepthUpdate` to callers via the + * `on_depth_changed` delegate. + * + * @note Users of this class should bind their handler to the + * `on_depth_changed` delegate BEFORE calling `connect` to avoid missing an + * update (as they are incremental, a missed update corrupts the sequence + * thereafter). + */ class BinanceDiffDepthSubscription { public: BinanceDiffDepthSubscription(); @@ -23,13 +33,33 @@ class BinanceDiffDepthSubscription { ~BinanceDiffDepthSubscription(); + /** + * @brief Connects to a binance market data site and begins forwarding + * updates to the `on_depth_changed` delegate + */ void connect(); + + /** + * @brief Adds a symbol to the market data subscription + * + * @note Idempotent + * @note Can be called before or after `connect` has been called + */ void add_symbol(const std::string &symbol); + + /** + * @brief Removes a symbol from the market data subscription + * + * @note Idempotent + */ void remove_symbol(const std::string &symbol); using OnDepthChanged = spartan::Delegate; + /** + * @brief The depth changed callback + */ OnDepthChanged &on_depth_changed(); private: diff --git a/src/lib/md/binance/BinanceDiffDepthUpdate.h b/src/lib/md/binance/BinanceDiffDepthUpdate.h index 9b4b5f9f5..1fb451ae4 100644 --- a/src/lib/md/binance/BinanceDiffDepthUpdate.h +++ b/src/lib/md/binance/BinanceDiffDepthUpdate.h @@ -10,6 +10,11 @@ namespace bts::md::binance { class BinanceDepthSnapshot; +/** + * @brief Represents a Binance 'Diff. Depth' update + * + * @remark https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream + */ class BinanceDiffDepthUpdate { public: // json name: e diff --git a/src/lib/md/binance/BinanceMiniTickerUpdate.h b/src/lib/md/binance/BinanceMiniTickerUpdate.h index b351af5a8..f8484b867 100644 --- a/src/lib/md/binance/BinanceMiniTickerUpdate.h +++ b/src/lib/md/binance/BinanceMiniTickerUpdate.h @@ -4,6 +4,12 @@ namespace bts::md::binance { +/** + * @brief Represents a Binance 'Individual Symbol Mini Ticker' update + * + * @remark + * https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream + */ class BinanceMiniTickerUpdate { public: // json name: e diff --git a/src/lib/md/binance/BinancePartialBookDepthUpdate.h b/src/lib/md/binance/BinancePartialBookDepthUpdate.h index 023040f65..093d08951 100644 --- a/src/lib/md/binance/BinancePartialBookDepthUpdate.h +++ b/src/lib/md/binance/BinancePartialBookDepthUpdate.h @@ -4,6 +4,12 @@ namespace bts::md::binance { +/** + * @brief Represents a Binance 'Partial Book Depth Streams' update + * + * @remark + * https://binance-docs.github.io/apidocs/spot/en/#partial-book-depth-streams + */ class BinancePartialBookDepthUpdate { public: // json name: lastUpdateId diff --git a/src/lib/md/binance/BinanceWebsocketStreamDemuxer.h b/src/lib/md/binance/BinanceWebsocketStreamDemuxer.h index 37c41ea00..12cbfb7c4 100644 --- a/src/lib/md/binance/BinanceWebsocketStreamDemuxer.h +++ b/src/lib/md/binance/BinanceWebsocketStreamDemuxer.h @@ -7,6 +7,12 @@ namespace bts::md::binance { +/** + * @brief Demuxes updates on a binance websocket by stream + * + * @remark Neccessary because binance muxes multiple streams on a single + * websocket + */ class BinanceWebsocketStreamDemuxer : public io::websocket::IWebsocketListener { public: BinanceWebsocketStreamDemuxer() = default; From 10bd10fbf10cadc753d96fea5298f3cca9a14861 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Fri, 7 Jan 2022 14:27:26 -0500 Subject: [PATCH 03/33] Update externals (adds missing std dir to includes) --- externals | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/externals b/externals index f937c3334..397ca900a 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit f937c33349e5d7eeb9fe0445732e62550b8732ef +Subproject commit 397ca900ab84677a786f8bfd2d6ffa812b7bdddf From 9d0cc5ef91e64dc95002fe49dccaf2bf675f2ad2 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Fri, 7 Jan 2022 15:42:18 -0500 Subject: [PATCH 04/33] Adding include opitonal to fix the build --- src/lib/CMakeDeps_win.cmake | 2 +- src/lib/md/binance/BinanceDepthStreamSite.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/CMakeDeps_win.cmake b/src/lib/CMakeDeps_win.cmake index 3058bcb98..a242a7db9 100644 --- a/src/lib/CMakeDeps_win.cmake +++ b/src/lib/CMakeDeps_win.cmake @@ -1 +1 @@ -set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/domain/Currency.proto;api/domain/SecurityType.proto;api/domain/Venue.proto;api/io/URL.proto;api/md/MarketDataSubscriptionParams.proto;api/md/binance/BinanceMarketDataSubscriptionParams.proto;api/md/deribit/DeribitMarketDataSubscriptionParams.proto;api/md/ftx/FTXMarketDataSubscriptionParams.proto;api/md/glbx/GlbxMarketDataSubscriptionParams.proto;api/md/huobi/HuobiMarketDataSubscriptionParams.proto;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/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/AnalyticsService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.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/position_cfg.conf;config/defaults/span.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/AlgoTypes.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/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spartan.proto;config/protos/spreader.proto;config/protos/subprocess.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/sod.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;io/QueryParams.cpp;io/URL.cpp;io/http/CurlHandle.cpp;io/http/HTTPClient.cpp;io/http/HTTPHeaders.cpp;io/http/HTTPRequest.cpp;io/http/HTTPResponse.cpp;io/websocket/WebsocketClient.cpp;io/websocket/WebsocketClientConfiguration.cpp;io/websocket/WebsocketError.cpp;io/websocket/WebsocketMessage.cpp;io/websocket/WebsocketSSLClientInternal.cpp;io/websocket/tests/WebsocketClientTests.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/MarketDataError.cpp;md/MarketDataGateway.cpp;md/MarketDataRegistrationFactory.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityMarketState.cpp;md/SecurityOracle.cpp;md/SecurityStore.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/binance/BinanceBookLevel.cpp;md/binance/BinanceDepthBootstrapper.cpp;md/binance/BinanceDepthSnapshot.cpp;md/binance/BinanceDepthStreamParams.cpp;md/binance/BinanceDepthStreamSite.cpp;md/binance/BinanceDepthStreamSiteKey.cpp;md/binance/BinanceDiffDepthSubscription.cpp;md/binance/BinanceDiffDepthUpdate.cpp;md/binance/BinanceMarketDataSubscription.cpp;md/binance/BinanceWebsocketStreamDemuxer.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/listeners/LiveLadderPrinter.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.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;md/vendor/OnixsUtils.cpp;os/os.cpp;os/tests/os_tests.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;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/MathUtils.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/sftp.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/IDGeneratorTests.cpp;utils/tests/MathUtilsTests.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/domain/Currency.proto;api/domain/SecurityType.proto;api/domain/Venue.proto;api/io/URL.proto;api/md/MarketDataSubscriptionParams.proto;api/md/binance/BinanceMarketDataSubscriptionParams.proto;api/md/deribit/DeribitMarketDataSubscriptionParams.proto;api/md/ftx/FTXMarketDataSubscriptionParams.proto;api/md/glbx/GlbxMarketDataSubscriptionParams.proto;api/md/huobi/HuobiMarketDataSubscriptionParams.proto;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/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/AnalyticsService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.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/position_cfg.conf;config/defaults/span.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/AlgoTypes.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/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spartan.proto;config/protos/spreader.proto;config/protos/subprocess.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/sod.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;io/QueryParams.cpp;io/URL.cpp;io/http/CurlHandle.cpp;io/http/HTTPClient.cpp;io/http/HTTPHeaders.cpp;io/http/HTTPRequest.cpp;io/http/HTTPResponse.cpp;io/websocket/WebsocketClient.cpp;io/websocket/WebsocketClientConfiguration.cpp;io/websocket/WebsocketError.cpp;io/websocket/WebsocketMessage.cpp;io/websocket/WebsocketSSLClientInternal.cpp;io/websocket/tests/WebsocketClientTests.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/MarketDataError.cpp;md/MarketDataGateway.cpp;md/MarketDataRegistrationFactory.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityMarketState.cpp;md/SecurityOracle.cpp;md/SecurityStore.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/binance/BinanceBookLevel.cpp;md/binance/BinanceDepthBootstrapper.cpp;md/binance/BinanceDepthSnapshot.cpp;md/binance/BinanceDepthStreamParams.cpp;md/binance/BinanceDepthStreamSite.cpp;md/binance/BinanceDepthStreamSiteKey.cpp;md/binance/BinanceDiffDepthSubscription.cpp;md/binance/BinanceDiffDepthUpdate.cpp;md/binance/BinanceWebsocketStreamDemuxer.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/listeners/LiveLadderPrinter.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.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;md/vendor/OnixsUtils.cpp;os/os.cpp;os/tests/os_tests.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;utils/AuthSessionManager.cpp;utils/AuthToken.cpp;utils/Dispatcher.cpp;utils/GrowableSPSCQueue.cpp;utils/HTTPStream.cpp;utils/MathUtils.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/sftp.cpp;utils/stats.cpp;utils/tests/AuthTokenTests.cpp;utils/tests/IDGeneratorTests.cpp;utils/tests/MathUtilsTests.cpp;utils/tests/SingleWriterConcurrentVectorTests.cpp;utils/thread_manager.cpp) \ No newline at end of file diff --git a/src/lib/md/binance/BinanceDepthStreamSite.h b/src/lib/md/binance/BinanceDepthStreamSite.h index ab851cae1..79afd576a 100644 --- a/src/lib/md/binance/BinanceDepthStreamSite.h +++ b/src/lib/md/binance/BinanceDepthStreamSite.h @@ -14,6 +14,7 @@ #include "lib/md/binance/BinanceDiffDepthUpdate.h" #include "lib/utils/ContainsKey.h" #include "lib/utils/bts_assert.h" +#include #include #include From 8a4e90e1be84cedb91adc176f2b064bc2f3624f9 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 2 Jan 2022 14:21:29 -0500 Subject: [PATCH 05/33] refactor: Clean up BTSColor * Rename argb props to be lower case * Make some member fns static extensions * Remove Serializable attribute * Use a single uint prop (rather than 4 byte props) for protobuf serialization --- .../MarketView/MarketViewWindowFactory.cs | 8 +- .../Trading/Ladder/VM/LadderOrderVM.cs | 21 +- .../Trading/Ladder/VM/LadderSettingsVM.cs | 2 +- .../spark/core/FontsAndColors/BTSColor.cs | 350 +++---- .../core/FontsAndColors/BTSColorExtension.cs | 2 +- .../core/FontsAndColors/BTSColorExtensions.cs | 69 ++ .../ColorPicker/Code/ColorSwatchItem.cs | 2 +- .../view/Converters/BTSColorConverter.cs | 18 +- .../spark/view/Extensions/WPFExtensions.cs | 895 +++++++++--------- src/client/spark_core/utils/BitHelper.cs | 28 +- 10 files changed, 701 insertions(+), 694 deletions(-) create mode 100644 src/client/spark/core/FontsAndColors/BTSColorExtensions.cs diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs index f87b00520..d42a0aaad 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindowFactory.cs @@ -83,10 +83,10 @@ namespace bts.shell { var ask_col_index = columns.FindIndex(x => x.id == col_id(Columns.Ask)); if (bid_col_index > -1 && ask_col_index > -1) { if (!columns[bid_col_index].background_color_override.HasValue) { - columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint())); + columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value)); } if (!columns[ask_col_index].background_color_override.HasValue) { - columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint())); + columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value)); } } // and enable background color upgrade @@ -253,11 +253,11 @@ namespace bts.shell { bool applied = false; if (bid_col_index > -1 && ask_col_index > -1) { if (!columns[bid_col_index].background_color_override.HasValue) { - columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint())); + columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value)); applied = true; } if (!columns[ask_col_index].background_color_override.HasValue) { - columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint())); + columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value)); applied = true; } } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index 3e88bdb88..a9f24ed07 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -94,19 +94,14 @@ namespace mbts.spark { } public void update() { - // update brushes - Color color; - switch (side) { - case Side.Buy: color = BTSColors.MarketData.bid_alt; break; - case Side.Sell: color = BTSColors.MarketData.ask_alt; break; - case Side.Undefined: - default: - color = BTSColors.MarketData.bid_ask_alt_blend; break; - } - var darker = BTSColor.darken2(color.R, color.G, color.B, 0.75); - Color dark = new Color() { A = 255, R = darker.r, G = darker.g, B = darker.b }; - var buy_sell_background_fill_color = new SolidColorBrush(color); - buy_sell_background_fill_color.Freeze(); + var color = side switch { + Side.Buy => BTSColors.MarketData.bid_alt, + Side.Sell => BTSColors.MarketData.ask_alt, + _ => BTSColors.MarketData.bid_ask_alt_blend, + }; + var (r, g, b) = color.darken2(0.75); + var dark = Color.FromRgb(r, g, b); + var buy_sell_background_fill_color = color.to_brush().frozen(); background = buy_sell_background_fill_color; hoverbackground = mkbrush(dark, _darkbg, 0); diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index e86517914..859388626 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -726,7 +726,7 @@ namespace mbts.spark { public LadderMarketBreakLine get_settings() => new LadderMarketBreakLine { - color = new BTSColor(color).ToUint(), + color = new BTSColor(color).value, show = show, refresh_mode = refresh_mode }; diff --git a/src/client/spark/core/FontsAndColors/BTSColor.cs b/src/client/spark/core/FontsAndColors/BTSColor.cs index 699a5cbdf..b1b670e5a 100644 --- a/src/client/spark/core/FontsAndColors/BTSColor.cs +++ b/src/client/spark/core/FontsAndColors/BTSColor.cs @@ -1,259 +1,179 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +namespace mbts.ui { + using bts.utils; -namespace mbts.ui { - [Serializable] - [ProtoBuf.ProtoContract(Name = "SerializableColorWrapper")] - public class BTSColor { - public BTSColor() { - A = 255; - B = 128; - R = 128; - G = 128; - } + using ProtoBuf; - public BTSColor(byte gray) { - A = 255; - B = gray; - R = gray; - G = gray; - } + using System; - public BTSColor(byte r, byte g, byte b) { - A = 255; - R = r; - G = g; - B = b; - } + [ProtoContract] + public class BTSColor : IEquatable { + public BTSColor() : this(255, 128, 128, 128) { } + + public BTSColor(byte gray) : this(255, gray, gray, gray) { } + + public BTSColor(byte r, byte g, byte b) : this(255, r, g, b) { } public BTSColor(byte a, byte r, byte g, byte b) { - A = a; - R = r; - G = g; - B = b; + this.a = a; + this.r = r; + this.g = g; + this.b = b; } public BTSColor(System.Windows.Media.Color color) { - A = color.A; - R = color.R; - G = color.G; - B = color.B; + a = color.A; + r = color.R; + g = color.G; + b = color.B; } public BTSColor(System.Drawing.Color color) { - A = color.A; - R = color.R; - G = color.G; - B = color.B; + a = color.A; + r = color.R; + g = color.G; + b = color.B; } public BTSColor(byte alpha, BTSColor color) { - A = alpha; - R = color.R; - G = color.G; - B = color.B; + a = alpha; + r = color.r; + g = color.g; + b = color.b; } - public BTSColor(uint source) { - var arr = BitConverter.GetBytes(source); - - A = (byte)(arr[3] != 0 ? arr[3] : 0xff); - R = arr[2]; - G = arr[1]; - B = arr[0]; - } - - public override bool Equals(object obj) { - if (obj != null) { - if (obj is BTSColor) - return ((BTSColor)obj).A == A && ((BTSColor)obj).B == B && ((BTSColor)obj).R == R && ((BTSColor)obj).G == G; - if (obj is System.Windows.Media.Color) - return ((System.Windows.Media.Color)obj).A == A && ((System.Windows.Media.Color)obj).B == B && ((System.Windows.Media.Color)obj).R == R && ((System.Windows.Media.Color)obj).G == G; - else if (obj is System.Drawing.Color) - return ((System.Drawing.Color)obj).A == A && ((System.Drawing.Color)obj).B == B && ((System.Drawing.Color)obj).R == R && ((System.Drawing.Color)obj).G == G; - } - return false; - } - - public override int GetHashCode() { - return (int)ToUint(); - } - - public uint ToUint() { - return ((uint)A << 24) | ((uint)R << 16) | ((uint)G << 8) | (uint)B; - } + public BTSColor(uint value) => + this.value = value; public enum LightenMethod { Absolute, Relative } - // return a new BTSColor that has been lightened by the specified amount - public BTSColor lighten(int value, LightenMethod method = LightenMethod.Relative) { - var hsl = to_hsl(); + public byte a { + get => (byte)(value >> 24); + set => this.value = BitHelper.set_byte(this.value, value, 24); + } - double _l = hsl.Item3; + public byte r { + get => (byte)(value >> 16); + set => this.value = BitHelper.set_byte(this.value, value, 16); + } - if (method == LightenMethod.Relative) { - _l += _l * value / 100; - } else { - _l += value / 100; + public byte g { + get => (byte)(value >> 8); + set => this.value = BitHelper.set_byte(this.value, value, 8); + } + + public byte b { + get => (byte)value; + set => this.value = BitHelper.set_byte(this.value, value, 0); + } + + [ProtoMember(1)] + public uint value { get; set; } + + public static double hue(double h, double s, double l) { + double m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; + double m1 = l * 2 - m2; + + switch (h) { + case < 0: + h += 1; + break; + case > 1: + h -= 1; + break; } - var rgb = to_rgb(hsl.Item1, hsl.Item2, _l); - - byte _r = (byte)rgb.Item1; - byte _g = (byte)rgb.Item2; - byte _b = (byte)rgb.Item3; - - return new BTSColor(_r, _g, _b); + if (h * 6 < 1) { + return m1 + (m2 - m1) * h * 6; + } + if (h * 2 < 1) { + return m2; + } + if (h * 3 < 2) { + return m1 + (m2 - m1) * (2 / 3 - h) * 6; + } + return m1; } - // Lighten by a negative number - public BTSColor darken(int value, LightenMethod method = LightenMethod.Relative) { - return lighten(value * -1); + // convert an HSL color into RGB + public static (double r, double g, double b) to_rgb(double h, double s, double l) { + h = h % 360 / 360; + s = Math.Min(1, Math.Max(0, s / 100)); + l = Math.Min(1, Math.Max(0, l / 100)); + + return ( + hue(h + 1 / 3, s, l) * 255, + hue(h, s, l) * 255, + hue(h - 1 / 3, s, l) * 255); } - public static (byte r, byte g, byte b) darken2(byte r, byte g, byte b, double darker = 0.75) { - return ((byte)(r * darker), (byte)(g * darker), (byte)(b * darker)); + public void Deconstruct(out byte a, out byte r, out byte g, out byte b) { + a = this.a; + r = this.r; + g = this.g; + b = this.b; } + public static implicit operator System.Drawing.Color(BTSColor x) => + x is null ? + System.Drawing.Color.Gray : + System.Drawing.Color.FromArgb(x.a, x.r, x.g, x.b); - #region Properties + public static implicit operator BTSColor(System.Drawing.Color x) => + new(x); - [ProtoBuf.ProtoMember(2), DefaultValue((byte)255)] - public byte A { get; private set; } + public static implicit operator System.Windows.Media.Color(BTSColor x) => + x is null ? + System.Windows.Media.Colors.Gray : + System.Windows.Media.Color.FromArgb(x.a, x.r, x.g, x.b); - [ProtoBuf.ProtoMember(6), DefaultValue((byte)128)] - public byte R { get; private set; } + public static implicit operator BTSColor(System.Windows.Media.Color x) => + new(x); - [ProtoBuf.ProtoMember(8), DefaultValue((byte)128)] - public byte G { get; private set; } - - [ProtoBuf.ProtoMember(4), DefaultValue((byte)128)] - public byte B { get; private set; } - - #endregion - - public static implicit operator System.Drawing.Color(BTSColor x) { - if (x != null) - return System.Drawing.Color.FromArgb(x.A, x.R, x.G, x.B); - return System.Drawing.Color.Gray; - } - - public static implicit operator BTSColor(System.Drawing.Color x) { - return new BTSColor(x); - } - - public static implicit operator System.Windows.Media.Color(BTSColor x) { - if (x != null) - return System.Windows.Media.Color.FromArgb(x.A, x.R, x.G, x.B); - return System.Windows.Media.Colors.Gray; - } - - public static implicit operator BTSColor(System.Windows.Media.Color x) { - return new BTSColor(x); - } - - static public implicit operator System.Windows.Media.Brush(BTSColor x) { - var v = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(x.A, x.R, x.G, x.B)); + public static implicit operator System.Windows.Media.Brush(BTSColor x) { + var v = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(x.a, x.r, x.g, x.b)); v.Freeze(); return v; } - static public implicit operator BTSColor(System.Windows.Media.SolidColorBrush x) { - return new BTSColor(x.Color); + public static implicit operator BTSColor(System.Windows.Media.SolidColorBrush x) => + new(x.Color); + + public static implicit operator BTSColor(byte x) => + new(x); + + public static implicit operator uint(BTSColor x) => + x.value; + + public static implicit operator BTSColor(uint x) => + new(x); + + public static implicit operator BTSColor(SettingsColor x) => + new((byte)x.A, (byte)x.R, (byte)x.G, (byte)x.B); + + public static implicit operator SettingsColor(BTSColor x) => + new() { A = x.a, R = x.r, G = x.g, B = x.b }; + + public BTSColor clone() => + new(a, r, g, b); + + public bool Equals(BTSColor other) => + other != null && value == other.value; + + public override bool Equals(object obj) { + if (obj is BTSColor bts_color) + return Equals(bts_color); + if (obj is System.Windows.Media.Color media_color) + return Equals(new BTSColor(media_color)); + if (obj is System.Drawing.Color drawing_color) + return Equals(new BTSColor(drawing_color)); + return false; } - public static implicit operator BTSColor(byte x) { - return new BTSColor(x); - } - - public static implicit operator uint(BTSColor x) { - return x.ToUint(); - } - - public static implicit operator BTSColor(uint x) { - return new BTSColor(x); - } - - public static implicit operator BTSColor(SettingsColor x) { - return new BTSColor((byte)x.A, (byte)x.R, (byte)x.G, (byte)x.B); - } - - public static implicit operator SettingsColor(BTSColor x) { - return new SettingsColor() { A = x.A, R = x.R, G = x.G, B = x.B }; - } - - #region Private Functions - - // convert the current color into HSL - private Tuple to_hsl() { - double rr = (double)R / (double)byte.MaxValue; - double gg = (double)G / (double)byte.MaxValue; - double bb = (double)B / (double)byte.MaxValue; - - var max = Math.Max(Math.Max(rr, gg), bb); - var min = Math.Min(Math.Min(rr, gg), bb); - double h = 0; - double s = 0; - double l = (max + min) / 2; - double d = max - min; - if (min != max) { - s = l > 0.5 ? - d / (2 - max - min) : - d / (max + min); - if (max == rr) h = (gg - bb) / d + (gg < bb ? 6 : 0); - if (max == gg) h = (bb - rr) / d + 2; - if (max == bb) h = (rr - gg) / d + 4; - h /= 6; - h = h * 360; - - s = s * 100; - l = l * 100; - } - - return Tuple.Create(h, s, l); - - } - - // convert an HSL color into RGB - private Tuple to_rgb(double h, double s, double l) { - h = (h % 360) / 360; - s = Math.Min(1, Math.Max(0, s / 100)); - l = Math.Min(1, Math.Max(0, l / 100)); - - double r = hue(h + 1 / 3, s, l) * 255; - double g = hue(h, s, l) * 255; - double b = hue(h - 1 / 3, s, l) * 255; - - return Tuple.Create(r, g, b); - } - - private double hue(double h, double s, double l) { - double m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; - double m1 = l * 2 - m2; - - h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); - - if (h * 6 < 1) { - return m1 + (m2 - m1) * h * 6; - } else if (h * 2 < 1) { - return m2; - } else if (h * 3 < 2) { - return m1 + (m2 - m1) * (2 / 3 - h) * 6; - } else { - return m1; - } - } - #endregion - - + public override int GetHashCode() => + // Must return a const bc argb props are mutable + 0; } - } diff --git a/src/client/spark/core/FontsAndColors/BTSColorExtension.cs b/src/client/spark/core/FontsAndColors/BTSColorExtension.cs index 52a43966c..247683785 100644 --- a/src/client/spark/core/FontsAndColors/BTSColorExtension.cs +++ b/src/client/spark/core/FontsAndColors/BTSColorExtension.cs @@ -86,7 +86,7 @@ namespace mbts.ui { } if (Alpha != 0) { - out_color = new BTSColor((Byte)Alpha, out_color.R, out_color.G, out_color.B); + out_color = new BTSColor((Byte)Alpha, out_color.r, out_color.g, out_color.b); } // if the property type is a Color then return a Color diff --git a/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs b/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs new file mode 100644 index 000000000..5d788f7c3 --- /dev/null +++ b/src/client/spark/core/FontsAndColors/BTSColorExtensions.cs @@ -0,0 +1,69 @@ + +namespace mbts.ui { + using System; + + static class BTSColorExtensions { + public static System.Windows.Media.SolidColorBrush to_brush(this BTSColor color) => + new(color); + + public static System.Windows.Media.Color to_media_color(this BTSColor color) => + System.Windows.Media.Color.FromArgb(color.a, color.r, color.g, color.b); + + // return a new BTSColor that has been lightened by the specified amount + public static BTSColor lighten(this BTSColor color, int value, BTSColor.LightenMethod method = BTSColor.LightenMethod.Relative) { + var (h, s, l) = color.to_hsl(); + + if (method == BTSColor.LightenMethod.Relative) { + l += l * value / 100; + } else { + l += value / 100; + } + + var (r, g, b) = BTSColor.to_rgb(h, s, l); + return new((byte)r, (byte)g, (byte)b); + } + + // Lighten by a negative number + public static BTSColor darken(this BTSColor color, int value, BTSColor.LightenMethod method = BTSColor.LightenMethod.Relative) => + color.lighten(value * -1); + + public static (byte r, byte g, byte b) darken2(this BTSColor color, double darker = 0.75) => + ((byte)(color.r * darker), (byte)(color.g * darker), (byte)(color.b * darker)); + + // convert the current color into HSL + public static (double h, double s, double l) to_hsl(this BTSColor color) { + double rr = color.r / (double)byte.MaxValue; + double gg = color.g / (double)byte.MaxValue; + double bb = color.b / (double)byte.MaxValue; + + var max = Math.Max(Math.Max(rr, gg), bb); + var min = Math.Min(Math.Min(rr, gg), bb); + double h = 0; + double s = 0; + double l = (max + min) / 2; + double d = max - min; + + if (min == max) { + return (h, s, l); + } + + s = l > 0.5 ? + d / (2 - max - min) : + d / (max + min); + if (max == rr) { + h = (gg - bb) / d + (gg < bb ? 6 : 0); + } + if (max == gg) { + h = (bb - rr) / d + 2; + } + if (max == bb) { + h = (rr - gg) / d + 4; + } + h *= 60; + s *= 100; + l *= 100; + + return (h, s, l); + } + } +} diff --git a/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs index db38f7750..99712d599 100644 --- a/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs +++ b/src/client/spark/view/Controls/ColorPicker/Code/ColorSwatchItem.cs @@ -28,7 +28,7 @@ namespace mbts.ui.controls.color_picker { get => (_color ?? (_color = _color_id.rgb_color())).Value; set { _color = value; - _color_id = new BTSColor(value).ToUint(); + _color_id = new BTSColor(value).value; } } diff --git a/src/client/spark/view/Converters/BTSColorConverter.cs b/src/client/spark/view/Converters/BTSColorConverter.cs index d5e5db271..199ef5ff4 100644 --- a/src/client/spark/view/Converters/BTSColorConverter.cs +++ b/src/client/spark/view/Converters/BTSColorConverter.cs @@ -1,18 +1,18 @@ using System; +using System.Globalization; using System.Windows.Data; using System.Windows.Media; namespace mbts.ui.converters { public class BTSColorConverter : IValueConverter { - public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value is Color) return value; - BTSColor c = value as BTSColor ?? new BTSColor(); - return Color.FromArgb(c.A, c.R, c.G, c.B); - } + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => + value is Color color ? + color : + (value as BTSColor ?? new BTSColor()).as_media_color(); - public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value is Color) return new BTSColor((Color)value); - return value as BTSColor ?? new BTSColor(); - } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => + value is Color color ? + new BTSColor(color.A, color.R, color.G, color.B) : + value as BTSColor ?? new BTSColor(); } } diff --git a/src/client/spark/view/Extensions/WPFExtensions.cs b/src/client/spark/view/Extensions/WPFExtensions.cs index 2746a6c21..fdbab44ed 100644 --- a/src/client/spark/view/Extensions/WPFExtensions.cs +++ b/src/client/spark/view/Extensions/WPFExtensions.cs @@ -1,449 +1,446 @@ -using bts; -using bts.collections; -using bts.utils; - -using mbts.ui.utility; -using mbts.utils; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Linq; -using System.Reactive.Linq; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Input; -using System.Windows.Media; - -namespace mbts.ui { - static class WPFExtensions { - public static object get_template_child(this Control control, string name) { - if (control == null) throw new ArgumentNullException(nameof(control)); - return control?.Template?.FindName(name, control); - } - - public static T get_template_child(this Control control, string name) { - object obj = get_template_child(control, name); - return ConvertUtils.try_convert(obj); - } - - public static bool try_get_template_child(this Control control, string name, out object result) { - if (control == null) throw new ArgumentNullException(nameof(control)); - var t = control.Template; - if (t != null) { - result = control.Template.FindName(name, control); - return result != null; - } - result = null; - return false; - } - - public static bool try_get_template_child(this Control control, string name, out T result) { - if (try_get_template_child(control, name, out object obj)) - return ConvertUtils.try_convert(obj, out result); - result = default; - return false; - } - - public static object assert_template_child(this Control control, string name) { - if (!try_get_template_child(control, name, out object result)) - throw new InvalidOperationException($"Template must have a child named '{name}'"); - return result; - } - - public static T assert_template_child(this Control control, string name) { - if (!try_get_template_child(control, name, out T result)) - throw new InvalidOperationException($"Template must have a {typeof(T)} child named '{name}'"); - return result; - } - - public static IEnumerable visual_children(this FrameworkElement v) { - var count = VisualTreeHelper.GetChildrenCount(v); - for (var x = 0; x < count; x++) { - yield return VisualTreeHelper.GetChild(v, x); - } - } - - // TODO: replace this method with 'argb_color' - // - before that, need to verify that no settings/colors become 'invisible' as a result. - public static Color rgb_color(this UInt32 color) { - var bytes = BitConverter.GetBytes(color); - return Color.FromRgb(bytes[2], bytes[1], bytes[0]); - } - - public static Color argb_color(this uint color) { - var bytes = BitConverter.GetBytes(color); - return Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]); - } - - /// - /// Creates a blended color, whose a, r, g, b channels are the average of two colors. - /// - public static Color blend_with(this Color color, Color other) => - Color.FromArgb( - (byte)(((ushort)color.A + (ushort)other.A) / 2), - (byte)(((ushort)color.R + (ushort)other.R) / 2), - (byte)(((ushort)color.G + (ushort)other.G) / 2), - (byte)(((ushort)color.B + (ushort)other.B) / 2)); - - public static SolidColorBrush to_brush(this BTSColor color) => - new SolidColorBrush(color); - - public static Brush rgb_brush(this uint color) { - var brush = new SolidColorBrush(rgb_color(color)); - brush.Freeze(); - return brush; - } - - public static Brush argb_brush(this uint color) { - var brush = new SolidColorBrush(argb_color(color)); - brush.Freeze(); - return brush; - } - - public static SolidColorBrush rgb_solid_brush(this uint color) => - new SolidColorBrush(rgb_color(color)); - - public static UInt32 rgb_color(this Color color) { - return (uint)color.A << 24 | (uint)color.R << 16 | (uint)color.G << 8 | (uint)color.B; - } - - public static Brush to_brush(this Color color) => - new SolidColorBrush(color); - - public static SolidColorBrush to_solid_brush(this Color color) => - new SolidColorBrush(color); - - public static Brush frozen(this Brush brush) { - brush.Freeze(); - return brush; - } - - public static SolidColorBrush frozen(this SolidColorBrush brush) { - brush.Freeze(); - return brush; - } - - public static Color with(this Color color, byte alpha) => - Color.FromArgb(alpha, color.R, color.G, color.B); - - public static SolidColorBrush with(this SolidColorBrush brush, double opacity) { - brush.Opacity = opacity; - return brush; - } - - public static Pen frozen(this Pen pen) { - pen.Freeze(); - return pen; - } - - public static ImageSource frozen(this ImageSource image_source) { - image_source.Freeze(); - return image_source; - } - - public static Point within_bounds(this Point point, double x_min = 0, double y_min = 0, double x_max = double.PositiveInfinity, double y_max = double.PositiveInfinity) => - new Point(MathUtils.within_range(x_min, x_max, point.X), MathUtils.within_range(y_min, y_max, point.Y)); - - // Perform a breadth first traversal of all children returning any that match the predicate. - // Matching children are *not* further traversed - public static IEnumerable visual_children_where(this FrameworkElement v, Func match) { - var children = visual_children(v).OfType().ToList(); - while (children.Count() > 0) { - var next = new List(); - foreach (var c in children) { - if (match(c)) { - yield return c; - } else { - next.AddRange(visual_children(c).OfType()); - } - } - children = next; - } - } - - public static IEnumerable descendants_of_type(this FrameworkElement v) { - return v.visual_children_where(fe => fe is T).Cast(); - } - - public static bool try_find_descendent_of_type(this FrameworkElement element, out T result) where T : DependencyObject => - element.descendants_of_type().TryGetFirst(out result); - - public static bool try_find_ancestor_of_type(this FrameworkElement element, out T result) where T : DependencyObject { - result = find_ancestor_of_type(element); - return result != null; - } - - public static bool try_find_ancestor_of_type(this FrameworkContentElement element, out T result) where T : DependencyObject { - result = find_ancestor_of_type(element); - return result != null; - } - - public static T find_ancestor_of_type(this FrameworkElement element) where T : DependencyObject { - return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); - T impl(DependencyObject d) { - if (d is T direct_match) - return direct_match; - if (d is FrameworkElement el) { - if (el.find_ancestor_of_type() is T rv) - return rv; - } else if (d is FrameworkContentElement cel) { - if (cel.find_ancestor_of_type() is T rv) - return rv; - } - return null; - } - IEnumerable candidates() { - yield return element.Parent; - yield return element.TemplatedParent; - yield return VisualTreeHelper.GetParent(element); - } - } - - public static T find_ancestor_of_type(this FrameworkContentElement element) where T : DependencyObject { - return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); - T impl(DependencyObject d) { - if (d is T direct_match) - return direct_match; - if (d is FrameworkElement el) { - if (el.find_ancestor_of_type() is T rv) - return rv; - } else if (d is FrameworkContentElement cel) { - if (cel.find_ancestor_of_type() is T rv) - return rv; - } - return null; - } - IEnumerable candidates() { - yield return element.Parent; - yield return element.TemplatedParent; - yield return VisualTreeHelper.GetParent(element); - } - } - - public static void clear_bindings(this DependencyObject d_obj, params DependencyProperty[] d_props) { - foreach (var dp in d_props) - BindingOperations.ClearBinding(d_obj, dp); - } - - public static IDisposable attach_binding(this DependencyObject target, DependencyProperty target_property, string path, FrameworkElement source_view, IValueConverter converter = null) { - object source_vm = source_view.DataContext; - try_reset_binding(); - source_view.DataContextChanged += on_data_context_changed; - return Disposable.Create(() => { - try { - source_view.DataContextChanged -= on_data_context_changed; - } catch (Exception ex) { - Log.Ui.warn($"Error detaching from {nameof(source_view)}.{nameof(FrameworkElement.DataContextChanged)} event: {ex}."); - } - }); - void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) { - source_vm = e.NewValue; - try_reset_binding(); - } - void try_reset_binding() { - if (source_vm != null) - target.reset_binding(target_property, new Binding(path) { Source = source_vm, Converter = converter }); - } - } - - public static void reset_binding(this DependencyObject target, DependencyProperty target_property, BindingBase binding) { - BindingOperations.ClearBinding(target, target_property); - BindingOperations.SetBinding(target, target_property, binding); - } - - public static void TryRaiseCanExecuteChanged(this ICommand command) { - if (command == null) return; - else if (command is IRaiseCanExecuteChangedCommand temp) - temp.RaiseCanExecuteChanged(); - else - throw new NotImplementedException("This ICommand does not implement IRaiseCanExecuteChanged"); - } - - public static Task ExecuteAsync(this ICommand command, object parameter) { - ExceptionAssert.Argument.NotNull(command, nameof(command)); - if (command is IAsyncCommand acmd) - return acmd.Execute(parameter); - else - return Task.Run(() => command.Execute(parameter)); - } - - public static void TryExecuteIfCan(this ICommand command, object parameter) { - if (command != null) - ExecuteIfCan(command, parameter); - } - - public static void ExecuteIfCan(this ICommand command, object parameter) { - ExceptionAssert.Argument.NotNull(command, nameof(command)); - if (command.CanExecute(parameter)) - command.Execute(parameter); - } - - public static IDisposable ObserveProperty(this DependencyObject instance, DependencyProperty property, EventHandler callback) { - var descriptor = DependencyPropertyDescriptor.FromProperty(property, instance.GetType()); - if (descriptor != null) { - descriptor.AddValueChanged(instance, callback); - return Disposable.Create(() => descriptor.RemoveValueChanged(instance, callback)); - } - throw new ArgumentException("Could not find property descriptor given type"); - } - - public static IObservable Observe(this DependencyObject instance, DependencyProperty property) { - Log.assert(typeof(T) == instance.GetType()); - return Observable.Create(observer => { - return instance.ObserveProperty(property, (o, e) => { - observer.OnNext((T)instance.GetValue(property)); - }); - }); - } - - public static void CommitAny(this IEditableCollectionView collection) { - if (collection.IsEditingItem) { - collection.CommitEdit(); - } else if (collection.IsAddingNew) { - collection.CommitNew(); - } - } - - public static void CancelAny(this IEditableCollectionView collection) { - if (collection.IsEditingItem) { - if (collection.CanCancelEdit) - collection.CancelEdit(); - } else if (collection.IsAddingNew) { - collection.CancelNew(); - } - } - - public static void ClearMouseBindings(this UIElement element, MouseAction action) => - ClearMouseBindings(element, action, ModifierKeys.None); - - public static void ClearMouseBindings(this UIElement element, MouseAction action, ModifierKeys modifiers) { - for (int i = 0; i < element.InputBindings.Count; i++) { - var mb = element.InputBindings[i] as MouseBinding; - if (mb != null) { - var g = mb.Gesture as MouseGesture; - if (g != null && g.MouseAction == action && g.Modifiers == modifiers) - element.InputBindings.RemoveAt(i); - } - } - } - - public static void ClearKeyBindings(this UIElement element, Key key) => - ClearKeyBindings(element, key, ModifierKeys.None); - - public static void ClearKeyBindings(this UIElement element, Key key, ModifierKeys modifiers) { - for (int i = 0; i < element.InputBindings.Count; i++) { - if (element.InputBindings[i] is KeyBinding kb && kb.Key == key && kb.Modifiers == modifiers) - element.InputBindings.RemoveAt(i--); - } - } - - public static void ClearCommandBindings(this UIElement element, RoutedCommand cmd) { - for (int i = 0; i < element.CommandBindings.Count; i++) { - if (element.CommandBindings[i].Command == cmd) - element.CommandBindings.RemoveAt(i--); - } - } - - public static void EnsureIsVisible(this Window window) { - if (!window.IsVisible) window.Show(); - if (window.WindowState == WindowState.Minimized) { - window.WindowState = WindowState.Normal; - } - window.ensure_onscreen(); - window.Activate(); - } - - public static Size MeasureText(this Typeface font, double size, string text) { -#pragma warning disable CS0618 // Type or member is obsolete - var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, font, size, Brushes.Black); -#pragma warning restore CS0618 // Type or member is obsolete - return new Size(ft.Width, ft.Height); - } - - public static void SetSortingCriteria(this ICollectionView collection_view, IEnumerable sorting_criteria) { - collection_view.SortDescriptions.Clear(); - if (sorting_criteria != null) - foreach (var sc in sorting_criteria) - collection_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)); - } - - /// - /// Converts .SortDescriptions into a List<>. - /// - public static List get_sorting_criteria(this ICollectionView collection_view, ObservableCollection columns) => - collection_view.SortDescriptions - .Select(sd => new SortingCriteria(columns.FirstOrDefault(c => c.sort_member_path == sd.PropertyName)?.id, sd.Direction == ListSortDirection.Ascending)) - .Where(sc => sc.col_name != null) - .ToList(); - - public static IEnumerable get_sorting_criteria(this ICollectionView collection_view, IEnumerable columns) => - get_sorting_criteria(collection_view.SortDescriptions, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); - - public static IEnumerable get_sorting_criteria(IEnumerable sort_descriptions, IEnumerable<(string id, string path)> columns) => - from sd in sort_descriptions - join col in columns - on sd.PropertyName equals col.path - select new SortingCriteria(col.id, sd.Direction == ListSortDirection.Ascending); - - public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable columns) => - get_sort_descriptions(sorting_criterion, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); - - public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable<(string id, string path)> columns) => - from sc in sorting_criterion - join col in columns - on sc.col_name equals col.id - select new SortDescription(col.path, sc.direction()); - - /// - /// Converts each into a and assigns the result to .SortDescriptions. - /// - public static void set_sort_descriptions(this ICollectionView collection_view, IEnumerable sorting_criterion, ObservableCollection columns) { - using (collection_view.DeferRefresh()) { - collection_view.SortDescriptions.SetItems(sorting_criterion.empty_if_null() - .Select(sc => new SortDescription( - columns.FirstOrDefault(c => string.Equals(c.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase))?.sort_member_path, - sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)) - .Where(sd => !string.IsNullOrEmpty(sd.PropertyName))); - } - } - - public static IObservable> subscribe_sorting_criterion(this ICollectionView collection_view, Func sort_member_to_id) => - Observable.Create>(o => { - INotifyCollectionChanged notification_src = collection_view.SortDescriptions; - IList sort_descriptions = collection_view.SortDescriptions; - var sorting_criterion = sort_descriptions.Select(to_criteria).ToList(); - notification_src.CollectionChanged += on_sort_descriptions_changed; - o.OnNext(sorting_criterion); - return Disposable.Create(dispose); - // local methods - void on_sort_descriptions_changed(object sender, NotifyCollectionChangedEventArgs e) { - CollectionHelper.reflect_change(sorting_criterion, collection_view.SortDescriptions, to_criteria, null, e); - o.OnNext(sorting_criterion); - } - SortingCriteria to_criteria(SortDescription sd) => new SortingCriteria(sort_member_to_id(sd.PropertyName), sd.Direction == ListSortDirection.Ascending); - void dispose() => notification_src.CollectionChanged -= on_sort_descriptions_changed; - }); - - public static IEnumerable FlatItems(this CollectionViewGroup group) { - foreach (var item in group.Items) { - if (item is CollectionViewGroup nested) { - foreach (var ni in FlatItems(nested)) - yield return ni; - } else { - yield return item; - } - } - } - - public static Rect Expanded(this Rect rect, double uniform_dimension) { - // since Rect is a struct, we are mutating a copy of the caller's actual rect - rect.Inflate(new Size(uniform_dimension, uniform_dimension)); - return rect; - } - } -} +using bts; +using bts.collections; +using bts.utils; + +using mbts.ui.utility; +using mbts.utils; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui { + static class WPFExtensions { + public static object get_template_child(this Control control, string name) { + if (control == null) throw new ArgumentNullException(nameof(control)); + return control?.Template?.FindName(name, control); + } + + public static T get_template_child(this Control control, string name) { + object obj = get_template_child(control, name); + return ConvertUtils.try_convert(obj); + } + + public static bool try_get_template_child(this Control control, string name, out object result) { + if (control == null) throw new ArgumentNullException(nameof(control)); + var t = control.Template; + if (t != null) { + result = control.Template.FindName(name, control); + return result != null; + } + result = null; + return false; + } + + public static bool try_get_template_child(this Control control, string name, out T result) { + if (try_get_template_child(control, name, out object obj)) + return ConvertUtils.try_convert(obj, out result); + result = default; + return false; + } + + public static object assert_template_child(this Control control, string name) { + if (!try_get_template_child(control, name, out object result)) + throw new InvalidOperationException($"Template must have a child named '{name}'"); + return result; + } + + public static T assert_template_child(this Control control, string name) { + if (!try_get_template_child(control, name, out T result)) + throw new InvalidOperationException($"Template must have a {typeof(T)} child named '{name}'"); + return result; + } + + public static IEnumerable visual_children(this FrameworkElement v) { + var count = VisualTreeHelper.GetChildrenCount(v); + for (var x = 0; x < count; x++) { + yield return VisualTreeHelper.GetChild(v, x); + } + } + + // TODO: replace this method with 'argb_color' + // - before that, need to verify that no settings/colors become 'invisible' as a result. + public static Color rgb_color(this UInt32 color) { + var bytes = BitConverter.GetBytes(color); + return Color.FromRgb(bytes[2], bytes[1], bytes[0]); + } + + public static Color argb_color(this uint color) { + var bytes = BitConverter.GetBytes(color); + return Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]); + } + + /// + /// Creates a blended color, whose a, r, g, b channels are the average of two colors. + /// + public static Color blend_with(this Color color, Color other) => + Color.FromArgb( + (byte)(((ushort)color.A + (ushort)other.A) / 2), + (byte)(((ushort)color.R + (ushort)other.R) / 2), + (byte)(((ushort)color.G + (ushort)other.G) / 2), + (byte)(((ushort)color.B + (ushort)other.B) / 2)); + + public static Brush rgb_brush(this uint color) { + var brush = new SolidColorBrush(rgb_color(color)); + brush.Freeze(); + return brush; + } + + public static Brush argb_brush(this uint color) { + var brush = new SolidColorBrush(argb_color(color)); + brush.Freeze(); + return brush; + } + + public static SolidColorBrush rgb_solid_brush(this uint color) => + new SolidColorBrush(rgb_color(color)); + + public static UInt32 rgb_color(this Color color) { + return (uint)color.A << 24 | (uint)color.R << 16 | (uint)color.G << 8 | (uint)color.B; + } + + public static Brush to_brush(this Color color) => + new SolidColorBrush(color); + + public static SolidColorBrush to_solid_brush(this Color color) => + new SolidColorBrush(color); + + public static Brush frozen(this Brush brush) { + brush.Freeze(); + return brush; + } + + public static SolidColorBrush frozen(this SolidColorBrush brush) { + brush.Freeze(); + return brush; + } + + public static Color with(this Color color, byte alpha) => + Color.FromArgb(alpha, color.R, color.G, color.B); + + public static SolidColorBrush with(this SolidColorBrush brush, double opacity) { + brush.Opacity = opacity; + return brush; + } + + public static Pen frozen(this Pen pen) { + pen.Freeze(); + return pen; + } + + public static ImageSource frozen(this ImageSource image_source) { + image_source.Freeze(); + return image_source; + } + + public static Point within_bounds(this Point point, double x_min = 0, double y_min = 0, double x_max = double.PositiveInfinity, double y_max = double.PositiveInfinity) => + new Point(MathUtils.within_range(x_min, x_max, point.X), MathUtils.within_range(y_min, y_max, point.Y)); + + // Perform a breadth first traversal of all children returning any that match the predicate. + // Matching children are *not* further traversed + public static IEnumerable visual_children_where(this FrameworkElement v, Func match) { + var children = visual_children(v).OfType().ToList(); + while (children.Count() > 0) { + var next = new List(); + foreach (var c in children) { + if (match(c)) { + yield return c; + } else { + next.AddRange(visual_children(c).OfType()); + } + } + children = next; + } + } + + public static IEnumerable descendants_of_type(this FrameworkElement v) { + return v.visual_children_where(fe => fe is T).Cast(); + } + + public static bool try_find_descendent_of_type(this FrameworkElement element, out T result) where T : DependencyObject => + element.descendants_of_type().TryGetFirst(out result); + + public static bool try_find_ancestor_of_type(this FrameworkElement element, out T result) where T : DependencyObject { + result = find_ancestor_of_type(element); + return result != null; + } + + public static bool try_find_ancestor_of_type(this FrameworkContentElement element, out T result) where T : DependencyObject { + result = find_ancestor_of_type(element); + return result != null; + } + + public static T find_ancestor_of_type(this FrameworkElement element) where T : DependencyObject { + return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); + T impl(DependencyObject d) { + if (d is T direct_match) + return direct_match; + if (d is FrameworkElement el) { + if (el.find_ancestor_of_type() is T rv) + return rv; + } else if (d is FrameworkContentElement cel) { + if (cel.find_ancestor_of_type() is T rv) + return rv; + } + return null; + } + IEnumerable candidates() { + yield return element.Parent; + yield return element.TemplatedParent; + yield return VisualTreeHelper.GetParent(element); + } + } + + public static T find_ancestor_of_type(this FrameworkContentElement element) where T : DependencyObject { + return candidates().ExceptNull().Distinct().Select(impl).ExceptNull().FirstOrDefault(); + T impl(DependencyObject d) { + if (d is T direct_match) + return direct_match; + if (d is FrameworkElement el) { + if (el.find_ancestor_of_type() is T rv) + return rv; + } else if (d is FrameworkContentElement cel) { + if (cel.find_ancestor_of_type() is T rv) + return rv; + } + return null; + } + IEnumerable candidates() { + yield return element.Parent; + yield return element.TemplatedParent; + yield return VisualTreeHelper.GetParent(element); + } + } + + public static void clear_bindings(this DependencyObject d_obj, params DependencyProperty[] d_props) { + foreach (var dp in d_props) + BindingOperations.ClearBinding(d_obj, dp); + } + + public static IDisposable attach_binding(this DependencyObject target, DependencyProperty target_property, string path, FrameworkElement source_view, IValueConverter converter = null) { + object source_vm = source_view.DataContext; + try_reset_binding(); + source_view.DataContextChanged += on_data_context_changed; + return Disposable.Create(() => { + try { + source_view.DataContextChanged -= on_data_context_changed; + } catch (Exception ex) { + Log.Ui.warn($"Error detaching from {nameof(source_view)}.{nameof(FrameworkElement.DataContextChanged)} event: {ex}."); + } + }); + void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) { + source_vm = e.NewValue; + try_reset_binding(); + } + void try_reset_binding() { + if (source_vm != null) + target.reset_binding(target_property, new Binding(path) { Source = source_vm, Converter = converter }); + } + } + + public static void reset_binding(this DependencyObject target, DependencyProperty target_property, BindingBase binding) { + BindingOperations.ClearBinding(target, target_property); + BindingOperations.SetBinding(target, target_property, binding); + } + + public static void TryRaiseCanExecuteChanged(this ICommand command) { + if (command == null) return; + else if (command is IRaiseCanExecuteChangedCommand temp) + temp.RaiseCanExecuteChanged(); + else + throw new NotImplementedException("This ICommand does not implement IRaiseCanExecuteChanged"); + } + + public static Task ExecuteAsync(this ICommand command, object parameter) { + ExceptionAssert.Argument.NotNull(command, nameof(command)); + if (command is IAsyncCommand acmd) + return acmd.Execute(parameter); + else + return Task.Run(() => command.Execute(parameter)); + } + + public static void TryExecuteIfCan(this ICommand command, object parameter) { + if (command != null) + ExecuteIfCan(command, parameter); + } + + public static void ExecuteIfCan(this ICommand command, object parameter) { + ExceptionAssert.Argument.NotNull(command, nameof(command)); + if (command.CanExecute(parameter)) + command.Execute(parameter); + } + + public static IDisposable ObserveProperty(this DependencyObject instance, DependencyProperty property, EventHandler callback) { + var descriptor = DependencyPropertyDescriptor.FromProperty(property, instance.GetType()); + if (descriptor != null) { + descriptor.AddValueChanged(instance, callback); + return Disposable.Create(() => descriptor.RemoveValueChanged(instance, callback)); + } + throw new ArgumentException("Could not find property descriptor given type"); + } + + public static IObservable Observe(this DependencyObject instance, DependencyProperty property) { + Log.assert(typeof(T) == instance.GetType()); + return Observable.Create(observer => { + return instance.ObserveProperty(property, (o, e) => { + observer.OnNext((T)instance.GetValue(property)); + }); + }); + } + + public static void CommitAny(this IEditableCollectionView collection) { + if (collection.IsEditingItem) { + collection.CommitEdit(); + } else if (collection.IsAddingNew) { + collection.CommitNew(); + } + } + + public static void CancelAny(this IEditableCollectionView collection) { + if (collection.IsEditingItem) { + if (collection.CanCancelEdit) + collection.CancelEdit(); + } else if (collection.IsAddingNew) { + collection.CancelNew(); + } + } + + public static void ClearMouseBindings(this UIElement element, MouseAction action) => + ClearMouseBindings(element, action, ModifierKeys.None); + + public static void ClearMouseBindings(this UIElement element, MouseAction action, ModifierKeys modifiers) { + for (int i = 0; i < element.InputBindings.Count; i++) { + var mb = element.InputBindings[i] as MouseBinding; + if (mb != null) { + var g = mb.Gesture as MouseGesture; + if (g != null && g.MouseAction == action && g.Modifiers == modifiers) + element.InputBindings.RemoveAt(i); + } + } + } + + public static void ClearKeyBindings(this UIElement element, Key key) => + ClearKeyBindings(element, key, ModifierKeys.None); + + public static void ClearKeyBindings(this UIElement element, Key key, ModifierKeys modifiers) { + for (int i = 0; i < element.InputBindings.Count; i++) { + if (element.InputBindings[i] is KeyBinding kb && kb.Key == key && kb.Modifiers == modifiers) + element.InputBindings.RemoveAt(i--); + } + } + + public static void ClearCommandBindings(this UIElement element, RoutedCommand cmd) { + for (int i = 0; i < element.CommandBindings.Count; i++) { + if (element.CommandBindings[i].Command == cmd) + element.CommandBindings.RemoveAt(i--); + } + } + + public static void EnsureIsVisible(this Window window) { + if (!window.IsVisible) window.Show(); + if (window.WindowState == WindowState.Minimized) { + window.WindowState = WindowState.Normal; + } + window.ensure_onscreen(); + window.Activate(); + } + + public static Size MeasureText(this Typeface font, double size, string text) { +#pragma warning disable CS0618 // Type or member is obsolete + var ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, font, size, Brushes.Black); +#pragma warning restore CS0618 // Type or member is obsolete + return new Size(ft.Width, ft.Height); + } + + public static void SetSortingCriteria(this ICollectionView collection_view, IEnumerable sorting_criteria) { + collection_view.SortDescriptions.Clear(); + if (sorting_criteria != null) + foreach (var sc in sorting_criteria) + collection_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)); + } + + /// + /// Converts .SortDescriptions into a List<>. + /// + public static List get_sorting_criteria(this ICollectionView collection_view, ObservableCollection columns) => + collection_view.SortDescriptions + .Select(sd => new SortingCriteria(columns.FirstOrDefault(c => c.sort_member_path == sd.PropertyName)?.id, sd.Direction == ListSortDirection.Ascending)) + .Where(sc => sc.col_name != null) + .ToList(); + + public static IEnumerable get_sorting_criteria(this ICollectionView collection_view, IEnumerable columns) => + get_sorting_criteria(collection_view.SortDescriptions, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); + + public static IEnumerable get_sorting_criteria(IEnumerable sort_descriptions, IEnumerable<(string id, string path)> columns) => + from sd in sort_descriptions + join col in columns + on sd.PropertyName equals col.path + select new SortingCriteria(col.id, sd.Direction == ListSortDirection.Ascending); + + public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable columns) => + get_sort_descriptions(sorting_criterion, columns.Select(c => (controls.DataGridEx.GetCellKey(c)?.ToString(), c.SortMemberPath))); + + public static IEnumerable get_sort_descriptions(this IEnumerable sorting_criterion, IEnumerable<(string id, string path)> columns) => + from sc in sorting_criterion + join col in columns + on sc.col_name equals col.id + select new SortDescription(col.path, sc.direction()); + + /// + /// Converts each into a and assigns the result to .SortDescriptions. + /// + public static void set_sort_descriptions(this ICollectionView collection_view, IEnumerable sorting_criterion, ObservableCollection columns) { + using (collection_view.DeferRefresh()) { + collection_view.SortDescriptions.SetItems(sorting_criterion.empty_if_null() + .Select(sc => new SortDescription( + columns.FirstOrDefault(c => string.Equals(c.id, sc.col_name, StringComparison.CurrentCultureIgnoreCase))?.sort_member_path, + sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)) + .Where(sd => !string.IsNullOrEmpty(sd.PropertyName))); + } + } + + public static IObservable> subscribe_sorting_criterion(this ICollectionView collection_view, Func sort_member_to_id) => + Observable.Create>(o => { + INotifyCollectionChanged notification_src = collection_view.SortDescriptions; + IList sort_descriptions = collection_view.SortDescriptions; + var sorting_criterion = sort_descriptions.Select(to_criteria).ToList(); + notification_src.CollectionChanged += on_sort_descriptions_changed; + o.OnNext(sorting_criterion); + return Disposable.Create(dispose); + // local methods + void on_sort_descriptions_changed(object sender, NotifyCollectionChangedEventArgs e) { + CollectionHelper.reflect_change(sorting_criterion, collection_view.SortDescriptions, to_criteria, null, e); + o.OnNext(sorting_criterion); + } + SortingCriteria to_criteria(SortDescription sd) => new SortingCriteria(sort_member_to_id(sd.PropertyName), sd.Direction == ListSortDirection.Ascending); + void dispose() => notification_src.CollectionChanged -= on_sort_descriptions_changed; + }); + + public static IEnumerable FlatItems(this CollectionViewGroup group) { + foreach (var item in group.Items) { + if (item is CollectionViewGroup nested) { + foreach (var ni in FlatItems(nested)) + yield return ni; + } else { + yield return item; + } + } + } + + public static Rect Expanded(this Rect rect, double uniform_dimension) { + // since Rect is a struct, we are mutating a copy of the caller's actual rect + rect.Inflate(new Size(uniform_dimension, uniform_dimension)); + return rect; + } + } +} diff --git a/src/client/spark_core/utils/BitHelper.cs b/src/client/spark_core/utils/BitHelper.cs index f669a3baa..d27157f55 100644 --- a/src/client/spark_core/utils/BitHelper.cs +++ b/src/client/spark_core/utils/BitHelper.cs @@ -1,6 +1,8 @@ namespace bts.utils { public static class BitHelper { + public static byte loaded_byte => _ByteBits.all; public static int loaded_int32 => _Int32Bits.all; + public static uint loaded_uint32 => _UInt32Bits.all; public static bool remove_flags(ref int target, int flags) { if ((target & flags) == flags) { @@ -9,6 +11,17 @@ } else return false; } + static class _ByteBits { + public static readonly byte all; + + static _ByteBits() { + all = 1 << 7; + all |= (byte)(all >> 1); + all |= (byte)(all >> 2); + all |= (byte)(all >> 4); + } + } + static class _Int32Bits { public static readonly int all; @@ -21,5 +34,18 @@ all |= (all >> 16); } } + + static class _UInt32Bits { + public static readonly uint all; + + static _UInt32Bits() { + all = 1u << 31; + all |= all >> 1; + all |= all >> 2; + all |= all >> 4; + all |= all >> 8; + all |= all >> 16; + } + } } -} \ No newline at end of file +} From 5a81c223c19d4bd20f5e0b948f23285e5110f7e1 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 3 Jan 2022 21:10:09 -0600 Subject: [PATCH 06/33] Remove old 'PAndl' window --- .../Modules/Trading/PAndLWindowFactory.cs | 183 ----- .../Modules/Trading/TradingShellModule.cs | 54 +- src/client/spark/core/Bus/SparkCommands.cs | 317 ++++---- src/client/spark/core/Bus/SparkTags.cs | 677 +++++++++--------- .../UserSettings/UserSettings.cs | 9 +- .../UserSettings/UserSettingsHub.cs | 10 - src/client/spark/view/Spark/PAndL/PAndLVM.cs | 372 ---------- .../spark/view/Spark/PAndL/PAndLView.xaml | 122 ---- .../spark/view/Spark/PAndL/PAndLView.xaml.cs | 16 - .../spark/view/Spark/PAndL/PAndLWindow.cs | 90 --- src/client/spark/view/Spark/PAndL/PnLData.cs | 58 -- .../spark/view/Spark/PAndL/PnLHelper.cs | 166 ----- .../spark/view/Spark/PAndL/PnLSummaryRow.cs | 229 ------ 13 files changed, 508 insertions(+), 1795 deletions(-) delete mode 100644 src/client/spark/Modules/Trading/PAndLWindowFactory.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PAndLVM.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PAndLView.xaml delete mode 100644 src/client/spark/view/Spark/PAndL/PAndLView.xaml.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PAndLWindow.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PnLData.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PnLHelper.cs delete mode 100644 src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs diff --git a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs b/src/client/spark/Modules/Trading/PAndLWindowFactory.cs deleted file mode 100644 index 6282559cf..000000000 --- a/src/client/spark/Modules/Trading/PAndLWindowFactory.cs +++ /dev/null @@ -1,183 +0,0 @@ -using bts.api; -using bts.settings; -using bts.spark; - -using mbts.persist; -using mbts.spark; -using mbts.spark.filters; -using mbts.ui; -using mbts.ui.settings; - -using ProtoBuf; - -using System; -using System.Collections.Generic; -using System.Composition; -using System.Linq; -using System.Reactive.Linq; -using System.Threading.Tasks; - -using static mbts.spark.PAndLView; -using static mbts.ui.controls.DIYGrid; - -namespace bts.shell { - internal class PAndLWindowFactory : ShellWindowFactory { - readonly IBus _bus; - readonly OrdersModel _orders_model; - readonly UserSettingsHub _settings_hub; - - public PAndLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, "SparkPAndL") { - _bus = bus; - _orders_model = orders_model; - _settings_hub = settings_hub; - _dispose = bus.subscribe(SparkTags.ShowPAndLTag).OnDispatcher().Subscribe(show); - } - - public static string col_id(Columns col) => col.ToString(); - - public override Task load(PAndLStartupData state) { - return Task.FromResult(_create(state)); - } - - async void show(PAndLStartupData startup_data) { - var w = await load(startup_data); - _bus.post(SparkTags.ShowWindow, w); - } - - IShellWindow _create(PAndLStartupData state) => - new PAndLWindow( - _orders_model, - this, - _bus, - state, - SparkCommands.ShowPAndL.icon, - _settings_hub.create_pandl_settings_manager(state.grid)); - - [ProtoContract] - public class PAndLStartupData { - - /// - /// Parameterless constructor for protobuf - /// - public PAndLStartupData() { } - - public PAndLStartupData(List sorting_criteria, FilterStates filters, pnl_calc_type calc_type, GridSettings grid = default) { - _sort_criteria = sorting_criteria; - this.filters = filters; - this.calc_type = calc_type; - this.grid = grid; - } - - public static GridSettings DefaultGridSettings => GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criterion); - - public IReadOnlyList sorting_criterion => _sort_criteria ?? (_sort_criteria = DefaultColumns.default_sorting_criterion.ToList()); - public static PAndLStartupData Default() => - new PAndLStartupData(null, new FilterStates(), pnl_calc_type.midpoint); - - - [ProtoMember(5)] - List _sort_criteria; - [ProtoMember(10)] - public FilterStates filters; - [ProtoMember(15)] - public pnl_calc_type calc_type; - //[ProtoMember(20)] - // ProtoMember 20 cannot be used further - [ProtoMember(25)] - public GridSettings grid; - - static class DefaultColumns { - - public static GridColumnSettings account => new GridColumnSettings(col_id(Columns.Account), DefaultColumnHeaders.Account, width: DefaultColumnWidths.Account); - public static GridColumnSettings exchange => new GridColumnSettings(col_id(Columns.Exchange), DefaultColumnHeaders.Exchange, false, width: DefaultColumnWidths.Exchange); - public static GridColumnSettings symbol => new GridColumnSettings(col_id(Columns.Symbol), DefaultColumnHeaders.Symbol, width: DefaultColumnWidths.Symbol); - public static GridColumnSettings security => new GridColumnSettings(col_id(Columns.Security), DefaultColumnHeaders.Security, width: DefaultColumnWidths.Security); - public static GridColumnSettings security_type => new GridColumnSettings(col_id(Columns.SecurityType), DefaultColumnHeaders.SecurityType, width: DefaultColumnWidths.SecurityType); - public static GridColumnSettings start_net_position => new GridColumnSettings(col_id(Columns.StartNetPos), DefaultColumnHeaders.StartNetPos, width: DefaultColumnWidths.Start_Net_Pos, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings start_pnl => new GridColumnSettings(col_id(Columns.StartPNL), DefaultColumnHeaders.StartPnL, false, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings day_long_pnl => new GridColumnSettings(col_id(Columns.DayLong), DefaultColumnHeaders.DayLong, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings day_short_pnl => new GridColumnSettings(col_id(Columns.DayShort), DefaultColumnHeaders.DayShort, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings raw_day_net_position => new GridColumnSettings(col_id(Columns.RawDayPos), DefaultColumnHeaders.RawDayPos, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right, is_visible: false); - public static GridColumnSettings day_pnl => new GridColumnSettings(col_id(Columns.DayPNL), DefaultColumnHeaders.DayPnL, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings total_net_pos => new GridColumnSettings(col_id(Columns.TotalNetPos), DefaultColumnHeaders.TotalNetPos, false, width: DefaultColumnWidths.Total_Net_Pos, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings total_pnl => new GridColumnSettings(col_id(Columns.TotalPNL), DefaultColumnHeaders.TotalPnL, false, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings pnl_price => new GridColumnSettings(col_id(Columns.PNLPrice), DefaultColumnHeaders.PnLPrice, width: DefaultColumnWidths.PnL_Generic, horizontal_alignment: System.Windows.HorizontalAlignment.Right); - public static GridColumnSettings has_day_trades => new GridColumnSettings(col_id(Columns.TradedToday), "Traded Today", width: 100, horizontal_alignment: System.Windows.HorizontalAlignment.Center); - - public static IEnumerable default_sorting_criterion { - get { - yield return new SortingCriteria(account.id, true); - yield return new SortingCriteria(exchange.id, true); - yield return new SortingCriteria(symbol.id, true); - yield return new SortingCriteria(security.id, true); - } - } - - public static IEnumerable all { - get { - yield return account; - yield return exchange; - yield return symbol; - yield return security; - yield return security_type; - yield return start_net_position; - yield return start_pnl; - yield return day_long_pnl; - yield return day_short_pnl; - yield return raw_day_net_position; - yield return day_pnl; - yield return total_net_pos; - yield return total_pnl; - yield return pnl_price; - yield return has_day_trades; - } - } - - } - } - - [ProtoContract] - public class FilterStates { - [ProtoMember(1)] - public string account_regex; - [ProtoMember(2)] - public string exchange_regex; - [ProtoMember(3)] - public string symbol_regex; - [ProtoMember(4)] - public string security_regex; - [ProtoMember(5)] - public IntMinMaxState start_net_pos; - [ProtoMember(6)] - public DoubleMinMaxState start_pnl; - [ProtoMember(7)] - public UIntMinMaxState day_long_pos; - [ProtoMember(8)] - public UIntMinMaxState day_short_pos; - [ProtoMember(16)] - public DoubleMinMaxState raw_day_net_pos; - [ProtoMember(9)] - public DoubleMinMaxState day_pnl; - [ProtoMember(10)] - public IntMinMaxState total_net_pos; - [ProtoMember(11)] - public DoubleMinMaxState total_pnl; - [ProtoMember(12)] - public DoubleMinMaxState pnl_price; - - // [ProtoMember(13)] - // ProtoMember 13 cannot be used further - [ProtoMember(14)] - public SecurityType[] security_types; - [ProtoMember(15)] - public bool[] has_day_trades; - } - - // migration rules - [Export(typeof(IPAndLGridSettingsMigrationRule))] - class AddMissingColumnsMigrationRule : IPAndLGridSettingsMigrationRule { - public bool apply(GridSettings settings, out GridSettings new_settings) => - settings.add_missing_columns(PAndLStartupData.DefaultGridSettings.columns, out new_settings); - } - } -} diff --git a/src/client/spark/Modules/Trading/TradingShellModule.cs b/src/client/spark/Modules/Trading/TradingShellModule.cs index d6cf9a120..df6c543ae 100644 --- a/src/client/spark/Modules/Trading/TradingShellModule.cs +++ b/src/client/spark/Modules/Trading/TradingShellModule.cs @@ -21,12 +21,10 @@ using static mbts.ui.shell.ProtoBufSerializationHelper; namespace bts.shell { [Export(typeof(IShellModule))] class TradingShellModule : IShellModule { - readonly PNLConfig _pnl_conf; // window factories readonly LadderWindowFactory _lwf; readonly OrderBookWindowFactory _obwf; readonly FillsWindowFactory _fwf; - readonly PAndLWindowFactory _old_plwf; readonly PNLWindowFactory _plwf; readonly AlgoStudioWindowFactory _aswf; readonly ManualFillsWindowFactory _mfwf; @@ -50,11 +48,7 @@ namespace bts.shell { _lwf = new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, mbo); _obwf = new OrderBookWindowFactory(this, bus, notification_service, notification_service_data_cache, orders_model, settings_hub); _fwf = new FillsWindowFactory(this, bus, settings_hub, orders_model); - _pnl_conf = new PNLConfig(mbts.config.Configuration.get()); - if (_pnl_conf.show_new_pnl) - _plwf = new PNLWindowFactory(this, bus, settings_hub, orders_model, position_model); - if (_pnl_conf.show_old_pnl) - _old_plwf = new PAndLWindowFactory(this, bus, settings_hub, orders_model); + _plwf = new PNLWindowFactory(this, bus, settings_hub, orders_model, position_model); _aswf = new AlgoStudioWindowFactory(this, bus, orders_model, error_reporter); _mfwf = new ManualFillsWindowFactory(this, bus, orders_model); } @@ -65,37 +59,22 @@ namespace bts.shell { public int priority => 20; - public IEnumerable actions { - get { - if (_actions == null) { - _actions = new List { - SparkCommands.ShowOrders.complete(() => bts.shell.orderbook.OrderBookStartupData.Default), - SparkCommands.ShowFills(null).complete(() => new FillsSettings()), - }; - if (_pnl_conf.show_new_pnl) - _actions.Add(SparkCommands.ShowPNL.complete(() => null)); - if (_pnl_conf.show_old_pnl) - _actions.Add(SparkCommands.ShowPAndL.complete(() => new PAndLWindowFactory.PAndLStartupData())); - _actions.AddRange(new[] { - SparkCommands.PickLadder, - SparkCommands.PickOrderTicket, - SparkCommands.ShowAlgoStudio.complete(() => new AlgoStudioWindowFactory.StartupData()), - SparkCommands.ShowManualFills().complete(() => ManualFillsSettings.Default) - }); - } - return _actions; - } - } + public IEnumerable actions => _actions ??= new() { + SparkCommands.ShowOrders.complete(() => orderbook.OrderBookStartupData.Default), + SparkCommands.ShowFills(null).complete(() => new FillsSettings()), + SparkCommands.ShowPNL.complete(() => null), + SparkCommands.PickLadder, + SparkCommands.PickOrderTicket, + SparkCommands.ShowAlgoStudio.complete(() => new AlgoStudioWindowFactory.StartupData()), + SparkCommands.ShowManualFills().complete(() => ManualFillsSettings.Default) + }; IEnumerable _window_factories { get { yield return _lwf; yield return _obwf; yield return _fwf; - if (_plwf != null) - yield return _plwf; - if (_old_plwf != null) - yield return _old_plwf; + yield return _plwf; yield return _aswf; yield return _mfwf; } @@ -111,16 +90,5 @@ namespace bts.shell { } _window_factories.DisposeAll(); } - - readonly struct PNLConfig { - public readonly bool - show_new_pnl, - show_old_pnl; - - public PNLConfig(bts.config.PNLOptions options) { - show_new_pnl = options.show_new_pnl; - show_old_pnl = options.show_old_pnl; - } - } } } diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index ab2637b34..c5ee84c5d 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -1,160 +1,157 @@ -using bts.api; -using bts.api.orderman; -using bts.shell; -using bts.shell.fills; -using bts.shell.manual_fills; - -using mbts; -using mbts.spark; -using mbts.ui; - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Windows.Input; - -namespace bts.spark { - static class SparkCommands { - // Market - public static PartialCommand ShowMarketView => - SparkCommand.create("Market View", Icons.Sheets, SparkTags.ShowMarketViewTag); - public static SparkCommand PickMarketView => - SparkCommand.create("Market View", Icons.Sheets, SparkTags.ShowPickMultiple, ShowMarketView); - - public static PartialCommand ShowTimeAndSales => - SparkCommand.create("Time and Sales", Icons.Clock, SparkTags.ShowTimeAndSalesTag); - public static SparkCommand PickTimeAndSales => - SparkCommand.create("Time and Sales", Icons.Clock, SparkTags.ShowPickMultiple, ShowTimeAndSales); - - // Trading - public static PartialCommand ShowOrders => - SparkCommand.create("Order Book", Icons.Book, SparkTags.ShowOrderBookTag); - - // Fills - public static PartialCommand ShowFills(KeyGesture key_gesture = null) => - SparkCommand.create("Fills", Icons.Payment, SparkTags.ShowFillsTag, key_gesture); - - public static PartialCommand ShowManualFills(KeyGesture key_gesture = null) => - SparkCommand.create("Manual Fills", Icons.DataEdit, SparkTags.ShowManualFillsTag, key_gesture); - - public static PartialCommand ShowPAndL => - SparkCommand.create("P&L (1.0)", Icons.Accounting, SparkTags.ShowPAndLTag); - - public static PartialCommand ShowPNL => - SparkCommand.create("P&L (2.0)", Icons.Accounting, SparkTags.ShowPNLTag); - - // Ladder - public static PartialCommand> ShowLadderAutoLookup(KeyGesture key_gesture = null) => - SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderAutoLookupTag, key_gesture); - - public static PartialCommand ShowLadder(KeyGesture key_gesture = null) => - SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderTag, key_gesture); - - public static PartialCommand> ShowLadders(KeyGesture key_gesture = null) => - SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLaddersTag, key_gesture); - - public static PartialCommand> ShowLinkedLadder => - SparkCommand.create("Linked Ladder", Icons.Ladder, SparkTags.ShowLinkedLadder); - public static SparkCommand PickLadder => - SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowPickOne, ShowLadder()); - - // Order Ticket - public static PartialCommand> ShowOrderTicketAutoLookup(KeyGesture key_gesture = null) => - SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketAutoLookupTag, key_gesture); - - public static PartialCommand<(OrderDefinitionImmutable def, double price, uint size)> ShowOrderTicket(KeyGesture key_gesture = null) => - SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketTag, key_gesture); - - public static PartialCommand ShowOrderTicketFromSecurity(KeyGesture key_gesture = null) => - SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketFromSecurityTag, key_gesture); - - public static SparkCommand PickOrderTicket => - SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowPickOne, ShowOrderTicketFromSecurity()); - - // Algo Studio - public static PartialCommand ShowAlgoStudio => - SparkCommand.create(AlgoStudioWindow.NAME, Icons.Tetris, SparkTags.ShowAlgoStudioTag); - - // Spreader - public static PartialCommand ShowSyntheticCreate(KeyGesture key_gesture = null) => - SparkCommand.create("Create Synthetic", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag, key_gesture); - - public static SparkCommand PickSyntheticCreate => - SparkCommand.create("Create Synthetic", Icons.AddSynthetic, SparkTags.ShowPickMultiple, ShowSyntheticCreate()); - - public static PartialCommand ShowSyntheticStrategy => - SparkCommand.create("Execution Strategy", Icons.Knight, SparkTags.ShowSyntheticStrategyTag); - - public static SparkCommand ShowSyntheticManagement => - SparkCommand.create("Synthetics", Icons.Synthetics, SparkTags.ShowSyntheticManagementTag); - - public static SparkCommand ShowLatencyReport => - SparkCommand.create("Latency Report", Icons.Analytics, SparkTags.NotImplemented); - - // Settings - public static SparkCommand ShowWorkspaces => - SparkCommand.create("Workspaces", Icons.FavoriteWindow, SparkTags.ShowWorkspaces); - public static SparkCommand ShowSettings => - SparkCommand.create("Settings", Icons.Admin, SparkTags.ShowSettings); - - // Support - public static SparkCommand ShowManual => - SparkCommand.create("Manual", Icons.Browser, SparkTags.ShowUri, new Uri("https://www.bluetradingsystems.com/documentation/")); - - public static SparkCommand ShowReleaseNotes => - SparkCommand.create("Release Notes", Icons.Browser, SparkTags.ShowUri, new Uri("bts://docs/release_notes/")); - - public static SparkCommand DoNothing => - SparkCommand.create("Nothing", Icons.Support, SparkTags.NotImplemented); - - public static SparkCommand ShowAuditLogs => - SparkCommand.create("Audit Logs", Icons.Book, SparkTags.NotImplemented); - - public static SparkCommand ShowDiagnostics => - SparkCommand.create("Diagnostics", Icons.Target, SparkTags.NotImplemented); - - public static SparkCommand ShowAboutSpark => - SparkCommand.create("About Spark", Icons.Support, SparkTags.About); - - public static SparkCommand ShowActivityLog => - SparkCommand.create("Activity Log", Icons.Wrench, SparkTags.ShowActivityLog); - - public static SparkCommand ShowGlobalAlerts => - SparkCommand.create("Alerts", Icons.Speaker, SparkTags.ShowGlobalAlertsTag); - - public static PartialCommand ShowReportIssue => - SparkCommand.create("Report a Problem", Icons.Support, SparkTags.Support); - - // Orders - public static PartialCommand> CancelSelectedOrders => - SparkCommand.create("Cancel Selected", Icons.CancelSelected, SparkTags.CancelOrders); - public static PartialCommand> CancelOrders => - SparkCommand.create("Cancel All", Icons.CancelOrders, SparkTags.CancelOrders); - public static PartialCommand> CancelBuyOrders => - SparkCommand.create("Cancel Buys", Icons.CancelBuys, SparkTags.CancelOrders); - public static PartialCommand> CancelSellOrders => - SparkCommand.create("Cancel Sells", Icons.CancelSells, SparkTags.CancelOrders); - public static PartialCommand ShowModifyOrder => - SparkCommand.create("Modify", Icons.ModifyOrder, SparkTags.ShowModifyOrderTag); - public static PartialCommand> RecreateSelectedOrders => - SparkCommand.create("Recreate", Icons.Beaker, SparkTags.RecreateOrder); - - // TODO: remove this method, eventually want all windows to use window_settings_command() - public static SparkCommand change_securities_command(Func<(PartialCommand, SecurityCriteria)> get_param) => - SparkCommand.create("Securities", Icons.HandPointingOverDocument, SparkTags.ShowAndEditPickMultiple, get_param); - - public static PartialCommand change_securities_callback(string window_name) => - SparkCommand.create(window_name, Icons.HandPointingOverDocument, new SparkTags.SparkTag($"Change {window_name} securities callback")); - - public static SparkCommand window_settings_command(IDialogCommand launch_settings_editor) => - new SparkCommandWrapper("Settings", Icons.Admin, launch_settings_editor); - - public static class KeyGestures { - public static readonly KeyGesture - ShowFills = new KeyGesture(Key.F, ModifierKeys.Control | ModifierKeys.Shift), - ShowLadder = new KeyGesture(Key.L, ModifierKeys.Control), - ShowOrderTicket = new KeyGesture(Key.T, ModifierKeys.Control), - ShowSyntheticCreate = new KeyGesture(Key.R, ModifierKeys.Control); - } - } -} +using bts.api; +using bts.api.orderman; +using bts.shell; +using bts.shell.fills; +using bts.shell.manual_fills; + +using mbts; +using mbts.spark; +using mbts.ui; + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Windows.Input; + +namespace bts.spark { + static class SparkCommands { + // Market + public static PartialCommand ShowMarketView => + SparkCommand.create("Market View", Icons.Sheets, SparkTags.ShowMarketViewTag); + public static SparkCommand PickMarketView => + SparkCommand.create("Market View", Icons.Sheets, SparkTags.ShowPickMultiple, ShowMarketView); + + public static PartialCommand ShowTimeAndSales => + SparkCommand.create("Time and Sales", Icons.Clock, SparkTags.ShowTimeAndSalesTag); + public static SparkCommand PickTimeAndSales => + SparkCommand.create("Time and Sales", Icons.Clock, SparkTags.ShowPickMultiple, ShowTimeAndSales); + + // Trading + public static PartialCommand ShowOrders => + SparkCommand.create("Order Book", Icons.Book, SparkTags.ShowOrderBookTag); + + // Fills + public static PartialCommand ShowFills(KeyGesture key_gesture = null) => + SparkCommand.create("Fills", Icons.Payment, SparkTags.ShowFillsTag, key_gesture); + + public static PartialCommand ShowManualFills(KeyGesture key_gesture = null) => + SparkCommand.create("Manual Fills", Icons.DataEdit, SparkTags.ShowManualFillsTag, key_gesture); + + public static PartialCommand ShowPNL => + SparkCommand.create("P&L (2.0)", Icons.Accounting, SparkTags.ShowPNLTag); + + // Ladder + public static PartialCommand> ShowLadderAutoLookup(KeyGesture key_gesture = null) => + SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderAutoLookupTag, key_gesture); + + public static PartialCommand ShowLadder(KeyGesture key_gesture = null) => + SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderTag, key_gesture); + + public static PartialCommand> ShowLadders(KeyGesture key_gesture = null) => + SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLaddersTag, key_gesture); + + public static PartialCommand> ShowLinkedLadder => + SparkCommand.create("Linked Ladder", Icons.Ladder, SparkTags.ShowLinkedLadder); + public static SparkCommand PickLadder => + SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowPickOne, ShowLadder()); + + // Order Ticket + public static PartialCommand> ShowOrderTicketAutoLookup(KeyGesture key_gesture = null) => + SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketAutoLookupTag, key_gesture); + + public static PartialCommand<(OrderDefinitionImmutable def, double price, uint size)> ShowOrderTicket(KeyGesture key_gesture = null) => + SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketTag, key_gesture); + + public static PartialCommand ShowOrderTicketFromSecurity(KeyGesture key_gesture = null) => + SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketFromSecurityTag, key_gesture); + + public static SparkCommand PickOrderTicket => + SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowPickOne, ShowOrderTicketFromSecurity()); + + // Algo Studio + public static PartialCommand ShowAlgoStudio => + SparkCommand.create(AlgoStudioWindow.NAME, Icons.Tetris, SparkTags.ShowAlgoStudioTag); + + // Spreader + public static PartialCommand ShowSyntheticCreate(KeyGesture key_gesture = null) => + SparkCommand.create("Create Synthetic", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag, key_gesture); + + public static SparkCommand PickSyntheticCreate => + SparkCommand.create("Create Synthetic", Icons.AddSynthetic, SparkTags.ShowPickMultiple, ShowSyntheticCreate()); + + public static PartialCommand ShowSyntheticStrategy => + SparkCommand.create("Execution Strategy", Icons.Knight, SparkTags.ShowSyntheticStrategyTag); + + public static SparkCommand ShowSyntheticManagement => + SparkCommand.create("Synthetics", Icons.Synthetics, SparkTags.ShowSyntheticManagementTag); + + public static SparkCommand ShowLatencyReport => + SparkCommand.create("Latency Report", Icons.Analytics, SparkTags.NotImplemented); + + // Settings + public static SparkCommand ShowWorkspaces => + SparkCommand.create("Workspaces", Icons.FavoriteWindow, SparkTags.ShowWorkspaces); + public static SparkCommand ShowSettings => + SparkCommand.create("Settings", Icons.Admin, SparkTags.ShowSettings); + + // Support + public static SparkCommand ShowManual => + SparkCommand.create("Manual", Icons.Browser, SparkTags.ShowUri, new Uri("https://www.bluetradingsystems.com/documentation/")); + + public static SparkCommand ShowReleaseNotes => + SparkCommand.create("Release Notes", Icons.Browser, SparkTags.ShowUri, new Uri("bts://docs/release_notes/")); + + public static SparkCommand DoNothing => + SparkCommand.create("Nothing", Icons.Support, SparkTags.NotImplemented); + + public static SparkCommand ShowAuditLogs => + SparkCommand.create("Audit Logs", Icons.Book, SparkTags.NotImplemented); + + public static SparkCommand ShowDiagnostics => + SparkCommand.create("Diagnostics", Icons.Target, SparkTags.NotImplemented); + + public static SparkCommand ShowAboutSpark => + SparkCommand.create("About Spark", Icons.Support, SparkTags.About); + + public static SparkCommand ShowActivityLog => + SparkCommand.create("Activity Log", Icons.Wrench, SparkTags.ShowActivityLog); + + public static SparkCommand ShowGlobalAlerts => + SparkCommand.create("Alerts", Icons.Speaker, SparkTags.ShowGlobalAlertsTag); + + public static PartialCommand ShowReportIssue => + SparkCommand.create("Report a Problem", Icons.Support, SparkTags.Support); + + // Orders + public static PartialCommand> CancelSelectedOrders => + SparkCommand.create("Cancel Selected", Icons.CancelSelected, SparkTags.CancelOrders); + public static PartialCommand> CancelOrders => + SparkCommand.create("Cancel All", Icons.CancelOrders, SparkTags.CancelOrders); + public static PartialCommand> CancelBuyOrders => + SparkCommand.create("Cancel Buys", Icons.CancelBuys, SparkTags.CancelOrders); + public static PartialCommand> CancelSellOrders => + SparkCommand.create("Cancel Sells", Icons.CancelSells, SparkTags.CancelOrders); + public static PartialCommand ShowModifyOrder => + SparkCommand.create("Modify", Icons.ModifyOrder, SparkTags.ShowModifyOrderTag); + public static PartialCommand> RecreateSelectedOrders => + SparkCommand.create("Recreate", Icons.Beaker, SparkTags.RecreateOrder); + + // TODO: remove this method, eventually want all windows to use window_settings_command() + public static SparkCommand change_securities_command(Func<(PartialCommand, SecurityCriteria)> get_param) => + SparkCommand.create("Securities", Icons.HandPointingOverDocument, SparkTags.ShowAndEditPickMultiple, get_param); + + public static PartialCommand change_securities_callback(string window_name) => + SparkCommand.create(window_name, Icons.HandPointingOverDocument, new SparkTags.SparkTag($"Change {window_name} securities callback")); + + public static SparkCommand window_settings_command(IDialogCommand launch_settings_editor) => + new SparkCommandWrapper("Settings", Icons.Admin, launch_settings_editor); + + public static class KeyGestures { + public static readonly KeyGesture + ShowFills = new KeyGesture(Key.F, ModifierKeys.Control | ModifierKeys.Shift), + ShowLadder = new KeyGesture(Key.L, ModifierKeys.Control), + ShowOrderTicket = new KeyGesture(Key.T, ModifierKeys.Control), + ShowSyntheticCreate = new KeyGesture(Key.R, ModifierKeys.Control); + } + } +} diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index 11797f9b2..571e25b47 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -1,339 +1,338 @@ -using bts.api; -using bts.api.orderman; -using bts.shell; -using bts.shell.fills; -using bts.shell.manual_fills; -using bts.spark; - -using mbts.ui; -using mbts.ui.controls; - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Threading.Tasks; -using bts.api.analytics; -using mbts.analytics; -using mbts.ui.converters; -using mbts.spark.filters; -using System.Diagnostics; - -namespace mbts.spark { - - static class SparkTags { - #region Core Data - public static ITag> SecuritiesTag { get; } = - new SparkTag>("Securities"); - public static ITag> ServerSecuritiesTag { get; } = - new SparkTag>("ServerSecurities"); - public static ITag> FakeSecuritiesTag { get; } = - new SparkTag>("FakeSecurities"); - public static ITag> SyntheticstrategiesTag { get; } = new SparkTag>("SyntheticSecuritiesTag"); - #endregion - - #region Order - public static ITag> RecreateOrder { get; } = new SparkTag>(); - - public static ITag> CancelOrders { get; } = new SparkTag>(); - public static ITag> DetachOrders { get; } = new SparkTag>(); - public static ITag<(uint key, double price, uint size)> UpdateOrder { get; } = new SparkTag<(uint, double, uint)>(); - - public static ITag ShowModifyOrderTag { get; } = new SparkTag(nameof(ShowModifyOrderTag)); - public static ITag> ShowOrderTicketAutoLookupTag { get; } = new SparkTag>(nameof(ShowOrderTicketAutoLookupTag)); - public static ITag ShowOrderTicketFromSecurityTag = new SparkTag(nameof(ShowOrderTicketFromSecurityTag)); - public static ITag<(OrderDefinitionImmutable def, double price, uint size)> ShowOrderTicketTag = new SparkTag<(OrderDefinitionImmutable def, double price, uint size)>(nameof(ShowOrderTicketTag)); - #endregion - - #region Selection/Utility - public static ITag<(PartialCommand, SecurityCriteria)> ShowAndEditPickMultiple { get; } = new SparkTag<(PartialCommand, SecurityCriteria)>("EditPickN"); - public static ITag> ShowPickMultiple { get; } = new SparkTag>("PickN"); - public static ITag> ShowPickOne { get; } = new SparkTag>("Pick1"); - public static ITag<(PartialCommand, SecurityCriteria)> FilterPickOne { get; } = new SparkTag<(PartialCommand, SecurityCriteria)>("FilterPick1"); - - public static ITag ShowWindow { get; } = new SparkTag("Show Window"); - public static ITag> ShowWindowAsync { get; } = new SparkTag>("ShowWindowAsync"); - public static ITag ActivateWindow { get; } = new SparkTag("Activate Window"); - public static ITag ShowWorkspaces { get; } = new SparkTag(nameof(ShowWorkspaces)); - public static ITag ShowSettings { get; } = new SparkTag(nameof(ShowSettings)); - public static ITag ShowUri { get; } = new SparkTag("ShowUri"); - public static ITag Support { get; } = new SparkTag(nameof(Support)); - public static ITag About { get; } = new SparkTag("About"); - public static ITag ShowActivityLog { get; } = new SparkTag("Show Activity Log"); - public static ITag LogActivity { get; } = new SparkTag("Activity Log"); - - public static ITag NotImplemented { get; } = new SparkTag("Not Implemented"); - #endregion - - #region Spark Window - public static ITag ShowFillsTag { get; } = new SparkTag(nameof(ShowFillsTag)); - public static ITag ShowManualFillsTag { get; } = new SparkTag(nameof(ShowManualFillsTag)); - // TODO: maybe get rid of the singlular ShowLadderTag, and just use the plural ShowLaddersTag. - // The owners of the various SparkWindows may remove dependencies on the former at their leasure. - // For now, both tags go through the same logic in the LadderWindowFactory anyways. - public static ITag ShowLadderTag { get; } = new SparkTag("Show Ladder"); - // TODO: get rid of the SecurityMD ShowLadderTag. This has created burdensome dependency issues. - public static ITag> ShowLadderAutoLookupTag { get; } = new SparkTag>("Show Ladder Auto Lookup"); - public static ITag> ShowLaddersTag { get; } = new SparkTag>(nameof(ShowLaddersTag)); - public static ITag> ShowLinkedLadder { get; } = new SparkTag>("Linked Ladder"); - public static ITag ShowMarketViewTag { get; } = new SparkTag("Show MarketView"); - public static ITag ShowOrderBookTag { get; } = new SparkTag(nameof(ShowOrderBookTag)); - public static ITag ShowPAndLTag { get; } = new SparkTag(nameof(ShowPAndLTag)); - public static ITag ShowPNLTag { get; } = new SparkTag(nameof(ShowPNLTag)); - public static ITag<(SecurityImmutable security, ExecutionStrategyImmutable strategy)> ShowSyntheticCloneTag { get; } = new SparkTag<(SecurityImmutable security, ExecutionStrategyImmutable strategy)>(nameof(ShowSyntheticCloneTag)); - public static ITag ShowSyntheticCreateTag { get; } = new SparkTag(nameof(ShowSyntheticCreateTag)); - public static ITag ShowSyntheticStrategyTag { get; } = new SparkTag(nameof(ShowSyntheticStrategyTag)); - public static ITag ShowSyntheticManagementTag { get; } = new SparkTag(nameof(ShowSyntheticManagementTag)); - public static ITag ShowTimeAndSalesTag { get; } = new SparkTag("Show TimeAndSales"); - public static ITag ShowAlgoStudioTag { get; } = new SparkTag($"Show {AlgoStudioWindow.NAME}"); - #endregion - - #region Ladder - public static ITag RequestRecenterLadder { get; } = new SparkTag(nameof(RequestRecenterLadder)); - public static ITag RecenterLadderBegin { get; } = new SparkTag(nameof(RecenterLadderBegin)); - public static ITag RecenterLadderNow { get; } = new SparkTag(nameof(RecenterLadderNow)); - - #endregion - - #region AW2 - // Publisher : VolSurfaceBlackboardManager - public static ITag - VolSurfaceNonVolInputTag { get; } = new SparkTag("VolSurfaceNonVolInputTag"); - // Publisher : SingleVolSurfaceNonVolDataSource - public static ITag VolSurfaceNonVolDataTag(int vs_id) { - return new KeyedSparkTag(vs_id); - } - // Publisher: SingleVolSurfaceNonVolDataSource - public static ITag VolSurfaceContractsTag(int vs_id) { - return new KeyedSparkTag(vs_id); - } - // Publisher: VolSurfaceVM - public static ITag CreateHeatmapTag { get; } = new SparkTag("CreateHeatmapTag"); - - // Publisher: VolSurfaceBlackboardManager - // User: VoLSurfaceModule - public static ITag> VolSurfaceListTag { get; } = - new SparkTag>("VolSurfaceListTag"); - - // Publisher: VolSurfaceShellModuleContentVM - public static ITag VolSurfaceCreateTag { get; } = - new SparkTag("VolSurfaceCreateTag"); - - // Publisher: VolSurfaceShellModuleContentVM - public static ITag VolSurfaceDeleteTag { get; } = new SparkTag("VolSurfaceDeleteTag"); - - // Publisher : VolSurfaceDisplayModel - public static ITag VolSurfaceLaunchTheoWindowTag { get; } = new SparkTag("VolSurfaceLaunchTheoWindowTag"); - - // Publisher : VoLSurfaceTheoShellControl - // Data : true/false saying its visible or not - public static ITag VolSurfaceTheoWindowStateTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceTheoWindowStateTag"); - } - - // Publisher: VolSurfaceDisplayModel - public static ITag VolSurfaceActivationTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceActivationTag"); - } - - // Publisher: VolSurfaceDisplayModel - // Data: True/False - public static ITag VolSurfaceDirtyStateTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceDirtyStateTag"); - } - - // Publisher : VolSurfaceDisplayModel - // Data : VolSurfaceCalculationRequest - public static ITag VolSurfaceCalculationRequestTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceCalculationRequestTag"); - } - - // Publisher : SingleVolSurfaceRequestCalculator - // Data : VolSurfaceCalculationResponse - public static ITag VolSurfaceCalculationResponseTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceCalculationResponseTag"); - } - - // When the UI intends to save the vol surface (data or input) - // Publisher: VolSurfaceDisplayModel - public static ITag VolSurfaceCommitTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceCommitTag"); - } - - // Publisher: SingleVolSurfaceGateway - // Data: mbts.analytics.VolSurfaceInput - public static ITag VolSurfaceCommittedInputTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceCommittedInputTag"); - } - - // Publisher: SingleVolSurfaceGateway - // Data: IEnumeration of VolSurfaceSnapshot (ui side object that encaps byte[], - // along side of id, transaction_id etc) - public static ITag> VolSurfaceInputSnapshotListTag(int vs_id) { - return new KeyedSparkTag, int>(vs_id, "VolSurfaceInputSnapshotListTag"); - } - - // Publisher: SingleVolSurfaceCommittedOutputRetriever - // Data: mbts.analytics.VolSurfaceOutput - public static ITag VolSurfaceCommittedOutputTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceCommittedOutputTag"); - } - - // Publisher : SingleVolSurfaceTheoSource - // Data : VolSurfaceTheoData (contracts, committed theos, cand theos) - public static ITag VolSurfaceTheoOutputTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceTheoOutputTag"); - } - - // Publisher: SingleVolSurfaceOptionDriverSource - // Data: Dictionary (these are option expirations to driver mid point) - public static ITag> VolSurfaceOptionDriverTag(int vs_id) { - return new KeyedSparkTag, int>(vs_id, "VolSurfaceOptionDriverTag"); - } - - // This is the tag for the market price of all driver - // symbols, ex the market price for all ES future - // expirations - // Publisher: SingleVolSurfaceOptionDriverSource - // Data: Dictionary - public static ITag> VolSurfaceDriverSymbolPriceTag(int vs_id) { - return new KeyedSparkTag, int>(vs_id, "VolSurfaceDriverSymbolPriceTag"); - } - - // Publisher: SingleVolSurfaceMarketImpliedVolSource - // Data: Dictionary> - public static ITag>> VolSurfaceMarketImpliedVolTag(int vs_id) { - return new KeyedSparkTag>, int>(vs_id, "VolSurfaceMarketImpliedVolTag"); - } - - // Publisher : VolSurfaceDisplayModel - // Data : VolSurfaceMacroGridSettings - public static ITag VolSurfaceMacroGridSettingsTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceMacroGridSettingsTag"); - } - - // Publisher : VolSurfaceDisplayModel - // Data : Tuple - // - bool indicates whether or not Show Implied Vol is checked - public static ITag> VolSurfaceGridSelectionTag(int vs_id) { - return new KeyedSparkTag, int>(vs_id, "VolSurfaceGridSelectionTag"); - } - - // Publisher : VolSurfaceDisplayModel - // Data : VolSurfaceEnum.MarketSide - public static ITag VolSurfaceMarketImpliedVolSide(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceMarketImpliedVolSide"); - } - - // Publisher : VolSurfaceDisplayModel - // Data : bool - public static ITag VolSurfaceIgnoreImpliedVolSettingsTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceIgnoreImpliedVolSettingsTag"); - } - - // List of symbol to volsurface mapping. - // Publisher: VolSurfaceBlackboardManager - public static ITag VolSurfaceUsageTag { get; } = - new SparkTag("VolSurfaceUsage"); - - // The AW2 machinary can compute and publish the theos - // right back locally(vs the server doing that) if configured that way. - // Publisher: SingleVolSurfaceClientTheosPublishHelper - // Data: IDictionary> - public static ITag>> VolSurfaceLocalTheosTag(int vs_id) { - return new KeyedSparkTag>, int>(vs_id, "VolSurfaceLocalTheosTag"); - } - - /// This is the periodic time sent out by the server - // Publisher: SingleVolSurfaceTimeSource - // Data: mbts.analytics.VolSurfaceStandardTime - public static ITag VolSurfaceStandardTimeTag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceStandardTimeTag"); - } - - // Publisher: VolSurfaceDisplayModel - // Data: Bool - public static ITag VolSurfaceActiveUITag(int vs_id) { - return new KeyedSparkTag(vs_id, "VolSurfaceActiveUITag"); - } - - // Publisher: SingleVolSurfaceClientTheosPublishHelper - // Data: VolSurfaceTheoAlertData - public static ITag VolSurfaceTheoAlertTag { get; } = - new SparkTag("VolSurfaceTheoAlertTag"); - - // Publisher: NMSheetControl - // Data: string - public static ITag VolSurfaceTheoAcceptanceConfirmationTag { get; } = - new SparkTag("VolSurfaceTheoAcceptanceConfirmationTag"); - - public static ITag AquireTag(string key) { - return new KeyedSparkTag(key, "AquireTag"); - } - - public static ITag SystemContractsTag { get; } = - new SparkTag("SystemContractsTag"); - - public static ITag OptionDriverBBOTag(string option_symbol) { - return new KeyedSparkTag(option_symbol, "OptionDriverBBOTag"); - } - - public static ITag OptionDriverSymbolBBOTag(string key) { - return new KeyedSparkTag(key, "OptionDriverSymbolBBOTag"); - } - - public static ITag ExpirationParametersInputTag { get; } = - new SparkTag( - "AnalyticsExpirationParametersMap"); - - public static ITag PrecomputedOptionTheoTag(string symbol) { - return new KeyedSparkTag(symbol, "PrecomputedOptionTheoTag"); - } - - public static ITag> ExpirationParametersCommitTag { get; } = - new SparkTag>( - "ExpirationParametersCommitTag"); - - public static ITag MessageDisplayTag { get; } = - new SparkTag("MessageDisplayTag"); - - public static ITag VolSurfaceLaunchTheoWindow { get; } = - new SparkTag("VolSurfaceLaunchTheoWindow"); - - public static ITag SparkTimer { get; } = - new SparkTag("SparkTimer"); - - #endregion - - public static ITag> SyntheticDeleteTag { get; } = new SparkTag>(nameof(SyntheticDeleteTag)); - - public static ITag ShowGlobalAlertsTag { get; } = new SparkTag(nameof(ShowGlobalAlertsTag)); - - public class Nothing { Nothing() { } } - - internal class SparkTag : ITag { - readonly string Name; - public SparkTag(string name = "") => Name = name; - public override string ToString() => Name; - } - - internal class KeyedSparkTag : ITag { - internal readonly TKey Key; - internal readonly string Name; - public KeyedSparkTag(TKey key, string name = "") { - Name = name; - Key = key; - } - public override string ToString() { - return Name + "_" + Key; - } - public override int GetHashCode() { - return ToString().GetHashCode(); - } - public override bool Equals(object obj) { - return obj != null && GetType() == obj.GetType() && - GetHashCode() == obj.GetHashCode(); - } - - } - } -} +using bts.api; +using bts.api.orderman; +using bts.shell; +using bts.shell.fills; +using bts.shell.manual_fills; +using bts.spark; + +using mbts.ui; +using mbts.ui.controls; + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Threading.Tasks; +using bts.api.analytics; +using mbts.analytics; +using mbts.ui.converters; +using mbts.spark.filters; +using System.Diagnostics; + +namespace mbts.spark { + + static class SparkTags { + #region Core Data + public static ITag> SecuritiesTag { get; } = + new SparkTag>("Securities"); + public static ITag> ServerSecuritiesTag { get; } = + new SparkTag>("ServerSecurities"); + public static ITag> FakeSecuritiesTag { get; } = + new SparkTag>("FakeSecurities"); + public static ITag> SyntheticstrategiesTag { get; } = new SparkTag>("SyntheticSecuritiesTag"); + #endregion + + #region Order + public static ITag> RecreateOrder { get; } = new SparkTag>(); + + public static ITag> CancelOrders { get; } = new SparkTag>(); + public static ITag> DetachOrders { get; } = new SparkTag>(); + public static ITag<(uint key, double price, uint size)> UpdateOrder { get; } = new SparkTag<(uint, double, uint)>(); + + public static ITag ShowModifyOrderTag { get; } = new SparkTag(nameof(ShowModifyOrderTag)); + public static ITag> ShowOrderTicketAutoLookupTag { get; } = new SparkTag>(nameof(ShowOrderTicketAutoLookupTag)); + public static ITag ShowOrderTicketFromSecurityTag = new SparkTag(nameof(ShowOrderTicketFromSecurityTag)); + public static ITag<(OrderDefinitionImmutable def, double price, uint size)> ShowOrderTicketTag = new SparkTag<(OrderDefinitionImmutable def, double price, uint size)>(nameof(ShowOrderTicketTag)); + #endregion + + #region Selection/Utility + public static ITag<(PartialCommand, SecurityCriteria)> ShowAndEditPickMultiple { get; } = new SparkTag<(PartialCommand, SecurityCriteria)>("EditPickN"); + public static ITag> ShowPickMultiple { get; } = new SparkTag>("PickN"); + public static ITag> ShowPickOne { get; } = new SparkTag>("Pick1"); + public static ITag<(PartialCommand, SecurityCriteria)> FilterPickOne { get; } = new SparkTag<(PartialCommand, SecurityCriteria)>("FilterPick1"); + + public static ITag ShowWindow { get; } = new SparkTag("Show Window"); + public static ITag> ShowWindowAsync { get; } = new SparkTag>("ShowWindowAsync"); + public static ITag ActivateWindow { get; } = new SparkTag("Activate Window"); + public static ITag ShowWorkspaces { get; } = new SparkTag(nameof(ShowWorkspaces)); + public static ITag ShowSettings { get; } = new SparkTag(nameof(ShowSettings)); + public static ITag ShowUri { get; } = new SparkTag("ShowUri"); + public static ITag Support { get; } = new SparkTag(nameof(Support)); + public static ITag About { get; } = new SparkTag("About"); + public static ITag ShowActivityLog { get; } = new SparkTag("Show Activity Log"); + public static ITag LogActivity { get; } = new SparkTag("Activity Log"); + + public static ITag NotImplemented { get; } = new SparkTag("Not Implemented"); + #endregion + + #region Spark Window + public static ITag ShowFillsTag { get; } = new SparkTag(nameof(ShowFillsTag)); + public static ITag ShowManualFillsTag { get; } = new SparkTag(nameof(ShowManualFillsTag)); + // TODO: maybe get rid of the singlular ShowLadderTag, and just use the plural ShowLaddersTag. + // The owners of the various SparkWindows may remove dependencies on the former at their leasure. + // For now, both tags go through the same logic in the LadderWindowFactory anyways. + public static ITag ShowLadderTag { get; } = new SparkTag("Show Ladder"); + // TODO: get rid of the SecurityMD ShowLadderTag. This has created burdensome dependency issues. + public static ITag> ShowLadderAutoLookupTag { get; } = new SparkTag>("Show Ladder Auto Lookup"); + public static ITag> ShowLaddersTag { get; } = new SparkTag>(nameof(ShowLaddersTag)); + public static ITag> ShowLinkedLadder { get; } = new SparkTag>("Linked Ladder"); + public static ITag ShowMarketViewTag { get; } = new SparkTag("Show MarketView"); + public static ITag ShowOrderBookTag { get; } = new SparkTag(nameof(ShowOrderBookTag)); + public static ITag ShowPNLTag { get; } = new SparkTag(nameof(ShowPNLTag)); + public static ITag<(SecurityImmutable security, ExecutionStrategyImmutable strategy)> ShowSyntheticCloneTag { get; } = new SparkTag<(SecurityImmutable security, ExecutionStrategyImmutable strategy)>(nameof(ShowSyntheticCloneTag)); + public static ITag ShowSyntheticCreateTag { get; } = new SparkTag(nameof(ShowSyntheticCreateTag)); + public static ITag ShowSyntheticStrategyTag { get; } = new SparkTag(nameof(ShowSyntheticStrategyTag)); + public static ITag ShowSyntheticManagementTag { get; } = new SparkTag(nameof(ShowSyntheticManagementTag)); + public static ITag ShowTimeAndSalesTag { get; } = new SparkTag("Show TimeAndSales"); + public static ITag ShowAlgoStudioTag { get; } = new SparkTag($"Show {AlgoStudioWindow.NAME}"); + #endregion + + #region Ladder + public static ITag RequestRecenterLadder { get; } = new SparkTag(nameof(RequestRecenterLadder)); + public static ITag RecenterLadderBegin { get; } = new SparkTag(nameof(RecenterLadderBegin)); + public static ITag RecenterLadderNow { get; } = new SparkTag(nameof(RecenterLadderNow)); + + #endregion + + #region AW2 + // Publisher : VolSurfaceBlackboardManager + public static ITag + VolSurfaceNonVolInputTag { get; } = new SparkTag("VolSurfaceNonVolInputTag"); + // Publisher : SingleVolSurfaceNonVolDataSource + public static ITag VolSurfaceNonVolDataTag(int vs_id) { + return new KeyedSparkTag(vs_id); + } + // Publisher: SingleVolSurfaceNonVolDataSource + public static ITag VolSurfaceContractsTag(int vs_id) { + return new KeyedSparkTag(vs_id); + } + // Publisher: VolSurfaceVM + public static ITag CreateHeatmapTag { get; } = new SparkTag("CreateHeatmapTag"); + + // Publisher: VolSurfaceBlackboardManager + // User: VoLSurfaceModule + public static ITag> VolSurfaceListTag { get; } = + new SparkTag>("VolSurfaceListTag"); + + // Publisher: VolSurfaceShellModuleContentVM + public static ITag VolSurfaceCreateTag { get; } = + new SparkTag("VolSurfaceCreateTag"); + + // Publisher: VolSurfaceShellModuleContentVM + public static ITag VolSurfaceDeleteTag { get; } = new SparkTag("VolSurfaceDeleteTag"); + + // Publisher : VolSurfaceDisplayModel + public static ITag VolSurfaceLaunchTheoWindowTag { get; } = new SparkTag("VolSurfaceLaunchTheoWindowTag"); + + // Publisher : VoLSurfaceTheoShellControl + // Data : true/false saying its visible or not + public static ITag VolSurfaceTheoWindowStateTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceTheoWindowStateTag"); + } + + // Publisher: VolSurfaceDisplayModel + public static ITag VolSurfaceActivationTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceActivationTag"); + } + + // Publisher: VolSurfaceDisplayModel + // Data: True/False + public static ITag VolSurfaceDirtyStateTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceDirtyStateTag"); + } + + // Publisher : VolSurfaceDisplayModel + // Data : VolSurfaceCalculationRequest + public static ITag VolSurfaceCalculationRequestTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceCalculationRequestTag"); + } + + // Publisher : SingleVolSurfaceRequestCalculator + // Data : VolSurfaceCalculationResponse + public static ITag VolSurfaceCalculationResponseTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceCalculationResponseTag"); + } + + // When the UI intends to save the vol surface (data or input) + // Publisher: VolSurfaceDisplayModel + public static ITag VolSurfaceCommitTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceCommitTag"); + } + + // Publisher: SingleVolSurfaceGateway + // Data: mbts.analytics.VolSurfaceInput + public static ITag VolSurfaceCommittedInputTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceCommittedInputTag"); + } + + // Publisher: SingleVolSurfaceGateway + // Data: IEnumeration of VolSurfaceSnapshot (ui side object that encaps byte[], + // along side of id, transaction_id etc) + public static ITag> VolSurfaceInputSnapshotListTag(int vs_id) { + return new KeyedSparkTag, int>(vs_id, "VolSurfaceInputSnapshotListTag"); + } + + // Publisher: SingleVolSurfaceCommittedOutputRetriever + // Data: mbts.analytics.VolSurfaceOutput + public static ITag VolSurfaceCommittedOutputTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceCommittedOutputTag"); + } + + // Publisher : SingleVolSurfaceTheoSource + // Data : VolSurfaceTheoData (contracts, committed theos, cand theos) + public static ITag VolSurfaceTheoOutputTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceTheoOutputTag"); + } + + // Publisher: SingleVolSurfaceOptionDriverSource + // Data: Dictionary (these are option expirations to driver mid point) + public static ITag> VolSurfaceOptionDriverTag(int vs_id) { + return new KeyedSparkTag, int>(vs_id, "VolSurfaceOptionDriverTag"); + } + + // This is the tag for the market price of all driver + // symbols, ex the market price for all ES future + // expirations + // Publisher: SingleVolSurfaceOptionDriverSource + // Data: Dictionary + public static ITag> VolSurfaceDriverSymbolPriceTag(int vs_id) { + return new KeyedSparkTag, int>(vs_id, "VolSurfaceDriverSymbolPriceTag"); + } + + // Publisher: SingleVolSurfaceMarketImpliedVolSource + // Data: Dictionary> + public static ITag>> VolSurfaceMarketImpliedVolTag(int vs_id) { + return new KeyedSparkTag>, int>(vs_id, "VolSurfaceMarketImpliedVolTag"); + } + + // Publisher : VolSurfaceDisplayModel + // Data : VolSurfaceMacroGridSettings + public static ITag VolSurfaceMacroGridSettingsTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceMacroGridSettingsTag"); + } + + // Publisher : VolSurfaceDisplayModel + // Data : Tuple + // - bool indicates whether or not Show Implied Vol is checked + public static ITag> VolSurfaceGridSelectionTag(int vs_id) { + return new KeyedSparkTag, int>(vs_id, "VolSurfaceGridSelectionTag"); + } + + // Publisher : VolSurfaceDisplayModel + // Data : VolSurfaceEnum.MarketSide + public static ITag VolSurfaceMarketImpliedVolSide(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceMarketImpliedVolSide"); + } + + // Publisher : VolSurfaceDisplayModel + // Data : bool + public static ITag VolSurfaceIgnoreImpliedVolSettingsTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceIgnoreImpliedVolSettingsTag"); + } + + // List of symbol to volsurface mapping. + // Publisher: VolSurfaceBlackboardManager + public static ITag VolSurfaceUsageTag { get; } = + new SparkTag("VolSurfaceUsage"); + + // The AW2 machinary can compute and publish the theos + // right back locally(vs the server doing that) if configured that way. + // Publisher: SingleVolSurfaceClientTheosPublishHelper + // Data: IDictionary> + public static ITag>> VolSurfaceLocalTheosTag(int vs_id) { + return new KeyedSparkTag>, int>(vs_id, "VolSurfaceLocalTheosTag"); + } + + /// This is the periodic time sent out by the server + // Publisher: SingleVolSurfaceTimeSource + // Data: mbts.analytics.VolSurfaceStandardTime + public static ITag VolSurfaceStandardTimeTag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceStandardTimeTag"); + } + + // Publisher: VolSurfaceDisplayModel + // Data: Bool + public static ITag VolSurfaceActiveUITag(int vs_id) { + return new KeyedSparkTag(vs_id, "VolSurfaceActiveUITag"); + } + + // Publisher: SingleVolSurfaceClientTheosPublishHelper + // Data: VolSurfaceTheoAlertData + public static ITag VolSurfaceTheoAlertTag { get; } = + new SparkTag("VolSurfaceTheoAlertTag"); + + // Publisher: NMSheetControl + // Data: string + public static ITag VolSurfaceTheoAcceptanceConfirmationTag { get; } = + new SparkTag("VolSurfaceTheoAcceptanceConfirmationTag"); + + public static ITag AquireTag(string key) { + return new KeyedSparkTag(key, "AquireTag"); + } + + public static ITag SystemContractsTag { get; } = + new SparkTag("SystemContractsTag"); + + public static ITag OptionDriverBBOTag(string option_symbol) { + return new KeyedSparkTag(option_symbol, "OptionDriverBBOTag"); + } + + public static ITag OptionDriverSymbolBBOTag(string key) { + return new KeyedSparkTag(key, "OptionDriverSymbolBBOTag"); + } + + public static ITag ExpirationParametersInputTag { get; } = + new SparkTag( + "AnalyticsExpirationParametersMap"); + + public static ITag PrecomputedOptionTheoTag(string symbol) { + return new KeyedSparkTag(symbol, "PrecomputedOptionTheoTag"); + } + + public static ITag> ExpirationParametersCommitTag { get; } = + new SparkTag>( + "ExpirationParametersCommitTag"); + + public static ITag MessageDisplayTag { get; } = + new SparkTag("MessageDisplayTag"); + + public static ITag VolSurfaceLaunchTheoWindow { get; } = + new SparkTag("VolSurfaceLaunchTheoWindow"); + + public static ITag SparkTimer { get; } = + new SparkTag("SparkTimer"); + + #endregion + + public static ITag> SyntheticDeleteTag { get; } = new SparkTag>(nameof(SyntheticDeleteTag)); + + public static ITag ShowGlobalAlertsTag { get; } = new SparkTag(nameof(ShowGlobalAlertsTag)); + + public class Nothing { Nothing() { } } + + internal class SparkTag : ITag { + readonly string Name; + public SparkTag(string name = "") => Name = name; + public override string ToString() => Name; + } + + internal class KeyedSparkTag : ITag { + internal readonly TKey Key; + internal readonly string Name; + public KeyedSparkTag(TKey key, string name = "") { + Name = name; + Key = key; + } + public override string ToString() { + return Name + "_" + Key; + } + public override int GetHashCode() { + return ToString().GetHashCode(); + } + public override bool Equals(object obj) { + return obj != null && GetType() == obj.GetType() && + GetHashCode() == obj.GetHashCode(); + } + + } + } +} diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs index b3e5283fc..edd7a130a 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs @@ -58,12 +58,10 @@ namespace mbts.spark { [ProtoMember(8)] GridSettings _synthetic_management_grid; [ProtoMember(9)] - GridSettings _pnl_grid; - [ProtoMember(10)] bts.shell.orderbook.OrderBookGridSettings _order_book_grid; - [ProtoMember(13)] + [ProtoMember(10)] PNLSettings _pnl; - [ProtoMember(14)] + [ProtoMember(11)] GlobalAlertSettings _alerts; public UserSettings() { } @@ -79,7 +77,6 @@ namespace mbts.spark { public GridSettings time_and_sales_grid => _time_and_sales_grid ?? (_time_and_sales_grid = GridSettings.Default.with(bts.shell.time_and_sales.TimeAndSalesSettings.DefaultColumns.all)); public GridSettings fills_grid => _fills_grid ?? (_fills_grid = bts.shell.fills.FillsSettings.DefaultGridSettings); public GridSettings synthetic_management_grid => _synthetic_management_grid ?? (_synthetic_management_grid = bts.shell.SyntheticManagementWindowFactory.StartupData.DefaultGridSettings); - public GridSettings pnl_grid => _pnl_grid ?? (_pnl_grid = bts.shell.PAndLWindowFactory.PAndLStartupData.DefaultGridSettings); public PNLSettings pnl => _pnl ?? (_pnl = PNLSettings.Default); public bts.shell.orderbook.OrderBookGridSettings order_book_grid => _order_book_grid ?? (_order_book_grid = bts.shell.orderbook.OrderBookStartupData.Default.grid_settings_wrapper()); @@ -92,7 +89,6 @@ namespace mbts.spark { GridSettings time_and_sales = null, GridSettings provided_fills_gridsettings = null, GridSettings provided_synthetic_management_gridsettings = null, - GridSettings provided_pnl_gridsettings = null, PNLSettings pnl = null, bts.shell.orderbook.OrderBookGridSettings order_book_grid = null, GlobalAlertSettings alerts = null) { @@ -103,7 +99,6 @@ namespace mbts.spark { _time_and_sales_grid = time_and_sales ?? _time_and_sales_grid, _fills_grid = provided_fills_gridsettings ?? _fills_grid, _synthetic_management_grid = provided_synthetic_management_gridsettings ?? _synthetic_management_grid, - _pnl_grid = provided_pnl_gridsettings ?? _pnl_grid, _pnl = pnl ?? _pnl, _order_book_grid = order_book_grid ?? _order_book_grid, _alerts = alerts ?? _alerts diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs index 51f1b1cfb..ecee271b8 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs @@ -27,7 +27,6 @@ namespace mbts.persist { static readonly IImmutableProperty _fills_propi = ImmutableProperty.create(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)), _mview_propi = ImmutableProperty.create(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)), - _pandl_propi = ImmutableProperty.create(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)), _synth_propi = ImmutableProperty.create(us => us.synthetic_management_grid, (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)); static readonly IImmutableProperty @@ -37,7 +36,6 @@ namespace mbts.persist { readonly BehaviorSubject _default_settings_subject = new BehaviorSubject(UserSettings.factory_defaults); readonly IEnumerable _fills_migration_rules; readonly IEnumerable _mview_migration_rules; - readonly IEnumerable _pandl_migration_rules; readonly IEnumerable _pnl_migration_rules; readonly IEnumerable _synth_migration_rules; readonly IUserPersist _persist; @@ -56,7 +54,6 @@ namespace mbts.persist { _persist = persist; _fills_migration_rules = fills_migration_rules ?? Enumerable.Empty(); _mview_migration_rules = mview_migration_rules ?? Enumerable.Empty(); - _pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty(); _pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty(); _synth_migration_rules = synth_migration_rules ?? Enumerable.Empty(); init(); @@ -68,7 +65,6 @@ namespace mbts.persist { var wrapped_rules = new[] { _fills_migration_rules.merge().wrap(_fills_propi), _mview_migration_rules.merge().wrap(_mview_propi), - _pandl_migration_rules.merge().wrap(_pandl_propi), _pnl_migration_rules.merge().wrap(_pnl_propi), _synth_migration_rules.merge().wrap(_synth_propi) }; @@ -132,12 +128,6 @@ namespace mbts.persist { _mview_migration_rules, _mview_propi); - public IWindowSettingsManager create_pandl_settings_manager(GridSettings instance_settings) => - _create_settings_manager( - instance_settings, - _pandl_migration_rules, - _pandl_propi); - public IWindowSettingsManager create_pnl_settings_manager(PNLSettings instance_settings) => _create_settings_manager( instance_settings, diff --git a/src/client/spark/view/Spark/PAndL/PAndLVM.cs b/src/client/spark/view/Spark/PAndL/PAndLVM.cs deleted file mode 100644 index f0fd0ec64..000000000 --- a/src/client/spark/view/Spark/PAndL/PAndLVM.cs +++ /dev/null @@ -1,372 +0,0 @@ -using bts; -using bts.api; -using bts.api.core; -using bts.api.orderman; - -using mbts.persist; -using mbts.spark.filters; -using mbts.ui; -using mbts.ui.settings; -using mbts.ui.shell; -using mbts.ui.utility; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Linq; -using System.Reactive.Linq; -using System.Windows; -using System.Windows.Data; -using System.Windows.Media; - -using static bts.shell.PAndLWindowFactory; -using static mbts.spark.PAndLView; -using static mbts.ui.controls.DIYGrid; - -namespace mbts.spark { - class PAndLVM : DisposableViewModelBase { - bool _use_position_service = true; - - public PAndLVM(IBus bus, OrdersModel orders_model, PAndLStartupData startup_data, IWindowSettingsManager settings_manager) { - _bus = bus; - _mdlookup = new MDLookup(bus.subscribe(SparkTags.SecuritiesTag)); - _orders_model = orders_model; - _settings_manager = settings_manager; - _selected_pnl_calc_type = backing(nameof(selected_pnl_calc_type)); - // get initial value from settings - // else default to midpoint - // TODO: - // need to respond to settings change somehow as the - // combobox that selected_pnl_calc_type is bound to will be - // gone from this form. - // ditto start of day changes, but this will be a bit more involved - // since we'll need to create a new PnLCalculator when this changes. (infrequent, if ever) - _selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint; - _selected_pnl_calc_type.Changed += pnl_calc_type_changed; - IDisposable pnl = null; - - // Circa 2019-05-20, instead of calculating based off our on_pnl_data (i.e. on_fill_tuples), we are instead - // migrating to use consume data published by the position service. Leaving this branch in place - // in case we need to perform additional troubleshooting when this rolls out, but *not* adding a config - // toggle per Taha. - // Once the PnL-via-position service is confirmed good, we can refactor much of how the underlying pnl data - // is structured and calculated. - if (!_use_position_service) { - pnl = _orders_model.on_fill_tuples.Select(ft => new PnLData(ft, _get_security_md(ft.security)), pd => pd.fill.FillKey) - .Sample(_POSITION_UPDATE_PERIOD) - .OnDispatcher() - .Subscribe(pnl_data => { - if (pnl_data != null) { - var summary_position_rows = - from pnl_item in pnl_data.state.Values - group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md, pnl_item.security_type) into grouping - /* let start_of_day = _get_start_of_day(grouping.Key.symbol) */ - select new PnLSummaryRow(_selected_pnl_calc_type.Value, - grouping.Key, - grouping.Where(y => y.fill.FillKind != Fill.Types.FillKind.Sod).Sum(y => (uint)y.buy_quantity), - grouping.Where(y => y.fill.FillKind != Fill.Types.FillKind.Sod).Sum(y => (uint)y.sell_quantity), - grouping.Sum(y => (int)(y.buy_quantity - y.sell_quantity)), - grouping.Where(y => y.fill.FillKind == Fill.Types.FillKind.Sod).Sum(y => (int)(y.buy_quantity - y.sell_quantity)), - double.NaN, - double.NaN, - grouping.weighted_average(y => y.fill.LastPrice, y => y.buy_quantity), - grouping.weighted_average(y => y.fill.LastPrice, y => y.sell_quantity), - grouping.Select(i => i.fill), - null - ); - // remove rows for which there is no net pos or no day pos - summary_position_rows = summary_position_rows.Where(r => - !(r.start_net_position == 0 && r.day_long_quantity == 0 && r.day_short_quantity == 0) - ); - _pnl_data.sync_with(summary_position_rows); - _last_pnl_update_time = DateTime.Now; - } - }); - } else { - pnl = _orders_model.on_positions - .Sample(_POSITION_UPDATE_PERIOD) - .OnDispatcher() - .Subscribe(position_data => { - if (position_data != null) { - var summary_position_rows = position_data.state.Values.Select(p => { - var si = p.Item1; - var pos = p.Item2; - var sec_md = _get_security_md(si); - var key = (p.Item2.Account, si?.Exchange, si?.Symbol, si, sec_md, si?.security_type()); - return new PnLSummaryRow(_selected_pnl_calc_type.Value, - key, - (uint)pos.DayLongPos, - (uint)pos.DayShortPos, - (int)pos.total_pos(), - (int)pos.sod_pos(), - pos.raw_day_long_pos(), - pos.raw_day_short_pos(), - pos.DayLongAvgPrice, - pos.DayShortAvgPrice, - null, - pos - ); - }); - - // remove rows for which there is no net pos or no day pos - summary_position_rows = summary_position_rows.Where(r => - !(r.start_net_position == 0 && r.day_long_quantity == 0 && r.day_short_quantity == 0 && r.raw_day_long_position == 0 && r.raw_day_short_position == 0) - ); - _pnl_data.sync_with(summary_position_rows); - _last_pnl_update_time = DateTime.Now; - } - }); - } - pnl_view = CollectionViewSource.GetDefaultView(_pnl_data); - - // restore filter state - var fs = startup_data?.filters; - if (fs != null) { - account_filter.load_state(fs.account_regex); - exchange_string_filter.load_state(fs.exchange_regex); - symbol_filter.load_state(fs.symbol_regex); - security_filter.load_state(fs.security_regex); - start_position_filter.load_state(fs.start_net_pos); - start_pnl_filter.load_state(fs.start_pnl); - day_long_quantity_filter.load_state(fs.day_long_pos); - day_short_quantity_filter.load_state(fs.day_short_pos); - raw_day_net_position_filter.load_state(fs.raw_day_net_pos); - day_pnl_filter.load_state(fs.day_pnl); - total_net_position_filter.load_state(fs.total_net_pos); - total_pnl_filter.load_state(fs.total_pnl); - pnl_price_filter.load_state(fs.pnl_price); - security_type_filter.load_state(fs.security_types); - has_day_trades_filter.load_state(fs.has_day_trades); - } else { - // this is debt that will have to be paid down at some point, similar to the pnl_calc_type thing above - // these should come from the default startup_data. - security_type_filter.load_state(new[] { SecurityType.Future }); - } - pnl_view.CollectionChanged += Pnl_view_CollectionChanged; - - add_col(Columns.Account, DefaultColumnHeaders.Account, r => r.account, nameof(PnLSummaryRow.account), DefaultColumnWidths.Account, account_filter, DataGridFilterKnownTemplates.Regex); - add_col(Columns.Exchange, DefaultColumnHeaders.Exchange, r => r.exchange_string, nameof(PnLSummaryRow.exchange), DefaultColumnWidths.Exchange, exchange_string_filter, DataGridFilterKnownTemplates.Regex); - add_col(Columns.Symbol, DefaultColumnHeaders.Symbol, r => r.symbol, nameof(PnLSummaryRow.symbol), DefaultColumnWidths.Symbol, symbol_filter, DataGridFilterKnownTemplates.Regex); - add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security_text, nameof(PnLSummaryRow.security), DefaultColumnWidths.Security, security_filter, DataGridFilterKnownTemplates.Regex); - add_col(Columns.SecurityType, DefaultColumnHeaders.SecurityType, r => r.security_type.ToString(), nameof(PnLSummaryRow.security_type), DefaultColumnWidths.SecurityType, security_type_filter, DataGridFilterKnownTemplates.DiscreteValues); - add_col(Columns.StartNetPos, DefaultColumnHeaders.StartNetPos, r => r.start_net_position.ToString(), nameof(PnLSummaryRow.start_net_position), DefaultColumnWidths.Start_Net_Pos, start_position_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right); - add_col(Columns.StartPNL, DefaultColumnHeaders.StartPnL, r => r.start_pnl_text, nameof(PnLSummaryRow.start_pnl), DefaultColumnWidths.PnL_Generic, start_pnl_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right, r => r.start_pnl_background); - add_col(Columns.DayLong, DefaultColumnHeaders.DayLong, r => r.day_long_quantity.ToString(), nameof(PnLSummaryRow.day_long_quantity), DefaultColumnWidths.PnL_Generic, day_long_quantity_filter, DataGridFilterKnownTemplates.UIntMinMax, HorizontalAlignment.Right); - add_col(Columns.DayShort, DefaultColumnHeaders.DayShort, r => r.day_short_quantity.ToString(), nameof(PnLSummaryRow.day_short_quantity), DefaultColumnWidths.PnL_Generic, day_short_quantity_filter, DataGridFilterKnownTemplates.UIntMinMax, HorizontalAlignment.Right); - // convert nan to 0 so text is consistent with other position columns - add_col(Columns.RawDayPos, DefaultColumnHeaders.RawDayPos, r => SparkUtils.fmt_position(r.raw_day_net_position), nameof(PnLSummaryRow.raw_day_net_position), DefaultColumnWidths.PnL_Generic, raw_day_net_position_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right); - add_col(Columns.DayPNL, DefaultColumnHeaders.DayPnL, r => r.day_pnl_text, nameof(PnLSummaryRow.day_pnl), 90, day_pnl_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right, r => r.day_pnl_background); - add_col(Columns.TradedToday, "Traded Today", r => r.has_day_trades_text, nameof(PnLSummaryRow.has_day_trades), 100, has_day_trades_filter, DataGridFilterKnownTemplates.YesNo, HorizontalAlignment.Center); - add_col(Columns.TotalNetPos, DefaultColumnHeaders.TotalNetPos, r => r.total_net_position.ToString(), nameof(PnLSummaryRow.total_net_position), DefaultColumnWidths.Total_Net_Pos, total_net_position_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right); - add_col(Columns.TotalPNL, DefaultColumnHeaders.TotalPnL, r => r.total_pnl_text, nameof(PnLSummaryRow.total_pnl), DefaultColumnWidths.PnL_Generic, total_pnl_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right, r => r.total_pnl_background); - add_col(Columns.PNLPrice, DefaultColumnHeaders.PnLPrice, r => r.pnl_price_text, nameof(PnLSummaryRow.pnl_price), DefaultColumnWidths.PnL_Generic, pnl_price_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right); - void add_col(Columns key, string header, Func get_text, string sort_prop, double width, IDataGridColumnFilter filter, string filter_template, HorizontalAlignment h_align = HorizontalAlignment.Left, Func get_background = null) { - var col = new RenderTextColumn(key, get_text, filter, filter_template, get_background); - col.Header = header; - col.Width = width; - col.sort_member_path = sort_prop; - col.horizontal_alignment = h_align; - col.id = col_id(key); - columns.Add(col); - } - - // restore sort state or supply default value - pnl_view.set_sort_descriptions(startup_data.sorting_criterion, columns); - - var col_settings_flags = new Dictionary { - { Columns.StartPNL.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.DayPNL.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - { Columns.TotalPNL.ToString(), GridColumnSettingsFeatureFlags.ImmutableFontColor }, - }; - - grid_settings_manager = new SimpleGridSettingsManager(columns, col_settings_flags, _pnl_data); - // this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.) - grid_settings_manager.load_from(settings_manager.current_settings()); - - - // setup the main Disposable and - // hook up grid filters - _dispose = Disposable.Create(pnl, - settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager), - DataGridFilterHelper.hook_filters(pnl_view, - account_filter, - exchange_string_filter, - symbol_filter, - security_filter, - start_position_filter, - start_pnl_filter, - day_long_quantity_filter, - day_short_quantity_filter, - raw_day_net_position_filter, - day_pnl_filter, - total_net_position_filter, - total_pnl_filter, - pnl_price_filter, - weighted_average_buy_filter, - weighted_average_sell_filter, - security_type_filter, - has_day_trades_filter), - WorkLoop.Start("PAndL", _UPDATE_PERIOD, _calculate_pnl) - ); - } - - public ObservableCollection columns { get; } = new ObservableCollection(); - public SimpleGridSettingsManager grid_settings_manager { get; } - public GridSettings get_grid_save_state() { - if (_settings_manager.instance_settings == null) - return null; - else - return grid_settings_manager.create(); - } - - private void Pnl_view_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { - _update_totals(); - } - - private void pnl_calc_type_changed(pnl_calc_type oldval, pnl_calc_type newval) { - _calculate_pnl(); - } - - protected override void Dispose(bool disposing) { - pnl_view.CollectionChanged -= Pnl_view_CollectionChanged; - _selected_pnl_calc_type.Changed -= pnl_calc_type_changed; - } - - void _update_totals() { - if (pnl_view != null) { - total_aggregate_pnl = pnl_view.Cast().Where(r => !Double.IsNaN(r.total_pnl)).Sum(r => r.total_pnl); - total_aggregate_day_pnl = pnl_view.Cast().Where(r => !Double.IsNaN(r.total_pnl)).Sum(r => r.day_pnl); - total_aggregate_net_pos = pnl_view.Cast().Sum(r => r.total_net_position); - total_aggregate_buy_qty = pnl_view.Cast().Sum(r => r.day_long_quantity); - total_aggregate_sell_qty = pnl_view.Cast().Sum(r => r.day_short_quantity); - } - } - - void _calculate_pnl() { - // only update the pnl if we haven't updated it via a - // position update in a while - if (DateTime.Now.Subtract(_last_pnl_update_time) > _UPDATE_PERIOD) { - foreach (var r in _pnl_data) { - if (_selected_pnl_calc_type.Value != pnl_calc_type.none) { - r.update_pnl(_selected_pnl_calc_type.Value); - } - } - _update_totals(); - } - } - - SecurityMD? _get_security_md(SecurityImmutable? si) => _mdlookup.get_md(si?.Id); - - - #region Properties - - public ICollectionView pnl_view { get; } - - public List pnl_calc_types { get; } = EnumHelper.get_values_except(pnl_calc_type.none, pnl_calc_type.waterfall, pnl_calc_type.bid_or_ask, pnl_calc_type.open, pnl_calc_type.close).ToList(); - - public pnl_calc_type selected_pnl_calc_type { - get => _selected_pnl_calc_type.Value; - set => _selected_pnl_calc_type.Value = value; - } - - public double total_aggregate_pnl { - get { - return _total_aggregate_pnl; - } - set { - _total_aggregate_pnl = value; - RaisePropertyChanged(); - } - } - - public double total_aggregate_day_pnl { - get { return _total_aggregate_day_pnl; } - set { - _total_aggregate_day_pnl = value; - RaisePropertyChanged(); - } - } - - public double total_aggregate_net_pos { - get { return _total_aggregate_net_pos; } - set { - _total_aggregate_net_pos = value; - RaisePropertyChanged(); - } - } - - public double total_aggregate_buy_qty { - get { return _total_aggregate_buy_qty; } - set { - _total_aggregate_buy_qty = value; - RaisePropertyChanged(); - } - } - - public double total_aggregate_sell_qty { - get { return _total_aggregate_sell_qty; } - set { - _total_aggregate_sell_qty = value; - RaisePropertyChanged(); - } - } - - #region Filters - - public IDataGridColumnPersistentFilter account_filter { get; } = new RegexFilterVM(r => r.account, nameof(PnLSummaryRow.account)); - public IDataGridColumnPersistentFilter exchange_string_filter { get; } = new RegexFilterVM(r => r.exchange_string, nameof(PnLSummaryRow.exchange_string)); - public IDataGridColumnPersistentFilter symbol_filter { get; } = new RegexFilterVM(r => r.symbol, nameof(PnLSummaryRow.symbol)); - public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security_text, nameof(PnLSummaryRow.security_text)); - public IDataGridColumnPersistentFilter start_position_filter { get; } = new IntMinMax(r => r.start_net_position, nameof(PnLSummaryRow.start_net_position)); - public IDataGridColumnPersistentFilter start_pnl_filter { get; } = new DoubleMinMax(r => r.start_pnl, nameof(PnLSummaryRow.start_pnl)); - public IDataGridColumnPersistentFilter day_long_quantity_filter { get; } = new UIntMinMax(r => r.day_long_quantity, nameof(PnLSummaryRow.day_long_quantity)); - public IDataGridColumnPersistentFilter day_short_quantity_filter { get; } = new UIntMinMax(r => r.day_short_quantity, nameof(PnLSummaryRow.day_short_quantity)); - public IDataGridColumnPersistentFilter raw_day_net_position_filter { get; } = new DoubleMinMax(r => r.raw_day_net_position, nameof(PnLSummaryRow.raw_day_net_position)); - public IDataGridColumnPersistentFilter day_pnl_filter { get; } = new DoubleMinMax(r => r.day_pnl, nameof(PnLSummaryRow.day_pnl)); - public IDataGridColumnPersistentFilter total_net_position_filter { get; } = new IntMinMax(r => r.total_net_position, nameof(PnLSummaryRow.total_net_position)); - public IDataGridColumnPersistentFilter total_pnl_filter { get; } = new DoubleMinMax(r => r.total_pnl, nameof(PnLSummaryRow.total_pnl)); - public IDataGridColumnPersistentFilter pnl_price_filter { get; } = new DoubleMinMax(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price)); - public IDataGridColumnPersistentFilter weighted_average_buy_filter { get; } = new DoubleMinMax(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy)); - public IDataGridColumnPersistentFilter weighted_average_sell_filter { get; } = new DoubleMinMax(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell)); - public IDataGridColumnPersistentFilter security_type_filter { get; } = DiscreteValuesFilterVM.Create(EnumHelper.get_values_except(SecurityType.Option, SecurityType.Stock, SecurityType.Synthetic).ToArray(), r => r.security_type, nameof(PnLSummaryRow.security_type)); - public IDataGridColumnPersistentFilter has_day_trades_filter { get; } = DiscreteValuesFilterVM.Create(new[] { true, false }, r => r.has_day_trades, nameof(PnLSummaryRow.has_day_trades)); - - public FilterStates get_filters_states() => new FilterStates { - account_regex = account_filter.get_state(), - exchange_regex = exchange_string_filter.get_state(), - symbol_regex = exchange_string_filter.get_state(), - security_regex = security_filter.get_state(), - start_net_pos = start_position_filter.get_state(), - start_pnl = start_pnl_filter.get_state(), - day_long_pos = day_long_quantity_filter.get_state(), - day_short_pos = day_short_quantity_filter.get_state(), - raw_day_net_pos = raw_day_net_position_filter.get_state(), - day_pnl = day_pnl_filter.get_state(), - total_net_pos = total_net_position_filter.get_state(), - total_pnl = total_pnl_filter.get_state(), - pnl_price = pnl_price_filter.get_state(), - security_types = security_type_filter.get_state(), - has_day_trades = has_day_trades_filter.get_state(), - }; - - #endregion - - public List get_sorting_states() => pnl_view.get_sorting_criteria(columns); - - #endregion - - readonly IBus _bus; - readonly OrdersModel _orders_model; - readonly MDLookup _mdlookup; - IWindowSettingsManager _settings_manager; - static readonly TimeSpan _UPDATE_PERIOD = TimeSpan.FromSeconds(1); - static readonly TimeSpan _POSITION_UPDATE_PERIOD = TimeSpan.FromMilliseconds(333); - readonly Property _selected_pnl_calc_type; - - double _total_aggregate_pnl, _total_aggregate_day_pnl, _total_aggregate_net_pos, _total_aggregate_buy_qty, _total_aggregate_sell_qty; - DateTime _last_pnl_update_time = DateTime.MinValue; - ObservableCollection _pnl_data = new ObservableCollection(); - - } -} diff --git a/src/client/spark/view/Spark/PAndL/PAndLView.xaml b/src/client/spark/view/Spark/PAndL/PAndLView.xaml deleted file mode 100644 index 29e1e652a..000000000 --- a/src/client/spark/view/Spark/PAndL/PAndLView.xaml +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/client/spark/view/Spark/PAndL/PAndLView.xaml.cs b/src/client/spark/view/Spark/PAndL/PAndLView.xaml.cs deleted file mode 100644 index 7fe60d7dd..000000000 --- a/src/client/spark/view/Spark/PAndL/PAndLView.xaml.cs +++ /dev/null @@ -1,16 +0,0 @@ -using mbts.ui.controls; - -using System.Windows.Controls; - -namespace mbts.spark { - internal partial class PAndLView : UserControl { - public enum Columns { Account, Exchange, Symbol, Security, SecurityType, StartNetPos, StartPNL, DayLong, DayShort, DayPNL, TotalNetPos, TotalPNL, PNLPrice, TradedToday, RawDayPos } - - public PAndLView(PAndLVM vm) { - InitializeComponent(); - DataContext = vm; - } - } - - class PnLRowView : DIYGrid.HighPerformanceRow { } -} diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs deleted file mode 100644 index c11aa33d6..000000000 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ /dev/null @@ -1,90 +0,0 @@ -using bts.api; -using bts.shell; -using bts.spark; - -using mbts.persist; -using mbts.ui; -using mbts.ui.settings; -using mbts.ui.spark; -using mbts.ui.utility; - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reactive.Linq; -using System.Windows; -using System.Windows.Media; - -namespace mbts.spark { - internal class PAndLWindow : SparkWindow, ISharedWindow { - const string _window_type = "PAndL"; - readonly IWindowSettingsManager _settings_manager; - PAndLWindowFactory.PAndLStartupData _startup_data; - OrdersModel _orders_model; - PAndLView _view; - PAndLVM _vm; - PAndLWindowFactory _factory; - IReadOnlyList _commands; - - public PAndLWindow(OrdersModel orders_model, PAndLWindowFactory factory, IBus bus, PAndLWindowFactory.PAndLStartupData startup_data, ImageSource Icon, IWindowSettingsManager settings_manager) - : base("P&L", bus, factory, SparkCommands.ShowPAndL.icon) { - _orders_model = orders_model; - _factory = factory; - _startup_data = startup_data; - _settings_manager = settings_manager; - Icon.Freeze(); - thread_id = config.Configuration.get().pnl ? "PnL" : null; - } - - public override string window_type => _window_type; - public override PAndLWindowFactory.PAndLStartupData SaveState => _startup_data = - new PAndLWindowFactory.PAndLStartupData( - _vm.get_sorting_states(), - _vm.get_filters_states(), - _vm.selected_pnl_calc_type, - _vm.get_grid_save_state() - ); - public override UIElement Content => _view; - public override IEnumerable Commands => _commands; - - public override double MinWidth => - PAndLWindowFactory.PAndLStartupData.DefaultGridSettings.columns.Sum(gcs => gcs.width) - + SPARK_MENU_COLLAPSED_WIDTH - + LAUNCHER_BUTTON_BORDER_WIDTH - + EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH; - - public string thread_id { get; } - - public void thread_init() { - _vm = new PAndLVM(_bus, _orders_model, _startup_data, _settings_manager); - _view = new PAndLView(_vm); - _view.DataContext = _vm; - _commands = new List { - SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new ShellSettingsDialogVM( - _settings_manager, - us => us.pnl_grid, - UserSettings.FileExtensions.GRID, - s => _vm.grid_settings_manager.create_vm( - // we need to get the most up to date GridSettings when launching b/c users may - // have changed some settings on the grid directly, like column widths. - s.with(_vm.columns.Select( c => c.create())) - ) - ); - vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t)); - // TODO: bind to main window's Title - var dialog = new ShellSettingsDialog { DataContext = vm }; - vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); - return dialog; - })) - }; - } - - public override void Dispose() { - Disposable.dispose(ref _vm); - Commands.OfType().DisposeAll(); - } - - - } -} diff --git a/src/client/spark/view/Spark/PAndL/PnLData.cs b/src/client/spark/view/Spark/PAndL/PnLData.cs deleted file mode 100644 index 05a4acd7e..000000000 --- a/src/client/spark/view/Spark/PAndL/PnLData.cs +++ /dev/null @@ -1,58 +0,0 @@ -using bts.api; -using bts.api.orderman; - -using System; -using System.ComponentModel; - -using static bts.api.orderman.Fill.Types; - -namespace mbts.spark { - - [Flags] - public enum pnl_calc_type { - none = 0, - [Description("Last Tradeable Price Avalanche")] - waterfall = 1, - [Description("Last")] - last = 2, - [Description("Bid/Ask")] - bid_or_ask = 4, - [Description("Midpoint")] - midpoint = 8, - [Description("Open")] - open = 16, - [Description("Close")] - close = 32, - [Description("Settle")] - settle = 64 - } - - class PnLData { - - readonly FillTuple _fill_tuple; - readonly SecurityMD? _md; - - public PnLData(FillTuple fill_tuple, SecurityMD? md) { - // It is entirely possible for the FillTuple to have a security but for no SecrityMD to be available. For example: expired security - _md = md; - _fill_tuple = fill_tuple; - } - - public string key => _fill_tuple.fill.FillKey; - public FillImmutable fill => _fill_tuple.fill; - public SecurityMD? sec_md => _md; - public SecurityImmutable? security => _fill_tuple.security; - public OrderRecordImmutable? order => _fill_tuple.order; - - public string account => _fill_tuple.account; - public Venue? exchange => security?.Exchange; - public string symbol => security?.Symbol; - public double buy_quantity => (fill.Side == Side.Buy) ? fill.LastShares : 0; - public double sell_quantity => (fill.Side == Side.Sell) ? fill.LastShares : 0; - public SecurityType? security_type => security?.security_type(); - - public override string ToString() { - return $"Fill: ( {account} {exchange} {security.ToString()} buy: {buy_quantity} sell: {sell_quantity} ) Security: {security.ToString()}"; - } - } -} diff --git a/src/client/spark/view/Spark/PAndL/PnLHelper.cs b/src/client/spark/view/Spark/PAndL/PnLHelper.cs deleted file mode 100644 index a94efa59b..000000000 --- a/src/client/spark/view/Spark/PAndL/PnLHelper.cs +++ /dev/null @@ -1,166 +0,0 @@ -using bts.api; -using bts.api.orderman; - -using mbts.co2; - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace mbts.spark { - internal static class PnLHelper { - static readonly Dictionary cpp_dict = config.Configuration.get().cpp_entry; - - /// - /// Looks up the cash per point (cpp) for the given SecurityImmutable. - /// If the SecurityImmutable is a cross-product exchange-traded spread, - /// such as a crack spread, where the legs have differing cpps, then - /// we'll return Double.Nan; - /// - /// The SecurityImmutable for which we will look up a cpp - /// The found cpp, else Double.NaN - public static double get_cpp(this SecurityImmutable s) { - if (s.security_type() == SecurityType.Spread) { - var distinct_cpps = s.Spread.Legs - .Select(l => get_cpp_for_symbol(l.Security.Symbol)) - .Distinct(); - bool all_legs_have_same_cpp = distinct_cpps.Count() < 2; - return all_legs_have_same_cpp ? distinct_cpps.First() : Double.NaN; - } else { - return get_cpp_for_symbol(s.Symbol); - } - - double get_cpp_for_symbol(string symbol) { - if (cpp_dict.TryGetValue(symbol, out double cpp_out)) { - return cpp_out; - } - return double.NaN; - } - } - - public static bool get_driver(SecurityMD sec_md, pnl_calc_type pnl_request, ref double driver_price, double bid_price, double ask_price) { - // we always want to pass in 0 to the md query so that we don't get back NaN if the market - // data hasn't changed between query periods - ulong last_trade_time = 0; - // last is only used in waterfall and last calculations, so if neither of those types are selected - // we should not exit early if last is somehow not avaialble - if (!sec_md.md.get_last_trade(ref last_trade_time, out NativePriceSize last, out DateTime unused1, out ulong unused2) && pnl_request.HasFlag(pnl_calc_type.waterfall | pnl_calc_type.last)) return false; - - if (pnl_request.HasFlag(pnl_calc_type.waterfall)) { - // last price is available and withing range of available bid and ask - if (!Double.IsNaN(last.price) && last.price >= bid_price && last.price <= ask_price) { - driver_price = last.price; - return true; - } - - double mid = TickUtils.mid_tick(sec_md.security.ContractSpec, bid_price, ask_price); - // last price is not valid, so try the mid - if (!Double.IsNaN(mid)) { - driver_price = mid; - return true; - } - - // last bid - // ltp and bid available, no ask - if (!Double.IsNaN(last.price) && !Double.IsNaN(bid_price) && Double.IsNaN(ask_price)) { - // if last >= bid then last else bid - if (last.price >= bid_price) { - driver_price = last.price; - return true; - } else { - driver_price = bid_price; - return true; - } - } - - // last ask - // ltp and ask available, no bid - if (!Double.IsNaN(last.price) && !Double.IsNaN(ask_price) && Double.IsNaN(bid_price)) { - // if last <= ask then last else ask - if (last.price <= ask_price) { - driver_price = last.price; - return true; - } else { - driver_price = ask_price; - return true; - } - } - - // last only - if (!Double.IsNaN(last.price)) { - driver_price = last.price; - return true; - } - - // indicative, no support yet - - // bid or ask available and a settle - if ((!Double.IsNaN(bid_price) || !Double.IsNaN(ask_price)) && !Double.IsNaN(sec_md.md.settlement_price)) { - // if bid and no ask and settle and bid > Settle - if (!Double.IsNaN(bid_price) && Double.IsNaN(ask_price) && !Double.IsNaN(sec_md.md.settlement_price) && bid_price > sec_md.md.settlement_price) { - driver_price = bid_price; - return true; - } - // if ask and no bid and settle and ask < Settle - if (!Double.IsNaN(ask_price) && Double.IsNaN(bid_price) && !Double.IsNaN(sec_md.md.settlement_price) && ask_price < sec_md.md.settlement_price) { - driver_price = ask_price; - return true; - } - } - - // Settlement - // neither bid or ask are available - if (!Double.IsNaN(sec_md.md.settlement_price)) { - driver_price = sec_md.md.settlement_price; - return true; - } - - // Close - driver_price = sec_md.md.close_price; - return true; - - } // end waterfall - - if (pnl_request.HasFlag(pnl_calc_type.last)) { driver_price = last.price; return true; } - // note that bid_or_ask is not considered here since this method only - // supports returning a single driver price; see update_pnl - if (pnl_request.HasFlag(pnl_calc_type.midpoint)) { driver_price = (bid_price + ask_price) / 2.0; return true; } - if (pnl_request.HasFlag(pnl_calc_type.open)) { driver_price = sec_md.md.open_price; return true; } - if (pnl_request.HasFlag(pnl_calc_type.close)) { driver_price = sec_md.md.close_price; return true; } - if (pnl_request.HasFlag(pnl_calc_type.settle)) { driver_price = sec_md.md.settlement_price; return true; } - driver_price = Double.NaN; - return false; - } - - /// - /// FillImmutable extension method that calculates PnL based on the fill's LastPrice and LastShares - /// - /// The fill for which you'd like to calculate PnL - /// The driver price - /// The instruments cash per point - /// The PnL double or Double.NaN when the driver IsNaN or the Fill side is Undefined - public static double get_pnl(this FillImmutable fill, double driver, double cpp) { - if (!Double.IsNaN(driver)) { - if (fill.Side == Side.Buy) { return get_long_pnl(driver, fill.LastPrice, fill.LastShares, cpp); } - if (fill.Side == Side.Sell) { return get_short_pnl(driver, fill.LastPrice, fill.LastShares, cpp); } - } - return Double.NaN; - } - - public static double get_pnl(this FillImmutable fill, double bid_for_long, double ask_for_short, double cpp) { - if (fill.Side == Side.Buy) { return fill.get_pnl(bid_for_long, cpp); } - if (fill.Side == Side.Sell) { return fill.get_pnl(ask_for_short, cpp); } - return Double.NaN; - } - - public static double get_long_pnl(double driver, double price, double quantity, double cpp) => - quantity == 0 ? 0 : (driver - price) * quantity * cpp; - - public static double get_short_pnl(double driver, double price, double quantity, double cpp) => - quantity == 0 ? 0 : (price - driver) * quantity * cpp; - - - } -} diff --git a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs b/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs deleted file mode 100644 index 51a02932d..000000000 --- a/src/client/spark/view/Spark/PAndL/PnLSummaryRow.cs +++ /dev/null @@ -1,229 +0,0 @@ -using bts.api; -using bts.api.orderman; -using bts.api.position; - -using mbts.co2; -using mbts.ui; -using mbts.ui.controls; -using mbts.ui.converters; -using mbts.ui.shell; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Windows.Media; - -namespace mbts.spark { - class PnLSummaryRow : ViewModelBase, IEquatable, DIYGrid.IRowVM { - static readonly SignedDataStore _brushes; - readonly PnLDoubleBrushCell _start_pnl, _day_pnl, _total_pnl; - readonly CellProperty _pnl_price, _weighted_average_buy, _weighted_average_sell; - (string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md, SecurityType? sec_type) key; - IEnumerable _fills; - double _driver; - PositionUnitImmutable? _pu; - - static PnLSummaryRow() { - _brushes = new SignedDataStore(mk_brush(Colors.Green), mk_brush(Colors.Black), mk_brush(Colors.Red), mk_brush(Colors.Black)); - Brush mk_brush(Color c) => - new SolidColorBrush(c) { Opacity = 0.33 }.frozen(); - } - - public PnLSummaryRow(pnl_calc_type calc_type, - (string, Venue?, string, SecurityImmutable?, SecurityMD?, SecurityType?) key, - uint day_buy_quant, - uint day_sell_quant, - int net_pos, - int sod_pos, - double raw_day_long, - double raw_day_short, - double wavg_buy, - double wavg_sell, - IEnumerable fills, - PositionUnitImmutable? pu) { - this.key = key; - _start_pnl = new PnLDoubleBrushCell(this, nameof(start_pnl)); - _day_pnl = new PnLDoubleBrushCell(this, nameof(day_pnl)); - _total_pnl = new PnLDoubleBrushCell(this, nameof(total_pnl)); - day_long_quantity = day_buy_quant; - day_short_quantity = day_sell_quant; - total_net_position = net_pos; - start_net_position = sod_pos; - raw_day_long_position = raw_day_long; - raw_day_short_position = raw_day_short; - _pnl_price = new CellProperty(this, nameof(pnl_price), price => this.security.spec_or_default().format(price), 0); - _weighted_average_buy = new CellProperty(this, nameof(weighted_average_buy), price => this.security.spec_or_default().format(price), wavg_buy); - _weighted_average_sell = new CellProperty(this, nameof(weighted_average_sell), price => this.security.spec_or_default().format(price), wavg_sell); - _fills = fills; - _pu = pu; - - // set the initial pnl and pnl_price when there has been a - // position update i.e. this constructor - update_pnl(calc_type); - } - - public void update_pnl(pnl_calc_type pnl_request) { - if (key.sec_md.HasValue) { - bool dirty = false; - double cpp = key.security.Value.get_cpp(); - ulong bbo_ref = 0; - - // regardless if pnl is bid_or_ask or based on some other driver setting - // we still need to get the bid and ask - if (key.sec_md.Value.md.get_bbo(ref bbo_ref, out NativePriceSize bid, out NativePriceSize ask)) { - double bid_price = bid.price; - double ask_price = ask.price; - if (pnl_request.HasFlag(pnl_calc_type.bid_or_ask)) { - double summary_pnl = 0.0; - double start_pnl_total = 0.0; - double day_pnl_total = 0.0; - if (_fills != null) { - foreach (var fill in _fills) { - double _tick_pnl = fill.get_pnl(bid_price, ask_price, cpp); - summary_pnl += _tick_pnl; - if (fill.FillKind != Fill.Types.FillKind.Sod) { - day_pnl_total += _tick_pnl; - } else { - start_pnl_total += _tick_pnl; - } - } - } else if (_pu.HasValue) { - day_pnl_total = - PnLHelper.get_long_pnl(bid_price, weighted_average_buy, day_long_quantity, cpp) + - PnLHelper.get_short_pnl(ask_price, weighted_average_sell, day_short_quantity, cpp); - start_pnl_total = - PnLHelper.get_long_pnl(bid_price, _pu.Value.SodLongAvgPrice, _pu.Value.SodLongPos, cpp) + - PnLHelper.get_short_pnl(ask_price, _pu.Value.SodShortAvgPrice, _pu.Value.SodShortPos, cpp); - summary_pnl = day_pnl_total + start_pnl_total; - } - - _total_pnl.on_next_distinct(summary_pnl, ref dirty); - _day_pnl.on_next_distinct(day_pnl_total, ref dirty); - _start_pnl.on_next_distinct(start_pnl_total, ref dirty); - _pnl_price.on_next_distinct(double.NaN, ref dirty); - } else { - if (PnLHelper.get_driver(key.sec_md.Value, pnl_request, ref _driver, bid_price, ask_price)) { - double summary_pnl = 0.0; - double start_pnl_total = 0.0; - double day_pnl_total = 0.0; - if (_fills != null) { - foreach (var fill in _fills) { - double _tick_pnl = fill.get_pnl(_driver, cpp); - summary_pnl += _tick_pnl; - if (fill.FillKind != Fill.Types.FillKind.Sod) { - day_pnl_total += _tick_pnl; - } else { - start_pnl_total += _tick_pnl; - } - } - } else if (_pu.HasValue) { - day_pnl_total = - PnLHelper.get_long_pnl(_driver, weighted_average_buy, day_long_quantity, cpp) + - PnLHelper.get_short_pnl(_driver, weighted_average_sell, day_short_quantity, cpp); - start_pnl_total = - PnLHelper.get_long_pnl(_driver, _pu.Value.SodLongAvgPrice, _pu.Value.SodLongPos, cpp) + - PnLHelper.get_short_pnl(_driver, _pu.Value.SodShortAvgPrice, _pu.Value.SodShortPos, cpp); - summary_pnl = day_pnl_total + start_pnl_total; - } - _total_pnl.on_next_distinct(summary_pnl, ref dirty); - _day_pnl.on_next_distinct(day_pnl_total, ref dirty); - _start_pnl.on_next_distinct(start_pnl_total, ref dirty); - _pnl_price.on_next_distinct(_driver, ref dirty); - } - } - - } - - if (dirty) - raise_invalidated(); - } - } - - // probably need to come up with a GetHashCode() while we're in here - public bool Equals(PnLSummaryRow other) { - return other != null && - key.account == other.account && - key.exchange == other.exchange && - key.security == other.security && - key.symbol == other.symbol && - day_long_quantity == other.day_long_quantity && - day_short_quantity == other.day_short_quantity && - raw_day_long_position.Equals(other.raw_day_long_position) && - raw_day_short_position.Equals(other.raw_day_short_position) && - total_pnl == other.total_pnl; - } - - public override int GetHashCode() { - int hash = 1; - if (!string.IsNullOrEmpty(key.account)) hash ^= key.account.GetHashCode(); - if (key.exchange.HasValue) hash ^= key.exchange.Value.GetHashCode(); - if (key.security.HasValue) hash ^= key.security.Value.GetHashCode(); - if (!string.IsNullOrEmpty(key.symbol)) hash ^= key.symbol.GetHashCode(); - return hash; - } - - public override string ToString() { - return $"account: {account} exchange: {exchange_string} symbol: {symbol} security: {security_text} buy_quantity: {day_long_quantity} sell_quantity: {day_short_quantity} pnl: {total_pnl}"; - } - - public event Action invalidated; - // non-numeric - public string account => key.account; - public Venue exchange => key.exchange ?? Venue.Unset; - public string exchange_string => exchange.ToString(); - public string symbol => key.symbol; - public SecurityImmutable? security => key.security; - public SecurityType security_type => key.sec_type.GetValueOrDefault(); - public string security_text => security.display_name(); - // positions - public int start_net_position { get; } - public int total_net_position { get; } - public uint day_long_quantity { get; } - public uint day_short_quantity { get; } - public double raw_day_long_position { get; } - public double raw_day_short_position { get; } - public double raw_day_net_position => raw_day_long_position - raw_day_short_position; - // start pnl - public double start_pnl => _start_pnl.value; - public string start_pnl_text => _start_pnl.text; - public Brush start_pnl_background => _start_pnl.background; - // day pnl - public double day_pnl => _day_pnl.value; - public string day_pnl_text => _day_pnl.text; - public Brush day_pnl_background => _day_pnl.background; - // total pnl - public double total_pnl => _total_pnl.value; - public string total_pnl_text => _total_pnl.text; - public Brush total_pnl_background => _total_pnl.background; - // pnl price - public double pnl_price => _pnl_price.value; - public string pnl_price_text => _pnl_price.text; - // pnl weighted averages - public double weighted_average_buy => _weighted_average_buy.value; - public string weighted_average_buy_text => _weighted_average_buy.text; - public double weighted_average_sell => _weighted_average_sell.value; - public string weighted_average_sell_text => _weighted_average_sell.text; - // - public bool has_day_trades => day_long_quantity != 0 || day_short_quantity != 0; - public string has_day_trades_text => has_day_trades ? "Yes" : "No"; - - - public void raise_invalidated() => invalidated?.Invoke(); - - //public IEnumerable sod_fills => _fills.Where(f => f.Timestamp.ToDateTime() >= _start_of_day); - //public IEnumerable pos_fills => _fills.Where(f => f.Timestamp.ToDateTime() < _start_of_day); - - class PnLDoubleBrushCell : CellProperty { - Brush _background; - - public PnLDoubleBrushCell(PnLSummaryRow owner, string prop) : base(owner, prop, d => double.IsNaN(d) ? string.Empty : d.ToString("N2"), double.NaN) => - _value_set += _ => { - _background = null; - }; - - public Brush background => _background ?? (_background = _brushes.get(value)); - } - - } -} From fe7097771b8d9ef0d3a472c2237bd118c69bfe84 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 3 Jan 2022 22:26:57 -0600 Subject: [PATCH 07/33] Derive SparkWindow from DisposableViewModelBase --- .../Market/MarketView/MarketViewWindow.cs | 11 +++++----- .../Market/TimeAndSales/TimeAndSalesWindow.cs | 4 +--- .../Spreader/SyntheticManagementWindow.cs | 20 +++++++++++-------- .../Support/ActivityLog/ActivityLogWindow.cs | 10 ++++------ .../Trading/AlgoStudio/AlgoStudioWindow.cs | 4 +--- .../Modules/Trading/Fills/FillsWindow.cs | 19 +++++++++++------- .../Trading/OrderBook/OrderBookWindow.cs | 11 +++++----- src/client/spark/view/Spark/SparkWindow.cs | 16 +++++---------- 8 files changed, 45 insertions(+), 50 deletions(-) diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 36f1e5615..0c1dc2f89 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -43,6 +43,11 @@ namespace mbts.spark { _settings_manager = settings_manager; Icon.Freeze(); thread_id = config.Configuration.get().market_view ? "MarketView" : null; + _dispose = Disposable.Create(() => { + Disposable.dispose(ref _subscriptions); + _vm.Dispose(); + Commands.OfType().DisposeAll(); + }); } event Action _state_changed; @@ -193,12 +198,6 @@ namespace mbts.spark { _sorted_selected_security_criteria_backing = null; } - public override void Dispose() { - Disposable.dispose(ref _subscriptions); - _vm.Dispose(); - Commands.OfType().DisposeAll(); - } - protected override void OnParentViewCreated(SparkWindowView parent_view) => _menu_display_vm.safe_bind_to_view(parent_view); } diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index 63bfb8c3d..3d02061be 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -60,6 +60,7 @@ namespace bts.shell.time_and_sales { _can_pause_updates = can_pause_updates; thread_id = mbts.config.Configuration.get().time_and_sales ? _window_type : null; Icon.Freeze(); + _dispose = Disposable.Create(_dispose_resources); } event Action _security_criteria_changed; @@ -88,9 +89,6 @@ namespace bts.shell.time_and_sales { } } - public override void Dispose() => - _dispose_resources(); - public void thread_init() { _dispose_resources(); _ensure_state(); diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index 29eac2581..ec6e6948a 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -33,7 +33,7 @@ namespace mbts.spark { SyntheticManagementView _view; SparkMenuDisplayVM _menu_display_vm; IDisposable _subscriptions; - IReadOnlyList _commands; + List _commands; readonly IWindowSettingsManager _settings_manager; public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, IWindowSettingsManager settings_manager) @@ -42,7 +42,15 @@ namespace mbts.spark { _state = state; _settings_manager = settings_manager; Icon.Freeze(); - thread_id = config.Configuration.get().synthetic_management ? "SyntheticManagement" : null; + thread_id = config.Configuration.get().synthetic_management ? + "SyntheticManagement" : null; + _dispose = Disposable.Create(() => { + Disposable.dispose(ref _vm); + if (_commands != null) { + _commands.OfType().DisposeAll(); + _commands = null; + } + }); } public override string window_type => _window_type; @@ -65,7 +73,8 @@ namespace mbts.spark { var current_row_source = vm_connectable_builder.create(vm => vm.current_row_observable); var current_row_connectable_builder = new ConnectableSeriesBuilder(current_row_source); - _commands = new SparkCommand[] { + Log.isnull(_commands); + _commands = new() { SparkCommand.create("Add", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag).complete( () => new SecurityCriteria(), () => true ), SparkCommand.create("Remove", Icons.RemoveSynthetic, SparkTags.SyntheticDeleteTag).complete( @@ -132,11 +141,6 @@ namespace mbts.spark { SyntheticImporter.import_from_file(path, _bus, _orders_model); } - public override void Dispose() { - Disposable.dispose(ref _vm); - Commands.OfType().DisposeAll(); - } - protected override void OnParentViewCreated(SparkWindowView parent_view) => _menu_display_vm.safe_bind_to_view(parent_view); diff --git a/src/client/spark/Modules/Support/ActivityLog/ActivityLogWindow.cs b/src/client/spark/Modules/Support/ActivityLog/ActivityLogWindow.cs index 6bfd226ef..806edb011 100644 --- a/src/client/spark/Modules/Support/ActivityLog/ActivityLogWindow.cs +++ b/src/client/spark/Modules/Support/ActivityLog/ActivityLogWindow.cs @@ -19,12 +19,13 @@ namespace bts.shell { const string _window_type = "ActivityLog"; readonly IObservable _message_src; readonly LogViewerMessageCollection _messages = new LogViewerMessageCollection(); - IDisposable _dispose; + IDisposable _ui_thread_dispose; LogViewer _content; public ActivityLogWindow(IObservable messages, IBus bus, ActivityWindowFactory isw) : base("Activity Log", bus, isw, SparkCommands.ShowActivityLog.icon) { _message_src = messages; + _dispose = Disposable.Create(() => Disposable.dispose(ref _ui_thread_dispose)); } public override string window_type => _window_type; @@ -34,12 +35,9 @@ namespace bts.shell { public string thread_id => nameof(ActivityLogWindow); - public override void Dispose() { - Disposable.dispose(ref _dispose); - } - public void thread_init() { - _dispose = _message_src.OnDispatcher().Subscribe(_messages.AddLog); + Log.isnull(_ui_thread_dispose); + _ui_thread_dispose = _message_src.OnDispatcher().Subscribe(_messages.AddLog); _content = new LogViewer { ItemsSource = _messages, diff --git a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs index 5583802aa..44c1cc345 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/AlgoStudioWindow.cs @@ -42,6 +42,7 @@ namespace mbts.spark { _model = model; _state = state; thread_id = config.Configuration.get().algo_studio ? "AlgoStudio" : null; + _dispose = Disposable.Create(_dispose_core); } public override StartupData SaveState => _state = _vm.create(); @@ -58,9 +59,6 @@ namespace mbts.spark { bts.config.AlgoStudioOptions _ui_configuration => _model.algo_model.ui_configuration; - public override void Dispose() => - _dispose_core(); - public void thread_init() { _dispose_core(); _vm = new AlgoStudioVM(_model); diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index fc7a20daf..7b22e2b19 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -21,14 +21,16 @@ using System.Windows; namespace mbts.spark { class FillsWindow : SparkWindow, ISharedWindow { public const string window_type_name = "Fills"; + readonly AllowOnce _init_guard = new AllowOnce("Fills"); readonly OrdersModel _orders_model; readonly IWindowSettingsManager _settings_manager; + FillsVM _vm; FillsView _view; FillsSettings _state; SparkMenuDisplayVM _menu_display_vm; - IReadOnlyList _commands; + List _commands; public FillsWindow(FillsWindowFactory factory, IBus bus, OrdersModel orders_model, FillsSettings state, WindowSettingsManager settings_manager) : base("Fills", bus, factory, SparkCommands.ShowFills().icon) { @@ -36,6 +38,13 @@ namespace mbts.spark { _state = state; _settings_manager = settings_manager; thread_id = config.Configuration.get().fills ? "Fills" : null; + _dispose = Disposable.Create(() => { + Disposable.dispose(ref _vm); + if (_commands != null) { + _commands.OfType().DisposeAll(); + _commands = null; + } + }); } public override string window_type => window_type_name; @@ -62,7 +71,8 @@ namespace mbts.spark { _vm = new FillsVM(_bus, _orders_model, _state, _settings_manager); _view = new FillsView { DataContext = _vm }; - _commands = new List { + Log.isnull(_commands); + _commands = new() { // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { var vm = new ShellSettingsDialogVM( @@ -84,11 +94,6 @@ namespace mbts.spark { }; } - public override void Dispose() { - Disposable.dispose(ref _vm); - Commands.OfType().DisposeAll(); - } - protected override void OnParentViewCreated(SparkWindowView parent_view) => _menu_display_vm.safe_bind_to_view(parent_view); } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index 3bc7d85ec..145650b38 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -51,6 +51,11 @@ namespace mbts.spark { _settings_manager = settings_manager; _can_edit_specific_algo_params = can_edit_specific_algo_params; thread_id = config.Configuration.get().order_book ? "OrderBook" : null; + _dispose = Disposable.Create(() => { + Disposable.dispose(_thread_init_resources); + Disposable.dispose(ref _attachment_exit_sub); + Disposable.dispose(ref _vm); + }); } public override OrderBookStartupData SaveState { @@ -72,12 +77,6 @@ namespace mbts.spark { + EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH; public string thread_id { get; } - public override void Dispose() { - Disposable.dispose(_thread_init_resources); - Disposable.dispose(ref _attachment_exit_sub); - Disposable.dispose(ref _vm); - } - public void thread_init() { Log.assert(_thread_init_resources == null, $"{nameof(_thread_init_resources)} must be initialized in thread_init."); _thread_init_resources = new List(); diff --git a/src/client/spark/view/Spark/SparkWindow.cs b/src/client/spark/view/Spark/SparkWindow.cs index cd838db8d..9a0773af4 100644 --- a/src/client/spark/view/Spark/SparkWindow.cs +++ b/src/client/spark/view/Spark/SparkWindow.cs @@ -16,7 +16,7 @@ using System.Windows; using System.Windows.Media; namespace bts.spark { - abstract class SparkWindow : IShellWindow, IMeasureContentSize { + abstract class SparkWindow : DisposableViewModelBase, IShellWindow, IMeasureContentSize { protected const double SPARK_MENU_COLLAPSED_WIDTH = 54, LAUNCHER_BUTTON_BORDER_WIDTH = 5, @@ -138,8 +138,6 @@ namespace bts.spark { _shell_window_arrived?.Invoke(); } - public abstract void Dispose(); - protected virtual void OnParentViewCreated(SparkWindowView parent_view) { } class AnonymousShared : SparkWindow, ISharedWindow { @@ -148,7 +146,7 @@ namespace bts.spark { Action _on_parent_view_created; IEnumerable _commands; UIElement _content; - IDisposable _dispose; + IDisposable _ui_thread_dispose; double _min_width, _min_height, _min_width_offset, _min_height_offset; public AnonymousShared(string window_type, @@ -174,6 +172,7 @@ namespace bts.spark { _min_height_offset = min_height_offset; _min_height = min_height; _on_parent_view_created = on_parent_view_created; + _dispose = Disposable.Create(() => Disposable.dispose(ref _ui_thread_dispose)); } public override string window_type { get; } @@ -195,16 +194,11 @@ namespace bts.spark { public void thread_init() { Log.assert(_thread_init != null, "Thread init has already been executed."); - var (content, commands, get_save_state, dispose) = _thread_init(); + (_content, _commands, _get_save_state, _ui_thread_dispose) = _thread_init(); + Log.isnull(_ui_thread_dispose); _thread_init = null; - _content = content; - _commands = commands; - _get_save_state = get_save_state; - _dispose = dispose; } - public override void Dispose() => Disposable.dispose(ref _dispose); - protected override void OnParentViewCreated(SparkWindowView parent_view) { if (_on_parent_view_created != null) { _on_parent_view_created(parent_view); From 6f7e2ab2017f8e8b4967db64dfa7a9ee93994784 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 4 Jan 2022 14:06:10 -0500 Subject: [PATCH 08/33] refactor: Clean up VolSurfaceExtensions * Run formatter * Replace foreach loops w/ less verbose linq style extensions --- src/client/spark/AW2/VolSurfaceExtensions.cs | 82 ++++++++------------ 1 file changed, 33 insertions(+), 49 deletions(-) diff --git a/src/client/spark/AW2/VolSurfaceExtensions.cs b/src/client/spark/AW2/VolSurfaceExtensions.cs index d1443ffce..d51edbaee 100644 --- a/src/client/spark/AW2/VolSurfaceExtensions.cs +++ b/src/client/spark/AW2/VolSurfaceExtensions.cs @@ -1,52 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using mbts.ui.controls; -using bts.api; -using bts.api.analytics; -using Microsoft.Scripting.Actions; - + namespace mbts.spark { - internal static class VolSurfaceExtensions { + using bts.api; + using bts.api.analytics; + + using mbts.ui.controls; + + using System.Collections.Generic; + using System.Linq; + + static class VolSurfaceExtensions { // VolSurfaceUsage - public static IEnumerable vss(this VolSurfaceUsageListImmutable list) { - HashSet rv = new HashSet(); - foreach (VolSurfaceUsageEntryImmutable e in list.UsageList) { - rv.Add(e.VsId); - } - return rv; - } - public static Nullable get_vs_id(this VolSurfaceUsageListImmutable list, SecurityTuple security_tuple) { - foreach (VolSurfaceUsageEntryImmutable e in list.UsageList) { - if (e.SymbolName == security_tuple.security_name && - e.SymbolVenue == security_tuple.security_exchange) { - return e.VsId; - } - } - return null; - } - public static Nullable get_vs_id(this VolSurfaceUsageListImmutable list, string option_name) { - SecurityTuple st = new SecurityTuple(SecurityType.Option, option_name, Venue.Unset); - return get_vs_id(list, st); - } - public static bool symbol_driven_by_vs(this VolSurfaceUsageListImmutable list, - string option_name, int vs_id) { - foreach (var usage in list.UsageList) { - if (usage.SymbolName == option_name && - usage.VsId == vs_id) { - return true; - } - } - return false; - } - public static HashSet hidden_cols(this VolSurfaceMacroGridSettings gs) { - return new HashSet(gs.configuration.column_configurations.Where(cc => !cc.visible).Select(cc => cc.name)); - } - public static mbts.analytics.VolSurfaceExpiration ToVSExp(this VolSurfaceDisplayGridExpiration vsdge) { - return new mbts.analytics.VolSurfaceExpiration { expiration = vsdge.expiration, symbol = vsdge.symbol }; - } - public static mbts.SecurityExpiration ToSecurityExp(this VolSurfaceDisplayGridExpiration vsdge) { - return new mbts.SecurityExpiration(Venue.Unset, SecurityType.Option, vsdge.symbol, vsdge.expiration); - } + public static IEnumerable vss(this VolSurfaceUsageListImmutable list) => + new HashSet(list.UsageList.Select(e => e.VsId)); + + public static int? get_vs_id(this VolSurfaceUsageListImmutable list, SecurityTuple security_tuple) => + list.UsageList.TryGetFirst(e => e.SymbolName == security_tuple.security_name && + e.SymbolVenue == security_tuple.security_exchange, out var res) ? + res.VsId : null; + + public static int? get_vs_id(this VolSurfaceUsageListImmutable list, string option_name) => + get_vs_id(list, new SecurityTuple(SecurityType.Option, option_name, Venue.Unset)); + + public static bool symbol_driven_by_vs(this VolSurfaceUsageListImmutable list, string option_name, int vs_id) => + list.UsageList.Any(u => u.SymbolName == option_name && u.VsId == vs_id); + + public static HashSet hidden_cols(this VolSurfaceMacroGridSettings gs) => + new(gs.configuration.column_configurations.Where(cc => !cc.visible).Select(cc => cc.name)); + + public static analytics.VolSurfaceExpiration ToVSExp(this VolSurfaceDisplayGridExpiration vsdge) => + new() { expiration = vsdge.expiration, symbol = vsdge.symbol }; + + public static SecurityExpiration ToSecurityExp(this VolSurfaceDisplayGridExpiration vsdge) => + new(Venue.Unset, SecurityType.Option, vsdge.symbol, vsdge.expiration); } -} \ No newline at end of file +} From 36a84d28e2fecb9b9841d17981db25ab76375c2e Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 4 Jan 2022 14:57:21 -0500 Subject: [PATCH 09/33] refactor: Improve RemoveWhere ext fn impl * Don't allocate list of items to remove * Return the number of items removed --- .../Collections/Extensions/ListExtensions.cs | 1132 +++++++++-------- 1 file changed, 573 insertions(+), 559 deletions(-) diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index 2476b8b9f..d41ee27f3 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -1,560 +1,574 @@ -using bts.utils; -using mbts.utils; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace bts.collections { - public static class ListExtensions { - public static void InsertSorted(this IList list, T item) => - list.InsertSorted(item, Comparer.Default); - - public static void InsertSorted(this IList list, IEnumerable items) => - InsertSorted(list, items, Comparer.Default); - - public static void InsertSorted(this IList list, IEnumerable items, IComparer comparer) { - foreach (var item in items) - list.InsertSorted(item, comparer); - } - - public static void InsertSorted(this IList list, T item, IComparer comparer) { - int i = CollectionHelper.binary_search(list, item, comparer); - list.Insert(i < 0 ? ~i : i, item); - } - - public static void InsertSorted(this List list, T value, IComparer comparer) { - int i = list.BinarySearch(value, comparer); - list.Insert(i < 0 ? ~i : i, value); - } - - public static void InsertOrReplaceSorted(this IList list, T item, IComparer comparer) { - int i = CollectionHelper.binary_search(list, item, comparer); - if (i < 0) { - list.Insert(~i, item); - } else { - list[i] = item; - } - } - - public static bool RemoveSorted(this IList list, T item, IComparer comparer) { - int i = CollectionHelper.binary_search(list, item, comparer); - if (i < 0) - return false; - list.RemoveAt(i); - return true; - } - - public static void RemoveSorted(this IList list, IEnumerable items) where T : IComparable => - RemoveSorted(list, items, Comparer.Default); - - public static void RemoveSorted(this IList list, IEnumerable items, IComparer comparer) { - foreach (var item in items) { - int i = CollectionHelper.binary_search(list, item, comparer); - if (i >= 0) - list.RemoveAt(i); - } - } - - public static T Pop(this IList list, int index) { - T rv = list.ElementAt(index); - list.RemoveAt(index); - return rv; - } - - public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { - for(int i = 0; i < list.Count; i++) { - if (key_selector(list[i]).Equals(key)) { - result = list[i]; - return true; - } - } - result = default(T); - return false; - } - - public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { - if (list.Pop(key, key_selector, out T result)) { - result.Dispose(); - return true; - } - return false; - } - - public static bool IsNullOrEmpty(this IList source) => - source == null || source.Count == 0; - - public static IEnumerable ExceptAt(this List list, int index) { - for (int i = 0; i < index; i++) - yield return list[i]; - for (int i = index + 1; i < list.Count; i++) - yield return list[i]; - } - - public static void RemoveWhere(this IList list, Func where) { foreach (var r in list.Where(where).ToList()) list.Remove(r); } - - public static void RemoveWhere(this IList list, Func where, Action on_remove) { - int count = list.Count; - for (int i = 0; i < count; i++) { - var t = list[i]; - if (where(t)) { - list.RemoveAt(i--); - --count; - on_remove(t); - } - } - } - - public static TResult[] ToArray(this IList list, Func selector) { - var array = new TResult[list.Count]; - for (int i = 0; i < list.Count; i++) - array[i] = selector(list[i]); - return array; - } - - public static bool SafeTryGetAt(this IList list, int index, out T value) { - if (list != null && index >= 0 && index < list.Count) { - value = list[index]; - return true; - } - value = default; - return false; - } - - public static bool TryGetAt(this IList list, int index, out T value) { - if (index >= 0 && index < list.Count) { - value = list[index]; - return true; - } - value = default; - return false; - } - - public static IList WrapValue(T value) => - new ValueListWrapper(value); - - public static IList WrapType(this IList list) => - new TypeWrapper(list); - - public static IList WrapReverse(this IList list) => - new ReverseWrapper(list); - - public static IReadOnlyList WrapReverseRO(this IList list) => - new ReverseWrapper(list); - - public static IList WrapSubRange(this IList list, int start) => - new SubRangeWrapper(list, start, list.Count - start); - - public static IList WrapSubRange(this IList list, int start, int length) => - new SubRangeWrapper(list, start, length); - - public static IReadOnlyList WrapSubRangeRO(this IList list, int start, int length) => - new SubRangeWrapper(list, start, length); - - public static IList WrapSkip(this IList list, int skip) => - new SkipFrontWrapper(list, skip); - - public static IList WrapSelector(this IList list, Func convert, Func convert_back = null) => - new SelectorWrapper(list, convert, convert_back); - - public static IList WrapSelectorHidden(this IList list, Func convert, Func convert_back = null) => - new SelectorWrapper(list, convert, convert_back); - - public static IList WrapSelector(this IList list, Func convert, Func convert_back) => - new SelectorWrapper(list, convert, convert_back); - - public static IReadOnlyList WrapSelectorRO(this IList list, Func convert) => - new SelectorWrapper(list, convert, null); - - private static Random rng = new Random(); - - public static void Shuffle(this IList list) { - int n = list.Count; - while (n > 1) { - n--; - int k = rng.Next(n + 1); - T value = list[k]; - list[k] = list[n]; - list[n] = value; - } - } - - public static void RemoveAt(this IList list, int index, int count) { - for (int i = 0; i < count; i++) - list.RemoveAt(index); - } - - public static int IndexOf(IReadOnlyList list, T value) { - for (int i = 0; i < list.Count; i++) - if (value.Equals(list[i])) - return i; - return -1; - } - - // unlike new T[] { value }, this struct prohibits changing the value at index 0. - struct ValueListWrapper : IList { - readonly T _value; - - public ValueListWrapper(T value) => - _value = value; - - public T this[int index] { - get => index == 0 ? _value : throw new IndexOutOfRangeException(); - set => throw new NotSupportedException(); - } - public int Count => 1; - public bool IsReadOnly => true; - - void ICollection.Add(T item) => throw new NotSupportedException(); - void ICollection.Clear() => throw new NotSupportedException(); - public bool Contains(T item) => _value.Equals(item); - public void CopyTo(T[] array, int arrayIndex) => array[arrayIndex] = _value; - public IEnumerator GetEnumerator() { - yield return _value; - } - public int IndexOf(T item) => _value.Equals(item) ? 0 : -1; - void IList.Insert(int index, T item) => throw new NotSupportedException(); - bool ICollection.Remove(T item) => throw new NotSupportedException(); - void IList.RemoveAt(int index) => throw new NotSupportedException(); - IEnumerator IEnumerable.GetEnumerator() { - yield return _value; - } - } - - class TypeWrapper : IList, IReadOnlyList { - readonly IList _source; - - public TypeWrapper(IList source) => - _source = source; - - public T this[int index] { - get => _source[index] is T v ? v : default; - set => _source[index] = value; - } - public int Count => _source.Count; - public bool IsReadOnly => _source.IsReadOnly; - - public void Add(T item) => _source.Add(item); - public void Clear() => _source.Clear(); - public bool Contains(T item) => _source.Contains(item); - public void CopyTo(T[] array, int array_index) => _source.CopyTo(array, array_index); - public IEnumerator GetEnumerator() { - for (int i = 0; i < _source.Count; i++) - yield return _source[i] is T v ? v : default; - } - public int IndexOf(T item) => _source.IndexOf(item); - public void Insert(int index, T item) => _source.Insert(index, item); - public bool Remove(T item) { - int index = _source.IndexOf(item); - if (index >= 0) { - _source.RemoveAt(index); - return true; - } else return false; - } - public void RemoveAt(int index) => _source.RemoveAt(index); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - - class ReverseWrapper : IList, IReadOnlyList { - readonly IList _source; - - public ReverseWrapper(IList source) => - _source = source ?? throw new ArgumentNullException(nameof(source)); - - public T this[int index] { - get => _source[_check_reverse(index)]; - set => _source[_check_reverse(index)] = value; - } - - public int Count => _source.Count; - - public bool IsReadOnly => _source.IsReadOnly; - - public void Add(T item) => _source.Insert(0, item); - public void Clear() => _source.Clear(); - public bool Contains(T item) => _source.Contains(item); - public void CopyTo(T[] array, int arrayIndex) { - for (int i = 0; i < Count; i++) - array[arrayIndex + i] = _source[_reverse(i)]; - } - public IEnumerator GetEnumerator() { - for (int i = Count - 1; i >= 0; i--) - yield return _source[i]; - } - public int IndexOf(T item) { - /// Though it isn't stated in the IList contract, it is standard practice for 'IndexOf' to return -1 if the item isn't found. - /// Therefor, if 'i' is negative, return it directly (without reversing it). - int i = _source.IndexOf(item); - return i < 0 ? i : _reverse(i); - } - public void Insert(int index, T item) => _source.Insert(_check_reverse(index), item); - public bool Remove(T item) => _source.Remove(item); - public void RemoveAt(int index) => _source.RemoveAt(_check_reverse(index)); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - // Validates the index before reversing it, so any inevitable 'IndexOutOfRange' exception isn't incidentally reversed too. - int _check_reverse(int index) => - index < 0 ? throw ExceptionBuilder.IndexOutOfRange.lt_zero() : - index >= Count ? throw ExceptionBuilder.IndexOutOfRange.gte_length() : - _reverse(index); - - int _reverse(int index) => - Count - index - 1; - } - - class SubRangeWrapper : IList, IReadOnlyList { - readonly IList _source; - readonly int _start; - - public SubRangeWrapper(IList source, int start, int count) { - _source = source; - _start = start; - Count = count; - } - - public T this[int index] { - get => _source[_convert_index(index)]; - set => _source[_convert_index(index)] = value; - } - public int Count { get; private set; } - public bool IsReadOnly => _source.IsReadOnly; - - public void Add(T item) { - int index = _start + Count; - if (index < _source.Count) { - _source.Insert(index, item); - } else _source.Add(item); - Count++; - } - public void Clear() { - if (_source is List l) { - /// Favor ; it is optimized. - l.RemoveRange(_start, Count); - Count = 0; - } else { - while (Count > 0) { - _source.RemoveAt(_start); - Count--; - } - } - } - public bool Contains(T item) => IndexOf(item) >= 0; - public void CopyTo(T[] array, int arrayIndex) { - for (int i = 0; i < Count; i++) - array[i + arrayIndex] = _source[i + _start]; - } - public IEnumerator GetEnumerator() { - int stop = _start + Count; - for (int i = _start; i < stop; i++) - yield return _source[i]; - } - public int IndexOf(T item) { - int i = 0; - foreach (T v in this) { - if (v.Equals(item)) - return i; - i++; - } - return -1; - } - public void Insert(int index, T item) { - _source.Insert(_convert_index(index), item); - Count++; - } - public bool Remove(T item) { - int i = IndexOf(item); - if (i >= 0) { - _source.RemoveAt(i); - Count--; - return true; - } - return false; - } - public void RemoveAt(int index) { - _source.RemoveAt(_convert_index(index)); - Count--; - } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - int _convert_index(int index) { - if (index >= Count || index < 0) throw new ArgumentOutOfRangeException(nameof(index)); - return _start + index; - } - } - - class SelectorWrapper : IList, IList, IReadOnlyList { - readonly Func _convert; - readonly Func _convert_back; - readonly IList _source; - - public SelectorWrapper(IList source, Func convert, Func convert_back) { - _source = source; - _convert = convert; - _convert_back = convert_back; - } - - public T this[int index] { - get => _convert(_source[index]); - set => _source[index] = _convert_back(value); - } - public int Count => _source.Count; - public bool IsReadOnly => _source.IsReadOnly && _convert_back != null; - - public void Add(T item) => _source.Add(_convert_back(item)); - public void Clear() => _source.Clear(); - public bool Contains(T item) => _source.Contains(_convert_back(item)); - public void CopyTo(T[] array, int arrayIndex) { - for (int i = 0; i < _source.Count; i++) - array[arrayIndex + i] = _convert(_source[i]); - } - public IEnumerator GetEnumerator() { - for (int i = 0; i < _source.Count; i++) - yield return _convert(_source[i]); - } - public int IndexOf(T item) => _source.IndexOf(_convert_back(item)); - public void Insert(int index, T item) => _source.Insert(index, _convert_back(item)); - public bool Remove(T item) { - int i = _source.IndexOf(_convert_back(item)); - if (i >= 0) { - _source.RemoveAt(i); - return true; - } else return false; - } - public void RemoveAt(int index) => _source.RemoveAt(index); - - #region IList (non-generic) - object IList.this[int index] { - get => this[index]; - set { - if (value is T v) - this[index] = v; - } - } - bool IList.IsFixedSize => _source.IsFixedSize; - bool IList.IsReadOnly => IsReadOnly; - bool ICollection.IsSynchronized => _source.IsSynchronized; - object ICollection.SyncRoot => _source.SyncRoot; - int IList.Add(object value) { - if (value is T v) { - return _source.Add(_convert_back(v)); - } else throw new ArgumentException(nameof(value), $"Unexpected type '{value?.GetType()}.'"); - } - bool IList.Contains(object value) => value is T v && _source.Contains(_convert_back(v)); - void ICollection.CopyTo(Array array, int index) { - for (int i = 0; i < _source.Count; i++) - array.SetValue(_convert(_source[index]), index + i); - } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - int IList.IndexOf(object value) => value is T v ? IndexOf(v) : -1; - void IList.Insert(int index, object value) { - if (value is T v) - Insert(index, v); - } - void IList.Remove(object value) { - if (value is T v) - Remove(v); - } - void IList.RemoveAt(int index) => RemoveAt(index); - #endregion - } - - class SelectorWrapper : IList, IReadOnlyList { - readonly Func _convert; - readonly Func _convert_back; - readonly IList _source; - - public SelectorWrapper(IList source, Func convert, Func convert_back) { - _source = source; - _convert = convert; - _convert_back = convert_back; - } - - public TOut this[int index] { - get => _convert(_source[index]); - set => _source[index] = _convert_back(value); - } - public int Count => _source.Count; - public bool IsReadOnly => _source.IsReadOnly && _convert_back != null; - public void Add(TOut item) => _source.Add(_convert_back(item)); - public void Clear() => _source.Clear(); - public bool Contains(TOut item) => _source.Contains(_convert_back(item)); - public void CopyTo(TOut[] array, int arrayIndex) { - for (int i = 0; i < _source.Count; i++) - array[arrayIndex + i] = _convert(_source[i]); - } - public IEnumerator GetEnumerator() { - for (int i = 0; i < _source.Count; i++) - yield return _convert(_source[i]); - } - public int IndexOf(TOut item) => _source.IndexOf(_convert_back(item)); - public void Insert(int index, TOut item) => _source.Insert(index, _convert_back(item)); - public bool Remove(TOut item) => _source.Remove(_convert_back(item)); - public void RemoveAt(int index) => _source.RemoveAt(index); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - - class SkipFrontWrapper : IList, IReadOnlyList { - readonly IList _source; - readonly int _skip; - - public SkipFrontWrapper(IList source, int skip) { - _source = source; - _skip = skip; - } - - public T this[int index] { - get => _source[_skip + index]; - set => _source[_skip + index] = value; - } - - public int Count { - get { - int c = _source.Count; - return c > _skip ? (c - _skip) : 0; - } - } - - public bool IsReadOnly => _source.IsReadOnly; - - public void Add(T item) => _source.Add(item); - public void Clear() { - int c = Count; - if (c == 0) - return; - if (_source is List l) { - l.RemoveRange(_skip, c); - } else { - for (int i = 0; i < c; i++) - _source.RemoveAt(_skip); - } - } - public bool Contains(T item) => IndexOf(item) >= 0; - public void CopyTo(T[] array, int arrayIndex) { - arrayIndex -= _skip; - for (int i = _skip; i < _source.Count; i++) - array[arrayIndex + i] = _source[i]; - } - public IEnumerator GetEnumerator() { - for (int i = _skip; i < _source.Count; i++) - yield return _source[i]; - } - public int IndexOf(T item) { - for (int i = _skip; i < _source.Count; i++) { - if (_source[i].Equals(item)) - return i - _skip; - } - return -1; - } - public void Insert(int index, T item) => _source.Insert(index + _skip, item); - public bool Remove(T item) { - int i = IndexOf(item); - if (i >= 0) { - _source.RemoveAt(i + _skip); - return true; - } else return false; - } - public void RemoveAt(int index) => _source.RemoveAt(index + _skip); - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - } - } +using bts.utils; +using mbts.utils; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace bts.collections { + public static class ListExtensions { + public static void InsertSorted(this IList list, T item) => + list.InsertSorted(item, Comparer.Default); + + public static void InsertSorted(this IList list, IEnumerable items) => + InsertSorted(list, items, Comparer.Default); + + public static void InsertSorted(this IList list, IEnumerable items, IComparer comparer) { + foreach (var item in items) + list.InsertSorted(item, comparer); + } + + public static void InsertSorted(this IList list, T item, IComparer comparer) { + int i = CollectionHelper.binary_search(list, item, comparer); + list.Insert(i < 0 ? ~i : i, item); + } + + public static void InsertSorted(this List list, T value, IComparer comparer) { + int i = list.BinarySearch(value, comparer); + list.Insert(i < 0 ? ~i : i, value); + } + + public static void InsertOrReplaceSorted(this IList list, T item, IComparer comparer) { + int i = CollectionHelper.binary_search(list, item, comparer); + if (i < 0) { + list.Insert(~i, item); + } else { + list[i] = item; + } + } + + public static bool RemoveSorted(this IList list, T item, IComparer comparer) { + int i = CollectionHelper.binary_search(list, item, comparer); + if (i < 0) + return false; + list.RemoveAt(i); + return true; + } + + public static void RemoveSorted(this IList list, IEnumerable items) where T : IComparable => + RemoveSorted(list, items, Comparer.Default); + + public static void RemoveSorted(this IList list, IEnumerable items, IComparer comparer) { + foreach (var item in items) { + int i = CollectionHelper.binary_search(list, item, comparer); + if (i >= 0) + list.RemoveAt(i); + } + } + + public static T Pop(this IList list, int index) { + T rv = list.ElementAt(index); + list.RemoveAt(index); + return rv; + } + + public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { + for(int i = 0; i < list.Count; i++) { + if (key_selector(list[i]).Equals(key)) { + result = list[i]; + return true; + } + } + result = default(T); + return false; + } + + public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { + if (list.Pop(key, key_selector, out T result)) { + result.Dispose(); + return true; + } + return false; + } + + public static bool IsNullOrEmpty(this IList source) => + source == null || source.Count == 0; + + public static IEnumerable ExceptAt(this List list, int index) { + for (int i = 0; i < index; i++) + yield return list[i]; + for (int i = index + 1; i < list.Count; i++) + yield return list[i]; + } + + public static int RemoveWhere(this IList list, Func where) { + int num_removed = 0; + for (int i = 0; i < list.Count;) { + if (where(list[i])) { + list.RemoveAt(i); + num_removed++; + continue; + } + i++; + } + return num_removed; + } + + public static int RemoveWhere(this IList list, Func where, Action on_remove) { + int num_removed = 0; + for (int i = 0; i < list.Count;) { + var t = list[i]; + if (where(t)) { + list.RemoveAt(i--); + on_remove(t); + num_removed++; + continue; + } + i++; + } + return num_removed; + } + + public static TResult[] ToArray(this IList list, Func selector) { + var array = new TResult[list.Count]; + for (int i = 0; i < list.Count; i++) + array[i] = selector(list[i]); + return array; + } + + public static bool SafeTryGetAt(this IList list, int index, out T value) { + if (list != null && index >= 0 && index < list.Count) { + value = list[index]; + return true; + } + value = default; + return false; + } + + public static bool TryGetAt(this IList list, int index, out T value) { + if (index >= 0 && index < list.Count) { + value = list[index]; + return true; + } + value = default; + return false; + } + + public static IList WrapValue(T value) => + new ValueListWrapper(value); + + public static IList WrapType(this IList list) => + new TypeWrapper(list); + + public static IList WrapReverse(this IList list) => + new ReverseWrapper(list); + + public static IReadOnlyList WrapReverseRO(this IList list) => + new ReverseWrapper(list); + + public static IList WrapSubRange(this IList list, int start) => + new SubRangeWrapper(list, start, list.Count - start); + + public static IList WrapSubRange(this IList list, int start, int length) => + new SubRangeWrapper(list, start, length); + + public static IReadOnlyList WrapSubRangeRO(this IList list, int start, int length) => + new SubRangeWrapper(list, start, length); + + public static IList WrapSkip(this IList list, int skip) => + new SkipFrontWrapper(list, skip); + + public static IList WrapSelector(this IList list, Func convert, Func convert_back = null) => + new SelectorWrapper(list, convert, convert_back); + + public static IList WrapSelectorHidden(this IList list, Func convert, Func convert_back = null) => + new SelectorWrapper(list, convert, convert_back); + + public static IList WrapSelector(this IList list, Func convert, Func convert_back) => + new SelectorWrapper(list, convert, convert_back); + + public static IReadOnlyList WrapSelectorRO(this IList list, Func convert) => + new SelectorWrapper(list, convert, null); + + private static Random rng = new Random(); + + public static void Shuffle(this IList list) { + int n = list.Count; + while (n > 1) { + n--; + int k = rng.Next(n + 1); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } + + public static void RemoveAt(this IList list, int index, int count) { + for (int i = 0; i < count; i++) + list.RemoveAt(index); + } + + public static int IndexOf(IReadOnlyList list, T value) { + for (int i = 0; i < list.Count; i++) + if (value.Equals(list[i])) + return i; + return -1; + } + + // unlike new T[] { value }, this struct prohibits changing the value at index 0. + struct ValueListWrapper : IList { + readonly T _value; + + public ValueListWrapper(T value) => + _value = value; + + public T this[int index] { + get => index == 0 ? _value : throw new IndexOutOfRangeException(); + set => throw new NotSupportedException(); + } + public int Count => 1; + public bool IsReadOnly => true; + + void ICollection.Add(T item) => throw new NotSupportedException(); + void ICollection.Clear() => throw new NotSupportedException(); + public bool Contains(T item) => _value.Equals(item); + public void CopyTo(T[] array, int arrayIndex) => array[arrayIndex] = _value; + public IEnumerator GetEnumerator() { + yield return _value; + } + public int IndexOf(T item) => _value.Equals(item) ? 0 : -1; + void IList.Insert(int index, T item) => throw new NotSupportedException(); + bool ICollection.Remove(T item) => throw new NotSupportedException(); + void IList.RemoveAt(int index) => throw new NotSupportedException(); + IEnumerator IEnumerable.GetEnumerator() { + yield return _value; + } + } + + class TypeWrapper : IList, IReadOnlyList { + readonly IList _source; + + public TypeWrapper(IList source) => + _source = source; + + public T this[int index] { + get => _source[index] is T v ? v : default; + set => _source[index] = value; + } + public int Count => _source.Count; + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Add(item); + public void Clear() => _source.Clear(); + public bool Contains(T item) => _source.Contains(item); + public void CopyTo(T[] array, int array_index) => _source.CopyTo(array, array_index); + public IEnumerator GetEnumerator() { + for (int i = 0; i < _source.Count; i++) + yield return _source[i] is T v ? v : default; + } + public int IndexOf(T item) => _source.IndexOf(item); + public void Insert(int index, T item) => _source.Insert(index, item); + public bool Remove(T item) { + int index = _source.IndexOf(item); + if (index >= 0) { + _source.RemoveAt(index); + return true; + } else return false; + } + public void RemoveAt(int index) => _source.RemoveAt(index); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + class ReverseWrapper : IList, IReadOnlyList { + readonly IList _source; + + public ReverseWrapper(IList source) => + _source = source ?? throw new ArgumentNullException(nameof(source)); + + public T this[int index] { + get => _source[_check_reverse(index)]; + set => _source[_check_reverse(index)] = value; + } + + public int Count => _source.Count; + + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Insert(0, item); + public void Clear() => _source.Clear(); + public bool Contains(T item) => _source.Contains(item); + public void CopyTo(T[] array, int arrayIndex) { + for (int i = 0; i < Count; i++) + array[arrayIndex + i] = _source[_reverse(i)]; + } + public IEnumerator GetEnumerator() { + for (int i = Count - 1; i >= 0; i--) + yield return _source[i]; + } + public int IndexOf(T item) { + /// Though it isn't stated in the IList contract, it is standard practice for 'IndexOf' to return -1 if the item isn't found. + /// Therefor, if 'i' is negative, return it directly (without reversing it). + int i = _source.IndexOf(item); + return i < 0 ? i : _reverse(i); + } + public void Insert(int index, T item) => _source.Insert(_check_reverse(index), item); + public bool Remove(T item) => _source.Remove(item); + public void RemoveAt(int index) => _source.RemoveAt(_check_reverse(index)); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + // Validates the index before reversing it, so any inevitable 'IndexOutOfRange' exception isn't incidentally reversed too. + int _check_reverse(int index) => + index < 0 ? throw ExceptionBuilder.IndexOutOfRange.lt_zero() : + index >= Count ? throw ExceptionBuilder.IndexOutOfRange.gte_length() : + _reverse(index); + + int _reverse(int index) => + Count - index - 1; + } + + class SubRangeWrapper : IList, IReadOnlyList { + readonly IList _source; + readonly int _start; + + public SubRangeWrapper(IList source, int start, int count) { + _source = source; + _start = start; + Count = count; + } + + public T this[int index] { + get => _source[_convert_index(index)]; + set => _source[_convert_index(index)] = value; + } + public int Count { get; private set; } + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) { + int index = _start + Count; + if (index < _source.Count) { + _source.Insert(index, item); + } else _source.Add(item); + Count++; + } + public void Clear() { + if (_source is List l) { + /// Favor ; it is optimized. + l.RemoveRange(_start, Count); + Count = 0; + } else { + while (Count > 0) { + _source.RemoveAt(_start); + Count--; + } + } + } + public bool Contains(T item) => IndexOf(item) >= 0; + public void CopyTo(T[] array, int arrayIndex) { + for (int i = 0; i < Count; i++) + array[i + arrayIndex] = _source[i + _start]; + } + public IEnumerator GetEnumerator() { + int stop = _start + Count; + for (int i = _start; i < stop; i++) + yield return _source[i]; + } + public int IndexOf(T item) { + int i = 0; + foreach (T v in this) { + if (v.Equals(item)) + return i; + i++; + } + return -1; + } + public void Insert(int index, T item) { + _source.Insert(_convert_index(index), item); + Count++; + } + public bool Remove(T item) { + int i = IndexOf(item); + if (i >= 0) { + _source.RemoveAt(i); + Count--; + return true; + } + return false; + } + public void RemoveAt(int index) { + _source.RemoveAt(_convert_index(index)); + Count--; + } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + int _convert_index(int index) { + if (index >= Count || index < 0) throw new ArgumentOutOfRangeException(nameof(index)); + return _start + index; + } + } + + class SelectorWrapper : IList, IList, IReadOnlyList { + readonly Func _convert; + readonly Func _convert_back; + readonly IList _source; + + public SelectorWrapper(IList source, Func convert, Func convert_back) { + _source = source; + _convert = convert; + _convert_back = convert_back; + } + + public T this[int index] { + get => _convert(_source[index]); + set => _source[index] = _convert_back(value); + } + public int Count => _source.Count; + public bool IsReadOnly => _source.IsReadOnly && _convert_back != null; + + public void Add(T item) => _source.Add(_convert_back(item)); + public void Clear() => _source.Clear(); + public bool Contains(T item) => _source.Contains(_convert_back(item)); + public void CopyTo(T[] array, int arrayIndex) { + for (int i = 0; i < _source.Count; i++) + array[arrayIndex + i] = _convert(_source[i]); + } + public IEnumerator GetEnumerator() { + for (int i = 0; i < _source.Count; i++) + yield return _convert(_source[i]); + } + public int IndexOf(T item) => _source.IndexOf(_convert_back(item)); + public void Insert(int index, T item) => _source.Insert(index, _convert_back(item)); + public bool Remove(T item) { + int i = _source.IndexOf(_convert_back(item)); + if (i >= 0) { + _source.RemoveAt(i); + return true; + } else return false; + } + public void RemoveAt(int index) => _source.RemoveAt(index); + + #region IList (non-generic) + object IList.this[int index] { + get => this[index]; + set { + if (value is T v) + this[index] = v; + } + } + bool IList.IsFixedSize => _source.IsFixedSize; + bool IList.IsReadOnly => IsReadOnly; + bool ICollection.IsSynchronized => _source.IsSynchronized; + object ICollection.SyncRoot => _source.SyncRoot; + int IList.Add(object value) { + if (value is T v) { + return _source.Add(_convert_back(v)); + } else throw new ArgumentException(nameof(value), $"Unexpected type '{value?.GetType()}.'"); + } + bool IList.Contains(object value) => value is T v && _source.Contains(_convert_back(v)); + void ICollection.CopyTo(Array array, int index) { + for (int i = 0; i < _source.Count; i++) + array.SetValue(_convert(_source[index]), index + i); + } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + int IList.IndexOf(object value) => value is T v ? IndexOf(v) : -1; + void IList.Insert(int index, object value) { + if (value is T v) + Insert(index, v); + } + void IList.Remove(object value) { + if (value is T v) + Remove(v); + } + void IList.RemoveAt(int index) => RemoveAt(index); + #endregion + } + + class SelectorWrapper : IList, IReadOnlyList { + readonly Func _convert; + readonly Func _convert_back; + readonly IList _source; + + public SelectorWrapper(IList source, Func convert, Func convert_back) { + _source = source; + _convert = convert; + _convert_back = convert_back; + } + + public TOut this[int index] { + get => _convert(_source[index]); + set => _source[index] = _convert_back(value); + } + public int Count => _source.Count; + public bool IsReadOnly => _source.IsReadOnly && _convert_back != null; + public void Add(TOut item) => _source.Add(_convert_back(item)); + public void Clear() => _source.Clear(); + public bool Contains(TOut item) => _source.Contains(_convert_back(item)); + public void CopyTo(TOut[] array, int arrayIndex) { + for (int i = 0; i < _source.Count; i++) + array[arrayIndex + i] = _convert(_source[i]); + } + public IEnumerator GetEnumerator() { + for (int i = 0; i < _source.Count; i++) + yield return _convert(_source[i]); + } + public int IndexOf(TOut item) => _source.IndexOf(_convert_back(item)); + public void Insert(int index, TOut item) => _source.Insert(index, _convert_back(item)); + public bool Remove(TOut item) => _source.Remove(_convert_back(item)); + public void RemoveAt(int index) => _source.RemoveAt(index); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + class SkipFrontWrapper : IList, IReadOnlyList { + readonly IList _source; + readonly int _skip; + + public SkipFrontWrapper(IList source, int skip) { + _source = source; + _skip = skip; + } + + public T this[int index] { + get => _source[_skip + index]; + set => _source[_skip + index] = value; + } + + public int Count { + get { + int c = _source.Count; + return c > _skip ? (c - _skip) : 0; + } + } + + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Add(item); + public void Clear() { + int c = Count; + if (c == 0) + return; + if (_source is List l) { + l.RemoveRange(_skip, c); + } else { + for (int i = 0; i < c; i++) + _source.RemoveAt(_skip); + } + } + public bool Contains(T item) => IndexOf(item) >= 0; + public void CopyTo(T[] array, int arrayIndex) { + arrayIndex -= _skip; + for (int i = _skip; i < _source.Count; i++) + array[arrayIndex + i] = _source[i]; + } + public IEnumerator GetEnumerator() { + for (int i = _skip; i < _source.Count; i++) + yield return _source[i]; + } + public int IndexOf(T item) { + for (int i = _skip; i < _source.Count; i++) { + if (_source[i].Equals(item)) + return i - _skip; + } + return -1; + } + public void Insert(int index, T item) => _source.Insert(index + _skip, item); + public bool Remove(T item) { + int i = IndexOf(item); + if (i >= 0) { + _source.RemoveAt(i + _skip); + return true; + } else return false; + } + public void RemoveAt(int index) => _source.RemoveAt(index + _skip); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + } } \ No newline at end of file From fde11dc4a3716c41ebae4624252773bcccf0f5a6 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 5 Jan 2022 11:39:14 -0500 Subject: [PATCH 10/33] Remove unneccessary comment warning abt perf costs --- src/client/spark_api/utils/EqualityComparer.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/client/spark_api/utils/EqualityComparer.cs b/src/client/spark_api/utils/EqualityComparer.cs index a30f11b9b..9b6c5acd4 100644 --- a/src/client/spark_api/utils/EqualityComparer.cs +++ b/src/client/spark_api/utils/EqualityComparer.cs @@ -120,8 +120,6 @@ namespace bts.utils { return hash; } - // Note: be wary of the performance cost this method may have, as frequently creating large arrays can be expensive. - // If you wish to avoid this cost, consider making an overload like the method above, with the appropriate number of item-hash arguments public static int aggregate_hash(params int[] item_hashes) { int hash = _hash_seed; unchecked { From 43d614dde29aa80f24c22c837b8a60d8004fd108 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 5 Jan 2022 19:02:26 -0500 Subject: [PATCH 11/33] Add generic ICloneable interface For some reason this very basic utility isn't defined in dot net --- src/client/spark_api/utils/ICloneable.cs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/client/spark_api/utils/ICloneable.cs diff --git a/src/client/spark_api/utils/ICloneable.cs b/src/client/spark_api/utils/ICloneable.cs new file mode 100644 index 000000000..51b1e1bc4 --- /dev/null +++ b/src/client/spark_api/utils/ICloneable.cs @@ -0,0 +1,7 @@ +namespace bts { + using System; + + public interface ICloneable : ICloneable { + new T Clone(); + } +} From 79c55793afad3b5fef267ed4411635a19acd0f41 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 5 Jan 2022 19:11:08 -0500 Subject: [PATCH 12/33] refactor: Clean up VolSurfaceOutput * Implement generic ICloneable * Run formatter --- .../Analytics/Core/Output/VolSurfaceOutput.cs | 72 +++++++++---------- 1 file changed, 32 insertions(+), 40 deletions(-) diff --git a/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs b/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs index f66fceba7..728e1d19d 100644 --- a/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs +++ b/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs @@ -1,57 +1,49 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace mbts.analytics { + using bts; -namespace mbts.analytics -{ + using mbts.ui.shell; + + using System; + using System.Collections.Generic; + using System.Linq; + + /// /// Contains the input (and settings) and vol per strike - public class VolSurfaceOutput : ICloneable - { + /// + public class VolSurfaceOutput : ICloneable { public readonly VolSurfaceInput volsurface_input; public readonly IDictionary exp_output_map; public readonly IDictionary aux_data_map; - public VolSurfaceOutput(VolSurfaceInput this_volsurface_input, - IDictionary this_exp_output_map, - IDictionary this_aux_data_map) - { - volsurface_input = this_volsurface_input; - exp_output_map = this_exp_output_map; - aux_data_map = this_aux_data_map; + public VolSurfaceOutput( + VolSurfaceInput volsurface_input, + IDictionary exp_output_map, + IDictionary aux_data_map) { + this.volsurface_input = volsurface_input; + this.exp_output_map = exp_output_map; + this.aux_data_map = aux_data_map; } - public VolCurveOutput this[VolSurfaceExpiration exp] - { - get - { - VolCurveOutput rv = exp_output_map != null && exp_output_map.TryGetValue(exp, out rv) ? rv : VolCurveOutput.get_empty_output(Double.NaN, null); - return rv; - } - } + public VolCurveOutput this[VolSurfaceExpiration exp] => + exp_output_map != null && exp_output_map.TryGetValue(exp, out var res) ? + res : VolCurveOutput.get_empty_output(double.NaN, null); - public DateTime get_vol_time() - { + public DateTime get_vol_time() { /// TODO : this should be part of the data vs being in each exp /// (with the baked in assumption that its the same) return (aux_data_map != null && aux_data_map.Count > 0) ? aux_data_map.ElementAt(0).Value.base_vol_time : DateTime.MinValue; } - public object Clone() - { - return null; - // TODO - // return new VolSurfaceOutput(VolSurfaceUtilityFunctions.clone_proto(volsurface_input), - // new Dictionary(exp_output_map), - // new Dictionary(aux_data_map)); - } + public static VolSurfaceOutput get_empty_output() => new( + new VolSurfaceInput(), + new Dictionary(), + new Dictionary()); - public static VolSurfaceOutput get_empty_output() - { - return new VolSurfaceOutput(new VolSurfaceInput(), - new Dictionary(), - new Dictionary()); - } + public VolSurfaceOutput Clone() => new( + ProtoBufSerializationHelper.clone_protobuf(volsurface_input), + new Dictionary(exp_output_map), + new Dictionary(aux_data_map)); + + object ICloneable.Clone() => Clone(); } } From cee79afc23184c0a741e3c509828f3deeab568fd Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 6 Jan 2022 17:32:51 -0500 Subject: [PATCH 13/33] Make VolSurfaceDisplayModel class internal --- .../spark/AW2/VolSurfaceDisplayModel.cs | 26 +++++++++---------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/src/client/spark/AW2/VolSurfaceDisplayModel.cs b/src/client/spark/AW2/VolSurfaceDisplayModel.cs index 002f88a05..8f6d9b775 100644 --- a/src/client/spark/AW2/VolSurfaceDisplayModel.cs +++ b/src/client/spark/AW2/VolSurfaceDisplayModel.cs @@ -1,19 +1,17 @@ -using bts.api; +namespace mbts.spark { + using bts.api; + using bts.utils; -using mbts; -using mbts.analytics; + using mbts.analytics; + using mbts.ui.controls; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using mbts.ui.controls; -using bts.utils; -using System.Reactive.Linq; -using System.Collections; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reactive.Linq; + using System.Text; -namespace mbts.spark { - public class VolSurfaceDisplayModel : IDisposable { + class VolSurfaceDisplayModel : IDisposable { public enum DisplayModelState { /// Start state, as soon as the first /// server state is received, it gets @@ -601,4 +599,4 @@ namespace mbts.spark { Disposable.dispose(ref _subscriptions); } } -} \ No newline at end of file +} From 730174b6ffc6cd6627ef7262fb65c4743e2dd7ff Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 6 Jan 2022 18:30:00 -0500 Subject: [PATCH 14/33] Support multiple props w/ same name in detect_property_changes It is possible for a type to have multiple properties with the same name if that type is a reference type that inherits from a parent type, and hides one of the parent types properties with the 'new' keyword --- .../spark/core/Utility/ViewModelBase.cs | 1784 ++++++++--------- 1 file changed, 892 insertions(+), 892 deletions(-) diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index 945b1570c..1dab27f68 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -1,892 +1,892 @@ -using bts.collections; - -using mbts.ui.utility; -using mbts.utils; - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Linq; -using System.Linq.Expressions; -using System.Reactive.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using System.Windows.Input; - -namespace mbts.ui.shell { - interface IRaiseNotifyPropertyChanged { - void raise_notify_property_changed(string prop); - } - - interface IValidationViewModel : IRaiseNotifyPropertyChanged { - void set_error(string property, string message); - void clear_error(string property); - } - - interface IProperty : IObservable<(T oldval, T newval)> { - event PropertyChange Changing, Changed; - T Value { get; set; } - } - - interface IUserProperty : IProperty { - bool setter_called { get; } - void bypass_setter(T value); - } - - public delegate void PropertyChange(T oldval, T newval); - - static class ValidationViewModelExtensions { - public static void assert(this IValidationViewModel vm, bool condition, string property, string message) { - if (condition) vm.clear_error(property); - else vm.set_error(property, message); - } - - public static IObservable subscribe_has_errors(this INotifyDataErrorInfo vm, bool start_immediately = false) => - Observable.Create(o => { - bool last_value = vm.HasErrors; - if (start_immediately) - o.OnNext(vm.HasErrors); - vm.ErrorsChanged += on_errors_changed; - return Disposable.Create(() => vm.ErrorsChanged -= on_errors_changed); - void on_errors_changed(object sender, DataErrorsChangedEventArgs e) { - if (vm.HasErrors != last_value) - o.OnNext(last_value = !last_value); - } - }); - - public static IObservable SubscribeValue(this IProperty property) => - // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) - Observable.Create(o => property.Subscribe(ch => o.OnNext(ch.newval))); - - public static IProperty block_reentrancy(this IProperty source) => - new GatedPropertyWrapper(source); - - /// Blocks re-entrancy in setter. - class GatedPropertyWrapper : IProperty { - bool _is_updating; - readonly IProperty _source; - - public GatedPropertyWrapper(IProperty source) => - _source = source; - - public event PropertyChange Changing { add => _source.Changing += value; remove => _source.Changing -= value; } - public event PropertyChange Changed { add => _source.Changed += value; remove => _source.Changed -= value; } - - public T Value { - get => _source.Value; - set { - if (!_is_updating) { - _is_updating = true; - _source.Value = value; - _is_updating = false; - } - } - } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _source.Subscribe(observer); - } - } - - public class ViewModelBase : INotifyPropertyChanged, IRaiseNotifyPropertyChanged { - public ViewModelBase() { - _props = new Lazy(() => { - return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); - }); - } - protected void RaisePropertyChanged([CallerMemberName] string property = "") { - if (PropertyChanged != null) { - PropertyChanged(this, new PropertyChangedEventArgs(property)); - } - } - - protected void RaisePropertyChanged(params string[] properties) { - if (PropertyChanged != null) { - foreach (var prop in properties) { RaisePropertyChanged(prop); } - } - } - - void IRaiseNotifyPropertyChanged.raise_notify_property_changed(string prop) => - RaisePropertyChanged(prop); - - protected bool Set(ref T backing, T value, [CallerMemberName] string name = "") => - Set(ref backing, value, EqualityComparer.Default, name); - - protected bool Set(ref T backing, T value, [CallerMemberName] string name = "", params string[] dependent_props) { - if (Set(ref backing, value, EqualityComparer.Default, name)) { - RaisePropertyChanged(dependent_props); - return true; - } - return false; - } - - protected bool Set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName] string name = "") { - if (!comparer.Equals(backing, value)) { - backing = value; - RaisePropertyChanged(name); - return true; - } - return false; - } - - protected bool Set(ref T backing, T value, out T old_value, [CallerMemberName] string name = "") => - Set(ref backing, value, out old_value, EqualityComparer.Default, name); - - protected bool Set(ref T backing, T value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string name = "") { - old_value = backing; - if (!comparer.Equals(backing, value)) { - backing = value; - RaisePropertyChanged(name); - return true; - } - return false; - } - - public event PropertyChangedEventHandler PropertyChanged; - - private Lazy _props; - - - #region Object Diffing - public interface IObjSnapshot : IDisposable { - bool revert { get; set; } - } - - public class ObjSnapshot : IObjSnapshot { - readonly ViewModelBase _target; - readonly Dictionary _snapshot; - readonly IReadOnlyList _props; - - public ObjSnapshot(ViewModelBase viewModelBase, IReadOnlyList props) { - _target = viewModelBase; - _props = props; - _snapshot = snap(); - } - - public bool revert { get; set; } - - public void Dispose() { - var cur = snap(); - foreach (var kv in cur) { - object oldv = _snapshot[kv.Key]; - object newv = cur[kv.Key]; - if (!Equals(oldv, newv)) { - var prop = kv.Key.property; - if (revert && prop.CanWrite) - prop.SetValue(_target, oldv); - _target.RaisePropertyChanged(prop.Name); - } - } - } - - Dictionary snap() => - // NOTE: in the future we can optimize prop.GetValue() if needed - _props.ToDictionary(prop => new PropertyKeyWrapper(prop), prop => prop.GetValue(_target)); - - private class PropertyKeyWrapper : IEquatable { - public readonly PropertyInfo property; - public PropertyKeyWrapper(PropertyInfo property) => this.property = property; - public bool Equals(PropertyKeyWrapper other) => other != null && other.property.Name == property.Name; - public override bool Equals(object obj) => Equals(obj as PropertyKeyWrapper); - public override int GetHashCode() => property.Name.GetHashCode(); - } - } - - // Automatic (but shallow) property change notifications based on local object modifications - public ObjSnapshot detect_property_changes(params string[] props) { - if (props.Length == 0) return new ObjSnapshot(this, _props.Value); - else return new ObjSnapshot(this, _props.Value.Intersect(props, p => p.Name).ToList()); - } - - public ObjSnapshot detect_property_changes_except(params string[] props) { - if (props.Length == 0) return new ObjSnapshot(this, _props.Value); - else return new ObjSnapshot(this, _props.Value.Except(props, p => p.Name).ToList()); - } - #endregion - - #region automatic property - // use nameof() to add compile time checks - protected Property backing(string name, T default_value = default(T)) => - backing(name, EqualityComparer.Default, default_value); - - protected Property backing(string name, IEqualityComparer comparer, T default_value = default(T)) { - return new Property(this, name, comparer, default_value); - } - - protected Property backing(Expression> member, T default_value) { - var exp = (MemberExpression)member.Body; - return new Property(this, exp.Member.Name, default_value); - } - - // WILL invoke the get_value delegate - protected DelegateProperty backing(string name, Func get_value, params string[] invalidating_props) { - return new DelegateProperty(this, name, get_value, invalidating_props); - } - - // will NOT invoke the get_value delegate - protected DelegateProperty backing(string name, Func get_value, T default_value, params string[] invalidating_props) => - new DelegateProperty(this, name, get_value, default_value, invalidating_props); - - protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert) => - new PropertyAutoWrapper(this, name, initial_model, convert, EqualityComparer.Default); - - protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert, IEqualityComparer comparer) => - new PropertyAutoWrapper(this, name, initial_model, convert, comparer); - - protected DelegatePropertyAutoWrapper backing(string name, Func get_model, Func convert) => - new DelegatePropertyAutoWrapper(this, name, get_model, convert, EqualityComparer.Default); - - protected class Property : IProperty { - readonly string _propname; - readonly IEqualityComparer _comparer; - readonly ViewModelBase _owner; - T _value; - - public Property(ViewModelBase owner, string name, T default_value) - : this(owner, name, EqualityComparer.Default, default_value) { } - - public Property(ViewModelBase owner, string name, IEqualityComparer comparer, T default_value) { - _owner = owner; - _propname = name; - _comparer = comparer; - _value = default_value; - } - - public event PropertyChange Changing, Changed; - - public string name => _propname; - - public void set(T value) => - set_new(value); - - public bool set_new(T value) { - if (!Equals(value, _value)) { - Changing?.Invoke(_value, value); - var old = _value; - _value = value; - Changed?.Invoke(old, value); - _owner.RaisePropertyChanged(_propname); - return true; - } - return false; - } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => - Subscribe((oldval, newval) => observer.OnNext((oldval, newval))); - - public IDisposable Subscribe(PropertyChange callback) { - Changed += callback; - return Disposable.Create(() => Changed -= callback); - } - - public IObservable observe_current(bool start_immediately = false) { - var source = this.Select(vals => vals.newval); - if (start_immediately) - source = source.StartWith(() => _value); - return source; - } - - public T Value { - get { return _value; } - set { set(value); } - } - } - - protected class DelegateProperty : Property { - public DelegateProperty(ViewModelBase owner, string name, Func get_value, params string[] invalidating_props) - : this(owner, name, get_value, get_value(), invalidating_props) { } - - public DelegateProperty(ViewModelBase owner, string name, Func get_value, T default_value, params string[] invalidating_props) - : base(owner, name, default_value) { - _get_value = get_value; - if (invalidating_props != null && invalidating_props.Length > 0) { - var iprop_set = new HashSet(invalidating_props); - owner.PropertyChanged += (s, e) => { - if (iprop_set.Contains(e.PropertyName)) - refresh(); - }; - } - } - - readonly Func _get_value; - - public void refresh() => set(_get_value()); - public bool refresh_new() => set_new(_get_value()); - } - - /// - /// Inspired by ObservableAutoWrapper, a read/write TModel property is used to create a readonly TView property. - /// - protected class PropertyAutoWrapper : IObservable<((TModel model, TView view) oldval, (TModel model, TView view) newval)> { - readonly ViewModelBase _owner; - readonly Func _convert; - readonly IEqualityComparer _comparer; - readonly string _prop_name; - TModel _model; - TView _view; - - public PropertyAutoWrapper(ViewModelBase owner, string name, TModel initial_value, Func convert, IEqualityComparer comparer) { - _owner = owner; - _prop_name = name; - _model = initial_value; - _convert = convert; - _comparer = comparer; - _view = convert(_model); - } - - public event PropertyChange<(TModel model, TView view)> changing, changed; - - public string name => _prop_name; - public TModel model { get => _model; set => set(value); } - public TView view => _view; - - public void set(TModel model) => - set_new(model); - - public bool set_new(TModel model) { - if (_comparer.Equals(model, _model)) - return false; - TView new_view = _convert(model); - changing?.Invoke((_model, _view), (model, new_view)); - TView old_view = _view; - TModel old_model = _model; - _model = model; - _view = new_view; - changed?.Invoke((old_model, old_view), (_model, _view)); - _owner.RaisePropertyChanged(_prop_name); - return true; - } - - public IDisposable Subscribe(IObserver<((TModel model, TView view) oldval, (TModel model, TView view) newval)> observer) { - changed += pch; - return Disposable.Create(() => changed -= pch); - void pch((TModel, TView) o, (TModel, TView) n) => observer.OnNext((o, n)); - } - - public IObservable<(TModel model, TView view)> observe_current(bool start_immediately = false) { - var source = this.Select(vals => vals.newval); - if (start_immediately) - source = source.StartWith((_model, _view)); - return source; - } - } - - protected class DelegatePropertyAutoWrapper : PropertyAutoWrapper { - readonly Func _get_model; - - public DelegatePropertyAutoWrapper(ViewModelBase owner, string name, Func get_model, Func convert, IEqualityComparer comparer) - : base(owner, name, get_model(), convert, comparer) => _get_model = get_model; - - public void refresh() => set(_get_model()); - } - - /// - /// A thin wrapper around Property<T> that trips a 'setter_called' flag when the value is set through value-property-setter (i.e., through User interaction). - /// Note: This is class is particularly useful when a default/settings-based value arrives late, and the viewmodel must decide whether or not to override the current value. - /// - protected class UserProperty : IUserProperty { - readonly Property _prop_model; - - public UserProperty(Property prop_model) => - _prop_model = prop_model; - - public event PropertyChange Changing { add { _prop_model.Changing += value; } remove { _prop_model.Changing -= value; } } - public event PropertyChange Changed { add { _prop_model.Changed += value; } remove { _prop_model.Changed -= value; } } - - public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _prop_model.Subscribe(observer); - public IObservable observe_current(bool start_immediately = false) => _prop_model.observe_current(start_immediately); - - public T Value { - get => _prop_model.Value; - set { - setter_called = true; - _prop_model.set(value); - } - } - public bool setter_called { get; private set; } - - /// - /// Sets the value without tripping the 'setter_called' flag. - /// - public void bypass_setter(T value) => _prop_model.set(value); - /// - /// Sets 'setter_called' to false. - /// - public void reset() => setter_called = false; - - public void on_inline_prop(InlineUserProperty inline_prop) { - if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) - bypass_setter(inline_prop.value); - } - - public void on_inline_prop(InlineUserProperty inline_prop, Func select) { - if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) - bypass_setter(select(inline_prop.value)); - } - } - - #endregion - - protected class ObservablePropertySink : Property, IObserver { - public ObservablePropertySink(ViewModelBase owner, string name, T default_val) : base(owner, name, default_val) { } - public void OnCompleted() { } - public void OnError(Exception error) { } - - public void OnNext(T value) { set(value); } - } - } - - public class RequestViewCloseViewModelBase : ViewModelBase, IRequestViewClose { - public void TryClose() { - RequestClose?.Invoke(this, new EventArgs()); - } - - public event EventHandler RequestClose; - } - - public static class RequestViewCloseExtensions { - public static ICommand close_command(this shell.RequestViewCloseViewModelBase rvc) { - return new DelegateCommand(rvc.TryClose); - } - } - - public class VMValueWrapper : ViewModelBase where T : IEquatable { - public VMValueWrapper(T val) { _val = val; } - T _val; - public T value { get { return _val; } set { if (value == null || !value.Equals(_val)) { _val = value; RaisePropertyChanged(); } } } - } - - // Adds set_error and clear_error to ViewModelBase - public class ViewModelBaseWithValidation : ViewModelBase, INotifyDataErrorInfo, IValidationViewModel { - Dictionary _errors = new Dictionary(); - - protected bool assert(bool condition, [CallerMemberName] string property = "", string message = null) { - if (condition) { - clear_error(property); - return true; - } else if (!_errors.TryGetValue(property, out string result) || !string.Equals(message, result)) { - _errors[property] = message; - FireErrorsChanged(property); - } - return false; - } - - protected bool has_errors(string property) => - _errors.ContainsKey(property); - - protected void set_error(string property, string message, bool ignore_if_already_error = false) { - if (!_errors.ContainsKey(property) || !ignore_if_already_error) { - _errors[property] = message; - FireErrorsChanged(property); - } - } - void IValidationViewModel.set_error(string property, string message) => set_error(property, message); - - protected void clear_error(string property) { - if (_errors.ContainsKey(property)) { - _errors.Remove(property); - FireErrorsChanged(property); - } - } - void IValidationViewModel.clear_error(string property) => clear_error(property); - - protected async Task assert_flash_error(bool test, params string[] properties) { - if (!test) await flash_error(properties); - else { - foreach (var prop in properties) - clear_error(prop); - } - } - - protected async Task flash_error_msg(string msg, TimeSpan duration, params string[] properties) { - foreach (var prop in properties) - set_error(prop, msg); - await Task.Delay(duration); - foreach (var prop in properties) - clear_error(prop); - } - - protected async Task flash_error_msg(string msg, params string[] properties) => - await flash_error_msg(msg, mbts.spark.SparkUtils.UI.ErrorFlashDuration, properties); - - protected async Task flash_error(params string[] properties) => - await flash_error_msg(string.Empty, properties); - - protected IDisposable validation() { - IEnumerable current = _errors.Keys.ToList(); - _errors.Clear(); - return _validation(current); - } - - protected IDisposable validation(params string[] properties) { - IEnumerable current = _errors.Keys.Intersect(properties).ToList(); - foreach (var p in current) _errors.Remove(p); - return _validation(current); - } - - protected void validation_assert(bool test, string messsage, params string[] properties) { - if (!test) { - foreach (var prop in properties) { - set_error(prop, messsage); - } - } - } - - IDisposable _validation(IEnumerable validating_properties) => - Disposable.Create(() => { - foreach (var property in validating_properties) - if (!_errors.ContainsKey(property)) - FireErrorsChanged(property); - }); - - - void FireErrorsChanged(string property) { - ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property)); - } - - #region INotifyDataErrorInfo - public event EventHandler ErrorsChanged; - - public System.Collections.IEnumerable GetErrors(string propertyName) { - if (!string.IsNullOrEmpty(propertyName)) { - if (_errors.TryGetValue(propertyName, out string error)) { - yield return error; - } - } - } - - public bool HasErrors { - get { return _errors.Count != 0; } - } - - public IEnumerable AllErrors { get { return _errors.Values; } } - #endregion - - protected Property backing(string name, T default_value, IEnumerable> validation_steps, bool validate_now = false) { - void run_validation(T val) { - foreach (var pv in validation_steps) { - (bool valid, string msg) = pv.validate(val); - assert(valid, name, msg); - } - }; - - var prop = new Property(this, name, default_value); - prop.Changed += (old_val, new_val) => run_validation(new_val); - if (validate_now) { - run_validation(prop.Value); - } - return prop; - } - - protected UserProperty user_backing(string name, T default_value = default) => - new UserProperty(backing(name, default_value)); - - protected UserProperty user_backing(Property property) => - new UserProperty(property); - - - // TODO: maybe include a revert_on_error flag? - protected class PropertyValidation { - public readonly Func validate; - - public PropertyValidation(Func validate) => - this.validate = val => (validate(val), null); - - public PropertyValidation(Func validate) => - this.validate = validate; - } - } - - public abstract class DisposableViewModelBase : ViewModelBaseWithValidation, IPropertyChangedDemuxer, IDisposable, IWillLetYouKnowWhenIDispose { - protected IDisposable _dispose = null; - List _observable_properties_backing; - List _observable_properties => _observable_properties_backing ?? (_observable_properties_backing = new List()); - PropertyChangedDemuxer _property_changed_demuxer_backing; - - IPropertyChangedDemuxer _property_changed_demuxer => - _property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this)); - - IObservable IPropertyChangedDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); - IObservable IObservableDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); - void IObserver.OnNext(PropertyChangedEventArgs value) => _property_changed_demuxer.OnNext(value); - void IObserver.OnError(Exception error) => _property_changed_demuxer.OnError(error); - void IObserver.OnCompleted() => _property_changed_demuxer.OnCompleted(); - - internal IPropertyChangedDemuxer as_demuxer() => this; - - protected Property backing(string name, IObservable source, T default_value = default(T)) { - var prop = new ObservablePropertySink(this, name, default_value); - _observable_properties.Add(source.Subscribe(prop)); - return prop; - } - - /// - /// Use this generic overload when the [T]value must be created from the [TData]data on this thread, and a simple observable.Select() call will not work. - /// Note: UI settings in particular may find this useful, as brushes and other Freezable types are not inherently thread safe. - /// - protected Property backing(string name, IObservable source, Func select, T default_value = default) { - var prop = new ObservablePropertySink(this, name, default_value); - _observable_properties.Add(source.OnDispatcher().Subscribe(d => prop.set(select(d)))); - return prop; - } - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => - backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// This overload makes it a little easier to access the overload where a message is supplied to the validation logic. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => - backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IReadOnlyList> validation_steps) => - backing(name, items, desired_item, select_default, EqualityComparer.Default, validation_steps); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - /// The selected_item property name. - /// The observable sequence of items. - /// The observable sequence of a desired item. - /// The fallback function to select an item by default. - /// The item-matching function used to preserve a selected item when new items arrive. - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer) => - backing(name, items, desired_item, select_default, comparer, new List>(0)); - - /// - /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - /// The selected_item property name. - /// The observable sequence of items. - /// The observable sequence of a desired item. - /// The fallback function to select an item by default. - /// The item-matching function used to preserve a selected item when new items arrive. - /// The validation steps to take when selected_item changes. - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { - var prop = new SelectorProperty(this, name, select_default, comparer, validation_steps); - attach(prop, items, desired_item); - return prop; - } - - protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func item_to_value, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { - var prop = new SelectorProperty(this, name, item_to_value, select_default, comparer, validation_steps); - attach(prop, items, desired_item); - return prop; - } - - protected void attach(SelectorProperty selector_property, IObservable> items, IObservable> desired_item) { - _observable_properties.Add(items.OnDispatcher().Subscribe(selector_property)); - _observable_properties.Add(desired_item.OnDispatcher().Subscribe(selector_property)); - } - - protected void set_dispose(IDisposable disposable) { - if (_dispose != null) throw new InvalidOperationException("Cannot set disposable twice"); - _dispose = disposable; - } - protected void set_dispose(params IDisposable[] garbage) { - set_dispose(Disposable.Create(garbage)); - } - - protected void observe_property(Property property, Action callback) => - observe_property(property, (o, n) => callback()); - - protected void observe_property(Property property, PropertyChange callback) => - concat_disposable(property.Subscribe(t => callback(t.oldval, t.newval))); - - protected T concated_disposable(T disposable) where T : IDisposable { - concat_disposable(disposable); - return disposable; - } - - protected void concat_disposable(params IDisposable[] disposables) { - if (!(_dispose is System.Reactive.Disposables.CompositeDisposable cd)) { - cd = new System.Reactive.Disposables.CompositeDisposable(); - if (_dispose != null) - cd.Add(_dispose); - _dispose = cd; - } - cd.AddRange(disposables); - } - - protected virtual void Dispose(bool disposing) { } - public void Dispose() { - Disposable.dispose(ref _dispose); - Disposable.dispose(_observable_properties_backing); - Disposable.dispose(ref _property_changed_demuxer_backing); - Dispose(true); - OnDisposed?.Invoke(true); - } - - protected class SelectorProperty : SelectorProperty { - public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) - : base(owner, prop_name, i => i, select_default, comparer, validation_steps) { } - } - - /// - /// Designed to observe an items source, and a [settings-driven] desired item. When a new desired item is observed, it will evaluate it's current state and determine if it should be assigned to the selected_item. - /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. - /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. - /// - protected class SelectorProperty : IObserver>, IObserver>, IObservable<(TValue oldval, TValue newval)> { - readonly DisposableViewModelBase _owner; - readonly string _prop_name; - readonly IReadOnlyList> _validation_steps; - readonly ObservableCollection _items = new ObservableCollection(); - readonly Func _select_default; - readonly IEqualityComparer _value_comparer; - readonly Func _item_to_value; - TValue _selected_item; - InlineUserProperty _desired_item = new InlineUserProperty(); - bool _is_user_selected_item, _is_items_source_changing; - - public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func item_to_value, Func select_default, IEqualityComparer value_comparer, IReadOnlyList> validation_steps) { - _owner = owner; - _prop_name = prop_name; - _item_to_value = item_to_value; - _select_default = select_default; - _value_comparer = value_comparer ?? EqualityComparer.Default; - _validation_steps = validation_steps; - items = new ReadOnlyObservableCollection(_items); - } - - public event SelectionChanged Changing, Changed; - - public ReadOnlyObservableCollection items { get; } - - public TValue selected_item { - get => _selected_item; - set => _set_selected_item(value, (_is_user_selected_item = !_is_items_source_changing) ? SelectionReason.UserSelectedNewValue : SelectionReason.CurrentValueWasRemoved); - } - - public IDisposable Subscribe(IObserver<(TValue oldval, TValue newval)> observer) => - Subscribe((oldval, newval, reason) => observer.OnNext((oldval, newval))); - - public IDisposable Subscribe(SelectionChanged callback) { - Changed += callback; - return Disposable.Create(() => Changed -= callback); - } - - public IObservable observe_current(bool start_now = false) { - var source = this.Select(vals => vals.newval); - if (start_now) - source = source.StartWith(selected_item); - return source; - } - - void IObserver>.OnNext(InlineUserProperty iup) { - _desired_item = iup; - _try_auto_select(); - } - void IObserver>.OnError(Exception error) { } - void IObserver>.OnCompleted() { } - - void IObserver>.OnNext(IEnumerable value) { - _is_items_source_changing = true; - if (_is_user_selected_item) { - var curr_selected_item = selected_item; - _items.sync_with(value); - if (_try_match_item(curr_selected_item, out TValue match)) { - _is_user_selected_item = true; - _set_selected_item(match, SelectionReason.CurrentValueWasRestored); - } else { - _is_user_selected_item = false; - _try_auto_select(); - } - } else { - _items.sync_with(value); - _try_auto_select(); - } - _is_items_source_changing = false; - } - void IObserver>.OnError(Exception error) { } - void IObserver>.OnCompleted() { } - - void _run_validation(TValue val) { - var invalid_steps = _validation_steps.Select(v => v.validate(val)).Where(r => !r.valid); - if (invalid_steps.Count() > 0) { - var error_msg = string.Join("\n", invalid_steps.Where(r => !string.IsNullOrEmpty(r.msg)).Select(r => r.msg)); - _owner.set_error(_prop_name, error_msg, true); - } else _owner.clear_error(_prop_name); - } - - void _try_auto_select() { - if (_is_user_selected_item) { - // if we have a user-selected item and the _desired_item for which we might want to set as the selected item - // isn't force_override, then no change - if (!_desired_item.force_override) { - return; - } - if (desired_item_valid() && _desired_item.force_override && _try_match_item(_desired_item.value, out TValue match)) { - _set_selected_item(match, SelectionReason.SettingsMandatedSelection); - return; - } - } else if (desired_item_valid() && _try_match_item(_desired_item.value, out TValue match)) { - _set_selected_item(match, SelectionReason.SettingsMandatedSelection); - return; - } - if (_try_match_item(_select_default(), out TValue default_match)) { - _set_selected_item(default_match, SelectionReason.Other); - } else { - // the _set_selected_item has never been entered, so validation has never ran, force it here - // so that if some value is required, the valdiation logic will catch it - _run_validation(selected_item); - } - bool desired_item_valid() => (_desired_item?.has_value).GetValueOrDefault(); - } - - void _set_selected_item(TValue value, SelectionReason reason) { - if (!_value_comparer.Equals(value, _selected_item)) { - Changing?.Invoke(_selected_item, value, reason); - var old = _selected_item; - _selected_item = value; - Changed?.Invoke(old, value, reason); - _owner.RaisePropertyChanged(_prop_name); - _run_validation(value); - } - } - - bool _try_match_item(TValue value, out TValue match) { - foreach (TItem item in _items) { - TValue v = _item_to_value(item); - if (_value_comparer.Equals(v, value)) { - match = v; - return true; - } - } - match = default; - return false; - } - - bool _try_match_item(TItem item, out TValue match) => - _try_match_item(_item_to_value(item), out match); - } - - public event Action OnDisposed; - } - - [Browsable(false)] - [EditorBrowsable(EditorBrowsableState.Never)] - static class NotifyDataErrorInfoExtensions { - public static IDisposable subscribe_errors_changed(this INotifyDataErrorInfo self, EventHandler callback) { - self.ErrorsChanged += callback; - return Disposable.Create(() => self.ErrorsChanged -= callback); - } - } -} +using bts.collections; + +using mbts.ui.utility; +using mbts.utils; + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Linq.Expressions; +using System.Reactive.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace mbts.ui.shell { + interface IRaiseNotifyPropertyChanged { + void raise_notify_property_changed(string prop); + } + + interface IValidationViewModel : IRaiseNotifyPropertyChanged { + void set_error(string property, string message); + void clear_error(string property); + } + + interface IProperty : IObservable<(T oldval, T newval)> { + event PropertyChange Changing, Changed; + T Value { get; set; } + } + + interface IUserProperty : IProperty { + bool setter_called { get; } + void bypass_setter(T value); + } + + public delegate void PropertyChange(T oldval, T newval); + + static class ValidationViewModelExtensions { + public static void assert(this IValidationViewModel vm, bool condition, string property, string message) { + if (condition) vm.clear_error(property); + else vm.set_error(property, message); + } + + public static IObservable subscribe_has_errors(this INotifyDataErrorInfo vm, bool start_immediately = false) => + Observable.Create(o => { + bool last_value = vm.HasErrors; + if (start_immediately) + o.OnNext(vm.HasErrors); + vm.ErrorsChanged += on_errors_changed; + return Disposable.Create(() => vm.ErrorsChanged -= on_errors_changed); + void on_errors_changed(object sender, DataErrorsChangedEventArgs e) { + if (vm.HasErrors != last_value) + o.OnNext(last_value = !last_value); + } + }); + + public static IObservable SubscribeValue(this IProperty property) => + // ensure notifications will be in on the same thread as IProperty.Subscribe (don't use .Select extension) + Observable.Create(o => property.Subscribe(ch => o.OnNext(ch.newval))); + + public static IProperty block_reentrancy(this IProperty source) => + new GatedPropertyWrapper(source); + + /// Blocks re-entrancy in setter. + class GatedPropertyWrapper : IProperty { + bool _is_updating; + readonly IProperty _source; + + public GatedPropertyWrapper(IProperty source) => + _source = source; + + public event PropertyChange Changing { add => _source.Changing += value; remove => _source.Changing -= value; } + public event PropertyChange Changed { add => _source.Changed += value; remove => _source.Changed -= value; } + + public T Value { + get => _source.Value; + set { + if (!_is_updating) { + _is_updating = true; + _source.Value = value; + _is_updating = false; + } + } + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _source.Subscribe(observer); + } + } + + public class ViewModelBase : INotifyPropertyChanged, IRaiseNotifyPropertyChanged { + public ViewModelBase() { + _props = new Lazy(() => { + return GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); + }); + } + protected void RaisePropertyChanged([CallerMemberName] string property = "") { + if (PropertyChanged != null) { + PropertyChanged(this, new PropertyChangedEventArgs(property)); + } + } + + protected void RaisePropertyChanged(params string[] properties) { + if (PropertyChanged != null) { + foreach (var prop in properties) { RaisePropertyChanged(prop); } + } + } + + void IRaiseNotifyPropertyChanged.raise_notify_property_changed(string prop) => + RaisePropertyChanged(prop); + + protected bool Set(ref T backing, T value, [CallerMemberName] string name = "") => + Set(ref backing, value, EqualityComparer.Default, name); + + protected bool Set(ref T backing, T value, [CallerMemberName] string name = "", params string[] dependent_props) { + if (Set(ref backing, value, EqualityComparer.Default, name)) { + RaisePropertyChanged(dependent_props); + return true; + } + return false; + } + + protected bool Set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName] string name = "") { + if (!comparer.Equals(backing, value)) { + backing = value; + RaisePropertyChanged(name); + return true; + } + return false; + } + + protected bool Set(ref T backing, T value, out T old_value, [CallerMemberName] string name = "") => + Set(ref backing, value, out old_value, EqualityComparer.Default, name); + + protected bool Set(ref T backing, T value, out T old_value, IEqualityComparer comparer, [CallerMemberName] string name = "") { + old_value = backing; + if (!comparer.Equals(backing, value)) { + backing = value; + RaisePropertyChanged(name); + return true; + } + return false; + } + + public event PropertyChangedEventHandler PropertyChanged; + + private Lazy _props; + + + #region Object Diffing + public interface IObjSnapshot : IDisposable { + bool revert { get; set; } + } + + public class ObjSnapshot : IObjSnapshot { + readonly ViewModelBase _target; + readonly Dictionary _snapshot; + readonly IReadOnlyList _props; + + public ObjSnapshot(ViewModelBase viewModelBase, IReadOnlyList props) { + _target = viewModelBase; + _props = props; + _snapshot = snap(); + } + + public bool revert { get; set; } + + public void Dispose() { + var cur = snap(); + foreach (var kv in cur) { + object oldv = _snapshot[kv.Key]; + object newv = cur[kv.Key]; + if (!Equals(oldv, newv)) { + var prop = kv.Key.property; + if (revert && prop.CanWrite) + prop.SetValue(_target, oldv); + _target.RaisePropertyChanged(prop.Name); + } + } + } + + Dictionary snap() => + // NOTE: in the future we can optimize prop.GetValue() if needed + _props.ToDictionaryCrushed(prop => new PropertyKeyWrapper(prop), prop => prop.GetValue(_target)); + + private class PropertyKeyWrapper : IEquatable { + public readonly PropertyInfo property; + public PropertyKeyWrapper(PropertyInfo property) => this.property = property; + public bool Equals(PropertyKeyWrapper other) => other != null && other.property.Name == property.Name; + public override bool Equals(object obj) => Equals(obj as PropertyKeyWrapper); + public override int GetHashCode() => property.Name.GetHashCode(); + } + } + + // Automatic (but shallow) property change notifications based on local object modifications + public ObjSnapshot detect_property_changes(params string[] props) { + if (props.Length == 0) return new ObjSnapshot(this, _props.Value); + else return new ObjSnapshot(this, _props.Value.Intersect(props, p => p.Name).ToList()); + } + + public ObjSnapshot detect_property_changes_except(params string[] props) { + if (props.Length == 0) return new ObjSnapshot(this, _props.Value); + else return new ObjSnapshot(this, _props.Value.Except(props, p => p.Name).ToList()); + } + #endregion + + #region automatic property + // use nameof() to add compile time checks + protected Property backing(string name, T default_value = default(T)) => + backing(name, EqualityComparer.Default, default_value); + + protected Property backing(string name, IEqualityComparer comparer, T default_value = default(T)) { + return new Property(this, name, comparer, default_value); + } + + protected Property backing(Expression> member, T default_value) { + var exp = (MemberExpression)member.Body; + return new Property(this, exp.Member.Name, default_value); + } + + // WILL invoke the get_value delegate + protected DelegateProperty backing(string name, Func get_value, params string[] invalidating_props) { + return new DelegateProperty(this, name, get_value, invalidating_props); + } + + // will NOT invoke the get_value delegate + protected DelegateProperty backing(string name, Func get_value, T default_value, params string[] invalidating_props) => + new DelegateProperty(this, name, get_value, default_value, invalidating_props); + + protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert) => + new PropertyAutoWrapper(this, name, initial_model, convert, EqualityComparer.Default); + + protected PropertyAutoWrapper backing(string name, TModel initial_model, Func convert, IEqualityComparer comparer) => + new PropertyAutoWrapper(this, name, initial_model, convert, comparer); + + protected DelegatePropertyAutoWrapper backing(string name, Func get_model, Func convert) => + new DelegatePropertyAutoWrapper(this, name, get_model, convert, EqualityComparer.Default); + + protected class Property : IProperty { + readonly string _propname; + readonly IEqualityComparer _comparer; + readonly ViewModelBase _owner; + T _value; + + public Property(ViewModelBase owner, string name, T default_value) + : this(owner, name, EqualityComparer.Default, default_value) { } + + public Property(ViewModelBase owner, string name, IEqualityComparer comparer, T default_value) { + _owner = owner; + _propname = name; + _comparer = comparer; + _value = default_value; + } + + public event PropertyChange Changing, Changed; + + public string name => _propname; + + public void set(T value) => + set_new(value); + + public bool set_new(T value) { + if (!Equals(value, _value)) { + Changing?.Invoke(_value, value); + var old = _value; + _value = value; + Changed?.Invoke(old, value); + _owner.RaisePropertyChanged(_propname); + return true; + } + return false; + } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => + Subscribe((oldval, newval) => observer.OnNext((oldval, newval))); + + public IDisposable Subscribe(PropertyChange callback) { + Changed += callback; + return Disposable.Create(() => Changed -= callback); + } + + public IObservable observe_current(bool start_immediately = false) { + var source = this.Select(vals => vals.newval); + if (start_immediately) + source = source.StartWith(() => _value); + return source; + } + + public T Value { + get { return _value; } + set { set(value); } + } + } + + protected class DelegateProperty : Property { + public DelegateProperty(ViewModelBase owner, string name, Func get_value, params string[] invalidating_props) + : this(owner, name, get_value, get_value(), invalidating_props) { } + + public DelegateProperty(ViewModelBase owner, string name, Func get_value, T default_value, params string[] invalidating_props) + : base(owner, name, default_value) { + _get_value = get_value; + if (invalidating_props != null && invalidating_props.Length > 0) { + var iprop_set = new HashSet(invalidating_props); + owner.PropertyChanged += (s, e) => { + if (iprop_set.Contains(e.PropertyName)) + refresh(); + }; + } + } + + readonly Func _get_value; + + public void refresh() => set(_get_value()); + public bool refresh_new() => set_new(_get_value()); + } + + /// + /// Inspired by ObservableAutoWrapper, a read/write TModel property is used to create a readonly TView property. + /// + protected class PropertyAutoWrapper : IObservable<((TModel model, TView view) oldval, (TModel model, TView view) newval)> { + readonly ViewModelBase _owner; + readonly Func _convert; + readonly IEqualityComparer _comparer; + readonly string _prop_name; + TModel _model; + TView _view; + + public PropertyAutoWrapper(ViewModelBase owner, string name, TModel initial_value, Func convert, IEqualityComparer comparer) { + _owner = owner; + _prop_name = name; + _model = initial_value; + _convert = convert; + _comparer = comparer; + _view = convert(_model); + } + + public event PropertyChange<(TModel model, TView view)> changing, changed; + + public string name => _prop_name; + public TModel model { get => _model; set => set(value); } + public TView view => _view; + + public void set(TModel model) => + set_new(model); + + public bool set_new(TModel model) { + if (_comparer.Equals(model, _model)) + return false; + TView new_view = _convert(model); + changing?.Invoke((_model, _view), (model, new_view)); + TView old_view = _view; + TModel old_model = _model; + _model = model; + _view = new_view; + changed?.Invoke((old_model, old_view), (_model, _view)); + _owner.RaisePropertyChanged(_prop_name); + return true; + } + + public IDisposable Subscribe(IObserver<((TModel model, TView view) oldval, (TModel model, TView view) newval)> observer) { + changed += pch; + return Disposable.Create(() => changed -= pch); + void pch((TModel, TView) o, (TModel, TView) n) => observer.OnNext((o, n)); + } + + public IObservable<(TModel model, TView view)> observe_current(bool start_immediately = false) { + var source = this.Select(vals => vals.newval); + if (start_immediately) + source = source.StartWith((_model, _view)); + return source; + } + } + + protected class DelegatePropertyAutoWrapper : PropertyAutoWrapper { + readonly Func _get_model; + + public DelegatePropertyAutoWrapper(ViewModelBase owner, string name, Func get_model, Func convert, IEqualityComparer comparer) + : base(owner, name, get_model(), convert, comparer) => _get_model = get_model; + + public void refresh() => set(_get_model()); + } + + /// + /// A thin wrapper around Property<T> that trips a 'setter_called' flag when the value is set through value-property-setter (i.e., through User interaction). + /// Note: This is class is particularly useful when a default/settings-based value arrives late, and the viewmodel must decide whether or not to override the current value. + /// + protected class UserProperty : IUserProperty { + readonly Property _prop_model; + + public UserProperty(Property prop_model) => + _prop_model = prop_model; + + public event PropertyChange Changing { add { _prop_model.Changing += value; } remove { _prop_model.Changing -= value; } } + public event PropertyChange Changed { add { _prop_model.Changed += value; } remove { _prop_model.Changed -= value; } } + + public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => _prop_model.Subscribe(observer); + public IObservable observe_current(bool start_immediately = false) => _prop_model.observe_current(start_immediately); + + public T Value { + get => _prop_model.Value; + set { + setter_called = true; + _prop_model.set(value); + } + } + public bool setter_called { get; private set; } + + /// + /// Sets the value without tripping the 'setter_called' flag. + /// + public void bypass_setter(T value) => _prop_model.set(value); + /// + /// Sets 'setter_called' to false. + /// + public void reset() => setter_called = false; + + public void on_inline_prop(InlineUserProperty inline_prop) { + if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) + bypass_setter(inline_prop.value); + } + + public void on_inline_prop(InlineUserProperty inline_prop, Func select) { + if (inline_prop.force_override || (inline_prop.has_value && !setter_called)) + bypass_setter(select(inline_prop.value)); + } + } + + #endregion + + protected class ObservablePropertySink : Property, IObserver { + public ObservablePropertySink(ViewModelBase owner, string name, T default_val) : base(owner, name, default_val) { } + public void OnCompleted() { } + public void OnError(Exception error) { } + + public void OnNext(T value) { set(value); } + } + } + + public class RequestViewCloseViewModelBase : ViewModelBase, IRequestViewClose { + public void TryClose() { + RequestClose?.Invoke(this, new EventArgs()); + } + + public event EventHandler RequestClose; + } + + public static class RequestViewCloseExtensions { + public static ICommand close_command(this shell.RequestViewCloseViewModelBase rvc) { + return new DelegateCommand(rvc.TryClose); + } + } + + public class VMValueWrapper : ViewModelBase where T : IEquatable { + public VMValueWrapper(T val) { _val = val; } + T _val; + public T value { get { return _val; } set { if (value == null || !value.Equals(_val)) { _val = value; RaisePropertyChanged(); } } } + } + + // Adds set_error and clear_error to ViewModelBase + public class ViewModelBaseWithValidation : ViewModelBase, INotifyDataErrorInfo, IValidationViewModel { + Dictionary _errors = new Dictionary(); + + protected bool assert(bool condition, [CallerMemberName] string property = "", string message = null) { + if (condition) { + clear_error(property); + return true; + } else if (!_errors.TryGetValue(property, out string result) || !string.Equals(message, result)) { + _errors[property] = message; + FireErrorsChanged(property); + } + return false; + } + + protected bool has_errors(string property) => + _errors.ContainsKey(property); + + protected void set_error(string property, string message, bool ignore_if_already_error = false) { + if (!_errors.ContainsKey(property) || !ignore_if_already_error) { + _errors[property] = message; + FireErrorsChanged(property); + } + } + void IValidationViewModel.set_error(string property, string message) => set_error(property, message); + + protected void clear_error(string property) { + if (_errors.ContainsKey(property)) { + _errors.Remove(property); + FireErrorsChanged(property); + } + } + void IValidationViewModel.clear_error(string property) => clear_error(property); + + protected async Task assert_flash_error(bool test, params string[] properties) { + if (!test) await flash_error(properties); + else { + foreach (var prop in properties) + clear_error(prop); + } + } + + protected async Task flash_error_msg(string msg, TimeSpan duration, params string[] properties) { + foreach (var prop in properties) + set_error(prop, msg); + await Task.Delay(duration); + foreach (var prop in properties) + clear_error(prop); + } + + protected async Task flash_error_msg(string msg, params string[] properties) => + await flash_error_msg(msg, mbts.spark.SparkUtils.UI.ErrorFlashDuration, properties); + + protected async Task flash_error(params string[] properties) => + await flash_error_msg(string.Empty, properties); + + protected IDisposable validation() { + IEnumerable current = _errors.Keys.ToList(); + _errors.Clear(); + return _validation(current); + } + + protected IDisposable validation(params string[] properties) { + IEnumerable current = _errors.Keys.Intersect(properties).ToList(); + foreach (var p in current) _errors.Remove(p); + return _validation(current); + } + + protected void validation_assert(bool test, string messsage, params string[] properties) { + if (!test) { + foreach (var prop in properties) { + set_error(prop, messsage); + } + } + } + + IDisposable _validation(IEnumerable validating_properties) => + Disposable.Create(() => { + foreach (var property in validating_properties) + if (!_errors.ContainsKey(property)) + FireErrorsChanged(property); + }); + + + void FireErrorsChanged(string property) { + ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(property)); + } + + #region INotifyDataErrorInfo + public event EventHandler ErrorsChanged; + + public System.Collections.IEnumerable GetErrors(string propertyName) { + if (!string.IsNullOrEmpty(propertyName)) { + if (_errors.TryGetValue(propertyName, out string error)) { + yield return error; + } + } + } + + public bool HasErrors { + get { return _errors.Count != 0; } + } + + public IEnumerable AllErrors { get { return _errors.Values; } } + #endregion + + protected Property backing(string name, T default_value, IEnumerable> validation_steps, bool validate_now = false) { + void run_validation(T val) { + foreach (var pv in validation_steps) { + (bool valid, string msg) = pv.validate(val); + assert(valid, name, msg); + } + }; + + var prop = new Property(this, name, default_value); + prop.Changed += (old_val, new_val) => run_validation(new_val); + if (validate_now) { + run_validation(prop.Value); + } + return prop; + } + + protected UserProperty user_backing(string name, T default_value = default) => + new UserProperty(backing(name, default_value)); + + protected UserProperty user_backing(Property property) => + new UserProperty(property); + + + // TODO: maybe include a revert_on_error flag? + protected class PropertyValidation { + public readonly Func validate; + + public PropertyValidation(Func validate) => + this.validate = val => (validate(val), null); + + public PropertyValidation(Func validate) => + this.validate = validate; + } + } + + public abstract class DisposableViewModelBase : ViewModelBaseWithValidation, IPropertyChangedDemuxer, IDisposable, IWillLetYouKnowWhenIDispose { + protected IDisposable _dispose = null; + List _observable_properties_backing; + List _observable_properties => _observable_properties_backing ?? (_observable_properties_backing = new List()); + PropertyChangedDemuxer _property_changed_demuxer_backing; + + IPropertyChangedDemuxer _property_changed_demuxer => + _property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this)); + + IObservable IPropertyChangedDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); + IObservable IObservableDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); + void IObserver.OnNext(PropertyChangedEventArgs value) => _property_changed_demuxer.OnNext(value); + void IObserver.OnError(Exception error) => _property_changed_demuxer.OnError(error); + void IObserver.OnCompleted() => _property_changed_demuxer.OnCompleted(); + + internal IPropertyChangedDemuxer as_demuxer() => this; + + protected Property backing(string name, IObservable source, T default_value = default(T)) { + var prop = new ObservablePropertySink(this, name, default_value); + _observable_properties.Add(source.Subscribe(prop)); + return prop; + } + + /// + /// Use this generic overload when the [T]value must be created from the [TData]data on this thread, and a simple observable.Select() call will not work. + /// Note: UI settings in particular may find this useful, as brushes and other Freezable types are not inherently thread safe. + /// + protected Property backing(string name, IObservable source, Func select, T default_value = default) { + var prop = new ObservablePropertySink(this, name, default_value); + _observable_properties.Add(source.OnDispatcher().Subscribe(d => prop.set(select(d)))); + return prop; + } + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => + backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// This overload makes it a little easier to access the overload where a message is supplied to the validation logic. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, params Func[] validation_steps) => + backing(name, items, desired_item, select_default, validation_steps.Select(v => new PropertyValidation(v)).ToList()); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IReadOnlyList> validation_steps) => + backing(name, items, desired_item, select_default, EqualityComparer.Default, validation_steps); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + /// The selected_item property name. + /// The observable sequence of items. + /// The observable sequence of a desired item. + /// The fallback function to select an item by default. + /// The item-matching function used to preserve a selected item when new items arrive. + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer) => + backing(name, items, desired_item, select_default, comparer, new List>(0)); + + /// + /// Returns a SelectorProperty<T> that observes an items source, and a desired item. When either observable ticks, it determines whether or not to assign the selected_item property. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + /// The selected_item property name. + /// The observable sequence of items. + /// The observable sequence of a desired item. + /// The fallback function to select an item by default. + /// The item-matching function used to preserve a selected item when new items arrive. + /// The validation steps to take when selected_item changes. + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { + var prop = new SelectorProperty(this, name, select_default, comparer, validation_steps); + attach(prop, items, desired_item); + return prop; + } + + protected SelectorProperty backing(string name, IObservable> items, IObservable> desired_item, Func item_to_value, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) { + var prop = new SelectorProperty(this, name, item_to_value, select_default, comparer, validation_steps); + attach(prop, items, desired_item); + return prop; + } + + protected void attach(SelectorProperty selector_property, IObservable> items, IObservable> desired_item) { + _observable_properties.Add(items.OnDispatcher().Subscribe(selector_property)); + _observable_properties.Add(desired_item.OnDispatcher().Subscribe(selector_property)); + } + + protected void set_dispose(IDisposable disposable) { + if (_dispose != null) throw new InvalidOperationException("Cannot set disposable twice"); + _dispose = disposable; + } + protected void set_dispose(params IDisposable[] garbage) { + set_dispose(Disposable.Create(garbage)); + } + + protected void observe_property(Property property, Action callback) => + observe_property(property, (o, n) => callback()); + + protected void observe_property(Property property, PropertyChange callback) => + concat_disposable(property.Subscribe(t => callback(t.oldval, t.newval))); + + protected T concated_disposable(T disposable) where T : IDisposable { + concat_disposable(disposable); + return disposable; + } + + protected void concat_disposable(params IDisposable[] disposables) { + if (!(_dispose is System.Reactive.Disposables.CompositeDisposable cd)) { + cd = new System.Reactive.Disposables.CompositeDisposable(); + if (_dispose != null) + cd.Add(_dispose); + _dispose = cd; + } + cd.AddRange(disposables); + } + + protected virtual void Dispose(bool disposing) { } + public void Dispose() { + Disposable.dispose(ref _dispose); + Disposable.dispose(_observable_properties_backing); + Disposable.dispose(ref _property_changed_demuxer_backing); + Dispose(true); + OnDisposed?.Invoke(true); + } + + protected class SelectorProperty : SelectorProperty { + public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func select_default, IEqualityComparer comparer, IReadOnlyList> validation_steps) + : base(owner, prop_name, i => i, select_default, comparer, validation_steps) { } + } + + /// + /// Designed to observe an items source, and a [settings-driven] desired item. When a new desired item is observed, it will evaluate it's current state and determine if it should be assigned to the selected_item. + /// Notes: If the user has selected an item (ie the selected_item has been assigned through the public setter), the desired item will be ignored unless force_override is true. + /// If the user has not selected an item, but the current items do not contain the desired item, it will re-evaluate whether or not to select the item when new items arrive. + /// + protected class SelectorProperty : IObserver>, IObserver>, IObservable<(TValue oldval, TValue newval)> { + readonly DisposableViewModelBase _owner; + readonly string _prop_name; + readonly IReadOnlyList> _validation_steps; + readonly ObservableCollection _items = new ObservableCollection(); + readonly Func _select_default; + readonly IEqualityComparer _value_comparer; + readonly Func _item_to_value; + TValue _selected_item; + InlineUserProperty _desired_item = new InlineUserProperty(); + bool _is_user_selected_item, _is_items_source_changing; + + public SelectorProperty(DisposableViewModelBase owner, string prop_name, Func item_to_value, Func select_default, IEqualityComparer value_comparer, IReadOnlyList> validation_steps) { + _owner = owner; + _prop_name = prop_name; + _item_to_value = item_to_value; + _select_default = select_default; + _value_comparer = value_comparer ?? EqualityComparer.Default; + _validation_steps = validation_steps; + items = new ReadOnlyObservableCollection(_items); + } + + public event SelectionChanged Changing, Changed; + + public ReadOnlyObservableCollection items { get; } + + public TValue selected_item { + get => _selected_item; + set => _set_selected_item(value, (_is_user_selected_item = !_is_items_source_changing) ? SelectionReason.UserSelectedNewValue : SelectionReason.CurrentValueWasRemoved); + } + + public IDisposable Subscribe(IObserver<(TValue oldval, TValue newval)> observer) => + Subscribe((oldval, newval, reason) => observer.OnNext((oldval, newval))); + + public IDisposable Subscribe(SelectionChanged callback) { + Changed += callback; + return Disposable.Create(() => Changed -= callback); + } + + public IObservable observe_current(bool start_now = false) { + var source = this.Select(vals => vals.newval); + if (start_now) + source = source.StartWith(selected_item); + return source; + } + + void IObserver>.OnNext(InlineUserProperty iup) { + _desired_item = iup; + _try_auto_select(); + } + void IObserver>.OnError(Exception error) { } + void IObserver>.OnCompleted() { } + + void IObserver>.OnNext(IEnumerable value) { + _is_items_source_changing = true; + if (_is_user_selected_item) { + var curr_selected_item = selected_item; + _items.sync_with(value); + if (_try_match_item(curr_selected_item, out TValue match)) { + _is_user_selected_item = true; + _set_selected_item(match, SelectionReason.CurrentValueWasRestored); + } else { + _is_user_selected_item = false; + _try_auto_select(); + } + } else { + _items.sync_with(value); + _try_auto_select(); + } + _is_items_source_changing = false; + } + void IObserver>.OnError(Exception error) { } + void IObserver>.OnCompleted() { } + + void _run_validation(TValue val) { + var invalid_steps = _validation_steps.Select(v => v.validate(val)).Where(r => !r.valid); + if (invalid_steps.Count() > 0) { + var error_msg = string.Join("\n", invalid_steps.Where(r => !string.IsNullOrEmpty(r.msg)).Select(r => r.msg)); + _owner.set_error(_prop_name, error_msg, true); + } else _owner.clear_error(_prop_name); + } + + void _try_auto_select() { + if (_is_user_selected_item) { + // if we have a user-selected item and the _desired_item for which we might want to set as the selected item + // isn't force_override, then no change + if (!_desired_item.force_override) { + return; + } + if (desired_item_valid() && _desired_item.force_override && _try_match_item(_desired_item.value, out TValue match)) { + _set_selected_item(match, SelectionReason.SettingsMandatedSelection); + return; + } + } else if (desired_item_valid() && _try_match_item(_desired_item.value, out TValue match)) { + _set_selected_item(match, SelectionReason.SettingsMandatedSelection); + return; + } + if (_try_match_item(_select_default(), out TValue default_match)) { + _set_selected_item(default_match, SelectionReason.Other); + } else { + // the _set_selected_item has never been entered, so validation has never ran, force it here + // so that if some value is required, the valdiation logic will catch it + _run_validation(selected_item); + } + bool desired_item_valid() => (_desired_item?.has_value).GetValueOrDefault(); + } + + void _set_selected_item(TValue value, SelectionReason reason) { + if (!_value_comparer.Equals(value, _selected_item)) { + Changing?.Invoke(_selected_item, value, reason); + var old = _selected_item; + _selected_item = value; + Changed?.Invoke(old, value, reason); + _owner.RaisePropertyChanged(_prop_name); + _run_validation(value); + } + } + + bool _try_match_item(TValue value, out TValue match) { + foreach (TItem item in _items) { + TValue v = _item_to_value(item); + if (_value_comparer.Equals(v, value)) { + match = v; + return true; + } + } + match = default; + return false; + } + + bool _try_match_item(TItem item, out TValue match) => + _try_match_item(_item_to_value(item), out match); + } + + public event Action OnDisposed; + } + + [Browsable(false)] + [EditorBrowsable(EditorBrowsableState.Never)] + static class NotifyDataErrorInfoExtensions { + public static IDisposable subscribe_errors_changed(this INotifyDataErrorInfo self, EventHandler callback) { + self.ErrorsChanged += callback; + return Disposable.Create(() => self.ErrorsChanged -= callback); + } + } +} From 8958507385be0df4814d6950c3ec65e893891528 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Fri, 7 Jan 2022 22:44:52 -0500 Subject: [PATCH 15/33] refactor: Make UIAdapter classes internal --- src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs | 2 +- .../spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs | 4 ++-- src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs | 4 ++-- src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs | 4 ++-- src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs | 2 +- .../spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs | 2 +- src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs | 4 ++-- 12 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs index a9fcbdf28..c82537d22 100644 --- a/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DiagnosticsUIAdapter.cs @@ -17,7 +17,7 @@ namespace mbts.ui.controls return rv; } } - public class DiagnosticsUIAdapter : IReadWriteGridAdapter + class DiagnosticsUIAdapter : IReadWriteGridAdapter { private const string _group = "Diagnostics"; private readonly VolSurfaceDisplayGridColumn _atm_straddle_col, _rr_col, _strangle_col, _put_bf_col, _call_bf_col, diff --git a/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs index 206335ed4..1bf1ba759 100644 --- a/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DriverUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class DriverUIAdapter : IReadWriteGridAdapter + class DriverUIAdapter : IReadWriteGridAdapter { private const string _group = "Driver"; private readonly VolSurfaceDisplayGridColumn _fwd_col, _ref_fwd_col, _live_driver_col, _driver_override_col; diff --git a/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs index 5495bf62f..494c97431 100644 --- a/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/DualQuadraticModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class DualQuadraticModelUIAdapter : IReadWriteGridAdapter + class DualQuadraticModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly VolSurfaceDisplayGridColumn _put_wing_strike_col, _put_slope_col, _put_curvature_col, @@ -99,4 +99,4 @@ namespace mbts.ui.controls }; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs index ca902c8c5..5390018cf 100644 --- a/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ExplicitSlopeWingUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter + class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter { private const string _group = "Wings"; private VolSurfaceDisplayGridColumn _p_wing_slope, _c_wing_slope, _p_wing_decay, _c_wing_decay; diff --git a/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs index bb1ae5a11..c7f2be58f 100644 --- a/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ImplicitSlopeWingUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter + class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter { private const string _group = "Wings"; private VolSurfaceDisplayGridColumn _p_wing_max, _c_wing_max; diff --git a/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs b/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs index 2268122b7..969f55239 100644 --- a/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/MiscColsUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class MiscColsUIAdapter : IReadWriteGridAdapter + class MiscColsUIAdapter : IReadWriteGridAdapter { private const string _group = "General"; private readonly VolSurfaceDisplayGridColumn _time_shift_col, _biz_time_output_col, _vol_time_years_output_col, _vol_time_days_per_year, diff --git a/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs b/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs index e1dcb1532..29893e269 100644 --- a/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/ParabolicVolPathUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class ParabolicVolPathUIAdapter : IReadWriteGridAdapter + class ParabolicVolPathUIAdapter : IReadWriteGridAdapter { private const string _group = "Vol Path"; private readonly VolSurfaceDisplayGridColumn _down_market_move, _down_market_vol_move, _up_market_move, _up_market_vol_move, _max_vol_increase, _max_vol_decrease; diff --git a/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs index 1696b7d74..94ef4cceb 100644 --- a/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/PolynomialModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class PolynomialModelUIAdapter : IReadWriteGridAdapter + class PolynomialModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly List> _put_cols, _call_cols; @@ -130,4 +130,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs b/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs index d43f5b90e..45f85fb85 100644 --- a/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/SplineModelUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class SplineModelUIAdapter : IReadWriteGridAdapter + class SplineModelUIAdapter : IReadWriteGridAdapter { private const string _group = "Main Curve"; private readonly List> _put_cols, _call_cols; @@ -123,4 +123,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs b/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs index 7f4c316ed..ed5d10d16 100644 --- a/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/StrikeConversionUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class StrikeConversionUIAdapter : IReadWriteGridAdapter + class StrikeConversionUIAdapter : IReadWriteGridAdapter { private const string _group = "Strike Dynamics"; private readonly VolSurfaceDisplayGridColumn _conv_fwd_slider_col, _conv_vol_slider_col, _conv_fwd_col, _conv_vol_col; diff --git a/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs b/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs index a868f8ed9..3bb4c9e22 100644 --- a/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/TwoWaySlopeVolPathUIAdapter.cs @@ -8,7 +8,7 @@ using mbts.spark; namespace mbts.ui.controls { - public class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter + class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter { private const string _group = "Vol Path"; private readonly VolSurfaceDisplayGridColumn _down_slope_col, _up_slope_col, _max_vol_inc_col, _max_vol_dec_col, _joint_speed_col; diff --git a/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs b/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs index ffe88f364..e01a66f7f 100644 --- a/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs +++ b/src/client/spark/AW2/UIAdapters/VolSurfaceUIAdapter.cs @@ -11,7 +11,7 @@ using bts; namespace mbts.ui.controls { - public class VolSurfaceUIAdapter + class VolSurfaceUIAdapter { private class MyComparerWrapper : IComparer { @@ -150,4 +150,4 @@ namespace mbts.ui.controls return rv; } } -} \ No newline at end of file +} From cd19cbf0b47424ec0143bfe84baf21716683620c Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 6 Jan 2022 17:37:02 -0500 Subject: [PATCH 16/33] Early cut of aw2 ui (most likely will have bugs) Rough around the edges, but functional enough to be a useful diagnostic tool as we iron out aw2 --- .../AnalyticsExpirationParametersVM.cs | 365 ++ .../AnalyticsExpirationParametersView.xaml | 544 +++ .../AnalyticsExpirationParametersView.xaml.cs | 68 + .../AnalyticsExpirationParametersWindow.cs | 42 + ...lyticsExpirationParametersWindowFactory.cs | 35 + .../AnalyticsParametersUIModel.cs | 40 + src/client/spark/AW2/Graph/AxisPosition.cs | 13 + .../spark/AW2/Graph/DateTimeIntervalType.cs | 12 + src/client/spark/AW2/Graph/GraphPoint.cs | 22 + src/client/spark/AW2/Graph/IVolTermsSeries.cs | 9 + .../spark/AW2/Graph/LineSeriesSettings.cs | 36 + src/client/spark/AW2/Graph/LineStyle.cs | 16 + src/client/spark/AW2/Graph/MarkerShape.cs | 11 + .../spark/AW2/Graph/ScatterSeriesSettings.cs | 44 + .../spark/AW2/Graph/VolTermsLineSeriesVM.cs | 40 + .../AW2/Graph/VolTermsScatterSeriesVM.cs | 37 + .../BTSTabularGridColumnConfiguration.cs | 5 + .../AW2/Grid/VolSurfaceDisplayUtilities.cs | 69 +- .../AW2/Grid/VolSurfaceMacroGridSettings.cs | 65 +- .../AW2/UISettings/VolSurfaceGraphSettings.cs | 153 + .../UISettings/VolSurfaceWindowSettings.cs | 46 + .../AW2/View/VolSurfaceMacroControlView.xaml | 129 + .../View/VolSurfaceMacroControlView.xaml.cs | 8 + .../AW2/View/VolSurfaceSettingsEditor.xaml | 1293 +++++++ .../AW2/View/VolSurfaceSettingsEditor.xaml.cs | 14 + .../View/VolSurfaceShellModuleContent.xaml | 146 + .../View/VolSurfaceShellModuleContent.xaml.cs | 11 + .../AW2/View/VolSurfaceTimeDecayEditor.xaml | 111 + .../View/VolSurfaceTimeDecayEditor.xaml.cs | 33 + .../spark/AW2/View/VolSurfaceView2.xaml | 649 ++++ .../spark/AW2/View/VolSurfaceView2.xaml.cs | 76 + .../spark/AW2/ViewModel/AlgoMenuItemVM.cs | 36 + .../spark/AW2/ViewModel/ExpSelectionGridVM.cs | 118 + .../Graph/VolSurfaceGraphSeriesHelper.cs | 102 + .../Graph/VolSurfaceGraphSeriesType.cs | 25 + .../AW2/ViewModel/Graph/VolSurfaceGraphVM.cs | 388 +++ .../Grid/HistoricVolSurfaceRowControl.cs | 200 ++ .../ViewModel/Grid/VolSurfaceRowContext.cs | 349 ++ .../ViewModel/Grid/VolSurfaceRowControl.cs | 372 ++ .../AW2/ViewModel/Grid/VolSurfaceRowView.cs | 6 + .../Grid/VolSurfaceSimplifiedGridVM.cs | 350 ++ .../VolSurfaceAdvancedSettingsEditorVM.cs | 74 + .../VolSurfaceGraphSettingsEditorVM.cs | 65 + .../VolSurfaceGridSettingsEditorVM.cs | 75 + .../VolSurfaceSettingsEditorVM.cs | 872 +++++ .../AW2/ViewModel/VolSurfaceEventDemux.cs | 64 + .../ViewModel/VolSurfaceGlobalParameterVM.cs | 101 + .../AW2/ViewModel/VolSurfaceMacroActionsVM.cs | 92 + .../ViewModel/VolSurfaceTimeDecayEditorVM.cs | 115 + .../spark/AW2/ViewModel/VolSurfaceVM.cs | 200 ++ .../spark/AW2/ViewModel/VolTermsGraphVM.cs | 191 + src/client/spark/AW2/VolSurfaceExtensions.cs | 36 +- src/client/spark/AW2/VolSurfaceModule.cs | 180 + src/client/spark/AW2/VolSurfaceWindow.cs | 42 + .../spark/AW2/VolSurfaceWindowFactory.cs | 33 + .../Core/Settings/SecurityExpiration.cs | 3 + .../Core/Settings/VolSurfaceSettings.cs | 66 +- src/client/spark/Images/Icons.cs | 1 + src/client/spark/Spark.csproj | 2 + src/client/spark/Themes/generic.xaml | 2 + src/client/spark/core/Bus/SparkCommands.cs | 10 +- src/client/spark/core/Bus/SparkTags.cs | 7 +- .../ObservableAggregateCollection.cs | 11 + .../spark/core/ShellInterface/IShellModule.cs | 5 + .../spark/core/Utility/ViewModelBase.cs | 11 +- .../spark/view/Controls/DIYGrid/DIYGrid.cs | 3071 +++++++++-------- .../Controls/DIYGrid/DIYGridResources.xaml | 14 + .../DIYGrid/Row/HighPerformanceRow.cs | 17 +- .../view/Controls/DIYGrid/Row/RowBase.cs | 311 +- .../view/Controls/DIYGrid/Row/RowUtils.cs | 14 + .../DIYGrid/Settings/GridColumnSettings.cs | 3 + .../DIYGrid/Settings/GridSettingsHelper.cs | 6 + .../spark/view/Controls/Graph/AxisVM.cs | 279 ++ .../spark/view/Controls/Graph/BTSGraphAxis.cs | 208 ++ .../view/Controls/Graph/BTSGraphSeries.cs | 22 + .../spark/view/Controls/Graph/BTSGraphVM.cs | 86 + .../view/Controls/Graph/BTSOxyGraph.xaml | 103 + .../view/Controls/Graph/BTSOxyGraph.xaml.cs | 311 ++ .../view/Controls/Graph/DateTimeAxisVM.cs | 90 + .../spark/view/Controls/Graph/LineSeriesVM.cs | 41 + .../spark/view/Controls/Graph/LinearAxisVM.cs | 46 + .../view/Controls/Graph/ScatterSeriesVM.cs | 53 + .../spark/view/Controls/Graph/SeriesSetVM.cs | 29 + .../spark/view/Controls/Graph/SeriesVM.cs | 132 + src/client/spark/view/Controls/TextBoxEx.xaml | 174 + .../spark/view/Controls/TextBoxEx.xaml.cs | 182 + .../view/Controls/Time/DateTimePicker.xaml.cs | 20 +- .../view/Converters/BTSColorConverter.cs | 2 +- .../Extensions/Command/FileDialogCommand.cs | 6 +- .../view/Extensions/OxyPlotExtensions.cs | 181 + .../spark/view/Extensions/WPFExtensions.cs | 10 +- .../view/Shell/ProtoBufSerializationHelper.cs | 11 + .../view/Shell/ViewModels/ShellModuleVM.cs | 3 +- .../spark/view/Utility/PropertyUpdateGate.cs | 22 +- .../spark_api/security/SecurityExtensions.cs | 10 +- .../spark_api/security/SecurityFormatter.cs | 4 + .../Extensions/EnumerableExtensions.cs | 101 +- .../Collections/Extensions/ListExtensions.cs | 90 +- src/client/spark_core/utils/BitHelper.cs | 13 + src/client/spark_core/utils/CompareUtils.cs | 5 +- .../spark_core/utils/ObservableExtensions.cs | 34 +- .../spark_core/utils/StringExtensions.cs | 23 +- .../spark_core/utils/TupleExtensions.cs | 18 +- 103 files changed, 12303 insertions(+), 1788 deletions(-) create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs create mode 100644 src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs create mode 100644 src/client/spark/AW2/Graph/AxisPosition.cs create mode 100644 src/client/spark/AW2/Graph/DateTimeIntervalType.cs create mode 100644 src/client/spark/AW2/Graph/GraphPoint.cs create mode 100644 src/client/spark/AW2/Graph/IVolTermsSeries.cs create mode 100644 src/client/spark/AW2/Graph/LineSeriesSettings.cs create mode 100644 src/client/spark/AW2/Graph/LineStyle.cs create mode 100644 src/client/spark/AW2/Graph/MarkerShape.cs create mode 100644 src/client/spark/AW2/Graph/ScatterSeriesSettings.cs create mode 100644 src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs create mode 100644 src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs create mode 100644 src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs create mode 100644 src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs create mode 100644 src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml create mode 100644 src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs create mode 100644 src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml create mode 100644 src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs create mode 100644 src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml create mode 100644 src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs create mode 100644 src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml create mode 100644 src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs create mode 100644 src/client/spark/AW2/View/VolSurfaceView2.xaml create mode 100644 src/client/spark/AW2/View/VolSurfaceView2.xaml.cs create mode 100644 src/client/spark/AW2/ViewModel/AlgoMenuItemVM.cs create mode 100644 src/client/spark/AW2/ViewModel/ExpSelectionGridVM.cs create mode 100644 src/client/spark/AW2/ViewModel/Graph/VolSurfaceGraphSeriesHelper.cs create mode 100644 src/client/spark/AW2/ViewModel/Graph/VolSurfaceGraphSeriesType.cs create mode 100644 src/client/spark/AW2/ViewModel/Graph/VolSurfaceGraphVM.cs create mode 100644 src/client/spark/AW2/ViewModel/Grid/HistoricVolSurfaceRowControl.cs create mode 100644 src/client/spark/AW2/ViewModel/Grid/VolSurfaceRowContext.cs create mode 100644 src/client/spark/AW2/ViewModel/Grid/VolSurfaceRowControl.cs create mode 100644 src/client/spark/AW2/ViewModel/Grid/VolSurfaceRowView.cs create mode 100644 src/client/spark/AW2/ViewModel/Grid/VolSurfaceSimplifiedGridVM.cs create mode 100644 src/client/spark/AW2/ViewModel/SettingsEditors/VolSurfaceAdvancedSettingsEditorVM.cs create mode 100644 src/client/spark/AW2/ViewModel/SettingsEditors/VolSurfaceGraphSettingsEditorVM.cs create mode 100644 src/client/spark/AW2/ViewModel/SettingsEditors/VolSurfaceGridSettingsEditorVM.cs create mode 100644 src/client/spark/AW2/ViewModel/SettingsEditors/VolSurfaceSettingsEditorVM.cs create mode 100644 src/client/spark/AW2/ViewModel/VolSurfaceEventDemux.cs create mode 100644 src/client/spark/AW2/ViewModel/VolSurfaceGlobalParameterVM.cs create mode 100644 src/client/spark/AW2/ViewModel/VolSurfaceMacroActionsVM.cs create mode 100644 src/client/spark/AW2/ViewModel/VolSurfaceTimeDecayEditorVM.cs create mode 100644 src/client/spark/AW2/ViewModel/VolSurfaceVM.cs create mode 100644 src/client/spark/AW2/ViewModel/VolTermsGraphVM.cs create mode 100644 src/client/spark/AW2/VolSurfaceModule.cs create mode 100644 src/client/spark/AW2/VolSurfaceWindow.cs create mode 100644 src/client/spark/AW2/VolSurfaceWindowFactory.cs create mode 100644 src/client/spark/view/Controls/Graph/AxisVM.cs create mode 100644 src/client/spark/view/Controls/Graph/BTSGraphAxis.cs create mode 100644 src/client/spark/view/Controls/Graph/BTSGraphSeries.cs create mode 100644 src/client/spark/view/Controls/Graph/BTSGraphVM.cs create mode 100644 src/client/spark/view/Controls/Graph/BTSOxyGraph.xaml create mode 100644 src/client/spark/view/Controls/Graph/BTSOxyGraph.xaml.cs create mode 100644 src/client/spark/view/Controls/Graph/DateTimeAxisVM.cs create mode 100644 src/client/spark/view/Controls/Graph/LineSeriesVM.cs create mode 100644 src/client/spark/view/Controls/Graph/LinearAxisVM.cs create mode 100644 src/client/spark/view/Controls/Graph/ScatterSeriesVM.cs create mode 100644 src/client/spark/view/Controls/Graph/SeriesSetVM.cs create mode 100644 src/client/spark/view/Controls/Graph/SeriesVM.cs create mode 100644 src/client/spark/view/Controls/TextBoxEx.xaml create mode 100644 src/client/spark/view/Controls/TextBoxEx.xaml.cs create mode 100644 src/client/spark/view/Extensions/OxyPlotExtensions.cs diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs new file mode 100644 index 000000000..7cc124e47 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersVM.cs @@ -0,0 +1,365 @@ +namespace mbts.spark { + using bts.api; + + using mbts; + using mbts.analytics; + using mbts.ui; + using mbts.ui.controls; + using mbts.ui.shell; + using mbts.ui.utility; + using mbts.utils; + + using ProtoBuf; + + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Collections.Specialized; + using System.Linq; + using System.Reactive.Linq; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + using System.Windows.Input; + + class AnalyticsExpirationParametersVM : DisposableViewModelBase { + readonly IBus _bus; + readonly AnalyticsParametersUIModel _model; + readonly ObservableCollection _parameters = new(); + + bool _auto_copy_rolls_is_checked; + bool _auto_copy_rates_is_checked; + // IRaiseCanExecuteChangedCommand _copy_roll_schedule_to_selection; + // IRaiseCanExecuteChangedCommand _copy_roll_target_to_selection; + // IRaiseCanExecuteChangedCommand _copy_settlement_price_to_selection; + // IRaiseCanExecuteChangedCommand _copy_delta_beta_to_selection; + // IRaiseCanExecuteChangedCommand _copy_vega_beta_to_selection; + // IRaiseCanExecuteChangedCommand _smart_copy_roll_target; + // IRaiseCanExecuteChangedCommand _smart_copy_riskless_rate; + + public AnalyticsExpirationParametersVM(IBus bus, AnalyticsParametersUIModel model, StartupData startup_data) { + _bus = bus ?? throw new ArgumentNullException(nameof(bus)); + _model = model ?? throw new ArgumentNullException(nameof(model)); + non_options_with_empty = new ObservableAggregateCollection( + new() { SecurityExpiration.empty }, non_options); + + if (startup_data != null) { + if (!startup_data.selected_symbols.is_null_or_empty()) { + checked_symbols.AddRange(startup_data.selected_symbols); + } + auto_copy_rolls_is_checked = startup_data.auto_copy_rolls_is_checked; + auto_copy_rates_is_checked = startup_data.auto_copy_rates_is_checked; + } + + + dialog_skirt_items.Add(new DialogSkirtItem("Commit", + new AsyncCommand(async _ => { + var param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag) + .StopAfter(TimeSpan.FromSeconds(30)) + .FirstOrDefaultAsync(); + if (param_map != null) { + _model.commit(rows.Select(_from_row)); + } + }))); + + dialog_skirt_items.Add(new DialogSkirtItem("Revert", new DelegateCommand(_ => { + foreach (var r in rows) { + r.revert(); + } + }))); + + checked_symbols.CollectionChanged += _on_checked_symbols_changed; + _model.on_expiration_parameters += sync_params; + + _dispose = Disposable.Create( + ObservableAutoWrapper.connect(_parameters, rows, _to_row, r => r.Dispose()), + Disposable.Create(() => { + checked_symbols.CollectionChanged -= _on_checked_symbols_changed; + _model.on_expiration_parameters -= sync_params; + _parameters.Clear(); + rows.DisposeAll(); + })); + init_async().ignore(); + + async Task init_async() { + var initial_param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag).FirstOrDefaultAsync(); + if (initial_param_map != null) { + sync_params(initial_param_map); + } + } + + void sync_params(AnalyticsExpirationParametersMap param_map) { + _parameters.sync_with(param_map.get_sorted_exps().Select(exp => param_map.get_parameter(exp))); + non_options.sync_with(param_map.get_sorted_exps().Where(exp => exp.security_type != SecurityType.Option)); + //this of course assumes rows are sorted by Exp! + rows.GroupBy(r => r.security.expiration.Month).ForEach(exp_group => { + exp_group.ForEach(r => r.is_last_row_of_month_group = false); + exp_group.ElementAt(exp_group.Count() - 1).is_last_row_of_month_group = true; + }); + + List uniq = rows.Select(x => x.security.symbol).Distinct().ToList(); + uniq.Sort(); + // the data source for the MSDD (contiains unique symbol names + // and set the initial selection to all + distinct_symbols.sync_with(uniq); + if (checked_symbols.Count == 0) { + // check all the symbols in the first load + checked_symbols.sync_with(uniq); + // the data source for the DataGrid, filtered according to the selected rows in the MSDD + filtered_for_visible_rows.sync_with(rows); + } else { + // the form has just been commited, but rather than sync_with the original row collection, + // which will reset the grid to all symbols, we need to sync_with the checked symbols again to reset + // the red outline of the cell + filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol))); + } + } + } + + public ObservableCollection non_options { get; } = new(); + public ObservableCollection non_options_with_empty { get; } = new(); + public ObservableCollection filtered_for_visible_rows { get; } = new(); + public ObservableCollection checked_symbols { get; } = new(); + public ObservableCollection distinct_symbols { get; } = new(); + public ObservableCollection rows { get; } = new(); + public ObservableCollection selected_rows { get; } = new(); + public ObservableCollection dialog_skirt_items { get; } = new(); + + public bool auto_copy_rolls_is_checked { + get => _auto_copy_rolls_is_checked; + set => Set(ref _auto_copy_rolls_is_checked, value); + } + + public bool auto_copy_rates_is_checked { + get => _auto_copy_rates_is_checked; + set => Set(ref _auto_copy_rates_is_checked, value); + } + + ExpParamsRow _to_row(AnalyticsExpirationParameters exp_params) => + new(exp_params, this); + + AnalyticsExpirationParameters _from_row(ExpParamsRow row) => + new(row.security, row.driver, row.deliverable.is_empty() ? null : row.deliverable, row.roll_schedule.is_empty() ? null : row.roll_schedule, row.roll_target, row.riskless_rate, row.settlement_price, row.delta_beta, row.vega_beta); + + public StartupData get_state() => + new() { + selected_symbols = checked_symbols.Cast().ToArray(), + auto_copy_rates_is_checked = auto_copy_rates_is_checked, + auto_copy_rolls_is_checked = auto_copy_rolls_is_checked + }; + + void _on_checked_symbols_changed(object sender, NotifyCollectionChangedEventArgs e) => + filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol))); + + public class ExpParamsRow : DisposableViewModelBase, AnalyticsExpirationParametersView.IExpParamsRow { + readonly AnalyticsExpirationParameters _original_params; + readonly AnalyticsExpirationParametersVM _owner; + readonly Property _roll_schedule; + readonly Property _roll_schedule_dirty; + + double _roll_target; + double _riskless_rate; + double _settlement_price; + double _delta_beta; + double _vega_beta; + SecurityExpiration _driver; + SecurityExpiration _deliverable; + bool _is_last_row_of_month_group; + + IRaiseCanExecuteChangedCommand _copy_driver_to_selection; + IRaiseCanExecuteChangedCommand _copy_deliverable_to_selection; + readonly ObservantCommand _smart_copy_roll_target_cmd; + readonly ObservantCommand _smart_copy_riskless_rate_cmd; + + public ExpParamsRow(AnalyticsExpirationParameters param, AnalyticsExpirationParametersVM owner) { + _original_params = param; + _owner = owner; + security = param.security; + _driver = param.driver_security; + _deliverable = param.deliverable_security; + _roll_schedule = backing(nameof(roll_schedule), param.roll_schedule_expiration); + _roll_schedule_dirty = backing( + nameof(roll_schedule_dirty), + _roll_schedule.observe_current(true) + .Select(rs => !rs.Equals(_original_params.roll_schedule_expiration))); + _roll_target = param.roll_target; + _riskless_rate = param.riskless_rate; + _settlement_price = param.settlement_price; + _delta_beta = param.delta_beta; + _vega_beta = param.vega_beta; + _delta_beta = param.delta_beta; + _vega_beta = param.vega_beta; + + _smart_copy_roll_target_cmd = new ObservantCommand(_smart_copy_roll_target); + _smart_copy_riskless_rate_cmd = new ObservantCommand(_smart_copy_riskless_rate); + + _dispose = Disposable.Create( + _roll_schedule.observe_current(true) + .CombineLatest(_roll_schedule_dirty.observe_current(true), (rs, rs_dirty) => (rs, rs_dirty)) + .Select(tup => !tup.rs.is_empty() && !tup.rs_dirty) + .Subscribe(new CompositeObserver(_smart_copy_roll_target_cmd, _smart_copy_riskless_rate_cmd))); + } + + public SecurityExpiration security { get; } + public SecurityExpiration driver { get => _driver; set => Set(ref _driver, value); } + public SecurityExpiration deliverable { get => _deliverable; set => Set(ref _deliverable, value); } + public SecurityExpiration roll_schedule { get => _roll_schedule.Value; set => _roll_schedule.Value = value; } + + public bool is_last_row_of_month_group { + get => _is_last_row_of_month_group; + set => Set(ref _is_last_row_of_month_group, value); + } + + public double roll_target { + get => _roll_target; + set => _handle_input(_original_params.roll_target, ref _roll_target, value); + } + + public double riskless_rate { + get => _riskless_rate; + set => _handle_input(_original_params.riskless_rate, ref _riskless_rate, value); + } + + public double settlement_price { + get => _settlement_price; + set => _handle_input(_original_params.settlement_price, ref _settlement_price, value); + } + + public double delta_beta { + get => _delta_beta; + set => _handle_input(_original_params.delta_beta, ref _delta_beta, value); + } + + public double vega_beta { + get => _vega_beta; + set => _handle_input(_original_params.vega_beta, ref _vega_beta, value); + } + + public bool driver_dirty => !_driver.Equals(_original_params.driver_security); + public bool deliverable_dirty => !_deliverable.Equals(_original_params.deliverable_security); + public bool roll_schedule_dirty => !_roll_schedule.Equals(_original_params.roll_schedule_expiration); + public bool roll_target_dirty => !_roll_target.Equals(_original_params.roll_target); + public bool riskless_rate_dirty => !_riskless_rate.Equals(_original_params.riskless_rate); + public bool settlement_price_dirty => !_settlement_price.Equals(_original_params.settlement_price); + public bool delta_beta_dirty => !_delta_beta.Equals(_original_params.delta_beta); + public bool vega_beta_dirty => !_vega_beta.Equals(_original_params.vega_beta); + + public ICommand copy_driver_to_selection_cmd => _copy_driver_to_selection ??= new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.driver = driver; + r.RaisePropertyChanged(nameof(r.driver)); + } + }); + + public ICommand copy_deliverable_to_selection_cmd => _copy_deliverable_to_selection ??= new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.deliverable = deliverable; + r.RaisePropertyChanged(nameof(r.deliverable)); + } + }); + + public ICommand copy_roll_schedule_to_selection_cmd => new DelegateCommand(_ => { + foreach (var r in _get_selected_rows()) { + r.roll_schedule = roll_schedule; + r.RaisePropertyChanged(nameof(r.roll_schedule)); + } + }); + + public ICommand copy_roll_target_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.roll_target = roll_target; + } + }); + + public ICommand copy_riskless_rate_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.riskless_rate = riskless_rate; + } + }); + + public ICommand copy_settlement_price_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.settlement_price = settlement_price; + } + }); + + public ICommand copy_delta_beta_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.delta_beta = delta_beta; + } + }); + + public ICommand copy_vega_beta_to_selection_cmd => new DelegateCommand(() => { + foreach (var r in _get_selected_rows()) { + r.vega_beta = vega_beta; + } + }); + + public ICommand smart_copy_roll_target_cmd => _smart_copy_roll_target_cmd; + public ICommand smart_copy_riskless_rate_cmd => _smart_copy_riskless_rate_cmd; + + public void revert() { + driver = _original_params.driver_security; + deliverable = _original_params.deliverable_security; + roll_schedule = _original_params.roll_schedule_expiration; + roll_target = _original_params.roll_target; + riskless_rate = _original_params.riskless_rate; + settlement_price = _original_params.settlement_price; + delta_beta = _original_params.delta_beta; + vega_beta = _original_params.vega_beta; + } + + void _handle_input(double orig, ref double current, double next, [CallerMemberName] string prop = "") { + if (current.Equals(next)) { + return; + } + bool raise_dirty = current.Equals(orig) != next.Equals(orig); + current = next; + RaisePropertyChanged(prop); + if (raise_dirty) { + RaisePropertyChanged(prop + "_dirty"); + } + if (prop == nameof(roll_target) && _smart_copy_roll_target_cmd.CanExecute(null) && _owner.auto_copy_rolls_is_checked) { + _smart_copy_roll_target(); + } + if (prop == nameof(riskless_rate) && _smart_copy_riskless_rate_cmd.CanExecute(null) && _owner.auto_copy_rates_is_checked) { + _smart_copy_riskless_rate(); + } + } + + IEnumerable _get_selected_rows() => + _owner.selected_rows.OfType().ToList(); + + IEnumerable _get_smart_copy_roll_target_rows() { + var target_exps = _owner._model.get_smart_copy_roll_exps(_original_params); + var target_rows = _owner.rows.Where(r => target_exps.Contains(r.security)); + return target_rows; + } + + void _smart_copy_roll_target() { + foreach (var r in _get_smart_copy_roll_target_rows()) { + r.roll_target = roll_target; + } + } + + void _smart_copy_riskless_rate() { + foreach (var r in _get_smart_copy_roll_target_rows()) { + r.riskless_rate = riskless_rate; + } + } + } + + [ProtoContract] + public class StartupData { + public const int VERSION = 1; + + [ProtoMember(10)] + public string[] selected_symbols; + + [ProtoMember(20)] + public bool auto_copy_rates_is_checked; + + [ProtoMember(30)] + public bool auto_copy_rolls_is_checked; + } + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml new file mode 100644 index 000000000..ceee7bce0 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml @@ -0,0 +1,544 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs new file mode 100644 index 000000000..ed8e31abe --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersView.xaml.cs @@ -0,0 +1,68 @@ +namespace mbts.ui.shell { + using bts.api; + + using System; + using System.Windows; + using System.Windows.Controls; + using System.Windows.Data; + using System.Windows.Input; + + /// + /// Interaction logic for AnalyticsExpirationParametersView.xaml + /// + partial class AnalyticsExpirationParametersView : UserControl { + public AnalyticsExpirationParametersView() => + InitializeComponent(); + + public interface IExpParamsRow { + ICommand copy_driver_to_selection_cmd { get; } + ICommand copy_deliverable_to_selection_cmd { get; } + ICommand copy_roll_schedule_to_selection_cmd { get; } + ICommand copy_roll_target_to_selection_cmd { get; } + ICommand copy_riskless_rate_to_selection_cmd { get; } + ICommand copy_settlement_price_to_selection_cmd { get; } + ICommand copy_delta_beta_to_selection_cmd { get; } + ICommand copy_vega_beta_to_selection_cmd { get; } + ICommand smart_copy_roll_target_cmd { get; } + } + + void grid_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e) { + if (e.OriginalSource is not FrameworkElement el) { + return; + } + var cell = el.find_ancestor_of_type(); + if (cell?.ContextMenu is not ContextMenu cm || cell.DataContext is not IExpParamsRow row) { + return; + } + cm.DataContext = row; + cm.IsOpen = true; + e.Handled = true; + } + } + + class ExpTextConverter : IValueConverter { + public ExpTextConverter() { + NullOrEmptyText = "None"; + } + + public bool ShowType { get; set; } + public bool ShowSymbol { get; set; } + public bool MapExp { get; set; } + public string NullOrEmptyText { get; set; } + + public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { + var exp = value as SecurityExpiration; + if (exp == null || exp.is_empty()) { + return NullOrEmptyText; + } + return ShowSymbol ? + SecurityFormatter.format_future(exp.symbol, exp.expiration) : + DateFormatter.Format(exp.expiration, DateFormat.MonthCodeLastDigitYear); + } + + public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { + throw new NotImplementedException(); + } + } + +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs new file mode 100644 index 000000000..5aced279e --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindow.cs @@ -0,0 +1,42 @@ +namespace mbts.spark { + using bts.api; + using bts.spark; + + using mbts.ui.shell; + + using System; + using System.Windows; + + class AnalyticsExpirationParametersWindow : SparkWindow { + const string _window_type = nameof(AnalyticsExpirationParametersWindow); + + readonly Lazy _model; + readonly Lazy _vm; + + public AnalyticsExpirationParametersWindow( + IBus bus, AnalyticsExpirationParametersWindowFactory factory, AnalyticsExpirationParametersVM.StartupData startup_data) + : base("Analytics Exp Params", bus, factory) { + _model = new Lazy(() => new AnalyticsParametersUIModel(_bus)); + _vm = new Lazy( + () => new AnalyticsExpirationParametersVM(bus, _model.Value, startup_data)); + _dispose = Disposable.Create(() => { + if (_vm.IsValueCreated) { + _vm.Value.Dispose(); + } + if (_model.IsValueCreated) { + _model.Value.Dispose(); + } + }); + } + + public override string window_type => _window_type; + + public override AnalyticsExpirationParametersVM.StartupData SaveState => + _vm.IsValueCreated ? _vm.Value.get_state() : null; + + public override UIElement Content => + new AnalyticsExpirationParametersView { + DataContext = _vm.Value + }; + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs new file mode 100644 index 000000000..714d57151 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsExpirationParametersWindowFactory.cs @@ -0,0 +1,35 @@ +namespace mbts.spark { + using bts.api; + using bts.shell; + + using mbts.ui; + + using System; + using System.Linq; + using System.Reactive.Linq; + using System.Threading.Tasks; + + class AnalyticsExpirationParametersWindowFactory : ShellWindowFactory { + readonly IBus _bus; + + public AnalyticsExpirationParametersWindowFactory(IShellModule module, IBus bus) + : base(module, "Analytics Exp Params") { + _bus = bus; + _dispose = bus.subscribe(SparkTags.show_analytics_exp_params).OnDispatcher().Subscribe(_show); + } + + public override Task load(AnalyticsExpirationParametersVM.StartupData state) => + Task.FromResult(_create(state)); + + void _show(SparkTags.Nothing _) => + _bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData())); + + void _show(SecurityCriteria security_criteria) => + _bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData { + selected_symbols = (security_criteria?.clauses?.FirstOrDefault())?.symbols ?? Array.Empty() + })); + + IShellWindow _create(AnalyticsExpirationParametersVM.StartupData startup_data) => + new AnalyticsExpirationParametersWindow(_bus, this, startup_data); + } +} diff --git a/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs b/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs new file mode 100644 index 000000000..e330ff160 --- /dev/null +++ b/src/client/spark/AW2/AnalyticsParameters/AnalyticsParametersUIModel.cs @@ -0,0 +1,40 @@ +namespace mbts.spark { + using bts.api; + + using mbts; + using mbts.analytics; + + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + class AnalyticsParametersUIModel : IDisposable { + AnalyticsExpirationParametersMap _curr_val = null; + readonly IBus _bus; + readonly IDisposable _sub; + + public event Action on_expiration_parameters; + + public AnalyticsParametersUIModel(IBus bus) { + _bus = bus; + _sub = _bus.subscribe(SparkTags.ExpirationParametersInputTag) + .Subscribe(d => on_expiration_parameters?.Invoke(d)); + } + + public void commit(IEnumerable data) => + _bus.post(SparkTags.ExpirationParametersCommitTag, data); + + public IEnumerable get_smart_copy_roll_exps(AnalyticsExpirationParameters source) { + if (_curr_val != null) { + foreach (var kv in _curr_val.exp_map) + if (kv.Value.roll_schedule_expiration.Equals(source.roll_schedule_expiration)) + yield return kv.Key; + } + } + + public void Dispose() => + _sub.Dispose(); + } +} diff --git a/src/client/spark/AW2/Graph/AxisPosition.cs b/src/client/spark/AW2/Graph/AxisPosition.cs new file mode 100644 index 000000000..86a005fc6 --- /dev/null +++ b/src/client/spark/AW2/Graph/AxisPosition.cs @@ -0,0 +1,13 @@ +namespace mbts.spark { + enum AxisPosition { + None, + TopLeftToRight, + TopRightToLeft, + BottomLeftToRight, + BottomRightToLeft, + LeftTopToBottom, + LeftBottomToTop, + RightTopToBottom, + RightBottomToTop + } +} diff --git a/src/client/spark/AW2/Graph/DateTimeIntervalType.cs b/src/client/spark/AW2/Graph/DateTimeIntervalType.cs new file mode 100644 index 000000000..ee21d1c7c --- /dev/null +++ b/src/client/spark/AW2/Graph/DateTimeIntervalType.cs @@ -0,0 +1,12 @@ +namespace mbts.spark { + enum DateTimeIntervalType { + Auto, + Seconds, + Minutes, + Hours, + Days, + Weeks, + Months, + Years + } +} diff --git a/src/client/spark/AW2/Graph/GraphPoint.cs b/src/client/spark/AW2/Graph/GraphPoint.cs new file mode 100644 index 000000000..f63b48ad2 --- /dev/null +++ b/src/client/spark/AW2/Graph/GraphPoint.cs @@ -0,0 +1,22 @@ +namespace mbts.spark { + using mbts.ui.shell; + + /// ** BTSGraphPoint in edge ** + /// + /// Represents a point in a graph + /// + class GraphPointVM : ViewModelBase { + object _x; + object _y; + + public GraphPointVM() { } + + public GraphPointVM(object x, object y) { + this.x = x; + this.x = y; + } + + public object x { get => _x; set => Set(ref _x, value); } + public object y { get => _y; set => Set(ref _y, value); } + } +} diff --git a/src/client/spark/AW2/Graph/IVolTermsSeries.cs b/src/client/spark/AW2/Graph/IVolTermsSeries.cs new file mode 100644 index 000000000..b96af2d69 --- /dev/null +++ b/src/client/spark/AW2/Graph/IVolTermsSeries.cs @@ -0,0 +1,9 @@ +namespace mbts.spark { + using System; + using System.Collections.Generic; + + interface IVolTermsSeries { + bool is_committed { get; } + void update_points(IReadOnlyDictionary vol_map); + } +} diff --git a/src/client/spark/AW2/Graph/LineSeriesSettings.cs b/src/client/spark/AW2/Graph/LineSeriesSettings.cs new file mode 100644 index 000000000..798436597 --- /dev/null +++ b/src/client/spark/AW2/Graph/LineSeriesSettings.cs @@ -0,0 +1,36 @@ +namespace mbts.spark { + using mbts.ui; + + using ProtoBuf; + + using System; + + [ProtoContract] + class LineSeriesSettings : IEquatable, ICloneable { + [ProtoMember(1)] + public LineStyle line_style { get; set; } + [ProtoMember(2)] + public double stroke_thickness { get; set; } + [ProtoMember(3)] + public BTSColor color { get; set; } + + public object Clone() => + new LineSeriesSettings { + line_style = line_style, + stroke_thickness = stroke_thickness, + color = color.clone() + }; + + public bool Equals(LineSeriesSettings other) => + other != null && + line_style == other.line_style && + stroke_thickness.Equals(other.stroke_thickness) && + color == other.color; + + public override bool Equals(object obj) => + Equals(obj as LineSeriesSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/Graph/LineStyle.cs b/src/client/spark/AW2/Graph/LineStyle.cs new file mode 100644 index 000000000..236b45027 --- /dev/null +++ b/src/client/spark/AW2/Graph/LineStyle.cs @@ -0,0 +1,16 @@ +namespace mbts.spark { + enum LineStyle { + None, + Solid, + Dashed, + Dot, + DashDot, + DashDashDot, + DashDotDot, + DashDashDotDot, + LongDash, + LongDashDot, + LongDashDotDot, + Automatic + }; +} diff --git a/src/client/spark/AW2/Graph/MarkerShape.cs b/src/client/spark/AW2/Graph/MarkerShape.cs new file mode 100644 index 000000000..551282546 --- /dev/null +++ b/src/client/spark/AW2/Graph/MarkerShape.cs @@ -0,0 +1,11 @@ +namespace mbts.spark { + enum MarkerShape { + None, + Circle, + Cross, Diamond, + Plus, + Square, + Star, + Triangle + } +} diff --git a/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs b/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs new file mode 100644 index 000000000..fd7b53b33 --- /dev/null +++ b/src/client/spark/AW2/Graph/ScatterSeriesSettings.cs @@ -0,0 +1,44 @@ +namespace mbts.spark { + using mbts.ui; + + using ProtoBuf; + + using System; + + [ProtoContract] + class ScatterSeriesSettings : IEquatable, ICloneable { + public ScatterSeriesSettings() { } + + public ScatterSeriesSettings(MarkerShape shape, double size, BTSColor color) { + this.shape = shape; + this.size = size; + this.color = color; + } + + [ProtoMember(1)] + public MarkerShape shape { get; set; } + [ProtoMember(2)] + public double size { get; set; } + [ProtoMember(3)] + public BTSColor color { get; set; } + + public object Clone() => + new ScatterSeriesSettings { + shape = shape, + size = size, + color = color.clone() + }; + + public bool Equals(ScatterSeriesSettings other) => + other != null && + shape == other.shape && + size.Equals(other.size) && + color == other.color; + + public override bool Equals(object obj) => + Equals(obj as ScatterSeriesSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs b/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs new file mode 100644 index 000000000..05e1e9f5d --- /dev/null +++ b/src/client/spark/AW2/Graph/VolTermsLineSeriesVM.cs @@ -0,0 +1,40 @@ +namespace mbts.spark { + using bts.collections; + + using mbts.ui; + + using System; + using System.Collections.Generic; + using System.Linq; + + /// ** VolTermsLineSeries in edge ** + /// + /// Represents a scatter series in a graph + /// + class VolTermsLineSeriesVM : LineSeriesVM, IVolTermsSeries { + bool _is_committed; + // public VolTermsLineSeriesVM(bool is_committed) { + // this.is_committed = is_committed; + // name = is_committed ? "Committed" : "Candidate"; + // is_visible = true; + // color = BTSColors.VolSurfaceGraph.main_curve; + // line_style = is_committed ? LineStyle.Solid : LineStyle.Dashed; + // stroke_thickness = 1.5; + // } + + public bool is_committed { + get => _is_committed; + set { + if (Set(ref _is_committed, value)) { + name = value ? "Committed" : "Candidate"; + } + } + } + + public void update_points(IReadOnlyDictionary vol_map) => + points.SetItems(vol_map + .Where(kv => !double.IsNaN(kv.Value)) + .OrderBy(kv => kv.Key) + .Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value))); + } +} diff --git a/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs b/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs new file mode 100644 index 000000000..5f08d7f8f --- /dev/null +++ b/src/client/spark/AW2/Graph/VolTermsScatterSeriesVM.cs @@ -0,0 +1,37 @@ +namespace mbts.spark { + using bts.collections; + + using mbts.ui; + + using System; + using System.Collections.Generic; + using System.Linq; + + class VolTermsScatterSeriesVM : ScatterSeriesVM, IVolTermsSeries { + bool _is_committed; + + // public VolTermsScatterSeriesVM(bool is_committed) { + // this.is_committed = is_committed; + // name = is_committed ? "Committed" : "Candidate"; + // is_visible = true; + // marker_color = BTSColors.VolSurfaceGraph.main_curve_atm; + // marker_shape = MarkerShape.Circle; + // marker_size = 3.0; + // } + + public bool is_committed { + get => _is_committed; + set { + if (Set(ref _is_committed, value)) { + name = value ? "Committed" : "Candidate"; + } + } + } + + public void update_points(IReadOnlyDictionary vol_map) => + points.SetItems(vol_map + .Where(kv => !double.IsNaN(kv.Value)) + .OrderBy(kv => kv.Key) + .Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value))); + } +} diff --git a/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs b/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs index 004e73eb0..a90d9a963 100644 --- a/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs +++ b/src/client/spark/AW2/Grid/Settings/BTSTabularGridColumnConfiguration.cs @@ -24,6 +24,11 @@ namespace mbts.ui.controls header_font_weight = System.Drawing.FontStyle.Bold; wpf_width = Double.NaN; } + + internal BTSTabularGridColumnConfiguration(mbts.ui.settings.GridColumnSettings settings) { + /// TODO (maybe): need to resolve diffs between this class and + } + [ProtoMember(1)] public string name { get; set; } [ProtoMember(2)] diff --git a/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs b/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs index 68d18bc23..d95f47dbf 100644 --- a/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs +++ b/src/client/spark/AW2/Grid/VolSurfaceDisplayUtilities.cs @@ -4,28 +4,22 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace mbts.ui.controls -{ - public class VolSurfaceDisplayUtilities - { - public static double parse_double(object obj) - { +namespace mbts.ui.controls { + class VolSurfaceDisplayUtilities { + public static double parse_double(object obj) { obj = obj ?? Double.NaN; double rv = obj is Double ? (double)obj : (Double.TryParse(obj.ToString(), out rv) ? rv : Double.NaN); return rv; } - public static bool parse_boolean(object obj, bool def_value) - { + public static bool parse_boolean(object obj, bool def_value) { bool rv; rv = Boolean.TryParse(obj == null ? String.Empty : obj.ToString(), out rv) ? rv : def_value; return rv; } - public static Func get_parse_double(double multiplier) - { - return (text) => - { + public static Func get_parse_double(double multiplier) { + return (text) => { double rv = Double.NaN; rv = Double.TryParse(text, out rv) ? rv : Double.NaN; rv /= multiplier; @@ -33,45 +27,35 @@ namespace mbts.ui.controls }; } - public static Func get_double_tostring(double tick_base, double tick_interval, double multiplier) - { - return (data) => - { - if (data != null && data is double) - { + public static Func get_double_tostring(double tick_base, double tick_interval, double multiplier) { + return (data) => { + if (data != null && data is double) { double d_data = (double)data; d_data *= multiplier; return Double.IsNaN(d_data) ? String.Empty : _to_string(d_data, tick_base, tick_interval); - } - else + } else return String.Empty; }; } - public static Func get_double_tickmove(double tick_base, double tick_move, double multiplier) - { - return (data, is_up) => - { - if (data != null && data is double) - { + public static Func get_double_tickmove(double tick_base, double tick_move, double multiplier) { + return (data, is_up) => { + if (data != null && data is double) { double d_data = (double)data; d_data *= multiplier; d_data = is_up ? d_data + (tick_move / tick_base) : d_data - (tick_move / tick_base); d_data /= multiplier; return d_data; - } - else + } else return data; }; } public static VolSurfaceDisplayGridColumn get_double_output_col(string group, string name, string display_name, double tick_base, double tick_interval, double multiplier, - VolSurfaceMacroGridSettings grid_settings) - { + VolSurfaceMacroGridSettings grid_settings) { BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings); - if (col_config != null) - { + if (col_config != null) { _assign(col_config.tick_base, ref tick_base); _assign(col_config.tick_interval, ref tick_interval); _assign(col_config.multiplier, ref multiplier); @@ -79,15 +63,13 @@ namespace mbts.ui.controls return new VolSurfaceDisplayGridTextOutputColumn(group, name, display_name, null, get_double_tostring(tick_base, tick_interval, multiplier), get_parse_double(multiplier)); - } + } public static VolSurfaceDisplayGridColumn get_double_input_col(string group, string name, string display_name, double tick_base, double tick_interval, double tick_move, double multiplier, - VolSurfaceMacroGridSettings grid_settings) - { + VolSurfaceMacroGridSettings grid_settings) { BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings); - if (col_config != null) - { + if (col_config != null) { _assign(col_config.tick_base, ref tick_base); _assign(col_config.tick_interval, ref tick_interval); _assign(col_config.tick_move, ref tick_move); @@ -99,20 +81,17 @@ namespace mbts.ui.controls get_double_tickmove(tick_base, tick_move, multiplier)); } - private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting) - { - return grid_setting != null ? grid_setting.get_col_setting(col_name) : null; + private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting) { + return grid_setting != null ? grid_setting.get_cell_conf(col_name) : null; } - private static string _to_string (double d, double tick_base, double tick_interval) - { - return d.ToString(); + private static string _to_string(double d, double tick_base, double tick_interval) { + return d.ToString(); // TODO // return TickConverter2.to_tick(d, new TickConverter2.TickTypeInfo(tick_base == 100.0, (int)tick_base, tick_interval, false)); } - private static void _assign(double d, ref double v) - { + private static void _assign(double d, ref double v) { if (_is_valid(d)) v = d; } diff --git a/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs b/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs index abad18f24..f4466910f 100644 --- a/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs +++ b/src/client/spark/AW2/Grid/VolSurfaceMacroGridSettings.cs @@ -1,34 +1,43 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using mbts; -using mbts.ui.controls; -using mbts.ui.shell; +namespace mbts.ui.controls { + using System; + using System.Collections.Generic; + using System.Linq; -namespace mbts.ui.controls -{ + using mbts.ui.settings; + using mbts.ui.shell; -[ProtoBuf.ProtoContract()] - public class VolSurfaceMacroGridSettings : ICloneable - { - [ProtoBuf.ProtoMember(1)] - public BTSTabularGridConfiguration configuration { get; set; } + using ProtoBuf; - public object Clone() { - return ProtoBufSerializationHelper.clone_protobuf(this); + [ProtoContract] + class VolSurfaceMacroGridSettings : ICloneable { + public static VolSurfaceMacroGridSettings Default => + new() { + configuration = new GridSettings() + }; + + [ProtoMember(1)] + public GridSettings configuration { get; set; } + + /// This should be the same size as ; + /// the cell configurations are associated with the + /// in the same corresponding index. + [ProtoMember(2)] + public List cell_settings { get; } = new List(); + + public GridColumnSettings get_col_setting(string col_name) => + GridSettingsHelper.try_find_column(configuration.columns, col_name, out var res) ? res : null; + + public BTSTabularGridCellConfiguration get_cell_conf(string col_name) { + if (cell_settings.Count != configuration.columns.Count) { + throw new InvalidOperationException( + $"{nameof(cell_settings)} doesn't have the same number of " + + $"elements as {nameof(configuration)}.${nameof(GridSettings.columns)}"); + } + return GridSettingsHelper.try_find_column(configuration.columns, col_name, out var _, out var idx) ? + cell_settings[idx] : null; } - private IDictionary _col_setting_map = null; - - public BTSTabularGridCellConfiguration get_col_setting(string col_name) - { - if (_col_setting_map == null) - _col_setting_map = configuration != null ? configuration.column_configurations.ToDictionary(c => c.name, c => c.cell_configuration) : new Dictionary(); - BTSTabularGridCellConfiguration rv = _col_setting_map.TryGetValue(col_name, out rv) ? rv : null; - return rv; - } + public object Clone() => + ProtoBufSerializationHelper.clone_protobuf(this); } - -} \ No newline at end of file +} diff --git a/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs b/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs new file mode 100644 index 000000000..31e7c75aa --- /dev/null +++ b/src/client/spark/AW2/UISettings/VolSurfaceGraphSettings.cs @@ -0,0 +1,153 @@ +using mbts.ui; +using mbts.ui.controls.graph; +using mbts.ui.shell; + +using ProtoBuf; + +using System; +using System.Collections.Generic; + +namespace mbts.spark { + [ProtoContract] + class VolSurfaceGraphSettings : IEquatable, ICloneable { + public static VolSurfaceGraphSettings get_default() { + return new VolSurfaceGraphSettings { + put_control_points = new ScatterSeriesSettings { + color = BTSColors.VolSurfaceGraph.put_special, + shape = MarkerShape.Circle, + size = 3.0 + }, + atm = new ScatterSeriesSettings { + shape = MarkerShape.Diamond, + size = 4.5, + color = BTSColors.VolSurfaceGraph.main_curve_atm + }, + call_control_points = new ScatterSeriesSettings { + color = BTSColors.VolSurfaceGraph.call_special, + shape = MarkerShape.Circle, + size = 3.0 + }, + put_wing = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.wing, + stroke_thickness = 1.5 + }, + inner_curve = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.main_curve, + stroke_thickness = 1.5 + }, + call_wing = new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.wing, + stroke_thickness = 1.5 + }, + implied_puts = new ScatterSeriesSettings { + shape = MarkerShape.Circle, + size = 1.5, + color = BTSColors.VolSurfaceGraph.implied_put + }, + implied_atm = new ScatterSeriesSettings { + shape = MarkerShape.Cross, + size = 4.5, + color = BTSColors.VolSurfaceGraph.implied_atm + }, + implied_calls = new ScatterSeriesSettings { + shape = MarkerShape.Circle, + size = 1.5, + color = BTSColors.VolSurfaceGraph.implied_call + }, + vol_path = get_default_vol_path_settings(), + exp_bounds = new ExpGraphBounds[0] + }; + } + + public static LineSeriesSettings get_default_vol_path_settings() { + return new LineSeriesSettings { + color = BTSColors.VolSurfaceGraph.vol_path, + stroke_thickness = 1.5 + }; + } + + [ProtoMember(1)] + public ScatterSeriesSettings call_control_points; + [ProtoMember(2)] + public ScatterSeriesSettings put_control_points; + + [ProtoMember(3)] + public LineSeriesSettings put_wing; + [ProtoMember(4)] + public LineSeriesSettings inner_curve; + [ProtoMember(5)] + public LineSeriesSettings call_wing; + + [ProtoMember(6)] + public ScatterSeriesSettings implied_puts; + [ProtoMember(7)] + public ScatterSeriesSettings implied_calls; + + [ProtoMember(8)] + public ScatterSeriesSettings atm; + [ProtoMember(9)] + public ScatterSeriesSettings implied_atm; + + [ProtoMember(10)] + public LineSeriesSettings vol_path; + + [ProtoMember(11)] + public ExpGraphBounds[] exp_bounds; + + //private LineSeriesSettings _vol_path; + //public LineSeriesSettings vol_path { + // get { + // return _vol_path ?? (_vol_path = new LineSeriesSettings { + // color = BTSColors.VolSurfaceGraph.vol_path, + // thickness = 1.5 + // }); + // } + //} + + public object Clone() => + ProtoBufSerializationHelper.clone_protobuf(this); + + public bool Equals(VolSurfaceGraphSettings other) => + other != null && + call_control_points.safe_equals(other.call_control_points) && + call_wing.safe_equals(other.call_wing) && + implied_calls.safe_equals(other.implied_calls) && + put_control_points.safe_equals(other.put_control_points) && + put_wing.safe_equals(other.put_wing) && + implied_puts.safe_equals(other.implied_puts) && + inner_curve.safe_equals(other.inner_curve) && + atm.safe_equals(other.atm) && + implied_atm.safe_equals(other.implied_atm) && + vol_path.safe_equals(other.vol_path) && + exp_bounds.safe_sequence_equals(other.exp_bounds); + + public override bool Equals(object obj) => + Equals(obj as VolSurfaceGraphSettings); + + public override int GetHashCode() => + GetType().GetHashCode(); + } + + [ProtoContract] + class ExpGraphBounds : IEquatable { + [ProtoMember(1)] + public SecurityExpirationProto exp { get; set; } + + [ProtoMember(2)] + public AxisBounds x_bounds { get; set; } + + [ProtoMember(3)] + public AxisBounds y_bounds { get; set; } + + public bool Equals(ExpGraphBounds other) => + other != null && + x_bounds.safe_equals(other.x_bounds) && + y_bounds.safe_equals(other.y_bounds); + + public override bool Equals(object obj) => + Equals(obj as ExpGraphBounds); + + public override int GetHashCode() => + GetType().GetHashCode(); + } +} diff --git a/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs b/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs new file mode 100644 index 000000000..f61c8eb79 --- /dev/null +++ b/src/client/spark/AW2/UISettings/VolSurfaceWindowSettings.cs @@ -0,0 +1,46 @@ +namespace mbts.spark { + using mbts.analytics; + + using ProtoBuf; + + using System.Collections.Generic; + + [ProtoContract] + class VolSurfaceWindowSettings { + public static int version => 1; + + [ProtoMember(1)] + public int id { get; set; } + + [ProtoMember(2)] + public ui.controls.graph.BTSGraphAxis vol_curve_x_axis { get; set; } + + [ProtoMember(3)] + public ui.controls.graph.BTSGraphAxis vol_curve_y_axis { get; set; } + + [ProtoMember(4)] + public List vol_curve_visible_series { get; set; } + + [ProtoMember(5)] + public List hidden_exps { get; set; } + + [ProtoMember(6)] + public bool show_mkt_implied_vol { get; set; } + + [ProtoMember(7)] + public VolSurfaceGraphSettings vol_curve_graph_settings { get; set; } + + [ProtoMember(8)] + public ui.controls.VolSurfaceMacroGridSettings macro_grid_settings { get; set; } + + public bool Equals(VolSurfaceWindowSettings other) => + other != null && + id == other.id && + vol_curve_x_axis.safe_equals(other.vol_curve_x_axis) && + vol_curve_y_axis.safe_equals(other.vol_curve_y_axis) && + vol_curve_visible_series.safe_sequence_equals(other.vol_curve_visible_series) && + hidden_exps.safe_sequence_equals(other.hidden_exps) && + show_mkt_implied_vol == other.show_mkt_implied_vol && + vol_curve_graph_settings.safe_equals(other.vol_curve_graph_settings); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml new file mode 100644 index 000000000..987c0ed89 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + Up + Down + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs new file mode 100644 index 000000000..b4aaf002d --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceMacroControlView.xaml.cs @@ -0,0 +1,8 @@ +namespace mbts.ui.controls { + using System.Windows.Controls; + + partial class VolSurfaceMacroControlView : UserControl { + public VolSurfaceMacroControlView() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml new file mode 100644 index 000000000..d4c224d09 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml @@ -0,0 +1,1293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Volatility Time Decays Automatically + + + + + If unchecked, volatility will be calculated according to the regular calendar year, like interest, + + and both will refer to the "Regular Calendar Days per Year" value below. + + + + + Use Business Calendar for Volatility + + + + + + Regular Calendar Days per Year + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Strike Axis + Wing Axis + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs new file mode 100644 index 000000000..a93a517ca --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceSettingsEditor.xaml.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace mbts.ui.shell { + partial class VolSurfaceSettingsEditor : Window { + public VolSurfaceSettingsEditor() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml new file mode 100644 index 000000000..be205f024 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml @@ -0,0 +1,146 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs new file mode 100644 index 000000000..293ccd9b6 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceShellModuleContent.xaml.cs @@ -0,0 +1,11 @@ +namespace mbts.ui.shell { + using System.Windows.Controls; + + /// + /// Interaction logic for VolSurfaceShellModuleContent.xaml + /// + partial class VolSurfaceShellModuleContent : UserControl { + public VolSurfaceShellModuleContent() => + InitializeComponent(); + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml new file mode 100644 index 000000000..a36803d02 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs new file mode 100644 index 000000000..211c9a909 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceTimeDecayEditor.xaml.cs @@ -0,0 +1,33 @@ +using System; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Threading; + +namespace mbts.ui.shell { + /// + /// Interaction logic for VolSurfaceTimeDecayEditor.xaml + /// + partial class VolSurfaceTimeDecayEditor : UserControl { + public VolSurfaceTimeDecayEditor() => + InitializeComponent(); + + void decay_hours_Loaded(object sender, System.Windows.RoutedEventArgs e) { + var tb = (TextBox)sender; + tb.Focus(); + Keyboard.Focus(tb); + } + + void time_picker_KeyDown(object sender, KeyEventArgs e) { + if (e.Key == Key.Enter) { + e.Handled = true; + add_item_button.Focus(); + ICommand command = add_item_button.Command; + if (command != null) { + object parameter = add_item_button.CommandParameter; + if (add_item_button.Command.CanExecute(parameter)) + add_item_button.Command.Execute(parameter); + } + } + } + } +} diff --git a/src/client/spark/AW2/View/VolSurfaceView2.xaml b/src/client/spark/AW2/View/VolSurfaceView2.xaml new file mode 100644 index 000000000..b45fe6939 --- /dev/null +++ b/src/client/spark/AW2/View/VolSurfaceView2.xaml @@ -0,0 +1,649 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +