diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index be29b579c..c4500a003 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -4,6 +4,19 @@ weight = 3 sort_by = "weight" insert_anchor_links = "right" +++ +## 2.11.0 +### User Visible Changes + - Fixed fills form time filter to also apply to SOD fills + - Addressed an issue that could prevent the web Admin UI from displaying over slow HTTP connections + - Removed the option to enter manual spread fills + - Fixed an issue that could cause erroneous fill account attribution in the event of a crash +### 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 + - Improved system tests + - Improved log messages in UI to include dispatcher thread name + - Added support for Windows core dumps in the UI + ## 2.10.0 ### User Visible Changes - Fills now include information about the algo that originated the fill diff --git a/docker/linux b/docker/linux index e13bb5d8d..c40e6eba4 160000 --- a/docker/linux +++ b/docker/linux @@ -1 +1 @@ -Subproject commit e13bb5d8df14171a9a5abfdb8b6b4ecbc519032a +Subproject commit c40e6eba4ba72480a68cf784b6ffbcacc3fbf4af diff --git a/externals b/externals index b5ca26428..6d8f64ca5 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit b5ca264286e2a7033b7ce6ad0000254dea03dc8a +Subproject commit 6d8f64ca5cee3acbf9addb51428f25d54b9f906a 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..5ffeb3ec9 100644 --- a/src/client/spark/Daemons/ErrorReporter.cs +++ b/src/client/spark/Daemons/ErrorReporter.cs @@ -10,10 +10,10 @@ using System.Reactive.Linq; using System.Windows.Threading; using System.Windows; using System.Threading.Tasks; -using mbts.ui.shell; +using System.Windows; +using Google.Protobuf; -namespace bts.spark -{ +namespace bts.spark { [Export, Export(typeof(IShellDaemon))] public class ErrorReporter : IShellDaemon, IDisposable { readonly ErrorReportService _svc; @@ -21,9 +21,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")); } @@ -48,6 +48,45 @@ namespace bts.spark ErrorMessage = message, }); } + public async Task report_silently(string contact, string description, string userdata) { + var request = append_logs(new ErrorReport { + User = _username, + ErrorMessage = description, + UserDescription = userdata, + Contact = contact + }.immutable()); + var reply = await _svc.send_report_async(request); + } + + public static ErrorReportImmutable append_logs(ErrorReportImmutable src) { + var result = src.CloneToMutable(); + + var windows_log = LogUtil.read_windows_event_log(); + if (!windows_log.IsEmpty) { + result.Files.Add(new FileData { + Name = "Application.evtx.gz", + Contents = windows_log + }); + } + + var (data,date) = LogUtil.read_latest_crash_dump(); + if (!data.IsEmpty) { + result.Files.Add(new FileData { + Name = $"spark-{date.ToString("s")}.dmp.gz", + Contents = data + }); + } + + var spark_log = LogUtil.read_logs_compressed(); + if (!spark_log.IsEmpty) { + result.Files.Add(new FileData { + Name = "log.gz", + Contents = spark_log + }); + } + return result.immutable(); + } + } static class ErrorReporterExtensions { 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/OopsDaemon.cs b/src/client/spark/Daemons/OopsDaemon.cs new file mode 100644 index 000000000..190f98fa2 --- /dev/null +++ b/src/client/spark/Daemons/OopsDaemon.cs @@ -0,0 +1,55 @@ +using System; +using System.ComponentModel.Composition; +using mbts.ui; +using mbts; +using Newtonsoft.Json; +using System.Threading.Tasks; + +namespace bts.spark { + [Export(typeof(IShellDaemon))] + class OopsDaemon : IShellDaemon, IDisposable { + [ImportingConstructor] + public OopsDaemon(ErrorReporter e) { + var pid = get_pid(); + if (pid.HasValue) { + handle_unclean_shutdown(e, pid.Value); + } + save_pid(); + } + + public void Dispose() { + clear_pid(); + } + + void handle_unclean_shutdown(ErrorReporter e, int oldpid) { + string extra = ""; + try { + var conf = mbts.config.Configuration.get(); + extra = JsonConvert.SerializeObject(conf, Formatting.Indented); + } + catch { } + Task.Run(() => e.report_silently( + $"Host: {Environment.MachineName}", + $"pid: {oldpid}\n{extra}", + "Automated crash report") + ); + } + + const string _subkey = @"Software\BTS"; + private void save_pid() { + using (var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_subkey)) { + key.SetValue("pid", System.Diagnostics.Process.GetCurrentProcess().Id, Microsoft.Win32.RegistryValueKind.DWord); + } + } + private void clear_pid() { + using (var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_subkey)) { + key.DeleteValue("pid",false); + } + } + private int? get_pid() { + using (var key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_subkey)) { + return key.GetValue("pid") as int?; + } + } + } +} 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 60ef0ee70..75a876716 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); @@ -147,6 +147,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/ManualFills/ManualFillsVM.cs b/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs index 57579502c..8dcdb489e 100644 --- a/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs +++ b/src/client/spark/Modules/Trading/ManualFills/ManualFillsVM.cs @@ -70,7 +70,7 @@ namespace bts.shell.manual_fills { mfd => new ManualFillRow(mfd), mfr => mfr.data), _bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m => { - security_map = m; + security_map = new FilteredDictionary(m, smd => smd.security.ContractCase == Security.ContractOneofCase.Future); RaisePropertyChanged(nameof(security_map)); }), ObservableAutoWrapper.connect_item_hooks(_persisted_rows, r => Disposable.Create(dirty_mon.join(r), selection_mon.join(r))), 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/Controls/DataGridEx/Filters/Views/TimeFilter.cs b/src/client/spark/view/Controls/DataGridEx/Filters/Views/TimeFilter.cs index 20155813d..145228b80 100644 --- a/src/client/spark/view/Controls/DataGridEx/Filters/Views/TimeFilter.cs +++ b/src/client/spark/view/Controls/DataGridEx/Filters/Views/TimeFilter.cs @@ -24,6 +24,7 @@ namespace mbts.ui { public TimeTextTuple end => _end; public bool is_active => _mode == TimeFilterMode.Today || + _mode == TimeFilterMode.CMEOpen || (_mode == TimeFilterMode.Period && (_begin.result.HasValue || _end.result.HasValue)); diff --git a/src/client/spark/view/Controls/Dialogs/SupportRequestWindow.xaml.cs b/src/client/spark/view/Controls/Dialogs/SupportRequestWindow.xaml.cs index 89e202b05..a5a139800 100644 --- a/src/client/spark/view/Controls/Dialogs/SupportRequestWindow.xaml.cs +++ b/src/client/spark/view/Controls/Dialogs/SupportRequestWindow.xaml.cs @@ -1,10 +1,4 @@ -using bts.support; -using Google.Protobuf; -using mbts; -using mbts.ui; -using mbts.ui.shell; -using mbts.ui.utility; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -18,6 +12,13 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; +using bts.support; +using Google.Protobuf; +using mbts; +using mbts.ui; +using mbts.ui.controls; +using mbts.ui.shell; +using mbts.ui.utility; namespace bts.view.controls { partial class SupportRequestWindow : Window { @@ -50,28 +51,40 @@ namespace bts.view.controls { _base = report_base; send_command = new DelegateCommand(send_report, _ => !string.IsNullOrWhiteSpace(_text.Value)); _text = backing(nameof(user_text), ""); - _text.Changed += (_,__) => send_command.TryRaiseCanExecuteChanged(); + _text.Changed += (_, __) => send_command.TryRaiseCanExecuteChanged(); _contact = backing(nameof(user_contact), ""); - _contact.Changed += (_,__) => send_command.TryRaiseCanExecuteChanged(); + _contact.Changed += (_, __) => send_command.TryRaiseCanExecuteChanged(); } async void send_report(object _) { - ByteString screenshot = null; - if (include_screenshot) { - var stream = ScreenCapture.capture_encoded("jpeg"); - screenshot = await ByteString.FromStreamAsync(stream); - } - var reply = await _service.send_report_async(_base.with( - user_description: _text.Value, - contact: user_contact, - log: include_logs ? LogUtil.read_logs() : "", - image: screenshot - )); - if (reply.success) { - BTSMessageBox.Show("Your message has been received.", "Thank You", BTSMessageBoxButtons.OK, MessageBoxImage.Information, is_modal: false, top_most:true); - } - else { - BTSMessageBox.Show($"There was an error submitting your message. '{reply.error_message}'", "Error", BTSMessageBoxButtons.OK, MessageBoxImage.Error, is_modal: false, top_most: true); + using (var d = new BusyDialog { Text = "Sending your error report...", Topmost = true }) { + d.Show(); + ByteString screenshot = null; + if (include_screenshot) { + var stream = ScreenCapture.capture_encoded("jpeg"); + screenshot = await ByteString.FromStreamAsync(stream); + } + var request = await Task.Run(() => { + var result = _base.with( + user_description: _text.Value, + contact: user_contact, + image: screenshot); + if (include_logs) { + result = spark.ErrorReporter.append_logs(result); + } + return result; + }); + + var reply = await _service.send_report_async(request); + if (reply.success) { + Log.Ui.info("Support request message has been received."); + BTSMessageBox.Show("Your message has been received.", "Thank You", BTSMessageBoxButtons.OK, MessageBoxImage.Information, is_modal: false, top_most: true); + } + else { + var errmsg = $"There was an error submitting your message. '{reply.error_message}'"; + Log.Ui.error(errmsg); + BTSMessageBox.Show(errmsg, "Error", BTSMessageBoxButtons.OK, MessageBoxImage.Error, is_modal: false, top_most: true); + } } } diff --git a/src/client/spark/view/Controls/TickUpDown/TickUpDown.xaml b/src/client/spark/view/Controls/TickUpDown/TickUpDown.xaml index 5a392c532..1915202c2 100644 --- a/src/client/spark/view/Controls/TickUpDown/TickUpDown.xaml +++ b/src/client/spark/view/Controls/TickUpDown/TickUpDown.xaml @@ -457,15 +457,15 @@ Name="PART_TextBox" u:TextBoxBehavior.EnableArrowKeyTraverse="True" BorderThickness="0"> - + - + + diff --git a/src/client/spark/view/Controls/Time/DateTimePicker.xaml b/src/client/spark/view/Controls/Time/DateTimePicker.xaml index 9a8deb2cc..f0fc67218 100644 --- a/src/client/spark/view/Controls/Time/DateTimePicker.xaml +++ b/src/client/spark/view/Controls/Time/DateTimePicker.xaml @@ -93,7 +93,6 @@ u:TextBoxBehavior.EnableArrowKeyTraverse="True" u:Behavior.DisablePaste="True" Height="20" - BorderThickness="0" > 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/ShellModel.cs b/src/client/spark/view/Shell/ShellModel.cs index 776ee66cd..7832bf1c5 100644 --- a/src/client/spark/view/Shell/ShellModel.cs +++ b/src/client/spark/view/Shell/ShellModel.cs @@ -114,10 +114,16 @@ namespace mbts.ui } public void Dispose() { - foreach (IShellModule module in _modules.OrderBy(m => m.priority).Reverse()) { + foreach (var module in _modules.OrderBy(m => m.priority).Reverse()) { module.Dispose(); } _modules.Clear(); + foreach (var daemon in _services) { + if (daemon is IDisposable d) { + d.Dispose(); + } + } + _services.Clear(); } } } \ No newline at end of file diff --git a/src/client/spark/view/Shell/ViewModels/LauncherVM.cs b/src/client/spark/view/Shell/ViewModels/LauncherVM.cs index 63b760725..de9a13c52 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; @@ -123,7 +122,7 @@ namespace mbts.ui.shell { _shown = true; if (_window != null) { Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose; - if (shown != null) shown(); + shown?.Invoke(); _window.Show(); } } @@ -140,4 +139,4 @@ namespace mbts.ui.shell { #endregion } -} +} \ No newline at end of file diff --git a/src/client/spark/view/Shell/ViewModels/ShellThreadFactory.cs b/src/client/spark/view/Shell/ViewModels/ShellThreadFactory.cs index b28b21b41..0419641eb 100644 --- a/src/client/spark/view/Shell/ViewModels/ShellThreadFactory.cs +++ b/src/client/spark/view/Shell/ViewModels/ShellThreadFactory.cs @@ -42,8 +42,8 @@ namespace mbts.ui.shell try { Dispatcher.Run(); } - catch (Exception e) { - Log.assert(false, e.ToString()); + catch (Exception ex) { + Log.assert(false, $"Exception on dispatcher thread '{name}': {ex}."); } finally { Log.Ui.info("Disposing slow {0} and cleaning up background thread.".fmt(name)); diff --git a/src/client/spark_api/api/Update.cs b/src/client/spark_api/api/Update.cs index 004e81dec..92bf6a471 100644 --- a/src/client/spark_api/api/Update.cs +++ b/src/client/spark_api/api/Update.cs @@ -100,7 +100,7 @@ namespace bts.api.core { // Add foreach (var v in next.added) { var k = _key(v); - if (removed.TryPop(k, out var oldval)) { + if (removed.Remove(k, out var oldval)) { changes.AddOrMerge(new Change(oldval, v)); } else { added[k] = v; @@ -110,7 +110,7 @@ namespace bts.api.core { // Change foreach (var c in next.changes) { var k = _key(c.Old); - if (!added.TryReplace(k, c.New)) + if (!added.Replace(k, c.New)) changes.AddOrMerge(c); } @@ -162,10 +162,10 @@ namespace bts.api.core { public bool Remove(TKey key) => _cache.Remove(key); - public bool TryPop(TKey key, out TValue value) => + public bool Remove(TKey key, out TValue value) => _cache.TryGetValue(key, out value) && _cache.Remove(key); - public bool TryReplace(TKey key, TValue value) { + public bool Replace(TKey key, TValue value) { if (_cache.ContainsKey(key)) { _cache[key] = value; return true; @@ -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/TestRunner/InProcessTestRunner.cs b/src/client/spark_core/TestRunner/InProcessTestRunner.cs index 871f06b58..4b786d1f5 100644 --- a/src/client/spark_core/TestRunner/InProcessTestRunner.cs +++ b/src/client/spark_core/TestRunner/InProcessTestRunner.cs @@ -10,9 +10,9 @@ using System.Diagnostics; namespace bts.test { public static class InProcessTestRunner { - public static void run_test_synchronously(string v, TestEnumerator enumerator, Action report) { - foreach (var t in enumerator.find(v)) { - run_test_synchronously(t, report); + public static void run_test_synchronously(string v, TestType type, TestEnumerator enumerator, Action report) { + foreach (var t in enumerator.find(v,type)) { + run_test_synchronously(t, report); } } public static void run_test_synchronously(TestMethod test, Action report) { diff --git a/src/client/spark_core/TestRunner/TestEnumerator.cs b/src/client/spark_core/TestRunner/TestEnumerator.cs index e18c9b838..0fbaf3087 100644 --- a/src/client/spark_core/TestRunner/TestEnumerator.cs +++ b/src/client/spark_core/TestRunner/TestEnumerator.cs @@ -36,18 +36,19 @@ namespace bts.test { } - public IEnumerable find(string name) { + public IEnumerable find(string name, TestType type) { foreach (var g in TestGroups) { foreach (var t in g.methods) { - if (g.name == name || t.name == name || t.full_name == name) { + if (g.test_type == type && + (g.name == name || t.name == name || t.full_name == name)) { yield return t; } } } } - public IEnumerable match(IEnumerable names) { - return names.SelectMany(find).Distinct(); + public IEnumerable match(TestType type, IEnumerable names) { + return names.SelectMany(name => find(name,type)).Distinct(); } } 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 diff --git a/src/client/spark_core/logging/LogUtil.cs b/src/client/spark_core/logging/LogUtil.cs new file mode 100644 index 000000000..7c7d569b8 --- /dev/null +++ b/src/client/spark_core/logging/LogUtil.cs @@ -0,0 +1,96 @@ +using System; +using System.IO; +using mbts.config; +using System.IO.Compression; +using System.Runtime.InteropServices; +using Google.Protobuf; +using bts; +using System.Linq; +using bts.support; + +namespace mbts +{ + public static class LogUtil { + private static string log_path = Path.Combine(Configuration.get().data_path, "logging", "log"); + + + + public static ByteString read_logs_compressed() { + return FileUtils.read_and_gzip(log_path); + } + + public static (ByteString,DateTime) read_latest_crash_dump() { + // Find the latest crash dump + // If it is < 5 days old + // gzip it in place (delete original) + // upload the gziped dump + + var crash_dump_folder = "c:\\programdata\\bts\\crash_dumps"; + FileUtils.keep_n_matching_files(crash_dump_folder, "*.gz", 4); + try { + if (Directory.Exists(crash_dump_folder)) { + var latest = + Directory.GetFiles(crash_dump_folder, "*.dmp") + .Select(f => new { name = f, modified = File.GetLastWriteTimeUtc(f) }) + .OrderBy(f => f.modified) + .Reverse() + .FirstOrDefault(); + if (latest != null) { + if (DateTime.Now - latest.modified <= TimeSpan.FromDays(5)) { + var newname = FileUtils.gzip_file_in_place(latest.name); + if (!string.IsNullOrEmpty(newname)) { + return (ByteString.FromStream(File.OpenRead(newname)), latest.modified); + } + } + } + } + } + catch (Exception e) { + Log.Gen.error($"Failed to read crash dumps. Exception: {e.Message}"); + } + return (ByteString.Empty, DateTime.MinValue); + } + + public static ByteString read_windows_event_log() { + // try to export the events to temp + var temp = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".evtx"); + bool success = NativeMethods.EvtExportLog( + IntPtr.Zero, + "Application", + "*", + temp, + NativeMethods.EventExportLogFlags.ChannelPath); + if (success) { + var result = FileUtils.read_and_gzip(temp); + FileUtils.try_delete(temp); + return result; + } + else { + string msg = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message; + Log.Gen.error($"Error exporting windows event log. {msg}"); + } + return ByteString.Empty; + } + + + static class NativeMethods { + [Flags] + public enum EventExportLogFlags { + ChannelPath = 1, + LogfilePath = 2, + TolerateQueryErrors = 0x1000 + } + + [DllImport("wevtapi.dll", CallingConvention=CallingConvention.Winapi, CharSet = CharSet.Auto, SetLastError =true)] + public static extern bool EvtExportLog( + IntPtr session, + string path, + string query, + string targetPath, + [MarshalAs(UnmanagedType.I4)] + EventExportLogFlags flags); + + } + + } +} diff --git a/src/client/spark_core/logging/Logger.cs b/src/client/spark_core/logging/Logger.cs deleted file mode 100644 index a1dacd603..000000000 --- a/src/client/spark_core/logging/Logger.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.Net.Mail; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using mbts.config; -using System.Collections.Generic; - - -namespace mbts -{ - public static class LogUtil { - public static string read_logs() { - var log_path = Path.Combine(Configuration.get().data_path, "logging", "log"); - if (File.Exists(log_path)) { - try { - using (var f = File.Open(log_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - var reader = new StreamReader(f); - return reader.ReadToEnd(); - } - } - catch (Exception e) { - return e.ToString(); - } - } - return "Log file does not exist"; - } - - } -} diff --git a/src/client/spark_core/utils/FileUtils.cs b/src/client/spark_core/utils/FileUtils.cs new file mode 100644 index 000000000..6be341755 --- /dev/null +++ b/src/client/spark_core/utils/FileUtils.cs @@ -0,0 +1,76 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Linq; +using Google.Protobuf; + +namespace bts.support { + static class FileUtils { + public static bool try_delete(string path) { + try { + if (File.Exists(path)) { + File.Delete(path); + } + else if (Directory.Exists(path)) { + Directory.Delete(path, true); + } + } + catch { + return false; + } + return true; + } + + public static ByteString read_and_gzip(string path) { + if (File.Exists(path)) { + try { + using (var fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite /*Note: ReadWrite is more permissive than Read*/)) + using (var ms = new MemoryStream()) + using (var gz = new GZipStream(ms, CompressionMode.Compress, true)) { + fs.CopyTo(gz); + gz.Close(); + return ByteString.CopyFrom(ms.GetBuffer(), 0, (int)ms.Length); + } + } + catch (Exception e) { + Log.Gen.error($"Failed to read file '{path}' -- {e.Message}"); + return ByteString.Empty; + } + } + return ByteString.Empty; + } + + + // If input exists compress it and add a .gz extension + // original file is deleted + public static string gzip_file_in_place(string file) { + if (File.Exists(file)) { + string destination = file + ".gz"; + using (var input = File.OpenRead(file)) { + using (var output = File.OpenWrite(destination)) { + using (var writer = new GZipStream(output, CompressionMode.Compress)) { + input.CopyTo(writer); + } + } + } + try_delete(file); + return destination; + } + return null; + } + + // Delete the oldest files matching pattern (*.txt) keeping {count} files + public static void keep_n_matching_files(string directory, string pattern, int count) { + var to_delete = + Directory.GetFiles(directory, pattern) + .Select(f => new { name = f, modified = File.GetLastWriteTimeUtc(f) }) + .OrderBy(f => f.modified) + .Reverse() + .Skip(count); + + foreach (var f in to_delete) { + try_delete(f.name); + } + } + } +} diff --git a/src/client/spark_test/api/ApiUpdateTests.cs b/src/client/spark_test/api/ApiUpdateTests.cs index e41f9dbce..1b9e9dff7 100644 --- a/src/client/spark_test/api/ApiUpdateTests.cs +++ b/src/client/spark_test/api/ApiUpdateTests.cs @@ -347,6 +347,12 @@ namespace mbts.api.Test { var a3 = new Update(new[] { "a3" }, empty, new[] { new Change("a2", "a3") }, empty, key); var merged = a2.merge(a3); Assert.SequenceEqual(new[] { new Change("a1", "a3") }, merged.changes); + // clear the state, then add a2 back + // (this validates the fix for the Update.naggle bug where interim changes were converted into added/removed). + var cleared = new Update(empty, empty, Array.Empty>(), merged.all, key); + a2 = new Update(new[] { "a2" }, new[] { "a2" }, Array.Empty>(), empty, key); + merged = merged.merge(cleared).merge(a2); + Assert.SequenceEqual(new[] { new Change("a1", "a2") }, merged.changes); } T id(T t) => t; diff --git a/src/client/sparkcmd/Cmd/TestCommand.cs b/src/client/sparkcmd/Cmd/TestCommand.cs index 9b071eb7a..aff93988d 100644 --- a/src/client/sparkcmd/Cmd/TestCommand.cs +++ b/src/client/sparkcmd/Cmd/TestCommand.cs @@ -48,7 +48,7 @@ namespace sparkcmd { } else Configuration.initialize(); - Console.WriteLine(JsonConvert.SerializeObject(o)); + ConsoleEx.WriteLine(JsonConvert.SerializeObject(o), ConsoleColor.DarkGray); if (o.list) { list_tests((o.type)); @@ -58,13 +58,19 @@ namespace sparkcmd { if (o.timeout == 0 && o.tests.Count() == 1 && !o.self_contained) { //System.Threading.Thread.Sleep(5000); using (var trr = new TestResultReceiver(true)) { - InProcessTestRunner.run_test_synchronously(o.tests.First(), Enumerator, trr.get_reporter()); + InProcessTestRunner.run_test_synchronously(o.tests.First(), o.type, Enumerator, trr.get_reporter()); trr.print_summary(); + if (trr.ResultCount == 0) { + ConsoleEx.Write("No ", ConsoleColor.Red); + ConsoleEx.Write(o.type.ToString(), ConsoleColor.Yellow); + ConsoleEx.WriteLine($" tests matched filter '{o.tests.First()}'", ConsoleColor.Red); + return -1; + } return trr.ErrorCount; } } else if (o.tests.Count() > 0) { - return run_tests(o, Enumerator.match(o.tests)); + return run_tests(o, Enumerator.match(o.type, o.tests)); } else { return run_tests(o, Enumerator.get_of_type(o.type)); diff --git a/src/client/sparkcmd/Program.cs b/src/client/sparkcmd/Program.cs index 8999b8bcc..96b1d2dc8 100644 --- a/src/client/sparkcmd/Program.cs +++ b/src/client/sparkcmd/Program.cs @@ -29,8 +29,12 @@ namespace sparkcmd { // initialized from c++ instead of c# BTSNativeMethods.provide_command_line(args, args.Length); + var parser = new Parser(ps => { + ps.CaseInsensitiveEnumValues = true; + }); + // note: this can be made to infer the options type list from the list of delegates - return Parser.Default + return parser .ParseArguments< ConfigcheckOptions, ScriptClientOptions, diff --git a/src/client/sparkcmd/sparkcmd.csproj b/src/client/sparkcmd/sparkcmd.csproj index 52d9db007..b05a9d2d3 100644 --- a/src/client/sparkcmd/sparkcmd.csproj +++ b/src/client/sparkcmd/sparkcmd.csproj @@ -22,7 +22,7 @@ - + diff --git a/src/lib/api/service_compiler/templates/c#/immutable.pb.cs b/src/lib/api/service_compiler/templates/c#/immutable.pb.cs index 06c8260c6..2698f8750 100644 --- a/src/lib/api/service_compiler/templates/c#/immutable.pb.cs +++ b/src/lib/api/service_compiler/templates/c#/immutable.pb.cs @@ -10,6 +10,7 @@ namespace {{package}} { {{#each message_type}} partial class {{name}} : bts.api.IImmutableMessage { MessageDescriptor bts.api.IImmutableMessage.Descriptor => {{name}}.Descriptor; + public {{name}}Immutable immutable() => new {{name}}Immutable(this); } public readonly partial struct {{name}}Immutable : bts.api.IImmutableMessage { readonly {{name}} _impl; diff --git a/src/lib/api/service_helpers/AdminServiceUtils.cpp b/src/lib/api/service_helpers/AdminServiceUtils.cpp index ebffa69f8..261acaeae 100644 --- a/src/lib/api/service_helpers/AdminServiceUtils.cpp +++ b/src/lib/api/service_helpers/AdminServiceUtils.cpp @@ -1028,38 +1028,60 @@ std::string AdminServiceUtils::find_user_company_id (const bts::api::admin::Admi return rv; } -std::pair -AdminServiceUtils::find_user_account_matches (const bts::api::admin::AdminData& admin_data, - const std::string& connection, const std::string& exchange_account, +std::pair +AdminServiceUtils::find_user_account_matches (const AdminData& admin_data, + const std::string& connection, + const std::string& exchange_account, const std::string& exchange_user, api::Venue exchange){ - bts::api::admin::AdminServiceOperationResult find_account_result, find_user_result; - auto account_ptrs = accounts(admin_data, false); - auto user_ptrs = users(admin_data, false); - for(const bts::api::admin::BTSAccount* account_ptr : account_ptrs){ - if (account_has_connection(*account_ptr, connection)){ - if (boost::algorithm::iequals(exchange_account, find_account_exchange_account(admin_data,*account_ptr,exchange,find_account_result)) && - find_account_result.is_success()) - { - for(const bts::api::admin::BTSUser* user_ptr : user_ptrs) - { - if (boost::algorithm::iequals(exchange_user,find_user_exchange_id(admin_data,*user_ptr,exchange,find_user_result)) && - find_user_result.is_success()) - return std::pair(account_ptr,user_ptr); - - //This code eventually gets called by get_reverse_routing_record(...) - //At the ice, they send back the login level tag50 in exec reports which doesn't match any user level tag50s in the exchange_user - //so instead we look for the CompanyID (or client_id, tag 109) field here. If this field matches we have a good bet that - //the user we find is enough to fulfill the routing record enough to cancel or modify orphaned orders, etc - if (boost::algorithm::iequals(exchange_user,find_user_company_id(admin_data,*user_ptr,exchange,find_user_result)) && - find_user_result.is_success()) - return std::pair(account_ptr,user_ptr); - } - } - } + AdminServiceOperationResult find_account_result, find_user_result; + // i. uses the exchange and exchange_user to reverse lookup the user(s) + auto user_ptrs = users(admin_data, false); + std::vector matching_users; + for (BTSUser const* u : user_ptrs){ + auto exchange_u = find_user_exchange_id(admin_data, *u, + exchange, find_user_result); + if (find_user_result.is_success() && boost::algorithm::iequals ( + exchange_u, + exchange_user)) + matching_users.push_back(u); } - return std::pair(nullptr, nullptr); + // i.5 + //At the ice, they send back the login level tag50 in exec reports which doesn't match any user level tag50s in the exchange_user + //so instead we look for the CompanyID (or client_id, tag 109) field here. If this field matches we have a good bet that + //the user we find is enough to fulfill the routing record enough to cancel or modify orphaned orders, etc + for (BTSUser const* u : user_ptrs) + { + auto exchange_u = find_user_company_id(admin_data, *u, exchange, find_user_result); + if (find_user_result.is_success() && boost::algorithm::iequals ( exchange_u, exchange_user)) + matching_users.push_back(u); + } + // ii. uses the exchange, connection and exchange_account to reverse lookup the account(s) + auto account_ptrs = accounts(admin_data, false); + std::vector matching_accounts; + for (BTSAccount const* a :account_ptrs) + if (account_has_connection(*a, connection)){ + auto exchange_a = find_account_exchange_account(admin_data, *a, + exchange, + find_account_result); + if (find_account_result.is_success() && boost::algorithm::iequals ( + exchange_a, + exchange_account)) + matching_accounts.push_back(a); + } + // iii. finds the first account from ii that the user from i is authorized to trade + for (BTSUser const* u : matching_users){ + std::vector user_auth_accounts; + find_user_trading_accounts (admin_data, u->id(), user_auth_accounts); + for (BTSAccount const* i : user_auth_accounts) + for (BTSAccount const* j : matching_accounts) + if(i->id() == j->id()) + return std::pair(i,u); + } + return std::pair(nullptr, nullptr); } + + // for a given user finds the account permissions (if permissions are // derived from the group, it traverses the group hierarcy to find the // correct permissions. diff --git a/src/lib/api/service_helpers/AdminServiceUtils.h b/src/lib/api/service_helpers/AdminServiceUtils.h index 2b55f6874..dc6095e41 100644 --- a/src/lib/api/service_helpers/AdminServiceUtils.h +++ b/src/lib/api/service_helpers/AdminServiceUtils.h @@ -215,6 +215,9 @@ public: const BTSUser& user, api::Venue exchange, AdminServiceOperationResult& out_result); + // i. uses the exchange and exchange_user to reverse lookup the user(s) + // ii. uses the exchange, connection and exchange_account to reverse lookup the account(s) + // iii. finds the first account from ii that a user from i is authorized to trade static std::string find_user_company_id ( const AdminData& data, const BTSUser& user, diff --git a/src/lib/api/services/ErrorReportService.proto b/src/lib/api/services/ErrorReportService.proto index d85ec4e4c..d5d382d9d 100644 --- a/src/lib/api/services/ErrorReportService.proto +++ b/src/lib/api/services/ErrorReportService.proto @@ -4,6 +4,11 @@ option csharp_namespace="bts.support"; import "lib/api/apioptions.proto"; import "google/protobuf/timestamp.proto"; +message FileData { + string name = 1; + bytes contents = 2; +} + message ErrorReport { google.protobuf.Timestamp timestamp = 1; string user = 2; @@ -13,6 +18,7 @@ message ErrorReport { string log = 6; bytes image = 7; string contact = 8; + repeated FileData files = 9; } message ErrorResponse { } diff --git a/src/lib/api/services/OrderService.proto b/src/lib/api/services/OrderService.proto index 4a12cb0a6..bcccb7746 100644 --- a/src/lib/api/services/OrderService.proto +++ b/src/lib/api/services/OrderService.proto @@ -334,6 +334,7 @@ message RoutingRecord { string smp_id = 6 ; SelfMatchPreventionInstruction smp_instruction = 7; string location = 8; + string cust_order_handling_inst = 9; string sender_compid = 15; string clearing_firm = 20; diff --git a/src/lib/config/defaults/keycode.conf b/src/lib/config/defaults/keycode.conf index dd3365479..5b41d0705 100644 --- a/src/lib/config/defaults/keycode.conf +++ b/src/lib/config/defaults/keycode.conf @@ -1,9 +1,13 @@ + + #nusers: 1 #allow concurrent : true #expires: 2019-Dec-31 00:00:00 637133472000000000 -#generation_time: 2019-Sep-16 17:50:57.225054 5248728548999638444 +#generation_time: 2019-Sep-30 15:52:10.434845 5248740573731736354 EncryptedKeyCode { value { - keycode: "E7sUCxYuveyuvvBfwMdTrUCpFROJWQvsy4pYjwZ+zonjHwEmDkjxbxaqUEKqMzBbAq3YFnxIGOrQpRJte71SEoG5FGy4ZoRrVOjrMdNVLmieUWtZU43FKGJzImj/tJKEXu2xgwYJRZTj/AJ8C30PuVnzm0qUmR+UCgCOxKVeK0OFlo6zSqyDutcy5kLW3va+nTuFp43aknm6Iiu8LFW16wa6QDDCSQd4QgnHmiz5wyMC90yGBE4qObTKRGKDl5mWsjEL16aWK2ZO/0/ebFgGG8WygQfkeFzJS7B4q5Ta0nkSkVyLZjq1LN2/g9AXeCzCJUX5/F96kdfsnfSgAJepeg==" + keycode: "fVZlub92ulkXME+uZSyO9+WmyAXYKD735Qzxxfdj4G+SqEDTuwfNxOZVPS3TCFQqWPDmgjKTbbvfqIrGe3icxkVObUcUoS7lBXRXFrSvzOfs9eTz9RqHRvquDidnOzKxmSXsxV2bMb21UqBCJFeTzb4Q6Agp8EtjXJRc57UMVVygvdXg528S3ocBIq1V4W5NYraFn5WpqrTuBhpYbnsZAHi77s/EEwUT+6la3J2OHPtbiQnB6JFb0zsExMuzE4gwp79ojuQ5pnV2DXBZFNwxYvFyBUU/ac6oU89saZ/ay1DbOjz76TNqnNFewZvzdXZl3y6+X1eblX2streH2pn7gg==" } -} \ No newline at end of file +} + + diff --git a/src/lib/config/protos/orderman_cfg.proto b/src/lib/config/protos/orderman_cfg.proto index 5d899ea95..aee3e0802 100644 --- a/src/lib/config/protos/orderman_cfg.proto +++ b/src/lib/config/protos/orderman_cfg.proto @@ -9,4 +9,5 @@ message OrdermanCfg { } repeated Executor executor = 1; optional uint32 default_iceberg_pause_secs = 2 [default = 0]; + optional string fallback_cust_order_handling_inst = 3 [default = "Y"]; } diff --git a/src/lib/config/protos/toggles.proto b/src/lib/config/protos/toggles.proto index f1733290f..5c3c87ee0 100644 --- a/src/lib/config/protos/toggles.proto +++ b/src/lib/config/protos/toggles.proto @@ -58,3 +58,7 @@ message EnsureOnScreenWithWorkAreaRect { // Should verify that the code works with every monitor arrangement before enabling by default. optional bool enabled = 1 [default = false]; } + +message IgnoreNansInDayPnL { + optional bool enabled = 1 [default = true]; +} \ No newline at end of file diff --git a/src/lib/jetfix/codec/FieldDefinitions.h b/src/lib/jetfix/codec/FieldDefinitions.h index 8c3373052..5ba96346a 100644 --- a/src/lib/jetfix/codec/FieldDefinitions.h +++ b/src/lib/jetfix/codec/FieldDefinitions.h @@ -9,6 +9,7 @@ namespace jetfix { namespace fix { typedef BoolField<1028> ManualOrderIndicator; +typedef StringField<1031> CustOrderHandlingInst; typedef BoolField<123> GapFillFlag; typedef BoolField<43> PossDupFlag; typedef BoolField<9768> InFlightMitigation; diff --git a/src/lib/jetfix/codec/MessageDefinitions.h b/src/lib/jetfix/codec/MessageDefinitions.h index fe849c027..75f45f3e6 100644 --- a/src/lib/jetfix/codec/MessageDefinitions.h +++ b/src/lib/jetfix/codec/MessageDefinitions.h @@ -45,7 +45,8 @@ typedef FIXMsg + TransactTimeStr, + CustOrderHandlingInst > ExecutionReportMsg; typedef FIXMsg diff --git a/src/lib/orderman/actors/GLBXExecutionGateway.cpp b/src/lib/orderman/actors/GLBXExecutionGateway.cpp index 68210573f..8adc93eee 100644 --- a/src/lib/orderman/actors/GLBXExecutionGateway.cpp +++ b/src/lib/orderman/actors/GLBXExecutionGateway.cpp @@ -262,6 +262,10 @@ void GLBXExecutionGateway::on_exe_report( if (msg.has()) str_to(msg.get(), &data->exchange_fill_id); str_to(msg.get(), &data->transact_time); + + if (msg.has()) + data->cust_order_handling_inst = msg.get(); + data->cfg = &me->cfg; data->msg = text_msg; data->exchange = api::Venue::VENUE_GLBX; diff --git a/src/lib/orderman/orderman_utils/ExecutionReport.h b/src/lib/orderman/orderman_utils/ExecutionReport.h index 34e0f2225..5ffc627b3 100644 --- a/src/lib/orderman/orderman_utils/ExecutionReport.h +++ b/src/lib/orderman/orderman_utils/ExecutionReport.h @@ -34,6 +34,7 @@ public: ExchangeFillID exchange_fill_id; mercury::TimeStampStr transact_time; config::JetFIX::Connection const *cfg; + std::string cust_order_handling_inst; std::string msg; api::Venue exchange; int64_t ice_cl_ord_id; diff --git a/src/lib/orderman/orders/GLBXNativeOrder.cpp b/src/lib/orderman/orders/GLBXNativeOrder.cpp index c5d26a72f..0442b337e 100644 --- a/src/lib/orderman/orders/GLBXNativeOrder.cpp +++ b/src/lib/orderman/orders/GLBXNativeOrder.cpp @@ -15,6 +15,7 @@ #include "lib/orderman/securities/ISecurityDB.h" #include "lib/utils/PBUtils.h" #include "lib/utils/bts_chrono.h" +#include "lib/config/protos/orderman_cfg.pb.h" #include "lib/orderman/actors/order_manager/OrderServices.h" @@ -336,6 +337,7 @@ NativeOrder::on_init_from_exe_report(ExecutionReport const &er, rr.set_cti_code(CTICode(er.cfg->cti_code()[0])); rr.set_customer_or_firm(CustomerOrFirm(er.cfg->customer_or_firm())); rr.set_location(er.cfg->sender_locationid()); + rr.set_cust_order_handling_inst(er.cust_order_handling_inst); on_init_recovered(orecord, os); return orecord.def(); } @@ -1102,6 +1104,13 @@ void NativeOrder::report_state() { me->services->report_state(me->state); } +std::string NativeOrder::get_cust_order_handling_inst(api::orderman::RoutingRecord const&rr) { + if (rr.cust_order_handling_inst().size()) + return rr.cust_order_handling_inst(); + else + return config::get().fallback_cust_order_handling_inst(); +} + void NativeOrder::init_fix() { bts_assert(me->sec); @@ -1129,6 +1138,8 @@ void NativeOrder::init_fix() { create_encoding.add(rr.cti_code()); create_encoding.add(sec.glbx().security_desc()); create_encoding.add(clordid); + create_encoding.add (get_cust_order_handling_inst(rr)); + if (rr.smp_id().size()) { create_encoding.add(rr.smp_id()); if (rr.smp_instruction() != SELF_MATCH_PREVENTION_INSTRUCTION_UNDEFINED) @@ -1158,6 +1169,7 @@ void NativeOrder::init_fix() { update_encoding.add(clordid); update_encoding.add(clordid); update_encoding.add(true); + update_encoding.add (get_cust_order_handling_inst(rr)); // Self Match Protection if (rr.smp_id().size()) { update_encoding.add(rr.smp_id()); diff --git a/src/lib/orderman/orders/GLBXNativeOrder.h b/src/lib/orderman/orders/GLBXNativeOrder.h index 82d7c8ae3..f8f106748 100644 --- a/src/lib/orderman/orders/GLBXNativeOrder.h +++ b/src/lib/orderman/orders/GLBXNativeOrder.h @@ -71,6 +71,7 @@ class NativeOrder : public NativeOrderBase { void ignore_or_cancel(std::string const &, api::orderman::OrderError, OrderOpResult *out) ; + std::string get_cust_order_handling_inst(api::orderman::RoutingRecord const&) ; }; typedef NativeOrder GLBXNativeOrder; diff --git a/src/server/sparkd/exchange_sim/book/OrderMatcher.h b/src/server/sparkd/exchange_sim/book/OrderMatcher.h index 4e4301762..f5d58ac43 100644 --- a/src/server/sparkd/exchange_sim/book/OrderMatcher.h +++ b/src/server/sparkd/exchange_sim/book/OrderMatcher.h @@ -14,27 +14,56 @@ namespace bts { namespace ex_sim { +// An order matcher maintains a book of same security orders +// and generates matches as the sides cross class OrderMatcher { public: OrderMatcher(); ~OrderMatcher(); + // Add a new order, returning any updates to the new order or + // existing ones resulting from matching void add_new(Order const &, std::vector *out); + + // Add a new order or, if a threshold of existing orders at same + // level from the same owner is met, merge its quantity with the + // last similar order. The merge is usefull to keep memory growth + // in check. Return any changes resulting from matching on the new + // order. void add_or_merge(Order const &, std::vector *out); + // Change an existing order, returning any changed orders that + // resulted matches made possible by the update. void update(std::string const &clorid, Price, Quantity, std::vector *out); + + // Cancel an existing order, removing it from the book void cancel(std::string const &clorid); + // Try to reduce the quantity available at the specified level, + // side by the specified owner, by the specified amount. The + // updated orders are not returned. void try_reduce_quantity_at_level(api::Side, Price level, Quantity by_quantity, std::string const& order_owner); + + // Take the all the orders and consolidated their quantities, per + // level, in a book structure Book get_book() const; - OrderBook get_order_book(const char*) const; - + + // Copy all the orders *not* owned by owner to a PB type that can + // be stored on disk + OrderBook get_order_book(const char* owner) const; + + // Get a single order Order const *get_order(std::string const &clorid); - + + // Orders are kept in two multisets (one for bids, one for + // offers). Each multiset uses a comparison operator that uses + // first the price and then the time_changed of each order to sort + // the orders. FIFO matching is a matter of peeling off matching + // entries from bid and offer. using OrdersSide = std::multiset; struct Trade { diff --git a/src/server/sparkd/http/WebServer.cpp b/src/server/sparkd/http/WebServer.cpp index 11a6cea27..c5d8e8160 100644 --- a/src/server/sparkd/http/WebServer.cpp +++ b/src/server/sparkd/http/WebServer.cpp @@ -84,6 +84,7 @@ namespace http { // Turn off logging _server.clear_access_channels(websocketpp::log::alevel::all); _server.clear_error_channels(websocketpp::log::alevel::all); + _server.set_open_handshake_timeout(0); run(); } diff --git a/src/server/sparkd/position/PositionServicePNLHelper.cpp b/src/server/sparkd/position/PositionServicePNLHelper.cpp index 403c9b52b..a547f6643 100644 --- a/src/server/sparkd/position/PositionServicePNLHelper.cpp +++ b/src/server/sparkd/position/PositionServicePNLHelper.cpp @@ -4,6 +4,7 @@ #include "lib/os/os.h" #include "PositionServicePNLHelper.h" #include "lib/config/protos/cme_reference_data.pb.h" +#include "lib/config/protos/toggles.pb.h" #include "lib/config/config.h" #include "lib/utils/PBUtils.h" @@ -217,6 +218,15 @@ double PositionServicePNLHelper::_compute_day_pnl ( (md - u.pos().day_long_avg_price()), short_pnl = std::abs(u.pos().day_short_pos()) * u.cash_value() * (u.pos().day_short_avg_price() - md); + + if(config::get().enabled()) + { + if(bts::os::is_nan(long_pnl)) + long_pnl = 0.0; + if(bts::os::is_nan(short_pnl)) + short_pnl = 0.0; + } + pnl = long_pnl + short_pnl; break; } diff --git a/src/server/sparkd/support/ErrorReportService.cpp b/src/server/sparkd/support/ErrorReportService.cpp index 1a90be267..5b972267a 100644 --- a/src/server/sparkd/support/ErrorReportService.cpp +++ b/src/server/sparkd/support/ErrorReportService.cpp @@ -29,6 +29,17 @@ ErrorReportServer::ErrorReportServer(bts::api::ServiceContext& context) : ErrorReportServer::~ErrorReportServer() {} +void write_file(const std::string& destination, const std::string& data) { + if (data.size() > 0) { + std::ofstream file; + file.open(destination, std::ios::binary); + if (file.is_open()) { + file << data; + file.close(); + } + } +} + void ErrorReportServer::send_report( const ErrorReport& request, const api::Response& reply) { @@ -37,7 +48,7 @@ void ErrorReportServer::send_report( auto dt = datetime::local_now(); auto dir_name = request.user() + "-" + datetime::FIX_timestamp(dt); dir_name = os::sanitize_file_name(dir_name); - dir_name = get_report_dir() + dir_name; + dir_name = get_report_dir() + dir_name + "/"; // create directory with that name boost::filesystem::create_directories(dir_name); @@ -46,7 +57,7 @@ void ErrorReportServer::send_report( // user_text.txt std::ofstream file; - file.open(dir_name + "/user_text.txt"); + file.open(dir_name + "user_text.txt"); if (file.is_open()) { file << request.user() << " - " << request.contact() << std::endl; file << "================" << std::endl; @@ -56,20 +67,13 @@ void ErrorReportServer::send_report( file.close(); } // logs.txt - if (request.log().size() > 0) { - file.open(dir_name + "/logs.txt"); - if (file.is_open()) { - file << request.log(); - file.close(); - } - } + write_file(dir_name + "logs.txt", request.log()); // screenshot.jpeg - if (request.image().size() > 0) { - file.open(dir_name + "/screenshot.jpeg", std::ios::binary); - if (file.is_open()) { - file << request.image(); - file.close(); - } + write_file(dir_name + "screenshot.jpeg", request.image()); + for (const auto& fd : request.files()) { + // boost::filesystem::path p = fd.name(); + auto name = os::sanitize_file_name(fd.name()); + write_file(dir_name + name, fd.contents()); } // log error for visibility