diff --git a/src/client/spark/core/Collections/SetMap.cs b/src/client/spark/core/Collections/SetMap.cs index a3b360ee9..29cd73496 100644 --- a/src/client/spark/core/Collections/SetMap.cs +++ b/src/client/spark/core/Collections/SetMap.cs @@ -57,6 +57,18 @@ namespace mbts.collections { return false; } + public bool remove(TKey key) => + _dictionary.Remove(key); + + public void clear() => _dictionary.Clear(); + + public bool try_pop(TKey key, out ISet value) { + if (try_lookup(key, out value)) { + remove(key); + return true; + } else return false; + } + public bool try_lookup(TKey key, out ISet value) { if (_dictionary.TryGetValue(key, out InternalGroupSet result)) { value = result; diff --git a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs b/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs index 6054c1442..2de0efa43 100644 --- a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs @@ -449,6 +449,23 @@ namespace System.Collections.Generic { .ToDictionary(vals => vals.k, vals => (vals.Item2, vals.Item3)) ); } + + /// + /// If TryGetValue succeeds, result will be set with the corresponding value, and the key will be removed (returns true). + /// Otherwise, result is set to default, and nothing is removed (returns false). + /// + /// + /// + /// + /// + /// + /// + public static bool TryPopValue(this IDictionary dictionary, TKey key, out TValue result) { + if (dictionary.TryGetValue(key, out result)) { + dictionary.Remove(key); + return true; + } else return false; + } } public static class ListExtensions diff --git a/src/client/spark/core/Utility/AnonymousEqualityComparer.cs b/src/client/spark/core/Utility/AnonymousEqualityComparer.cs index f3e0f55a4..66115ca2f 100644 --- a/src/client/spark/core/Utility/AnonymousEqualityComparer.cs +++ b/src/client/spark/core/Utility/AnonymousEqualityComparer.cs @@ -20,6 +20,9 @@ namespace mbts.utils { return Create((x, y) => x.HasValue ? y.HasValue && eqc.Equals(key_selector(x.Value), key_selector(y.Value)) : !y.HasValue); } + public static IEqualityComparer CreateNullable(Func equals) where T : struct => + new AnonymousEqualityComparer((a, b) => a.HasValue ? b.HasValue && equals(a.Value, b.Value) : !b.HasValue); + public static bool NullCheckEquals(T x, T y, Func non_null_equals) where T : class, IEquatable => x == null ? y == null : y != null && diff --git a/src/client/spark/core/Utility/CompareUtils.cs b/src/client/spark/core/Utility/CompareUtils.cs index e69351b96..8e714db66 100644 --- a/src/client/spark/core/Utility/CompareUtils.cs +++ b/src/client/spark/core/Utility/CompareUtils.cs @@ -13,6 +13,11 @@ namespace mbts.utils { #region Comparison public static Comparison safe_comparison(Func compare) => (a, b) => a.safe_compare(b, compare); + + public static Comparison nullable_comparison(Func compare) where T : struct => + (a, b) => a.HasValue ? + b.HasValue ? compare(a.Value, b.Value) : 1 : + b.HasValue ? -1 : 0; #endregion } } \ No newline at end of file diff --git a/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs index 90a2605e3..d717f4a9d 100644 --- a/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs +++ b/src/client/spark/view/Controls/DIYGrid/Columns/ColumnBase.cs @@ -45,7 +45,7 @@ namespace mbts.ui.controls { internal interface IKeyedColumn { TColKey key { get; } } - + internal interface IFilterableColumn { IDataGridColumnFilter filter { get; } string filter_template { get; } @@ -57,13 +57,16 @@ namespace mbts.ui.controls { original_width = double.NaN; public static readonly DependencyProperty SortDirectionProperty = - WPFHelper.create_dp(nameof(SortDirection)); + WPFHelper.create_dp( + nameof(SortDirection), (o, v) => o.OnSortDirectionChanged(v)); public ListSortDirection? SortDirection { get => GetValue(SortDirectionProperty) as ListSortDirection?; set => SetValue(SortDirectionProperty, value); } public string sort_member_path { get; set; } public double original_width { get; set; } public bool is_collapsed { get; set; } + + protected virtual void OnSortDirectionChanged(ListSortDirection? new_value) { } } internal abstract class ColumnBase : ColumnBase, IKeyedColumn { diff --git a/src/client/spark/view/Spark/Core/OrderUtils.cs b/src/client/spark/view/Spark/Core/OrderUtils.cs index 688d294a7..9b3707078 100644 --- a/src/client/spark/view/Spark/Core/OrderUtils.cs +++ b/src/client/spark/view/Spark/Core/OrderUtils.cs @@ -9,7 +9,7 @@ using static mbts.ui.utilities.DisplayNameHelper; namespace mbts.spark { static class OrderUtils { - public static uint filled(OrderRecordImmutable order) => + public static uint filled(this OrderRecordImmutable order) => order.HasState ? order.State.FilledQuantity : 0u; public static double fill_ratio(OrderRecordImmutable order) { @@ -20,18 +20,54 @@ namespace mbts.spark { return double.NaN; } + public static uint quantity(this OrderRecordImmutable order) => + order.HasState ? order.State.Quantity : 0u; + public static int working_quantity(this OrderRecordImmutable order) => order.HasState ? (int)order.State.Quantity - (int)order.State.FilledQuantity : 0; public static double price(this OrderRecordImmutable order) => order.HasState ? order.State.Price : double.NaN; + public static double avg_price(this OrderRecordImmutable order) => + order.HasState ? order.State.AvgPrice : double.NaN; + + public static double last_price(this OrderRecordImmutable order) => + order.HasState ? order.State.LastPrice : double.NaN; + + public static string last_msg(this OrderRecordImmutable order) => + order.HasState ? order.State.LastMsg : string.Empty; + public static DateTime created(this OrderRecordImmutable order) => order.HasState && order.State.HasCreated ? order.State.Created.ToDateTime().ToLocalTime() : DateTime.MinValue; public static DateTime last_change(this OrderRecordImmutable order) => order.HasState && order.State.HasLastChange ? order.State.LastChange.ToDateTime().ToLocalTime() : DateTime.MinValue; + public static OrderStatus status(this OrderRecordImmutable order) => + order.HasState ? order.State.Status : OrderStatus.Error; + + public static uint security_key(this OrderRecordImmutable order) => + order.HasDef ? order.Def.SecurityKey : 0u; + + public static Side side(this OrderRecordImmutable order) => + order.HasDef ? order.Def.Side : Side.Undefined; + + public static string user(this OrderRecordImmutable order) => + order.HasDef ? order.Def.User : string.Empty; + + public static string account(this OrderRecordImmutable order) => + order.HasDef ? order.Def.Account : string.Empty; + + public static CustomOrderDefinition.CustomOneofCase order_type(this OrderRecordImmutable order) => + order.HasDef && order.Def.HasCustomDef ? order.Def.CustomDef.CustomCase : CustomOrderDefinition.CustomOneofCase.None; + + public static OrderSubType sub_type(this OrderRecordImmutable order) => + order.HasDef ? order.Def.SubType : OrderSubType.None; + + public static TimeInForce time_in_force(this OrderRecordImmutable order) => + order.HasDef ? order.Def.TimeInForce : TimeInForce.Undefined; + public static string full_description(this OrderRecordImmutable order, SecurityImmutable security) { StringBuilder sb = new StringBuilder(); string sec_key_text; diff --git a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookCell.cs b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookCell.cs new file mode 100644 index 000000000..f8f04a248 --- /dev/null +++ b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookCell.cs @@ -0,0 +1,111 @@ +using mbts.utils; +using System; +using System.Collections.Generic; +using System.ComponentModel; + +namespace mbts.spark { + partial class CVOrderBookRowVM { + public interface IOrderBookCell : IComparable, INotifyPropertyChanged { + string text { get; } + bool refresh(); + } + + public static class CellFactory { + public static OrderBookCell create(CVOrderBookRowVM row, ICVOrderBookColumn column, Func get_value, Func> get_cell, Func format = null) => + new OrderBookCell(row, column, get_value, get_cell, format, new Comparison(Comparer.Default.Compare), EqualityComparer.Default); + + public static OrderBookCell create(CVOrderBookRowVM row, ICVOrderBookColumn column, Func get_value, Func> get_cell, Comparison comparison, Func format = null) => + new OrderBookCell(row, column, get_value, get_cell, format, comparison, EqualityComparer.Default); + + public static OrderBookCell create_nullable(CVOrderBookRowVM row, ICVOrderBookColumn column, Func get_value, Func> get_cell, Func format = null) + where T : struct => new OrderBookCell(row, column, get_value, get_cell, format, CompareUtils.nullable_comparison(Comparer.Default.Compare), EqualityComparer.CreateNullable(EqualityComparer.Default.Equals)); + + public static OrderBookCell create_nullable(CVOrderBookRowVM row, ICVOrderBookColumn column, Func get_value, Func> get_cell, Func compare, Func format = null) + where T : struct => new OrderBookCell(row, column, get_value, get_cell, format, CompareUtils.nullable_comparison(compare), EqualityComparer.CreateNullable(EqualityComparer.Default.Equals)); + } + + public class OrderBookCell : IComparable>, IOrderBookCell { + readonly CVOrderBookRowVM _row; + readonly ICVOrderBookColumn _column; + readonly Func _get_value; + readonly Func> _get_cell; + readonly Func _format; + readonly Comparison _comparison; + readonly IEqualityComparer _eq_comparer; + T _value; + string _text; + + public OrderBookCell(CVOrderBookRowVM row, ICVOrderBookColumn column, Func get_value, Func> get_cell, Func format, Comparison comparison, IEqualityComparer eq_comparer) { + _row = row; + _column = column; + _get_value = get_value; + _get_cell = get_cell; + _format = format ?? new Func(v => v?.ToString() ?? string.Empty); + _comparison = comparison; + _eq_comparer = eq_comparer; + _value = _get_value(_row); + } + + public event PropertyChangedEventHandler PropertyChanged; + + public T value => _value; + public string text => _text ?? (_text = _format(_value)); + + public bool refresh() { + var v = _get_value(_row); + if (!_eq_comparer.Equals(v, _value)) { + _value = v; + _text = null; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(value))); + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(text))); + return true; + } + return false; + } + + public int CompareTo(OrderBookCell other) { + if (other == null) + return 1; + var lin = _lineage(_row); + var olin = _lineage(other._row); + int c = 0; + using (var en = lin.GetEnumerator()) + using (var oen = olin.GetEnumerator()) { + while (en.MoveNext() && oen.MoveNext()) { + if (en.Current.order_key.value != oen.Current.order_key.value) { + c = _comparison(_get_cell(en.Current).value, _get_cell(oen.Current).value); + if (c != 0) + return c; + else { + c = en.Current.order_key.value.CompareTo(oen.Current.order_key.value); + return _column.SortDirection.HasValue && _column.SortDirection.Value == ListSortDirection.Ascending ? c : -c; + } + } + } + } + return _column.SortDirection.HasValue && _column.SortDirection.Value == ListSortDirection.Ascending ? + lin.Count.CompareTo(olin.Count) : olin.Count.CompareTo(lin.Count); + } + + public int CompareTo(object obj) => + CompareTo(obj as OrderBookCell); + + public override string ToString() => text; + + // any performance benefits of caching parent rows should be negligable - _book_vm.get_parent() uses a dictionary lookup + static List _lineage(CVOrderBookRowVM r) { + var origin = r; + var rv = new List(2); // 99% of the time, this list won't have more than 2 elements + while (r.order.has_parent()) { + r = r._book_vm.get_order_vm(r.parent_order_key.value); + if (r == null) + break; + rv.Add(r); + } + rv.Reverse(); + rv.Add(origin); + return rv; + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookColumns.cs b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookColumns.cs new file mode 100644 index 000000000..276aa139a --- /dev/null +++ b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookColumns.cs @@ -0,0 +1,519 @@ +using bts.api; +using bts.api.orderman; +using mbts.spark.filters; +using mbts.ui; +using mbts.ui.converters; +using mbts.ui.utility; +using mbts.ui.utility.text; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Media; +using static bts.shell.OrderBookWindowFactory; +using static mbts.spark.OrderBookView; +using static mbts.ui.controls.DIYGrid; +using OrderType = bts.api.orderman.CustomOrderDefinition.CustomOneofCase; + +namespace mbts.spark { + // This interface is used to hide ColumnBase.SortDirection, and offer a SortDirection member that does NOT require a DependencyProperty lookup. + // In OrderBookRowVM, each "cell(property)" has a corresponding TreeComparable property that the column uses for sorting + // - each columns' sort_member_path points to the TreeComparable. + // The TreeComparable class needs to know which direction it is sorting so it can force child-orders to always be beneath their parents. + // - when comparing with their parent, it must return 1 if Ascending, -1 if Descending. + // Since the TreeComparables in each row must access their respective column SortDirections in their CompareTo methods, those DP lookups could add significant overhead in large collections. + // I considered adding ListSortDirection members directly to OrderBookVM, and letting the TreeComparables refer to that property, + // but decided it would be better to let the Columns own it so we wouldn't have to worry about keeping the 2 props in sync. + // TODO: Maybe binding to the SortDirection would be less smelly? + // - initially, I tried to bind to the SortDirection of each column, unfortunately, the binding target was not updated before the ICollectionView sorting took place. + // I decided it was not worth changing the DIYGrid.Sorting function to force the SortDirection binding targets to update immediately, before the ICollectionView sorting. + interface ICVOrderBookColumn { + ListSortDirection? SortDirection { get; } + IDataGridColumnFilter filter { get; } + } + + partial class CVOrderBookVM { + public class CVOrderBookColumnCollection : ObservableCollection, IDisposable { + public CVOrderBookColumnCollection(OrdersModel model, OrderBookStartupData startup_data) { + // security + Add(security_column = new SecurityColumn(this, + new RegexFilterVM(r => r.security.text, value_path(nameof(OrderBookRowVM.security_text))))); + // time_created + Add(time_created_column = new TimeCreatedColumn( + new TimeFilterVM(r => r.time_created.value, value_path(nameof(OrderBookRowVM.time_created))))); + // last_change + Add(last_change_column = new LastChangeTimeColumn( + new TimeFilterVM(r => r.last_change.value, value_path(nameof(CVOrderBookRowVM.last_change))))); + // user + Add(user_column = new SimpleTextColumn( + Columns.User, + DefaultColumnHeaders.User, + nameof(CVOrderBookRowVM.user), + r => r.user.value, + DefaultColumnWidths.User, + DiscreteValuesFilterVM.Create( + model.factory.users, + r => r.user.value, + value_path(nameof(CVOrderBookRowVM.user))), + DataGridFilterKnownTemplates.DiscreteValues)); + // account + Add(account_column = new SimpleTextColumn( + Columns.Account, + DefaultColumnHeaders.Account, + nameof(CVOrderBookRowVM.account), + r => r.account.value, + DefaultColumnWidths.Account, + DiscreteValuesFilterVM.Create( + model.factory.subscribe_accounts(), + r => r.account.value, + vals => vals.ToArray(), + vals => Observable.Return(vals), + value_path(nameof(CVOrderBookRowVM.account))), + DataGridFilterKnownTemplates.DiscreteValues)); + // exchange + Add(exchange_column = new SimpleTextColumn( + Columns.Exchange, + DefaultColumnHeaders.Exchange, + nameof(CVOrderBookRowVM.exchange), + r => r.exchange.text, + DefaultColumnWidths.Exchange, + DiscreteValuesFilterVM.Create( + EnumHelper.get_values_except(Venue.Unset).ToList(), + r => r.exchange.value, + value_path(nameof(CVOrderBookRowVM.exchange))), + DataGridFilterKnownTemplates.EnumValues)); + // time in force + Add(time_in_force_column = new SimpleTextColumn( + Columns.TimeInForce, + DefaultColumnHeaders.TimeInForce, + nameof(CVOrderBookRowVM.time_in_force), + r => r.time_in_force.text, + DefaultColumnWidths.TimeInForce, + DiscreteValuesFilterVM.Create( + EnumHelper.get_values().ToList(), + r => r.time_in_force.value, + value_path(nameof(CVOrderBookRowVM.time_in_force))), + DataGridFilterKnownTemplates.EnumValues)); + // order type + Add(order_type_column = new OrderBookOrderTypeColumn( + DiscreteValuesFilterVM.Create( + EnumHelper.get_values_except(OrderType.None).ToList(), + r => r.order_type.value, + value_path(nameof(CVOrderBookRowVM.order_type))))); + // order sub type + Add(sub_type_column = new SimpleTextColumn( + Columns.SubType, + "Sub Type", + nameof(CVOrderBookRowVM.order_sub_type), + r => r.order_sub_type.text, + 80, + DiscreteValuesFilterVM.Create( + EnumHelper.get_values().ToList(), + r => r.order_sub_type.value, + value_path(nameof(CVOrderBookRowVM.order_sub_type))), + SubTypeFilterTemplateKey)); + // side + Add(side_column = new SideColumn( + DiscreteValuesFilterVM.Create( + new[] { Side.Buy, Side.Sell }, + r => r.side.value, + value_path(nameof(CVOrderBookRowVM.side))))); + // quantity + Add(qty_column = new SizeColumn( + new UIntMinMax(r => r.quantity.value, value_path(nameof(CVOrderBookRowVM.quantity))))); + // price + Add(price_column = new PriceColumn( + new DoubleMinMax(r => r.price.value, value_path(nameof(CVOrderBookRowVM.price))))); + // filled quantity + Add(filled_qty_column = new FilledColumn( + new UIntMinMax(r => r.filled_quantity.value, value_path(nameof(CVOrderBookRowVM.filled_quantity))))); + // avg filled price + Add(avg_price_column = new AvgFilledColumn( + new DoubleMinMax(r => r.avg_price.value, value_path(nameof(CVOrderBookRowVM.avg_price))))); + // last filled price + Add(last_price_column = new LastFilledColumn( + new DoubleMinMax(r => r.last_price.value, value_path(nameof(CVOrderBookRowVM.last_price))))); + // status + Add(status_column = new SimpleTextColumn( + Columns.Status, + "Status", + nameof(CVOrderBookRowVM.status), + r => r.status.text, + 80, + DiscreteValuesFilterVM.Create( + EnumHelper.get_values().ToList(), + r => r.status.value, + value_path(nameof(CVOrderBookRowVM.status))), + DataGridFilterKnownTemplates.EnumValues)); + // last message + Add(last_message_column = new OrderBookLastMessageColumn( + new RegexFilterVM( + r => r.last_msg.value, + value_path(nameof(CVOrderBookRowVM.last_msg))))); + // security key + Add(security_key_column = new SimpleTextColumn( + Columns.SecurityKey, + DefaultColumnHeaders.SecurityKey, + nameof(CVOrderBookRowVM.security_key), + r => r.security_key.text, + DefaultColumnWidths.SecurityKey, + new RegexFilterVM( + r => r.security_key.text, + value_path(nameof(CVOrderBookRowVM.security_key))), + DataGridFilterKnownTemplates.Regex)); + // order key + Add(order_key_column = new SimpleTextColumn( + Columns.OrderKey, + DefaultColumnHeaders.OrderKey, + nameof(CVOrderBookRowVM.order_key), + r => r.order_key.text, + DefaultColumnWidths.OrderKey, + new RegexFilterVM( + r => r.order_key.text, + value_path(nameof(CVOrderBookRowVM.order_key))), + DataGridFilterKnownTemplates.Regex)); + // parent key (this is for diagnostic purposes, remove this column once OrderBook seems stable again) + Add(parent_key_column = new SimpleTextColumn( + Columns.ParentKey, + "Parent Key", + nameof(CVOrderBookRowVM.parent_order_key), + r => r.parent_order_key.text, + 80, + new RegexFilterVM( + r => r.parent_order_key.text, + value_path(nameof(CVOrderBookRowVM.parent_order_key))), + DataGridFilterKnownTemplates.Regex)); + + string value_path(string cell_name) => + string.Join(".", cell_name, nameof(CVOrderBookRowVM.OrderBookCell.value)); //uint is an arbitrary 'T', just want to get compile check on 'value' path. + + if (startup_data?.filters is FilterStates fs) { + // TODO: add "security filter" data to FilterStates + time_created_column.filter.load_state(fs.time_created); + user_column.filter.load_state(fs.users); + account_column.filter.load_state(fs.accounts); + price_column.filter.load_state(fs.price); + qty_column.filter.load_state(fs.qty); + filled_qty_column.filter.load_state(fs.qty_filled); + side_column.filter.load_state(fs.sides); + order_type_column.filter.load_state(fs.order_types); + // TODO: add "sub_type column.filter" data to FilterStates + time_in_force_column.filter.load_state(fs.tifs); + exchange_column.filter.load_state(fs.exchanges); + + order_key_column.filter.load_state(fs.order_key_regex); + avg_price_column.filter.load_state(fs.avg_price); + last_price_column.filter.load_state(fs.last_price); + status_column.filter.load_state(fs.statuses); + last_message_column.filter.load_state(fs.exchange_message_regex); + last_change_column.filter.load_state(fs.last_change); + security_column.filter.load_state(fs.security_regex); + } + if (startup_data?.sort_criteria is List lsc) { + foreach (var sc in lsc) + this.ApplyToFirst(c => c.sort_member_path == sc.col_name, c => c.SortDirection = sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending); + } + foreach (var c in this.Cast()) + c.filter.filter_changed += _set_active_filters; + _set_active_filters(); + } + + List> _active_filters; + + public event Action filter_changed; + + public SecurityColumn security_column { get; } + public TimeCreatedColumn time_created_column { get; } + public LastChangeTimeColumn last_change_column { get; } + public SimpleTextColumn user_column { get; } + public SimpleTextColumn account_column { get; } + public SimpleTextColumn exchange_column { get; } + public SimpleTextColumn time_in_force_column { get; } + public OrderBookOrderTypeColumn order_type_column { get; } + public SimpleTextColumn sub_type_column { get; } + public SideColumn side_column { get; } + public SizeColumn qty_column { get; } + public PriceColumn price_column { get; } + public FilledColumn filled_qty_column { get; } + public LastFilledColumn last_price_column { get; } + public AvgFilledColumn avg_price_column { get; } + public SimpleTextColumn status_column { get; } + public OrderBookLastMessageColumn last_message_column { get; } + public SimpleTextColumn security_key_column { get; } + public SimpleTextColumn order_key_column { get; } + public SimpleTextColumn parent_key_column { get; } + + public bool filter(CVOrderBookRowVM row) => _active_filters.All(f => f.filter(row)); + + public FilterStates get_filter_states() => + new FilterStates { + order_key_regex = order_key_column.filter.get_state(), + time_created = time_created_column.filter.get_state(), + users = user_column.filter.get_state(), + accounts = account_column.filter.get_state(), + exchanges = exchange_column.filter.get_state(), + tifs = time_in_force_column.filter.get_state(), + order_types = order_type_column.filter.get_state(), + sides = side_column.filter.get_state(), + qty = qty_column.filter.get_state(), + price = price_column.filter.get_state(), + qty_filled = filled_qty_column.filter.get_state(), + avg_price = avg_price_column.filter.get_state(), + last_price = last_price_column.filter.get_state(), + statuses = status_column.filter.get_state(), + exchange_message_regex = last_message_column.filter.get_state(), + last_change = last_change_column.filter.get_state(), + security_regex = security_column.filter.get_state() + }; + + public void Dispose() { + foreach (var c in this.Cast()) { + c.filter.filter_changed -= _set_active_filters; + (c.filter as IDisposable)?.Dispose(); + } + } + + void _set_active_filters() { + _active_filters = this + .Cast() + .Select(c => c.filter) + .Where(f => f.active.GetValueOrDefault()) + .ToList(); + filter_changed?.Invoke(); + } + } + + public abstract class OrderbookColumnBase : ColumnBase, IKeyedColumn, IFilterableColumn, ICVOrderBookColumn { + ListSortDirection? _cached_sort_direction; + readonly string _filter_template; + + protected OrderbookColumnBase(Columns col_key, string header, string sort_prop, double width, IDataGridColumnPersistentFilter filter, string filter_template) : base(col_key) { + Width = width; + Header = header; + sort_member_path = sort_prop; + this.filter = filter; + _filter_template = filter_template; + _cached_sort_direction = SortDirection; + } + + public IDataGridColumnPersistentFilter filter { get; } + + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter IFilterableColumn.filter => filter; + string IFilterableColumn.filter_template => _filter_template; + ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction; + + protected override void OnSortDirectionChanged(ListSortDirection? new_value) => _cached_sort_direction = new_value; + } + + public class SimpleTextColumn : OrderbookColumnBase, IRenderColumn { + readonly Func _get_text; + public SimpleTextColumn(Columns key, string header, string sort_prop, Func get_text, double width, IDataGridColumnPersistentFilter filter, string filter_template) + : base(key, header, sort_prop, width, filter, filter_template) => _get_text = get_text; + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) { + string text = _get_text(row); + if (!string.IsNullOrEmpty(text)) + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, text, position, RowHeight, + Brushes.Black, null, HorizontalAlignment.Left, VerticalAlignment.Center, DefaultCellPadding); + } + } + + #region Explicit Column Defs + public class SideColumn : OrderbookColumnBase, IRenderColumn { + public SideColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.Side, "B/S", nameof(CVOrderBookRowVM.side), DefaultColumnWidths.Side, filter, DataGridFilterKnownTemplates.EnumValues) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.side.text, position, RowHeight, + RenderUtils.get_side_brush(row), null, HorizontalAlignment.Left, VerticalAlignment.Center, DefaultCellPadding); + } + + public class SizeColumn : OrderbookColumnBase, IRenderColumn { + public SizeColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.Size, "Qty", nameof(CVOrderBookRowVM.quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax) { + sort_member_path = nameof(CVOrderBookRowVM.quantity); + } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.quantity.text, position, RowHeight, + RenderUtils.get_side_brush(row), null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding); + } + + public class FilledColumn : OrderbookColumnBase, IRenderColumn { + public FilledColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.Filled, "Filled Qty", nameof(CVOrderBookRowVM.filled_quantity), DefaultColumnWidths.Size, filter, DataGridFilterKnownTemplates.UIntMinMax) { + sort_member_path = nameof(CVOrderBookRowVM.filled_quantity); + } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.filled_quantity.text, position, RowHeight, + RenderUtils.get_side_brush(row), null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding); + } + + public class PriceColumn : OrderbookColumnBase, IRenderColumn { + public PriceColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.Price, "Price", nameof(CVOrderBookRowVM.price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.price.text, + position, RowHeight, Brushes.Black, null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding); + } + + public class AvgFilledColumn : OrderbookColumnBase, IRenderColumn { + public AvgFilledColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.AvgFilled, "Avg Filled", nameof(CVOrderBookRowVM.avg_price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) { + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.avg_price.text, + position, RowHeight, Brushes.Black, null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding); + } + } + + public class LastFilledColumn : OrderbookColumnBase, IRenderColumn { + public LastFilledColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.LastPrice, "Last Filled", nameof(CVOrderBookRowVM.last_price), DefaultColumnWidths.Price, filter, DataGridFilterKnownTemplates.DoubleMinMax) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.last_price.text, + position, RowHeight, Brushes.Black, null, HorizontalAlignment.Right, VerticalAlignment.Center, DefaultCellPadding); + } + + public class TimeCreatedColumn : OrderbookColumnBase, IRenderColumn { + public TimeCreatedColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.Time, "Time", nameof(CVOrderBookRowVM.time_created), DefaultColumnWidths.Time, filter, DataGridFilterKnownTemplates.TimeFilter) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.time_created.text, + position, RowHeight, Brushes.Black, null, HorizontalAlignment.Left, VerticalAlignment.Center, DefaultCellPadding); + } + + public class LastChangeTimeColumn : OrderbookColumnBase, IRenderColumn { + public LastChangeTimeColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.LastChange, "Last Change", nameof(CVOrderBookRowVM.last_change), DefaultColumnWidths.Time, filter, DataGridFilterKnownTemplates.TimeFilter) { } + + public void draw(CVOrderBookRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) => + CellRender.draw_text(dc, RenderUtils.get_glyph_context(row), RenderUtils.font_size, row.last_change.text, + position, RowHeight, Brushes.Black, null, HorizontalAlignment.Left, VerticalAlignment.Center, DefaultCellPadding); + } + + public class OrderBookOrderTypeColumn : OrderTypeColumn, ICVOrderBookColumn { + ListSortDirection? _cached_sort_direction; + public OrderBookOrderTypeColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.OrderType, new Binding($"{nameof(CVOrderBookRowVM.order_type)}.{nameof(CVOrderBookRowVM.OrderBookCell.value)}"), new Binding(nameof(CVOrderBookRowVM.order_metadata)), filter) { + this.filter = filter; + sort_member_path = nameof(CVOrderBookRowVM.order_type); + font_weight_binding = RenderUtils.get_font_weight_binding(); + _cached_sort_direction = SortDirection; + } + + public new IDataGridColumnPersistentFilter filter { get; } + + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction; + + protected override void OnSortDirectionChanged(ListSortDirection? new_value) => _cached_sort_direction = new_value; + } + + public class OrderBookLastMessageColumn : TextColumn, ICVOrderBookColumn { + ListSortDirection? _cached_sort_direction; + + public OrderBookLastMessageColumn(IDataGridColumnPersistentFilter filter) + : base(Columns.LastMessage, new Binding(nameof(CVOrderBookRowVM.last_msg)), filter, DataGridFilterKnownTemplates.Regex) { + this.filter = filter; + Header = "Last Message"; + Width = 80; + sort_member_path = nameof(CVOrderBookRowVM.last_msg); + tooltip_binding = new Binding(nameof(CVOrderBookRowVM.last_msg)); + } + + public new IDataGridColumnPersistentFilter filter { get; } + + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction; + + protected override void OnSortDirectionChanged(ListSortDirection? new_value) => _cached_sort_direction = new_value; + } + + public class SecurityColumn : FrameworkElementColumnBase, ICVOrderBookColumn, IFilterableColumn { + readonly BindingBase _font_weight_binding = RenderUtils.get_font_weight_binding(); + readonly IValueConverter _expander_visiblilty_converter = new ui.converters.BooleanToVisibilityConverter { VisibilityForFalse = Visibility.Hidden }; + readonly IValueConverter _margin_converter = new AnonymousValueConverter(level => new Thickness(10 * level, 0, 0, 0)); + + ListSortDirection? _cached_sort_direction; + + public SecurityColumn(CVOrderBookColumnCollection owner, IDataGridColumnPersistentFilter filter) : base(Columns.Security) { + this.filter = filter; + Header = DefaultColumnHeaders.Security; + Width = DefaultColumnWidths.Security; + sort_member_path = nameof(CVOrderBookRowVM.security); + _cached_sort_direction = SortDirection; + } + + public IDataGridColumnPersistentFilter filter { get; } + + IDataGridColumnFilter ICVOrderBookColumn.filter => filter; + IDataGridColumnFilter IFilterableColumn.filter { get; } + string IFilterableColumn.filter_template => DataGridFilterKnownTemplates.Regex; + ListSortDirection? ICVOrderBookColumn.SortDirection => _cached_sort_direction; + + public override FrameworkElement view_factory() { + // expander + var toggle_button = new ToggleButton { ClickMode = ClickMode.Press, IsThreeState = false }; + toggle_button.SetBinding(ToggleButton.IsCheckedProperty, new Binding(nameof(CVOrderBookRowVM.is_expanded))); + toggle_button.SetBinding(ToggleButton.MarginProperty, new Binding(nameof(CVOrderBookRowVM.depth_level)) { Converter = _margin_converter }); + toggle_button.SetBinding(ToggleButton.VisibilityProperty, new Binding(nameof(CVOrderBookRowVM.is_parent)) { Converter = _expander_visiblilty_converter }); + toggle_button.SetResourceReference(ToggleButton.StyleProperty, ExpandCollapseToggleStyleKey); + // + var security_view = new TextBlock(); + security_view.SetBinding(TextBlock.TextProperty, nameof(CVOrderBookRowVM.security)); + security_view.SetBinding(TextBlock.FontWeightProperty, _font_weight_binding); + // + var grid = new Grid(); + Grid.SetColumn(security_view, 1); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); + grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); + grid.Children.Add(toggle_button); + grid.Children.Add(security_view); + return grid; + } + + protected override void OnSortDirectionChanged(ListSortDirection? new_value) => _cached_sort_direction = new_value; + } + #endregion + + static class RenderUtils { + public static readonly Brush _working_order_brush = 0xffedcdu.rgb_brush(); + public static readonly GlyphContext _child_glyph_context = TextUtils.StandardGlyphContext.with(FontWeights.Light); + public static double font_size = FontSizes.Small; + + public static readonly IValueConverter + _sub_type_text_converter = new ui.spark.converters.OrderSubTypeDisplayTextConverter(), + _side_brush_converter = new AnonymousValueConverter(s => s == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask), + _font_weight_converter = new AnonymousValueConverter(is_child => is_child ? FontWeights.Light : FontWeights.Normal); + public static readonly IMultiValueConverter + _price_text_converter = new ui.spark.converters.TickDisplayConverter(), + _background_converter = new AnonymousMultiValueConverter( + (selected, status) => selected || status != OrderStatus.Working ? Brushes.Transparent : _working_order_brush); + + public static BindingBase _get_background_binding() { + var mb = new MultiBinding { Converter = _background_converter }; + mb.Bindings.Add(new Binding(nameof(ListBoxItem.IsSelected)) { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1) }); + mb.Bindings.Add(new Binding(nameof(CVOrderBookRowVM.status))); + return mb; + } + + static RenderUtils() => _working_order_brush.Freeze(); + + public static GlyphContext get_glyph_context(CVOrderBookRowVM r) => r.is_child ? _child_glyph_context : TextUtils.StandardGlyphContext; + public static Brush get_side_brush(CVOrderBookRowVM r) => r.side.value == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask; + public static BindingBase get_font_weight_binding() => new Binding(nameof(CVOrderBookRowVM.is_child)) { Converter = _font_weight_converter }; + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs new file mode 100644 index 000000000..434f77e24 --- /dev/null +++ b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookRowVM.cs @@ -0,0 +1,205 @@ +using bts.api; +using bts.api.orderman; +using bts.spark; +using mbts.ui; +using mbts.ui.shell; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Input; +using OrderStatus = bts.api.orderman.OrderStatus; + +namespace mbts.spark { + partial class CVOrderBookRowVM : ViewModelBase, IEquatable, ui.controls.DIYGrid.IRowVM, ui.controls.DIYGrid.IActionableRowVM { + readonly CVOrderBookVM _book_vm; + readonly OrdersModel _model; + readonly Property _visible, _expanded; + readonly HashSet _child_order_ids = new HashSet(); + readonly ObservantCommand _show_order_modify_cmd; + OrderRecordImmutable _order; + SecurityImmutable? _security; + + public CVOrderBookRowVM(IBus bus, CVOrderBookVM source_vm, OrdersModel model, OrderRecordImmutable record, SecurityImmutable? s) { + _book_vm = source_vm; + _model = model; + _order = record; + _security = s; + // cells + security = CellFactory.create_nullable(this, _book_vm.columns.security_column, r => r._security, r => r.security, v => v.HasValue ? v.Value.ToString() : "unknown security"); + security_key = CellFactory.create(this, _book_vm.columns.security_key_column, r => r._order.security_key(), r => r.security_key); + parent_order_key = CellFactory.create(this, _book_vm.columns.parent_key_column, r => r._order.ParentKey, r => r.parent_order_key); + order_key = CellFactory.create(this, _book_vm.columns.order_key_column, r => r._order.Key, r => r.order_key); + time_created = CellFactory.create(this, _book_vm.columns.time_created_column, r => r._order.created(), r => r.time_created, format_date); + user = CellFactory.create(this, _book_vm.columns.user_column, r => _order.user(), r => r.user); + account = CellFactory.create(this, _book_vm.columns.account_column, r => r._order.account(), r => r.account); + exchange = CellFactory.create(this, _book_vm.columns.exchange_column, r => r._security.HasValue ? _security.Value.Exchange : Venue.Unset, r => r.exchange); + time_in_force = CellFactory.create(this, _book_vm.columns.time_in_force_column, r => r._order.time_in_force(), r => r.time_in_force); + order_type = CellFactory.create(this, _book_vm.columns.order_type_column, r => r._order.order_type(), r => r.order_type); + order_sub_type = CellFactory.create(this, _book_vm.columns.sub_type_column, r => r._order.sub_type(), r => r.order_sub_type, format_sub_type); + side = CellFactory.create(this, _book_vm.columns.side_column, r => r._order.side(), r => r.side); + last_change = CellFactory.create(this, _book_vm.columns.last_change_column, r => _order.last_change(), r => r.last_change, format_date); + price = CellFactory.create(this, _book_vm.columns.price_column, r => _order.price(), r => r.price, format_price); + quantity = CellFactory.create(this, _book_vm.columns.qty_column, r => _order.quantity(), r => r.quantity); + filled_quantity = CellFactory.create(this, _book_vm.columns.filled_qty_column, r => _order.filled(), r => r.filled_quantity); + avg_price = CellFactory.create(this, _book_vm.columns.avg_price_column, r => _order.avg_price(), r => r.avg_price, format_price); + last_price = CellFactory.create(this, _book_vm.columns.last_price_column, r => _order.last_price(), r => r.last_price, format_price); + status = CellFactory.create(this, _book_vm.columns.status_column, r => _order.status(), r => r.status); + last_msg = CellFactory.create(this, _book_vm.columns.last_message_column, r => _order.last_msg(), r => r.last_msg); + // + string format_price(double v) => _security.HasValue ? _security.Value.ContractSpec.format(v) : v.ToString(); + string format_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}"; + string format_sub_type(OrderSubType v) { + switch (v) { + case OrderSubType.HedgingLeg: return "H"; + case OrderSubType.QuotingLeg: return "Q"; + default: return string.Empty; + } + } + // + _visible = backing(nameof(is_visible), record.has_parent() && source_vm.get_order_vm(record.ParentKey) is CVOrderBookRowVM parent ? parent.is_visible && parent.is_expanded : true); + _expanded = backing(nameof(is_expanded), true); + toggle_command = new DelegateCommand(() => is_expanded = !is_expanded); + _show_order_modify_cmd = new ObservantCommand(() => bus.post(SparkTags.ShowModifyOrderTag, _order.Key)); + _show_order_modify_cmd.OnNext(status.value == OrderStatus.Working); + } + + public event Action invalidated; + + public OrderRecordImmutable order => _order; + // Core + public OrderBookCell order_key { get; } + public OrderBookCell parent_order_key { get; } + public OrderBookCell security_key { get; } + public OrderBookCell security { get; } + public OrderBookCell exchange { get; } + // Def + public OrderBookCell order_type { get; } + public OrderBookCell side { get; } + public OrderBookCell user { get; } + public OrderBookCell account { get; } + public OrderBookCell time_in_force { get; } + public OrderBookCell time_created { get; } + // State + public OrderBookCell last_change { get; } + public OrderBookCell status { get; } + public OrderBookCell price { get; } + public OrderBookCell quantity { get; } + public OrderBookCell filled_quantity { get; } + public OrderBookCell last_price { get; } + public OrderBookCell avg_price { get; } + public OrderBookCell last_msg { get; } + public OrderBookCell order_sub_type { get; } + public string order_sub_type_abbreviation => _order.Def.SubType == OrderSubType.None ? string.Empty : _order.Def.SubType.ToString().Substring(0, 1); + public OrderMetadata order_metadata => _model.factory.get_metadata(order_type.value); + // Commands + public ICommand toggle_command { get; } + ICommand ui.controls.DIYGrid.IActionableRowVM.default_command => _show_order_modify_cmd; + // Accessories + public bool is_parent => _child_order_ids.Count > 0; + public bool is_child => _order.has_parent(); + public IReadOnlyCollection child_order_ids => _child_order_ids; + public bool is_visible { get => _visible.Value; set => _visible.set(value); } + public bool is_expanded { + get => _expanded.Value; + set { + _expanded.set(value); + foreach (var k in child_order_ids) { + if (_book_vm.get_order_vm(k) is CVOrderBookRowVM vm) + vm.is_visible = value; + } + } + } + public int depth_level { + get { + int i = 1; + var curr = _order; + while (curr.has_parent() && _book_vm.try_get_order(curr.ParentKey, out curr)) + i++; + return i; + } + } + + // '_dynamic_render_cells' are presented by 'RenderColumns,' and may change value during the lifetime of this row + // Note: by instantiating all these cells inside a CellPropertyGroup, we can update all of them with a single call. + // this reduces the risk of accidentally failing to update one of the cells, esp if we make changes to them down the road. + IEnumerable _dynamic_render_cells { + get { + yield return last_change; + yield return price; + yield return quantity; + yield return filled_quantity; + yield return avg_price; + yield return last_price; + yield return status; + yield return last_msg; + } + } + + IEnumerable _security_dependent_cells { + get { + yield return security; + yield return price; + yield return avg_price; + yield return last_price; + } + } + + public void add_child_order(uint child_order_id) { + _child_order_ids.Add(child_order_id); + // we don't need to raise this every single time + if (_child_order_ids.Count == 1) + RaisePropertyChanged("is_parent"); + _book_vm.get_order_vm(child_order_id)?.on_parent_updated(); + } + + public void remove_child_order(uint child_order_id) { + if (_child_order_ids.Remove(child_order_id)) { + if (_child_order_ids.Count == 0) + RaisePropertyChanged(nameof(is_parent)); + } + } + + /// + /// Raises PropertyChanged events for all live sorting properties, then calls parent_updated() on all descendents. + /// Note: call this method when parent order is added, removed, or changed. + /// + public void on_parent_updated() { + foreach (var p in _book_vm.live_sorting_props) + RaisePropertyChanged(p); + is_visible = _book_vm.get_order_vm(parent_order_key.value) is CVOrderBookRowVM parent ? parent.is_visible && parent.is_expanded : true; + foreach (var k in _child_order_ids) { + var child_vm = _book_vm.get_order_vm(k); + if (child_vm != null) + child_vm.on_parent_updated(); + } + } + + public void update_order(OrderRecordImmutable order) { + _order = order; + // use Count(), as opposed to Any(), to force it to iterate through all cells + if (_dynamic_render_cells.Count(c => c.refresh()) > 0) + invalidated?.Invoke(); + _show_order_modify_cmd.OnNext(status.value == OrderStatus.Working); + foreach (var p in _book_vm.live_sorting_props) + RaisePropertyChanged(p); + foreach (var child in _child_order_ids) + _book_vm.get_order_vm(child)?.on_parent_updated(); + } + + public void update_security(SecurityImmutable security) { + _security = security; + // use Count(), as opposed to Any(), to force it to iterate through all cells + if (_security_dependent_cells.Count(c => c.refresh()) > 0) + invalidated?.Invoke(); + if (_book_vm.live_sorting_props.Contains(nameof(security))) + RaisePropertyChanged(nameof(security)); + foreach (var child in _child_order_ids) + _book_vm.get_order_vm(child)?.on_parent_updated(); + } + + public bool Equals(CVOrderBookRowVM other) => other != null && other.order_key == order_key; + public override bool Equals(object obj) => Equals(obj as CVOrderBookRowVM); + public override int GetHashCode() => _order.GetHashCode(); + public override string ToString() => $"{order_key} {last_change} {parent_order_key}"; + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookVM.cs b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookVM.cs new file mode 100644 index 000000000..8e4a987b7 --- /dev/null +++ b/src/client/spark/view/Spark/Shell/CVOrderBook/CVOrderBookVM.cs @@ -0,0 +1,212 @@ +using bts.api; +using bts.api.core; +using bts.api.orderman; +using mbts.collections; +using mbts.ui; +using mbts.ui.controls; +using mbts.ui.shell; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using System.Windows.Controls; +using System.Windows.Data; +using static bts.shell.OrderBookWindowFactory; + +namespace mbts.spark { + partial class CVOrderBookVM : DisposableViewModelBase, IHandleRowSelection, IOrderBookVM { + // these come from -> ((ICollectionViewLiveShaping)rows_view).LiveSortingProperties + // each row accesses the public 'live_sorting_props' when it, or an ancestor order, is updated, + // copying the collection locally avoids constantly casting rows_view to ICollectionViewLiveShaping. + readonly ObservableCollection _live_sorting_props; + readonly Property _current_row; + + IReadOnlyDictionary _orders_cache = new Dictionary(); + Dictionary _order_vms_cache = new Dictionary(); + ObservableCollection _order_vms = new ObservableCollection(); + ObservableCollection _selected_rows = new ObservableCollection(); + SetMap _parent_to_children = new SetMap(); + SetMap _security_orders = new SetMap(); + + public CVOrderBookVM(IBus bus, OrdersModel model, OrderBookStartupData state) { + columns = new CVOrderBookColumnCollection(model, state); + rows_view = CollectionViewSource.GetDefaultView(_order_vms); + columns.filter_changed += rows_view.Refresh; + var cvls = (ICollectionViewLiveShaping)rows_view; + _live_sorting_props = cvls.LiveSortingProperties; + cvls.IsLiveFiltering = true; + cvls.IsLiveSorting = true; + cvls.LiveFilteringProperties.Add(nameof(CVOrderBookRowVM.is_visible)); + rows_view.Filter = obj => { + if (obj is CVOrderBookRowVM vm) { + if (!vm.is_visible) + return false; + if (vm.child_order_ids.Count > 0 && vm.is_expanded) { + foreach (var child_key in vm.child_order_ids) { + if (columns.filter(_order_vms_cache[child_key])) + return true; + } + } + return columns.filter(vm); + } + return false; + }; + _current_row = backing(nameof(current_row)); + if (state?.sort_criteria is List lsc && lsc.Count > 0) { + foreach (var sc in lsc) { + rows_view.SortDescriptions.Add(new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending)); + if (!_live_sorting_props.Contains(sc.col_name)) + _live_sorting_props.Add(sc.col_name); + } + } else { + rows_view.SortDescriptions.Add(new SortDescription(nameof(CVOrderBookRowVM.time_created), ListSortDirection.Descending)); + _live_sorting_props.Add(nameof(CVOrderBookRowVM.time_created)); + } + + SetMap missing_security_orders = new SetMap(); + IReadOnlyDictionary security_dict = new Dictionary(); + + _dispose = Disposable.Create( + bus.subscribe(SparkTags.SecuritiesTag).ObserveOnDispatcher().Subscribe(on_securities), + model.on_orders.ObserveOnDispatcher().Subscribe(on_orders), + columns); + + void on_orders(TableUpdate table) { + // check sum (seems like there is a bug in orders api, see repro steps below) + // 1) with an CVOrderBook open, enter a few 500+ lot iceberg order with < 20 show_quantity + // 2) wait until the orders are filled, or until fills inexplicably stop coming in + // 3) open another CVOrderBook, all the orders in the new book will have 'Status = inactive' + // 4) open the log file and scroll to the bottom to find a log-message that came from the code below + IEnumerable added, removed; + if (_orders_cache.Count != (table.state.Count + table.removed.Count - table.added.Count)) { + Logger.error(bts.log.Subsystem.Ui, $"CVOrderBook detected non-incremental changes in orders api, will delete all rows and (re)add everything in api state: " + + $"orderbook count before update({_orders_cache.Count}), update.state count({table.state.Count}), update.added count({table.added.Count}), update.removed count({table.removed.Count})."); + _order_vms.Clear(); + _parent_to_children.clear(); + added = table.state.Values; + removed = Enumerable.Empty(); + } else { + added = table.added; + removed = table.removed; + } + _orders_cache = table.state; + var changed_keys = new HashSet(); + foreach (var o in removed) { + // if state has it, then it wasn't actually removed, just changed + if (table.state.TryGetValue(o.Key, out OrderRecordImmutable changed_order)) { + changed_keys.Add(o.Key); + _order_vms_cache[o.Key].update_order(changed_order); + } else if (_order_vms_cache.TryPopValue(o.Key, out CVOrderBookRowVM vm)) { + _security_orders.remove(o.Def.SecurityKey, o.Key); + _order_vms.Remove(vm); + if (o.has_parent()) { + _parent_to_children.remove(o.ParentKey, o.Key); + get_order_vm(o.ParentKey)?.remove_child_order(o.Key); + } + if (_parent_to_children.try_pop(o.Key, out ISet children)) { + foreach (var k in children) + _order_vms_cache[k].on_parent_updated(); + } + missing_security_orders.remove(o.Key); + } + } + var orphans = new List(); + foreach (var o in added) { + if (changed_keys.Contains(o.Key)) + continue; + _security_orders.add(o.Def.SecurityKey, o.Key); + var vm = new CVOrderBookRowVM(bus, this, model, o, security_dict.TryGetValue(o.Def.SecurityKey, out SecurityMD smd) ? new SecurityImmutable?(smd.security) : null); + if (!vm.security.value.HasValue) + missing_security_orders.add(o.Def.SecurityKey, o.Key); + _order_vms_cache.Add(o.Key, vm); + if (_parent_to_children.try_lookup(o.Key, out ISet children)) + foreach (var k in children) { + // ** if children arrived in earlier update, this will notify them + // that their parent has arrived, and cause them to be properly sorted ** + vm.add_child_order(k); + } + if (o.has_parent()) { + _parent_to_children.add(o.ParentKey, o.Key); + if (_order_vms_cache.TryGetValue(o.ParentKey, out CVOrderBookRowVM pvm)) { + pvm.add_child_order(o.Key); + } else { + // look for orphans' parents again after all new orders have been added to _order_vm_cache + orphans.Add(vm); + continue; + } + } + _order_vms.Add(vm); + } + // ** add the orphans now, most likely their parent was added after them in the iteration + // if not, they will be notified when their parent arrives, and be properly sorted then. ** + foreach (var vm in orphans) { + get_order_vm(vm.parent_order_key.value)?.add_child_order(vm.order_key.value); + _order_vms.Add(vm); + } + order_received?.Invoke(this, new EventArgs()); + } + + // I assume we don't need to worry about orders "losing" or "changing" their security + // once the order vm discovers its security (by id), it will never change. + void on_securities(IReadOnlyDictionary securities) { + security_dict = securities; + foreach (var missing_sec_orders in missing_security_orders.ToList()) { + if (securities.TryGetValue(missing_sec_orders.Key, out SecurityMD smd)) { + missing_security_orders.remove(missing_sec_orders.Key); + foreach (var order_key in missing_sec_orders) { + var vm = _order_vms_cache[order_key]; + vm.update_security(smd.security); + } + } + } + } + } + + public event EventHandler selected_order_changed; + public event EventHandler order_received; + + public CVOrderBookColumnCollection columns { get; } + public IReadOnlyList live_sorting_props => _live_sorting_props; + public ICollectionView rows_view { get; } + // this is a misnomer, but i want to support both kinds of OrderBookVMs, and OrderBookView currently binds to 'visible_orders,' + public ICollectionView visible_orders => rows_view; + public CVOrderBookRowVM current_row { get => _current_row.Value; set => _current_row.Value = value ?? _selected_rows.FirstOrDefault(); } + public OrderRecordImmutable? current_order => current_row?.order; + + public IEnumerable active_order_keys => _active_order_records.Select(o => o.Key); + public IEnumerable active_buy_order_keys => _active_order_records.Where(o => o.Def.Side == Side.Buy).Select(o => o.Key); + public IEnumerable active_sell_order_keys => _active_order_records.Where(o => o.Def.Side == Side.Sell).Select(o => o.Key); + public IEnumerable selected_orders => _selected_rows.Select(r => r.order); + + IEnumerable _active_order_records => _order_vms.Where(x => x.order.is_active()).Select(x => x.order); + + public bool try_get_order(uint key, out OrderRecordImmutable order) => + _orders_cache.TryGetValue(key, out order); + + public CVOrderBookRowVM get_order_vm(uint key) => + _order_vms_cache.TryGetValue(key, out CVOrderBookRowVM vm) ? vm : null; + + // need to add sort_member_path to ICollectionView.LiveSortingProperties + // since child-orders' sort position must always follow their parent, + // if their parent is added after the child, the sort order must be updated. + public void on_sorting(DIYGridSortingEventArgs e) { + if (e.Column.SortDirection.HasValue) { + if (!_live_sorting_props.Contains(e.Column.sort_member_path)) + _live_sorting_props.Add(e.Column.sort_member_path); + } else { + _live_sorting_props.Remove(e.Column.sort_member_path); + } + } + + public void row_selection_changed(SelectionChangedEventArgs e) { + RowSelectionHelper.apply_changes(_selected_rows, e); + selected_order_changed?.Invoke(this, current_order); + } + + public List get_sorting_states() => rows_view.GetSortingCriteria(); + public FilterStates get_filter_states() => columns.get_filter_states(); + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookVM.cs b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookVM.cs index f066b4b95..61fc5ed05 100644 --- a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookVM.cs +++ b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookVM.cs @@ -22,7 +22,7 @@ using static mbts.spark.OrderBookView; using static mbts.ui.controls.DIYGrid; namespace mbts.spark { - partial class OrderBookVM : DisposableViewModelBase, IHandleRowSelection { + partial class OrderBookVM : DisposableViewModelBase, IHandleRowSelection, IOrderBookVM { readonly OrderBookWindowFactory _creator; readonly OrdersModel _model; ObservableCollection _selected_rows = new ObservableCollection(); @@ -221,8 +221,8 @@ namespace mbts.spark { } } - public void sort_grid(ColumnBase column) { - if (_get_comparer_for_column(column, out Comparer sorter)) { + public void on_sorting(DIYGridSortingEventArgs e) { + if (_get_comparer_for_column(e.Column, out Comparer sorter)) { SortedTree forest = new SortedTree( sorter , row_vm => row_vm.order.Key @@ -236,6 +236,10 @@ namespace mbts.spark { _orders.sync_with(forest); } } + // We ALWAYS want to set this here, else the grid tries to be helpful + // and sort with its own CollectionView, which destroys the SortedTree + // sort order; we want it to never use the CollectionView + e.Handled = true; } private bool _get_comparer_for_sort_description(SortDescription sc, out Comparer s) { @@ -434,6 +438,7 @@ namespace mbts.spark { public OrderBookRowVM current_row { get => _current_row.Value; set => _current_row.Value = value ?? _selected_rows.FirstOrDefault(); } public OrderRecordImmutable? current_order => current_row?.order; public ObservableCollection selected_rows => _selected_rows; + public IEnumerable selected_orders => _selected_rows.Select(r => r.order); #region Filters public IDataGridColumnPersistentFilter price_filter { get; } = new DoubleMinMax(r => r.price, nameof(OrderBookRowVM.price)); @@ -456,6 +461,7 @@ namespace mbts.spark { public IDataGridColumnPersistentFilter exchange_message_filter { get; } public IDataGridColumnPersistentFilter security_filter { get; } = new RegexFilterVM(r => r.security_text, nameof(OrderBookRowVM.security_text)); + public FilterStates get_filter_states() => new FilterStates { order_key_regex = order_key_filter.get_state(), diff --git a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml index a31f752e1..bb7f52295 100644 --- a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml +++ b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml @@ -53,24 +53,57 @@ + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + - - - - - - - - - - - + + \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml.cs b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml.cs index a409a64fd..1ad75b6c7 100644 --- a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml.cs +++ b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookView.xaml.cs @@ -1,34 +1,61 @@ +using bts.api.orderman; +using bts.shell; +using mbts.ui; using mbts.ui.controls; -using System.ComponentModel; +using System; +using System.Collections.Generic; using System.Windows.Controls; namespace mbts.spark { + interface IOrderBookVM : IDisposable { + event EventHandler selected_order_changed; + event EventHandler order_received; + // + OrderRecordImmutable? current_order { get; } + IEnumerable active_buy_order_keys { get; } + IEnumerable active_sell_order_keys { get; } + IEnumerable active_order_keys { get; } + IEnumerable selected_orders { get; } + // + void on_sorting(DIYGridSortingEventArgs e); + List get_sorting_states(); + OrderBookWindowFactory.FilterStates get_filter_states(); + } + internal partial class OrderBookView : UserControl { - public enum Columns { Security, Time, LastChange, User, Account, Exchange, TimeInForce, OrderType, SubType, Side, Size, Price, Filled, AvgFilled, LastPrice, Status, LastMessage, SecurityKey, OrderKey } + public enum Columns { Security, Time, LastChange, User, Account, Exchange, TimeInForce, OrderType, SubType, Side, Size, Price, Filled, AvgFilled, LastPrice, Status, LastMessage, SecurityKey, OrderKey, ParentKey } public const string SubTypeFilterTemplateKey = "SubTypeFilterTemplate", - ExpandCollapseToggleStyleKey = "ExpandCollapseToggleStyle"; + ExpandCollapseToggleStyleKey = "ExpandCollapseToggleStyle", + RowStyleKey = "RowStyle", + RowTemplateKey = "RowTemplateKey", + CVRowStyleKey = "CVRowStyle", + CVRowTemplateKey = "CVRowTemplateKey"; + + public static string ActiveRowStyleKey => + OrderBookWindow.cv_orderbook_enabled ? CVRowStyleKey : RowStyleKey; + + public static string ActiveRowTemplateKey => + OrderBookWindow.cv_orderbook_enabled ? CVRowTemplateKey : RowTemplateKey; + public const double RowHeight = 17; - OrderBookVM _vm; - //DataGridEx _grid; - public OrderBookView(OrderBookVM vm) { + IOrderBookVM _vm; + + public OrderBookView(IOrderBookVM vm) { InitializeComponent(); _vm = vm; DataContext = vm; } - public void data_grid_sorting(object sender, DIYGridSortingEventArgs args) { - args.Column.SortDirection = args.Column.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending; - _vm.sort_grid(args.Column); - - // We ALWAYS want to set this here, else the grid tries to be helpful - // and sort with its own CollectionView, which destroys the SortedTree - // sort order; we want it to never use the CollectionView - args.Handled = true; - } + void data_grid_sorting(object sender, DIYGridSortingEventArgs args) => + _vm.on_sorting(args); } class OrderBookRowView : DIYGrid.HighPerformanceRow { public OrderBookRowView() : base(OrderBookView.RowHeight) { } } + + class CVOrderBookRowView : DIYGrid.HighPerformanceRow { + public CVOrderBookRowView() : base(OrderBookView.RowHeight) { } + } } \ No newline at end of file diff --git a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookWindow.cs b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookWindow.cs index b05667103..11294aa1b 100644 --- a/src/client/spark/view/Spark/Shell/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/view/Spark/Shell/OrderBook/OrderBookWindow.cs @@ -11,11 +11,12 @@ using System.Windows.Media; namespace mbts.spark { internal class OrderBookWindow : SparkWindow, ISharedWindow { + public static readonly bool cv_orderbook_enabled = config.Configuration.get().enabled; const string _window_type = "OrderBook", ORDERBOOK_THREAD_ID = "OrderBook"; OrderBookWindowFactory.OrderBookStartupData _state; OrdersModel _model; - OrderBookVM _vm; + IOrderBookVM _vm; OrderBookView _view; OrderBookWindowFactory _factory; SparkCommand[] _commands; @@ -52,11 +53,13 @@ namespace mbts.spark { } public void thread_init() { - _vm = new OrderBookVM(_factory, base._bus, _model, _state); + _vm = cv_orderbook_enabled ? + (IOrderBookVM)new CVOrderBookVM(_bus, _model, _state) : + (IOrderBookVM)new OrderBookVM(_factory, base._bus, _model, _state); _view = new OrderBookView(_vm); _view.DataContext = _vm; - _show_fills_command = SparkCommands.ShowFills.complete(() => new FillsWindowFactory.StartupData(_vm.selected_rows.Select(r => r.order.Key).ToLArray())); + _show_fills_command = SparkCommands.ShowFills.complete(() => new FillsWindowFactory.StartupData(_vm.selected_orders.Select(r => r.Key).ToArray())); _modify_order_command = SparkCommands.ShowModifyOrder.complete( () => _vm.current_order.Value.Key, @@ -90,13 +93,8 @@ namespace mbts.spark { ); _cancel_selected_orders_command = SparkCommands.CancelSelectedOrders.complete( - () => _vm.selected_rows.Where(x => x.status == bts.api.orderman.OrderStatus.Working).Select(x => x.order.Key), - can_execute: () => { - if (_vm.selected_rows.Count > 0) { - return _vm.selected_rows.Any(x => x.status == bts.api.orderman.OrderStatus.Working); - } - return false; - } + () => _vm.selected_orders.Where(x => x.status() == OrderStatus.Working).Select(x => x.Key), + can_execute: () => _vm.selected_orders.Any(x => x.status() == OrderStatus.Working) ); _commands = new SparkCommand[] { diff --git a/src/lib/config/protos/toggles.proto b/src/lib/config/protos/toggles.proto index 3bb630b66..bd98954b6 100644 --- a/src/lib/config/protos/toggles.proto +++ b/src/lib/config/protos/toggles.proto @@ -10,4 +10,8 @@ package bts.config.toggles; message LaddersOnThreads { optional bool enabled = 1 [default = true]; +} + +message CVOrderBook { + optional bool enabled = 1 [default = true]; } \ No newline at end of file