diff --git a/src/client/spark/Admin/AdminModel.cs b/src/client/spark/Admin/AdminModel.cs index 6ba429faf..7cf24f3cf 100644 --- a/src/client/spark/Admin/AdminModel.cs +++ b/src/client/spark/Admin/AdminModel.cs @@ -109,6 +109,22 @@ namespace mbts.spark { public AccountTuple? get_default_account() => _account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst(); + public async Task[]> set_risk_limits(IReadOnlyDictionary> state) { + var results = await Task.WhenAll(state.Select(impl)); + return results; + async Task> impl(KeyValuePair> kv) { + var prlimits = new ProprietaryRiskLimits(); + foreach (var (sec, lim) in kv.Value) { + var api_lim = AccountSecurityRiskLimitsDataHelper.from_client_data(sec, lim); + prlimits.SecurityLimits.Add(api_lim); + } + return await _service.update_proprietary_risk_limits_async(new ProprietaryRiskLimitsAPIArgument { + AccountId = kv.Key, + ProprietaryRiskLimits = prlimits + }); + } + } + public Task<(bool success, string error_msg)> add_or_update_risk_limits(uint account_key, IEnumerable<(uint security_key, RiskLimits limits)> new_limits) { return _modify_risk_limits("Updating Risk Limits", account_key, add_limits); // diff --git a/src/client/spark/Admin/RiskLimits.cs b/src/client/spark/Admin/RiskLimits.cs index 3cacb23f6..cc93bfef7 100644 --- a/src/client/spark/Admin/RiskLimits.cs +++ b/src/client/spark/Admin/RiskLimits.cs @@ -22,6 +22,9 @@ namespace bts.admin.risk { public override int GetHashCode() => EqualityComparer.auto_phase(security.GetHashCode(), account.GetHashCode()); + + public static bool operator ==(AccountSecurityKey a, AccountSecurityKey b) => a.Equals(b); + public static bool operator !=(AccountSecurityKey a, AccountSecurityKey b) => !a.Equals(b); } readonly struct AccountSecurityRiskLimits : IEquatable { @@ -138,9 +141,9 @@ namespace bts.admin.risk { api_data.MinSellPrice, api_data.MaxBuyPrice)); - public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null) => + public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null, AccountSecurityKey? key = null) => new AccountSecurityRiskLimits( - cli_data.key, + key ?? cli_data.key, limits ?? cli_data.limits, account: account ?? new AccountTuple(cli_data.account_key, cli_data.account_name), security: security ?? cli_data.security); diff --git a/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsImporter.cs b/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsImporter.cs new file mode 100644 index 000000000..6c5383280 --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsImporter.cs @@ -0,0 +1,105 @@ +using bts.admin.risk; +using bts.api.core; +using bts.collections; +using mbts; +using mbts.ui; +using mbts.ui.utility; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reactive.Linq; +using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent; + +namespace bts.shell.risk_management { + static class RiskLimitsImporter { + /// + /// Parses the specified file and passes the results to the delegate. + /// If the parser encounters improperly formatted values, a dialog is automatically opened + /// + /// An IDisposable that will close the import-conflicts-dialog (if it was launched). + public static IDisposable import_limits(string file_name, IReadOnlyDictionary security_map, IReadOnlyDictionary account_map, Action> on_parsed) { + if (string.IsNullOrEmpty(file_name)) + throw new ArgumentException("File name is null or empty.", nameof(file_name)); + if (security_map is null) + throw new ArgumentNullException(nameof(security_map)); + if (account_map is null) + throw new ArgumentNullException(nameof(account_map)); + if (on_parsed is null) + throw new ArgumentNullException(nameof(on_parsed)); + IReadOnlyList parsed_limit_items; + try { + parsed_limit_items = RiskLimitsParser.parse_rows( + File.ReadAllLines(file_name), + MappedDictionary.create(security_map, sec_md => sec_md.security), + account_map) + .ToList(); + } catch (Exception ex) { + BTSMessageBox.Error($"Error importing limits: {ex}.", RiskManagementWindow.window_type_display_name); + return null; + } + var conflicts = RiskLimitsParser.get_conflicts(parsed_limit_items); + if (conflicts.Count > 0) { + // init vm + var vm = new RiskLimitsImportVM(parsed_limit_items.Count) { + security_map = security_map + }; + // add rows + foreach (var kv in conflicts) { + var resolve_del = RiskLimitsParser.assign_component(kv.Key); + foreach (var text_groups in kv.Value) { + var eval = get_error_value(kv.Key); + var row = new RiskLimitsImportVM.Row(kv.Key, text_groups.Key, text_groups.Value, eval, eval); + vm.rows.Add(row); + vm.import_request += () => { + foreach (var pmf in text_groups.Value) { + if (resolve_del(pmf.result, row.value) is AccountSecurityRiskLimits resolved) + pmf.result = resolved; + } + }; + } + } + var win = new RiskLimitsImportConflictsDialog { + DataContext = vm, + Title = RiskManagementWindow.window_type_display_name, + Topmost = true + }; + IDisposable dispose = null; + vm.RequestClose += (s, e) => Disposable.dispose(ref dispose); + vm.import_request += () => { + on_parsed(parsed_limit_items); + Disposable.dispose(ref dispose); + }; + Disposable.dispose(ref dispose); + vm.accounts.SetItems(account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).Cast()); + dispose = Disposable.Create( + vm, + Disposable.Create(close)); + win.move_to_mouse(-200, -75); + win.Show(); + return dispose; + + void close() => WindowUtilities.force_close(win); + object get_error_value(Component component) { + switch (component) { + case Component.MaxNetLongPosition: + case Component.MaxNetShortPosition: + case Component.ClipLimit: + return 0; + case Component.MinPrice: + case Component.MaxPrice: + return double.NaN; + case Component.IsPositionLimitEnabled: + case Component.IsClipLimitEnabled: + case Component.IsPriceLimitEnabled: + return false; + default: return null; + } + } + } else { + on_parsed(parsed_limit_items); + } + return null; + } + } +} diff --git a/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsParser.cs b/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsParser.cs new file mode 100644 index 000000000..0b7be320a --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/Model/RiskLimitsParser.cs @@ -0,0 +1,250 @@ +using bts.admin.risk; +using bts.api; +using bts.collections; +using bts.utils; +using mbts.ui.utility; +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using RiskLimitsComponent = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent; + +namespace bts.shell.risk_management { + class ParsedRiskLimits { + public readonly Guid unpersisted_id = Guid.NewGuid(); + public AccountSecurityRiskLimits result { get; set; } + + public (string text, bool success) security { get; set; } + public (string text, bool success) account { get; set; } + public (string text, bool success) max_long_position { get; set; } + public (string text, bool success) max_short_position { get; set; } + public (string text, bool success) is_position_limit_enabled { get; set; } + public (string text, bool success) clip_limit { get; set; } + public (string text, bool success) is_clip_limit_enabled { get; set; } + public (string text, bool success) min_price { get; set; } + public (string text, bool success) max_price { get; set; } + public (string text, bool success) is_price_limit_enabled { get; set; } + + public bool Equals(ParsedRiskLimits other) => other != null && unpersisted_id == other.unpersisted_id; + public override bool Equals(object obj) => Equals(obj as ParsedRiskLimits); + public override int GetHashCode() => unpersisted_id.GetHashCode(); + } + + static class RiskLimitsParser { + public const string file_extension = "csv"; + + public static Func assign_component(RiskLimitsComponent component) { + switch (component) { + case RiskLimitsComponent.Security: return (mf, val) => mf.with(key: new AccountSecurityKey(mf.account_key, ConvertUtils.try_convert(val)?.Id ?? 0)); + case RiskLimitsComponent.Account: return (mf, val) => mf.with(key: new AccountSecurityKey(ConvertUtils.try_convert(val)?.id ?? 0, mf.key.security)); + case RiskLimitsComponent.MaxNetLongPosition: return (mf, val) => mf.with(mf.limits.with(max_long_position: ConvertUtils.try_convert(val))); + case RiskLimitsComponent.MaxNetShortPosition: return (mf, val) => mf.with(mf.limits.with(max_short_position: ConvertUtils.try_convert(val))); + case RiskLimitsComponent.IsPositionLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert(val))); + case RiskLimitsComponent.ClipLimit: return (mf, val) => mf.with(mf.limits.with(clip_limit: ConvertUtils.try_convert(val))); + case RiskLimitsComponent.IsClipLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert(val))); + case RiskLimitsComponent.MinPrice: return (mf, val) => mf.with(mf.limits.with(min_price: ConvertUtils.try_convert(val, double.NaN))); + case RiskLimitsComponent.MaxPrice: return (mf, val) => mf.with(mf.limits.with(max_price: ConvertUtils.try_convert(val, double.NaN))); + case RiskLimitsComponent.IsPriceLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert(val))); + default: throw new NotImplementedException(); + } + } + + public static ImmutableDictionary>> get_conflicts(IEnumerable parsed_limits) { + // Add all the components up front (a simple optimizatino since there aren't many), + // so there is no need to check for there existence as various conflicts are added. + // After all conflicts have been added, remove the empty entries. + var missing_components = EnumHelper.get_values() + .ToImmutableDictionary(c => c, c => ImmutableDictionary>.Empty) + .ToBuilder(); + foreach (var pmf in parsed_limits) { + if (!pmf.security.success) { + add_missing(RiskLimitsComponent.Security, pmf.security.text, pmf); + } + if (!pmf.account.success) { + add_missing(RiskLimitsComponent.Account, pmf.account.text, pmf); + } + if (!pmf.max_long_position.success) { + add_missing(RiskLimitsComponent.MaxNetLongPosition, pmf.max_long_position.text, pmf); + } + if (!pmf.max_short_position.success) { + add_missing(RiskLimitsComponent.MaxNetShortPosition, pmf.max_short_position.text, pmf); + } + if (!pmf.is_position_limit_enabled.success) { + add_missing(RiskLimitsComponent.IsPositionLimitEnabled, pmf.is_position_limit_enabled.text, pmf); + } + if (!pmf.clip_limit.success) { + add_missing(RiskLimitsComponent.ClipLimit, pmf.clip_limit.text, pmf); + } + if (!pmf.is_clip_limit_enabled.success) { + add_missing(RiskLimitsComponent.IsClipLimitEnabled, pmf.is_clip_limit_enabled.text, pmf); + } + if (!pmf.min_price.success) { + add_missing(RiskLimitsComponent.MinPrice, pmf.min_price.text, pmf); + } + if (!pmf.max_price.success) { + add_missing(RiskLimitsComponent.MaxPrice, pmf.max_price.text, pmf); + } + if (!pmf.is_price_limit_enabled.success) { + add_missing(RiskLimitsComponent.IsPriceLimitEnabled, pmf.is_price_limit_enabled.text, pmf); + } + } + // remove empty component conflicts + var empty_keys = missing_components.Where(kv => kv.Value.Count == 0).Select(kv => kv.Key).ToList(); + missing_components.RemoveRange(empty_keys); + return missing_components.ToImmutable(); + // local methods + void add_missing(RiskLimitsComponent component, string text, ParsedRiskLimits prl) { + if (!missing_components.TryGetValue(component, out var conflicts)) { + conflicts = ImmutableDictionary>.Empty; + } + if (!conflicts.TryGetValue(text, out var affected)) { + affected = ImmutableList.Empty; + } + missing_components[component] = conflicts.SetItem(text, affected.Add(prl)); + } + } + + // This implementation prioritizes simplicity over speed. + // The security desc lookup could be better optimized, but the speed at which limits are imported is probably not a paramount concern. + public static IEnumerable parse_rows(IEnumerable rows, IReadOnlyDictionary security_map, IReadOnlyDictionary account_map) => + parse_rows(rows, + reverse_lookup(MappedDictionary.create(security_map, s => s.ToString())), + reverse_lookup(account_map)); + + public static IEnumerable parse_rows(IEnumerable rows, Func security_id_lookup, Func account_id_lookup) { + var columns = new[] { + (Headers.Security, Cells.security(security_id_lookup)), + (Headers.Account, Cells.account(account_id_lookup)), + (Headers.MaxNetLongPosition, Cells.max_long_position), + (Headers.MaxNetShortPosition, Cells.max_short_position), + (Headers.IsPositionLimitEnabled, Cells.is_position_limit_enabled), + (Headers.ClipLimit, Cells.clip_limit), + (Headers.IsClipLimitEnabled, Cells.is_clip_limit_enabled), + (Headers.MinPrice, Cells.min_price), + (Headers.MaxPrice, Cells.max_price), + (Headers.IsPriceLimitEnabled, Cells.is_price_limit_enabled) + }.ToDictionary(col => col.Item1, col => col.Item2.with_null_check()); + return RowParser.parse_rows(rows, columns, Cells.delimiter); + } + + public static Func reverse_lookup(IReadOnlyDictionary map) { + var lookup = map.ToLookup(kv => kv.Value, kv => kv.Key); + return cell_text => lookup.Contains(cell_text) ? lookup[cell_text].First() : default; + } + + static class Headers { + public const string + Security = "Security", + Account = "Account", + MaxNetLongPosition = "Max Long", + MaxNetShortPosition = "Max Short", + IsPositionLimitEnabled = "Enforce Position", + ClipLimit = "Clip", + IsClipLimitEnabled = "Enforce Clip", + MinPrice = "Min Price", + MaxPrice = "Max Price", + IsPriceLimitEnabled = "Enforce Price"; + } + + static class Cells { + public const char delimiter = ','; + + public static RowParser.AssignColumnValue security(Func reverse_id_lookup) { + return impl; + void impl(ref ParsedRiskLimits pmf, string text) { + pmf.result = pmf.result.with(key: new AccountSecurityKey(pmf.result.key.account, reverse_id_lookup(text))); + pmf.security = (text, pmf.result.key.security != 0); + } + } + + public static RowParser.AssignColumnValue account(Func reverse_id_lookup) { + return impl; + void impl(ref ParsedRiskLimits pmf, string text) { + pmf.result = pmf.result.with(key: new AccountSecurityKey(reverse_id_lookup(text), pmf.result.key.security)); + pmf.account = (text, pmf.result.key.account != 0); + } + } + + public static void max_long_position(ref ParsedRiskLimits pmf, string cell_text) { + if (uint.TryParse(cell_text, out uint v)) { + pmf.result = pmf.result.with(pmf.result.limits.with(max_long_position: v)); + pmf.max_long_position = (cell_text, true); + } else { + pmf.max_long_position = (cell_text, false); + } + } + + public static void max_short_position(ref ParsedRiskLimits pmf, string cell_text) { + if (uint.TryParse(cell_text, out uint v)) { + pmf.result = pmf.result.with(pmf.result.limits.with(max_short_position: v)); + pmf.max_short_position = (cell_text, true); + } else { + pmf.max_short_position = (cell_text, false); + } + } + + public static void is_position_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) { + if (_try_parse_yes_no(cell_text, out var result)) { + pmf.result = pmf.result.with(pmf.result.limits.with(is_position_limit_enabled: result)); + pmf.is_position_limit_enabled = (cell_text, true); + } else { + pmf.is_position_limit_enabled = (cell_text, false); + } + } + + public static void clip_limit(ref ParsedRiskLimits pmf, string cell_text) { + if (uint.TryParse(cell_text, out uint v)) { + pmf.result = pmf.result.with(pmf.result.limits.with(clip_limit: v)); + pmf.clip_limit = (cell_text, true); + } else { + pmf.clip_limit = (cell_text, false); + } + } + + public static void is_clip_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) { + if (_try_parse_yes_no(cell_text, out var result)) { + pmf.result = pmf.result.with(pmf.result.limits.with(is_clip_limit_enabled: result)); + pmf.is_clip_limit_enabled = (cell_text, true); + } else { + pmf.is_clip_limit_enabled = (cell_text, false); + } + } + + static bool _try_parse_yes_no(string text, out bool result) { + switch (text?.Trim()?.ToLower()) { + case "y": result = true; break; + case "n": result = false; break; + default: result = default; return false; + } + return true; + } + + public static void min_price(ref ParsedRiskLimits pmf, string cell_text) { + if (double.TryParse(cell_text, out var v)) { + pmf.result = pmf.result.with(pmf.result.limits.with(min_price: v)); + pmf.min_price = (cell_text, true); + } else { + pmf.min_price = (cell_text, false); + } + } + + public static void max_price(ref ParsedRiskLimits pmf, string cell_text) { + if (double.TryParse(cell_text, out var v)) { + pmf.result = pmf.result.with(pmf.result.limits.with(max_price: v)); + pmf.max_price = (cell_text, true); + } else { + pmf.max_price = (cell_text, false); + } + } + + public static void is_price_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) { + if (_try_parse_yes_no(cell_text, out var result)) { + pmf.result = pmf.result.with(pmf.result.limits.with(is_price_limit_enabled: result)); + pmf.is_price_limit_enabled = (cell_text, true); + } else { + pmf.is_price_limit_enabled = (cell_text, false); + } + } + } + } +} diff --git a/src/client/spark/Modules/Trading/RiskManagement/RiskManagementWindow.cs b/src/client/spark/Modules/Trading/RiskManagement/RiskManagementWindow.cs index 0debd99f5..7e2d6c616 100644 --- a/src/client/spark/Modules/Trading/RiskManagement/RiskManagementWindow.cs +++ b/src/client/spark/Modules/Trading/RiskManagement/RiskManagementWindow.cs @@ -1,5 +1,6 @@ using bts.admin.risk; using bts.api; +using bts.collections; using bts.spark; using mbts; using mbts.persist; @@ -18,15 +19,15 @@ using System.Windows.Data; namespace bts.shell.risk_management { class RiskManagementWindow : SparkWindow, ISharedWindow { - const string - _window_type_id = "RiskManagement", - _window_type_display_name = "Risk Management"; + public const string + window_type_id = "RiskManagement", + window_type_display_name = "Risk Management"; readonly IWindowSettingsManager _settings_manager; readonly AdminModel _model; FrameworkElement _view; IReadOnlyList _commands; - IDisposable _settings_sub, _securities_sub; + IDisposable _settings_sub, _securities_sub, _cmd_subscriptions; RiskManagementSettings _settings; RiskManagementVM _vm; SimpleGridSettingsManagerVM _grid_settings_manager => _vm.grid_settings_manager; @@ -39,17 +40,17 @@ namespace bts.shell.risk_management { IWindowSettingsManager settings_manager, ISaveWindow isw, RiskManagementSettings settings) - : base(_window_type_display_name, bus, isw, Icons.Risk) { + : base(window_type_display_name, bus, isw, Icons.Risk) { // _settings_manager = settings_manager; _settings = settings; _model = model; - thread_id = mbts.config.Configuration.get().risk_management ? "OrderBook" : null; + thread_id = mbts.config.Configuration.get().risk_management ? window_type_id : null; _securities_sub = bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec_map => _security_map = sec_map); } public override IEnumerable Commands => _commands; - public override string window_type => _window_type_id; + public override string window_type => window_type_id; public override RiskManagementSettings SaveState => (_vm?.create() ?? RiskManagementSettings.Default).with(menu_display: _menu_display_vm.safe_create()); @@ -65,6 +66,7 @@ namespace bts.shell.risk_management { public string thread_id { get; } public override void Dispose() { + Disposable.dispose(ref _cmd_subscriptions); _commands.empty_if_null().OfType().DisposeAll(); Disposable.dispose(ref _securities_sub); Disposable.dispose(ref _settings_sub); @@ -79,11 +81,11 @@ namespace bts.shell.risk_management { Log.assert(_settings_sub == null, "Grid settings subscription has already been initialized."); // initialize everything: menu_display_vm, vm, settings subscription, and view _menu_display_vm = _init_menu_display_vm(_settings.menu_display); - _vm = _init_vm(_model, _settings); + _vm = _init_vm(_bus.subscribe(SparkTags.SecuritiesTag), _model, _settings); _settings_sub = _settings_manager.subscribe_current() .OnDispatcher() .Subscribe(gs => _vm.load_from(gs)); - _commands = new List(_mk_commands()); + (_commands, _cmd_subscriptions) = _mk_commands(); _view = new RiskManagementControl { DataContext = _vm }; } @@ -93,17 +95,25 @@ namespace bts.shell.risk_management { return vm; } - static RiskManagementVM _init_vm(AdminModel model, RiskManagementSettings settings) { + static RiskManagementVM _init_vm(IObservable> securities_source, AdminModel model, RiskManagementSettings settings) { var vm = new RiskManagementVM(model.account_security_risk_limits, model.on_account_tuples); vm.request_update_limit += update_limit; vm.load_from(settings); + var vm_sec_sub = securities_source.OnDispatcher().Subscribe(sec_map => vm.security_map = sec_map); + vm.OnDisposed += _ => Disposable.dispose(ref vm_sec_sub); return vm; - void update_limit(AccountSecurityRiskLimits lim) => - model.add_or_update_risk_limits(lim.account_key, new[] { (lim.security_key, lim.limits) }).ignore(); + void update_limit(AccountSecurityRiskLimits lim) { + model.set_risk_limits( + MappedDictionary.create( + vm.build_account_limits_map(), acc_sec_lims => acc_sec_lims.Select(asl => (asl.security_key, asl.limits)))) + .ignore(); + } } - IEnumerable _mk_commands() { - yield return new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => { + (List cmds, IDisposable subscriptions) _mk_commands() { + var subs = new List(); + var cmds = new List(); + cmds.Add(new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => { if (_vm is null) return null; var account_id = _vm.selected_account?.id ?? 0; @@ -122,33 +132,60 @@ namespace bts.shell.risk_management { } } } - })); - var edit_selected_rows_cmd = new DialogCommand(() => { + }))); + var edit_cmd = new DialogCommand(() => { if (!(_vm?.selected_account).HasValue) return null; var account_id = _vm.selected_account.Value.id; - var targets = _vm.selected_rows.Select(r => r.create()).ToList(); + var targets = _vm.selected_rows.Select(r => r.data).ToList(); var init_state = RiskLimitsModification.aggregate_common_props(targets); return mk_row_editor_dialog(init_state, commit, false); void commit(RiskLimitsModification mod) => - _model.add_or_update_risk_limits(account_id, targets.Select(r => (r.security_key, mod.apply(r.limits)))).ignore(); + _vm.modify_rows(targets.WrapSelector(t => t.key, null), mod); }, () => _vm.selected_rows.Count > 0, true, off_x: -300, off_y: -60); - _vm.selected_rows_changed += edit_selected_rows_cmd.RaiseCanExecuteChanged; - yield return new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_selected_rows_cmd); + _vm.selected_rows_changed += edit_cmd.RaiseCanExecuteChanged; + cmds.Add(new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_cmd)); + var revert_selected_rows_cmd = ObservantCommand.create(() => _vm?.revert(_vm.selected_rows), out var revert_selected_rows_observer); + subs.Add(_vm.subscribe_selected_rows() + .Select(srs => srs.Count > 0) + .And(_vm.subscribe_has_dirty_rows()) + .OnDispatcher() + .Subscribe(revert_selected_rows_observer)); + cmds.Add(new SparkCommandCommand("Revert Selected Rows", Icons.UndoCircular, revert_selected_rows_cmd)); - var delete_selected_rows_cmd = new DelegateCommand(() => { + cmds.Add(new SparkCommandCommand("Import Limits", Icons.Import, + FileDialogCommand.open_file(file => _vm?.import_limits(file), extensions: RiskLimitsParser.file_extension))); + + var save_cmd = new SparkCommandCommand("Save", Icons.Disk, ObservantCommand.create(() => { + //_vm.selected_account.Value.id, _vm.rows.Where(r => r.) + var lims = _vm.build_account_limits_map(); + var mlims = MappedDictionary.create(lims, l => l.Select(lim => (lim.security_key, lim.limits))); + _model.set_risk_limits(mlims).ignore(); + }, out var save_observer)); + cmds.Add(save_cmd); + subs.Add(_vm.subscribe_has_dirty_rows().OnDispatcher().Subscribe(save_observer)); + + var delete_cmd = new DelegateCommand(() => { if (!(_vm?.selected_account).HasValue) return; - var selected_rows = _vm.selected_rows; + var to_remove = _vm.selected_rows; var account_id = _vm.selected_account.Value.id; - if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({selected_rows.Count})?", "Delete Limits")) - _model.delete_risk_limits(account_id, selected_rows.Select(r => r.security_key)).ignore(); + if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({to_remove.Count})?", "Delete Limits")) { + // remove unpersisted limits first (i.e., imports), then delete the persisted ones. + foreach (var r in to_remove) { + if (!r.is_persisted) { + _vm.rows.RemoveSorted(r, _vm.row_comparer); + to_remove = to_remove.Remove(r); + } + } + _model.delete_risk_limits(account_id, to_remove.Select(r => r.security_key)).ignore(); + } }, () => _vm.selected_rows.Count > 0); - _vm.selected_rows_changed += delete_selected_rows_cmd.RaiseCanExecuteChanged; + _vm.selected_rows_changed += delete_cmd.RaiseCanExecuteChanged; - yield return new SparkCommandCommand("Delete", Icons.Trash, delete_selected_rows_cmd); + cmds.Add(new SparkCommandCommand("Delete", Icons.Trash, delete_cmd)); // wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes - yield return SparkCommands.window_settings_command(new DialogCommand(() => { + cmds.Add(SparkCommands.window_settings_command(new DialogCommand(() => { if (_vm is null) return null; _settings_manager.instance_settings = _vm.create().grid; @@ -162,8 +199,9 @@ namespace bts.shell.risk_management { var dialog = new ShellSettingsDialog { DataContext = settings_vm }; settings_vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog); return dialog; - })); - yield return _menu_display_vm.spark_cmd; + }))); + cmds.Add(_menu_display_vm.spark_cmd); + return (cmds, Disposable.wrap_collection(subs)); // although only the api only requires security keys, // the actual securities are used in this method so the user can see them in the view diff --git a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsImportConflictsVM.cs b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsImportConflictsVM.cs new file mode 100644 index 000000000..e7fe7855d --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsImportConflictsVM.cs @@ -0,0 +1,105 @@ +using bts.api; +using bts.collections; +using mbts; +using mbts.collections; +using mbts.ui; +using mbts.ui.shell; +using mbts.ui.utility; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Reactive.Linq; +using System.Windows.Data; +using System.Windows.Input; +using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent; + +namespace bts.shell.risk_management { + class RiskLimitsImportVM : DisposableViewModelBase, IRequestViewClose { + readonly RefCountMap _conflicts = new RefCountMap(); + IReadOnlyDictionary _security_map = DictionaryHelper.empty(); + + public RiskLimitsImportVM(int num_limits) { + rows_view = CollectionViewSource.GetDefaultView(rows); + ok_cmd = new DelegateCommand(() => import_request?.Invoke()); + cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs())); + this.num_limits = num_limits; + _dispose = ObservableAutoWrapper.connect_item_hooks(rows, r => + r.subscribe_has_error().Subscribe(has_error => { + if (has_error) { + if (r.affected_limits.Count(_conflicts.increment_adds_key) == 0) + return; + } else if (r.affected_limits.Count(_conflicts.decrement_removes_key) == 0) + return; + RaisePropertyChanged(nameof(num_successfully_parsed_limits)); + })); + } + + public event Action import_request; + public event EventHandler RequestClose; + + public ObservableCollection rows { get; } = new ObservableCollection(); + public ICollectionView rows_view { get; } + public int num_limits { get; } + public int num_successfully_parsed_limits => num_limits - _conflicts.Count; + // misc items sources + public IEnumerable sides => new[] { Side.Buy, Side.Sell }; + public ObservableCollection accounts { get; } = new ObservableCollection(); + public IReadOnlyDictionary security_map { + get => _security_map; + set { + if (!ReferenceEquals(_security_map, value)) { + _security_map = value; + _resolve_securities(); + RaisePropertyChanged(); + } + } + } + // commands + public ICommand ok_cmd { get; } + public ICommand cancel_cmd { get; } + + void _resolve_securities() { + if (_security_map == null) + return; + var reverse_lookup = RiskLimitsParser.reverse_lookup(MappedDictionary.create(_security_map, v => v.security.ToString())); + foreach (var r in rows) { + if (r.component == Component.Security && r.has_error) { + var id = reverse_lookup(r.text); + if (id != 0 && _security_map.TryGetValue(id, out var smd)) + r.value = smd.security; + } + } + } + + public class Row : ViewModelBase, ITemplateSelectorKey { + readonly DelegateProperty _has_error; + object _value; + string _text; + + public Row(Component component, string text, IReadOnlyCollection affected_limits, object error_value, object value) { + this.component = component; + this.text = text; + this.affected_limits = affected_limits; + _value = value; + _has_error = backing(nameof(has_error), () => Equals(this.value, error_value)); + } + + public Component component { get; } + public string text { get => _text; set => Set(ref _text, value); } + public IReadOnlyCollection affected_limits { get; } + public object value { + get => _value; + set { + if (Set(ref _value, value)) + _has_error.refresh(); + } + } + public bool has_error => _has_error.Value; + string ITemplateSelectorKey.key => component.ToString(); + + public IObservable subscribe_has_error() => _has_error.observe_current(true); + } + } +} diff --git a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsModificationVM.cs b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsModificationVM.cs index 3bbb39d42..4af801f8d 100644 --- a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsModificationVM.cs +++ b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsModificationVM.cs @@ -87,6 +87,7 @@ namespace bts.shell.risk_management { public RiskLimitsModification( SecurityImmutable? security = null, SecurityCriteria security_criteria = null, + AccountTuple? account = null, uint? max_long_position = null, uint? max_short_position = null, bool? is_position_limit_enabled = null, @@ -98,6 +99,7 @@ namespace bts.shell.risk_management { // this.security = security; this.security_criteria = security_criteria; + this.account = account; this.max_long_position = max_long_position; this.max_short_position = max_short_position; this.is_position_limit_enabled = is_position_limit_enabled; @@ -110,6 +112,7 @@ namespace bts.shell.risk_management { public SecurityImmutable? security { get; } public SecurityCriteria security_criteria { get; } + public AccountTuple? account { get; } // position public uint? max_long_position { get; } public uint? max_short_position { get; } @@ -126,6 +129,7 @@ namespace bts.shell.risk_management { new RiskLimitsModification( _common_value(limit_items, l => l.security, s => s), null, + _common_value(limit_items, l => new AccountTuple(l.account_key, l.account_name)), _common_value(limit_items, l => l.limits.max_long_position), _common_value(limit_items, l => l.limits.max_short_position), _common_value(limit_items, l => l.limits.is_position_limit_enabled), @@ -146,8 +150,25 @@ namespace bts.shell.risk_management { min_price: min_price ?? target.min_price, max_price: max_price ?? target.max_price); + public RiskLimitsModification with(RiskLimitsModification other_mod) => + with( + other_mod.security.HasValue ? other_mod.security.Value : security, + other_mod.account.HasValue ? other_mod.account.Value : account, + security_criteria: other_mod.security_criteria ?? security_criteria, + max_long_position: other_mod.max_long_position ?? max_long_position, + max_short_position: other_mod.max_short_position ?? max_short_position, + is_position_limit_enabled: other_mod.is_position_limit_enabled ?? is_position_limit_enabled, + clip_limit: other_mod.clip_limit ?? clip_limit, + is_clip_limit_enabled: other_mod.is_clip_limit_enabled ?? is_clip_limit_enabled, + min_price: other_mod.min_price ?? min_price, + max_price: other_mod.max_price ?? max_price, + is_price_limit_enabled: other_mod.is_price_limit_enabled ?? is_price_limit_enabled); + //new RiskLimitsModification(security: other_mod.security ?? security, + // security_criteria: other_mod.security ?? security); + public RiskLimitsModification with( OptionalNullable? security = null, + OptionalNullable? account = null, SecurityCriteria security_criteria = null, OptionalNullable? max_long_position = null, OptionalNullable? max_short_position = null, @@ -161,6 +182,7 @@ namespace bts.shell.risk_management { new RiskLimitsModification( security.HasValue ? security.Value.value : this.security, security_criteria ?? this.security_criteria, + account.HasValue ? account.Value.value : this.account, max_long_position.HasValue ? max_long_position.Value.value : this.max_long_position, max_short_position.HasValue ? max_short_position.Value.value : this.max_short_position, is_position_limit_enabled.HasValue ? is_position_limit_enabled.Value.value : this.is_position_limit_enabled, diff --git a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsVM.cs b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsVM.cs index 2a4b28a4e..84ced89ac 100644 --- a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsVM.cs +++ b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskLimitsVM.cs @@ -1,89 +1,114 @@ using bts.admin.risk; using bts.api; using bts.utils; -using mbts.spark; using mbts.ui; using mbts.ui.shell; using System; -using System.Runtime.CompilerServices; namespace bts.shell.risk_management { - class RiskLimitsVM : ViewModelBase, IValueFactory { - readonly DeferrableActionWrapper _result_changed; - // The user can modify some props directly in the grid. - // However, the sorting relies on immutable data - // (binary search may break if the applicable comparisons change, - // depending on the current sorting criteria). - // As a work-around, the rows are sorted by the committed_data. - // Any modifications made through the prop setters are assumed to be 'user-changes' - // (as the props are bound to the view), - /// and the committed data is only changed through . - AccountSecurityRiskLimits _committed_data, _mutable_data; + class RiskLimitsVM : ViewModelBase, IEquatable { + RiskLimitsVM(AccountSecurityKey id) => + this.id = id; - public RiskLimitsVM() => - _result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke()); + public event Action request_commit; - public RiskLimitsVM(AccountSecurityRiskLimits data) : this() { - _committed_data = data; - _mutable_data = data; - } + /// The user can modify some props directly in the grid, + /// which may or may not give the row a new sort-position. + /// For this reason, the owner-viewmodel () + /// is notified both immediately before, and after the changes are reflected in . + /// By responding to those events, the owner-viewmodel can safely process any + /// sorting-changes without breaking binary search functionality. + /// , - public event Action result_changed; + /// + /// This event is raised just before a new value is assigned to . + /// + public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changing; + /// + /// This event is raised immediately after a new value is assigned to . + /// + public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changed; + public event Action is_dirty_changed; - public SecurityImmutable? security => _committed_data.security; - public uint security_key => _committed_data.security_key; - public string account_name => _committed_data.account_name; - public uint account_key => _committed_data.account_key; + public AccountSecurityKey id { get; } + public SecurityImmutable? security => data.security; + public string security_text => is_persisted ? security.ToString() : $"*{security}"; + public uint security_key => data.security_key; + public string account_name => data.account_name; + public uint account_key => data.key.account; // position limit - public bool is_position_limit_enabled { get => _mutable_limits.is_position_limit_enabled; set => _set_limits(_mutable_limits.with(is_position_limit_enabled: value)); } - public uint max_long_position { get => _mutable_limits.max_long_position; set => _set_limits(_mutable_limits.with(max_long_position: value)); } - public uint max_short_position { get => _mutable_limits.max_short_position; set => _set_limits(_mutable_limits.with(max_short_position: value)); } + public bool is_position_limit_enabled { get => _limits.is_position_limit_enabled; set => _modify(new RiskLimitsModification(is_position_limit_enabled: value)); } + public uint max_long_position { get => _limits.max_long_position; set => _modify(new RiskLimitsModification(max_long_position: value)); } + public uint max_short_position { get => _limits.max_short_position; set => _modify(new RiskLimitsModification(max_short_position: value)); } // clip limit - public bool is_clip_limit_enabled { get => _mutable_limits.is_clip_limit_enabled; set => _set_limits(_mutable_limits.with(is_clip_limit_enabled: value)); } - public uint clip_limit { get => _mutable_limits.clip_limit; set => _set_limits(_mutable_limits.with(clip_limit: value)); } + public bool is_clip_limit_enabled { get => _limits.is_clip_limit_enabled; set => _modify(new RiskLimitsModification(is_clip_limit_enabled: value)); } + public uint clip_limit { get => _limits.clip_limit; set => _modify(new RiskLimitsModification(clip_limit: value)); } // price limit - public bool is_price_limit_enabled { get => _mutable_limits.is_price_limit_enabled; set => _set_limits(_mutable_limits.with(is_price_limit_enabled: value)); } - public double max_price { get => _mutable_limits.max_price; set => _set_limits(_mutable_limits.with(max_price: value)); } - public double min_price { get => _mutable_limits.min_price; set => _set_limits(_mutable_limits.with(min_price: value)); } - public AccountSecurityKey row_id => new AccountSecurityKey(account_key, security_key); - public AccountSecurityRiskLimits committed_data => _committed_data; + public bool is_price_limit_enabled { get => _limits.is_price_limit_enabled; set => _modify(new RiskLimitsModification(is_price_limit_enabled: value)); } + public double min_price { get => _limits.min_price; set => _modify(new RiskLimitsModification(min_price: value)); } + public double max_price { get => _limits.max_price; set => _modify(new RiskLimitsModification(max_price: value)); } - RiskLimits _mutable_limits { - get => _mutable_data.limits; - set => _mutable_data = _mutable_data.with(limits: value); + public bool is_persisted => committed_data.HasValue; + public bool is_dirty => !committed_data.HasValue || !committed_data.Value.Equals(data); + + public AccountSecurityRiskLimits data { get; private set; } + public AccountSecurityRiskLimits? committed_data { get; private set; } + RiskLimits _limits => data.limits; + + public static RiskLimitsVM create_placeholder(AccountSecurityRiskLimits state) { + var vm = new RiskLimitsVM(state.key); + vm.load(state, false); + return vm; } - public AccountSecurityRiskLimits create() => _mutable_data; + public static RiskLimitsVM create_persisted(AccountSecurityRiskLimits state) { + var vm = new RiskLimitsVM(state.key); + vm.load(state, true); + return vm; + } - public void load_from(AccountSecurityRiskLimits value) { - using (_result_changed.defer_execution()) + public void load(AccountSecurityRiskLimits new_state, bool is_committed) { using (detect_property_changes()) { - _committed_data = value; - _mutable_data = value; + bool was_dirty = is_dirty; + if (is_committed) + committed_data = new_state; + if (!data.Equals(new_state)) { + value_changing?.Invoke((data, new_state)); + var orig_state = data; + data = new_state; + value_changed?.Invoke((orig_state, new_state)); + } + if (is_dirty != was_dirty) + is_dirty_changed?.Invoke(); } } - public void apply_modifications(RiskLimitsModification m) => - load_from(_committed_data.with( - _committed_data.limits.with(m.is_position_limit_enabled, - m.max_long_position, - m.max_short_position, - m.is_clip_limit_enabled, - m.clip_limit, - m.is_price_limit_enabled, - m.min_price, - m.max_short_position), - new AccountTuple(_committed_data.account_key, _committed_data.account_name), - m.security)); + public bool Equals(RiskLimitsVM other) => + other != null && id == other.id; - void _set_limits(RiskLimits new_limits, [CallerMemberName] string prop = "") => - _set_limits(new_limits, new[] { prop }); + public override bool Equals(object obj) => + Equals(obj as RiskLimitsVM); - void _set_limits(RiskLimits new_limits, params string[] invalidate_props) { - if (!_mutable_limits.Equals(new_limits)) { - _mutable_limits = new_limits; - RaisePropertyChanged(invalidate_props); - _result_changed.execute(); + public override int GetHashCode() => + id.GetHashCode(); + + void _modify(RiskLimitsModification mod) { + var new_value = data.with(limits: mod.apply(data.limits)); + if (committed_data.HasValue) { + // if the user just toggled one of the limits on/off, request an immediate update to persist the change + // (the on/off toggles are the only props that can be edited directly in the grid, + // the user might find it annoying if they have to click 'Save' just to turn the limits on/off. + var clims = committed_data.Value.limits; + load(new_value, false); + var revert_mod = new RiskLimitsModification(is_position_limit_enabled: clims.is_position_limit_enabled, is_clip_limit_enabled: clims.is_clip_limit_enabled, is_price_limit_enabled: clims.is_price_limit_enabled); + var reverted_lims = new_value = new_value.with(limits: revert_mod.apply(new_value.limits)); + if (reverted_lims.limits.Equals(clims)) { + // since only the limit toggle props were reverted, + // the above equality indicates that only the limit toggle props were modified. + request_commit?.Invoke(); + } + } else { + load(new_value, false); } } } diff --git a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskManagementVM.cs b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskManagementVM.cs index af4b348ab..5bcf8fa62 100644 --- a/src/client/spark/Modules/Trading/RiskManagement/VM/RiskManagementVM.cs +++ b/src/client/spark/Modules/Trading/RiskManagement/VM/RiskManagementVM.cs @@ -15,6 +15,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; +using System.IO; using System.Linq; using System.Reactive.Linq; using System.Windows.Controls; @@ -36,27 +37,32 @@ namespace bts.shell.risk_management { .wrap(r => r.key); static IComparer _row_id_comparer => - _data_row_id_comparer.wrap(r => r.committed_data); + _data_row_id_comparer.wrap(r => r.data); - readonly DeferrableActionWrapper _result_changed, _refresh_filter_changed, _selected_rows_changed; + readonly DeferrableActionWrapper _refresh_filter_changed, _selected_rows_changed, _dirty_rows_changed; readonly ColumnSortManager _sort_manager; readonly ObservableCollection _columns = new ObservableCollection(); readonly Dictionary _column_map = new Dictionary(); readonly SelectorVM _accounts_vm = new SelectorVM(acc => acc?.id ?? 0) { comparer = Comparer.Default.to_nullable() }; - IReadOnlyDictionary _cache = DictionaryHelper.empty(); - ImmutableSortedSet _selected_rows = ImmutableSortedSet.Create(_row_id_comparer); IList _data_rows; + ImmutableSortedSet _selected_rows = ImmutableSortedSet.Create(_row_id_comparer); IComparer _data_comparer = _data_row_id_comparer; IComparer _row_comparer; + IDisposable _import_limits_op; + ImmutableDictionary _dirty_rows = ImmutableDictionary.Empty; + ImmutableDictionary _imported_row_map = ImmutableDictionary.Empty; + Dictionary _row_cache = new Dictionary(); public RiskManagementVM(IObservable> data_source, IObservable> accounts_source) { - _result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke()); _selected_rows_changed = new DeferrableActionWrapper(() => selected_rows_changed?.Invoke()); + _refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter())); + _dirty_rows_changed = new DeferrableActionWrapper(() => dirty_rows_changed?.Invoke(dirty_rows)); _sort_manager = new ColumnSortManager(_columns.OfType(), null); - _data_rows = rows.WrapSelector(r => r.committed_data, lim => new RiskLimitsVM(lim)); + _sort_manager.active_sorting_changed += () => + data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer); + _data_rows = rows.WrapSelector(r => r.data, null); _accounts_vm.selected_item_changed += () => { RaisePropertyChanged(nameof(selected_account)); - _result_changed.execute(); _refresh_filter_changed.execute(); }; column_map = FunctionalIndex.create(_find_column); @@ -66,7 +72,6 @@ namespace bts.shell.risk_management { throw new InvalidOperationException(); }, c => c.id.ToString(), cs => cs.id); }, null); - _refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter())); ///////////////// // Columns ///////////////// @@ -155,6 +160,7 @@ namespace bts.shell.risk_management { }).to_comparer(); _column_map = _columns.ToDictionary(c => c.id); columns = ObservableAutoWrapper.SelectObservable(_columns, c => c); + var filter_source = Observable.FromEvent>(cb => _filter_changed += cb, cb => _filter_changed -= cb) .StartWith(_mk_filter); @@ -209,13 +215,31 @@ namespace bts.shell.risk_management { return col; } - IDisposable subscribe_row_changes(RiskLimitsVM r) { - r.result_changed += on_limits_changed; - return Disposable.Create(() => r.result_changed -= on_limits_changed); - void on_limits_changed() { - var lim = r.create(); - if (_cache.TryGetValue(lim.key, out var curr_lim) && !lim.Equals(curr_lim)) - request_update_limit?.Invoke(lim); + IDisposable subscribe_row_changes(RiskLimitsVM row) { + row.value_changing += on_value_changing; + row.value_changed += on_value_changed; + row.request_commit += on_request_commit; + check_dirty(); + return Disposable.Create(() => { + row.value_changing -= on_value_changing; + row.value_changed -= on_value_changed; + row.request_commit -= on_request_commit; + }); + + void on_value_changing((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) => + on_row_data_changed(new Change(change.old_value, change.new_value), false); + + void on_value_changed((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) => + check_dirty(); + + void on_request_commit() => + request_update_limit?.Invoke(row.data); + + void check_dirty() { + int dr_count = _dirty_rows.Count; + _dirty_rows = row.is_dirty ? _dirty_rows.Add(row.id, row) : _dirty_rows.Remove(row.id); + if (dr_count != _dirty_rows.Count) + _dirty_rows_changed.execute(); } } @@ -223,22 +247,74 @@ namespace bts.shell.risk_management { _accounts_vm.update_items(new_accounts.Cast()); void on_data(TableUpdate table) { - _cache = table.state; - var comp = data_comparer; - _data_rows.RemoveSorted(table.removed.Concat(table.changes.Old()), comp); - _data_rows.InsertSorted(table.added.Concat(table.changes.New()), comp); + using (_dirty_rows_changed.defer_execution()) + using (_selected_rows_changed.defer_execution()) { + foreach (var lim in table.removed) { + if (_row_cache.TryGetValue(lim.key, out var row)) { + _data_rows.RemoveSorted(row.data, data_comparer); + if (row.committed_data.HasValue) + _row_cache.Remove(lim.key); + } + } + foreach (var ch in table.changes) { + on_row_data_changed(ch, true); + } + foreach (var lim in table.added) { + if (_row_cache.TryGetValue(lim.key, out var row)) { + // if row is already here, it must be an import + // overwrite the import with the persisted row (this probably won't happen in practice) + rows.RemoveSorted(row, row_comparer); + } + var new_row = RiskLimitsVM.create_persisted(lim); + _row_cache[lim.key] = new_row; + rows.InsertSorted(new_row, row_comparer); + } + } + } + + void on_row_data_changed(Change change, bool is_persisted) { + Log.assert(_row_cache.TryGetValue(change.Old.key, out var row)); + int old_index = CollectionHelper.binary_search(rows, row, row_comparer); + Log.assert(old_index >= 0); + int new_index = CollectionHelper.binary_search(_data_rows, change.New, _data_comparer); + // if the change came from the server (i.e., a persisted change that the row-vm doesn't already know about), + // load the new data (current modifications will be overwritten). + // Otherwise, the change is presumably the result of an uncommitted user-edit, which the row must already know about. + if (is_persisted) { + row.load(change.New, true); + if (_dirty_rows.Remove(row.id, out _dirty_rows)) + _dirty_rows_changed.execute(); + } + if (new_index < 0) + new_index = ~new_index; + if (Math.Abs(new_index - old_index) > 1) { + if (new_index > old_index) + new_index--; + rows.Move(old_index, new_index); + } } } - public event Action result_changed, selected_rows_changed; + public event Action selected_rows_changed; public event Action request_update_limit; + public event Action> dirty_rows_changed; event Action> _filter_changed; public IReadOnlyIndex column_map { get; } + public bool has_unpersisted_limits => false; // this collection is needed to control the column order public IReadOnlyObservableCollection columns { get; } public ObservableCollection rows { get; } = new ObservableCollection(); - public IReadOnlyList selected_rows => _selected_rows; + /// + /// The selected rows are provided as an so they can be observed/accessed on different threads. + /// . + /// + public ImmutableSortedSet selected_rows => _selected_rows; + /// + /// The dirty rows are provided as an so they can be observed/accessed on different threads. + /// . + /// + public ImmutableDictionary dirty_rows => _dirty_rows; public IReadOnlyObservableCollection accounts => _accounts_vm.items; public AccountTuple? selected_account { get => _accounts_vm.selected_item ?? default; @@ -251,13 +327,20 @@ namespace bts.shell.risk_management { if (value != null) { _data_comparer = value; _row_comparer = null; - _data_rows.sync_with(_data_rows.Ordered(value).ToList()); + rows.sync_with(rows.Ordered(row_comparer)); _selected_rows = _selected_rows.WithComparer(row_comparer); } } } + public IComparer row_comparer => - _row_comparer ?? (_row_comparer = data_comparer?.wrap(r => r.committed_data)); + _row_comparer ?? (_row_comparer = data_comparer?.wrap(r => r.data)); + + public IReadOnlyDictionary security_map { get; set; } = DictionaryHelper.empty(); + + public IReadOnlyDictionary> build_account_limits_map() => + _data_rows.GroupBy(dr => dr.account_key) + .ToDictionary(g => g.Key, g => g.AsEnumerable()); public RiskManagementSettings create() { var grid = grid_settings_manager.create(); @@ -268,9 +351,10 @@ namespace bts.shell.risk_management { public void load_from(RiskManagementSettings settings) { if (settings is null) throw new ArgumentNullException(nameof(settings)); - using (_result_changed.defer_execution()) { - if (settings.grid != null) - grid_settings_manager.load_from(settings.grid); + if (settings.grid != null) + grid_settings_manager.load_from(settings.grid); + _sort_manager.SortingCriteria = settings.sorting_criteria; + using (_refresh_filter_changed.defer_execution()) { foreach (var col in _columns) col.load_from(null, settings.filters); _accounts_vm.try_select(settings.account_id, true); @@ -280,8 +364,48 @@ namespace bts.shell.risk_management { public void load_from(GridSettings grid) { if (grid is null) throw new ArgumentNullException(nameof(grid)); - using (_result_changed.defer_execution()) - grid_settings_manager.load_from(grid); + grid_settings_manager.load_from(grid); + } + + public void modify_rows(IEnumerable targets, RiskLimitsModification mod) { + foreach (var key in targets) { + if (_row_cache.TryGetValue(key, out var row)) { + var new_data = row.data.with(limits: mod.apply(row.data.limits)); + row.load(new_data, false); + } + } + } + + public void revert(IEnumerable targets) { + foreach (var row in targets) { + if (row.committed_data.HasValue) + row.load(row.committed_data.Value, true); + } + } + + public void import_limits(string file_name) { + Disposable.dispose(ref _import_limits_op); + _import_limits_op = RiskLimitsImporter.import_limits(file_name, + security_map, + accounts.Where(a => a.HasValue) + .ToDictionary(a => a.Value.id, a => a.Value.name), + add_imported_rows); + + void add_imported_rows(IEnumerable imported_rows) { + foreach (var ir in imported_rows) { + var res = ir.result; + if (!res.security.HasValue && security_map.TryGetValue(res.security_key, out var sec_md)) + res = res.with(security: sec_md.security); + if (string.IsNullOrEmpty(res.account_name) && accounts.TryGetFirst(a => a?.id == res.account_key, out var acc)) + res = res.with(account: acc); + var new_row = RiskLimitsVM.create_placeholder(res); + if (_row_cache.TryGetValue(res.key, out var row)) { + rows.RemoveSorted(row, row_comparer); + } + _row_cache[res.key] = new_row; + rows.InsertSorted(new_row, row_comparer); + } + } } void IHandleRowSelection.row_selection_changed(SelectionChangedEventArgs e) { @@ -293,7 +417,7 @@ namespace bts.shell.risk_management { void IHandleGridSorting.on_sorting(object sender, DIYGridSortingEventArgs e) { _sort_manager.OnColumnClick(e.Column, KeyboardExtensions.IsShiftDown()); - data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer); + e.Handled = true; } RiskManagementColumnModel _find_column(string key_str) => @@ -310,4 +434,33 @@ namespace bts.shell.risk_management { return lim => lim.account_key == acc_id && (col_filter_pred is null || col_filter_pred(lim)); } } + + static class RiskManagementVMExtensions { + public static IObservable> subscribe_selected_rows(this RiskManagementVM vm) => + vm is null ? + throw new ArgumentNullException(nameof(vm)) : + Observable.Create>(o => { + o.OnNext(vm.selected_rows); + vm.selected_rows_changed += on_selected_rows_changed; + return Disposable.Create(() => vm.selected_rows_changed -= on_selected_rows_changed); + void on_selected_rows_changed() => + o.OnNext(vm.selected_rows); + }) + .SubscribeOnDispatcher(); + + public static IObservable subscribe_has_dirty_rows(this RiskManagementVM vm) => + vm is null ? + throw new ArgumentNullException(nameof(vm)) : + Observable.Create(o => { + bool last_fired = vm.dirty_rows.Count > 0; + o.OnNext(last_fired); + vm.dirty_rows_changed += on_dirty_rows_changed; + return Disposable.Create(() => vm.dirty_rows_changed -= on_dirty_rows_changed); + void on_dirty_rows_changed(ImmutableDictionary drs) { + if (last_fired != drs.Count > 0) + o.OnNext(last_fired = !last_fired); + } + }) + .SubscribeOnDispatcher(); + } } diff --git a/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml new file mode 100644 index 000000000..db4ca1e63 --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml.cs b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml.cs new file mode 100644 index 000000000..e0654330c --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsDialog.xaml.cs @@ -0,0 +1,11 @@ +using System.Windows; + +namespace bts.shell.risk_management { + /// + /// Interaction logic for RiskLimitsImportConflictsDialog.xaml + /// + partial class RiskLimitsImportConflictsDialog : Window { + public RiskLimitsImportConflictsDialog() => + InitializeComponent(); + } +} diff --git a/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml new file mode 100644 index 000000000..52307a115 --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml.cs b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml.cs new file mode 100644 index 000000000..ca16898ed --- /dev/null +++ b/src/client/spark/Modules/Trading/RiskManagement/View/RiskLimitsImportConflictsView.xaml.cs @@ -0,0 +1,38 @@ +using System.Windows.Controls; + +namespace bts.shell.risk_management { + /// + /// Interaction logic for RiskLimitsImportConflictsView.xaml + /// + partial class RiskLimitsImportConflictsView : UserControl { + public RiskLimitsImportConflictsView() => + InitializeComponent(); + + public enum RiskLimitsComponent { + Security, + Account, + MaxNetLongPosition, + MaxNetShortPosition, + IsPositionLimitEnabled, + ClipLimit, + IsClipLimitEnabled, + MinPrice, + MaxPrice, + IsPriceLimitEnabled + } + + public static class RiskLimitsComponentNames { + public static readonly string + Security = RiskLimitsComponent.Security.ToString(), + Account = RiskLimitsComponent.Account.ToString(), + MaxNetLongPosition = RiskLimitsComponent.MaxNetLongPosition.ToString(), + MaxNetShortPosition = RiskLimitsComponent.MaxNetShortPosition.ToString(), + IsPositionLimitEnabled = RiskLimitsComponent.IsPositionLimitEnabled.ToString(), + ClipLimit = RiskLimitsComponent.ClipLimit.ToString(), + IsClipLimitEnabled = RiskLimitsComponent.IsClipLimitEnabled.ToString(), + MinPrice = RiskLimitsComponent.MinPrice.ToString(), + MaxPrice = RiskLimitsComponent.MaxPrice.ToString(), + IsPriceLimitEnabled = RiskLimitsComponent.IsPriceLimitEnabled.ToString(); + } + } +} diff --git a/src/client/spark/Modules/Trading/RiskManagement/View/RiskManagementControl.xaml b/src/client/spark/Modules/Trading/RiskManagement/View/RiskManagementControl.xaml index ac9103875..8af18d509 100644 --- a/src/client/spark/Modules/Trading/RiskManagement/View/RiskManagementControl.xaml +++ b/src/client/spark/Modules/Trading/RiskManagement/View/RiskManagementControl.xaml @@ -15,6 +15,14 @@ Background="{StaticResource CommonBackground}" > + + + 1.0 + + + 0.6 + +