diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs index 07073bd1a..7813861cd 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoDefinitionVM.cs @@ -374,6 +374,29 @@ namespace mbts.spark { } } + public void load_many(IEnumerable defs) { + var def_list = defs as IList ?? defs.ToList(); + switch (def_list.Count) { + case 0: algo_root = null; break; + case 1: load_def(def_list[0]); break; + default: + var def = def_list[0]; + var key = OrderDataHelper.get_shallow_factory_key(def); + if (algo_root?.id == key) { + algo_root.load_many(def_list); + } else if (_algo_roots.TryGetValue(key, out IAlgoVM vm)) { + vm.load_many(def_list); + algo_root = vm; + } else { + OrderTypeVMFactory.create(key, def.display_name(), def.CustomCase, is_expanded: true); + algo_roots.Add(vm = _mk_algo_root(def)); + vm.load_many(def_list); + algo_root = vm; + } + break; + } + } + public void load(AlgoData data) { _assert_can_load(data.key); if (algo_root != null) diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoParamRowVM.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoParamRowVM.cs index 10592c1ef..be20c48b6 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoParamRowVM.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoParamRowVM.cs @@ -18,8 +18,21 @@ namespace mbts.spark { public IAlgoVM algo { get; set; } public IAlgoParamVM param { get; } - public int level => parent == null ? 0 : parent.level + 1; public AlgoParamRowVM parent { get; } + public int level => parent == null ? 0 : parent.level + 1; + public string path_disambiguation { + get { + if (parent == null) + return string.Empty; + string pd = parent.path_disambiguation; + if (parent.algo.order_type == bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Cover) { + if (pd.Length > 0) + pd += "."; + pd += parent.param.display_name; + } + return pd; + } + } public bool is_enabled { get => _is_enabled; set => Set(ref _is_enabled, value); } public void raise_invalidated() => invalidated?.Invoke(); diff --git a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs index 69b8de0f3..e9ec228a4 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/VM/AlgoVMWrapper.cs @@ -102,6 +102,7 @@ namespace mbts.spark { public void assign_to(CustomOrderDefinition value) => _algo_root?.assign_to(value); public bool key_match(KeyEventArgs e) => _algo_root?.key_match(e) ?? false; public void load_from(CustomOrderDefinitionImmutable value) => _algo_root?.load_from(value); + public void load_many(IEnumerable values) => _algo_root?.load_many(values); public Task load_from_async(CustomOrderDefinitionImmutable definition) => _algo_root is IAlgoVM vm ? vm.load_from_async(definition) : Task.FromResult(null); IDisposable _set_hooks(AlgoDefinitionVM vm) { diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml index 9a0223338..fdfc22798 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml @@ -4,12 +4,14 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sp="clr-namespace:mbts.spark" + xmlns:u="clr-namespace:mbts.ui" xmlns:c="clr-namespace:mbts.ui.controls" xmlns:cv="clr-namespace:mbts.ui.converters" xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:uag="clr-namespace:mbts.ui.spark.algo" xmlns:uspcv="clr-namespace:mbts.ui.spark.converters" xmlns:sys="clr-namespace:System;assembly=mscorlib" + u:StateManager.VisualState="{Binding CanUserChangeAlgoRoot, RelativeSource={RelativeSource Self}, Converter={x:Static usp:AlgoEditorGridView.AlgoRootVisualStateConverter}}" > @@ -35,6 +37,7 @@ + - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + Algo + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs index eaaa6d160..b188c8db9 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoEditorGridView.xaml.cs @@ -1,13 +1,19 @@ using mbts.spark; using mbts.ui.controls; +using mbts.ui.converters; using mbts.ui.utility; using System; using System.Windows; using System.Windows.Controls; +using System.Windows.Data; using System.Windows.Documents; namespace mbts.ui.spark { partial class AlgoEditorGridView : UserControl { + public static readonly IValueConverter + AlgoRootVisualStateConverter = ValueConverter.create(show_bbo => show_bbo ? VisualStateNames.AlgoRoot.Active : VisualStateNames.AlgoRoot.Inactive), + AlgoRootComboBoxMarginConverter = ValueConverter.create(name_col_width => new Thickness(name_col_width + 8, 0, 0, 0)); + readonly ObservableAggregateCollection _param_rows = new ObservableAggregateCollection(); IDisposable _rows_hook; @@ -22,6 +28,16 @@ namespace mbts.ui.spark { public CollectionViewSource> ParamRowsViewSource { get; } + #region CanUserChangeAlgoRoot + public static readonly DependencyProperty CanUserChangeAlgoRootProperty = + WPFHelper.create_dp(nameof(CanUserChangeAlgoRoot)); + + public bool CanUserChangeAlgoRoot { + get => (bool)GetValue(CanUserChangeAlgoRootProperty); + set => SetValue(CanUserChangeAlgoRootProperty, value); + } + #endregion + #region ShowAlgoTypeNodes public static readonly DependencyProperty ShowAlgoTypeNodesProperty = WPFHelper.create_dp( @@ -46,19 +62,6 @@ namespace mbts.ui.spark { } #endregion - #region ShowAlgoTypeNodes - public static readonly DependencyProperty ShowExecutionStrategyProperty = - DependencyProperty.RegisterAttached("ShowExecutionStrategy", typeof(bool), typeof(AlgoEditorGridView), - new PropertyMetadata(false, (d, e) => { - var el = (FrameworkElement)d; - if (el.try_find_ancestor_of_type(out DataGridRow row_view)) - row_view.SetCurrentValue(DataGridRow.DetailsVisibilityProperty, (bool)e.NewValue ? Visibility.Visible : Visibility.Collapsed); - })); - - public static bool GetShowExecutionStrategy(DependencyObject d) => (bool)d.GetValue(ShowExecutionStrategyProperty); - public static void SetShowExecutionStrategy(DependencyObject d, bool value) => d.SetValue(ShowExecutionStrategyProperty, value); - #endregion - void _on_execution_strategy_toggle_click(object sender, RoutedEventArgs e) { if (sender is Hyperlink hl && hl.try_find_ancestor_of_type(out DataGridRow row_view)) { Visibility vis; string text; @@ -74,6 +77,16 @@ namespace mbts.ui.spark { row_view.SetCurrentValue(DataGridRow.DetailsVisibilityProperty, vis); } } + + public static class VisualStateNames { + public static class AlgoRoot { + public const string GroupName = nameof(AlgoRoot); + + public static readonly string + Active = $"{GroupName}{VisualStates.Active}", + Inactive = $"{GroupName}{VisualStates.Inactive}"; + } + } } class AlgoEditorGridRowStyleSelector : StyleSelector { diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs index 631588f33..c0b02627e 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamRowsHelper.cs @@ -12,7 +12,20 @@ namespace mbts.ui.spark { partial class AlgoEditorGridView : UserControl { static class AlgoParamRowsHelper { public static IDisposable reset(AlgoDefinitionVM algo, ObservableAggregateCollection rows, bool include_algo_type_rows) => - algo == null ? null : new CompositeDisposable(_wrap_rows(algo, rows, include_algo_type_rows)) { rows.clear_collections }; + algo == null ? null : new CompositeDisposable(algo.observe_algo_root().SubscribeHookLatest(a => { + rows.clear_collections(); + if (a == null) + return Disposable.empty; + var child_rows = new ObservableAggregateCollection(); + /// Note: the order of operations here matters + /// has the potential to trigger a lot of CollectionChanged events (depending on how deep the algo-tree is). + /// There is no need to burden the aggregate 'rows' with echoing all of these events, if the child-row collection is finished changing when it is added to the aggregate. + var hook = _wrap_rows(a, null, child_rows, include_algo_type_rows); + rows.add_collection(child_rows.AsReadOnly()); + return hook; + })) { + rows.clear_collections + }; static IDisposable _wrap_rows(AlgoDefinitionVM algo_def, ObservableAggregateCollection rows, bool include_algo_type_rows) { AlgoParamRowVM root = null; diff --git a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs index 63967f2e0..19eab2d13 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/View/AlgoEditorGridView/AlgoParamTemplateSelector.cs @@ -1,5 +1,6 @@ using bts.spark; using mbts.spark; +using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; @@ -12,8 +13,10 @@ namespace mbts.ui.spark { public DataTemplate BoolTemplate { get; set; } public DataTemplate IntTemplate { get; set; } public DataTemplate UIntTemplate { get; set; } + public DataTemplate NullableUIntTemplate { get; set; } public DataTemplate DoubleTemplate { get; set; } public DataTemplate EnumTemplate { get; set; } + public DataTemplate NullableEnumTemplate { get; set; } public DataTemplate StringTemplate { get; set; } public DataTemplate QuantityMeasureTemplate { get; set; } public DataTemplate OrderDefTemplate { get; set; } @@ -23,28 +26,26 @@ namespace mbts.ui.spark { public override DataTemplate SelectTemplate(object item, DependencyObject container) { IAlgoParamVM pvm = item as IAlgoParamVM ?? (item as AlgoParamRowVM)?.param; if (pvm != null) { - if (pvm is IAlgoParamVM) - return DoubleTemplate; - if (pvm is IAlgoParamVM) - return IntTemplate; - if (pvm is IAlgoParamVM) - return UIntTemplate; - if (pvm is IAlgoParamVM) - return BoolTemplate; - if (pvm is IAlgoParamVM) - return StringTemplate; - if (pvm is IAlgoParamVM) - return OrderDefTemplate; - if (pvm is IAlgoParamVM) - return QuantityMeasureTemplate; - if (pvm is IAlgoParamVM) - return ExecutionStrategyTemplate; - if (pvm is IAlgoParamVM) - return TimestampTemplate; + if (pvm is IAlgoParamVM) return DoubleTemplate; + if (pvm is IAlgoParamVM) return IntTemplate; + if (pvm is IAlgoParamVM) return UIntTemplate; + if (pvm is IAlgoParamVM) return NullableUIntTemplate; + if (pvm is IAlgoParamVM) return BoolTemplate; + if (pvm is IAlgoParamVM) return StringTemplate; + if (pvm is IAlgoParamVM) return OrderDefTemplate; + if (pvm is IAlgoParamVM) return QuantityMeasureTemplate; + if (pvm is IAlgoParamVM) return ExecutionStrategyTemplate; + if (pvm is IAlgoParamVM) return TimestampTemplate; var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), typeof(IAlgoParamVM<>)).FirstOrDefault(); if (targ != null) { if (targ.IsEnum) return EnumTemplate; + else if (targ.IsNullable()) { + targ = targ.GetGenericArguments()[0]; + if (targ.IsEnum) + return NullableEnumTemplate; + } + } } return null; diff --git a/src/client/spark/Modules/Trading/Ladder/LadderModel.cs b/src/client/spark/Modules/Trading/Ladder/LadderModel.cs index 7576b8374..2ff11fa2f 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderModel.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderModel.cs @@ -1,17 +1,23 @@ using bts; using bts.api; +using bts.api.orderman; +using bts.collections; using mbts.co2; +using System; +using System.Collections.Generic; +using System.Reactive.Linq; using System.Threading.Tasks; namespace mbts.spark { class LadderModel { readonly OrdersModel _order_gateway; - readonly MarketDataAuxiliaryModel _md_auxiliary_model; - public LadderModel(SecurityMD source, OrdersModel ordergw, MarketDataAuxiliaryModel md_auxiliary_model) { + public LadderModel(SecurityMD source, OrdersModel ordergw, Func order_filter = null) { security_md = source; _order_gateway = ordergw; - _md_auxiliary_model = md_auxiliary_model; + orders = ordergw.working_orders; + if (order_filter != null) + orders = orders.Select(order_map => new FilteredDictionary(order_map, order_filter)); } public enum CancelType { All, Bids, Asks } @@ -20,7 +26,7 @@ namespace mbts.spark { public SecurityImmutable security => security_md.security; public MDConsumerHandle md => security_md.md; public OrdersModel order_gateway => _order_gateway; - public MarketDataAuxiliaryModel md_auxiliary_model => _md_auxiliary_model; + public IObservable> orders { get; } public Task cancel_orders(CancelType ct) { switch (ct) { diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index 6d1784488..2b5dc8881 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -257,8 +257,8 @@ namespace mbts.spark { ask_column.background = BTSColors.MarketData.ask; price_column.background = BTSColors.LadderSpecial.default_column_background; last_column.background = 0xFFFFFF; - return new LadderSettings { - row_height = 20, + var rv = new LadderSettings { + row_height = 22, grid_line_color = 0x535353, orders_column = orders_column, bid_column = bid_column, @@ -301,6 +301,8 @@ namespace mbts.spark { zoom_factor = _default_zoom_factor, net_change = NetChangeTerms.None, }; + rv.row_height = LadderRender.measure_row_height(rv); + return rv; } } diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 33c8b36ec..b36af3813 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -23,16 +23,14 @@ namespace bts.shell { readonly IWindowManager _wm; readonly UserSettingsHub _settings_hub; readonly OrdersModel _orders_model; - readonly MarketDataAuxiliaryModel _md_auxiliary_model; IReadOnlyDictionary _securities = new Dictionary(); - public LadderWindowFactory(IShellModule owner, IBus bus, IWindowManager wm, UserSettingsHub settings_hub, OrdersModel orders_model, MarketDataAuxiliaryModel md_auxiliary_model) + public LadderWindowFactory(IShellModule owner, IBus bus, IWindowManager wm, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, "SparkLadder") { _bus = bus; _wm = wm; _settings_hub = settings_hub; _orders_model = orders_model; - _md_auxiliary_model = md_auxiliary_model; _ladder_conf = new LadderConfig(Configuration.get(), Configuration.get().ladder); _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s), @@ -56,14 +54,14 @@ namespace bts.shell { IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings) { var id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; var view = new Lazy(() => { - var model = new LadderModel(md, _orders_model, _md_auxiliary_model); + var model = new LadderModel(md, _orders_model); var settings_manager = new WindowSettingsManager( _settings_hub, state_settings == null || state_settings.use_defaults ? null : state_settings, us => sanitize_ladder_settings(us.ladder), (us, v) => us.with(sanitize_ladder_settings(v))); var init = state_settings ?? settings_manager.default_settings; init.use_defaults |= state_settings == null; - var vm = new LadderVM(_bus, model, settings_manager, init); + var vm = LadderVM.create(_bus, model, settings_manager, init); vm.order_properties_vm.open_algo_popup_on_select = _ladder_conf.open_algo_popup_on_select; var lv = new LadderView(vm); foreach (var kv in AlgoStudioModelUtils.get_dynamic_resources(vm.model.order_gateway.algo_model.ui_configuration)) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 5be07f911..2828e094a 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -38,14 +38,26 @@ namespace mbts.spark { IEqualityComparer _equality; Dictionary _slot_price_vs_orders; - public LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) { + public static LadderVM create(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) { + var non_shared_wsm = settings_manager.as_non_shared(); + return new LadderVM(bus, model, settings_manager, non_shared_wsm, init, new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), settings_manager.subscribe_current().Select(s => new InlineOrderProperties(model.order_gateway, s)))); + } + + public static LadderVM create_readonly(IBus bus, LadderModel model) { + var default_settings = LadderSettings.Default; + return create_readonly(bus, model, new WindowSettingsManager.DisconnectedImpl(default_settings), default_settings); + } + + public static LadderVM create_readonly(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) => + new LadderVM(bus, model, settings_manager, settings_manager.as_non_shared(), init); + + LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, IWindowSettingsManagerNonShared non_shared_wsm, LadderSettings init, OrderPropertiesEditorVM order_properties_vm = null) { _bus = bus; _model = model; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); _slot_price_vs_orders = new Dictionary(_equality); - var non_shared_wsm = settings_manager.as_non_shared(); _settings_manager = non_shared_wsm; - order_properties_vm = new OrderPropertiesEditorVM(_model.order_gateway, Observable.Return(_model.security_md), _settings_manager.subscribe_current().Select(s => new InlineOrderProperties(_model.order_gateway, s))); + this.order_properties_vm = order_properties_vm; _high = backing(nameof(high), double.NaN); _low = backing(nameof(low), double.NaN); _change = backing(nameof(change), double.NaN); @@ -126,13 +138,11 @@ namespace mbts.spark { _dispose = Disposable.Create( settings_command, non_shared_wsm, - settings.OnDispatcher().Subscribe(s => order_properties_vm.on_favorite_algos(s.favorite_algos)), - order_properties_vm, - order_properties_vm.observe_account(true).Select(a => a?.name ?? string.Empty).Subscribe(account_positions), + get_order_properties_editor_hooks(), account_positions, size_calculator = new CalculatorLogic(0, _settings_manager.subscribe_current().Select(s => s.calculator_buttons)), bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update), - model.order_gateway.working_orders.OnDispatcher().Subscribe(working => { + model.orders.OnDispatcher().Subscribe(working => { // Here we manage N orders to 1 price slot in the ladder Dictionary> orders_used_in_this_update = new Dictionary>(_equality); @@ -225,6 +235,13 @@ namespace mbts.spark { WorkLoop.Start($"Ladder '{security}'", _tick), Disposable.Create(() => _on_disposed_impl?.Invoke(true)) ); + IDisposable get_order_properties_editor_hooks() => + order_properties_vm == null ? + Disposable.empty : + Disposable.Create( + settings.OnDispatcher().Subscribe(s => order_properties_vm.on_favorite_algos(s.favorite_algos)), + order_properties_vm, + order_properties_vm.observe_account(true).Select(a => a?.name ?? string.Empty).Subscribe(account_positions)); } public IBus bus => _bus; @@ -269,6 +286,7 @@ namespace mbts.spark { public ulong volume => _volume.Value; public bool auto_clear { get => _auto_clear.Value; set => _auto_clear.set(value); } public CalculatorLogic size_calculator { get; } + /// Important: can be null. public OrderPropertiesEditorVM order_properties_vm { get; } public ObservableCollection orders { get; } public IAsyncCommand cancel_command { get; } @@ -318,6 +336,8 @@ namespace mbts.spark { } public void key_down(KeyEventArgs e) { + if (order_properties_vm == null) + return; // the ctrl modifier requirement helps avoid keyboard-input collisions w/ algo-templates popup if (!KeyboardExtensions.IsCtrlDown()) return; var new_algo = order_properties_vm.algo_definitions.FirstOrDefault(o => o.algo_root.key_match(e)); @@ -328,6 +348,8 @@ namespace mbts.spark { } public async void send_order((double price, Side? side, bool size_from_alternate) args) { + if (order_properties_vm == null) + return; var s = _settings_manager.current_settings(); if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (args.size_from_alternate && s.alternate_order_size == 0)) return; @@ -383,8 +405,10 @@ namespace mbts.spark { } }); - void _show_ticket() => - _bus.post(SparkTags.ShowOrderTicketTag, (new OrderDefinitionImmutable(order_properties_vm.create(Side.Buy)), 0d, 0u)); + void _show_ticket() { + if (order_properties_vm != null) + _bus.post(SparkTags.ShowOrderTicketTag, (new OrderDefinitionImmutable(order_properties_vm.create(Side.Buy)), 0d, 0u)); + } void _tick() { _update_header(); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index 2f91999d2..ecc038596 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -5,8 +5,8 @@ using bts.utils; using mbts.co2; using mbts.ui; using mbts.ui.controls; +using mbts.ui.extensions; using mbts.ui.spark; -using mbts.ui.utility; using mbts.ui.utility.text; using mbts.utils; using System; @@ -53,7 +53,7 @@ namespace mbts.spark { LadderVM _vm; LadderTactileAdorner _tactile_adorner; ulong _prices_updated; - NativePriceSize[] _bids, _asks; + NativePriceSize[] _bids = new NativePriceSize[NativePriceHelpers.COCONUT_MAX_DEPTH], _asks = new NativePriceSize[NativePriceHelpers.COCONUT_MAX_DEPTH]; bool _price_dirty = false; double[] _price_list = null; IComparer _price_comparer; @@ -81,6 +81,7 @@ namespace mbts.spark { }; RecenterCommand = new DelegateCommand(_scroll_to_center); DataContextChanged += (s, e) => _connect_vm(); + IsVisibleChanged += (s, e) => _connect_vm(); Unloaded += (s, e) => { Disposable.dispose(ref _settings_sub); Disposable.dispose(ref _tick_sub); @@ -192,6 +193,25 @@ namespace mbts.spark { set => SetValue(LastColumnWidthProperty, value); } + #region CanUserSendOrders + public static readonly DependencyProperty CanUserSendOrdersProperty = + DependencyProperty.Register( + nameof(CanUserSendOrders), + typeof(bool), + typeof(LadderGridHost), + new PropertyMetadata(true, (d, e) => ((LadderGridHost)d).OnCanUserSendOrdersChanged(e))); + + public bool CanUserSendOrders { + get => (bool)GetValue(CanUserSendOrdersProperty); + set => SetValue(CanUserSendOrdersProperty, value); + } + + event Action CanUserSendOrdersChanged; + + void OnCanUserSendOrdersChanged(DependencyPropertyChangedEventArgs e) => + CanUserSendOrdersChanged?.Invoke((bool)e.NewValue); + #endregion + #region Command public ICommand Command { get => (ICommand)GetValue(CommandProperty); @@ -244,6 +264,26 @@ namespace mbts.spark { public void drag_out_of_bounds() => _tactile_adorner?.drag_out_of_bounds(); + public void scroll_to_price(double price) { + if (_scrollViewer == null || _price_list.is_null_or_empty()) + return; + if (security.ContractSpec.tickdiff(_price_list[0], price) is int target_row) { + int visible_row_count = (int)(_scrollViewer.ActualHeight / _settings.row_height); + int curr_row = visible_row_count + (int)(_scrollViewer.VerticalOffset / _settings.row_height); + if ((target_row > curr_row && target_row < _row_count) || (target_row < (curr_row - visible_row_count) && target_row >= 0)) + _scroll_to_row(target_row); + } + } + + public IObservable subscribe_hover_column() => + Observable.Create(o => { + notify(Mouse.GetPosition(this)); + return this.SubscribePreviewMouseMove((s, e) => notify(e.GetPosition(this))); + void notify(Point pt) => + o.OnNext(_column_for_point(pt)?.column_type ?? ColumnType.None); + }); + + public override void OnApplyTemplate() { base.OnApplyTemplate(); _scrollViewer = this.descendants_of_type().First(); @@ -419,14 +459,18 @@ namespace mbts.spark { void _connect_vm() { _dispose_resources(); _vm = DataContext as LadderVM; - if (_vm != null) { + if (!IsVisible) + return; + else if (_vm == null) { + _clear_visuals(); + } 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_dirty = true; _vm.on_tick += _tick; _settings_sub = _vm.settings.OnDispatcher().Subscribe(_settings_updated); - _volume_sub = _vm.model.md_auxiliary_model.security_volume_at_price(security.Id).Subscribe(t => _volume_container.write_value(t.state.Values)); + _volume_sub = _vm.model.order_gateway.md_auxiliary_model.security_volume_at_price(security.Id).Subscribe(t => _volume_container.write_value(t.state.Values)); _tick_sub = Disposable.Create(() => _vm.on_tick -= _tick); } } @@ -459,11 +503,21 @@ namespace mbts.spark { Storyboard.SetTargetProperty(anim, new PropertyPath(Behavior.AnimatedScrollViewerVerticalOffsetProperty)); sb.Begin(); } else { - _scrollViewer.ScrollToVerticalOffset(_row_count * (_settings.row_height / 2) - (ActualHeight / 2)); + _scroll_to_row(_row_count / 2); } } } + void _scroll_to_row(int row) => + _scrollViewer.ScrollToVerticalOffset((row * _settings.row_height) - (ActualHeight / 2)); + + IObservable _subscribe_can_send_orders() => + Observable.Create(o => { + o.OnNext(CanUserSendOrders); + CanUserSendOrdersChanged += o.OnNext; + return Disposable.Create(() => CanUserSendOrdersChanged -= o.OnNext); + }); + #region Timer.Tick, Refresh Methods void _tick() { if (_settings != null) { @@ -636,6 +690,26 @@ namespace mbts.spark { _ordershost.Height = height; _render_grid_background(); } + + void _clear_visuals() { + if (_settings == null) + return; + _price_list = new double[_row_count]; + for (int i = 0; i < _price_list.Length; i++) + _price_list[i] = double.NaN; + Array.Clear(_bids, 0, _bids.Length); + Array.Clear(_asks, 0, _asks.Length); + _price_dirty = true; + LadderRender.clear_prices(_price_vis_tup.visual, _row_count, _settings.row_height, _settings.price_column, _price_vis_tup.glyph_context); + _refresh_bid_mkt_break(); + _refresh_ask_mkt_break(); + _refresh_mid_mkt_break(); + _refresh_session_low_line(); + _refresh_session_high_line(); + _refresh_session_range(); + _refresh_last_trade(); + _refresh_sizes(); + } #endregion #region Market Break, Session Low/High Utils @@ -887,4 +961,4 @@ namespace mbts.spark { } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs index 014176202..35d862f25 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderRender.cs @@ -4,7 +4,6 @@ using bts.api.md.auxiliary; using mbts.co2; using mbts.ui; using mbts.ui.controls; -using mbts.ui.spark; using mbts.ui.utility.text; using System; using System.Collections.Generic; @@ -86,6 +85,16 @@ namespace mbts.spark { return result; } + public static void clear_prices(DrawingVisual price, int row_count, double row_height, LadderColumnSettings settings, GlyphContext glyph_context) { + var foreground = settings.foreground.rgb_brush(); + var fprices = _format_empty_prices(row_count, row_height, settings, glyph_context); + using (var dc = price.RenderOpen()) + using (_draw_with_clip(dc, settings, row_height, row_count)) { + for (int x = 0; x < row_count; ++x) + dc.DrawGlyphRun(foreground, fprices[x]); + } + } + public static double[] render_prices(DrawingVisual price, GlyphContext glyph_context, double mid, double wrt_price, bool format_in_tick_terms, int row_count, double row_height, LadderColumnSettings settings, ContractSpecificationImmutable spec) { var dprices = gen_prices(mid, row_count, spec); @@ -293,6 +302,12 @@ namespace mbts.spark { dc.DrawRectangle(new SolidColorBrush(color.rgb_color()) { Opacity = 0.2 }, null, new Rect(0, high_index * row_height, settings.width, (low_index - high_index) * row_height)); } + static GlyphRun[] _format_empty_prices(int row_count, double row_height, LadderColumnSettings settings, GlyphContext glyph_context) { + var result = new GlyphRun[row_count]; + Parallel.For(0, row_count, i => result[i] = format_text("-", i, row_height, settings, glyph_context)); + return result; + } + static IDisposable _draw_with_clip(DrawingContext dc, LadderColumnSettings settings, double row_height, int row_count) { dc.PushClip(new RectangleGeometry(new Rect(0, 0, settings.width, row_height * row_count))); return Disposable.Create(dc.Pop); diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs index d2687010d..ef8d80395 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderTactileAdorner.cs @@ -1,9 +1,9 @@ using mbts.ui; using mbts.ui.controls; using mbts.ui.extensions; -using mbts.ui.utility.text; using System; using System.Collections.Generic; +using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; @@ -30,7 +30,7 @@ namespace mbts.spark { readonly LadderGridHost _host; readonly IList _hooks; - bool _is_mouse_over, _is_mouse_down, _is_mouse_dragging; + bool _is_mouse_over, _is_mouse_down, _is_mouse_dragging, _can_send_orders; int _curr_row; Column _curr_column = Column.Empty; @@ -41,6 +41,10 @@ namespace mbts.spark { _bid_mouse_down_pen = new Pen(new SolidColorBrush(Color.FromRgb(102, 178, 255)), 1).frozen(); _ask_mouse_down_pen = new Pen(new SolidColorBrush(Color.FromRgb(255, 178, 102)), 1).frozen(); _hooks = new List { + _host._subscribe_can_send_orders().Subscribe(v => { + _can_send_orders = v; + _host.Cursor = _evaluate_position(); + }), _host.SubscribeMouseEnter(_host_MouseEnter), _host.SubscribeMouseMove(_host_MouseMove), _host.SubscribeMouseLeave(_host_MouseLeave), @@ -88,7 +92,7 @@ namespace mbts.spark { _draw_cell(drawingContext, _navy_pen, x, y, _curr_column.settings.width); } } - else if (_is_mouse_over && (_curr_column.column_type == ColumnType.Bid || _curr_column.column_type == ColumnType.Ask)) { + else if (_is_mouse_over && _can_send_orders && (_curr_column.column_type == ColumnType.Bid || _curr_column.column_type == ColumnType.Ask)) { double y = _curr_row * _host._settings.row_height; double x = _curr_column.x_left; Pen style = default; @@ -112,12 +116,17 @@ namespace mbts.spark { } } + Cursor _evaluate_position() { + var pos = Mouse.GetPosition(_host); + return _evaluate_position(_host._column_for_point(pos), pos, _host.columns); + } + Cursor _evaluate_position(Column column, Point point, Column[] columns) { if (columns.Length == 0) return Cursors.Arrow; switch (column.column_type) { case ColumnType.Bid: - case ColumnType.Ask: return Cursors.Hand; + case ColumnType.Ask: return _can_send_orders ? Cursors.Hand : Cursors.No; default: return Cursors.Arrow; } } diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderViewHelper.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderViewHelper.cs new file mode 100644 index 000000000..e4bbee4d5 --- /dev/null +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderViewHelper.cs @@ -0,0 +1,14 @@ +using mbts.ui; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; + +namespace mbts.ui.spark { + static class LadderViewHelper { + public static readonly DragDeltaEventHandler ColumnHeaderThumb_DragDeltaHandler = + (s, e) => + e.Handled = + s is Thumb thumb && + thumb.try_find_ancestor_of_type(out Canvas canvas) && + canvas.ActualWidth + e.HorizontalChange < canvas.MinWidth; + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml new file mode 100644 index 000000000..706ea1fa6 --- /dev/null +++ b/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml.cs b/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml.cs new file mode 100644 index 000000000..d89ecfd1b --- /dev/null +++ b/src/client/spark/Modules/Trading/Ladder/View/MiniLadderView.xaml.cs @@ -0,0 +1,29 @@ +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark { + partial class MiniLadderView : UserControl { + public MiniLadderView() => + InitializeComponent(); + + #region Settings + public static readonly DependencyProperty SettingsProperty = + WPFHelper.create_dp(nameof(Settings)); + + public mbts.spark.LadderSettings Settings { + get => GetValue(SettingsProperty) as mbts.spark.LadderSettings; + set => SetValue(SettingsProperty, value); + } + #endregion + + #region CanUserSendOrders + public static readonly DependencyProperty CanUserSendOrdersProperty = + WPFHelper.create_dp(nameof(CanUserSendOrders)); + + public bool CanUserSendOrders { + get => (bool)GetValue(CanUserSendOrdersProperty); + set => SetValue(CanUserSendOrdersProperty, value); + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs index 734e6e959..0441a6a72 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookRowVM.cs @@ -6,13 +6,10 @@ using mbts.ui; using mbts.ui.controls; using mbts.ui.shell; using System; -using System.Reactive; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; +using System.Reactive.Linq; using System.Windows.Input; using System.Windows.Media; -using System.Reactive.Linq; +using Columns = mbts.spark.OrderBookGridView.ColumnKeys; namespace mbts.spark { partial class OrderBookRowVM : DisposableViewModelBase, IEquatable, DIYGrid.IRowVM { @@ -104,6 +101,7 @@ namespace mbts.spark { public uint quantity => order.quantity(); public uint filled_quantity => order.filled(); public string last_msg => order.last_msg(); + public string filled_status_desc => order.filled_status_description(security.spec_or_default()); // Tree public bool is_parent { get => _is_parent; set => Set(ref _is_parent, value); } public bool is_child => order.has_parent(); @@ -185,54 +183,50 @@ namespace mbts.spark { public void update(OrderSecurityAlgoMeta order_tuple) { Log.assert(order_tuple.order.Key == this.order.Key, "OrderBookRowVM: update_order was called with an order with the wrong key."); - bool had_security = _security.HasValue; - var old_order_tuple = this.order_tuple; // _show_order_modify_cmd is lazy (instantiated in the default_command getter); it might be null, don't not force instantiation bool? could_modify_execute = _show_order_modify_cmd?.CanExecute(null); - OrderRecordImmutable old_order = old_order_tuple.order; + var old_order_tuple = this.order_tuple; + var dirty = ViewRefresh.get_dirty_cells(old_order_tuple, order_tuple); this.order_tuple = order_tuple; - // most cells are "render-cells," which don't use databindings - the only way to update such cells is to raise the invalidated event - bool invalidate = !( - old_order.last_change() == order.last_change() && - old_order.filled() == order.filled() && - old_order.last_price() == order.last_price() && - old_order.avg_price().Equals(order.avg_price()) && - old_order.price().Equals(order.price()) && - old_order.quantity() == order.quantity() && - old_order.last_msg() == order.last_msg()); - // however, the order-type and security cells DO use databindings - if these cells have changed, the PropertyChanged event must be raised regardless of whether or not invalidated is raised - if (old_order.order_type() != order.order_type()) + // order type + if ((Columns.OrderType & dirty) != 0) RaisePropertyChanged(nameof(order_type), nameof(order_metadata)); - if (old_order.quantity() != order.quantity()) { - RaisePropertyChanged(nameof(quantity)); - RaisePropertyChanged(nameof(is_qty_dirty)); - } - if (old_order.price() != order.price()) { + // quantity + if ((Columns.Size & dirty) != 0) + RaisePropertyChanged(nameof(quantity), nameof(is_qty_dirty)); + // price + if ((Columns.Price & dirty) != 0) { RaisePropertyChanged(nameof(price)); RaisePropertyChanged(nameof(is_price_dirty)); } - if (!had_security && _security.HasValue) { + // security + if ((Columns.Security & dirty) != 0) RaisePropertyChanged(nameof(security), nameof(security_text)); - // need to raise invalidated to refresh the price cells (the security.ContractSpec determines how they are formatted - Ticks!) - invalidate = true; - } + // badge fill if (old_order_tuple.meta?.badge_color != order_tuple.meta?.badge_color) { + // invalidate by setting to null (will be re-instantiated in the public getter) _badge_fill = null; RaisePropertyChanged(nameof(badge_fill)); } + // display name if (old_order_tuple.display_name() != order_tuple.display_name()) RaisePropertyChanged(nameof(display_name)); - if (old_order.status() != order.status()) { - invalidate = true; + // status + if ((Columns.Status & dirty) != 0) RaisePropertyChanged(nameof(status)); - } - if (old_order.last_msg() != order.last_msg()) { + // last message + if ((Columns.LastMessage & dirty) != 0) RaisePropertyChanged(nameof(last_msg)); - } + // filled status desc + if ((ViewRefresh.filled_status_desc_mask & dirty) != 0) + RaisePropertyChanged(nameof(filled_status_desc)); + // show order modify cmd if (could_modify_execute.HasValue && could_modify_execute.Value != _show_order_modify_cmd.CanExecute(null)) _show_order_modify_cmd.RaiseCanExecuteChanged(); + // always raise updated updated?.Invoke((old_order_tuple, order_tuple)); - if (invalidate) + // conditionally raise invalidated + if ((dirty & ViewRefresh.invalidate_mask) != 0) raise_invalidated(); } @@ -254,5 +248,52 @@ namespace mbts.spark { string _fmt_price(double v) => security.HasValue ? security.Value.ContractSpec.format(v) : Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string); + + static class ViewRefresh { + public const Columns + invalidate_mask = + Columns.Security | + Columns.LastChange | + Columns.Filled | + Columns.LastPrice | + Columns.AvgFilled | + Columns.Price | + Columns.Size | + Columns.Status | + Columns.ParentKey | + Columns.AttachedTargetOrderKey | + Columns.LastMessage, + filled_status_desc_mask = + Columns.Filled | + Columns.AvgFilled | + Columns.Status; + + public static Columns get_dirty_cells(OrderSecurityAlgoMeta oldval, OrderSecurityAlgoMeta newval) { + var dirty = (Columns)0; + if (oldval.security != newval.security) + dirty |= Columns.Security; + if (oldval.order.last_change() != newval.order.last_change()) + dirty |= Columns.LastChange; + if (oldval.order.filled() != newval.order.filled()) + dirty |= Columns.Filled; + if (oldval.order.last_price() != newval.order.last_price()) + dirty |= Columns.LastPrice; + if (oldval.order.avg_price() != newval.order.avg_price()) + dirty |= Columns.AvgFilled; + if (oldval.order.price() != newval.order.price()) + dirty |= Columns.Price; + if (oldval.order.quantity() != newval.order.quantity()) + dirty |= Columns.Size; + if (oldval.order.ParentKey != newval.order.ParentKey) + dirty |= Columns.ParentKey; + if (oldval.order.attached_target_order_key() != newval.order.attached_target_order_key()) + dirty |= Columns.AttachedTargetOrderKey; + if (oldval.order.status() != newval.order.status()) + dirty |= Columns.Status; + if (oldval.order.last_msg() != newval.order.last_msg()) + dirty |= Columns.LastMessage; + return dirty; + } + } } -} +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 525b0716a..3bf7fc24d 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -13,12 +13,14 @@ using mbts.ui.controls; using mbts.ui.settings; using mbts.ui.shell; using mbts.ui.utility; +using mbts.utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; +using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; using System.Windows.Controls; @@ -35,23 +37,27 @@ using Columns = mbts.spark.OrderBookGridView.ColumnKeys; namespace mbts.spark { partial class OrderBookVM : DisposableViewModelBase, IHandleRowSelection, IHandleGridSorting { const double - _min_visible_right_panel_width = 200, - _min_visible_fills_slave_grid_height = 100; + _min_right_panel_width = 200, + _min_order_params_height = 300, + _min_ladder_height = 100, + _min_fills_height = 100; readonly IBus _bus; readonly OrdersModel _model; readonly Property _current_row; - readonly Property _fills_slave_grid_is_visible; + readonly Property _fills_slave_grid_is_visible, _show_ladder, _show_fills, _show_order_params; readonly OrderBookRowCollection _row_collection; readonly OrderBookColumnCollection _columns; readonly IWindowSettingsManager _settings_manager; readonly SelectedOrderParamsMon _selected_params_mon; double _raw_right_panel_width = OrderBookStartupData.Default.right_panel_width, + _order_params_height = OrderBookStartupData.Default.order_params_height, + _ladder_height = OrderBookStartupData.Default.ladder_height, _raw_fills_slave_grid_height = OrderBookStartupData.Default.fills_slave_grid_height; OrderBookStartupData _state; bool _show_right_panel = OrderBookStartupData.Default.show_right_panel, - _is_attaching_algos, + _is_attaching_orders, _is_row_collection_populated; public OrderBookVM(IObservable owner_title, IBus bus, INotificationService notification_service, OrdersModel model, IWindowSettingsManager settings_manager, bool rows_are_initially_expanded = false) { @@ -61,6 +67,9 @@ namespace mbts.spark { order_mod_vm = new OrderParamsVM(this, AlgoDefinitionVM.create(model, OrderDataHelper.Defaults.AlgoData(), editing_permissions: AlgoEditingPermissions.AllowEditValues)); order_mod_vm.algo_vm.editing_permissions_mask = AlgoEditingPermissions.None; order_mod_vm.algo_vm.algo_root = null; + _show_ladder = backing(nameof(show_ladder), false); + _show_fills = backing(nameof(show_fills), false); + _show_order_params = backing(nameof(show_order_params), false); attach_vm = new OrderParamsVM(this, AlgoDefinitionVM.create(_model, OrderDataHelper.Defaults.AlgoData(CustomOrderDefinition.CustomOneofCase.Iceberg), editing_permissions: AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowEditValues)); _fills_slave_grid_is_visible = backing(nameof(fills_slave_grid_is_visible), false); _settings_manager = settings_manager; @@ -73,13 +82,13 @@ namespace mbts.spark { _columns.filter_changed += on_filter_changed; collapse_all_rows_command = new DelegateCommand(_row_collection.collapse_all); expand_all_rows_command = new DelegateCommand(_row_collection.expand_all); - var modify_selected_algos_async_cmd = new AsyncCommand(_modify_selected_algos_async, () => _selected_params_mon.all_active); - modify_selected_algos_command = modify_selected_algos_async_cmd; + var modify_selected_orders_async_cmd = new AsyncCommand(_modify_selected_orders_async, () => _selected_params_mon.all_active); + modify_selected_orders_cmd = modify_selected_orders_async_cmd; var send_attached_orders_async_cmd = new AsyncCommand(send_attached_orders_async, () => _selected_params_mon.all_active); send_attached_orders_cmd = send_attached_orders_async_cmd; - cancel_attach_orders_cmd = new DelegateCommand(() => is_attaching_algos = false); + cancel_attach_orders_cmd = new DelegateCommand(() => is_attaching_orders = false); begin_attach_command = new DelegateCommand(() => begin_attach_algos(), () => selected_rows.Count > 0); - detach_command = new DelegateCommand(() => detach_selected_algos(), () => selected_rows.Count > 0); + detach_command = new DelegateCommand(() => detach_selected_orders(), () => selected_rows.Count > 0); toggle_show_right_panel_cmd = new DelegateCommand(() => show_right_panel = !show_right_panel); toggle_fills_slave_grid_is_visible_cmd = new DelegateCommand(() => fills_slave_grid_is_visible = !fills_slave_grid_is_visible); grid_settings_manager = _create_grid_settings_manager(owner_title, bus, notification_service, model, rows, core_columns); @@ -88,7 +97,23 @@ namespace mbts.spark { end_attaching += on_end_attaching; concat_disposable( connect_common_selected_params(order_mod_vm), + _show_ladder.Subscribe(ch => { + if (ch.newval && ladder_height < _min_ladder_height) + ladder_height = _min_ladder_height; + }), + _show_order_params.Subscribe(ch => { + if (ch.newval && order_params_height < _min_order_params_height) + order_params_height = _min_order_params_height; + }), + _show_fills.Subscribe(ch => { + if (ch.newval && fills_slave_grid_height < _min_fills_height) + fills_slave_grid_height = _min_fills_height; + }), _selected_params_mon.subscribe_all_active().Subscribe(on_all_selected_orders_active_changed), + _selected_params_mon.subscribe_security_plurality().Subscribe(p => { + security_plurality = p; + RaisePropertyChanged(nameof(security_plurality)); + }), model.on_order_tuples.OnDispatcher().Subscribe(_row_collection.update), grid_settings_manager, order_mod_vm.algo_vm.connect_data(Observable.Return(model)), @@ -96,7 +121,7 @@ namespace mbts.spark { order_mod_vm.algo_vm, bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(_selected_params_mon.on_security_md_map), attach_vm, - _fills_slave_grid_is_visible.observe_current(true) + _show_fills.observe_current(true) .Subscribe(is_visible => fills_vm.value = is_visible ? new FillsVM( bus, model, Observable.Return(FillsWindowFactory.StartupData.Default()), @@ -117,22 +142,24 @@ namespace mbts.spark { } IObservable> mk_fills_slave_predicate_src() => Observable.Create>(o => { - return selected_rows.Observe().BufferLatest(TimeSpan.FromSeconds(0.2)).OnDispatcher().Subscribe(_ => { - var keys = new HashSet(selected_rows.SelectMany(r => new[] { r }.Concat(_row_collection.get_descendent_rows(r))).Select(r => r.order_key)); - o.OnNext(ft => keys.Contains(ft.fill.OrderKey)); - }); + notify(); + return _subscribe_throttled_selected_rows().OnDispatcher().Subscribe(_ => notify()); + void notify() { + var keys = new HashSet(selected_hierarchical_rows.Select(r => r.order_key)); + o.OnNext(new Func(ft => keys.Contains(ft.fill.OrderKey))); + } }); void on_filter_changed() => _row_collection.filter = _columns.get_filter(); void on_all_selected_orders_active_changed(bool newval) { order_mod_vm.algo_vm.editing_permissions_mask = newval ? AlgoEditingPermissions.AllowEditValues : AlgoEditingPermissions.None; - modify_selected_algos_async_cmd.RaiseCanExecuteChanged(); + modify_selected_orders_async_cmd.RaiseCanExecuteChanged(); send_attached_orders_async_cmd.RaiseCanExecuteChanged(); } async Task send_attached_orders_async() { - is_attaching_algos = false; + is_attaching_orders = false; try { double price = attach_vm.price; uint size = attach_vm.size_calculator.value ?? 0; @@ -167,13 +194,7 @@ namespace mbts.spark { IDisposable connect_common_selected_params(OrderParamsVM vm) => Disposable.Create( - _selected_params_mon.subscribe_algo().Subscribe(newval => { - if (newval.HasValue) { - order_mod_vm.algo_vm.load_def(newval.Value); - } else { - order_mod_vm.algo_vm.algo_root = null; - } - }), + _selected_params_mon.subscribe_algos().Subscribe(vm.algo_vm.load_many), _selected_params_mon.subscribe_security_md().Subscribe(newval => vm.security_md = newval), _selected_params_mon.subscribe_price().Subscribe(newval => vm.price = newval), _selected_params_mon.subscribe_size().Subscribe(newval => vm.size_calculator.value = newval), @@ -211,17 +232,18 @@ namespace mbts.spark { public OrderParamsVM attach_vm { get; } public ObservableCollection selected_rows { get; } = new ObservableCollection(); public IEnumerable selected_orders => selected_rows.Select(r => r.order); + public IEnumerable selected_hierarchical_rows => selected_rows.SelectMany(r => new[] { r }.Concat(_row_collection.get_descendent_rows(r))); public _GridSettingsManager grid_settings_manager { get; } - public bool is_attaching_algos { - get => _is_attaching_algos; + public bool is_attaching_orders { + get => _is_attaching_orders; set { - if (Set(ref _is_attaching_algos, value)) + if (Set(ref _is_attaching_orders, value)) (value ? begin_attaching : end_attaching)?.Invoke(); } } public ICommand collapse_all_rows_command { get; } public ICommand expand_all_rows_command { get; } - public ICommand modify_selected_algos_command { get; } + public ICommand modify_selected_orders_cmd { get; } public ICommand send_attached_orders_cmd { get; } public ICommand cancel_attach_orders_cmd { get; } public ICommand begin_attach_command { get; } @@ -230,20 +252,38 @@ namespace mbts.spark { public ICommand toggle_fills_slave_grid_is_visible_cmd { get; } public bool show_right_panel { get => _show_right_panel; - set => Set(ref _show_right_panel, value); + set { + if (Set(ref _show_right_panel, value) && value && !(show_order_params || show_ladder || show_fills)) + show_order_params = true; + } } public double right_panel_width { - get => Math.Max(_raw_right_panel_width, _min_visible_right_panel_width); + get => Math.Max(_raw_right_panel_width, _min_right_panel_width); set => Set(ref _raw_right_panel_width, value); } + public double order_params_height { + get => _order_params_height; + set => Set(ref _order_params_height, value); + } public double fills_slave_grid_height { - get => Math.Max(_raw_fills_slave_grid_height, _min_visible_fills_slave_grid_height); + get => _raw_fills_slave_grid_height; set => Set(ref _raw_fills_slave_grid_height, value); } + public double ladder_height { + get => _ladder_height; + set => Set(ref _ladder_height, value); + } public bool is_row_collection_populated { get => _is_row_collection_populated; set => Set(ref _is_row_collection_populated, value); } + public bool show_ladder { get => _show_ladder.Value; set => _show_ladder.set(value); } + public bool show_fills { get => _show_fills.Value; set => _show_fills.set(value); } + public bool show_order_params { get => _show_order_params.Value; set => _show_order_params.set(value); } + public Plurality security_plurality { get; private set; } + + public IObservable subscribe_show_ladder() => + _show_ladder.observe_current(true); public void row_selection_changed(SelectionChangedEventArgs e) { try { @@ -274,16 +314,34 @@ namespace mbts.spark { public OrderBookStartupData create() { var (filters, sorting) = _columns.create(); var gs = grid_settings_manager.create(); - return new OrderBookStartupData(filters, gs.general.with(sorting_criterion: sorting), _show_right_panel, _raw_right_panel_width, _raw_fills_slave_grid_height, fills_slave_grid_is_visible, gs.predicate_animations, use_defaults: _settings_manager.instance_settings == null); + return new OrderBookStartupData( + filters, + gs.general.with(sorting_criterion: sorting), + _show_right_panel, + _raw_right_panel_width, + _raw_fills_slave_grid_height, + show_fills, + gs.predicate_animations, + use_defaults: _settings_manager.instance_settings == null) { + order_params_height = order_params_height, + show_ladder = show_ladder, + show_order_params = show_order_params, + ladder_height = ladder_height + }; } public void load_from(OrderBookStartupData state) { if (state == null) return; _state = state; show_right_panel = state.show_right_panel; + show_order_params = state.show_order_params; right_panel_width = state.right_panel_width; + order_params_height = state.order_params_height; fills_slave_grid_height = state.fills_slave_grid_height; fills_slave_grid_is_visible = state.fills_slave_grid_is_visible; + show_fills = state.fills_slave_grid_is_visible; + show_ladder = state.show_ladder; + ladder_height = state.ladder_height; var gs = state.grid_settings_wrapper(); if (gs != null) { grid_settings_manager.load_from(gs); @@ -328,9 +386,9 @@ namespace mbts.spark { } } - public void begin_attach_algos() => is_attaching_algos = true; + public void begin_attach_algos() => is_attaching_orders = true; - public void detach_selected_algos() => + public void detach_selected_orders() => _detach_orders(selected_rows .Where(r => r.order.can_detach()) .Select(r => this._get_branch_root(r)) @@ -404,7 +462,7 @@ namespace mbts.spark { } } - async Task _modify_selected_algos_async() { + async Task _modify_selected_orders_async() { var malgo = order_mod_vm.algo_vm.algo_root?.created_assigned(); var algo = malgo == null ? (CustomOrderDefinitionImmutable?)null : new CustomOrderDefinitionImmutable(malgo); double? price = DoubleHelper.nan_nullable(order_mod_vm.price); @@ -415,6 +473,9 @@ namespace mbts.spark { } } + IObservable> _subscribe_throttled_selected_rows() => + selected_rows.Observe().BufferLatest(TimeSpan.FromSeconds(0.2)).Select(_ => selected_rows); + static _GridSettingsManager _create_grid_settings_manager( IObservable owner_title, IBus bus, INotificationService notification_service, OrdersModel model, ObservableCollection rows, ObservableCollection columns) { // make font-weight immutable for all columns (the font-weight rule is hard-coded: Regular for root-orders, Light for all others) @@ -525,6 +586,8 @@ namespace mbts.spark { public class OrderParamsVM : DisposableViewModelBase { readonly SelectorProperty _accounts; readonly OrderBookVM _owner; + HashSet _selected_order_tree = new HashSet(); + LadderVM _ladder_vm; SecurityMD? _security_md; double _price = 0; @@ -549,7 +612,13 @@ namespace mbts.spark { Array.Empty>()); set_price_command = new DelegateCommand(p => price = p); bbo = new BBOVM { security_md = security_md }; - _dispose = Disposable.Create( bbo, algo_vm); + _dispose = new CompositeDisposable(bbo, algo_vm, + owner._subscribe_throttled_selected_rows().OnDispatcher().Subscribe(_ => { + _selected_order_tree = new HashSet(_owner.selected_hierarchical_rows.Select(r => r.order_key)); + _reset_ladder_vm(); + })) { + () => Disposable.dispose(ref _ladder_vm) + }; } public ReadOnlyObservableCollection accounts => _accounts.items; @@ -559,7 +628,8 @@ namespace mbts.spark { get => _security_md; set { if (Set(ref _security_md, value)) { - RaisePropertyChanged(nameof(security), nameof(spec)); + _reset_ladder_vm(); + RaisePropertyChanged(nameof(security), nameof(spec), nameof(ladder_vm)); bbo.security_md = value; } } @@ -568,11 +638,22 @@ namespace mbts.spark { public double price { get => _price; set => Set(ref _price, value); } public CalculatorLogic size_calculator { get; } public AlgoDefinitionVM algo_vm { get; } + public LadderVM ladder_vm => _ladder_vm; public BBOVM bbo { get; } public ICommand send_order { get; } public ICommand set_price_command { get; } OrdersModel _model => _owner._model; + + void _reset_ladder_vm() { + if (_ladder_vm == null && !_security_md.HasValue) + return; + Disposable.replace(ref _ladder_vm, + _security_md.HasValue ? + LadderVM.create_readonly(_owner._bus, new LadderModel(security_md.Value, _owner._model, new Func(osec => _selected_order_tree.Contains(osec.order.Key)))) : + null); + RaisePropertyChanged(nameof(ladder_vm)); + } } /// @@ -580,7 +661,11 @@ namespace mbts.spark { /// class SelectedOrderParamsMon { static readonly TimeSpan _throttle = TimeSpan.FromSeconds(0.1); - readonly CommonValueMonitor _algo_mon = new CommonValueMonitor(); + readonly CommonValueGroupMonitor _algo_def_mon = + new CommonValueGroupMonitor( + ask => ask, + EqualityComparer.Default, + EqualityComparer.Create(ask => ask.algo, OrderDataHelper.EqualsHelpers.custom_order_def_compareri)); readonly CommonValueMonitor _spreader_security_mon = new CommonValueMonitor(); readonly CommonValueMonitor _security_mon = new CommonValueMonitor(); readonly CommonValueMonitor _price_mon = new CommonValueMonitor(double.NaN); @@ -593,7 +678,7 @@ namespace mbts.spark { public SelectedOrderParamsMon(DynamicOrderHelper dyn_helper) { _dyn_helper = dyn_helper; - _group_mon.add_member_mon(_algo_mon, _algo_key); + _group_mon.add_member_mon(_algo_def_mon, _algo_key); _group_mon.add_member_mon(_spreader_security_mon, _get_spreader_sec, s => s.HasValue); _group_mon.add_member_mon(_security_mon, osam => osam.security, s => s.HasValue); _group_mon.add_member_mon(_price_mon, osam => osam.order.price()); @@ -604,7 +689,6 @@ namespace mbts.spark { event Action _security_md_map_changed; - public CustomOrderDefinitionImmutable? algo => _algo_mon.common_value_nullable()?.algo; public SecurityImmutable? security => _security_mon.common_value; public SecurityMD? security_md => security is SecurityImmutable sec && _security_md_map.TryGetValue(sec.Id, out SecurityMD smd) ? smd : (SecurityMD?)null; public SecurityImmutable? spreader_security => _spreader_security_mon.common_value; @@ -613,7 +697,7 @@ namespace mbts.spark { public AccountTuple? account => _account_mon.common_value_nullable(); public bool all_active => _all_active_mon.common_value; - public IObservable subscribe_algo() => _algo_mon.SubscribeThrottledNullable(_throttle).Select(ask => ask.HasValue ? ask.Value.algo: (CustomOrderDefinitionImmutable?)null); + public IObservable> subscribe_algos() => _algo_def_mon.SubscribeThrottled(_throttle, (ask, vals) => vals.Select(v => v.algo), Enumerable.Empty()); public IObservable subscribe_spreader_security() => _spreader_security_mon.SubscribeThrottled(_throttle); public IObservable subscribe_security() => _security_mon.SubscribeThrottled(_throttle); public IObservable subscribe_security_md() => @@ -637,6 +721,7 @@ namespace mbts.spark { public IObservable subscribe_size() => _size_mon.SubscribeThrottledNullable(_throttle); public IObservable subscribe_account() => _account_mon.SubscribeThrottledNullable(_throttle); public IObservable subscribe_all_active() => _all_active_mon.SubscribeThrottled(_throttle); + public IObservable subscribe_security_plurality() => _security_mon.SubscribePluralityThrottled(_throttle); public IDisposable begin_udpate() => _group_mon.defer_updates(); @@ -657,8 +742,10 @@ namespace mbts.spark { } void _on_row_updated((OrderSecurityAlgoMeta oldval, OrderSecurityAlgoMeta newval) ch) { - _group_mon.remove(ch.oldval); - _group_mon.add(ch.newval); + using (begin_udpate()) { + _group_mon.remove(ch.oldval); + _group_mon.add(ch.newval); + } } static SecurityImmutable? _get_spreader_sec(OrderSecurityAlgoMeta osam) => diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index a4819f624..ff09673f5 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -136,7 +136,7 @@ namespace mbts.spark { var detach_selected_orders_command = new SparkCommandCommand( "Detach And Cancel Selected Orders", Icons.DetachAlgos, - new DelegateCommand(_vm.detach_selected_algos, () => _vm.selected_rows.Count > 0), + new DelegateCommand(_vm.detach_selected_orders, () => _vm.selected_rows.Count > 0), new KeyGesture(Key.D, ModifierKeys.Control | ModifierKeys.Shift)); var toggle_collapse_all_command = new SparkCommandCommand("Collapse All", @@ -209,7 +209,7 @@ namespace mbts.spark { protected override void OnParentViewCreated(SparkWindowView parent_view) => Disposable.replace(ref _attachment_exit_sub, parent_view.SubscribePreviewKeyDown((s, e) => { if (e.Key == Key.Escape || (e.Key == Key.Z && KeyboardExtensions.IsCtrlDown())) - _vm.is_attaching_algos = false; + _vm.is_attaching_orders = false; })); } } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs index c39c8998b..23fa78a51 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindowFactory.cs @@ -50,10 +50,14 @@ namespace bts.shell { [ProtoContract] public class OrderBookStartupData { - const bool _default_show_right_panel = true; + const bool + _default_show_right_panel = true, + _default_show_order_params = true; const double _default_right_panel_width = 400, - _default_fills_slave_grid_height = 138; + _default_order_params_height = 250, + _default_fills_slave_grid_height = 300, + _default_ladder_height = 350; // ALREADY USED TAGS // [ProtoMember(5)] // public readonly List sort_criteria; @@ -73,6 +77,14 @@ namespace bts.shell { [ProtoMember(17)] [DefaultValue(_default_right_panel_width)] public double right_panel_width { get; set; } + // show order params + [ProtoMember(23)] + [DefaultValue(_default_show_order_params)] + public bool show_order_params { get; set; } + // order params height + [ProtoMember(24)] + [DefaultValue(_default_order_params_height)] + public double order_params_height { get; set; } // fills slave grid height [ProtoMember(18)] [DefaultValue(_default_fills_slave_grid_height)] @@ -80,6 +92,13 @@ namespace bts.shell { // fills slave grid is visible [ProtoMember(19)] public bool fills_slave_grid_is_visible { get; set; } + // ladder height + [ProtoMember(21)] + [DefaultValue(_default_ladder_height)] + public double ladder_height { get; set; } + // show ladder + [ProtoMember(22)] + public bool show_ladder { get; set; } // predicate animations [ProtoMember(20)] [Obsolete] @@ -90,8 +109,11 @@ namespace bts.shell { public OrderBookStartupData() { show_right_panel = _default_show_right_panel; + show_order_params = _default_show_order_params; right_panel_width = _default_right_panel_width; + order_params_height = _default_order_params_height; fills_slave_grid_height = _default_fills_slave_grid_height; + ladder_height = _default_ladder_height; } public OrderBookStartupData(FilterStates filters, GridSettings grid = default, bool show_right_panel = false, double right_panel_width = 0, double fills_slave_grid_height = 0, bool fills_slave_grid_is_visible = false, IEnumerable predicate_animations = null, bool use_defaults = false) { @@ -122,7 +144,10 @@ namespace bts.shell { _default_show_right_panel, _default_right_panel_width, _default_fills_slave_grid_height, - use_defaults: true); + use_defaults: true) { + show_order_params = _default_show_order_params, + order_params_height = _default_order_params_height + }; public static OrderBookGridSettings DefaultGrid => new OrderBookGridSettings(_default_general_grid); diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs index 05ca6fb04..ffe4fa7e2 100644 --- a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookGridView.xaml.cs @@ -13,33 +13,33 @@ namespace mbts.spark { // IMPORTANT: these enums are stored as strings in the general-purpose GridColumnSettings proto, and are used to ID THE COLUMNS! // Do NOT RENAME them! However, if you must, be sure to write an IShellWindowMigrationRule or something to account for backwards compatability. public enum ColumnKeys { - Security, - Symbol, - Time, - LastChange, - User, - Account, - Exchange, - TimeInForce, - OrderType, - SubType, - Side, - Size, - Price, - Filled, - AvgFilled, - LastPrice, - Status, - LastMessage, - SecurityKey, - OrderKey, - ParentKey, - AttachedTargetOrderKey, - Cancel, - EditableQty, - EditablePrice, - Attach, - Detach + Security = 1, + Symbol = 1 << 1, + Time = 1 << 2, + LastChange = 1 << 3, + User = 1 << 4, + Account = 1 << 5, + Exchange = 1 << 6, + TimeInForce = 1 << 7, + OrderType = 1 << 8, + SubType = 1 << 9, + Side = 1 << 10, + Size = 1 << 11, + Price = 1 << 12, + Filled = 1 << 13, + AvgFilled = 1 << 14, + LastPrice = 1 << 15, + Status = 1 << 16, + LastMessage = 1 << 17, + SecurityKey = 1 << 18, + OrderKey = 1 << 19, + ParentKey = 1 << 20, + AttachedTargetOrderKey = 1 << 21, + Cancel = 1 << 22, + EditableQty = 1 << 23, + EditablePrice = 1 << 24, + Attach = 1 << 25, + Detach = 1 << 26 } public OrderBookGridView() => diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml index 309394968..29a3bb24a 100644 --- a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml @@ -4,6 +4,7 @@ x:Name="Root" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + xmlns:api="clr-namespace:bts.api;assembly=spark_api" xmlns:sp="clr-namespace:mbts.spark" xmlns:u="clr-namespace:mbts.ui" xmlns:c="clr-namespace:mbts.ui.controls" @@ -21,9 +22,18 @@ 5 - 64 + + + + + + + + + + + + + + + + + + + + @ + + + + + + + + + + + + @@ -89,15 +195,15 @@ - - - - + + + + - + @@ -135,99 +241,239 @@ BorderThickness="1,0,0,0" Visibility="Collapsed" /> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + - - + + + - + - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + (No orders are selected) + + + + + + + + + + - - - - - + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs index fa4defab4..7004e8c3e 100644 --- a/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderBookView.xaml.cs @@ -1,16 +1,20 @@ +using bts.api.orderman; +using bts.utils; using mbts.ui; using mbts.ui.controls; using mbts.ui.controls.adorners; using mbts.ui.converters; using mbts.ui.extensions; using mbts.ui.spark; +using mbts.ui.utility; using mbts.utils; using System; using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; -using System.Windows.Input; using System.Windows.Media; using OrderParamsVM = mbts.spark.OrderBookVM.OrderParamsVM; @@ -18,29 +22,58 @@ namespace mbts.spark { internal partial class OrderBookView : UserControl { public const double GridSplitterWidth = 5, - GridSplitterHeight = 5, - MinAlgoEditorHeight = 64, - MinAttachOrderParamsPanelWidth = 340, - AttachOrderParamsPanelWidthRatio = 0.33; + GridSplitterHeight = 5; public static readonly IValueConverter - OrderDescriptionConverter = ValueConverter.create(row => row == null ? string.Empty : row.order.short_description(row.security)), - RightPanelVisualStateConverter = ValueConverter.create(is_modifying => is_modifying ? VisualStateNames.RightPanel.ModifyOrders : VisualStateNames.RightPanel.Normal), - FillsSlaveGridMaxHeightConverter = ValueConverter.create(right_panel_height => right_panel_height - (GridSplitterHeight + MinAlgoEditorHeight)), - FillsPanelVisualStateConverter = ValueConverter.create(show => show ? VisualStateNames.FillsPanel.Active : VisualStateNames.FillsPanel.Inactive), - FillsSlaveGridStateConverter = ValueConverter.create(is_fills_grid_visible => is_fills_grid_visible ? VisualStateNames.FillsPanel.Active : VisualStateNames.FillsPanel.Inactive), - AttachmentTargetCursorConverter = ValueConverter.create(is_active => is_active ? Cursors.Pen : Cursors.Arrow); + RightPanelVisualStateConverter = ValueConverter.create(show_panel => show_panel ? VisualStateNames.RightPanel.Active : VisualStateNames.RightPanel.Inactive), + OrderDescriptionVisualStateConverter = ValueConverter.create(row => row != null ? VisualStateNames.OrderDescription.Active : VisualStateNames.OrderDescription.Inactive), + LadderVisualStateConverter = ValueConverter.create(security_plurality => { + switch (security_plurality) { + case Plurality.None: return VisualStateNames.Ladder.NoSecuritySelected; + case Plurality.One: return VisualStateNames.Ladder.OneSecuritySelected; + case Plurality.Many: return VisualStateNames.Ladder.ManySecuritiesSelected; + default: return null; + } + }); public static readonly IMultiValueConverter - RightPanelDialogSkirtLeftAnchorConverter = ValueConverter.create((canvas_width, skirt_width) => canvas_width - skirt_width + GridSplitterWidth); + RightPanelDialogSkirtLeftAnchorConverter = ValueConverter.create((canvas_width, skirt_width) => canvas_width - skirt_width + GridSplitterWidth), + SlaveDataVisualStateConverter = ValueConverter.create( + (show_order_params, show_fills, show_ladder) => { + VisualStateNames.SlaveData.Data d = (VisualStateNames.SlaveData.Data)0; + if (show_order_params) + d |= VisualStateNames.SlaveData.Data.OrderParams; + if (show_fills) + d |= VisualStateNames.SlaveData.Data.Fills; + if (show_ladder) + d |= VisualStateNames.SlaveData.Data.Ladder; + return VisualStateNames.SlaveData.fmt_name(d); + }); IDisposable _attach_op; public OrderBookView(OrderBookVM vm) { InitializeComponent(); DataContext = vm; + // 'send attach orders' behavior vm.begin_attaching += begin_attach_orders; vm.end_attaching += () => Disposable.dispose(ref _attach_op); + // 'scroll to current order' behavior (mini ladder) + vm.SubscribeDisposed(vm.subscribe_show_ladder().SubscribeHookLatest(show => show ? connect_mini_ladder_auto_scroll() : null)); + IDisposable connect_mini_ladder_auto_scroll() { + bool is_busy = false; + vm.selected_order_changed += on_selected_order_changed; + return Disposable.Create(() => vm.selected_order_changed -= on_selected_order_changed); + async void on_selected_order_changed(OrderRecordImmutable? order) { + if (order.HasValue && !is_busy) { + is_busy = true; + await Task.Delay(200); + if (vm.current_order.HasValue && vm.current_order.Value.security_key() == ladder.ladder_grid_host.security.Id && vm.current_order.Value.is_active()) + ladder.ladder_grid_host.scroll_to_price(vm.current_order.Value.price()); + is_busy = false; + } + } + } } public new OrderBookVM DataContext { @@ -55,7 +88,11 @@ namespace mbts.spark { var attach_orders_view = new OrderParamsPanel { DataContext = vm, Margin = new Thickness(6), - ShowAlgoTypeNodes = true + CanUserChangeAlgoRoot = true, + ShowAccount = false, + ShowTimeInForce = false, + ShowCalculatorButtons = false, + ShowBBO = false }; attach_orders_view.SetBinding(OrderParamsPanel.PriceProperty, new Binding(nameof(OrderParamsVM.price)) { Source = vm }); attach_orders_view.SetBinding(OrderParamsPanel.SizeProperty, new Binding($"{nameof(CalculatorLogic.value)}") { Source = vm.size_calculator }); @@ -95,7 +132,8 @@ namespace mbts.spark { VerticalPosition.Middle, 0, orders_grid.RowHeight) { - OpenRelativeToMouse = true + OpenRelativeToMouse = true, + ClipToBounds = true }; popup_adorner.attach(); popup_adorner.IsOpen = true; @@ -107,7 +145,7 @@ namespace mbts.spark { () => { popup_adorner.IsOpen = false; popup_adorner.detach(); - DataContext.is_attaching_algos = false; + DataContext.is_attaching_orders = false; } }; } @@ -117,17 +155,51 @@ namespace mbts.spark { public const string GroupName = nameof(RightPanel); public static readonly string - Normal = $"{GroupName}{nameof(Normal)}", - ModifyOrders = $"{GroupName}{nameof(ModifyOrders)}"; + Active = $"{GroupName}{VisualStates.Active}", + Inactive = $"{GroupName}{VisualStates.Inactive}"; } - public static class FillsPanel { - public const string GroupName = nameof(FillsPanel); + public static class OrderDescription { + public const string GroupName = nameof(OrderDescription); public static readonly string Active = $"{GroupName}{VisualStates.Active}", Inactive = $"{GroupName}{VisualStates.Inactive}"; } + + public static class Ladder { + public const string GroupName = nameof(Ladder); + + public static readonly string + NoSecuritySelected = $"{GroupName}{nameof(NoSecuritySelected)}", + OneSecuritySelected = $"{GroupName}{nameof(OneSecuritySelected)}", + ManySecuritiesSelected = $"{GroupName}{nameof(ManySecuritiesSelected)}"; + } + + public static class SlaveData { + public const string GroupName = nameof(SlaveData); + + public static readonly string + None = $"{GroupName}{nameof(None)}", + OrderParams = $"{GroupName}{nameof(OrderParams)}", + OrderParamsLadder = $"{GroupName}{nameof(OrderParamsLadder)}", + OrderParamsFills = $"{GroupName}{nameof(OrderParamsFills)}", + OrderParamsLadderFills = $"{GroupName}{nameof(OrderParamsLadderFills)}", + LadderFills = $"{GroupName}{nameof(LadderFills)}", + Ladder = $"{GroupName}{nameof(Ladder)}", + Fills = $"{GroupName}{nameof(Fills)}"; + + public enum Data { + OrderParams = 1, + Ladder = 1 << 1, + Fills = 1 << 2 + } + + public static string fmt_name(Data d) { + var vis_data = string.Join("", EnumHelper.split_flags(d)); + return vis_data == string.Empty ? None : GroupName + vis_data; + } + } } } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml index c67a096aa..f29db7f3e 100644 --- a/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml +++ b/src/client/spark/Modules/Trading/OrderBook/View/OrderParamsPanel.xaml @@ -1,14 +1,26 @@  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -30,10 +100,16 @@ - + + - + @@ -84,7 +160,8 @@ - + +