diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index 1613660d5..6ac73aa18 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -1,77 +1,83 @@ -using bts.api; -using bts.api.orderman; -using bts.shell.orderbook; -using bts.utils; - -using mbts.persist; -using mbts.spark.utilities; -using mbts.ui; -using mbts.ui.shell; -using mbts.ui.spark; - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Input; -using System.Windows.Media; - +#nullable enable namespace mbts.spark { + using bts.api; + using bts.api.orderman; + using bts.shell.orderbook; + using bts.utils; + + using mbts.persist; + using mbts.ui; + using mbts.ui.shell; + using mbts.ui.spark; + + using Spark.Core; + + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.Immutable; + using System.Linq; + using System.Reactive.Linq; + using System.Threading.Tasks; + using System.Windows; + using System.Windows.Input; + using System.Windows.Media; + class LadderOrderVM : DisposableViewModelBase { - #region Colors - static readonly Color _colorbg = Colors.White, _darkbg = Color.FromRgb(0xbf, 0xbf, 0xbf); + static readonly Color _colorbg = Colors.White; + static readonly Color _darkbg = Color.FromRgb(0xbf, 0xbf, 0xbf); static readonly Brush _color_bg_brush = _colorbg.rgb_color().rgb_brush(); - static Brush mkbrush(Color color, Color endcolor, double pct_complete) { - GradientStopCollection stops = new GradientStopCollection(); - stops.Add(new GradientStop(color, 0.0)); - stops.Add(new GradientStop(color, pct_complete)); - stops.Add(new GradientStop(endcolor, pct_complete)); - stops.Add(new GradientStop(endcolor, 1.0)); - return new LinearGradientBrush(stops) { - StartPoint = new System.Windows.Point(0, 0.5), - EndPoint = new System.Windows.Point(1, 0.5) - }; - } - #endregion readonly LadderVM _owner; - readonly IBus _bus; + readonly double _real_price; readonly Property _font_family; readonly Property _font_weight; - readonly Property _font_size, _grid_row_height; - readonly Property _foreground, _background, _hoverbackground, _border; - readonly Property _has_multiple_orders_at_same_level, _is_hedge_order; + readonly Property _font_size; + readonly Property _grid_row_height; + readonly Property _foreground; + readonly Property _background; + readonly Property _hoverbackground; + readonly Property _border; + readonly Property _has_multiple_orders_at_same_level; + readonly Property _is_hedge_order; readonly Property _algo_type; readonly Property _algo_studio_abbreviation; - IObservable _bs; + readonly DelegateProperty> _text_lines; + readonly DeferrableActionWrapper _clear_phantom_price; + + ImmutableDictionary _orders = + ImmutableDictionary.Empty; LadderSettings.BadgeStyle _current_badge_style; - int _n_active_price_change_ops = 0; - double _real_price = double.NaN, _phantom_price = double.NaN; - uint filled, num_root_orders; - double quantity; - double working_quantity; - uint? _min_piq = UInt32.MaxValue; + double _phantom_price = double.NaN; + uint _filled; + uint _num_root_orders; + double _quantity; + uint? _min_piq = uint.MaxValue; - public event Action piq_changed; - - LadderModel model => _owner.model; - ImmutableDictionary _orders = ImmutableDictionary.Empty; - - public LadderOrderVM(ImmutableDictionary orders, double real_price, LadderVM owner, IBus bus, IObservable bs) { + public LadderOrderVM( + ImmutableDictionary orders, + double real_price, + LadderVM owner, + IObservable badge_style + ) { _owner = owner; - _bus = bus; - _bs = bs; + _orders = orders; _real_price = real_price; - // settings - var fs = UserSettings.factory_defaults.ladder; - _font_family = backing(nameof(font_family), owner.settings, get_font_family, get_font_family(fs)); - _font_weight = backing(nameof(font_weight), owner.settings, get_font_weight, get_font_weight(fs)); - _font_size = backing(nameof(font_size), owner.settings, get_font_size, get_font_size(fs)); - _foreground = backing(nameof(foreground), owner.settings, get_foreground, get_foreground(fs)); - _grid_row_height = backing(nameof(grid_row_height), owner.settings, get_row_height, get_row_height(fs)); + _text_lines = backing(nameof(text_lines), () => { + var fmt = MDDisplayHelper.get_value_formatter(_owner.display_quantity_divisor); + return BadgeRender.format(side, _quantity, _filled, _current_badge_style, fmt); + }); + _clear_phantom_price = new(() => { + _phantom_price = double.NaN; + RaisePropertyChanged(nameof(price)); + }); + + var fds = UserSettings.factory_defaults.ladder; + _font_family = backing(nameof(font_family), owner.settings, get_font_family, get_font_family(fds)); + _font_weight = backing(nameof(font_weight), owner.settings, get_font_weight, get_font_weight(fds)); + _font_size = backing(nameof(font_size), owner.settings, get_font_size, get_font_size(fds)); + _foreground = backing(nameof(foreground), owner.settings, get_foreground, get_foreground(fds)); + _grid_row_height = backing(nameof(grid_row_height), owner.settings, get_row_height, get_row_height(fds)); _background = backing(nameof(background), _color_bg_brush); _hoverbackground = backing(nameof(hoverbackground), _color_bg_brush); _border = backing(nameof(border), _color_bg_brush); @@ -79,103 +85,22 @@ namespace mbts.spark { _is_hedge_order = backing(nameof(is_hedge_order), false); _algo_type = backing(nameof(algo_type), CustomOrderDefinition.CustomOneofCase.None); _algo_studio_abbreviation = backing(nameof(algo_studio_abbreviation), string.Empty); - FontFamily get_font_family(LadderSettings s) => new FontFamily(s.orders_column.font_family); - FontWeight get_font_weight(LadderSettings s) => ui.utility.text.TextUtils.from_open_type_weight_safe(s.orders_column.font_weight); + + _dispose = Disposable.Create( + badge_style.OnDispatcher().Subscribe(badge => { + _current_badge_style = badge; + _text_lines.refresh(); + })); + + FontFamily get_font_family(LadderSettings s) => new(s.orders_column.font_family); + FontWeight get_font_weight(LadderSettings s) => + ui.utility.text.TextUtils.from_open_type_weight_safe(s.orders_column.font_weight); double get_font_size(LadderSettings s) => s.orders_column.font_size; Brush get_foreground(LadderSettings s) => s.orders_column.foreground.rgb_brush(); double get_row_height(LadderSettings s) => s.row_height; - _orders = orders; - - _dispose = Disposable.Create( - _bs.Subscribe(badge => { - _current_badge_style = badge; - _set_badge_text(); - }) - ); } - public void update() { - var color = side switch { - Side.Buy => BTSColors.MarketData.bid_alt, - Side.Sell => BTSColors.MarketData.ask_alt, - _ => BTSColors.MarketData.bid_ask_alt_blend, - }; - var (r, g, b) = color.darken2(0.75); - var dark = Color.FromRgb(r, g, b); - var buy_sell_background_fill_color = color.to_brush().frozen(); - background = buy_sell_background_fill_color; - hoverbackground = mkbrush(dark, _darkbg, 0); - - num_root_orders = 0; - filled = 0; - working_quantity = 0; - quantity = 0; - foreach (var n in _root_nodes()) { - num_root_orders++; - filled += n.filled(); - working_quantity += n.working_quantity(); - quantity += n.quantity(); - } - - // if this badge only represents a single order, then is_exchange_order and the border (= algo color) - // should be set appropriately - if (num_root_orders == 1) { - var single_order = _root_nodes().First(); - var single_order_metadata = _owner.model.order_gateway.factory.get_metadata(single_order); - border = single_order_metadata.Color.rgb_brush(); - if (_orders.TryGetValue(single_order.Key, out var opm)) { - algo_studio_abbreviation = _sanitize_abbreviation(string.IsNullOrEmpty(opm.meta?.abbreviation) ? _generate_abbreviation_for_algo_studio_algo(opm.algo) : opm.meta?.abbreviation); - border = opm.meta?.badge_color?.rgb_color().rgb_brush() ?? border; - } - if (single_order.order_type().is_bts_algo_type()) { - algo_type = single_order.order_type(); - } else { - algo_type = CustomOrderDefinition.CustomOneofCase.None; - } - - } else { - border = new SolidColorBrush(color); - } - has_multiple_orders_at_same_level = num_root_orders > 1; - is_hedge_order = _root_nodes().Any(o => o.sub_type() == OrderSubType.HedgingLeg); - - _set_badge_text(); - - string _generate_abbreviation_for_algo_studio_algo(AlgoData? a) { - char[] delim = { ' ' }; - string candidate = string.Empty; - if (a.HasValue) { - var algo_name = a.Value.name; - var words = algo_name.Split(delim, StringSplitOptions.RemoveEmptyEntries); - if (words.Length == 1) { - var single_word = words[0]; - if (single_word.Length > 1) { - candidate = words[0]; - } else { - candidate = single_word; - } - } else { - candidate = string.Join(string.Empty, words.Take(2).Select(w => w.Substring(0, 1))); - } - } - return candidate.ToUpper(); - } - - string _sanitize_abbreviation(string ab) { - string candidate = ab; - if (ab.Length > 2) { - candidate = candidate.Substring(0, 2); - } - return candidate.ToUpper(); - } - - } - - private void _set_badge_text() { - var fmt = MDDisplayHelper.get_value_formatter(_owner.display_quantity_divisor); - text_lines = BadgeRender.format(side, quantity, filled, _current_badge_style, fmt); - RaisePropertyChanged(nameof(text_lines)); - } + public event Action? piq_changed; public uint security_key => _owner.security.Id; public double price { get => double.IsNaN(_phantom_price) ? _real_price : _phantom_price; } @@ -192,7 +117,7 @@ namespace mbts.spark { public double real_price => _real_price; public Side side { get { - var distinct_sides = _root_nodes().Select(o => o.side()).Distinct(); + var distinct_sides = _root_nodes.Select(o => o.side()).Distinct(); if (distinct_sides.Count() > 1) { return Side.Undefined; } @@ -200,93 +125,148 @@ namespace mbts.spark { } } - IEnumerable _root_nodes() => _orders.Values.Select(_owner.get_root_at_price).DistinctOn(OrderUtils.RecordKeySelector); + public IReadOnlyList text_lines => _text_lines.Value; - public IReadOnlyList text_lines { get; private set; } - - public bool has_phantom_price => !double.IsNaN(_phantom_price); - - public ICommand cancel_command => new DelegateCommand(() => _execute_command(_cancel_order)); - - public event Action command_executed; - void _execute_command(Action action) { - action(); - command_executed?.Invoke(); - } + public bool has_phantom_price => !_phantom_price.is_nan(); public FontFamily font_family => _font_family.Value; public FontWeight font_weight => _font_weight.Value; public double font_size => _font_size.Value; public double grid_row_height => _grid_row_height.Value; public Brush foreground => _foreground.Value; - public Brush background { get => _background.Value; private set => _background.Value = value; } - public Brush hoverbackground { get => _hoverbackground.Value; private set => _hoverbackground.Value = value; } - public Brush border { get => _border.Value; private set => _border.Value = value; } - public string summary => _root_nodes().Any() ? $"Badge containing root orders: {string.Join(",", _root_nodes().Select(o => o.Key))}" : string.Empty; - public bool has_multiple_orders_at_same_level { get => _has_multiple_orders_at_same_level.Value; private set => _has_multiple_orders_at_same_level.Value = value; } - public bool is_hedge_order { get => _is_hedge_order.Value; private set => _is_hedge_order.Value = value; } - public CustomOrderDefinition.CustomOneofCase algo_type { get => _algo_type.Value; private set => _algo_type.Value = value; } - public string algo_studio_abbreviation { get => _algo_studio_abbreviation.Value; private set => _algo_studio_abbreviation.Value = value; } - public IEnumerable root_orders => _root_nodes(); + public Brush background { + get => _background.Value; + private set => _background.Value = value; + } + + public Brush hoverbackground { + get => _hoverbackground.Value; + private set => _hoverbackground.Value = value; + } + + public Brush border { + get => _border.Value; + private set => _border.Value = value; + } + + public string summary => + _root_nodes.Any() ? + $"Badge containing root orders: {",".join(_root_nodes.Select(o => o.Key))}" : + string.Empty; + + public bool has_multiple_orders_at_same_level { + get => _has_multiple_orders_at_same_level.Value; + private set => _has_multiple_orders_at_same_level.Value = value; + } + + public bool is_hedge_order { + get => _is_hedge_order.Value; + private set => _is_hedge_order.Value = value; + } + + public CustomOrderDefinition.CustomOneofCase algo_type { + get => _algo_type.Value; + private set => _algo_type.Value = value; + } + + public string algo_studio_abbreviation { + get => _algo_studio_abbreviation.Value; + private set => _algo_studio_abbreviation.Value = value; + } + + public IEnumerable root_orders => _root_nodes; + + public ICommand cancel_cmd => new Command(_cancel); + + IEnumerable _root_nodes => + _orders.Values.Select(_owner.get_root_at_price).DistinctOn(OrderUtils.RecordKeySelector); + + LadderModel _model => _owner.model; 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(); } - void _cancel_order() { - foreach (var order in _root_nodes()) { - model.order_gateway.cancel_order(order).ignore(); - } - } - - // on Stop/Limit order updates - // When not triggered, allow for modification to StopPrice - // else treat modification as normal (Price) public async void try_set_price(OrderRecordImmutable order, double new_price) { - if (order.working_quantity() <= 0) return; + if (order.working_quantity() <= 0) { + return; + } + _phantom_price = new_price; RaisePropertyChanged(nameof(price)); - ++_n_active_price_change_ops; - if (await _owner.model.order_gateway.update_order(order, new_price, order.State.Quantity, null)) { - // wait 3 secs, then give up if price change still hasn't taken effect + using var _ = _clear_phantom_price.defer_execution(true); + + if (await _owner.model.order_gateway.update_order( + order, new_price, order.State.Quantity, null)) { + // wait 3 secs before clearing the phantom price await Task.Delay(3000); } - // only update when the last price change op is finished - if (--_n_active_price_change_ops == 0) { - _phantom_price = double.NaN; - RaisePropertyChanged(nameof(price)); - } } - public OrderBookVM create_orderbook_vm() { - // We are returning a new OrderBookVM each time b/c after - // successive launches of the mini-ob from the same badge, we get an exception - // System.InvalidOperationException: Sharing GridViewColumn among multiple GridViewColumnCollections or adding the same GridViewColumn into one GridViewColumnCollection more than once is not allowed. - // I checked with Eric and he guesses that what is happening is that the Popup is throwing away the grid, but the binding doesn't remove the columns from that grid - // - // I think returning a new OrderbookVM is okay at the moment since this Popup window will not be saving any state at this time + public void update() { + var color = side switch { + Side.Buy => BTSColors.MarketData.bid_alt, + Side.Sell => BTSColors.MarketData.ask_alt, + _ => BTSColors.MarketData.bid_ask_alt_blend, + }; + var (r, g, b) = color.darken2(0.75); + var dark = Color.FromRgb(r, g, b); + var buy_sell_background_fill_color = color.to_brush().frozen(); + background = buy_sell_background_fill_color; + hoverbackground = _mk_hover_bg_brush(dark, _darkbg, 0); + + (_num_root_orders, _filled, _quantity) = _root_nodes + .Select(n => (1u, n.filled(), n.quantity())) + .Sum(); + + if (_num_root_orders == 1) { + var order = _root_nodes.First(); + border = _owner.model.order_gateway.factory.get_metadata(order).Color.rgb_brush(); + if (_orders.TryGetValue(order.Key, out var opm)) { + algo_studio_abbreviation = (opm.meta?.abbreviation).is_null_or_empty() ? + _abbreviate_algo(opm.algo) : opm.meta?.abbreviation ?? string.Empty; + border = opm.meta?.badge_color?.rgb_color().rgb_brush() ?? border; + } + algo_type = order.order_type().is_bts_algo_type() ? + order.order_type() : CustomOrderDefinition.CustomOneofCase.None; + } else { + border = new SolidColorBrush(color); + } + has_multiple_orders_at_same_level = _num_root_orders > 1; + is_hedge_order = _root_nodes.Any(o => o.sub_type() == OrderSubType.HedgingLeg); + _text_lines.refresh(); + } + + public OrderBookVM? create_orderbook_vm() { var ticks = _owner.spec.full_ticks_from_zero(real_price); if (!ticks.HasValue) { - // this is an unexpected code path, but not necessarily a reason to crash, so log a warning and return null return null; } var min_price = _owner.spec.tickup(0, ticks.Value); var max_price = _owner.spec.tickup(min_price, 1); - var state = new bts.shell.orderbook.OrderBookStartupData( - new bts.shell.orderbook.FilterStates { + + var state = new OrderBookStartupData( + new FilterStates { security_criteria = SecurityCriteria.from_securities(_owner.security), statuses = new[] { OrderStatus.Working }, order_types = AlgoID.exchange_algo_keys }, - bts.shell.orderbook.OrderBookStartupData.default_mini_grid.with(_owner.current_settings.mini_ob.value), - use_defaults: false - ); - var settings_man = new WindowSettingsManager.DisconnectedImpl(state.orderbook_grid); - var obvm = new OrderBookVM(_owner.bus, null, _owner.model.order_gateway, settings_man, true, - global_filter: o => o.order.order.ui_price() >= min_price - MathUtils.EPSILON && o.order.order.ui_price() <= max_price - MathUtils.EPSILON); - _owner.settings.Subscribe(s => settings_man.instance_settings = settings_man.instance_settings.with(s.mini_ob.value)); + OrderBookStartupData.default_mini_grid.with(_owner.current_settings.mini_ob.value), + use_defaults: false); + var settings_man = new WindowSettingsManager.DisconnectedImpl( + state.orderbook_grid); + var obvm = new OrderBookVM( + _owner.bus, + null, + _owner.model.order_gateway, + settings_man, + true, + global_filter: order_price_filter); + + _owner.settings.Subscribe(s => + settings_man.instance_settings = settings_man.instance_settings.with(s.mini_ob.value)); obvm.columns.Insert(0, new OrderBookVM.AttachDetachColumn(typeof(MiniOrderBookView))); obvm.columns.Insert(0, new OrderBookVM.CommitColumn()); obvm.columns.Insert(0, new OrderBookVM.EditablePriceColumn()); @@ -294,15 +274,61 @@ namespace mbts.spark { obvm.columns.Insert(0, new OrderBookVM.UpdateColumn(typeof(MiniOrderBookView))); obvm.columns.Insert(0, new OrderBookVM.CancelColumn(nameof(OrderBookRowVM.cancel_command))); // the CheckColumn must be inserted at the front of the ObservableAppendCollection, - // and not mixed with the other columns in said ObservableAppendCollection's underlying ObservableCollection (the settings dialog uses the underlying collection). - // The user cannot adjust this column in the settings dialog, and it should always be the left-most column. + // and not mixed with the other columns in said ObservableAppendCollection's underlying + // ObservableCollection (the settings dialog uses the underlying collection). + // The user cannot adjust this column in the settings dialog, and it should always be the + // left-most column. obvm.columns.insert_front(new OrderBookVM.CheckColumn(nameof(OrderBookRowVM.is_selected))); obvm.load_from(state); return obvm; + + bool order_price_filter(OrderSecurityRootPair o) => + o.order.order.ui_price().is_within_range( + min_price - MathUtils.EPSILON, max_price + MathUtils.EPSILON); } - public override string ToString() { - return $"Price: {price} Order Count: {_orders.Values.Count()} Root Order Count: {_root_nodes().Count()} PIQ: {(this.min_piq.HasValue ? this.min_piq.Value.ToString() : "")}"; + public override string ToString() => + $"Price: {price} " + + $"Order Count: {_orders.Values.Count()} " + + $"Root Order Count: {_root_nodes.Count()} " + + $"PIQ: {min_piq?.ToString()}"; + + static string _abbreviate_algo(AlgoData? a) => + a.HasValue ? + _abbreviate_algo(a.Value.name.Split(' ', StringSplitOptions.RemoveEmptyEntries)) : + string.Empty; + + static string _abbreviate_algo(IEnumerable words) { + return new(impl().Select(c => c.upper()).Take(2).ToArray()); + + IEnumerable impl() { + using var en = words.GetEnumerator(); + if (!en.MoveNext()) { + return string.Empty; + } + // if it's only one word, just return the whole word, otherwise return the initials + if (!en.MoveNext()) { + return en.Current; + } + return string.Empty.join(words.Select(w => w[..1])); + } + } + + static Brush _mk_hover_bg_brush(Color color, Color endcolor, double pct_complete) => + new LinearGradientBrush(new() { + new(color, 0.0), + new(color, pct_complete), + new(endcolor, pct_complete), + new(endcolor, 1.0) + }) { + StartPoint = new(0, 0.5), + EndPoint = new(1, 0.5) + }; + + void _cancel() { + foreach (var order in _root_nodes) { + _model.order_gateway.cancel_order(order).ignore(); + } } } } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml index 987638614..a864e2ae2 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml @@ -1,809 +1,809 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.5 - 0.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Auto Clear - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1.5 + 0.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Auto Clear + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark_core/utils/CharExtensions.cs b/src/client/spark_core/utils/CharExtensions.cs new file mode 100644 index 000000000..43f058783 --- /dev/null +++ b/src/client/spark_core/utils/CharExtensions.cs @@ -0,0 +1,9 @@ +namespace Spark.Core { + public static class CharExtensions { + public static char upper(this char c) => + char.ToUpper(c); + + public static char lower(this char c) => + char.ToLower(c); + } +}