diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index 8f1c26d04..81afe5ca3 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -7,7 +7,7 @@ insert_anchor_links = "right" ## 2.11.0 ### Internal Changes - Added support for tag 1031. Currently defaults to Y, can it be override through config. - + - To facilitate support, allowed the bts user to view and edit algos from all other users ## 2.10.0 ### User Visible Changes - Fills now include information about the algo that originated the fill diff --git a/src/client/spark/Admin/AdminModel.cs b/src/client/spark/Admin/AdminModel.cs index 9e8508b22..2ff340e18 100644 --- a/src/client/spark/Admin/AdminModel.cs +++ b/src/client/spark/Admin/AdminModel.cs @@ -1,83 +1,74 @@ using bts; using bts.api.admin; +using bts.api.core; +using bts.utils; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; -using System.Reactive.Subjects; -using bts.api.core; -using mbts.ui.shell; namespace mbts.spark { [Export] class AdminModel : IDisposable { public readonly UserTuple user; - - readonly BehaviorSubject> - _accounts_subject = new BehaviorSubject>(new Dictionary()), - _users_subject = new BehaviorSubject>(new Dictionary()); - IReadOnlyDictionary - _account_map = new Dictionary(), - _user_map = new Dictionary(); - readonly BehaviorSubject _wrapper_subject = new BehaviorSubject(new AdminModelWrapper()); - IDisposable _dispose; + + IDisposable _dispose; + IReadOnlyDictionary _account_map = DictionaryHelper.empty(); [ImportingConstructor] - AdminModel(AdminService service, [Import]UserTuple user) { + AdminModel(AdminService service, UserTuple user) { this.user = user; - _dispose = service.subscribei_admin_data().Select(update => { - _wrapper_subject.OnNext(new AdminModelWrapper(update.all.TryFirst(), user.name)); - IEnumerable active_users = - from admin_data in update.all - from bts_user in admin_data.Users - where bts_user.Name == user.name && bts_user.HasUserData && bts_user.UserData.HasAccountPermissions - select bts_user; - - IEnumerable active_accounts = - from admin_data in update.all - from bts_account in admin_data.Accounts - where bts_account.IsPresent && _wrapper_subject.Value.can_view_account(bts_account.Name) - join account_id in ( - from bts_user in active_users - from account_id in bts_user.UserData.AccountPermissions.AccountPermissions.Keys - select account_id - ) on bts_account.Id equals account_id - select bts_account; - - var users = active_users.ToDictionary(u => u.Id, u => u.Name); - var accounts = active_accounts.ToDictionary(a => a.Id, a => a.Name); - return (users, accounts); - }).Subscribe(t => { - _account_map = t.accounts; - _user_map = t.users; - _users_subject.OnNext(_user_map = t.users); - _accounts_subject.OnNext(_account_map = t.accounts); - }); + // accounts + on_accounts = service.subscribei_admin_data() + .Select(up => up.all.TryGetFirst(out var ad) && ad.Users.Where(u => u.Name == user.name).TryGetSingle(out var usr) && usr.HasUserData && usr.UserData.HasAccountPermissions ? + usr.UserData.AccountPermissions.AccountPermissions + .Where(kv => kv.Value.TradingPermission.HasPermissions && kv.Value.AdminPermission.HasPermissions) + .Select(kv => ad.Accounts.Where(a => a.Id == kv.Key).TryGetSingle(out var acc) ? acc : (BTSAccountImmutable?)null) + .Where(acc => acc.HasValue) + .Select(acc => acc.Value) + .ToDictionary(acc => acc.Id, acc => acc.Name) : + new Dictionary(0)) + .Replay(1) + .RefCount(); + // users + on_users = Observable.Return(DictionaryHelper.wrap_value(user.id, user.name)); + all_user_tuples = user.permissions == UserTuple.Permissions.Admin ? + service.subscribei_admin_data() + .Select(u => u.all.TryFirst()) + .Where(ad => ad.HasValue) + .Select(ad => ad.Value.Users + .Where(u => user.can_access_user_data(u.Id)) + .Select(u => new UserTuple(u.Id, u.Name)) + .ToDictionary(UserTuple.key_fn)) + .Table(UserTuple.key_fn) + .Cache() : + Observable.Return(TableUpdate.mk_empty(UserTuple.key_fn).with_added(new[] { user })); + _dispose = on_accounts.Subscribe(map => _account_map = map); } - public IObservable> on_users => _users_subject.AsObservable(); - public IObservable> on_accounts => _accounts_subject.AsObservable(); - public IObservable> on_user_tuples => on_users.Select(d => d.Select(kv => new UserTuple(kv.Key, kv.Value)).ToList()); - public IObservable> on_account_tuples => on_accounts.Select(d => d.Select(kv => new AccountTuple(kv.Key, kv.Value)).ToList()); - public IObservable on_admin_data => _wrapper_subject.AsObservable(); + public IObservable> on_users { get; } + public IObservable> on_accounts { get; } + public IObservable> all_user_tuples { get; } + public IObservable> on_account_tuples => on_accounts.Select(d => d.Select(kv => new AccountTuple(kv.Key, kv.Value)).ToListSorted(a => a.name)); - public AccountTuple? get_default_account() { - foreach (var kv in _account_map) { - return new AccountTuple(kv.Key, kv.Value); - } - return null; - } - public uint? get_user_id(string user) => _id_for_name(user, _user_map); - public uint? get_account_id(string account) => _id_for_name(account, _account_map); - public void Dispose() => Disposable.dispose(ref _dispose); + public IObservable> permission_filter(IObservable> positions, Func get_account_id) where TKey : IEquatable => + user.permissions == UserTuple.Permissions.Admin ? + positions : + positions.Filter(on_accounts.Select(map => new Func(p => map.ContainsKey(get_account_id(p))))); - static uint? _id_for_name(string name, IReadOnlyDictionary map) { - foreach (var kv in map) { - if (kv.Value == name) - return kv.Key; - } - return null; - } + public IObservable> permission_filter(IObservable> positions, Func get_account_name) where TKey : IEquatable => + user.permissions == UserTuple.Permissions.Admin ? + positions : + positions.Filter(on_accounts.Select(map => { + var hash = new HashSet(map.Values); + return new Func(v => hash.Contains(get_account_name(v))); + })); + + public AccountTuple? get_default_account() => + _account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst(); + + public void Dispose() => + Disposable.dispose(ref _dispose); } } \ No newline at end of file diff --git a/src/client/spark/Daemons/AboutDaemon.cs b/src/client/spark/Daemons/AboutDaemon.cs index 8a8ad2f06..1777477cb 100644 --- a/src/client/spark/Daemons/AboutDaemon.cs +++ b/src/client/spark/Daemons/AboutDaemon.cs @@ -3,15 +3,10 @@ using mbts; using mbts.config; using mbts.spark; using mbts.ui; -using mbts.ui.shell; using System; -using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; -using System.Linq; using System.Reactive.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows; using System.Windows.Input; @@ -23,8 +18,8 @@ namespace bts.ui { IDisposable _dispose; [ImportingConstructor] - public AboutDaemon(IBus bus, [Import(LoginContainer.Exports.UserName)]string username) { - _user = username; + public AboutDaemon(IBus bus, UserTuple user) { + _user = user.name; _bus = bus; _dispose = bus.subscribe(SparkTags.About).OnDispatcher().Subscribe(_ => show_about()); } @@ -63,4 +58,4 @@ namespace bts.ui { Disposable.dispose(ref _dispose); } } -} +} \ No newline at end of file diff --git a/src/client/spark/Daemons/ErrorReporter.cs b/src/client/spark/Daemons/ErrorReporter.cs index fa8ccc6ad..cfd5bc936 100644 --- a/src/client/spark/Daemons/ErrorReporter.cs +++ b/src/client/spark/Daemons/ErrorReporter.cs @@ -7,13 +7,11 @@ using mbts.ui; using System; using System.ComponentModel.Composition; using System.Reactive.Linq; -using System.Windows.Threading; -using System.Windows; using System.Threading.Tasks; -using mbts.ui.shell; +using System.Windows; +using System.Windows.Threading; -namespace bts.spark -{ +namespace bts.spark { [Export, Export(typeof(IShellDaemon))] public class ErrorReporter : IShellDaemon, IDisposable { readonly ErrorReportService _svc; @@ -21,9 +19,9 @@ namespace bts.spark IDisposable _dispose; [ImportingConstructor] - public ErrorReporter(ErrorReportService svc, IBus bus, [Import(LoginContainer.Exports.UserName)] string username) { + public ErrorReporter(ErrorReportService svc, IBus bus, UserTuple user) { _svc = svc; - _username = username; + _username = user.name; _dispose = bus.subscribe(SparkTags.Support).OnDispatcher().Subscribe(msg => show_support_window(msg, "Report a problem")); } diff --git a/src/client/spark/Daemons/MDDaemon.cs b/src/client/spark/Daemons/MDDaemon.cs index a2f866421..b6bcfa70b 100644 --- a/src/client/spark/Daemons/MDDaemon.cs +++ b/src/client/spark/Daemons/MDDaemon.cs @@ -1,5 +1,6 @@ using bts.api; using bts.api.synthetic; +using bts.md; using mbts; using mbts.co2; using mbts.spark; @@ -7,15 +8,10 @@ using mbts.ui; using System; using System.Collections.Generic; using System.ComponentModel.Composition; +using System.Linq; using System.Reactive.Linq; using System.Threading.Tasks; -using System.Linq; using SecurityKey = System.UInt32; -using System.Collections.Concurrent; -using System.Threading; -using bts.api.user; -using bts.md; -using mbts.ui.shell; namespace bts { [Export(typeof(IInitializable))] @@ -25,17 +21,21 @@ namespace bts { readonly Lazy _ss; readonly Dictionary _deleted_synthetics = new Dictionary(); - static uint get_naggle() => mbts.config.Configuration.get().naggle_ms; - [ImportingConstructor] - public MDDaemon(Lazy bus, Lazy token, Lazy ss, [Import(LoginContainer.Exports.UserID)]uint user_id) : - base(get_naggle(), MDSourceOptions.DeferInit, user_id) { + public MDDaemon(Lazy bus, Lazy token, Lazy ss, UserTuple user) + : base(mbts.config.Configuration.get().naggle_ms, MDSourceOptions.DeferInit, user) { _bus = bus; _token = token; - _ss = ss; + _ss = ss; } - override public void initialize() { + public int priority => 55; + + [Export] + MDConsumer consumer => _consumer; + IBus bus => _bus.Value; + + public override void initialize() { _relay.set_token(_token.Value); _dispose.Add( _ss.Value.subscribei_metadata() @@ -60,16 +60,8 @@ namespace bts { // Post full dictionary of syntheics here bus.post(SparkTags.SyntheticstrategiesTag, t); })); - _dispose.Add( this.on_securities.Subscribe( (md) => { - bus.post(SparkTags.SecuritiesTag, md); - })); + _dispose.Add(on_securities.Subscribe(md => bus.post(SparkTags.SecuritiesTag, md))); Task.Run(run); } - - [Export] - MDConsumer consumer => _consumer; - - public int priority => 55; - IBus bus => _bus.Value; } } \ No newline at end of file diff --git a/src/client/spark/Daemons/ShellLatencyDaemon.cs b/src/client/spark/Daemons/ShellLatencyDaemon.cs index 0f4e10fd3..723174cb6 100644 --- a/src/client/spark/Daemons/ShellLatencyDaemon.cs +++ b/src/client/spark/Daemons/ShellLatencyDaemon.cs @@ -3,17 +3,13 @@ using bts.metrics; using mbts; using mbts.config; using mbts.ui; -using mbts.ui.shell; using System; -using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Net.NetworkInformation; -using System.Text; using System.Threading.Tasks; namespace bts.perf { - [Export, Export(typeof(IShellDaemon))] class ShellLatencyDaemon : IShellDaemon, IDisposable { readonly ShellLatencyService _service; @@ -24,10 +20,10 @@ namespace bts.perf { Ping _pinger = new Ping(); [ImportingConstructor] - public ShellLatencyDaemon(ShellLatencyService service, [Import(LoginContainer.Exports.UserName)] string user) { + public ShellLatencyDaemon(ShellLatencyService service, UserTuple user) { _service = service; _version = Configuration.get().version; - _username = user; + _username = user.name; _hostname = Environment.MachineName; _forever_ping_host(_pinger); @@ -105,4 +101,4 @@ namespace bts.perf { Disposable.dispose(ref _subs); } } -} +} \ No newline at end of file diff --git a/src/client/spark/Modules/Market/MarketShellModule.cs b/src/client/spark/Modules/Market/MarketShellModule.cs index f2db00136..391801886 100644 --- a/src/client/spark/Modules/Market/MarketShellModule.cs +++ b/src/client/spark/Modules/Market/MarketShellModule.cs @@ -5,7 +5,6 @@ using mbts.co2; using mbts.persist; using mbts.spark; using mbts.ui; -using mbts.ui.shell; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; @@ -13,13 +12,11 @@ using System.Threading.Tasks; using System.Windows.Media; using static mbts.ui.shell.ProtoBufSerializationHelper; -namespace bts.shell -{ +namespace bts.shell { [Export(typeof(IShellModule))] - class MarketShellModule : IShellModule - { + class MarketShellModule : IShellModule { [ImportingConstructor] - public MarketShellModule(IBus bus, MDConsumer consumer, UserSettingsHub settings_hub, OrdersModel orders_model, [Import(LoginContainer.Exports.UserName)]string user_name) { + public MarketShellModule(IBus bus, MDConsumer consumer, UserSettingsHub settings_hub, OrdersModel orders_model) { _tsf = new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub); _mvf = new MarketViewWindowFactory(this, bus, settings_hub, orders_model); } diff --git a/src/client/spark/Modules/Spreader/SpreaderModel.cs b/src/client/spark/Modules/Spreader/SpreaderModel.cs index f34af26ab..916e7f078 100644 --- a/src/client/spark/Modules/Spreader/SpreaderModel.cs +++ b/src/client/spark/Modules/Spreader/SpreaderModel.cs @@ -1,7 +1,9 @@ -using bts.api; +using bts; +using bts.api; +using bts.api.core; using bts.api.synthetic; +using bts.collections; using bts.spark; -using mbts.ui.shell; using System; using System.Collections.Generic; using System.ComponentModel.Composition; @@ -18,11 +20,36 @@ namespace mbts.spark { readonly uint _user_id; [ImportingConstructor] - public SpreaderModel(IBus bus, SyntheticSecurityService service, ErrorReporter error, [Import(LoginContainer.Exports.UserID)]uint user_id) { + public SpreaderModel(IBus bus, SyntheticSecurityService service, AdminModel admin_model, ErrorReporter error, UserTuple user) { _bus = bus; _service = service; _error = error; - _user_id = user_id; + _user_id = user.id; + // synthetic tuples + var strategy_source = _bus.subscribe(SparkTags.SyntheticstrategiesTag) + .Select(map => MappedDictionary.create(map, (k, v) => (k, v))) + .Table(tup => tup.security_id); + + var synthetic_source = _bus.subscribe(SparkTags.SecuritiesTag) + .Select(map => new FilteredDictionary(map, smd => smd.security.ContractCase == Security.ContractOneofCase.Synthetic)) + .Table(smd => smd.security.Id); + + var synthetic_user_join = synthetic_source.LeftJoin( + admin_model.all_user_tuples, + SecurityMD.key_fn, + UserTuple.key_fn, + smd => smd.security.Synthetic.UserId, + (smd, sid, ut, uid) => new SyntheticTuple(smd.security, ut.name, null), + (smd, sid, uid) => new SyntheticTuple(smd.security, null, null), + SyntheticTuple.key_fn); + + synthetic_tuples = synthetic_user_join.LeftJoin( + strategy_source, + SyntheticTuple.key_fn, + tup => tup.security_id, + (synth_tup, id, strat_tup) => new SyntheticTuple(synth_tup.security, synth_tup.user_name, strat_tup.strategy), + (synth_tup, id) => synth_tup, + SyntheticTuple.key_fn); } public IObservable> strategy => _bus.subscribe(SparkTags.SyntheticstrategiesTag); @@ -36,6 +63,8 @@ namespace mbts.spark { .LeftJoin(strategies, (security, strategy) => (new ExecutionStrategyImmutable?(strategy), security), security => (new ExecutionStrategyImmutable?(), security)) ); + public IObservable> synthetic_tuples { get; } + public IObservable security_strategy(uint security_key) => strategy.TrySelect(s => { bool success = s.TryGetValue(security_key, out ExecutionStrategyImmutable result); diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs b/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs index c3b7e6bea..e74b52c18 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementView.xaml.cs @@ -7,8 +7,15 @@ namespace mbts.ui.spark { /// Interaction logic for SyntheticManagementView.xaml /// partial class SyntheticManagementView : UserControl { + public enum Columns { + Name, + Description, + n_legs, + n_working_orders, + SecurityKey, + User + } - public enum Columns { Name, Description, n_legs, n_working_orders, SecurityKey} public SyntheticManagementView() => InitializeComponent(); } diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs index 52458556b..cfbe2b7e3 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindow.cs @@ -10,6 +10,7 @@ using mbts.ui.utility; using mbts.utils; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Linq; using System.Reactive.Linq; using System.Windows; @@ -27,7 +28,7 @@ namespace mbts.spark { readonly IWindowSettingsManager _settings_manager; - public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, WindowSettingsManager settings_manager) + public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, IWindowSettingsManager settings_manager) : base("Synthetic Management", bus, factory, SparkCommands.ShowSyntheticManagement.icon) { _orders_model = orders_model; _state = state; @@ -66,8 +67,8 @@ namespace mbts.spark { ), SparkCommand.create("Clone", Icons.CloneSynthetic, SparkTags.ShowSyntheticCloneTag).complete( current_row_connectable_builder.create(observe_row_strategy), rs => rs.HasValue, select_row_strategy_tuple - ), SparkCommands.ShowLadder(SparkCommands.KeyGestures.ShowLadder).complete( - vm_connectable_builder.create(vm => vm.current_security_md), md => md.HasValue, ConvertUtils.ValueOrDefault + ), SparkCommands.ShowLadderAutoLookup(SparkCommands.KeyGestures.ShowLadder).complete( + vm_connectable_builder.create(vm => vm.current_security_observable.Select(s => s.HasValue ? ImmutableHashSet.Empty.Add(s.Value.Id) : null)), id => id != null ), SparkCommands.ShowOrders.complete(() => { var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default; ob_settings.filters = new bts.shell.orderbook.FilterStates { diff --git a/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs b/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs index e676dd306..29125b873 100644 --- a/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs +++ b/src/client/spark/Modules/Spreader/SyntheticManagementWindowFactory.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.settings; using mbts.persist; using mbts.spark; using mbts.spark.filters; @@ -7,6 +8,7 @@ using mbts.ui.settings; using ProtoBuf; using System; using System.Collections.Generic; +using System.ComponentModel.Composition; using System.Reactive.Linq; using System.Threading.Tasks; using static mbts.ui.controls.DIYGrid; @@ -33,13 +35,8 @@ namespace bts.shell { public async void show(SparkTags.Nothing nothing) => _bus.post(SparkTags.ShowWindow, await load(new StartupData())); - IShellWindow _create(StartupData state) { - var settings_manager = new WindowSettingsManager(_settings_hub, - state.grid, - get: us => us.synthetic_management_grid, - set: (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)); - return new SyntheticManagementWindow(this, _bus, _orders_model, state, settings_manager); - } + IShellWindow _create(StartupData state) => + new SyntheticManagementWindow(this, _bus, _orders_model, state, _settings_hub.create_synth_settings_manager(state.grid)); [ProtoContract] public class StartupData { @@ -67,6 +64,7 @@ namespace bts.shell { public static GridColumnSettings n_legs => new GridColumnSettings(col_id(Columns.n_legs), DefaultColumnHeaders.N_Legs, width: DefaultColumnWidths.N_Legs); public static GridColumnSettings n_working_orders => new GridColumnSettings(col_id(Columns.n_working_orders), DefaultColumnHeaders.N_Working_Orders, width: DefaultColumnWidths.N_Working_Orders); public static GridColumnSettings security_key => new GridColumnSettings(col_id(Columns.SecurityKey), DefaultColumnHeaders.SecurityKey, is_visible: false, width: DefaultColumnWidths.SecurityKey); + public static GridColumnSettings user => new GridColumnSettings(col_id(Columns.User), DefaultColumnHeaders.User, is_visible: false, width: DefaultColumnWidths.User); public static IEnumerable default_sorting_criterion { get { @@ -81,6 +79,7 @@ namespace bts.shell { yield return n_legs; yield return n_working_orders; yield return security_key; + yield return user; } } @@ -101,6 +100,15 @@ namespace bts.shell { public UIntMinMaxState n_working_orders; [ProtoMember(6)] public string security_key; + [ProtoMember(7)] + public uint[] user; + } + + // migration rules + [Export(typeof(ISyntheticManagementMigrationRule))] + class AddMissingColumnsMigrationRule : ISyntheticManagementMigrationRule { + public bool apply(GridSettings settings, out GridSettings new_settings) => + settings.add_missing_columns(StartupData.DefaultGridSettings.columns, out new_settings); } } -} +} \ No newline at end of file diff --git a/src/client/spark/Modules/Spreader/VM/SyntheticManagementDialogVM.cs b/src/client/spark/Modules/Spreader/VM/SyntheticManagementDialogVM.cs index c6dd59102..1f63cb046 100644 --- a/src/client/spark/Modules/Spreader/VM/SyntheticManagementDialogVM.cs +++ b/src/client/spark/Modules/Spreader/VM/SyntheticManagementDialogVM.cs @@ -1,12 +1,15 @@ -using bts.api; +using bts; +using bts.api; using bts.collections; using bts.spark; +using bts.utils; using mbts.persist; using mbts.spark.filters; using mbts.ui; using mbts.ui.settings; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using System.Reactive.Linq; @@ -17,43 +20,45 @@ using static mbts.ui.controls.DIYGrid; using static mbts.ui.spark.SyntheticManagementView; namespace mbts.spark { - class SyntheticManagementDialogVM : SecurityMDGrid { + class SyntheticManagementDialogVM : SecurityGrid { readonly IBus _bus; readonly OrdersModel _orders_model; - IWindowSettingsManager _settings_manager; - + readonly IWindowSettingsManager _settings_manager; public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager settings_manager) : this(bus, orders_model, settings_manager, null, null) { } public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager settings_manager, IReadOnlyCollection sorting, FilterStates filters) - : base(orders_model.spreader.strategy_tuple.Select(map => map.Values), sorting) { + : base(orders_model.spreader.synthetic_tuples.Select(t => t.state.Values), sorting) { _bus = bus; _orders_model = orders_model; + _settings_manager = settings_manager; + // init filters + user_filter = DiscreteValuesFilterVM.CreateTableUpdate(r => r.user_tuple, UserTuple.key_fn, out var user_filter_items_observer, out var user_filter_items_view, nameof(Row.user_tuple)); + user_filter_items_view.CustomSort = Comparer.Default.wrap(ut => ut.name).to_non_generic(); if (filters != null) { create_time_filter.load_state(filters.create_time); name_filter.load_state(filters.name); description_filter.load_state(filters.description); n_legs_filter.load_state(filters.n_legs); n_working_orders_filter.load_state(filters.n_working_orders); - security_key_filter.load_state(filters.security_key); + security_key_filter.load_state(filters.security_key); + user_filter.load_state(filters.user); } - _settings_manager = settings_manager; // columns add_col(Columns.Name, DefaultColumnHeaders.Name, r => r.name, nameof(Row.name), name_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Security); add_col(Columns.Description, DefaultColumnHeaders.Description, r => r.description, nameof(Row.description), description_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.Description); add_col(Columns.n_legs, DefaultColumnHeaders.N_Legs, r => r.n_legs.ToString(), nameof(Row.n_legs), n_legs_filter, DataGridFilterKnownTemplates.IntMinMax, DefaultColumnWidths.N_Legs); columns.Add(new HyperlinkElementColumn( - Columns.n_working_orders, - new Binding(nameof(Row.n_working_orders)), + Columns.n_working_orders, + new Binding(nameof(Row.n_working_orders)), new Binding(nameof(Row.show_order_book)), n_working_orders_filter, DataGridFilterKnownTemplates.UIntMinMax) { id = col_id(Columns.n_working_orders), Header = DefaultColumnHeaders.N_Working_Orders, Width = DefaultColumnWidths.N_Working_Orders - } - ); + }); add_col(Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, r => r.security_key.ToString(), nameof(Row.security_key), security_key_filter, DataGridFilterKnownTemplates.Regex, DefaultColumnWidths.SecurityKey); - + add_col(Columns.User, DefaultColumnHeaders.User, r => r.user_name, nameof(Row.user_name), user_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.User); // void add_col(Columns col_key, string header, Func get_text, string prop, IDataGridColumnFilter filter, string filter_template, double width) => columns.Add(new RenderTextColumn(col_key, get_text, filter, filter_template) { @@ -63,42 +68,39 @@ namespace mbts.spark { Width = width }); // - grid_settings_manager = new SimpleGridSettingsManager(columns, new Dictionary { }, row_vms); + grid_settings_manager = new SimpleGridSettingsManager(columns, DictionaryHelper.empty(), row_vms); // this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.) grid_settings_manager.load_from(settings_manager.current_settings()); _resources.AddRange( - DataGridFilterHelper.hook_filters(rows_view, create_time_filter, name_filter, description_filter, n_legs_filter, n_working_orders_filter, security_key_filter), + orders_model.admin_model.all_user_tuples.OnDispatcher().Subscribe(user_filter_items_observer), + DataGridFilterHelper.hook_all(this, rows_view), settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager) ); } - protected override Row row_factory((ExecutionStrategyImmutable? strategy, SecurityMD md) row_model) => - new Row(_bus, row_model.md, row_model.strategy, _orders_model); - - protected override void on_row_removed(Row row) => row.Dispose(); - - public ObservableCollection columns { get; } = new ObservableCollection(); + public ObservableCollection columns { get; } = new ObservableCollection(); public SimpleGridSettingsManager grid_settings_manager { get; } - public GridSettings get_grid_save_state() { - if (_settings_manager.instance_settings == null) - return null; - else - return grid_settings_manager.create(); - } - - public StartupData create() => - new StartupData(rows_view.get_sorting_criteria(columns), _get_filter_states(), get_grid_save_state()); - - - #region Filters public IDataGridColumnPersistentFilter create_time_filter { get; } = new TimeFilterVM(r => r.create_time, nameof(Row.create_time)); public IDataGridColumnPersistentFilter name_filter { get; } = new RegexFilterVM(r => r.name, nameof(Row.name)); public IDataGridColumnPersistentFilter description_filter { get; } = new RegexFilterVM(r => r.description, nameof(Row.description)); public IDataGridColumnPersistentFilter n_legs_filter { get; } = new IntMinMax(r => r.n_legs, nameof(Row.n_legs)); public IDataGridColumnPersistentFilter n_working_orders_filter { get; } = new UIntMinMax(r => r.n_working_orders, nameof(Row.n_legs)); public IDataGridColumnPersistentFilter security_key_filter { get; } = new RegexFilterVM(r => r.security_key.ToString(), nameof(Row.security_key)); + public IDataGridColumnPersistentFilter user_filter { get; } + + public GridSettings get_grid_save_state() => + _settings_manager.instance_settings == null ? null : grid_settings_manager.create(); + + public StartupData create() => + new StartupData(rows_view.get_sorting_criteria(columns), _get_filter_states(), get_grid_save_state()); + + protected override Row row_factory(SyntheticTuple row_model) => + new Row(_bus, row_model, _orders_model); + + protected override void on_row_removed(Row row) => + row.Dispose(); FilterStates _get_filter_states() => new FilterStates { @@ -107,19 +109,19 @@ namespace mbts.spark { name = name_filter.get_state(), n_legs = n_legs_filter.get_state(), n_working_orders = n_working_orders_filter.get_state(), - security_key = security_key_filter.get_state() + security_key = security_key_filter.get_state(), + user = user_filter.get_state() }; - #endregion - public class Row : SecurityMDRow, IEquatable, IRowVM, IActionableRowVM { - public readonly ExecutionStrategyImmutable? strategy; + public class Row : SecurityRow, IEquatable, IRowVM, IActionableRowVM { + public readonly SyntheticTuple synthetic_tuple; readonly IBus _bus; readonly Property _n_working_orders; - public Row(IBus bus, SecurityMD security_md, ExecutionStrategyImmutable? strategy, OrdersModel orders_model) : base(security_md) { + public Row(IBus bus, SyntheticTuple synthetic_tuple, OrdersModel orders_model) : base(synthetic_tuple.security) { _bus = bus; - this.strategy = strategy; + this.synthetic_tuple = synthetic_tuple; _n_working_orders = backing(nameof(n_working_orders), orders_model.on_security_orders(security_key) .Select(t => (uint)(t.state @@ -133,25 +135,23 @@ namespace mbts.spark { show_order_book = new DelegateCommand(_show_order_book); } + public event Action invalidated; + public DateTime create_time => DateTime.MinValue; //TODO public string name { get; } + public string user_name => synthetic_tuple.user_name; + public UserTuple user_tuple => new UserTuple(synthetic_tuple.security.Synthetic.UserId, user_name); public int n_legs { get; } public string description { get; } + public ExecutionStrategyImmutable? strategy => synthetic_tuple.strategy; public bool strategy_present => strategy.HasValue; public uint n_working_orders => _n_working_orders.Value; public ICommand show_ladder { get; } public ICommand show_order_book { get; } public ICommand default_command => show_ladder; - - public ObservableCollection row_animations => new ObservableCollection(); - - public IReadOnlyList cell_stores => new IGridCellStore[0]; - - - public event Action invalidated; - - public void raise_invalidated() => invalidated?.Invoke(); + public void raise_invalidated() => + invalidated?.Invoke(); public bool Equals(Row other) => other != null && @@ -163,10 +163,8 @@ namespace mbts.spark { public override int GetHashCode() => security_key.GetHashCode(); - - void _show_ladder() => - _bus.post(SparkTags.ShowLadderTag, md); + _bus.post(SparkTags.ShowLadderAutoLookupTag, ImmutableHashSet.Empty.Add(security.Id)); void _show_order_book() { var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default; @@ -177,4 +175,4 @@ namespace mbts.spark { } } } -} +} \ No newline at end of file diff --git a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs index a955270d7..aec98c8cd 100644 --- a/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs +++ b/src/client/spark/Modules/Trading/AlgoStudio/Model/AlgoStudioFlatDefinitionModel.cs @@ -27,7 +27,7 @@ namespace mbts.spark { _error_reporter = error_reporter; definitions = service.subscribei_algo_definitions() - .Filter(r => r.Metadata.IsActive && r.Metadata.CreatorUserId == _admin_model.user.id) + .Filter(r => r.Metadata.IsActive && _admin_model.user.can_access_user_data(r.Metadata.CreatorUserId)) .SelectKeyValue(_definition_data, d => d.key) .Table() .Cache(); diff --git a/src/client/spark/Modules/Trading/Fills/FillsVM.cs b/src/client/spark/Modules/Trading/Fills/FillsVM.cs index d600aef4f..8509914e1 100644 --- a/src/client/spark/Modules/Trading/Fills/FillsVM.cs +++ b/src/client/spark/Modules/Trading/Fills/FillsVM.cs @@ -118,8 +118,8 @@ namespace mbts.spark { add_col_expl(Columns.Side, new SideColumn(Columns.Side, r => r.side, side_filter) { id = col_id(Columns.Side) }, side_filter); // all others (easily identified by the enum 'Columns.Foo') add_col(Columns.FillTime, DefaultColumnHeaders.FillTime, r => r.fill_time.ToString("M/d h:mm:ss tt"), new TimeFilterVM(r => r.fill.Timestamp.ToDateTimeOffset().LocalDateTime), DataGridFilterKnownTemplates.TimeFilter, DefaultColumnWidths.Time); - add_col(Columns.User, DefaultColumnHeaders.User, r => r.user, dv_filter_rx(_model.factory.subscribe_users().Select(d => d.Values), r => r.order?.user() ?? string.Empty), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.User); - add_col(Columns.Account, DefaultColumnHeaders.Account, r => r.account, dv_filter_rx(_model.factory.subscribe_accounts().Select(d => d.Values), r => r.account), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Account); + add_col(Columns.User, DefaultColumnHeaders.User, r => r.user, dv_filter_rx(_model.factory.subscribe_users().Select(d => d.Values.Ordered()), r => r.order?.user() ?? string.Empty), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.User); + add_col(Columns.Account, DefaultColumnHeaders.Account, r => r.account, dv_filter_rx(_model.factory.subscribe_accounts().Select(d => d.Values.Ordered()), r => r.account), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Account); add_col(Columns.Exchange, DefaultColumnHeaders.Exchange, r => r.exchange.ToString(), dv_filter(EnumHelper.get_values().ToArray(), r => r.security.exchange_or_default()), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Exchange); add_col(Columns.TimeInForce, DefaultColumnHeaders.TimeInForce, r => r.time_in_force.ToString(), dv_filter(EnumHelper.get_values().ToArray(), r => r.order?.time_in_force() ?? TimeInForce.Undefined), DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.TimeInForce); add_col(Columns.Size, DefaultColumnHeaders.Size, r => r.size.ToString(), new DoubleMinMax(r => r.fill.LastShares), DataGridFilterKnownTemplates.UIntMinMax, DefaultColumnWidths.Size); @@ -146,6 +146,7 @@ namespace mbts.spark { }); _dispose = new CompositeDisposable( ObservableAutoWrapper.connect(col_tups, columns, ct => ct.col), + ObservableAutoWrapper.connect_item_hooks(col_tups, ct => ct.filter as IDisposable), RXCollection.connect(rows, fills_buffer.Filter(filter_src, FillTuple.key_fn), comp_src, ft => new Row(ft, model), r => r.fill_tuple), fills_source.OnDispatcher().Subscribe(t => { last_unfiltered_fills = t; diff --git a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs index e7a16fdce..0d1b3ac40 100644 --- a/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/Ladder/LadderWindowFactory.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.collections; using bts.md; using mbts; using mbts.config; @@ -50,6 +51,7 @@ namespace bts.shell { _mbo = mbo; _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s), + bus.subscribe(SparkTags.ShowLadderAutoLookupTag).Subscribe(_show_windows), bus.subscribe(SparkTags.ShowLadderTag).OnDispatcher().Subscribe(s => show_windows(new[] { s })), bus.subscribe(SparkTags.ShowLaddersTag).OnDispatcher().Subscribe(show_windows) ); @@ -273,7 +275,21 @@ namespace bts.shell { }); } - void show_windows(IReadOnlyCollection securities) { + async void _show_windows(IImmutableSet securities) { + if (securities == null) + return; + var start_time = DateTime.Now; + do { + var found = securities.KeyJoin(_securities).ToList(); + securities = securities.RemoveRange(found.Select(SecurityMD.key_fn)); + show_windows(found); + if (securities.Count == 0) + break; + await Task.Delay(500); + } while ((DateTime.Now - start_time) < _ladder_conf.security_timeout); + } + + void show_windows(IEnumerable securities) { int n_allowed = (int)_ladder_conf.max_open_ladders - _wm.list_windows().Where(w => w.window_type == _window_type).Count(); int n_opened = 0; foreach (var s in securities) { diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs index b9330c030..eb5a11bfb 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookColumns.cs @@ -121,7 +121,7 @@ namespace mbts.spark { r => r.user, DefaultColumnWidths.User, DiscreteValuesFilterVM.Create( - model.factory.subscribe_users().Select(d => d.Values), + model.factory.subscribe_users().Select(d => d.Values.Ordered()), ort => ort.order.order.user(), nameof(OrderBookRowVM.user)), DataGridFilterKnownTemplates.DiscreteValues, @@ -133,7 +133,7 @@ namespace mbts.spark { r => r.account, DefaultColumnWidths.Account, DiscreteValuesFilterVM.Create( - model.factory.subscribe_accounts().Select(d => d.Values), + model.factory.subscribe_accounts().Select(d => d.Values.Ordered()), ort => ort.order.order.account(), vals => vals.ToArray(), vals => Observable.Return(vals), diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 40990a269..612a0adeb 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -239,7 +239,7 @@ namespace mbts.spark { grid_settings_manager, order_mod_vm.algo_vm.connect_data(Observable.Return(model)), order_mod_vm.algo_vm.connect_data(_selected_params_mon.subscribe_spreader_security()), - order_mod_vm.algo_vm, + order_mod_vm, attach_vm, _show_fills.observe_current(true) .Subscribe(is_visible => { @@ -735,17 +735,13 @@ namespace mbts.spark { _size_permissions = AlgoParamPermissions.ReadOnly | AlgoParamPermissions.Write; SecurityMD? _security_md; - public OrderParamsVM(OrderBookVM owner, AlgoFormats init_format, AlgoEditingPermissions init_permissions) - : this(owner, - AlgoDefinitionVM.create( - owner._model, - AlgoData.create_unpersisted(OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase.Iceberg), CustomOrderDefinition.CustomOneofCase.Iceberg.display_name()), - init_format: init_format, - editing_permissions: init_permissions)) { } - - OrderParamsVM(OrderBookVM owner, AlgoDefinitionVM algo_vm) { + public OrderParamsVM(OrderBookVM owner, AlgoFormats init_format, AlgoEditingPermissions init_permissions) { _owner = owner; - this.algo_vm = algo_vm; + algo_vm = AlgoDefinitionVM.create( + owner._model, + AlgoData.create_unpersisted(OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase.Iceberg), CustomOrderDefinition.CustomOneofCase.Iceberg.display_name()), + init_format: init_format, + editing_permissions: init_permissions); _accounts = backing( nameof(selected_account), _model.factory.subscribe_account_tuples(), @@ -784,7 +780,8 @@ namespace mbts.spark { appended_param_rows.insert_front(new AlgoParamRowVM(root, _price_param, null, AlgoParamTemplateKeys.Price)); } }), - ObservableAutoWrapper.connect_item_hooks(param_rows, dirty_params_mon.join)); + ObservableAutoWrapper.connect_item_hooks(param_rows, dirty_params_mon.join), + algo_vm); // payup methods void payup_bid(int ticks) => payup(bbo.bid, -ticks); void payup_ask(int ticks) => payup(bbo.ask, ticks); diff --git a/src/client/spark/Orders/OrderDataHelper.cs b/src/client/spark/Orders/OrderDataHelper.cs index 27df49a4c..6d26b2a3a 100644 --- a/src/client/spark/Orders/OrderDataHelper.cs +++ b/src/client/spark/Orders/OrderDataHelper.cs @@ -67,7 +67,6 @@ namespace mbts.spark.utilities { public IObservable> subscribe_accounts() => _admin_model.on_accounts; public IObservable> subscribe_users() => _admin_model.on_users; - public IObservable> subscribe_user_tuples() => _admin_model.on_user_tuples; public IObservable> subscribe_account_tuples() => _admin_model.on_account_tuples; #region Defaults diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index 920acfca3..ffeceeb34 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -59,18 +59,26 @@ namespace mbts.spark { this.md_auxiliary_model = md_auxiliary_model; var scheduler = ThreadPoolScheduler.Instance; var interval = TimeSpan.FromMilliseconds(100); - on_orders = - _service - .subscribei_orders() - .Naggle(interval, scheduler) - .PermissionFilter(admin_model.on_admin_data) - .join(sstore, order => order.security_key()) + on_orders = admin_model + .permission_filter( + _service.subscribei_orders() + .Naggle(interval, scheduler), + o => o.account_id() + ).join(sstore, order => order.security_key()) .Table() .Cache(); - on_positions = _position_service.subscribei_position_data().Naggle(interval, scheduler).PermissionFilter(admin_model.on_admin_data).join(sstore, pos => pos.SecurityId).Table().Cache(); - on_pnl = _position_service.subscribei_pnl_data() - .Naggle(interval, scheduler) + on_positions = admin_model + .permission_filter( + _position_service.subscribei_position_data().Naggle(interval, scheduler), + p => p.AccountId) + .join(sstore, pos => pos.SecurityId) + .Table() + .Cache(); + on_pnl = admin_model + .permission_filter( + _position_service.subscribei_pnl_data().Naggle(interval, scheduler), + p => p.Pos.AccountId) .join(sstore, p => p.Pos.SecurityId) .TableCheckedAutoCorrect(EqualityComparer<(SecurityImmutable? sec, PNLUnitImmutable data)>.Default) .Where(t => t.has_changes()) @@ -173,10 +181,11 @@ namespace mbts.spark { .Where(t => t.has_changes()) .Cache(); // fill tuples - var on_fills = - _service.subscribei_fills() - .Naggle(interval, scheduler) - .PermissionFilter(admin_model.on_admin_data) + var on_fills = admin_model + .permission_filter( + _service.subscribei_fills() + .Naggle(interval, scheduler), + f => f.Account) .join(sstore, f => f.SecurityKey) .Table().Cache(); var fill_order_tuples_join = on_fills.LeftJoin( diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index 1c2e0cea5..ee4414e48 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -8,6 +8,7 @@ using mbts.spark; using mbts.ui; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Windows.Input; namespace bts.spark { @@ -41,6 +42,9 @@ namespace bts.spark { SparkCommand.create("P&L (2.0)", Icons.Accounting, SparkTags.ShowPNLTag); // Ladder + public static PartialCommand> ShowLadderAutoLookup(KeyGesture key_gesture = null) => + SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderAutoLookupTag, key_gesture); + public static PartialCommand ShowLadder(KeyGesture key_gesture = null) => SparkCommand.create("Ladder", Icons.Ladder, SparkTags.ShowLadderTag, key_gesture); diff --git a/src/client/spark/core/Bus/SparkTags.cs b/src/client/spark/core/Bus/SparkTags.cs index 0449e8065..311e7fb13 100644 --- a/src/client/spark/core/Bus/SparkTags.cs +++ b/src/client/spark/core/Bus/SparkTags.cs @@ -7,6 +7,7 @@ using bts.spark; using mbts.ui; using System; using System.Collections.Generic; +using System.Collections.Immutable; using System.Threading.Tasks; namespace mbts.spark { @@ -55,6 +56,8 @@ namespace mbts.spark { // The owners of the various SparkWindows may remove dependencies on the former at their leasure. // For now, both tags go through the same logic in the LadderWindowFactory anyways. public static ITag ShowLadderTag { get; } = new SparkTag("Show Ladder"); + // TODO: get rid of the SecurityMD ShowLadderTag. This has created burdensome dependency issues. + public static ITag> ShowLadderAutoLookupTag { get; } = new SparkTag>("Show Ladder Auto Lookup"); public static ITag> ShowLaddersTag { get; } = new SparkTag>(nameof(ShowLaddersTag)); public static ITag> ShowLinkedLadder { get; } = new SparkTag>("Linked Ladder"); public static ITag ShowMarketViewTag { get; } = new SparkTag("Show MarketView"); diff --git a/src/client/spark/core/ShellInterface/UISettings.cs b/src/client/spark/core/ShellInterface/UISettings.cs index 2b454f848..48385d724 100644 --- a/src/client/spark/core/ShellInterface/UISettings.cs +++ b/src/client/spark/core/ShellInterface/UISettings.cs @@ -11,6 +11,7 @@ using bts.api.persistence; using System.Text.RegularExpressions; using System.Reactive.Linq; using bts.spark; +using bts; namespace mbts.persist { @@ -146,16 +147,18 @@ namespace mbts.persist } [Export(typeof(IUserPersist))] - public class UserUISettings : UISettingsBase - { + public class UserUISettings : UISettingsBase { string _user; - [ImportingConstructor] - public UserUISettings([Import("userid")]uint user, [Import("settings")]PersistenceService persist, ErrorReporter err) + public UserUISettings(uint user_id, [Import("settings")]PersistenceService persist, ErrorReporter err) : base(persist,err) { - _user = $"User {user}"; + _user = $"User {user_id}"; } + [ImportingConstructor] + UserUISettings(UserTuple user, [Import("settings")]PersistenceService persist, ErrorReporter err) + : this(user.id, persist, err) { } + protected override string user() { return _user; } } } diff --git a/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs b/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs index 9e4b314c5..ce301199a 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/ISettingsMigrationRule.cs @@ -17,6 +17,7 @@ namespace bts.settings { interface IMarketViewGridSettingsMigrationRule : ISettingsMigrationRule { } interface IPAndLGridSettingsMigrationRule : ISettingsMigrationRule { } interface IPNLSettingsMigrationRule : ISettingsMigrationRule { } + interface ISyntheticManagementMigrationRule : ISettingsMigrationRule { } static class SettingsMigrationHelper { public static bool apply(T settings, IEnumerable> migration_rules, out T new_settings) { diff --git a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs index a2b70175d..50dd84359 100644 --- a/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs +++ b/src/client/spark/core/ShellInterface/UserSettings/UserSettingsHub.cs @@ -25,7 +25,8 @@ namespace mbts.persist { static readonly IImmutableProperty _fills_propi = ImmutableProperty.create(us => us.fills_grid, (us, gs) => us.with(provided_fills_gridsettings: gs)), _mview_propi = ImmutableProperty.create(us => us.market_view_grid, (us, gs) => us.with(provided_market_view_gridsettings: gs)), - _pandl_propi = ImmutableProperty.create(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)); + _pandl_propi = ImmutableProperty.create(us => us.pnl_grid, (us, gs) => us.with(provided_pnl_gridsettings: gs)), + _synth_propi = ImmutableProperty.create(us => us.synthetic_management_grid, (us, gs) => us.with(provided_synthetic_management_gridsettings: gs)); static readonly IImmutableProperty _pnl_propi = ImmutableProperty.create(us => us.pnl, (us, pnl) => us.with(pnl: pnl)); @@ -36,6 +37,7 @@ namespace mbts.persist { readonly IEnumerable _mview_migration_rules; readonly IEnumerable _pandl_migration_rules; readonly IEnumerable _pnl_migration_rules; + readonly IEnumerable _synth_migration_rules; readonly IUserPersist _persist; UserSettings _default_settings; @@ -46,13 +48,15 @@ namespace mbts.persist { [ImportMany]IEnumerable fills_migration_rules, [ImportMany]IEnumerable mview_migration_rules, [ImportMany]IEnumerable pandl_migration_rules, - [ImportMany]IEnumerable pnl_migration_rules) { + [ImportMany]IEnumerable pnl_migration_rules, + [ImportMany]IEnumerable synth_migration_rules) { // _persist = persist; _fills_migration_rules = fills_migration_rules ?? Enumerable.Empty(); _mview_migration_rules = mview_migration_rules ?? Enumerable.Empty(); _pandl_migration_rules = pandl_migration_rules ?? Enumerable.Empty(); _pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty(); + _synth_migration_rules = synth_migration_rules ?? Enumerable.Empty(); init(); async void init() { UserSettings s; @@ -62,7 +66,9 @@ namespace mbts.persist { var wrapped_rules = new[] { _fills_migration_rules.merge().wrap(_fills_propi), _mview_migration_rules.merge().wrap(_mview_propi), - _pandl_migration_rules.merge().wrap(_pandl_propi) + _pandl_migration_rules.merge().wrap(_pandl_propi), + _pnl_migration_rules.merge().wrap(_pnl_propi), + _synth_migration_rules.merge().wrap(_synth_propi) }; SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules); // TODO: move ladder sanitization logic into ISettingsMigrationRule @@ -136,6 +142,12 @@ namespace mbts.persist { _pnl_migration_rules, _pnl_propi); + public IWindowSettingsManager create_synth_settings_manager(GridSettings instance_settings) => + _create_settings_manager( + instance_settings, + _synth_migration_rules, + _synth_propi); + public async Task save_default(UserSettings value) { // notify observers before persisting so the changes are reflected immediately in the ui lock (_default_settings_lock) { diff --git a/src/client/spark/core/Utility/ObjectSnapshot.cs b/src/client/spark/core/Utility/ObjectSnapshot.cs index 4e8418417..e649f55ed 100644 --- a/src/client/spark/core/Utility/ObjectSnapshot.cs +++ b/src/client/spark/core/Utility/ObjectSnapshot.cs @@ -15,12 +15,8 @@ namespace bts.utils { } static class ObjectSnapshot { - public static IEnumerable> property_delegates_of_type() where TSource : class where TValue : class { - var tval = typeof(TValue); - return typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance) - .Where(p => tval.IsAssignableFrom(p.PropertyType)) - .Select(_prop_getter); - } + public static IReadOnlyList> property_delegates_of_type() => + PropertyGetterStore.value; public static IObservable> property_table(T instance, params string[] prop_names) where T : INotifyPropertyChanged => _property_table(instance, Array.ConvertAll(prop_names, PropertyInfoStore.type.GetProperty)); @@ -162,6 +158,18 @@ namespace bts.utils { } } + static class PropertyGetterStore { + public static readonly IReadOnlyList> value; + + static PropertyGetterStore() { + var tval = typeof(TValue); + value = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => tval.IsAssignableFrom(p.PropertyType)) + .Select(_prop_getter) + .ToReadOnlyList(); + } + } + class PropNode { public readonly PropertyInfo prop; diff --git a/src/client/spark/core/data/SyntheticTuple.cs b/src/client/spark/core/data/SyntheticTuple.cs new file mode 100644 index 000000000..b0717f1b5 --- /dev/null +++ b/src/client/spark/core/data/SyntheticTuple.cs @@ -0,0 +1,46 @@ +using bts.api; +using bts.spark; +using bts.utils; +using System; + +namespace bts { + struct SyntheticTuple : IEquatable, IComparable, IComparable { + public static readonly Func key_fn = a => a.security.Id; + public static readonly Func nullable_key_fn = a => a.HasValue ? a.Value.security.Id : 0u; + + public readonly SecurityImmutable security; + public readonly string user_name; + public readonly ExecutionStrategyImmutable? strategy; + public readonly int? num_working_orders; + + public SyntheticTuple(SecurityImmutable security, string user_name, ExecutionStrategyImmutable? strategy, int? num_working_orders = null) { + this.security = security; + this.user_name = user_name; + this.strategy = strategy; + this.num_working_orders = num_working_orders; + } + + public int CompareTo(SyntheticTuple other) => + SecurityHelper.Comparer.Compare(security, other.security); + + int IComparable.CompareTo(object obj) => + obj is SyntheticTuple other ? CompareTo(other) : 1; + + public bool Equals(SyntheticTuple other) => + security == other.security && + user_name == other.user_name && + EqualityComparer.nullable_equals(strategy, other.strategy); + + public override bool Equals(object obj) => + EqualityComparer.equals_obj(this, obj); + + public override int GetHashCode() => + security.Id.GetHashCode(); + + public override string ToString() => + user_name == null ? security.ToString() : $"{user_name}:{security}"; + + public static bool operator ==(SyntheticTuple a, SyntheticTuple b) => a.Equals(b); + public static bool operator !=(SyntheticTuple a, SyntheticTuple b) => !a.Equals(b); + } +} diff --git a/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs b/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs index 54822a36e..1c13e5a21 100644 --- a/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs +++ b/src/client/spark/view/Controls/DataGridEx/Filters/DataGridFilterHelper.cs @@ -1,11 +1,22 @@ -using System; +using bts.utils; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace mbts.spark.filters { static class DataGridFilterHelper { - public static IDisposable hook_filters(ICollectionView rows, params IDataGridColumnFilter[] filters) { + public static IDisposable hook_all(TSource source, ICollectionView rows) => + hook_filters(rows, + ObjectSnapshot.property_delegates_of_type>() + .Select(f => f(source)) + .ExceptNull() + .ToList()); + + public static IDisposable hook_filters(ICollectionView rows, params IDataGridColumnFilter[] filters) => + hook_filters(rows, filters.AsEnumerable()); + + public static IDisposable hook_filters(ICollectionView rows, IEnumerable> filters) { var icvls = (ICollectionViewLiveShaping)rows; icvls.IsLiveFiltering = true; return _hook_filters(set_filter, filters); @@ -22,7 +33,7 @@ namespace mbts.spark.filters { } } - static IDisposable _hook_filters(Action set_filter, params IDataGridColumnFilter[] filters) { + static IDisposable _hook_filters(Action set_filter, IEnumerable> filters) { foreach (var f in filters) f.filter_changed += set_filter; set_filter(); @@ -34,7 +45,7 @@ namespace mbts.spark.filters { }); } - static List> _get_active_filters(IDataGridColumnFilter[] filters) => + static List> _get_active_filters(IEnumerable> filters) => filters.Where(f => f.active.HasValue && f.active.Value).ToList(); } diff --git a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs index ce8927104..e42550ee5 100644 --- a/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs +++ b/src/client/spark/view/Controls/DataGridEx/Filters/VM/DiscreteValuesFilterVM.cs @@ -68,10 +68,11 @@ namespace mbts.spark.filters { Func factory, Func key, out IObserver> items_observer, - out ListCollectionView items_view) + out ListCollectionView items_view, + string prop_name = null) where TKey : struct, IEquatable => // - CreateTableUpdate(factory, key, keys => keys, keys => keys.ToArray(), out items_observer, out items_view); + CreateTableUpdate(factory, key, keys => keys, keys => keys.ToArray(), out items_observer, out items_view, prop_name); public static IDataGridColumnPersistentFilter CreateTableUpdate( Func factory, @@ -79,10 +80,11 @@ namespace mbts.spark.filters { Func> load_state, Func, TState> get_state, out IObserver> items_observer, - out ListCollectionView items_view) + out ListCollectionView items_view, + string prop_name = null) where TKey : struct, IEquatable { // - var filter = new TableUpdateItemsFilter(factory, key, load_state, get_state); + var filter = new TableUpdateItemsFilter(factory, key, load_state, get_state, prop_name); items_observer = filter; items_view = filter.items_view; return filter; @@ -291,8 +293,8 @@ namespace mbts.spark.filters { readonly HashSet _selected_keys = new HashSet(), _desired_keys = new HashSet(); ListCollectionView _items_view; - public TableUpdateItemsFilter(Func factory, Func key, Func> load_state, Func, TState> get_state) - : base(factory, null) { + public TableUpdateItemsFilter(Func factory, Func key, Func> load_state, Func, TState> get_state, string prop_name) + : base(factory, prop_name) { _factory = factory; _key = key; _load_state = load_state; diff --git a/src/client/spark/view/Shell/Login/LoginModel.cs b/src/client/spark/view/Shell/Login/LoginModel.cs index 35f666503..9fb963b61 100644 --- a/src/client/spark/view/Shell/Login/LoginModel.cs +++ b/src/client/spark/view/Shell/Login/LoginModel.cs @@ -15,8 +15,7 @@ namespace mbts.ui.shell { // The LoginContainer participates in the startup Import/Export dependency system // Since the login form should not depend on *anything* it will be shown before this is created // Once this is created it access the global LoginModel and retrieves the username - internal class LoginContainer - { + class LoginContainer { [ImportingConstructor] public LoginContainer(ServiceContext context) { var model = LoginModel.instance; @@ -28,10 +27,8 @@ namespace mbts.ui.shell { model.Dispose(); } - [Export(Exports.UserName)] public string UserName { get; private set; } - [Export(Exports.UserID)] public uint UserId { get; private set; } [Export] @@ -42,13 +39,6 @@ namespace mbts.ui.shell { [Export("workspace")] public string Workspace { get; private set; } - - public static class Exports { - public const string - UserName = "username", - UserID = "userid", - UserTuple = "usertuple"; - } } public struct User { diff --git a/src/client/spark/view/Shell/ViewModels/LauncherVM.cs b/src/client/spark/view/Shell/ViewModels/LauncherVM.cs index 63b760725..9fd63320c 100644 --- a/src/client/spark/view/Shell/ViewModels/LauncherVM.cs +++ b/src/client/spark/view/Shell/ViewModels/LauncherVM.cs @@ -12,8 +12,7 @@ using System.Windows.Input; namespace mbts.ui.shell { [Export(typeof(ILauncher))] - public class LauncherVM : ViewModelBase, ILauncher - { + public class LauncherVM : ViewModelBase, ILauncher { Window _window; string _user; readonly IBus _bus; @@ -23,9 +22,9 @@ namespace mbts.ui.shell { [ImportingConstructor] public LauncherVM( ObservableCollection modules, - [Import(LoginContainer.Exports.UserName)]string username, + UserTuple user, ErrorReporter errors, IBus bus) { - _user = username; + _user = user.name; _modules = new ObservableAutoWrapper(modules, m => new ShellModuleVM(m, bus)); _error_service = errors; _bus = bus; @@ -140,4 +139,4 @@ namespace mbts.ui.shell { #endregion } -} +} \ No newline at end of file diff --git a/src/client/spark_api/api/Update.cs b/src/client/spark_api/api/Update.cs index 8522a6430..92bf6a471 100644 --- a/src/client/spark_api/api/Update.cs +++ b/src/client/spark_api/api/Update.cs @@ -745,13 +745,19 @@ namespace bts.api.core { return new CompositeDisposable(source.Subscribe(aggregator.on_left), right.Subscribe(aggregator.on_right)); }); - public static IObservable AggregateLatest(this IObservable source, IObservable right, - Func, TRight, TAggregate> update_left, Func, TAggregate> update_right, TAggregate seed, + public static IObservable AggregateLatest( + this IObservable source, + IObservable right, + Func, TRight, TAggregate> update_left, + Func, TAggregate> update_right, + Func seed_factory, Func result_selector, - TLeft init_left = default, TRight init_right = default) => + TLeft init_left = default, + TRight init_right = default) => + // Observable.Create(o => { Log.DataFlow.diag($"Create AggregateLatest (Left: {typeof(TLeft)}, Right: {typeof(TRight)})."); - var aggregator = new ConcurrentAggregator(update_left, update_right, agg => o.OnNext(result_selector(agg)), seed, init_left, init_right); + var aggregator = new ConcurrentAggregator(update_left, update_right, agg => o.OnNext(result_selector(agg)), seed_factory(), init_left, init_right); return new CompositeDisposable(source.Subscribe(aggregator.on_left), right.Subscribe(aggregator.on_right)); }); diff --git a/src/client/spark_api/api/Update/TableUpdateFullJoin.cs b/src/client/spark_api/api/Update/TableUpdateFullJoin.cs index c1cc9d2b3..a66381fb3 100644 --- a/src/client/spark_api/api/Update/TableUpdateFullJoin.cs +++ b/src/client/spark_api/api/Update/TableUpdateFullJoin.cs @@ -18,7 +18,7 @@ namespace bts.api.core { return left_source.AggregateLatest, TableUpdate, (TableUpdate result, IReadOnlyDictionary left_state, IReadOnlyDictionary right_state), TableUpdate>(right_source, process_left, process_right, - (TableUpdate.mk_empty(result_key), new Dictionary(0), new Dictionary(0)), + () => (TableUpdate.mk_empty(result_key), new Dictionary(0), new Dictionary(0)), t => t.result, TableUpdate.mk_empty(left_key), TableUpdate.mk_empty(right_key)); // left diff --git a/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs index 1b6832260..eb9f7a56f 100644 --- a/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs +++ b/src/client/spark_api/api/Update/TableUpdateLeftJoin.cs @@ -20,7 +20,7 @@ namespace bts.api.core { right_source, process_left, process_right, - (TableUpdate.mk_empty(result_key), new Dictionary>()), + () => (TableUpdate.mk_empty(result_key), new Dictionary>()), state => state.result, TableUpdate.mk_empty(left_key), TableUpdate.mk_empty(right_key)); diff --git a/src/client/spark/core/data/UserTuple.cs b/src/client/spark_api/data/UserTuple.cs similarity index 52% rename from src/client/spark/core/data/UserTuple.cs rename to src/client/spark_api/data/UserTuple.cs index b0689a74f..c4200b75c 100644 --- a/src/client/spark/core/data/UserTuple.cs +++ b/src/client/spark_api/data/UserTuple.cs @@ -1,15 +1,28 @@ using System; namespace bts { - struct UserTuple : IEquatable, IComparable, IComparable { + public readonly struct UserTuple : IEquatable, IComparable, IComparable { + const string _admin_name = "bts"; + public static readonly Func key_fn = u => u.id; + public static UserTuple admin => new UserTuple(0, _admin_name, Permissions.Admin); public readonly uint id; public readonly string name; + public readonly Permissions permissions; - public UserTuple(uint id, string name) { + public UserTuple(uint id, string name) + : this(id, name, name == _admin_name ? Permissions.Admin : Permissions.Regular) { } + + public UserTuple(uint id, string name, Permissions permissions) { this.id = id; this.name = name; + this.permissions = permissions; + } + + public enum Permissions { + Regular, + Admin } public int CompareTo(UserTuple other) { @@ -28,4 +41,9 @@ namespace bts { public static bool operator ==(UserTuple a, UserTuple b) => a.Equals(b); public static bool operator !=(UserTuple a, UserTuple b) => !a.Equals(b); } -} + + public static class UserTupleExtensions { + public static bool can_access_user_data(this UserTuple user, uint user_id) => + user.id == user_id || user.permissions == UserTuple.Permissions.Admin; + } +} \ No newline at end of file diff --git a/src/client/spark_api/md/MDSource.cs b/src/client/spark_api/md/MDSource.cs index 7281aba04..7aefc929a 100644 --- a/src/client/spark_api/md/MDSource.cs +++ b/src/client/spark_api/md/MDSource.cs @@ -13,84 +13,78 @@ namespace bts.md { enum MDSourceOptions { DeferInit = 1, } - class MDSource : IObserver>, IDisposable - { + + class MDSource : IObserver>, IDisposable { const uint _no_user_id = 0; + protected readonly MDConsumer _consumer = new MDConsumer(); protected readonly Co2RelayControl _relay; - protected DateTime _version = DateTime.MinValue; protected readonly ConcurrentDictionary _exchange_sec_map = new ConcurrentDictionary(); - protected List _dispose = new List(); protected readonly MDSourceOptions _options; - readonly uint _user_id; + protected DateTime _version = DateTime.MinValue; + protected List _dispose = new List(); - public MDSource(uint naggle_ms, MDSourceOptions options = 0, uint user_id = _no_user_id) - { + readonly UserTuple _user; + readonly BehaviorSubject> _on_securities = + new BehaviorSubject>(new ConcurrentDictionary()); + + public MDSource(uint naggle_ms, MDSourceOptions options = 0) + : this(naggle_ms, options, UserTuple.admin) { } + + public MDSource(uint naggle_ms, MDSourceOptions options, UserTuple user) { _options = options; - _user_id = user_id; + _user = user; _relay = new Co2RelayControl(_consumer, naggle_ms); _relay.preload_securities((co2.MDRequest.Types.Flags)0xff).ignore(); _dispose.Add(_consumer.on_security.Subscribe(this)); - if(!options.HasFlag(MDSourceOptions.DeferInit)) + if (!options.HasFlag(MDSourceOptions.DeferInit)) initialize(); } - readonly BehaviorSubject> _on_securities = - new BehaviorSubject>( new ConcurrentDictionary() ); public IObservable> on_securities => _on_securities; - virtual public void initialize() - { + public virtual void initialize() => Task.Run(run); - } - public void set_token(AuthTokenImmutable token) - { + public void set_token(AuthTokenImmutable token) => _relay.set_token(token); - } public void OnCompleted() { } - public void OnError(Exception error) => Log.Md.error(error.ToString()); + + public void OnError(Exception error) => + Log.Md.error(error.ToString()); + public void OnNext(List values) { if (values.Count > 0) { foreach (var v in values) { - if (_user_id != _no_user_id && - v.security.ContractCase == Security.ContractOneofCase.Synthetic && - v.security.Synthetic.UserId != _user_id && - v.security.Synthetic.UserId != _no_user_id) { - continue; + if (v.security.ContractCase != Security.ContractOneofCase.Synthetic || _user.can_access_user_data(v.security.Synthetic.UserId)) { + var smd = new SecurityMD(new SecurityImmutable(v.security), v.handle); + _exchange_sec_map.AddOrUpdate(smd.security.Id, smd, (_, __) => smd); } - var smd = new SecurityMD(new SecurityImmutable(v.security), v.handle); - _exchange_sec_map.AddOrUpdate(smd.security.Id, smd, (_, __) => smd); } _version = DateTime.UtcNow; } } - public void Dispose() => Disposable.dispose(_dispose); - async protected Task run() - { + public void Dispose() => + Disposable.dispose(_dispose); + + protected async Task run() { DateTime run_version = DateTime.MinValue; - while (true) - { + while (true) { var exch = _exchange_sec_map; var current_version = _version; - if (current_version > run_version) - { + if (current_version > run_version) { run_version = current_version; - try - { + try { Log.Md.info($"MDSource publishing {exch.Count} securities"); _on_securities.OnNext(exch); - } - catch (Exception e) - { + } catch (Exception e) { Log.Md.error($"Error in publish_securities: {e}"); } } await Task.Delay(TimeSpan.FromSeconds(1)); } } - } -} +} \ No newline at end of file diff --git a/src/client/spark_api/md/SecurityMD.cs b/src/client/spark_api/md/SecurityMD.cs index d4ce00c1b..6af6e0324 100644 --- a/src/client/spark_api/md/SecurityMD.cs +++ b/src/client/spark_api/md/SecurityMD.cs @@ -1,13 +1,11 @@ using bts.api; using mbts.co2; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace mbts { - struct SecurityMD : IEquatable { + readonly struct SecurityMD : IEquatable { + public static readonly Func key_fn = smd => smd.security.Id; + public SecurityImmutable security { get; } public MDConsumerHandle md { get; } @@ -36,4 +34,4 @@ namespace mbts { return !(left == right); } } -} +} \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs index d0f9c95cb..4ff0a9aa7 100644 --- a/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/DictionaryExtensions.cs @@ -278,6 +278,9 @@ namespace System.Collections.Generic { public static IComparer> key_comparer() => Impl.key_comparer; + public static IReadOnlyDictionary wrap_value(TKey key, TValue value) => + new Impl.ValueWrapper(key, value); + static class Impl { public static readonly IReadOnlyDictionary empty = new ReadOnlyDictionary(new Dictionary(0)); @@ -297,6 +300,57 @@ namespace System.Collections.Generic { public int Compare(object x, object y) => x is KeyValuePair xkv ? (y is KeyValuePair ykv ? Compare(xkv, ykv) : 1) : -1; } + + public class ValueWrapper : IReadOnlyDictionary { + readonly TKey _key; + readonly TValue _value; + readonly IEqualityComparer _key_comparer; + + public ValueWrapper(TKey key, TValue value) + : this(key, value, EqualityComparer.Default) { } + + public ValueWrapper(TKey key, TValue value, IEqualityComparer key_comparer) { + _key = key; + _value = value; + _key_comparer = key_comparer; + } + + public TValue this[TKey key] => + _key_comparer.Equals(key, _key) ? _value : throw new KeyNotFoundException(); + + public int Count => 1; + + public IEnumerable Keys { + get { + yield return _key; + } + } + + public IEnumerable Values { + get { + yield return _value; + } + } + + public bool ContainsKey(TKey key) => _key_comparer.Equals(key, _key); + + public IEnumerator> GetEnumerator() { + yield return new KeyValuePair(_key, _value); + } + + IEnumerator IEnumerable.GetEnumerator() { + yield return new KeyValuePair(_key, _value); + } + + public bool TryGetValue(TKey key, out TValue value) { + if (_key_comparer.Equals(key, _key)) { + value = _value; + return true; + } + value = default; + return false; + } + } } } } \ No newline at end of file diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index c6fcd85e2..c1384e079 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -343,6 +343,18 @@ namespace System.Collections.Generic { return false; } + public static List ToListSorted(this IEnumerable enumerable, Func key_selector) => + enumerable.ToListSorted(key_selector, Comparer.Default); + + public static List ToListSorted(this IEnumerable enumerable, Func key_selector, IComparer key_comparer) => + enumerable.ToListSorted(key_comparer.wrap(key_selector)); + + public static List ToListSorted(this IEnumerable enumerable, IComparer comparer) { + var list = new List(enumerable); + list.Sort(comparer); + return list; + } + /// /// Simply returns enumerable.ToList(), under the guise ofo IReadOnlyList<> /// diff --git a/src/client/spark_core/Collections/Extensions/ImmutableSetExtensions.cs b/src/client/spark_core/Collections/Extensions/ImmutableSetExtensions.cs new file mode 100644 index 000000000..d22b9f6df --- /dev/null +++ b/src/client/spark_core/Collections/Extensions/ImmutableSetExtensions.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace bts.collections { + public static class ImmutableSetExtensions { + public static IImmutableSet RemoveRange(this IImmutableSet source, IEnumerable values) { + /// Prefer the implementation. + /// It uses an to remove values, which is optimized for bulk changes (less memory allocations, etc.). + if (source is ImmutableHashSet ihs) { + return ihs.RemoveRange(values); + } + if (source == null) throw new ArgumentNullException(nameof(source)); + if (values == null) throw new ArgumentNullException(nameof(values)); + foreach (var v in values) + source = source.Remove(v); + return source; + } + + public static ImmutableHashSet RemoveRange(this ImmutableHashSet source, IEnumerable values) { + if (source == null) throw new ArgumentNullException(nameof(source)); + if (values == null) throw new ArgumentNullException(nameof(values)); + var bd = source.ToBuilder(); + foreach (var v in values) + bd.Remove(v); + return bd.ToImmutable(); + } + } +} \ No newline at end of file diff --git a/src/client/spark_core/admin/AdminModelWrapper.cs b/src/client/spark_core/admin/AdminModelWrapper.cs deleted file mode 100644 index d709c7675..000000000 --- a/src/client/spark_core/admin/AdminModelWrapper.cs +++ /dev/null @@ -1,64 +0,0 @@ -using bts; -using bts.api.admin; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace bts.api.core -{ - public class AdminModelWrapper - { - readonly AdminDataImmutable? _admin_data; - public AdminDataImmutable? admin_data => _admin_data; - readonly string _user_name; - readonly List _allowed_accounts; - readonly Dictionary _allowed_account_dict = new Dictionary(); - public AdminModelWrapper(AdminDataImmutable? admin_data = null, string user_name = null) - { - _admin_data = admin_data; - _user_name = user_name ?? string.Empty; - _allowed_accounts = search_admin(u => u.Name == _user_name).Where(x => - { - return (x.Item2 != null && x.Item2.HasPermissions) || (x.Item3 != null && x.Item3.HasPermissions); - }).Select(xx => xx.Item1).ToList(); - foreach (var val in _allowed_accounts) - _allowed_account_dict[val.Name] = val.Name; - } - public IEnumerable viewable_accounts() - { - return _allowed_accounts; - } - public bool can_view_account(string account) - { - return _allowed_account_dict.ContainsKey(account) || _user_name.ToLower().Equals("bts"); - } - - IEnumerable> - search_admin(Func predicate) - { - var rv = new List>(); - if (_admin_data.HasValue) - { - var users = _admin_data.Value.Users.Where(predicate); - if (users != null && users.Count() == 1) - { - var user = users.ElementAt(0); - if (user.HasUserData && user.UserData.HasAccountPermissions) - { - foreach (var kv in user.UserData.AccountPermissions.AccountPermissions) - { - var account_id = kv.Key; - var accounts = _admin_data.Value.Accounts.Where(a => a.Id == account_id); - if (accounts != null && accounts.Count() == 1) - { - var account = accounts.ElementAt(0); - rv.Add(Tuple.Create(account, kv.Value.TradingPermission, kv.Value.AdminPermission)); - } - } - } - } - } - return rv; - } - } -} \ No newline at end of file diff --git a/src/client/spark_core/admin/PermissionFilters.cs b/src/client/spark_core/admin/PermissionFilters.cs deleted file mode 100644 index 3da6a137c..000000000 --- a/src/client/spark_core/admin/PermissionFilters.cs +++ /dev/null @@ -1,64 +0,0 @@ -using bts; -using bts.api; -using bts.api.core; -using bts.api.orderman; -using bts.api.position; -using bts.spark; -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Collections.Specialized; -using System.Linq; -using System.Reactive.Concurrency; -using System.Reactive.Linq; - -namespace bts.api.core -{ - public static class PermissionFilters - { - public static IObservable> - PermissionFilter(this IObservable> source, IObservable am) - { - var pred = Observable.Create>( observer => - { - return am.Subscribe(x => - { - Func filter = (z => x.can_view_account(z.Account)); - observer.OnNext(filter); - }); - }); - - return source.Filter(pred); - } - - public static IObservable> - PermissionFilter(this IObservable> source, IObservable am) - { - var pred = Observable.Create>(observer => - { - return am.Subscribe(x => - { - Func filter = (z => x.can_view_account(z.Def.Account ?? string.Empty)); - observer.OnNext(filter); - }); - }); - - return source.Filter(pred); - } - - public static IObservable> - PermissionFilter(this IObservable> source, IObservable am) - { - var pred = Observable.Create>(observer => - { - return am.Subscribe(x => - { - Func filter = (z => x.can_view_account(z.Account)); - observer.OnNext(filter); - }); - }); - - return source.Filter(pred); - } - } -} \ No newline at end of file