diff --git a/.gitignore b/.gitignore index e0769acc0..d87a92c1b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,5 @@ src/server/sparkd/orderman/perf_analysis/trace_data/ *.fsx.lock src/lib/orderman/perf_analysis/logs/latency_data/ trace_data/ +/src/lib/orderman/perf_analysis/last_pretty_log.csv +/src/lib/orderman/perf_analysis/log.csv diff --git a/.vscode/launch.json b/.vscode/launch.json index 163cad3eb..d3f66bbaf 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -36,8 +36,8 @@ "name": "SDK Launch", "type": "clr", "request": "launch", - "program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe", - "args": ["md","GLBX","Future","ZN", "ZNU8"], + "program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe", + "args": ["md","GLBX","Future","CL", "CLZ9", "--user=bts", "--pass="], "cwd": "${workspaceRoot}", "stopAtEntry": false, "externalConsole": true, @@ -48,7 +48,7 @@ "type": "clr", "request": "launch", "program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE", - "args": ["${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64.xll"], + "args": ["${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll"], "cwd": "${workspaceRoot}", "stopAtEntry": false, "externalConsole": true, @@ -209,7 +209,7 @@ "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", - "args": ["test","Co2Tests"], + "args": ["test","AuthToken"], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", "environment": [], diff --git a/doc/dev/dev_process.md b/doc/dev/dev_process.md index 20e02e94d..2d7445a1f 100644 --- a/doc/dev/dev_process.md +++ b/doc/dev/dev_process.md @@ -53,6 +53,19 @@ implementation phase developers should reach out to Pedro for UI reviews, architecture and design concerns as well as specification trade off concerns. +* Verification. Once code is complete think carefully about the best way +to verify that it is good before it goes to production. We don't have a +dedicated QA cycle to flush out bugs so it's important that a change be +fully tested before it's marked "Ready to Merge." For any non-trivial +change consider enlisting a 'test buddy' to help review the code and +think of test cases that you may not have considered. Stability from +release to release is especially critical right now as we develop a +reputation in the futures world. + - Code Reviews + - Unit tests + - System tests + - Manual tests + * Merge. Once a project is considered complete by developers, a PR that includes Pedro should be created (unless, as mentioned above, an early PR was already created in the development phase). Whether the PR diff --git a/doc/user/docs/release_notes.md b/doc/user/docs/release_notes.md index c4a49f9b5..0c9701cf6 100644 --- a/doc/user/docs/release_notes.md +++ b/doc/user/docs/release_notes.md @@ -1,4 +1,17 @@ # Release Notes +## 1.4.3 + +### Ladder Usability Improvements + - Controls found in Left Pane of the ladder can now be hidden via the checkboxes found under Ladder Form -> Settings button -> Left Pane tab + - The Left Pane is now scrollable with the mouse wheel when there isn't enough vertical space to accomodate the entire form + - The Left Pane can now grown and shrunk horizontally via the splitter between the left pane and the main ladder area +### Performance Improvements + - Requoting and hedging latency has been reduced by up to 30% +### Software Development Kit (SDK) Improvements + - The API now enforces authentication +### Bug Fixes + - The Market View form now honors filters when new securities are added + ## 1.4.2 ### User Interface Improvements diff --git a/docker/linux b/docker/linux index 8ee969259..f6d8d5986 160000 --- a/docker/linux +++ b/docker/linux @@ -1 +1 @@ -Subproject commit 8ee9692597d9e59adf0a3ab77610b711892f79a6 +Subproject commit f6d8d59860bc40672a4ac9ab4e69a54541c4d236 diff --git a/externals b/externals index 5f21fd13e..69f863923 160000 --- a/externals +++ b/externals @@ -1 +1 @@ -Subproject commit 5f21fd13e7e802f46a263cefb6d21c2fba667e4b +Subproject commit 69f863923502b11c8d7fde491e4b5aec5b705e97 diff --git a/src/client/spark/Admin/AdminModel.cs b/src/client/spark/Admin/AdminModel.cs index da1ae42f4..af7cf9499 100644 --- a/src/client/spark/Admin/AdminModel.cs +++ b/src/client/spark/Admin/AdminModel.cs @@ -6,6 +6,7 @@ using System.ComponentModel.Composition; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; +using bts.api.core; namespace mbts.spark { [Export] diff --git a/src/client/spark/Daemons/MDDaemon.cs b/src/client/spark/Daemons/MDDaemon.cs index 76c89157f..816faac4a 100644 --- a/src/client/spark/Daemons/MDDaemon.cs +++ b/src/client/spark/Daemons/MDDaemon.cs @@ -17,31 +17,22 @@ using bts.api.user; namespace bts { [Export(typeof(IInitializable))] - class MDSource : IObserver>, IInitializable, IDisposable { + class MDDaemon : bts.md.MDSource, IObserver>, IInitializable, IDisposable { readonly Lazy _bus; - readonly Lazy _token; + readonly Lazy _token; readonly Lazy _ss; - readonly MDConsumer _consumer = new MDConsumer(); - readonly Co2RelayControl _relay; readonly Dictionary _deleted_synthetics = new Dictionary(); - long _version = 0; - readonly ConcurrentDictionary _exchange_sec_map = new ConcurrentDictionary(); - List _dispose = new List(); + + static uint get_naggle() => mbts.config.Configuration.get().naggle_ms; [ImportingConstructor] - public MDSource( - Lazy bus, - Lazy token, - Lazy ss) { + public MDDaemon(Lazy bus, Lazy token, Lazy ss) : base(get_naggle(), true) { _bus = bus; _token = token; - _ss = ss; - _relay = new Co2RelayControl(_consumer); - _relay.preload_securities((co2.MDRequest.Types.Flags)0xff).ignore(); - _dispose.Add(_consumer.on_security.Subscribe(this)); + _ss = ss; } - public void initialize() { + override public void initialize() { _relay.set_token(_token.Value); _dispose.Add( _ss.Value.subscribei_metadata() @@ -66,6 +57,9 @@ 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); + })); Task.Run(run); } @@ -74,37 +68,5 @@ namespace bts { public int priority => 55; IBus bus => _bus.Value; - - public void OnCompleted() { } - public void OnError(Exception error) => Log.Md.error(error.ToString()); - public void OnNext(List values) { - if (values.Count > 0) { - foreach (var v in values) { - var smd = new SecurityMD(v.security, v.handle); - _exchange_sec_map.AddOrUpdate(smd.security.Id, smd, (_, __) => smd); - } - _version += 1; - } - } - - public void Dispose() => Disposable.dispose(_dispose); - async Task run() { - long run_version = 0; - while (true) { - var exch = _exchange_sec_map; - long current_version = _version; - if (current_version > run_version) { - run_version = current_version; - try { - Log.Md.info($"MDSource publishing {exch.Count} securities"); - bus.post(SparkTags.SecuritiesTag, exch); - } 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/Daemons/ShellServices.cs b/src/client/spark/Daemons/ShellServices.cs index 831fb332a..68361701c 100644 --- a/src/client/spark/Daemons/ShellServices.cs +++ b/src/client/spark/Daemons/ShellServices.cs @@ -13,10 +13,7 @@ using System.ComponentModel.Composition; namespace Spark { public class ShellServices { [Export] - public static ServiceContext context { get; } = new ServiceContext(); - - [Export] - public UserService user_service => context.locate(); + public ServiceContext context { get; } = new ServiceContext(); [Export("settings")] public PersistenceService settings_service => context.locate("settings"); diff --git a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs index 8c604dca4..4dce5ec3a 100644 --- a/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs +++ b/src/client/spark/Modules/Market/MarketView/MarketViewRow.cs @@ -35,7 +35,7 @@ namespace mbts.spark { readonly CellProperty _working_bids_text, _working_asks_text; readonly MyOrderSummarizer _order_summarizer = new MyOrderSummarizer(); readonly MDDisplayHelper.SizeFormatter _size_formatter = MDDisplayHelper.get_formatter(MarketSizeDisplay.get_default()); - uint _bid_direct_size, _bid_merged_size, _ask_direct_size, _ask_merged_size; + Property _bid_direct_size, _bid_merged_size, _ask_direct_size, _ask_merged_size; string _bid_merged_size_text, _ask_merged_size_text; ulong _bbo_ref, _last_ref; @@ -45,28 +45,33 @@ namespace mbts.spark { _security_text = smd.security.ToString(); _security_key_text = security_key.ToString(); string format_price(double price) => security.ContractSpec.format(price); - _position = new CellProperty(0); + _position = new CellProperty(this, nameof(position), 0); _bid_price = backing(nameof(bid_price), double.NaN); _ask_price = backing(nameof(ask_price), double.NaN); _last_price = backing(nameof(last_price), double.NaN); - _last_size = new CellProperty(0); + _last_size = new CellProperty(this, nameof(last_size), 0); _day_change = backing(nameof(day_change), double.NaN); _session_low = backing(nameof(session_low), double.NaN); _session_high = backing(nameof(session_high), double.NaN); _settlement = backing(nameof(settlement), double.NaN); - _volume = new CellProperty(0); - _inside_bids = new CellProperty(); - _inside_asks = new CellProperty(); - _working_bid_volume = new CellProperty(); - _working_ask_volume = new CellProperty(); + _volume = new CellProperty(this, nameof(volume), 0); + _inside_bids = new CellProperty(this, nameof(inside_bids)); + _inside_asks = new CellProperty(this, nameof(inside_asks)); + _working_bid_volume = new CellProperty(this, nameof(working_bid_volume)); + _working_ask_volume = new CellProperty(this, nameof(working_ask_volume)); + // + _bid_direct_size = backing(nameof(bid_direct_size), default(uint)); + _bid_merged_size = backing(nameof(bid_merged_size), default(uint)); + _ask_direct_size = backing(nameof(ask_direct_size), default(uint)); + _ask_merged_size = backing(nameof(ask_merged_size), default(uint)); // _working_orders = new ObservableFilterCollection(_orders, o => o.is_active()); _working_bids = new ObservableFilterCollection(_working_orders, o => o.Def.Side == Side.Buy); _working_asks = new ObservableFilterCollection(_working_orders, o => o.Def.Side == Side.Sell); - _working_best_bid = new CellProperty(format_price, double.NaN); - _working_best_ask = new CellProperty(format_price, double.NaN); - _working_bids_text = new CellProperty(string.Empty); - _working_asks_text = new CellProperty(string.Empty); + _working_best_bid = new CellProperty(this, nameof(working_best_bid), format_price, double.NaN); + _working_best_ask = new CellProperty(this, nameof(working_best_ask), format_price, double.NaN); + _working_bids_text = new CellProperty(this, nameof(working_bids_text), string.Empty); + _working_asks_text = new CellProperty(this, nameof(working_asks_text), string.Empty); // default_command = new DelegateCommand(_show_ladder); bid_price_click = new DelegateCommand(() => _show_order_ticket(MarketViewView.Columns.Bid)); @@ -100,15 +105,15 @@ namespace mbts.spark { public double last_price => _last_price.Value; public uint last_size => _last_size.value; public double bid_price => _bid_price.Value; - public uint bid_direct_size => _bid_direct_size; - public uint bid_implied_size => _bid_merged_size - _bid_direct_size; - public uint bid_merged_size => _bid_merged_size; - public string bid_merged_size_text => _bid_merged_size_text ?? (_bid_merged_size_text = _size_formatter(_bid_merged_size, bid_implied_size)); + public uint bid_direct_size => _bid_direct_size.Value; + public uint bid_implied_size => _bid_merged_size.Value - _bid_direct_size.Value; + public uint bid_merged_size => _bid_merged_size.Value; + public string bid_merged_size_text => _bid_merged_size_text ?? (_bid_merged_size_text = _size_formatter(_bid_merged_size.Value, bid_implied_size)); public double ask_price => _ask_price.Value; - public uint ask_direct_size => _ask_direct_size; - public uint ask_implied_size => _ask_merged_size - _ask_direct_size; - public uint ask_merged_size => _ask_merged_size; - public string ask_merged_size_text => _ask_merged_size_text ?? (_ask_merged_size_text = _size_formatter(_ask_merged_size, ask_implied_size)); + public uint ask_direct_size => _ask_direct_size.Value; + public uint ask_implied_size => _ask_merged_size.Value - _ask_direct_size.Value; + public uint ask_merged_size => _ask_merged_size.Value; + public string ask_merged_size_text => _ask_merged_size_text ?? (_ask_merged_size_text = _size_formatter(_ask_merged_size.Value, ask_implied_size)); public ulong volume => _volume.value; public double settlement => _settlement.Value; public double day_change => _day_change.Value; @@ -144,9 +149,9 @@ namespace mbts.spark { bool dirty = false; if (md.md.get_bbo(ref _bbo_ref, out NativePriceSize b, out NativePriceSize a)) { _bid_price.set(b.price); - refresh_size(ref b, ref _bid_direct_size, ref _bid_merged_size, ref _bid_merged_size_text, nameof(bid_merged_size_text)); + refresh_size(ref b, _bid_direct_size, _bid_merged_size, ref _bid_merged_size_text, nameof(bid_merged_size_text)); _ask_price.set(a.price); - refresh_size(ref a, ref _ask_direct_size, ref _ask_merged_size, ref _ask_merged_size_text, nameof(ask_merged_size_text)); + refresh_size(ref a, _ask_direct_size, _ask_merged_size, ref _ask_merged_size_text, nameof(ask_merged_size_text)); _inside_bids.on_next_distinct(_bid_price.Value >= _working_best_bid.value, ref dirty); _inside_asks.on_next_distinct(_ask_price.Value <= _working_best_ask.value, ref dirty); } @@ -162,10 +167,10 @@ namespace mbts.spark { if (dirty) invalidated?.Invoke(); - void refresh_size(ref NativePriceSize nps, ref uint direct, ref uint merged, ref string text, string text_prop) { - if (nps.size != merged || nps.direct_size != direct) { - merged = nps.size; - direct = nps.direct_size; + void refresh_size(ref NativePriceSize nps, Property direct, Property merged, ref string text, string text_prop) { + if (nps.size != merged.Value || nps.direct_size != direct.Value) { + merged.set(nps.size); + direct.set(nps.direct_size); text = null; dirty = true; RaisePropertyChanged(text_prop); @@ -266,7 +271,15 @@ namespace mbts.spark { _working_best_ask.on_next_distinct(_order_summarizer.best_working_ask, ref dirty); _inside_bids.on_next_distinct(_order_summarizer.best_working_bid >= bid_price, ref dirty); _inside_asks.on_next_distinct(_order_summarizer.best_working_ask <= ask_price, ref dirty); - RaisePropertyChanged(nameof(working_bids_text), nameof(working_asks_text)); + + RaisePropertyChanged( + // Implied might not be ever set, so it probably does not RaisePropertyChanged either + // This might be part of the filter funk? + //nameof(bid_implied_size), + //nameof(ask_implied_size), + nameof(working_bids_text), + nameof(working_asks_text) + ); } #endregion diff --git a/src/client/spark/Modules/Trading/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/LadderWindowFactory.cs index ff6a809de..d9abb26b8 100644 --- a/src/client/spark/Modules/Trading/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/LadderWindowFactory.cs @@ -61,10 +61,12 @@ namespace bts.shell { var view = new Lazy(() => { var model = new LadderModel(md, _orders_model, _md_auxiliary_model); var settings_manager = new WindowSettingsManager( - _settings_hub, state_settings, + _settings_hub, state_settings == null || state_settings.use_defaults ? null : state_settings, us => sanitize_ladder_settings(us.ladder), (us, v) => us.with(sanitize_ladder_settings(v))); - var vm = new LadderVM(_bus, model, settings_manager); + var init = state_settings ?? settings_manager.default_settings; + init.use_defaults |= state_settings == null; + var vm = new LadderVM(_bus, model, settings_manager, init); return new LadderView(vm); }); string thread = Configuration.get().enabled ? $"Ladder{id:00}" : ""; diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index fbbba6c40..200b835ff 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -46,8 +46,8 @@ namespace mbts.spark { this.algo_model = algo_model; var scheduler = ThreadPoolScheduler.Instance; var interval = TimeSpan.FromMilliseconds(100); - on_orders = _service.subscribei_orders().Naggle(interval, scheduler).PermissionFilter(admin_model).Table().Cache(); - on_positions = _position_service.subscribei_position_data().Naggle(interval, scheduler).PermissionFilter(admin_model).Table().Cache(); + on_orders = _service.subscribei_orders().Naggle(interval, scheduler).PermissionFilter(admin_model.on_admin_data).Table().Cache(); + on_positions = _position_service.subscribei_position_data().Naggle(interval, scheduler).PermissionFilter(admin_model.on_admin_data).Table().Cache(); working_orders = on_orders.Scan( ImmutableDictionary.Empty, @@ -57,7 +57,7 @@ namespace mbts.spark { on_order_tuples = order_record_tuple_source.subscribe_incremental_update(); on_order_tuples_table = order_record_tuple_source.subscribe_incremental_table_update(); on_order_securities = order_record_tuple_source.subscribe_order_securities(); - on_fills = _service.subscribei_fills().Naggle(interval, scheduler).PermissionFilter(admin_model).Table().Cache(); + on_fills = _service.subscribei_fills().Naggle(interval, scheduler).PermissionFilter(admin_model.on_admin_data).Table().Cache(); _activity = new OrderActivitySummarizer(bus, on_orders); on_fill_tuples = FillTupleSource.create_observable(bus.subscribe(SparkTags.SecuritiesTag), on_orders, on_fills); _security_orders_demuxer = new TableUpdateDemuxer(o => o.Key, o => o.security_key()); diff --git a/src/client/spark/core/Bus/SparkCommands.cs b/src/client/spark/core/Bus/SparkCommands.cs index da8cb9328..4d01de4aa 100644 --- a/src/client/spark/core/Bus/SparkCommands.cs +++ b/src/client/spark/core/Bus/SparkCommands.cs @@ -3,6 +3,7 @@ using bts.api.orderman; using bts.shell; using mbts.spark; using mbts.ui; +using mbts; using System; using System.Collections.Generic; diff --git a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs index b288bb402..74aa1624d 100644 --- a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs @@ -218,9 +218,7 @@ namespace mbts private Func _comparer_func; public DelegateComparer(Func comparer_func) { _comparer_func = comparer_func; } public int Compare(T x, T y) { return _comparer_func(x, y); } - } - - public static void ignore(this Task t) { } + } public static Google.Protobuf.WellKnownTypes.Timestamp ToGoogleTime(this DateTime self) { return Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(self); diff --git a/src/client/spark/core/Settings/UserPersistFactory.cs b/src/client/spark/core/Settings/UserPersistFactory.cs index 3c1b8db02..e6a211e95 100644 --- a/src/client/spark/core/Settings/UserPersistFactory.cs +++ b/src/client/spark/core/Settings/UserPersistFactory.cs @@ -22,12 +22,12 @@ namespace mbts.ui.settings readonly PersistenceService _persist; [ImportingConstructor] - public UISettingsFactory(UserService login, [Import("settings")] PersistenceService persist) { + public UISettingsFactory(AuthService login, [Import("settings")] PersistenceService persist) { _persist = persist; _users = get_users(login); } - async Task get_users(UserService login) { + async Task get_users(AuthService login) { var users = await login.get_users_async(null); if (users.success) return users.value.Users.ToArray(); else return new User[0]; diff --git a/src/client/spark/core/ShellInterface/UISettings.cs b/src/client/spark/core/ShellInterface/UISettings.cs index 58e0cd849..2b454f848 100644 --- a/src/client/spark/core/ShellInterface/UISettings.cs +++ b/src/client/spark/core/ShellInterface/UISettings.cs @@ -120,7 +120,7 @@ namespace mbts.persist public IObservable>> subscribe(string ns, string pattern) { var re = new Regex(pattern); return _persist - .subscribe_ns(new NamespaceSubArgs() { Ns = uns(ns) }) + .subscribe_ns(uns(ns)) .Select(update => update.added .Where(item => re.IsMatch(item.Key)) diff --git a/src/client/spark/view/Controls/DIYGrid/CellProperty.cs b/src/client/spark/view/Controls/DIYGrid/CellProperty.cs index 758d0474d..754ee552d 100644 --- a/src/client/spark/view/Controls/DIYGrid/CellProperty.cs +++ b/src/client/spark/view/Controls/DIYGrid/CellProperty.cs @@ -1,16 +1,21 @@ -using System; +using mbts.ui.shell; +using System; using System.Reactive.Linq; using System.Reactive.Subjects; namespace mbts.spark { class CellProperty : ISubject { readonly Func _format; + readonly IRaiseNotifyPropertyChanged _owner; + readonly string _prop_name; string _text; - public CellProperty(T initial_value = default) - : this(t => t.ToString(), initial_value) { } + public CellProperty(IRaiseNotifyPropertyChanged owner, string prop_name, T initial_value = default) + : this(owner, prop_name, t => t.ToString(), initial_value) { } - public CellProperty(Func format, T initial_value = default) { + public CellProperty(IRaiseNotifyPropertyChanged owner, string prop_name, Func format, T initial_value = default) { + _owner = owner; + _prop_name = prop_name; _format = format; value = initial_value; } @@ -24,6 +29,7 @@ namespace mbts.spark { if (!value.Equals(this.value)) { OnNext(value); dirty = true; + _owner.raise_notify_property_changed(_prop_name); } } diff --git a/src/client/spark/view/Converters/ResponsiveTextConverter.cs b/src/client/spark/view/Converters/ResponsiveTextConverter.cs new file mode 100644 index 000000000..c47df0794 --- /dev/null +++ b/src/client/spark/view/Converters/ResponsiveTextConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Windows; +using System.Windows.Data; + +namespace mbts.ui.converters { + class ResponsiveTextConverter : IValueConverter { + + public string ShortText { get; set; } + public string LongText { get; set; } + public double Threshold { get; set; } + + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is double _input) { + if (_input < Threshold) { + return ShortText; + } else { + return LongText; + } + } + return LongText; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + throw new NotImplementedException(); + } + } +} diff --git a/src/client/spark/view/Shell/Login/LoginModel.cs b/src/client/spark/view/Shell/Login/LoginModel.cs index 1845850f0..20e770318 100644 --- a/src/client/spark/view/Shell/Login/LoginModel.cs +++ b/src/client/spark/view/Shell/Login/LoginModel.cs @@ -1,39 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel.Composition; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Threading; -using mbts.config; -using mbts.ui.native; -using mbts.utils; -using bts.co2; -using bts.api.user; +using bts; +using bts.api; +using bts.api.core; using bts.api.persistence; -using bts; +using bts.api.user; +using mbts.config; +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Threading; -namespace mbts.ui.shell -{ +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 { [ImportingConstructor] - public LoginContainer(UserService user, [Import("settings")] PersistenceService persist) { + public LoginContainer(ServiceContext context) { var model = LoginModel.instance; - model.provide_services(user, persist); + model.provide_services(context); // await_login pumps the dispatcher but doesn't allow control to return to MEF until the username and workspace are available model.await_login(); - var u = model.get_user(); - UserName = u.name; - UserId = u.id; - Token = u.token; + (UserName,UserId,Token) = model.get_user(); Workspace = model.get_workspace(); model.Dispose(); } @@ -44,21 +34,19 @@ namespace mbts.ui.shell [Export("userid")] public uint UserId { get; private set; } [Export] - public AuthToken Token { get; private set; } + public AuthTokenImmutable Token { get; private set; } [Export("workspace")] public string Workspace { get; private set; } } public struct User { - public User(string name, uint id, AuthToken token) { + public User(string name, uint id) { this.name = name; this.id = id; - this.token = token; } public readonly string name; public readonly UInt32 id; - public readonly AuthToken token; } public class LoginModel : IDisposable @@ -66,11 +54,10 @@ namespace mbts.ui.shell // Singleton to help bootstrap the system private static LoginModel _instance = new LoginModel(); public static LoginModel instance { get { return _instance; } } - private User _user; private string _workspace; private PreloginWorkspaceEnumerator _enum_workspace; - - UserService _logon; + + ServiceContext _ctx; DispatcherFrame _frame = new DispatcherFrame(); private LoginModel() { @@ -82,13 +69,14 @@ namespace mbts.ui.shell public string ErrorMessage { get; private set; } public bool HasFatalError { get; set; } public User[] Users { get; private set; } - - + + // The final username - public User get_user() { - Log.assert_d(!string.IsNullOrEmpty(_user.name)); - return _user; + public (string, uint, AuthTokenImmutable) get_user() { + Log.assert_d(!string.IsNullOrEmpty(_ctx.user)); + return (_ctx.user, _ctx.user_id, _ctx.token.Value); } + public string get_workspace() { return _workspace ?? ""; } @@ -112,13 +100,13 @@ namespace mbts.ui.shell } // Wait for the hub to create the login doodad - (var users, var persist) = await _hub_src.Task; - _logon = users; + _ctx = await _hub_src.Task; // Populate the UI - _enum_workspace = new PreloginWorkspaceEnumerator(persist); - var response = await _logon.get_users_async(new GetUsersRequest()); + _enum_workspace = new PreloginWorkspaceEnumerator(_ctx.locate("settings")); + var auth = _ctx.locate(); + var response = await auth.get_users_async(new GetUsersRequest()); if (response.success) { - Users = response.value.Users.Select(x => new User(x.Login,x.Id, null)).OrderBy(u => u.name).ToArray(); + Users = response.value.Users.Select(x => new User(x.Login,x.Id)).OrderBy(u => u.name).ToArray(); } else { ErrorMessage = "Logon: " + response.error_message; @@ -129,49 +117,37 @@ namespace mbts.ui.shell #endregion - public async Task<(bool success,string info)> do_login(string username, string workspace, string password) { + public async Task do_login(string username, string workspace, string password) { if (Users.Select(u => u.name).Contains(username)) { - var response = await _logon.authenticate_login_async(new AuthenticateLoginRequest() { - Login = username, - Password = password ??"" - }); - if (response.success) { - if (response.value.IsValid) { - _workspace = workspace; - set_authenticated_user(new User(username, response.value.UserId, response.value.Token)); - return (true, ""); - } - else { - return (false, response.value.Reason); - } - } - else { - return (false, response.error_message); + var result = await _ctx.login(username, password); + if (result.success) { + _workspace = workspace; + on_user_authenticated(_ctx.user, _ctx.token); } + return result; } - return (false, "Invalid username"); + return new LoginResult("Invalid username"); } - private void set_authenticated_user(User user) { - Log.assert(!string.IsNullOrEmpty(user.name)); - Log.assert(Users.Select(u => u.name).Contains(user.name)); - _user = user; - Environment.SetEnvironmentVariable("BTS_USER", user.name); + private void on_user_authenticated(string username, AuthTokenImmutable? token) { + Log.assert(!string.IsNullOrEmpty(username)); + Log.assert(Users.Select(u => u.name).Contains(username)); + Environment.SetEnvironmentVariable("BTS_USER", username); _frame.Continue = false; } public void await_login() { - if (string.IsNullOrEmpty(_user.name)) { + if (!_ctx.token.HasValue) { Dispatcher.PushFrame(_frame); } } #region provide hub - public void provide_services(UserService u, PersistenceService p) { - _hub_src.TrySetResult((u,p)); + internal void provide_services(ServiceContext ctx) { + _hub_src.TrySetResult(ctx); } - private TaskCompletionSource<(UserService, PersistenceService)> _hub_src = new TaskCompletionSource<(UserService, PersistenceService)>(); + private TaskCompletionSource _hub_src = new TaskCompletionSource(); #endregion #region Dispose diff --git a/src/client/spark/view/Shell/Login/LoginViewModel.cs b/src/client/spark/view/Shell/Login/LoginViewModel.cs index c2140dc91..b9994863d 100644 --- a/src/client/spark/view/Shell/Login/LoginViewModel.cs +++ b/src/client/spark/view/Shell/Login/LoginViewModel.cs @@ -138,14 +138,15 @@ namespace mbts.ui.shell if (selected_workspace == "New workspace...") { selected_workspace = null; } - (bool success, string message) = await _model.do_login(Name, selected_workspace, Password); - if (success) { VisualState = "Loading"; } - if (!success && !string.IsNullOrEmpty(message)) { - WarningMessage = message; + var result = await _model.do_login(Name, selected_workspace, Password); + if (result.success) { VisualState = "Loading"; } + if (!result.success && !string.IsNullOrEmpty(result.reason)) { + WarningMessage = result.reason; VisualState = "BadPassword"; } - else if (!string.IsNullOrEmpty(message)) { - BTSMessageBox.Show(message, "Login Message", BTSMessageBoxButtons.OK, MessageBoxImage.Information); + else if (!string.IsNullOrEmpty(result.reason)) { + // Login was successful but we have a message for the user + BTSMessageBox.Show(result.reason, "Login Message", BTSMessageBoxButtons.OK, MessageBoxImage.Information); } } private void OnCancel(object unused) { diff --git a/src/client/spark/view/Shell/Workspaces/SettingsManagerTool.cs b/src/client/spark/view/Shell/Workspaces/SettingsManagerTool.cs index cddfa7c5e..d25162176 100644 --- a/src/client/spark/view/Shell/Workspaces/SettingsManagerTool.cs +++ b/src/client/spark/view/Shell/Workspaces/SettingsManagerTool.cs @@ -11,7 +11,7 @@ namespace bts.settings { public class SettingsManagerTool { public static void run() { var sc = new ServiceContext(); - var users = sc.locate(); + var users = sc.locate(); var persist = sc.locate("settings"); var user_list = users.get_users(new GetUsersRequest()); var user_names = user_list.Users.Select(u => u.Login); diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index bd9f61f64..a9667b532 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -110,7 +110,7 @@ namespace mbts.spark { { var lgh = source as LadderGridHost; double width_adjustment = (double)(uint) e.NewValue - (double)(uint) e.OldValue; - lgh._adjust_column_width(lgh.columns.First(c => c.column_type == ColumnType.Order), width_adjustment); + lgh._adjust_column_width(lgh.columns.FirstOrDefault(c => c.column_type == ColumnType.Order), width_adjustment); } public uint bid_column_width @@ -126,7 +126,7 @@ namespace mbts.spark { { var lgh = source as LadderGridHost; double width_adjustment = (double)(uint) e.NewValue - (double)(uint) e.OldValue; - lgh._adjust_column_width(lgh.columns.First(c => c.column_type == ColumnType.Bid), width_adjustment); + lgh._adjust_column_width(lgh.columns.FirstOrDefault(c => c.column_type == ColumnType.Bid), width_adjustment); } public uint price_column_width @@ -142,7 +142,7 @@ namespace mbts.spark { { var lgh = source as LadderGridHost; double width_adjustment = (double)(uint) e.NewValue - (double)(uint) e.OldValue; - lgh._adjust_column_width(lgh.columns.First(c => c.column_type == ColumnType.Price), width_adjustment); + lgh._adjust_column_width(lgh.columns.FirstOrDefault(c => c.column_type == ColumnType.Price), width_adjustment); } @@ -159,14 +159,14 @@ namespace mbts.spark { { var lgh = source as LadderGridHost; double width_adjustment = (double)(uint) e.NewValue - (double)(uint) e.OldValue; - lgh._adjust_column_width(lgh.columns.First(c => c.column_type == ColumnType.Ask), width_adjustment); + lgh._adjust_column_width(lgh.columns.FirstOrDefault(c => c.column_type == ColumnType.Ask), width_adjustment); } public static readonly DependencyProperty VolumeColumnWidthProperty = WPFHelper.create_dp( nameof(VolumeColumnWidth), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, - (o, oldval, newval) => o._adjust_column_width(o.columns.First(c => c.column_type == ColumnType.Volume), (double)newval - (double)oldval), + (o, oldval, newval) => o._adjust_column_width(o.columns.FirstOrDefault(c => c.column_type == ColumnType.Volume), (double)newval - (double)oldval), 50u); public uint VolumeColumnWidth { @@ -178,7 +178,7 @@ namespace mbts.spark { WPFHelper.create_dp( nameof(LastColumnWidth), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, - (o, oldval, newval) => o._adjust_column_width(o.columns.First(c => c.column_type == ColumnType.Last), (double)newval - (double)oldval), + (o, oldval, newval) => o._adjust_column_width(o.columns.FirstOrDefault(c => c.column_type == ColumnType.Last), (double)newval - (double)oldval), 50u); public uint LastColumnWidth { @@ -327,6 +327,8 @@ namespace mbts.spark { } void _adjust_column_width(Column column, double adjustment) { + if (column == null) + return; int new_col_width; switch (column.column_type) { case ColumnType.Order: new_col_width = (int)orders_column_width; break; @@ -662,22 +664,10 @@ namespace mbts.spark { } else { init = false; prev_row_height = _settings.row_height; - // This is a general issue with default-settings: - // "Not every property in the settings object should be shared across windows." - // Column widths are one such property (they are changed from the actual Ladder window, not the settings dialog). - // Below is a hack which prevents overwriting current column widths; until we come up with a better solution this will suffice. - // TODO: fix this by moving such properties from the settings proto into a separate proto (or come up with a better workaround/solution) - copy_col_width(v => v.orders_column); - copy_col_width(v => v.bid_column); - copy_col_width(v => v.price_column); - copy_col_width(v => v.ask_column); - copy_col_width(v => v.volume_column.general); - copy_col_width(v => v.last_column); - void copy_col_width(Func select_col) => - select_col(s).width = select_col(_settings).width; } - // - _settings = s; + /// The viewmodel will always have the most up-to-date settings, so ignore and just get it from . + /// This is a workaround for the global settings-defaults issue: when defaults are updated, some properties are inadvertantly overwritten, such as column-widths, etc. + _settings = _vm.get_save_state(); _bid_vis_tup.glyph_context = glyph_context(s.bid_column); _ask_vis_tup.glyph_context = glyph_context(s.ask_column); _price_vis_tup.glyph_context = glyph_context(s.price_column); @@ -698,18 +688,19 @@ namespace mbts.spark { // Renders the grid lines and column backgrounds _visualHost.AddVisualChild(_gridvis); // Orders column - orders_column_width = s.orders_column.width; + SetCurrentValue(orders_column_widthProperty, s.orders_column.width); _ordershost.update_settings(_price_list, _price_comparer, s.row_height, s.orders_column); foreach (var col in columns) { if (col.visual_tup != null) { if (col.settings.show) { _visualHost.AddVisualChild(col.visual_tup.visual); switch (col.column_type) { - case ColumnType.Bid: bid_column_width = col.settings.width; break; - case ColumnType.Price: price_column_width = col.settings.width; break; - case ColumnType.Ask: ask_column_width = col.settings.width; break; + case ColumnType.Bid: SetCurrentValue(bid_column_widthProperty, col.settings.width); break; + case ColumnType.Price: SetCurrentValue(price_column_widthProperty, col.settings.width); break; + case ColumnType.Ask: SetCurrentValue(ask_column_widthProperty, col.settings.width); break; + case ColumnType.Last: SetCurrentValue(LastColumnWidthProperty, col.settings.width); break; case ColumnType.Volume: - VolumeColumnWidth = col.settings.width; + SetCurrentValue(VolumeColumnWidthProperty, col.settings.width); _volume_container.mark_dirty(); break; } diff --git a/src/client/spark/view/Spark/Ladder/LadderSettings.cs b/src/client/spark/view/Spark/Ladder/LadderSettings.cs index 1d1bd0865..ad288beea 100644 --- a/src/client/spark/view/Spark/Ladder/LadderSettings.cs +++ b/src/client/spark/view/Spark/Ladder/LadderSettings.cs @@ -8,6 +8,7 @@ using System.Windows; using bts.proto; using mbts.ui.spark; using System.Collections.Generic; +using System.ComponentModel; namespace mbts.spark { // IMPORTANT: BE SURE TO ADD ANY NEW PROPERTIES TO THE EQUALS FUNCTION! @@ -178,7 +179,33 @@ namespace mbts.spark { // From the settings dialog, default settings will only be persisted when they are NOT EQUAL to the current default settings. // Settings are liable to change in the near future, so an internal IEqualityComparer simply won't do as it risks becoming out of date. [ProtoContract] - class LadderSettings : IDefaultableSettings, IEquatable { + class LadderSettings : IEquatable { + const double _default_order_entry_panel_width = 110.0; + + // Default proto constructor + // Added this so that when clients upgrade to a version with new settings, + // the default values are applied correctly; thx to John for this tip + public LadderSettings() { + day_visible = true; + high_visible = true; + low_visible = true; + open_visible = true; + settle_visible = true; + volume_visible = true; + account_visible = true; + tif_visible = true; + order_type_visible = true; + account_position_visible = true; + size_presets_visible = true; + cancel_buys_visible = true; + cancel_sells_visible = true; + cancel_all_visible = true; + auto_clear_visible = true; + clear_visible = true; + order_entry_panel_initial_width = _default_order_entry_panel_width; + use_defaults = true; + } + public static LadderSettings Default { get { LadderColumnSettings @@ -216,7 +243,24 @@ namespace mbts.spark { session_high_line = new LadderMarketBreakLine { color = BTSColors.MarketData.session_high, show = true }, session_range_fill = new LadderMarketBreakLine { color = BTSColors.MarketData.session_range_fill, show = true }, alternate_order_size = 0, - size_display = MarketSizeDisplay.get_default() + size_display = MarketSizeDisplay.get_default(), + day_visible = true, + high_visible = true, + low_visible = true, + open_visible = true, + settle_visible = true, + volume_visible = true, + account_visible = true, + tif_visible = true, + order_type_visible = true, + account_position_visible = true, + size_presets_visible = true, + cancel_buys_visible = true, + cancel_sells_visible = true, + cancel_all_visible = true, + auto_clear_visible = true, + clear_visible = true, + order_entry_panel_initial_width = _default_order_entry_panel_width }; } } @@ -277,17 +321,46 @@ namespace mbts.spark { public VolumeColumnSettings volume_column { get; set; } [ProtoMember(26)] public MarketSizeDisplay size_display { get; set; } - [ProtoMember(27)] + + // order entry panel items show/hide + [ProtoMember(27), DefaultValue(true)] + public bool day_visible { get; set; } + [ProtoMember(28), DefaultValue(true)] + public bool high_visible { get; set; } + [ProtoMember(29), DefaultValue(true)] + public bool low_visible { get; set; } + [ProtoMember(30), DefaultValue(true)] + public bool open_visible { get; set; } + [ProtoMember(31), DefaultValue(true)] + public bool settle_visible { get; set; } + [ProtoMember(32), DefaultValue(true)] + public bool volume_visible { get; set; } + [ProtoMember(33), DefaultValue(true)] + public bool account_visible { get; set; } + [ProtoMember(34), DefaultValue(true)] + public bool tif_visible { get; set; } + [ProtoMember(35), DefaultValue(true)] + public bool order_type_visible { get; set; } + [ProtoMember(36), DefaultValue(true)] + public bool account_position_visible { get; set; } + [ProtoMember(37), DefaultValue(true)] + public bool size_presets_visible { get; set; } + [ProtoMember(38), DefaultValue(true)] + public bool cancel_buys_visible { get; set; } + [ProtoMember(39), DefaultValue(true)] + public bool cancel_sells_visible { get; set; } + [ProtoMember(40), DefaultValue(true)] + public bool cancel_all_visible { get; set; } + [ProtoMember(41), DefaultValue(true)] + public bool auto_clear_visible { get; set; } + [ProtoMember(42), DefaultValue(true)] + public bool clear_visible { get; set; } + // + [ProtoMember(43), DefaultValue(_default_order_entry_panel_width)] + public double order_entry_panel_initial_width { get; set; } + [ProtoMember(44), DefaultValue(true)] public bool use_defaults { get; set; } - [ProtoMember(28)] - List _template_favorites; - public List template_favorites => _template_favorites ?? (_template_favorites = new List()); - - [ProtoMember(29)] - List _template_defaults; - public List template_defaults => _template_defaults ?? (_template_defaults = new List()); - public bool Equals(LadderSettings other) => other != null && row_height == other.row_height && @@ -313,9 +386,24 @@ namespace mbts.spark { session_range_fill.safe_equals(other.session_range_fill) && volume_column.safe_equals(other.volume_column) && size_display.safe_equals(other.size_display) && - use_defaults == use_defaults && - template_favorites.SequenceEqual(other.template_favorites) && - template_defaults.SequenceEqual(other.template_defaults); + day_visible == other.day_visible && + high_visible == other.high_visible && + low_visible == other.low_visible && + open_visible == other.open_visible && + settle_visible == other.settle_visible && + volume_visible == other.volume_visible && + account_visible == other.account_visible && + tif_visible == other.tif_visible && + order_type_visible == other.order_type_visible && + account_position_visible == other.account_position_visible && + size_presets_visible == other.size_presets_visible && + cancel_buys_visible == other.cancel_buys_visible && + cancel_sells_visible == other.cancel_sells_visible && + cancel_all_visible == other.cancel_all_visible && + auto_clear_visible == other.auto_clear_visible && + clear_visible == other.clear_visible && + order_entry_panel_initial_width == other.order_entry_panel_initial_width && + use_defaults == other.use_defaults; public override bool Equals(object obj) => Equals(obj as LadderSettings); @@ -344,9 +432,42 @@ namespace mbts.spark { EqualityComparer.safe_get_hash_code(session_range_fill), EqualityComparer.safe_get_hash_code(volume_column), EqualityComparer.safe_get_hash_code(size_display), - use_defaults.GetHashCode(), - EqualityComparer.safe_aggregate_hash(template_favorites), - EqualityComparer.safe_aggregate_hash(template_defaults)); + day_visible.GetHashCode(), + high_visible.GetHashCode(), + low_visible.GetHashCode(), + open_visible.GetHashCode(), + settle_visible.GetHashCode(), + volume_visible.GetHashCode(), + account_visible.GetHashCode(), + tif_visible.GetHashCode(), + order_type_visible.GetHashCode(), + account_position_visible.GetHashCode(), + size_presets_visible.GetHashCode(), + cancel_buys_visible.GetHashCode(), + cancel_sells_visible.GetHashCode(), + cancel_all_visible.GetHashCode(), + auto_clear_visible.GetHashCode(), + clear_visible.GetHashCode(), + order_entry_panel_initial_width.GetHashCode(), + use_defaults.GetHashCode()); + + public struct WindowSpecifics { + public readonly double order_entry_panel_width; + public readonly uint orders_column_width, bid_column_width, price_column_width, ask_column_width, last_column_width, volume_column_width; + + public WindowSpecifics(LadderSettings s) + : this(s.order_entry_panel_initial_width, s.orders_column.width, s.bid_column.width, s.price_column.width, s.ask_column.width, s.last_column.width, s.volume_column.general.width) { } + + public WindowSpecifics(double order_entry_panel_width, uint orders_column_width, uint bid_column_width, uint price_column_width, uint ask_column_width, uint last_column_width, uint volume_column_width) { + this.order_entry_panel_width = order_entry_panel_width; + this.orders_column_width = orders_column_width; + this.bid_column_width = bid_column_width; + this.price_column_width = price_column_width; + this.ask_column_width = ask_column_width; + this.last_column_width = last_column_width; + this.volume_column_width = volume_column_width; + } + } } static class LadderSettingsExtensions { @@ -361,5 +482,21 @@ namespace mbts.spark { public static IEnumerable visible_columns(this LadderSettings settings) => settings.all_columns().Where(c => c.show); + + public static LadderSettings.WindowSpecifics get_window_specifics(this LadderSettings settings) => + new LadderSettings.WindowSpecifics(settings); + + public static LadderSettings with_window_specifics(this LadderSettings source, LadderSettings.WindowSpecifics specifics) { + // must use clone bc we are applying settings that are specific to each individual LadderWindow, and should not be shared among all ladders (even if it is default settings). + source = SparkUtils.clone_proto(source); + source.order_entry_panel_initial_width = specifics.order_entry_panel_width; + source.orders_column.width = specifics.orders_column_width; + source.bid_column.width = specifics.bid_column_width; + source.price_column.width = specifics.price_column_width; + source.ask_column.width = specifics.ask_column_width; + source.last_column.width = specifics.last_column_width; + source.volume_column.general.width = specifics.volume_column_width; + return source; + } } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Spark/Ladder/LadderSettingsVM.cs b/src/client/spark/view/Spark/Ladder/LadderSettingsVM.cs index 4047a6ca4..3c5d297c6 100644 --- a/src/client/spark/view/Spark/Ladder/LadderSettingsVM.cs +++ b/src/client/spark/view/Spark/Ladder/LadderSettingsVM.cs @@ -17,6 +17,7 @@ namespace mbts.spark { readonly Property _badge_style; readonly Property _alternate_order_size; readonly DelegateProperty _row_height; + Func _get_order_entry_panel_width; LadderSettings _current; LadderColumnSettingsVM _orders = new OrdersColumnSettingsVM(), @@ -32,14 +33,33 @@ namespace mbts.spark { _session_low_mkt_line = new LadderMarketBreakLineVM("Session Low", 2, 1), _session_high_mkt_line = new LadderMarketBreakLineVM("Session High", 2, 1, false), _session_range_fill = new LadderMarketBreakLineVM("Session Range", 0, 0, false); + OrderEntryPanelItemVisibilityVM + _day_visibility = new OrderEntryPanelItemVisibilityVM("Day Change"), + _high_visibility = new OrderEntryPanelItemVisibilityVM("High"), + _low_visibility = new OrderEntryPanelItemVisibilityVM("Low"), + _open_visibility = new OrderEntryPanelItemVisibilityVM("Open"), + _settle_visibility = new OrderEntryPanelItemVisibilityVM("Settle"), + _volume_visibility = new OrderEntryPanelItemVisibilityVM("Volume"), + _account_visibility = new OrderEntryPanelItemVisibilityVM("Account"), + _tif_visibility = new OrderEntryPanelItemVisibilityVM("Time In Force"), + _order_type_visibility = new OrderEntryPanelItemVisibilityVM("Order Type"), + _account_position_visibility = new OrderEntryPanelItemVisibilityVM("Account Position"), + _size_preset_visibility = new OrderEntryPanelItemVisibilityVM("Size Presets"), + _auto_clear_visibility = new OrderEntryPanelItemVisibilityVM("Auto Clear"), + _clear_visibility = new OrderEntryPanelItemVisibilityVM("Clear"), + _cancel_buys_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Buys"), + _cancel_sells_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Sells"), + _cancel_all_visibility = new OrderEntryPanelItemVisibilityVM("Cancel All"); - public LadderSettingsVM(bool is_synthetic) { + public LadderSettingsVM(bool is_synthetic, Func get_left_panel_width) { this.is_synthetic = is_synthetic; size_presets = new ObservableEditableCollection>(_create_size_preset_vm); size_presets.CollectionChanged += (s, e) => RaisePropertyChanged(nameof(size_presets_text)); _badge_style = backing(nameof(badge_style)); _badge_style.Changed += _badge_style_Changed; _alternate_order_size = backing(nameof(alternate_order_size)); + _get_order_entry_panel_width = get_left_panel_width; + // be sure to initialize backings before this measure_row_height call _row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result())); _orders.font_size_changed += on_font_size_changed; _bid.font_size_changed += on_font_size_changed; @@ -108,6 +128,27 @@ namespace mbts.spark { } } + public IEnumerable order_entry_panel_items { + get { + yield return _day_visibility; + yield return _high_visibility; + yield return _low_visibility; + yield return _open_visibility; + yield return _settle_visibility; + yield return _volume_visibility; + yield return _account_visibility; + yield return _tif_visibility; + yield return _order_type_visibility; + yield return _account_position_visibility; + yield return _size_preset_visibility; + yield return _clear_visibility; + yield return _auto_clear_visibility; + yield return _cancel_buys_visibility; + yield return _cancel_sells_visibility; + yield return _cancel_all_visibility; + } + } + public string key => GridOrLadderSettingsSelectorKeys.Ladder; public void load(LadderSettings settings) { @@ -128,6 +169,26 @@ namespace mbts.spark { _session_low_mkt_line.assign_from(_current.session_low_line); _session_high_mkt_line.assign_from(_current.session_high_line); _session_range_fill.assign_from(_current.session_range_fill); + _day_visibility.show = settings.day_visible; + _high_visibility.show = settings.high_visible; + _low_visibility.show = settings.low_visible; + _open_visibility.show = settings.open_visible; + _settle_visibility.show = settings.settle_visible; + _volume_visibility.show = settings.volume_visible; + _account_visibility.show = settings.account_visible; + _tif_visibility.show = settings.tif_visible; + _order_type_visibility.show = settings.order_type_visible; + _account_position_visibility.show = settings.account_position_visible; + _size_preset_visibility.show = settings.size_presets_visible; + _clear_visibility.show = settings.clear_visible; + _auto_clear_visibility.show = settings.auto_clear_visible; + _cancel_buys_visibility.show = settings.cancel_buys_visible; + _cancel_sells_visibility.show = settings.cancel_sells_visible; + _cancel_all_visibility.show = settings.cancel_all_visible; + // do not read the order entry panel width here from settings + // because it could have changed from the UI + // there might be a better way of doing this, like how + // does the widths of the ladder grid column pull this off? } public LadderSettings get_result() { @@ -149,6 +210,23 @@ namespace mbts.spark { clone.session_high_line = _session_high_mkt_line.get_settings(); clone.session_range_fill = _session_range_fill.get_settings(); clone.row_height = LadderRender.measure_row_height(clone); + clone.day_visible = _day_visibility.show; + clone.high_visible = _high_visibility.show; + clone.low_visible = _low_visibility.show; + clone.open_visible = _open_visibility.show; + clone.settle_visible = _settle_visibility.show; + clone.volume_visible = _volume_visibility.show; + clone.account_visible = _account_visibility.show; + clone.tif_visible = _tif_visibility.show; + clone.order_type_visible = _order_type_visibility.show; + clone.account_position_visible = _account_position_visibility.show; + clone.size_presets_visible = _size_preset_visibility.show; + clone.auto_clear_visible = _auto_clear_visibility.show; + clone.clear_visible = _clear_visibility.show; + clone.cancel_buys_visible = _cancel_buys_visibility.show; + clone.cancel_sells_visible = _cancel_sells_visibility.show; + clone.cancel_all_visible = _cancel_all_visibility.show; + clone.order_entry_panel_initial_width = _get_order_entry_panel_width(); return clone; } @@ -276,6 +354,19 @@ namespace mbts.spark { }; } + public class OrderEntryPanelItemVisibilityVM : ViewModelBase { + readonly Property _show; + + public OrderEntryPanelItemVisibilityVM(string name) { + this.name = name; + _show = backing(nameof(show), true); + } + + public string name { get; } + public bool show { get => _show.Value; set => _show.Value = value; } + + } + public class VolumeColumnVM : ViewModelBase { readonly DelegateProperty _any_visible; public VolumeColumnVM() { diff --git a/src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml b/src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml index eeceec542..732551d00 100644 --- a/src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml +++ b/src/client/spark/view/Spark/Ladder/LadderSettingsView.xaml @@ -140,6 +140,7 @@ + @@ -232,6 +233,7 @@ + @@ -350,6 +352,7 @@ + @@ -440,6 +443,7 @@ + @@ -557,6 +561,7 @@ + @@ -592,6 +597,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Spark/Ladder/LadderVM.cs b/src/client/spark/view/Spark/Ladder/LadderVM.cs index 04209f3a0..bc0edc86a 100644 --- a/src/client/spark/view/Spark/Ladder/LadderVM.cs +++ b/src/client/spark/view/Spark/Ladder/LadderVM.cs @@ -20,18 +20,23 @@ using System.Windows.Media; namespace mbts.spark { class LadderVM : DisposableViewModelBase, IWillLetYouKnowWhenIDispose, IKeyListener { + static readonly Brush _transparent_status_brush = BTSColors.UI.transparent; + readonly IBus _bus; readonly LadderModel _model; - readonly Property _high, _low, _change, _open, _settlement, _position; + readonly Property _high, _low, _change, _open, _settlement, _position, _left_panel_width; + readonly Property _orders_column_width, _bid_column_width, _price_column_width, _ask_column_width, _last_column_width, _volume_column_width; readonly Property _volume; - readonly Property _auto_clear; + readonly Property _auto_clear, _show_day, _show_high, _show_low, _show_open, _show_settle, _show_volume, _show_account, + _show_tif, _show_order_type, _show_account_position, _show_size_preset, _show_auto_clear, _show_clear, _show_cancel_buys, + _show_cancel_sells, _show_cancel_all; readonly Property _bid_background, _bid_foreground, _ask_background, _ask_foreground; IWindowSettingsManager _settings_manager; ulong _misc_time = 0; IEqualityComparer _equality; Dictionary _slot_price_vs_orders; - public LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager) { + public LadderVM(IBus bus, LadderModel model, IWindowSettingsManager settings_manager, LadderSettings init) { _bus = bus; _model = model; _equality = TickUtils.tick_equality_comparer(_model.security.ContractSpec); @@ -44,13 +49,22 @@ namespace mbts.spark { _change = backing(nameof(change), double.NaN); _open = backing(nameof(open), double.NaN); _settlement = backing(nameof(settlement), double.NaN); + // init window-specific settings: these properties should not observe settings updates; they are independent from the settings dialog, so it doesn't make sense that the settings dialog should cause them to change. + var ws = init.get_window_specifics(); + _orders_column_width = backing(nameof(orders_column_width), ws.orders_column_width); + _bid_column_width = backing(nameof(bid_column_width), ws.bid_column_width); + _price_column_width = backing(nameof(price_column_width), ws.price_column_width); + _ask_column_width = backing(nameof(ask_column_width), ws.ask_column_width); + _last_column_width = backing(nameof(last_column_width), ws.last_column_width); + _volume_column_width = backing(nameof(volume_column_width), ws.volume_column_width); + _left_panel_width = backing(nameof(left_panel_width), ws.order_entry_panel_width); // remember: account_positions needs to subscribe to selected_account; both the sub and account_positions need to be disposed var account_positions = new KeyDrivenObservableSeries(a => _model.order_gateway.security_total_position(security.Id, a)); _position = backing(nameof(position), account_positions.OnDispatcher()); _volume = backing(nameof(volume), 0ul); _auto_clear = backing(nameof(auto_clear), false); _status = backing(nameof(status_message), ""); - _status_brush = backing(nameof(status_background), (Brush)BTSColors.UI.spark_menu_background); + _status_brush = backing(nameof(status_background), _transparent_status_brush); // brush props _bid_background = brush_prop(nameof(bid_background), s => s.bid_column.background.rgb_brush()); _bid_foreground = brush_prop(nameof(bid_foreground), s => s.bid_column.foreground.rgb_brush()); @@ -58,6 +72,27 @@ namespace mbts.spark { _ask_foreground = brush_prop(nameof(ask_foreground), s => s.ask_column.foreground.rgb_brush()); Property brush_prop(string name, Func get_brush) => backing(name, settings_manager.subscribe_current().OnDispatcher(), get_brush); + // bool visibility props + _show_day = bool_prop(nameof(show_day), s => s.day_visible); + _show_high = bool_prop(nameof(show_high), s => s.high_visible); + _show_low = bool_prop(nameof(show_low), s => s.low_visible); + _show_open = bool_prop(nameof(show_open), s => s.open_visible); + _show_settle = bool_prop(nameof(show_settle), s => s.settle_visible); + _show_volume = bool_prop(nameof(show_volume), s => s.volume_visible); + _show_account = bool_prop(nameof(show_account), s => s.account_visible); + _show_tif = bool_prop(nameof(show_tif), s => s.tif_visible); + _show_order_type = bool_prop(nameof(show_order_type), s => s.order_type_visible); + _show_account_position = bool_prop(nameof(show_account_position), s => s.account_position_visible); + _show_size_preset = bool_prop(nameof(show_size_preset), s => s.size_presets_visible); + _show_auto_clear = bool_prop(nameof(show_auto_clear), s => s.auto_clear_visible); + _show_clear = bool_prop(nameof(show_clear), s => s.clear_visible); + _show_cancel_buys = bool_prop(nameof(show_cancel_buys), s => s.cancel_buys_visible); + _show_cancel_sells = bool_prop(nameof(show_cancel_sells), s => s.cancel_sells_visible); + _show_cancel_all = bool_prop(nameof(show_cancel_all), s => s.cancel_all_visible); + + Property bool_prop(string name, Func get_bool) => + backing(name, settings_manager.subscribe_current().OnDispatcher(), get_bool); + // position_click_command = new DelegateCommand(() => size_calculator.value = DoubleHelper.safe_convert_to_uint(Math.Abs(position))); send_order_command = new DelegateCommand<(double price, Side? side, bool size_from_alternate)>(send_order); @@ -68,10 +103,10 @@ namespace mbts.spark { var vm = new WindowSettingsDialogVM( settings_manager, s => s.ladder, UserSettings.FileExtensions.LADDER, s => { - var svm = new LadderSettingsVM(security.ContractCase == Security.ContractOneofCase.Synthetic); + var svm = new LadderSettingsVM(security.ContractCase == Security.ContractOneofCase.Synthetic, () => left_panel_width); svm.load(s); return svm; - }); + }, s => s.with_window_specifics(get_save_state().get_window_specifics())); var dialog = new ui.spark.SimpleGridSettingsDialog { DataContext = vm, Title = $"Ladder Settings - '{security}'" @@ -202,7 +237,7 @@ namespace mbts.spark { await Task.Delay(TimeSpan.FromSeconds(5)); if (_status.Value == a.message) { _status.set(""); - _status_brush.set(BTSColors.UI.spark_menu_background); + _status_brush.set(_transparent_status_brush); } } } @@ -233,31 +268,37 @@ namespace mbts.spark { public Brush ask_background => _ask_background.Value; public Brush ask_foreground => _ask_foreground.Value; public DialogCommand settings_command { get; } + public bool show_day { get => _show_day.Value; set => _show_day.set(value); } + public bool show_high { get => _show_high.Value; set => _show_high.set(value); } + public bool show_low { get => _show_low.Value; set => _show_low.set(value); } + public bool show_open { get => _show_open.Value; set => _show_open.set(value); } + public bool show_settle { get => _show_settle.Value; set => _show_settle.set(value); } + public bool show_volume { get => _show_volume.Value; set => _show_volume.set(value); } + public bool show_account { get => _show_account.Value; set => _show_account.set(value); } + public bool show_tif { get => _show_tif.Value; set => _show_tif.set(value); } + public bool show_order_type { get => _show_order_type.Value; set => _show_order_type.set(value); } + public bool show_account_position { get => _show_account_position.Value; set => _show_account_position.set(value); } + public bool show_size_preset { get => _show_size_preset.Value; set => _show_size_preset.set(value); } + public bool show_auto_clear { get => _show_auto_clear.Value; set => _show_auto_clear.set(value); } + public bool show_clear { get => _show_clear.Value; set => _show_clear.set(value); } + public bool show_cancel_buys { get => _show_cancel_buys.Value; set => _show_cancel_buys.set(value); } + public bool show_cancel_sells { get => _show_cancel_sells.Value; set => _show_cancel_sells.set(value); } + public bool show_cancel_all { get => _show_cancel_all.Value; set => _show_cancel_all.set(value); } + public double left_panel_width { get => _left_panel_width.Value; set => _left_panel_width.set(value); } + public uint orders_column_width { get => _orders_column_width.Value; set => _orders_column_width.set(value); } + public uint bid_column_width { get => _bid_column_width.Value; set => _bid_column_width.set(value); } + public uint price_column_width { get => _price_column_width.Value; set => _price_column_width.set(value); } + public uint ask_column_width { get => _ask_column_width.Value; set => _ask_column_width.set(value); } + public uint last_column_width { get => _last_column_width.Value; set => _last_column_width.set(value); } + public uint volume_column_width { get => _volume_column_width.Value; set => _volume_column_width.set(value); } internal LadderModel model => _model; - internal IObservable settings => _settings_manager.subscribe_current(t => { - if (t.instance == null) - return t.defaults; - else if (!t.instance.use_defaults) - return t.instance; - else { - var rv = SparkUtils.clone_proto(t.defaults); - rv.use_defaults = true; - // TODO: use instance-settings to overwrite the defaults for properties that are not edited in the settings dialog (e.g. column widths) - return rv; - } - }); + internal IObservable settings => _settings_manager.subscribe_current(); public LadderSettings get_save_state() { - // TODO: save an actual OrderDefinition to preserve order params. - LadderSettings settings; - if (_settings_manager.instance_settings == null) { - settings = SparkUtils.clone_proto(_settings_manager.default_settings); - settings.use_defaults = true; - } else { - settings = SparkUtils.clone_proto(_settings_manager.instance_settings); - } - settings.default_order_type = order_properties_vm.selected_algo_definition?.algo_root?.order_type ?? settings.default_order_type; - return settings; + var state = _settings_manager.current_settings(); + state = state.with_window_specifics(new LadderSettings.WindowSpecifics(left_panel_width, orders_column_width, bid_column_width, price_column_width, ask_column_width, last_column_width, volume_column_width)); + state.use_defaults = _settings_manager.instance_settings == null; + return state; } public void key_down(KeyEventArgs e) { @@ -316,6 +357,7 @@ namespace mbts.spark { _change.set(mid - md.settlement_price); } _volume.set(volume); + _misc_time = _model.md.misc_timestamp; } } @@ -334,4 +376,4 @@ namespace mbts.spark { on_tick?.Invoke(); } } -} \ No newline at end of file +} diff --git a/src/client/spark/view/Spark/Ladder/LadderView.xaml b/src/client/spark/view/Spark/Ladder/LadderView.xaml index 5ef8a6021..eada9d37a 100644 --- a/src/client/spark/view/Spark/Ladder/LadderView.xaml +++ b/src/client/spark/view/Spark/Ladder/LadderView.xaml @@ -1,16 +1,19 @@ - + @@ -28,6 +31,13 @@ + + + + + + + - - + + - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + + + + - - - - - - - - - - - Auto Clear - - - - - - - - + + + Auto Clear + + + +