From 74dd36bde127df1428f526ed663835b989087b09 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 7 May 2019 17:31:52 -0400 Subject: [PATCH 01/21] SPARK-2380 add MBO popup --- .../Modules/Trading/LadderWindowFactory.cs | 15 ++++++- .../Modules/Trading/TradingShellModule.cs | 15 +++++-- .../spark/view/Spark/Ladder/LadderGridHost.cs | 33 ++++++++++++++-- .../spark/view/Spark/Ladder/LadderModel.cs | 6 ++- .../view/Spark/Ladder/LadderOrdersHost.cs | 6 +-- .../spark/view/Spark/Ladder/LadderVM.cs | 6 +-- .../view/Spark/Ladder/MBO/MBODetailView.cs | 33 ++++++++++++++++ .../spark/view/Utility/AutoClosePopup.cs | 39 +++++++++++++++++++ src/client/sparkcmd/Cmd/MBOCommand.cs | 16 +------- src/lib/api/services/MBOService.proto | 7 ++-- src/lib/md/MBOServiceServer.cpp | 39 ++++++++++++------- 11 files changed, 167 insertions(+), 48 deletions(-) create mode 100644 src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs create mode 100644 src/client/spark/view/Utility/AutoClosePopup.cs diff --git a/src/client/spark/Modules/Trading/LadderWindowFactory.cs b/src/client/spark/Modules/Trading/LadderWindowFactory.cs index 0cf81e9e1..c796c52fd 100644 --- a/src/client/spark/Modules/Trading/LadderWindowFactory.cs +++ b/src/client/spark/Modules/Trading/LadderWindowFactory.cs @@ -1,4 +1,5 @@ using bts.api; +using bts.md; using mbts; using mbts.config; using mbts.persist; @@ -21,12 +22,21 @@ namespace bts.shell { readonly LadderConfig _ladder_conf; readonly IBus _bus; readonly IWindowManager _wm; + readonly MBOService _mbo; readonly UserSettingsHub _settings_hub; readonly OrdersModel _orders_model; readonly MarketDataAuxiliaryModel _md_auxiliary_model; IReadOnlyDictionary _securities = new Dictionary(); - public LadderWindowFactory(IShellModule owner, IBus bus, IWindowManager wm, UserSettingsHub settings_hub, OrdersModel orders_model, MarketDataAuxiliaryModel md_auxiliary_model) + public LadderWindowFactory( + IShellModule owner, + IBus bus, + IWindowManager wm, + UserSettingsHub settings_hub, + OrdersModel orders_model, + MarketDataAuxiliaryModel md_auxiliary_model, + MBOService mbo) + : base(owner, "SparkLadder") { _bus = bus; _wm = wm; @@ -34,6 +44,7 @@ namespace bts.shell { _orders_model = orders_model; _md_auxiliary_model = md_auxiliary_model; _ladder_conf = new LadderConfig(Configuration.get(), Configuration.get().enabled); + _mbo = mbo; _dispose = Disposable.Create( bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s), bus.subscribe(SparkTags.ShowLadderTag).OnDispatcher().Subscribe(s => show_windows(new[] { s })), @@ -56,7 +67,7 @@ namespace bts.shell { IShellWindow create_ladder_window(SecurityMD md, LadderSettings state_settings) { var id = Interlocked.Increment(ref _ladder_count) % Environment.ProcessorCount; var view = new Lazy(() => { - var model = new LadderModel(md, _orders_model, _md_auxiliary_model); + var model = new LadderModel(md, _orders_model, _md_auxiliary_model, _mbo); var settings_manager = new WindowSettingsManager( _settings_hub, state_settings == null || state_settings.use_defaults ? null : state_settings, us => sanitize_ladder_settings(us.ladder), diff --git a/src/client/spark/Modules/Trading/TradingShellModule.cs b/src/client/spark/Modules/Trading/TradingShellModule.cs index e824de727..cdd252f13 100644 --- a/src/client/spark/Modules/Trading/TradingShellModule.cs +++ b/src/client/spark/Modules/Trading/TradingShellModule.cs @@ -21,9 +21,18 @@ namespace bts.shell { AlgoStudioWindowFactory _aswf; [ImportingConstructor] - public TradingShellModule(IBus bus, IWindowManager wm, INotificationService notification_service, INotificationServiceDataCache notification_service_data_cache, - UserSettingsHub settings_hub, OrdersModel orders_model, PAndLModel pandl_model, MarketDataAuxiliaryModel md_auxiliary_model, ErrorReporter error_reporter) { - _lwf = new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, md_auxiliary_model); + public TradingShellModule( + IBus bus, + IWindowManager wm, + INotificationService notification_service, + INotificationServiceDataCache notification_service_data_cache, + UserSettingsHub settings_hub, + OrdersModel orders_model, + PAndLModel pandl_model, + MarketDataAuxiliaryModel md_auxiliary_model, + md.MBOService mbo, + ErrorReporter error_reporter) { + _lwf = new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, md_auxiliary_model, mbo); _obwf = new OrderBookWindowFactory(this, bus, notification_service, notification_service_data_cache, orders_model, settings_hub); _fwf = new FillsWindowFactory(this, bus, settings_hub, orders_model); _plwf = new PAndLWindowFactory(this, bus, settings_hub, pandl_model); diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index 97e8f73a5..8220c13ed 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -1,6 +1,7 @@ using bts; using bts.api; using bts.api.md.auxiliary; +using bts.md; using bts.utils; using mbts.co2; using mbts.ui; @@ -16,6 +17,7 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Reactive.Linq; +using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; @@ -271,8 +273,9 @@ namespace mbts.spark { Focus(); var point = e.GetPosition(this); var column = _column_for_point(point); - if (column.column_type == ColumnType.Price && e.ChangedButton == MouseButton.Middle) - _scroll_to_center(); + if (column.column_type == ColumnType.Price && e.ChangedButton == MouseButton.Middle) { + show_mbo_popup(point).ignore(); + } else if (_settings != null) { var price = price_for_point(point); Side? bs = null; @@ -283,13 +286,37 @@ namespace mbts.spark { if (bs.HasValue) { using (_tactile_adorner.show_busy(_row_for_point(point), bs.Value == Side.Buy ? ColumnType.Bid : ColumnType.Ask)) await Command.ExecuteAsync(pbs); - } else + } + else { Command.Execute(pbs); + } } } base.OnMouseDown(e); } + private async Task show_mbo_popup(Point point) { + var price = price_for_point(point); + var data = + await _vm.model.mbo_service.get_orders_for_security_async(new MBOSecurityQuery { + SecurityId = _vm.model.security.Id, + PriceLevel = price, + Limit = 256 + }); + if (data.success) { + var popup = new AutoClosePopup { + PlacementTarget = this, + PlacementRectangle = new Rect(point, point), + IsOpen = true, + Child = new Border { + BorderBrush = Brushes.Black, + BorderThickness = new Thickness(1.0), + Child = new MBODetailView(data.value.Orders) + } + }; + } + } + protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { var column = _column_for_point(e.GetPosition(this)); if (column.column_type == ColumnType.Price) diff --git a/src/client/spark/view/Spark/Ladder/LadderModel.cs b/src/client/spark/view/Spark/Ladder/LadderModel.cs index 7576b8374..7746aa5d6 100644 --- a/src/client/spark/view/Spark/Ladder/LadderModel.cs +++ b/src/client/spark/view/Spark/Ladder/LadderModel.cs @@ -1,5 +1,6 @@ using bts; using bts.api; +using bts.md; using mbts.co2; using System.Threading.Tasks; @@ -8,10 +9,11 @@ namespace mbts.spark { readonly OrdersModel _order_gateway; readonly MarketDataAuxiliaryModel _md_auxiliary_model; - public LadderModel(SecurityMD source, OrdersModel ordergw, MarketDataAuxiliaryModel md_auxiliary_model) { + public LadderModel(SecurityMD source, OrdersModel ordergw, MarketDataAuxiliaryModel md_auxiliary_model, MBOService mbo) { security_md = source; _order_gateway = ordergw; _md_auxiliary_model = md_auxiliary_model; + this.mbo_service = mbo; } public enum CancelType { All, Bids, Asks } @@ -22,6 +24,8 @@ namespace mbts.spark { public OrdersModel order_gateway => _order_gateway; public MarketDataAuxiliaryModel md_auxiliary_model => _md_auxiliary_model; + public MBOService mbo_service { get; } + public Task cancel_orders(CancelType ct) { switch (ct) { case CancelType.All: return _order_gateway.cancel_security_orders(security.Id); diff --git a/src/client/spark/view/Spark/Ladder/LadderOrdersHost.cs b/src/client/spark/view/Spark/Ladder/LadderOrdersHost.cs index 131f54707..07ead43b5 100644 --- a/src/client/spark/view/Spark/Ladder/LadderOrdersHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderOrdersHost.cs @@ -72,8 +72,7 @@ namespace mbts.spark { panel.Children.Remove(item); } } - } //else - //Log.Ui.warn($"Failed to remove order ({order.id}): order not in {nameof(LadderOrdersHost)}'s {nameof(_orders)}."); + } } public void clear_orders() { @@ -187,11 +186,8 @@ namespace mbts.spark { Margin = Badge.DefaultMargin, Orientation = Orientation.Horizontal, MaxWidth = _col_width - //MaxHeight = _row_height, - //ClipToBounds = true }; - //var view_box = new Viewbox { Child = panel, Width = _col_width, Height = _row_height }; _position_panel(panel, price); _stacks[price] = new PriceCellComponents(panel); Children.Add(panel); diff --git a/src/client/spark/view/Spark/Ladder/LadderVM.cs b/src/client/spark/view/Spark/Ladder/LadderVM.cs index b32e25417..aaa50ab03 100644 --- a/src/client/spark/view/Spark/Ladder/LadderVM.cs +++ b/src/client/spark/view/Spark/Ladder/LadderVM.cs @@ -236,7 +236,7 @@ namespace mbts.spark { // we return only entries who have piqs and whose piqs are not uint.Max // uint.Max happens when the server is restarted but the client is still up // maybe long term we don't show this data while the exchange connection is down - public IEnumerable<(double, uint)> price_vs_piq => _slot_price_vs_orders.Values.Where(result => result.min_piq.HasValue && result.min_piq.Value != uint.MaxValue).Select(o => (o.price, o.min_piq.Value)); + public IEnumerable<(double, uint)> price_vs_piq => _slot_price_vs_orders.Values.Where(result => result.min_piq.HasValue && result.min_piq.Value != uint.MaxValue).Select(o => (o.price, o.min_piq.Value)); public bool is_synthetic => _model.security.ContractCase == Security.ContractOneofCase.Synthetic; Property _status; @@ -383,8 +383,8 @@ namespace mbts.spark { } void _show_book() => - _bus.post(SparkTags.ShowOrderBookTag, new bts.shell.OrderBookWindowFactory.OrderBookStartupData { - filters = new bts.shell.OrderBookWindowFactory.FilterStates { + _bus.post(SparkTags.ShowOrderBookTag, new OrderBookWindowFactory.OrderBookStartupData { + filters = new OrderBookWindowFactory.FilterStates { security_criteria = new SecurityCriteria(security) } }); diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs new file mode 100644 index 000000000..76204b1c8 --- /dev/null +++ b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs @@ -0,0 +1,33 @@ +using System.Windows; +using System.Windows.Media; +using System.Collections.Generic; +using bts.api.orderman; +using System.Linq; +using bts.md; +using bts; +using mbts.ui; +using System.Windows.Input; + +namespace mbts.spark { + internal class MBODetailView : UIElement { + IEnumerable _orders; + + public MBODetailView(IEnumerable orders) { + _orders = orders; + } + + protected override Size MeasureCore(Size availableSize) { + return new Size(100, 100); + } + + protected override void OnRender(DrawingContext dc) { + base.OnRender(dc); + dc.DrawRectangle(Brushes.Purple, null, new Rect(0, 0, 100, 100)); + int count = 0; + foreach (var pos in _orders) { + ++count; + dc.DrawRectangle(Brushes.Black, null, new Rect(0, count*4, pos.Size * 2, 2)); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Utility/AutoClosePopup.cs b/src/client/spark/view/Utility/AutoClosePopup.cs new file mode 100644 index 000000000..c69a5d78b --- /dev/null +++ b/src/client/spark/view/Utility/AutoClosePopup.cs @@ -0,0 +1,39 @@ +using bts; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; +using System.Windows.Threading; + +namespace mbts.ui.controls { + class AutoClosePopup : System.Windows.Controls.Primitives.Popup { + public AutoClosePopup() { } + + public new FrameworkElement Child { + get => base.Child as FrameworkElement; + set { + var old_child = Child; + base.Child = value; + hook_child_events(value); + } + } + + private void hook_child_events(FrameworkElement fe) { + fe.Loaded += Child_Loaded; + fe.MouseDown += Child_MouseDown; + } + + private void Child_MouseDown(object sender, MouseButtonEventArgs e) { + if (!e.Handled) { + IsOpen = false; + } + } + + private void Child_Loaded(object sender, RoutedEventArgs e) { + var cap = ((FrameworkElement)sender).CaptureMouse(); + } + } +} diff --git a/src/client/sparkcmd/Cmd/MBOCommand.cs b/src/client/sparkcmd/Cmd/MBOCommand.cs index c7a828e4d..3e8c8fa3f 100644 --- a/src/client/sparkcmd/Cmd/MBOCommand.cs +++ b/src/client/sparkcmd/Cmd/MBOCommand.cs @@ -23,26 +23,14 @@ namespace bts { return 0; } - static void dump_mbo(UInt32 key, api.Side side) { + static void dump_mbo(uint key, api.Side side) { using (var ctx = new ServiceContext()) { var mbo = ctx.locate(); var data = mbo.get_orders_for_security(new MBOSecurityQuery { SecurityId = key }); Console.WriteLine($"Order data for {data.SecurityId}"); - IEnumerable orders = data.Bid; - switch(side) { - case api.Side.Undefined: - orders = data.Ask.Concat(data.Bid); - break; - case api.Side.Buy: - orders = data.Bid; - break; - case api.Side.Sell: - orders = data.Ask; - break; - } var price = 0.0; - foreach(var e in orders) { + foreach(var e in data.Orders) { if (e.Price != price) { price = e.Price; Console.WriteLine("================"); diff --git a/src/lib/api/services/MBOService.proto b/src/lib/api/services/MBOService.proto index 7ceabb12c..67ed0d08b 100644 --- a/src/lib/api/services/MBOService.proto +++ b/src/lib/api/services/MBOService.proto @@ -13,16 +13,17 @@ message OrderPIQ { message OrderPosition { uint64 exchange_id = 1; uint32 order_id = 2; - float price = 10; + double price = 10; int32 size = 11; } message PositionData { uint32 security_id = 1; - repeated OrderPosition bid = 10; - repeated OrderPosition ask = 20; + repeated OrderPosition orders = 10; } message MBOSecurityQuery { uint32 security_id = 1; + double price_level = 2; + uint32 limit = 3; } service MBOService { diff --git a/src/lib/md/MBOServiceServer.cpp b/src/lib/md/MBOServiceServer.cpp index 6cabb35a0..84fa9eeb0 100644 --- a/src/lib/md/MBOServiceServer.cpp +++ b/src/lib/md/MBOServiceServer.cpp @@ -307,27 +307,38 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, reverse.insert(std::make_pair(pair.second.exchange_id(), pair.first)); } + size_t count = 0; if(handle.is_initialized()) { auto mbo = handle.get_mbo(); if (mbo) { for (const auto& o : mbo->bids) { - auto* entry = response.add_bid(); - entry->set_exchange_id(o.id.value()); - entry->set_price(o.price.price()); - entry->set_size(o.size); - auto iter = reverse.find(o.id); - if (iter != reverse.end()) { - entry->set_order_id(iter->second.value()); + double price = o.price.price(); + if (os::is_nan(request.price_level()) || request.price_level() == price) { + ++count; + if (request.limit() && count > request.limit()) break; + auto* entry = response.add_orders(); + entry->set_exchange_id(o.id.value()); + entry->set_price(price); + entry->set_size(o.size); + auto iter = reverse.find(o.id); + if (iter != reverse.end()) { + entry->set_order_id(iter->second.value()); + } } } for (const auto& o : mbo->asks) { - auto* entry = response.add_ask(); - entry->set_exchange_id(o.id.value()); - entry->set_price(o.price.price()); - entry->set_size(o.size); - auto iter = reverse.find(o.id); - if (iter != reverse.end()) { - entry->set_order_id(iter->second.value()); + double price = o.price.price(); + if (os::is_nan(request.price_level()) || request.price_level() == price) { + ++count; + if (request.limit() && count > request.limit()) break; + auto* entry = response.add_orders(); + entry->set_exchange_id(o.id.value()); + entry->set_price(o.price.price()); + entry->set_size(o.size); + auto iter = reverse.find(o.id); + if (iter != reverse.end()) { + entry->set_order_id(iter->second.value()); + } } } } From 96572539a7647a27d4a2dbc710c82bca4b935da6 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 9 May 2019 13:05:47 -0400 Subject: [PATCH 02/21] SPARK-2381 View MBO in ladder --- .../spark/view/Spark/Ladder/LadderGridHost.cs | 42 ++++---- .../view/Spark/Ladder/MBO/MBODetailView.cs | 101 ++++++++++++++++-- .../spark/view/Utility/AutoClosePopup.cs | 12 +-- src/lib/config/protos/UI.proto | 1 + src/lib/md/MBOServiceServer.cpp | 10 +- 5 files changed, 127 insertions(+), 39 deletions(-) diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index 8220c13ed..867ebff23 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -3,6 +3,7 @@ using bts.api; using bts.api.md.auxiliary; using bts.md; using bts.utils; +using bts.config; using mbts.co2; using mbts.ui; using mbts.ui.controls; @@ -23,6 +24,7 @@ using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; +using mbts.config; namespace mbts.spark { partial class LadderGridHost : Control { @@ -274,7 +276,7 @@ namespace mbts.spark { var point = e.GetPosition(this); var column = _column_for_point(point); if (column.column_type == ColumnType.Price && e.ChangedButton == MouseButton.Middle) { - show_mbo_popup(point).ignore(); + show_mbo_popup(point); } else if (_settings != null) { var price = price_for_point(point); @@ -295,26 +297,24 @@ namespace mbts.spark { base.OnMouseDown(e); } - private async Task show_mbo_popup(Point point) { - var price = price_for_point(point); - var data = - await _vm.model.mbo_service.get_orders_for_security_async(new MBOSecurityQuery { - SecurityId = _vm.model.security.Id, - PriceLevel = price, - Limit = 256 - }); - if (data.success) { - var popup = new AutoClosePopup { - PlacementTarget = this, - PlacementRectangle = new Rect(point, point), - IsOpen = true, - Child = new Border { - BorderBrush = Brushes.Black, - BorderThickness = new Thickness(1.0), - Child = new MBODetailView(data.value.Orders) - } - }; - } + private void show_mbo_popup(Point point) { + var query = new MBOSecurityQuery { + SecurityId = _vm.model.security.Id, + PriceLevel = price_for_point(point), + Limit = Configuration.get().max_mbo_orders + }; + var view = new MBODetailView(_vm.model.mbo_service, _vm.model.security.ContractSpec, query); + var popup = new AutoClosePopup { + PlacementTarget = this, + PlacementRectangle = new Rect(point, point), + IsOpen = true, + Child = new Border { + BorderBrush = Brushes.Black, + BorderThickness = new Thickness(0.5), + Child = view + } + }; + view.RequestClose += (o, _) => popup.IsOpen = false; } protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs index 76204b1c8..8b72f9330 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs @@ -7,26 +7,115 @@ using bts.md; using bts; using mbts.ui; using System.Windows.Input; +using System.Threading.Tasks; +using System; +using mbts.ui.utility.text; +using bts.api; namespace mbts.spark { - internal class MBODetailView : UIElement { + struct DrawParams { + public Size size; + public double scale; + public double max; + } + + internal class MBODetailView : UIElement, IRequestViewClose { + readonly MBOService _mbo; + readonly Brush _background = BTSColors.LadderSpecial.default_column_background; + readonly ContractSpecificationImmutable _spec; + DrawParams _dp = new DrawParams() { + size = new Size(200, 50), + scale = 1.0 + }; IEnumerable _orders; - public MBODetailView(IEnumerable orders) { - _orders = orders; + FormattedText _header; + FormattedText _footer = TextUtils.GetFormattedText("le footeur"); + + public MBODetailView(MBOService mbo, ContractSpecificationImmutable spec, MBOSecurityQuery query) { + _mbo = mbo; + _orders = Enumerable.Empty(); + _spec = spec; + _header = TextUtils.GetFormattedText($"Orders at {_spec.format(query.PriceLevel)}"); + load_orders(query).ignore(); + } + public event EventHandler RequestClose; + + public async Task load_orders(MBOSecurityQuery query) { + var data = await _mbo.get_orders_for_security_async(query); + if (data.success && data.value.Orders.Count > 0) { + _orders = data.value.Orders; + _header = TextUtils.GetFormattedText($"{data.value.Orders.Count} Orders at {_spec.format(query.PriceLevel)}"); + _dp = compute_dimensions(_orders, _header.Height); + InvalidateMeasure(); + } + else { + RequestClose?.Invoke(this, null); + } + } + static DrawParams compute_dimensions(IEnumerable orders, double header_size) { + var count = orders.Count(); + var max = orders.Max(o => o.Size); + // We want the width to stretch between about 100px to 400px + double width = 200.0; + double scale = width / max; + return new DrawParams { + // top/bottom padding = 2 * text+margin + 10px for grid scale + size = new Size(width + 20, (count * 4) + (2*(header_size+10)+10)), + scale = 200 / max, + // round up to the nearest 10 + max = (Math.Ceiling(max/10.0)*10.0) + }; } protected override Size MeasureCore(Size availableSize) { - return new Size(100, 100); + return _dp.size; } protected override void OnRender(DrawingContext dc) { base.OnRender(dc); - dc.DrawRectangle(Brushes.Purple, null, new Rect(0, 0, 100, 100)); + // determine bounds + dc.DrawRectangle(_background, null, new Rect(0, 0, _dp.size.Width, _dp.size.Height)); int count = 0; + double start = _header.Height + 10; foreach (var pos in _orders) { ++count; - dc.DrawRectangle(Brushes.Black, null, new Rect(0, count*4, pos.Size * 2, 2)); + // 2px wide lines ever 4px + var brush = pos.OrderId == 0 ? BTSColors.text_default_brush : BTSColors.MarketData.ask_brush; + dc.DrawRectangle(brush, null, new Rect(0, start+count*4, pos.Size * _dp.scale, 1)); + } + // draw header at the top + if (_header != null) dc.DrawText(_header, new Point(5, 5)); + // draw scale at the bottom + draw_scale(dc); + } + + private void draw_scale(DrawingContext dc) { + var pen = new Pen(BTSColors.text_default_brush, 0.5); + var smallTick = 5 * _dp.scale; + if (smallTick > _dp.size.Width) { + // shrink to tick = 1 for very small scales + smallTick = _dp.scale; + } + var largeTick = 2 * smallTick; + var baseline = _dp.size.Height - 20; + dc.DrawLine(pen, new Point(0, baseline), new Point(_dp.size.Width, baseline)); + for (double x = smallTick; x < _dp.size.Width; x += smallTick) { + bool large = x % largeTick == 0; + var tickLength = large ? 6.0 : 3.0; + dc.DrawLine(pen, new Point(x, baseline), new Point(x, baseline + tickLength)); + + if (x + smallTick > _dp.size.Width) { + // last tick mark + var size = (int)(x / _dp.scale); + var text = TextUtils.GetFormattedText(size.ToString(), 9.0); + var left = x - text.Width / 2; + var right = left + text.Width/2; + if (right > _dp.size.Width) { + left -= (right - _dp.size.Width); + } + dc.DrawText(text, new Point(x - text.Width / 2, baseline + tickLength + 2)); + } } } } diff --git a/src/client/spark/view/Utility/AutoClosePopup.cs b/src/client/spark/view/Utility/AutoClosePopup.cs index c69a5d78b..ec57040cf 100644 --- a/src/client/spark/view/Utility/AutoClosePopup.cs +++ b/src/client/spark/view/Utility/AutoClosePopup.cs @@ -1,12 +1,5 @@ -using bts; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; +using System.Windows; using System.Windows.Input; -using System.Windows.Threading; namespace mbts.ui.controls { class AutoClosePopup : System.Windows.Controls.Primitives.Popup { @@ -24,6 +17,9 @@ namespace mbts.ui.controls { private void hook_child_events(FrameworkElement fe) { fe.Loaded += Child_Loaded; fe.MouseDown += Child_MouseDown; + if (fe is IRequestViewClose vc) { + vc.RequestClose += (o,_) => IsOpen = false; + } } private void Child_MouseDown(object sender, MouseButtonEventArgs e) { diff --git a/src/lib/config/protos/UI.proto b/src/lib/config/protos/UI.proto index cb228c2f3..579701ce5 100644 --- a/src/lib/config/protos/UI.proto +++ b/src/lib/config/protos/UI.proto @@ -57,6 +57,7 @@ message LadderKnobs { optional uint32 max_open_ladders = 4 [default = 75]; optional uint32 security_timeout_secs = 5 [default = 60]; optional bool open_algo_popup_on_select = 6 [default = false]; + optional uint32 max_mbo_orders = 7 [default = 200]; } message ShellPingOptions { diff --git a/src/lib/md/MBOServiceServer.cpp b/src/lib/md/MBOServiceServer.cpp index 84fa9eeb0..70eb77e8a 100644 --- a/src/lib/md/MBOServiceServer.cpp +++ b/src/lib/md/MBOServiceServer.cpp @@ -313,12 +313,13 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, if (mbo) { for (const auto& o : mbo->bids) { double price = o.price.price(); - if (os::is_nan(request.price_level()) || request.price_level() == price) { + bool isnan = os::is_nan(request.price_level()); + if (isnan || request.price_level() == price) { ++count; if (request.limit() && count > request.limit()) break; auto* entry = response.add_orders(); entry->set_exchange_id(o.id.value()); - entry->set_price(price); + if (isnan) entry->set_price(price); entry->set_size(o.size); auto iter = reverse.find(o.id); if (iter != reverse.end()) { @@ -328,12 +329,13 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, } for (const auto& o : mbo->asks) { double price = o.price.price(); - if (os::is_nan(request.price_level()) || request.price_level() == price) { + bool isnan = os::is_nan(request.price_level()); + if (isnan || request.price_level() == price) { ++count; if (request.limit() && count > request.limit()) break; auto* entry = response.add_orders(); entry->set_exchange_id(o.id.value()); - entry->set_price(o.price.price()); + if (isnan) entry->set_price(price); entry->set_size(o.size); auto iter = reverse.find(o.id); if (iter != reverse.end()) { From dd049374d7693be89f2126ff9877d2e95fc9e889 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 9 May 2019 14:26:14 -0400 Subject: [PATCH 03/21] Fix equality comparison between mbo price levels --- src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs | 2 +- src/lib/md/MBOServiceServer.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs index 8b72f9330..83402b47a 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs @@ -105,7 +105,7 @@ namespace mbts.spark { var tickLength = large ? 6.0 : 3.0; dc.DrawLine(pen, new Point(x, baseline), new Point(x, baseline + tickLength)); - if (x + smallTick > _dp.size.Width) { + if (x + smallTick >= _dp.size.Width) { // last tick mark var size = (int)(x / _dp.scale); var text = TextUtils.GetFormattedText(size.ToString(), 9.0); diff --git a/src/lib/md/MBOServiceServer.cpp b/src/lib/md/MBOServiceServer.cpp index 70eb77e8a..3ba0f9f66 100644 --- a/src/lib/md/MBOServiceServer.cpp +++ b/src/lib/md/MBOServiceServer.cpp @@ -4,6 +4,7 @@ #include "lib/api/services/OrderService.client.pb.h" #include "lib/utils/Dispatcher.h" #include "lib/utils/TimeStamp.h" +#include "lib/domain_model/Security.h" #include "MDClient.h" #include "ExchangeOrderKey.h" #include "MBOProcessor.h" @@ -308,13 +309,14 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, } size_t count = 0; + auto tick = handle.get_minimum_tick(); if(handle.is_initialized()) { auto mbo = handle.get_mbo(); if (mbo) { for (const auto& o : mbo->bids) { double price = o.price.price(); bool isnan = os::is_nan(request.price_level()); - if (isnan || request.price_level() == price) { + if (isnan || securities::test_price_equality(request.price_level(), price, tick)) { ++count; if (request.limit() && count > request.limit()) break; auto* entry = response.add_orders(); @@ -330,7 +332,7 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, for (const auto& o : mbo->asks) { double price = o.price.price(); bool isnan = os::is_nan(request.price_level()); - if (isnan || request.price_level() == price) { + if (isnan || securities::test_price_equality(request.price_level(), price, tick)) { ++count; if (request.limit() && count > request.limit()) break; auto* entry = response.add_orders(); From 3789d735934a2fbfe351479a5a4c7d1e9510957a Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 9 May 2019 16:25:25 -0400 Subject: [PATCH 04/21] Do not allow minTick to be 0 (infinite loop) --- .../view/Spark/Ladder/MBO/MBODetailView.cs | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs index 83402b47a..38f750be4 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using System; using mbts.ui.utility.text; using bts.api; +using System.Windows.Threading; namespace mbts.spark { struct DrawParams { @@ -28,17 +29,30 @@ namespace mbts.spark { scale = 1.0 }; IEnumerable _orders; - FormattedText _header; FormattedText _footer = TextUtils.GetFormattedText("le footeur"); + DispatcherTimer _timer; + + MBOSecurityQuery _query; public MBODetailView(MBOService mbo, ContractSpecificationImmutable spec, MBOSecurityQuery query) { _mbo = mbo; _orders = Enumerable.Empty(); _spec = spec; + _query = query; _header = TextUtils.GetFormattedText($"Orders at {_spec.format(query.PriceLevel)}"); load_orders(query).ignore(); + _timer = new DispatcherTimer() { + Interval = TimeSpan.FromSeconds(0.25), + IsEnabled = true, + }; + _timer.Tick += timer_Tick; } + + private void timer_Tick(object sender, EventArgs e) { + load_orders(_query).ignore(); + } + public event EventHandler RequestClose; public async Task load_orders(MBOSecurityQuery query) { @@ -53,6 +67,7 @@ namespace mbts.spark { RequestClose?.Invoke(this, null); } } + static DrawParams compute_dimensions(IEnumerable orders, double header_size) { var count = orders.Count(); var max = orders.Max(o => o.Size); @@ -62,7 +77,7 @@ namespace mbts.spark { return new DrawParams { // top/bottom padding = 2 * text+margin + 10px for grid scale size = new Size(width + 20, (count * 4) + (2*(header_size+10)+10)), - scale = 200 / max, + scale = 200.0 / max, // round up to the nearest 10 max = (Math.Ceiling(max/10.0)*10.0) }; @@ -92,7 +107,7 @@ namespace mbts.spark { private void draw_scale(DrawingContext dc) { var pen = new Pen(BTSColors.text_default_brush, 0.5); - var smallTick = 5 * _dp.scale; + var smallTick = Math.Max(5 * _dp.scale, 2); if (smallTick > _dp.size.Width) { // shrink to tick = 1 for very small scales smallTick = _dp.scale; From bee1df45adb9a1c5b7ebe8fa93db0e295455aeb7 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 14 May 2019 11:52:51 -0400 Subject: [PATCH 05/21] SPARK-2430 prioritize draining incremental queue over publishing shapshots --- src/lib/md/MBOProcessor.cpp | 163 +++++++++++++----- src/lib/md/MBOProcessor.h | 10 +- src/server/sparkd/cmds/Run.cpp | 2 +- .../md/platforms/mdp3_onixs/MDP3Listener.cpp | 4 +- 4 files changed, 128 insertions(+), 51 deletions(-) diff --git a/src/lib/md/MBOProcessor.cpp b/src/lib/md/MBOProcessor.cpp index 88cc1f3f2..926d7903a 100644 --- a/src/lib/md/MBOProcessor.cpp +++ b/src/lib/md/MBOProcessor.cpp @@ -1,15 +1,21 @@ #include "MBOProcessor.h" -#include "lib/utils/Dispatcher.h" #include "lib/utils/ConcurrentPool.h" #include "lib/config/config.h" #include "lib/config/protos/toggles.pb.h" +#include "lib/utils/thread_manager.h" #include #include #include #include +#include +#include +#ifndef _WIN32 +#include +#endif #include +#include namespace bts { @@ -57,34 +63,126 @@ void print_pool_stats(const utils::ConcurrentPool& pool) { } typedef tbb::concurrent_hash_map MapType; +struct Incremental { + MBOWorkingState* state; + inc::Update update; +}; struct MBOProcessorImpl { utils::ConcurrentPool pool; + tbb::concurrent_queue incremental_input; MapType snapshots; - utils::Dispatcher& dispatcher; - utils::DispatcherTimer timer; - MBOProcessorImpl(utils::Dispatcher& d) : + bool running; + utils::TimeStamp last_pool_print; + std::thread thread; + + MBOProcessorImpl() : pool(2048,512), snapshots(), - dispatcher(d), - timer(d, 600*1000, [&]() { print_pool_stats(pool); }) - { - if (config::get().enabled()) { - timer.start(); - } + running(true), + last_pool_print(utils::TimeStamp::invalid()), + thread(threading::make_thread("MBO", [=]() { process_incremental(); })) + { + if (config::get().enabled()) { + last_pool_print = utils::TimeStamp::now(); } + + } + + ~MBOProcessorImpl() { + running = false; + thread.join(); + } + + void publish_snapshot(SecurityKey key, MBOSnapshot** snapshot) { + bts_assert(*snapshot != nullptr); + MapType::accessor accessor; + snapshots.insert(accessor, key); + std::swap(accessor->second, *snapshot); + if (*snapshot != nullptr) { + // Note: relase() must happen inside accessor lifetime to ensure correctness + pool.release(snapshot); + } + } + + void publish_incremental(MBOWorkingState& state) { + // determine if we need to publish + auto key = SecurityKey(state.handle.key()); + if (key.value() != invalid_security_key) { + auto snap = pool.allocate(); + snap->bids.reserve(state.bid.size()); + snap->asks.reserve(state.ask.size()); + copy_to_snapshot(state, snap); + publish_snapshot(key, &snap); + } + } + + void process_incremental() { + #ifndef _WIN32 + // drain queue and update state + // insert changed state pointers into a set + // after draining publish the set in small batches + // re-check input queue regularly + + btree::btree_set dirty; + std::vector clean; + + while(running) { + Incremental temp; + + // Drain entire input queue quickly + while(incremental_input.try_pop(temp)) { + bts_assert_d(temp.state != nullptr); + if (temp.state != nullptr) { + apply_incremental(*temp.state, temp.update); + dirty.insert(temp.state); + } + } + + // publish a small batch of snapshots (then check queue again) + for (auto iter = dirty.begin(); iter != dirty.end(); ++iter) { + publish_incremental(**iter); + clean.push_back(*iter); + if (clean.size() >= 128) break; + } + + // Remove 'clean' from set + for (const auto& iter : clean) { + dirty.erase(iter); + } + clean.clear(); + + // If the queue is still empty sleep briefly + if (incremental_input.empty()) { + if (last_pool_print != TimeStamp::invalid()) { + auto now = TimeStamp::now(); + if ((now - last_pool_print).seconds() > 600) { + last_pool_print = now; + print_pool_stats(pool); + } + } + std::this_thread::sleep_for( + std::chrono::milliseconds(1) + ); + } + + } + #endif + } + }; // // Processor -MBOProcessor::MBOProcessor(utils::Dispatcher* d) : - _me(std::make_shared(d == nullptr ? utils::Dispatcher::background() : *d)), - _producer(_me), - _consumer(_me) -{} +MBOProcessor::MBOProcessor() : + _me(std::make_shared()), + _writer(_me), + _reader(_me) +{ +} -MBOWriter& MBOProcessor::writer() { return _producer;} -MBOReader& MBOProcessor::reader() { return _consumer; } +MBOWriter& MBOProcessor::writer() { return _writer;} +MBOReader& MBOProcessor::reader() { return _reader; } // // Writer @@ -98,18 +196,11 @@ void MBOWriter::release_snapshot(MBOSnapshot** s) { _me->pool.release(s); } void MBOWriter::publish_snapshot(SecurityKey key, MBOSnapshot** snapshot) { - bts_assert(*snapshot != nullptr); - MapType::accessor accessor; - _me->snapshots.insert(accessor, key); - std::swap(accessor->second, *snapshot); - if (*snapshot != nullptr) { - // Note: relase() must happen inside accessor lifetime to ensure correctness - _me->pool.release(snapshot); - } + _me->publish_snapshot(key,snapshot); } +#if 0 bool MBOWriter::validate_snapshot(uint32_t exchid, SecurityKey key, MBOSnapshot* control) { - // bts_assert_msg(false, "TO USE THIS VALIDATION YOU MUST MAKE enqueue_incremental SYNCRONOUS"); #define REQUIRE(a,b,y) \ if ((a) != (b)) { \ LOG(md,Error, "Validation error exch:{} sec:{} {}!={} other:{}", exchid, key.value(), a, b, y); \ @@ -137,25 +228,11 @@ bool MBOWriter::validate_snapshot(uint32_t exchid, SecurityKey key, MBOSnapshot* #undef REQUIRE return true; } +#endif void MBOWriter::enqueue_incremental(MBOWorkingState& state, const inc::Update& update) { LOG(md,Diag, "sec:{} : {}", state.handle.key(), update); - - _me->dispatcher.post([this,&state,update]() { - // fast part - apply_incremental(state,update); - // slow part - publish_incremental(state); - }); -} -void MBOWriter::publish_incremental(MBOWorkingState& state) { - // determine if we need to publish - auto key = SecurityKey(state.handle.key()); - if (key.value() != invalid_security_key) { - auto snap = allocate_snapshot(state.bid.size(), state.ask.size()); - copy_to_snapshot(state, snap); - publish_snapshot(key, &snap); - } + _me->incremental_input.push({&state, update}); } void copy_to_snapshot(MBOWorkingState& state, MBOSnapshot* dest) { @@ -267,4 +344,4 @@ ostream& operator<<(ostream& os, const inc::Update& update) { return os; } -} \ No newline at end of file +} diff --git a/src/lib/md/MBOProcessor.h b/src/lib/md/MBOProcessor.h index f3a92b59b..de36b3931 100644 --- a/src/lib/md/MBOProcessor.h +++ b/src/lib/md/MBOProcessor.h @@ -2,7 +2,6 @@ #include "lib/domain_model/SecurityKey.h" #include "lib/domain_model/Security.h" #include "lib/utils/TimeStamp.h" -#include "lib/utils/Dispatcher.h" #include "IntPrice.h" #include "ExchangeOrderKey.h" #include "MDProducerHandle.h" @@ -152,8 +151,6 @@ class MBOWriter { // Enqueue the update to the mbo work queue. void enqueue_incremental(MBOWorkingState&, const inc::Update&); - // Update working state and publish directly. - void publish_incremental(MBOWorkingState&); }; class MBOReader { @@ -169,11 +166,11 @@ class MBOReader { class MBOProcessor { std::shared_ptr _me; - MBOWriter _producer; - MBOReader _consumer; + MBOWriter _writer; + MBOReader _reader; public: - MBOProcessor(utils::Dispatcher* _=nullptr); + MBOProcessor(); MBOWriter& writer(); MBOReader& reader(); }; @@ -184,3 +181,4 @@ public: namespace std { std::ostream& operator<<(std::ostream& os, const bts::md::inc::Update&); } + diff --git a/src/server/sparkd/cmds/Run.cpp b/src/server/sparkd/cmds/Run.cpp index 547e04fc0..f1df545c4 100644 --- a/src/server/sparkd/cmds/Run.cpp +++ b/src/server/sparkd/cmds/Run.cpp @@ -60,7 +60,7 @@ int Run::execute(std::vector const &) { persistence::PersistenceServiceServer settings_saver(sc, "settings"); user::AuthServiceServer login_server(sc); - md::MBOProcessor mbo(&utils::Dispatcher::get_named("MBO")); + md::MBOProcessor mbo; auto* mbowriter = config::get().enabled() ? &mbo.writer() : nullptr; md::run_market_datapublishers(mbowriter); diff --git a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp index b06b185f7..7276310a3 100644 --- a/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp +++ b/src/server/sparkd/md/platforms/mdp3_onixs/MDP3Listener.cpp @@ -120,7 +120,8 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con onBookUpdate(sec, book, book_type_implied); } -void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, const onixs::MboBook& book) { +void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::MboBook& ) { + #if 0 if (_mbo) { auto data = _index.get_security(sec.id()); if (data == nullptr) return; @@ -136,6 +137,7 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con } _mbo->validate_snapshot(sec.id(), SecurityKey(key), snapshot); } + #endif } // From 6f630a0e62377d37285574d1dd1f9ae5532a14da Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Tue, 14 May 2019 17:03:17 -0400 Subject: [PATCH 06/21] MBOService should indicate bid/ask --- src/client/sparkcmd/Cmd/MBOCommand.cs | 2 +- src/lib/api/services/MBOService.proto | 3 ++- src/lib/md/MBOServiceServer.cpp | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/client/sparkcmd/Cmd/MBOCommand.cs b/src/client/sparkcmd/Cmd/MBOCommand.cs index 3e8c8fa3f..6a73ec2e3 100644 --- a/src/client/sparkcmd/Cmd/MBOCommand.cs +++ b/src/client/sparkcmd/Cmd/MBOCommand.cs @@ -30,7 +30,7 @@ namespace bts { Console.WriteLine($"Order data for {data.SecurityId}"); var price = 0.0; - foreach(var e in data.Orders) { + foreach(var e in data.Bid.Concat(data.Ask)) { if (e.Price != price) { price = e.Price; Console.WriteLine("================"); diff --git a/src/lib/api/services/MBOService.proto b/src/lib/api/services/MBOService.proto index 67ed0d08b..af8e89d56 100644 --- a/src/lib/api/services/MBOService.proto +++ b/src/lib/api/services/MBOService.proto @@ -18,7 +18,8 @@ message OrderPosition { } message PositionData { uint32 security_id = 1; - repeated OrderPosition orders = 10; + repeated OrderPosition bid = 10; + repeated OrderPosition ask = 11; } message MBOSecurityQuery { uint32 security_id = 1; diff --git a/src/lib/md/MBOServiceServer.cpp b/src/lib/md/MBOServiceServer.cpp index 3ba0f9f66..5141fda31 100644 --- a/src/lib/md/MBOServiceServer.cpp +++ b/src/lib/md/MBOServiceServer.cpp @@ -319,7 +319,7 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, if (isnan || securities::test_price_equality(request.price_level(), price, tick)) { ++count; if (request.limit() && count > request.limit()) break; - auto* entry = response.add_orders(); + auto* entry = response.add_bid(); entry->set_exchange_id(o.id.value()); if (isnan) entry->set_price(price); entry->set_size(o.size); @@ -335,7 +335,7 @@ void MBOServiceServer::get_orders_for_security(const MBOSecurityQuery& request, if (isnan || securities::test_price_equality(request.price_level(), price, tick)) { ++count; if (request.limit() && count > request.limit()) break; - auto* entry = response.add_orders(); + auto* entry = response.add_ask(); entry->set_exchange_id(o.id.value()); if (isnan) entry->set_price(price); entry->set_size(o.size); From 06520791faa1ed5ca35b8dc9026ad206a7185496 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Wed, 15 May 2019 16:32:26 -0400 Subject: [PATCH 07/21] SPARK-2444 MBO UI polish --- src/client/spark/Spark.csproj | 4 + .../spark/view/Spark/Ladder/LadderGridHost.cs | 42 +++--- .../view/Spark/Ladder/MBO/MBODetailView.cs | 137 ------------------ .../view/Spark/Ladder/MBO/MBOPopupModel.cs | 127 ++++++++++++++++ .../view/Spark/Ladder/MBO/MBOPopupView.cs | 116 +++++++++++++++ .../Ladder/MBO/PositionDataExtensions.cs | 19 +++ 6 files changed, 289 insertions(+), 156 deletions(-) delete mode 100644 src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs create mode 100644 src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs create mode 100644 src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs create mode 100644 src/client/spark/view/Spark/Ladder/MBO/PositionDataExtensions.cs diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index dbf62a939..be22f1613 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -57,6 +57,7 @@ + @@ -79,6 +80,9 @@ Code + + Code + diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index 867ebff23..786e6b07b 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -276,7 +276,7 @@ namespace mbts.spark { var point = e.GetPosition(this); var column = _column_for_point(point); if (column.column_type == ColumnType.Price && e.ChangedButton == MouseButton.Middle) { - show_mbo_popup(point); + show_mbo_popup(point).ignore(); } else if (_settings != null) { var price = price_for_point(point); @@ -297,24 +297,28 @@ namespace mbts.spark { base.OnMouseDown(e); } - private void show_mbo_popup(Point point) { - var query = new MBOSecurityQuery { - SecurityId = _vm.model.security.Id, - PriceLevel = price_for_point(point), - Limit = Configuration.get().max_mbo_orders - }; - var view = new MBODetailView(_vm.model.mbo_service, _vm.model.security.ContractSpec, query); - var popup = new AutoClosePopup { - PlacementTarget = this, - PlacementRectangle = new Rect(point, point), - IsOpen = true, - Child = new Border { - BorderBrush = Brushes.Black, - BorderThickness = new Thickness(0.5), - Child = view - } - }; - view.RequestClose += (o, _) => popup.IsOpen = false; + private async Task show_mbo_popup(Point point) { + var query = MBOPopupModel.default_query.with( + security_id: _vm.model.security.Id, + price_level: price_for_point(point) + ); + var model = new MBOPopupModel(_vm.model.mbo_service, _vm.model.security, query); + // Load the first set of orders so we know if there are any before showing the popup + var result = await model.load_orders(); + if (result.success && result.value.orders.Count() > 0) { + var view = new MBOPopupView(model, result.value); + var popup = new AutoClosePopup { + PlacementTarget = this, + PlacementRectangle = new Rect(point, point), + IsOpen = true, + Child = new Border { + BorderBrush = Brushes.Black, + BorderThickness = new Thickness(0.5), + Child = view, + } + }; + view.RequestClose += (o, _) => popup.IsOpen = false; + } } protected override void OnMouseDoubleClick(MouseButtonEventArgs e) { diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs deleted file mode 100644 index 38f750be4..000000000 --- a/src/client/spark/view/Spark/Ladder/MBO/MBODetailView.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System.Windows; -using System.Windows.Media; -using System.Collections.Generic; -using bts.api.orderman; -using System.Linq; -using bts.md; -using bts; -using mbts.ui; -using System.Windows.Input; -using System.Threading.Tasks; -using System; -using mbts.ui.utility.text; -using bts.api; -using System.Windows.Threading; - -namespace mbts.spark { - struct DrawParams { - public Size size; - public double scale; - public double max; - } - - internal class MBODetailView : UIElement, IRequestViewClose { - readonly MBOService _mbo; - readonly Brush _background = BTSColors.LadderSpecial.default_column_background; - readonly ContractSpecificationImmutable _spec; - DrawParams _dp = new DrawParams() { - size = new Size(200, 50), - scale = 1.0 - }; - IEnumerable _orders; - FormattedText _header; - FormattedText _footer = TextUtils.GetFormattedText("le footeur"); - DispatcherTimer _timer; - - MBOSecurityQuery _query; - - public MBODetailView(MBOService mbo, ContractSpecificationImmutable spec, MBOSecurityQuery query) { - _mbo = mbo; - _orders = Enumerable.Empty(); - _spec = spec; - _query = query; - _header = TextUtils.GetFormattedText($"Orders at {_spec.format(query.PriceLevel)}"); - load_orders(query).ignore(); - _timer = new DispatcherTimer() { - Interval = TimeSpan.FromSeconds(0.25), - IsEnabled = true, - }; - _timer.Tick += timer_Tick; - } - - private void timer_Tick(object sender, EventArgs e) { - load_orders(_query).ignore(); - } - - public event EventHandler RequestClose; - - public async Task load_orders(MBOSecurityQuery query) { - var data = await _mbo.get_orders_for_security_async(query); - if (data.success && data.value.Orders.Count > 0) { - _orders = data.value.Orders; - _header = TextUtils.GetFormattedText($"{data.value.Orders.Count} Orders at {_spec.format(query.PriceLevel)}"); - _dp = compute_dimensions(_orders, _header.Height); - InvalidateMeasure(); - } - else { - RequestClose?.Invoke(this, null); - } - } - - static DrawParams compute_dimensions(IEnumerable orders, double header_size) { - var count = orders.Count(); - var max = orders.Max(o => o.Size); - // We want the width to stretch between about 100px to 400px - double width = 200.0; - double scale = width / max; - return new DrawParams { - // top/bottom padding = 2 * text+margin + 10px for grid scale - size = new Size(width + 20, (count * 4) + (2*(header_size+10)+10)), - scale = 200.0 / max, - // round up to the nearest 10 - max = (Math.Ceiling(max/10.0)*10.0) - }; - } - - protected override Size MeasureCore(Size availableSize) { - return _dp.size; - } - - protected override void OnRender(DrawingContext dc) { - base.OnRender(dc); - // determine bounds - dc.DrawRectangle(_background, null, new Rect(0, 0, _dp.size.Width, _dp.size.Height)); - int count = 0; - double start = _header.Height + 10; - foreach (var pos in _orders) { - ++count; - // 2px wide lines ever 4px - var brush = pos.OrderId == 0 ? BTSColors.text_default_brush : BTSColors.MarketData.ask_brush; - dc.DrawRectangle(brush, null, new Rect(0, start+count*4, pos.Size * _dp.scale, 1)); - } - // draw header at the top - if (_header != null) dc.DrawText(_header, new Point(5, 5)); - // draw scale at the bottom - draw_scale(dc); - } - - private void draw_scale(DrawingContext dc) { - var pen = new Pen(BTSColors.text_default_brush, 0.5); - var smallTick = Math.Max(5 * _dp.scale, 2); - if (smallTick > _dp.size.Width) { - // shrink to tick = 1 for very small scales - smallTick = _dp.scale; - } - var largeTick = 2 * smallTick; - var baseline = _dp.size.Height - 20; - dc.DrawLine(pen, new Point(0, baseline), new Point(_dp.size.Width, baseline)); - for (double x = smallTick; x < _dp.size.Width; x += smallTick) { - bool large = x % largeTick == 0; - var tickLength = large ? 6.0 : 3.0; - dc.DrawLine(pen, new Point(x, baseline), new Point(x, baseline + tickLength)); - - if (x + smallTick >= _dp.size.Width) { - // last tick mark - var size = (int)(x / _dp.scale); - var text = TextUtils.GetFormattedText(size.ToString(), 9.0); - var left = x - text.Width / 2; - var right = left + text.Width/2; - if (right > _dp.size.Width) { - left -= (right - _dp.size.Width); - } - dc.DrawText(text, new Point(x - text.Width / 2, baseline + tickLength + 2)); - } - } - } - } -} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs new file mode 100644 index 000000000..85f699bd6 --- /dev/null +++ b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs @@ -0,0 +1,127 @@ +using bts.api; +using bts.api.core; +using bts.md; +using mbts.config; +using mbts.ui.utility.text; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; + +namespace mbts.spark { + public struct MBOPopupData { + public readonly Side side; + public readonly IReadOnlyList orders; + + public MBOPopupData(Side side, IReadOnlyList orders) { + this.side = side; + this.orders = orders; + } + } + public struct MBOPopupDrawParams { + public MBOPopupData data; + public Size size => new Size(300, header.Height + margin.Top + margin.Bottom + (row_height*data.orders.Count) + margin.Bottom); + public FormattedText header; + + public static readonly Thickness margin = new Thickness(10, 5, 5, 5); + + //columns + public double row_height => header.Height + 2; + public double bar_height => 0.6 * row_height; + + public List row_numbers; + public double numbers_width; + public List row_labels; + public double scale; + + // footer + public double footer_height => 20; + } + + public class MBOPopupModel { + const double font_size = 10.0; + readonly MBOService _mbo; + readonly SecurityImmutable _security; + readonly MBOSecurityQueryImmutable _query; + readonly Dictionary _cache; + int _max_order_size = 1; + + public MBOPopupModel(MBOService mbo, SecurityImmutable security, MBOSecurityQueryImmutable query) { + _mbo = mbo; + _security = security; + _query = query; + + // prime the cache with numbers on the left hand side + _cache = + Enumerable.Range(0, (int)default_query.Limit) + .AsParallel() + .Select(i => TextUtils.GetFormattedText(i.ToString(), font_size)) + .ToDictionary(ft => ft.Text); + } + + FormattedText format_text(string s, bool bold=false) { + // cache FormattedText for the life of the popup + if (_cache.TryGetValue(s, out FormattedText ft)) { + return ft; + } + else + ft = bold ? TextUtils.GetFormattedTextBold(s, font_size) : TextUtils.GetFormattedText(s, font_size); + _cache.TryAdd(s, ft); + return ft; + } + + public async Task> load_orders() { + var data = await _mbo.get_orders_for_security_async(_query); + if (data.success) { + var side = data.value.side(); + IEnumerable orders = new OrderPosition[0]; + if (side == Side.Buy) orders = data.value.Bid; + if (side == Side.Sell) orders = data.value.Ask; + return new Result(new MBOPopupData(side, orders.Select(o => (OrderPositionImmutable)o).ToList())); + } + else { + return new Result(data.code); + } + } + + string buy_sell_text(Side side) { + switch (side) { + case Side.Buy: return "BUY"; + case Side.Sell: return "SELL"; + default: + case Side.Undefined: return ""; + } + } + + public MBOPopupDrawParams compute_layout(MBOPopupData p) { + var pdp = new MBOPopupDrawParams { data = p }; + pdp.header = format_text( + $"{buy_sell_text(p.side)} {_security.security_desc()} @ {_security.ContractSpec.format(_query.PriceLevel)}", true); + + var margin = MBOPopupDrawParams.margin; + var text_margin = margin.Left + margin.Right; + + pdp.row_numbers = p.orders.Select((o, i) => format_text(i.ToString())).ToList(); + pdp.numbers_width = (int)pdp.row_numbers.Max(r => r.Width) + text_margin; + pdp.row_labels = p.orders.Select(o => format_text(o.Size.ToString())).ToList(); + var max_label_width = pdp.row_labels.Max(l => l.Width) + text_margin; + + var available_width = pdp.size.Width - pdp.numbers_width - max_label_width; + _max_order_size = Math.Max(p.orders.Max(o => o.Size), _max_order_size); + pdp.scale = available_width / _max_order_size; + + return pdp; + } + + #region static + public static readonly MBOSecurityQueryImmutable default_query = (MBOSecurityQueryImmutable) + new MBOSecurityQuery { + Limit = Configuration.get().max_mbo_orders + }; + #endregion + } + +} diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs new file mode 100644 index 000000000..80243fce9 --- /dev/null +++ b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs @@ -0,0 +1,116 @@ +using System.Windows; +using System.Windows.Media; +using System.Collections.Generic; +using bts.api.orderman; +using System.Linq; +using bts.md; +using bts; +using mbts.ui; +using System.Windows.Input; +using System.Threading.Tasks; +using System; +using mbts.ui.utility.text; +using bts.api; +using System.Windows.Threading; + +namespace mbts.spark { + internal class MBOPopupView : UIElement, IRequestViewClose { + readonly Brush _background = BTSColors.LadderSpecial.default_column_background; + readonly MBOPopupModel _model; + DispatcherTimer _timer; + MBOPopupDrawParams _dp; + + public MBOPopupView(MBOPopupModel model, MBOPopupData p) { + _model = model; + _dp = model.compute_layout(p); + _timer = new DispatcherTimer() { + Interval = TimeSpan.FromSeconds(0.25), + IsEnabled = true, + }; + _timer.Tick += timer_Tick; + } + + private async void timer_Tick(object sender, EventArgs e) { + //NOTE: What if load_orders takes too long? + var result = await _model.load_orders(); + if (result.success && result.value.orders.Count > 0) { + _dp = _model.compute_layout(result.value); + InvalidateVisual(); + } + else RequestClose?.Invoke(this, null); + } + + public event EventHandler RequestClose; + + protected override Size MeasureCore(Size availableSize) { + return _dp.size; + } + + static Thickness margin => MBOPopupDrawParams.margin; + protected override void OnRender(DrawingContext dc) { + base.OnRender(dc); + // draw background + dc.DrawRectangle(_background, null, new Rect(0, 0, _dp.size.Width, _dp.size.Height)); + // draw header + dc.DrawText(_dp.header, new Point(margin.Left, margin.Top)); + // draw grid + draw_grid(dc, _dp, _dp.header.Height + margin.Top + margin.Bottom); + } + + static Brush brush_for(Side side, OrderPositionImmutable order) { + if (order.OrderId != 0) return Brushes.Black; + switch (side) { + case Side.Buy: return BTSColors.MarketData.bid_brush; + case Side.Sell: return BTSColors.MarketData.ask_brush; + default: + return Brushes.DarkGray; + } + } + + static void draw_grid(DrawingContext dc, MBOPopupDrawParams dp, double offset) { + for (int x = 0; x < dp.data.orders.Count(); ++x) { + // draw numbers + var number = dp.row_numbers[x]; + var left_offset = dp.numbers_width - number.Width - 5; + dc.DrawText(number, new Point(left_offset, offset)); + // draw rectangles + var order = dp.data.orders[x]; + var rect = new Rect(dp.numbers_width, offset + (dp.row_height-dp.bar_height)/2, order.Size * dp.scale, dp.bar_height); + dc.DrawRectangle(brush_for(dp.data.side, order), null,rect); + // draw sizes + var label = dp.row_labels[x]; + dc.DrawText(label, new Point(rect.Right+margin.Right, offset)); + offset += dp.row_height; + } + } + + //private void draw_scale(DrawingContext dc) { + // var pen = new Pen(BTSColors.text_default_brush, 0.5); + // var smallTick = Math.Max(5 * _dp.scale, 2); + // if (smallTick > _dp.size.Width) { + // // shrink to tick = 1 for very small scales + // smallTick = _dp.scale; + // } + // var largeTick = 2 * smallTick; + // var baseline = _dp.size.Height - 20; + // dc.DrawLine(pen, new Point(0, baseline), new Point(_dp.size.Width, baseline)); + // for (double x = smallTick; x < _dp.size.Width; x += smallTick) { + // bool large = x % largeTick == 0; + // var tickLength = large ? 6.0 : 3.0; + // dc.DrawLine(pen, new Point(x, baseline), new Point(x, baseline + tickLength)); + + // if (x + smallTick >= _dp.size.Width) { + // // last tick mark + // var size = (int)(x / _dp.scale); + // var text = TextUtils.GetFormattedText(size.ToString(), 9.0); + // var left = x - text.Width / 2; + // var right = left + text.Width/2; + // if (right > _dp.size.Width) { + // left -= (right - _dp.size.Width); + // } + // dc.DrawText(text, new Point(x - text.Width / 2, baseline + tickLength + 2)); + // } + // } + //} + } +} \ No newline at end of file diff --git a/src/client/spark/view/Spark/Ladder/MBO/PositionDataExtensions.cs b/src/client/spark/view/Spark/Ladder/MBO/PositionDataExtensions.cs new file mode 100644 index 000000000..7379ee3de --- /dev/null +++ b/src/client/spark/view/Spark/Ladder/MBO/PositionDataExtensions.cs @@ -0,0 +1,19 @@ +using bts.api; +using bts.md; + +namespace mbts.spark { + static class PositionDataExtensions { + public static Side side(this PositionData pd) { + var bidlen = pd.Bid.Count; + var asklen = pd.Ask.Count; + if (bidlen > 0 && asklen == 0) { + return Side.Buy; + } + else if (asklen > 0 && bidlen == 0) { + return Side.Sell; + } + return Side.Undefined; + } + } + +} From a2d4eb7d1029b9ca585c68ee6ae25b597a16170e Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 10:43:23 -0400 Subject: [PATCH 08/21] SPARK-2444 MBO Polish 2 - the Scrollening --- .../spark/view/Spark/Ladder/LadderGridHost.cs | 6 +- .../view/Spark/Ladder/MBO/MBOPopupModel.cs | 20 ++++--- .../view/Spark/Ladder/MBO/MBOPopupView.cs | 58 +++++-------------- .../spark/view/Utility/AutoClosePopup.cs | 14 ++--- 4 files changed, 38 insertions(+), 60 deletions(-) diff --git a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs index 786e6b07b..26ad3ff9c 100644 --- a/src/client/spark/view/Spark/Ladder/LadderGridHost.cs +++ b/src/client/spark/view/Spark/Ladder/LadderGridHost.cs @@ -314,7 +314,11 @@ namespace mbts.spark { Child = new Border { BorderBrush = Brushes.Black, BorderThickness = new Thickness(0.5), - Child = view, + Child = new ScrollViewer { + VerticalScrollBarVisibility = ScrollBarVisibility.Hidden, + HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled, + Content = view, + } } }; view.RequestClose += (o, _) => popup.IsOpen = false; diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs index 85f699bd6..acb47a9be 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs @@ -23,7 +23,8 @@ namespace mbts.spark { } public struct MBOPopupDrawParams { public MBOPopupData data; - public Size size => new Size(300, header.Height + margin.Top + margin.Bottom + (row_height*data.orders.Count) + margin.Bottom); + public double width => 300.0; + public double height; public FormattedText header; public static readonly Thickness margin = new Thickness(10, 5, 5, 5); @@ -36,18 +37,17 @@ namespace mbts.spark { public double numbers_width; public List row_labels; public double scale; - - // footer - public double footer_height => 20; } public class MBOPopupModel { - const double font_size = 10.0; + const double font_size = 9.0; readonly MBOService _mbo; readonly SecurityImmutable _security; readonly MBOSecurityQueryImmutable _query; readonly Dictionary _cache; int _max_order_size = 1; + double _height = 0; + public MBOPopupModel(MBOService mbo, SecurityImmutable security, MBOSecurityQueryImmutable query) { _mbo = mbo; @@ -56,7 +56,7 @@ namespace mbts.spark { // prime the cache with numbers on the left hand side _cache = - Enumerable.Range(0, (int)default_query.Limit) + Enumerable.Range(1, 1+(int)default_query.Limit) .AsParallel() .Select(i => TextUtils.GetFormattedText(i.ToString(), font_size)) .ToDictionary(ft => ft.Text); @@ -104,15 +104,19 @@ namespace mbts.spark { var margin = MBOPopupDrawParams.margin; var text_margin = margin.Left + margin.Right; - pdp.row_numbers = p.orders.Select((o, i) => format_text(i.ToString())).ToList(); + pdp.row_numbers = p.orders.Select((o, i) => format_text((i+1).ToString())).ToList(); pdp.numbers_width = (int)pdp.row_numbers.Max(r => r.Width) + text_margin; pdp.row_labels = p.orders.Select(o => format_text(o.Size.ToString())).ToList(); var max_label_width = pdp.row_labels.Max(l => l.Width) + text_margin; - var available_width = pdp.size.Width - pdp.numbers_width - max_label_width; + var available_width = pdp.width - pdp.numbers_width - max_label_width; _max_order_size = Math.Max(p.orders.Max(o => o.Size), _max_order_size); pdp.scale = available_width / _max_order_size; + pdp.height = _height = + Math.Max(_height, + pdp.header.Height + margin.Top + margin.Bottom + (pdp.row_height * p.orders.Count) + margin.Bottom); + return pdp; } diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs index 80243fce9..34d3b94a4 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupView.cs @@ -17,40 +17,39 @@ namespace mbts.spark { internal class MBOPopupView : UIElement, IRequestViewClose { readonly Brush _background = BTSColors.LadderSpecial.default_column_background; readonly MBOPopupModel _model; - DispatcherTimer _timer; MBOPopupDrawParams _dp; public MBOPopupView(MBOPopupModel model, MBOPopupData p) { _model = model; _dp = model.compute_layout(p); - _timer = new DispatcherTimer() { - Interval = TimeSpan.FromSeconds(0.25), - IsEnabled = true, - }; - _timer.Tick += timer_Tick; + IsVisibleChanged += (o, _) => poll_orders(); } - private async void timer_Tick(object sender, EventArgs e) { - //NOTE: What if load_orders takes too long? - var result = await _model.load_orders(); - if (result.success && result.value.orders.Count > 0) { - _dp = _model.compute_layout(result.value); - InvalidateVisual(); + private async void poll_orders() { + while (IsVisible) { + var result = await _model.load_orders(); + if (result.success && result.value.orders.Count > 0) { + Log.Ui.diag($"MBOpopup got {result.value.orders.Count} orders"); + _dp = _model.compute_layout(result.value); + InvalidateMeasure(); + InvalidateVisual(); + } + else RequestClose?.Invoke(this, null); + await Task.Delay(250); } - else RequestClose?.Invoke(this, null); } public event EventHandler RequestClose; protected override Size MeasureCore(Size availableSize) { - return _dp.size; + return new Size(_dp.width, _dp.height); } static Thickness margin => MBOPopupDrawParams.margin; protected override void OnRender(DrawingContext dc) { base.OnRender(dc); // draw background - dc.DrawRectangle(_background, null, new Rect(0, 0, _dp.size.Width, _dp.size.Height)); + dc.DrawRectangle(_background, null, new Rect(0, 0, _dp.width, _dp.height)); // draw header dc.DrawText(_dp.header, new Point(margin.Left, margin.Top)); // draw grid @@ -83,34 +82,5 @@ namespace mbts.spark { offset += dp.row_height; } } - - //private void draw_scale(DrawingContext dc) { - // var pen = new Pen(BTSColors.text_default_brush, 0.5); - // var smallTick = Math.Max(5 * _dp.scale, 2); - // if (smallTick > _dp.size.Width) { - // // shrink to tick = 1 for very small scales - // smallTick = _dp.scale; - // } - // var largeTick = 2 * smallTick; - // var baseline = _dp.size.Height - 20; - // dc.DrawLine(pen, new Point(0, baseline), new Point(_dp.size.Width, baseline)); - // for (double x = smallTick; x < _dp.size.Width; x += smallTick) { - // bool large = x % largeTick == 0; - // var tickLength = large ? 6.0 : 3.0; - // dc.DrawLine(pen, new Point(x, baseline), new Point(x, baseline + tickLength)); - - // if (x + smallTick >= _dp.size.Width) { - // // last tick mark - // var size = (int)(x / _dp.scale); - // var text = TextUtils.GetFormattedText(size.ToString(), 9.0); - // var left = x - text.Width / 2; - // var right = left + text.Width/2; - // if (right > _dp.size.Width) { - // left -= (right - _dp.size.Width); - // } - // dc.DrawText(text, new Point(x - text.Width / 2, baseline + tickLength + 2)); - // } - // } - //} } } \ No newline at end of file diff --git a/src/client/spark/view/Utility/AutoClosePopup.cs b/src/client/spark/view/Utility/AutoClosePopup.cs index ec57040cf..a14298903 100644 --- a/src/client/spark/view/Utility/AutoClosePopup.cs +++ b/src/client/spark/view/Utility/AutoClosePopup.cs @@ -1,9 +1,13 @@ -using System.Windows; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Controls; using System.Windows.Input; namespace mbts.ui.controls { class AutoClosePopup : System.Windows.Controls.Primitives.Popup { - public AutoClosePopup() { } + public AutoClosePopup() { + StaysOpen = false; + } public new FrameworkElement Child { get => base.Child as FrameworkElement; @@ -15,8 +19,8 @@ namespace mbts.ui.controls { } private void hook_child_events(FrameworkElement fe) { - fe.Loaded += Child_Loaded; fe.MouseDown += Child_MouseDown; + fe.PreviewMouseDown += Child_MouseDown; if (fe is IRequestViewClose vc) { vc.RequestClose += (o,_) => IsOpen = false; } @@ -27,9 +31,5 @@ namespace mbts.ui.controls { IsOpen = false; } } - - private void Child_Loaded(object sender, RoutedEventArgs e) { - var cap = ((FrameworkElement)sender).CaptureMouse(); - } } } From f33a13bfc8fb0ad345a89000c55b5bebd35c465a Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 13:36:19 -0400 Subject: [PATCH 09/21] Wire mbo popup to ladder in order book --- src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs | 2 +- src/client/spark/Orders/OrdersModel.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs index 325c49469..45a77f7bc 100644 --- a/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs +++ b/src/client/spark/Modules/Trading/OrderBook/OrderBookVM.cs @@ -884,7 +884,7 @@ namespace mbts.spark { _security_md.HasValue ? LadderVM.create_readonly( _owner._bus, - new LadderModel(security_md.Value, _owner._model, null/*mbo*/, + new LadderModel(security_md.Value, _owner._model, _owner._model.mbo_service, new Func(osec => _selected_order_tree.Contains(osec.order.Key)))) : null); RaisePropertyChanged(nameof(ladder_vm)); diff --git a/src/client/spark/Orders/OrdersModel.cs b/src/client/spark/Orders/OrdersModel.cs index 078da0e39..13ef57b6d 100644 --- a/src/client/spark/Orders/OrdersModel.cs +++ b/src/client/spark/Orders/OrdersModel.cs @@ -182,6 +182,7 @@ namespace mbts.spark { public IObservable> studio_algos_with_meta { get; } public AdminModel admin_model { get; } + public MBOService mbo_service => _mbo_service; public IAlgoStudioModel algo_model { get; } public IObservable> on_security_working_orders_with_piq(uint security) => From 6d6ecb33bacd40bcbf3b706252fbadd8768ce743 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 15:08:51 -0400 Subject: [PATCH 10/21] =?UTF-8?q?SPARK-2450=20Simulator=20MBO=20realism=20?= =?UTF-8?q?=E2=84=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/config/protos/ExchangeSimCfg.proto | 1 + .../sparkd/exchange_sim/book/OrderMatcher.cpp | 32 ++++++++++--------- .../sparkd/exchange_sim/book/OrderMatcher.h | 9 ++++-- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/lib/config/protos/ExchangeSimCfg.proto b/src/lib/config/protos/ExchangeSimCfg.proto index 6cf1f7dc1..b2d69068f 100644 --- a/src/lib/config/protos/ExchangeSimCfg.proto +++ b/src/lib/config/protos/ExchangeSimCfg.proto @@ -9,5 +9,6 @@ message ExchangeSim { string replay_file = 12 [default = "futures.coconut"]; bool local_relay = 13; } + optional uint32 orders_per_level = 20 [default = 10]; } diff --git a/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp b/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp index 1f1c4b78c..2238e4a30 100644 --- a/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp +++ b/src/server/sparkd/exchange_sim/book/OrderMatcher.cpp @@ -2,6 +2,8 @@ #include "lib/utils/bts_assert.h" #include "server/sparkd/exchange_sim/book/Book.h" #include "server/sparkd/exchange_sim/book/Order.h" +#include "lib/config/config.h" +#include "lib/config/protos/ExchangeSimCfg.pb.h" #include @@ -10,11 +12,12 @@ namespace ex_sim { struct OrderMatcher::PImpl { PImpl() - : bids(OrderCmp(false)), asks(OrderCmp(true)) {} + : bids(OrderCmp(false)), asks(OrderCmp(true)), max_orders(config::get().orders_per_level()) {} OrdersSide bids; OrdersSide asks; std::vector pending_trades; + size_t max_orders; }; OrderMatcher::OrderMatcher() @@ -53,24 +56,24 @@ void OrderMatcher::add_new(Order const &o, std::vector *out) { match(out); } -std::pair -OrderMatcher::find_level(OrdersSide &side, double level) +OrderMatcher::Level OrderMatcher::find_level(OrdersSide &side, double level) { - std::pair result {side.end(), side.end()}; + auto first = side.end(), second = side.end(); + size_t count = 0; for (auto it = side.begin() ; it != side.end(); it++) { - if (price_equals(it->price(),level)) { - result.first = it; + first = it; for (;it != side.end(); it++) { + ++count; if (!price_equals(it->price(),level)) break; } - result.second = it; + second = it; break; } } - return result; + return { first, second, count }; } void OrderMatcher::add_or_merge(Order const &o, std::vector *out) { @@ -82,12 +85,12 @@ void OrderMatcher::add_or_merge(Order const &o, std::vector *out) { side = &me->asks; auto range = find_level(*side,o.price()); - // If the last order at this level is the same owner we can update it if (range.first != range.second) { auto last = range.second; last--; - if (last->owner() == o.owner()) { + // Keep enough orders to make MBO look good but don't grow forever + if (last->owner() == o.owner() && range.size > me->max_orders) { auto no_const = const_cast(&(*last)); no_const->set_open_quantity(last->open_quantity() + o.quantity()); match(out); @@ -139,11 +142,10 @@ void OrderMatcher::cancel(std::string const &clordid) { void OrderMatcher::try_reduce_quantity_at_level( api::Side side, Price level, Quantity by_quantity, std::string const &order_owner) { - std::pair range; - if (side == api::SIDE_BUY) - range = find_level(me->bids,level.value()); - else - range = find_level(me->asks,level.value()); + auto range = + side == api::SIDE_BUY ? + find_level(me->bids,level.value()) : + find_level(me->asks,level.value()); std::vector orders_to_cancel; for (auto it = range.first; it != range.second && by_quantity.value(); diff --git a/src/server/sparkd/exchange_sim/book/OrderMatcher.h b/src/server/sparkd/exchange_sim/book/OrderMatcher.h index 86a5a1b3c..4e4301762 100644 --- a/src/server/sparkd/exchange_sim/book/OrderMatcher.h +++ b/src/server/sparkd/exchange_sim/book/OrderMatcher.h @@ -9,6 +9,7 @@ #include #include +#include namespace bts { namespace ex_sim { @@ -48,8 +49,12 @@ class OrderMatcher { std::unique_ptr me; void match(std::vector *out); void match(Order *bid, Order *ask); - std::pair - find_level(OrdersSide &side, double level); + struct Level { + OrderMatcher::OrdersSide::iterator first; + OrderMatcher::OrdersSide::iterator second; + size_t size; + }; + Level find_level(OrdersSide &side, double level); }; From 6081128b9210da59499f216382307079eb71117c Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 15:11:26 -0400 Subject: [PATCH 11/21] move sparkvm launch to the top of the debug menu --- .vscode/launch.json | 237 ++++++++++++++++++++++++++------------------ 1 file changed, 143 insertions(+), 94 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 17ef37c0b..71b5a8e9e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,83 +1,14 @@ { "version": "0.2.0", "configurations": [ - - { - "name": "(gdb) Launch", - "type": "cppdbg", - "request": "launch", - "program": "${workspaceRoot}/build/ninja_debug/server/sparkd/sparkd", - "args": ["run"], - "stopAtEntry": false, - "cwd": "${workspaceRoot}/build/ninja_debug/src/server/sparkd", - "environment": [], - "externalConsole": true, - "MIMode": "gdb", - "setupCommands": [ - { - "description": "Enable pretty-printing for gdb", - "text": "-enable-pretty-printing", - "ignoreFailures": true - } - ] - }, - { - "name": "Client Launch", - "type": "clr", - "request": "launch", - "program": "${workspaceRoot}/build/Debug/bin/net471/spark.exe", - "args": [], - "cwd": "${workspaceRoot}", - "stopAtEntry": false, - "externalConsole": true, - "requireExactSource": false - }, - { - "name": "SDK Launch", - "type": "clr", - "request": "launch", - "program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe", - "args": ["md","GLBX","Future","CL", "CLZ9", "--user=bts", "--pass="], - "cwd": "${workspaceRoot}", - "stopAtEntry": false, - "externalConsole": true, - "requireExactSource": false - }, - { - "name": "Excel Launch", - "type": "clr", - "request": "launch", - "program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE", - "args": ["${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll"], - "cwd": "${workspaceRoot}", - "stopAtEntry": false, - "externalConsole": true, - "requireExactSource": false - }, - { - "name": "Client Tests", - "type": "clr", - "request": "launch", - "program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe", - "args": ["test","test_filter"], - "cwd": "${workspaceRoot}", - "stopAtEntry": false, - "externalConsole": true, - "requireExactSource": false - }, - { - "name": "Client Attach", - "type": "clr", - "request": "attach", - "processId":"${command:pickProcess}" - }, { "name": "SparkVM Launch", "type": "cppdbg", "request": "launch", - "program": "/home/bts/spark/build/ninja_debug/server/sparkd", - "args": ["run"], + "args": [ + "run" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/server/", "environment": [], @@ -102,24 +33,113 @@ "description": "LD LIBRARY", "text": "set env LD_LIBRARY_PATH=.", "ignoreFailures": false - } + } ], "pipeTransport": { "pipeCwd": "${workspaceRoot}", "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { "/home/bts/spark/": "${workspaceRoot}" } }, + { + "name": "(gdb) Launch", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceRoot}/build/ninja_debug/server/sparkd/sparkd", + "args": [ + "run" + ], + "stopAtEntry": false, + "cwd": "${workspaceRoot}/build/ninja_debug/src/server/sparkd", + "environment": [], + "externalConsole": true, + "MIMode": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + } + ] + }, + { + "name": "Client Launch", + "type": "clr", + "request": "launch", + "program": "${workspaceRoot}/build/Debug/bin/net471/spark.exe", + "args": [], + "cwd": "${workspaceRoot}", + "stopAtEntry": false, + "externalConsole": true, + "requireExactSource": false + }, + { + "name": "SDK Launch", + "type": "clr", + "request": "launch", + "program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe", + "args": [ + "md", + "GLBX", + "Future", + "CL", + "CLZ9", + "--user=bts", + "--pass=" + ], + "cwd": "${workspaceRoot}", + "stopAtEntry": false, + "externalConsole": true, + "requireExactSource": false + }, + { + "name": "Excel Launch", + "type": "clr", + "request": "launch", + "program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE", + "args": [ + "${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll" + ], + "cwd": "${workspaceRoot}", + "stopAtEntry": false, + "externalConsole": true, + "requireExactSource": false + }, + { + "name": "Client Tests", + "type": "clr", + "request": "launch", + "program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe", + "args": [ + "test", + "test_filter" + ], + "cwd": "${workspaceRoot}", + "stopAtEntry": false, + "externalConsole": true, + "requireExactSource": false + }, + { + "name": "Client Attach", + "type": "clr", + "request": "attach", + "processId": "${command:pickProcess}" + }, { "name": "Spreader Tests", "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", - "args": ["test", "[spreader]"], + "args": [ + "test", + "[spreader]" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", "environment": [], @@ -139,7 +159,9 @@ "pipeTransport": { "pipeCwd": "${workspaceRoot}", "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { @@ -151,7 +173,10 @@ "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", - "args": ["test", "[admin_service]"], + "args": [ + "test", + "[admin_service]" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", "environment": [], @@ -171,7 +196,9 @@ "pipeTransport": { "pipeCwd": "${workspaceRoot}", "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { @@ -183,7 +210,10 @@ "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd", - "args": ["test", "[limiter]"], + "args": [ + "test", + "[limiter]" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/", "environment": [], @@ -203,7 +233,9 @@ "pipeTransport": { "pipeCwd": "${workspaceRoot}", "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { @@ -215,7 +247,10 @@ "type": "cppdbg", "request": "launch", "program": "/home/bts/spark/build/ninja_debug/server/sparkd", - "args": ["test", "[mbo]"], + "args": [ + "test", + "[mbo]" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/server/", "environment": [], @@ -240,14 +275,16 @@ "pipeTransport": { "pipeCwd": "${workspaceRoot}", "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { "/home/bts/spark/": "${workspaceRoot}" } }, - { + { "name": "SparkVM attach", "type": "cppdbg", "request": "attach", @@ -255,16 +292,18 @@ "processId": "${command:pickRemoteProcess}", "MIMode": "gdb", "pipeTransport": { - "pipeCwd": "${workspaceRoot}", - "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], - "debuggerPath": "/usr/bin/gdb" + "pipeCwd": "${workspaceRoot}", + "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", + "pipeArgs": [ + "bts@sparkvm" + ], + "debuggerPath": "/usr/bin/gdb" }, "sourceFileMap": { - "/home/bts/spark/": "${workspaceRoot}" + "/home/bts/spark/": "${workspaceRoot}" } - }, - { + }, + { "name": "Python", "type": "python", "request": "launch", @@ -274,7 +313,9 @@ "cwd": "${workspaceRoot}", "env": {}, "envFile": "${workspaceRoot}/.env", - "args": [ "DEBUG" ], + "args": [ + "DEBUG" + ], "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", @@ -288,7 +329,9 @@ "processId": "${command:pickRemoteProcess}", "pipeTransport": { "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/home/bts/vsdbg/vsdbg", "pipeCwd": "${workspaceRoot}", "quoteArgs": true @@ -303,12 +346,18 @@ "type": "coreclr", "request": "launch", "program": "/usr/bin/dotnet", - "args": ["sparkcmd.dll", "test", "test_join_create_and_takeout_market"], + "args": [ + "sparkcmd.dll", + "test", + "test_join_create_and_takeout_market" + ], "stopAtEntry": false, "cwd": "/home/bts/spark/build/ninja_debug/server", "pipeTransport": { "pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe", - "pipeArgs": ["bts@sparkvm"], + "pipeArgs": [ + "bts@sparkvm" + ], "debuggerPath": "/home/bts/vsdbg/vsdbg", "pipeCwd": "${workspaceRoot}", "quoteArgs": true From 7bd183c8a41492295633801363a574428816bdc4 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 15:29:59 -0400 Subject: [PATCH 12/21] btree_set benchmarks are very interesting --- src/server/sparkd/cmds/Benchmark.cpp | 33 ++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/server/sparkd/cmds/Benchmark.cpp b/src/server/sparkd/cmds/Benchmark.cpp index d62e01f9e..62d1ce8e3 100644 --- a/src/server/sparkd/cmds/Benchmark.cpp +++ b/src/server/sparkd/cmds/Benchmark.cpp @@ -34,6 +34,10 @@ #include #include +#include +#include +#include + #include #include namespace bts { @@ -655,6 +659,35 @@ void int_price_less(benchmark::State& state) { } BENCHMARK(int_price_less)->Range(8, 8 << 11); + +void set_hashset(benchmark::State& state) { + std::unordered_set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + } +} +void set_stdset(benchmark::State& state) { + std::set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + } +} +void set_btreeset(benchmark::State& state) { + btree::btree_set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + } +} +BENCHMARK(set_hashset); +BENCHMARK(set_stdset); +BENCHMARK(set_btreeset); + std::string Benchmark::help() { return "Run micro-benchmarks. Use --benchmark_filter=regex to run only " "specific benchmarks."; From e5254dcf7f9d35f0291502dc6df29f8c4c7e1fe5 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 15:40:17 -0400 Subject: [PATCH 13/21] btree_set benchmarks are veerry interesting --- src/server/sparkd/cmds/Benchmark.cpp | 50 ++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/src/server/sparkd/cmds/Benchmark.cpp b/src/server/sparkd/cmds/Benchmark.cpp index 62d1ce8e3..31e1019c4 100644 --- a/src/server/sparkd/cmds/Benchmark.cpp +++ b/src/server/sparkd/cmds/Benchmark.cpp @@ -660,7 +660,7 @@ void int_price_less(benchmark::State& state) { BENCHMARK(int_price_less)->Range(8, 8 << 11); -void set_hashset(benchmark::State& state) { +void set_hashset_insert(benchmark::State& state) { std::unordered_set s; size_t x = 0; for (auto _ : state) { @@ -668,7 +668,7 @@ void set_hashset(benchmark::State& state) { s.insert(x); } } -void set_stdset(benchmark::State& state) { +void set_stdset_insert(benchmark::State& state) { std::set s; size_t x = 0; for (auto _ : state) { @@ -676,7 +676,7 @@ void set_stdset(benchmark::State& state) { s.insert(x); } } -void set_btreeset(benchmark::State& state) { +void set_btreeset_insert(benchmark::State& state) { btree::btree_set s; size_t x = 0; for (auto _ : state) { @@ -684,9 +684,47 @@ void set_btreeset(benchmark::State& state) { s.insert(x); } } -BENCHMARK(set_hashset); -BENCHMARK(set_stdset); -BENCHMARK(set_btreeset); + +void set_hashset_iterate(benchmark::State& state) { + std::unordered_set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + for (const auto& p : s) { + benchmark::DoNotOptimize(p); + } + } +} +void set_stdset_iterate(benchmark::State& state) { + std::set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + for (const auto& p : s) { + benchmark::DoNotOptimize(p); + } + } +} +void set_btreeset_iterate(benchmark::State& state) { + btree::btree_set s; + size_t x = 0; + for (auto _ : state) { + x = std::rand(); + s.insert(x); + for (const auto& p : s) { + benchmark::DoNotOptimize(p); + } + } +} + +BENCHMARK(set_hashset_insert); +BENCHMARK(set_stdset_insert); +BENCHMARK(set_btreeset_insert); +BENCHMARK(set_hashset_iterate); +BENCHMARK(set_stdset_iterate); +BENCHMARK(set_btreeset_iterate); std::string Benchmark::help() { return "Run micro-benchmarks. Use --benchmark_filter=regex to run only " From 0f1735fba2a6d41983e8e7a2a4f5dbfa916a8383 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 16:39:50 -0400 Subject: [PATCH 14/21] SPARK-2453 Do not end order on bid/ask middle click --- .../spark/Modules/Trading/Ladder/VM/LadderVM.cs | 12 +++++++----- .../Modules/Trading/Ladder/View/LadderGridHost.cs | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs index c7b7804c7..faf13ea3d 100644 --- a/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs +++ b/src/client/spark/Modules/Trading/Ladder/VM/LadderVM.cs @@ -116,7 +116,7 @@ namespace mbts.spark { //_window_height = backing(nameof(window_height), settings_manager.subscribe_current().OnDispatcher().Select(s => s.zoom_factor), (scale) => scale * 600); //_window_width = backing(nameof(window_width), settings_manager.subscribe_current().OnDispatcher().Select(s => s.zoom_factor), (scale) => scale * 420); 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); + send_order_command = new DelegateCommand<(double price, Side? side, MouseButton button)>(send_order); cancel_command = new AsyncCommand(_model.cancel_orders, true); show_book_command = new DelegateCommand(_show_book); show_ticket_command = new DelegateCommand(_show_ticket); @@ -348,13 +348,15 @@ namespace mbts.spark { } } - public async void send_order((double price, Side? side, bool size_from_alternate) args) { + public async void send_order((double price, Side? side, MouseButton buton) args) { + if (args.buton == MouseButton.Middle) return; + var size_from_alternate = args.buton == MouseButton.Right; if (order_properties_vm == null) return; var s = _settings_manager.current_settings(); - if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (args.size_from_alternate && s.alternate_order_size == 0)) + if (DoubleHelper.IsNaNOrInfinity(args.price) || !args.side.HasValue || HasErrors || order_properties_vm.HasErrors || (size_from_alternate && s.alternate_order_size == 0)) return; - else if (!args.size_from_alternate && (!size_calculator.value.HasValue || size_calculator.value.Value == 0)) { + else if (!size_from_alternate && (!size_calculator.value.HasValue || size_calculator.value.Value == 0)) { size_calculator.flash_error(); } else { var order = order_properties_vm.create(args.side.Value); @@ -371,7 +373,7 @@ namespace mbts.spark { } } - uint size = args.size_from_alternate ? s.alternate_order_size : (uint)Math.Abs(size_calculator.value.Value); + uint size = size_from_alternate ? s.alternate_order_size : (uint)Math.Abs(size_calculator.value.Value); await _model.order_gateway.send_order(order, args.price, size); if (auto_clear) size_calculator.value = 0; diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index f7b400f37..845d9ba8f 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -332,7 +332,7 @@ namespace mbts.spark { Side? bs = null; if (column.column_type == ColumnType.Bid) bs = Side.Buy; if (column.column_type == ColumnType.Ask) bs = Side.Sell; - var pbs = (price, bs, e.ChangedButton == MouseButton.Right); + var pbs = (price, bs, e.ChangedButton); if (Command != null && Command.CanExecute(pbs)) { if (bs.HasValue) { using (_tactile_adorner.show_busy(_row_for_point(point), bs.Value == Side.Buy ? ColumnType.Bid : ColumnType.Ask)) From d6e586c4cea49e75a2dad9ab68924dcd49244714 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Thu, 16 May 2019 16:44:18 -0400 Subject: [PATCH 15/21] SPARK2452 - Update release notes for MBO --- doc/user/content/release_notes/_index.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index f7fb3889d..2919a6e44 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -4,6 +4,14 @@ weight = 3 sort_by = "weight" insert_anchor_links = "right" +++ +## 2.0.1 +### User Visible Changes + - Middle click the ladder price column to show the orders for that price level + - Middle click the bid or ask column in the ladder no longer sends an order + +### Internal changes + - Improved market by order performance under heavy load + ## 2.0.0 ### User Visible Changes - Support for attaching and detaching algos to existing orders From 3483ac0712a666176de328b7f0f56666349f9edc Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 09:03:49 -0400 Subject: [PATCH 16/21] Code review feedback --- .../spark/Modules/Trading/Ladder/View/LadderGridHost.cs | 2 +- src/client/spark/Spark.csproj | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs index 845d9ba8f..1fd2c21f9 100644 --- a/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs +++ b/src/client/spark/Modules/Trading/Ladder/View/LadderGridHost.cs @@ -354,7 +354,7 @@ namespace mbts.spark { var model = new MBOPopupModel(_vm.model.mbo_service, _vm.model.security, query); // Load the first set of orders so we know if there are any before showing the popup var result = await model.load_orders(); - if (result.success && result.value.orders.Count() > 0) { + if (result.success && result.value.orders.Count > 0) { var view = new MBOPopupView(model, result.value); var popup = new AutoClosePopup { PlacementTarget = this, diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index 8494935e0..914c9f524 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -57,7 +57,6 @@ - @@ -80,9 +79,6 @@ Code - - Code - From 476206edb0434fb3f2069e331595786931bd3c5c Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 10:19:04 -0400 Subject: [PATCH 17/21] add piq/mbo manual test --- testing/manual/ladder/badges.txt | 6 ++-- testing/manual/ladder/piq_mbo.txt | 57 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 testing/manual/ladder/piq_mbo.txt diff --git a/testing/manual/ladder/badges.txt b/testing/manual/ladder/badges.txt index 1a6d8eaf7..7ebcc32a5 100644 --- a/testing/manual/ladder/badges.txt +++ b/testing/manual/ladder/badges.txt @@ -28,12 +28,12 @@ the badge will have a green border, depicting the single-order limit order type the badge will have a dot in the upper right hand corner (7) 2. Now place another limit order at the same level: -the badge now has a triangle in the lower right, indicating we have multiple workikng orders (9) +the badge now has a triangle in the lower right, indicating we have multiple working orders (9) the green border and dot have gone away (5, 7) Now place another limit below the bid: -3. Outcome similar to 1, except the background color is ligther bid background color (blue) +3. Outcome similar to 1, except the background color is lighter bid background color (blue) Now place an a Buy Iceberg at the same level with a sufficiently large qty, say 200, as your working ask @@ -44,7 +44,7 @@ Test 2 ------ This will test characteristics 4,10 -1. Create a spreader comprised 1 quoting leg and 1 heding leg of your favorite instruments and place a spread order +1. Create a spreader comprised 1 quoting leg and 1 hedging leg of your favorite instruments and place a spread order 2. Pull up the spreader ladder and place a sell order above the market 3. Pull up the quoting leg's ladder and observe the badge; it may be helpful to pull up the Orderbook to find the price at which the leg is being quoted. The badge should have a rectangle filled in with the Spreader algo's color diff --git a/testing/manual/ladder/piq_mbo.txt b/testing/manual/ladder/piq_mbo.txt new file mode 100644 index 000000000..b6cc21aa6 --- /dev/null +++ b/testing/manual/ladder/piq_mbo.txt @@ -0,0 +1,57 @@ +Introduction +------------- + +Ideally this test should be done with a cert connection because the simulator can be quirky. If you ignore this advice and use sim you must not admit it to anyone. + +Only exchange orders will have a PIQ so you should probably just use a Limit order for this test. + +General Stuff to Look For: +-------------------------- +- The MBO popup is 'live' and should update as the market moves. +- The MBO popup should increase in size if more orders are added while it is open. +- The MBO popup should not shrink when orders are removed. It only grows. +- The scale of the bars is based on the largest order seen by the popup. + - If a larger order shows up it will scale down the other orders. + - When the large order goes away it should *not* expand the other bars. The scale only increases while the popup is open. + - For example: + - You open the popup and there are 2 orders of size [1,2] + - size 1 will be about half way across the available space and 2 will fill the space. + - An order of size 5 comes around it will fill the available space and the other orders will be 20%, 40% across respectively. + - If the size 5 order is canceled the [1,2] orders stay at 20%, 40% rather than growing to fill the space. + - If you close and re-open the popup state is reset and [1,2] will be 50%/100% again. +- Middle clicking on a row with no data does not open the popup. + - This doesn't mean clicking past the end of the visible book won't show anything. The MBO tracks much deeper than the market by price. If there's a gap between 2 prices that's a good spot to test. + + +Part 1: +------- +- Find a security with a non-empty market that isn't moving too fast. Cert can be temperamental so open the market view and filter for Qty > 0. +- Open settings and turn on the PIQ column (settings -> column settings) +- Choose a price near the top of the book and middle click the price column to show the MBO popup. +- Add up the sizes in the popup and make sure they agree with the total size in the bid or ask column on the ladder. + - Test both sides of the market near the top and away from the top. +- Enter an order. + - The PIQ column should reflect the number of orders ahead of you in the queue. The size in the bid/ask column is how many orders were there when you entered your order so you should expect the PIQ to be the size from before you entered your order. + When the market moves you should expect your PIQ to go down. If cert is working correctly your PIQ should never go up. + - Open the MBO popup. Your order should be shown in a different color from the other orders at that level. + - Verify that your order position matches the value from the PIQ column. + - Test both sides of the market near the top and away from the top. +- Moving your order to a different price or *increasing* the size of your order will move you to the back of the queue. + - If you ignored the instructions and you're using cert this probably won't work. You should have listened. +- Reducing the size of your order should not change your queue position. You might may have to be quick to observe this. + +Part 2: +------- +- Open several securities with varying tick sizes and make sure that the MBO popup opens for all levels of the book where there is a size. +- Why? The ladder sends the price you click on to the server and the server must identify the right price level. As you know, the IEEE double is out to get you. + +Part 3: +------- +- The MBO popup should expand either up or down from the mouse position to maximize the available space. +- If the number of orders exceeds the space available the mouse wheel should work to let you scroll up/down to see the rest (up to LadderKnobs.max_mbo_orders which defaults to 200) +- Find a security with enough orders to cause scrolling by either + - Connect to a prod system and look at a ZN spread (i.e. ZNM9 - ZNU9) + - Enter a bunch of orders at the level on cert. + - If you try this on sim (you're not a very good listener, are you?) It will cap out at ExchangeSim.orders_per_level (default:10) +- Make sure that scrolling works. + From 0e449844ca874482c0c2c42692b970b2e6b2715c Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 10:25:28 -0400 Subject: [PATCH 18/21] Clarify this point --- testing/manual/ladder/piq_mbo.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/manual/ladder/piq_mbo.txt b/testing/manual/ladder/piq_mbo.txt index b6cc21aa6..ea9eb6448 100644 --- a/testing/manual/ladder/piq_mbo.txt +++ b/testing/manual/ladder/piq_mbo.txt @@ -50,7 +50,7 @@ Part 3: - The MBO popup should expand either up or down from the mouse position to maximize the available space. - If the number of orders exceeds the space available the mouse wheel should work to let you scroll up/down to see the rest (up to LadderKnobs.max_mbo_orders which defaults to 200) - Find a security with enough orders to cause scrolling by either - - Connect to a prod system and look at a ZN spread (i.e. ZNM9 - ZNU9) + - Connect to a demo system with production md and look at a ZN spread (i.e. ZNM9 - ZNU9) - Enter a bunch of orders at the level on cert. - If you try this on sim (you're not a very good listener, are you?) It will cap out at ExchangeSim.orders_per_level (default:10) - Make sure that scrolling works. From 6fb1140a9760f3d6691bf02d2794fb336d5ed61f Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 10:29:12 -0400 Subject: [PATCH 19/21] test review feedback --- testing/manual/ladder/piq_mbo.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/manual/ladder/piq_mbo.txt b/testing/manual/ladder/piq_mbo.txt index ea9eb6448..3cce313fa 100644 --- a/testing/manual/ladder/piq_mbo.txt +++ b/testing/manual/ladder/piq_mbo.txt @@ -37,7 +37,7 @@ Part 1: - Verify that your order position matches the value from the PIQ column. - Test both sides of the market near the top and away from the top. - Moving your order to a different price or *increasing* the size of your order will move you to the back of the queue. - - If you ignored the instructions and you're using cert this probably won't work. You should have listened. + - If you ignored the instructions and you're using sim this probably won't work. You should have listened. - Reducing the size of your order should not change your queue position. You might may have to be quick to observe this. Part 2: From a12c3128a34a77f1aabc54674e6ae23a1288e9a0 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 11:45:22 -0400 Subject: [PATCH 20/21] Don't allow mbo popup index number to flicker width --- src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs index a536f9e2c..ede6f0e84 100644 --- a/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs +++ b/src/client/spark/view/Spark/Ladder/MBO/MBOPopupModel.cs @@ -47,6 +47,7 @@ namespace mbts.spark { readonly Dictionary _cache; int _max_order_size = 1; double _height = 0; + double _number_width = 0; public MBOPopupModel(MBOService mbo, SecurityImmutable security, MBOSecurityQueryImmutable query) { @@ -106,7 +107,7 @@ namespace mbts.spark { var text_margin = margin.Left + margin.Right; pdp.row_numbers = p.orders.Select((o, i) => format_text((i+1).ToString())).ToList(); - pdp.numbers_width = (int)pdp.row_numbers.Max(r => r.Width) + text_margin; + pdp.numbers_width = _number_width = Math.Max(_number_width, (int)pdp.row_numbers.Max(r => r.Width) + text_margin); pdp.row_labels = p.orders.Select(o => format_text(o.Size.ToString())).ToList(); var max_label_width = pdp.row_labels.Max(l => l.Width) + text_margin; From 13e911760d07a654d1c1f130c1d696a35caae049 Mon Sep 17 00:00:00 2001 From: Eric Harding Date: Fri, 17 May 2019 11:46:06 -0400 Subject: [PATCH 21/21] Middle click off popup shoudl close popup --- .../spark/view/Utility/AutoClosePopup.cs | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/client/spark/view/Utility/AutoClosePopup.cs b/src/client/spark/view/Utility/AutoClosePopup.cs index a14298903..df73a81ad 100644 --- a/src/client/spark/view/Utility/AutoClosePopup.cs +++ b/src/client/spark/view/Utility/AutoClosePopup.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; @@ -7,6 +8,11 @@ namespace mbts.ui.controls { class AutoClosePopup : System.Windows.Controls.Primitives.Popup { public AutoClosePopup() { StaysOpen = false; + CommandBindings.Add(new CommandBinding( + ApplicationCommands.Close, + (o,_) => { IsOpen = false; } + )); + InputBindings.Add(new KeyBinding(ApplicationCommands.Close, Key.Escape, ModifierKeys.None)); } public new FrameworkElement Child { @@ -19,16 +25,20 @@ namespace mbts.ui.controls { } private void hook_child_events(FrameworkElement fe) { - fe.MouseDown += Child_MouseDown; - fe.PreviewMouseDown += Child_MouseDown; + MouseDown += OnMouseDown; + fe.MouseDown += OnMouseDown; + fe.PreviewMouseDown += OnMouseDown; if (fe is IRequestViewClose vc) { vc.RequestClose += (o,_) => IsOpen = false; } } - private void Child_MouseDown(object sender, MouseButtonEventArgs e) { - if (!e.Handled) { - IsOpen = false; + private void OnMouseDown(object sender, MouseButtonEventArgs e) { + if (sender == this && e.MiddleButton == MouseButtonState.Pressed) IsOpen = false; + else { + if (!e.Handled) { + IsOpen = false; + } } } }