diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index 6c9278cc5..70cfa834f 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -33,7 +33,7 @@ namespace bts.shell { readonly bool _close_on_send; IReadOnlyDictionary _accounts = new Dictionary(0); IReadOnlyDictionary _md_map; - TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> _orders; + TableUpdate _orders; IDisposable _dispose; [ImportingConstructor] @@ -106,17 +106,23 @@ namespace bts.shell { } void _show_modify_order(uint order_key) { - if (_orders.state.TryGetValue(order_key, out var ori) && ori.sec.HasValue - && (ori.order.HasDef && ori.order.Def.HasCustomDef && !(ori.order.Def.CustomDef.HasStop || ori.order.Def.CustomDef.HasStopLimit))) { - var md = _md_map.TryGetValue(ori.order.security_key()); - _show_order_window(new OrderModificationDialog { - DataContext = new ExistingOrderTicketVM(_model, - Observable.Return((md, ori.order)), - _bus.subscribe(SparkTags.AccountsTag), - Observable.Return(LadderSettings.Default.calculator_buttons) - ) - }); + if (!_orders.state.TryGetValue(order_key, out var ori) || !ori.security.HasValue) { + return; } + switch (ori.order.order_type()) { + case CustomOrderDefinition.CustomOneofCase.Stop: + case CustomOrderDefinition.CustomOneofCase.StopLimit: + case CustomOrderDefinition.CustomOneofCase.None: + return; + } + var md = _md_map.TryGetValue(ori.order.security_key()); + _show_order_window(new OrderModificationDialog { + DataContext = new ExistingOrderTicketVM(_model, + Observable.Return((md, ori.order)), + _bus.subscribe(SparkTags.AccountsTag), + Observable.Return(LadderSettings.Default.calculator_buttons) + ) + }); } LadderSettings _get_settings(SecurityImmutable sec) { diff --git a/src/client/spark/Model/Trading/OrderDataSource.cs b/src/client/spark/Model/Trading/OrderDataSource.cs index ba3186a07..8576d6580 100644 --- a/src/client/spark/Model/Trading/OrderDataSource.cs +++ b/src/client/spark/Model/Trading/OrderDataSource.cs @@ -41,34 +41,34 @@ namespace Spark.Model.Trading { .Naggle(interval, scheduler), o => o.account_id()) .join(sec_resolver, o => o.security_key()) + .Select(o => new OrderRecordTuple(o.val, o.sec), o => o.key) .Table() .Cache(); working_orders = orders.Filter(tup => tup.order.is_active()).Cache(); security_orders = orders - .SelectKeyValue(tup => new OrderSecurity(tup), OrderSecurityHelper.key_fn) - .GroupTable(OrderSecurityHelper.key_fn, tup => tup.order.Def.SecurityKey) + .GroupTable(o => o.key, o => o.security_id) .Cache(); account_security_orders = orders.GroupTable( - t => t.order.Key, - t => new AccountSecurityKey(t.order.account_id(), t.order.security_key())) + o => o.key, + o => new AccountSecurityKey(o.account_id, o.security_id)) .Cache(); working_account_security_orders = working_orders .Filter(o => o.order.is_exchange_order()) .GroupTable( - t => t.order.Key, - t => new AccountSecurityKey(t.order.account_id(), t.order.security_key())) + o => o.key, + o => new AccountSecurityKey(o.account_id, o.security_id)) .Cache(); } - public IObservable> orders { get; } - public IObservable> working_orders { get; } - public IObservable, uint>> security_orders { get; } + public IObservable> orders { get; } + public IObservable> working_orders { get; } + public IObservable, uint>> security_orders { get; } - public IObservable, AccountSecurityKey>> account_security_orders { get; } - public IObservable, AccountSecurityKey>> working_account_security_orders { get; } + public IObservable, AccountSecurityKey>> account_security_orders { get; } + public IObservable, AccountSecurityKey>> working_account_security_orders { get; } } } diff --git a/src/client/spark/Model/Trading/PositionModel.cs b/src/client/spark/Model/Trading/PositionModel.cs index 6df2438e7..940e8ccb6 100644 --- a/src/client/spark/Model/Trading/PositionModel.cs +++ b/src/client/spark/Model/Trading/PositionModel.cs @@ -84,7 +84,7 @@ namespace Spark.Trading { (acc_orders, pnl_id) => { var (security, account_id, account) = acc_orders.table.state.Values.TryGetFirst(out var tup) ? - (tup.sec, tup.order.account_id(), tup.order.account()) : + (tup.security, tup.account_id, tup.account_name) : (null, 0, null); return new PNLRowData(pnl_id, security: security, diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs index 2a5ef7e76..4b38acd7a 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewVM.cs @@ -17,6 +17,7 @@ namespace mbts.spark { using mbts.ui.utility; using mbts.utils; + using Spark.Api.Orders; using Spark.Core; using Spark.Core.Collections; using Spark.Core.Data; @@ -639,7 +640,10 @@ namespace mbts.spark { } OrderBookVM _mk_orderbook_vm_common( - bts.shell.orderbook.FilterStates filters, IEnumerable hide_cols, IObservable> orders_source = null) { + bts.shell.orderbook.FilterStates filters, + IEnumerable hide_cols, + IObservable> orders_source = null + ) { var state = new bts.shell.orderbook.OrderBookStartupData(filters, bts.shell.orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false); state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_cols); var settings_man = new WindowSettingsManager.DisconnectedImpl(state.orderbook_grid); diff --git a/src/client/spark/Modules/Trading/Ladder/LadderModel.cs b/src/client/spark/Modules/Trading/Ladder/LadderModel.cs index d672d6dda..d00ffe1f4 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderModel.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderModel.cs @@ -8,6 +8,7 @@ using bts.md; using mbts.analytics; using mbts.co2; +using Spark.Api.Orders; using Spark.Core.Data; using Spark.Trading; @@ -28,13 +29,14 @@ namespace mbts.spark { IObservable greeks, ISecurityMetadataStore sec_meta_store, MBOService mbo, - Func order_filter = null) { + Func order_filter = null) { security_md = source; _order_gateway = ordergw; this.position_model = position_model; this.fair_value_model = fair_value_model; this.sec_meta_store = sec_meta_store; - orders = ordergw.on_security_working_orders_with_piq(source.security.Id); + orders = ordergw.on_security_working_orders_with_piq(source.security.Id) + .Select(o => new OrderRecordTuple(o.order, o.security, o.piq, o.algo), o => o.key); this.greeks = greeks; this.mbo_service = mbo; if (order_filter != null) { @@ -51,7 +53,7 @@ namespace mbts.spark { public IPositionModel position_model { get; } public FairValueModel fair_value_model { get; } public ISecurityMetadataStore sec_meta_store { get; } - public IObservable> orders { get; } + public IObservable> orders { get; } public IObservable greeks { get; } public MBOService mbo_service { get; } @@ -63,7 +65,7 @@ namespace mbts.spark { IBus bus, ISecurityMetadataStore sec_meta_store, MBOService mbo, - Func order_filter = null) { + Func order_filter = null) { var all_sec_greeks = bus.subscribe(SparkTags.Greeks); var sec_greeks = all_sec_greeks .Select(gs => gs.TryGetValue(source.security.Id) ?? GreeksTuple.empty) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index eb99b2ac2..13514db75 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -47,8 +47,8 @@ namespace mbts.spark { readonly DelegateProperty> _text_lines; readonly DeferrableAction _clear_phantom_price; - ImmutableDictionary _orders = - ImmutableDictionary.Empty; + ImmutableDictionary _orders = + ImmutableDictionary.Empty; LadderSettings.BadgeStyle _current_badge_style; double _phantom_price = double.NaN; double _filled; @@ -57,7 +57,7 @@ namespace mbts.spark { uint? _min_piq = uint.MaxValue; public LadderOrderVM( - ImmutableDictionary orders, + ImmutableDictionary orders, double real_price, LadderVM owner, IObservable badge_style @@ -182,11 +182,11 @@ namespace mbts.spark { public ICommand cancel_cmd => new Command(_cancel); IEnumerable _root_nodes => - _orders.Values.Select(_owner.get_root_at_price).DistinctOn(OrderUtils.RecordKeySelector); + _orders.Values.Select(_owner.get_root_at_price).DistinctOn(o => o.Key); LadderModel _model => _owner.model; - public void sync_orders(ImmutableDictionary new_orders) { + public void sync_orders(ImmutableDictionary new_orders) { _orders = new_orders; min_piq = new_orders.Count == 0 ? null : new_orders.Values.Select(o => o.piq).Min(); } @@ -286,7 +286,7 @@ namespace mbts.spark { obvm.load_from(state); return obvm; - bool order_price_filter(OrderSecurityRootPair o) => + bool order_price_filter(OrderRecordTupleWithRoot o) => o.order.order.ui_price().is_within_range( min_price - MathUtils.EPSILON, max_price + MathUtils.EPSILON); } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 4e39df0a5..3463a77f0 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -97,7 +97,7 @@ namespace mbts.spark { bool _show_raw_day_position; ulong _misc_time = 0; ulong _last_trade_time = 0; - IReadOnlyDictionary _cache = DictionaryHelper.empty(); + IReadOnlyDictionary _cache = DictionaryHelper.empty(); ImmutableDictionary _favorite_algo_metadata_map = ImmutableDictionary.Empty; ContractSpecificationImmutable? _spec; @@ -747,7 +747,7 @@ namespace mbts.spark { } } - internal OrderRecordImmutable get_root_at_price(OrderSecurity op) { + internal OrderRecordImmutable get_root_at_price(OrderRecordTuple op) { double p = _normalize_price(op.order.ui_price()); return lineage(op.order.ParentKey) .Where(o => _equality.Equals(p, _normalize_price(o.ui_price()))) @@ -761,13 +761,13 @@ namespace mbts.spark { } } - static IObservable<(ImmutableSortedDictionary> price_index, IReadOnlyDictionary map)> _order_price_source( - IObservable> source, + static IObservable<(ImmutableSortedDictionary> price_index, IReadOnlyDictionary map)> _order_price_source( + IObservable> source, IComparer price_comp, Func normalize_price ) { - return Observable.Create<(ImmutableSortedDictionary>, IReadOnlyDictionary)>(o => { - var state = ImmutableSortedDictionary.Create>(price_comp); + return Observable.Create<(ImmutableSortedDictionary>, IReadOnlyDictionary)>(o => { + var state = ImmutableSortedDictionary.Create>(price_comp); var sub = source.Subscribe(table => { var bd = state.ToBuilder(); @@ -800,7 +800,7 @@ namespace mbts.spark { bd[price] = index.Add(new_order.order.Key, new_order); } else { bd[price] = ImmutableDictionary.CreateRange(new[] { - new KeyValuePair(new_order.order.Key, new_order) + new KeyValuePair(new_order.order.Key, new_order) }); } } @@ -809,10 +809,10 @@ namespace mbts.spark { return sub; }); - bool price_changed(Change ch) => + bool price_changed(Change ch) => price_comp.Compare(ch.New.order.ui_price(), ch.Old.order.ui_price()) != 0; - double get_price(OrderSecurity order) { + double get_price(OrderRecordTuple order) { var p = order.order.ui_price(); if (!(normalize_price is null)) p = normalize_price(p); diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVMContainer.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVMContainer.cs index fd6ee30bc..08ef6289d 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVMContainer.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVMContainer.cs @@ -7,6 +7,7 @@ namespace mbts.spark { using mbts.ui; using mbts.ui.shell; + using Spark.Api.Orders; using Spark.Core.Data; using Spark.Core.Disposables; using Spark.Trading; @@ -112,8 +113,8 @@ namespace mbts.spark { var settings_src = Observable.Return(LadderSettings.sanitize(LadderSettings.Default)); _value = LadderVM.create_readonly(_bus, model, settings_src); - bool order_filter(OrderSecurity osec) => - _selected_order_tree.Contains(osec.order.Key); + bool order_filter(OrderRecordTuple o) => + _selected_order_tree.Contains(o.order.Key); } } } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs index 99b2d7121..6c5d23eb7 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs @@ -40,7 +40,7 @@ namespace mbts.spark { // This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup. interface ICVOrderBookColumn : IKeyedColumn, IGridColumn { ListSortDirection? SortDirection { get; set; } - IDataGridColumnFilter filter { get; } + IDataGridColumnFilter filter { get; } IComparer comparer { get; } } @@ -76,7 +76,7 @@ namespace mbts.spark { public OrderBookColumnCollection(IBus bus, OrdersModel model, IObservable<(IEnumerable added, IEnumerable removed)> order_securities) { // security Add(security_column = new SecurityColumn( - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( order_securities, ort => ort.order.security ?? Security.Defaults.SecurityImmutable, SecurityCriteria.from_securities, @@ -91,7 +91,7 @@ namespace mbts.spark { DefaultColumnHeaders.Symbol, r => r.symbol, DefaultColumnWidths.Symbol, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList(), ort => ort.order.security?.Symbol ?? string.Empty, nameof(OrderBookRowVM.symbol) @@ -104,7 +104,7 @@ namespace mbts.spark { "Time", r => r.time_created_text, DefaultColumnWidths.Time, - new TimeFilterVM( + new TimeFilterVM( ort => ort.order.order.created(), nameof(OrderBookRowVM.time_created)), DataGridFilterKnownTemplates.TimeFilter, @@ -115,7 +115,7 @@ namespace mbts.spark { "Last Change", r => r.last_change_text, DefaultColumnWidths.Time, - new TimeFilterVM( + new TimeFilterVM( ort => ort.order.order.last_change(), nameof(OrderBookRowVM.last_change)), DataGridFilterKnownTemplates.TimeFilter, @@ -126,7 +126,7 @@ namespace mbts.spark { DefaultColumnHeaders.User, r => r.user, DefaultColumnWidths.User, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( bus.subscribe(SparkTags.Users) .Select(d => d.Values.Select(ut => ut.name).Distinct().Ordered()), ort => ort.order.order.user(), @@ -139,7 +139,7 @@ namespace mbts.spark { DefaultColumnHeaders.Account, r => r.account, DefaultColumnWidths.Account, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( bus.subscribe(SparkTags.AccountsTag) .Select(d => d.Values.Select(ut => ut.name).Distinct().Ordered()), ort => ort.order.order.account(), @@ -154,7 +154,7 @@ namespace mbts.spark { DefaultColumnHeaders.Exchange, r => r.exchange.ToString(), DefaultColumnWidths.Exchange, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( EnumHelper.get_values_except(Venue.Unset).ToList(), ort => ort.order.security.exchange_or_default(), nameof(OrderBookRowVM.exchange)), @@ -166,7 +166,7 @@ namespace mbts.spark { DefaultColumnHeaders.TimeInForce, r => r.time_in_force.ToString(), DefaultColumnWidths.TimeInForce, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( EnumHelper.get_values().ToList(), ort => ort.order.order.time_in_force(), nameof(OrderBookRowVM.time_in_force)), @@ -182,8 +182,8 @@ namespace mbts.spark { nameof(OrderBookRowVM.badge_fill), nameof(OrderBookRowVM.display_name), _wrap_comparer(r => r.order_type), - DiscreteValuesFilterVM.CreateTableUpdate( - o => new AlgoDataVM(o.order.algo), + DiscreteValuesFilterVM.CreateTableUpdate( + o => new AlgoDataVM(o.order.algo ?? AlgoData.empty), vm => AlgoID.from_algo_key(vm.data.key), out var order_type_filter_observer, out var order_type_items_view))); _resources.Add(algo_items_source.Subscribe(order_type_filter_observer)); order_type_items_view.CustomSort = algo_items_comp; @@ -193,9 +193,9 @@ namespace mbts.spark { Columns.RootAlgoType, nameof(OrderBookRowVM.root_algo_badge_fill), nameof(OrderBookRowVM.root_algo_display_name), - _wrap_comparer(r => r.order_tuple.root.algo.value.CustomCase), - DiscreteValuesFilterVM.CreateTableUpdate( - o => new AlgoDataVM(o.root.algo), + _wrap_comparer(r => r.order_tuple.root.algo_type), + DiscreteValuesFilterVM.CreateTableUpdate( + o => new AlgoDataVM(o.root.algo ?? AlgoData.empty), vm => AlgoID.from_algo_key(vm.data.key), out var root_algo_type_observer, out var root_algo_type_items_view), DefaultColumnHeaders.RootAlgoType)); _resources.Add(algo_items_source.Subscribe(root_algo_type_observer)); @@ -207,7 +207,7 @@ namespace mbts.spark { "Sub Type", r => r.order_sub_type_text, 80, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( EnumHelper.get_values().ToList(), ort => ort.order.order.sub_type(), nameof(OrderBookRowVM.order_sub_type)), @@ -215,13 +215,13 @@ namespace mbts.spark { _wrap_comparer(r => r.order_sub_type))); // side Add(side_column = new SideColumn( - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( new[] { Side.Buy, Side.Sell }, ort => ort.order.order.side(), nameof(OrderBookRowVM.side)))); // quantity Add(qty_column = new SizeColumn( - new DoubleMinMax( + new DoubleMinMax( ort => ort.order.order.quantity(), nameof(OrderBookRowVM.quantity)))); // edit quantity column // not usually part of the main order book, but it's useful to add it @@ -229,7 +229,7 @@ namespace mbts.spark { //Add(edit_qty_column = new EditableQtyColumn()); // filled quantity Add(filled_qty_column = new FilledColumn( - new DoubleMinMax( + new DoubleMinMax( ort => ort.order.order.filled_quantity(), nameof(OrderBookRowVM.filled_quantity)))); // price @@ -238,7 +238,7 @@ namespace mbts.spark { "Price", r => r.price_text, DefaultColumnWidths.Price, - new PriceMinMax( + new PriceMinMax( ort => ort.order.order.price(), nameof(OrderBookRowVM.price)), DataGridFilterKnownTemplates.DoubleMinMax, @@ -254,7 +254,7 @@ namespace mbts.spark { "Avg Price", r => r.avg_price_text, DefaultColumnWidths.Price, - new PriceMinMax( + new PriceMinMax( ort => ort.order.order.avg_price(), nameof(OrderBookRowVM.avg_price)), DataGridFilterKnownTemplates.DoubleMinMax, @@ -265,21 +265,21 @@ namespace mbts.spark { "Last Filled", r => r.last_price_text, DefaultColumnWidths.Price, - new PriceMinMax( + new PriceMinMax( ort => ort.order.order.last_price(), nameof(OrderBookRowVM.last_price)), DataGridFilterKnownTemplates.DoubleMinMax, _wrap_comparer(r => r.last_price))); // piq Add(piq_column = new PiqColumn( - new UIntMinMax(ort => ort.order.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq)))); + new UIntMinMax(ort => ort.order.piq ?? uint.MaxValue, nameof(OrderBookRowVM.piq)))); // status Add(status_column = new SimpleTextColumn( Columns.Status, "Status", r => r.status.ToString(), 80, - DiscreteValuesFilterVM.Create( + DiscreteValuesFilterVM.Create( EnumHelper.get_values().ToList(), ort => ort.order.order.status(), nameof(OrderBookRowVM.status)), @@ -287,7 +287,7 @@ namespace mbts.spark { _wrap_comparer(r => r.status))); // last message Add(last_message_column = new OrderBookLastMessageColumn( - new RegexFilterVM( + new RegexFilterVM( ort => ort.order.order.last_msg(), nameof(OrderBookRowVM.last_msg)))); // security key @@ -296,7 +296,7 @@ namespace mbts.spark { DefaultColumnHeaders.SecurityKey, r => r.security_key.ToString(), DefaultColumnWidths.SecurityKey, - new RegexFilterVM( + new RegexFilterVM( ort => ort.order.order.security_key().ToString(), nameof(OrderBookRowVM.security_key)), DataGridFilterKnownTemplates.Regex, @@ -307,7 +307,7 @@ namespace mbts.spark { DefaultColumnHeaders.OrderKey, r => r.order_key.ToString(), DefaultColumnWidths.OrderKey, - new RegexFilterVM( + new RegexFilterVM( ort => ort.order.order.Key.ToString(), nameof(OrderBookRowVM.order_key)), DataGridFilterKnownTemplates.Regex, @@ -318,7 +318,7 @@ namespace mbts.spark { "Parent Key", r => r.parent_order_key.ToString(), DefaultColumnWidths.ParentKey, - new RegexFilterVM( + new RegexFilterVM( ort => ort.order.order.ParentKey.ToString(), nameof(OrderBookRowVM.parent_order_key)), DataGridFilterKnownTemplates.Regex, @@ -329,7 +329,7 @@ namespace mbts.spark { DefaultColumnHeaders.AttachedTargetOrderKey, r => r.order.attached_target_order_key().ToString(), DefaultColumnWidths.AttachedTargetOrderKey, - new RegexFilterVM( + new RegexFilterVM( ort => ort.order.order.attached_target_order_key().ToString(), nameof(OrderBookRowVM.parent_order_key)), DataGridFilterKnownTemplates.Regex, @@ -451,9 +451,9 @@ namespace mbts.spark { } } - public Func get_filter() { + public Func get_filter() { var active_filters = this.OfType().Where(c => c.filter.active.GetValueOrDefault()).Select(c => c.filter).ToArray(); - return active_filters.Length == 0 ? null : new Func(r => active_filters.All(f => f.filter(r))); + return active_filters.Length == 0 ? null : new Func(r => active_filters.All(f => f.filter(r))); } public OrderBookSortingData get_sorting_data() { @@ -554,7 +554,7 @@ namespace mbts.spark { GlyphContext _root_glyph_context, _child_glyph_context; protected OrderbookColumnBase(Columns col_key, string header, Func get_text, double width, - IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) : base(col_key) { + IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) : base(col_key) { id = key.ToString(); Width = width; Header = header; @@ -571,10 +571,10 @@ namespace mbts.spark { } } - public IDataGridColumnPersistentFilter filter { get; } + public IDataGridColumnPersistentFilter filter { get; } public IComparer comparer { get; } - IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; IDataGridColumnFilter IFilterableColumn.filter_model => filter; string IFilterableColumn.filter_template => _filter_template; ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; } @@ -588,7 +588,7 @@ namespace mbts.spark { public class SimpleTextColumn : OrderbookColumnBase, IRenderColumn { public SimpleTextColumn(Columns key, string header, Func get_text, double width, - IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) + IDataGridColumnPersistentFilter filter, string filter_template, IComparer comparer) : base(key, header, get_text, width, filter, filter_template, comparer) { } public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => @@ -608,7 +608,7 @@ namespace mbts.spark { #region Explicit Column Defs public class SideColumn : OrderbookColumnBase, IRenderColumn { - public SideColumn(IDataGridColumnPersistentFilter filter) + public SideColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Side, "B/S", r => r.side.ToString(), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues, _wrap_comparer(r => r.side)) { } public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => @@ -627,7 +627,7 @@ namespace mbts.spark { } public class SizeColumn : OrderbookColumnBase, IRenderColumn { - public SizeColumn(IDataGridColumnPersistentFilter filter) + public SizeColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Size, "Qty", r => r.display_quantity_text, DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.quantity)) { } public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => @@ -646,7 +646,7 @@ namespace mbts.spark { } public class FilledColumn : OrderbookColumnBase, IRenderColumn { - public FilledColumn(IDataGridColumnPersistentFilter filter) + public FilledColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Filled, "Filled Qty", r => r.display_filled_quantity.ToString(), DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.DoubleMinMax, _wrap_comparer(r => r.filled_quantity)) { } public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => @@ -668,7 +668,7 @@ namespace mbts.spark { readonly BindingBase _foreground_binding; ListSortDirection? _cached_sort_direction; - public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer row_comparer, IDataGridColumnPersistentFilter filter, string header = DefaultColumnHeaders.OrderType) + public OrderBookOrderTypeColumn(Columns key, string badge_fill_binding_path, string display_name_binding_path, IComparer row_comparer, IDataGridColumnPersistentFilter filter, string header = DefaultColumnHeaders.OrderType) : base(key, new Binding(badge_fill_binding_path), new Binding(display_name_binding_path), filter, header) { id = key.ToString(); this.filter = filter; @@ -678,11 +678,11 @@ namespace mbts.spark { this.comparer = row_comparer; } - public IDataGridColumnPersistentFilter filter { get; } + public IDataGridColumnPersistentFilter filter { get; } public override string filter_template => DataGridFilterKnownTemplates.AlgoType; public IComparer comparer { get; } - IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; } public override FrameworkElement view_factory() { @@ -700,7 +700,7 @@ namespace mbts.spark { public class OrderBookLastMessageColumn : TextColumn, ICVOrderBookColumn { ListSortDirection? _cached_sort_direction; - public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter filter) + public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter filter) : base(Columns.LastMessage, filter, DataGridFilterKnownTemplates.Regex) { id = key.ToString(); this.filter = filter; @@ -710,10 +710,10 @@ namespace mbts.spark { ToolTipBinding = new Binding(nameof(OrderBookRowVM.last_msg)); } - public IDataGridColumnPersistentFilter filter { get; } + public IDataGridColumnPersistentFilter filter { get; } public IComparer comparer => _wrap_comparer(r => r.last_msg); - IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; } protected override void OnSortDirectionChanged(ListSortDirection? new_value) { @@ -723,7 +723,7 @@ namespace mbts.spark { } public class PiqColumn : OrderbookColumnBase, IRenderColumn { - public PiqColumn(IDataGridColumnPersistentFilter filter) + public PiqColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Piq, "PIQ", r => r.piq_text, DefaultColumnWidths.Qty, filter, DataGridFilterKnownTemplates.UIntMinMax, _wrap_comparer(r => r.piq)) { } public void draw(OrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => @@ -748,7 +748,7 @@ namespace mbts.spark { ListSortDirection? _cached_sort_direction; - public SecurityColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Security) { + public SecurityColumn(IDataGridColumnPersistentFilter filter) : base(Columns.Security) { id = key.ToString(); this.filter = filter; _foreground_binding = RenderUtils.get_foreground_binding(this); @@ -757,13 +757,13 @@ namespace mbts.spark { _cached_sort_direction = SortDirection; } - public IDataGridColumnPersistentFilter filter { get; } + public IDataGridColumnPersistentFilter filter { get; } public IComparer comparer => ComparerWrapper.wrap( r => r.security, Comparer.Default); - IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; IDataGridColumnFilter IFilterableColumn.filter_model => filter; string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.DiscreteValues; ListSortDirection? ICVOrderBookColumn.SortDirection { get => _cached_sort_direction; set => SortDirection = value; } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs index 312a747e3..2af345e5e 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs @@ -24,7 +24,7 @@ using Columns = mbts.spark.OrderBookGridView.ColumnKeys; using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable; namespace mbts.spark { - partial class OrderBookRowVM : IEquatable, DIYGrid.IRowVM, IHierarchicalRow, INotifyPropertyChanged { + partial class OrderBookRowVM : IEquatable, DIYGrid.IRowVM, IHierarchicalRow, INotifyPropertyChanged { public static readonly IComparer key_comparer = Comparer.Default.wrap(r => r.order_key).to_safe(); const string _unknown_security_price_format_string = "0.#########"; @@ -45,7 +45,7 @@ namespace mbts.spark { double _prospective_price; Action _on_selection_changed; - public OrderBookRowVM(OrderBookVM owner, OrderSecurityRootPair order_tuple, bool is_expanded, Action on_selection_changed) { + public OrderBookRowVM(OrderBookVM owner, OrderRecordTupleWithRoot order_tuple, bool is_expanded, Action on_selection_changed) { _owner = owner; this.order_tuple = order_tuple; _is_expanded = is_expanded; @@ -59,19 +59,19 @@ namespace mbts.spark { //// when the OrderBookVM.selected_order_changes, this emulates the selected //// order changing since the current_row setter invokes the selected_order_changed //// handler - public IObservable subscribe_data() { - return Observable.FromEvent( + public IObservable subscribe_data() { + return Observable.FromEvent( cb => () => cb(order_tuple), cb => invalidated += cb, cb => invalidated -= cb); } public event Action invalidated; - public event Action<(OrderSecurityRootPair oldval, OrderSecurityRootPair newval)> updated; + public event Action<(OrderRecordTupleWithRoot oldval, OrderRecordTupleWithRoot newval)> updated; public event PropertyChangedEventHandler PropertyChanged; // Core - public OrderSecurityRootPair order_tuple { get; private set; } + public OrderRecordTupleWithRoot order_tuple { get; private set; } public OrderRecordImmutable order => order_tuple.order.order; public OrderMetadata order_metadata => _owner.get_metadata(this); public Brush badge_fill => _badge_fill ?? (_badge_fill = OrderUtils.badge_fill(order_tuple.order.meta, order_metadata)); @@ -140,7 +140,7 @@ namespace mbts.spark { order.filled_status_description(security.spec_or_default(), _quantity_display_settings); // Root Algo - public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo.value.CustomCase; + public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo_type; public OrderMetadata root_algo_order_metadata => _owner.get_metadata(root_algo_order_type); public Brush root_algo_badge_fill => _root_algo_badge_fill ?? (_root_algo_badge_fill = new SolidColorBrush(_root_algo_badge_color)); public string root_algo_display_name => order_tuple.root.display_name(); @@ -289,7 +289,7 @@ namespace mbts.spark { bool IHierarchicalRow.is_parent => is_parent; bool IHierarchicalRow.is_expanded => is_expanded; int IHierarchicalRow.depth_level => depth_level; - OrderSecurityRootPair IHierarchicalRow.value => order_tuple; + OrderRecordTupleWithRoot IHierarchicalRow.value => order_tuple; void IHierarchicalRow.on_is_parent_changed(bool is_parent) => this.is_parent = is_parent; /// Do NOT actually call the setter (it has side effects) - the row collection calls this method when the row is expanded/collapsed by some **external means, outside of this class. @@ -301,7 +301,7 @@ namespace mbts.spark { /// void IHierarchicalRow.on_is_expanded_changed(bool is_expanded) => Set(ref _is_expanded, is_expanded, nameof(is_expanded)); void IHierarchicalRow.on_depth_level_changed(int depth_level) => this.depth_level = depth_level; - void IHierarchicalRow.on_value_changed(OrderSecurityRootPair value) => update(value); + void IHierarchicalRow.on_value_changed(OrderRecordTupleWithRoot value) => update(value); #endregion private void _unselect_me() { @@ -317,7 +317,7 @@ namespace mbts.spark { internal void expand_internal() => Set(ref _is_expanded, true, nameof(is_expanded)); internal void collapse_internal() => Set(ref _is_expanded, false, nameof(is_expanded)); - public void update(OrderSecurityRootPair order_tuple) { + public void update(OrderRecordTupleWithRoot order_tuple) { Log.assert(order_tuple.order.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key."); // _show_order_modify_cmd is lazy (instantiated in the default_command getter); it might be null, don't not force instantiation bool? could_modify_execute = _show_order_modify_cmd?.CanExecute(null); @@ -365,7 +365,7 @@ namespace mbts.spark { RaisePropertyChanged(nameof(badge_fill)); } // display name - if (old_order_tuple.order.algo.name != order_tuple.order.algo.name) + if (old_order_tuple.order.algo?.name != order_tuple.order.algo_name) RaisePropertyChanged(nameof(display_name)); // root badge fill if (_root_algo_badge_color_backing.HasValue) { @@ -374,10 +374,10 @@ namespace mbts.spark { RaisePropertyChanged(nameof(root_algo_badge_fill)); } // root display name - if (old_order_tuple.root.algo.name != order_tuple.root.algo.name) + if (old_order_tuple.root.algo_name != order_tuple.root.algo_name) RaisePropertyChanged(nameof(root_algo_display_name)); // root order type - if (old_order_tuple.root.algo.value.CustomCase != order_tuple.root.algo.value.CustomCase) { + if (old_order_tuple.root.algo_type != order_tuple.root.algo_type) { RaisePropertyChanged(nameof(root_algo_order_type)); } // status @@ -493,7 +493,8 @@ namespace mbts.spark { Columns.AvgFilled | Columns.Status; - public static Columns get_dirty_cells(OrderSecurityRootPair oldval, OrderSecurityRootPair newval) { + public static Columns get_dirty_cells( + OrderRecordTupleWithRoot oldval, OrderRecordTupleWithRoot newval) { var dirty = (Columns)0; if (oldval.order.security != newval.order.security) dirty |= Columns.Security; diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 5d9f987f1..d5cc117e1 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -56,7 +56,7 @@ namespace mbts.spark { readonly Property _current_row; readonly ObservableSortedCollection _selected_rows = new ObservableSortedCollection(OrderBookRowVM.key_comparer); readonly DelegateProperty _show_order_params, _show_ladder, _show_fills, _can_attach_selected_orders, _can_detach_selected_orders; - readonly OperableHierarchicalCollection _row_collection; + readonly OperableHierarchicalCollection _row_collection; readonly OrderBookColumnCollection _columns; readonly IWindowSettingsManager _settings_manager; readonly IWindowSettingsManager _fills_settings_manager = new WindowSettingsManager.DisconnectedImpl(FillsSettings.MiniGridSettings, FillsSettings.MiniGridSettings); @@ -64,7 +64,7 @@ namespace mbts.spark { readonly CommonValueMonitor _selected_security_mon = new CommonValueMonitor(); readonly RightPanelModel _right_panel = new RightPanelModel(); readonly CustomStateSynchronizer _custom_state_sync; - readonly Func _global_filter; + readonly Func _global_filter; OrderBookFillsGridSettings _cached_fills_settings = OrderBookStartupData.DefaultFillsGrid; double _raw_right_panel_width = OrderBookStartupData.Default.right_panel_width, @@ -79,7 +79,7 @@ namespace mbts.spark { _is_attaching_orders, _is_row_collection_populated, _all_rows_selected; - IReadOnlyDictionary _cached_orders = DictionaryHelper.empty(); + IReadOnlyDictionary _cached_orders = DictionaryHelper.empty(); IReadOnlyDictionary _cached_attachable = DictionaryHelper.empty(), _cached_detachable = DictionaryHelper.empty(); IReadOnlyDictionary _cached_securities = new Dictionary(0); HashSet @@ -95,7 +95,7 @@ namespace mbts.spark { ISecurityMetadataStore sec_meta_store, IWindowSettingsManager settings_manager, bool rows_are_initially_expanded = false, - Func global_filter = null) + Func global_filter = null) : this( bus, notification_service, @@ -113,10 +113,10 @@ namespace mbts.spark { OrdersModel model, IPositionModel position_model, ISecurityMetadataStore sec_meta_store, - IObservable> orders_source, + IObservable> orders_source, IWindowSettingsManager settings_manager, bool rows_are_initially_expanded = false, - Func global_filter = null) { + Func global_filter = null) { _bus = bus; _model = model; @@ -157,7 +157,7 @@ namespace mbts.spark { _columns = new OrderBookColumnCollection(bus, model, model.on_order_securities.Select(x => (x.added.Values, x.removed.Values))); // we use an ObservableAppendCollection b/c the mini-ob needs a cancel column at the front columns = new ObservableAppendCollection(_columns); - _row_collection = new OperableHierarchicalCollection( + _row_collection = new OperableHierarchicalCollection( row_factory, r => r.order.order.Key, r => r.order.order.ParentKey, @@ -362,7 +362,7 @@ namespace mbts.spark { } }); - OrderBookRowVM row_factory(OrderSecurityRootPair o) { + OrderBookRowVM row_factory(OrderRecordTupleWithRoot o) { var row = new OrderBookRowVM(this, o, rows_are_initially_expanded, on_is_selected_changed) { is_attachable = _cached_attachable.TryGetValue(o.order.order.Key, out bool ia) && ia, is_detachable = _cached_detachable.TryGetValue(o.order.order.Key, out bool id) @@ -595,16 +595,16 @@ namespace mbts.spark { public IObservable subscribe_show_fills() => _show_fills.observe_current(true); public IObservable subscribe_show_ladder() => _show_ladder.observe_current(true); public IObservable subscribe_show_order_params() => _show_order_params.observe_current(true); - public IObservable subscribe_single_selected_order() => - Observable.Create(o => { - OrderSecurityAlgo? last_fired = null; + public IObservable subscribe_single_selected_order() => + Observable.Create(o => { + OrderRecordTuple? last_fired = null; orders_changed += notify; _current_row.Changed += on_current_row_changed; notify(); return Disposable.Create(dispose); // local methods void notify() { - var next = current_row == null ? (OrderSecurityAlgo?)null : current_row.order_tuple.order; + var next = current_row == null ? (OrderRecordTuple?)null : current_row.order_tuple.order; if (next != last_fired) o.OnNext(last_fired = next); } @@ -846,7 +846,7 @@ namespace mbts.spark { // ---- var update_params = selected_rows.Select(r => update_params_factory(r.order_tuple.root)).ToList(); await Task.WhenAll(update_params.Select(t => _model.update_order(t.order, new_price: price, new_size: size, new_algo: t.new_algo))); - (OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderSecurityAlgo order_tuple) { + (OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderRecordTuple order_tuple) { var mod_algo = order_tuple.order.Def.CustomDef.CloneToMutable(); if (mod_algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) { mod_algo_vm.assign_to(mod_algo.Composite.Definition); @@ -940,25 +940,25 @@ namespace mbts.spark { struct FilterData : IEquatable { public readonly AlgoTreeDisplayMode algo_tree_display_mode; public readonly FilterStates column_filters; - public readonly Func global_filter; + public readonly Func global_filter; - public FilterData(AlgoTreeDisplayMode algo_tree_display_mode, FilterStates column_filters, Func global_filter) { + public FilterData(AlgoTreeDisplayMode algo_tree_display_mode, FilterStates column_filters, Func global_filter) { this.algo_tree_display_mode = algo_tree_display_mode; this.column_filters = column_filters; this.global_filter = global_filter; } - public Func build_predicate() { + public Func build_predicate() { if (global_filter == null) return _build_predicate_core(); var core_pred = _build_predicate_core(); if (core_pred == null) return global_filter; var glbf = global_filter; - return new Func(o => glbf(o) && core_pred(o)); + return new Func(o => glbf(o) && core_pred(o)); } - Func _build_predicate_core() { + Func _build_predicate_core() { var pred = column_filters.build_predicate(); if (algo_tree_display_mode == AlgoTreeDisplayMode.RootAndLeafNodes) { if (pred == null) { @@ -967,7 +967,7 @@ namespace mbts.spark { var col_pred = pred; pred = o => tree_disp_pred(o) && col_pred(o); } - bool tree_disp_pred(OrderSecurityRootPair o) => + bool tree_disp_pred(OrderRecordTupleWithRoot o) => !o.order.order.has_parent() || o.order.order.is_exchange_order() || o.order.order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader; diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs index 610c7ed65..ded215662 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs @@ -124,8 +124,8 @@ namespace bts.shell.orderbook { } static class FilterStatesExtensions { - public static Func build_predicate(this FilterStates fs) { - var pb = new ColumnPredicateBuilder(); + public static Func build_predicate(this FilterStates fs) { + var pb = new ColumnPredicateBuilder(); // security pb.add_security_criteria(fs.security_criteria, o => o.order.security); // regex @@ -142,7 +142,7 @@ namespace bts.shell.orderbook { pb.add_discrete_values(fs.exchanges, o => o.order.security?.Exchange ?? Venue.Unset); pb.add_discrete_values(fs.tifs, o => o.order.order.time_in_force()); pb.add_discrete_values(fs.order_types, o => AlgoID.from_custom_def(o.order.order.Def.CustomDef)); - pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root.algo.key)); + pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root.algo?.key ?? default)); pb.add_discrete_values(fs.order_sub_types, o => o.order.order.sub_type()); pb.add_discrete_values(fs.sides, o => o.order.order.side()); pb.add_discrete_values(fs.statuses, o => o.order.order.status()); diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettings.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettings.cs index 6dba70052..cb9b29fc3 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettings.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettings.cs @@ -7,6 +7,8 @@ using mbts.ui; using ProtoBuf; +using Spark.Api.Orders; + using System; using System.Collections.Generic; using System.ComponentModel; @@ -20,7 +22,7 @@ namespace bts.shell.orderbook { } [ProtoContract] - class OrderBookGridSettings : IGridSettingsWithNotifications, IEquatable { + class OrderBookGridSettings : IGridSettingsWithNotifications, IEquatable { const AlgoTreeDisplayMode _default_algo_tree_display_mode = AlgoTreeDisplayMode.FullTree; // general [ProtoMember(1)] @@ -44,7 +46,7 @@ namespace bts.shell.orderbook { } public IReadOnlyList predicate_animations => _predicate_animations ?? (_predicate_animations = new List()); - IEnumerable> IGridSettingsWithNotifications.predicate_animations => predicate_animations; + IEnumerable> IGridSettingsWithNotifications.predicate_animations => predicate_animations; public OrderBookGridSettings with(GridSettings general) => new OrderBookGridSettings(general ?? this.general, predicate_animations) { diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettingsManager.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettingsManager.cs index 9460e1333..e4745aee2 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettingsManager.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookGridSettingsManager.cs @@ -8,6 +8,7 @@ using mbts.ui.controls; using mbts.ui.settings; using mbts.ui.utility; +using Spark.Api.Orders; using Spark.Core.Data; using Spark.Core.Disposables; @@ -46,17 +47,17 @@ namespace bts.shell.orderbook { ISecurityMetadataStore sec_meta_store, IEnumerable rows, ObservableCollection columns) { - core_manager = new GridSettingsManager( + core_manager = new GridSettingsManager( bus, model, rows, columns, () => new OrderRecordTuplePredicate(), () => { - var pvm = PredicateVMWrapper.create( + var pvm = PredicateVMWrapper.create( OrderRecordTuplePredicateVMFactory.get_oneofs(bus, model), rp => rp.predicate_type_case); pvm.selected_predicate_type = pvm.predicate_types.FirstOrDefault(); return pvm; }, col_id => { - var pvm = PredicateVMWrapper.create( + var pvm = PredicateVMWrapper.create( OrderRecordTuplePredicateVMFactory.get_oneofs(bus, model), rp => rp.predicate_type_case); pvm.selected_predicate_type = _corresponding_predicate_type(EnumHelper.parse_or_default(col_id)); return pvm; @@ -64,15 +65,15 @@ namespace bts.shell.orderbook { (gen, anims) => new OrderBookGridSettings(gen, anims.empty_if_null().Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_data, a.cell_animations, a.row_animations, a.sound_notifications))) { algo_tree_display_mode = _algo_tree_display_mode }, p => p.create_predicate(notification_service.data_cache, sec_meta_store), p => p.create_notification_predicate(notification_service.data_cache, sec_meta_store), - notification_service == null ? new Func, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order, - notification_service == null ? new Func, IDisposable>(t => Disposable.empty) : notification_service.link_to_order, + notification_service == null ? new Func, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order, + notification_service == null ? new Func, IDisposable>(t => Disposable.empty) : notification_service.link_to_order, hard_column_flags); _core_man_as_observer = core_manager; } public event Action algo_tree_display_mode_changed; - public GridSettingsManager core_manager { get; } + public GridSettingsManager core_manager { get; } public AlgoTreeDisplayMode algo_tree_display_mode { get => _algo_tree_display_mode; diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettingsVM.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettingsVM.cs index 575d7fac1..d40703dc9 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettingsVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookSettingsVM.cs @@ -8,6 +8,8 @@ using mbts.ui.settings; using mbts.ui.shell; using mbts.ui.spark; +using Spark.Api.Orders; + using System; using System.Collections.Generic; @@ -15,23 +17,23 @@ namespace bts.shell.orderbook { class OrderBookSettingsVM : DisposableViewModelBase, IWindowSettingsVM, ITemplateSelectorKey { AlgoTreeDisplayMode _algo_tree_display_mode; - public OrderBookSettingsVM(GridSettingsVM core_settings_vm) => + public OrderBookSettingsVM(GridSettingsVM core_settings_vm) => this.core_settings_vm = core_settings_vm; public OrderBookSettingsVM( IBus bus, OrdersModel orders_model, Func predicate_data_factory, - Func> notification_predicate_factory, + Func> notification_predicate_factory, Func> create_predicate_vm, Func> create_column_predicate_vm, - Func>, OrderBookGridSettings> create_settings_obj, + Func>, OrderBookGridSettings> create_settings_obj, IReadOnlyDictionary column_flags = null) { - core_settings_vm = new GridSettingsVM( + core_settings_vm = new GridSettingsVM( bus, orders_model, predicate_data_factory, notification_predicate_factory, create_predicate_vm, create_column_predicate_vm, create_settings_obj, column_flags); } - public GridSettingsVM core_settings_vm { get; } + public GridSettingsVM core_settings_vm { get; } public AlgoTreeDisplayMode algo_tree_display_mode { get => _algo_tree_display_mode; set => Set(ref _algo_tree_display_mode, value); } string ITemplateSelectorKey.key => GridSettingsTemplateKeys.OrderBook; diff --git a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs index c5a03dd6a..e3cfe430c 100644 --- a/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs +++ b/src/client/spark/Modules/Trading/PNL/VM/PNLVM.cs @@ -48,7 +48,7 @@ namespace bts.shell.pnl { static readonly TimeSpan _auxiliary_grid_update_throttle = TimeSpan.FromSeconds(0.2); // delegates - static readonly Func _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key()); + static readonly Func _order_pnl_key_fn = o => new PNLKey(o.order.order.account_id(), o.order.order.security_key()); static readonly Func _fill_pnl_key_fn = f => new PNLKey(f.account_id, f.fill.SecurityKey); readonly IBus _bus; @@ -503,7 +503,7 @@ namespace bts.shell.pnl { switch (header) { case PNLHeaderRowDisplay.SelectedTotal: // throttle selection changes (they have a potentially high frequency) - var filter_src = System.Reactive.Linq.ObservableExtensions.FromEventThrottle>( + var filter_src = System.Reactive.Linq.ObservableExtensions.FromEventThrottle>( cb => _selection_changed += cb, cb => _selection_changed -= cb, _ => _mk_selected_items_filter(_order_pnl_key_fn), @@ -791,7 +791,11 @@ namespace bts.shell.pnl { Func _mk_selected_items_filter(Func key_selector) => _mk_items_filter(_selected_rows.Select(r => r.key), key_selector); - OrderBookVM _mk_orderbook_vm_common(orderbook.FilterStates filters, IEnumerable hide_counterparts, IObservable> orders_source = null) { + OrderBookVM _mk_orderbook_vm_common( + orderbook.FilterStates filters, + IEnumerable hide_counterparts, + IObservable> orders_source = null + ) { var state = new orderbook.OrderBookStartupData(filters, orderbook.OrderBookStartupData.default_mini_grid, use_defaults: false); state.orderbook_grid.general = GridSettingsHelper.hide_cols(state.orderbook_grid.general, hide_counterparts); var settings_man = new WindowSettingsManager.DisconnectedImpl(state.orderbook_grid); @@ -807,9 +811,9 @@ namespace bts.shell.pnl { IObservable> _visible_fills_source() => _orders_model.on_fill_tuples.Filter(_visible_items_filter_source(_fill_pnl_key_fn), FillTuple.key_fn); - IObservable> _visible_orders_source() => - _orders_model.on_order_tuples_with_root_and_piq.Filter( - _visible_items_filter_source(_order_pnl_key_fn), o => o.order.order.Key); + IObservable> _visible_orders_source() => + _orders_model.on_order_tuples_with_root_and_piq + .Filter(_visible_items_filter_source(_order_pnl_key_fn), o => o.order.order.Key); IObservable> _visible_items_filter_source(Func key_selector) => Observable.Create>(o => { diff --git a/src/client/spark/Notifications/INotificationService.cs b/src/client/spark/Notifications/INotificationService.cs index b43008de4..b0c69b0a7 100644 --- a/src/client/spark/Notifications/INotificationService.cs +++ b/src/client/spark/Notifications/INotificationService.cs @@ -11,6 +11,7 @@ using mbts.spark; using mbts.ui; using mbts.utils; +using Spark.Api.Orders; using Spark.Core.Disposables; using System; @@ -26,8 +27,8 @@ namespace bts.shell { INotificationServiceDataCache data_cache { get; } IDisposable link_to_activity(IPredicate predicate, SoundNotification sound); IDisposable link_to_activity(INotificationPredicate toast_notification_predicate); - IDisposable link_to_order(IPredicate predicate, SoundNotification sound); - IDisposable link_to_order(INotificationPredicate toast_notification_predicate); + IDisposable link_to_order(IPredicate predicate, SoundNotification sound); + IDisposable link_to_order(INotificationPredicate toast_notification_predicate); // Note: security criteria should not be incorporated in the predicate's 'trigger' impl. // It is easier/cleaner if the INotificationService incorporates the criteria internally. IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate predicate, SoundNotification sound); @@ -38,7 +39,7 @@ namespace bts.shell { // activity notifications readonly NotificationProcessor _activity_notifications; // order notifications - readonly NotificationProcessor _order_notifications; + readonly NotificationProcessor _order_notifications; // trade notifications readonly NotificationProcessor _trade_notifications; readonly MDConsumer _consumer; @@ -55,7 +56,7 @@ namespace bts.shell { public NotificationService(IBus bus, INotifier notifier, OrdersModel orders_model, MDConsumer consumer) { this.notifier = notifier; _activity_notifications = new NotificationProcessor(notifier); - _order_notifications = new NotificationProcessor(notifier); + _order_notifications = new NotificationProcessor(notifier); _trade_notifications = new NotificationProcessor(notifier); _consumer = consumer; _dispose = Disposable.Create( @@ -78,8 +79,9 @@ namespace bts.shell { public IDisposable link_to_activity(IPredicate predicate, SoundNotification sound) => _activity_notifications.link(predicate, sound); public IDisposable link_to_activity(INotificationPredicate toast_notification_predicate) => _activity_notifications.link(toast_notification_predicate); - public IDisposable link_to_order(IPredicate predicate, SoundNotification sound) => _order_notifications.link(predicate, sound); - public IDisposable link_to_order(INotificationPredicate toast_notification_predicate) => _order_notifications.link(toast_notification_predicate); + public IDisposable link_to_order(IPredicate predicate, SoundNotification sound) => _order_notifications.link(predicate, sound); + public IDisposable link_to_order(INotificationPredicate notification_predicate) => + _order_notifications.link(notification_predicate); public IDisposable link_to_trades(SecurityCriteria security_criteria, IPredicate predicate, SoundNotification sound) { if (predicate == null) { @@ -119,7 +121,7 @@ namespace bts.shell { void _on_activity(Activity activity) => _activity_notifications.process_item(activity); - void _on_orders(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) { + void _on_orders(TableUpdate update) { // must update notification_service_data_cache first, some of the predicate/triggers (esp. ToastNotifications) will use the notification_service_data_cache to lookup order-history _data_cache.update(update.as_iincremental()); foreach (var o in update.added.Concat(update.changed)) diff --git a/src/client/spark/Notifications/INotificationServiceDataCache.cs b/src/client/spark/Notifications/INotificationServiceDataCache.cs index 6cff8c154..d3cf8b456 100644 --- a/src/client/spark/Notifications/INotificationServiceDataCache.cs +++ b/src/client/spark/Notifications/INotificationServiceDataCache.cs @@ -4,6 +4,8 @@ using bts.api.orderman; using mbts.spark; using mbts.utils; +using Spark.Api.Orders; + using System; using System.Collections.Generic; @@ -17,12 +19,12 @@ namespace bts.shell { interface INotificationServiceDataCache { DateTime last_order_reset_time { get; } bool is_first_order_update { get; } - IReadOnlyDictionary>> order_history { get; } + IReadOnlyDictionary>> order_history { get; } } static class NotificationServiceDataCacheExtensions { - public static OrderSecurity? get_previous_order_state(this INotificationServiceDataCache notification_service_data_cache, uint key) { - if (notification_service_data_cache.order_history.TryGetValue(key, out List> l)) { + public static OrderRecordTuple? get_previous_order_state(this INotificationServiceDataCache notification_service_data_cache, uint key) { + if (notification_service_data_cache.order_history.TryGetValue(key, out List> l)) { if (l.Count > 1) { return l[l.Count - 2].data; } @@ -44,15 +46,15 @@ namespace bts.shell { partial class NotificationService : INotificationService, IDisposable { class DataCache : INotificationServiceDataCache { const int _buffer_size = 10; - readonly Dictionary _order_cache = new Dictionary(); - readonly Dictionary>> _order_history = new Dictionary>>(); + readonly Dictionary _order_cache = new(); + readonly Dictionary>> _order_history = new(); - public IReadOnlyDictionary>> order_history => _order_history; + public IReadOnlyDictionary>> order_history => _order_history; public DateTime last_order_reset_time { get; private set; } public bool is_first_order_update { get; private set; } - internal void update(IIncrementalUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> data) { + internal void update(IIncrementalUpdate data) { DateTime now = DateTime.Now; if (data.removed.Count == _order_cache.Count) { last_order_reset_time = now; @@ -62,7 +64,7 @@ namespace bts.shell { foreach (var kv in data.removed) { if (data.added.ContainsKey(kv.Key)) { _order_cache[kv.Key] = kv.Value; - _order_history[kv.Key].Add(new TimeStampedData(kv.Value, now)); + _order_history[kv.Key].Add(new TimeStampedData(kv.Value, now)); } else { _order_cache.Remove(kv.Key); // TODO: maybe these shouldn't be removed? @@ -76,9 +78,9 @@ namespace bts.shell { continue; _order_cache.Add(kv.Key, kv.Value); _order_history.AddOrUpdate(kv.Key, - k => new List> { new TimeStampedData(kv.Value, now) }, + k => new List> { new(kv.Value, now) }, (k, l) => { - l.Add(new TimeStampedData(kv.Value, now)); + l.Add(new TimeStampedData(kv.Value, now)); if (l.Count >= 10) l.RemoveAt(0); }); diff --git a/src/client/spark/Notifications/ToastNotification.cs b/src/client/spark/Notifications/ToastNotification.cs index adabe57ae..94ec08f8c 100644 --- a/src/client/spark/Notifications/ToastNotification.cs +++ b/src/client/spark/Notifications/ToastNotification.cs @@ -65,7 +65,7 @@ namespace bts.shell { public static IToastNotification order_filled(OrderRecordImmutable oldval, OrderRecordImmutable newval, SecurityImmutable? security) => new OrderFilledToastNotification(oldval, newval, security); - public static IToastNotification order_filled(OrderSecurity oldval, OrderSecurity newval) => + public static IToastNotification order_filled(OrderRecordTuple oldval, OrderRecordTuple newval) => new OrderFilledToastNotification(oldval.order, newval.order, newval.security); public static IToastNotification order_completed( @@ -75,7 +75,7 @@ namespace bts.shell { new OrderCompletedToastNotification(order, security, qty_display); public static IToastNotification order_completed( - OrderSecurity order, TickDisplaySettingsImmutable qty_display) => + OrderRecordTuple order, TickDisplaySettingsImmutable qty_display) => new OrderCompletedToastNotification(order.order, order.security, qty_display); public static IToastNotification order_status_changed(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) => diff --git a/src/client/spark/Orders/FillTuple.cs b/src/client/spark/Orders/FillTuple.cs index 1b8602142..39a72b0d5 100644 --- a/src/client/spark/Orders/FillTuple.cs +++ b/src/client/spark/Orders/FillTuple.cs @@ -15,16 +15,19 @@ namespace mbts.spark { public readonly FillImmutable fill; public readonly SecurityImmutable? security; - OrderSecurityRootPair? _order_tuple; + OrderRecordTupleWithRoot? _order_tuple; - public FillTuple(FillImmutable fill, SecurityImmutable? security, OrderSecurityRootPair? order_tuple) { + public FillTuple( + FillImmutable fill, + SecurityImmutable? security, + OrderRecordTupleWithRoot? order_tuple) { this.fill = fill; this.security = security; _order_tuple = order_tuple; } - public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderSecurity? order_tuple) - : this(fill.val, fill.sec, order_tuple.HasValue ? OrderSecurityRootPair.from_order_security(order_tuple.Value) : (OrderSecurityRootPair?)null) { } + public FillTuple((SecurityImmutable? sec, FillImmutable val) fill, OrderRecordTuple? order_tuple) + : this(fill.val, fill.sec, order_tuple.HasValue ? new(order_tuple.Value) : null) { } public AlgoData? algo => _order_tuple.HasValue ? _order_tuple.Value.order.algo : (AlgoData?)null; @@ -41,7 +44,7 @@ namespace mbts.spark { public AlgoDefinitionMetadata? root_algo_meta => _order_tuple.HasValue ? _order_tuple.Value.root.meta : null; - public OrderSecurityAlgo? root_order_security => _order_tuple?.root; + public OrderRecordTuple? root_order_security => _order_tuple?.root; public AccountTuple account_tuple => new(account_id, account); diff --git a/src/client/spark/Orders/OrderActivitySummarizer.cs b/src/client/spark/Orders/OrderActivitySummarizer.cs index 3a7a27089..96cc3e012 100644 --- a/src/client/spark/Orders/OrderActivitySummarizer.cs +++ b/src/client/spark/Orders/OrderActivitySummarizer.cs @@ -36,12 +36,11 @@ namespace bts.spark { static readonly IEqualityComparer _id_comparer = bts.utils.EqualityComparer.Create(a => a.Key); - public OrderActivitySummarizer(IBus bus, IObservable> orders) { + public OrderActivitySummarizer(IBus bus, IObservable> orders) { _bus = bus; _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec => _security = sec), - orders.Subscribe(orders_updated) - ); + orders.Subscribe(orders_updated)); } public void Dispose() => Disposable.dispose(ref _dispose); @@ -143,12 +142,12 @@ namespace bts.spark { #endregion - void orders_updated(TableUpdate<(SecurityImmutable? sec, OrderRecordImmutable order), uint> update) { + void orders_updated(TableUpdate update) { foreach (var o in update.added) { if (!string.IsNullOrEmpty(o.order.State.LastMsg) && o.order.State.Created.ToDateTime().Date == DateTime.Today) { - if (o.sec.HasValue) { - log_status(ActivityLogCategory.warn, o.sec.Value, o.order.State.LastMsg); + if (o.security.HasValue) { + log_status(ActivityLogCategory.warn, o.security.Value, o.order.State.LastMsg); } } } @@ -156,7 +155,7 @@ namespace bts.spark { foreach (var order in update.changes) { var neworder = order.New.order; var oldorder = order.Old.order; - var security = order.New.sec ?? order.Old.sec; + var security = order.New.security ?? order.Old.security; // // description var mod_desc = modified_description(oldorder, neworder, security?.ContractSpec); diff --git a/src/client/spark/Orders/OrderParamsAggregator.cs b/src/client/spark/Orders/OrderParamsAggregator.cs index 153233966..888aba0c1 100644 --- a/src/client/spark/Orders/OrderParamsAggregator.cs +++ b/src/client/spark/Orders/OrderParamsAggregator.cs @@ -32,10 +32,10 @@ namespace mbts.spark { readonly CommonValueMonitor _size_mon = new(); readonly CommonValueMonitor _account_mon = new CommonValueMonitor(); readonly CommonValueMonitor _all_active_mon = new CommonValueMonitor(); - readonly CommonValueMonitorMultiplexor _group_mon = new CommonValueMonitorMultiplexor(); - readonly Func _lookup_order; + readonly CommonValueMonitorMultiplexor _group_mon = new(); + readonly Func _lookup_order; - public OrderParamsAggregator(TimeSpan throttle, Func lookup_order) { + public OrderParamsAggregator(TimeSpan throttle, Func lookup_order) { _throttle = throttle; _lookup_order = lookup_order; _group_mon.add_member_mon(_algo_def_mon, _build_algo_tree); @@ -88,21 +88,21 @@ namespace mbts.spark { public IDisposable defer_updates() => _group_mon.defer_updates(); - public void Add(OrderSecurityAlgo order_tuple) => + public void Add(OrderRecordTuple order_tuple) => _group_mon.add(order_tuple); - public void Remove(OrderSecurityAlgo order_tuple) => + public void Remove(OrderRecordTuple order_tuple) => _group_mon.remove(order_tuple); public void Clear() => _group_mon.clear(); - static SecurityImmutable? _get_spreader_sec(OrderSecurityAlgo osam) => + static SecurityImmutable? _get_spreader_sec(OrderRecordTuple osam) => OrderDataHelper.enumerate_algo_hierarchy(osam.order.Def.CustomDef.CloneToMutable()) .Any(algo => algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Spreader) ? osam.security : null; - CustomOrderDefinitionImmutable _build_algo_tree(OrderSecurityAlgo root) => + CustomOrderDefinitionImmutable _build_algo_tree(OrderRecordTuple root) => root.order.Def.AttachTargetOrderKey == 0 ? root.order.Def.CustomDef : new CustomOrderDefinitionImmutable(_add_attached_targets(root.order.Def.CustomDef.CloneToMutable(), root.order.Key, root.order.Def.AttachTargetOrderKey)); @@ -124,7 +124,7 @@ namespace mbts.spark { return mroot; } - Stack _lineage(uint root, uint target) { + Stack _lineage(uint root, uint target) { // check args/preconditions if (root == 0) throw new ArgumentException("Cannot be zero.", nameof(root)); if (target == 0) throw new ArgumentException("Cannot be zero.", nameof(target)); @@ -138,8 +138,8 @@ namespace mbts.spark { // **If the lineage is disjointed, and we never reach the root, return null** var ival = inner.Value; var lin_stack = ival.order.attached_target_order_key() != 0 ? - _lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack() : - new Stack(); + _lineage(ival.order.Key, ival.order.attached_target_order_key()) ?? new Stack() : + new Stack(); lin_stack.Push(ival); target = ival.order.ParentKey; while (target != root) { diff --git a/src/client/spark/Orders/OrderSecurity.cs b/src/client/spark/Orders/OrderSecurity.cs index 3f98173eb..c141a200c 100644 --- a/src/client/spark/Orders/OrderSecurity.cs +++ b/src/client/spark/Orders/OrderSecurity.cs @@ -39,6 +39,9 @@ namespace bts.api.orderman { public AlgoData? algo { get; } public AlgoDefinitionMetadata? meta { get; } + public OrderRecordTuple to_record_tuple() => + new(order, security, piq, algo, meta); + public bool Equals(OrderSecurity other) => order == other.order && security == other.security && @@ -88,6 +91,9 @@ namespace bts.api.orderman { public string display_name() => order.display_name(algo, security); + public OrderRecordTuple to_record_tuple() => + new(order, security, piq, algo, meta); + public bool Equals(OrderSecurityAlgo other) => order == other.order && piq == other.piq && @@ -134,6 +140,9 @@ namespace bts.api.orderman { OrderSecurityAlgo.from_order_security(order), OrderSecurityAlgo.from_order_security(root)); + public OrderRecordTupleWithRoot to_record_tuple() => + new(order.to_record_tuple(), _root?.to_record_tuple()); + public bool Equals(OrderSecurityRootPair other) => order == other.order && _root == other._root; diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index 214c8b2be..3431c11a2 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -34,8 +34,8 @@ using System.Reactive.Linq; using System.Threading.Tasks; - using OrderUpdate = bts.api.core.TableUpdate<(bts.api.SecurityImmutable? sec, bts.api.orderman.OrderRecordImmutable order), uint>; - using OrderUpdatePiq = bts.api.core.TableUpdate; + using OrderUpdate = bts.api.core.TableUpdate; + using OrderUpdatePiq = bts.api.core.TableUpdate; [Export] class OrdersModel : IDisposable { @@ -53,7 +53,7 @@ readonly ErrorReporter _error; readonly OrderActivitySummarizer _activity; readonly TableUpdateDemuxer _security_orders_demuxer; - readonly TableUpdateDemuxer _security_working_orders_with_piq_demuxer; + readonly TableUpdateDemuxer _security_working_orders_with_piq_demuxer; readonly OrderDataSource _data_source; /// is updated atomically from multiple threads (use a local copy to @@ -98,12 +98,13 @@ on_order_securities = on_orders .as_iincremental() - .filter(t => t.sec.HasValue) - .Select(t => t.sec.Value); + .filter(t => t.security.HasValue) + .Select(t => t.security.Value); _activity = new OrderActivitySummarizer(bus, on_orders); _security_orders_demuxer = new TableUpdateDemuxer(o => o.Key, o => o.security_key()); - _security_working_orders_with_piq_demuxer = new TableUpdateDemuxer(o => o.order.Key, o => o.order.security_key()); + _security_working_orders_with_piq_demuxer = new( + o => o.order.Key, o => o.order.security_key()); studio_algos_with_meta = algo_model.definitions.LeftJoin( algo_model.metadata_service.subscribe_metadata().Table(m => m.id), d => d.key, @@ -118,21 +119,17 @@ t => t.order.Key, am => am.algo.key, t => AlgoKey.from_composite_key(t.order.algo_template_key()), - (os, okey, am, mkey) => new OrderSecurity(os.sec, os.order, null, am.algo, am.meta), - (os, okey, mkey) => new OrderSecurity(os.sec, os.order, null, null, null), + (os, okey, am, mkey) => new OrderRecordTuple(os.order, os.security, null, am.algo, am.meta), + (os, okey, mkey) => new OrderRecordTuple(os.order, os.security, null, null, null), ot => ot.order.Key) .Cache(); - on_order_tuples_with_piq = on_order_tuples.LeftJoin< - OrderSecurity, - OrderPIQImmutable, - OrderSecurity, - uint>( + on_order_tuples_with_piq = on_order_tuples.LeftJoin( mbo_service.subscribei_piq().Table(), o => o.order.Key, piq => piq.OrderId, - (osam, _, p) => new OrderSecurity(osam.security, osam.order, p.Position, osam.algo, osam.meta), - (osam, _) => new OrderSecurity(osam.security, osam.order, null, osam.algo, osam.meta), + (osam, _, p) => new OrderRecordTuple(osam.order, osam.security, p.Position, osam.algo, osam.meta), + (osam, _) => new OrderRecordTuple(osam.order, osam.security, null, osam.algo, osam.meta), osp => osp.order.Key ).Cache(); @@ -140,16 +137,16 @@ on_order_tuples_with_root = on_order_tuples.RootDependent( o => o.order.Key, o => o.order.ParentKey, - OrderSecurityRootPair.from_order_security, - OrderSecurityRootPair.from_order_security, + (o, r) => new OrderRecordTupleWithRoot(o, r), + o => new OrderRecordTupleWithRoot(o), o => o.root.order.Key) .Cache(); // order tuples with root and piq on_order_tuples_with_root_and_piq = on_order_tuples_with_piq.RootDependent( o => o.order.Key, o => o.order.ParentKey, - OrderSecurityRootPair.from_order_security, - OrderSecurityRootPair.from_order_security, + (o, r) => new OrderRecordTupleWithRoot(o, r), + o => new OrderRecordTupleWithRoot(o), o => o.root.order.Key) .Cache(); @@ -252,9 +249,9 @@ public SpreaderModel spreader => _spreader; public IObservable on_orders => _data_source.orders; public IObservable on_order_tuples_with_piq { get; } - public IObservable> on_order_tuples { get; } - public IObservable> on_order_tuples_with_root { get; } - public IObservable> on_order_tuples_with_root_and_piq { get; } + public IObservable> on_order_tuples { get; } + public IObservable> on_order_tuples_with_root { get; } + public IObservable> on_order_tuples_with_root_and_piq { get; } public IObservable, uint>> on_orders_can_detach { get; } public IObservable, uint>> on_orders_can_attach { get; } public IObservable> on_order_securities { get; } @@ -264,7 +261,7 @@ public IObservable> studio_algos_with_meta { get; } public IObservable> on_manual_fills_securities { get; } public IObservable> on_manual_fill_tuples { get; } - public IObservable, uint>> security_orders => _data_source.security_orders; + public IObservable, uint>> security_orders => _data_source.security_orders; public AdminModel admin_model { get; } public MBOService mbo_service => _mbo_service; @@ -273,7 +270,7 @@ public AlgoTypeSetImmutable get_permitted_algos(SecurityImmutable security) => _algo_provider.get_permitted_algos(security); - public IObservable> on_security_working_orders_with_piq(uint security) => + public IObservable> on_security_working_orders_with_piq(uint security) => _security_working_orders_with_piq_demuxer.subscribe(security); public IObservable> on_security_orders(uint security) => @@ -471,30 +468,8 @@ public void Dispose() => Disposable.dispose(ref _dispose); - static ImmutableDictionary _update_working_orders(ImmutableDictionary target, OrderUpdate table) { - var clone = target.ToBuilder(); - foreach (var o in table.removed) { - if (o.order.is_active()) { - clone.Remove(o.order.Key); - } - } - foreach (var o in table.changes) { - if (o.Old.order.is_active()) { - clone.Remove(o.Old.order.Key); - } - if (o.New.order.is_active()) { - clone.Add(o.New.order.Key, o.New); - } - } - foreach (var o in table.added) { - if (o.order.is_active()) { - clone.Add(o.order.Key, o); - } - } - return clone.ToImmutableDictionary(); - } - - static ImmutableDictionary _update_working_orders(ImmutableDictionary target, OrderUpdatePiq table) { + static ImmutableDictionary _update_working_orders( + ImmutableDictionary target, OrderUpdate table) { var clone = target.ToBuilder(); foreach (var o in table.removed) { if (o.order.is_active()) { diff --git a/src/client/spark/Predicates/Data/Events/OrderCanceledEventPredicate.cs b/src/client/spark/Predicates/Data/Events/OrderCanceledEventPredicate.cs index 0c5dbad2e..8f13abbbc 100644 --- a/src/client/spark/Predicates/Data/Events/OrderCanceledEventPredicate.cs +++ b/src/client/spark/Predicates/Data/Events/OrderCanceledEventPredicate.cs @@ -8,6 +8,8 @@ using mbts.ui.settings; using ProtoBuf; +using Spark.Api.Orders; + using System; using System.Collections.Generic; using System.ComponentModel; @@ -47,13 +49,13 @@ namespace mbts { } } - public IPredicate create(object obj) => + public IPredicate create(object obj) => create_predicate((INotificationServiceDataCache)obj); - public IPredicate create_predicate(INotificationServiceDataCache data_cache) => + public IPredicate create_predicate(INotificationServiceDataCache data_cache) => OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Canceled, security, data_cache); - public INotificationPredicate create_toast(INotificationServiceDataCache data_cache) => + public INotificationPredicate create_toast(INotificationServiceDataCache data_cache) => new MyToaster(security?.create(), data_cache); public bool Equals(OrderCanceledEventPredicate other) => other != null && other.security.safe_equals(other.security); @@ -63,7 +65,7 @@ namespace mbts { static bool _is_canceled(OrderRecordImmutable o) => o.HasState && o.State.Status == OrderStatus.Canceled; - class MyToaster : INotificationPredicate, IEquatable { + class MyToaster : INotificationPredicate, IEquatable { readonly IPredicate _security_predicate; readonly INotificationServiceDataCache _data_cache; @@ -72,13 +74,13 @@ namespace mbts { _data_cache = data_cache; } - public IToastNotification trigger(OrderSecurity order) => + public IToastNotification trigger(OrderRecordTuple order) => OrderEventPredicateHelper.check_order_transition_trigger(order, _is_canceled, _security_predicate, _data_cache, out var oldval) ? ToastNotifications.order_status_changed(order.order.Key, OrderEventPredicateHelper.get_nullable_status(oldval), OrderStatus.Canceled, order.security) : ToastNotifications.empty; - bool IPredicate.trigger(OrderSecurity order) => + bool IPredicate.trigger(OrderRecordTuple order) => OrderEventPredicateHelper.check_order_transition_predicate(order, _is_canceled, _security_predicate, _data_cache); public bool Equals(MyToaster other) => diff --git a/src/client/spark/Predicates/Data/Events/OrderCompletedEventPredicate.cs b/src/client/spark/Predicates/Data/Events/OrderCompletedEventPredicate.cs index c4073ee55..1766a5548 100644 --- a/src/client/spark/Predicates/Data/Events/OrderCompletedEventPredicate.cs +++ b/src/client/spark/Predicates/Data/Events/OrderCompletedEventPredicate.cs @@ -8,6 +8,7 @@ using mbts.ui.settings; using ProtoBuf; +using Spark.Api.Orders; using Spark.Core.Data; using System; @@ -52,13 +53,13 @@ namespace mbts { } } - public IPredicate create(object obj) => + public IPredicate create(object obj) => create_predicate((INotificationServiceDataCache)obj); - public IPredicate create_predicate(INotificationServiceDataCache data_cache) => + public IPredicate create_predicate(INotificationServiceDataCache data_cache) => OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Completed, security, data_cache); - public INotificationPredicate create_toast( + public INotificationPredicate create_toast( INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) => new MyToaster(security?.create(), data_cache, sec_meta_store); @@ -69,7 +70,7 @@ namespace mbts { static bool _is_completed(OrderRecordImmutable o) => o.HasState && o.State.Status == OrderStatus.Completed; - class MyToaster : INotificationPredicate, IEquatable { + class MyToaster : INotificationPredicate, IEquatable { readonly IPredicate _security_predicate; readonly INotificationServiceDataCache _data_cache; readonly ISecurityMetadataStore _sec_meta_store; @@ -83,7 +84,7 @@ namespace mbts { _sec_meta_store = sec_meta_store; } - public IToastNotification trigger(OrderSecurity order) { + public IToastNotification trigger(OrderRecordTuple order) { if (!OrderEventPredicateHelper.check_order_transition_predicate( order, _is_completed, _security_predicate, _data_cache)) { return ToastNotifications.empty; @@ -95,7 +96,7 @@ namespace mbts { return ToastNotifications.order_completed(order, qty_display); } - bool IPredicate.trigger(OrderSecurity order) => + bool IPredicate.trigger(OrderRecordTuple order) => OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache); public bool Equals(MyToaster other) => diff --git a/src/client/spark/Predicates/Data/Events/OrderEventPredicateHelper.cs b/src/client/spark/Predicates/Data/Events/OrderEventPredicateHelper.cs index 0c1c80873..e29912039 100644 --- a/src/client/spark/Predicates/Data/Events/OrderEventPredicateHelper.cs +++ b/src/client/spark/Predicates/Data/Events/OrderEventPredicateHelper.cs @@ -3,6 +3,8 @@ using bts.api.orderman; using bts.shell; using bts.utils; +using Spark.Api.Orders; + using System; namespace mbts { @@ -10,13 +12,23 @@ namespace mbts { /// /// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.' /// - public static bool check_order_transition_predicate(OrderSecurity order, Func order_predicate_core, IPredicate security_predicate, INotificationServiceDataCache data_cache) => + public static bool check_order_transition_predicate( + OrderRecordTuple order, + Func order_predicate_core, + IPredicate security_predicate, + INotificationServiceDataCache data_cache) => check_order_transition_trigger(order, order_predicate_core, security_predicate, data_cache, out var _); /// /// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.' Oldval will be null if the order did not previously exist, or does not currently pass the predicate. /// - public static bool check_order_transition_trigger(OrderSecurity order, Func order_predicate_core, IPredicate security_predicate, INotificationServiceDataCache data_cache, out OrderSecurity? oldval) { + public static bool check_order_transition_trigger( + OrderRecordTuple order, + Func order_predicate_core, + IPredicate security_predicate, + INotificationServiceDataCache data_cache, + out OrderRecordTuple? oldval + ) { if (check_security_predicate(order, security_predicate) && order_predicate_core(order.order)) { oldval = data_cache.get_previous_order_state(order.order.Key); return oldval == null ? !data_cache.is_first_order_update : !order_predicate_core(oldval.Value.order); @@ -28,19 +40,23 @@ namespace mbts { /// /// Checks if the 'security predicate is null,' or 'it is not null, and the order has a non-null security which passes.' /// - public static bool check_security_predicate(OrderSecurity order, IPredicate security_predicate) => + public static bool check_security_predicate( + OrderRecordTuple order, IPredicate security_predicate) => security_predicate == null || (order.security.HasValue && security_predicate.trigger(order.security.Value)); - public static OrderStatus? get_nullable_status(OrderSecurity? order) { + public static OrderStatus? get_nullable_status(OrderRecordTuple? order) { if (order?.order.HasState == true) return order?.order.State.Status; return null; } - public static IPredicate create_status_transition_predicate(OrderStatus status, SecurityPredicate security_predicate, INotificationServiceDataCache data_cache) => + public static IPredicate create_status_transition_predicate( + OrderStatus status, + SecurityPredicate security_predicate, + INotificationServiceDataCache data_cache) => new OrderStatusTransitionPredicate(status, security_predicate?.create(), data_cache); - class OrderStatusTransitionPredicate : IPredicate, IEquatable { + class OrderStatusTransitionPredicate : IPredicate, IEquatable { readonly IPredicate _security_predicate; readonly INotificationServiceDataCache _data_cache; readonly OrderStatus _status; @@ -51,7 +67,7 @@ namespace mbts { _data_cache = data_cache; } - public bool trigger(OrderSecurity value) => + public bool trigger(OrderRecordTuple value) => check_order_transition_predicate(value, o => o.HasState && o.State.Status == _status, _security_predicate, _data_cache); public bool Equals(OrderStatusTransitionPredicate other) => diff --git a/src/client/spark/Predicates/Data/Events/OrderFilledEventPredicate.cs b/src/client/spark/Predicates/Data/Events/OrderFilledEventPredicate.cs index 63668fc85..561a9e9a0 100644 --- a/src/client/spark/Predicates/Data/Events/OrderFilledEventPredicate.cs +++ b/src/client/spark/Predicates/Data/Events/OrderFilledEventPredicate.cs @@ -14,8 +14,6 @@ using System; using System.Collections.Generic; - using OrderSecurity = bts.api.orderman.OrderSecurity; - static class OrderFilledEventPredicateVMFactory { public static Dictionary> get_oneofs(IBus bus) => new Dictionary> { @@ -53,13 +51,13 @@ } } - public IPredicate create(object obj) => + public IPredicate create(object obj) => create_predicate((INotificationServiceDataCache)obj); - public IPredicate create_predicate(INotificationServiceDataCache notification_service_data_cache) => + public IPredicate create_predicate(INotificationServiceDataCache notification_service_data_cache) => new FillTrigger(_create_model(notification_service_data_cache)); - public INotificationPredicate create_toast(INotificationServiceDataCache notification_service_data_cache) => + public INotificationPredicate create_toast(INotificationServiceDataCache notification_service_data_cache) => new FillToastNotificationTrigger(_create_model(notification_service_data_cache)); public bool Equals(OrderFilledEventPredicate other) => other != null && other.security.safe_equals(other.security); @@ -79,7 +77,7 @@ } // Please review carfully - public (OrderSecurity oldval, OrderSecurity newval)? get_filled_order_args(OrderSecurity ort) { + public (OrderRecordTuple oldval, OrderRecordTuple newval)? get_filled_order_args(OrderRecordTuple ort) { if (ort.order.is_exchange_order() && OrderEventPredicateHelper.check_security_predicate(ort, _security_predicate)) { if (_data_cache.get_previous_order_state(ort.order.Key) is var oldval && oldval.HasValue) { if (ort.order.filled_quantity() > oldval?.order.filled_quantity()) { @@ -89,25 +87,25 @@ // old order will be a copy of new order, except with filledQuantity set to 0 var old_state = ort.order.State.CloneToMutable(); old_state.FilledQuantity = 0; - return (new OrderSecurity(ort.security, ort.order.with(state: old_state), ort.piq), ort); + return (new(ort.order.with(state: old_state), ort.security, ort.piq), ort); } } return null; } } - class FillTrigger : IPredicate { + class FillTrigger : IPredicate { protected readonly FillTriggerModel _model; public FillTrigger(FillTriggerModel model) => _model = model; - public bool trigger(OrderSecurity order) => _model.get_filled_order_args(order).HasValue; + public bool trigger(OrderRecordTuple order) => _model.get_filled_order_args(order).HasValue; } - class FillToastNotificationTrigger : FillTrigger, INotificationPredicate { + class FillToastNotificationTrigger : FillTrigger, INotificationPredicate { public FillToastNotificationTrigger(FillTriggerModel model) : base(model) { } - public new IToastNotification trigger(OrderSecurity value) { + public new IToastNotification trigger(OrderRecordTuple value) { var args = _model.get_filled_order_args(value); if (args.HasValue) { return ToastNotifications.order_filled(args.Value.oldval, args.Value.newval); diff --git a/src/client/spark/Predicates/Data/Events/OrderSentEventPredicate.cs b/src/client/spark/Predicates/Data/Events/OrderSentEventPredicate.cs index 4d6811756..32e14002b 100644 --- a/src/client/spark/Predicates/Data/Events/OrderSentEventPredicate.cs +++ b/src/client/spark/Predicates/Data/Events/OrderSentEventPredicate.cs @@ -15,8 +15,6 @@ using System.Collections.Generic; using System.ComponentModel; - using OrderSecurity = bts.api.orderman.OrderSecurity; - static class OrderSentEventPredicateVMFactory { public static Dictionary> get_oneofs(IBus bus) => new Dictionary> { @@ -56,12 +54,12 @@ } } - public IPredicate create(object obj) => + public IPredicate create(object obj) => create_predicate((INotificationServiceDataCache)obj); - public IPredicate create_predicate(INotificationServiceDataCache data_cache) { + public IPredicate create_predicate(INotificationServiceDataCache data_cache) { var sec_pred = security?.create(); - return PredicateBuilder.create(os => + return PredicateBuilder.create(os => // verify security (sec_pred == null || (os.security.HasValue && sec_pred.trigger(os.security.Value))) && // verify not stale @@ -72,7 +70,7 @@ (data_cache.order_history.TryGetValue(os.order.Key, out var hist) && hist.Count == 1)); } - public INotificationPredicate create_toast(INotificationServiceDataCache data_cache) => + public INotificationPredicate create_toast(INotificationServiceDataCache data_cache) => throw new NotImplementedException(); public bool Equals(OrderSentEventPredicate other) => diff --git a/src/client/spark/Predicates/Data/OrderRecordTuplePredicate.cs b/src/client/spark/Predicates/Data/OrderRecordTuplePredicate.cs index d442d17c3..ac88c97c2 100644 --- a/src/client/spark/Predicates/Data/OrderRecordTuplePredicate.cs +++ b/src/client/spark/Predicates/Data/OrderRecordTuplePredicate.cs @@ -15,7 +15,6 @@ using Spark.Core.Data; using System; using System.Collections.Generic; -using OrderSecurity = bts.api.orderman.OrderSecurity; using PTOC = mbts.OrderRecordTuplePredicate.PredicateTypeOneofCase; namespace mbts { @@ -225,7 +224,7 @@ namespace mbts { } } - public IPredicate create_predicate( + public IPredicate create_predicate( INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) { switch (predicate_type_case) { case PTOC.Security: return wrap(_security.create(), r => r.security); @@ -256,11 +255,11 @@ namespace mbts { default: return null; } // - IPredicate wrap(IPredicate trigger, Func select) => - trigger.wrap(select); + IPredicate wrap(IPredicate trigger, Func select) => + trigger.wrap(select); } - public INotificationPredicate create_notification_predicate( + public INotificationPredicate create_notification_predicate( INotificationServiceDataCache notification_service_data_cache, ISecurityMetadataStore sec_meta_store) { if (!is_toast_enabled) @@ -381,7 +380,7 @@ namespace mbts { } [ProtoContract] - class OrderRecordTuplePredicateAnimations : IPredicateAnimationsData { + class OrderRecordTuplePredicateAnimations : IPredicateAnimationsData { [ProtoMember(1)] OrderRecordTuplePredicate _predicate; [ProtoMember(2)] diff --git a/src/client/spark_api/Orders/OrderRecordTuple.cs b/src/client/spark_api/Orders/OrderRecordTuple.cs index 88c2f9b14..c237186d2 100644 --- a/src/client/spark_api/Orders/OrderRecordTuple.cs +++ b/src/client/spark_api/Orders/OrderRecordTuple.cs @@ -2,20 +2,39 @@ namespace Spark.Api.Orders { using bts.api; using bts.api.orderman; + using bts.utils; + + using mbts.spark; using System; public readonly struct OrderRecordTuple : IEquatable { - public OrderRecordTuple(OrderRecordImmutable order, SecurityImmutable? security = null) { + public OrderRecordTuple( + OrderRecordImmutable order, + SecurityImmutable? security = null, + uint? piq = null, + AlgoData? algo = null, + AlgoDefinitionMetadata? algo_meta = null + ) { this.order = order; this.security = security; + this.piq = piq; + this.algo = algo; + this.meta = algo_meta; } public OrderRecordImmutable order { get; } public SecurityImmutable? security { get; } - + public uint? piq { get; } + public AlgoData? algo { get; } + public AlgoDefinitionMetadata? meta { get; } + public CustomOrderDefinition.CustomOneofCase algo_type => + (algo?.value)?.CustomCase ?? order.order_type(); + public string? algo_name => algo?.name; + public uint key => order.Key; public uint account_id => order.account_id(); + public string account_name => order.account(); public uint security_id => order.security_key(); public bool Equals(OrderRecordTuple other) => @@ -34,4 +53,35 @@ namespace Spark.Api.Orders { public static bool operator !=(OrderRecordTuple left, OrderRecordTuple right) => !(left == right); } + + public readonly struct OrderRecordTupleWithRoot : IEquatable { + readonly OrderRecordTuple? _root; + + public OrderRecordTupleWithRoot(OrderRecordTuple order, OrderRecordTuple? root = null) { + this.order = order; + _root = root; + } + + public OrderRecordTuple order { get; } + public OrderRecordTuple root => _root ?? order; + + public uint key => order.key; + public uint security_id => order.security_id; + + public bool Equals(OrderRecordTupleWithRoot other) => + order.Equals(other.order) && + EqualityComparer.nullable_equals(_root, other._root); + + public override bool Equals(object? obj) => + obj is OrderRecordTupleWithRoot other && Equals(other); + + public override int GetHashCode() => + HashCode.Combine(order, _root); + + public static bool operator ==(OrderRecordTupleWithRoot left, OrderRecordTupleWithRoot right) => + left.Equals(right); + + public static bool operator !=(OrderRecordTupleWithRoot left, OrderRecordTupleWithRoot right) => + !(left == right); + } } diff --git a/src/client/spark_api/Orders/OrdersExtensions.cs b/src/client/spark_api/Orders/OrdersExtensions.cs index 2e4301cc6..d846fb8a2 100644 --- a/src/client/spark_api/Orders/OrdersExtensions.cs +++ b/src/client/spark_api/Orders/OrdersExtensions.cs @@ -196,6 +196,10 @@ namespace Spark.Api.Orders { public static bool can_detach(this OrderRecordImmutable order) => order.attached_target_order_key() == 0 && order.has_parent(); + + public static string display_name(this OrderRecordTuple order) => + order.order.display_name(order.algo, order.security); + public static string display_name( this OrderRecordImmutable order, AlgoData? algo, SecurityImmutable? security = null) { if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader && security.HasValue)