From 3e7e57276325d93a033c8c54a8ad95b701025a02 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:43:43 -0500 Subject: [PATCH 01/30] move/rename 'SimpleGridSettingsDialog' -> 'ShellSettingsDialog' --- .../spark/Modules/Market/MarketView/MarketViewWindow.cs | 2 +- .../Modules/Market/TimeAndSales/TimeAndSalesWindow.cs | 2 +- .../spark/Modules/Spreader/SyntheticManagementWindow.cs | 2 +- src/client/spark/Modules/Trading/Fills/FillsWindow.cs | 2 +- src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs | 2 +- src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs | 2 +- .../spark/Modules/Trading/OrderBook/OrderBookWindow.cs | 2 +- .../Settings/ShellSettingsDialog.xaml} | 8 ++++---- .../Settings/ShellSettingsDialog.xaml.cs} | 6 +++--- src/client/spark/view/Spark/PAndL/PAndLWindow.cs | 2 +- 10 files changed, 15 insertions(+), 15 deletions(-) rename src/client/spark/view/{Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml => Shell/Settings/ShellSettingsDialog.xaml} (94%) rename src/client/spark/view/{Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs => Shell/Settings/ShellSettingsDialog.xaml.cs} (68%) diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 10d875227..4f8ed89b2 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -156,7 +156,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Market View Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Market View Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index b075d16ef..297d874e7 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -82,7 +82,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Time and Sales Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Time and Sales Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index 86d656b3e..be568334e 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -87,7 +87,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 9c4e93dab..79e745e26 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -72,7 +72,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = $"{window_type_name} Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = $"{window_type_name} Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 350ce7c72..c5874acef 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -136,7 +136,7 @@ namespace mbts.spark { svm.load(s); return svm; }, s => s.with_window_specifics(get_save_state().get_window_specifics())); - var dialog = new ui.spark.SimpleGridSettingsDialog { + var dialog = new ui.spark.ShellSettingsDialog { DataContext = vm, Title = $"Ladder Settings - '{security}'" }; diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index e92d0d929..b9a1f3386 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -137,7 +137,7 @@ namespace mbts.spark { ), show_save_as_defaults: false); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = title, DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = title, DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })); diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index a13669bda..9d718ff15 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -175,7 +175,7 @@ namespace mbts.spark { } ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { DataContext = gs_vm }; + var dialog = new ShellSettingsDialog { DataContext = gs_vm }; dialog.SetBinding(Window.TitleProperty, new Binding($"{nameof(gs_vm.instance_vm)}.{nameof(OrderBookGridSettingsVM.owner_title)}") { Converter = ValueConverter.create(str => (string.IsNullOrEmpty(str) ? _default_title : str) + " Settings") }); diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml similarity index 94% rename from src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml rename to src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml index d114c1cb1..b0b7afeca 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml @@ -1,5 +1,5 @@  - + - + @@ -82,7 +82,7 @@ - + diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs similarity index 68% rename from src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs rename to src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs index d69574424..098ff1e2e 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/SimpleGridSettingsDialog.xaml.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml.cs @@ -2,10 +2,10 @@ namespace mbts.ui.spark { /// - /// Interaction logic for SimpleGridSettingsDialog.xaml + /// Interaction logic for ShellSettingsDialog.xaml /// - public partial class SimpleGridSettingsDialog : Window { - public SimpleGridSettingsDialog() => + public partial class ShellSettingsDialog : Window { + public ShellSettingsDialog() => InitializeComponent(); public const string ResetToFactoryKey = "Reset", CopyFromOtherKey = "Copy"; diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index 67524836d..28e6466d8 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -69,7 +69,7 @@ namespace mbts.spark { ) ); // TODO: bind to main window's Title - var dialog = new SimpleGridSettingsDialog { Title = "PnL Grid Settings", DataContext = vm }; + var dialog = new ShellSettingsDialog { Title = "PnL Grid Settings", DataContext = vm }; vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; })) From 8add53a559e9f664db3ffeacceddf745784bf770 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:44:18 -0500 Subject: [PATCH 02/30] move/rename 'WindowSettingsDialogVM' -> 'ShellSettingsDialogVM' --- .../spark/Modules/Market/MarketView/MarketViewWindow.cs | 2 +- .../spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs | 2 +- .../spark/Modules/Spreader/SyntheticManagementWindow.cs | 2 +- src/client/spark/Modules/Trading/Fills/FillsWindow.cs | 2 +- src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs | 2 +- src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs | 2 +- src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs | 2 +- .../Settings/ShellSettingsDialogVM.cs} | 4 ++-- src/client/spark/view/Spark/PAndL/PAndLWindow.cs | 2 +- 9 files changed, 10 insertions(+), 10 deletions(-) rename src/client/spark/view/{Spark/Utilities/WindowSettingsDialogVM.cs => Shell/Settings/ShellSettingsDialogVM.cs} (89%) diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs index 4f8ed89b2..a9652edcf 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewWindow.cs @@ -144,7 +144,7 @@ namespace mbts.spark { SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.market_view_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs index 297d874e7..8ab059534 100644 --- a/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/Modules/Market/TimeAndSales/TimeAndSalesWindow.cs @@ -70,7 +70,7 @@ namespace mbts.spark { SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)), // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, s => s.time_and_sales_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index be568334e..6cfa693d2 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -75,7 +75,7 @@ namespace mbts.spark { }; return ob_settings; }), SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.synthetic_management_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs index 79e745e26..20c36e90d 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsWindow.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsWindow.cs @@ -60,7 +60,7 @@ namespace mbts.spark { _commands = new List { // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.fills_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index c5874acef..351615776 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -129,7 +129,7 @@ namespace mbts.spark { show_book_command = new DelegateCommand(_show_book); show_ticket_command = new DelegateCommand(_show_ticket); settings_command = new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( settings_manager, s => s.ladder, UserSettings.FileExtensions.LADDER, s => { var svm = new LadderSettingsVM(model.order_gateway, security.ContractCase == Security.ContractOneofCase.Synthetic, () => left_panel_width, () => zoom_factor); diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index b9a1f3386..53d35ecbb 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -125,7 +125,7 @@ namespace mbts.spark { toggle_show_fills_cmd = new DelegateCommand(() => show_fills = !show_fills); launch_fills_settings_cmd = concated_disposable(new DialogCommand(() => { const string title = "Order Book 'Mini' Fills Grid"; - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _fills_settings_manager, us => us.fills_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs index 9d718ff15..fa89ed3de 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookWindow.cs @@ -161,7 +161,7 @@ namespace mbts.spark { toggle_expand_all_command.group = CommandGroups.Auxiliary; var show_grid_settings_command = SparkCommands.window_settings_command(new DialogCommand(() => { - var gs_vm = new WindowSettingsDialogVM( + var gs_vm = new ShellSettingsDialogVM( _settings_manager, us => us.order_book_grid, UserSettings.FileExtensions.GRID, diff --git a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs similarity index 89% rename from src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs rename to src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs index 4340f2724..90649db2a 100644 --- a/src/client/spark/view/Spark/Utilities/WindowSettingsDialogVM.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs @@ -11,13 +11,13 @@ namespace mbts.spark { T get_result(); } - class WindowSettingsDialogVM : ViewModelBase, IRequestViewClose, IDisposable where T : class, IEquatable where TVM : IWindowSettingsVM { + class ShellSettingsDialogVM : ViewModelBase, IRequestViewClose, IDisposable where T : class, IEquatable where TVM : IWindowSettingsVM { readonly Property _use_default; readonly DialogSkirtItem _ok_item, _apply_item, _cancel_item, _apply_to_defaults_item; readonly DelegateProperty> _left_skirt_items; readonly List _resources = new List(2); // initialize with 2 capacity bc the only potential disposables are the instance/default vms - public WindowSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null, bool show_save_as_defaults = true) { + public ShellSettingsDialogVM(IWindowSettingsManager settings_manager, Func get_factory_settings, string settings_file_ext, Func vm_factory, Func merge_with_current = null, bool show_save_as_defaults = true) { if (merge_with_current == null) merge_with_current = s => s; // by default, each new window will use their own instance settings diff --git a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs index 28e6466d8..4efa927b1 100644 --- a/src/client/spark/view/Spark/PAndL/PAndLWindow.cs +++ b/src/client/spark/view/Spark/PAndL/PAndLWindow.cs @@ -57,7 +57,7 @@ namespace mbts.spark { _view.DataContext = _vm; _commands = new List { SparkCommands.window_settings_command(new DialogCommand(() => { - var vm = new WindowSettingsDialogVM( + var vm = new ShellSettingsDialogVM( _settings_manager, us => us.pnl_grid, UserSettings.FileExtensions.GRID, From 67de7c5a33f85e5cbe970588af467cb636308290 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:44:52 -0500 Subject: [PATCH 03/30] clean up Spark.csproj --- src/client/spark/Spark.csproj | 63 +---------------------------------- 1 file changed, 1 insertion(+), 62 deletions(-) diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index 914c9f524..f7ada36af 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -52,12 +52,6 @@ - - - - - - @@ -68,60 +62,5 @@ - - - - - - - Code - - - Code - - - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - MSBuild:Compile - - - - - + From 512175966d276e4d179eb30b226abac556327cf5 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:45:19 -0500 Subject: [PATCH 04/30] KeyedStyleSelector._try_get_item_key returns false if key is found but null --- src/client/spark/view/Utility/KeyedStyleSelector.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/spark/view/Utility/KeyedStyleSelector.cs b/src/client/spark/view/Utility/KeyedStyleSelector.cs index be8fe33d5..043b66483 100644 --- a/src/client/spark/view/Utility/KeyedStyleSelector.cs +++ b/src/client/spark/view/Utility/KeyedStyleSelector.cs @@ -26,7 +26,7 @@ namespace mbts.ui { protected virtual bool _try_get_item_key(object item, out TKey result) { if (item is IStyleSelectorKey ssk) { result = ssk.key; - return true; + return result != null; } result = default; return false; From 7a31adcc1ed2cf6275cb5686fdc4c975b05c2a7a Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:45:52 -0500 Subject: [PATCH 05/30] added DictionaryHelper.key_comparer() --- .../Extensions/DictionaryExtensions.cs | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs index e1f450d91..ac6be385d 100644 --- a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs @@ -246,11 +246,30 @@ namespace System.Collections.Generic { public static class DictionaryHelper { public static IReadOnlyDictionary empty() => - Empty.value; + Impl.empty; - static class Empty { - public static readonly IReadOnlyDictionary value = + public static IComparer> key_comparer() => + Impl.key_comparer; + + static class Impl { + public static readonly IReadOnlyDictionary empty = new ReadOnlyDictionary(new Dictionary(0)); + + public static readonly IComparer> key_comparer = + new KeyComparer(Comparer.Default); + + class KeyComparer : IComparer>, IComparer { + readonly IComparer _comparer; + + public KeyComparer(IComparer comparer) => + _comparer = comparer; + + public int Compare(KeyValuePair x, KeyValuePair y) => + _comparer.Compare(x.Key, y.Key); + + public int Compare(object x, object y) => + x is KeyValuePair xkv ? (y is KeyValuePair ykv ? Compare(xkv, ykv) : 1) : -1; + } } } } \ No newline at end of file From 6d069f517443a492708e82c12c5754d8f0dc0480 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:46:14 -0500 Subject: [PATCH 06/30] added ListExtensions.WrapSkip() (returns an IList impl that skips the first n items in the source list) --- .../Collections/Extensions/ListExtensions.cs | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/src/client/spark_core/Collections/Extensions/ListExtensions.cs b/src/client/spark_core/Collections/Extensions/ListExtensions.cs index a056e754f..194085d20 100644 --- a/src/client/spark_core/Collections/Extensions/ListExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/ListExtensions.cs @@ -116,6 +116,9 @@ namespace bts.collections { public static IList WrapSubRange(this IList list, int start, int length) => new SubRangeWrapper(list, start, length); + public static IList WrapSkip(this IList list, int skip) => + new SkipFrontWrapper(list, skip); + public static IList WrapSelector(this IList list, Func convert, Func convert_back = null) => new SelectorWrapper(list, convert, convert_back); @@ -408,5 +411,69 @@ namespace bts.collections { public void RemoveAt(int index) => _source.RemoveAt(index); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } + + class SkipFrontWrapper : IList, IReadOnlyList { + readonly IList _source; + readonly int _skip; + + public SkipFrontWrapper(IList source, int skip) { + _source = source; + _skip = skip; + } + + public T this[int index] { + get => _source[_skip + index]; + set => _source[_skip + index] = value; + } + + public int Count { + get { + int c = _source.Count; + return c > _skip ? (c - _skip) : 0; + } + } + + public bool IsReadOnly => _source.IsReadOnly; + + public void Add(T item) => _source.Add(item); + public void Clear() { + int c = Count; + if (c == 0) + return; + if (_source is List l) { + l.RemoveRange(_skip, c); + } else { + for (int i = 0; i < c; i++) + _source.RemoveAt(_skip); + } + } + public bool Contains(T item) => IndexOf(item) >= 0; + public void CopyTo(T[] array, int arrayIndex) { + arrayIndex -= _skip; + for (int i = _skip; i < _source.Count; i++) + array[arrayIndex + i] = _source[i]; + } + public IEnumerator GetEnumerator() { + for (int i = _skip; i < _source.Count; i++) + yield return _source[i]; + } + public int IndexOf(T item) { + for (int i = _skip; i < _source.Count; i++) { + if (_source[i].Equals(item)) + return i - _skip; + } + return -1; + } + public void Insert(int index, T item) => _source.Insert(index + _skip, item); + public bool Remove(T item) { + int i = IndexOf(item); + if (i >= 0) { + _source.RemoveAt(i + _skip); + return true; + } else return false; + } + public void RemoveAt(int index) => _source.RemoveAt(index + _skip); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } } } \ No newline at end of file From be42f9e583f17aed167adf458896a9ff9f1726f1 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:46:50 -0500 Subject: [PATCH 07/30] general purpose ToolBar view --- src/client/spark/Themes/generic.xaml | 1 + .../spark/view/Controls/ToolBar/ToolBar.xaml | 226 ++++++++++++++++++ 2 files changed, 227 insertions(+) create mode 100644 src/client/spark/view/Controls/ToolBar/ToolBar.xaml diff --git a/src/client/spark/Themes/generic.xaml b/src/client/spark/Themes/generic.xaml index 27edee3ec..52e66ff7d 100644 --- a/src/client/spark/Themes/generic.xaml +++ b/src/client/spark/Themes/generic.xaml @@ -14,6 +14,7 @@ + diff --git a/src/client/spark/view/Controls/ToolBar/ToolBar.xaml b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml new file mode 100644 index 000000000..d0633f245 --- /dev/null +++ b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml @@ -0,0 +1,226 @@ + + + 4 + 8 + 240 + #FFE8EDF9 + #FFC5CBF9 + #FF888888 + + #FFC5CBF9 + #FFDDDDDD + + White + #FFCCCCCC + #FFAAAAAA + #200080FF + #800080FF + #FFE5E5E5 + #FFF0F0F0 + + + #FF888888 + #FF888888 + #80DADADA + #90006CD9 + #FFAAAAAA + Black + + + + + + + + + + + + + + \ No newline at end of file From 69f3f1f467c2c26bcd7be8b17b67e36ca901a739 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:47:26 -0500 Subject: [PATCH 08/30] normalize line endings in Converters.xaml (why does it feel like i've done this before?) --- src/client/spark/view/Resources/Converters.xaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/client/spark/view/Resources/Converters.xaml b/src/client/spark/view/Resources/Converters.xaml index f31f2aef3..12ef41b11 100644 --- a/src/client/spark/view/Resources/Converters.xaml +++ b/src/client/spark/view/Resources/Converters.xaml @@ -83,7 +83,7 @@ - - + + From 5ddb0f92ea8b0020557170042994988b30756203 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 13 Jun 2019 00:24:43 -0500 Subject: [PATCH 09/30] ObservantCommand impl was not updating 'CanExecute' --- src/client/spark/core/Commands/ObservantCommand.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/client/spark/core/Commands/ObservantCommand.cs b/src/client/spark/core/Commands/ObservantCommand.cs index dfa053196..ccf8d19c0 100644 --- a/src/client/spark/core/Commands/ObservantCommand.cs +++ b/src/client/spark/core/Commands/ObservantCommand.cs @@ -45,8 +45,10 @@ namespace mbts.ui { var cmd = new DelegateCommand(() => execute(param), () => can_execute); observer = new AnonymousObserver(p => { param = p; - if (can_execute != get_can_execute(param)) + if (can_execute != get_can_execute(param)) { + can_execute = !can_execute; cmd.RaiseCanExecuteChanged(); + } }); return cmd; } From bef46390beeb17e2afd2f07448a5d407b77eb52f Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 13 Jun 2019 16:53:44 -0500 Subject: [PATCH 10/30] ContractPickerPopup - remove automatic Header binding, so callers may override it --- .../spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml | 1 + .../spark/Modules/Trading/ManualFills/ManualFillsView.xaml | 1 + .../spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml | 1 + .../spark/view/Spark/ContractPicker/ContractPickerPopup.xaml | 1 - 4 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml index 18da3c039..c8673c321 100644 --- a/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml +++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillRowEditor.xaml @@ -65,6 +65,7 @@ SecurityMap="{DynamicResource ResourceKey={x:Static usp:ManualFillRowEditor.SecuritiesKey}}" SelectedSecurity="{Binding security}" ShowDialogSkirt="True" + ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" /> diff --git a/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml index 22f954abb..1b16271ff 100644 --- a/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml +++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsView.xaml @@ -145,6 +145,7 @@ SecurityMap="{Binding DataContext.security_map, RelativeSource={RelativeSource AncestorType=DataGrid}, Mode=OneWay}" SelectedSecurity="{Binding security, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ShowDialogSkirt="True" + ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" /> diff --git a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml index be5ca7445..88fd35b7f 100644 --- a/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml +++ b/src/client/spark/view/Controls/DIYGrid/Settings/GridSettingsView.xaml @@ -230,6 +230,7 @@ SelectedCriteria="{Binding value}" SecurityMap="{Binding Path='[security_map]', UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" Header="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}}" + ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" /> diff --git a/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml b/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml index 6bc4b493e..35af16a13 100644 --- a/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml +++ b/src/client/spark/view/Spark/ContractPicker/ContractPickerPopup.xaml @@ -5,7 +5,6 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sp="clr-namespace:mbts.spark" xmlns:c="clr-namespace:mbts.ui.controls" - ToolTip="{Binding SelectedCriteria, RelativeSource={RelativeSource Self}, Converter={x:Static c:ContractPickerPopup.SecurityCriteriaTextConverter}, Mode=OneWay}" ShowExpanderArrow="False" Padding="2,0" > From 7c329ceebe1ed11c4ad6e9bc92f1500b9cc4014a Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 13 Jun 2019 11:16:09 -0500 Subject: [PATCH 11/30] DisposableViewModelBase - initialize '_observable_properties' lazily in property getter --- src/client/spark/core/Utility/ViewModelBase.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index 3fafe9d08..dce4db9d0 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -592,7 +592,8 @@ namespace mbts.ui.shell { public abstract class DisposableViewModelBase : ViewModelBaseWithValidation, IPropertyChangedDemuxer, IDisposable, IWillLetYouKnowWhenIDispose { protected IDisposable _dispose = null; - private List _observable_properties; + List _observable_properties_backing; + List _observable_properties => _observable_properties_backing ?? (_observable_properties_backing = new List()); PropertyChangedDemuxer _property_changed_demuxer_backing; IPropertyChangedDemuxer _property_changed_demuxer => @@ -607,7 +608,6 @@ namespace mbts.ui.shell { internal IPropertyChangedDemuxer as_demuxer() => this; protected Property backing(string name, IObservable source, T default_value = default(T)) { - if (_observable_properties == null) _observable_properties = new List(); var prop = new ObservablePropertySink(this, name, default_value); _observable_properties.Add(source.Subscribe(prop)); return prop; @@ -618,7 +618,6 @@ namespace mbts.ui.shell { /// Note: UI settings in particular may find this useful, as brushes and other Freezable types are not inherently thread safe. /// protected Property backing(string name, IObservable source, Func select, T default_value = default) { - if (_observable_properties == null) _observable_properties = new List(); var prop = new ObservablePropertySink(this, name, default_value); _observable_properties.Add(source.OnDispatcher().Subscribe(d => prop.set(select(d)))); return prop; @@ -685,7 +684,6 @@ namespace mbts.ui.shell { } protected void attach(SelectorProperty selector_property, IObservable> items, IObservable> desired_item) { - if (_observable_properties == null) _observable_properties = new List(); _observable_properties.Add(items.OnDispatcher().Subscribe(selector_property)); _observable_properties.Add(desired_item.OnDispatcher().Subscribe(selector_property)); } @@ -722,7 +720,7 @@ namespace mbts.ui.shell { protected virtual void Dispose(bool disposing) { } public void Dispose() { Disposable.dispose(ref _dispose); - Disposable.dispose(_observable_properties); + Disposable.dispose(_observable_properties_backing); Disposable.dispose(ref _property_changed_demuxer_backing); Dispose(true); OnDisposed?.Invoke(true); From 82a9b4521a09fbd220b3218b0518182d0ea30f53 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Thu, 13 Jun 2019 11:25:21 -0500 Subject: [PATCH 12/30] DisposableViewModelBase - in subscribe(), use the _property_changed_demuxer via the property (which lazily inits the backing) --- src/client/spark/core/Utility/ViewModelBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/spark/core/Utility/ViewModelBase.cs b/src/client/spark/core/Utility/ViewModelBase.cs index dce4db9d0..3800e98bf 100644 --- a/src/client/spark/core/Utility/ViewModelBase.cs +++ b/src/client/spark/core/Utility/ViewModelBase.cs @@ -599,7 +599,7 @@ namespace mbts.ui.shell { IPropertyChangedDemuxer _property_changed_demuxer => _property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this)); - IObservable IPropertyChangedDemuxer.subscribe(string property) => (_property_changed_demuxer_backing ?? (_property_changed_demuxer_backing = new PropertyChangedDemuxer(this))).subscribe(property); + IObservable IPropertyChangedDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); IObservable IObservableDemuxer.subscribe(string property) => _property_changed_demuxer.subscribe(property); void IObserver.OnNext(PropertyChangedEventArgs value) => _property_changed_demuxer.OnNext(value); void IObserver.OnError(Exception error) => _property_changed_demuxer.OnError(error); From 666765ffbbddfbf659748506dff9d24d74dfc9af Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 16 Jun 2019 12:25:07 -0500 Subject: [PATCH 13/30] LadderSettingsVM implements IObservable --- .../Trading/Ladder/VM/LadderSettingsVM.cs | 163 +++++++++++++----- 1 file changed, 116 insertions(+), 47 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index e1c33486b..aac89a1c2 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -11,6 +11,8 @@ using mbts.ui.utility; using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using System.Windows; @@ -19,10 +21,11 @@ using System.Windows.Media; using TextUtils = mbts.ui.utility.text.TextUtils; namespace mbts.spark { - class LadderSettingsVM : ViewModelBase, IWindowSettingsVM, ITemplateSelectorKey, IDisposable { + class LadderSettingsVM : DisposableViewModelBase, IWindowSettingsVM, IValueFactory, IObservable, ITemplateSelectorKey { readonly Property _badge_style; readonly Property _alternate_order_size; readonly DelegateProperty _row_height; + readonly DeferrableActionWrapper _update; LadderSettings.NetChangeTerms _price_format; Func _get_order_entry_panel_width, _get_zoom_factor; LadderSettings _current; @@ -79,10 +82,25 @@ namespace mbts.spark { _ask.font_size_changed += on_font_size_changed; _last.font_size_changed += on_font_size_changed; _piq.font_size_changed += on_font_size_changed; - + // update + _update = new DeferrableActionWrapper(() => result_changed?.Invoke()); + foreach (var c in _observable_components) + c.PropertyChanged += on_prop_changed; + favorite_algos_vm.items.CollectionChanged += on_favorite_algo_items_CollectionChanged; + _dispose = Disposable.Create(() => { + favorite_algos_vm.items.CollectionChanged -= on_favorite_algo_items_CollectionChanged; + favorite_algos_vm.Dispose(); + foreach (var c in _observable_components) + c.PropertyChanged -= on_prop_changed; + }); + // local methods void on_font_size_changed(double oldval, double newval) => _row_height.refresh(); + void on_prop_changed(object sender, PropertyChangedEventArgs e) => _update.execute(); + void on_favorite_algo_items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => _update.execute(); } + public event Action result_changed; + private void _badge_style_Changed(LadderSettings.BadgeStyle oldval, LadderSettings.BadgeStyle newval) { if (newval == LadderSettings.BadgeStyle.Alternate && _orders.font_size == 10) { _orders.font_size = 7; @@ -172,49 +190,95 @@ namespace mbts.spark { public string key => GridSettingsTemplateKeys.Ladder; + IEnumerable _observable_components { + get { + // columns + yield return _orders; + yield return _bid; + yield return _price; + yield return _ask; + yield return _last; + yield return _piq; + yield return _volume; + yield return _volume.general; + // market break lines + yield return _bid_mkt_line; + yield return _ask_mkt_line; + yield return _mid_mkt_line; + yield return _session_low_mkt_line; + yield return _session_high_mkt_line; + yield return _session_range_fill; + // left panel + yield return _zoom_slider_visbility; + yield return _day_visibility; + yield return _high_visibility; + yield return _low_visibility; + yield return _open_visibility; + yield return _settle_visibility; + yield return _volume_visibility; + yield return _account_visibility; + yield return _tif_visibility; + yield return _order_type_visibility; + yield return _account_position_visibility; + yield return _day_position_visibility; + yield return _size_preset_visibility; + yield return _auto_clear_visibility; + yield return _clear_visibility; + yield return _cancel_buys_visibility; + yield return _cancel_sells_visibility; + yield return _cancel_all_visibility; + // other + yield return size_display; + yield return favorite_algos_vm; + yield return this; + } + } + public void load(LadderSettings settings) { - _current = settings; - badge_style = settings.badge_style; - alternate_order_size = settings.alternate_order_size; - 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))); - _orders.assign_from(_current.orders_column); - _bid.assign_from(_current.bid_column); - _ask.assign_from(_current.ask_column); - _price.assign_from(_current.price_column); - _volume.assign_from(_current.volume_column); - _last.assign_from(_current.last_column); - _piq.assign_from(_current.piq_column); - _bid_mkt_line.assign_from(_current.bid_break_line); - _ask_mkt_line.assign_from(_current.ask_break_line); - _mid_mkt_line.assign_from(_current.mid_break_line); - _session_low_mkt_line.assign_from(_current.session_low_line); - _session_high_mkt_line.assign_from(_current.session_high_line); - _session_range_fill.assign_from(_current.session_range_fill); - _zoom_slider_visbility.show = settings.zoom_slider_visible; - _day_visibility.show = settings.day_visible; - _high_visibility.show = settings.high_visible; - _low_visibility.show = settings.low_visible; - _open_visibility.show = settings.open_visible; - _settle_visibility.show = settings.settle_visible; - _volume_visibility.show = settings.volume_visible; - _account_visibility.show = settings.account_visible; - _tif_visibility.show = settings.tif_visible; - _order_type_visibility.show = settings.order_type_visible; - _account_position_visibility.show = settings.account_position_visible; - _day_position_visibility.show = settings.day_position_visible; - _size_preset_visibility.show = settings.size_presets_visible; - _clear_visibility.show = settings.clear_visible; - _auto_clear_visibility.show = settings.auto_clear_visible; - _cancel_buys_visibility.show = settings.cancel_buys_visible; - _cancel_sells_visibility.show = settings.cancel_sells_visible; - _cancel_all_visibility.show = settings.cancel_all_visible; - price_format = settings.net_change; - // do not read the order entry panel width here from settings - // because it could have changed from the UI - // there might be a better way of doing this, like how - // does the widths of the ladder grid column pull this off? + using (_update.defer_execution()) { + _current = settings; + badge_style = settings.badge_style; + alternate_order_size = settings.alternate_order_size; + 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))); + _orders.assign_from(_current.orders_column); + _bid.assign_from(_current.bid_column); + _ask.assign_from(_current.ask_column); + _price.assign_from(_current.price_column); + _volume.assign_from(_current.volume_column); + _last.assign_from(_current.last_column); + _piq.assign_from(_current.piq_column); + _bid_mkt_line.assign_from(_current.bid_break_line); + _ask_mkt_line.assign_from(_current.ask_break_line); + _mid_mkt_line.assign_from(_current.mid_break_line); + _session_low_mkt_line.assign_from(_current.session_low_line); + _session_high_mkt_line.assign_from(_current.session_high_line); + _session_range_fill.assign_from(_current.session_range_fill); + _zoom_slider_visbility.show = settings.zoom_slider_visible; + _day_visibility.show = settings.day_visible; + _high_visibility.show = settings.high_visible; + _low_visibility.show = settings.low_visible; + _open_visibility.show = settings.open_visible; + _settle_visibility.show = settings.settle_visible; + _volume_visibility.show = settings.volume_visible; + _account_visibility.show = settings.account_visible; + _tif_visibility.show = settings.tif_visible; + _order_type_visibility.show = settings.order_type_visible; + _account_position_visibility.show = settings.account_position_visible; + _day_position_visibility.show = settings.day_position_visible; + _size_preset_visibility.show = settings.size_presets_visible; + _clear_visibility.show = settings.clear_visible; + _auto_clear_visibility.show = settings.auto_clear_visible; + _cancel_buys_visibility.show = settings.cancel_buys_visible; + _cancel_sells_visibility.show = settings.cancel_sells_visible; + _cancel_all_visibility.show = settings.cancel_all_visible; + price_format = settings.net_change; + // do not read the order entry panel width here from settings + // because it could have changed from the UI + // there might be a better way of doing this, like how + // does the widths of the ladder grid column pull this off? + } } public LadderSettings get_result() { @@ -262,7 +326,13 @@ namespace mbts.spark { return clone; } - public void Dispose() => favorite_algos_vm.Dispose(); + public IDisposable defer_updates() => _update.defer_execution(); + + IDisposable IObservable.Subscribe(IObserver observer) { + result_changed += notify; + return Disposable.Create(() => result_changed -= notify); + void notify() => observer.OnNext(get_result()); + } IMutableValueWrapperVM _create_size_preset_vm() => _create_size_preset_vm(0); IMutableValueWrapperVM _create_size_preset_vm(uint init) { @@ -408,7 +478,6 @@ namespace mbts.spark { public string name { get; } public bool show { get => _show.Value; set => _show.Value = value; } - } public class VolumeColumnVM : ViewModelBase { @@ -590,4 +659,4 @@ namespace mbts.spark { } } } -} \ No newline at end of file +} From 485991b0461c7713408ce4dd89859418b9abea47 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Mon, 17 Jun 2019 11:54:04 -0500 Subject: [PATCH 14/30] LadderSettingsVM - assume algos in settings proto exist (avoid 'deleting' favs when create is called before first algo-TableUpdate arrives) --- .../Modules/Trading/Ladder/VM/LadderSettingsVM.cs | 7 ++++++- .../spark/core/Collections/KeyedItemSelector.cs | 12 ++++++------ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index aac89a1c2..aad5be993 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -631,7 +631,12 @@ namespace mbts.spark { } public LadderFavoriteAlgosSettings create() => - new LadderFavoriteAlgosSettings(_raw_items.Where(fai => fai.algo_definition != null).Select(fai => fai.algo_definition.key).ToArray(), column_count); + new LadderFavoriteAlgosSettings(_raw_items + .Select(fai => fai.algo_definition?.key ?? fai.selector.desired_key) + .Where(k => k.HasValue) + .Select(k => k.Value) + .ToArray(), + column_count); FavoriteAlgoItem _item_factory() => new FavoriteAlgoItem(_algo_definitions, new ListCollectionView(_algo_definitions) { diff --git a/src/client/spark/core/Collections/KeyedItemSelector.cs b/src/client/spark/core/Collections/KeyedItemSelector.cs index acd629134..ad8be9565 100644 --- a/src/client/spark/core/Collections/KeyedItemSelector.cs +++ b/src/client/spark/core/Collections/KeyedItemSelector.cs @@ -128,7 +128,6 @@ namespace mbts.collections { readonly Property _value; readonly Func _key_selector; readonly string _prop_name; - TKey? _desired_key; public KeyedItemSelector(IRaiseNotifyPropertyChanged owner, string prop_name, IObservableCollection items, Func key) { _owner = owner; @@ -143,23 +142,24 @@ namespace mbts.collections { get => _value.Value; set { _value.set(value); - if (_desired_key.HasValue) { + if (desired_key.HasValue) { items.CollectionChanged -= _on_items_CollectionChanged; - _desired_key = null; + desired_key = null; } _owner.raise_notify_property_changed(_prop_name); } } + public TKey? desired_key { get; private set; } public bool try_select(TKey key) { if (items.TryGetFirst(i => _key_selector(i).Equals(key), out T result)) { value = result; return true; } else { - if (!_desired_key.HasValue) { + if (!desired_key.HasValue) { items.CollectionChanged += _on_items_CollectionChanged; } - _desired_key = key; + desired_key = key; return false; } } @@ -169,7 +169,7 @@ namespace mbts.collections { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Replace: foreach (T i in e.NewItems) - if (_key_selector(i).Equals(_desired_key.Value)) { + if (_key_selector(i).Equals(desired_key.Value)) { value = i; return; } From c40055dd2f3011db3ad5ce54c663473b2c187ed8 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 12 Jun 2019 23:47:53 -0500 Subject: [PATCH 15/30] SPARK-2493 Add multiple profiles for ladder settings --- src/client/spark/Images/Icons.cs | 2 + src/client/spark/Images/Vector/Icons.xaml | 4 + .../Trading/Ladder/LadderWindowFactory.cs | 144 +++++-- .../Trading/Ladder/VM/LadderSettingsVM.cs | 23 +- .../Modules/Trading/Ladder/VM/LadderVM.cs | 89 ++--- .../Modules/Trading/OrderBook/OrderBookVM.cs | 66 ++-- src/client/spark/Spark.csproj | 1 + .../UserSettings/ISettingsProfileService.cs | 70 ++++ .../UserSettings/SettingsProfile.cs | 79 ++++ .../UserSettings/UserSettings.cs | 36 +- .../UserSettings/UserSettingsHub.cs | 51 ++- src/client/spark/view/Colors.xaml | 7 + .../view/Controls/Dialogs/OKCancelDialog.xaml | 33 ++ .../Controls/Dialogs/OKCancelDialog.xaml.cs | 66 ++++ .../spark/view/Controls/ToolBar/ToolBar.xaml | 2 +- .../spark/view/Resources/ComboBoxes.xaml | 12 + .../Shell/Settings/ShellSettingsDialog.xaml | 366 ++++++++++++++++-- .../Settings/ShellSettingsDialog.xaml.cs | 7 +- .../Shell/Settings/ShellSettingsDialogVM.cs | 313 ++++++++++++++- .../SecurityCriteriaExtensions.cs | 3 + src/client/spark/view/Utility/WPFHelper.cs | 3 + .../Extensions/EnumerableExtensions.cs | 38 ++ 22 files changed, 1243 insertions(+), 172 deletions(-) create mode 100644 src/client/spark/core/ShellInterface/UserSettings/ISettingsProfileService.cs create mode 100644 src/client/spark/core/ShellInterface/UserSettings/SettingsProfile.cs create mode 100644 src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml create mode 100644 src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs diff --git a/src/client/spark/Images/Icons.cs b/src/client/spark/Images/Icons.cs index dcc11df03..3cc17164d 100644 --- a/src/client/spark/Images/Icons.cs +++ b/src/client/spark/Images/Icons.cs @@ -24,6 +24,7 @@ namespace mbts.ui { AddFileThinGeometryKey = nameof(AddFileThinGeometryKey), AttachAlgosKey = nameof(AttachAlgosKey), CheckMarkGeometryKey = nameof(CheckMarkGeometryKey), + CopyWFGeometryKey = nameof(CopyWFGeometryKey), DataEditGeometryKey = nameof(DataEditGeometryKey), DetachAlgosKey = nameof(DetachAlgosKey), DiskGeometryKey = nameof(DiskGeometryKey), @@ -147,6 +148,7 @@ namespace mbts.ui { public static ImageSource ModifyOrder { get { return load_resource_and_freeze("ModifyOrder"); } } public static ImageSource CheckMark => create_icon(CheckMarkGeometryKey); public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } } + public static ImageSource CopyWF => create_icon(CopyWFGeometryKey); public static ImageSource DataEdit => create_icon(DataEditGeometryKey, Brushes.White, new Pen(Brushes.Black, 1).frozen()); public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } } public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red); diff --git a/src/client/spark/Images/Vector/Icons.xaml b/src/client/spark/Images/Vector/Icons.xaml index e5c29b5e4..a0ce61363 100644 --- a/src/client/spark/Images/Vector/Icons.xaml +++ b/src/client/spark/Images/Vector/Icons.xaml @@ -48,6 +48,10 @@ + + M14.733902,12.084991L9.751783,17.388992 12.982842,17.436005C13.569886,17.462997 14.5229,17.350998 14.876848,17.005005 14.954852,16.929993 15.031879,16.824005 15.02486,16.593002 14.986895,15.457993 14.838883,13.438004 14.733902,12.084991z M22.507753,11.134453C22.480678,11.134323,22.467085,11.135494,22.469961,11.136993L20.64694,11.145004 16.291904,11.192993C16.388891,12.405991 16.596901,15.100998 16.647928,16.539001 16.668924,17.177994 16.448888,17.742004 16.007904,18.168991 15.210897,18.947998 13.893864,19.065002 13.179865,19.065002L9.2818066,19.005005 9.3258129,25.522003 9.3728109,25.528 9.3278271,25.882996 9.3317944,26.395996 9.3107983,26.397995C9.3167797,26.789993,9.3378369,27.552994,9.3958212,29.065994L9.4068075,29.393005C9.4207855,29.819992 9.5648295,29.994995 9.6707884,30.089005 9.9807898,30.365997 10.539817,30.390991 10.717799,30.369003L10.717799,30.375C10.88284,30.354996 11.280855,30.356003 12.823844,30.365997 13.867863,30.371002 15.206869,30.376999 16.594886,30.376999 20.757965,30.376999 23.270998,30.354996 23.862007,30.311005 24.454971,30.268005 24.661029,29.154999 24.690021,28.729996 24.690021,28.729996 24.677997,27.876999 24.661029,26.582993 24.612016,22.671005 24.51198,14.697998 24.472002,12.802002 24.461013,12.302994 24.316969,11.929993 24.034008,11.662003 23.547475,11.200003 22.697284,11.13536 22.507753,11.134453z M8.8867823,2.8410034L2.5417312,10.296997 6.4037791,10.356995C6.8917614,10.390991 8.3258005,10.341003 8.9567896,9.7299957 9.1738335,9.5189972 9.2667919,9.2659912 9.2558046,8.9089966 9.2067934,7.3889923 9.0258213,4.7480011 8.8867823,2.8410034z M10.424826,1.6239929C10.551842,3.302002 10.816799,6.951004 10.876797,8.8560028 10.903836,9.6750031 10.636804,10.360992 10.083818,10.897995 9.0667769,11.882004 7.3527657,11.987991 6.6627546,11.987991 6.4657918,11.987991 6.3367616,11.979004 6.3177796,11.977005L1.6477377,11.905991C1.6387044,14.278992 1.6236895,20.283997 1.6496909,22.358994 1.651705,22.569992 1.6437093,22.780991 1.6366904,22.992004 1.6117265,23.593994 1.5926833,24.112991 1.8537338,24.386002 2.0716933,24.612991 2.6497034,24.886002 4.1457549,24.886002 6.0127832,24.886002 7.0867711,24.876999 7.6967641,24.867004L7.6457993,17.259995 14.853899,9.5849915 16.681924,9.5650024 16.681924,9.5429993 19.454908,9.5289917 19.406934,2.6210022C19.323925,2.3549957,18.960945,1.6239929,17.387928,1.6239929z M9.1738335,0L17.387928,0C19.94692,0,20.874971,1.5299988,21.022983,2.4329987L21.077976,9.5209961 22.446951,9.5139923C22.43395,9.5130005 24.031017,9.4250031 25.148035,10.481995 25.753999,11.054001 26.071996,11.822998 26.092992,12.766998 26.142006,15.065994 26.281044,26.268997 26.307047,28.412003L26.311014,28.764999C26.279029,29.817993 25.750032,31.802002 23.979013,31.931 23.342958,31.977005 20.887972,32 16.683878,32 13.798893,32 11.107818,31.988998 10.808803,31.987991 10.789821,31.990997 9.5147806,32.112 8.6008288,31.309006 8.0858074,30.854996 7.8107797,30.229004 7.7838017,29.444992L7.7728153,29.126999C7.721789,27.759995 7.6978022,26.970993 7.6898061,26.490005 7.0547882,26.5 5.9867817,26.509003 4.1457549,26.509003 2.4377257,26.509003 1.3387128,26.192001 0.68367504,25.509003 -0.055286743,24.742004 -0.017322397,23.742004 0.012707477,22.938004 0.020702986,22.744003 0.028698692,22.559998 0.026684528,22.378998 -0.00029337304,20.240997 0.016674615,13.856995 0.026684528,11.212997L0.026684528,10.867004 0.14167619,10.610992 8.7147823,0.54100037 8.7088009,0.45899963 8.8018194,0.43800354z + + M10.830011,12.05L13.334007,12.05 13.334007,16.535997 17.819998,16.535997 17.819998,19.03902 13.334007,19.03902 13.334007,23.525016 10.830988,23.525016 10.830988,19.03902 6.3460046,19.03902 6.3449975,16.53499 10.830988,16.535997z M2.2799975,2.4149805L2.2799975,29.580015 22.121998,29.580015 22.121998,8.500008 15.83599,8.500008 15.83599,2.4149805z M0,0L15.83599,0 17.125998,0 22.681996,5.439977 24.407,7.125007 24.407,32.000001 0,32.000001z diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 6f3e43c41..8ea85b91b 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -6,11 +6,14 @@ using mbts.persist; using mbts.spark; using mbts.ui; using mbts.ui.spark; +using mbts.ui.utility; using ProtoBuf; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Reactive.Linq; +using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using System.Windows; @@ -52,37 +55,127 @@ namespace bts.shell { public async override Task load(LadderSaveState state) { await Wait.until_true(() => _securities.ContainsKey(state.security_key), _ladder_conf.security_timeout); if (_securities.TryGetValue(state.security_key, out SecurityMD security)) { - return create_ladder_window(security, state.settings); + return create_ladder_window(security, state.settings, state.settings_id); } return null; } - static LadderSaveState _get_state(LadderVM vm) => - new LadderSaveState { security_key = vm.security.Id, settings = vm.get_save_state() }; + LadderSaveState _get_state(LadderVM vm, uint id) { + LadderSettings s = vm.get_save_state(); + if (id != 0 && (!_settings_hub.current.ladder_profiles.TryGetFirst(lp => lp.id == id, out var result) || !s.Equals(result.value))) { + // either the profile was deleted, or the ladder settings diverged from the profile (this happens when the user changes settings outside of the settings dialog, such as column widths, left panel width, etc.) + id = 0; + } + return new LadderSaveState { security_key = vm.security.Id, settings = s, settings_id = id }; + } int _ladder_count = 0; - IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings) { - var id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; + IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings, uint settings_id = 0) { + IDisposable active_settings_dialog = null; + var thread_id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; var view = new Lazy(() => { + // resources var model = new LadderModel(md, _orders_model, _mbo); - 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 = LadderVM.create(_bus, model, settings_manager, init); + var profile_service = new SettingsProfileService(_settings_hub, + us => ImmutableDictionary>.Empty.AddRange(us.ladder_profiles.ToDictionary( + lp => lp.id, + lp => new SettingsProfile(lp.id, lp.name, sanitize_ladder_settings(lp.value), lp.security_criteria))), + (us, lps) => us.with(ladder_profiles: lps.Values.Select(lp => new LadderSettingsProfile(lp.id, lp.name, lp.value, lp.security_criteria)).ToArray())); + LadderSettings last_value = state_settings; + var settings_subject = new BehaviorSubject(last_value); + // vm + var vm = LadderVM.create(_bus, model, last_value ?? _settings_hub.current.ladder, settings_subject.Where(s => s != null)); vm.order_properties_vm.open_algo_popup_on_select = _ladder_conf.open_algo_popup_on_select; vm.order_properties_vm.use_algo_param_grid = _ladder_conf.use_algo_param_grid; + vm.request_settings_dialog += open_settings_dialog; + bool initialized = false; + var settings_subscription = _settings_hub.subscribe_default_settings().Subscribe(on_user_settings); + vm.OnDisposed += disposing => { + Disposable.dispose(ref active_settings_dialog); + Disposable.dispose(ref settings_subject); + }; + // view var lv = new LadderView(vm); foreach (var kv in AlgoStudioModelUtils.get_dynamic_resources(vm.model.order_gateway.algo_model.ui_configuration)) lv.Resources[kv.Key] = kv.Value; return lv; + // local methods + void on_user_settings(UserSettings us) { + if (initialized) { + if (settings_id == 0) { + // not on a profile, don't respond to default settings changes + return; + } else if (us.ladder_profiles.TryGetFirst(p => p.id == settings_id, out var profile)) { + if (!last_value.Equals(vm.get_save_state())) { + settings_id = 0; + } else { + settings_subject.OnNext(last_value = profile.value); + } + } else { + // profile was deleted; keep the current settings and switch to the 'Local' profile. + settings_id = 0; + } + } else if (_settings_hub.initialized) { + initialized = true; + if (settings_id != 0) { + if (us.ladder_profiles.TryGetFirst(p => p.id == settings_id, out var profile)) { + last_value = profile.value; + } else { + settings_id = 0; + } + } + if (settings_id == 0 && last_value == null) { + foreach (var lp in _settings_hub.current.ladder_profiles) { + // TODO: Use a kind of 'match priority' to resolve conflicts when the security is included in more than 1 profile's security criteria. + // In the meantime, simply use the first match. + if (lp.security_criteria.includes(md.security)) { + last_value = lp.value; + settings_id = lp.id; + break; + } + } + if (last_value == null) + last_value = _settings_hub.current.ladder; + } + settings_subject.OnNext(last_value); + } + } + + void open_settings_dialog() { + var dialog_vm = new ProfiledShellSettingsDialogVM( + profile_service, + us => us.ladder ?? LadderSettings.Default, + s => { + var svm = new LadderSettingsVM(model.order_gateway, vm.security.ContractCase == Security.ContractOneofCase.Synthetic, () => vm.left_panel_width, () => vm.zoom_factor); + svm.load(s); + return svm; + }, vm.get_save_state(), + UserSettings.FileExtensions.LADDER, + settings_id); + dialog_vm.applied += apply; + var dialog = new ShellSettingsDialog { + DataContext = dialog_vm, + Title = $"Ladder Settings - '{vm.security}'" + }; + dialog.Resources[ShellSettingsDialog.SecurityMapKey] = _securities; + dialog_vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); + Disposable.replace(ref active_settings_dialog, Disposable.Create(() => { + Disposable.dispose(ref dialog_vm); + WindowUtilities.force_close(dialog); + })); + dialog.move_to_mouse(-500, -500); + dialog.Show(); + void apply(SettingsProfile profile) { + settings_id = profile.id; + last_value = profile.value; + settings_subject.OnNext(profile.value); + } + } }); - string thread = _ladder_conf.ladders_on_threads ? $"Ladder{id:00}" : ""; + string thread = _ladder_conf.ladders_on_threads ? $"Ladder{thread_id:00}" : ""; return ShellWindow.create( module, md.security.ToString(), _window_type, view, - (v,s) => save(_get_state(((LadderView)v).vm), s), + (v,s) => save(_get_state(((LadderView)v).vm, settings_id), s), icon: Icons.Ladder, thread_id: thread); // if there are new props, make sure they are not null, invalid, etc. @@ -125,27 +218,6 @@ namespace bts.shell { } } - // TODO: whenever we re-implement the linked ladder, need to add some field to the LadderSaveState to indicate the owning window - //void show_linked(IObservable keystream) { - // var view = new LadderView(); - // IDisposable sub = null; - // var window = - // ShellWindow.create(module, "loading", view, - // Disposable.Create(() => { - // (view.DataContext as LadderVM)?.Dispose(); - // sub?.Dispose(); - // }), s => { - // var vm = view.DataContext as LadderVM; - // if (vm != null) save(_get_state(vm), s); - // }, Icons.Ladder); - // sub = - // keystream - // .Select(smd => new LadderVM(_bus, new LadderModel(smd, _orders_model), - // Observable.Return(_orders_model.factory.default_ladder_settings(smd.security))) - // ).Aggregate((old, vm) => { old.Dispose(); return vm; }) - // .Subscribe(vm => { view.DataContext = vm; window.Title = vm.security.ToString(); }); - //} - readonly struct LadderConfig { public readonly uint max_open_ladders; public readonly bool ladders_on_threads, open_algo_popup_on_select, use_algo_param_grid; @@ -167,5 +239,7 @@ namespace bts.shell { public UInt32 security_key; [ProtoMember(2)] public mbts.spark.LadderSettings settings; + [ProtoMember(3)] + public uint settings_id; } } \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index aad5be993..3bf68712d 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -8,12 +8,14 @@ using mbts.ui.controls.color_picker; using mbts.ui.shell; using mbts.ui.spark; using mbts.ui.utility; +using mbts.utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; +using System.Reactive.Disposables; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; @@ -87,16 +89,21 @@ namespace mbts.spark { foreach (var c in _observable_components) c.PropertyChanged += on_prop_changed; favorite_algos_vm.items.CollectionChanged += on_favorite_algo_items_CollectionChanged; - _dispose = Disposable.Create(() => { - favorite_algos_vm.items.CollectionChanged -= on_favorite_algo_items_CollectionChanged; - favorite_algos_vm.Dispose(); - foreach (var c in _observable_components) - c.PropertyChanged -= on_prop_changed; - }); + _dispose = new CompositeDisposable(ObservableAutoWrapper.connect_item_hooks(favorite_algos_vm.items, connect_favorite_algo)) { dispose_resources }; // local methods void on_font_size_changed(double oldval, double newval) => _row_height.refresh(); void on_prop_changed(object sender, PropertyChangedEventArgs e) => _update.execute(); void on_favorite_algo_items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => _update.execute(); + IDisposable connect_favorite_algo(FavoriteAlgoItem item) { + item.PropertyChanged += on_prop_changed; + return Disposable.Create(() => item.PropertyChanged -= on_prop_changed); + } + void dispose_resources() { + favorite_algos_vm.items.CollectionChanged -= on_favorite_algo_items_CollectionChanged; + favorite_algos_vm.Dispose(); + foreach (var c in _observable_components) + c.PropertyChanged -= on_prop_changed; + } } public event Action result_changed; @@ -334,6 +341,9 @@ namespace mbts.spark { void notify() => observer.OnNext(get_result()); } + LadderSettings IValueFactory.create() => get_result(); + void IValueFactory.load_from(LadderSettings value) => load(value); + IMutableValueWrapperVM _create_size_preset_vm() => _create_size_preset_vm(0); IMutableValueWrapperVM _create_size_preset_vm(uint init) { var vm = PropertyWrapperVMUtils.create_mutable_vm(init); @@ -478,6 +488,7 @@ namespace mbts.spark { public string name { get; } public bool show { get => _show.Value; set => _show.Value = value; } + } public class VolumeColumnVM : ViewModelBase { diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 351615776..1055e3d51 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -1,13 +1,11 @@ -using bts.api; +using bts.api; using bts.api.orderman; using bts.shell; using bts.spark; using bts.utils; using mbts.co2; -using mbts.persist; using mbts.ui; using mbts.ui.shell; -using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; @@ -36,32 +34,29 @@ namespace mbts.spark { readonly PropertyAutoWrapper _bid_background, _bid_foreground, _ask_background, _ask_foreground; double _position, _day_position; bool _show_account_position, _show_day_position; - IWindowSettingsManager _settings_manager; ulong _misc_time = 0; ulong _last_trade_time = 0; IEqualityComparer _equality; Dictionary _slot_price_vs_orders; IReadOnlyDictionary _cache = DictionaryHelper.empty(); + LadderSettings _current_settings; - 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(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)))); - 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, IObservable settings) => + create_readonly(bus, model, LadderSettings.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); + public static LadderVM create_readonly(IBus bus, LadderModel model, LadderSettings init, IObservable settings) => + new LadderVM(bus, model, init, settings); - LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, IWindowSettingsManagerNonShared non_shared_wsm, LadderSettings init, OrderPropertiesEditorVM order_properties_vm = null) { + LadderVM(IBus bus, LadderModel model, LadderSettings init, IObservable settings, OrderPropertiesEditorVM order_properties_vm = null) { _bus = bus; _model = model; + _current_settings = init; + this.settings = settings; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); _slot_price_vs_orders = new Dictionary(_equality); - _settings_manager = non_shared_wsm; this.order_properties_vm = order_properties_vm; _high = backing(nameof(high), double.NaN); _low = backing(nameof(low), double.NaN); @@ -87,6 +82,8 @@ namespace mbts.spark { // All settings observers should be aggregated together, so they can all share the same subscription to the settings // (these subscriptions are not horribly expensive, but they're not free either - even more so with the .OnDispatcher() extension). var settings_observer = new CompositeObserver { + /// first things first: assign our + (s => _current_settings = s), // brush props (_bid_background = brush_prop(nameof(bid_background), s => s.bid_column.background)).set, (_bid_foreground = brush_prop(nameof(bid_foreground), s => s.bid_column.foreground)).set, @@ -128,30 +125,14 @@ namespace mbts.spark { cancel_command = new AsyncCommand(_model.cancel_orders, true); show_book_command = new DelegateCommand(_show_book); show_ticket_command = new DelegateCommand(_show_ticket); - settings_command = new DialogCommand(() => { - var vm = new ShellSettingsDialogVM( - settings_manager, s => s.ladder, UserSettings.FileExtensions.LADDER, - s => { - var svm = new LadderSettingsVM(model.order_gateway, security.ContractCase == Security.ContractOneofCase.Synthetic, () => left_panel_width, () => zoom_factor); - svm.load(s); - return svm; - }, s => s.with_window_specifics(get_save_state().get_window_specifics())); - var dialog = new ui.spark.ShellSettingsDialog { - DataContext = vm, - Title = $"Ladder Settings - '{security}'" - }; - vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); - return dialog; - }, -500, -500); + settings_command = new DelegateCommand(() => request_settings_dialog?.Invoke()); orders = new ObservableCollection(); _dispose = Disposable.Create( - settings_manager.subscribe_current().OnDispatcher().Subscribe(settings_observer), - settings_command, - non_shared_wsm, + settings.OnDispatcher().Subscribe(settings_observer), get_order_properties_editor_hooks(), - size_calculator = new CalculatorLogic(0, _settings_manager.subscribe_current().Select(s => s.calculator_buttons)), + size_calculator = new CalculatorLogic(0, settings.Select(s => s.calculator_buttons).OnDispatcher()), 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 => { @@ -176,7 +157,7 @@ namespace mbts.spark { 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_manager.subscribe_current().Select(s => s.badge_style)); + 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; } @@ -250,7 +231,7 @@ namespace mbts.spark { public IBus bus => _bus; - public event Action on_tick; + public event Action on_tick, request_settings_dialog; public MDConsumerHandle md => _model.md; // we return only entries who have piqs and whose piqs are not uint.Max @@ -302,11 +283,11 @@ namespace mbts.spark { public ICommand send_order_command { get; } public ICommand show_book_command { get; } public ICommand show_ticket_command { get; } + public ICommand settings_command { get; } public Brush bid_background => _bid_background.view; public Brush bid_foreground => _bid_foreground.view; public Brush ask_background => _ask_background.view; public Brush ask_foreground => _ask_foreground.view; - public DialogCommand settings_command { get; } public bool show_day => _show_day.view; public bool show_high => _show_high.view; public bool show_low => _show_low.view; @@ -347,7 +328,7 @@ namespace mbts.spark { public uint piq_column_width { get => _piq_column_width.Value; set => _piq_column_width.set(value); } public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); } internal LadderModel model => _model; - internal IObservable settings => _settings_manager.subscribe_current(); + internal IObservable settings { get; } internal OrderRecordImmutable get_root_at_price((OrderRecordImmutable order, uint? _, AlgoData? __, AlgoDefinitionMetadata? meta) op) { var order = op.order; double p = order.price(); @@ -365,12 +346,18 @@ namespace mbts.spark { } } - public LadderSettings get_save_state() { - var state = _settings_manager.current_settings(); - state = state.with_window_specifics(new LadderSettings.WindowSpecifics(left_panel_width, orders_column_width, bid_column_width, price_column_width, ask_column_width, last_column_width, volume_column_width, zoom_factor, piq_column_width)); - state.use_defaults = _settings_manager.instance_settings == null; - return state; - } + public LadderSettings get_save_state() => + _current_settings.with_window_specifics( + new LadderSettings.WindowSpecifics( + left_panel_width, + orders_column_width, + bid_column_width, + price_column_width, + ask_column_width, + last_column_width, + volume_column_width, + zoom_factor, + piq_column_width)); public void key_down(KeyEventArgs e) { if (order_properties_vm == null) @@ -384,20 +371,18 @@ namespace mbts.spark { } } - public void send_order((double price, Side? side, MouseButton buton) args) { - if (args.buton == MouseButton.Middle) return; - var size_from_alternate = args.buton == MouseButton.Right; - if (order_properties_vm == null) + public void send_order((double price, Side? side, MouseButton button) args) { + if (order_properties_vm == null || args.button == MouseButton.Middle) return; - var s = _settings_manager.current_settings(); - if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (size_from_alternate && s.alternate_order_size == 0)) { + var size_from_alternate = args.button == MouseButton.Right; + if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (size_from_alternate && _current_settings.alternate_order_size == 0)) { return; } if (!size_from_alternate && (!size_calculator.value.HasValue || size_calculator.value.Value == 0)) { size_calculator.flash_error(); } else { - uint size = size_from_alternate ? s.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0); + uint size = size_from_alternate ? _current_settings.alternate_order_size : (uint)Math.Abs(size_calculator.value ?? 0); send_order_async(args.side.Value, size, args.price).ignore(); } } diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 53d35ecbb..f228e057f 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -430,19 +430,34 @@ namespace mbts.spark { if (e.RemovedItems != null) { foreach (var row_vm in e.RemovedItems.OfType()) { row_vm.is_selected = false; - _selected_params_mon.on_row_unselected(row_vm); + _selected_params_mon.on_row_unselected(_get_root(row_vm.order_tuple)); _attachable_selected_orders.Remove(row_vm.order_key); _detachable_selected_orders.Remove(row_vm.order_key); } } if (e.AddedItems != null) { foreach (var row_vm in e.AddedItems.OfType()) { + var root = _get_root(row_vm.order_tuple); row_vm.is_selected = true; - _selected_params_mon.on_row_selected(row_vm); + row_vm.updated += on_updated; + _selected_params_mon.on_row_selected(root); if (row_vm.is_attachable) _attachable_selected_orders.Add(row_vm.order_key); if (row_vm.is_detachable) _detachable_selected_orders.Add(row_vm.order_key); + void on_updated((OrderSecurity oldval, OrderSecurity newval) change) { + if (!row_vm.is_selected) { + // self destruct + row_vm.updated -= on_updated; + return; + } + var new_root = _get_root(change.newval); + if (!new_root.Equals(root)) { + _selected_params_mon.on_row_unselected(root); + _selected_params_mon.on_row_selected(new_root); + root = new_root; + } + } } } RowSelectionHelper.apply_changes(selected_rows, e); @@ -547,13 +562,6 @@ namespace mbts.spark { public bool try_get_parent(OrderBookRowVM row, out OrderSecurity parent) => _cached_orders.TryGetValue(row.parent_order_key, out parent); - public OrderRecordImmutable get_root(OrderRecordImmutable r) { - while (r.ParentKey != 0 && _cached_orders.TryGetValue(r.ParentKey, out var parent_osam)) { - r = parent_osam.order; - } - return r; - } - internal void detach_orders(OrderBookRowVM order) => _detach_orders_async(new[] { order }).ignore(); @@ -591,6 +599,18 @@ namespace mbts.spark { } } + OrderBookRowVM _get_root_row(OrderBookRowVM row) { + while (row.parent_order_key != 0 && _row_collection.get_parent(row.parent_order_key) is OrderBookRowVM prow) + row = prow; + return row; + } + + OrderSecurity _get_root(OrderSecurity os) { + while (os.order.ParentKey != 0 && _cached_orders.TryGetValue(os.order.ParentKey, out var pos)) + os = pos; + return os; + } + void _on_filter_changed() { var fd = new FilterData(grid_settings_manager.algo_tree_display_mode, _columns.create_filter_states()); if (!fd.Equals(_cached_filter_data)) { @@ -611,6 +631,7 @@ namespace mbts.spark { } } + // Note: modifications are performed on the selected orders' ROOT orders. async Task _modify_selected_orders_async() { double? price = DoubleHelper.nan_nullable(order_mod_vm.price); uint? size = order_mod_vm.size; @@ -623,17 +644,17 @@ namespace mbts.spark { // their values will be cleared (in the param grid gui), and the modifications will not be applied. // FYI this behavior is implemented to support 'partial edits.' (e.g., changing the 'price' for multiple orders that do not have the same 'size'). // ---- - var update_params = selected_rows.Select(update_params_factory).ToList(); + var update_params = selected_rows.Select(r => update_params_factory(_get_root(r.order_tuple))).ToList(); await Task.WhenAll(update_params.Select(t => _model.update_order(t.order, new_price: price, new_size: size, new_algo: t.new_algo))); - (OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderBookRowVM row) { - var mod_algo = row.order.Def.CustomDef.CloneToMutable(); + (OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderSecurity order_tuple) { + var mod_algo = order_tuple.order.Def.CustomDef.CloneToMutable(); if (mod_algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) { mod_algo_vm.assign_to(mod_algo.Composite.Definition); } else { mod_algo_vm.assign_to(mod_algo); } var mod_algoi = new CustomOrderDefinitionImmutable(mod_algo); - return (row.order, OrderDataHelper.EqualsHelpers.equals(row.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi); + return (order_tuple.order, OrderDataHelper.EqualsHelpers.equals(order_tuple.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi); } } else await Task.WhenAll(selected_rows.Select(r => _model.update_order(r.order, price))); } @@ -883,11 +904,10 @@ namespace mbts.spark { return; Disposable.replace(ref _ladder_vm, _security_md.HasValue ? - LadderVM.create_readonly( - _owner._bus, + LadderVM.create_readonly(_owner._bus, new LadderModel(security_md.Value, _owner._model, _owner._model.mbo_service, - new Func(osec => _selected_order_tree.Contains(osec.order.Key)))) : - null); + new Func(osec => _selected_order_tree.Contains(osec.order.Key))), + Observable.Return(LadderSettings.Default)) : null); RaisePropertyChanged(nameof(ladder_vm)); } void _assign_param_permissions(IAlgoParamVM param, ref AlgoParamPermissions permissions_backing, AlgoParamPermissions permissions) { @@ -1006,15 +1026,11 @@ namespace mbts.spark { public IDisposable begin_udpate() => _group_mon.defer_updates(); - public void on_row_selected(OrderBookRowVM row) { - _group_mon.add(row.order_tuple); - row.updated += _on_row_updated; - } + public void on_row_selected(OrderSecurity order_tuple) => + _group_mon.add(order_tuple); - public void on_row_unselected(OrderBookRowVM row) { - _group_mon.remove(row.order_tuple); - row.updated -= _on_row_updated; - } + public void on_row_unselected(OrderSecurity order_tuple) => + _group_mon.remove(order_tuple); public void on_security_md_map(IReadOnlyDictionary security_md_map) { _security_md_map = security_md_map; diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index f7ada36af..eb2a4d081 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -42,6 +42,7 @@ + diff --git a/src/client/spark/core/ShellInterface/UserSettings/ISettingsProfileService.cs b/src/client/spark/core/ShellInterface/UserSettings/ISettingsProfileService.cs new file mode 100644 index 000000000..dd373d437 --- /dev/null +++ b/src/client/spark/core/ShellInterface/UserSettings/ISettingsProfileService.cs @@ -0,0 +1,70 @@ +using bts.api.core; +using mbts.spark; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Reactive.Linq; + +namespace mbts.persist { + /// + /// This service offers methods to save named settings, and observe the resultant named-settings . + /// + /// The type of settings. + interface ISettingsProfileService where T : class, IEquatable { + uint add_or_update(SettingsProfile value); + IReadOnlyList add_or_update(IEnumerable> value); + void remove(uint id); + IObservable, uint>> subscribe_all(); + } + + class SettingsProfileService : ISettingsProfileService where T : class, IEquatable { + readonly UserSettingsHub _hub; + readonly Func>> _get_profiles; + readonly Func>, UserSettings> _set_profiles; + + public SettingsProfileService(UserSettingsHub hub, Func>> get_profiles, Func>, UserSettings> set_profiles) { + _hub = hub; + _get_profiles = get_profiles; + _set_profiles = set_profiles; + } + + // Note: this operation is atomic, but does not protect against overwrites. + // This is not cause for concern, since settings are saved via user intervention (not programatically), + // it is pracically impossible for the user to click 'Save' fast enough to cause an incidental overwrite. + public uint add_or_update(SettingsProfile value) { + var curr = _hub.current; + var mdata = _get_profiles(curr); + if (value.id == 0) + value = value.with(curr.next_ladder_profile_id); + _hub.save_default(_set_profiles(curr, mdata.SetItem(value.id, value))).ignore(); + return value.id; + } + + public IReadOnlyList add_or_update(IEnumerable> values) { + var curr = _hub.current; + var builder = _get_profiles(curr).ToBuilder(); + var ids = new List(); + uint new_id = curr.next_ladder_profile_id; + foreach (var value in values) { + if (value.id == 0) { + builder.Add(new_id, value.with(new_id)); + new_id++; + } else { + builder[value.id] = value; + } + } + _hub.save_default(_set_profiles(curr, builder.ToDictionary())).ignore(); + return ids; + } + + public void remove(uint id) { + var curr = _hub.current; + _hub.save_default(_set_profiles(curr, _get_profiles(curr).Remove(id))).ignore(); + } + + public IObservable, uint>> subscribe_all() => + _hub.subscribe_default_settings().Select(_get_profiles).Table(SettingsProfile.key_fn); + } +} \ No newline at end of file diff --git a/src/client/spark/core/ShellInterface/UserSettings/SettingsProfile.cs b/src/client/spark/core/ShellInterface/UserSettings/SettingsProfile.cs new file mode 100644 index 000000000..5a0e4c302 --- /dev/null +++ b/src/client/spark/core/ShellInterface/UserSettings/SettingsProfile.cs @@ -0,0 +1,79 @@ +using ProtoBuf; +using System; + +namespace mbts.spark { + interface ISettingsProfile { + uint id { get; } + string name { get; } + T value { get; } + SecurityCriteria security_criteria { get; } + } + + struct SettingsProfile : IEquatable> where T : class, IEquatable { + public static readonly Func, uint> key_fn = ns => ns.id; + + public readonly uint id; + public readonly string name; + public readonly T value; + public readonly SecurityCriteria security_criteria; + + public SettingsProfile(uint id, string name, T value, SecurityCriteria security_criteria = null) { + this.id = id; + this.name = name; + this.value = value; + this.security_criteria = security_criteria; + } + + public SettingsProfile with(uint? id = null, string name = null, T value = null, SecurityCriteria security_criteria = null) => + new SettingsProfile(id ?? this.id, name ?? this.name, value ?? this.value, security_criteria ?? this.security_criteria); + + public bool Equals(SettingsProfile other) => + id == other.id && + name == other.name && + value.safe_equals(other.value) && + security_criteria.safe_equals(other.security_criteria); + + public override bool Equals(object obj) => + obj is SettingsProfile other && Equals(other); + + public override int GetHashCode() => + id.GetHashCode(); + } + + [ProtoContract] + class LadderSettingsProfile : ISettingsProfile, IEquatable { + public LadderSettingsProfile() { } + + public LadderSettingsProfile(uint id, string name, LadderSettings value, SecurityCriteria security_criteria = null) { + this.id = id; + this.name = name; + this.value = value; + this.security_criteria = security_criteria; + } + + [ProtoMember(1)] + public uint id { get; } + + [ProtoMember(2)] + public string name { get; } + + [ProtoMember(3)] + public LadderSettings value { get; } + + [ProtoMember(4)] + public SecurityCriteria security_criteria { get; } + + public LadderSettingsProfile with(uint? id = null, LadderSettings value = null) => + new LadderSettingsProfile(id ?? this.id, name, value ?? this.value, security_criteria); + + public bool Equals(LadderSettingsProfile other) => + other != null && + id == other.id && + name == other.name && + value.safe_equals(other.value) && + security_criteria.safe_equals(other.security_criteria); + + public override bool Equals(object obj) => Equals(obj as LadderSettingsProfile); + public override int GetHashCode() => id.GetHashCode(); + } +} \ No newline at end of file diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs index 61068c253..6dbe4c73d 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettings.cs @@ -2,11 +2,14 @@ using mbts.ui.settings; using ProtoBuf; using System; +using System.Collections.Generic; +using System.Linq; namespace mbts.spark { interface IDefaultableSettings { bool use_defaults { get; set; } } + /// /// The settings Mothership. All window - and any other future user based - settings should have a corresponding default member here. /// @@ -25,6 +28,18 @@ namespace mbts.spark { [ProtoMember(1)] LadderSettings _ladder; + [ProtoMember(11)] + readonly LadderSettingsProfile[] _ladder_profiles; + /// When Profiles Are Deleted, ladders that were using that profile shall copy the profile's settings to a local profile. + /// Therefor: + /// Deleted profile ids must never be reused. + /// If they were reused, consider an unloaded workspace with ladders that were using the deleted profile. + /// If such a workspace was reloaded after a new profile was saved with the deleted one's id, the ladders using that deleted profile would suddenly be using the new profile. + /// To Prevent IDs From Being Recycled: + /// The last profile id is stored in the protobuf (). + /// Anytime a profile is added, it shall use . + [ProtoMember(12)] + uint _last_ladder_profile_id; // removing NotificationSettings these from proto-serialization, since they are disabled by default for now. // This way, when they are enabled, there won't be any backwards compatability issues to worry about, as no clients will have persisted them yet. NotificationSettings _notification; @@ -44,7 +59,12 @@ namespace mbts.spark { public UserSettings() { } + public UserSettings(LadderSettingsProfile[] ladder_profiles) => + _ladder_profiles = ladder_profiles; + public LadderSettings ladder => _ladder ?? (_ladder = LadderSettings.Default); + public IReadOnlyList ladder_profiles => _ladder_profiles ?? Array.Empty(); + public uint next_ladder_profile_id => _last_ladder_profile_id + 1; public NotificationSettings notification => _notification ?? (_notification = NotificationSettings.Default); public GridSettings market_view_grid => _market_view_grid ?? (_market_view_grid = bts.shell.MarketViewWindowFactory.StartupData.DefaultGridSettings); public GridSettings time_and_sales_grid => _time_and_sales_grid ?? (_time_and_sales_grid = GridSettings.Default.with(bts.shell.TimeAndSalesWindowFactory.StartupData.DefaultColumns.all)); @@ -53,15 +73,16 @@ namespace mbts.spark { public GridSettings pnl_grid => _pnl_grid ?? (_pnl_grid = bts.shell.PAndLWindowFactory.PAndLStartupData.DefaultGridSettings); public bts.shell.orderbook.OrderBookGridSettings order_book_grid => _order_book_grid ?? (_order_book_grid = bts.shell.orderbook.OrderBookStartupData.Default.grid_settings_wrapper()); - public UserSettings with(LadderSettings ladder = null, - NotificationSettings notification = null, - GridSettings provided_market_view_gridsettings = null, + public UserSettings with(LadderSettings ladder = null, + LadderSettingsProfile[] ladder_profiles = null, + NotificationSettings notification = null, + GridSettings provided_market_view_gridsettings = null, GridSettings time_and_sales = null, GridSettings provided_fills_gridsettings = null, GridSettings provided_synthetic_management_gridsettings = null, GridSettings provided_pnl_gridsettings = null, - bts.shell.orderbook.OrderBookGridSettings order_book_grid = null) => - new UserSettings { + bts.shell.orderbook.OrderBookGridSettings order_book_grid = null) { + var us = new UserSettings(ladder_profiles ?? _ladder_profiles) { _ladder = ladder ?? _ladder, _notification = notification ?? _notification, _market_view_grid = provided_market_view_gridsettings ?? _market_view_grid, @@ -69,8 +90,11 @@ namespace mbts.spark { _fills_grid = provided_fills_gridsettings ?? _fills_grid, _synthetic_management_grid = provided_synthetic_management_gridsettings ?? _synthetic_management_grid, _pnl_grid = provided_pnl_gridsettings ?? _pnl_grid, - _order_book_grid = order_book_grid ?? _order_book_grid + _order_book_grid = order_book_grid ?? _order_book_grid, }; + us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault()); + return us; + } public static class FileExtensions { public const string diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs index 3ebab980a..7a85ae795 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs @@ -1,7 +1,10 @@ using bts; +using bts.utils; using mbts.spark; using System; +using System.Collections.Generic; using System.ComponentModel.Composition; +using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; @@ -28,15 +31,40 @@ namespace mbts.persist { UserSettings s; try { s = await _persist.get(NAME_SPACE, DEFAULT_KEY); + if (s != null) { + // ensure valid named ladder set (w/ distinct, non-zero ids) + var ladder_profile_map = new Dictionary(); + var unidentified_lps = new List(); + foreach (var lp in s.ladder_profiles) { + if (lp.id == 0) { + unidentified_lps.Add(lp); + } else ladder_profile_map[lp.id] = lp; + } + uint id = s.next_ladder_profile_id; + foreach (var lp in unidentified_lps) { + ladder_profile_map[id] = lp.with(id); + id++; + } + var sorted_lps = ladder_profile_map.Values.ToArray(); + Array.Sort(sorted_lps, Comparer.Default.wrap(lp => lp.id)); + if (!sorted_lps.SequenceEqual(s.ladder_profiles)) + await _persist.set(NAME_SPACE, DEFAULT_KEY, s = s.with(ladder_profiles: sorted_lps)); + } } catch(Exception ex) { Log.Persist.warn($"Error loading {typeof(UserSettings)} from namespace '{NAME_SPACE}', will restore factory defaults and continue as usual: {ex}"); await save_default(s = UserSettings.factory_defaults); } - if (s != null) - _set_and_notify(s); + lock (_default_settings_lock) { + initialized = true; + if (s != null) + _default_settings_subject.OnNext(_default_settings = s); + } } } + // indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details) + public bool initialized { get; private set; } + /// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately. /// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies. public IObservable subscribe_default_settings() => _default_settings_subject.AsObservable(); @@ -49,20 +77,19 @@ namespace mbts.persist { } public async Task save_default(UserSettings value) { - _set_and_notify(value); + // notify observers before persisting so the changes are reflected immediately in the ui + lock (_default_settings_lock) { + _default_settings_subject.OnNext(_default_settings = value); + } + await _persist_async(); + } + + async Task _persist_async() { try { - await _persist.set(NAME_SPACE, DEFAULT_KEY, value); + await _persist.set(NAME_SPACE, DEFAULT_KEY, _default_settings); } catch(Exception ex) { Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}"); } } - - void _set_and_notify(UserSettings value) { - lock (_default_settings_lock) { - _default_settings = value; - // notify observers before persisting so the changes are reflected immediately in the ui - _default_settings_subject.OnNext(value); - } - } } } \ No newline at end of file diff --git a/src/client/spark/view/Colors.xaml b/src/client/spark/view/Colors.xaml index 00d1bea3b..300d3b647 100644 --- a/src/client/spark/view/Colors.xaml +++ b/src/client/spark/view/Colors.xaml @@ -36,6 +36,13 @@ + + #3D26A0DA + #FF26A0DA + #FFF5F5F5 + #FFF1F1F1 + #FFE2E3E3 + #FF212121 #FFFFFFFF diff --git a/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml new file mode 100644 index 000000000..89a555391 --- /dev/null +++ b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs new file mode 100644 index 000000000..fc376904a --- /dev/null +++ b/src/client/spark/view/Controls/Dialogs/OKCancelDialog.xaml.cs @@ -0,0 +1,66 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace mbts.ui.controls { + /// + /// Interaction logic for TextBoxDialog.xaml + /// + partial class OKCancelDialog : Window { + UIElement _core_content_view; + Panel _content_root; + + public OKCancelDialog() => + InitializeComponent(); + + #region CoreContent + public static readonly DependencyProperty CoreContentProperty = + WPFHelper.create_dp( + nameof(CoreContent), + (o, v) => o._try_load_content()); + + public object CoreContent { + get => GetValue(CoreContentProperty); + set => SetValue(CoreContentProperty, value); + } + #endregion + + #region OKCommand + public static readonly DependencyProperty OKCommandProperty = + WPFHelper.create_dp(nameof(OKCommand)); + + public ICommand OKCommand { + get => GetValue(OKCommandProperty) as ICommand; + set => SetValue(OKCommandProperty, value); + } + #endregion + + #region CancelCommand + public static readonly DependencyProperty CancelCommandProperty = + WPFHelper.create_dp(nameof(CancelCommand)); + + public ICommand CancelCommand { + get => GetValue(CancelCommandProperty) as ICommand; + set => SetValue(CancelCommandProperty, value); + } + #endregion + + void _content_root_Loaded(object sender, RoutedEventArgs e) { + if (_content_root == null) { + _content_root = sender as Panel; + _try_load_content(); + } + } + + void _try_load_content() { + if (_content_root == null) + return; + try { + if (_core_content_view != null) + _content_root.Children.Remove(_core_content_view); + var c = CoreContent; + _content_root.Children.Add(_core_content_view = c as UIElement ?? new ContentControl { Content = c }); + } catch { } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/ToolBar/ToolBar.xaml b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml index d0633f245..b35eef748 100644 --- a/src/client/spark/view/Controls/ToolBar/ToolBar.xaml +++ b/src/client/spark/view/Controls/ToolBar/ToolBar.xaml @@ -41,7 +41,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + Profile: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hint: this will not apply to existing ladders. + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - InitializeComponent(); - public const string ResetToFactoryKey = "Reset", CopyFromOtherKey = "Copy"; + public const string + ResetToFactoryKey = "Reset", + CopyFromOtherKey = "Copy", + LocalProfileItemTemplateKey = "LocalProfileItemTemplate", + SaveAsStyleKey = "SaveAsStyle", + SecurityMapKey = "SecurityMap"; } static class GridSettingsTemplateKeys { diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs index 90649db2a..2365f1c99 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs @@ -1,9 +1,21 @@ -using mbts.persist; +using bts.collections; +using bts.utils; +using mbts.collections; +using mbts.persist; using mbts.ui; using mbts.ui.controls; using mbts.ui.shell; +using mbts.ui.spark; +using mbts.ui.utility; +using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reactive.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; namespace mbts.spark { interface IWindowSettingsVM where T : class { @@ -102,4 +114,301 @@ namespace mbts.spark { public void Dispose() => Disposable.dispose(_resources); } -} + + class ProfiledShellSettingsDialogVM : DisposableViewModelBase, IRequestViewClose where T : class, IEquatable where TVM : class, IValueFactory, IObservable where TProfile : ISettingsProfile { + readonly IComparer> _key_comp = Comparer.Default.wrap(SettingsProfile.key_fn); + readonly Property _selected_profile; + readonly Func _vm_factory; + readonly ProfileVM _local_profile; + bool _is_copy_menu_open; + DialogSkirtItem _apply_item, _ok_item, _cancel_item; + MenuItemVM _import_item, _export_item, _load_factory_item; + + public ProfiledShellSettingsDialogVM(ISettingsProfileService profile_service, Func get_fallback, Func vm_factory, T init, string file_ext, uint settings_id = 0) { + _vm_factory = vm_factory; + // profile collections + var skip_local = profiles.WrapSkip(1); + var skip_local_wrapper = skip_local.WrapSelector( + p => new SettingsProfile(p.id, p.name, p.value.create(), p.security_criteria), + ns => new ProfileVM(ns.id, vm_factory(ns.value), ns.name, ns.security_criteria)); + profiles.Add(_local_profile = new ProfileVM(0, vm_factory(init), "local", template_key: ShellSettingsDialog.LocalProfileItemTemplateKey)); + _selected_profile = backing(nameof(selected_profile), _local_profile); + // dialog skirt items + _apply_item = new DialogSkirtItem("Apply", new DelegateCommand(apply)); + _ok_item = new DialogSkirtItem("OK", new DelegateCommand(new Action(apply) + close)) { is_default = true }; + _cancel_item = new DialogSkirtItem("Cancel", new DelegateCommand(close)) { is_cancel = true }; + // cmds + add_profile_cmd = new DelegateCommand(begin_add_profile); + copy_profile_cmd = new DelegateCommand(copy_profile); + revert_profile_cmd = ObservantCommand.create(revert_profile, ProfileVM.subscribe_is_dirty_fn, out var revert_profile_observer); + save_profile_cmd = ObservantCommand.create(save_profile, ProfileVM.subscribe_is_global_dirty_fn, out var save_profile_observer); + save_profile_as_cmd = ObservantCommand.create(begin_save_profile_as, ProfileVM.is_global_fn, out var save_as_observer); + save_all_cmd = ObservantCommand.create(save_all, out var save_all_observer); + delete_profile_cmd = ObservantCommand.create(delete, ProfileVM.is_global_fn, out var delete_observer); + // toolbar + const string import_group = "i", export_group = "e"; + (string name, string[] extensions) file_filter = ($"{file_ext} settings files", new[] { file_ext }); + var import_cmd = FileDialogCommand.import_proto(s => selected_profile?.load_value_from(s), type_name: file_ext, filter_items: file_filter); + var export_cmd = FileDialogCommand.export_proto(() => instance_vm.create(), filter_items: file_filter); + _load_factory_item = new MenuItemVM("Load Factory Defaults", new DelegateCommand(() => selected_profile?.load_value_from(get_fallback(UserSettings.factory_defaults))), Icons.Factory); + _import_item = new MenuItemVM("Load Settings File ...", import_cmd, Icons.Import, import_group); + _export_item = new MenuItemVM("Save Settings File ...", export_cmd, Icons.Export, export_group); + // + var is_global_dirty_mon = new ReactiveThresholdMonitor(ProfileVM.subscribe_is_global_dirty_fn); + _dispose = Disposable.Create( + ObservableAutoWrapper.connect_item_hooks(profiles, p => Disposable.Create(is_global_dirty_mon.join(p), p)), + is_global_dirty_mon.Subscribe(save_all_observer), + _selected_profile.observe_current(true).Subscribe(v => { + revert_profile_observer.OnNext(v); + save_profile_observer.OnNext(v); + save_as_observer.OnNext(v); + delete_observer.OnNext(v); + RaisePropertyChanged(nameof(instance_vm)); + }), + profile_service.subscribe_all().OnDispatcher().Subscribe(table => { + var prev_selected_name = selected_profile?.name; + skip_local_wrapper.RemoveSorted(table.removed, _key_comp); + foreach (var ns in table.changed) { + int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp); + if (i >= 0) + skip_local[i].load_from(ns); + } + foreach (var ns in table.added) { + int i = CollectionHelper.binary_search(skip_local_wrapper, ns, _key_comp); + if (i >= 0) + continue; + i = ~i; + skip_local_wrapper.Insert(i, ns); + if (settings_id == ns.id) { + if (ns.value.Equals(init)) + selected_profile = skip_local[i]; + settings_id = 0; + } + } + })); + + void apply() { + if (selected_profile != null) { + var newval = selected_profile.create(); + if (selected_profile.id != 0) + profile_service.add_or_update(newval); + selected_profile.commit_current(); + applied?.Invoke(newval); + } + } + void close() => RequestClose?.Invoke(this, new EventArgs()); + void delete(ProfileVM target) { + if (target.id != 0 && BTSMessageBox.Confirm($"Are you sure you want to delete '{target.name}?'", "Settings Profile")) + profile_service.remove(target.id); + } + void copy_profile(ProfileVM target) { + if (selected_profile != null) { + if (target == null) { + // copy to new + var profile = selected_profile.create().with(0, $"{selected_profile.name} - Copy"); + target = new ProfileVM(profile_service.add_or_update(profile), _vm_factory(profile.value), profile.name); + } + target.load_value_from(selected_profile.create().value); + is_copy_menu_open = false; + selected_profile = target; + } + } + // cmd impl + void begin_add_profile() => choose_name_dialog("New Profile", selected_profile, (t, n) => save_profile_as(null, n)).Show(); + void begin_save_profile_as(ProfileVM target) => choose_name_dialog($"Rename '{target.name}'", target, (t, n) => save_profile_as(t ?? target, n)).Show(); + void revert_profile(ProfileVM target) => target?.revert(); + void save_profile(ProfileVM target) => save_profile_as(target, target?.name); + // + void save_profile_as(ProfileVM target, string name) { + if (name == null || selected_profile == null) + return; + SettingsProfile val; + if (target != null) { + // overwrite target profile + val = selected_profile.create().with(name: name); + target.commit(val); + selected_profile = target; + profile_service.add_or_update(val); + } else { + // create new profile (set id=0 so 'store' knows to add a new profile, rather than update an existing one) + val = selected_profile.create().with(0, name); + uint id = profile_service.add_or_update(val); + /// Add the new profile to () so it can then be assigned to without being immediately unselected. + /// remember: val needs the new id before it can be added. + val = val.with(id); + // the save process is asynchronous now, but if that were to change, the new setting vm would have been added (already) in the iobservable settings callback. + // check that a vm with this id doesn't already exist before adding it . + int i = CollectionHelper.binary_search(skip_local_wrapper, val, _key_comp); + if (i < 0) + skip_local_wrapper.Insert(i = ~i, val); + selected_profile = skip_local[i]; + } + } + void save_all() => + profile_service.add_or_update(skip_local.Select(p => p.create())); + + Window choose_name_dialog(string title, ProfileVM target, Action commit) { + var text_box = new TextBox { Width = 160, Margin = new Thickness(8, 0, 0, 0), Text = target?.name ?? string.Empty }; + TextBoxBehavior.SetFocusOnLoaded(text_box, true); + WPFTextBoxAutoComplete.AutoCompleteBehavior.SetAutoCompleteItemsSource(text_box, skip_local.Select(vm => vm.name).ToList()); + // panel + var panel = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(8) }; + panel.Children.Add(new TextBlock { Text = "Name:", VerticalAlignment = VerticalAlignment.Center }); + panel.Children.Add(text_box); + // dialog + var dialog = new OKCancelDialog { + Title = title, + OKCommand = new DelegateCommand(() => commit(skip_local.FirstOrDefault(vm => vm.name == text_box.Text), text_box.Text)), + CoreContent = panel, + Topmost = true + }; + dialog.move_to_mouse(-100, -80); + return dialog; + } + } + + public event Action> applied; + public event EventHandler RequestClose; + + public ObservableCollection profiles { get; } = new ObservableCollection(); + public ProfileVM selected_profile { + get => _selected_profile.Value; + set { + if (_selected_profile.set_new(value) && value != null) + value.is_selected = true; + } + } + public TVM instance_vm => selected_profile?.value; + public bool is_copy_menu_open { get => _is_copy_menu_open; set => Set(ref _is_copy_menu_open, value); } + + public ICommand add_profile_cmd { get; } + public ICommand copy_profile_cmd { get; } + public ICommand delete_profile_cmd { get; } + public ICommand revert_profile_cmd { get; } + public ICommand edit_profile_securities_cmd { get; } + public ICommand save_profile_cmd { get; } + public ICommand save_profile_as_cmd { get; } + public ICommand save_all_cmd { get; } + + public IEnumerable action_menu_items { + get { + yield return _import_item; + yield return _export_item; + yield return _load_factory_item; + } + } + public IEnumerable left_skirt_items { get { yield break; } } + public IEnumerable right_skirt_items { + get { + yield return _apply_item; + yield return _ok_item; + yield return _cancel_item; + } + } + + public class ProfileVM : ViewModelBase, IValueFactory>, IEquatable, ITemplateSelectorKey, IDisposable { + // static delegates + public static readonly Func is_global_fn = p => p != null && p.is_global; + public static readonly Func> subscribe_is_global_dirty_fn = p => p?.is_global ?? false ? p.subscribe_is_dirty() : Observable.Return(false); + public static readonly Func> subscribe_is_dirty_fn = p => p != null ? p.subscribe_is_dirty() : Observable.Return(false); + // + readonly DeferrableActionWrapper _refresh_is_dirty; + readonly DelegateProperty _is_dirty; + // + SecurityCriteria _security_criteria; + SettingsProfile _committed, _last_result; + string _name, _template_key; + bool _is_selected; + IDisposable _dispose; + + public ProfileVM(uint id, TVM value, string name, SecurityCriteria security_criteria = null, string template_key = null) { + this.id = id; + this.value = value; + _name = name; + _security_criteria = security_criteria; + _template_key = template_key; + _committed = _last_result = create(); + _is_dirty = backing(nameof(is_dirty), () => !_last_result.Equals(_committed)); + _refresh_is_dirty = new DeferrableActionWrapper(_is_dirty.refresh); + _dispose = value.Subscribe(v => { + _last_result = _last_result.with(value: v); + _refresh_is_dirty.execute(); + }); + } + + public uint id { get; } + public TVM value { get; } + public string name { + get => _name; + set { + if (Set(ref _name, value)) { + _last_result = _last_result.with(name: value); + _is_dirty.refresh(); + } + } + } + public bool is_global => id != 0; + public bool is_dirty => _is_dirty.Value; + public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); } + public SecurityCriteria security_criteria { + get => _security_criteria; + set { + if (Set(ref _security_criteria, value)) { + _last_result = _last_result.with(security_criteria: security_criteria); + _is_dirty.refresh(); + } + } + } + + string ITemplateSelectorKey.key => _template_key; + + public SettingsProfile create() => + new SettingsProfile(id, name, value.create(), security_criteria); + + public void load_from(SettingsProfile data) { + using (_refresh_is_dirty.defer_execution()) { + _load_from(data); + /// assign directly to , to capture props that aren't visible in the dialog (i.e., props that are manipulated in the main window) + _last_result = data; + } + } + + public void load_value_from(T value) { + using (_refresh_is_dirty.defer_execution()) + this.value.load_from(value); + } + + public void commit(SettingsProfile data) { + using (_refresh_is_dirty.defer_execution()) + _load_from(_committed = data); + } + + public void commit_current() { + _committed = _last_result; + _refresh_is_dirty.execute(); + } + + public void revert() { + using (_refresh_is_dirty.defer_execution()) { + _load_from(_committed); + _last_result = _committed; + } + } + + public IObservable subscribe_is_dirty() => _is_dirty.observe_current(true); + + public void Dispose() => Disposable.dispose(ref _dispose); + + public bool Equals(ProfileVM other) => id == other?.id; + public override bool Equals(object obj) => Equals(obj as ProfileVM); + public override int GetHashCode() => id.GetHashCode(); + public override string ToString() => _name; + + void _load_from(SettingsProfile data) { + name = data.name; + security_criteria = data.security_criteria; + value.load_from(data.value); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs b/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs index 4eefe61b0..d97a0a99a 100644 --- a/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs +++ b/src/client/spark/view/Spark/ContractPicker/SecurityCriteriaExtensions.cs @@ -96,5 +96,8 @@ namespace mbts.spark { clause.security_types.is_null_or_empty() && !clause.security_keys.is_null_or_empty() && !clause.security_keys.Distinct().Skip(1).Any(); + + public static bool includes(this SecurityCriteria security_criteria, SecurityImmutable security) => + security_criteria != null && ContractPickerModel.security_in_criteria(security_criteria, security); } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/WPFHelper.cs b/src/client/spark/view/Utility/WPFHelper.cs index b1aea246d..03c5171e7 100644 --- a/src/client/spark/view/Utility/WPFHelper.cs +++ b/src/client/spark/view/Utility/WPFHelper.cs @@ -16,6 +16,9 @@ namespace mbts.ui { static class WPFHelper { public delegate void PropertyChangedCallback(TOwner owner, TValue old_value, TValue new_value); + public static DependencyProperty create_dp(string name, Action callback, object default_value = null) => + DependencyProperty.Register(name, typeof(object), typeof(TOwner), new PropertyMetadata(default_value, (d, e) => callback(ConvertUtils.try_convert(d), e.NewValue))); + public static DependencyProperty create_dp(string name, TValue default_value = default) => DependencyProperty.Register(name, typeof(TValue), typeof(TOwner), new PropertyMetadata(default_value)); diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index 3b0c6d69d..831f297e7 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -382,6 +382,25 @@ namespace System.Collections.Generic { } #endregion + #region MinOrDefault + public static T MinOrDefault(this IEnumerable source) where T : IComparable => + MinOrDefault(source, default); + + public static T MinOrDefault(this IEnumerable source, T default_value) where T : IComparable { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + T min = en.Current; + while (en.MoveNext()) { + if (min.CompareTo(en.Current) > 0) + min = en.Current; + } + return min; + } + } + return default_value; + } + #endregion + #region MinElement public static TElement MinElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MinElement(enumerable, select_value, default(TElement)); @@ -448,6 +467,25 @@ namespace System.Collections.Generic { } #endregion + #region MaxOrDefault + public static T MaxOrDefault(this IEnumerable source) where T : IComparable => + MaxOrDefault(source, default); + + public static T MaxOrDefault(this IEnumerable source, T default_value) where T : IComparable { + using (var en = source.GetEnumerator()) { + if (en.MoveNext()) { + T max = en.Current; + while (en.MoveNext()) { + if (max.CompareTo(en.Current) < 0) + max = en.Current; + } + return max; + } + } + return default_value; + } + #endregion + #region MaxElement public static TElement MaxElement(this IEnumerable enumerable, Func select_value) where T : IComparable => MaxElement(enumerable, select_value, default(TElement)); From a1ffc24ed9a78f60dfbe32a0c3db62505d439e76 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Fri, 14 Jun 2019 15:53:22 -0500 Subject: [PATCH 16/30] LadderVM - size_calculator uses shared settings subscription --- .../spark/Modules/Trading/Ladder/VM/LadderVM.cs | 4 ++-- src/client/spark/view/Spark/Shell/CalculatorLogic.cs | 11 ++++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 1055e3d51..678282a83 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -110,6 +110,7 @@ namespace mbts.spark { 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))) { RaisePropertyChanged(nameof(position_display_text)); } + size_calculator.buttons = s.calculator_buttons; } }; PropertyAutoWrapper bool_prop(string name, Func get_bool) => @@ -132,7 +133,6 @@ namespace mbts.spark { _dispose = Disposable.Create( settings.OnDispatcher().Subscribe(settings_observer), get_order_properties_editor_hooks(), - size_calculator = new CalculatorLogic(0, settings.Select(s => s.calculator_buttons).OnDispatcher()), 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 => { @@ -275,7 +275,7 @@ namespace mbts.spark { public double day_position => _day_position; public ulong volume => _volume.Value; public bool auto_clear { get => _auto_clear.Value; set => _auto_clear.set(value); } - public CalculatorLogic size_calculator { get; } + public CalculatorLogic size_calculator { get; } = new CalculatorLogic(0); /// Important: can be null. public OrderPropertiesEditorVM order_properties_vm { get; } public ObservableCollection orders { get; } diff --git a/src/client/spark/view/Spark/Shell/CalculatorLogic.cs b/src/client/spark/view/Spark/Shell/CalculatorLogic.cs index 56a81f4fb..6433e10e1 100644 --- a/src/client/spark/view/Spark/Shell/CalculatorLogic.cs +++ b/src/client/spark/view/Spark/Shell/CalculatorLogic.cs @@ -7,17 +7,18 @@ using System.Windows.Input; namespace mbts.spark { public class CalculatorLogic : DisposableViewModelBase { readonly UserProperty _value; - readonly Property _buttons; + int[] _buttons; - public CalculatorLogic(uint? initial_size, IObservable buttons_source) { + public CalculatorLogic(uint? initial_size) => _value = new UserProperty(backing(nameof(value), initial_size)); - _buttons = backing(nameof(buttons), buttons_source); - } + + public CalculatorLogic(uint? initial_size, IObservable buttons_source) : this(initial_size) => + _dispose = buttons_source.Subscribe(newval => buttons = newval); public uint? value { get => _value.Value; set => _value.Value = value; } public bool value_setter_called => _value.setter_called; public IObservable value_observable => _value.Select(vals => vals.newval); - public int[] buttons { get => _buttons.Value; set => _buttons.set(value); } + public int[] buttons { get => _buttons; set => Set(ref _buttons, value); } public ICommand click => new DelegateCommand(handle_calculator_click); public ICommand set_value_command => new DelegateCommand(v => _value.Value = v); public ICommand clear => new DelegateCommand(() => _value.Value = null); From 613ba8004dafd4041adb5b642c02a532824297c3 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 13:47:05 -0500 Subject: [PATCH 17/30] LadderView - make Min/MaxZoomFactor consts (were StaticResources) --- .../Trading/Ladder/View/LadderView.xaml | 20 ++++++++++------ .../Trading/Ladder/View/LadderView.xaml.cs | 23 ++++++------------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml index f2bf4d0e3..c85b5ab34 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml @@ -288,8 +288,11 @@ /> - + @@ -309,11 +312,14 @@ - + diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs index f4f6ecea7..efaf28cda 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderView.xaml.cs @@ -11,6 +11,12 @@ using System.Windows.Input; namespace mbts.spark { partial class LadderView : UserControl { + public const double + MinLeftPanelWidth = 60, + MaxLeftPanelWidth = 150, + MinZoomFactor = 0.5, + MaxZoomFactor = 1.5; + public static IMultiValueConverter PositionToolTipConverter = ValueConverter.create((account, show_day_pos, show_total_pos) => { const string day_pos_text = "day", total_pos_text = "total"; @@ -40,8 +46,6 @@ namespace mbts.spark { return sb.ToString(); }); - readonly double _max_zoom, _min_zoom; - internal LadderView(LadderVM vm) { InitializeComponent(); _column_headers_presenter.Columns = new GridViewColumnCollection(); @@ -50,19 +54,6 @@ namespace mbts.spark { this.vm = vm; DataContext = vm; DataContextChanged += datacontext_changed; - if (TryFindResource("MaxZoomFactor") is double found_max) { - _max_zoom = found_max; - } else { - // is there a better way of not specifying the constant twice ? - // once in the resource dictionary here and again in the xaml, seems like there has to be a better way - _max_zoom = 1.5; - } - // ditto - if (TryFindResource("MinZoomFactor") is double found_min) { - _min_zoom = found_min; - } else { - _min_zoom = 0.5; - } _ui_scaler.MouseDoubleClick += _ui_scaler_MouseDoubleClick; this.PreviewMouseWheel += LadderView_PreviewMouseWheel; this.PreviewMouseDown += LadderView_PreviewMouseDown; @@ -78,7 +69,7 @@ namespace mbts.spark { var delta = (e.Delta > 0) ? 0.1 : -0.1; var proposed_scaler_value = _ui_scaler.Value + delta; // Here we enforce the same contraints that are on the gui slider regarding min and max - if (_min_zoom < proposed_scaler_value && proposed_scaler_value < _max_zoom) { + if (MinZoomFactor < proposed_scaler_value && proposed_scaler_value < MaxZoomFactor) { _ui_scaler.Value = proposed_scaler_value; } } From 18a80516d518fe440988f608b55739008d2a91fa Mon Sep 17 00:00:00 2001 From: John Colvin Date: Sun, 16 Jun 2019 12:23:34 -0500 Subject: [PATCH 18/30] SPARK-2489 / SPARK-2499 eliminate 'window specific settings,' treat all props like regular settings --- src/client/spark/Daemons/OrderTicketDaemon.cs | 7 +- .../Trading/AlgoStudio/Model/AlgoKey.cs | 10 + .../Modules/Trading/Ladder/LadderSettings.cs | 13 +- .../Trading/Ladder/LadderWindowFactory.cs | 2 +- .../Trading/Ladder/VM/LadderSettingsVM.cs | 123 +++++++++--- .../Modules/Trading/Ladder/VM/LadderVM.cs | 26 ++- .../Ladder/View/LadderSettingsView.xaml | 187 ++++++++++++++---- .../spark/Orders/OrderPropertiesEditorVM.cs | 41 ++-- .../core/Collections/KeyedItemSelector.cs | 9 + .../Collections/ObservableKeyedCollection.cs | 14 ++ .../spark/core/Utility/SelectionModel.cs | 30 +++ src/client/spark/core/data/AccountTuple.cs | 1 + 12 files changed, 373 insertions(+), 90 deletions(-) diff --git a/src/client/spark/Daemons/OrderTicketDaemon.cs b/src/client/spark/Daemons/OrderTicketDaemon.cs index 84e473c46..cf18c0835 100644 --- a/src/client/spark/Daemons/OrderTicketDaemon.cs +++ b/src/client/spark/Daemons/OrderTicketDaemon.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System.ComponentModel.Composition; using System.Reactive.Linq; using System.Windows; +using LadderSettings = mbts.spark.LadderSettings; namespace bts.shell { [Export(typeof(IShellDaemon))] @@ -48,14 +49,14 @@ namespace bts.shell { void _show_order_ticket(SecurityMD smd) => _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, - Observable.Return(_model.factory.default_ladder_settings(smd.security))) + Observable.Return(LadderSettings.Default)) }); void _show_order_ticket((OrderDefinitionImmutable def, double price, uint size) ops) { if (_md_map.TryGetValue(ops.def.SecurityKey, out SecurityMD smd)) _show_order_window(new OrderTicket { DataContext = new NewOrderTicketVM(_model, smd, ops.def, ops.price, ops.size, - Observable.Return(_model.factory.default_ladder_settings(smd.security).calculator_buttons)) + Observable.Return(LadderSettings.Default.calculator_buttons)) }); } @@ -66,7 +67,7 @@ namespace bts.shell { _show_order_window(new OrderModificationDialog { DataContext = new ExistingOrderTicketVM(_model, Observable.Return((md,ori.order)), - Observable.Return(_model.factory.default_ladder_settings(ori.sec.Value).calculator_buttons) + Observable.Return(LadderSettings.Default.calculator_buttons) ) }); } diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs index 98c414a46..5fce60395 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs @@ -52,6 +52,16 @@ namespace mbts.spark { return new AlgoID(CustomOrderDefinition.CustomOneofCase.None); } + public static AlgoKey to_algo_key(AlgoID id, IMaskIndexInt32 dynamic_type_index) { + if (id._factory_key.HasValue) + return new AlgoKey(id._factory_key.Value); + if (id._persisted_key.HasValue) + return new AlgoKey(new AlgoPersistedKey(id._persisted_key.Value)); + if (id._dynamic_key != null) + return new AlgoKey(new AlgoNameStructureKey(id._dynamic_key, AlgoStructureSerializer.structure_key(dynamic_type_index.to_int(id._dynamic_key)))); + return default; + } + public bool Equals(AlgoID other) => _factory_key == other._factory_key && _dynamic_key == other._dynamic_key && diff --git a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs index e20468abe..abe7111fa 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderSettings.cs @@ -286,8 +286,8 @@ namespace mbts.spark { volume_column = VolumeColumnSettings.Default, calculator_buttons = new[] { 1, 5, 10, 25, 50, 100 }, scroll_bar_visible = false, - default_order_type = CustomOrderDefinition.CustomOneofCase.Limit, default_time_in_force = TimeInForce.Day, + default_algo = new AlgoID(CustomOrderDefinition.CustomOneofCase.Limit), animate_recenter = true, badge_style = BadgeStyle.Normal, bid_break_line = new LadderMarketBreakLine { color = 0, show = true }, @@ -362,6 +362,10 @@ namespace mbts.spark { public bool scroll_bar_visible { get; set; } // USED [ProtoMember(11)] // USED [ProtoMember(12)] + [ProtoMember(51)] + public uint default_account { get; set; } + [ProtoMember(52)] + public AlgoID default_algo { get; set; } [ProtoMember(13)] public CustomOrderDefinition.CustomOneofCase default_order_type { get; set; } [ProtoMember(14)] @@ -372,6 +376,8 @@ namespace mbts.spark { public bool animate_recenter { get; set; } = true; [ProtoMember(17)] public BadgeStyle badge_style { get; set; } + [ProtoMember(53)] + public bool auto_clear { get; set; } [ProtoMember(18)] public LadderMarketBreakLine bid_break_line { get; set; } @@ -467,11 +473,13 @@ namespace mbts.spark { piq_column.safe_equals(other.piq_column) && calculator_buttons.safe_equals(other.calculator_buttons, (a, b) => a.SequenceEqual(b)) && scroll_bar_visible == other.scroll_bar_visible && - default_order_type == other.default_order_type && + default_account == other.default_account && + default_algo == other.default_algo && default_time_in_force == other.default_time_in_force && size == other.size && animate_recenter == other.animate_recenter && badge_style == other.badge_style && + auto_clear == other.auto_clear && bid_break_line.safe_equals(other.bid_break_line) && ask_break_line.safe_equals(other.ask_break_line) && mid_break_line.safe_equals(other.mid_break_line) && @@ -520,7 +528,6 @@ namespace mbts.spark { EqualityComparer.safe_get_hash_code(piq_column), EqualityComparer.safe_get_hash_code(calculator_buttons), scroll_bar_visible.GetHashCode(), - default_order_type.GetHashCode(), default_time_in_force.GetHashCode(), size.GetHashCode(), animate_recenter.GetHashCode(), diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 8ea85b91b..7025f59db 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -146,7 +146,7 @@ namespace bts.shell { profile_service, us => us.ladder ?? LadderSettings.Default, s => { - var svm = new LadderSettingsVM(model.order_gateway, vm.security.ContractCase == Security.ContractOneofCase.Synthetic, () => vm.left_panel_width, () => vm.zoom_factor); + var svm = new LadderSettingsVM(model.order_gateway, vm.security); svm.load(s); return svm; }, vm.get_save_state(), diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs index 3bf68712d..2a28fba8c 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderSettingsVM.cs @@ -1,4 +1,6 @@ -using bts.api; +using bts; +using bts.api; +using bts.api.orderman; using bts.collections; using bts.utils; using mbts.collections; @@ -27,9 +29,17 @@ namespace mbts.spark { readonly Property _badge_style; readonly Property _alternate_order_size; readonly DelegateProperty _row_height; + readonly UserProperty _default_account; + readonly UserProperty _default_algo; readonly DeferrableActionWrapper _update; + readonly ObservableKeyedCollection _accounts = new ObservableKeyedCollection(AccountTuple.nullable_key_fn); + readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); + readonly OrdersModel _model; + uint? _desired_account; + AlgoID? _desired_algo; + TimeInForce _default_time_in_force; LadderSettings.NetChangeTerms _price_format; - Func _get_order_entry_panel_width, _get_zoom_factor; + double _order_entry_panel_width, _zoom_factor; LadderSettings _current; LadderColumnSettingsVM _orders = new OrdersColumnSettingsVM(), @@ -66,16 +76,17 @@ namespace mbts.spark { _cancel_sells_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Sells"), _cancel_all_visibility = new OrderEntryPanelItemVisibilityVM("Cancel All"); - public LadderSettingsVM(OrdersModel model, bool is_synthetic, Func get_left_panel_width, Func get_zoom_factor) { - this.is_synthetic = is_synthetic; - favorite_algos_vm = new FavoriteAlgosVM(model); + public LadderSettingsVM(OrdersModel model, SecurityImmutable security) { + _model = model; + is_synthetic = security.ContractCase == Security.ContractOneofCase.Synthetic; + 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)); _badge_style = backing(nameof(badge_style)); _badge_style.Changed += _badge_style_Changed; _alternate_order_size = backing(nameof(alternate_order_size)); - _get_order_entry_panel_width = get_left_panel_width; - _get_zoom_factor = get_zoom_factor; + _default_account = user_backing(nameof(default_account)); + _default_algo = user_backing(nameof(default_algo)); // be sure to initialize backings before this measure_row_height call _row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result())); _orders.font_size_changed += on_font_size_changed; @@ -84,12 +95,27 @@ namespace mbts.spark { _ask.font_size_changed += on_font_size_changed; _last.font_size_changed += on_font_size_changed; _piq.font_size_changed += on_font_size_changed; + // accounts + accounts_view = new ListCollectionView(_accounts) { + CustomSort = Comparer.Default.to_nullable().to_non_generic() + }; // update _update = new DeferrableActionWrapper(() => result_changed?.Invoke()); foreach (var c in _observable_components) c.PropertyChanged += on_prop_changed; favorite_algos_vm.items.CollectionChanged += on_favorite_algo_items_CollectionChanged; - _dispose = new CompositeDisposable(ObservableAutoWrapper.connect_item_hooks(favorite_algos_vm.items, connect_favorite_algo)) { dispose_resources }; + _algo_definitions.AddRange(_model.factory.default_algos(security).Values.Select(algo_factory)); + _dispose = new CompositeDisposable( + _model.factory.subscribe_accounts().OnDispatcher().Subscribe(acc_map => { + _accounts.SyncWithDictionary(MappedDictionary.create(acc_map, account_factory)); + _try_select_desired_account(); + }), + ObservableAutoWrapper.connect_item_hooks(favorite_algos_vm.items, connect_favorite_algo), + _model.algo_model.definitions.OnDispatcher().Subscribe(update => { + AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, update, algo_factory); + _try_select_desired_algo(); + }) + ) { dispose_resources }; // local methods void on_font_size_changed(double oldval, double newval) => _row_height.refresh(); void on_prop_changed(object sender, PropertyChangedEventArgs e) => _update.execute(); @@ -104,6 +130,8 @@ namespace mbts.spark { foreach (var c in _observable_components) c.PropertyChanged -= on_prop_changed; } + AccountTuple? account_factory(KeyValuePair kv) => new AccountTuple(kv.Key, kv.Value); + AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data, false); } public event Action result_changed; @@ -128,8 +156,19 @@ namespace mbts.spark { } public MarketSizeDisplayVM size_display { get; } = new MarketSizeDisplayVM(); + // price format public LadderSettings.NetChangeTerms price_format { get => _price_format; set => Set(ref _price_format, value); } public IEnumerable price_format_options => EnumHelper.get_values(); + // time in force + public TimeInForce default_time_in_force { get => _default_time_in_force; set => Set(ref _default_time_in_force, value); } + public IEnumerable time_in_force_options => EnumHelper.get_values_except(TimeInForce.Undefined); + // account + public AccountTuple? default_account { get => _default_account.Value; set => _default_account.Value = value; } + public ICollectionView accounts_view { get; } + // algo + public AlgoDefinitionVM default_algo { get => _default_algo.Value; set => _default_algo.Value = value; } + public IReadOnlyObservableCollection algo_definitions => _algo_definitions; + // favorites public FavoriteAlgosVM favorite_algos_vm { get; } public double row_height => _row_height.Value; @@ -172,6 +211,8 @@ namespace mbts.spark { } } + public double order_entry_panel_width { get => _order_entry_panel_width; set => Set(ref _order_entry_panel_width, value); } + public double zoom_factor { get => _zoom_factor; set => Set(ref _zoom_factor, value); } public IEnumerable order_entry_panel_items { get { yield return _zoom_slider_visbility; @@ -249,6 +290,7 @@ namespace mbts.spark { 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))); + // columns _orders.assign_from(_current.orders_column); _bid.assign_from(_current.bid_column); _ask.assign_from(_current.ask_column); @@ -256,12 +298,24 @@ namespace mbts.spark { _volume.assign_from(_current.volume_column); _last.assign_from(_current.last_column); _piq.assign_from(_current.piq_column); + // market break lines _bid_mkt_line.assign_from(_current.bid_break_line); _ask_mkt_line.assign_from(_current.ask_break_line); _mid_mkt_line.assign_from(_current.mid_break_line); _session_low_mkt_line.assign_from(_current.session_low_line); _session_high_mkt_line.assign_from(_current.session_high_line); _session_range_fill.assign_from(_current.session_range_fill); + // left-panel (defaults) + default_time_in_force = settings.default_time_in_force; + // - account + _desired_account = settings.default_account; + _try_select_desired_account(true); + // - algo + _desired_algo = settings.default_algo; + _try_select_desired_algo(true); + // left-panel (components) + order_entry_panel_width = settings.order_entry_panel_initial_width; + zoom_factor = settings.zoom_factor; _zoom_slider_visbility.show = settings.zoom_slider_visible; _day_visibility.show = settings.day_visible; _high_visibility.show = settings.high_visible; @@ -281,10 +335,6 @@ namespace mbts.spark { _cancel_sells_visibility.show = settings.cancel_sells_visible; _cancel_all_visibility.show = settings.cancel_all_visible; price_format = settings.net_change; - // do not read the order entry panel width here from settings - // because it could have changed from the UI - // there might be a better way of doing this, like how - // does the widths of the ladder grid column pull this off? } } @@ -295,6 +345,7 @@ namespace mbts.spark { clone.favorite_algos = favorite_algos_vm.create(); clone.size_display = size_display.create(); clone.calculator_buttons = size_presets.Select(vm => (int)vm.value).ToArray(); + // columns, row height (the latter determined by columns font size) clone.orders_column = _orders.get_settings(); clone.bid_column = _bid.get_settings(); clone.price_column = _price.get_settings(); @@ -302,13 +353,22 @@ namespace mbts.spark { clone.volume_column = _volume.get_settings(); clone.last_column = _last.get_settings(); clone.piq_column = _piq.get_settings(); + clone.row_height = LadderRender.measure_row_height(clone); + // market break lines clone.bid_break_line = _bid_mkt_line.get_settings(); clone.ask_break_line = _ask_mkt_line.get_settings(); clone.mid_break_line = _mid_mkt_line.get_settings(); clone.session_low_line = _session_low_mkt_line.get_settings(); clone.session_high_line = _session_high_mkt_line.get_settings(); clone.session_range_fill = _session_range_fill.get_settings(); - clone.row_height = LadderRender.measure_row_height(clone); + // left-panel (defaults) + if (default_account.HasValue) + clone.default_account = default_account.Value.id; + clone.default_time_in_force = default_time_in_force; + clone.default_algo = default_algo != null ? + AlgoID.from_algo_key(default_algo.key, _model.dynamic_helper.dynamic_type_index) : + (_desired_algo ?? LadderSettings.Default.default_algo); + // left-panel (components) clone.day_visible = _day_visibility.show; clone.high_visible = _high_visibility.show; clone.low_visible = _low_visibility.show; @@ -326,9 +386,9 @@ namespace mbts.spark { clone.cancel_buys_visible = _cancel_buys_visibility.show; clone.cancel_sells_visible = _cancel_sells_visibility.show; clone.cancel_all_visible = _cancel_all_visibility.show; - clone.order_entry_panel_initial_width = _get_order_entry_panel_width(); + clone.order_entry_panel_initial_width = _order_entry_panel_width; clone.zoom_slider_visible = _zoom_slider_visbility.show; - clone.zoom_factor = _get_zoom_factor(); + clone.zoom_factor = zoom_factor; clone.net_change = price_format; return clone; } @@ -350,6 +410,20 @@ namespace mbts.spark { vm.PropertyChanged += (s, e) => RaisePropertyChanged(nameof(size_presets_text)); return vm; } + + void _try_select_desired_account(bool bypass_setter = false) { + if (_desired_account.HasValue && (!_default_account.setter_called || bypass_setter) && _accounts.TryGetValue(_desired_account.Value, out var acc_tup)) { + _desired_account = null; + _default_account.bypass_setter(acc_tup); + } + } + + void _try_select_desired_algo(bool bypass_setter = false) { + if (_desired_algo.HasValue && (!_default_algo.setter_called || bypass_setter) && _algo_definitions.TryGetValue(AlgoID.to_algo_key(_desired_algo.Value, _model.dynamic_helper.dynamic_type_index), out var vm)) { + _desired_algo = null; + _default_algo.bypass_setter(vm); + } + } public class LadderColumnSettingsVM : ViewModelBase, ITemplateSelectorKey { readonly Property _font_size; @@ -360,6 +434,7 @@ namespace mbts.spark { readonly DelegateProperty _font_display_name; readonly Property _show; readonly string _template_key; + uint _width; public LadderColumnSettingsVM(string name, string template_key = null, bool can_toggle_show = false) { this.name = name; @@ -391,7 +466,7 @@ namespace mbts.spark { public FontWeight font_weight => _font_weight.Value; public string font_display_name => _font_display_name.Value; public double font_size { get => _font_size.Value; set => _font_size.Value = value; } - public uint width { get; set; } + public uint width { get => _width; set => Set(ref _width, value); } public bool show { get => _show.Value; set => _show.Value = value; } public bool can_toggle_show { get; } public bool show_details { get; private set; } @@ -416,7 +491,6 @@ namespace mbts.spark { show = settings.show; foreground = settings.foreground.rgb_color(); background = settings.background.rgb_color(); - RaisePropertyChanged(nameof(width), nameof(show)); } public LadderColumnSettings get_settings() { @@ -612,17 +686,15 @@ namespace mbts.spark { } public class FavoriteAlgosVM : DisposableViewModelBase, IValueFactoryVM { - readonly ObservableKeyedCollection _algo_definitions = new ObservableKeyedCollection(d => d.key); + readonly IObservableCollection _algo_definitions; readonly ObservableCollection _raw_items = new ObservableCollection(); int _column_count = 2; - public FavoriteAlgosVM(OrdersModel model) { + public FavoriteAlgosVM(IObservableCollection algo_definitions) { + _algo_definitions = algo_definitions; items = new ObservableAggregateCollection(_raw_items, new ObservableCollection { FavoriteAlgoItem.AddButtonPlaceholderItem }); add_item_cmd = new DelegateCommand(() => _raw_items.Add(_item_factory())); remove_item_cmd = new DelegateCommand(fai => _raw_items.Remove(fai)); - _dispose = model.algo_model.definitions.OnDispatcher().Subscribe(update => { - AlgoCollectionHelper.update_persisted_definitions(_algo_definitions, update, d => AlgoDefinitionVM.create(model, d, false)); - }); } public ObservableCollection items { get; } @@ -644,14 +716,15 @@ namespace mbts.spark { public LadderFavoriteAlgosSettings create() => new LadderFavoriteAlgosSettings(_raw_items .Select(fai => fai.algo_definition?.key ?? fai.selector.desired_key) - .Where(k => k.HasValue) + .Where(k => k.HasValue && k.Value.is_persisted) .Select(k => k.Value) .ToArray(), column_count); FavoriteAlgoItem _item_factory() => new FavoriteAlgoItem(_algo_definitions, new ListCollectionView(_algo_definitions) { - CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic() + CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic(), + Filter = obj => obj is AlgoDefinitionVM vm && vm.key.is_persisted }); } @@ -662,7 +735,7 @@ namespace mbts.spark { protected FavoriteAlgoItem() { } - public FavoriteAlgoItem(ObservableKeyedCollection algo_definitions, ICollectionView algo_definitions_view) { + public FavoriteAlgoItem(IObservableCollection algo_definitions, ICollectionView algo_definitions_view) { selector = new KeyedItemSelector(this, nameof(algo_definition), algo_definitions, d => d.key); this.algo_definitions_view = algo_definitions_view; } diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 678282a83..1af443c18 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -76,7 +76,7 @@ namespace mbts.spark { _zoom_factor = backing(nameof(zoom_factor), ws.zoom_factor); // remember: account_positions needs to subscribe to selected_account; both the sub and account_positions need to be disposed _volume = backing(nameof(volume), 0ul); - _auto_clear = backing(nameof(auto_clear), false); + _auto_clear = backing(nameof(auto_clear), init.auto_clear); _status = backing(nameof(status_message), ""); _status_brush = backing(nameof(status_background), _transparent_status_brush); // All settings observers should be aggregated together, so they can all share the same subscription to the settings @@ -111,6 +111,18 @@ namespace mbts.spark { RaisePropertyChanged(nameof(position_display_text)); } size_calculator.buttons = s.calculator_buttons; + _auto_clear.set(s.auto_clear); + // column widths + _orders_column_width.set(s.orders_column.width); + _bid_column_width.set(s.bid_column.width); + _price_column_width.set(s.price_column.width); + _ask_column_width.set(s.ask_column.width); + _last_column_width.set(s.last_column.width); + _piq_column_width.set(s.piq_column.width); + _volume_column_width.set(s.volume_column.general.width); + // left panel/zoom + _left_panel_width.set(s.order_entry_panel_initial_width); + _zoom_factor.set(s.zoom_factor); } }; PropertyAutoWrapper bool_prop(string name, Func get_bool) => @@ -346,8 +358,8 @@ namespace mbts.spark { } } - public LadderSettings get_save_state() => - _current_settings.with_window_specifics( + public LadderSettings get_save_state() { + var rv = _current_settings.with_window_specifics( new LadderSettings.WindowSpecifics( left_panel_width, orders_column_width, @@ -358,6 +370,14 @@ namespace mbts.spark { volume_column_width, zoom_factor, piq_column_width)); + rv.auto_clear = auto_clear; + rv.default_time_in_force = order_properties_vm.selected_time_in_force; + if (order_properties_vm.selected_account.HasValue) + rv.default_account = order_properties_vm.selected_account.Value.id; + if (order_properties_vm.selected_algo_definition != null) + rv.default_algo = AlgoID.from_algo_key(order_properties_vm.selected_algo_definition.key); + return rv; + } public void key_down(KeyEventArgs e) { if (order_properties_vm == null) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 879ac260f..02c3a7799 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -4,15 +4,16 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ice="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" + 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:sys="clr-namespace:System;assembly=mscorlib" + xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" TextElement.FontSize="{x:Static u:FontSizes.Small}" > - 4 8 12 @@ -27,6 +28,7 @@ 57 70 81 + 50 160 153 @@ -43,11 +45,13 @@ - + + + + - - - - - - - + + + + + + + + + + + + + + + + + + + + + + Left Panel Width + + + + Zoom Factor + + + + + + + + + + + + + + + + + + + + + Account + + + Time In Force + + + Algo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + @@ -873,6 +873,8 @@ + + Left Panel Width @@ -882,6 +884,10 @@ Zoom Factor + + + Auto Clear + @@ -923,7 +929,7 @@ - + From 85947080738dfefa9b47c161406ca0f6bfa9a316 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 18:47:24 -0500 Subject: [PATCH 22/30] LadderVM.get_save_state - null check for order_properties_vm --- .../spark/Modules/Trading/Ladder/VM/LadderVM.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index 1495126f5..b2fb11823 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -371,11 +371,13 @@ namespace mbts.spark { zoom_factor, piq_column_width)); rv.auto_clear = auto_clear; - rv.default_time_in_force = order_properties_vm.selected_time_in_force; - if (order_properties_vm.selected_account.HasValue) - rv.default_account = order_properties_vm.selected_account.Value.id; - if (order_properties_vm.selected_algo_definition != null) - rv.default_algo = AlgoID.from_algo_key(order_properties_vm.selected_algo_definition.key, _model.order_gateway.dynamic_helper.dynamic_type_index); + if (order_properties_vm != null) { + rv.default_time_in_force = order_properties_vm.selected_time_in_force; + if (order_properties_vm.selected_account.HasValue) + rv.default_account = order_properties_vm.selected_account.Value.id; + if (order_properties_vm.selected_algo_definition != null) + rv.default_algo = AlgoID.from_algo_key(order_properties_vm.selected_algo_definition.key, _model.order_gateway.dynamic_helper.dynamic_type_index); + } return rv; } From 5b767482d7d082ecb9770004c524690ad303f1f8 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 18:58:50 -0500 Subject: [PATCH 23/30] LadderSettingsView - rearrange GroupBoxes in 'Left Panel' tab --- .../Ladder/View/LadderSettingsView.xaml | 96 +++++++++---------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index b1ef30bfa..f5fcbc6e3 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -836,8 +836,9 @@ - + + 22 @@ -848,76 +849,71 @@ - - - - - - - - + + + - - + - - - + - + - + + + + + + + Left Panel Width - - + + + + + + + + + + + Zoom Factor - - - - - Auto Clear - - - - - - - - - - - - - - - - - + + + + + + + + + + + - Account - + Account + - Time In Force - + Time In Force + - Algo - + Algo + @@ -927,9 +923,13 @@ + + + Auto Clear + - + From 2bc54b0dbb445bcb089896a215004f08f667267d Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 19:00:47 -0500 Subject: [PATCH 24/30] LadderSettingsView - 'Market Price/Size' tab Grid.IsSharedSizeScope=True --- .../spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index f5fcbc6e3..4a15def0e 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -625,7 +625,7 @@ - + From fa51d7f44183d6095020a6413acf627945f9692d Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 22:14:29 -0500 Subject: [PATCH 25/30] LadderSettingsView - abstract magic const out into StaticResource --- .../Modules/Trading/Ladder/View/LadderSettingsView.xaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml index 4a15def0e..23a767e3a 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderSettingsView.xaml @@ -839,6 +839,7 @@ 22 + 32 @@ -882,7 +883,7 @@ - + @@ -895,7 +896,7 @@ - + From 2b3901fdbe2ac068389ed403f7e4c3d930a1552c Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 18 Jun 2019 22:15:52 -0500 Subject: [PATCH 26/30] dispose LadderSettingsDialog viewmodel when window closes --- .../Trading/Ladder/LadderWindowFactory.cs | 43 ++++++++++++++++--- .../Shell/Settings/ShellSettingsDialogVM.cs | 3 +- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 7025f59db..9e733bfb1 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -158,18 +158,51 @@ namespace bts.shell { Title = $"Ladder Settings - '{vm.security}'" }; dialog.Resources[ShellSettingsDialog.SecurityMapKey] = _securities; - dialog_vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); - Disposable.replace(ref active_settings_dialog, Disposable.Create(() => { - Disposable.dispose(ref dialog_vm); - WindowUtilities.force_close(dialog); - })); + dialog_vm.RequestClose += on_request_close; + dialog.Closed += on_closed; + Disposable.replace(ref active_settings_dialog, Disposable.Create(destroy_all)); dialog.move_to_mouse(-500, -500); dialog.Show(); + // local methods void apply(SettingsProfile profile) { settings_id = profile.id; last_value = profile.value; settings_subject.OnNext(profile.value); } + // idempotent + void destroy_all() { + destroy_window(); + destroy_vm(); + } + // idempotent + void destroy_window() { + if (dialog == null) return; + try { + var temp = dialog; + dialog = null; + temp.Closed -= on_closed; + temp.Close(); + } catch (Exception ex) { + on_error("closing window", ex); + } + } + // idempotent + void destroy_vm() { + if (dialog_vm == null) return; + try { + var temp = dialog_vm; + dialog_vm = null; + temp.applied -= apply; + temp.RequestClose -= on_request_close; + temp.Dispose(); + } catch (Exception ex) { + on_error("disposing vm", ex); + } + } + void on_closed(object sender, EventArgs e) => destroy_all(); + void on_request_close(object sender, EventArgs e) => destroy_all(); + void on_error(string action_desc, Exception error) => + Log.Ui.warn($"LadderSettingsDialog error {action_desc}: {error}."); } }); string thread = _ladder_conf.ladders_on_threads ? $"Ladder{thread_id:00}" : ""; diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs index 61716735b..d3e7591af 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs @@ -330,10 +330,11 @@ namespace mbts.spark { _committed = _last_result = create(); _is_dirty = backing(nameof(is_dirty), () => !_last_result.Equals(_committed)); _refresh_is_dirty = new DeferrableActionWrapper(_is_dirty.refresh); - _dispose = value.Subscribe(v => { + var sub = value.Subscribe(v => { _last_result = _last_result.with(value: v); _refresh_is_dirty.execute(); }); + _dispose = value is IDisposable d ? Disposable.Create(sub, d) : sub; } public uint id { get; } From 11ca6326f3db5c670eecd934548475b6a30f25fa Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 19 Jun 2019 13:19:09 -0500 Subject: [PATCH 27/30] refactor 'AlgoID.from_order_def' -> 'AlgoID.from_custom_def' --- .../spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs | 10 +++++----- .../OrderBook/Settings/OrderBookFilterStates.cs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs index 14dcdd6fc..e7b16bc26 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoKey.cs @@ -39,11 +39,11 @@ namespace mbts.spark { _persisted_key = persisted_key; } - public static AlgoID from_order_def(OrderDefinitionImmutable order_def) { - switch (order_def.CustomDef.CustomCase) { - case CustomOrderDefinition.CustomOneofCase.Composite: return new AlgoID(order_def.CustomDef.Composite.AlgoTemplateKey); - case CustomOrderDefinition.CustomOneofCase.Dynamic: return new AlgoID(order_def.CustomDef.Dynamic.DynamicOrderType); - default: return new AlgoID(order_def.CustomDef.CustomCase); + public static AlgoID from_custom_def(CustomOrderDefinitionImmutable custom_def) { + switch (custom_def.CustomCase) { + case CustomOrderDefinition.CustomOneofCase.Composite: return new AlgoID(custom_def.Composite.AlgoTemplateKey); + case CustomOrderDefinition.CustomOneofCase.Dynamic: return new AlgoID(custom_def.Dynamic.DynamicOrderType); + default: return new AlgoID(custom_def.CustomCase); } } diff --git a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs index 4253a5e24..52c09c565 100644 --- a/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs +++ b/src/client/spark/Modules/Trading/OrderBook/Settings/OrderBookFilterStates.cs @@ -136,7 +136,7 @@ namespace bts.shell.orderbook { pb.add_discrete_values(fs.accounts, o => o.order.account()); pb.add_discrete_values(fs.exchanges, o => o.security?.Exchange ?? Venue.Unset); pb.add_discrete_values(fs.tifs, o => o.order.time_in_force()); - pb.add_discrete_values(fs.order_types, o => AlgoID.from_order_def(o.order.Def)); + pb.add_discrete_values(fs.order_types, o => AlgoID.from_custom_def(o.order.Def.CustomDef)); pb.add_discrete_values(fs.root_algo_types, o => AlgoID.from_algo_key(o.root_algo.key, dynamic_type_index)); pb.add_discrete_values(fs.order_sub_types, o => o.order.sub_type()); pb.add_discrete_values(fs.sides, o => o.order.side()); From 8b33c7fb5cba19a59bbac956f3132b2447b53371 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 19 Jun 2019 13:21:36 -0500 Subject: [PATCH 28/30] Ladder Profile's 'default_algo' is fit to the security type (allows profiles to be shared between outrights/synths) --- .../Trading/Ladder/LadderWindowFactory.cs | 49 +++++++++++++++---- .../Shell/Settings/ShellSettingsDialogVM.cs | 9 ++-- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index 9e733bfb1..507a736a8 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -4,9 +4,9 @@ using mbts; using mbts.config; using mbts.persist; using mbts.spark; +using mbts.spark.utilities; using mbts.ui; using mbts.ui.spark; -using mbts.ui.utility; using ProtoBuf; using System; using System.Collections.Generic; @@ -62,9 +62,17 @@ namespace bts.shell { LadderSaveState _get_state(LadderVM vm, uint id) { LadderSettings s = vm.get_save_state(); - if (id != 0 && (!_settings_hub.current.ladder_profiles.TryGetFirst(lp => lp.id == id, out var result) || !s.Equals(result.value))) { - // either the profile was deleted, or the ladder settings diverged from the profile (this happens when the user changes settings outside of the settings dialog, such as column widths, left panel width, etc.) - id = 0; + if (id != 0) { + if (!_settings_hub.current.ladder_profiles.TryGetFirst(lp => lp.id == id, out var result)) { + // profile was deleted + id = 0; + } else { + var curr_profile = _fit_to_sec(result.value, vm.security.ContractCase); + if (!s.Equals(curr_profile)) { + // ladder's settings diverged from the profile (this happens when the user changes settings outside of the settings dialog, such as column widths, left panel width, etc.) + id = 0; + } + } } return new LadderSaveState { security_key = vm.security.Id, settings = s, settings_id = id }; } @@ -81,7 +89,7 @@ namespace bts.shell { lp => lp.id, lp => new SettingsProfile(lp.id, lp.name, sanitize_ladder_settings(lp.value), lp.security_criteria))), (us, lps) => us.with(ladder_profiles: lps.Values.Select(lp => new LadderSettingsProfile(lp.id, lp.name, lp.value, lp.security_criteria)).ToArray())); - LadderSettings last_value = state_settings; + LadderSettings last_value = fit_to_sec(state_settings); var settings_subject = new BehaviorSubject(last_value); // vm var vm = LadderVM.create(_bus, model, last_value ?? _settings_hub.current.ladder, settings_subject.Where(s => s != null)); @@ -100,6 +108,9 @@ namespace bts.shell { lv.Resources[kv.Key] = kv.Value; return lv; // local methods + LadderSettings fit_to_sec(LadderSettings s) => + _fit_to_sec(s, md.security.ContractCase); + void on_user_settings(UserSettings us) { if (initialized) { if (settings_id == 0) { @@ -109,7 +120,7 @@ namespace bts.shell { if (!last_value.Equals(vm.get_save_state())) { settings_id = 0; } else { - settings_subject.OnNext(last_value = profile.value); + settings_subject.OnNext(last_value = fit_to_sec(profile.value)); } } else { // profile was deleted; keep the current settings and switch to the 'Local' profile. @@ -119,7 +130,7 @@ namespace bts.shell { initialized = true; if (settings_id != 0) { if (us.ladder_profiles.TryGetFirst(p => p.id == settings_id, out var profile)) { - last_value = profile.value; + last_value = fit_to_sec(profile.value); } else { settings_id = 0; } @@ -129,19 +140,20 @@ namespace bts.shell { // TODO: Use a kind of 'match priority' to resolve conflicts when the security is included in more than 1 profile's security criteria. // In the meantime, simply use the first match. if (lp.security_criteria.includes(md.security)) { - last_value = lp.value; + last_value = fit_to_sec(lp.value); settings_id = lp.id; break; } } if (last_value == null) - last_value = _settings_hub.current.ladder; + last_value = fit_to_sec(_settings_hub.current.ladder); } settings_subject.OnNext(last_value); } } void open_settings_dialog() { + // dialog vm var dialog_vm = new ProfiledShellSettingsDialogVM( profile_service, us => us.ladder ?? LadderSettings.Default, @@ -149,10 +161,13 @@ namespace bts.shell { var svm = new LadderSettingsVM(model.order_gateway, vm.security); svm.load(s); return svm; - }, vm.get_save_state(), + }, + fit_to_sec, + vm.get_save_state(), UserSettings.FileExtensions.LADDER, settings_id); dialog_vm.applied += apply; + // dialog var dialog = new ShellSettingsDialog { DataContext = dialog_vm, Title = $"Ladder Settings - '{vm.security}'" @@ -251,6 +266,20 @@ namespace bts.shell { } } + LadderSettings _fit_to_sec(LadderSettings s, Security.ContractOneofCase sec_type) { + if (s == null) return null; + var algo_key = AlgoID.to_algo_key(s.default_algo, _orders_model.dynamic_helper.dynamic_type_index); + if (algo_key.mode == AlgoKey.Mode.Factory) { + var fitted_algo = OrderDataHelper.fit_to_type(algo_key.factory.structure.build_algo(_orders_model.dynamic_helper), sec_type); + if (fitted_algo.HasValue) { + // be sure to clone ('s' may be shared) + s = SparkUtils.clone_proto(s); + s.default_algo = AlgoID.from_custom_def(fitted_algo.Value); + } + } + return s; + } + readonly struct LadderConfig { public readonly uint max_open_ladders; public readonly bool ladders_on_threads, open_algo_popup_on_select, use_algo_param_grid; diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs index d3e7591af..f6cdeafd6 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialogVM.cs @@ -124,7 +124,7 @@ namespace mbts.spark { DialogSkirtItem _apply_item, _ok_item, _cancel_item; MenuItemVM _import_item, _export_item, _load_factory_item; - public ProfiledShellSettingsDialogVM(ISettingsProfileService profile_service, Func get_fallback, Func vm_factory, T init, string file_ext, uint settings_id = 0) { + public ProfiledShellSettingsDialogVM(ISettingsProfileService profile_service, Func get_fallback, Func vm_factory, Func normalize, T init, string file_ext, uint settings_id = 0) { _vm_factory = vm_factory; // profile collections var skip_local = profiles.WrapSkip(1); @@ -178,9 +178,10 @@ namespace mbts.spark { if (i >= 0) continue; i = ~i; - skip_local_wrapper.Insert(i, ns); - if (settings_id == ns.id) { - if (ns.value.Equals(init)) + var temp = ns.with(value: normalize(ns.value)); + skip_local_wrapper.Insert(i, temp); + if (settings_id == temp.id) { + if (temp.value.Equals(init)) selected_profile = skip_local[i]; settings_id = 0; } From 0a3e12e01203cb408b3123d99ac1141a69ea50d5 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 19 Jun 2019 13:42:20 -0500 Subject: [PATCH 29/30] SPARK-2521 / SPARK-2522 rename 'Local' -> 'Custom' --- .../spark/view/Shell/Settings/ShellSettingsDialog.xaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml index 21eb7eb83..2394396fa 100644 --- a/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml +++ b/src/client/spark/view/Shell/Settings/ShellSettingsDialog.xaml @@ -130,10 +130,10 @@ - + - + @@ -223,13 +223,13 @@ - + - + - + From d9b25fb778f9f03fe2d46a5cb3b45f9f21fbceb6 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 19 Jun 2019 13:53:12 -0500 Subject: [PATCH 30/30] threadstatic fields cannot be initialized inline --- src/client/spark/core/Utility/ProtoHelper.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/client/spark/core/Utility/ProtoHelper.cs b/src/client/spark/core/Utility/ProtoHelper.cs index 31d54f208..1f65f357d 100644 --- a/src/client/spark/core/Utility/ProtoHelper.cs +++ b/src/client/spark/core/Utility/ProtoHelper.cs @@ -61,7 +61,8 @@ namespace bts.utils { static class MutableFactoryStore { [ThreadStatic] - static readonly Dictionary> _factories = new Dictionary>(); + static Dictionary> _factories_backing; + static Dictionary> _factories => _factories_backing ?? (_factories_backing = new Dictionary>()); public static Func get(Type type) => _factories.GetOrAdd(type,