From 54d82e1773f447690faea606c6fffed4ec115c44 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Tue, 10 Dec 2019 17:38:49 -0600 Subject: [PATCH] DeleteSyntheticDaemon - improve logging, support batch delete --- .../spark/Daemons/DeleteSyntheticDaemon.cs | 97 ++++++++++++++++--- .../Spreader/Import/SyntheticImporter.cs | 6 +- .../spark/Modules/Spreader/SpreaderModel.cs | 22 +++++ .../Spreader/SyntheticManagementWindow.cs | 2 +- src/client/spark/Orders/OrdersModel.cs | 6 ++ src/client/spark/core/Bus/SparkTags.cs | 2 +- 6 files changed, 116 insertions(+), 19 deletions(-) diff --git a/src/client/spark/Daemons/DeleteSyntheticDaemon.cs b/src/client/spark/Daemons/DeleteSyntheticDaemon.cs index 52819f4e3..e9f0758d7 100644 --- a/src/client/spark/Daemons/DeleteSyntheticDaemon.cs +++ b/src/client/spark/Daemons/DeleteSyntheticDaemon.cs @@ -4,43 +4,112 @@ using mbts; using mbts.spark; using mbts.ui; using System; +using System.Collections.Generic; +using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; +using System.Threading; +using System.Windows; namespace bts { [Export, Export(typeof(IShellDaemon))] class DeleteSyntheticDaemon : IShellDaemon, IDisposable { + // request_id is noted in the series of log messages that occur during a particular delete op. + static int _request_id = 1; + readonly OrdersModel _orders_model; readonly ErrorReporter _error_reporter; + IReadOnlyDictionary _strategy_map = + DictionaryHelper.empty(); + IDisposable _dispose; [ImportingConstructor] public DeleteSyntheticDaemon(IBus bus, OrdersModel orders_model, ErrorReporter error_reporter) { _orders_model = orders_model; _error_reporter = error_reporter; - _dispose = bus.subscribe(SparkTags.SyntheticDeleteTag) - .OnDispatcher() - .Subscribe(_delete_synthetic); + _dispose = Disposable.Create( + bus.subscribe(SparkTags.SyntheticDeleteTag).Subscribe(_delete_synthetic), + orders_model.spreader.strategy.Subscribe(map => _strategy_map = map)); } public void Dispose() => Disposable.dispose(ref _dispose); - async void _delete_synthetic(uint id) { - var (orders, orders_success) = await _orders_model.on_orders.FirstAsyncTask(SparkUtils.DefaultTimeOut); + async void _delete_synthetic(IImmutableSet keys) { + var log = new LoggerContext(Log.Ui, $"Synthetic Delete Req {unchecked(Interlocked.Increment(ref _request_id))} - ", null); + if (keys.is_null_or_empty()) { + log.warn("received empty delete request (no securities specified)."); + return; + } + log.info($"received request to delete the following {keys.Count} securities: {string.Join(", ", keys)}"); + var (orders, orders_success) = await _orders_model.security_order_groups.FirstAsyncTask(SparkUtils.DefaultTimeOut); if (!orders_success) { - _error_reporter.report_error($"Unable to delete synthetic security ({id}): unable to determine whether or not security ({id}) has working orders (deletion is not permitted while there are working orders)."); - Log.Ui.warn($"Ignoring request to delete synthetic security ({id}) because the orders lookup timed out (must confirm no working orders)."); - } else if (orders.state.Values.Any(o => o.order.Def.SecurityKey == id && o.order.is_non_terminal())) { - Log.Ui.warn($"Ignoring request to delete synthetic security ({id}) because non-terminal-orders were detected."); + var msg = "Unable to delete synthetic securities: " + + $"timed out waiting for orders table (must verify that a synthetic security does not have any working orders before it can be deleted)."; + _error_reporter.report_error(msg); + log.warn(msg); } else { - ExecutionStrategyImmutable? strategy = await _orders_model.spreader.lookup_strategy_async(id); - if (strategy.HasValue) { - ExecutionStrategyImmutable deleted_strategy = strategy.Value.with(deleted: true); - await _orders_model.spreader.save_strategy(id, deleted_strategy); + var working_orders = new List(); + var missing_strategies = new List(); + var items = new List<(uint key, ExecutionStrategyImmutable strategy)>(); + var temp_strats = _strategy_map; + foreach (var k in keys) { + if (orders.state.TryGetValue(k, out var sec_group) && sec_group.table.state.Values.Any(tup => tup.order.is_active())) { + working_orders.Add(k); + } else if (!temp_strats.TryGetValue(k, out var strat)) { + missing_strategies.Add(k); + } else { + items.Add((k, strat.with(deleted: true))); + } } + var lines = new List(); + if (working_orders.Count > 0) { + lines.Add($"skipping {working_orders.Count} securities because they have working orders."); + } + if (missing_strategies.Count > 0) { + lines.Add($"skipping {missing_strategies.Count} securities because their execution strategies were not discovered."); + } + if (lines.Count > 0) + log.warn(string.Join("; ", lines)); + var errors = await _orders_model.spreader.save_strategies(items); + int error_count = errors.Count(e => !string.IsNullOrEmpty(e)); + log.info($"{items.Count - error_count}/{items.Count} attempted deletes were successful (skipped {working_orders.Count + missing_strategies.Count})."); + // display results to user + const string dialog_title = "Synthetic Deletion"; + string display_msg; + MessageBoxImage icon = MessageBoxImage.None; + if (keys.Count > 1) { + if (error_count == 0 && working_orders.Count == 0 && missing_strategies.Count == 0) { + display_msg = $"Synthetic securities have been deleted."; + icon = MessageBoxImage.Information; + } else { + display_msg = $"{keys.Count - error_count - working_orders.Count - missing_strategies.Count}/{keys.Count} securities were successfully deleted."; + icon = MessageBoxImage.Error; + } + } else { + if (error_count == 0 && working_orders.Count == 0 && missing_strategies.Count == 0) { + display_msg = "Synthetic security has been deleted."; + icon = MessageBoxImage.Information; + } else { + string reason; + if (error_count > 0) { + reason = errors[0]; + } else if (missing_strategies.Count > 0) { + reason = "did not find execution strategy."; + } else if (working_orders.Count > 0) { + reason = "working orders detected."; + } else { + // unexpected code path + reason = "unknown error."; + } + icon = MessageBoxImage.Error; + display_msg = $"Unable to delete synthetic security: " + reason; + } + } + BTSMessageBox.Show(display_msg, dialog_title, BTSMessageBoxButtons.OK, icon); } } } -} \ No newline at end of file +} diff --git a/src/client/spark/Modules/Spreader/Import/SyntheticImporter.cs b/src/client/spark/Modules/Spreader/Import/SyntheticImporter.cs index 0b8b2c802..7271fa417 100644 --- a/src/client/spark/Modules/Spreader/Import/SyntheticImporter.cs +++ b/src/client/spark/Modules/Spreader/Import/SyntheticImporter.cs @@ -7,6 +7,7 @@ using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reactive.Linq; @@ -167,9 +168,8 @@ namespace mbts.spark { $"{num_succeeded}/{parsed_synths.Count} synthetics were successfully imported.\n" + "Would you like to keep the imports that were successful?", _import_title)) { - Parallel.ForEach( - new_ids.Where(r => r.key.HasValue), - r => bus.post(SparkTags.SyntheticDeleteTag, r.key.Value)); + bus.post(SparkTags.SyntheticDeleteTag, + ImmutableHashSet.CreateRange(new_ids.Where(r => r.key.HasValue).Select(r => r.key.Value))); } } else { BTSMessageBox.Show( diff --git a/src/client/spark/Modules/Spreader/SpreaderModel.cs b/src/client/spark/Modules/Spreader/SpreaderModel.cs index 4c4e330f4..d71b8faea 100644 --- a/src/client/spark/Modules/Spreader/SpreaderModel.cs +++ b/src/client/spark/Modules/Spreader/SpreaderModel.cs @@ -163,6 +163,28 @@ namespace mbts.spark { (r, success) => success, "saving strategy"); + public async Task save_strategies(IEnumerable<(uint key, ExecutionStrategyImmutable strategy)> items) { + // Copy everything to a new list, to guarentee that it won't be altered during the op. + // The performance impact should be insignificant, as this should be a rare call. + var item_list = new List<(uint key, ExecutionStrategyImmutable strategy, int index)>(items.Select((item, index) => (item.key, item.strategy, index))); + string[] errors = new string[item_list.Count]; + await Task.WhenAll(item_list.Select(impl)); + return errors; + async Task impl((uint key, ExecutionStrategyImmutable strategy, int index) tup) { + var (key, strategy, index) = tup; + try { + var result = await _service.update_security_metadata_async(new Metadata { + SecurityKey = key, + Strategy = strategy.CloneToMutable() + }); + if (!result.success) + errors[index] = result.error_message; + } catch (Exception ex) { + errors[index] = ex.ToString(); + } + } + } + public async Task verify_name_is_unique(string name) { var (result, success) = await strategy_tuple.FirstAsyncTask(SparkUtils.DefaultTimeOut); name = name.Trim().ToLower(); diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index 52c33465f..e7b449de9 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -112,7 +112,7 @@ namespace mbts.spark { r == null ? Observable.Return(new RowStrategy?()) : _orders_model.spreader.security_strategy(r.security.Id).Select(strategy => RowStrategy.create(r.security, strategy)); - uint select_security_id(RowModificationParams? rmp) => rmp.HasValue ? rmp.Value.security.Id : 0; + IImmutableSet select_security_id(RowModificationParams? rmp) => ImmutableHashSet.Create(rmp.HasValue ? rmp.Value.security.Id : 0); (SecurityImmutable, ExecutionStrategyImmutable) select_row_strategy_tuple(RowStrategy? rs) => rs.HasValue ? (rs.Value.security, rs.Value.strategy) : default; bool can_execute(RowModificationParams? rmp) => rmp.HasValue && !rmp.Value.has_working_orders; diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index ccc189f82..e8106c1db 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -148,6 +148,11 @@ namespace mbts.spark { OrderSecurityRootPair.from_order_security, OrderSecurityHelper.root_pair_key_fn ).Cache(); + // security order groups + security_order_groups = on_orders + .SelectKeyValue(tup => new OrderSecurity(tup), OrderSecurityHelper.key_fn) + .GroupTable(OrderSecurityHelper.key_fn, tup => tup.order.Def.SecurityKey) + .Cache(); // working account orders var working_account_order_groups = working_orders.GroupTable(t => t.order.Key, t => new PNLKey(t.order.account_id(), t.order.security_key())); // security account pnl @@ -278,6 +283,7 @@ namespace mbts.spark { public IObservable> studio_algos_with_meta { get; } public IObservable> on_manual_fills_securities { get; } public IObservable> on_manual_fill_tuples { get; } + public IObservable, uint>> security_order_groups { get; } public AdminModel admin_model { get; } public MBOService mbo_service => _mbo_service; diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index 311e7fb13..326e97026 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -79,7 +79,7 @@ namespace mbts.spark { #endregion - public static ITag SyntheticDeleteTag { get; } = new SparkTag(nameof(SyntheticDeleteTag)); + public static ITag> SyntheticDeleteTag { get; } = new SparkTag>(nameof(SyntheticDeleteTag)); public static ITag ShowGlobalAlertsTag { get; } = new SparkTag(nameof(ShowGlobalAlertsTag));