diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index f847433eb..6865d87d3 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -334,6 +334,7 @@ namespace mbts.spark { // this class is 100% mutable (there are literally 0 readonly members), // so GetHashCode must return the same hash for every instance. static readonly int _type_hash = typeof(LadderSettings).GetHashCode(); + uint _ticks_per_row; // Default proto constructor // Added this so that when clients upgrade to a version with new settings, @@ -603,6 +604,12 @@ namespace mbts.spark { [ProtoMember(61), DefaultValue(true)] public bool status_message_visible { get; set; } + [ProtoMember(62)] + public uint ticks_per_row { + get => Math.Max(_ticks_per_row, 1); + set => _ticks_per_row = value; + } + [ProtoMember(900)] public LadderOrderLimits ladder_order_limits { get; set; } @@ -712,7 +719,8 @@ namespace mbts.spark { a.max_clip == b.max_clip && a.price_display_format == b.price_display_format && a.status_message_visible == b.status_message_visible && - a.ladder_order_limits.safe_equals(b.ladder_order_limits); + a.ladder_order_limits.safe_equals(b.ladder_order_limits) && + a._ticks_per_row == b._ticks_per_row; public bool Equals(LadderSettings other) => profile_equals(this, other) && diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs index c41da7846..05473c334 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs @@ -1,13 +1,16 @@ 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; @@ -52,9 +55,9 @@ namespace mbts.spark { public event Action piq_changed; LadderModel model => _owner.model; - Dictionary _orders = new Dictionary(); + ImmutableDictionary _orders = ImmutableDictionary.Empty; - public LadderOrderVM((OrderRecordImmutable, uint?, AlgoData?, AlgoDefinitionMetadata?) op, double real_price, LadderVM owner, IBus bus, IObservable bs) { + public LadderOrderVM(ImmutableDictionary orders, double real_price, LadderVM owner, IBus bus, IObservable bs) { _owner = owner; _bus = bus; _bs = bs; @@ -78,8 +81,7 @@ namespace mbts.spark { 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; - // - add_order(op); + _orders = orders; _dispose = Disposable.Create( _bs.Subscribe(badge => { @@ -175,41 +177,6 @@ namespace mbts.spark { RaisePropertyChanged(nameof(text_lines)); } - /// - /// Add Order performs an add the first time it's called via the constructor. When it's called, directly - /// it really serves as an update/replace. Also note that since the min_piq is a separate piece of state representing - /// the lowest piq of the orders the badge represents, we must reevaluate if that has changed on said update. - /// - public void add_order((OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta) new_op) { - _orders[new_op.order.Key] = new_op; - // reevaluate min piq if this order's piq is less - if (new_op.p.HasValue) { - // if this lovm only represents 1 order and the piq is now different, regardless of what it is that's our piq - if (_orders.Count == 1 && new_op.p.Value != min_piq) { - min_piq = new_op.p.Value; - } else if (new_op.p.Value < min_piq) { - min_piq = new_op.p.Value; - } - } - } - - public void remove_order(uint order_key) { - _orders.Remove(order_key); - // on a remove, potentially the order w/ the lowest piq has been removed, so - // if the min() is now > than the current min_piq, update the min_piq - var prospective_piq = _orders.Select(op => op.Value.p).Where(piq => piq.HasValue).Min(); - if (prospective_piq > min_piq) { - min_piq = prospective_piq; - } - } - - //public void update(OrderRecordImmutable neworder) { - // Log.assert(neworder.Key == id, $"OrderVM.update was called with an order with a different Key({neworder.Key}) from original({id})"); - // using (detect_property_changes()) { - // _init(neworder); - // } - //} - public uint security_key => _owner.security.Id; public double price { get => double.IsNaN(_phantom_price) ? _real_price : _phantom_price; } public uint? min_piq { @@ -261,9 +228,13 @@ namespace mbts.spark { 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 IReadOnlyList order_keys => _orders.Keys.ToReadOnlyList(); public IEnumerable root_orders => _root_nodes(); + 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(); @@ -296,14 +267,13 @@ namespace mbts.spark { // 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 - var price_filter = new filters.DoubleMinMaxState(); - price_filter.minimum.value = real_price; - price_filter.maximum.value = real_price; + var ticks = _owner.spec.full_ticks_from_zero(real_price); + var min_price = _owner.spec.tickup(0, ticks); + var max_price = _owner.spec.tickup(min_price, 1); var state = new bts.shell.orderbook.OrderBookStartupData( new bts.shell.orderbook.FilterStates { security_criteria = new SecurityCriteria(_owner.security), - price = price_filter, statuses = new[] { OrderStatus.Working }, order_types = AlgoID.exchange_algo_keys }, @@ -311,7 +281,8 @@ namespace mbts.spark { 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); + 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)); obvm.columns.Insert(0, new OrderBookVM.AttachDetachColumn(typeof(MiniOrderBookView))); obvm.columns.Insert(0, new OrderBookVM.CommitColumn()); diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index fc9db73b6..c41fb8936 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -4,6 +4,7 @@ using bts.api.orderman; using bts.collections; using bts.persist.algo; using bts.proto; +using bts.shell.ladder; using bts.shell.orderbook; using bts.utils; using mbts.collections; @@ -40,6 +41,7 @@ namespace mbts.spark { readonly ObservableKeyedCollection _accounts = new ObservableKeyedCollection(AccountTuple.nullable_key_fn); readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); readonly OrdersModel _model; + readonly SecurityImmutable _security; uint? _desired_account; AlgoID? _desired_algo; TimeInForce _default_time_in_force; @@ -48,6 +50,7 @@ namespace mbts.spark { double _order_entry_panel_width, _zoom_factor; bool _auto_clear, _show_warn_on_cross, _enforce_max_clip, _enforce_max_settlement_cross_ticks; int _max_settlement_cross_ticks; + uint _ticks_per_row; LadderSettings _current; LadderColumnSettingsVM _orders = new OrdersColumnSettingsVM(), @@ -88,7 +91,7 @@ namespace mbts.spark { public LadderSettingsVM(OrdersModel model, SecurityImmutable security) { _model = model; - is_synthetic = security.ContractCase == Security.ContractOneofCase.Synthetic; + _security = security; favorite_algos_vm = new FavoriteAlgosVM(_algo_definitions); size_presets = new ObservableEditableCollection>(_create_size_preset_vm); size_presets.CollectionChanged += (s, e) => RaisePropertyChanged(nameof(size_presets_text)); @@ -110,6 +113,9 @@ namespace mbts.spark { accounts_view = new ListCollectionView(_accounts) { CustomSort = Comparer.Default.to_nullable().to_non_generic() }; + // cmds + tick_up_ticks_per_row_cmd = new DelegateCommand(increment_ticks_per_row); + tick_down_ticks_per_row_cmd = new DelegateCommand(decrement_ticks_per_row); // update _update = new DeferrableActionWrapper(() => result_changed?.Invoke()); mini_ob.result_changed += _update.execute; @@ -155,6 +161,26 @@ namespace mbts.spark { } AccountTuple? account_factory(uint key, string name) => new AccountTuple(key, name); AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data); + void increment_ticks_per_row() { + var tpr = ticks_per_row; + for (uint i = 1; i < 100; i++) { + var new_tpr = LadderUtils.fit_ticks_per_row_to_dollars(security.ContractSpec, ticks_per_row + i); + if (new_tpr != tpr) { + ticks_per_row = new_tpr; + break; + } + } + } + void decrement_ticks_per_row() { + var tpr = ticks_per_row; + for (uint i = 1; i < tpr; i++) { + var new_tpr = LadderUtils.fit_ticks_per_row_to_dollars(security.ContractSpec, tpr - i); + if (new_tpr != tpr) { + ticks_per_row = new_tpr; + break; + } + } + } } public event Action result_changed; @@ -177,6 +203,16 @@ namespace mbts.spark { get => _alternate_order_size.Value; set => _alternate_order_size.Value = value; } + public uint ticks_per_row { + get => _ticks_per_row; + set => Set(ref _ticks_per_row, value, dependent_props: nameof(rounded_ticks_per_row)); + } + public ICommand tick_up_ticks_per_row_cmd { get; } + public ICommand tick_down_ticks_per_row_cmd { get; } + // since settings profiles may be shared among ladders + // of different securities/tick sizes, the ticks per row setting + // may need to be rounded to a number that is a factor of $1.00 + public uint? rounded_ticks_per_row => LadderUtils.fit_ticks_per_row_to_dollars(_security.ContractSpec, ticks_per_row); public MarketSizeDisplayVM size_display { get; } = new MarketSizeDisplayVM(); public SimpleGridSettingsVM mini_ob { get; } = new SimpleGridSettingsVM(OrderBookGridSettingsManager.hard_column_flags); @@ -209,7 +245,7 @@ namespace mbts.spark { public FavoriteAlgosVM favorite_algos_vm { get; } public double row_height => _row_height.Value; - public bool is_synthetic { get; } + public bool is_synthetic => _security.ContractCase == Security.ContractOneofCase.Synthetic; public IEnumerable column_items { get { @@ -326,6 +362,7 @@ namespace mbts.spark { _current = settings; badge_style = settings.badge_style; alternate_order_size = settings.alternate_order_size; + ticks_per_row = settings.ticks_per_row; favorite_algos_vm.load_from(settings.favorite_algos); size_display.load_from(settings.size_display); size_presets.SetItems(settings.calculator_buttons.empty_if_null().Select(s => _create_size_preset_vm((uint)s))); @@ -407,6 +444,7 @@ namespace mbts.spark { } clone.badge_style = badge_style; clone.alternate_order_size = alternate_order_size; + clone.ticks_per_row = ticks_per_row; clone.favorite_algos = favorite_algos_vm.create(); clone.size_display = size_display.create(); clone.calculator_buttons = size_presets.Select(vm => (int)vm.value).ToArray(); diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 9268f6137..2a34d9a41 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -1,14 +1,16 @@ using bts.api; +using bts.api.core; using bts.api.orderman; using bts.proto; using bts.shell; +using bts.shell.ladder; using bts.spark; using bts.utils; using mbts.co2; using mbts.spark.utilities; using mbts.ui; using mbts.ui.shell; -using mbts.ui.spark; +using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; @@ -28,7 +30,6 @@ namespace mbts.spark { readonly IBus _bus; readonly LadderModel _model; readonly Property _high, _low, _change, _open, _settlement, _left_panel_width, _zoom_factor; - //readonly Property _window_width, _window_height; readonly Property _orders_column_width, _bid_column_width, _price_column_width, _ask_column_width, _last_column_width, _volume_column_width, _piq_column_width; readonly Property _volume; readonly Property _auto_clear; @@ -49,8 +50,10 @@ namespace mbts.spark { ulong _last_trade_time = 0; IEqualityComparer _equality; Dictionary _slot_price_vs_orders; + ImmutableSortedDictionary _order_price_index; IReadOnlyDictionary _cache = DictionaryHelper.empty(); ImmutableDictionary _favorite_algo_map = ImmutableDictionary.Empty; + ContractSpecificationImmutable? _spec; public static LadderVM create(IBus bus, LadderModel model, LadderSettings init, IObservable settings) => new LadderVM(bus, model, init, settings, new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), settings.Select(s => new InlineOrderProperties(model.order_gateway, s)))); @@ -65,6 +68,7 @@ namespace mbts.spark { _bus = bus; _model = model; current_settings = init; + _order_price_index = ImmutableSortedDictionary.Create(spec.price_comparer()); this.settings = settings; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); display_quantity_divisor = model.order_gateway.security_auxiliary_model.get_display_quantity_divisor(model.security); @@ -122,6 +126,8 @@ namespace mbts.spark { (_show_zoom = bool_prop(nameof(show_zoom), s => s.zoom_slider_visible)).set, (_show_status_message = bool_prop(nameof(show_status_message), s => s.status_message_visible)).set, s => { + // invalidate spec in case 'ticks per row' changed + _spec = null; if ( Set(ref _show_account_position, s.account_position_visible, nameof(show_account_position)) | Set(ref _show_day_position, s.day_position_visible, nameof(show_day_position)) | @@ -159,71 +165,43 @@ namespace mbts.spark { settings_command = new DelegateCommand(() => request_settings_dialog?.Invoke()); orders = new ObservableCollection(); + var orders_source = settings.Select(s => s.ticks_per_row).DistinctUntilChanged() + .SelectManyInSeries(tpr => { + var spec = LadderUtils.multiply_tick_size(security.ContractSpec, tpr); + var price_comp = Comparer.Create((a, b) => { + var aticks = spec.full_ticks_from_zero(a); + var bticks = spec.full_ticks_from_zero(b); + return aticks.CompareTo(bticks); + }); + return _order_price_source(model.orders, price_comp, p => LadderUtils.normalize_price(spec, p)); + }); _dispose = Disposable.Create( settings.OnDispatcher().Subscribe(settings_observer), get_order_properties_editor_hooks(), bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update), - // we need to hook this up to model.orders which is filtered for just the security - model.orders.OnDispatcher().Subscribe(working => { + orders_source.OnDispatcher().Subscribe(tup => { // Here we manage N orders to 1 price slot in the ladder Dictionary> orders_used_in_this_update = new Dictionary>(_equality); - _cache = working.state; - - foreach (var os in _cache.Values) { - var wo = os.order; - var slot_price_target = wo.ui_price(); - var order_type = wo.order_type(); - var filled = wo.filled(); - - if (_slot_price_vs_orders.TryGetValue(slot_price_target, out LadderOrderVM slot_vm)) { - slot_vm.add_order((wo, os.piq, os.algo, os.meta)); - } else { - slot_vm = new LadderOrderVM((wo, os.piq, os.algo, os.meta), slot_price_target, this, _bus, settings.Select(s => s.badge_style).OnDispatcher()); - _slot_price_vs_orders[slot_price_target] = slot_vm; - } - - // keep track of slot prices vs orders; we use this below to remove orders from the LadderOrderVMs - // that are not found in this callback run - if (!orders_used_in_this_update.TryGetValue(slot_price_target, out HashSet orders_at_level)) { - orders_at_level = new HashSet(); - } - orders_at_level.Add(wo.Key); - orders_used_in_this_update[slot_price_target] = orders_at_level; - + _cache = tup.map; + /// remove empty price slots (the vm will be disposed automatically when it is removed from ) + var removed_prices = _slot_price_vs_orders.Keys.Except(tup.price_index.Keys).ToList(); + foreach (var p in removed_prices) + _slot_price_vs_orders.Remove(p); + // add or update current price slots + foreach (var kv in tup.price_index) { + _slot_price_vs_orders.AddOrUpdate(kv.Key, + order_vm => order_vm.sync_orders(kv.Value), + () => new LadderOrderVM(kv.Value, kv.Key, this, _bus, settings.Select(s => s.badge_style).OnDispatcher())); } - - // remove any orders from the lovm that aren't in here - foreach(var kvp in orders_used_in_this_update) { - var slot_vm = _slot_price_vs_orders[kvp.Key]; - foreach(var existing_order_key in slot_vm.order_keys) { - if (!kvp.Value.Contains(existing_order_key)) { - slot_vm.remove_order(existing_order_key); - } - } - } - - - // update dirty brushes and text - foreach (var lovm in _slot_price_vs_orders.Values) { - lovm.update(); - } - - // complete removal of slots that were not updated - // orders_used_in_this_update.Keys are the price levels in the update - foreach (var slot_price in _slot_price_vs_orders.Keys.ToList()) { - if (!orders_used_in_this_update.Keys.Contains(slot_price)) { - _slot_price_vs_orders.TryGetValue(slot_price, out LadderOrderVM removal_candidate); - if (removal_candidate != null) { - removal_candidate.Dispose(); - } - _slot_price_vs_orders.Remove(slot_price); - } - } - + // sync the collection orders.sync_with(_slot_price_vs_orders.Values); + // update badge colors, text, etc. + foreach (var lovm in orders) + lovm.update(); }), WorkLoop.Start($"Ladder '{security}'", _tick), + ObservableAutoWrapper.dispose_on_removed(orders, true), Disposable.Create(() => _on_disposed_impl?.Invoke(true)) ); IDisposable get_order_properties_editor_hooks() { @@ -299,6 +277,8 @@ namespace mbts.spark { remove => _on_disposed_impl -= value; } public SecurityImmutable security => _model.security; + public ContractSpecificationImmutable spec => _spec ?? ( + _spec = LadderUtils.multiply_tick_size(security.ContractSpec, current_settings?.ticks_per_row ?? 1)).Value; public uint display_quantity_divisor { get; } public LadderSettings current_settings { get; private set; } public double high => _high.Value; @@ -409,11 +389,11 @@ namespace mbts.spark { double _max_left_panel_scroll_position => Math.Max(0, _left_panel_extent_height - _left_panel_view_port_height); - internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoData? __, AlgoDefinitionMetadata? meta) op) { + internal OrderRecordImmutable get_root_at_price(OrderSecurity op) { var order = op.order; - double p = order.ui_price(); + double p = _normalize_price(order.ui_price()); foreach (var o in lineage(order.ParentKey)) { - if (_equality.Equals(p, o.ui_price())) + if (_equality.Equals(p, _normalize_price(o.ui_price()))) order = o; } return order; @@ -542,6 +522,75 @@ namespace mbts.spark { } } + static IObservable<(ImmutableSortedDictionary> price_index, IReadOnlyDictionary map)> _order_price_source( + IObservable> source, + ContractSpecificationImmutable spec) { + var price_comp = Comparer.Create((a, b) => { + var aticks = spec.full_ticks_from_zero(a); + var bticks = spec.full_ticks_from_zero(b); + return aticks.CompareTo(bticks); + }); + return _order_price_source(source, price_comp, p => LadderUtils.normalize_price(spec, p)); + } + + 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); + var sub = source.Subscribe(table => { + var bd = state.ToBuilder(); + // removes + var removes = table.removed.Concat(table.changes.Where(price_changed).Old()); + foreach (var old_order in removes) { + var price = get_price(old_order); + if (bd.TryGetValue(price, out var index)) { + var new_index = index.Remove(old_order.order.Key); + if (new_index.Count == 0) { + bd.Remove(price); + } else { + bd[price] = new_index; + } + } + } + // changes + var changes = table.changes.Where(ch => !price_changed(ch)).New(); + foreach (var changed_order in changes) { + var price = get_price(changed_order); + bd[price] = bd[price].SetItem(changed_order.order.Key, changed_order); + } + // adds + var adds = table.added.Concat(table.changes.Where(price_changed).New()); + foreach (var new_order in adds) { + var price = get_price(new_order); + if (bd.TryGetValue(price, out var index)) { + bd[price] = index.Add(new_order.order.Key, new_order); + } else { + bd[price] = ImmutableDictionary.CreateRange( + new[] { new KeyValuePair(new_order.order.Key, new_order) }); + } + } + o.OnNext((state = bd.ToImmutable(), table.state)); + }); + return sub; + }); + + bool price_changed(Change ch) => + price_comp.Compare(ch.New.order.ui_price(), ch.Old.order.ui_price()) != 0; + + double get_price(OrderSecurity order) { + var p = order.order.ui_price(); + if (!(normalize_price is null)) + p = normalize_price(p); + return p; + } + } + + double _normalize_price(double price) => + LadderUtils.normalize_price(spec, price); + bool _validate_price(Side side, double price, out string msg) { msg = null; if (!price.is_real()) { diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index b1504f514..e37f88dc6 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -2,6 +2,7 @@ using bts.api; using bts.api.md.auxiliary; using bts.collections; +using bts.shell.ladder; using bts.utils; using mbts.co2; using mbts.ui; @@ -365,6 +366,17 @@ namespace mbts.spark { Column[] columns { get; set; } = new Column[0]; IEnumerable _visible_columns => columns.Where(c => c.settings.show); + ContractSpecificationImmutable? _spec_backing; + ContractSpecificationImmutable _spec { + get { + if (_spec_backing.HasValue) { + return _spec_backing.Value; + } else if (_vm != null) { + _spec_backing = LadderUtils.multiply_tick_size(security.ContractSpec, _settings?.ticks_per_row ?? 1); + } + return SecurityDataHelper.Defaults.ContractSpecificationImmutable; + } + } int _row_count => _price_list?.Count ?? 0; @@ -388,7 +400,7 @@ namespace mbts.spark { } public void scroll_to_price(double price) { - var tick = security.ContractSpec.tickdiff(price, 0); + var tick = _spec.tickdiff(price, 0); if (tick.HasValue) { scroll_to_tick(tick.Value); } @@ -610,7 +622,7 @@ namespace mbts.spark { Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) { _vm?.recenter_all_ladders(); } else { - var tgt = security.ContractSpec.tickdiff(_mkt_break_lines.origin, 0.0); + var tgt = _spec.tickdiff(_mkt_break_lines.origin, 0.0); if (tgt.HasValue) { scroll_to_tick(tgt.Value); } @@ -643,10 +655,10 @@ namespace mbts.spark { _price_list == null ? double.NaN : _price_list[row]; uint? _bid_size_from_row(int row) => - _size_from_row(row, _price_list, _bids, _vm.security.ContractSpec); + _size_from_row(row, _price_list, _bids, _spec); uint? _ask_size_from_row(int row) => - _size_from_row(row, _price_list, _asks, _vm.security.ContractSpec); + _size_from_row(row, _price_list, _asks, _spec); uint _volume_from_row(int row) { const int max_tries = 3; @@ -741,7 +753,7 @@ namespace mbts.spark { _price_list, _settings.row_height, column.settings, - security.ContractSpec, + _spec, _vm.md.settlement_price, _settings.net_change == LadderSettings.NetChangeTerms.Ticks); } else { @@ -751,7 +763,7 @@ namespace mbts.spark { _price_list, _settings.row_height, column.settings, - security.ContractSpec, + _spec, _settings.price_display_format); } break; @@ -769,7 +781,7 @@ namespace mbts.spark { } void render_market_col(NativePriceSize[] depth) { var mid = LadderRender.index_of(_price_list, _last_origin_price, _price_comparer); - LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security.ContractSpec, column.settings, _fmt_mkt_depth_item); + LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, _spec, column.settings, _fmt_mkt_depth_item); } } _apply_column_visual_offset(); @@ -797,7 +809,6 @@ namespace mbts.spark { void _connect_vm() { _dispose_resources(); _vm = DataContext as LadderVM; - _price_list.spec = _vm.security.ContractSpec; if (!IsVisible) return; else if (_vm == null) { @@ -805,7 +816,7 @@ namespace mbts.spark { } else { _vm.OnDisposed += _on_vm_disposed; _prices_updated = 0; - _price_comparer = Comparer.Create((x, y) => security.ContractSpec.tick_equals(x, y) ? 0 : y.CompareTo(x)); + _price_comparer = Comparer.Create((x, y) => _spec.tick_equals(_normalize_price(x), _normalize_price(y)) ? 0 : y.CompareTo(x)); _price_dirty = true; _piq_dirty = true; // **use local vm to protect against re-assignment, @@ -1073,14 +1084,14 @@ namespace mbts.spark { if (!_settings.piq_column.show) return; int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer); - LadderRender.render_piqs(_piq_vis_tup.visual, _last_vis_tup.glyph_context, origin_index, _price_list, _vm.price_vs_piq, _settings.row_height, security.ContractSpec, _settings.piq_column, _fmt_mkt_quantity); + LadderRender.render_piqs(_piq_vis_tup.visual, _last_vis_tup.glyph_context, origin_index, _price_list, _vm.price_vs_piq, _settings.row_height, _spec, _settings.piq_column, _fmt_mkt_quantity); } void _refresh_sizes() { Log.assert_d(_price_list != null); int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer); - LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column, _fmt_mkt_depth_item); - LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column, _fmt_mkt_depth_item); + LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, _spec, _settings.bid_column, _fmt_mkt_depth_item); + LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, _spec, _settings.ask_column, _fmt_mkt_depth_item); } /// @@ -1108,7 +1119,7 @@ namespace mbts.spark { _price_list, vapls, _settings.row_height, - security.ContractSpec, + _spec, _settings.volume_column, last_index, _get_last_arrow_string(), @@ -1177,31 +1188,46 @@ namespace mbts.spark { prices != null && prices.Length > 0 ? prices[0].price : double.NaN; double _get_bid_market_break() { + var raw_bid_break = _get_bid_market_break_raw(); + return _normalize_price(raw_bid_break); + } + + double _normalize_price(double price) => + LadderUtils.normalize_price(_spec, price); + + double _get_bid_market_break_raw() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_bid) ? - double.IsNaN(best_ask) ? _vm.settlement : security.ContractSpec.tickdown(best_ask) : + double.IsNaN(best_ask) ? _vm.settlement : _spec.tickdown(best_ask) : best_bid; } double _get_ask_market_break() { + var raw_ask_break = _get_ask_market_break_raw(); + return _normalize_price(raw_ask_break); + } + double _get_ask_market_break_raw() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_ask) ? double.IsNaN(best_bid) ? _vm.settlement : best_bid : - security.ContractSpec.tickdown(best_ask); + _spec.tickdown(best_ask); } double _get_mid_market_break() { double best_bid = _get_top_price(_bids); double best_ask = _get_top_price(_asks); return double.IsNaN(best_bid) ? - double.IsNaN(best_ask) ? _vm.settlement : security.ContractSpec.tickdown(best_ask) : - double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(security.ContractSpec, best_bid, best_ask); + double.IsNaN(best_ask) ? _vm.settlement : _spec.tickdown(best_ask) : + double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(_spec, best_bid, best_ask); } - double _get_session_low() => _vm.md.session_low; - double _get_session_high() => _vm.md.session_high; + double _get_session_low() => _normalize_price(_get_session_low_raw()); + double _get_session_high() => _normalize_price(_get_session_high_raw()); + + double _get_session_low_raw() => _vm.md.session_low; + double _get_session_high_raw() => _vm.md.session_high; void _render_mkt_break(DrawingVisual vis, double price, uint color) => LadderRender.render_mkt_break(vis, _row_for_price(price), _settings.row_height, color); @@ -1210,6 +1236,9 @@ namespace mbts.spark { LadderRender.render_single_grid_line(vis, row, _settings.row_height, color, _price_column.x_left, _settings.price_column.width); #endregion + void _invalidate_spec() => + _spec_backing = null; + void _settings_updated(LadderSettings s) { bool init; double prev_row_height; @@ -1223,6 +1252,10 @@ namespace mbts.spark { /// The viewmodel will always have the most up-to-date settings, so ignore and just get it from . /// This is a workaround for the global settings-defaults issue: when defaults are updated, some properties are inadvertantly overwritten, such as column-widths, etc. _settings = _vm.get_save_state(); + _invalidate_spec(); + if (_price_list != null) { + _price_list.spec = _spec; + } _bid_vis_tup.glyph_context = glyph_context(s.bid_column); _ask_vis_tup.glyph_context = glyph_context(s.ask_column); _price_vis_tup.glyph_context = glyph_context(s.price_column); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs index 15c5ff500..7ac357c54 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs @@ -198,15 +198,26 @@ namespace mbts.spark { var foreground = settings.foreground.rgb_brush(); int curr_index = origin_index; double curr_price = prices[curr_index]; - for (int i = 0; i < rungs.Length; i++) { - if (rungs[i].is_nan) break; - double price = rungs[i].price; + NativePriceSize curr_size = NativePriceSize.NO_MARKET; + var row_tick_groups = rungs + .TakeWhile(nps => !nps.is_nan) + .AggregateConsecutiveGroups(() => NativePriceSize.NO_MARKET, + (aggr, rung) => rung.with( + direct_size: aggr.direct_size + rung.direct_size, + implied_size: aggr.implied_size + rung.implied_size), + rung => { + //spec.round_to_tick(rung.price); + return spec.tickup(0, spec.full_ticks_from_zero(rung.price)); + }); + foreach (var rung in row_tick_groups) { + //double price = spec.round_to_tick(rung.price); + var price = spec.tickup(0, spec.full_ticks_from_zero(rung.price)); // prices are in descending order, so get diff from curr_price - price int tick_diff = spec.tickdiff_unchecked(curr_price, price); curr_index += tick_diff; curr_price = price; if (curr_index >= 0 && curr_index < prices.Count) { - var gr = format_text(fmt(rungs[i]), curr_index, row_height, settings, glyph_context); + var gr = format_text(fmt(rung), curr_index, row_height, settings, glyph_context); dc.DrawGlyphRun(foreground, gr); } else break; } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 099a408d4..7d58d7179 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -670,6 +670,7 @@ IsEnabled="{Binding can_choose_alternate_implied_format}" ItemsSource="{Binding alternate_implied_format_options}" SelectedItem="{Binding selected_alternate_implied_format}" + VerticalAlignment="Top" /> @@ -728,7 +729,38 @@ Visibility="{Binding is_synthetic, Converter={StaticResource NetChangeGroupBoxIsVisibleVisibilityConverter}}" Padding="4" > - + + + + + + + + + + + + Ticks Per Row + + + + + + + + + + + spec.tickup(0, spec.full_ticks_from_zero(price)); + + public static uint fit_ticks_per_row_to_dollars(ContractSpecificationImmutable spec, uint ticks_per_row) => + _fit_ticks_per_row_to_dollars(spec, ticks_per_row) ?? 1; + + static uint? _fit_ticks_per_row_to_dollars(ContractSpecificationImmutable spec, uint ticks_per_row) { + if (ticks_per_row == 0) + return null; + // it is assumed that low tick will be the same as high tick; + // however, best to double check - return null if this isn't the case (let the caller decide what to do). + var tf = TickUtils.get_tick_factors(spec); + if (!tf.low_tick.Equals(tf.high_tick) || !tf.is_valid() || tf.low_tick.is_integer()) + return null; + var ticks_per_dollar = (uint)(tf.low_tick.tick_base / tf.low_tick.tick_unit); + // if ticks_per_row is greater than ticks_per_dollar, round to a multiple of ticks_per_dollar + if (ticks_per_row > ticks_per_dollar) { + return (uint)Math.Floor((double)(ticks_per_row / ticks_per_dollar)); + } else if (ticks_per_row == ticks_per_dollar) { + return ticks_per_row; + } else { + uint max_decrease_adj = ticks_per_row; + uint max_increase_adj = ticks_per_dollar - ticks_per_row - 1; + for (uint adj = 0; adj < Math.Max(max_decrease_adj, max_increase_adj); adj++) { + if (adj < max_decrease_adj) { + var result = ticks_per_row - adj; + if (ticks_per_dollar % result == 0) + return result; + } + if (adj < max_increase_adj) { + var result = ticks_per_row + adj; + if (ticks_per_dollar % result == 0) + return result; + } + } + } + return null; + } + } +} diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 6232d9253..9ef2fff9f 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -52,6 +52,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; OrderBookFillsGridSettings _cached_fills_settings = OrderBookStartupData.DefaultFillsGrid; double _raw_right_panel_width = OrderBookStartupData.Default.right_panel_width, @@ -71,8 +72,8 @@ namespace mbts.spark { FilterData _cached_filter_data; public OrderBookVM( - IBus bus, INotificationService notification_service, OrdersModel model, IWindowSettingsManager settings_manager, bool rows_are_initially_expanded = false) - : this(bus, notification_service, model, OrdersModel.piq_enabled ? model.on_order_tuples_with_root_and_piq : model.on_order_tuples_with_root, settings_manager, rows_are_initially_expanded) { } + IBus bus, INotificationService notification_service, OrdersModel model, IWindowSettingsManager settings_manager, bool rows_are_initially_expanded = false, Func global_filter = null) + : this(bus, notification_service, model, OrdersModel.piq_enabled ? model.on_order_tuples_with_root_and_piq : model.on_order_tuples_with_root, settings_manager, rows_are_initially_expanded, global_filter) { } public OrderBookVM( IBus bus, @@ -80,10 +81,12 @@ namespace mbts.spark { OrdersModel model, IObservable> orders_source, IWindowSettingsManager settings_manager, - bool rows_are_initially_expanded = false) { + bool rows_are_initially_expanded = false, + Func global_filter = null) { _bus = bus; _model = model; + _global_filter = global_filter; _selected_params_mon = new OrderParamsAggregator(model.dynamic_helper, _selection_change_throttle, k => _cached_orders.TryGetValue(k, out var o) ? o.order : (OrderSecurityAlgo?)null); ladder_vm = new LadderVMContainer(bus, model); order_mod_vm = new OrderParamsVM(this, AlgoEditingPermissions.AllowEditValues); @@ -611,7 +614,7 @@ namespace mbts.spark { // resume column filter updates _columns.filter_changed += _on_filter_changed; grid_settings_manager.algo_tree_display_mode_changed += _on_filter_changed; - var new_filter = new FilterData(grid_settings_manager.algo_tree_display_mode, _columns.create_filter_states()); + var new_filter = new FilterData(grid_settings_manager.algo_tree_display_mode, _columns.create_filter_states(), _global_filter); var new_sort = _columns.get_sorting_data(); if (!new_filter.Equals(_cached_filter_data)) { _cached_filter_data = new_filter; @@ -686,7 +689,7 @@ namespace mbts.spark { } void _on_filter_changed() { - var fd = new FilterData(grid_settings_manager.algo_tree_display_mode, _columns.create_filter_states()); + var fd = new FilterData(grid_settings_manager.algo_tree_display_mode, _columns.create_filter_states(), _global_filter); if (!fd.Equals(_cached_filter_data)) { _cached_filter_data = fd; _row_collection.filter = fd.build_predicate(); @@ -975,13 +978,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 FilterData(AlgoTreeDisplayMode algo_tree_display_mode, FilterStates column_filters) { + 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() { + 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)); + } + + Func _build_predicate_core() { var pred = column_filters.build_predicate(); if (algo_tree_display_mode == AlgoTreeDisplayMode.RootAndLeafNodes) { if (pred == null) { diff --git a/src/client/spark/core/GlobalExtensions/TickExtensions.cs b/src/client/spark/core/GlobalExtensions/TickExtensions.cs index 0a02ae03d..a0e40cced 100644 --- a/src/client/spark/core/GlobalExtensions/TickExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/TickExtensions.cs @@ -18,6 +18,9 @@ namespace mbts { public static bool is_valid(this RegionalTickFactors regional_tick) => regional_tick.low_tick.is_valid() && regional_tick.high_tick.is_valid(); + public static bool is_integer(this TickFactors tick) => + tick.tick_unit == tick.tick_base; + public static double tick_unit_frac(this TickFactors tick) => tick.tick_unit / tick.tick_base; diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index b4a7f6a75..6fff88072 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -112,6 +112,14 @@ namespace mbts.ui.shell { protected bool Set(ref T backing, T value, [CallerMemberName]string name = "") => Set(ref backing, value, EqualityComparer.Default, name); + protected bool Set(ref T backing, T value, [CallerMemberName] string name = "", params string[] dependent_props) { + if (Set(ref backing, value, EqualityComparer.Default, name)) { + RaisePropertyChanged(dependent_props); + return true; + } + return false; + } + protected bool Set(ref T backing, T value, IEqualityComparer comparer, [CallerMemberName]string name = "") { if (!comparer.Equals(backing, value)) { backing = value; diff --git a/src/client/spark/view/Spark/Core/TickUtils.cs b/src/client/spark/view/Spark/Core/TickUtils.cs index 2bc29007f..03e440a3c 100644 --- a/src/client/spark/view/Spark/Core/TickUtils.cs +++ b/src/client/spark/view/Spark/Core/TickUtils.cs @@ -21,6 +21,9 @@ namespace mbts.spark { public static ContractSpecificationImmutable spec_or_default(this SecurityMD? security_md) => (security_md?.security).spec_or_default(); + public static IComparer price_comparer(this ContractSpecificationImmutable spec) => + MathUtils.epsilon_comparer.wrap(p => spec.round_to_tick(p)); + public static double ticksize(this ContractSpecificationImmutable spec, double price) => Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick; @@ -162,7 +165,7 @@ namespace mbts.spark { double intpart = (long)value; double floatpart = value % 1; double tick = spec.ticksize(value); - floatpart = ((int)(floatpart / tick)) * tick; + floatpart = ((int)Math.Round(floatpart / tick)) * tick; return intpart + floatpart; } @@ -174,6 +177,15 @@ namespace mbts.spark { return intpart + floatpart; } + // this assumes that lowTick and HighTick are the same + public static int full_ticks_from_zero(this ContractSpecificationImmutable spec, double value) { + if (value < 0) { + return -full_ticks_from_zero(spec, -value); + } + int ticks = (int)(value / spec.LowTick); + return ticks; + } + public static RegionalTickFactors get_regional_ticks(ContractSpecificationImmutable? spec) => spec.HasValue ? TickStore.get(spec.Value) : TickStore.default_rtf; diff --git a/src/client/spark_api/Co2/PriceSize.cs b/src/client/spark_api/Co2/PriceSize.cs index 3b91b089c..1b2f644ae 100644 --- a/src/client/spark_api/Co2/PriceSize.cs +++ b/src/client/spark_api/Co2/PriceSize.cs @@ -112,5 +112,9 @@ namespace mbts.co2 { return !a.Equals(b); } } - + + static class NativePriceSizeExtensions { + public static NativePriceSize with(this NativePriceSize nps, uint? direct_size = null, uint? implied_size = null) => + new NativePriceSize(nps.int_price, direct_size ?? nps.direct_size, implied_size ?? nps.implied_size); + } } diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index 981798a85..a009ff234 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -83,6 +83,49 @@ namespace System.Collections.Generic { return rv; } + public static IEnumerable AggregateConsecutiveGroups( + this IEnumerable source, + Func seed_factory, + Func aggregate, + Func group_key) => + AggregateConsecutiveGroups(source, seed_factory, aggregate, group_key, EqualityComparer.Default); + + public static IEnumerable AggregateConsecutiveGroups( + this IEnumerable source, + Func seed_factory, + Func aggregate, + Func group_key, + IEqualityComparer group_key_comparer) { + // + if (source is null) + throw new ArgumentNullException(nameof(source)); + if (seed_factory is null) + throw new ArgumentNullException(nameof(seed_factory)); + if (aggregate is null) + throw new ArgumentNullException(nameof(aggregate)); + if (group_key is null) + throw new ArgumentNullException(nameof(group_key)); + if (group_key_comparer is null) + throw new ArgumentNullException(nameof(group_key_comparer)); + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + var curr_group = group_key(en.Current); + var agg = aggregate(seed_factory(), en.Current); + while (en.MoveNext()) { + var group = group_key(en.Current); + if (group_key_comparer.Equals(group, curr_group)) + agg = aggregate(agg, en.Current); + else { + yield return agg; + curr_group = group; + agg = aggregate(seed_factory(), en.Current); + } + } + yield return agg; + } + } + } + public static bool CountAtLeast(this IEnumerable source, int count) { if (count < 0) throw new ArgumentException(ExceptionBuilder.Format.LessThan(0), nameof(count));