From 90a046d539de6a6947fb448caa74fa0075efbcf1 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 18 Jan 2023 13:01:27 -0500 Subject: [PATCH] feat (ui): Use fractional qtys in md Changing quantities from ints to floats introduces new rounding/display issues (unlike with ints, we can't just call 'ToString()' and expect consistent formatting). Formatting settings are needed, such as num-decimal-places and display-multiplier, and they must be configurable per SecurityCriteria. Fortunately, such configuration already exists in the form of SecurityMetadata config (we tackled the same issue for order-entry). In order to integrate this (newer) config with market data, references to the (older) SymbolUIConfiguration (used once upon a time for DJ work), had to be replaced. --- .../spark/AlgoProvider/AlgoProviderFactory.cs | 25 ++- .../spark/AlgoProvider/IAlgoProvider.cs | 22 ++- .../MarketImpliedVol/VolSurfaceMDUnit.cs | 2 +- src/client/spark/Daemons/MergedMDDaemon.cs | 2 +- src/client/spark/Daemons/OrderTicketDaemon.cs | 34 +++- .../spark/Model/Trading/OrderDataSource.cs | 1 - .../spark/Model/Trading/PositionModel.cs | 7 +- .../spark/Modules/Market/MarketShellModule.cs | 2 +- .../MarketView/MarketViewFilterStates.cs | 81 +++++--- .../Market/MarketView/MarketViewRow.cs | 173 ++++++++++-------- .../Modules/Market/MarketView/MarketViewVM.cs | 24 +-- .../Market/MarketView/MarketViewView.xaml.cs | 3 +- .../Market/TimeAndSales/TimeAndSalesRowVM.cs | 21 ++- .../Market/TimeAndSales/TimeAndSalesVM.cs | 22 +-- .../Market/TimeAndSales/TimeAndSalesWindow.cs | 9 +- .../Market/TimeAndSalesWindowFactory.cs | 12 +- .../Modules/Trading/Ladder/VM/LadderVM.cs | 2 +- .../Trading/Ladder/View/LadderGridHost.cs | 22 ++- .../Trading/Ladder/View/LadderRender.cs | 22 ++- .../Trading/ManualFills/ManualFillsModel.cs | 2 +- .../Modules/Trading/OrderBook/OrderBookVM.cs | 3 +- .../Trading/PNL/VM/PNLCellIndexBuilder.cs | 17 +- .../spark/Modules/Trading/PNL/VM/PNLRowVM.cs | 10 +- .../Notifications/INotificationService.cs | 9 +- .../spark/Orders/ExistingOrderTicketVM.cs | 21 ++- src/client/spark/Orders/NewOrderTicketVM.cs | 21 ++- .../Orders/OrderModificationControl.xaml | 20 +- .../Orders/OrderTypeVMs/IcebergOrderVM.cs | 93 ++++------ .../Orders/OrderTypeVMs/OrderTypeVMFactory.cs | 55 +++++- src/client/spark/Orders/OrderUtils.cs | 11 +- src/client/spark/Orders/OrdersModel.cs | 7 +- .../Security/ISecurityAuxiliaryDataModel.cs | 51 ------ src/client/spark/Trades/TradeInfo.cs | 17 +- src/client/spark/Trades/TradesSource.cs | 22 ++- src/client/spark/core/Bus/SparkCommands.cs | 3 +- src/client/spark/core/Bus/SparkTags.cs | 4 +- .../view/Controls/DIYGrid/CellProperty.cs | 32 +++- .../Order/AlgoContentTemplateSelector.xaml | 4 +- src/client/spark/view/Shell/ShellModel.cs | 1 - .../spark/view/Spark/Utilities/BBOVM.cs | 7 +- .../view/Spark/Utilities/ISecurityMDPump.cs | 36 ++-- .../Domain/SecurityMetadataExtensions.cs | 40 ++++ .../spark_api/MarketData/MDConsumerHandle.cs | 4 +- .../spark_api/MarketData/NativePriceSize.cs | 11 +- .../MarketData/NativePriceSizeExtensions.cs | 2 +- .../spark_api/data/ISecurityMetadataStore.cs | 16 ++ .../spark_api/data/ticks/TickExtensions.cs | 32 ++++ src/lib/config/protos/ui.proto | 9 - 48 files changed, 619 insertions(+), 427 deletions(-) delete mode 100644 src/client/spark/Security/ISecurityAuxiliaryDataModel.cs create mode 100644 src/client/spark_api/Domain/SecurityMetadataExtensions.cs diff --git a/src/client/spark/AlgoProvider/AlgoProviderFactory.cs b/src/client/spark/AlgoProvider/AlgoProviderFactory.cs index 52e8f66fa..be95e13a4 100644 --- a/src/client/spark/AlgoProvider/AlgoProviderFactory.cs +++ b/src/client/spark/AlgoProvider/AlgoProviderFactory.cs @@ -5,6 +5,8 @@ using bts.api.core; using mbts.ui.utility; using mbts.utils; +using Spark.Core.Data; + using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -18,7 +20,11 @@ using AlgoType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; namespace mbts.spark { class AlgoProviderFactory { [ImportingConstructor] - public AlgoProviderFactory(IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) { + public AlgoProviderFactory( + IAlgoStudioModel studio_model, + DynamicOrderHelper dynamic_helper, + ISecurityMetadataStore sec_meta_store + ) { var from_conf = config.Configuration.get(); if (from_conf.rules.Count == 0) { // There seems to be a config race bug, where the returned config values are empty, despite having entries in spark.conf. @@ -100,8 +106,9 @@ namespace mbts.spark { "\n\n\tAttachable\n" + attachable_rules.fmt_diagnostic("\n\t\t")); - security_algo_provider = new AlgoProvider(rules, studio_model, dynamic_helper, security_auxiliary_model); - attachable_algo_provider = new AttachableAlgoProvider(attachable_rules, studio_model, dynamic_helper, security_auxiliary_model); + security_algo_provider = new AlgoProvider(rules, studio_model, dynamic_helper, sec_meta_store); + attachable_algo_provider = new AttachableAlgoProvider( + attachable_rules, studio_model, dynamic_helper, sec_meta_store); } else { var algo_type_data = EnumHelper.get_values_except(AlgoType.Dynamic, AlgoType.Composite, AlgoType.None) @@ -109,8 +116,16 @@ namespace mbts.spark { .Concat(dynamic_helper.dynamic_types.Select(dt => _get_type_data(AlgoType.Dynamic, dt))) .ToListLazy(); var conf_sets = from_conf.rules.Select(r => _to_security_algo_set(r, dynamic_helper, algo_type_data)).ToList(); - security_algo_provider = new AlgoProvider(conf_sets.Select(tup => tup.standard).ToList(), studio_model, dynamic_helper, security_auxiliary_model); - attachable_algo_provider = new AttachableAlgoProvider(conf_sets.Select(tup => tup.attachable).ToList(), studio_model, dynamic_helper, security_auxiliary_model); + security_algo_provider = new AlgoProvider( + conf_sets.Select(tup => tup.standard).ToList(), + studio_model, + dynamic_helper, + sec_meta_store); + attachable_algo_provider = new AttachableAlgoProvider( + conf_sets.Select(tup => tup.attachable).ToList(), + studio_model, + dynamic_helper, + sec_meta_store); } } diff --git a/src/client/spark/AlgoProvider/IAlgoProvider.cs b/src/client/spark/AlgoProvider/IAlgoProvider.cs index ff2f37755..060690726 100644 --- a/src/client/spark/AlgoProvider/IAlgoProvider.cs +++ b/src/client/spark/AlgoProvider/IAlgoProvider.cs @@ -8,6 +8,8 @@ using mbts.spark.utilities; using mbts.ui.utility; using mbts.utils; +using Spark.Core.Data; + using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -30,20 +32,24 @@ namespace mbts.spark { class AlgoProvider : IAlgoProvider { readonly IEnumerable _security_algo_types; readonly IAlgoStudioModel _studio_model; - readonly ISecurityAuxiliaryDataModel _security_auxiliary_model; readonly IObservable> _studio_algos_source; readonly DynamicOrderHelper _dynamic_helper; + readonly ISecurityMetadataStore _sec_meta_store; readonly AlgoTypeSetImmutable _full_set; - public AlgoProvider(IEnumerable algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) { + public AlgoProvider( + IEnumerable algo_sets, + IAlgoStudioModel studio_model, + DynamicOrderHelper dynamic_helper, + ISecurityMetadataStore sec_meta_store) { _security_algo_types = algo_sets; _studio_model = studio_model; _dynamic_helper = dynamic_helper; + _sec_meta_store = sec_meta_store; _full_set = new AlgoTypeSetImmutable( ImmutableHashSet.CreateRange( EnumHelper.get_values_except(CustomOrderDefinition.CustomOneofCase.None, CustomOrderDefinition.CustomOneofCase.Dynamic, CustomOrderDefinition.CustomOneofCase.Composite)), ImmutableHashSet.CreateRange(dynamic_helper.dynamic_types)); - _security_auxiliary_model = security_auxiliary_model; /// initialize with an empty table, so the /// /// calls made by the 'subscribe_algos' methods will fire at least once, even if the underlying @@ -96,7 +102,7 @@ namespace mbts.spark { clause, _dynamic_helper, def => _fit_to_type(def, security, _security_algo_types), - _security_auxiliary_model.get_display_quantity_divisor(security)); + _sec_meta_store.get_qty_display_divisor(security)); var filtered_studio_algos = _studio_algos_source .StartWith(TableUpdate.mk_empty(AlgoData.key_fn)) @@ -180,8 +186,12 @@ namespace mbts.spark { } class AttachableAlgoProvider : AlgoProvider, IAttachableAlgoProvider { - public AttachableAlgoProvider(IEnumerable algo_sets, IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) - : base(algo_sets, studio_model, dynamic_helper, security_auxiliary_model) { } + public AttachableAlgoProvider( + IEnumerable algo_sets, + IAlgoStudioModel studio_model, + DynamicOrderHelper dynamic_helper, + ISecurityMetadataStore sec_meta_store) + : base(algo_sets, studio_model, dynamic_helper, sec_meta_store) { } // arbitrarily assign LimitOrderDefinition (this is just a placeholder; the real child is the attach target algo). // Note: although 'None' might seem approrpriate, the server requires a valid definition (perhaps this will change in the future). diff --git a/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMDUnit.cs b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMDUnit.cs index eeb5a21b6..ca02476c2 100644 --- a/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMDUnit.cs +++ b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMDUnit.cs @@ -29,7 +29,7 @@ namespace mbts.analytics { public VolSurfaceMDUnit(NativePriceSize bid, NativePriceSize ask, double mark_price) - : this(bid.price, bid.size_f, ask.price, ask.size_f, mark_price) { + : this(bid.price, bid.size, ask.price, ask.size, mark_price) { } public bool is_two_sided() { return bid_size != 0 && ask_size != 0; } diff --git a/src/client/spark/Daemons/MergedMDDaemon.cs b/src/client/spark/Daemons/MergedMDDaemon.cs index 4ae563c26..e8f329b04 100644 --- a/src/client/spark/Daemons/MergedMDDaemon.cs +++ b/src/client/spark/Daemons/MergedMDDaemon.cs @@ -60,7 +60,7 @@ namespace bts { rv += $"id: {kv.Key} desc: {sec.security_desc()} sym: {sec.Symbol} " + $"exp: {sec.security_expiration()} " + $"k: {sec.Option.Strike} cp: {sec.Option.CallPut} " + - $"bid: p: {bid.price} q: {bid.size} qf: {bid.size_f} ask: p: {ask.price} q: {ask.size} qf: {ask.size_f}" + + $"bid: p: {bid.price} q: {bid.size} qf: {bid.size} ask: p: {ask.price} q: {ask.size} qf: {ask.size}" + "\n"; } } diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index 5856e594d..59182a399 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -10,6 +10,7 @@ using mbts.spark; using mbts.ui; using mbts.ui.spark; +using Spark.Core.Data; using Spark.Core.Disposables; using System; @@ -26,6 +27,7 @@ namespace bts.shell { class OrderTicketDaemon : IShellDaemon { readonly IBus _bus; readonly OrdersModel _model; + readonly ISecurityMetadataStore _sec_meta_store; readonly UserSettingsHub _settings_hub; readonly ErrorReporter _error_reporter; readonly bool _close_on_send; @@ -34,12 +36,30 @@ namespace bts.shell { IDisposable _dispose; [ImportingConstructor] - public OrderTicketDaemon(IBus bus, OrdersModel model, UserSettingsHub settings_hub, ErrorReporter error_reporter) - : this(bus, model, settings_hub, error_reporter, Configuration.get().close_on_send) { } + public OrderTicketDaemon( + IBus bus, + OrdersModel model, + ISecurityMetadataStore sec_meta_store, + UserSettingsHub settings_hub, + ErrorReporter error_reporter) + : this( + bus, + model, + sec_meta_store, + settings_hub, + error_reporter, + Configuration.get().close_on_send) { } - public OrderTicketDaemon(IBus bus, OrdersModel model, UserSettingsHub settings_hub, ErrorReporter error_reporter, bool close_on_send) { + public OrderTicketDaemon( + IBus bus, + OrdersModel model, + ISecurityMetadataStore sec_meta_store, + UserSettingsHub settings_hub, + ErrorReporter error_reporter, + bool close_on_send) { _bus = bus; _model = model; + _sec_meta_store = sec_meta_store; _settings_hub = settings_hub; _error_reporter = error_reporter; _close_on_send = close_on_send; @@ -77,7 +97,7 @@ namespace bts.shell { }); } - void _show_order_ticket((OrderDefinitionImmutable def, double price, uint size) ops) { + void _show_order_ticket((OrderDefinitionImmutable def, double price, double size) ops) { var (def, price, size) = ops; if (!_md_map.TryGetValue(def.SecurityKey, out SecurityMD smd)) { return; @@ -116,9 +136,9 @@ namespace bts.shell { _show_order_window(new OrderModificationDialog { DataContext = new ExistingOrderTicketVM(_model, Observable.Return((md, ori.order)), - Observable.Return(LadderSettings.Default.calculator_buttons) - ) - }); + Observable.Return(LadderSettings.Default.calculator_buttons), + _sec_meta_store.get_qty_display(ori.sec.Value)) + }); } } diff --git a/src/client/spark/Model/Trading/OrderDataSource.cs b/src/client/spark/Model/Trading/OrderDataSource.cs index f4a03530f..ae613861b 100644 --- a/src/client/spark/Model/Trading/OrderDataSource.cs +++ b/src/client/spark/Model/Trading/OrderDataSource.cs @@ -28,7 +28,6 @@ namespace Spark.Model.Trading { AdminModel admin_model, SecurityResolver sec_resolver, OrderService order_service, - ISecurityAuxiliaryDataModel security_auxiliary_model, ErrorReporter error_reporter ) { var scheduler = ThreadPoolScheduler.Instance; diff --git a/src/client/spark/Model/Trading/PositionModel.cs b/src/client/spark/Model/Trading/PositionModel.cs index 8e229fff6..f23841a9a 100644 --- a/src/client/spark/Model/Trading/PositionModel.cs +++ b/src/client/spark/Model/Trading/PositionModel.cs @@ -15,6 +15,7 @@ namespace Spark.Trading { using Spark.Api.Reactive; using Spark.Core; + using Spark.Core.Data; using Spark.Core.Disposables; using Spark.Core.Reactive; using Spark.Model.Trading; @@ -43,7 +44,7 @@ namespace Spark.Trading { PositionService position_service, OrderService order_service, OrderDataSource order_data, - ISecurityAuxiliaryDataModel security_auxiliary_model, + ISecurityMetadataStore sec_meta_store, ErrorReporter error_reporter) { var scheduler = ThreadPoolScheduler.Instance; var interval = TimeSpan.FromMilliseconds(100); @@ -91,8 +92,8 @@ namespace Spark.Trading { account_name: account, working: WorkingOrderData.Create( acc_orders.table.state.Values.Select(t => t.order), - new QuantityConversionData( - security_auxiliary_model.get_display_quantity_divisor(security), + new( + sec_meta_store.get_qty_display_divisor(security), QuantityConversionOpType.DivideActual))); }, PNLRowData.key_fn) diff --git a/src/client/spark/Modules/Market/MarketShellModule.cs b/src/client/spark/Modules/Market/MarketShellModule.cs index 4ceccd9e3..a4578b4c2 100644 --- a/src/client/spark/Modules/Market/MarketShellModule.cs +++ b/src/client/spark/Modules/Market/MarketShellModule.cs @@ -32,7 +32,7 @@ new MarketViewWindowFactory( this, bus, settings_hub, orders_model, position_model, sec_meta_store), new OptionsViewWindowFactory(this, orders_model, bus), - new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub, orders_model.security_auxiliary_model), + new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub), }; public string name => "Market"; diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewFilterStates.cs b/src/client/spark/Modules/Market/MarketView/MarketViewFilterStates.cs index 2a6783160..dc2e282c0 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewFilterStates.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewFilterStates.cs @@ -12,16 +12,28 @@ namespace bts.shell.market_view { public string security { get; set; } [ProtoMember(2)] public DoubleMinMaxState bid_price { get; set; } - [ProtoMember(3)] - public UIntMinMaxState bid_merged_size { get; set; } + + // [ProtoMember(3)] + // public UIntMinMaxState bid_merged_size { get; set; } + [ProtoMember(103)] + public DoubleMinMaxState bid_merged_size { get; set; } + [ProtoMember(4)] public DoubleMinMaxState ask_price { get; set; } - [ProtoMember(5)] - public UIntMinMaxState ask_merged_size { get; set; } + + // [ProtoMember(5)] + // public UIntMinMaxState ask_merged_size { get; set; } + [ProtoMember(105)] + public DoubleMinMaxState ask_merged_size { get; set; } + [ProtoMember(6)] public DoubleMinMaxState last_price { get; set; } - [ProtoMember(7)] - public UIntMinMaxState last_size { get; set; } + + // [ProtoMember(7)] + // public UIntMinMaxState last_size { get; set; } + [ProtoMember(107)] + public DoubleMinMaxState last_size { get; set; } + [ProtoMember(8)] public DoubleMinMaxState day_change { get; set; } [ProtoMember(9)] @@ -30,26 +42,51 @@ namespace bts.shell.market_view { public DoubleMinMaxState session_low { get; set; } [ProtoMember(11)] public DoubleMinMaxState session_high { get; set; } - [ProtoMember(12)] - public IntMinMaxState day_position { get; set; } + // [ProtoMember(12)] + // public IntMinMaxState day_position { get; set; } + [ProtoMember(112)] + public DoubleMinMaxState day_position { get; set; } [ProtoMember(27)] public DoubleMinMaxState raw_day_position { get; set; } - [ProtoMember(13)] - public IntMinMaxState working_bid_volume { get; set; } - [ProtoMember(14)] - public IntMinMaxState working_ask_volume { get; set; } - [ProtoMember(15)] - public ULongMinMaxState volume { get; set; } + + // [ProtoMember(13)] + // public IntMinMaxState working_bid_volume { get; set; } + [ProtoMember(113)] + public DoubleMinMaxState working_bid_volume { get; set; } + + // [ProtoMember(14)] + // public IntMinMaxState working_ask_volume { get; set; } + [ProtoMember(114)] + public DoubleMinMaxState working_ask_volume { get; set; } + + // [ProtoMember(15)] + // public ULongMinMaxState volume { get; set; } + [ProtoMember(115)] + public DoubleMinMaxState volume { get; set; } + [ProtoMember(16)] public string security_key { get; set; } - [ProtoMember(17)] - public UIntMinMaxState bid_direct_size { get; set; } - [ProtoMember(18)] - public UIntMinMaxState bid_implied_size { get; set; } - [ProtoMember(19)] - public UIntMinMaxState ask_direct_size { get; set; } - [ProtoMember(20)] - public UIntMinMaxState ask_implied_size { get; set; } + + // [ProtoMember(17)] + // public UIntMinMaxState bid_direct_size { get; set; } + [ProtoMember(117)] + public DoubleMinMaxState bid_direct_size { get; set; } + + // [ProtoMember(18)] + // public UIntMinMaxState bid_implied_size { get; set; } + [ProtoMember(118)] + public DoubleMinMaxState bid_implied_size { get; set; } + + // [ProtoMember(19)] + // public UIntMinMaxState ask_direct_size { get; set; } + [ProtoMember(119)] + public DoubleMinMaxState ask_direct_size { get; set; } + + // [ProtoMember(20)] + // public UIntMinMaxState ask_implied_size { get; set; } + [ProtoMember(120)] + public DoubleMinMaxState ask_implied_size { get; set; } + [ProtoMember(21)] public string market_description { get; set; } [ProtoMember(22)] diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs index 166994e01..7094e8e38 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs @@ -1,6 +1,7 @@ namespace mbts.spark { using bts.api; using bts.api.core; + using bts.api.domain; using bts.api.orderman; using bts.api.position; using bts.collections; @@ -14,6 +15,7 @@ using mbts.ui.shell; using mbts.utils; + using Spark.Api.Domain; using Spark.Api.Position; using Spark.Core; using Spark.Core.Disposables; @@ -48,21 +50,21 @@ readonly CellProperty _day_position; readonly CellProperty _raw_day_position; - readonly CellProperty _last_size; - readonly CellProperty _volume; + readonly CellProperty _last_size; + readonly CellProperty _volume; readonly CellProperty _inside_bids; readonly CellProperty _inside_asks; - readonly CellProperty _working_bid_volume; - readonly CellProperty _working_ask_volume; + readonly CellProperty _working_bid_volume; + readonly CellProperty _working_ask_volume; readonly CellProperty _working_best_bid; readonly CellProperty _working_best_ask; - readonly PropertyAutoWrapper _bid_direct_size; - readonly PropertyAutoWrapper _bid_implied_size; - readonly PropertyAutoWrapper _bid_merged_size; - readonly PropertyAutoWrapper _ask_direct_size; - readonly PropertyAutoWrapper _ask_implied_size; - readonly PropertyAutoWrapper _ask_merged_size; + readonly Property _bid_direct_size; + readonly Property _bid_implied_size; + readonly Property _bid_merged_size; + readonly Property _ask_direct_size; + readonly Property _ask_implied_size; + readonly Property _ask_merged_size; // greeks readonly Property _greeks; @@ -77,10 +79,13 @@ ulong _bbo_ref; ulong _last_ref; - double? _display_qty_divisor_backing; bool _is_visible; - public Row(IBus bus, SecurityMD smd, OrdersModel orders_model, IPositionModel position_model) { + public Row( + IBus bus, + SecurityMD smd, + OrdersModel orders_model, + IPositionModel position_model) { _bus = bus; security_md = smd; _orders_model = orders_model; @@ -89,29 +94,29 @@ smd.quantity_display.TickFactors : new(new() { TickBase = 1, TickUnit = 1 })); _raise_invalidated = new(() => invalidated?.Invoke()); - _day_position = new CellProperty(this, nameof(day_position), fmt_display_qty_double); - _raw_day_position = new CellProperty(this, nameof(raw_day_position), fmt_display_qty_double); + _day_position = new CellProperty(this, nameof(day_position), fmt_qty); + _raw_day_position = new CellProperty(this, nameof(raw_day_position), fmt_qty); _bid_price = backing(nameof(bid_price), double.NaN); _ask_price = backing(nameof(ask_price), double.NaN); _last_price = backing(nameof(last_price), double.NaN); - _last_size = new CellProperty(this, nameof(last_qty), fmt_display_qty_uint); + _last_size = new CellProperty(this, nameof(last_qty), fmt_qty); _day_change = backing(nameof(day_change), double.NaN); _session_low = backing(nameof(session_low), double.NaN); _session_high = backing(nameof(session_high), double.NaN); _last_price_from_spread = backing(nameof(last_price_from_spread), false); _settlement = backing(nameof(settlement), double.NaN); - _volume = new CellProperty(this, nameof(volume), fmt_display_qty_ulong, 0); + _volume = new CellProperty(this, nameof(volume), fmt_qty, 0); _inside_bids = new CellProperty(this, nameof(inside_bids)); _inside_asks = new CellProperty(this, nameof(inside_asks)); - _working_bid_volume = new CellProperty(this, nameof(working_bid_volume)); - _working_ask_volume = new CellProperty(this, nameof(working_ask_volume)); + _working_bid_volume = new CellProperty(this, nameof(working_bid_volume)); + _working_ask_volume = new CellProperty(this, nameof(working_ask_volume)); - _bid_direct_size = backing(nameof(dbid_qty), 0u, convert_display_qty_uint); - _bid_implied_size = backing(nameof(ibid_qty), 0u, convert_display_qty_uint); - _bid_merged_size = backing(nameof(bid_qty), 0u, convert_display_qty_uint); - _ask_direct_size = backing(nameof(dask_qty), 0u, convert_display_qty_uint); - _ask_implied_size = backing(nameof(iask_qty), 0u, convert_display_qty_uint); - _ask_merged_size = backing(nameof(ask_qty), 0u, convert_display_qty_uint); + _bid_direct_size = backing(nameof(dbid_qty), 0D); + _bid_implied_size = backing(nameof(ibid_qty), 0D); + _bid_merged_size = backing(nameof(bid_qty), 0D); + _ask_direct_size = backing(nameof(dask_qty), 0D); + _ask_implied_size = backing(nameof(iask_qty), 0D); + _ask_merged_size = backing(nameof(ask_qty), 0D); _working_best_bid = new CellProperty( this, nameof(working_best_bid), format_price, double.NaN); @@ -144,32 +149,28 @@ _animation.animations_changed += on_animations_changed; _dispose = Disposable.Create( - attach_prop_changed_cb(_bid_direct_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(dbid_qty_text))), - attach_prop_changed_cb(_bid_implied_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(ibid_qty_text))), - attach_prop_changed_cb(_bid_merged_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(bid_qty_text))), - attach_prop_changed_cb(_ask_direct_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(dask_qty_text))), - attach_prop_changed_cb(_ask_implied_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(iask_qty_text))), - attach_prop_changed_cb(_ask_merged_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(ask_qty_text))), _orders_model.on_security_root_orders(security.Id).OnDispatcher().Subscribe(on_orders), position_model.on_security_positions(security.Id).OnDispatcher().Subscribe(on_security_positions), _inside_bids.OnDispatcher().Subscribe(v => _animation.animate_working_bids_inside(v.newval)), _inside_asks.OnDispatcher().Subscribe(v => _animation.animate_working_asks_inside(v.newval)), _day_change.OnDispatcher().Subscribe(v => _animation.animate_day_change(v.newval > v.oldval)), + _bid_direct_size.invalidate_others_on_change(nameof(dbid_qty_display)), + _bid_implied_size.invalidate_others_on_change(nameof(ibid_qty_display)), + _bid_merged_size.invalidate_others_on_change(nameof(bid_qty_display)), + _ask_direct_size.invalidate_others_on_change(nameof(dask_qty_display)), + _ask_implied_size.invalidate_others_on_change(nameof(iask_qty_display)), + _ask_merged_size.invalidate_others_on_change(nameof(ask_qty_display)), + _last_size.invalidate_on_change(nameof(last_qty_display)), + _day_position.invalidate_on_change(nameof(day_position_display)), + _raw_day_position.invalidate_on_change(nameof(raw_day_position_display)), + _working_bid_volume.invalidate_on_change(nameof(working_bid_volume_display)), + _working_ask_volume.invalidate_on_change(nameof(working_ask_volume_display)), Disposable.Create(() => _animation.animations_changed -= on_animations_changed)); void on_animations_changed() => RaisePropertyChanged(nameof(animations)); - uint convert_display_qty_uint(uint value) => - (uint)((double)value).safe_divide(_display_qty_divisor); - - string fmt_display_qty_uint(uint value) => - ((double)value).safe_divide(_display_qty_divisor).ToString(); - - string fmt_display_qty_ulong(ulong value) => - ((double)value).safe_divide(_display_qty_divisor).ToString(); - - string fmt_display_qty_double(double value) => - value.safe_divide(_display_qty_divisor).ToString(); + string fmt_qty(double value) => + _qty_display.format(value); void on_orders(ITableUpdateTransform orders) { foreach (var o in orders.removed) { @@ -196,15 +197,6 @@ raise_invalidated(); } } - - PropertyChange mk_echo_prop_changed_cb(params string[] props) => - (oldval, newval) => RaisePropertyChanged(props); - - IDisposable attach_prop_changed_cb( - PropertyAutoWrapper prop, PropertyChange<(TModel, TView)> callback) { - prop.changed += callback; - return Disposable.Create(() => prop.changed -= callback); - } } public event Action invalidated; @@ -217,55 +209,83 @@ public bool inside_bids => _inside_bids.value; public bool inside_asks => _inside_asks.value; public double day_position => _day_position.value; + public double day_position_display => _qty_display.to_display_value(day_position); public string day_position_text => _day_position.text; public double raw_day_position => _raw_day_position.value; - public string raw_day_position_text => SparkUtils.fmt_position(raw_day_position.safe_divide(_display_qty_divisor)); + public string raw_day_position_text => _raw_day_position.text; + public double raw_day_position_display => _qty_display.to_display_value(raw_day_position); + public double last_price => _last_price.Value; public bool last_price_from_spread => _last_price_from_spread.Value; - public uint last_qty => _last_size.value; + public double last_qty => _last_size.value; public string last_qty_text => _last_size.text; + public double last_qty_display => _qty_display.to_display_value(last_qty); // bid price/size public double bid_price => _bid_price.Value; - public uint dbid_qty => _bid_direct_size.model; - public uint ibid_qty => _bid_merged_size.model - _bid_direct_size.model; - public uint bid_qty => _bid_merged_size.model; + public double dbid_qty => _bid_direct_size.Value; + public double ibid_qty => _bid_merged_size.Value - _bid_direct_size.Value; + public double bid_qty => _bid_merged_size.Value; // bid size text - public string dbid_qty_text => _bid_direct_size.view.ToString(); - public string ibid_qty_text => _bid_implied_size.view.ToString(); - public string bid_qty_text => _bid_merged_size.view.ToString(); + public string dbid_qty_text => _qty_display.format(dbid_qty); + public string ibid_qty_text => _qty_display.format(ibid_qty); + public string bid_qty_text => _qty_display.format(bid_qty); + + // bid display size + // The grid filters reference display values (rather than actual) since that is what the + // user sees in the grid. + public double dbid_qty_display => _qty_display.to_display_value(dbid_qty); + public double ibid_qty_display => _qty_display.to_display_value(ibid_qty); + public double bid_qty_display => _qty_display.to_display_value(bid_qty); // ask price/size public double ask_price => _ask_price.Value; - public uint dask_qty => _ask_direct_size.model; - public uint iask_qty => _ask_implied_size.model; - public uint ask_qty => _ask_merged_size.model; + public double dask_qty => _ask_direct_size.Value; + public double iask_qty => _ask_implied_size.Value; + public double ask_qty => _ask_merged_size.Value; // ask size text - public string dask_qty_text => _ask_direct_size.view.ToString(); - public string iask_qty_text => _ask_implied_size.view.ToString(); - public string ask_qty_text => _ask_merged_size.view.ToString(); + public string dask_qty_text => _qty_display.format(dask_qty); + public string iask_qty_text => _qty_display.format(iask_qty); + public string ask_qty_text => _qty_display.format(ask_qty); - public ulong volume => _volume.value; + // ask display size + // The grid filters reference display values (rather than actual) since that is what the + // user sees in the grid. + public double dask_qty_display => _qty_display.to_display_value(dask_qty); + public double iask_qty_display => _qty_display.to_display_value(iask_qty); + public double ask_qty_display => _qty_display.to_display_value(ask_qty); + + public double volume => _volume.value; public string volume_text => _volume.text; public double settlement => _settlement.Value; public double day_change => _day_change.Value; public double session_low => _session_low.Value; public double session_high => _session_high.Value; - public int working_bid_volume => _working_bid_volume.value; - public int working_ask_volume => _working_ask_volume.value; + + // working bids + public double working_bid_volume => _working_bid_volume.value; public string working_bids_text => OrderUtils.order_collection_summary( _order_summarizer.best_working_bid, - _order_summarizer.best_working_bid_qty.safe_divide((int)_display_qty_divisor), - _order_summarizer.working_bid_qty.safe_divide((int)_display_qty_divisor), - security.ContractSpec); + _order_summarizer.best_working_bid_qty, + _order_summarizer.working_bid_qty, + security.ContractSpec, + _qty_display); + public double working_bid_volume_display => + _qty_display.to_display_value(working_bid_volume); + public double working_best_bid => _working_best_bid.value; + + // working asks + public double working_ask_volume => _working_ask_volume.value; public string working_asks_text => OrderUtils.order_collection_summary( _order_summarizer.best_working_ask, - ((double)_order_summarizer.best_working_ask_qty).safe_divide(_display_qty_divisor), - ((double)_order_summarizer.working_ask_qty).safe_divide(_display_qty_divisor), - security.ContractSpec); - public double working_best_bid => _working_best_bid.value; + _order_summarizer.best_working_ask_qty, + _order_summarizer.working_ask_qty, + security.ContractSpec, + _qty_display); + public double working_ask_volume_display => + _qty_display.to_display_value(working_ask_volume); public double working_best_ask => _working_best_ask.value; // ice @@ -315,10 +335,11 @@ public ICommand working_asks_click { get; } public ICommand default_command { get; } - double _display_qty_divisor => _display_qty_divisor_backing ?? - (_display_qty_divisor_backing = _orders_model.security_auxiliary_model.get_display_quantity_divisor(security)).Value; IMDConsumerHandle _md => security_md.md; + TickDisplaySettingsImmutable _qty_display => + security_md.quantity_display; + public string format_price(double price) => security.ContractSpec.format(price); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs index 2a5ef7e76..72613686a 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs @@ -386,25 +386,25 @@ namespace mbts.spark { public IDataGridColumnPersistentFilter security_filter { get; } public IDataGridColumnPersistentFilter bid_price_filter { get; } = new DoubleMinMax(r => r.bid_price, nameof(Row.bid_price)); - public IDataGridColumnPersistentFilter bid_qty_filter { get; } = new UIntMinMax(r => r.bid_qty, nameof(Row.bid_qty)); - public IDataGridColumnPersistentFilter dbid_qty_filter { get; } = new UIntMinMax(r => r.dbid_qty, nameof(Row.dbid_qty)); - public IDataGridColumnPersistentFilter ibid_qty_filter { get; } = new UIntMinMax(r => r.ibid_qty, nameof(Row.ibid_qty)); + public IDataGridColumnPersistentFilter bid_qty_filter { get; } = new DoubleMinMax(r => r.bid_qty_display, nameof(Row.bid_qty_display)); + public IDataGridColumnPersistentFilter dbid_qty_filter { get; } = new DoubleMinMax(r => r.dbid_qty_display, nameof(Row.dbid_qty_display)); + public IDataGridColumnPersistentFilter ibid_qty_filter { get; } = new DoubleMinMax(r => r.ibid_qty_display, nameof(Row.ibid_qty_display)); public IDataGridColumnPersistentFilter ask_price_filter { get; } = new DoubleMinMax(r => r.ask_price, nameof(Row.ask_price)); - public IDataGridColumnPersistentFilter ask_qty_filter { get; } = new UIntMinMax(r => r.ask_qty, nameof(Row.ask_qty)); - public IDataGridColumnPersistentFilter dask_qty_filter { get; } = new UIntMinMax(r => r.dask_qty, nameof(Row.dask_qty)); - public IDataGridColumnPersistentFilter iask_qty_filter { get; } = new UIntMinMax(r => r.iask_qty, nameof(Row.iask_qty)); + public IDataGridColumnPersistentFilter ask_qty_filter { get; } = new DoubleMinMax(r => r.ask_qty_display, nameof(Row.ask_qty_display)); + public IDataGridColumnPersistentFilter dask_qty_filter { get; } = new DoubleMinMax(r => r.dask_qty_display, nameof(Row.dask_qty_display)); + public IDataGridColumnPersistentFilter iask_qty_filter { get; } = new DoubleMinMax(r => r.iask_qty_display, nameof(Row.iask_qty_display)); public IDataGridColumnPersistentFilter last_price_filter { get; } = new DoubleMinMax(r => r.last_price, nameof(Row.last_price)); public IDataGridColumnPersistentFilter last_spread_price_filter { get; } = new RegexFilterVM(r => r.last_price_from_spread.ToString(), nameof(Row.last_price_from_spread)); - public IDataGridColumnPersistentFilter last_qty_filter { get; } = new UIntMinMax(r => r.last_qty, nameof(Row.last_qty)); + public IDataGridColumnPersistentFilter last_qty_filter { get; } = new DoubleMinMax(r => r.last_qty_display, nameof(Row.last_qty_display)); public IDataGridColumnPersistentFilter day_change_filter { get; } = new DoubleMinMax(r => r.day_change, nameof(Row.day_change)); public IDataGridColumnPersistentFilter settlement_filter { get; } = new DoubleMinMax(r => r.settlement, nameof(Row.settlement)); public IDataGridColumnPersistentFilter session_low_filter { get; } = new DoubleMinMax(r => r.session_low, nameof(Row.session_low)); public IDataGridColumnPersistentFilter session_high_filter { get; } = new DoubleMinMax(r => r.session_high, nameof(Row.session_high)); - public IDataGridColumnPersistentFilter day_position_filter { get; } = new IntMinMax(r => unchecked((int)r.day_position), nameof(Row.day_position)); - public IDataGridColumnPersistentFilter raw_day_position_filter { get; } = new DoubleMinMax(r => r.raw_day_position, nameof(Row.raw_day_position)); - public IDataGridColumnPersistentFilter working_bid_volume_filter { get; } = new IntMinMax(r => r.working_bid_volume, nameof(Row.working_bid_volume)); - public IDataGridColumnPersistentFilter working_ask_volume_filter { get; } = new IntMinMax(r => r.working_ask_volume, nameof(Row.working_ask_volume)); - public IDataGridColumnPersistentFilter volume_filter { get; } = new ULongMinMax(r => r.volume, nameof(Row.volume)); + public IDataGridColumnPersistentFilter day_position_filter { get; } = new DoubleMinMax(r => r.day_position_display, nameof(Row.day_position_display)); + public IDataGridColumnPersistentFilter raw_day_position_filter { get; } = new DoubleMinMax(r => r.raw_day_position, nameof(Row.raw_day_position_display)); + public IDataGridColumnPersistentFilter working_bid_volume_filter { get; } = new DoubleMinMax(r => r.working_bid_volume_display, nameof(Row.working_bid_volume_display)); + public IDataGridColumnPersistentFilter working_ask_volume_filter { get; } = new DoubleMinMax(r => r.working_ask_volume_display, nameof(Row.working_ask_volume_display)); + public IDataGridColumnPersistentFilter volume_filter { get; } = new DoubleMinMax(r => r.volume, nameof(Row.volume)); public IDataGridColumnPersistentFilter security_key_filter { get; } = new RegexFilterVM(r => r.security_key.ToString(), nameof(Row.security_key)); public IDataGridColumnPersistentFilter market_description_filter { get; } = new RegexFilterVM(r => r.security.HasIce ? r.security.Ice.MarketDescription : "", nameof(Row.market_description)); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs b/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs index b972ac1a9..10f84ead1 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewView.xaml.cs @@ -110,7 +110,8 @@ namespace mbts.ui.spark { }); } - async void _show_order_ticket(SecurityMD security_md, double price = double.NaN, uint size = 0) { + async void _show_order_ticket( + SecurityMD security_md, double price = double.NaN, double size = 0) { var resources = new OrderTicketResources(); resources.MergedDictionaries.Add(new AuxiliaryDataResources()); diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs index f90a253ef..d672ec309 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesRowVM.cs @@ -1,5 +1,6 @@ namespace bts.shell.time_and_sales { using bts.api; + using bts.api.domain; using bts.co2; using bts.utils; @@ -28,22 +29,19 @@ readonly TradeMessageImmutable _trade; readonly GreeksTuple _greeks_tuple; - readonly Func _get_display_qty_divisor; - double? _display_size; public TimeAndSalesRowVM( int row_key, - SecurityImmutable security, + SecurityMD security_md, TradeMessageImmutable trade, double volume, - GreeksTuple greeks_tuple, - Func get_display_qty_divisor) { + GreeksTuple greeks_tuple + ) { this.row_key = row_key; - this.security = security; + this.security_md = security_md; _trade = trade; this.volume = volume; _greeks_tuple = greeks_tuple; - _get_display_qty_divisor = get_display_qty_divisor ?? new(sec => 1); } public event Action invalidated; @@ -51,15 +49,16 @@ public int row_key { get; } public uint trade_key => _trade.Key; public uint security_key => security.Id; - public SecurityImmutable security { get; } + public SecurityMD security_md { get; } + public SecurityImmutable security => security_md.security; public DateTime time => new LLDateTime((ulong)_trade.Time).to_datetime().ToLocalTime(); public double price => _trade.price(); public double size => _trade.Size; - public double display_size => _display_size ?? - (_display_size = size.safe_divide(_get_display_qty_divisor(security))).Value; + public double display_size => _qty_display.to_display_value(size); + public string size_text => _qty_display.format(size); public AggressorSide aggressor_side => _trade.AggressorSide; public double volume { get; } @@ -73,6 +72,8 @@ public double delta => _greeks_tuple.delta; public double display_delta => delta * 100; + TickDisplaySettingsImmutable _qty_display => security_md.quantity_display; + public void raise_invalidated() => invalidated?.Invoke(); diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs index ffee85951..ffca5e43f 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesVM.cs @@ -53,7 +53,6 @@ _refresh_filter, _refresh_sort, _refresh_selected_rows; - readonly Func _get_display_qty_divisor; IComparer _comparer_backing; Func _filter_backing; ImmutableHashSet _selected_rows = ImmutableHashSet.Empty; @@ -70,12 +69,9 @@ _filter_change_count, _sort_change_count; - public TimeAndSalesVM( - IWindowSettingsManager settings_manager, - Func get_display_qty_divisor) { + public TimeAndSalesVM(IWindowSettingsManager settings_manager) { _sort_manager = new ColumnSortManager( columns.WrapSelector(c => c as ISortableDIYGridColumn, null), ColKey.RowKey.ToString()); - _get_display_qty_divisor = get_display_qty_divisor ?? new(sec => 1); _comparer_backing = _sort_manager.BuildComparer(_get_column_comparer); _log = new LoggerContext( Log.Ui, $"Time And Sales VM ({Interlocked.Increment(ref _id_counter)})", null); @@ -86,7 +82,7 @@ security_filter = new RegexFilterVM( r => r.security.ToString(), nameof(TimeAndSalesRowVM.security)); price_filter = new DoubleMinMax(r => r.price); - size_filter = new DoubleMinMax(r => r.size, nameof(TimeAndSalesRowVM.size)); + size_filter = new DoubleMinMax(r => r.display_size, nameof(TimeAndSalesRowVM.size)); aggressor_filter = DiscreteValuesFilterVM.Create( EnumHelper.get_values().ToArray(), r => r.aggressor_side); security_key_filter = new RegexFilterVM(r => r.security_key.ToString()); @@ -112,7 +108,7 @@ add_col(ColKey.Security, fmt_sec, ColWidth.Security, security_filter, FilterType.Regex); add_col(ColKey.Time, fmt_time, ColWidth.Time, time_filter, FilterType.TimeFilter); add_col(ColKey.Price, fmt_price, ColWidth.Price, price_filter, FilterType.DoubleMinMax, h_align: HorizontalAlignment.Right, get_fg: _get_aggressor_brush); - add_col(ColKey.Size, fmt_display_size, ColWidth.Qty, size_filter, FilterType.UIntMinMax, h_align: HorizontalAlignment.Right, get_fg: _get_aggressor_brush); + add_col(ColKey.Size, r => r.size_text, ColWidth.Qty, size_filter, FilterType.UIntMinMax, h_align: HorizontalAlignment.Right, get_fg: _get_aggressor_brush); add_col(ColKey.Aggressor, fmt_aggressor, ColWidth.Aggressor, aggressor_filter, FilterType.EnumValues, get_fg: _get_aggressor_brush); add_col(ColKey.SecurityKey, fmt_sec_key, ColWidth.SecurityKey, security_key_filter, FilterType.Regex); add_col(ColKey.Volume, fmt_volume, ColWidth.Volume, volume_filter, FilterType.DoubleMinMax, h_align: HorizontalAlignment.Right); @@ -144,7 +140,6 @@ static string fmt_sec(TimeAndSalesRowVM row) => row.security.ToString(); static string fmt_time(TimeAndSalesRowVM row) => row.time.ToString("h:mm:ss tt"); static string fmt_price(TimeAndSalesRowVM row) => row.security.spec_or_default().format(row.price); - static string fmt_display_size(TimeAndSalesRowVM row) => row.display_size.ToString(); static string fmt_aggressor(TimeAndSalesRowVM row) => row.aggressor_side.ToString(); static string fmt_volume(TimeAndSalesRowVM row) => new TickFactors(1, 100).format(row.volume); static string fmt_vol(TimeAndSalesRowVM row) => new TickFactors(1, 100).format(row.display_vol); @@ -356,7 +351,7 @@ } var all_rows_bd = _all_rows.ToBuilder(); foreach (var t in trades) { - var r = _row_factory.create(t, _get_display_qty_divisor); + var r = _row_factory.create(t); all_rows_bd.Add(r); if (_filter_backing is null || _filter_backing(r)) { rows.InsertSorted(r, _comparer); @@ -471,16 +466,13 @@ // the row key must be unique to each row in the collection int _row_id_counter; - public TimeAndSalesRowVM create( - TradeInfo trade_info, - Func get_display_qty_divisor) => + public TimeAndSalesRowVM create(TradeInfo trade_info) => new( _row_id_counter++, - trade_info.security, + trade_info.security_md, trade_info.trade, trade_info.volume, - trade_info.greeks_tuple ?? GreeksTuple.empty, - get_display_qty_divisor); + trade_info.greeks_tuple ?? GreeksTuple.empty); } } } diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index bae15ec1c..808121495 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -40,8 +40,6 @@ [DisallowNull] readonly IWindowSettingsManager _settings_manager; readonly bool _can_pause_updates; - [DisallowNull] - readonly Func _get_display_qty_divisor; TimeAndSalesVM _vm; SecurityCriteria _security_criteria_backing; @@ -58,7 +56,6 @@ [DisallowNull] TimeAndSalesSettings state, [DisallowNull] IWindowSettingsManager settings_manager, bool can_pause_updates, - Func get_display_qty_divisor, string thread_id) : base(WINDOW_DISPLAY_NAME, bus, factory, SparkCommands.ShowTimeAndSales.icon) { if (factory is null) { @@ -76,7 +73,6 @@ _security_criteria_backing = _state.security_criteria; _settings_manager = settings_manager ?? throw new ArgumentNullException(nameof(settings_manager)); _can_pause_updates = can_pause_updates; - _get_display_qty_divisor = get_display_qty_divisor ?? new Func(sec => 1); this.thread_id = thread_id; Icon.Freeze(); @@ -128,7 +124,7 @@ } _menu_display_vm = new SparkMenuDisplayVM(); _menu_display_vm.load_from(_state.menu_display); - _vm = new TimeAndSalesVM(_settings_manager, _get_display_qty_divisor); + _vm = new(_settings_manager); var current_sec_key_src = _observe_current_row().Select(r => { var result = ImmutableHashSet.Empty; if (r is not null) { @@ -195,8 +191,7 @@ var trades_source = TradesSource.create( _consumer, - _bus.subscribe(SparkTags.SecuritiesTag) - .Select(sec_md_map => MappedDictionary.create(sec_md_map, sec_md => sec_md.security)), + _bus.subscribe(SparkTags.SecuritiesTag), security_criteria_src.StartWith(() => _security_criteria).Select(sc => new[] { sc }), _trade_poll_interval); trades_source = TradesSource.with_greeks(trades_source, _bus.subscribe(SparkTags.Greeks)); diff --git a/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs b/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs index 9190d0a61..0283fda2e 100644 --- a/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs +++ b/src/client/spark/Modules/Market/TimeAndSalesWindowFactory.cs @@ -10,6 +10,7 @@ using mbts.ui; using mbts.ui.settings; + using Spark.Api.Domain; using Spark.Core.Disposables; using System; @@ -21,21 +22,15 @@ readonly IBus _bus; readonly MDConsumer _consumer; readonly UserSettingsHub _settings_hub; - readonly ISecurityAuxiliaryDataModel _security_auxiliary_model; IReadOnlyDictionary _securities = new Dictionary(); public TimeAndSalesWindowFactory( - IShellModule module, - IBus bus, - MDConsumer consumer, - UserSettingsHub settings_hub, - ISecurityAuxiliaryDataModel security_auxiliary_model) - : base(module, TimeAndSalesWindow.WINDOW_TYPE_NAME) { + IShellModule module, IBus bus, MDConsumer consumer, UserSettingsHub settings_hub) + : base(module, TimeAndSalesWindow.WINDOW_TYPE_NAME) { _bus = bus; _consumer = consumer; _settings_hub = settings_hub; - _security_auxiliary_model = security_auxiliary_model; _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s), bus.subscribe(SparkTags.ShowTimeAndSalesTag).OnDispatcher().Subscribe(show) @@ -55,7 +50,6 @@ state, settings_man, conf.can_pause_updates, - _security_auxiliary_model.get_display_quantity_divisor, thread_id); return Task.FromResult(win); } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 03fc74e5c..f96a6a137 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -113,7 +113,7 @@ namespace mbts.spark { current_settings = init; this.settings = settings; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); - display_quantity_divisor = model.order_gateway.security_auxiliary_model.get_display_quantity_divisor(model.security); + display_quantity_divisor = model.sec_meta_store.get_qty_display_divisor(security); size_calculator.display_divisor = display_quantity_divisor; size_calculator.display_settings = model.security_md.quantity_display; _slot_price_vs_orders = new Dictionary(_equality); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index daae5e32d..5a7632135 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -744,15 +744,19 @@ namespace mbts.spark { internal double price_for_point(Point point) => _price_for_row(_row_for_point(point)); - static uint? _size_from_row(int row, IList price_list, NativePriceSize[] depth, ContractSpecificationImmutable spec) { - if (price_list == null || depth == null) return null; - else return row <= price_list.Count ? _size_from_price(price_list[row], depth, spec) : null; - } + static double _size_from_row( + int row, + IList price_list, + NativePriceSize[] depth, + ContractSpecificationImmutable spec) => + price_list is null || depth is null || row >= price_list.Count ? + double.NaN : _size_from_price(price_list[row], depth, spec); - static uint? _size_from_price(double price, NativePriceSize[] depth, ContractSpecificationImmutable spec) { + static double _size_from_price( + double price, NativePriceSize[] depth, ContractSpecificationImmutable spec) { if (!double.IsNaN(price) && depth.TryGetFirst(nps => spec.tick_equals(price, nps.price), out NativePriceSize result)) return result.size; - return null; + return double.NaN; } int _row_for_point(Point point) { @@ -764,10 +768,10 @@ namespace mbts.spark { double _price_for_row(int row) => _price_list == null ? double.NaN : _price_list[row]; - uint? _bid_size_from_row(int row) => + double _bid_size_from_row(int row) => _size_from_row(row, _price_list, _bids, _spec); - uint? _ask_size_from_row(int row) => + double _ask_size_from_row(int row) => _size_from_row(row, _price_list, _asks, _spec); uint _volume_from_row(int row) { @@ -1522,7 +1526,7 @@ namespace mbts.spark { } // This is designed to be a redundant null check for _fmt_mkt_quantity_impl. - string _fmt_mkt_quantity(uint value) { + string _fmt_mkt_quantity(double value) { // Assign the impl delegate to a local variable, just in case it is reassigned on another thread. // This shouldn't happen, but better to avoid the potential null ref just in case it does. Expect the unexpected. var impl = _fmt_mkt_quantity_impl; diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs index fc60056b0..5f4be6760 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs @@ -282,7 +282,7 @@ namespace mbts.spark { VolumeColumnSettings settings, int last_index, string last_size_and_direction, - Func fmt_value) { + Func fmt_value) { // if (!data.Any()) { _clear_visual(dv); @@ -305,8 +305,7 @@ namespace mbts.spark { _clear_visual(dv); return; } - if (fmt_value is null) - fmt_value = FormattingDelegates.default_string(); + fmt_value ??= FormattingDelegates.default_string(); // inflate the max so that the graph never fills the available space double max = data.Max(v => v.Volume) * 1.1; _render_cells(dv, row_height, data.Select(d => (d.Price, d)), settings.general, prices, spec, render_cell); @@ -392,9 +391,15 @@ namespace mbts.spark { } } - internal static void render_last(DrawingVisual dv, GlyphContext glyph_context, NativePriceSize last, int index, double row_height, LadderColumnSettings settings, Func fmt_value) { - if (fmt_value is null) - fmt_value = FormattingDelegates.default_string(); + internal static void render_last( + DrawingVisual dv, + GlyphContext glyph_context, + NativePriceSize last, + int index, + double row_height, + LadderColumnSettings settings, + Func fmt_value) { + fmt_value ??= FormattingDelegates.default_string(); using (var dc = dv.RenderOpen()) { var gr = format_text(fmt_value(last.size), index, row_height, settings, glyph_context); dc.DrawGlyphRun(settings.foreground.rgb_brush(), gr); @@ -411,14 +416,13 @@ namespace mbts.spark { double row_height, ContractSpecificationImmutable spec, LadderColumnSettings settings, - Func fmt_value) { + Func fmt_value) { // using (var dc = dv.RenderOpen()) { using (_draw_with_clip(dc, settings, row_height, prices.Count)) { if (!prices.within_range(origin_index) || pvp.is_null_or_empty()) return; - if (fmt_value is null) - fmt_value = FormattingDelegates.default_string(); + fmt_value ??= FormattingDelegates.default_string(); var foreground = settings.foreground.rgb_brush(); int curr_index = origin_index; double curr_price = prices[curr_index]; diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs index 2a849c0a1..daa4ff1e9 100644 --- a/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs +++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsModel.cs @@ -120,6 +120,6 @@ namespace bts.shell.manual_fills { await _model.update_manual_fills(fills); public double get_display_qty_divisor(SecurityImmutable? security) => - _model.security_auxiliary_model.get_display_quantity_divisor(security); + _model.sec_meta_store.get_qty_display_divisor(security); } } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 5ceec571b..2978776ac 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -19,6 +19,7 @@ using mbts.ui.spark; using mbts.ui.utility; using mbts.utils; +using Spark.Api.Domain; using Spark.Core.Collections; using Spark.Core.Data; using Spark.Core.Disposables; @@ -747,7 +748,7 @@ namespace mbts.spark { public OrderMetadata get_metadata(OrderBookRowVM row) => _model.factory.get_metadata(row.order.actual_order_type()); internal double get_display_qty_divisor(SecurityImmutable? security) => - _model.security_auxiliary_model.get_display_quantity_divisor(security); + _model.sec_meta_store.get_qty_display_divisor(security); internal void show_order_modify(OrderBookRowVM row) => _bus.post(SparkTags.ShowModifyOrderTag, row.order_key); diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs index 1c4c571c7..2dd719f88 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLCellIndexBuilder.cs @@ -1,3 +1,4 @@ +using bts.api.domain; using bts.utils; using mbts.spark; @@ -16,9 +17,9 @@ namespace bts.shell.pnl { public readonly DIYGridAnimationModel animation_model = new DIYGridAnimationModel(TimeSpan.FromSeconds(0.3)); static Func _fmt_working_order_data( - Func fmt_qty) => + TickDisplaySettingsImmutable? qty_display) => d => OrderUtils.order_collection_summary( - d.top_price, d.display_top_volume, d.display_working_total, fmt_qty); + d.top_price, d.display_top_volume, d.display_working_total, qty_display); static readonly IComparer _working_total_comparer = Comparer.Default.wrap(d => d.working_total); @@ -73,7 +74,7 @@ namespace bts.shell.pnl { PNLView.Columns key, Func get, Func get_market, - Func fmt_qty) => + TickDisplaySettingsImmutable? qty_display) => _add_working( key, BTSColors.MarketData.bid, @@ -81,13 +82,13 @@ namespace bts.shell.pnl { get, get_market, OrderDataHelper.PriceComparer, - fmt_qty); + qty_display); public PNLCellVM add_working_short( PNLView.Columns key, Func get, Func get_market, - Func fmt_qty) => + TickDisplaySettingsImmutable? qty_display) => _add_working( key, BTSColors.MarketData.ask, @@ -95,7 +96,7 @@ namespace bts.shell.pnl { get, get_market, new ReverseComparer(OrderDataHelper.PriceComparer), - fmt_qty); + qty_display); PNLCellVM _add_working( PNLView.Columns key, @@ -104,7 +105,7 @@ namespace bts.shell.pnl { Func get, Func get_market, IComparer price_comparer, - Func fmt_qty) { + TickDisplaySettingsImmutable? qty_display) { var delta_trig = DIYGridTriggerAnimations.delta_trigger(key, increase, decrease) .wrap(r => get(r).working_total); var top_of_book_trig = new TopOfBookTrigger(key, increase, @@ -119,7 +120,7 @@ namespace bts.shell.pnl { var cell = add( key, get, - _fmt_working_order_data(fmt_qty), + _fmt_working_order_data(qty_display), EqualityComparer.Default, _working_total_comparer); animation_model.add_trigger(delta_trig); diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLRowVM.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLRowVM.cs index 7d6aad25c..f43927472 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLRowVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLRowVM.cs @@ -92,11 +92,15 @@ namespace bts.shell.pnl { // working working_net_pos = _cell_map.add_net_pos( ColumnKeys.WorkingNetPos, d => d.display_working_net_pos, fmt_qty); + var qty_display = _sec_meta_store.get_qty_display(security); working_long_pos = _cell_map.add_working_long( - ColumnKeys.WorkingLongPos, d => d.working.long_data, d => d.bid_price, fmt_qty); + ColumnKeys.WorkingLongPos, + d => d.working.long_data, + d => d.bid_price, + qty_display); working_long_avg_price = _cell_map.add_long_price(ColumnKeys.WorkingLongAvgPrice, d => d.working_long_avg_price); working_short_pos = _cell_map.add_working_short( - ColumnKeys.WorkingShortPos, r => r.working.short_data, r => r.ask_price, fmt_qty); + ColumnKeys.WorkingShortPos, r => r.working.short_data, r => r.ask_price, qty_display); working_short_avg_price = _cell_map.add_short_price(ColumnKeys.WorkingShortAvgPrice, d => d.working_short_avg_price); // total total_pnl = _cell_map.add_pnl_double(ColumnKeys.TotalPNL, d => d.total_pnl); @@ -293,7 +297,7 @@ namespace bts.shell.pnl { return _quantity_display_backing.Value; } if (security.HasValue) { - _quantity_display_backing = _sec_meta_store.get(security.Value)?.QuantityDisplay; + _quantity_display_backing = _sec_meta_store.get_qty_display(security.Value); } return _quantity_display_backing ??= Security.Defaults.quantity_display_settingsi; } diff --git a/src/client/spark/Notifications/INotificationService.cs b/src/client/spark/Notifications/INotificationService.cs index b43008de4..d44017bee 100644 --- a/src/client/spark/Notifications/INotificationService.cs +++ b/src/client/spark/Notifications/INotificationService.cs @@ -63,10 +63,11 @@ namespace bts.shell { orders_model.on_orders.Subscribe(_on_orders), TradesSource.create( consumer, - bus.subscribe(SparkTags.SecuritiesTag).BufferLatest(TimeSpan.FromSeconds(2)) - .Table(s => s.security.Id) - .Where(t => t.has_changes()) - .Select(m => MappedDictionary.create(m.state, smd => smd.security)), + bus.subscribe(SparkTags.SecuritiesTag) + .BufferLatest(TimeSpan.FromSeconds(2)) + .Table(s => s.security.Id) + .Where(t => t.has_changes()) + .Select(m => m.state), _trade_criteria_subject, TimeSpan.FromSeconds(0.2)) .Subscribe(_trade_notifications.process_items)); diff --git a/src/client/spark/Orders/ExistingOrderTicketVM.cs b/src/client/spark/Orders/ExistingOrderTicketVM.cs index ee00d0036..49e7b85fa 100644 --- a/src/client/spark/Orders/ExistingOrderTicketVM.cs +++ b/src/client/spark/Orders/ExistingOrderTicketVM.cs @@ -1,5 +1,6 @@ using bts; using bts.api; +using bts.api.domain; using bts.api.orderman; using mbts.ui; @@ -22,12 +23,13 @@ namespace mbts.spark { readonly Property _current_time_in_force; readonly Property _current_order_type; readonly Property _price_dirty, _size_dirty, _account_dirty, _time_in_force_dirty, _order_type_dirty; - double _display_quantity_divisor = 1; + readonly Property _qty_display; public ExistingOrderTicketVM( OrdersModel model, IObservable<(SecurityMD? security_md, OrderRecordImmutable order)> order_source, - IObservable calculator_buttons + IObservable calculator_buttons, + TickDisplaySettingsImmutable? qty_display ) { uint? key = null; var security_md_source = order_source.Where(ot => ot.security_md.HasValue).Select(ot => ot.security_md.Value); @@ -35,6 +37,8 @@ namespace mbts.spark { _security = backing(nameof(security), security_md_source.Select(smd => smd.security), Security.Defaults.SecurityImmutable); properties_vm = new OrderPropertiesEditorVM(model, security_md_source, order_source.Select(ot => new InlineOrderProperties(model, ot.order.Def))); _price = backing(nameof(price), double.NaN); + _qty_display = backing( + nameof(this.qty_display), qty_display ?? Security.Defaults.quantity_display_settingsi); size_calculator = new(null, calculator_buttons); _current_price = backing(nameof(current_price), order_source.Select(ort => ort.order.State.Price)); _current_size = backing(nameof(current_size), order_source.Select(ort => ort.order.State.Quantity)); @@ -94,7 +98,7 @@ namespace mbts.spark { properties_vm, security_md_source.OnDispatcher().Subscribe(smd => { bbo.security_md = smd; - display_quantity_divisor = model.security_auxiliary_model.get_display_quantity_divisor(smd.security); + qty_display = smd.quantity_display; size_calculator.display_settings = smd.quantity_display; }), bbo, @@ -117,13 +121,12 @@ namespace mbts.spark { public OrderPropertiesEditorVM properties_vm { get; } public double price { get => _price.Value; set => _price.Value = value; } public CalculatorLogic size_calculator { get; } - public double display_quantity_divisor { - get => _display_quantity_divisor; - private set { - Set(ref _display_quantity_divisor, value); - size_calculator.display_divisor = value; - } + + public TickDisplaySettingsImmutable qty_display { + get => _qty_display.Value; + set => _qty_display.set(value); } + public double current_price => _current_price.Value; public uint current_size => _current_size.Value; public AccountTuple current_account => _current_account.Value; diff --git a/src/client/spark/Orders/NewOrderTicketVM.cs b/src/client/spark/Orders/NewOrderTicketVM.cs index f0dfd8910..5eedcc99d 100644 --- a/src/client/spark/Orders/NewOrderTicketVM.cs +++ b/src/client/spark/Orders/NewOrderTicketVM.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.api.domain; using bts.api.orderman; using mbts.ui; @@ -44,7 +45,7 @@ namespace mbts.spark { class NewOrderTicketVM : DisposableViewModelBase, IRequestViewClose { readonly Property _security; - double _display_quantity_divisor = 1; + readonly Property _qty_display; public NewOrderTicketVM(OrdersModel model, SecurityMD security_md, OrderDefinitionImmutable def, double price, double size, IObservable calculator_buttons) : this(model, Observable.Return(security_md), Observable.Return(new InlineOrderTicketProperties(model, def, price, size)), calculator_buttons) { } @@ -59,10 +60,13 @@ namespace mbts.spark { OrdersModel model, IObservable security_md_source, IObservable props_source, - IObservable calculator_buttons + IObservable calculator_buttons, + TickDisplaySettingsImmutable? qty_display = null ) { _security = backing(nameof(security), security_md_source.Select(smd => smd.security), Security.Defaults.SecurityImmutable); properties_vm = new OrderPropertiesEditorVM(model, security_md_source, props_source.Select(p => p.order_props)); + _qty_display = backing( + nameof(this.qty_display), qty_display ?? Security.Defaults.quantity_display_settingsi); bbo = new BBOVM(); size_calculator = new(0, calculator_buttons); send_order = new DelegateCommand(side => { @@ -78,7 +82,7 @@ namespace mbts.spark { bbo, security_md_source.OnDispatcher().Subscribe(smd => { bbo.security_md = smd; - display_quantity_divisor = model.security_auxiliary_model.get_display_quantity_divisor(smd.security); + qty_display = smd.quantity_display; size_calculator.display_settings = smd.quantity_display; }), size_calculator, @@ -103,13 +107,12 @@ namespace mbts.spark { public SecurityImmutable security => _security.Value; public double price { get; set; } public CalculatorLogic size_calculator { get; } - public double display_quantity_divisor { - get => _display_quantity_divisor; - private set { - Set(ref _display_quantity_divisor, value); - size_calculator.display_divisor = value; - } + + public TickDisplaySettingsImmutable qty_display { + get => _qty_display.Value; + set => _qty_display.set(value); } + public OrderPropertiesEditorVM properties_vm { get; } public BBOVM bbo { get; } public bool close_on_send { get; set; } diff --git a/src/client/spark/Orders/OrderModificationControl.xaml b/src/client/spark/Orders/OrderModificationControl.xaml index 7d6c2f554..920af065c 100644 --- a/src/client/spark/Orders/OrderModificationControl.xaml +++ b/src/client/spark/Orders/OrderModificationControl.xaml @@ -121,9 +121,9 @@ CommandParameter="{Binding bbo.bid_size}" Foreground="{u:BTSColor MarketData.bid}" > - - - + + + @@ -159,9 +159,11 @@ Command="{Binding Path=DataContext.click, RelativeSource={RelativeSource AncestorType=ItemsControl}}" > - - - + + + diff --git a/src/client/spark/Orders/OrderTypeVMs/IcebergOrderVM.cs b/src/client/spark/Orders/OrderTypeVMs/IcebergOrderVM.cs index 61bb1617f..e33323f30 100644 --- a/src/client/spark/Orders/OrderTypeVMs/IcebergOrderVM.cs +++ b/src/client/spark/Orders/OrderTypeVMs/IcebergOrderVM.cs @@ -1,7 +1,10 @@ -using bts.api.orderman; +using bts.api; +using bts.api.domain; +using bts.api.orderman; -using mbts.ui; +using mbts.ui.shell; +using Spark.Api.Domain; using Spark.Core.Disposables; using System; @@ -11,72 +14,52 @@ using System.Reactive.Linq; namespace mbts.spark { static partial class OrderTypeVMFactory { class IcebergOrderVM : OrderTypeVMBase { - readonly Property _show_quantity; - readonly DisplayQuantityMultiplier _display_qty_translator = - DisplayQuantityMultiplier.create_double(); + readonly Property _show_quantity; + readonly DelegateProperty _qty_display; new IDisposable _dispose; public IcebergOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) : base(key, display_name, editing_permissions) { - _show_quantity = add_property( - "show_quantity", + _qty_display = backing( + nameof(qty_display), + () => try_get_qty_display() ?? Security.Defaults.quantity_display_settingsi); + _show_quantity = add_nullable_property( + nameof(show_quantity), IcebergOrderDefinition.ShowQuantityFieldNumber, - double.NaN, - double.NaN, - to_display_value: v => _qty_conversion.to_display(v), - from_display_value: v => _qty_conversion.from_display(v), - refresh_display_value: - Observable.Create(o => { - _request_refresh_display += refresh; - return Disposable.Create(() => _request_refresh_display -= refresh); - void refresh() => - o.OnNext(Unit.Default); - })); - _show_quantity.Changed += on_show_quantity_changed; - _dispose = Disposable.Create( - _display_qty_translator.connect_owner(this, nameof(display_show_quantity)), - _display_qty_translator.subscribe_actual_value().Subscribe(v => _show_quantity.Value = v), - Disposable.Create(() => _show_quantity.Changed -= on_show_quantity_changed)); + init_value: double.NaN, + validate_on_changed: true, + refresh_display_value: Observable.FromEvent, Unit>( + cb => (o, n) => cb(Unit.Default), + cb => _qty_display.Changed += cb, + cb => _qty_display.Changed -= cb)); - void on_show_quantity_changed(double oldval, double newval) => - _display_qty_translator.actual_value = newval; - } - - event Action _request_refresh_display; - - public double display_show_quantity { - get => _display_qty_translator.display_value; - set => _display_qty_translator.display_value = value; - } - - QuantityConversionData _qty_conversion { - get => _display_qty_translator.conversion_data; - set { - if (_display_qty_translator.conversion_data != value) { - _display_qty_translator.conversion_data = value; - _request_refresh_display?.Invoke(); + TickDisplaySettingsImmutable? try_get_qty_display() { + if (security_md.HasValue) { + return security_md.Value.quantity_display; } + if (security.HasValue && model is not null) { + return model.sec_meta_store.get(security.Value)?.qty_display() ?? + Security.Defaults.quantity_display_settingsi; + } + return null; } } + public double? show_quantity { + get => _show_quantity.Value; + set => _show_quantity.set(value); + } + + public TickDisplaySettingsImmutable qty_display { + get => _qty_display.Value; + set => _qty_display.set(value); + } + protected override void on_model_internal() => - _refresh_display(); + _qty_display.refresh(); protected override void on_security_internal() => - _refresh_display(); - - void _refresh_display() { - if (model == null) { - _qty_conversion = default; - } else { - var divisor = model.security_auxiliary_model.get_display_quantity_divisor(security); - if (divisor == 1 || divisor == 0) { - _qty_conversion = default; - } else { - _qty_conversion = new(divisor, QuantityConversionOpType.DivideActual); - } - } - } + _qty_display.refresh(); protected override void Dispose(bool disposing) { Disposable.dispose(ref _dispose); diff --git a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs index f9e503f2a..931ccc649 100644 --- a/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs +++ b/src/client/spark/Orders/OrderTypeVMs/OrderTypeVMFactory.cs @@ -428,9 +428,22 @@ namespace mbts.spark { return prop; } - protected Property add_nullable_property(string prop_name, int target_field_number, T init_value = default, bool validate_on_changed = false, AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite) where T : struct { + protected Property add_nullable_property( + string prop_name, + int target_field_number, + T init_value = default, + bool validate_on_changed = false, + AlgoParamPermissions permissions = AlgoParamPermissions.ReadWrite, + IObservable refresh_display_value = null) where T : struct { var prop = backing(prop_name, init_value); - _on_nullable_property_added(prop_name, target_field_number, prop, prop.set, validate_on_changed, permissions); + _on_nullable_property_added( + prop_name, + target_field_number, + prop, + prop.set, + validate_on_changed, + permissions, + refresh_display_value); return prop; } @@ -624,17 +637,39 @@ namespace mbts.spark { } } - void _on_nullable_property_added(string prop_name, int target_field_number, IProperty prop, Action assign_to_prop, bool validate_on_changed, AlgoParamPermissions permissions) where T : struct { + void _on_nullable_property_added( + string prop_name, + int target_field_number, + IProperty prop, + Action assign_to_prop, + bool validate_on_changed, + AlgoParamPermissions permissions, + IObservable refresh_display_value = null) where T : struct { var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number); var param = new AlgoParamVM(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions }; _algo_params.Add(param); - _auto_props.Add(new AutoProp(prop_name, mval => { - if (mval != null && prop.Value.HasValue) - field_desc.Accessor.SetValue(mval, prop.Value.Value); - }, - mval => assign_to_prop_and_commit(mval == null ? default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), - mvals => assign_to_prop_and_commit(mvals.Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))).Distinct().TryGetSingle(out T dv) ? dv : (T?)null), - _link_props(param, prop, assign_to_prop, null, validate_on_changed))); + + var prop_hook = _link_props(param, prop, assign_to_prop, null, validate_on_changed); + if (refresh_display_value != null) { + prop_hook = Disposable.Create( + refresh_display_value.Subscribe(_ => param.refresh_display_value()), + prop_hook); + } + + _auto_props.Add(new AutoProp( + prop_name, + mval => { + if (mval != null && prop.Value.HasValue) + field_desc.Accessor.SetValue(mval, prop.Value.Value); + }, + mval => assign_to_prop_and_commit(mval is null ? + default : ConvertUtils.try_convert(field_desc.Accessor.GetValue(mval))), + mvals => assign_to_prop_and_commit(mvals + .Select(v => ConvertUtils.try_convert(field_desc.Accessor.GetValue(v))) + .Distinct() + .TryGetSingle(out var dv) ? dv : null), + prop_hook)); + void assign_to_prop_and_commit(T? value) { assign_to_prop(value); param.mark_committed(); diff --git a/src/client/spark/Orders/OrderUtils.cs b/src/client/spark/Orders/OrderUtils.cs index 975f9856b..64cd6d3df 100644 --- a/src/client/spark/Orders/OrderUtils.cs +++ b/src/client/spark/Orders/OrderUtils.cs @@ -1,5 +1,6 @@ using bts; using bts.api; +using bts.api.domain; using bts.api.orderman; using bts.co2; using bts.spark; @@ -379,26 +380,28 @@ namespace mbts.spark { double best_price, double best_price_volume, double total_volume, - Func fmt_qty = null) => + TickDisplaySettingsImmutable? qty_display = null) => order_collection_summary( best_price, best_price_volume, total_volume, Security.Defaults.ContractSpecificationImmutable, - fmt_qty); + qty_display); public static string order_collection_summary( double best_price, double best_price_volume, double total_volume, ContractSpecificationImmutable spec, - Func fmt_qty = null) { + TickDisplaySettingsImmutable? qty_display = null) { if (total_volume == 0) return string.Empty; - fmt_qty ??= v => v.ToString(); return total_volume == best_price_volume ? $"{fmt_qty(best_price_volume)} @ {spec.format(best_price)}" : $"{fmt_qty(best_price_volume)} ({fmt_qty(total_volume)}) @ {spec.format(best_price)}"; + + string fmt_qty(double value) => + qty_display?.format(value) ?? value.ToString(); } public static string order_collection_summary( diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index 483c87d66..9e3870b10 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -17,6 +17,7 @@ using Spark.Api.Position; using Spark.Api.Reactive; + using Spark.Core.Data; using Spark.Core.Disposables; using Spark.Core.Reactive; using Spark.Model.Trading; @@ -40,7 +41,7 @@ class OrdersModel : IDisposable { public static readonly bool piq_enabled = Configuration.get().enabled; public readonly MarketDataAuxiliaryModel md_auxiliary_model; - public readonly ISecurityAuxiliaryDataModel security_auxiliary_model; + public readonly ISecurityMetadataStore sec_meta_store; readonly IBus _bus; readonly IAlgoProvider _algo_provider, _attachable_algo_provider; @@ -72,7 +73,7 @@ DynamicOrderHelper dynamic_helper, AdminModel admin_model, IAlgoStudioModel algo_model, - ISecurityAuxiliaryDataModel security_auxiliary_model, + ISecurityMetadataStore sec_meta_store, MarketDataAuxiliaryModel md_auxiliary_model, IAlgoProvider algo_provider, IAttachableAlgoProvider attachable_algo_provider, @@ -93,7 +94,7 @@ this.admin_model = admin_model; this.algo_model = algo_model; this.md_auxiliary_model = md_auxiliary_model; - this.security_auxiliary_model = security_auxiliary_model; + this.sec_meta_store = sec_meta_store; var scheduler = ThreadPoolScheduler.Instance; var interval = TimeSpan.FromMilliseconds(100); diff --git a/src/client/spark/Security/ISecurityAuxiliaryDataModel.cs b/src/client/spark/Security/ISecurityAuxiliaryDataModel.cs deleted file mode 100644 index c59ddc197..000000000 --- a/src/client/spark/Security/ISecurityAuxiliaryDataModel.cs +++ /dev/null @@ -1,51 +0,0 @@ -using bts.api; -using bts.utils; - -using mbts.config; - -using Spark.Core; - -using System.Collections.Generic; -using System.Composition; - -namespace mbts.spark { - interface ISecurityAuxiliaryDataModel { - SecurityAuxiliaryData? get_auxiliary_data(SecurityImmutable security); - } - - readonly struct SecurityAuxiliaryData { - public SecurityAuxiliaryData(uint quantity_divisor) => - this.quantity_divisor = quantity_divisor; - - public static SecurityAuxiliaryData Default => new SecurityAuxiliaryData(1); - - public uint quantity_divisor { get; } - } - - [Export(typeof(ISecurityAuxiliaryDataModel))] - class SecurityAuxiliaryDataModel : ISecurityAuxiliaryDataModel { - readonly Dictionary _auxiliary_data = new Dictionary(); - - public SecurityAuxiliaryDataModel() { - var sym_config = Configuration.get(); - var sym_config_items = Configuration.get().items; - foreach (var item in sym_config_items) - _auxiliary_data[item.symbol] = new SecurityAuxiliaryData(item.display_quantity_divisor); - } - - public SecurityAuxiliaryData? get_auxiliary_data(SecurityImmutable security) => - security.ToString().safe_contains("ICE Lots") ? - new SecurityAuxiliaryData(1) : - _auxiliary_data.TryGetValue(security.Symbol, out var d) ? d : (SecurityAuxiliaryData?)null; - } - - static class SecurityAuxiliaryDataModelExtensions { - public static double get_display_quantity( - this ISecurityAuxiliaryDataModel model, SecurityImmutable? security, double actual_qty) => - actual_qty.safe_divide(model.get_display_quantity_divisor(security)); - - public static double get_display_quantity_divisor( - this ISecurityAuxiliaryDataModel model, SecurityImmutable? security) => - security.HasValue ? model.get_auxiliary_data(security.Value)?.quantity_divisor ?? 1 : 1; - } -} diff --git a/src/client/spark/Trades/TradeInfo.cs b/src/client/spark/Trades/TradeInfo.cs index 9aea69a09..82067d117 100644 --- a/src/client/spark/Trades/TradeInfo.cs +++ b/src/client/spark/Trades/TradeInfo.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.api.domain; using bts.co2; using mbts.analytics; @@ -7,32 +8,36 @@ using Spark.Core; namespace mbts.spark { struct TradeInfo { - public readonly SecurityImmutable security; + public readonly SecurityMD security_md; public readonly TradeMessageImmutable trade; public readonly GreeksTuple? greeks_tuple; public readonly double volume; public TradeInfo( - SecurityImmutable security, + SecurityMD security_md, TradeMessageImmutable trade, GreeksTuple? greeks_tuple = null, - double volume = double.NaN) { - this.security = security; + double volume = double.NaN + ) { + this.security_md = security_md; this.trade = trade; this.greeks_tuple = greeks_tuple; this.volume = volume; } + + public SecurityImmutable security => security_md.security; + public TickDisplaySettingsImmutable qty_display => security_md.quantity_display; } static class TradeInfoExtensions { public static TradeInfo with( this in TradeInfo trade_info, - SecurityImmutable? security = null, + SecurityMD? security_md = null, TradeMessageImmutable? trade = null, Optional greeks_tuple = default, double? volume = null) => new( - security ?? trade_info.security, + security_md ?? trade_info.security_md, trade ?? trade_info.trade, greeks_tuple.value_or(trade_info.greeks_tuple), volume ?? trade_info.volume); diff --git a/src/client/spark/Trades/TradesSource.cs b/src/client/spark/Trades/TradesSource.cs index 63654b548..26144541a 100644 --- a/src/client/spark/Trades/TradesSource.cs +++ b/src/client/spark/Trades/TradesSource.cs @@ -9,6 +9,7 @@ using mbts.co2; using mbts.utils; + using Spark.Core.Data; using Spark.Core.Disposables; using System; @@ -51,15 +52,15 @@ static class TradesSource { public static IEnumerable aggregate_security_criteria( - IEnumerable securities, + IEnumerable security_mds, IEnumerable security_criteria_items) => - securities.Where(s => security_criteria_items.Any(sc => sc.includes(s))) - .Select(Product.from_security) + security_mds.Where(s => security_criteria_items.Any(sc => sc.includes(s.security))) + .Select(s => Product.from_security(s.security)) .Distinct(); public static IObservable> create( MDConsumer consumer, - IObservable> security_map, + IObservable> security_map, IObservable> security_criteria, TimeSpan poll_interval) => security_criteria @@ -75,7 +76,7 @@ if (!channels.TryGetValue(p, out var c)) { c = new ChannelConsumer( consumer.get_channel(p.symbol, p.type, p.exchange), - map.Values.Where(s => Product.from_security(s).Equals(p))); + map.Values.Where(s => Product.from_security(s.security).Equals(p))); channels = channels.Add(p, c); } active.Add(c); @@ -130,21 +131,22 @@ class ChannelConsumer { readonly MDConsumerChannel _channel; - readonly Dictionary _securities; + readonly Dictionary _security_mds; long _cursor = 0; public ChannelConsumer(MDConsumerChannel channel) => _channel = channel; - public ChannelConsumer(MDConsumerChannel channel, IEnumerable securities) { + public ChannelConsumer(MDConsumerChannel channel, IEnumerable security_mds) { _channel = channel; - _securities = securities.ToDictionaryCrushed(s => s.Id); + _security_mds = security_mds.ToDictionaryCrushed(s => s.id); } public IEnumerable read_trades() { foreach (var tm in _channel.read_trades(ref _cursor)) { - if (tm != null && _securities.TryGetValue(tm.Key, out SecurityImmutable sec)) - yield return new TradeInfo(sec, new TradeMessageImmutable(tm)); + if (tm != null && _security_mds.TryGetValue(tm.Key, out var smd)) + yield return new TradeInfo( + smd, new TradeMessageImmutable(tm)); } } } diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index 84f459c1f..b6cee7fe9 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -89,7 +89,8 @@ namespace bts.spark { 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) => + public static PartialCommand<(OrderDefinitionImmutable def, double price, double size)> ShowOrderTicket( + KeyGesture key_gesture = null) => SparkCommand.create("Order Ticket", Icons.AddOrders, SparkTags.ShowOrderTicketTag, key_gesture); public static PartialCommand ShowOrderTicketFromSecurity(KeyGesture key_gesture = null) => diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index 215e9a18a..ab84187c7 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -61,8 +61,8 @@ namespace mbts.spark { public static ITag> ShowOrderTicketAutoLookupTag { get; } = _mk_tag>(); public static ITag ShowOrderTicketFromSecurityTag { get; } = _mk_tag(); - public static ITag<(OrderDefinitionImmutable def, double price, uint size)> ShowOrderTicketTag { get; } = - _mk_tag<(OrderDefinitionImmutable def, double price, uint size)>(); + public static ITag<(OrderDefinitionImmutable def, double price, double size)> ShowOrderTicketTag { get; } = + _mk_tag<(OrderDefinitionImmutable def, double price, double size)>(); public static ITag RFQSend { get; } = _mk_tag(); public static ITag> RFQDialog { get; } = _mk_tag>(); diff --git a/src/client/spark/view/Controls/DIYGrid/CellProperty.cs b/src/client/spark/view/Controls/DIYGrid/CellProperty.cs index 6629029d6..5b9acb84b 100644 --- a/src/client/spark/view/Controls/DIYGrid/CellProperty.cs +++ b/src/client/spark/view/Controls/DIYGrid/CellProperty.cs @@ -1,5 +1,7 @@ using mbts.ui.shell; +using Spark.Core.Disposables; + using System; using System.Reactive.Linq; using System.Reactive.Subjects; @@ -21,7 +23,7 @@ namespace mbts.spark { value = initial_value; } - protected event Action<(T oldval, T newval)> _value_set; + public event Action<(T oldval, T newval)> changed; public T value { get; private set; } public string text => _text ?? (_text = _format(value)); @@ -46,11 +48,11 @@ namespace mbts.spark { public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(T value) { - if (_value_set != null) { + if (changed != null) { T prev = this.value; this.value = value; _text = null; - _value_set.Invoke((prev, value)); + changed.Invoke((prev, value)); } else { this.value = value; _text = null; @@ -58,7 +60,29 @@ namespace mbts.spark { } public IDisposable Subscribe(IObserver<(T oldval, T newval)> observer) => - Observable.FromEvent, (T oldval, T newval)>(cb => _value_set += cb, cb => _value_set -= cb) + Observable.FromEvent, (T oldval, T newval)>(cb => changed += cb, cb => changed -= cb) .Subscribe(observer); + + /// + /// Invokes a callback whenever changes. This method has less overhead + /// than IObservable<(T, T)>.Subscribe (doesn't use locks, try/catch error handling, etc.). As + /// a simple event hookup, the callback is invoked immediately, and is thus always on the same + /// thread as the one that changed the value. + /// + public IDisposable subscribe_event(Action<(T oldval, T newval)> callback) { + changed += callback; + return Disposable.Create(() => changed -= callback); + } + + public IDisposable invalidate_on_change(params string[] props) { + changed += on_changed; + return Disposable.Create(() => changed -= on_changed); + + void on_changed((T oldval, T newval) obj) { + for (int i = 0; i < props.Length; i++) { + _owner.raise_notify_property_changed(props[i]); + } + } + } } } diff --git a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml index c908be7f6..25c9ab3cc 100644 --- a/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml +++ b/src/client/spark/view/Controls/Order/AlgoContentTemplateSelector.xaml @@ -1232,11 +1232,11 @@ Margin="{StaticResource Margin.LP1}" ToolTip="Maximum size to show on exchange, this is the BTS provided iceberg" /> - + Value="{Binding show_quantity}" /> _security_md?.security; @@ -27,8 +28,8 @@ namespace mbts.spark { } public double bid => _bid; public double ask => _ask; - public uint bid_size => _bid_size; - public uint ask_size => _ask_size; + public double bid_size => _bid_size; + public double ask_size => _ask_size; void _begin_polling() { Disposable.dispose(ref _md_poll); diff --git a/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs b/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs index 3efcae696..f7e202544 100644 --- a/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs +++ b/src/client/spark/view/Spark/Utilities/ISecurityMDPump.cs @@ -12,15 +12,15 @@ using System.Reactive.Subjects; namespace mbts.spark.utilities { internal interface ISecurityMDPump { - IObservable<(double bid, uint bid_size, double ask, uint ask_size)> bbo { get; } - IObservable<(double last, uint last_size, DateTime time_stamp, ulong volume)> last_trade { get; } + IObservable<(double bid, double bid_size, double ask, double ask_size)> bbo { get; } + IObservable<(double last, double last_size, DateTime time_stamp, double volume)> last_trade { get; } IObservable bid_price { get; } - IObservable bid_size { get; } + IObservable bid_size { get; } IObservable ask_price { get; } - IObservable ask_size { get; } + IObservable ask_size { get; } IObservable last_price { get; } - IObservable last_size { get; } - IObservable volume { get; } + IObservable last_size { get; } + IObservable volume { get; } IObservable session_low { get; } IObservable session_high { get; } IObservable settlement_price { get; } @@ -59,8 +59,8 @@ namespace mbts.spark.utilities { private ulong _bbo_ref, _last_ref; private double _bid_price, _ask_price, _last_price; - private uint _bid_size, _ask_size, _last_size; - private ulong _volume; + private double _bid_size, _ask_size, _last_size; + private double _volume; private DateTime _last_time; private bool _refresh_bbo(IMDConsumerHandle md) { @@ -85,19 +85,23 @@ namespace mbts.spark.utilities { return false; } - private (double, uint, double, uint) _select_bbo() { return (_bid_price, _bid_size, _ask_price, _ask_size); } - private (double, uint, DateTime, ulong) _select_last() { return (_last_price, _last_size, _last_time, _volume); } + private (double, double, double, double) _select_bbo() { return (_bid_price, _bid_size, _ask_price, _ask_size); } + private (double, double, DateTime, double) _select_last() { return (_last_price, _last_size, _last_time, _volume); } + + public IObservable<(double bid, double bid_size, double ask, double ask_size)> bbo => + _bbo_pump.Select(_ => _select_bbo()).StartWith(_select_bbo()); + + public IObservable<(double last, double last_size, DateTime time_stamp, double volume)> last_trade => + _last_pump.Select(_ => _select_last()).StartWith(_select_last()); - public IObservable<(double bid, uint bid_size, double ask, uint ask_size)> bbo => _bbo_pump.Select(_ => _select_bbo()).StartWith(_select_bbo()); - public IObservable<(double last, uint last_size, DateTime time_stamp, ulong volume)> last_trade => _last_pump.Select(_ => _select_last()).StartWith(_select_last()); public IObservable bid_price => _bbo_pump.Select(_ => _bid_price).DistinctUntilChanged().StartWith(_bid_price); - public IObservable bid_size => _bbo_pump.Select(_ => _bid_size).DistinctUntilChanged().StartWith(_bid_size); + public IObservable bid_size => _bbo_pump.Select(_ => _bid_size).DistinctUntilChanged().StartWith(_bid_size); public IObservable ask_price => _bbo_pump.Select(_ => _ask_price).DistinctUntilChanged().StartWith(_ask_price); - public IObservable ask_size => _bbo_pump.Select(_ => _ask_size).DistinctUntilChanged().StartWith(_ask_size); + public IObservable ask_size => _bbo_pump.Select(_ => _ask_size).DistinctUntilChanged().StartWith(_ask_size); public IObservable last_price => _bbo_pump.Select(_ => _last_price).DistinctUntilChanged().StartWith(_last_price); - public IObservable last_size => _bbo_pump.Select(_ => _last_size).DistinctUntilChanged().StartWith(_last_size); + public IObservable last_size => _bbo_pump.Select(_ => _last_size).DistinctUntilChanged().StartWith(_last_size); public IObservable last_time => _last_pump.Select(_ => _last_time).DistinctUntilChanged().StartWith(_last_time); - public IObservable volume => _last_pump.Select(_ => _volume).DistinctUntilChanged().StartWith(_volume); + public IObservable volume => _last_pump.Select(_ => _volume).DistinctUntilChanged().StartWith(_volume); public IObservable session_low => _root_pump.Select(md => md.session_low).DistinctUntilChanged(); public IObservable session_high => _root_pump.Select(md => md.session_high).DistinctUntilChanged(); public IObservable settlement_price => _root_pump.Select(md => md.settlement_price).DistinctUntilChanged(); diff --git a/src/client/spark_api/Domain/SecurityMetadataExtensions.cs b/src/client/spark_api/Domain/SecurityMetadataExtensions.cs new file mode 100644 index 000000000..436dfb75d --- /dev/null +++ b/src/client/spark_api/Domain/SecurityMetadataExtensions.cs @@ -0,0 +1,40 @@ +#nullable enable +namespace Spark.Api.Domain { + using bts.api.domain; + using bts.utils; + + using mbts; + + public static class SecurityMetadataExtensions { + public static TickDisplaySettingsImmutable? qty_display( + this SecurityMetadataImmutable sec_meta) => + sec_meta.HasQuantityDisplay ? sec_meta.QuantityDisplay : null; + + public static string fmt_qty(this SecurityMetadataImmutable sec_meta, double qty) => + sec_meta.HasQuantityDisplay ? sec_meta.QuantityDisplay.format(qty) : qty.ToString(); + + public static double from_display_qty( + this SecurityMetadataImmutable sec_meta, double display_qty) => + sec_meta.HasQuantityDisplay ? + sec_meta.QuantityDisplay.from_display_value(display_qty) : + display_qty; + + public static double to_display_qty( + this SecurityMetadataImmutable sec_meta, double actual_qty) => + sec_meta.HasQuantityDisplay ? + sec_meta.QuantityDisplay.to_display_value(actual_qty) : + actual_qty; + + public static double get_qty_display_divisor(this SecurityMetadataImmutable sec_meta) => + sec_meta.qty_display()?.get_display_divisor() ?? 1; + + public static double get_display_divisor( + this TickDisplaySettingsImmutable tick_display_settings) { + var disp_mult = tick_display_settings.DisplayMultiplier; + if (!disp_mult.is_real_non_zero()) { + return 1; + } + return 1 / disp_mult; + } + } +} diff --git a/src/client/spark_api/MarketData/MDConsumerHandle.cs b/src/client/spark_api/MarketData/MDConsumerHandle.cs index 1241d5107..4ed8cce4a 100644 --- a/src/client/spark_api/MarketData/MDConsumerHandle.cs +++ b/src/client/spark_api/MarketData/MDConsumerHandle.cs @@ -162,7 +162,7 @@ // Compare bids if (direct.int_price == implied.int_price) { - bid[x] = new NativePriceSize(direct.int_price, direct.size_f, implied.size_f); + bid[x] = new NativePriceSize(direct.int_price, direct.size, implied.size); dbid_idx++; ibid_idx++; } @@ -185,7 +185,7 @@ // Compare asks if (direct.int_price == implied.int_price) { - ask[x] = new NativePriceSize(direct.int_price, direct.size_f, implied.size_f); + ask[x] = new NativePriceSize(direct.int_price, direct.size, implied.size); dask_idx++; iask_idx++; } diff --git a/src/client/spark_api/MarketData/NativePriceSize.cs b/src/client/spark_api/MarketData/NativePriceSize.cs index 0f838752c..88777f0d7 100644 --- a/src/client/spark_api/MarketData/NativePriceSize.cs +++ b/src/client/spark_api/MarketData/NativePriceSize.cs @@ -38,18 +38,15 @@ namespace mbts.co2 { public IntPrice int_price => _price; public long mantissa => _price.mantissa; public sbyte exponent => _price.exponent; - public uint size => (uint)_size; - public uint direct_size => (uint)_direct_size; - public uint implied_size => (uint)(_size - _direct_size); - public Size size_f => _size; - public Size direct_size_f => _direct_size; - public Size implied_size_f => _size - _direct_size; + public Size size => _size; + public Size direct_size => _direct_size; + public Size implied_size => _size - _direct_size; public double price => _price.price(); public bool is_nan => _price.is_nan; public override string ToString() => - $"{price} {size_f} ({implied_size})"; + $"{price} {size} ({implied_size})"; public override bool Equals(object obj) => obj is NativePriceSize p ? Equals(p) : base.Equals(obj); diff --git a/src/client/spark_api/MarketData/NativePriceSizeExtensions.cs b/src/client/spark_api/MarketData/NativePriceSizeExtensions.cs index 6a1d25fff..56abcf83a 100644 --- a/src/client/spark_api/MarketData/NativePriceSizeExtensions.cs +++ b/src/client/spark_api/MarketData/NativePriceSizeExtensions.cs @@ -1,7 +1,7 @@ namespace mbts.co2 { static class NativePriceSizeExtensions { public static NativePriceSize with( - this NativePriceSize nps, uint? direct_size = null, uint? implied_size = null) => + this NativePriceSize nps, float? direct_size = null, float? implied_size = null) => new(nps.int_price, direct_size ?? nps.direct_size, implied_size ?? nps.implied_size); } } diff --git a/src/client/spark_api/data/ISecurityMetadataStore.cs b/src/client/spark_api/data/ISecurityMetadataStore.cs index 3d35c1755..d65a1f5de 100644 --- a/src/client/spark_api/data/ISecurityMetadataStore.cs +++ b/src/client/spark_api/data/ISecurityMetadataStore.cs @@ -2,8 +2,24 @@ namespace Spark.Core.Data { using bts.api; using bts.api.domain; + using bts.utils; + + using Spark.Api.Domain; public interface ISecurityMetadataStore { SecurityMetadataImmutable? get(SecurityImmutable security); } + + public static class SecurityMetadataStoreExtensions { + public static TickDisplaySettingsImmutable? get_qty_display( + this ISecurityMetadataStore sec_meta_store, SecurityImmutable? sec) => + sec.HasValue ? sec_meta_store.get(sec.Value)?.qty_display() : null; + + public static double get_qty_display_divisor( + this ISecurityMetadataStore sec_meta_store, SecurityImmutable? sec) { + var qty_display = sec_meta_store.get_qty_display(sec); + var divisor = qty_display?.get_display_divisor() ?? 1; + return divisor.is_real_non_zero() ? divisor : 1; + } + } } diff --git a/src/client/spark_api/data/ticks/TickExtensions.cs b/src/client/spark_api/data/ticks/TickExtensions.cs index fd7a92bbe..a728057bf 100644 --- a/src/client/spark_api/data/ticks/TickExtensions.cs +++ b/src/client/spark_api/data/ticks/TickExtensions.cs @@ -192,6 +192,38 @@ namespace mbts { return format(display_settings.tick_factors, value, display_settings); } + public static double from_display_value( + this bts.api.domain.TickDisplaySettingsImmutable display_settings, + double display_value, + bool round = true) { + // + var rv = display_value; + if (round && display_settings.HasTickFactors) { + rv = display_settings.TickFactors.round(rv); + } + var display_mult = display_settings.DisplayMultiplier; + if (display_mult.is_real_non_zero()) { + rv /= display_mult; + } + return rv; + } + + public static double to_display_value( + this bts.api.domain.TickDisplaySettingsImmutable display_settings, + double actual_value, + bool round = true) { + // + var rv = actual_value; + var display_mult = display_settings.DisplayMultiplier; + if (display_mult.is_real_non_zero()) { + rv *= display_mult; + } + if (round && display_settings.HasTickFactors) { + rv = display_settings.TickFactors.round(rv); + } + return rv; + } + public static double parse(this TickDisplaySettings display_settings, string text) => parse(display_settings.tick_factors, text, display_settings); diff --git a/src/lib/config/protos/ui.proto b/src/lib/config/protos/ui.proto index 172de7c34..25038b008 100644 --- a/src/lib/config/protos/ui.proto +++ b/src/lib/config/protos/ui.proto @@ -202,12 +202,3 @@ message OffsetAttachUIOptions { message ManualFillsOptions { optional bool modal_transactions = 1 [ default = true ]; } - -message SymbolUIConfigurationItem { - optional string symbol = 1 [ default = "" ]; - optional uint32 display_quantity_divisor = 2 [ default = 1 ]; -} - -message SymbolUIConfiguration { - repeated SymbolUIConfigurationItem items = 1; -}